๐คฏ 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(sandbox): drive folder picker and environment decoupling (#21003)
Rdmclin2d1ac1cbc664a
diff --git a/apps/server/src/routers/lambda/__tests__/environment.test.ts b/apps/server/src/routers/lambda/__tests__/environment.test.tsnew file mode 100644index 00000000000..daa2b69457f--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/environment.test.ts@@ -0,0 +1,232 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++const mockCreate = vi.fn();+const mockDelete = vi.fn();+const mockFindOwnedById = vi.fn();+const mockUpdate = vi.fn();++vi.mock('@/database/models/environment', () => ({+ EnvironmentModel: vi.fn(function () {+ return {+ create: mockCreate,+ delete: mockDelete,+ findOwnedById: mockFindOwnedById,+ query: vi.fn(async () => []),+ setVisibility: vi.fn(),+ update: mockUpdate,+ };+ }),+}));++const mockListRepositoryBranches = vi.fn();++vi.mock('@/server/services/connectorData', () => ({+ ConnectorDataService: vi.fn(function () {+ return {+ getGitHubClient: async () => ({ listRepositoryBranches: mockListRepositoryBranches }),+ };+ }),+}));++// The definitions need no drive: if this router ever asked for the claim, the+// throw would fail every test below.+vi.mock('@/server/services/sandbox', () => ({+ resolveSandboxStorageClaim: vi.fn(() => {+ throw new Error('environment definitions must not ask for a drive');+ }),+}));++const { environmentRouter } = await import('../environment');+const { ConnectorDataError } = await import('@lobechat/connector-data');++/** Shaped like the driver error drizzle surfaces, nested behind `cause`. */+const driverError = (code: string, constraint?: string) => {+ const error = new Error('constraint violated');+ (error as any).cause = { code, constraint };+ return error;+};++const environmentId = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';++describe('environmentRouter', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' };+ const caller = () => environmentRouter.createCaller(ctx);++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('environment kind', () => {+ // Stored with the rest of the definition, in the same jsonb column, so the+ // parse must keep it rather than strip it as an unknown key. Only `code`:+ // a folder of files is a folder on the drive, not an environment.+ it('stores a code environment and refuses any other kind', async () => {+ mockCreate.mockResolvedValue({ id: 'env-code', name: 'Atlas' });++ await caller().createEnvironment({ configuration: { kind: 'code' }, name: 'Atlas' });+ expect(mockCreate).toHaveBeenCalledWith(+ expect.objectContaining({ configuration: { kind: 'code' } }),+ );++ for (const kind of ['files', 'cluster']) {+ mockCreate.mockClear();+ await expect(+ caller().createEnvironment({ configuration: { kind: kind as never }, name: 'Refused' }),+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ }+ });++ it('still saves an edit to an environment the previous release stored as files', async () => {+ mockFindOwnedById.mockResolvedValue({ id: environmentId });+ mockUpdate.mockResolvedValue({ id: environmentId, name: 'Legacy' });++ await caller().updateEnvironment({+ configuration: { bootstrapCommand: 'make', kind: 'files' },+ id: environmentId,+ });++ expect(mockUpdate).toHaveBeenCalledWith(+ environmentId,+ expect.objectContaining({ configuration: { bootstrapCommand: 'make', kind: 'files' } }),+ );+ });++ it('creates the definition alone, with no folder on any drive', async () => {+ mockCreate.mockResolvedValue({ id: 'env-code', name: 'Atlas' });++ await expect(caller().createEnvironment({ name: 'Atlas' })).resolves.toEqual({+ id: 'env-code',+ name: 'Atlas',+ });+ });+ });++ describe('environment source urls', () => {+ it('stores a github checkout and refuses any other host', async () => {+ // The picker only ever produces a github.com URL, but this is an RPC: a+ // caller reaching it directly could otherwise name an internal address+ // and have a build make the execution plane fetch it.+ mockCreate.mockResolvedValue({ id: 'env-allowed', name: 'Allowed' });++ await caller().createEnvironment({+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }] },+ name: 'Allowed',+ });+ expect(mockCreate).toHaveBeenCalled();++ for (const url of [+ 'https://169.254.169.254/latest/meta-data',+ 'https://internal.corp/repo.git',+ 'https://github.com.attacker.test/a/b',+ 'http://github.com/a/b',+ ]) {+ mockCreate.mockClear();+ await expect(+ caller().createEnvironment({+ configuration: { sources: [{ kind: 'git', url }] },+ name: 'Refused',+ }),+ ).rejects.toThrow();+ expect(mockCreate).not.toHaveBeenCalled();+ }+ });+ });++ describe('environment names', () => {+ it.each(['environments_user_name_unique', 'environments_workspace_user_name_unique'])(+ 'maps a collision on %s to CONFLICT',+ async (constraint) => {+ mockCreate.mockRejectedValue(driverError('23505', constraint));++ await expect(caller().createEnvironment({ name: 'Data analysis' })).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'DUPLICATE_ENVIRONMENT_NAME',+ });+ },+ );++ it('maps a collision on rename to CONFLICT', async () => {+ mockUpdate.mockRejectedValue(driverError('23505', 'environments_user_name_unique'));++ await expect(+ caller().updateEnvironment({ id: environmentId, name: 'Data analysis' }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_ENVIRONMENT_NAME' });+ });++ it('leaves unrelated failures untouched', async () => {+ mockCreate.mockRejectedValue(driverError('23505', 'some_other_unique_index'));++ await expect(caller().createEnvironment({ name: 'Data analysis' })).rejects.not.toMatchObject(+ { code: 'CONFLICT' },+ );+ });+ });++ describe('removeEnvironment', () => {+ it('refuses while a folder is still initialized from it', async () => {+ mockFindOwnedById.mockResolvedValue({ id: environmentId });+ mockDelete.mockRejectedValue(driverError('23503'));++ await expect(caller().removeEnvironment({ id: environmentId })).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'ENVIRONMENT_HAS_INSTANCES',+ });+ });++ it('refuses an environment the caller does not own', async () => {+ mockFindOwnedById.mockResolvedValue(undefined);++ await expect(caller().removeEnvironment({ id: environmentId })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mockDelete).not.toHaveBeenCalled();+ });+ });++ describe('listGithubBranches', () => {+ it('lists the branches of one repository through the connected GitHub account', async () => {+ mockListRepositoryBranches.mockResolvedValue(['canary', 'main']);++ const result = await caller().listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });++ expect(result).toEqual({ branches: ['canary', 'main'], connected: true, truncated: false });+ expect(mockListRepositoryBranches).toHaveBeenCalledWith('lobehub', 'lobehub');+ });++ // At the ceiling the list may be partial; the picker falls back to typing+ // so a branch past it can still be entered.+ it('says when the list reached the ceiling and may be partial', async () => {+ mockListRepositoryBranches.mockResolvedValue(+ Array.from({ length: 1000 }, (_, index) => `branch-${index}`),+ );++ const result = await caller().listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });++ expect(result.truncated).toBe(true);+ });++ it('answers not connected rather than failing when GitHub is unavailable', async () => {+ mockListRepositoryBranches.mockRejectedValue(+ new ConnectorDataError({+ code: 'not_connected',+ message: 'no token',+ operation: 'listRepositoryBranches',+ provider: 'github',+ retryable: false,+ }),+ );++ const result = await caller().listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });++ expect(result).toEqual({ branches: [], connected: false, truncated: false });+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.tsdeleted file mode 100644index 9d1281b3eb0..00000000000--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.defaultInstance.test.ts+++ /dev/null@@ -1,325 +0,0 @@-// @vitest-environment node-import { getTestDB } from '@lobechat/database/test-utils';-import { pickDefaultInstance } from '@lobechat/utils/environmentInstance';-import { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import {- agents,- environmentInstances,- environments,- projectEnvironments,- projects,- users,-} from '@/database/schemas';-import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';--import { sandboxStorageRouter } from '../sandboxStorage';--/**- * The default-instance rules against a real database: what the router writes,- * what it refuses, and what a refusal leaves behind. Only the execution plane- * and the entitlement are stubbed; every row is read back from Postgres.- */-const serverDB = await getTestDB();-const userId = 'sandbox-default-instance-user';--const plane = vi.hoisted(() => ({- copyInstance: vi.fn(),- deleteInstance: vi.fn(),- readOccupancy: vi.fn(),-}));--vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {- const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');- return { ...(await importOriginal<object>()), wsCompatProcedure: mod.trpc.procedure };-});--vi.mock('@/libs/trpc/lambda/middleware', () => ({- serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),-}));--vi.mock('@/server/services/sandbox', () => ({- resolveSandboxSessionConfig: vi.fn(),- resolveSandboxStorageClaim: vi.fn(async () => ({ key: 'default-instance-ws', quotaBytes: 1 })),-}));--vi.mock('@/server/services/market', () => ({- MarketService: vi.fn(function () {- return { getSandboxStorageClient: () => plane };- }),-}));--const caller = () => sandboxStorageRouter.createCaller({ serverDB, userId } as any);--type CreateEnvironmentInput = Parameters<ReturnType<typeof caller>['createEnvironment']>[0];--/** As the current client calls it: asking for the default instance. */-const createEnvironment = async (input: CreateEnvironmentInput) => {- const { defaultInstance, ...environment } = await caller().createEnvironment({- ...input,- withDefaultInstance: true,- });-- return { ...environment, defaultInstance: defaultInstance! };-};--const instancesOf = (environmentId: string) =>- serverDB- .select()- .from(environmentInstances)- .where(eq(environmentInstances.environmentId, environmentId));--const environmentExists = async (id: string) =>- (await serverDB.select().from(environments).where(eq(environments.id, id))).length === 1;--const reset = async () => {- await serverDB.delete(projectEnvironments);- await serverDB.delete(projects);- await serverDB.delete(agents);- await serverDB.delete(environmentInstances);- await serverDB.delete(environments);- await serverDB.delete(users).where(eq(users.id, userId));-};--beforeEach(async () => {- await reset();- await serverDB.insert(users).values({ id: userId });- plane.copyInstance.mockReset().mockResolvedValue(undefined);- plane.deleteInstance.mockReset().mockResolvedValue(undefined);- plane.readOccupancy.mockReset().mockResolvedValue({ held: [], unavailable: false });-});--afterEach(reset);--describe('createEnvironment', () => {- it('persists exactly one instance with the environment, and returns it as the default', async () => {- const created = await createEnvironment({- configuration: { bootstrapCommand: 'pip install pandas' },- name: 'Python ๆฐๆฎๅๆ',- });-- const rows = await instancesOf(created.id);- expect(rows).toHaveLength(1);- expect(created.defaultInstance).toMatchObject({- environmentId: created.id,- id: rows[0].id,- kind: 'sandbox',- name: 'python-ๆฐๆฎๅๆ',- providerScope: 'default-instance-ws',- status: 'pending',- workingDirectory: 'python-ๆฐๆฎๅๆ',- });- expect(pickDefaultInstance(rows)?.id).toBe(created.defaultInstance.id);- // Building is a sandbox cold start, left for the client's next call.- expect(plane.readOccupancy).not.toHaveBeenCalled();- });-- it('stores a default instance with nothing to build as ready', async () => {- // No build will ever run for it, and a files environment offers no rebuild:- // a row left `pending` here could only be cleared by deleting the environment.- const created = await createEnvironment({- configuration: { kind: 'files' },- name: 'Quarterly reports',- });-- expect(created.defaultInstance.status).toBe('ready');- expect((await instancesOf(created.id))[0].status).toBe('ready');- });-- it('stores a later copy with nothing to build as ready too', async () => {- const created = await createEnvironment({- configuration: { kind: 'files' },- name: 'Quarterly reports',- });-- const copy = await caller().createInstanceForEnvironment({ environmentId: created.id });-- expect(copy.status).toBe('ready');- const rows = await instancesOf(created.id);- expect(rows.find((row) => row.id === copy.id)?.status).toBe('ready');- });-- it('creates the environment alone for a client that does not ask for a default instance', async () => {- // A client from before default instances opens its own create-instance- // dialog next; one made here too would leave it with two.- const created = await caller().createEnvironment({ name: 'Legacy client' });-- expect(created.defaultInstance).toBeUndefined();- expect(await instancesOf(created.id)).toHaveLength(0);- expect(await environmentExists(created.id)).toBe(true);- });-- it('derives the next directory when the slug is already taken in the workspace', async () => {- const first = await createEnvironment({ name: 'Atlas' });- const second = await createEnvironment({ name: 'atlas!' });-- expect(first.defaultInstance.workingDirectory).toBe('atlas');- expect(second.defaultInstance.workingDirectory).toBe('atlas-2');- });-- it('leaves nothing behind when the environment name is taken', async () => {- await createEnvironment({ name: 'Taken' });-- await expect(createEnvironment({ name: 'Taken' })).rejects.toMatchObject({- message: 'DUPLICATE_ENVIRONMENT_NAME',- });- expect(await serverDB.select().from(environmentInstances)).toHaveLength(1);- });-});--describe('removeInstance', () => {- it('refuses the default instance and keeps its row', async () => {- const created = await createEnvironment({ name: 'Keep default' });-- await expect(caller().removeInstance({ id: created.defaultInstance.id })).rejects.toMatchObject(- { code: 'FORBIDDEN', message: 'DEFAULT_INSTANCE' },- );-- expect(plane.deleteInstance).not.toHaveBeenCalled();- expect((await instancesOf(created.id)).map((row) => row.id)).toEqual([- created.defaultInstance.id,- ]);- });-- it('removes a later copy and leaves the default in place', async () => {- const created = await createEnvironment({ name: 'Two copies' });- const copy = await caller().createInstanceForEnvironment({ environmentId: created.id });-- await caller().removeInstance({ id: copy.id });-- expect(plane.deleteInstance).toHaveBeenCalledWith({ name: copy.id, topicId: undefined });- expect((await instancesOf(created.id)).map((row) => row.id)).toEqual([- created.defaultInstance.id,- ]);- });-- it('treats the lower id as the default when two instances share a creation time', async () => {- const created = await createEnvironment({ name: 'Tied' });- const copy = await caller().createInstanceForEnvironment({ environmentId: created.id });- await serverDB- .update(environmentInstances)- .set({ createdAt: new Date('2026-01-01T00:00:00Z') })- .where(eq(environmentInstances.environmentId, created.id));- const [lower, higher] = [created.defaultInstance.id, copy.id].sort();-- await expect(caller().removeInstance({ id: lower })).rejects.toMatchObject({- message: 'DEFAULT_INSTANCE',- });- await caller().removeInstance({ id: higher });-- expect((await instancesOf(created.id)).map((row) => row.id)).toEqual([lower]);- });-});--describe('copyInstance', () => {- it('refuses a held source without writing a row', async () => {- const created = await createEnvironment({ name: 'Held' });- plane.readOccupancy.mockResolvedValue({- held: [{ id: created.defaultInstance.id, own: false }],- unavailable: false,- });-- await expect(- caller().copyInstance({- id: created.defaultInstance.id,- name: 'copy',- workingDirectory: 'c',- }),- ).rejects.toMatchObject({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });-- expect(plane.copyInstance).not.toHaveBeenCalled();- expect(await instancesOf(created.id)).toHaveLength(1);- });-- it('refuses when occupancy cannot be read, rather than treating the source as free', async () => {- const created = await createEnvironment({ name: 'Unknown' });- plane.readOccupancy.mockRejectedValue(new Error('lease store down'));-- await expect(- caller().copyInstance({- id: created.defaultInstance.id,- name: 'copy',- workingDirectory: 'c',- }),- ).rejects.toMatchObject({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });-- expect(plane.copyInstance).not.toHaveBeenCalled();- expect(await instancesOf(created.id)).toHaveLength(1);- });-- it('copies an idle source into a ready instance', async () => {- const created = await createEnvironment({ name: 'Idle' });-- const copy = await caller().copyInstance({- id: created.defaultInstance.id,- name: 'copy',- workingDirectory: 'idle-copy',- });-- expect(copy.status).toBe('ready');- expect(await instancesOf(created.id)).toHaveLength(2);- });-});--describe('removeEnvironment', () => {- it('takes the default instance with it', async () => {- const created = await createEnvironment({ name: 'Gone' });-- await caller().removeEnvironment({ id: created.id });-- expect(plane.deleteInstance).toHaveBeenCalledWith({- name: created.defaultInstance.id,- topicId: undefined,- });- expect(await environmentExists(created.id)).toBe(false);- expect(await instancesOf(created.id)).toHaveLength(0);- });-- it('rolls everything back when a run still holds the default instance', async () => {- const created = await createEnvironment({ name: 'Held env' });- plane.deleteInstance.mockRejectedValue(new SandboxStorageFilesError('in use', 409));-- await expect(caller().removeEnvironment({ id: created.id })).rejects.toMatchObject({- code: 'CONFLICT',- });-- expect(await environmentExists(created.id)).toBe(true);- expect(await instancesOf(created.id)).toHaveLength(1);- });-- it('refuses an environment a project still uses before touching the snapshot', async () => {- const created = await createEnvironment({ name: 'Bound' });- const [agent] = await serverDB.insert(agents).values({ userId }).returning();- const [project] = await serverDB- .insert(projects)- .values({ coordinatorAgentId: agent.id, identifier: 'BND', name: 'Bound', userId })- .returning();- await serverDB- .insert(projectEnvironments)- .values({ environmentId: created.id, projectId: project.id });-- await expect(caller().removeEnvironment({ id: created.id })).rejects.toMatchObject({- code: 'CONFLICT',- message: 'ENVIRONMENT_HAS_INSTANCES',- });-- expect(plane.deleteInstance).not.toHaveBeenCalled();- expect(await environmentExists(created.id)).toBe(true);- expect((await instancesOf(created.id)).map((row) => row.id)).toEqual([- created.defaultInstance.id,- ]);- });-- it('refuses while a copy besides the default remains', async () => {- const created = await createEnvironment({ name: 'Crowded' });- await caller().createInstanceForEnvironment({ environmentId: created.id });-- await expect(caller().removeEnvironment({ id: created.id })).rejects.toMatchObject({- message: 'ENVIRONMENT_HAS_INSTANCES',- });-- expect(plane.deleteInstance).not.toHaveBeenCalled();- expect(await instancesOf(created.id)).toHaveLength(2);- });-});diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.tsnew file mode 100644index 00000000000..902bbcbbcfc--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.drive.test.ts@@ -0,0 +1,581 @@+// @vitest-environment node+import { deriveSandboxStorageKey } from '@lobechat/builtin-tool-cloud-sandbox';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { EnvironmentInstanceModel } from '@/database/models/environmentInstance';+import {+ agents,+ environmentInstances,+ environments,+ projectEnvironments,+ projects,+ users,+ workspaceMembers,+ workspaces,+} from '@/database/schemas';+import { sandboxStorageBinding } from '@/server/services/sandbox/binding';+import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';++import { environmentRouter } from '../environment';+import { sandboxStorageRouter } from '../sandboxStorage';++/**+ * The drive and the environments initialized on it, against a real database:+ * what the routers write, what they refuse, and what a shared drive shows each+ * member. Only the execution plane and the entitlement are stubbed; every row+ * is read back from Postgres.+ */+const serverDB = await getTestDB();+const ownerId = 'drive-owner';+const memberId = 'drive-member';+// Word characters only, like every workspace id the platform issues: it is+// what lets a member drive's key split back into workspace and member.+const workspaceId = 'drive_workspace';+const STORAGE_KEY = `ws-org-${workspaceId}`;+const personalKey = (userId: string) => `ws-mem-${workspaceId}-${userId}`;++const plane = vi.hoisted(() => ({+ copyInstance: vi.fn(),+ createDirectory: vi.fn(),+ deleteFile: vi.fn(),+ deleteInstance: vi.fn(),+ getStorage: vi.fn(),+ listFiles: vi.fn(),+ readOccupancy: vi.fn(),+ renameFile: vi.fn(),+ writeFile: vi.fn(),+}));++const entitlement = vi.hoisted(() => ({ claim: vi.fn() }));++/** The storage key of every client the router made, in order: whose drive each call reached. */+const reached = vi.hoisted(() => [] as (string | undefined)[]);++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {+ // Only the workspace gate is replaced; routers mounted beside this one (the+ // environment aliases) import the module's other middlewares as they are.+ const actual = await importOriginal<Record<string, unknown>>();+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { ...actual, wsCompatProcedure: mod.trpc.procedure };+});++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),+}));++vi.mock('@/server/services/sandbox', async () => {+ const binding = await vi.importActual<any>('@/server/services/sandbox/binding');++ return {+ ...binding,+ ...(await vi.importActual<object>('@/server/services/sandbox/driveAccess')),+ ...(await vi.importActual<object>('@/server/services/sandbox/driveUsage')),+ forgetDriveFolders: vi.fn(),+ resolveSandboxSessionConfig: vi.fn(),+ resolveSandboxStorageClaim: entitlement.claim,+ };+});++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(function (options: { userInfo?: { sandboxStorage?: { key?: string } } }) {+ return {+ getSandboxStorageClient: () => {+ reached.push(options?.userInfo?.sandboxStorage?.key);+ return plane;+ },+ };+ }),+}));++const asMember = (userId: string) => ({ serverDB, userId, workspaceId }) as any;+const drive = (userId = ownerId) => sandboxStorageRouter.createCaller(asMember(userId));+const definitions = (userId = ownerId) => environmentRouter.createCaller(asMember(userId));++const instancesOf = (environmentId: string) =>+ serverDB+ .select()+ .from(environmentInstances)+ .where(eq(environmentInstances.environmentId, environmentId));++const environmentExists = async (id: string) =>+ (await serverDB.select().from(environments).where(eq(environments.id, id))).length === 1;++const notFound = () => new SandboxStorageFilesError('not found', 404);++const reset = async () => {+ await serverDB.delete(projectEnvironments);+ await serverDB.delete(projects);+ await serverDB.delete(agents);+ await serverDB.delete(environmentInstances);+ await serverDB.delete(environments);+ await serverDB.delete(workspaceMembers).where(eq(workspaceMembers.workspaceId, workspaceId));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await serverDB.delete(users).where(eq(users.id, ownerId));+ await serverDB.delete(users).where(eq(users.id, memberId));+};++beforeEach(async () => {+ await reset();+ await serverDB.insert(users).values([{ id: ownerId }, { id: memberId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: ownerId, slug: workspaceId });+ // The real key for the drive asked about, the way the entitlement derives it.+ entitlement.claim.mockReset().mockImplementation(async (scope: any) => {+ const key = deriveSandboxStorageKey(scope);+ return key ? { key, quotaBytes: 1 } : null;+ });+ reached.length = 0;+ plane.getStorage.mockReset().mockImplementation(async () => ({ usageBytes: 10 }));+ plane.copyInstance.mockReset().mockResolvedValue(undefined);+ plane.createDirectory.mockReset().mockImplementation(async ({ path }) => ({ path }));+ plane.deleteFile.mockReset().mockImplementation(async ({ path }) => ({ path }));+ plane.deleteInstance.mockReset().mockResolvedValue(undefined);+ plane.listFiles.mockReset().mockRejectedValue(notFound());+ plane.readOccupancy.mockReset().mockResolvedValue({ held: [], unavailable: false });+ plane.renameFile.mockReset().mockImplementation(async ({ newPath }) => ({ path: newPath }));+ plane.writeFile.mockReset().mockImplementation(async ({ path }) => ({ path }));+});++afterEach(reset);++/** An environment and one folder initialized from it, as the picker makes them. */+const initializeFolder = async (+ userId: string,+ name: string,+ visibility: 'private' | 'public' = 'private',+) => {+ const environment = await definitions(userId).createEnvironment({ name, visibility });+ const instance = await drive(userId).createInstance({+ environmentId: environment.id,+ name,+ workingDirectory: name,+ });++ return { environment, instance };+};++describe('sandboxStorage.createEnvironment, as released', () => {+ // A client from before the environment router moved out sends+ // `withDefaultInstance` and starts the build of the instance it gets back.+ it('should create the default instance the old client asks for', async () => {+ const created = await drive().createEnvironment({+ name: 'Atlas',+ visibility: 'public',+ withDefaultInstance: true,+ });++ expect(created.defaultInstance).toMatchObject({ environmentId: created.id });+ expect(await instancesOf(created.id)).toHaveLength(1);+ });++ it('should still create the Files environment a released client offers', async () => {+ const created = await drive().createEnvironment({+ configuration: { kind: 'files' },+ name: 'Notes',+ visibility: 'public',+ withDefaultInstance: true,+ });++ expect(created.defaultInstance).toMatchObject({ environmentId: created.id });+ });++ it('should be the definition alone without the flag', async () => {+ const created = await drive().createEnvironment({ name: 'Atlas', visibility: 'public' });++ expect(created.defaultInstance).toBeUndefined();+ expect(await instancesOf(created.id)).toHaveLength(0);+ });++ it('should take the environment back when the instance cannot be made', async () => {+ entitlement.claim.mockResolvedValue(null);++ await expect(+ drive().createEnvironment({ name: 'Atlas', withDefaultInstance: true }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(definitions().listEnvironments()).resolves.toEqual({ environments: [] });+ });+});++describe('environment definitions', () => {+ it('are written and read without any drive', async () => {+ entitlement.claim.mockResolvedValue(null);++ const created = await definitions().createEnvironment({+ configuration: { bootstrapCommand: 'pip install pandas', kind: 'code' },+ name: 'Python ๆฐๆฎๅๆ',+ });++ expect(await instancesOf(created.id)).toHaveLength(0);+ await expect(definitions().listEnvironments()).resolves.toMatchObject({+ environments: [expect.objectContaining({ id: created.id, name: 'Python ๆฐๆฎๅๆ' })],+ });+ await definitions().updateEnvironment({ id: created.id, name: 'Renamed' });+ await expect(drive().listInstances({})).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('refuses a files environment: a folder of files is a folder on the drive', async () => {+ await expect(+ definitions().createEnvironment({ configuration: { kind: 'files' } as any, name: 'Docs' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('refuses to remove an environment a folder is still initialized from', async () => {+ const { environment, instance } = await initializeFolder(ownerId, 'atlas');++ await expect(definitions().removeEnvironment({ id: environment.id })).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'ENVIRONMENT_HAS_INSTANCES',+ });++ await drive().removeInstance({ id: instance.id });+ await definitions().removeEnvironment({ id: environment.id });+ expect(await environmentExists(environment.id)).toBe(false);+ });++ it('removes an environment with its copies through the released route', async () => {+ // Released clients delete an environment with its only copy in one call,+ // and the current page has no way to delete a copy at all.+ const { environment, instance } = await initializeFolder(ownerId, 'atlas');++ await drive().removeEnvironment({ id: environment.id });++ expect(plane.deleteInstance).toHaveBeenCalledWith({ name: instance.id, topicId: undefined });+ expect(await instancesOf(environment.id)).toHaveLength(0);+ expect(await environmentExists(environment.id)).toBe(false);+ });++ it('keeps the environment and its copy when the snapshot cannot be dropped', async () => {+ const { environment } = await initializeFolder(ownerId, 'atlas');+ plane.deleteInstance.mockRejectedValue(new Error('a run still holds it'));++ await expect(drive().removeEnvironment({ id: environment.id })).rejects.toBeTruthy();++ expect(await instancesOf(environment.id)).toHaveLength(1);+ expect(await environmentExists(environment.id)).toBe(true);+ });++ it('leaves every copy whole when a later snapshot cannot be dropped', async () => {+ // Copy by copy: the first is gone with its snapshot, the second keeps both.+ const { environment, instance: first } = await initializeFolder(ownerId, 'atlas');+ const second = await drive(ownerId).createInstance({+ environmentId: environment.id,+ name: 'atlas-2',+ workingDirectory: 'atlas-2',+ });+ plane.deleteInstance.mockImplementation(async ({ name }: { name: string }) => {+ if (name === second.id) throw new Error('a run still holds it');+ });++ await expect(drive().removeEnvironment({ id: environment.id })).rejects.toBeTruthy();++ const left = await instancesOf(environment.id);+ expect(left.map((entry) => entry.id)).toEqual([second.id]);+ expect(left.map((entry) => entry.id)).not.toContain(first.id);+ expect(await environmentExists(environment.id)).toBe(true);+ });++ it('loses no copy when a project still uses the environment', async () => {+ // The project's reference refuses the delete; the copy's row and its+ // snapshot must both still be there afterwards.+ const { environment } = await initializeFolder(ownerId, 'atlas');+ const [agent] = await serverDB.insert(agents).values({ userId: ownerId }).returning();+ const [project] = await serverDB+ .insert(projects)+ .values({ coordinatorAgentId: agent.id, identifier: 'ATL', name: 'Atlas', userId: ownerId })+ .returning();+ await serverDB+ .insert(projectEnvironments)+ .values({ environmentId: environment.id, projectId: project.id });++ await expect(drive().removeEnvironment({ id: environment.id })).rejects.toMatchObject({+ message: 'ENVIRONMENT_IN_PROJECT',+ });++ expect(plane.deleteInstance).not.toHaveBeenCalled();+ expect(await instancesOf(environment.id)).toHaveLength(1);+ expect(await environmentExists(environment.id)).toBe(true);+ });++ it('refuses an environment a project still uses', async () => {+ const created = await definitions().createEnvironment({ name: 'Bound' });+ const [agent] = await serverDB.insert(agents).values({ userId: ownerId }).returning();+ const [project] = await serverDB+ .insert(projects)+ .values({ coordinatorAgentId: agent.id, identifier: 'BND', name: 'Bound', userId: ownerId })+ .returning();+ await serverDB+ .insert(projectEnvironments)+ .values({ environmentId: created.id, projectId: project.id });++ await expect(definitions().removeEnvironment({ id: created.id })).rejects.toMatchObject({+ message: 'ENVIRONMENT_IN_PROJECT',+ });+ });+});++describe('initializing a folder', () => {+ it("creates a private environment's directory at the root of its owner's personal drive", async () => {+ const { environment, instance } = await initializeFolder(ownerId, 'atlas');++ expect(instance).toMatchObject({+ drive: 'personal',+ environmentId: environment.id,+ kind: 'sandbox',+ providerScope: personalKey(ownerId),+ status: 'pending',+ workingDirectory: 'atlas',+ });+ });++ it("creates a published environment's directory on the public drive", async () => {+ const { instance } = await initializeFolder(ownerId, 'shared', 'public');++ expect(instance).toMatchObject({ drive: 'public', providerScope: STORAGE_KEY });+ });++ it('never nests an environment directory', async () => {+ const environment = await definitions().createEnvironment({ name: 'Nested' });++ await expect(+ drive().createInstance({+ environmentId: environment.id,+ name: 'nested',+ workingDirectory: 'projects/nested',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('refuses a folder that already holds work', async () => {+ const environment = await definitions().createEnvironment({ name: 'Busy' });+ plane.listFiles.mockResolvedValue({ entries: [{ name: 'notes.md' }], path: 'busy' });++ await expect(+ drive().createInstance({+ environmentId: environment.id,+ name: 'busy',+ workingDirectory: 'busy',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'FOLDER_NOT_EMPTY' });+ expect(await instancesOf(environment.id)).toHaveLength(0);+ });++ it('removes any environment directory, the first one included', async () => {+ const { environment, instance } = await initializeFolder(ownerId, 'atlas');++ await drive().removeInstance({ id: instance.id });++ expect(plane.deleteInstance).toHaveBeenCalledWith({ name: instance.id, topicId: undefined });+ expect(await instancesOf(environment.id)).toHaveLength(0);+ });++ it('copies an occupied environment directory into a new root folder', async () => {+ const { instance } = await initializeFolder(ownerId, 'atlas');++ const copy = await drive().copyInstance({+ id: instance.id,+ name: 'atlas-copy',+ workingDirectory: 'atlas-copy',+ });++ expect(copy).toMatchObject({ status: 'ready', workingDirectory: 'atlas-copy' });+ });+});++/** A private environment's directory left on the public drive, from before personal drives. */+const legacyPrivateFolder = async (userId: string, name: string) => {+ const environment = await definitions(userId).createEnvironment({ name });+ const instance = await new EnvironmentInstanceModel(serverDB, userId, workspaceId).create({+ ...sandboxStorageBinding(STORAGE_KEY),+ environmentId: environment.id,+ name,+ workingDirectory: name,+ });++ return instance!;+};++describe("a member's personal drive", () => {+ it('is reached only by its owner', async () => {+ plane.listFiles.mockResolvedValue({ entries: [], path: '', truncated: false });+ await drive(ownerId).listFiles({ drive: 'personal' });+ await drive(memberId).listFiles({ drive: 'personal' });++ // Each member's call went to their own drive, and neither reached the other's.+ expect(reached).toEqual([personalKey(ownerId), personalKey(memberId)]);+ });++ it("lists a private environment's directory to its owner alone", async () => {+ const { instance } = await initializeFolder(ownerId, 'atlas');++ const mine = await drive(ownerId).listInstances({ drive: 'personal', withSizes: false });+ const theirs = await drive(memberId).listInstances({ drive: 'personal', withSizes: false });+ const onPublic = await drive(memberId).listInstances({ drive: 'public', withSizes: false });++ expect(mine.instances.map((entry) => entry.id)).toEqual([instance.id]);+ expect(theirs.instances).toEqual([]);+ expect(onPublic.instances).toEqual([]);+ });++ it("refuses another member every route into an instance on the owner's drive", async () => {+ const { instance } = await initializeFolder(ownerId, 'atlas');+ reached.length = 0;++ for (const call of [+ () => drive(memberId).listFiles({ instanceId: instance.id }),+ () => drive(memberId).readFile({ instanceId: instance.id, path: 'atlas/.env' }),+ () => drive(memberId).startInstanceBuild({ id: instance.id }),+ () => drive(memberId).removeInstance({ id: instance.id }),+ ]) {+ await expect(call()).rejects.toMatchObject({ code: 'NOT_FOUND' });+ }+ expect(reached.filter((key) => key === personalKey(ownerId))).toEqual([]);+ });+});++describe('the public drive', () => {+ it('is the same drive for every member', async () => {+ plane.listFiles.mockResolvedValue({ entries: [], path: '', truncated: false });+ await drive(ownerId).listFiles({ drive: 'public' });+ await drive(memberId).listFiles({});++ expect(reached).toEqual([STORAGE_KEY, STORAGE_KEY]);+ });++ it('hides a private environment directory left there, from its owner too', async () => {+ const legacy = await legacyPrivateFolder(ownerId, 'secret');+ await initializeFolder(ownerId, 'shared', 'public');+ plane.listFiles.mockResolvedValue({+ entries: ['projA', 'secret', 'shared'].map((name) => ({+ isDirectory: true,+ name,+ path: name,+ })),+ path: '',+ truncated: false,+ });++ const asMember = await drive(memberId).listFiles({});+ const asOwner = await drive(ownerId).listFiles({});++ expect(asMember.entries.map((entry) => entry.name)).toEqual(['projA', 'shared']);+ expect(asOwner.entries.map((entry) => entry.name)).toEqual(['projA', 'shared']);+ // Nested paths too: a recursive listing of the root reaches inside it.+ plane.listFiles.mockResolvedValue({+ entries: [{ isDirectory: false, name: 'key', path: 'secret/key' }],+ path: '',+ truncated: false,+ });+ expect((await drive(memberId).listFiles({ recursive: true })).entries).toEqual([]);+ await expect(drive(ownerId).readFile({ path: 'secret/.env' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ // Its owner is told what to do about it; nobody else learns it exists.+ const owned = await drive(ownerId).listInstances({ drive: 'public', withSizes: false });+ expect(owned.instances).toEqual([+ expect.objectContaining({ id: legacy.id, rebuildRequired: true }),+ expect.objectContaining({ rebuildRequired: false }),+ ]);+ const others = await drive(memberId).listInstances({ drive: 'public', withSizes: false });+ expect(others.instances.map((entry) => entry.rebuildRequired)).toEqual([false]);+ });++ it('refuses to move or delete a folder that holds one', async () => {+ // Renaming `projects` would carry `projects/secret` out from under the+ // path that keeps it hidden, into the open on the public drive.+ await legacyPrivateFolder(ownerId, 'projects/secret');++ await expect(+ drive(memberId).renameFile({ newPath: 'projects-old', path: 'projects' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'PATH_HOLDS_HIDDEN' });+ await expect(+ drive(ownerId).removeFile({ path: 'projects', recursive: true }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'PATH_HOLDS_HIDDEN' });+ expect(plane.renameFile).not.toHaveBeenCalled();+ expect(plane.deleteFile).not.toHaveBeenCalled();+ });++ it('builds nothing more into a private environment directory left there', async () => {+ const legacy = await legacyPrivateFolder(ownerId, 'secret');+ await serverDB+ .update(environmentInstances)+ .set({ configurationSnapshot: { bootstrapCommand: 'make' } })+ .where(eq(environmentInstances.id, legacy.id));++ await expect(drive(ownerId).startInstanceBuild({ id: legacy.id })).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'INSTANCE_REBUILD_REQUIRED',+ });+ await expect(+ drive(ownerId).copyInstance({ id: legacy.id, name: 'copy', workingDirectory: 'copy' }),+ ).rejects.toMatchObject({ message: 'INSTANCE_REBUILD_REQUIRED' });++ // What replaces it lands on the owner's personal drive.+ const rebuilt = await drive(ownerId).createInstanceForEnvironment({+ environmentId: legacy.environmentId,+ });+ expect(rebuilt.providerScope).toBe(personalKey(ownerId));+ });++ it('lets every member create, rename and delete ordinary folders at the root', async () => {+ await drive(memberId).createDirectory({ path: 'projB' });+ await drive(memberId).renameFile({ newPath: 'projC', path: 'projB' });+ await drive(memberId).removeFile({ path: 'projC', recursive: true });++ expect(plane.createDirectory).toHaveBeenCalledWith({ path: 'projB' });+ expect(plane.renameFile).toHaveBeenCalledWith({ newPath: 'projC', path: 'projB' });+ expect(plane.deleteFile).toHaveBeenCalledWith({ path: 'projC', recursive: true });+ });++ it('treats a folder an environment initialized as an ordinary folder', async () => {+ // Environments initialize a folder once; nothing keeps it read-only after.+ await initializeFolder(ownerId, 'atlas', 'public');+ plane.writeFile.mockResolvedValue({ path: 'atlas/notes.md' });+ plane.renameFile.mockResolvedValue({ path: 'atlas-old' });++ await expect(+ drive(ownerId).writeFile({ content: 'x', path: 'atlas/notes.md' }),+ ).resolves.toMatchObject({ path: 'atlas/notes.md' });+ await expect(+ drive(memberId).renameFile({ newPath: 'atlas-old', path: 'atlas' }),+ ).resolves.toMatchObject({ path: 'atlas-old' });+ expect(plane.writeFile).toHaveBeenCalled();+ expect(plane.renameFile).toHaveBeenCalled();+ });+});++describe('drive usage', () => {+ it("shows an admin each member's personal drive usage and nothing else of it", async () => {+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId: ownerId, workspaceId },+ { role: 'member', userId: memberId, workspaceId },+ ]);+ plane.getStorage.mockImplementation(async () => ({+ usageBytes: 5,+ workspaceUsageBytes: 15,+ }));++ const asAdmin = await sandboxStorageRouter+ .createCaller({ ...asMember(ownerId), workspaceRole: 'owner' })+ .getDriveUsage();+ const asMemberView = await sandboxStorageRouter+ .createCaller({ ...asMember(memberId), workspaceRole: 'member' })+ .getDriveUsage();++ expect(asAdmin).toMatchObject({+ drives: [+ { drive: 'public', usageBytes: 5 },+ { drive: 'personal', usageBytes: 5 },+ ],+ members: [{ usageBytes: 5, userId: memberId }],+ quotaBytes: 1,+ totalUsageBytes: 15,+ });+ expect(asMemberView.members).toBeNull();+ // The usage read is the only call made with the member's key.+ expect(plane.listFiles).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.tsindex 41acfcb3cf8..c3df81cf49b 100644--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts@@ -2,12 +2,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';// serverDatabase middleware calls getServerDB(); stub it (the model mock-// ignores the db handle anyway). A transaction just runs its body: rollback is-// covered against a real database in sandboxStorage.defaultInstance.test.ts.-const { mockServerDB, mockTransaction } = vi.hoisted(() => {- const mockTransaction = vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn({}));- return { mockServerDB: { transaction: mockTransaction }, mockTransaction };-});+// ignores the db handle anyway). Real-database behaviour is covered in+// sandboxStorage.drive.test.ts.+const { mockServerDB } = vi.hoisted(() => ({+ mockServerDB: { transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn({}) },+}));vi.mock('@/database/core/db-adaptor', () => ({getServerDB: vi.fn(function () {@@ -45,6 +44,15 @@ const mockInstanceFindOwnedById = vi.fn();const mockInstanceQuery = vi.fn();const mockInstanceUpdate = vi.fn();const mockInstanceRecordBuildResult = vi.fn();+const mockListStorageDirectories = vi.fn();++/**+ * Every stored instance names the drive it is on. The fixtures below mostly+ * leave it out, so a row that does not say is on the caller's public drive โ+ * the one `ctx` below resolves to.+ */+const onPublicDrive = <T>(row: T) =>+ row && typeof row === 'object' ? { providerScope: 'ws-org-ws-1', ...row } : row;vi.mock('@/database/models/environmentInstance', () => ({InstanceDirectoryOverlapError: class InstanceDirectoryOverlapError extends Error {},@@ -52,10 +60,13 @@ vi.mock('@/database/models/environmentInstance', () => ({return {create: mockInstanceCreate,delete: mockInstanceDelete,- findById: mockInstanceFindById,- findOwnedById: mockInstanceFindOwnedById,+ findById: async (...args: unknown[]) => onPublicDrive(await mockInstanceFindById(...args)),+ findOwnedById: async (...args: unknown[]) =>+ onPublicDrive(await mockInstanceFindOwnedById(...args)),findByWorkingDirectory: vi.fn(),- query: mockInstanceQuery,+ listStorageDirectories: mockListStorageDirectories,+ query: async (...args: unknown[]) =>+ ((await mockInstanceQuery(...args)) as unknown[] | undefined)?.map(onPublicDrive),recordBuildResult: mockInstanceRecordBuildResult,update: mockInstanceUpdate,};@@ -82,6 +93,8 @@ const mockBuildInstance = vi.fn();const mockBuildStatus = vi.fn();const mockListEnvironments = vi.fn();const mockStopInstance = vi.fn();+const mockRenameFile = vi.fn();+const mockCreateDirectory = vi.fn();vi.mock('@/server/services/market', () => ({MarketService: vi.fn(function () {@@ -90,6 +103,7 @@ vi.mock('@/server/services/market', () => ({buildInstance: mockBuildInstance,buildStatus: mockBuildStatus,copyInstance: mockCopyEnvironment,+ createDirectory: mockCreateDirectory,deleteInstance: mockDeleteEnvironment,getStorage: mockGetWorkspace,listEnvironmentSessions: mockListEnvironmentSessions,@@ -98,6 +112,7 @@ vi.mock('@/server/services/market', () => ({readFile: mockReadFile,readOccupancy: mockReadOccupancy,refreshUsage: mockRefreshUsage,+ renameFile: mockRenameFile,stopInstance: mockStopInstance,readStopTarget: async () => ({ sessionId: 'session-1', topicId: null }),writeFile: mockWriteFile,@@ -106,20 +121,14 @@ vi.mock('@/server/services/market', () => ({}),}));-const mockListRepositoryBranches = vi.fn();--vi.mock('@/server/services/connectorData', () => ({- ConnectorDataService: vi.fn(function () {- return {- getGitHubClient: async () => ({ listRepositoryBranches: mockListRepositoryBranches }),- };- }),-}));-const mockResolveClaim = vi.fn();const mockResolveSessionConfig = vi.fn();-vi.mock('@/server/services/sandbox', () => ({+vi.mock('@/server/services/sandbox', async () => ({+ ...(await vi.importActual<object>('@/server/services/sandbox/binding')),+ ...(await vi.importActual<object>('@/server/services/sandbox/driveAccess')),+ ...(await vi.importActual<object>('@/server/services/sandbox/driveUsage')),+ forgetDriveFolders: vi.fn(),resolveSandboxSessionConfig: mockResolveSessionConfig,resolveSandboxStorageClaim: mockResolveClaim,}));@@ -132,7 +141,6 @@ vi.mock('@/server/services/scm/cloneCredential', () => ({const { sandboxStorageRouter } = await import('../sandboxStorage');const { SandboxStorageFilesError } = await import('@/server/services/sandbox/storageFiles');-const { ConnectorDataError } = await import('@lobechat/connector-data');/** Shaped like the driver error drizzle surfaces, nested behind `cause`. */const uniqueViolation = (constraint: string) => {@@ -152,9 +160,21 @@ describe('sandboxStorageRouter', () => {mockResolveClaim.mockResolvedValue({ key: 'ws-org-1', quotaBytes: 1024 });mockInstanceRecordBuildResult.mockResolvedValue(undefined);mockReadOccupancy.mockResolvedValue({ held: [], unavailable: false });+ // A folder that is not on the drive yet, which is what a new environment+ // directory or a copy lands in.+ mockListFiles.mockRejectedValue(new SandboxStorageFilesError('not found', 404));+ mockListStorageDirectories.mockResolvedValue([]);});describe('createInstance', () => {+ beforeEach(() => {+ mockFindOwnedById.mockResolvedValue({+ id: environmentId,+ visibility: 'public',+ workspaceId: 'ws-1',+ });+ });+it("binds the instance to the caller's own workspace", async () => {// The binding is what `environment_instances_provider_path_unique` keys// on, so it has to name the caller's storage rather than be accepted from@@ -164,7 +184,7 @@ describe('sandboxStorageRouter', () => {await sandboxStorageRouter.createCaller(ctx).createInstance({environmentId,name: 'Atlas',- workingDirectory: 'projects/atlas',+ workingDirectory: 'atlas',});expect(mockInstanceCreate).toHaveBeenCalledWith(@@ -181,7 +201,7 @@ describe('sandboxStorageRouter', () => {sandboxStorageRouter.createCaller(ctx).createInstance({environmentId,name: 'Atlas',- workingDirectory: 'projects/atlas',+ workingDirectory: 'atlas',}),).rejects.toMatchObject({ code: 'NOT_FOUND' });});@@ -195,68 +215,30 @@ describe('sandboxStorageRouter', () => {sandboxStorageRouter.createCaller(ctx).createInstance({environmentId,name: 'Atlas',- workingDirectory: 'projects/atlas',+ workingDirectory: 'atlas',}),).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_INSTANCE_DIRECTORY' });});++ it('refuses to initialize a folder that already holds work', async () => {+ mockListFiles.mockResolvedValue({ entries: [{ name: 'notes.md' }], path: 'atlas' });++ await expect(+ sandboxStorageRouter.createCaller(ctx).createInstance({+ environmentId,+ name: 'Atlas',+ workingDirectory: 'atlas',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'FOLDER_NOT_EMPTY' });+ expect(mockInstanceCreate).not.toHaveBeenCalled();+ });});describe('removeInstance', () => {const instanceId = '0726286c-f1a1-4c9e-980d-80a8e837321d';- const defaultId = '00000000-0000-4000-8000-000000000001';- const created = new Date('2026-01-01T00:00:00Z');beforeEach(() => {mockInstanceFindOwnedById.mockResolvedValue({ environmentId, id: instanceId });- // An older sibling is the default, so the instance under test is a copy.- mockInstanceQuery.mockResolvedValue([- { createdAt: created, id: defaultId },- { createdAt: new Date('2026-02-01T00:00:00Z'), id: instanceId },- ]);- });-- it('refuses the default instance before reaching the execution plane', async () => {- // The default is what the environment is: it goes with the environment,- // and a broken one is rebuilt rather than deleted on its own.- mockInstanceFindOwnedById.mockResolvedValue({ environmentId, id: defaultId });-- await expect(- sandboxStorageRouter.createCaller(ctx).removeInstance({ id: defaultId }),- ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'DEFAULT_INSTANCE' });-- expect(mockInstanceQuery).toHaveBeenCalledWith({ environmentId });- expect(mockDeleteEnvironment).not.toHaveBeenCalled();- expect(mockInstanceDelete).not.toHaveBeenCalled();- });-- it("refuses an environment's only instance, which is its default", async () => {- mockInstanceQuery.mockResolvedValue([{ createdAt: created, id: instanceId }]);-- await expect(- sandboxStorageRouter.createCaller(ctx).removeInstance({ id: instanceId }),- ).rejects.toMatchObject({ message: 'DEFAULT_INSTANCE' });- expect(mockDeleteEnvironment).not.toHaveBeenCalled();- });-- it('decides a tie on creation time by id: the lower id is the default', async () => {- const lower = '10000000-0000-4000-8000-000000000000';- const higher = '90000000-0000-4000-8000-000000000000';- mockInstanceQuery.mockResolvedValue([- { createdAt: created, id: higher },- { createdAt: created, id: lower },- ]);- mockDeleteEnvironment.mockResolvedValue(undefined);- const caller = sandboxStorageRouter.createCaller(ctx);-- mockInstanceFindOwnedById.mockResolvedValue({ environmentId, id: lower });- await expect(caller.removeInstance({ id: lower })).rejects.toMatchObject({- message: 'DEFAULT_INSTANCE',- });-- mockInstanceFindOwnedById.mockResolvedValue({ environmentId, id: higher });- await caller.removeInstance({ id: higher });- expect(mockInstanceDelete).toHaveBeenCalledWith(higher);- expect(mockInstanceDelete).not.toHaveBeenCalledWith(lower);});it('deletes the row when the execution plane has no snapshot for it', async () => {@@ -383,17 +365,82 @@ describe('sandboxStorageRouter', () => {});});- // A workspace root is shared by every member and holds every instance's- // directory, so a path alone authorizes nothing there: each call is confined- // to one instance โ readable if visible, writable only by its owner.+ // The drive is in reach without an instance โ a shared drive's root and its+ // ordinary folders belong to every member โ but environment directories are+ // carved out of it: a colleague's private one is hidden, and every one is+ // read-only from outside.describe('file routes', () => {const instanceId = '9b2c7e1a-4d3f-4a8b-9c1d-2e3f4a5b6c7d';- it('refuses a workspace write that names no instance', async () => {+ it('writes an ordinary folder on a shared drive with no instance named', async () => {+ mockWriteFile.mockResolvedValue({ path: 'projA/a.txt' });++ await sandboxStorageRouter.createCaller(ctx).writeFile({ content: 'x', path: 'projA/a.txt' });++ expect(mockWriteFile).toHaveBeenCalledWith({ content: 'x', path: 'projA/a.txt' });+ expect(mockListStorageDirectories).toHaveBeenCalledWith(+ expect.objectContaining({ provider: 'market', providerScope: 'ws-org-1' }),+ );+ });++ it('writes into a folder an environment initialized like any other', async () => {+ mockListStorageDirectories.mockResolvedValue([+ { id: instanceId, visible: true, workingDirectory: 'atlas' },+ ]);+ mockWriteFile.mockResolvedValue({ path: 'atlas/a.txt' });+await expect(- sandboxStorageRouter.createCaller(ctx).writeFile({ content: 'x', path: 'work/a.txt' }),- ).rejects.toThrow('INSTANCE_REQUIRED');- expect(mockWriteFile).not.toHaveBeenCalled();+ sandboxStorageRouter.createCaller(ctx).writeFile({ content: 'x', path: 'atlas/a.txt' }),+ ).resolves.toMatchObject({ path: 'atlas/a.txt' });+ expect(mockWriteFile).toHaveBeenCalled();+ });++ it('renames an ordinary folder without overwriting', async () => {+ mockRenameFile.mockResolvedValue({ path: 'projB' });++ await expect(+ sandboxStorageRouter.createCaller(ctx).renameFile({ newPath: 'projB', path: 'projA' }),+ ).resolves.toEqual({ path: 'projB' });+ expect(mockRenameFile).toHaveBeenCalledWith({ newPath: 'projB', path: 'projA' });+ });++ it('leaves a private environment directory on the public drive out of the root listing', async () => {+ mockListStorageDirectories.mockResolvedValue([+ { id: instanceId, isPrivate: true, workingDirectory: 'secret' },+ ]);+ mockListFiles.mockResolvedValue({+ entries: [+ { isDirectory: true, name: 'projA', path: 'projA' },+ { isDirectory: true, name: 'secret', path: 'secret' },+ ],+ path: '',+ truncated: false,+ });+ const caller = sandboxStorageRouter.createCaller(ctx);++ const listing = await caller.listFiles({});++ expect(listing.entries.map((entry) => entry.name)).toEqual(['projA']);+ await expect(caller.readFile({ path: 'secret/key' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ // A personal drive is its owner's alone: nothing on it is hidden from them.+ it('hides nothing on the personal drive', async () => {+ mockListStorageDirectories.mockResolvedValue([+ { id: instanceId, isPrivate: true, workingDirectory: 'secret' },+ ]);+ mockListFiles.mockResolvedValue({+ entries: [{ isDirectory: true, name: 'secret', path: 'secret' }],+ path: '',+ truncated: false,+ });++ const listing = await sandboxStorageRouter.createCaller(ctx).listFiles({ drive: 'personal' });++ expect(listing.entries.map((entry) => entry.name)).toEqual(['secret']);+ expect(mockResolveClaim).toHaveBeenCalledWith(expect.objectContaining({ drive: 'personal' }));});it("refuses a read outside the instance's directory", async () => {@@ -417,37 +464,21 @@ describe('sandboxStorageRouter', () => {expect(mockListFiles).toHaveBeenCalledWith(expect.objectContaining({ path: 'work' }));});- it("reads a conversation's files through the instance its runs resolve to", async () => {- // The same resolution a run takes, so a public agent's conversation is- // held to published instances here too.- mockResolveSessionConfig.mockResolvedValue({ cwd: 'work', mode: 'persistent' });- mockReadFile.mockResolvedValue({ content: '' });+ it("lists a conversation's own folder when it names a topic and no path", async () => {+ mockResolveSessionConfig.mockResolvedValue({ cwd: 'projA', mode: 'drive' });+ mockListFiles.mockResolvedValue({ entries: [] });- await sandboxStorageRouter- .createCaller(ctx)- .readFile({ path: 'work/a.txt', topicId: 'topic-1' });- await expect(- sandboxStorageRouter- .createCaller(ctx)- .readFile({ path: 'other/a.txt', topicId: 'topic-1' }),- ).rejects.toThrow('PATH_OUTSIDE_INSTANCE');+ await sandboxStorageRouter.createCaller(ctx).listFiles({ topicId: 'topic-1' });+ expect(mockListFiles).toHaveBeenLastCalledWith(+ expect.objectContaining({ path: 'projA', topicId: 'topic-1' }),+ );+ // A temporary conversation has no folder of its own: the drive's root.mockResolveSessionConfig.mockResolvedValue({ mode: 'ephemeral' });- await expect(- sandboxStorageRouter.createCaller(ctx).listFiles({ topicId: 'topic-1' }),- ).rejects.toThrow('INSTANCE_REQUIRED');-- expect(mockReadFile).toHaveBeenCalledTimes(1);- });-- it('leaves a personal root to its owner', async () => {- mockWriteFile.mockResolvedValue({ path: 'notes.md' });-- await sandboxStorageRouter- .createCaller({ ...ctx, workspaceId: undefined })- .writeFile({ content: 'x', path: 'notes.md' });-- expect(mockWriteFile).toHaveBeenCalled();+ await sandboxStorageRouter.createCaller(ctx).listFiles({ topicId: 'topic-1' });+ expect(mockListFiles).toHaveBeenLastCalledWith(+ expect.objectContaining({ path: undefined, topicId: 'topic-1' }),+ );});});@@ -527,182 +558,6 @@ describe('sandboxStorageRouter', () => {});});- describe('createEnvironment', () => {- const created = { id: environmentId, name: 'Python ๆฐๆฎๅๆ' };-- it('creates the default instance in the same call and returns it unbuilt', async () => {- // The build is a sandbox cold start, so it stays the client's next call.- mockCreate.mockResolvedValue(created);- mockInstanceCreate.mockResolvedValue({- configurationSnapshot: { bootstrapCommand: 'pip install pandas' },- id: 'default-1',- status: 'pending',- workingDirectory: 'python-ๆฐๆฎๅๆ',- });-- const result = await sandboxStorageRouter.createCaller(ctx).createEnvironment({- configuration: { bootstrapCommand: 'pip install pandas' },- name: 'Python ๆฐๆฎๅๆ',- withDefaultInstance: true,- });-- expect(mockInstanceCreate).toHaveBeenCalledWith(- expect.objectContaining({- environmentId,- kind: 'sandbox',- name: 'python-ๆฐๆฎๅๆ',- providerScope: 'ws-org-1',- workingDirectory: 'python-ๆฐๆฎๅๆ',- }),- );- expect(result).toMatchObject({- defaultInstance: { id: 'default-1', status: 'pending' },- id: environmentId,- });- expect(mockTransaction).toHaveBeenCalledTimes(1);- expect(mockBuildInstance).not.toHaveBeenCalled();- expect(mockInstanceUpdate).not.toHaveBeenCalled();- });-- it('settles a default instance with nothing to build as ready, without waiting for the client', async () => {- // The client's follow-up build call may never arrive โ a closed tab is- // enough โ and nothing else would ever move the row out of `pending`.- mockCreate.mockResolvedValue(created);- mockInstanceCreate.mockResolvedValue({- configurationSnapshot: { kind: 'files' },- id: 'default-1',- status: 'pending',- workingDirectory: 'python-ๆฐๆฎๅๆ',- });-- const result = await sandboxStorageRouter.createCaller(ctx).createEnvironment({- configuration: { kind: 'files' },- name: 'Python ๆฐๆฎๅๆ',- withDefaultInstance: true,- });-- expect(mockInstanceUpdate).toHaveBeenCalledWith('default-1', { status: 'ready' });- expect(result.defaultInstance).toMatchObject({ id: 'default-1', status: 'ready' });- expect(mockBuildInstance).not.toHaveBeenCalled();- });-- it('creates no instance for a client that does not ask for one', async () => {- // A client from before default instances follows with its own- // create-instance dialog; an instance made here too would be a second.- mockCreate.mockResolvedValue(created);-- const result = await sandboxStorageRouter- .createCaller(ctx)- .createEnvironment({ name: 'Python ๆฐๆฎๅๆ' });-- expect(mockCreate).toHaveBeenCalledWith({ name: 'Python ๆฐๆฎๅๆ' });- expect(mockInstanceCreate).not.toHaveBeenCalled();- expect(result).toMatchObject({ id: environmentId });- expect(result.defaultInstance).toBeUndefined();- });-- it('derives the next free directory when the first is taken', async () => {- mockCreate.mockResolvedValue(created);- mockInstanceCreate- .mockRejectedValueOnce(uniqueViolation('environment_instances_provider_path_unique'))- .mockResolvedValueOnce({ id: 'default-1', workingDirectory: 'python-ๆฐๆฎๅๆ-2' });-- const result = await sandboxStorageRouter- .createCaller(ctx)- .createEnvironment({ name: 'Python ๆฐๆฎๅๆ', withDefaultInstance: true });-- expect(mockInstanceCreate).toHaveBeenLastCalledWith(- expect.objectContaining({ workingDirectory: 'python-ๆฐๆฎๅๆ-2' }),- );- expect(result.defaultInstance?.workingDirectory).toBe('python-ๆฐๆฎๅๆ-2');- });-- it('fails the whole transaction when its default instance cannot be created', async () => {- // No compensating delete: the environment insert is rolled back with it.- mockCreate.mockResolvedValue(created);- mockInstanceCreate.mockRejectedValueOnce(new Error('db down'));-- await expect(- sandboxStorageRouter- .createCaller(ctx)- .createEnvironment({ name: 'Python ๆฐๆฎๅๆ', withDefaultInstance: true }),- ).rejects.toThrow('db down');- expect(mockTransaction).toHaveBeenCalledTimes(1);- expect(mockDelete).not.toHaveBeenCalled();- });- });-- describe('removeEnvironment', () => {- const onlyInstance = { id: '0726286c-f1a1-4c9e-980d-80a8e837321d', kind: 'sandbox' };-- beforeEach(() => {- mockFindOwnedById.mockResolvedValue({ id: environmentId });- mockDelete.mockResolvedValue({ id: environmentId });- mockInstanceDelete.mockResolvedValue(onlyInstance);- });-- it('takes the default instance with it, rows first and the snapshot last', async () => {- // The snapshot goes only once both deletes have gone through, inside the- // transaction: anything that refuses earlier leaves it untouched.- mockInstanceQuery.mockResolvedValue([onlyInstance]);- mockDeleteEnvironment.mockRejectedValue(new SandboxStorageFilesError('gone', 404));-- await sandboxStorageRouter.createCaller(ctx).removeEnvironment({ id: environmentId });-- expect(mockTransaction).toHaveBeenCalledTimes(1);- expect(mockInstanceDelete).toHaveBeenCalledWith(onlyInstance.id);- expect(mockDelete).toHaveBeenCalledWith(environmentId);- expect(mockDeleteEnvironment).toHaveBeenCalledWith({ name: onlyInstance.id });- expect(mockDelete.mock.invocationCallOrder[0]).toBeLessThan(- mockDeleteEnvironment.mock.invocationCallOrder[0],- );- });-- it('never drops the snapshot when the environment delete is refused', async () => {- // A project still bound to the environment: its restrict reference fails- // the delete, the transaction rolls the instance row back, and the built- // state has not been touched.- mockInstanceQuery.mockResolvedValue([onlyInstance]);- const restricted = new Error('violates foreign key constraint');- (restricted as any).cause = { code: '23503' };- mockDelete.mockRejectedValueOnce(restricted);-- await expect(- sandboxStorageRouter.createCaller(ctx).removeEnvironment({ id: environmentId }),- ).rejects.toMatchObject({ code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });- expect(mockDeleteEnvironment).not.toHaveBeenCalled();- });-- it('fails the transaction when a run still holds the default instance', async () => {- mockInstanceQuery.mockResolvedValue([onlyInstance]);- mockDeleteEnvironment.mockRejectedValueOnce(new SandboxStorageFilesError('in use', 409));-- await expect(- sandboxStorageRouter.createCaller(ctx).removeEnvironment({ id: environmentId }),- ).rejects.toMatchObject({ code: 'CONFLICT' });- });-- it('refuses while copies other than the default remain', async () => {- mockInstanceQuery.mockResolvedValue([onlyInstance, { id: 'copy', kind: 'sandbox' }]);-- await expect(- sandboxStorageRouter.createCaller(ctx).removeEnvironment({ id: environmentId }),- ).rejects.toMatchObject({ code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });- expect(mockDeleteEnvironment).not.toHaveBeenCalled();- expect(mockDelete).not.toHaveBeenCalled();- });-- it('refuses an environment the caller does not own, before reaching the execution plane', async () => {- mockFindOwnedById.mockResolvedValue(undefined);-- await expect(- sandboxStorageRouter.createCaller(ctx).removeEnvironment({ id: environmentId }),- ).rejects.toMatchObject({ code: 'NOT_FOUND' });- expect(mockInstanceQuery).not.toHaveBeenCalled();- expect(mockDeleteEnvironment).not.toHaveBeenCalled();- });- });-describe('startInstanceBuild', () => {const spec = { bootstrapCommand: 'pnpm i', sources: [{ kind: 'git', url: 'https://x/y' }] };@@ -1105,75 +960,21 @@ describe('sandboxStorageRouter', () => {});});- describe('environment kind', () => {- // Stored with the rest of the definition, in the same jsonb column: no- // migration and no backfill, so the parse must keep it rather than strip it- // as an unknown key.- it('stores the kind chosen at creation and refuses any other value', async () => {- const caller = sandboxStorageRouter.createCaller(ctx);- mockCreate.mockResolvedValue({ id: 'env-files', name: 'Notes' });-- await caller.createEnvironment({ configuration: { kind: 'files' }, name: 'Notes' });- expect(mockCreate).toHaveBeenCalledWith(- expect.objectContaining({ configuration: { kind: 'files' } }),- );-- mockCreate.mockClear();- await expect(- caller.createEnvironment({- configuration: { kind: 'cluster' as never },- name: 'Refused',- }),- ).rejects.toThrow();- expect(mockCreate).not.toHaveBeenCalled();- });- });-- describe('environment source urls', () => {- it('stores a github checkout and refuses any other host', async () => {- // The picker only ever produces a github.com URL, but this is an RPC: a- // caller reaching it directly could otherwise name an internal address- // and have the build make the execution plane fetch it.- const caller = sandboxStorageRouter.createCaller(ctx);- mockCreate.mockResolvedValue({ id: 'env-allowed', name: 'Allowed' });- mockInstanceCreate.mockResolvedValue({ id: 'default-allowed' });-- await caller.createEnvironment({- configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }] },- name: 'Allowed',- });- expect(mockCreate).toHaveBeenCalled();-- for (const url of [- 'https://169.254.169.254/latest/meta-data',- 'https://internal.corp/repo.git',- 'https://github.com.attacker.test/a/b',- 'http://github.com/a/b',- ]) {- mockCreate.mockClear();- await expect(- caller.createEnvironment({- configuration: { sources: [{ kind: 'git', url }] },- name: 'Refused',- }),- ).rejects.toThrow();- expect(mockCreate).not.toHaveBeenCalled();- }- });- });-describe('entitlement', () => {- it('refuses every environment call without a workspace claim', async () => {+ it('refuses every drive call without a claim', async () => {// The execution plane would reject these anyway. Failing here keeps a- // client that renders the panel too eagerly from looking like a server+ // client that renders the picker too eagerly from looking like a server// fault, and keeps an unentitled caller from reaching the market at all.+ // The definitions these are built from need no drive โ see `environment`.mockResolveClaim.mockResolvedValue(null);const caller = sandboxStorageRouter.createCaller(ctx);- await expect(caller.createEnvironment({ name: 'Data analysis' })).rejects.toMatchObject({- code: 'FORBIDDEN',- });- expect(mockCreate).not.toHaveBeenCalled();+ await expect(+ caller.createInstance({ environmentId, name: 'atlas', workingDirectory: 'atlas' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(caller.listFiles({})).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockInstanceCreate).not.toHaveBeenCalled();+ expect(mockListFiles).not.toHaveBeenCalled();});});@@ -1214,39 +1015,6 @@ describe('sandboxStorageRouter', () => {});});- describe('environment names', () => {- it.each(['environments_user_name_unique', 'environments_workspace_user_name_unique'])(- 'maps a collision on %s to CONFLICT',- async (constraint) => {- mockCreate.mockRejectedValue(uniqueViolation(constraint));- const caller = sandboxStorageRouter.createCaller(ctx);-- await expect(caller.createEnvironment({ name: 'Data analysis' })).rejects.toMatchObject({- code: 'CONFLICT',- message: 'DUPLICATE_ENVIRONMENT_NAME',- });- },- );-- it('maps a collision on rename to CONFLICT', async () => {- mockUpdate.mockRejectedValue(uniqueViolation('environments_user_name_unique'));- const caller = sandboxStorageRouter.createCaller(ctx);-- await expect(- caller.updateEnvironment({ id: environmentId, name: 'Data analysis' }),- ).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_ENVIRONMENT_NAME' });- });-- it('leaves unrelated failures untouched', async () => {- mockCreate.mockRejectedValue(uniqueViolation('some_other_unique_index'));- const caller = sandboxStorageRouter.createCaller(ctx);-- await expect(caller.createEnvironment({ name: 'Data analysis' })).rejects.not.toMatchObject({- code: 'CONFLICT',- });- });- });-describe('copyInstance', () => {const source = {environmentId: '9f8b1c2d-0000-4000-8000-000000000001',@@ -1259,28 +1027,28 @@ describe('sandboxStorageRouter', () => {mockInstanceFindOwnedById.mockResolvedValue(source);mockInstanceCreate.mockResolvedValue({id: 'copy-id',- workingDirectory: 'projects/atlas-copy',+ workingDirectory: 'atlas-copy',});mockCopyEnvironment.mockResolvedValue(undefined);await sandboxStorageRouter.createCaller(ctx).copyInstance({id: environmentId,name: 'Atlas (copy)',- workingDirectory: 'projects/atlas-copy',+ workingDirectory: 'atlas-copy',});expect(mockInstanceCreate).toHaveBeenCalledWith(expect.objectContaining({environmentId: source.environmentId,name: 'Atlas (copy)',- workingDirectory: 'projects/atlas-copy',+ workingDirectory: 'atlas-copy',}),);// The copy's own folder, never the source's: sharing one would let either// instance's next save delete what the other still lists.expect(mockCopyEnvironment).toHaveBeenCalledWith({from: environmentId,- instanceDir: 'projects/atlas-copy',+ instanceDir: 'atlas-copy',to: 'copy-id',});});@@ -1296,7 +1064,7 @@ describe('sandboxStorageRouter', () => {sandboxStorageRouter.createCaller(ctx).copyInstance({id: environmentId,name: 'Atlas (copy)',- workingDirectory: 'projects/atlas-copy',+ workingDirectory: 'atlas-copy',}),).rejects.toThrow();expect(mockInstanceDelete).toHaveBeenCalledWith('copy-id');@@ -1422,49 +1190,4 @@ describe('sandboxStorageRouter', () => {expect(mockListEnvironmentSessions).not.toHaveBeenCalled();});});-- describe('listGithubBranches', () => {- it('lists the branches of one repository through the connected GitHub account', async () => {- mockListRepositoryBranches.mockResolvedValue(['canary', 'main']);-- const result = await sandboxStorageRouter- .createCaller(ctx)- .listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });-- expect(result).toEqual({ branches: ['canary', 'main'], connected: true, truncated: false });- expect(mockListRepositoryBranches).toHaveBeenCalledWith('lobehub', 'lobehub');- });-- // At the ceiling the list may be partial; the picker falls back to typing- // so a branch past it can still be entered.- it('says when the list reached the ceiling and may be partial', async () => {- mockListRepositoryBranches.mockResolvedValue(- Array.from({ length: 1000 }, (_, index) => `branch-${index}`),- );-- const result = await sandboxStorageRouter- .createCaller(ctx)- .listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });-- expect(result.truncated).toBe(true);- });-- it('answers not connected rather than failing when GitHub is unavailable', async () => {- mockListRepositoryBranches.mockRejectedValue(- new ConnectorDataError({- code: 'not_connected',- message: 'no token',- operation: 'listRepositoryBranches',- provider: 'github',- retryable: false,- }),- );-- const result = await sandboxStorageRouter- .createCaller(ctx)- .listGithubBranches({ owner: 'lobehub', repository: 'lobehub' });-- expect(result).toEqual({ branches: [], connected: false, truncated: false });- });- });});diff --git a/apps/server/src/routers/lambda/_schema/environment.ts b/apps/server/src/routers/lambda/_schema/environment.tsnew file mode 100644index 00000000000..d61a029f258--- /dev/null+++ b/apps/server/src/routers/lambda/_schema/environment.ts@@ -0,0 +1,92 @@+import { z } from 'zod';++import { relativePathSchema } from '../sandboxStorage/schemas';++/**+ * The hosts a checkout may name.+ *+ * An allowlist rather than an SSRF check on the resolved address, because the+ * clone does not happen here: the stored specification is handed to the+ * execution plane, which resolves and fetches it from its own network, so no+ * validation at this layer can speak for what that resolution will return.+ * Naming the hosts is the part this layer can be sure of โ and every producer+ * already names exactly one, since a source is chosen through the GitHub+ * repository picker and the UI parses the URL back assuming that host.+ */+const ALLOWED_SOURCE_HOSTS = new Set(['github.com', 'www.github.com']);++/**+ * Where source material comes from. Only `git` for now, and only over HTTPS:+ * the other transports authenticate with a key, and a specification that+ * carries no credentials cannot present one. Private repositories are a+ * separate problem, not a URL scheme.+ *+ * The host is checked because this schema guards an RPC, not the picker: a+ * caller reaching it directly could otherwise store any URL, and a build would+ * then make the execution plane fetch it โ an internal address included.+ */+const environmentSourceSchema = z.object({+ kind: z.literal('git'),+ /** Where the checkout lands, relative to the instance's own directory. */+ path: relativePathSchema.optional(),+ ref: z.string().trim().min(1).max(255).optional(),+ url: z+ .string()+ .url()+ .refine(+ (value) => {+ let parsed;+ try {+ parsed = new URL(value);+ } catch {+ return false;+ }++ return parsed.protocol === 'https:' && ALLOWED_SOURCE_HOSTS.has(parsed.hostname);+ },+ { message: 'Only https:// github.com git URLs are supported' },+ ),+});++/**+ * Non-secret values only. Enforced by shape as far as a shape can: the name has+ * to look like an environment variable, and the rest is said plainly in the UI+ * and in the type. A field that stores what the user types cannot tell a region+ * from a token, which is why secrets are resolved at use time instead.+ */+const environmentEnvSchema = z.record(+ z+ .string()+ .max(128)+ .regex(/^[A-Z_]\w*$/i, 'Must be a valid environment variable name'),+ z.string().max(4096),+);++export const configurationSchema = z.object({+ bootstrapCommand: z.string().max(8000).optional(),+ env: environmentEnvSchema.optional(),+ excludePaths: z.array(relativePathSchema).max(64).optional(),+ internetAccess: z.boolean().optional(),+ // Which form the product shows. Accepted here so it is stored rather than+ // stripped by the parse; it never travels on to the execution plane. New+ // environments are `code`: a folder of files is a folder on the drive, not+ // an environment. `files` is still accepted because the previous release+ // stored it, and an edit sends the stored configuration back whole โ refusing+ // 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(),+});++/**+ * A new environment's configuration: `code` only. {@link configurationSchema}+ * accepts the legacy `files` kind so a stored row can still be edited; nothing+ * creates one any more.+ */+export const newConfigurationSchema = configurationSchema.extend({+ kind: z.literal('code').optional(),+});diff --git a/apps/server/src/routers/lambda/environment.ts b/apps/server/src/routers/lambda/environment.tsnew file mode 100644index 00000000000..92788393711--- /dev/null+++ b/apps/server/src/routers/lambda/environment.ts@@ -0,0 +1,199 @@+import { ConnectorDataError } from '@lobechat/connector-data';+import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { EnvironmentModel } from '@/database/models/environment';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { ConnectorDataService } from '@/server/services/connectorData';++import { configurationSchema, newConfigurationSchema } from './_schema/environment';+import {+ rethrowDuplicateEnvironmentName,+ rethrowEnvironmentInUse,+} from './sandboxStorage/constraintErrors';+import { idSchema, nameSchema, visibilitySchema } from './sandboxStorage/schemas';++/**+ * Code environments: the definitions a folder can be initialized from โ the+ * repository to check out, what makes it usable, what it runs with.+ *+ * Definitions only, and answered from the database alone, so nothing here asks+ * for a drive: writing down how to set up a project is useful before anyone+ * has somewhere to run it, and is the same whether it is later run in the+ * cloud sandbox or on a device. What is built from a definition lives on the+ * drive and is managed through `sandboxStorage`, which does ask.+ */++/**+ * "You have not connected GitHub" travels as an error from the connector layer,+ * but for the picker it is an answer, not a failure โ the one it is there to+ * help the user fix.+ */+const isGithubUnavailable = (error: unknown): boolean =>+ error instanceof ConnectorDataError && error.provider === 'github' && !error.retryable;++const environmentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ environmentModel: new EnvironmentModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++const githubProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ connectorDataService: new ConnectorDataService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++/** The environment procedures, also answered under `sandboxStorage` for older clients. */+export const environmentProcedures = {+ /** A definition alone. Folders are initialized from it in the directory picker. */+ createEnvironment: environmentProcedure+ .input(+ z.object({+ configuration: newConfigurationSchema.optional(),+ description: z.string().max(2000).optional(),+ name: nameSchema,+ visibility: visibilitySchema.optional(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ ctx.environmentModel.create(input).catch(rethrowDuplicateEnvironmentName),+ ),++ /** Specifications only. Nothing here needs a sandbox session to answer. */+ listEnvironments: environmentProcedure+ .input(z.object({ visibility: visibilitySchema.optional() }).optional())+ .query(async ({ ctx, input }) => ({+ environments: await ctx.environmentModel.query(input?.visibility),+ })),++ /**+ * The branches of one repository, so the environment's checkout target is+ * picked from what exists rather than typed. No connection is not an error,+ * it is `connected: false`.+ */+ listGithubBranches: githubProcedure+ .input(z.object({ owner: z.string().min(1).max(255), repository: z.string().min(1).max(255) }))+ .query(async ({ ctx, input }) => {+ try {+ const client = await ctx.connectorDataService.getGitHubClient();+ const branches = await client.listRepositoryBranches(input.owner, input.repository);++ return {+ branches,+ connected: true,+ // At the ceiling the list may be missing branches, and a picker+ // that only offers what it was given would make those unselectable.+ truncated: branches.length >= MAX_REPOSITORY_BRANCHES,+ };+ } catch (error) {+ if (isGithubUnavailable(error)) return { branches: [], connected: false, truncated: false };++ throw error;+ }+ }),++ /**+ * Every repository this account can build an environment from, newest+ * activity first, each carrying the owner it belongs to so the caller can+ * group them without a second request per organization.+ *+ * A missing GitHub connection is NOT an error here: it is the state the+ * picker exists to resolve, so it answers `connected: false` and lets the+ * UI offer the connection instead of a failure.+ */+ listGithubRepositories: githubProcedure.query(async ({ ctx }) => {+ try {+ const client = await ctx.connectorDataService.getGitHubClient();++ return { connected: true, repositories: await client.listAccessibleRepositories() };+ } catch (error) {+ if (isGithubUnavailable(error)) return { connected: false, repositories: [] };++ throw error;+ }+ }),++ /**+ * Refused while any folder is still initialized from it: the reference is+ * `restrict`, and those folders are removed from the environment's list+ * first โ removing one drops what was built on the drive, which only the+ * drive's own router can do.+ */+ removeEnvironment: environmentProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ const environment = await ctx.environmentModel.findOwnedById(input.id);+ if (!environment)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ const removed = await ctx.environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return removed;+ }),++ /**+ * Publishing an environment to the workspace, or taking it back.+ *+ * Its own mutation rather than a field on `updateEnvironment`, because the+ * two are not the same kind of edit: renaming is between you and your own+ * row, while this one decides who else can run in what this environment+ * built โ and the client asks for confirmation before sending it.+ */+ setEnvironmentVisibility: environmentProcedure+ .input(z.object({ id: idSchema, visibility: visibilitySchema }))+ .mutation(async ({ ctx, input }) => {+ const updated = await ctx.environmentModel.setVisibility(input.id, input.visibility);+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return updated;+ }),++ /**+ * Edits the specification. Existing instances keep the one they were created+ * with โ a change here shapes what the NEXT folder is built from and touches+ * nothing a conversation has already installed or produced.+ */+ updateEnvironment: environmentProcedure+ .input(+ z.object({+ configuration: configurationSchema.optional(),+ description: z.string().max(2000).optional(),+ id: idSchema,+ name: nameSchema.optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { id, ...changes } = input;+ const updated = await ctx.environmentModel+ .update(id, changes)+ .catch(rethrowDuplicateEnvironmentName);+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return updated;+ }),+};++export const environmentRouter = router(environmentProcedures);++export type EnvironmentRouter = typeof environmentRouter;diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 66377756e92..6f274c6a71b 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -58,6 +58,7 @@ import { deviceMetricRouter } from './deviceMetric';import { documentRouter } from './document';import { documentCommentRouter } from './documentComment';import { documentLikeRouter } from './documentLike';+import { environmentRouter } from './environment';import { expertiseRouter } from './expertise';import { exporterRouter } from './exporter';import { fileRouter } from './file';@@ -128,6 +129,7 @@ export const lambdaRouter = router({agentEvalExternal: agentEvalExternalRouter,agentLabel: agentLabelRouter,agentSkills: agentSkillsRouter,+ environment: environmentRouter,sandboxStorage: sandboxStorageRouter,agentTrace: agentTraceRouter,expertise: expertiseRouter,diff --git a/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.tsindex 819cba3f454..3aebd6642c2 100644--- a/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/constraintErrors.ts@@ -71,14 +71,23 @@ export const rethrowDuplicateInstanceDirectory = (error: unknown): never => {throw error;};+/** The restrict reference a project holds on an environment it uses. */+const PROJECT_ENVIRONMENT_CONSTRAINT = 'project_environments_environment_id_environments_id_fk';+/**- * An environment with instances still on it. The reference is `restrict`+ * An environment with instances still on it, or a project still using it. The reference is `restrict`* on purpose โ deleting the specification out from under them would leave* directories and captured state nothing describes.*/export const rethrowEnvironmentInUse = (error: unknown): never => {if (getPostgresErrorField(error, 'code') === '23503') {- throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });+ // Said apart, because what to do differs: a project link is removed from+ // the project, while copies go with the environment on the drive route.+ const message =+ getPostgresErrorField(error, 'constraint') === PROJECT_ENVIRONMENT_CONSTRAINT+ ? 'ENVIRONMENT_IN_PROJECT'+ : 'ENVIRONMENT_HAS_INSTANCES';+ throw new TRPCError({ cause: error, code: 'CONFLICT', message });}throw error;diff --git a/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts b/apps/server/src/routers/lambda/sandboxStorage/driveScope.tsnew file mode 100644index 00000000000..3ccb3ce5f70--- /dev/null+++ b/apps/server/src/routers/lambda/sandboxStorage/driveScope.ts@@ -0,0 +1,192 @@+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { TRPCError } from '@trpc/server';++import type { EnvironmentInstanceModel } from '@/database/models/environmentInstance';+import { type DriveAccess, isPathWithin, sandboxStorageBinding } from '@/server/services/sandbox';+import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';++import { mapStorageError, type SandboxStorageClient } from './procedures';++/**+ * Whether a folder on the drive already holds something. `false` for one that+ * is not there or is empty; an unreachable drive is not read as either and+ * fails the call, since guessing "empty" could build over someone's work.+ */+export const isFolderOccupied = async (client: SandboxStorageClient, path: string) => {+ try {+ const listing = await client.listFiles({ path });+ return listing.entries.length > 0;+ } catch (error) {+ if (error instanceof SandboxStorageFilesError && error.status === 404) return false;+ return mapStorageError(error);+ }+};++export const assertFolderFree = async (client: SandboxStorageClient, path: string) => {+ if (await isFolderOccupied(client, path)) {+ throw new TRPCError({ code: 'CONFLICT', message: 'FOLDER_NOT_EMPTY' });+ }+};++/**+ * What a file route may touch on the drive, as paths relative to its root.+ *+ * Without an instance the whole drive is in reach: a personal drive is its+ * owner's, and the public drive's root and ordinary folders belong to every+ * member, who may list them and create, rename or delete folders in them. Two+ * kinds of folder are carved out of that, and both are environment+ * directories:+ *+ * - **Hidden** โ a private environment's directory on the public drive, left+ * over from before members had a personal drive; its home directory can+ * hold the owner's credentials. It is left out of every listing and refused+ * when named, for everyone, exactly as if it were not there โ and so is a+ * write to any folder that holds one, since moving or deleting that folder+ * would carry the hidden one along and out into the open.+ *+ * With an instance the route is confined to that instance's directory, read+ * only, and goes to the drive the instance is on.+ */+export interface DriveScope {+ /** The client of the drive this scope is on. */+ client: SandboxStorageClient;+ /** Legacy private environment directories nobody may see; see above. */+ hidden: string[];+ /** Where a route is confined; `''` is the whole drive. */+ root: string;+}++export interface DriveContext {+ claim: { key: string };+ client: SandboxStorageClient;+ drive: SandboxDrive;+ drives: DriveAccess;+ instanceModel: EnvironmentInstanceModel;+ workspaceId?: string | null;+}++/**+ * The drive an instance is on, from the caller's side. Another member's+ * personal drive is not one of the caller's, so an instance there is answered+ * the way a missing one is.+ */+export const resolveInstanceDrive = async (+ ctx: Pick<DriveContext, 'drives'>,+ instance: { providerScope?: string | null },+) => {+ const drive = ctx.drives.driveOf(instance.providerScope);+ const access = drive ? await ctx.drives.client(drive) : undefined;+ if (!drive || !access) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ return { ...access, drive };+};++/**+ * Refuses to build in or copy a private environment's directory left on the+ * public drive: it is hidden there and run by nobody, and the way forward is a+ * new copy on the owner's personal drive.+ */+export const assertNotLeftOnPublicDrive = async (+ ctx: Pick<DriveContext, 'instanceModel' | 'workspaceId'>,+ instance: { id: string },+ access: { claim: { key: string }; drive: SandboxDrive },+) => {+ if (!ctx.workspaceId || access.drive !== 'public') return;++ const directories = await ctx.instanceModel.listStorageDirectories(+ sandboxStorageBinding(access.claim.key),+ );+ if (directories.some((entry) => entry.id === instance.id && entry.isPrivate)) {+ throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_REBUILD_REQUIRED' });+ }+};++/** Whether the scope's drive is a workspace's public one, shared by every member. */++export const isPublicDrive = (ctx: Pick<DriveContext, 'drive' | 'workspaceId'>) =>+ !!ctx.workspaceId && ctx.drive === 'public';++export const resolveDriveScope = async (+ ctx: DriveContext,+ instanceId?: string,+): Promise<DriveScope> => {+ if (instanceId) {+ const instance = await ctx.instanceModel.findById(instanceId);+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });+ const { client } = await resolveInstanceDrive(ctx, instance);++ return {+ client,+ hidden: [],+ root: instance.workingDirectory,+ };+ }++ const directories = await ctx.instanceModel.listStorageDirectories(+ sandboxStorageBinding(ctx.claim.key),+ );++ return {+ client: ctx.client,+ hidden: isPublicDrive(ctx)+ ? directories.filter((entry) => entry.isPrivate).map((entry) => entry.workingDirectory)+ : [],+ root: '',+ };+};++/** Whether `path` is `root` itself or somewhere beneath it. */++export const isWithinRoot = (path: string, root: string) => !root || isPathWithin(path, root);++export const isHidden = (path: string, scope: DriveScope) =>+ scope.hidden.some((directory) => isPathWithin(path, directory));++export const assertReadable = (path: string, scope: DriveScope) => {+ if (!isWithinRoot(path, scope.root)) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });+ }+ // The same answer a path that does not exist gets: a folder this member may+ // not see is not one they get to learn about by guessing its name.+ if (isHidden(path, scope)) throw new TRPCError({ code: 'NOT_FOUND', message: 'PATH_NOT_FOUND' });+};++/**+ * The scope a write on the drive runs in. A folder initialized from an+ * environment is an ordinary folder โ environments are one-time initializers+ * โ so it is written, renamed and deleted like any other. Only a write that+ * names a legacy instance is refused: that is the route an older client takes+ * into an environment directory's own state, which belongs to its builds.+ */+export const resolveWritableScope = async (+ ctx: DriveContext,+ { instanceId, path }: { instanceId?: string; path: string },+) => {+ if (instanceId) throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });++ const scope = await resolveDriveScope(ctx);+ assertReadable(path, scope);+ // Refused without naming what is inside: the caller can see this folder,+ // so "not found" would be false, and the hidden one stays unnamed.+ if (scope.hidden.some((directory) => isPathWithin(directory, path))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_HOLDS_HIDDEN' });+ }++ return scope;+};++/** Names the instance a file route works in; see {@link resolveDriveScope}. */++/**+ * The drive an environment's directories are made on: a private environment's+ * on its owner's personal drive, a published one's on the public drive every+ * member can run it from. A personal account has the one drive.+ */+export const driveForEnvironment = (+ environment: { visibility?: string | null; workspaceId?: string | null },+ workspaceId?: string | null,+): SandboxDrive => {+ if (!workspaceId) return 'personal';++ return environment.workspaceId && environment.visibility === 'private' ? 'personal' : 'public';+};diff --git a/apps/server/src/routers/lambda/sandboxStorage/environments.ts b/apps/server/src/routers/lambda/sandboxStorage/environments.tsdeleted file mode 100644index fa8e51077cb..00000000000--- a/apps/server/src/routers/lambda/sandboxStorage/environments.ts+++ /dev/null@@ -1,240 +0,0 @@-import { TRPCError } from '@trpc/server';-import { z } from 'zod';--import { router } from '@/libs/trpc/lambda';--import { rethrowDuplicateEnvironmentName, rethrowEnvironmentInUse } from './constraintErrors';-import {- createDerivedInstance,- deleteInstanceSnapshot,- inEnvironmentTransaction,-} from './instanceOperations';-import { environmentProcedure, instanceProcedure } from './procedures';-import { idSchema, nameSchema, relativePathSchema, visibilitySchema } from './schemas';--/**- * The hosts a checkout may name.- *- * An allowlist rather than an SSRF check on the resolved address, because the- * clone does not happen here: the stored specification is handed to the- * execution plane, which resolves and fetches it from its own network, so no- * validation at this layer can speak for what that resolution will return.- * Naming the hosts is the part this layer can be sure of โ and every producer- * already names exactly one, since a source is chosen through the GitHub- * repository picker and the UI parses the URL back assuming that host.- */-const ALLOWED_SOURCE_HOSTS = new Set(['github.com', 'www.github.com']);--/**- * Where source material comes from. Only `git` for now, and only over HTTPS:- * the other transports authenticate with a key, and a specification that- * carries no credentials cannot present one. Private repositories are a- * separate problem, not a URL scheme.- *- * The host is checked because this schema guards an RPC, not the picker: an- * entitled caller reaching it directly could otherwise store any URL, and the- * build would then make the execution plane fetch it โ an internal address- * included.- */-const environmentSourceSchema = z.object({- kind: z.literal('git'),- /** Where the checkout lands, relative to the instance's own directory. */- path: relativePathSchema.optional(),- ref: z.string().trim().min(1).max(255).optional(),- url: z- .string()- .url()- .refine(- (value) => {- let parsed;- try {- parsed = new URL(value);- } catch {- return false;- }-- return parsed.protocol === 'https:' && ALLOWED_SOURCE_HOSTS.has(parsed.hostname);- },- { message: 'Only https:// github.com git URLs are supported' },- ),-});--/**- * Non-secret values only. Enforced by shape as far as a shape can: the name has- * to look like an environment variable, and the rest is said plainly in the UI- * and in the type. A field that stores what the user types cannot tell a region- * from a token, which is why secrets are resolved at use time instead.- */-const environmentEnvSchema = z.record(- z- .string()- .max(128)- .regex(/^[A-Z_]\w*$/i, 'Must be a valid environment variable name'),- z.string().max(4096),-);--const configurationSchema = z.object({- bootstrapCommand: z.string().max(8000).optional(),- env: environmentEnvSchema.optional(),- excludePaths: z.array(relativePathSchema).max(64).optional(),- internetAccess: z.boolean().optional(),- // Which form the product shows. Accepted here so it is stored rather than- // stripped by the parse; it never travels on to the execution plane.- kind: z.enum(['files', 'code']).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(),-});--export const environmentsRouter = router({- /**- * An environment, together with its default instance.- *- * The person creating an environment has not started any work yet, so there- * is nothing to ask them about where it should happen: the instance is- * created here, with the same derived directory a new copy gets, and every- * creation path ends with one. It is returned unbuilt โ building it- * cold-starts a sandbox, so the client fires `startInstanceBuild` next, the- * same split as for any other new instance.- *- * Both rows are written in one transaction, so a failure to create the- * instance leaves no environment behind either: the caller sees the failure- * and retries, instead of holding an environment that silently skipped the- * step.- *- * Asked for, not assumed. A client from before this follows the call with- * its own create-instance dialog, and an instance made here as well would- * leave it with two โ the unasked one being the default, which cannot be- * removed on its own. Such a client gets the environment alone, as it always- * did, and its first instance becomes the default.- */- createEnvironment: instanceProcedure- .input(- z.object({- configuration: configurationSchema.optional(),- description: z.string().max(2000).optional(),- name: nameSchema,- visibility: visibilitySchema.optional(),- withDefaultInstance: z.boolean().optional(),- }),- )- .mutation(async ({ ctx, input: { withDefaultInstance, ...input } }) =>- inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {- const environment = await environmentModel- .create(input)- .catch(rethrowDuplicateEnvironmentName);- if (!withDefaultInstance) return { ...environment, defaultInstance: undefined };-- const defaultInstance = await createDerivedInstance(- instanceModel,- ctx.claim.key,- environment,- );-- return { ...environment, defaultInstance };- }),- ),- /** Specifications only. Nothing here needs a sandbox session to answer. */- listEnvironments: environmentProcedure- .input(z.object({ visibility: visibilitySchema.optional() }).optional())- .query(async ({ ctx, input }) => ({- environments: await ctx.environmentModel.query(input?.visibility),- })),- /**- * Edits the specification. Existing instances keep the one they were created- * with โ a change here shapes what the NEXT instance is built from and- * touches nothing a conversation has already installed or produced.- */- updateEnvironment: environmentProcedure- .input(- z.object({- configuration: configurationSchema.optional(),- description: z.string().max(2000).optional(),- id: idSchema,- name: nameSchema.optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const { id, ...changes } = input;- const updated = await ctx.environmentModel- .update(id, changes)- .catch(rethrowDuplicateEnvironmentName);- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });-- return updated;- }),- /**- * Only the label. The directory does not move: the built state sits in it,- * and the execution plane has no rename that carries one to the other.- */- /**- * Publishing an environment to the workspace, or taking it back.- *- * Its own mutation rather than a field on `updateEnvironment`, because the- * two are not the same kind of edit: renaming is between you and your own- * row, while this one decides who else can run in what this environment- * built โ and the client asks for confirmation before sending it.- */- setEnvironmentVisibility: environmentProcedure- .input(z.object({ id: idSchema, visibility: visibilitySchema }))- .mutation(async ({ ctx, input }) => {- const updated = await ctx.environmentModel.setVisibility(input.id, input.visibility);- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });-- return updated;- }),- /**- * Refused while copies other than the default still reference it โ those go- * first.- *- * The default instance goes with the environment: it cannot be removed on- * its own, so for an environment with only that one left, deleting the- * environment is how it is deleted.- *- * Both rows go in one transaction, and the snapshot is dropped last, inside- * it. Anything that refuses โ a project still bound to the environment, an- * instance created meanwhile, a run still holding the snapshot โ rolls the- * rows back with the snapshot untouched, so a refused delete costs nothing.- * The one gap left is a commit that fails after the snapshot is gone, which- * leaves rows with nothing built behind them. What was lost is what this- * call was asked to delete, and the call reports its failure, so deleting- * again finishes the job. The other order is the one with no way back: rows- * gone and a snapshot nobody can see, name, or reclaim.- */- removeEnvironment: instanceProcedure- .input(z.object({ id: idSchema }))- .mutation(async ({ ctx, input }) => {- // Ownership before anything reaches the execution plane: a member who- // can see a published environment must not get its snapshot deleted on- // the way to being refused the row.- const environment = await ctx.environmentModel.findOwnedById(input.id);- if (!environment)- throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });-- const instances = await ctx.instanceModel.query({ environmentId: environment.id });- if (instances.length > 1) {- throw new TRPCError({ code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });- }-- const [onlyInstance] = instances;- // Only a sandbox instance has a snapshot this router can drop; any other- // kind keeps referencing the environment and the delete below says so.- const defaultInstance = onlyInstance?.kind === 'sandbox' ? onlyInstance : undefined;-- return inEnvironmentTransaction(ctx, async ({ environmentModel, instanceModel }) => {- if (defaultInstance) {- await instanceModel.delete(defaultInstance.id).catch(rethrowEnvironmentInUse);- }-- const removed = await environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);- if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });-- if (defaultInstance) await deleteInstanceSnapshot(ctx.client, defaultInstance.id);-- return removed;- });- }),-});diff --git a/apps/server/src/routers/lambda/sandboxStorage/files.ts b/apps/server/src/routers/lambda/sandboxStorage/files.tsindex 930cfb4411c..a2a8b89a7a3 100644--- a/apps/server/src/routers/lambda/sandboxStorage/files.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/files.ts@@ -1,141 +1,149 @@-import { TRPCError } from '@trpc/server';import { z } from 'zod';-import type { EnvironmentInstanceModel } from '@/database/models/environmentInstance';import { router } from '@/libs/trpc/lambda';-import { resolveSandboxSessionConfig } from '@/server/services/sandbox';+import { forgetDriveFolders, resolveSandboxSessionConfig } from '@/server/services/sandbox';+import { assertReadable, isHidden, resolveDriveScope, resolveWritableScope } from './driveScope';import { instanceProcedure, mapStorageError } from './procedures';-import { idSchema, relativePathSchema, topicIdSchema } from './schemas';+import { driveSchema, instanceIdSchema, relativePathSchema, topicIdSchema } from './schemas';/*** Ceiling on a single write. Generous for anything a person edits by hand and* small enough that a runaway body is refused before it is buffered โ this is* an editor's save path, not a bulk upload.*/-const MAX_FILE_CONTENT_BYTES = 1024 * 1024;+export const MAX_FILE_CONTENT_BYTES = 1024 * 1024;/*** Checked in UTF-8 bytes, which is what the cap is denominated in and what the* execution plane actually receives. `z.string().max()` counts UTF-16 code* units, so a megabyte of CJK would pass it and send roughly three.*/-const fileContentSchema = z+export const fileContentSchema = z.string().refine((value) => Buffer.byteLength(value, 'utf8') <= MAX_FILE_CONTENT_BYTES, {message: `File content exceeds ${MAX_FILE_CONTENT_BYTES} bytes`,});-/**- * The directory a file route may touch, as a path relative to the workspace- * root; `''` is the whole root.- *- * A workspace's root is shared by every member and holds every instance's- * directory, so a path alone authorizes nothing: it is confined to one- * instance, reached through the same rules as everywhere else. Reads follow- * visibility โ a published instance is readable by the members who run in it.- * Writes stay with the instance's owner, as every other write to an instance- * does. A conversation's own files are read through the instance its runs- * resolve to, so a public agent's conversation is held to published ones.- *- * A personal account's root belongs to its owner alone, which is the one case- * where no instance is needed.- *- * An instance's directory is never written through here: it is- * the saved copy of the sandbox's work tree, written by the sandbox alone. A- * write from outside would be overwritten by the next save, or leave the- * directory disagreeing with the record the next restore reads it by.- */-const resolveFileRoot = async (- ctx: {- instanceModel: EnvironmentInstanceModel;- serverDB: Parameters<typeof resolveSandboxSessionConfig>[0]['serverDB'];- userId: string;- workspaceId?: string | null;- },- { instanceId, topicId }: { instanceId?: string; topicId?: string },- access: 'read' | 'write',-): Promise<string> => {- if (instanceId) {- // Refused before the lookup: the answer is the same whether or not the- // instance exists, so there is nothing to find out by asking.- if (access === 'write') {- throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });- }- const instance = await ctx.instanceModel.findById(instanceId);- if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });-- return instance.workingDirectory;- }-- if (!ctx.workspaceId) return '';-- if (access === 'read' && topicId) {- const { cwd } = await resolveSandboxSessionConfig({- isShareVisitorRun: false,- serverDB: ctx.serverDB,- topicId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });- if (cwd) return cwd;- }-- throw new TRPCError({ code: 'FORBIDDEN', message: 'INSTANCE_REQUIRED' });-};--/** Whether `path` is `root` itself or somewhere beneath it. */-const isWithinRoot = (path: string, root: string) =>- !root || path === root || path.startsWith(`${root}/`);--const assertWithinRoot = (path: string, root: string) => {- if (!isWithinRoot(path, root)) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });- }-};--/** Names the instance a file route works in; see {@link resolveFileRoot}. */-const instanceIdSchema = idSchema.optional();-export const filesRouter = router({+ /**+ * Create a folder, parents included. Idempotent โ an existing folder is a+ * success, so a picker can offer "new folder" without first proving the+ * name is free.+ */createDirectory: instanceProcedure.input(- z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),+ z.object({+ drive: driveSchema,+ instanceId: instanceIdSchema,+ path: relativePathSchema,+ topicId: topicIdSchema,+ }),)- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {- assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));+ .mutation(async ({ ctx, input: { drive: _drive, instanceId, ...input } }) => {+ const scope = await resolveWritableScope(ctx, { instanceId, path: input.path });++ const created = await scope.client.createDirectory(input).catch(mapStorageError);+ forgetDriveFolders(ctx.claim.key);- return ctx.client.createDirectory(input).catch(mapStorageError);+ return created;}),+ /**+ * One folder's entries โ or, with `recursive`, everything under it โ with+ * the private environment directories left on the public drive left out.+ *+ * No path means "where this conversation works" when a topic is named and+ * it has a folder or an environment directory, and the drive's root+ * otherwise: the file panel asks the first question, the directory picker+ * the second.+ */listFiles: instanceProcedure.input(z.object({+ drive: driveSchema,instanceId: instanceIdSchema,path: relativePathSchema.optional(),recursive: z.boolean().optional(),topicId: topicIdSchema,}),)- .query(async ({ ctx, input: { instanceId, ...input } }) => {- const root = await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read');- // No path means "the top of what may be listed", which inside a- // workspace is the instance's directory, not the shared root.- const path = input.path ?? (root || undefined);- if (path !== undefined) assertWithinRoot(path, root);-- return ctx.client.listFiles({ ...input, path }).catch(mapStorageError);+ .query(async ({ ctx, input: { drive: _drive, instanceId, ...input } }) => {+ let scope = await resolveDriveScope(ctx, instanceId);++ let path = input.path ?? (scope.root || undefined);+ if (path === undefined && input.topicId && !instanceId) {+ const placement = await resolveSandboxSessionConfig({+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ topicId: input.topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (placement.mode !== 'ephemeral') {+ path = placement.cwd;+ // The conversation's folder is on the drive it resolved to โ an+ // environment directory's own drive, say โ which is not+ // necessarily the one this call was routed by.+ if (placement.drive !== ctx.drive) {+ const access = await ctx.drives.client(placement.drive);+ if (access) {+ scope = await resolveDriveScope({+ ...ctx,+ claim: access.claim,+ client: access.client,+ drive: placement.drive,+ });+ }+ }+ }+ }+ if (path !== undefined) assertReadable(path, scope);++ const listing = await scope.client.listFiles({ ...input, path }).catch(mapStorageError);+ if (scope.hidden.length === 0) return listing;++ return {+ ...listing,+ entries: listing.entries.filter((entry) => !isHidden(entry.path, scope)),+ };}),readFile: instanceProcedure.input(- z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),+ z.object({+ drive: driveSchema,+ instanceId: instanceIdSchema,+ path: relativePathSchema,+ topicId: topicIdSchema,+ }),)- .query(async ({ ctx, input: { instanceId, ...input } }) => {- assertWithinRoot(- input.path,- await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read'),- );+ .query(async ({ ctx, input: { drive: _drive, instanceId, ...input } }) => {+ const scope = await resolveDriveScope(ctx, instanceId);+ assertReadable(input.path, scope);- return ctx.client.readFile(input).catch(mapStorageError);+ return scope.client.readFile(input).catch(mapStorageError);+ }),+ /**+ * Rename or move a file or folder. Never overwrites: a destination that is+ * already there is refused, and so is anything touching an environment+ * directory โ at either end.+ */+ renameFile: instanceProcedure+ .input(+ z.object({+ drive: driveSchema,+ newPath: relativePathSchema,+ path: relativePathSchema,+ topicId: topicIdSchema,+ }),+ )+ .mutation(async ({ ctx, input: { drive: _drive, ...input } }) => {+ const scope = await resolveWritableScope(ctx, { path: input.path });+ await resolveWritableScope(ctx, { path: input.newPath });++ const renamed = await scope.client.renameFile(input).catch(mapStorageError);+ forgetDriveFolders(ctx.claim.key);++ return renamed;}),/*** Write a file's whole contents, creating it and its parents if needed.@@ -149,34 +157,33 @@ export const filesRouter = router({.input(z.object({content: fileContentSchema,+ drive: driveSchema,instanceId: instanceIdSchema,path: relativePathSchema,topicId: topicIdSchema,}),)- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {- assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));+ .mutation(async ({ ctx, input: { drive: _drive, instanceId, ...input } }) => {+ const scope = await resolveWritableScope(ctx, { instanceId, path: input.path });- return ctx.client.writeFile(input).catch(mapStorageError);+ return scope.client.writeFile(input).catch(mapStorageError);}),removeFile: instanceProcedure.input(z.object({+ drive: driveSchema,instanceId: instanceIdSchema,path: relativePathSchema,recursive: z.boolean().optional(),topicId: topicIdSchema,}),)- .mutation(async ({ ctx, input: { instanceId, ...input } }) => {- const root = await resolveFileRoot(ctx, { instanceId }, 'write');- assertWithinRoot(input.path, root);- // The instance's own directory is its identity, not a file in it:- // removing it would orphan the row and the snapshot that name it.- if (root && input.path === root) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'PATH_OUTSIDE_INSTANCE' });- }+ .mutation(async ({ ctx, input: { drive: _drive, instanceId, ...input } }) => {+ const scope = await resolveWritableScope(ctx, { instanceId, path: input.path });++ const removed = await scope.client.deleteFile(input).catch(mapStorageError);+ forgetDriveFolders(ctx.claim.key);- return ctx.client.deleteFile(input).catch(mapStorageError);+ return removed;}),});diff --git a/apps/server/src/routers/lambda/sandboxStorage/github.ts b/apps/server/src/routers/lambda/sandboxStorage/github.tsdeleted file mode 100644index 8a3ebe11967..00000000000--- a/apps/server/src/routers/lambda/sandboxStorage/github.ts+++ /dev/null@@ -1,76 +0,0 @@-import { ConnectorDataError } from '@lobechat/connector-data';-import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';-import { z } from 'zod';--import { router } from '@/libs/trpc/lambda';-import { ConnectorDataService } from '@/server/services/connectorData';--import { entitledProcedure } from './procedures';--/**- * "You have not connected GitHub" travels as an error from the connector layer,- * but for the picker it is an answer, not a failure โ the one it is there to- * help the user fix.- */-const isGithubUnavailable = (error: unknown): boolean =>- error instanceof ConnectorDataError && error.provider === 'github' && !error.retryable;--export const githubRouter = router({- /**- * Every repository this account can build an environment from, newest- * activity first, each carrying the owner it belongs to so the caller can- * group them without a second request per organization.- *- * A missing GitHub connection is NOT an error here: it is the state the- * picker exists to resolve, so it answers `connected: false` and lets the- * UI offer the connection instead of a failure.- */- /**- * The branches of one repository, so the environment's checkout target is- * picked from what exists rather than typed. Same shape as the repository- * listing: no connection is not an error, it is `connected: false`.- */- listGithubBranches: entitledProcedure- .input(z.object({ owner: z.string().min(1).max(255), repository: z.string().min(1).max(255) }))- .query(async ({ ctx, input }) => {- const service = new ConnectorDataService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );-- try {- const client = await service.getGitHubClient();- const branches = await client.listRepositoryBranches(input.owner, input.repository);-- return {- branches,- connected: true,- // At the ceiling the list may be missing branches, and a picker- // that only offers what it was given would make those unselectable.- truncated: branches.length >= MAX_REPOSITORY_BRANCHES,- };- } catch (error) {- if (isGithubUnavailable(error)) return { branches: [], connected: false, truncated: false };-- throw error;- }- }),- listGithubRepositories: entitledProcedure.query(async ({ ctx }) => {- const service = new ConnectorDataService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- );-- try {- const client = await service.getGitHubClient();-- return { connected: true, repositories: await client.listAccessibleRepositories() };- } catch (error) {- if (isGithubUnavailable(error)) return { connected: false, repositories: [] };-- throw error;- }- }),-});diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.tsindex 99d997ea0a8..44250bd776a 100644--- a/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/index.procedures.test.ts@@ -7,6 +7,11 @@ import { sandboxStorageRouter } from '.';* Pins the router's public surface: every procedure path, its kind, and its* middleware chain length (which encodes the procedure builder and its input* parsers). Splitting the router across files must keep all three.+ *+ * The environment and GitHub procedures are the `environment` router's own,+ * answered here under their released paths for older clients โ which is why+ * they carry its shorter chain (no drive claim, no entitlement) rather than+ * this router's.*/describe('sandboxStorageRouter procedures', () => {const procedures = (sandboxStorageRouter as any)._def.procedures as Record<string, any>;@@ -30,27 +35,29 @@ function expected(): Array<['createEnvironment', 'mutation', 15],['createInstance', 'mutation', 15],['createInstanceForEnvironment', 'mutation', 15],+ ['getDriveUsage', 'query', 12],['getEntitlement', 'query', 11],['getInstance', 'query', 15],- ['getStorage', 'query', 12],+ ['getStorage', 'query', 13],['instanceBuildStatus', 'query', 15],- ['listEnvironments', 'query', 14],+ ['listEnvironments', 'query', 12],['listFiles', 'query', 15],- ['listGithubBranches', 'query', 13],- ['listGithubRepositories', 'query', 12],+ ['listGithubBranches', 'query', 12],+ ['listGithubRepositories', 'query', 11],['listInstanceSessions', 'query', 15],['listInstances', 'query', 15],['readFile', 'query', 15],- ['refreshStorageUsage', 'mutation', 12],+ ['refreshStorageUsage', 'mutation', 13],['removeEnvironment', 'mutation', 15],['removeFile', 'mutation', 15],['removeInstance', 'mutation', 15],+ ['renameFile', 'mutation', 15],['renameInstance', 'mutation', 15],['resolveSessionPlacement', 'query', 12],- ['setEnvironmentVisibility', 'mutation', 14],+ ['setEnvironmentVisibility', 'mutation', 12],['startInstanceBuild', 'mutation', 15],['stopInstance', 'mutation', 15],- ['updateEnvironment', 'mutation', 14],+ ['updateEnvironment', 'mutation', 12],['writeFile', 'mutation', 15],];}diff --git a/apps/server/src/routers/lambda/sandboxStorage/index.ts b/apps/server/src/routers/lambda/sandboxStorage/index.tsindex 16f97341a30..d3b4ef0284e 100644--- a/apps/server/src/routers/lambda/sandboxStorage/index.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/index.ts@@ -1,28 +1,32 @@import { mergeRouters } from '@/libs/trpc/lambda';-import { environmentsRouter } from './environments';import { filesRouter } from './files';-import { githubRouter } from './github';import { instanceBuildRouter } from './instanceBuild';import { instancesRouter } from './instances';+import { legacyEnvironmentRouter } from './legacyEnvironment';import { storageRouter } from './storage';/**- * Browsing and managing the persistent sandbox workspace.+ * Browsing and managing the user's network drives, and the environment+ * directories (instances) initialized on them.*- * The workspace lives on a volume mounted into the sandbox runtime, so every- * call here runs inside a sandbox session on the caller's behalf. Paths are- * always relative to the workspace root; the absolute mount path never reaches- * a client, which leaves nothing for one to smuggle back.+ * The drive lives on a volume mounted into the sandbox runtime, so every call+ * here runs inside a sandbox session on the caller's behalf. Paths are always+ * relative to the drive's root; the absolute mount path never reaches a+ * client, which leaves nothing for one to smuggle back.+ *+ * The environment definitions and the GitHub pickers moved to the+ * `environment` router, which needs no drive. They are still answered here+ * under their released paths โ the same procedures, not copies โ so a desktop+ * build or a cached web client from before the move keeps working until it+ * updates; `createEnvironment` there keeps its released `withDefaultInstance`.*/-export const sandboxStorageRouter = mergeRouters(filesRouter,storageRouter,instancesRouter,instanceBuildRouter,- environmentsRouter,- githubRouter,+ legacyEnvironmentRouter,);export type SandboxStorageRouter = typeof sandboxStorageRouter;diff --git a/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.tsindex 43b089b9578..a46b1d8bba0 100644--- a/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts@@ -5,6 +5,7 @@ import { z } from 'zod';import { router } from '@/libs/trpc/lambda';import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';+import { assertNotLeftOnPublicDrive, resolveInstanceDrive } from './driveScope';import { isBuildable } from './instanceOperations';import { instanceProcedure, mapStorageError } from './procedures';import { idSchema, topicIdSchema } from './schemas';@@ -27,6 +28,9 @@ export const instanceBuildRouter = router({.mutation(async ({ ctx, input }) => {const instance = await ctx.instanceModel.findOwnedById(input.id);if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });+ const instanceDrive = await resolveInstanceDrive(ctx, instance);+ const { client } = instanceDrive;+ await assertNotLeftOnPublicDrive(ctx, instance, instanceDrive);// The definition this instance was created from, not the environment's// current one: a build has to produce what the instance says it is, and@@ -47,7 +51,7 @@ export const instanceBuildRouter = router({// now, so a held instance is refused before the row changes at all. A// lease store that did not answer is not read as "free" โ the runtime's// own lease still stands behind this and refuses a second writer.- const occupancy = await ctx.client+ const occupancy = await client.readOccupancy({ names: [input.id], topicId: input.topicId }).catch(() => ({ held: [], unavailable: true }));if (occupancy.held.some((entry) => entry.id === input.id)) {@@ -77,7 +81,7 @@ export const instanceBuildRouter = router({});try {- const { buildId } = await ctx.client.buildInstance({+ const { buildId } = await client.buildInstance({credentials: credential ? [credential] : undefined,// Where the checkout lands on the volume: the instance's own folder,// which is what its file browser opens.@@ -137,7 +141,8 @@ export const instanceBuildRouter = router({};}- const status = await ctx.client+ const { client } = await resolveInstanceDrive(ctx, instance);+ const status = await client.buildStatus({buildId: instance.buildId,logOffset: input.logOffset,diff --git a/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts b/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.tsindex a52726aa035..556b6429543 100644--- a/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/instanceOperations.ts@@ -1,20 +1,17 @@-import { type LobeChatDatabase } from '@lobechat/database';import {derivedInstanceDirectory,MAX_DERIVED_DIRECTORY_ATTEMPTS,} from '@lobechat/utils/environmentInstance';import { TRPCError } from '@trpc/server';-import { EnvironmentModel } from '@/database/models/environment';-import {- EnvironmentInstanceModel,- InstanceDirectoryOverlapError,-} from '@/database/models/environmentInstance';-import type { MarketService } from '@/server/services/market';+import type { EnvironmentInstanceModel } from '@/database/models/environmentInstance';+import { InstanceDirectoryOverlapError } from '@/database/models/environmentInstance';+import { sandboxStorageBinding } from '@/server/services/sandbox';import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';import { isDuplicateInstanceDirectory } from './constraintErrors';-import { mapStorageError } from './procedures';+import { isFolderOccupied } from './driveScope';+import { mapStorageError, type SandboxStorageClient } from './procedures';/*** Whether building from this definition does anything: an environment that@@ -27,47 +24,6 @@ export const isBuildable = (specification: { bootstrapCommand?: string | null; sources?: unknown[] | null } | null,): boolean => (specification?.sources?.length ?? 0) > 0 || Boolean(specification?.bootstrapCommand);-/**- * Where an instance lives, in the vocabulary `environment_instances` uses- * for every execution target it supports.- *- * The scope is the caller's workspace key and the resource is the one- * persistent workspace inside it โ there is exactly one, which is why the- * resource is named rather than identified. What distinguishes two instances is- * the directory, and `environment_instances_provider_path_unique` covers that- * tuple, so the database is what stops two copies landing in one folder.- */-export const sandboxBinding = (workspaceKey: string) => ({- deviceId: null,- kind: 'sandbox' as const,- provider: 'market',- providerResourceId: 'workspace',- providerScope: workspaceKey,-});--type SandboxStorageClient = ReturnType<MarketService['getSandboxStorageClient']>;--/**- * Run `fn` with the environment and instance models bound to one transaction,- * for the calls that must change both tables or neither.- */-export const inEnvironmentTransaction = <T>(- ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string | null },- fn: (models: {- environmentModel: EnvironmentModel;- instanceModel: EnvironmentInstanceModel;- }) => Promise<T>,-): Promise<T> =>- ctx.serverDB.transaction(async (tx) => {- const db = tx as unknown as LobeChatDatabase;- const workspaceId = ctx.workspaceId ?? undefined;-- return fn({- environmentModel: new EnvironmentModel(db, ctx.userId, workspaceId),- instanceModel: new EnvironmentInstanceModel(db, ctx.userId, workspaceId),- });- });-/*** A new sandbox instance of an environment the caller owns, with its directory* derived from the environment's name rather than asked for.@@ -80,17 +36,20 @@ export const inEnvironmentTransaction = <T>(*/export const createDerivedInstance = async (instanceModel: EnvironmentInstanceModel,+ client: SandboxStorageClient,workspaceKey: string,environment: { id: string; name: string },) => {for (let attempt = 1; attempt <= MAX_DERIVED_DIRECTORY_ATTEMPTS; attempt += 1) {const workingDirectory = derivedInstanceDirectory(environment.name, attempt);- if (await instanceModel.findByWorkingDirectory(workingDirectory)) continue;+ if (await instanceModel.findByWorkingDirectory(workingDirectory, workspaceKey)) continue;+ // An ordinary folder of the same name is somebody's work, not a free name.+ if (await isFolderOccupied(client, workingDirectory)) continue;const created = await instanceModel.create({- ...sandboxBinding(workspaceKey),+ ...sandboxStorageBinding(workspaceKey),environmentId: environment.id,// The directory is the only thing that distinguishes this instance// from its siblings right now, so it is also the only honest labeldiff --git a/apps/server/src/routers/lambda/sandboxStorage/instances.ts b/apps/server/src/routers/lambda/sandboxStorage/instances.tsindex cd60c94ef0e..285362ccd3c 100644--- a/apps/server/src/routers/lambda/sandboxStorage/instances.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/instances.ts@@ -1,28 +1,38 @@-import { isDefaultInstance } from '@lobechat/utils/environmentInstance';+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import { TRPCError } from '@trpc/server';import pMap from 'p-map';import { z } from 'zod';import { TopicModel } from '@/database/models/topic';import { router } from '@/libs/trpc/lambda';+import { forgetDriveFolders, sandboxStorageBinding } from '@/server/services/sandbox';import { stopSandboxInstance } from '@/server/services/sandbox/stopInstance';import { rethrowDuplicateInstanceDirectory } from './constraintErrors';import {- createDerivedInstance,- deleteInstanceSnapshot,- isBuildable,- sandboxBinding,-} from './instanceOperations';+ assertFolderFree,+ assertNotLeftOnPublicDrive,+ driveForEnvironment,+ resolveInstanceDrive,+} from './driveScope';+import { createDerivedInstance, deleteInstanceSnapshot, isBuildable } from './instanceOperations';import { instanceProcedure, mapStorageError } from './procedures';-import { idSchema, nameSchema, relativePathSchema, topicIdSchema } from './schemas';+import {+ driveSchema,+ idSchema,+ instanceDirectorySchema,+ nameSchema,+ topicIdSchema,+} from './schemas';/*** The topic the execution plane keys its file-browser console sessions to.* The same literal market uses (`MANAGEMENT_TOPIC_ID`); it is not a topic of* ours, so it is never looked up and the run is shown as a console session.*/-const MANAGEMENT_TOPIC_ID = 'sandbox-workspace-console';+export const MANAGEMENT_TOPIC_ID = 'sandbox-workspace-console';++/** The index that keeps two instances out of the same directory. */export const instancesRouter = router({/**@@ -36,12 +46,18 @@ export const instancesRouter = router({z.object({id: idSchema,name: nameSchema,- workingDirectory: relativePathSchema,+ workingDirectory: instanceDirectorySchema,}),).mutation(async ({ ctx, input }) => {const source = await ctx.instanceModel.findOwnedById(input.id);if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });+ // Beside the source, on the same drive: the copy starts from the+ // source's snapshot, which lives on that drive's volume.+ const sourceDrive = await resolveInstanceDrive(ctx, source);+ const { claim, client } = sourceDrive;+ await assertNotLeftOnPublicDrive(ctx, source, sourceDrive);+ await assertFolderFree(client, input.workingDirectory);// A held instance is mid-write, so a copy would capture a tree halfway// through a change. The execution plane refuses it too; asking first@@ -50,7 +66,7 @@ export const instancesRouter = router({// that did not answer is not read as "free" โ here that means refusing,// because unlike a rebuild there is no runtime lease standing behind a// copy to catch the second writer.- const occupancy = await ctx.client+ const occupancy = await client.readOccupancy({ names: [source.id] }).catch(() => ({ held: [], unavailable: true }));if (occupancy.unavailable || occupancy.held.some((entry) => entry.id === source.id)) {@@ -63,7 +79,7 @@ export const instancesRouter = router({// state as a brand-new instance, which the UI already handles.const created = await ctx.instanceModel.create({- ...sandboxBinding(ctx.claim.key),+ ...sandboxStorageBinding(claim.key),// The copy's files are the source's, so its definition is too. Left// to default, it would snapshot whatever the environment says now// and describe a checkout the copied tree does not contain.@@ -76,7 +92,7 @@ export const instancesRouter = router({if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });- await ctx.client+ await client.copyInstance({from: source.id,// The copy's own folder. Sharing the source's would let either@@ -117,24 +133,54 @@ export const instancesRouter = router({if (!environment)throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });- return createDerivedInstance(ctx.instanceModel, ctx.claim.key, environment);+ const access = await ctx.drives.client(driveForEnvironment(environment, ctx.workspaceId));+ if (!access) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This account has no persistent sandbox workspace',+ });+ }++ return createDerivedInstance(ctx.instanceModel, access.client, access.claim.key, environment);}),/**- * An instance of an environment: its own directory, its own captured- * state. Created empty โ nothing is built until a conversation runs in it.+ * Initialize a folder from an environment: an environment directory at the+ * drive's root, with its own captured state. Created unbuilt โ the caller+ * starts the build next, the same split as for any other new instance.+ *+ * Only a new folder, or an empty one. Building into a folder that already+ * holds work would mix a checkout into it, and a later rebuild would throw+ * that work away with the old checkout.*/createInstance: instanceProcedure.input(z.object({environmentId: idSchema,name: nameSchema,- workingDirectory: relativePathSchema,+ workingDirectory: instanceDirectorySchema,}),).mutation(async ({ ctx, input }) => {+ // The environment decides the drive, not the drive being browsed: a+ // private environment's directory goes on its owner's personal drive,+ // where no other member can reach the home directory it captures.+ const environment = await ctx.environmentModel.findOwnedById(input.environmentId);+ if (!environment)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });+ const drive = driveForEnvironment(environment, ctx.workspaceId);+ const access = await ctx.drives.client(drive);+ if (!access) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This account has no persistent sandbox workspace',+ });+ }++ await assertFolderFree(access.client, input.workingDirectory);+const created = await ctx.instanceModel.create({- ...sandboxBinding(ctx.claim.key),+ ...sandboxStorageBinding(access.claim.key),environmentId: input.environmentId,name: input.name,workingDirectory: input.workingDirectory,@@ -142,8 +188,9 @@ export const instancesRouter = router({.catch(rethrowDuplicateInstanceDirectory);if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });+ forgetDriveFolders(access.claim.key);- return created;+ return { ...created, drive };}),/*** One instance, from the database alone. Separate from `listInstances`@@ -151,9 +198,14 @@ export const instancesRouter = router({* and `listInstances` pays a sandbox cold start to answer how big everything* is โ seconds, for a label.*/- getInstance: instanceProcedure- .input(z.object({ id: idSchema }))- .query(async ({ ctx, input }) => (await ctx.instanceModel.findById(input.id)) ?? null),+ getInstance: instanceProcedure.input(z.object({ id: idSchema })).query(async ({ ctx, input }) => {+ const instance = await ctx.instanceModel.findById(input.id);+ if (!instance) return null;++ // Which of the caller's drives it is on, for the composer's label โ+ // `null` on a drive that is not theirs, which the run refuses.+ return { ...instance, drive: ctx.drives.driveOf(instance.providerScope) ?? null };+ }),/*** Instances, each joined with the state the execution plane actually* holds for it. An instance that was created but never used has no snapshot@@ -162,6 +214,12 @@ export const instancesRouter = router({listInstances: instanceProcedure.input(z.object({+ /**+ * Only the instances on this drive โ what a picker browsing one drive+ * asks for. Without it, every instance on any of the caller's drives,+ * which is what the environments page lists.+ */+ drive: driveSchema,environmentId: idSchema.optional(),topicId: topicIdSchema,/**@@ -174,35 +232,82 @@ export const instancesRouter = router({}),).query(async ({ ctx, input }) => {- const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });-- const [snapshots, occupancy] = await Promise.all([- input.withSizes- ? ctx.client- .listInstances({ topicId: input.topicId })- .then((result) => result.instances)- // If the store fails, the instances still exist and can still be- // renamed or selected โ only their sizes are unknown, so say so- // rather than failing a settings page.- .catch(() => null)+ // An instance on a drive that is not the caller's โ a colleague's+ // personal drive, under an environment they have since published โ is+ // not one the caller can run in, list the files of, or size.+ const located = (await ctx.instanceModel.query({ environmentId: input.environmentId }))+ .map((instance) => ({ drive: ctx.drives.driveOf(instance.providerScope), instance }))+ .filter(+ (entry): entry is { drive: SandboxDrive; instance: typeof entry.instance } =>+ !!entry.drive && (!input.drive || entry.drive === ctx.drive),+ );+ const instances = located.map((entry) => entry.instance);+ const driveById = new Map(located.map((entry) => [entry.instance.id, entry.drive]));++ // Private environments' directories left on the public drive: listed+ // for their owner โ the only member who sees a private environment โ+ // with the instruction to rebuild them, and run by nobody.+ const publicAccess =+ ctx.workspaceId && located.some((entry) => entry.drive === 'public')+ ? await ctx.drives.client('public')+ : undefined;+ const rebuildRequired = new Set(+ publicAccess+ ? (+ await ctx.instanceModel.listStorageDirectories(+ sandboxStorageBinding(publicAccess.claim.key),+ )+ )+ .filter((entry) => entry.isPrivate)+ .map((entry) => entry.id): [],- // Always, and separately from the sizes: this is a Redis read on the- // control plane, so it costs the same on every deployment, whereas the- // listing above opens the volume. An instance held by another- // conversation cannot be run in โ the lease answers the second writer- // with a 409 โ so a picker that does not know is a picker that offers- // a choice the first message will refuse.- instances.length > 0- ? ctx.client- .readOccupancy({- names: instances.map((instance) => instance.id),- topicId: input.topicId,- })- // Same rule the lease store itself follows: a failure is "not- // known", never "free".- .catch(() => ({ held: [], unavailable: true }))- : { held: [], unavailable: false },- ]);+ );++ // One client per drive, since each drive's snapshots and leases are+ // read through a claim for that drive.+ const drives = [...new Set(located.map((entry) => entry.drive))];+ const perDrive = await pMap(+ drives,+ async (drive) => {+ const access = await ctx.drives.client(drive);+ const names = located+ .filter((entry) => entry.drive === drive)+ .map((entry) => entry.instance.id);++ const [snapshots, occupancy] = await Promise.all([+ input.withSizes && access+ ? access.client+ .listInstances({ topicId: input.topicId })+ .then((result) => result.instances)+ // If the store fails, the instances still exist and can+ // still be renamed or selected โ only their sizes are+ // unknown, so say so rather than failing a settings page.+ .catch(() => null)+ : input.withSizes+ ? null+ : [],+ // Always, and separately from the sizes: this is a Redis read on+ // the control plane, so it costs the same on every deployment,+ // whereas the listing above opens the volume. An instance held by+ // another conversation cannot be run in โ the lease answers the+ // second writer with a 409 โ so a picker that does not know is a+ // picker that offers a choice the first message will refuse.+ access && names.length > 0+ ? access.client+ .readOccupancy({ names, topicId: input.topicId })+ // Same rule the lease store itself follows: a failure is+ // "not known", never "free".+ .catch(() => ({ held: [], unavailable: true }))+ : { held: [], unavailable: !access && names.length > 0 },+ ]);++ return { access, drive, occupancy, snapshots };+ },+ { concurrency: 5 },+ );+ const clientByDrive = new Map(+ perDrive.flatMap((entry) => (entry.access ? [[entry.drive, entry.access.client]] : [])),+ );// A build is polled by whoever has the Instances tab open, and nobody// has it open most of the time โ switch tabs mid-build and the verdict@@ -214,7 +319,9 @@ export const instancesRouter = router({const settled = await pMap(instances.filter((instance) => instance.buildId),async (instance) => {- const status = await ctx.client+ const client = clientByDrive.get(driveById.get(instance.id)!);+ if (!client) return null;+ const status = await client.buildStatus({ buildId: instance.buildId!, name: instance.id, topicId: input.topicId }).catch(() => null);if (!status || status.state === 'running') return null;@@ -234,8 +341,14 @@ export const instancesRouter = router({);const settledById = new Map(settled.filter((entry) => !!entry));- const byId = new Map((snapshots ?? []).map((snapshot) => [snapshot.id, snapshot]));- const heldBy = new Map(occupancy.held.map((entry) => [entry.id, entry.own]));+ const byId = new Map(+ perDrive.flatMap((entry) =>+ (entry.snapshots ?? []).map((snapshot) => [snapshot.id, snapshot] as const),+ ),+ );+ const heldBy = new Map(+ perDrive.flatMap((entry) => entry.occupancy.held.map((held) => [held.id, held.own])),+ );return {instances: instances.map((instance) => ({@@ -246,6 +359,8 @@ export const instancesRouter = router({buildable: isBuildable(instance.configurationSnapshot),buildError: settledById.get(instance.id)?.buildError ?? instance.buildError,createdAt: instance.createdAt,+ /** Which of the caller's drives the directory is on. */+ drive: driveById.get(instance.id)!,environmentId: instance.environmentId,id: instance.id,// Held by a running sandbox, and by whom. `own` is this topic's own@@ -254,12 +369,18 @@ export const instancesRouter = router({inUse: heldBy.has(instance.id),inUseByThisTopic: heldBy.get(instance.id) === true,name: instance.name,+ /**+ * A private environment's directory on the public drive, from+ * before members had drives of their own: hidden there, never run+ * in, and to be initialized again on the owner's personal drive.+ */+ rebuildRequired: rebuildRequired.has(instance.id),snapshot: byId.get(instance.id) ?? null,status: settledById.get(instance.id)?.status ?? instance.status,workingDirectory: instance.workingDirectory,})),- occupancyUnavailable: occupancy.unavailable,- snapshotsUnavailable: snapshots === null,+ occupancyUnavailable: perDrive.some((entry) => entry.occupancy.unavailable),+ snapshotsUnavailable: perDrive.some((entry) => entry.snapshots === null),};}),/**@@ -283,7 +404,9 @@ export const instancesRouter = router({}),).query(async ({ ctx, input }) => {- const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });+ const instances = (+ await ctx.instanceModel.query({ environmentId: input.environmentId })+ ).filter((instance) => ctx.drives.driveOf(instance.providerScope));if (instances.length === 0) return { sessions: [], unavailable: false };// Bounded: an environment's instance count is whatever the member made,@@ -292,8 +415,10 @@ export const instancesRouter = router({const pages = await pMap(instances,(instance) =>- ctx.client- .listEnvironmentSessions({ limit: input.limit, name: instance.id })+ resolveInstanceDrive(ctx, instance)+ .then(({ client }) =>+ client.listEnvironmentSessions({ limit: input.limit, name: instance.id }),+ )// One instance's history failing must not blank the others; the// caller is told the list is incomplete rather than shown "no runs"..catch(() => null),@@ -356,9 +481,9 @@ export const instancesRouter = router({};}),/**- * Remove one copy of an environment. The default instance is refused: it is- * what the environment is, so it goes when the environment does, and a- * broken one is rebuilt rather than deleted.+ * Remove an environment directory: what its builds left on the drive, and+ * the row. Any of them, the first included โ an environment owns no folder+ * of its own any more, so none is left to stand for it.*/removeInstance: instanceProcedure.input(z.object({ id: idSchema, topicId: topicIdSchema }))@@ -366,16 +491,13 @@ export const instancesRouter = router({const instance = await ctx.instanceModel.findOwnedById(input.id);if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });- const siblings = await ctx.instanceModel.query({ environmentId: instance.environmentId });- if (isDefaultInstance(instance, siblings)) {- throw new TRPCError({ code: 'FORBIDDEN', message: 'DEFAULT_INSTANCE' });- }-// Snapshot first, and only drop the row once it is gone: a row removed// while the snapshot survives leaves storage nobody can see, name, or// reclaim. The execution plane refuses while a session is using it, and// that refusal is the one the user needs to see.- await deleteInstanceSnapshot(ctx.client, instance.id, input.topicId);+ const { claim, client } = await resolveInstanceDrive(ctx, instance);+ await deleteInstanceSnapshot(client, instance.id, input.topicId);+ forgetDriveFolders(claim.key);return ctx.instanceModel.delete(input.id);}),@@ -392,9 +514,16 @@ export const instancesRouter = router({*/stopInstance: instanceProcedure.input(z.object({ id: idSchema }))- .mutation(async ({ ctx, input }) =>- stopSandboxInstance({ ...ctx, id: input.id }).catch(mapStorageError),- ),+ .mutation(async ({ ctx, input }) => {+ const instance = await ctx.instanceModel.findOwnedById(input.id);+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ // On the drive the instance is on, then the shared stop: it interrupts+ // the conversation holding the copy before releasing it.+ const { client } = await resolveInstanceDrive(ctx, instance);++ return stopSandboxInstance({ ...ctx, client, id: input.id }).catch(mapStorageError);+ }),renameInstance: instanceProcedure.input(z.object({ id: idSchema, name: nameSchema })).mutation(async ({ ctx, input }) => {diff --git a/apps/server/src/routers/lambda/sandboxStorage/legacyEnvironment.ts b/apps/server/src/routers/lambda/sandboxStorage/legacyEnvironment.tsnew file mode 100644index 00000000000..c40854e9c45--- /dev/null+++ b/apps/server/src/routers/lambda/sandboxStorage/legacyEnvironment.ts@@ -0,0 +1,124 @@+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';+import { z } from 'zod';++import { projectEnvironments } from '@/database/schemas';+import { router } from '@/libs/trpc/lambda';+import { forgetDriveFolders } from '@/server/services/sandbox';++import { configurationSchema } from '../_schema/environment';+import { environmentProcedures } from '../environment';+import { rethrowDuplicateEnvironmentName, rethrowEnvironmentInUse } from './constraintErrors';+import { driveForEnvironment, resolveInstanceDrive } from './driveScope';+import { createDerivedInstance, deleteInstanceSnapshot } from './instanceOperations';+import { instanceProcedure } from './procedures';+import { idSchema, nameSchema, visibilitySchema } from './schemas';++/**+ * `sandboxStorage.createEnvironment` as released, for clients from before the+ * environment router moved out: they send `withDefaultInstance: true` and+ * start the build of the `defaultInstance` they get back, and have no dialog+ * to create one themselves. Without the flag it is the definition alone, as+ * `environment.createEnvironment` is.+ *+ * All or nothing, as it was: an instance that cannot be made takes the new+ * environment back with it, so the caller sees the failure and retries.+ */+const legacyCreateEnvironment = instanceProcedure+ .input(+ z.object({+ // The released input, `files` included: desktop clients bundle the+ // form that still offers it. The new endpoint creates code only.+ configuration: configurationSchema.optional(),+ description: z.string().max(2000).optional(),+ name: nameSchema,+ visibility: visibilitySchema.optional(),+ withDefaultInstance: z.boolean().optional(),+ }),+ )+ .mutation(async ({ ctx, input: { withDefaultInstance, ...input } }) => {+ const environment = await ctx.environmentModel+ .create(input)+ .catch(rethrowDuplicateEnvironmentName);+ if (!withDefaultInstance) return { ...environment, defaultInstance: undefined };++ try {+ const access = await ctx.drives.client(driveForEnvironment(environment, ctx.workspaceId));+ if (!access) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This account has no persistent sandbox workspace',+ });+ }+ const defaultInstance = await createDerivedInstance(+ ctx.instanceModel,+ access.client,+ access.claim.key,+ environment,+ );++ return { ...environment, defaultInstance };+ } catch (error) {+ await ctx.environmentModel.delete(environment.id).catch(() => undefined);+ throw error;+ }+ });++/**+ * `sandboxStorage.removeEnvironment` as released: the environment goes with the+ * copies built from it, their snapshots and what their builds left on the+ * drive โ a file someone put in such a folder themselves stays. Released+ * clients offer no other way to delete a copy, and the current page shows+ * none, so this is how an environment that still has one is removed.+ *+ * Copy by copy, each as `removeInstance` removes one: its snapshot, then its+ * row. A snapshot the execution plane will not drop โ a run still holds it โ+ * stops there: the copies before it are gone whole, the rest are untouched,+ * and deleting again finishes the job. No copy is ever left as a row whose+ * snapshot is gone. A project still using the environment is refused first,+ * before anything is touched, since it would refuse the last step anyway.+ */+const legacyRemoveEnvironment = instanceProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ // Ownership before anything reaches the execution plane: a member who can+ // see a published environment must not get its snapshots deleted on the+ // way to being refused the row.+ const environment = await ctx.environmentModel.findOwnedById(input.id);+ if (!environment) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ const [projectLink] = await ctx.serverDB+ .select({ projectId: projectEnvironments.projectId })+ .from(projectEnvironments)+ .where(eq(projectEnvironments.environmentId, environment.id))+ .limit(1);+ if (projectLink) {+ throw new TRPCError({ code: 'CONFLICT', message: 'ENVIRONMENT_IN_PROJECT' });+ }++ const instances = (await ctx.instanceModel.query({ environmentId: environment.id })).filter(+ (entry) => entry.kind === 'sandbox',+ );+ for (const instance of instances) {+ const { claim, client } = await resolveInstanceDrive(ctx, instance);+ await deleteInstanceSnapshot(client, instance.id);+ forgetDriveFolders(claim.key);+ await ctx.instanceModel.delete(instance.id).catch(rethrowEnvironmentInUse);+ }++ const removed = await ctx.environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return removed;+ });++/**+ * The environment procedures under their released `sandboxStorage` paths โ+ * the same procedures, not copies โ with `createEnvironment` and+ * `removeEnvironment` keeping their released input and behavior.+ */+export const legacyEnvironmentRouter = router({+ ...environmentProcedures,+ createEnvironment: legacyCreateEnvironment,+ removeEnvironment: legacyRemoveEnvironment,+});diff --git a/apps/server/src/routers/lambda/sandboxStorage/procedures.ts b/apps/server/src/routers/lambda/sandboxStorage/procedures.tsindex b1ca32ee5c9..dc552a4e01b 100644--- a/apps/server/src/routers/lambda/sandboxStorage/procedures.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/procedures.ts@@ -1,13 +1,17 @@+import { DEFAULT_SANDBOX_DRIVE, type SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import { TRPCError } from '@trpc/server';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { EnvironmentModel } from '@/database/models/environment';import { EnvironmentInstanceModel } from '@/database/models/environmentInstance';+import { TopicModel } from '@/database/models/topic';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { MarketService } from '@/server/services/market';-import { resolveSandboxStorageClaim } from '@/server/services/sandbox';+import { createDriveAccess, resolveSandboxStorageClaim } from '@/server/services/sandbox';import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';+import { driveSchema } from './schemas';+/*** Statuses the execution plane uses deliberately, each carrying something the* user can act on. Anything else is a fault on the far side and says so.@@ -16,7 +20,7 @@ import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles* environment. Collapsing it into a generic upstream failure would replace the* only actionable message with one that suggests the product is broken.*/-const WORKSPACE_ERROR_CODES: Record<number, TRPCError['code']> = {+export const WORKSPACE_ERROR_CODES: Record<number, TRPCError['code']> = {400: 'BAD_REQUEST',403: 'FORBIDDEN',404: 'NOT_FOUND',@@ -42,14 +46,18 @@ export const mapStorageError = (error: unknown): never => {};/**- * Resolves the caller's sandbox-storage claim: which directory on the volume- * they are entitled to and how large it may be.+ * Resolves the caller's sandbox-storage claim for the drive the call names:+ * which directory on the volume they are entitled to and how large it may be.** It reads `ctx.workspaceId`, but that is the TEAM workspace, and it is read- * only to decide whose storage this is โ a member inside a team gets the- * team's shared directory, otherwise their personal one. The claim itself has- * nothing to do with the team workspace, which is why neither this nor- * anything built on it is named after one.+ * only to decide whose storage this is โ inside a team the public drive or+ * the member's personal one, otherwise their personal account's. The claim+ * itself has nothing to do with the team workspace, which is why neither this+ * nor anything built on it is named after one.+ *+ * A call that names no drive but names a topic addresses the topic's: the+ * working panel lists the conversation's own folder, and that folder is on+ * the drive the conversation picked.** The caller is always acting as themselves here โ a signed-in user browsing* their own storage, not an agent run executing under someone else's identity@@ -58,17 +66,38 @@ export const mapStorageError = (error: unknown): never => {export const storageClaimProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const workspaceId = ctx.workspaceId ?? undefined;+ const raw = (await opts.getRawInput()) as { drive?: unknown; topicId?: unknown } | undefined;- const claim = await resolveSandboxStorageClaim({- isShareVisitorRun: false,+ let drive: SandboxDrive = workspaceId ? DEFAULT_SANDBOX_DRIVE : 'personal';+ const named = driveSchema.safeParse(raw?.drive);+ if (workspaceId && named.success && named.data) {+ drive = named.data;+ } else if (workspaceId && typeof raw?.topicId === 'string' && raw.topicId) {+ // A lookup that fails leaves the call on the public drive, the default a+ // topic without a drive of its own means anyway.+ try {+ const topic = await new TopicModel(ctx.serverDB, ctx.userId, workspaceId).findById(+ raw.topicId,+ );+ if (topic?.metadata?.sandboxDrive === 'personal') drive = 'personal';+ } catch {+ /* keep the default */+ }+ }++ const drives = createDriveAccess({+ resolveClaim: resolveSandboxStorageClaim,serverDB: ctx.serverDB,userId: ctx.userId,workspaceId,});+ const claim = await drives.claim(drive);return opts.next({ctx: {claim,+ drive,+ drives,marketService: new MarketService({userInfo: { sandboxStorage: claim, userId: ctx.userId, workspaceId },}),@@ -130,3 +159,5 @@ export const instanceProcedure = environmentProcedure.use(async (opts) => {},});});++export type SandboxStorageClient = ReturnType<MarketService['getSandboxStorageClient']>;diff --git a/apps/server/src/routers/lambda/sandboxStorage/schemas.ts b/apps/server/src/routers/lambda/sandboxStorage/schemas.tsindex 5d149b256e0..3e4eb122068 100644--- a/apps/server/src/routers/lambda/sandboxStorage/schemas.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/schemas.ts@@ -1,4 +1,4 @@-import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';+import { isSafeSandboxCwd, SANDBOX_DRIVES } from '@lobechat/builtin-tool-cloud-sandbox';import { z } from 'zod';/** Relative workspace path, validated with the same rule the runtime applies. */@@ -37,3 +37,16 @@ export const idSchema = z.string().uuid();* client sends.*/export const visibilitySchema = z.enum(['private', 'public']);++export const driveSchema = z.enum(SANDBOX_DRIVES).optional();++/**+ * An environment directory's path: one folder at the drive's root, never+ * nested. Every member's environment directories sit side by side there, which+ * is what lets a listing tell them apart from ordinary folders at a glance.+ */+export const instanceDirectorySchema = relativePathSchema.refine((value) => !value.includes('/'), {+ message: 'An environment directory sits at the root of the drive',+});++export const instanceIdSchema = idSchema.optional();diff --git a/apps/server/src/routers/lambda/sandboxStorage/storage.ts b/apps/server/src/routers/lambda/sandboxStorage/storage.tsindex 75a070e110c..9ca73b9e3b5 100644--- a/apps/server/src/routers/lambda/sandboxStorage/storage.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/storage.ts@@ -1,9 +1,11 @@import { z } from 'zod';+import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';import { router } from '@/libs/trpc/lambda';-import { resolveSandboxSessionConfig } from '@/server/services/sandbox';+import { readDriveUsage, resolveSandboxSessionConfig } from '@/server/services/sandbox';import { entitledProcedure, mapStorageError, storageClaimProcedure } from './procedures';+import { driveSchema, topicIdSchema } from './schemas';export const storageRouter = router({/**@@ -13,6 +15,12 @@ export const storageRouter = router({* workspace.*/getEntitlement: storageClaimProcedure.query(async ({ ctx }) => ({+ /**+ * The drives this caller has: `public` and `personal` in a workspace,+ * `personal` alone in a personal account. Both of a workspace's drive+ * share one plan, so one is entitled exactly when the other is.+ */+ drives: ctx.drives.available,entitled: Boolean(ctx.claim),quotaBytes: ctx.claim?.quotaBytes ?? null,})),@@ -33,7 +41,7 @@ export const storageRouter = router({resolveSessionPlacement: storageClaimProcedure.input(z.object({ topicId: z.string().optional() })).query(async ({ ctx, input }) => {- const { claim, cwd, mode, workingDir } = await resolveSandboxSessionConfig({+ const { claim, cwd, drive, fallback, mode, workingDir } = await resolveSandboxSessionConfig({isShareVisitorRun: false,serverDB: ctx.serverDB,topicId: input.topicId,@@ -41,21 +49,37 @@ export const storageRouter = router({workspaceId: ctx.workspaceId ?? undefined,});- return claim ? { cwd, mode, workingDir } : null;+ // `fallback` says why a folder or environment directory the topic picked+ // is not where this run goes, so the composer can tell the person+ // before they send rather than after the work went somewhere temporary.+ return claim ? { cwd, drive, fallback, mode, workingDir } : null;}),- getStorage: entitledProcedure.query(async ({ ctx }) =>- ctx.client.getStorage().catch(mapStorageError),- ),+ // A topic stands for the drive it picked, so the working panel's tree is+ // rooted on the drive its files are actually on.+ getStorage: entitledProcedure+ .input(z.object({ drive: driveSchema, topicId: topicIdSchema }).optional())+ .query(async ({ ctx }) => ctx.client.getStorage().catch(mapStorageError)),/**- * Re-measure the workspace and answer with the fresh figure.+ * How much each of the caller's drives holds against the plan's quota.*- * A mutation rather than a query because it writes: it walks the volume and- * stamps the workspace as active. Kept off page load for that reason โ the- * settings page reads the stored number and offers this on its refresh- * button, so a page nobody asked to refresh cannot keep an idle workspace- * looking busy.+ * A workspace's public drive and every member's personal drive draw on one+ * pool, so the figure that decides whether a write is refused is their sum+ * โ the execution plane reports it beside each drive's own. An owner or+ * admin is also shown how much each other member's personal drive holds:+ * the amount, which is the workspace's to pay for, and never the contents,+ * which stay out of reach of every claim this router issues.*/- refreshStorageUsage: entitledProcedure.mutation(async ({ ctx }) =>- ctx.client.refreshUsage().catch(mapStorageError),+ getDriveUsage: entitledProcedure.query(async ({ ctx }) =>+ readDriveUsage({+ claim: ctx.claim,+ drives: ctx.drives,+ role: (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole,+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),),+ refreshStorageUsage: entitledProcedure+ .input(z.object({ drive: driveSchema }).optional())+ .mutation(async ({ ctx }) => ctx.client.refreshUsage().catch(mapStorageError)),});diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex 92eb22db3e1..a0cb4fd914f 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -320,6 +320,7 @@ const execInSandboxHandler = async ({fileService: ctx.fileService,marketService,sandboxCwd: sandbox.cwd,+ sandboxInitialization: sandbox.initialization,sandboxInstanceId: sandbox.environment,sandboxMode: sandbox.mode,sandboxSpecification: sandbox.specification,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.tsindex 5f18c8d6938..8525ff825a8 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/sandbox.ts@@ -135,6 +135,8 @@ export const spawnInCloudSandbox = async (sandbox: sandbox && {cwd: sandbox.cwd,environment: sandbox.environment,+ // Applied before the agent starts, so it opens on the checkout.+ initialization: sandbox.initialization,mode: sandbox.mode,// The environment's variables, network access, maintenance command// and sources all ride here; dropping it starts the run with nonediff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.tsindex 65204f29a63..006b3f0c42b 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -1,4 +1,5 @@import type { InternalExecAgentParams } from '../types';+import { pickSandboxPlacement } from './sandboxPlacement';export interface NewTopicMetadataInput {appContext?: InternalExecAgentParams['appContext'];@@ -61,10 +62,7 @@ export const buildNewTopicMetadata = ({...(editingGroupId && { editingGroupId }),taskId,...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),- ...(initialTopicMeta?.sandboxInstanceId && {- sandboxInstanceId: initialTopicMeta.sandboxInstanceId,- }),- ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),+ ...pickSandboxPlacement(initialTopicMeta),...(initialTopicMeta?.workingDirectory && {workingDirectory: initialTopicMeta.workingDirectory,}),diff --git a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.ts b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.tsnew file mode 100644index 00000000000..186b4b90b68--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';++import { pickSandboxPlacement } from './sandboxPlacement';++describe('pickSandboxPlacement', () => {+ it('carries the folder or the environment directory the composer chose', () => {+ expect(pickSandboxPlacement({ sandboxWorkingDirectory: 'reports' })).toEqual({+ sandboxWorkingDirectory: 'reports',+ });+ expect(pickSandboxPlacement({ sandboxInstanceId: 'inst-1' })).toEqual({+ sandboxInstanceId: 'inst-1',+ });+ });++ it('carries the drive the folder is on', () => {+ expect(+ pickSandboxPlacement({ sandboxDrive: 'personal', sandboxWorkingDirectory: 'notes' }),+ ).toEqual({ sandboxDrive: 'personal', sandboxWorkingDirectory: 'notes' });+ });++ it('carries nothing for a conversation that chose nothing', () => {+ expect(pickSandboxPlacement(undefined)).toEqual({});+ expect(pickSandboxPlacement({})).toEqual({});+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.ts b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.tsnew file mode 100644index 00000000000..f8e63e31ab7--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/sandboxPlacement.ts@@ -0,0 +1,20 @@+import type { InitialTopicMetadata } from '@lobechat/types';++/**+ * The cloud-sandbox placement a first send carries onto the topic it creates โ+ * a folder on one of the workspace's drives and the environment to initialize+ * it from โ without the keys it does not set, so an unset one never lands on the row as an explicit blank.+ */+export const pickSandboxPlacement = (+ metadata?: Pick<+ InitialTopicMetadata,+ 'sandboxDrive' | 'sandboxEnvironmentId' | 'sandboxInstanceId' | 'sandboxWorkingDirectory'+ >,+) => ({+ ...(metadata?.sandboxDrive && { sandboxDrive: metadata.sandboxDrive }),+ ...(metadata?.sandboxEnvironmentId && { sandboxEnvironmentId: metadata.sandboxEnvironmentId }),+ ...(metadata?.sandboxInstanceId && { sandboxInstanceId: metadata.sandboxInstanceId }),+ ...(metadata?.sandboxWorkingDirectory && {+ sandboxWorkingDirectory: metadata.sandboxWorkingDirectory,+ }),+});diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.tsindex 45e1485dd55..3129c4beb89 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.ts@@ -26,11 +26,22 @@ describe('buildCloudHeteroContext', () => {});expect(context).toContain('Your working directory is `lobehub-main`');- expect(context).toContain('persistent workspace');+ expect(context).toContain('environment directory');expect(context).toContain('- `./lobehub`');expect(context).not.toContain('/workspace');expect(context).not.toContain('ephemeral');// Code still has to reach the remote.expect(context).toContain('**Always commit and push**');});++ it('describes a drive folder as a folder on the network drive', () => {+ const context = buildCloudHeteroContext({+ repos: ['lobehub/lobehub'],+ sandbox: { cwd: 'reports', mode: 'drive' },+ });++ expect(context).toContain('`reports`, a folder on the user');+ expect(context).toContain('installed packages do not carry over');+ expect(context).not.toContain('/workspace');+ });});diff --git a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.tsindex a6f84b8e1cb..72fc6c68f02 100644--- a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts+++ b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts@@ -1,4 +1,4 @@-import type { SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';+import { isPersistentSandboxMode, type SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import type { UnansweredUserTurn } from './unansweredUserTurns';import { formatUnansweredUserTurns } from './unansweredUserTurns';@@ -24,9 +24,10 @@ export interface ConversationHistoryEntry {*//*** Where the run keeps its files. Absent or `ephemeral` renders the original- * wording byte for byte; `persistent` describes the instance directory the- * execution plane starts the run in โ by its place in the workspace, never by- * an absolute path, which is the plane's to choose.+ * wording byte for byte; `drive` describes the folder on the user's drive and+ * `persistent` the environment directory the execution plane starts the run in+ * โ by its place on the drive, never by an absolute path, which is the+ * plane's to choose.*/export interface CloudHeteroSandboxPlacement {/** Chosen subdirectory of the workspace, relative to its root. */@@ -58,7 +59,7 @@ export function buildCloudHeteroContext(params: {sandbox,unansweredUserTurns,} = params;- const persistent = sandbox?.mode === 'persistent';+ const persistent = isPersistentSandboxMode(sandbox?.mode);const parts: string[] = [];@@ -74,10 +75,12 @@ export function buildCloudHeteroContext(params: {const placementLines: string[] = persistent? ['## Cloud Workspace',- sandbox?.cwd- ? `You are running inside a LobeHub cloud sandbox. Your working directory is \`${sandbox.cwd}\`, a subdirectory of a **persistent workspace**: files written there survive session expiry and are still there in your next session.`- : 'You are running inside a LobeHub cloud sandbox. Your working directory is a **persistent workspace**: files written there survive session expiry and are shared with the other conversation topics that use this workspace.',- "The workspace root is above you. Its other subdirectories belong to this user's other topics โ reachable with relative paths, but do not write into them unless the user asks.",+ sandbox?.mode === 'drive'+ ? sandbox.cwd+ ? `You are running inside a LobeHub cloud sandbox. Your working directory is \`${sandbox.cwd}\`, a folder on the user's **network drive**: files written there survive session expiry and are still there in your next session. The machine itself starts fresh every session, so installed packages do not carry over.`+ : "You are running inside a LobeHub cloud sandbox. Your working directory is the root of the user's **network drive**: files written there survive session expiry and are still there in your next session. The machine itself starts fresh every session, so installed packages do not carry over."+ : `You are running inside a LobeHub cloud sandbox. Your working directory is ${sandbox?.cwd ? `\`${sandbox.cwd}\`, ` : ''}an **environment directory** on the user's drive: its files and the packages its setup installed survive session expiry and are restored in your next session.`,+ 'Other folders on the drive belong to other work โ reachable with relative paths, but do not write into them unless the user asks.','The workspace 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. Install packages and build where the toolchain puts things by default.','','## Sandbox Persistence',diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex ce4cddfd316..a48687c39b9 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -2,6 +2,7 @@// fs-heavy machinery into the Next.js server bundle, and its dynamic// `process.cwd()`-rooted fs calls make Vercel's file tracing pull the whole// repo source tree into every serverless function (250 MB limit blowout).+import { isPersistentSandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import {buildHeteroExecStdinPayload,type HeteroExecImageRef,@@ -52,7 +53,7 @@ export interface SandboxRunParams {*/sandbox?: Pick<SandboxSessionConfig,- 'cwd' | 'environment' | 'mode' | 'specification' | 'workingDir'+ 'cwd' | 'environment' | 'initialization' | 'mode' | 'specification' | 'workingDir'>;/*** Optional context injected as a text block BEFORE the user's prompt.@@ -168,13 +169,13 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<void// consistent --cwd the session id stored in topic.metadata.heteroSessionId// can't be resolved on --resume after a page reload.//- // A persistent run gets NO --cwd: the execution plane starts every command- // inside the instance's directory, and where it mounts the workspace is its+ // A persistent run (a drive folder or an environment directory) gets NO+ // --cwd: the execution plane starts every command inside that directory, and where it mounts the workspace is its// business โ a path spelled out here would be a second source of truth that// can only drift. `lh` falls back to its process cwd, which is that// directory, and it is the same one on every run of this topic, so session// files stay findable exactly as they do under /workspace.- const persistent = sandbox?.mode === 'persistent';+ const persistent = isPersistentSandboxMode(sandbox?.mode);const cwd = params.cwd ?? (persistent ? undefined : '/workspace');// Build the `lh hetero exec` command string.@@ -248,6 +249,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidconst sandboxService = createSandboxService({marketService,sandboxCwd: sandbox?.cwd,+ sandboxInitialization: sandbox?.initialization,sandboxInstanceId: sandbox?.environment,sandboxMode: sandbox?.mode,sandboxSpecification: sandbox?.specification,diff --git a/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts b/apps/server/src/services/sandbox/__tests__/driveFolder.test.tsnew file mode 100644index 00000000000..e88ceb2fcad--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts@@ -0,0 +1,62 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { driveFolderCacheSize, driveFolderExists, forgetDriveFolders } from '../driveFolder';++const listFiles = vi.fn();++vi.mock('@/server/services/market', () => ({+ // `function`, not an arrow: the service is constructed with `new`.+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getSandboxStorageClient: () => ({ listFiles }),+ };+ }),+}));++const claim = { key: 'ws-public-ws1', quotaBytes: 1024 };++const check = (path: string, key = claim.key) =>+ driveFolderExists({ claim: { ...claim, key }, path, userId: 'u1', workspaceId: 'ws1' });++beforeEach(() => {+ vi.useFakeTimers();+ listFiles.mockReset().mockResolvedValue({ entries: [] });+});++afterEach(() => {+ forgetDriveFolders(claim.key);+ for (let i = 0; i < 2000; i++) forgetDriveFolders(`k${i}`);+ vi.useRealTimers();+});++describe('driveFolderExists', () => {+ it('should answer a recently seen folder from the cache', async () => {+ await expect(check('reports')).resolves.toBe(true);+ await expect(check('reports')).resolves.toBe(true);++ expect(listFiles).toHaveBeenCalledTimes(1);+ });++ it('should ask again once the entry has expired', async () => {+ await check('reports');+ vi.advanceTimersByTime(15_000);+ await check('reports');++ expect(listFiles).toHaveBeenCalledTimes(2);+ });++ it('should drop expired entries when remembering a new folder', async () => {+ await check('a', 'k0');+ await check('b', 'k1');+ vi.advanceTimersByTime(15_000);+ await check('c', 'k2');++ expect(driveFolderCacheSize()).toBe(1);+ });++ it('should not remember more folders than its cap', async () => {+ for (let i = 0; i < 1100; i++) await check('folder', `k${i}`);++ expect(driveFolderCacheSize()).toBe(1000);+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/driveUsage.test.ts b/apps/server/src/services/sandbox/__tests__/driveUsage.test.tsnew file mode 100644index 00000000000..7c889363033--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/driveUsage.test.ts@@ -0,0 +1,102 @@+import { deriveSandboxStorageKey } from '@lobechat/builtin-tool-cloud-sandbox';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { readDriveUsage } from '../driveUsage';++const memberGetStorage = vi.fn();++vi.mock('@/server/services/market', () => ({+ // `function`, not an arrow: the service is constructed with `new`.+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getSandboxStorageClient: () => ({ getStorage: memberGetStorage }),+ };+ }),+}));++const WORKSPACE = 'ws1';+const members = [+ { avatar: null, fullName: 'Owner', userId: 'owner', username: null },+ { avatar: null, fullName: 'Ada', userId: 'ada', username: null },+ { avatar: null, fullName: 'Bo', userId: 'bo', username: null },+];++const serverDB = {+ select: () => ({ from: () => ({ innerJoin: () => ({ where: async () => members }) }) }),+} as any;++const accessWith = (publicInfo: Record<string, unknown>) => {+ const getStorage = vi.fn(async (params?: { withDrives?: boolean }) =>+ params?.withDrives ? publicInfo : { ...publicInfo, workspaceDrives: undefined },+ );+ const personal = vi.fn(async () => ({ usageBytes: 5 }));+ return {+ access: {+ available: ['public', 'personal'],+ client: async (drive: string) => ({+ client: { getStorage: drive === 'public' ? getStorage : personal },+ }),+ } as any,+ getStorage,+ };+};++const read = (access: any, role = 'owner') =>+ readDriveUsage({+ claim: { key: 'ws-org-ws1', quotaBytes: 1000 },+ drives: access,+ role,+ serverDB,+ userId: 'owner',+ workspaceId: WORKSPACE,+ });++describe('readDriveUsage', () => {+ beforeEach(() => {+ memberGetStorage.mockReset().mockResolvedValue({ usageBytes: 1 });+ });++ it("should take members' figures from the pool listing, without a read per member", async () => {+ const adaKey = deriveSandboxStorageKey({+ drive: 'personal',+ userId: 'ada',+ workspaceId: WORKSPACE,+ });+ const { access, getStorage } = accessWith({+ usageBytes: 100,+ workspaceDrives: [+ { storageKey: 'ws-org-ws1', usageBytes: 100 },+ { storageKey: adaKey, usageBytes: 40 },+ ],+ workspaceUsageBytes: 145,+ });++ const usage = await read(access);++ expect(getStorage).toHaveBeenCalledWith({ withDrives: true });+ expect(memberGetStorage).not.toHaveBeenCalled();+ expect(usage.members).toEqual([+ expect.objectContaining({ usageBytes: 40, userId: 'ada' }),+ // No row in the pool: never had a session, so nothing measured.+ expect.objectContaining({ usageBytes: null, userId: 'bo' }),+ ]);+ });++ it('should fall back to a read per member when the pool cannot be listed', async () => {+ const { access } = accessWith({ usageBytes: 100, workspaceUsageBytes: 145 });++ const usage = await read(access);++ expect(memberGetStorage).toHaveBeenCalledTimes(2);+ expect(usage.members?.map((member) => member.usageBytes)).toEqual([1, 1]);+ });++ it('should not ask for the pool, or list members, for a plain member', async () => {+ const { access, getStorage } = accessWith({ usageBytes: 100 });++ const usage = await read(access, 'member');++ expect(getStorage).toHaveBeenCalledWith({ withDrives: false });+ expect(usage.members).toBeNull();+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts b/apps/server/src/services/sandbox/__tests__/environmentInit.test.tsnew file mode 100644index 00000000000..3623c7ff5ae--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts@@ -0,0 +1,237 @@+import { execFileSync } from 'node:child_process';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ buildSandboxEnvironmentInitCommand,+ environmentInitRan,+ environmentInitReport,+ type SandboxInitialization,+ toSandboxInitialization,+} from '../environmentInit';++const sandbox = { home: '', tmp: '' };++const run = (command: string, cwd: string) => {+ const env = { ...process.env, HOME: sandbox.home, TMPDIR: sandbox.tmp };+ try {+ return {+ status: 0,+ stdout: execFileSync('bash', ['-c', command], { cwd, encoding: 'utf8', env }),+ };+ } catch (error) {+ const failure = error as { status: number; stdout: string };+ return { status: failure.status, stdout: failure.stdout };+ }+};++describe('toSandboxInitialization', () => {+ it('keeps git sources, setup and variables', () => {+ expect(+ toSandboxInitialization({+ configuration: {+ bootstrapCommand: ' pnpm install ',+ env: { REGION: 'us' },+ sources: [+ { kind: 'git', ref: 'main', url: 'https://github.com/a/b.git' },+ { kind: 'files', uri: 's3://legacy' },+ ],+ },+ id: 'env_1',+ name: 'Tools',+ }),+ ).toEqual({+ bootstrapCommand: 'pnpm install',+ env: { REGION: 'us' },+ environmentId: 'env_1',+ name: 'Tools',+ sources: [{ ref: 'main', url: 'https://github.com/a/b.git' }],+ });+ });++ it('asks for nothing when the environment has neither a repository nor setup', () => {+ expect(+ toSandboxInitialization({+ configuration: { sources: [{ kind: 'files', uri: 's3://x' }] },+ id: 'env_1',+ name: 'Empty',+ }),+ ).toBeUndefined();+ });+});++describe('buildSandboxEnvironmentInitCommand', () => {+ let root: string;+ let repo: string;+ let work: string;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'lobe-env-init-'));+ repo = join(root, 'repo');+ work = join(root, 'work');+ mkdirSync(repo);+ mkdirSync(work);+ sandbox.home = join(root, 'home');+ sandbox.tmp = join(root, 'tmp');+ mkdirSync(sandbox.home);+ mkdirSync(sandbox.tmp);+ const git = (...args: string[]) =>+ execFileSync('git', args, {+ cwd: repo,+ env: {+ ...process.env,+ GIT_AUTHOR_EMAIL: 't@t',+ GIT_AUTHOR_NAME: 't',+ GIT_COMMITTER_EMAIL: 't@t',+ GIT_COMMITTER_NAME: 't',+ },+ });+ git('init', '-q', '-b', 'main');+ writeFileSync(join(repo, 'README.md'), 'hello');+ git('add', '.');+ git('commit', '-qm', 'init');+ });++ afterEach(() => rmSync(root, { force: true, recursive: true }));++ const init = (overrides: Partial<SandboxInitialization> = {}): SandboxInitialization => ({+ bootstrapCommand: 'echo "$REGION" > setup.txt',+ env: { REGION: 'eu' },+ environmentId: 'env_1',+ name: "Bob's tools",+ sources: [{ url: `file://${repo}` }],+ ...overrides,+ });++ it('clones the repository with its history and runs setup with the variables, leaving nothing of its own', () => {+ const result = run(buildSandboxEnvironmentInitCommand(init()), work);++ expect(result.status).toBe(0);+ expect(environmentInitRan(result.stdout)).toBe(true);+ expect(environmentInitReport(result.stdout)).toBe(+ `Initialized from the environment Bob's tools.`,+ );+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('hello');+ expect(existsSync(join(work, '.git'))).toBe(true);+ expect(readFileSync(join(work, 'setup.txt'), 'utf8').trim()).toBe('eu');+ // Only what the repository and setup put there: no marker beside them.+ expect(readdirSync(work).sort()).toEqual(['.git', 'README.md', 'setup.txt']);+ expect(execFileSync('git', ['status', '--porcelain'], { cwd: work, encoding: 'utf8' })).toBe(+ '?? setup.txt\n',+ );+ });++ it('does nothing and prints nothing once the folder holds the checkout', () => {+ const command = buildSandboxEnvironmentInitCommand(init());+ run(command, work);+ rmSync(join(work, 'setup.txt'));++ const again = run(command, work);++ expect(again).toEqual({ status: 0, stdout: '' });+ expect(existsSync(join(work, 'setup.txt'))).toBe(false);+ });++ it('leaves a folder that already holds files alone, silently', () => {+ writeFileSync(join(work, 'mine.txt'), 'work');++ const result = run(buildSandboxEnvironmentInitCommand(init()), work);++ expect(result).toEqual({ status: 0, stdout: '' });+ expect(existsSync(join(work, 'README.md'))).toBe(false);+ });++ it('runs a setup that writes nothing into the folder once, not on every call', () => {+ // A global install leaves the folder empty, and each tool call starts a+ // fresh service: the record in the sandbox is what stops a rerun.+ const command = buildSandboxEnvironmentInitCommand(+ init({ bootstrapCommand: 'echo ran >> "$HOME/setup-runs"', sources: [] }),+ );++ expect(environmentInitRan(run(command, work).stdout)).toBe(true);+ expect(run(command, work).stdout).toBe('');+ expect(readFileSync(join(sandbox.home, 'setup-runs'), 'utf8')).toBe('ran\n');+ expect(readdirSync(work)).toEqual([]);+ });++ it('reports a failed setup once rather than retrying it on every call', () => {+ const command = buildSandboxEnvironmentInitCommand(+ init({ bootstrapCommand: 'exit 7', sources: [] }),+ );++ expect(environmentInitReport(run(command, work).stdout)).toContain('failed (exit 7)');+ expect(run(command, work).stdout).toBe('');+ });++ it('initializes another empty folder with the same environment on its own', () => {+ const command = buildSandboxEnvironmentInitCommand(init());+ const other = join(root, 'other');+ mkdirSync(other);++ run(command, work);++ expect(environmentInitRan(run(command, other).stdout)).toBe(true);+ expect(existsSync(join(other, 'README.md'))).toBe(true);+ });++ it('leaves no staging copy of the repository behind, whether setup succeeds or fails', () => {+ run(buildSandboxEnvironmentInitCommand(init()), work);+ const failing = join(root, 'failing');+ mkdirSync(failing);+ run(buildSandboxEnvironmentInitCommand(init({ bootstrapCommand: 'exit 3' })), failing);++ expect(readdirSync(sandbox.tmp)).toEqual([]);+ });++ it('gives git the clone credential for the clones alone, and keeps it out of the checkout', () => {+ const result = run(+ buildSandboxEnvironmentInitCommand(+ init({+ bootstrapCommand: 'echo "[$GIT_CONFIG_VALUE_0]" > seen.txt',+ cloneCredential: {+ header: 'Authorization: Basic c2VjcmV0',+ urlPrefix: 'https://github.com/',+ },+ }),+ ),+ work,+ );++ expect(environmentInitReport(result.stdout)).toContain('Initialized');+ // Setup, which runs after the clones, cannot read it back.+ expect(readFileSync(join(work, 'seen.txt'), 'utf8').trim()).toBe('[]');+ expect(readFileSync(join(work, '.git', 'config'), 'utf8')).not.toContain('c2VjcmV0');+ expect(result.stdout).not.toContain('c2VjcmV0');+ });++ it('keeps the variables out of the shell that runs afterwards', () => {+ run(buildSandboxEnvironmentInitCommand(init()), work);++ expect(+ run(`${buildSandboxEnvironmentInitCommand(init())}; echo "[$REGION]"`, work).stdout,+ ).toBe('[]\n');+ });++ it('refuses a source path that leaves the working directory', () => {+ const result = run(+ buildSandboxEnvironmentInitCommand(+ init({ sources: [{ path: '../out', url: `file://${repo}` }] }),+ ),+ work,+ );++ expect(result.stdout).toContain('unusable path');+ expect(existsSync(join(root, 'out'))).toBe(false);+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/service.test.ts b/apps/server/src/services/sandbox/__tests__/service.test.tsindex 72f1bea351e..ce9312bb1f1 100644--- a/apps/server/src/services/sandbox/__tests__/service.test.ts+++ b/apps/server/src/services/sandbox/__tests__/service.test.ts@@ -56,6 +56,108 @@ describe('SandboxMiddlewareService', () => {vi.restoreAllMocks();});+ describe('initializing from an environment', () => {+ const capabilities = {+ backgroundCommands: true,+ exportFile: true,+ files: true,+ languages: ['python'],+ persistentSession: true,+ shell: true,+ skillScripts: true,+ };+ const init = {+ environmentId: 'env-1',+ name: 'Hello',+ sources: [{ url: 'https://github.com/octocat/Hello-World' }],+ };++ const serviceWith = async (stdout: string) => {+ const { SandboxMiddlewareService: TestSandboxMiddlewareService } = await import('../service');+ const callTool = vi.fn(async (name: string, params: Record<string, unknown>) =>+ String(params.command).includes('__lobe_environment_ran')+ ? { result: { exitCode: 0, stderr: '', stdout }, success: true }+ : { result: { exitCode: 0, stderr: '', stdout: `ran ${name}` }, success: true },+ );+ const provider = {+ callTool,+ capabilities,+ exportFileToUploadUrl: vi.fn(),+ kind: 'market',+ } satisfies SandboxProvider;+ const service = new TestSandboxMiddlewareService(provider, {+ marketService: {} as MarketService,+ sandboxInitialization: init,+ topicId: 'topic-1',+ userId: 'user-1',+ });++ return { callTool, service };+ };++ it('applies the environment once, before the first tool, and says so in the first shell result', async () => {+ const { callTool, service } = await serviceWith(+ '__lobe_environment_ran\nInitialized from the environment Hello.\n',+ );++ const first = await service.callTool('runCommand', { command: 'ls' });+ await service.callTool('runCommand', { command: 'pwd' });++ const commands = callTool.mock.calls.map(([, params]) => String(params.command));+ expect(commands.filter((command) => command.includes('__lobe_environment_ran'))).toHaveLength(+ 1,+ );+ expect(commands[0]).toContain('git clone');+ expect((first.result as { stdout: string }).stdout).toBe(+ '[environment] Initialized from the environment Hello.\n\nran runCommand',+ );+ });++ it('keeps the report for the first shell result when an earlier call only read files', async () => {+ const { service } = await serviceWith(+ '__lobe_environment_ran\nInitializing from the environment Hello failed (exit 7).\n',+ );++ const read = await service.callTool('listFiles', { path: '.' });+ const shell = await service.callTool('runCommand', { command: 'ls' });+ const later = await service.callTool('runCommand', { command: 'pwd' });++ expect(JSON.stringify(read.result)).not.toContain('[environment]');+ expect((shell.result as { stdout: string }).stdout).toBe(+ '[environment] Initializing from the environment Hello failed (exit 7).\n\nran runCommand',+ );+ expect((later.result as { stdout: string }).stdout).toBe('ran runCommand');+ });++ it('says so when the initializer could not reach the sandbox, rather than nothing', async () => {+ const { callTool, service } = await serviceWith('');+ callTool.mockRejectedValueOnce(new Error('gateway down'));++ const result = await service.callTool('runCommand', { command: 'ls' });++ expect((result.result as { stdout: string }).stdout).toBe(+ '[environment] The environment "Hello" could not be applied: the sandbox did not respond. It will be tried again on the next command.\n\nran runCommand',+ );+ });++ it('treats a failed call that printed nothing as unreachable, not as initialized', async () => {+ const { callTool, service } = await serviceWith('');+ callTool.mockResolvedValueOnce({ result: null, success: false } as any);++ const result = await service.callTool('runCommand', { command: 'ls' });++ expect((result.result as { stdout: string }).stdout).toContain('could not be applied');+ });++ it('adds nothing to the result when the directory was already initialized', async () => {+ const { service } = await serviceWith('');++ const result = await service.callTool('runCommand', { command: 'ls' });++ expect((result.result as { stdout: string }).stdout).toBe('ran runCommand');+ });+ });+it('uploads provider exports through the shared file record flow', async () => {const { SandboxMiddlewareService: TestSandboxMiddlewareService } = await import('../service');const exportFileToUploadUrl = vi.fn(async () => ({diff --git a/apps/server/src/services/sandbox/__tests__/session.test.ts b/apps/server/src/services/sandbox/__tests__/session.test.tsindex 3a74162eb22..5f306340bf0 100644--- a/apps/server/src/services/sandbox/__tests__/session.test.ts+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts@@ -2,16 +2,24 @@ import type { LobeChatDatabase } from '@lobechat/database';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ driveFolderExists: vi.fn(),+ findEnvironmentById: vi.fn(),EnvironmentInstanceModel: vi.fn(),+ listStorageDirectories: vi.fn(),TopicModel: vi.fn(),findById: vi.fn(),getAgentVisibility: vi.fn(),findInstanceById: vi.fn(),resolveSandboxStorageClaim: vi.fn(),+ resolveScmCloneCredential: vi.fn(),}));const { findById, findInstanceById, getAgentVisibility, resolveSandboxStorageClaim } = mocks;+vi.mock('@/server/services/scm/cloneCredential', () => ({+ resolveScmCloneCredential: mocks.resolveScmCloneCredential,+}));+vi.mock('../entitlement', () => ({resolveSandboxStorageClaim: mocks.resolveSandboxStorageClaim,}));@@ -26,10 +34,20 @@ vi.mock('@/database/models/agent', () => ({}),}));+vi.mock('@/database/models/environment', () => ({+ EnvironmentModel: vi.fn(function () {+ return { findById: mocks.findEnvironmentById };+ }),+}));+vi.mock('@/database/models/environmentInstance', () => ({EnvironmentInstanceModel: mocks.EnvironmentInstanceModel,}));+vi.mock('../driveFolder', () => ({+ driveFolderExists: mocks.driveFolderExists,+}));+const { resolveSandboxSessionConfig } = await import('../session');const serverDB = {} as LobeChatDatabase;@@ -56,12 +74,30 @@ describe('resolveSandboxSessionConfig', () => {mocks.TopicModel.mockImplementation(function () {return { findById };});- mocks.EnvironmentInstanceModel.mockImplementation(function () {- return { findById: findInstanceById };+ // A stored instance always names its drive; a fixture that does not say+ // is on the drive this scope resolves to by default.+ mocks.EnvironmentInstanceModel.mockImplementation(function (+ _db: unknown,+ userId: string,+ workspaceId?: string,+ ) {+ const providerScope = workspaceId ? `ws-org-${workspaceId}` : `ws-${userId}`;++ return {+ findById: async (id: string) => {+ const row = await findInstanceById(id);+ return row ? { providerScope, ...row } : row;+ },+ listStorageDirectories: mocks.listStorageDirectories,+ };});+ mocks.driveFolderExists.mockReset();+ mocks.driveFolderExists.mockResolvedValue(true);+ mocks.listStorageDirectories.mockReset();+ mocks.listStorageDirectories.mockResolvedValue([]);resolveSandboxStorageClaim.mockResolvedValue(CLAIM);findById.mockResolvedValue({- metadata: { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'persistent' },+ metadata: { sandboxInstanceId: INSTANCE_ID },});findInstanceById.mockResolvedValue({id: INSTANCE_ID,@@ -75,6 +111,7 @@ describe('resolveSandboxSessionConfig', () => {it('carries the claim, the mode and the chosen instance', async () => {await expect(resolve()).resolves.toEqual({claim: CLAIM,+ drive: 'personal',cwd: 'projects/atlas',environment: INSTANCE_ID,mode: 'persistent',@@ -94,6 +131,7 @@ describe('resolveSandboxSessionConfig', () => {await expect(resolve()).resolves.toEqual({claim: CLAIM,+ drive: 'personal',cwd: 'projects/atlas',environment: INSTANCE_ID,mode: 'persistent',@@ -218,48 +256,230 @@ describe('resolveSandboxSessionConfig', () => {// whatever the request says, so reading the topic buys nothing. Leaving the// chosen instance untouched on the topic is what lets a resubscription resume// exactly where the user left off.- it('does not read the topic when there is no entitlement', async () => {+ it('looks no further than the drive when there is no entitlement', async () => {resolveSandboxStorageClaim.mockResolvedValue(null);+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'reports' } });- await expect(resolve()).resolves.toEqual({ claim: null, mode: 'ephemeral' });- expect(findById).not.toHaveBeenCalled();+ await expect(resolve()).resolves.toEqual({+ claim: null,+ drive: 'personal',+ mode: 'ephemeral',+ });+ expect(mocks.driveFolderExists).not.toHaveBeenCalled();});- // The claim is independent of the mode: the workspace exists whether or not- // THIS topic writes to it, and the file browser reads it from an ephemeral- // topic just as well.- it('keeps the claim on an ephemeral topic but drops the instance', async () => {- for (const metadata of [{}, { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'ephemeral' }]) {+ // The claim is independent of the placement: the drive exists whether or not+ // THIS topic writes to it, and the file browser reads it from a temporary+ // topic just as well. A mode left on an old topic chooses nothing any more.+ it('keeps the claim on a topic that picked nothing', async () => {+ for (const metadata of [{}, { sandboxMode: 'persistent' }]) {findById.mockResolvedValue({ metadata });- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'ephemeral' });+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ mode: 'ephemeral',+ });}+ expect(findInstanceById).not.toHaveBeenCalled();});- // A persistent topic that never chose one runs at the workspace root under- // the default environment, which is a working session โ just not a named one.- it('runs at the workspace root when no instance is chosen', async () => {- findById.mockResolvedValue({ metadata: { sandboxMode: 'persistent' } });+ describe("a workspace member's drives", () => {+ it('issues the claim for the drive the topic picked', async () => {+ findById.mockResolvedValue({+ metadata: { sandboxDrive: 'personal', sandboxWorkingDirectory: 'notes' },+ });++ await expect(resolve({ workspaceId: 'ws1' })).resolves.toEqual({+ claim: CLAIM,+ cwd: 'notes',+ drive: 'personal',+ mode: 'drive',+ });+ expect(resolveSandboxStorageClaim).toHaveBeenCalledWith(+ expect.objectContaining({ drive: 'personal', userId: 'user_1', workspaceId: 'ws1' }),+ );+ });++ it('lets a member work at the root of their personal drive', async () => {+ findById.mockResolvedValue({+ metadata: { sandboxDrive: 'personal', sandboxWorkingDirectory: '.' },+ });- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'persistent' });- expect(findInstanceById).not.toHaveBeenCalled();+ await expect(resolve({ workspaceId: 'ws1' })).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ mode: 'drive',+ });+ });++ it('runs an environment directory on the drive it is on, whatever the topic says', async () => {+ findById.mockResolvedValue({+ metadata: { sandboxDrive: 'public', sandboxInstanceId: INSTANCE_ID },+ });+ findInstanceById.mockResolvedValue({+ id: INSTANCE_ID,+ providerScope: 'ws-mem-ws1-user_1',+ workingDirectory: 'atlas',+ });++ await expect(resolve({ workspaceId: 'ws1' })).resolves.toMatchObject({+ cwd: 'atlas',+ drive: 'personal',+ mode: 'persistent',+ });+ });++ it("refuses an instance on another member's personal drive", async () => {+ findInstanceById.mockResolvedValue({+ id: INSTANCE_ID,+ providerScope: 'ws-mem-ws1-user_2',+ workingDirectory: 'atlas',+ });++ await expect(resolve({ workspaceId: 'ws1' })).resolves.toMatchObject({+ fallback: 'instanceUnavailable',+ mode: 'ephemeral',+ });+ });++ // From before members had drives of their own: hidden on the public drive+ // and not run in, because every member can reach that drive.+ it('asks for a rebuild of a private environment directory left on the public drive', async () => {+ mocks.listStorageDirectories.mockResolvedValue([+ { id: INSTANCE_ID, isPrivate: true, workingDirectory: 'projects/atlas' },+ ]);++ await expect(resolve({ workspaceId: 'ws1' })).resolves.toEqual({+ claim: CLAIM,+ drive: 'public',+ fallback: 'instanceRebuildRequired',+ mode: 'ephemeral',+ });+ });+ });++ describe('a folder on the drive', () => {+ it('runs as a drive in the folder it picked', async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'reports/q3' } });++ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ cwd: 'reports/q3',+ mode: 'drive',+ });+ expect(mocks.driveFolderExists).toHaveBeenCalledWith(+ expect.objectContaining({ claim: CLAIM, path: 'reports/q3' }),+ );+ });++ it('runs at the root of a personal drive, which needs no check', async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: '.' } });++ await expect(resolve()).resolves.toEqual({ claim: CLAIM, drive: 'personal', mode: 'drive' });+ expect(mocks.driveFolderExists).not.toHaveBeenCalled();+ });++ // Every member's folders live under a shared drive's root, and a session+ // there is narrowed to the folder it picked โ the root narrows nothing.+ it("refuses a shared drive's root and says why", async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: '.' } });++ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({+ claim: CLAIM,+ drive: 'public',+ fallback: 'rootNotAllowed',+ mode: 'ephemeral',+ });+ });++ // Deleted since it was picked: recreating it would bring back an empty+ // folder under a name someone chose to remove.+ it('falls back to a temporary sandbox when the folder is gone', async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'projA' } });+ mocks.driveFolderExists.mockResolvedValue(false);++ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({+ claim: CLAIM,+ drive: 'public',+ fallback: 'directoryMissing',+ mode: 'ephemeral',+ });+ });++ // A drive that could not be asked is not a folder that is gone.+ it('keeps the folder when the drive cannot answer', async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'projA' } });+ mocks.driveFolderExists.mockResolvedValue(undefined);++ await expect(resolve()).resolves.toMatchObject({ cwd: 'projA', mode: 'drive' });+ });++ it('works in a folder inside an environment directory like any other folder', async () => {+ // Environments are one-time initializers now: what one initialized is+ // an ordinary folder, and so is everything inside it.+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'atlas/src' } });+ mocks.listStorageDirectories.mockResolvedValue([+ { id: INSTANCE_ID, visible: false, workingDirectory: 'atlas' },+ ]);++ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({+ claim: CLAIM,+ cwd: 'atlas/src',+ drive: 'public',+ mode: 'drive',+ });+ });++ it('refuses a path that would not survive the fence', async () => {+ findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: '../other-user' } });++ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ fallback: 'directoryMissing',+ mode: 'ephemeral',+ });+ });++ it('prefers the instance when a topic somehow carries both', async () => {+ findById.mockResolvedValue({+ metadata: { sandboxInstanceId: INSTANCE_ID, sandboxWorkingDirectory: 'projA' },+ });++ await expect(resolve()).resolves.toMatchObject({+ environment: INSTANCE_ID,+ mode: 'persistent',+ });+ });});// Deleted, or never this member's โ the model answers the same for both.// Failing the call instead would leave the topic unable to run at all until- // someone edited a database row.- it('falls back to the default when the stored instance no longer resolves', async () => {+ // someone edited a database row; the run is temporary and says why.+ it('falls back to a temporary sandbox when the stored instance no longer resolves', async () => {findInstanceById.mockResolvedValue(undefined);- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'persistent' });+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ fallback: 'instanceUnavailable',+ mode: 'ephemeral',+ });});// The whole instance goes, not just the directory. Running its packages at- // the workspace root would put one instance's files under another's- // captured state โ silently, which is the failure worth preventing.+ // the drive root would put one instance's files under another's captured+ // state โ silently, which is the failure worth preventing.it('drops the whole instance when its directory would not survive the fence', async () => {findInstanceById.mockResolvedValue({ id: INSTANCE_ID, workingDirectory: '../other-user' });- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'persistent' });+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ fallback: 'instanceUnavailable',+ mode: 'ephemeral',+ });});// A workspace-public agent runs on its caller's session; a private@@ -271,13 +491,15 @@ describe('resolveSandboxSessionConfig', () => {it('looks the instance up as a public agent inside a workspace', async () => {findById.mockResolvedValue({agentId: 'agent-shared',- metadata: { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'persistent' },+ metadata: { sandboxInstanceId: INSTANCE_ID },});getAgentVisibility.mockResolvedValue('public');findInstanceById.mockResolvedValue(undefined);await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({claim: CLAIM,+ drive: 'public',+ fallback: 'instanceUnavailable',mode: 'ephemeral',});// The topic is read in the workspace's scope; in the personal scope a@@ -292,36 +514,12 @@ describe('resolveSandboxSessionConfig', () => {);});- // A workspace root is shared by every member and holds every instance's- // directory, so no run lands there by falling back โ deleted instance,- // unusable directory or none chosen alike. A personal root is the owner's- // own, which is why the tests above still expect it there.- it('never falls back to the shared root inside a workspace', async () => {- findInstanceById.mockResolvedValue(undefined);- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({- claim: CLAIM,- mode: 'ephemeral',- });-- findInstanceById.mockResolvedValue({ id: INSTANCE_ID, workingDirectory: '../other-user' });- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({- claim: CLAIM,- mode: 'ephemeral',- });-- findById.mockResolvedValue({ metadata: { sandboxMode: 'persistent' } });- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({- claim: CLAIM,- mode: 'ephemeral',- });- });-// Personal agents default to 'public' without meaning it, and every// personal environment is the owner's own โ so no agent read, no narrowing.it('does not narrow by agent visibility in personal mode', async () => {findById.mockResolvedValue({agentId: 'agent-personal',- metadata: { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'persistent' },+ metadata: { sandboxInstanceId: INSTANCE_ID },});await expect(resolve()).resolves.toMatchObject({ environment: INSTANCE_ID });@@ -339,6 +537,7 @@ describe('resolveSandboxSessionConfig', () => {await expect(resolve({ isShareVisitorRun: true })).resolves.toEqual({claim: null,+ drive: 'personal',mode: 'ephemeral',});expect(resolveSandboxStorageClaim).toHaveBeenCalledWith(@@ -351,20 +550,151 @@ describe('resolveSandboxSessionConfig', () => {it('degrades to ephemeral when the topic lookup throws', async () => {findById.mockRejectedValue(new Error('db down'));- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'ephemeral' });+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ mode: 'ephemeral',+ });});it('degrades to ephemeral when the instance lookup throws', async () => {findInstanceById.mockRejectedValue(new Error('db down'));- await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'ephemeral' });+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ drive: 'personal',+ mode: 'ephemeral',+ });});it('needs no topic to resolve the entitlement', async () => {await expect(resolve({ topicId: undefined })).resolves.toEqual({claim: CLAIM,+ drive: 'personal',mode: 'ephemeral',});expect(findById).not.toHaveBeenCalled();});++ describe('initializing from an environment', () => {+ const environment = {+ configuration: {+ bootstrapCommand: 'pnpm install',+ sources: [{ kind: 'git', url: 'https://github.com/octocat/Hello-World' }],+ },+ id: 'env-1',+ name: 'Hello',+ };++ beforeEach(() => {+ mocks.resolveScmCloneCredential.mockReset().mockResolvedValue(null);+ mocks.findEnvironmentById.mockReset().mockResolvedValue(environment);+ });++ it('initializes a folder on the drive from the environment the topic picked', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);+ mocks.driveFolderExists.mockResolvedValue(true);+ findById.mockResolvedValue({+ metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'app' },+ });++ await expect(resolve()).resolves.toMatchObject({+ cwd: 'app',+ initialization: {+ bootstrapCommand: 'pnpm install',+ environmentId: 'env-1',+ sources: [{ url: 'https://github.com/octocat/Hello-World' }],+ },+ mode: 'drive',+ });+ });++ it('carries the clone credential a private repository needs, resolved for this run', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });+ const credential = { header: 'Authorization: Basic eA==', urlPrefix: 'https://github.com/' };+ mocks.resolveScmCloneCredential.mockResolvedValue(credential);++ await expect(resolve()).resolves.toMatchObject({+ initialization: { cloneCredential: credential, environmentId: 'env-1' },+ });+ expect(mocks.resolveScmCloneCredential).toHaveBeenCalledWith(+ expect.objectContaining({ configuration: environment.configuration, userId: 'user_1' }),+ );+ });++ it('initializes without a credential when none is granted, so a public repository still clones', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });++ const config = await resolve();++ expect(config.initialization).toMatchObject({ environmentId: 'env-1' });+ expect(config.initialization).not.toHaveProperty('cloneCredential');+ });++ it('initializes a temporary sandbox too, which has no drive at all', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });++ await expect(resolve()).resolves.toMatchObject({+ initialization: { environmentId: 'env-1' },+ mode: 'ephemeral',+ });+ });++ it("keeps a member's private environment out of a workspace-public agent", async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });+ findById.mockResolvedValue({+ agentId: 'agent-shared',+ metadata: { sandboxEnvironmentId: 'env-1' },+ });+ getAgentVisibility.mockResolvedValue('public');++ const config = await resolve({ workspaceId: 'ws-1' });++ expect(getAgentVisibility).toHaveBeenCalledWith('agent-shared');+ expect(config).not.toHaveProperty('initialization');+ });++ it('applies a published environment for a workspace-public agent', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'public' });+ findById.mockResolvedValue({+ agentId: 'agent-shared',+ metadata: { sandboxEnvironmentId: 'env-1' },+ });+ getAgentVisibility.mockResolvedValue('public');++ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({+ initialization: { environmentId: 'env-1' },+ });+ });++ it('runs without one when the environment is no longer readable', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);+ mocks.findEnvironmentById.mockResolvedValue(undefined);+ findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-gone' } });++ const config = await resolve();++ expect(config.mode).toBe('ephemeral');+ expect(config).not.toHaveProperty('initialization');+ });++ it('never initializes a legacy instance run, which its build already set up', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);+ findInstanceById.mockResolvedValue({ id: INSTANCE_ID, workingDirectory: 'atlas' });+ findById.mockResolvedValue({+ metadata: { sandboxEnvironmentId: 'env-1', sandboxInstanceId: INSTANCE_ID },+ });++ const config = await resolve();++ expect(config.mode).toBe('persistent');+ expect(config).not.toHaveProperty('initialization');+ expect(mocks.findEnvironmentById).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/sandbox/__tests__/storageFiles.test.ts b/apps/server/src/services/sandbox/__tests__/storageFiles.test.tsindex e3ea4d88952..b71a62c043c 100644--- a/apps/server/src/services/sandbox/__tests__/storageFiles.test.ts+++ b/apps/server/src/services/sandbox/__tests__/storageFiles.test.ts@@ -61,6 +61,27 @@ describe('createSandboxStorageClient', () => {expect(JSON.parse(init.body).instanceDir).toBe('app-dev');});+ it('should rename through the storage rename endpoint without overwriting', async () => {+ respond(200, { data: { path: 'archive/q3' } });++ await expect(client.renameFile({ newPath: 'archive/q3', path: 'q3' })).resolves.toEqual({+ path: 'archive/q3',+ });++ const [url, init] = (fetch as any).mock.calls[0];+ expect(url).toBe('http://market.test/api/v1/sandbox/storages/current/rename');+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ newPath: 'archive/q3', path: 'q3' });+ });++ it('should surface a taken destination as a 409', async () => {+ respond(409, { error: 'conflict', error_description: 'Destination exists' });++ const error = await client.renameFile({ newPath: 'b', path: 'a' }).catch((e) => e);++ expect(error.status).toBe(409);+ });+it('should read one environment run history from the control plane', async () => {const page = { nextBefore: null, sessions: [] };respond(200, { data: page });diff --git a/apps/server/src/services/sandbox/__tests__/workspace.test.ts b/apps/server/src/services/sandbox/__tests__/workspace.test.tsindex 032da65751e..446a9f3d566 100644--- a/apps/server/src/services/sandbox/__tests__/workspace.test.ts+++ b/apps/server/src/services/sandbox/__tests__/workspace.test.ts@@ -5,6 +5,7 @@ import {formatSandboxStoragePromptVariables,isSafeSandboxCwd,isSafeSandboxEnvironmentId,+ sandboxDriveOfKey,type SandboxStoragePromptVariables,systemPrompt,} from '@lobechat/builtin-tool-cloud-sandbox';@@ -52,6 +53,42 @@ describe('deriveSandboxStorageKey', () => {it('keeps personal and organization namespaces apart', () => {expect(deriveSandboxStorageKey({ userId: 'u', workspaceId: 'wsp_42' })).toBe('ws-org-wsp_42');expect(deriveSandboxStorageKey({ userId: 'org-wsp_42' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: 'mem-wsp_42-user_a' })).toBeUndefined();+ });++ it('gives each workspace member a personal drive of their own', () => {+ expect(+ deriveSandboxStorageKey({ drive: 'personal', userId: 'user_a', workspaceId: 'wsp_42' }),+ ).toBe('ws-mem-wsp_42-user_a');+ expect(+ deriveSandboxStorageKey({ drive: 'personal', userId: 'user_b', workspaceId: 'wsp_42' }),+ ).toBe('ws-mem-wsp_42-user_b');+ expect(+ deriveSandboxStorageKey({ drive: 'public', userId: 'user_a', workspaceId: 'wsp_42' }),+ ).toBe('ws-org-wsp_42');+ });++ it('ignores the drive outside a workspace', () => {+ expect(deriveSandboxStorageKey({ drive: 'personal', userId: 'user_a' })).toBe('ws-user_a');+ expect(deriveSandboxStorageKey({ drive: 'public', userId: 'user_a' })).toBe('ws-user_a');+ });++ // The first `-` after `ws-mem-` separates the workspace from the member, so+ // a workspace id with a dash could split two ways and name someone else.+ it('refuses a member drive for a workspace id that would not split cleanly', () => {+ expect(+ deriveSandboxStorageKey({ drive: 'personal', userId: 'b', workspaceId: 'wsp-a' }),+ ).toBeUndefined();+ });++ it('names a key as the caller sees it', () => {+ const scope = { userId: 'user_a', workspaceId: 'wsp_42' };++ expect(sandboxDriveOfKey('ws-org-wsp_42', scope)).toBe('public');+ expect(sandboxDriveOfKey('ws-mem-wsp_42-user_a', scope)).toBe('personal');+ expect(sandboxDriveOfKey('ws-mem-wsp_42-user_b', scope)).toBeUndefined();+ expect(sandboxDriveOfKey('ws-user_a', { userId: 'user_a' })).toBe('personal');+ expect(sandboxDriveOfKey('ws-org-wsp_42', { userId: 'user_a' })).toBeUndefined();});});@@ -89,12 +126,12 @@ describe('formatSandboxStoragePromptVariables', () => {);});- it('describes a persistent workspace without naming a directory', () => {- const vars = formatSandboxStoragePromptVariables({ mode: 'persistent' });+ it('describes the drive root without naming a directory', () => {+ const vars = formatSandboxStoragePromptVariables({ mode: 'drive' });const rendered = render(vars);for (const key of placeholders) expect(rendered).not.toContain(key);- expect(vars.sandbox_workspace).toContain('persistent workspace');+ expect(vars.sandbox_workspace).toContain('network drive');// Steers heavy work away from the workspace without naming a scratch// directory: where installs land is the platform's business, and a path// written here would outlive whatever it decides to do with them.@@ -108,14 +145,14 @@ describe('formatSandboxStoragePromptVariables', () => {expect(rendered).not.toContain('Files from previous sessions may not persist');});- it('names the chosen subdirectory and places it under the workspace root', () => {+ it('names the chosen folder and keeps the run in it', () => {const vars = formatSandboxStoragePromptVariables({cwd: 'projects/atlas',- mode: 'persistent',+ mode: 'drive',});expect(vars.sandbox_workspace).toContain('`projects/atlas`');- expect(vars.sandbox_workspace).toContain('workspace root is above you');+ expect(vars.sandbox_workspace).toContain('Keep to this folder');// The generic "pick your own subdirectory" advice is wrong once one is// chosen โ the model is already in it.expect(vars.sandbox_workspace).not.toContain('its own subdirectory');@@ -132,8 +169,10 @@ describe('formatSandboxStoragePromptVariables', () => {// model that wrote one down would keep using it after the root moved.it('never hardcodes a mount path', () => {for (const input of [+ { mode: 'drive' } as const,+ { cwd: 'a/b', mode: 'drive' } as const,{ mode: 'persistent' } as const,- { cwd: 'a/b', mode: 'persistent' } as const,+ { cwd: 'a', mode: 'persistent' } as const,]) {const vars = formatSandboxStoragePromptVariables(input);expect(vars.sandbox_workspace).not.toContain('/mnt/');diff --git a/apps/server/src/services/sandbox/binding.ts b/apps/server/src/services/sandbox/binding.tsnew file mode 100644index 00000000000..6dfd9b147a1--- /dev/null+++ b/apps/server/src/services/sandbox/binding.ts@@ -0,0 +1,21 @@+/**+ * Where a drive's instances live, in the vocabulary `environment_instances`+ * uses for every execution target it supports.+ *+ * The scope is the drive's storage key and the resource is the one persistent+ * volume inside it โ there is exactly one, which is why the resource is named+ * rather than identified. What distinguishes two instances is the directory,+ * and `environment_instances_provider_path_unique` covers that tuple, so the+ * database is what stops two copies landing in one folder.+ */+export const sandboxStorageBinding = (storageKey: string) => ({+ deviceId: null,+ kind: 'sandbox' as const,+ provider: 'market',+ providerResourceId: 'workspace',+ providerScope: storageKey,+});++/** Whether `path` is `directory` itself or somewhere beneath it. */+export const isPathWithin = (path: string, directory: string) =>+ path === directory || path.startsWith(`${directory}/`);diff --git a/apps/server/src/services/sandbox/driveAccess.ts b/apps/server/src/services/sandbox/driveAccess.tsnew file mode 100644index 00000000000..27bb21832ce--- /dev/null+++ b/apps/server/src/services/sandbox/driveAccess.ts@@ -0,0 +1,75 @@+import {+ SANDBOX_DRIVES,+ type SandboxDrive,+ sandboxDriveOfKey,+ type SandboxStorageClaim,+} from '@lobechat/builtin-tool-cloud-sandbox';+import type { LobeChatDatabase } from '@lobechat/database';++import { MarketService } from '@/server/services/market';++import type { resolveSandboxStorageClaim } from './entitlement';++interface DriveAccessInput {+ /** Handed in rather than imported, so a caller's own seam for it is the one used. */+ resolveClaim: typeof resolveSandboxStorageClaim;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * One caller's drives, each claim resolved at most once per request.+ *+ * Personal drives are the caller's own and nobody else's: there is no way to+ * ask this for another member's, which is what keeps one member's personal+ * drive out of every other member's reach โ they would need a claim for its+ * key, and nothing built on this issues one.+ */+export const createDriveAccess = ({+ resolveClaim,+ serverDB,+ userId,+ workspaceId,+}: DriveAccessInput) => {+ const claims = new Map<SandboxDrive, Promise<SandboxStorageClaim | null>>();++ const claim = (drive: SandboxDrive) => {+ const cached = claims.get(drive);+ if (cached) return cached;++ const pending = resolveClaim({+ drive,+ isShareVisitorRun: false,+ serverDB,+ userId,+ workspaceId,+ });+ claims.set(drive, pending);++ return pending;+ };++ return {+ /** The drives this caller has: both in a workspace, the one otherwise. */+ available: (workspaceId ? [...SANDBOX_DRIVES] : ['personal']) as SandboxDrive[],+ claim,+ client: async (drive: SandboxDrive) => {+ const resolved = await claim(drive);++ return resolved+ ? {+ claim: resolved,+ client: new MarketService({+ userInfo: { sandboxStorage: resolved, userId, workspaceId },+ }).getSandboxStorageClient(),+ }+ : undefined;+ },+ /** Which of the caller's drives a storage key is, or `undefined` for none of theirs. */+ driveOf: (key: string | null | undefined) =>+ key ? sandboxDriveOfKey(key, { userId, workspaceId }) : undefined,+ };+};++export type DriveAccess = ReturnType<typeof createDriveAccess>;diff --git a/apps/server/src/services/sandbox/driveFolder.ts b/apps/server/src/services/sandbox/driveFolder.tsnew file mode 100644index 00000000000..e30393d0135--- /dev/null+++ b/apps/server/src/services/sandbox/driveFolder.ts@@ -0,0 +1,98 @@+import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';+import debug from 'debug';++import { MarketService } from '@/server/services/market';++import { SandboxStorageFilesError } from './storageFiles';++const log = debug('lobe-server:sandbox:drive-folder');++/**+ * How long a folder that was there is believed to still be there.+ *+ * A run resolves its placement several times โ the prompt, then every tool+ * call โ and each would otherwise ask the drive again. Only a positive answer+ * is kept, and briefly: a folder someone deletes shows up as gone within this+ * window, while a missing one is asked about every time so it is noticed the+ * moment it comes back.+ */+const EXISTS_TTL_MS = 15_000;++/**+ * The most folders remembered at once. A long-lived server sees every+ * workspace's drives, so the cache sheds the oldest entries rather than grow+ * with them.+ */+const EXISTS_MAX_ENTRIES = 1000;++const existsCache = new Map<string, number>();++/** Drop what has expired, then the oldest beyond the cap โ a Map iterates in insertion order. */+const remember = (cacheKey: string) => {+ const now = Date.now();+ existsCache.delete(cacheKey);+ for (const [key, at] of existsCache) {+ if (now - at >= EXISTS_TTL_MS) existsCache.delete(key);+ }+ while (existsCache.size >= EXISTS_MAX_ENTRIES) {+ const oldest = existsCache.keys().next().value;+ if (oldest === undefined) break;+ existsCache.delete(oldest);+ }+ existsCache.set(cacheKey, now);+};++interface DriveFolderInput {+ claim: SandboxStorageClaim;+ /** Relative to the drive's root. */+ path: string;+ userId: string;+ workspaceId?: string | null;+}++/**+ * Whether a folder a topic picked is still on the drive.+ *+ * `false` only on the drive's own "nothing there" answer. Anything else โ the+ * drive unreachable, a refusal โ is `undefined`, which a caller treats as+ * "keep the choice": a run that cannot ask must not lose its folder over it,+ * and the execution plane fences the path either way.+ */+export const driveFolderExists = async ({+ claim,+ path,+ userId,+ workspaceId,+}: DriveFolderInput): Promise<boolean | undefined> => {+ const cacheKey = `${claim.key}\0${path}`;+ const cachedAt = existsCache.get(cacheKey);+ if (cachedAt !== undefined && Date.now() - cachedAt < EXISTS_TTL_MS) return true;+ if (cachedAt !== undefined) existsCache.delete(cacheKey);++ try {+ await new MarketService({+ userInfo: { sandboxStorage: claim, userId, workspaceId: workspaceId ?? undefined },+ })+ .getSandboxStorageClient()+ .listFiles({ path });+ remember(cacheKey);++ return true;+ } catch (error) {+ existsCache.delete(cacheKey);+ if (error instanceof SandboxStorageFilesError && error.status === 404) return false;++ log('Could not check drive folder %s on %s: %O', path, claim.key, error);+ return undefined;+ }+};++/** For tests: how many folders are remembered. */+export const driveFolderCacheSize = () => existsCache.size;++/** Forget what is known about a drive's folders, after a write that may have moved them. */+export const forgetDriveFolders = (storageKey: string) => {+ for (const key of existsCache.keys()) {+ if (key.startsWith(`${storageKey}\0`)) existsCache.delete(key);+ }+};diff --git a/apps/server/src/services/sandbox/driveUsage.ts b/apps/server/src/services/sandbox/driveUsage.tsnew file mode 100644index 00000000000..6e5977b0d31--- /dev/null+++ b/apps/server/src/services/sandbox/driveUsage.ts@@ -0,0 +1,158 @@+import {+ deriveSandboxStorageKey,+ type SandboxDrive,+ type SandboxStorageClaim,+} from '@lobechat/builtin-tool-cloud-sandbox';+import type { LobeChatDatabase } from '@lobechat/database';+import { and, eq, isNull } from 'drizzle-orm';+import pMap from 'p-map';++import { users, workspaceMembers } from '@/database/schemas';+import { MarketService } from '@/server/services/market';++import type { DriveAccess } from './driveAccess';++/** Roles that may see how much each member's personal drive holds โ never what. */+const USAGE_ADMIN_ROLES = new Set(['admin', 'owner']);++export interface MemberDriveUsage {+ avatar: string | null;+ name: string | null;+ usageBytes: number | null;+ userId: string;+}++interface ReadDriveUsageInput {+ /** The caller's claim for the drive the call named; its quota is the pool's. */+ claim: SandboxStorageClaim;+ drives: DriveAccess;+ role?: string;+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * How much each of the caller's drives holds against the plan's quota.+ *+ * A workspace's public drive and every member's personal drive draw on one+ * pool, so the figure that decides whether a write is refused is their sum โ+ * the execution plane reports it beside each drive's own. An owner or admin is+ * also shown how much each other member's personal drive holds: the amount,+ * which is the workspace's to pay for, and never the contents. The claim used+ * to read a member's figure goes to the storage-info read alone; no listing,+ * read or write is ever made with it.+ */+export const readDriveUsage = async ({+ claim,+ drives: access,+ role,+ serverDB,+ userId,+ workspaceId,+}: ReadDriveUsageInput) => {+ const seesMembers = !!workspaceId && !!role && USAGE_ADMIN_ROLES.has(role);++ // For an owner or admin the public drive's read also lists every drive in+ // the pool, so the members' figures come from that one call.+ const read = async (drive: SandboxDrive) => {+ const resolved = await access.client(drive);+ if (!resolved) return null;++ return resolved.client+ .getStorage({ withDrives: seesMembers && drive === 'public' })+ .catch(() => null);+ };++ const drives = await pMap(+ access.available,+ async (drive) => ({ drive, info: await read(drive) }),+ { concurrency: 5 },+ );+ const reported = drives.find((entry) => entry.info?.workspaceUsageBytes != null)?.info;++ let members: MemberDriveUsage[] | null = null;+ if (workspaceId && seesMembers) {+ const rows = await serverDB+ .select({+ avatar: users.avatar,+ fullName: users.fullName,+ userId: workspaceMembers.userId,+ username: users.username,+ })+ .from(workspaceMembers)+ .innerJoin(users, eq(users.id, workspaceMembers.userId))+ .where(+ and(eq(workspaceMembers.workspaceId, workspaceId), isNull(workspaceMembers.deletedAt)),+ );++ const others = rows.filter((row) => row.userId !== userId);+ const describe = (row: (typeof others)[number], usageBytes: number | null) => ({+ avatar: row.avatar ?? null,+ name: row.fullName || row.username || null,+ usageBytes,+ userId: row.userId,+ });+ const keyOf = (memberId: string) =>+ deriveSandboxStorageKey({ drive: 'personal', userId: memberId, workspaceId });++ const pooled = drives.find((entry) => entry.drive === 'public')?.info?.workspaceDrives;+ if (pooled) {+ // One read answered for the whole pool. A member with no row there has+ // never had a session on their drive, so nothing was ever measured.+ const usageByKey = new Map(pooled.map((entry) => [entry.storageKey, entry.usageBytes]));+ members = others.map((row) => {+ const key = keyOf(row.userId);+ return describe(row, key ? (usageByKey.get(key) ?? null) : null);+ });+ } else {+ // An execution plane that cannot list the pool: one read per member,+ // bounded, since a workspace can be large.+ members = await pMap(+ others,+ async (row) => {+ const key = keyOf(row.userId);+ const info = key+ ? await new MarketService({+ userInfo: {+ sandboxStorage: { key, quotaBytes: claim.quotaBytes },+ userId,+ workspaceId,+ },+ })+ .getSandboxStorageClient()+ .getStorage()+ .catch(() => null)+ : null;++ return describe(row, info?.usageBytes ?? null);+ },+ { concurrency: 5 },+ );+ }+ }++ const measured = [+ ...drives.map((entry) => entry.info?.usageBytes),+ ...(members ?? []).map((member) => member.usageBytes),+ ].filter((value): value is number => typeof value === 'number');++ return {+ drives: drives.map(({ drive, info }) => ({+ drive,+ usageBytes: info?.usageBytes ?? null,+ usageCheckedAt: info?.usageCheckedAt ?? null,+ })),+ members,+ /** Whether the plan lets writes go past the quota, billed as overage. */+ overageAllowed: claim.overageAllowed === true,+ quotaBytes: claim.quotaBytes,+ /**+ * The pool's total as the execution plane judges it, or โ when it has not+ * said โ what this caller can add up from the drives it can see.+ */+ totalUsageBytes:+ reported?.workspaceUsageBytes ??+ (measured.length > 0 ? measured.reduce((sum, value) => sum + value, 0) : null),+ };+};diff --git a/apps/server/src/services/sandbox/entitlement.ts b/apps/server/src/services/sandbox/entitlement.tsindex fda4b409dc6..825e7a327bf 100644--- a/apps/server/src/services/sandbox/entitlement.ts+++ b/apps/server/src/services/sandbox/entitlement.ts@@ -47,6 +47,7 @@ export interface SandboxStorageClaimInput extends SandboxStorageScope {* what every session does today.*/export const resolveSandboxStorageClaim = async ({+ drive,isShareVisitorRun,serverDB,userId,@@ -54,7 +55,11 @@ export const resolveSandboxStorageClaim = async ({}: SandboxStorageClaimInput): Promise<SandboxStorageClaim | null> => {if (isShareVisitorRun) return null;- const key = deriveSandboxStorageKey({ userId, workspaceId });+ // The drive picks the key and nothing else: a workspace's public drive and+ // every member's personal drive draw on the workspace plan's one pool, so+ // each is issued the whole pool as its soft quota and the execution plane+ // judges the workspace on their sum.+ const key = deriveSandboxStorageKey({ drive, userId, workspaceId });if (!key) return null;try {diff --git a/apps/server/src/services/sandbox/environmentInit.ts b/apps/server/src/services/sandbox/environmentInit.tsnew file mode 100644index 00000000000..9797f187398--- /dev/null+++ b/apps/server/src/services/sandbox/environmentInit.ts@@ -0,0 +1,193 @@+import type { EnvironmentConfiguration } from '@lobechat/types';++/** Long enough for a shallow clone and a dependency install. */+export const SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS = 600_000;++/**+ * Where a sandbox records the folders it initialized: under its home, never in+ * the folder โ the folder holds only what the repository and setup put there.+ */+export const SANDBOX_ENVIRONMENT_STATE_DIR = '.lobe/environments';++/** Printed first by a run that did something, so a no-op is told apart without parsing. */+export const SANDBOX_ENVIRONMENT_RAN_LINE = '__lobe_environment_ran';++/**+ * What a working directory is initialized from: an environment's repository+ * and setup, and nothing else of it. Nothing is tracked once it has run, in+ * the database or in the folder.+ */+export interface SandboxInitialization {+ bootstrapCommand?: string;+ /**+ * A header git sends for one URL prefix, so a private repository clones: a+ * short-lived, repository-scoped token from the GitHub App installation, as+ * a build used to get. Resolved per run and never stored.+ */+ cloneCredential?: { header: string; urlPrefix: string };+ env?: Record<string, string>;+ environmentId: string;+ name: string;+ sources: { path?: string; ref?: string; url: string }[];+}++const shellQuote = (value: string): string => `'${value.replaceAll("'", String.raw`'\''`)}'`;++const ENV_NAME = /^[A-Z_]\w*$/i;++/**+ * The initialization an environment asks for, or `undefined` when it asks for+ * nothing โ no repository and no setup โ so picking an empty definition runs+ * nothing.+ *+ * Only git sources: a `files` source belongs to the release before folders on+ * the drive replaced it, and has no meaning in a folder that already is one.+ */+export const toSandboxInitialization = (environment: {+ configuration?: EnvironmentConfiguration | null;+ id: string;+ name: string;+}): SandboxInitialization | undefined => {+ const configuration = environment.configuration ?? {};+ const sources = (configuration.sources ?? []).flatMap((source) =>+ source.kind === 'git' && source.url+ ? [+ {+ url: source.url,+ ...(source.ref && { ref: source.ref }),+ ...(source.path && { path: source.path }),+ },+ ]+ : [],+ );+ const bootstrapCommand = configuration.bootstrapCommand?.trim() || undefined;+ if (sources.length === 0 && !bootstrapCommand) return undefined;++ return {+ environmentId: environment.id,+ name: environment.name,+ sources,+ ...(bootstrapCommand && { bootstrapCommand }),+ ...(configuration.env &&+ Object.keys(configuration.env).length > 0 && { env: configuration.env }),+ };+};++/** A destination inside the working directory, or `undefined` for a path that would leave it. */+const safeDestination = (path: string | undefined): string | undefined => {+ const value = (path ?? '.').trim() || '.';+ if (value.startsWith('/') || value.split('/').includes('..')) return undefined;++ return value;+};++/**+ * One idempotent shell command that applies an environment to the current+ * directory: clone each repository, then run setup.+ *+ * Nothing is written into the folder to say it was initialized. An empty+ * folder is initialized; a folder that holds anything is left alone, silently:+ * either an earlier run filled it, or it holds someone's work that a clone+ * would mix with and setup does not expect.+ *+ * Each run is also recorded in the sandbox itself, outside the folder, keyed+ * by the folder and the environment: a setup that installs globally writes+ * nothing into the folder, and without the record it would rerun on every+ * tool call, as each one starts a fresh service. A failed run is recorded too,+ * so it is not retried on every call either. The record goes with the+ * sandbox โ and so do global installs โ so a new sandbox initializes again.+ *+ * The variables are exported in a subshell, so they reach clone and setup and+ * not the commands the conversation runs afterwards.+ */+export const buildSandboxEnvironmentInitCommand = (init: SandboxInitialization): string => {+ const label = shellQuote(init.name);++ const exports = Object.entries(init.env ?? {})+ .filter(([key]) => ENV_NAME.test(key))+ .map(([key, value]) => `export ${key}=${shellQuote(value)}`);++ const clones = init.sources.map((source, index) => {+ const destination = safeDestination(source.path);+ if (!destination)+ return `echo ${shellQuote(`Skipped a repository with an unusable path: ${source.path}`)}`;++ const branch = source.ref ? ` --branch ${shellQuote(source.ref)}` : '';+ const url = shellQuote(source.url);+ // Cloned beside the directory and copied in, so a second repository can+ // land in a sub-path of a directory the first one already filled; the+ // checkout's own `.git` comes along.+ const staging = `"$__lobe_tmp/${index}"`;++ return [+ `git clone --depth 1${branch} ${url} ${staging}`,+ `mkdir -p ${shellQuote(destination)}`,+ `cp -a ${staging}/. ${shellQuote(destination)}/`,+ ].join(' && ');+ });++ // 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.+ const credential =+ init.cloneCredential && 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)}`,+ ],+ unset: [`unset GIT_CONFIG_COUNT GIT_CONFIG_KEY_0 GIT_CONFIG_VALUE_0`],+ }+ : { set: [], unset: [] };++ // Only when there is something to clone, and removed however the subshell+ // ends: a second copy of every repository would otherwise stay in the+ // sandbox, one more for each failed attempt.+ const staging =+ clones.length > 0 ? [`__lobe_tmp="$(mktemp -d)"`, `trap 'rm -rf "$__lobe_tmp"' EXIT`] : [];++ const steps = [+ ...exports,+ ...staging,+ ...credential.set,+ ...clones,+ ...credential.unset,+ ...(init.bootstrapCommand ? [init.bootstrapCommand] : []),+ ];++ // Joined with `&&` inside one subshell, so the first failure stops what+ // follows and its status is the subshell's.+ const body = `( set -e; ${steps.join(' && ')} )`;++ const record = `"\${HOME:-/tmp}/${SANDBOX_ENVIRONMENT_STATE_DIR}"`;+ const key = `"$(printf '%s|%s' "$PWD" ${shellQuote(init.environmentId)} | cksum | cut -d ' ' -f 1)"`;++ return [+ `__lobe_state=${record}/${key}`,+ `if [ ! -e "$__lobe_state" ] && [ -z "$(ls -A . 2>/dev/null)" ]; then`,+ ` echo ${SANDBOX_ENVIRONMENT_RAN_LINE}`,+ ` mkdir -p ${record}`,+ ` if ${body}; then`,+ ` echo done > "$__lobe_state"`,+ ` echo "Initialized from the environment "${label}"."`,+ ` else`,+ ` __lobe_status=$?`,+ ` echo failed > "$__lobe_state"`,+ ` echo "Initializing from the environment "${label}" failed (exit $__lobe_status)."`,+ ` fi`,+ `fi`,+ ].join('\n');+};++/** Whether the command's output says it ran, rather than finding the folder initialized. */+export const environmentInitRan = (stdout: string | undefined): boolean =>+ !!stdout && stdout.split('\n').some((line) => line.trim() === SANDBOX_ENVIRONMENT_RAN_LINE);++/** The run's own output, without the line that only says it ran. */+export const environmentInitReport = (stdout: string | undefined): string =>+ (stdout ?? '')+ .split('\n')+ .filter((line) => line.trim() !== SANDBOX_ENVIRONMENT_RAN_LINE)+ .join('\n')+ .trim();diff --git a/apps/server/src/services/sandbox/index.ts b/apps/server/src/services/sandbox/index.tsindex 77e380aaedf..3952bb7254e 100644--- a/apps/server/src/services/sandbox/index.ts+++ b/apps/server/src/services/sandbox/index.ts@@ -1,9 +1,15 @@+export { isPathWithin, sandboxStorageBinding } from './binding';+export type { DriveAccess } from './driveAccess';+export { createDriveAccess } from './driveAccess';+export { driveFolderExists, forgetDriveFolders } from './driveFolder';+export type { MemberDriveUsage } from './driveUsage';+export { readDriveUsage } from './driveUsage';export { resolveSandboxStorageClaim } from './entitlement';export { createSandboxService, getSandboxProviderKind } from './factory';export { MarketSandboxProvider, ServerSandboxService } from './providers/market';export { OnlyboxesSandboxProvider } from './providers/onlyboxes';export { normalizeSandboxCommandResult, SandboxMiddlewareService } from './service';-export type { SandboxSessionConfig } from './session';+export type { SandboxPlacementFallback, SandboxSessionConfig } from './session';export { resolveSandboxSessionConfig } from './session';export type {SandboxFileExporter,diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.tsindex cc4f270da13..fc04a97b146 100644--- a/apps/server/src/services/sandbox/providers/market.test.ts+++ b/apps/server/src/services/sandbox/providers/market.test.ts@@ -203,6 +203,14 @@ describe('MarketSandboxProvider', () => {});});+ it("redacts the clone credential an environment's initializer exports for git", () => {+ const params = {+ command: "export GIT_CONFIG_VALUE_0='Authorization: Basic c2VjcmV0' && git clone x",+ };++ expect(redactSandboxParams(params).command).not.toContain('c2VjcmV0');+ });+it('fully redacts a command that writes into ~/.creds/env, regardless of the credential names it carries', () => {const params = {command:diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex 7d3e028e7f2..739091e7a02 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -1,4 +1,4 @@-import type { SandboxCallToolResult } from '@lobechat/builtin-tool-cloud-sandbox';+import type { SandboxCallToolResult, SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import type { CodeInterpreterToolName } from '@lobehub/market-sdk';import debug from 'debug';@@ -16,7 +16,10 @@ import type {const log = debug('lobe-server:sandbox:market');const REDACTED_SANDBOX_PARAM = '[redacted]';-const SANDBOX_AUTH_ENV_PATTERN = /\b(LOBEHUB_JWT|GITHUB_TOKEN)=("[^"]*"|'[^']*'|\S+)/g;+// `GIT_CONFIG_VALUE_<n>` carries the clone credential an environment's+// initializer exports for git; see `buildSandboxEnvironmentInitCommand`.+const SANDBOX_AUTH_ENV_PATTERN =+ /\b(LOBEHUB_JWT|GITHUB_TOKEN|GIT_CONFIG_VALUE_\d+)=("[^"]*"|'[^']*'|\S+)/g;/*** Any command that writes into `~/.creds/env` (the path documented to the* model as where `injectCredsToSandbox` places credentials) carries@@ -89,7 +92,11 @@ export class MarketSandboxProvider implements SandboxProvider {// the request body itself, so naming them costs nothing on the wire.sandboxCwd,sandboxInstanceId,- sandboxMode,+ // Widened for `drive` alone, which the market accepts from the+ // release that added it while the published SDK still types the+ // pair it shipped with. Remove the cast with the SDK bump; the field+ // itself stays named, so it is still checked.+ sandboxMode: sandboxMode as Exclude<SandboxMode, 'drive'> | undefined,// The SDK types this one loosely (`Record<string, unknown>`) while// ours is a named shape, so only this field is widened โ the rest// stay checked, which is the point of dropping the blanket cast.diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.tsindex 8ba29a47349..8d5a88d93a1 100644--- a/apps/server/src/services/sandbox/service.ts+++ b/apps/server/src/services/sandbox/service.ts@@ -13,6 +13,12 @@ import {SANDBOX_INIT_TIMEOUT_MS,type SandboxInitDownload,} from './bootstrap';+import {+ buildSandboxEnvironmentInitCommand,+ environmentInitRan,+ environmentInitReport,+ SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS,+} from './environmentInit';import type {SandboxCommandResult,SandboxProvider,@@ -28,6 +34,9 @@ export class SandboxMiddlewareService implements SandboxService {readonly capabilities: SandboxProviderCapabilities;readonly kind: SandboxProviderKind;+ private environmentInitialized = false;+ /** What applying the environment said, until a shell result carries it. */+ private pendingEnvironmentReport: string | undefined;private filesInitialized = false;constructor(@@ -42,8 +51,66 @@ export class SandboxMiddlewareService implements SandboxService {toolName: string,params: Record<string, unknown>,): Promise<SandboxCallToolResult> {+ const report = await this.ensureEnvironmentInitialized();+ if (report) this.pendingEnvironmentReport = report;await this.ensureFilesInitialized();- return this.provider.callTool(toolName, params);+ const result = await this.provider.callTool(toolName, params);++ // Held until a shell result can carry it: a first call that lists or+ // reads files has no output to put it in, and dropping it would hide a+ // failed setup from the rest of the conversation.+ const pending = this.pendingEnvironmentReport;+ if (!pending || !SHELL_TOOLS.has(toolName)) return result;+ this.pendingEnvironmentReport = undefined;++ return withEnvironmentReport(toolName, result, pending);+ }++ /**+ * Apply the topic's environment to the working directory the first time this+ * service instance is used: clone its repository and run its setup there.+ *+ * The command itself decides whether to run: only an empty directory is+ * initialized, so a temporary sandbox is initialized each time it starts+ * empty and a folder on the drive once. Best-effort: a failure is reported,+ * never thrown, and the tool call it precedes still runs.+ *+ * Returns what the run printed when it did something, for the next shell+ * result to carry; nothing when the directory was already initialized.+ */+ private async ensureEnvironmentInitialized(): Promise<string | undefined> {+ if (this.environmentInitialized) return;+ this.environmentInitialized = true;++ const init = this.options.sandboxInitialization;+ if (!init || !this.provider.capabilities.shell) return;++ try {+ const result = await this.provider.callTool('runCommand', {+ command: buildSandboxEnvironmentInitCommand(init),+ timeout: SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS,+ });+ const stdout = (result.result as { stdout?: string } | null | undefined)?.stdout;+ // The command always exits cleanly, so a failed call that printed+ // nothing never reached the sandbox: said so, not passed off as a+ // folder that was already initialized.+ if (!environmentInitRan(stdout)) {+ return result.success ? undefined : environmentInitUnreachable(init.name);+ }++ log(+ 'Environment %s applied for topic %s: success=%s',+ init.environmentId,+ this.options.topicId,+ result.success,+ );++ return environmentInitReport(stdout) || undefined;+ } catch (error) {+ log('Environment init failed for topic %s: %O', this.options.topicId, error);++ return environmentInitUnreachable(init.name);+ }}/**@@ -230,3 +297,34 @@ export const normalizeSandboxCommandResult = (success,};};++const SHELL_TOOLS = new Set(['execScript', 'runCommand']);++/**+ * What the conversation is told when the initializer could not be run at all+ * โ the sandbox did not answer โ so a command that follows in an empty folder+ * is not mistaken for one in the checkout. Nothing was recorded, so the next+ * call tries again.+ */+const environmentInitUnreachable = (name: string) =>+ `The environment "${name}" could not be applied: the sandbox did not respond. It will be tried again on the next command.`;++/**+ * The first shell result after an environment was applied, with what applying+ * it said in front โ so the conversation sees why its directory now holds a+ * checkout, or why it does not. Other tools' results are left as they are:+ * they have no output to put it in.+ */+const withEnvironmentReport = (+ toolName: string,+ result: SandboxCallToolResult,+ report: string,+): SandboxCallToolResult => {+ const payload = result.result as { stdout?: string } | null | undefined;+ if (!SHELL_TOOLS.has(toolName) || !payload || typeof payload !== 'object') return result;++ return {+ ...result,+ result: { ...payload, stdout: `[environment] ${report}\n\n${payload.stdout ?? ''}` },+ };+};diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.tsindex 8e143fb38ff..508a56af772 100644--- a/apps/server/src/services/sandbox/session.ts+++ b/apps/server/src/services/sandbox/session.ts@@ -1,8 +1,12 @@import {+ DEFAULT_SANDBOX_DRIVE,DEFAULT_SANDBOX_MODE,isSafeSandboxCwd,isSafeSandboxEnvironmentId,+ SANDBOX_DRIVE_ROOT,SANDBOX_LOCAL_WORK_ROOT,+ type SandboxDrive,+ sandboxDriveOfKey,type SandboxMode,type SandboxStorageClaim,} from '@lobechat/builtin-tool-cloud-sandbox';@@ -11,14 +15,22 @@ import type { EnvironmentConfiguration } 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 { sandboxStorageBinding } from './binding';+import { driveFolderExists } from './driveFolder';import { resolveSandboxStorageClaim } from './entitlement';+import { type SandboxInitialization, toSandboxInitialization } from './environmentInit';import type { SandboxSessionSpecification } from './types';const log = debug('lobe-server:sandbox:session');+export type SandboxPlacementFallback =+ 'directoryMissing' | 'instanceRebuildRequired' | 'instanceUnavailable' | 'rootNotAllowed';+export interface SandboxSessionConfig {/*** The signed entitlement, or `null` when this run gets no persistent@@ -28,10 +40,16 @@ export interface SandboxSessionConfig {*/claim: SandboxStorageClaim | null;/**- * Chosen subdirectory of the workspace, relative to its root. Only ever set- * on a run that is actually persistent.+ * The folder the run works in, relative to the drive's root: the chosen+ * folder of a `drive` run, or an instance's directory. Absent on a drive run+ * at the root, and on every ephemeral one.*/cwd?: string;+ /**+ * Which of the workspace's drives {@link claim} names; always `personal` in+ * a personal account, which has only the one.+ */+ drive: SandboxDrive;/*** Snapshot to restore, or `undefined` for the caller's default. This is the* INSTANCE's id, not the environment's: what was installed belongs to one@@ -43,6 +61,29 @@ export interface SandboxSessionConfig {* to agree or the snapshot at the end is refused.*/environment?: string;+ /**+ * Why a placement the topic chose was not honoured, when the run fell back+ * to a temporary sandbox because of it. Set only on that fallback, so the+ * composer can say what happened instead of quietly running somewhere the+ * person did not pick:+ *+ * - `directoryMissing` โ the folder is no longer on the drive;+ * - `instanceUnavailable` โ the environment directory was deleted, is not+ * this member's to use, or the folder sits inside one;+ * - `instanceRebuildRequired` โ a private environment's directory left on+ * the workspace's public drive from before members had drives of their+ * own; it stays hidden there, and the environment has to be initialized+ * again on the owner's personal drive;+ * - `rootNotAllowed` โ the public drive's root, which every member's+ * folders live under, is not a folder anyone may work in.+ */+ fallback?: SandboxPlacementFallback;+ /**+ * The environment to initialize the working directory from, when the topic+ * picked one: applied once to a folder on the drive, and once per sandbox in+ * a temporary one. Never set on a legacy instance run โ its build did this.+ */+ initialization?: SandboxInitialization;mode: SandboxMode;/*** What the instance was built from, for the execution plane to act on while@@ -132,141 +173,301 @@ interface SandboxSessionConfigInput {/*** Everything the sandbox layer needs to know about persistence for one run,* resolved once: the entitlement that goes on the trust token, and the topic's- * own preferences that go on each request.+ * own placement that goes on each request. One of three:+ *+ * - **instance** (`persistent`) โ the topic is bound to an environment+ * directory: its folder plus the packages its build installed;+ * - **drive** โ the topic picked a folder on the drive (or its root, in a+ * personal account): the folder persists, nothing else does;+ * - **temporary** (`ephemeral`) โ nothing picked, or a pick that can no+ * longer be honoured, which then says why in `fallback`.*- * The topic is only consulted when an entitlement exists. Without one the- * execution plane routes to the ephemeral sandbox whatever the request says, so- * reading the preferences would buy nothing but a query โ and deliberately- * leaving the chosen instance untouched on the topic is what lets a lapsed- * subscription pick up exactly where it left off.+ * The topic is read first because it names the drive, and the drive names the+ * claim's key: a workspace has a public drive and one personal drive per+ * member, and a run is issued a claim for exactly one of them. Without an+ * entitlement the execution plane routes to the ephemeral sandbox whatever the+ * request says, and the placement is left untouched on the topic โ which is+ * what lets a lapsed subscription pick up exactly where it left off.** Never throws; a failed lookup degrades to the ephemeral sandbox every session* uses today.*/-export const resolveSandboxSessionConfig = async ({+const resolvePlacement = async ({isShareVisitorRun,serverDB,topicId,userId,workspaceId,}: SandboxSessionConfigInput): Promise<SandboxSessionConfig> => {- if (!serverDB) return { claim: null, mode: DEFAULT_SANDBOX_MODE };+ // A personal account has one drive, its own; a workspace run starts on the+ // public one until the topic says otherwise.+ const defaultDrive: SandboxDrive = workspaceId ? DEFAULT_SANDBOX_DRIVE : 'personal';+ if (!serverDB) return { claim: null, drive: defaultDrive, mode: DEFAULT_SANDBOX_MODE };- const claim = await resolveSandboxStorageClaim({- isShareVisitorRun,- serverDB,- userId,- workspaceId,- });+ // One claim per drive, and each is resolved at most once: the topic decides+ // which drive the run addresses, and a run only ever addresses one.+ const claimFor = (drive: SandboxDrive) =>+ resolveSandboxStorageClaim({ drive, isShareVisitorRun, serverDB, userId, workspaceId });- if (!claim || !topicId) {+ if (!topicId) {+ const claim = await claimFor(defaultDrive);log(- 'Ephemeral for topic %s: claim=%s topicId=%s userId=%s workspaceId=%s',- topicId,+ 'Ephemeral without a topic: claim=%s userId=%s workspaceId=%s',!!claim,- !!topicId,userId,workspaceId,);- return { claim, mode: DEFAULT_SANDBOX_MODE };+ return { claim, drive: defaultDrive, mode: DEFAULT_SANDBOX_MODE };}+ let drive = defaultDrive;+ let claim: SandboxStorageClaim | null = null;+ const fallBack = (fallback: SandboxPlacementFallback): SandboxSessionConfig => ({+ claim,+ drive,+ fallback,+ mode: DEFAULT_SANDBOX_MODE,+ });+try {// Scoped to the workspace the run is in: without it the model reads the// personal scope (`workspace_id IS NULL`), a workspace topic never- // resolves, and every workspace run silently loses its instance.+ // resolves, and every workspace run silently loses its placement.const topic = await new TopicModel(serverDB, userId, workspaceId ?? undefined).findById(topicId,);- if (topic?.metadata?.sandboxMode !== 'persistent') {+ const instanceId = topic?.metadata?.sandboxInstanceId;+ const folder = topic?.metadata?.sandboxWorkingDirectory;+ if (workspaceId && topic?.metadata?.sandboxDrive === 'personal') drive = 'personal';++ if (instanceId) {+ // A workspace-public agent runs on its caller's session, and a private+ // environment's captured state can hold that caller's credentials โ so+ // a shared agent reads published environments only. Personal mode has+ // no such boundary: its agents default to 'public' without meaning it.+ const callerAgentVisibility =+ workspaceId && topic.agentId+ ? await new AgentModel(serverDB, userId, workspaceId).getAgentVisibility(topic.agentId)+ : null;++ const instance = await new EnvironmentInstanceModel(+ serverDB,+ userId,+ workspaceId ?? undefined,+ callerAgentVisibility,+ ).findById(instanceId);++ // The instance lives on one drive and the run goes there, whatever the+ // topic's drive field says: the directory and its snapshot are on that+ // drive's volume and nowhere else. A drive that is not the caller's โ+ // another member's personal one โ is not a drive the caller can be+ // issued a claim for.+ const instanceDrive = instance+ ? sandboxDriveOfKey(instance.providerScope ?? '', { userId, workspaceId })+ : undefined;+ if (instanceDrive) drive = instanceDrive;+ claim = await claimFor(drive);+ if (!claim) return { claim, drive, mode: DEFAULT_SANDBOX_MODE };++ // Deleted, never this member's, or private under a public agent. Any+ // way, the conversation still runs โ in a temporary sandbox, and the+ // composer names why โ rather than not at all until someone edits a+ // database row.+ if (!instance || !instanceDrive) {+ log(+ 'Ignoring unresolvable sandboxInstanceId on topic %s: %o (agentId=%o visibility=%o scope user=%s workspace=%s)',+ topicId,+ instanceId,+ topic.agentId,+ callerAgentVisibility,+ userId,+ workspaceId,+ );++ return fallBack('instanceUnavailable');+ }++ // A private environment's directory on the public drive predates+ // personal drives. Its home directory can hold its owner's credentials,+ // and every member can reach the public drive, so it is not run in โ+ // the owner initializes the environment again on their personal drive.+ if (instanceDrive === 'public' && workspaceId) {+ const directories = await new EnvironmentInstanceModel(+ serverDB,+ userId,+ workspaceId,+ ).listStorageDirectories(sandboxStorageBinding(claim.key));+ if (directories.some((entry) => entry.id === instance.id && entry.isPrivate)) {+ log('Private instance %s on the public drive needs a rebuild', instance.id);+ return fallBack('instanceRebuildRequired');+ }+ }++ // The directory and the snapshot are one choice, so a bad half discards+ // the whole instance rather than half of it. Running the instance's+ // packages at the drive root would put one instance's files under+ // another's captured state, which is the exact mixing separate instances+ // exist to prevent โ and it would do it silently.+ const { id, workingDirectory } = instance;+ if (!isSafeSandboxCwd(workingDirectory) || !isSafeSandboxEnvironmentId(id)) {+ log('Ignoring unusable instance %s on topic %s: %o', id, topicId, workingDirectory);+ return fallBack('instanceUnavailable');+ }+log(- 'Ephemeral for topic %s: found=%s mode=%o instance=%o (scope user=%s workspace=%s)',+ 'Persistent for topic %s: instance=%s cwd=%o drive=%s',topicId,- !!topic,- topic?.metadata?.sandboxMode,- topic?.metadata?.sandboxInstanceId,- userId,- workspaceId,+ id,+ workingDirectory,+ drive,);- return { claim, mode: DEFAULT_SANDBOX_MODE };+ const specification = toSessionSpecification(instance.configurationSnapshot);++ return {+ claim,+ cwd: workingDirectory,+ drive,+ environment: id,+ mode: 'persistent',+ ...(specification && { specification }),+ ...(hasLocalCheckout(instance) && { workingDir: SANDBOX_LOCAL_WORK_ROOT }),+ };}- // Where a persistent run goes when it has no usable instance. In a- // personal account that is the account's own root. In a workspace the root- // is shared by every member and holds every instance's directory โ private- // ones included โ so a run with nothing it may use there gets a temporary- // directory instead, and the composer says so.- const fallback: SandboxSessionConfig = workspaceId- ? { claim, mode: DEFAULT_SANDBOX_MODE }- : { claim, mode: 'persistent' };+ // The topic is only consulted when an entitlement exists. Without one the+ // execution plane routes to the ephemeral sandbox whatever the request+ // says, and leaving the choice untouched on the topic is what lets a+ // lapsed subscription pick up exactly where it left off.+ claim = await claimFor(drive);+ if (!claim) {+ log('Ephemeral for topic %s: no claim for drive %s', topicId, drive);+ return { claim, drive, mode: DEFAULT_SANDBOX_MODE };+ }++ if (folder === undefined) {+ log('Ephemeral for topic %s: no folder picked', topicId);+ return { claim, drive, mode: DEFAULT_SANDBOX_MODE };+ }++ if (folder === SANDBOX_DRIVE_ROOT) {+ // A personal drive is its owner's alone, so its root is a folder like+ // any other. The public one holds every member's folders, and a session+ // there is narrowed to the one it picked โ the root narrows nothing.+ if (workspaceId && drive === 'public') return fallBack('rootNotAllowed');- const instanceId = topic.metadata.sandboxInstanceId;- if (!instanceId) {- log('Falling back for topic %s: persistent with no instance bound', topicId);+ log('Drive for topic %s at the root of %s', topicId, claim.key);+ return { claim, drive, mode: 'drive' };+ }++ if (!isSafeSandboxCwd(folder)) return fallBack('directoryMissing');- return fallback;+ // Deleted since it was picked โ by this member in another tab, or by a+ // colleague on the public drive. Recreating it silently would bring back+ // an empty folder under a name someone chose to remove.+ if ((await driveFolderExists({ claim, path: folder, userId, workspaceId })) === false) {+ log('Folder %o on topic %s is no longer on the drive', folder, topicId);+ return fallBack('directoryMissing');}- // A workspace-public agent runs on its caller's session, and a private- // environment's captured state can hold that caller's credentials โ so a- // shared agent reads published environments only. Personal mode has no- // such boundary: its agents default to 'public' without meaning it.- const callerAgentVisibility =- workspaceId && topic.agentId- ? await new AgentModel(serverDB, userId, workspaceId).getAgentVisibility(topic.agentId)- : null;-- // Deleted, never this member's, or private under a public agent. Any way,- // the conversation still runs, in the fallback above โ the alternative is- // a topic that cannot run at all until someone edits a database row. The- // composer names the private case.- const instance = await new EnvironmentInstanceModel(+ log('Drive for topic %s: cwd=%o drive=%s', topicId, folder, drive);+ return { claim, cwd: folder, drive, mode: 'drive' };+ } catch (error) {+ log('Failed to read sandbox preferences for topic %s: %O', topicId, error);+ return { claim: claim ?? (await claimFor(drive)), drive, mode: DEFAULT_SANDBOX_MODE };+ }+};++/**+ * The topic's environment as an initialization, or `undefined` when it picked+ * none, picked one the caller cannot read (deleted, or another member's+ * private one), or one that asks for nothing.+ */+const resolveInitialization = async ({+ serverDB,+ topicId,+ userId,+ workspaceId,+}: Required<Pick<SandboxSessionConfigInput, 'serverDB' | 'topicId'>> &+ Pick<SandboxSessionConfigInput, 'userId' | 'workspaceId'>): Promise<+ SandboxInitialization | undefined+> => {+ try {+ const topic = await new TopicModel(serverDB, userId, workspaceId ?? undefined).findById(+ topicId,+ );+ const environmentId = topic?.metadata?.sandboxEnvironmentId;+ if (!environmentId) return undefined;++ const environment = await new EnvironmentModel(serverDB,userId,workspaceId ?? undefined,- callerAgentVisibility,- ).findById(instanceId);- if (!instance) {- log(- 'Ignoring unresolvable sandboxInstanceId on topic %s: %o (agentId=%o visibility=%o scope user=%s workspace=%s)',- topicId,- instanceId,- topic.agentId,- callerAgentVisibility,- userId,- workspaceId,- );-- return fallback;+ ).findById(environmentId);+ if (!environment) {+ log('Ignoring unreadable sandboxEnvironmentId on topic %s: %s', topicId, environmentId);+ return undefined;}- // The directory and the snapshot are one choice, so a bad half discards the- // whole instance rather than half of it. Running the instance's packages at- // the workspace root would put one instance's files under another's- // captured state, which is the exact mixing separate instances exist to- // prevent โ and it would do it silently.- const { id, workingDirectory } = instance;- if (!isSafeSandboxCwd(workingDirectory) || !isSafeSandboxEnvironmentId(id)) {- log('Ignoring unusable instance %s on topic %s: %o', id, topicId, workingDirectory);- return fallback;+ // The same boundary legacy instances keep: a workspace-public agent runs+ // on its caller's session, and a private environment's variables, setup+ // and checkout are that caller's โ so a shared agent applies published+ // environments only.+ if (workspaceId && topic.agentId && environment.visibility !== 'public') {+ const agentVisibility = await new AgentModel(+ serverDB,+ userId,+ workspaceId,+ ).getAgentVisibility(topic.agentId);+ if (agentVisibility === 'public') {+ log(+ 'Not applying private environment %s for shared agent %s',+ environmentId,+ topic.agentId,+ );+ return undefined;+ }}- log('Persistent for topic %s: instance=%s cwd=%o', topicId, id, workingDirectory);+ const initialization = toSandboxInitialization(environment);+ if (!initialization || initialization.sources.length === 0) return initialization;- const specification = toSessionSpecification(instance.configurationSnapshot);+ // 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({+ configuration: environment.configuration ?? undefined,+ db: serverDB,+ userId,+ workspaceId,+ });- return {- claim,- cwd: workingDirectory,- environment: id,- mode: 'persistent',- ...(specification && { specification }),- ...(hasLocalCheckout(instance) && { workingDir: SANDBOX_LOCAL_WORK_ROOT }),- };+ return cloneCredential ? { ...initialization, cloneCredential } : initialization;} catch (error) {- log('Failed to read sandbox preferences for topic %s: %O', topicId, error);- return { claim, mode: DEFAULT_SANDBOX_MODE };+ log('Failed to read the environment for topic %s: %O', topicId, error);+ return undefined;}};++/**+ * Everything the sandbox layer needs to know about one run: where it works+ * ({@link resolvePlacement}) and, when the topic picked an environment, what+ * that working directory is initialized from. The environment is independent+ * of the placement โ a temporary sandbox is initialized as readily as a folder+ * โ except on a legacy instance run, which already has what its build made.+ *+ * Never throws; a failed lookup degrades to the ephemeral sandbox every session+ * uses today, without an environment.+ */+export const resolveSandboxSessionConfig = async (+ input: SandboxSessionConfigInput,+): Promise<SandboxSessionConfig> => {+ const config = await resolvePlacement(input);+ const { serverDB, topicId } = input;+ if (!serverDB || !topicId || config.mode === 'persistent') return config;++ const initialization = await resolveInitialization({ ...input, serverDB, topicId });++ return initialization ? { ...config, initialization } : config;+};diff --git a/apps/server/src/services/sandbox/storageFiles.ts b/apps/server/src/services/sandbox/storageFiles.tsindex b714998ad01..5eb3d712a49 100644--- a/apps/server/src/services/sandbox/storageFiles.ts+++ b/apps/server/src/services/sandbox/storageFiles.ts@@ -17,6 +17,8 @@ const log = debug('lobe-server:sandbox:workspace-files');*/export interface SandboxStorageFileEntry {isDirectory: boolean;+ /** A directory that is the top of a git checkout; absent where it is not. */+ isGitRepository?: boolean;modifiedAt?: string;name: string;/** Relative to the workspace root. */@@ -34,6 +36,11 @@ export interface SandboxStorageFileList {export interface SandboxStorageInfo {dir: string;key: string;+ /**+ * `public` or `member` for a workspace's drives, `personal` for an+ * account's own. Absent from an execution plane that predates member drives.+ */+ kind?: 'member' | 'personal' | 'public';lastActiveAt: string | null;/*** Outcome of the most recent environment snapshot. Snapshots happen when a@@ -46,6 +53,17 @@ export interface SandboxStorageInfo {status: 'active' | 'archived';usageBytes: number | null;usageCheckedAt: string | null;+ /**+ * Every drive in that pool with its stored figure, when the read asked for+ * them (`withDrives`). Absent from an execution plane that predates it.+ */+ workspaceDrives?: { storageKey: string; usageBytes: number | null }[];+ /**+ * A workspace drive's pool: its public drive plus every member's personal+ * one, which is the figure the quota is judged on. Absent for a personal+ * account's drive.+ */+ workspaceUsageBytes?: number | null;}/**@@ -264,8 +282,31 @@ export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageCreturn request(`${CURRENT_STORAGE}/file?${query.toString()}`, { method: 'DELETE' });},- getStorage: async (params: RequestContext = {}): Promise<SandboxStorageInfo> => {+ /**+ * Rename or move a file or folder. Never overwrites: an existing+ * destination is refused with 409, and the drive's root cannot be renamed.+ */+ renameFile: async (+ params: RequestContext & { newPath: string; path: string },+ ): Promise<{ path: string }> =>+ request(`${CURRENT_STORAGE}/rename`, {+ body: JSON.stringify({+ newPath: params.newPath,+ path: params.path,+ topicId: params.topicId,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ }),++ getStorage: async (+ params: RequestContext & {+ /** Also list every drive in a workspace pool with its figure, in this one read. */+ withDrives?: boolean;+ } = {},+ ): Promise<SandboxStorageInfo> => {const query = withTopic(new URLSearchParams(), params);+ if (params.withDrives) query.set('drives', 'true');const suffix = query.size > 0 ? `?${query.toString()}` : '';return request(`${CURRENT_STORAGE}${suffix}`);diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.tsindex 2d7c07f8cd7..e8270a280c9 100644--- a/apps/server/src/services/sandbox/types.ts+++ b/apps/server/src/services/sandbox/types.ts@@ -8,6 +8,8 @@ import type { LobeChatDatabase } from '@lobechat/database';import type { FileService } from '@/server/services/file';import type { MarketService } from '@/server/services/market';+import type { SandboxInitialization } from './environmentInit';+export type SandboxProviderKind = 'market' | 'onlyboxes';/**@@ -40,9 +42,17 @@ export interface SandboxSessionContext {* Working directory inside the persistent workspace, relative to its root.* Forwarded with every call; the execution plane composes it onto the* directory the entitlement names and fences the result. Only meaningful- * alongside `sandboxMode: 'persistent'`.+ * alongside a persistent `sandboxMode` โ a drive folder, or an instance's+ * directory; a drive without one works at the drive's root.*/sandboxCwd?: string;+ /**+ * The environment to initialize the working directory from before the first+ * call โ clone and setup, guarded by a marker the run leaves behind. Absent+ * when the topic picked none, and on a legacy instance run, whose build+ * already did this.+ */+ sandboxInitialization?: SandboxInitialization;/*** Named environment to restore for this run; absent means the caller's* default. Like `sandboxMode`, every call for a topic must carry the same@@ -50,8 +60,9 @@ export interface SandboxSessionContext {*/sandboxInstanceId?: string;/**- * Whether this run wants its working directory to survive the session.- * Absent means ephemeral. Half the decision โ the execution plane also+ * Whether this run wants its working directory to survive the session, and+ * how: `drive` keeps the folder only, `persistent` an instance with its+ * installed packages. Absent means ephemeral. Half the decision โ the execution plane also* requires an entitlement on the trust token, which is minted upstream of* this service.*/diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex 70fb51c6a81..0beafd9d536 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -162,6 +162,7 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {fileService,marketService,sandboxCwd: sandbox.cwd,+ sandboxInitialization: sandbox.initialization,sandboxInstanceId: sandbox.environment,sandboxSpecification: sandbox.specification,sandboxWorkingDir: sandbox.workingDir,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex 34f6d83d6f7..97d577a53ca 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -44,6 +44,7 @@ import {resolveSandboxSessionConfig,type SandboxSessionSpecification,} from '@/server/services/sandbox';+import type { SandboxInitialization } from '@/server/services/sandbox/environmentInit';import { SkillResourceService } from '@/server/services/skill/resource';import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';import {@@ -159,6 +160,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {private userId: string;private workspaceId?: string;private sandboxCwd?: string;+ private sandboxInitialization?: SandboxInitialization;private sandboxWorkingDir?: string;private sandboxInstanceId?: string;private sandboxMode?: SandboxMode;@@ -197,6 +199,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {* CLIs, injected credentials and anything outside the workspace with it.*/sandboxCwd?: string;+ sandboxInitialization?: SandboxInitialization;sandboxInstanceId?: string;sandboxMode?: SandboxMode;sandboxSpecification?: SandboxSessionSpecification;@@ -221,6 +224,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {this.userId = options.userId;this.workspaceId = options.workspaceId;this.sandboxCwd = options.sandboxCwd;+ this.sandboxInitialization = options.sandboxInitialization;this.sandboxWorkingDir = options.sandboxWorkingDir;this.sandboxInstanceId = options.sandboxInstanceId;this.sandboxMode = options.sandboxMode;@@ -360,6 +364,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {fileService: this.fileService,marketService: this.marketService,sandboxCwd: this.sandboxCwd,+ sandboxInitialization: this.sandboxInitialization,sandboxInstanceId: this.sandboxInstanceId,sandboxMode: this.sandboxMode,sandboxSpecification: this.sandboxSpecification,@@ -718,6 +723,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {fileService: this.fileService,marketService: this.marketService,sandboxCwd: this.sandboxCwd,+ sandboxInitialization: this.sandboxInitialization,sandboxInstanceId: this.sandboxInstanceId,sandboxMode: this.sandboxMode,sandboxSpecification: this.sandboxSpecification,@@ -781,6 +787,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {fileService: this.fileService,marketService: this.marketService,sandboxCwd: this.sandboxCwd,+ sandboxInitialization: this.sandboxInitialization,sandboxInstanceId: this.sandboxInstanceId,sandboxMode: this.sandboxMode,sandboxSpecification: this.sandboxSpecification,@@ -957,6 +964,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {operationId: context.operationId,resourceService,sandboxCwd: sandbox.cwd,+ sandboxInitialization: sandbox.initialization,sandboxInstanceId: sandbox.environment,sandboxMode: sandbox.mode,sandboxSpecification: sandbox.specification,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b30cc2a82a5..7e8e92948b7 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2011,6 +2011,37 @@"runtimeEnv.mode.noneDesc": "Disable runtime environment","runtimeEnv.selectMode": "Select Runtime Environment","runtimeEnv.title": "Runtime Environment",+ "sandboxDrive.browse": "Choose a folder on your driveโฆ",+ "sandboxDrive.browseDesc": "Files in it are kept across conversations",+ "sandboxDrive.browseOther": "Choose another folderโฆ",+ "sandboxDrive.building": "{{name}} ยท building",+ "sandboxDrive.environmentBuildingDesc": "Environment directory ยท building, usable once it finishes",+ "sandboxDrive.environmentDesc": "Environment directory ยท installed packages are kept too",+ "sandboxDrive.fallback.directoryMissing": "This folder no longer exists on the drive. Runs use a temporary sandbox until you pick another folder.",+ "sandboxDrive.fallback.instanceRebuildRequired": "This private environment directory is still on the public drive and needs to be rebuilt on your personal drive. This run will use a temporary sandbox.",+ "sandboxDrive.fallback.instanceUnavailable": "This environment directory canโt be used here any more. Runs use a temporary sandbox until you pick another one.",+ "sandboxDrive.fallback.rootNotAllowed": "The public driveโs root cannot be a working folder. This run will use a temporary sandbox; pick a folder.",+ "sandboxDrive.fallbackChip.directoryMissing": "Folder no longer exists",+ "sandboxDrive.fallbackChip.instanceRebuildRequired": "Rebuild on personal drive",+ "sandboxDrive.fallbackChip.instanceUnavailable": "Environment unavailable",+ "sandboxDrive.fallbackChip.rootNotAllowed": "Pick a folder",+ "sandboxDrive.folderDesc": "Folder on your drive ยท {{path}}",+ "sandboxDrive.folderOnDriveDesc": "{{drive}} ยท {{path}}",+ "sandboxDrive.manageEnvironments": "Environments",+ "sandboxDrive.pickerInfoTooltip": "Pick a folder on your drive and its files are kept across conversations. Without one, the sandbox is temporary.",+ "sandboxDrive.pickerTitle": "Working directory",+ "sandboxDrive.root": "Drive root",+ "sandboxDrive.upsell": "Keep files on a drive",+ "sandboxEnvironment.empty": "No environments yet. Create one in Environments.",+ "sandboxEnvironment.hint": "Cloned and set up once in the working directory before the first command. A folder that already has files is left as it is.",+ "sandboxEnvironment.loadFailed": "Couldn't load environments",+ "sandboxEnvironment.loading": "Loading environmentโฆ",+ "sandboxEnvironment.missing": "Environment unavailable",+ "sandboxEnvironment.none": "No environment",+ "sandboxEnvironment.noneDesc": "Start from an empty working directory",+ "sandboxEnvironment.retry": "Retry",+ "sandboxEnvironment.saveFailed": "Could not change the environment. Try again.",+ "sandboxEnvironment.title": "Environment","sandboxStorage.allCopiesBusy": "Every copy is in use","sandboxStorage.buildFailed": "Not built","sandboxStorage.building": "Building",diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex e443acd1329..c866db65b08 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -565,7 +565,7 @@"visibilityConfirm.makePrivate.itemLibrary": "It stays in the library you filed it in โ other members just stop seeing it there","visibilityConfirm.makePrivate.itemLoaded": "Content others have already loaded canโt be pulled back","visibilityConfirm.makePrivate.itemReferences": "Existing message attachments and references will show as unavailable",- "visibilityConfirm.publish.itemCapturedState": "Members can run its copies and reach everything it has captured โ files, CLI logins, your signed-in identity",+ "visibilityConfirm.publish.itemCapturedState": "Copies made before environments became one-time setups keep what they captured โ files, CLI logins, your signed-in identity โ and members can reach them","visibilityConfirm.publish.itemLoaded": "After switching back, content others have already loaded canโt be pulled back","visibilityConfirm.publish.itemReversible": "You can switch it back to private later from the same menu","visibilityConfirm.publish.itemVisible": "All workspace members will see this immediately",diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex 0af01c39f0e..e7a373fbb35 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -42,7 +42,42 @@"workingDirectory.detachedWorktree": "detached","workingDirectory.diffLineStatTooltip": "Added lines {{added}} ยท Deleted lines {{deleted}} ยท Changed files {{files}}","workingDirectory.diffStatTooltip": "Added {{added}} ยท Modified {{modified}} ยท Deleted {{deleted}}",+ "workingDirectory.drive.actionFailed": "That didnโt work. Try again.",+ "workingDirectory.drive.browseDescription": "Choose a folder on your drive.",+ "workingDirectory.drive.buildingDesc": "This environment directory is still building. It can be picked once the build finishes",+ "workingDirectory.drive.createCopy": "Create copy",+ "workingDirectory.drive.delete": "Delete",+ "workingDirectory.drive.deleteConfirmContent": "Everything in this folder is deleted from the drive, for everyone who can see it. Conversations working in it fall back to a temporary sandbox.",+ "workingDirectory.drive.deleteConfirmTitle": "Delete โ{{name}}โ?",+ "workingDirectory.drive.drives.personal": "Personal drive",+ "workingDirectory.drive.drives.public": "Public drive",+ "workingDirectory.drive.environmentBadge": "Environment",+ "workingDirectory.drive.folderNotEmpty": "This folder already has files in it. Only a new or empty folder can be initialized from an environment.",+ "workingDirectory.drive.folderTaken": "An environment directory with this name already exists.",+ "workingDirectory.drive.foldersLoadFailed": "Could not load this folder on your drive. Retry, or go back to the driveโs top level.",+ "workingDirectory.drive.gitRepository": "Git",+ "workingDirectory.drive.inUseDesc": "Another conversation is using this environment directory",+ "workingDirectory.drive.initializeHint": "The folder is created at the drive root and set up from this environment: the repository is cloned and its setup runs.",+ "workingDirectory.drive.initializeWith": "Initialize with",+ "workingDirectory.drive.moreActions": "More actions",+ "workingDirectory.drive.pickFailed": "Could not switch to this folder. Try again.",+ "workingDirectory.drive.pickFolderFirst": "Choose a folder first",+ "workingDirectory.drive.privateBlocked": "Private environment โ a shared agent canโt use it",+ "workingDirectory.drive.readOnly": "Environment directories are read-only here.",+ "workingDirectory.drive.rebuildInPersonal": "Private environment folders ({{names}}) are hidden here. Their owners can rebuild them on their personal drives.",+ "workingDirectory.drive.rename": "Rename",+ "workingDirectory.drive.renameFailed": "The folder couldnโt be renamed",+ "workingDirectory.drive.renameTitle": "Rename folder",+ "workingDirectory.drive.rootNotAllowed": "The driveโs root canโt be a working folder",+ "workingDirectory.drive.state.building": "Building",+ "workingDirectory.drive.state.failed": "Build failed",+ "workingDirectory.drive.state.inUse": "In use",+ "workingDirectory.drive.title": "Choose a folder on your drive","workingDirectory.enterPathManually": "Enter path manually",+ "workingDirectory.environment.label": "Code environment",+ "workingDirectory.environment.none": "No environment",+ "workingDirectory.errorDetailHide": "Hide details",+ "workingDirectory.errorDetailShow": "Show details","workingDirectory.filesAdded": "Added","workingDirectory.filesDeleted": "Deleted","workingDirectory.filesEmpty": "No uncommitted changes",@@ -118,6 +153,7 @@"workingDirectory.undo": "Undo","workingDirectory.unselected": "Not selected","workingDirectory.useFolder": "Use this folder",+ "workingDirectory.useFolderFailed": "Couldnโt use this folder.","workingDirectory.worktreeSearchPlaceholder": "Search worktrees","workingDirectory.worktreeUnavailable": "unavailable","workingDirectory.worktreesEmpty": "No worktrees found",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 89dd46a1b09..ec474902099 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -565,11 +565,73 @@"devices.visibilityTabs.private": "Private","devices.visibilityTabs.workspace": "Workspace","devices.workingDirectory": "Working dir: {{path}}",+ "drive.explorer.columns.kind": "Kind",+ "drive.explorer.columns.modified": "Date modified",+ "drive.explorer.columns.name": "Name",+ "drive.explorer.columns.size": "Size",+ "drive.explorer.delete": "Delete",+ "drive.explorer.deleteFileContent": "The file is removed from the drive.",+ "drive.explorer.deleteFolderContent": "The folder and everything in it are removed from the drive. Conversations working in it switch to a temporary sandbox.",+ "drive.explorer.deleteTitle": "Delete โ{{name}}โ?",+ "drive.explorer.empty": "This folder is empty",+ "drive.explorer.emptyRoot.personal": "Your drive is empty. Create a folder, then pick it as a conversationโs working folder.",+ "drive.explorer.emptyRoot.public": "No folders on the public drive yet. Create one to work in it with your team.",+ "drive.explorer.kind.file": "File",+ "drive.explorer.kind.fileWithExtension": "{{extension}} file",+ "drive.explorer.kind.folder": "Folder",+ "drive.explorer.kind.gitRepository": "Git repository",+ "drive.explorer.loadFailed": "Could not load this folder.",+ "drive.explorer.moreActions": "More actions",+ "drive.explorer.newFolder": "New folder",+ "drive.explorer.readOnly": "Environment directories are read-only",+ "drive.explorer.readOnlyHint": "Only its own sandbox sessions write to an environment directory, so you can browse it here but not change it.",+ "drive.explorer.rename": "Rename",+ "drive.loadFailed": "Could not load storage. Check your connection and try again.",+ "drive.retained.delete": "Delete",+ "drive.retained.deleteConfirm.desc": "Everything on it is deleted and cannot be recovered.",+ "drive.retained.deleteConfirm.title": "Delete {{name}}'s personal drive?",+ "drive.retained.deleted": "Drive deleted",+ "drive.retained.expiresIn": "Deleted in {{count}} days",+ "drive.retained.expiresToday": "Deleted today",+ "drive.retained.hint": "Kept for 30 days after a member leaves, then deleted automatically. They count toward the workspace pool until then. Only the amount is shown, never the files.",+ "drive.retained.lastError": "Last attempt failed: {{error}}",+ "drive.retained.move": "Move to public drive",+ "drive.retained.moveConfirm.desc": "Its files are moved into departed-members on the public drive, where every member can open them, and the personal drive is emptied. Only text files up to 1 MB can be moved; a drive holding anything else is left untouched.",+ "drive.retained.moveConfirm.title": "Move {{name}}'s drive to the public drive?",+ "drive.retained.moved": "Moved to {{path}} on the public drive",+ "drive.retained.title": "Departed members' personal drives",+ "drive.scope.personal": "Only you",+ "drive.scope.public": "Visible to all members",+ "drive.tabs.personal": "Personal drive",+ "drive.tabs.public": "Public drive",+ "drive.usage.enableOverage": "Turn on pay-as-you-go",+ "drive.usage.manage": "Manage in Storage",+ "drive.usage.memberUnmeasured": "Not measured",+ "drive.usage.membersHint": "Usage only โ contents stay private",+ "drive.usage.membersTitle": "Members' personal drives",+ "drive.usage.others": "Other members",+ "drive.usage.over": "Storage is over quota. Free up space or upgrade before more files can be saved.",+ "drive.usage.overBilled": "Over the quota. Files keep saving, and the extra is billed as pay-as-you-go overage.",+ "drive.usage.overBy": "{{size}} over the quota",+ "drive.usage.overageAskAdmin": "Ask a workspace admin to turn on pay-as-you-go to keep saving.",+ "drive.usage.overageModalTitle": "Keep saving past the quota",+ "drive.usage.poolTitle": "Workspace storage pool",+ "drive.usage.refresh": "Measure again",+ "drive.usage.remaining": "{{size}} left ยท {{percent}}% used",+ "drive.usage.showAllMembers": "Show all {{count}} members",+ "drive.usage.showFewerMembers": "Show fewer",+ "drive.usage.title": "Storage usage",+ "drive.usage.unmeasured": "Not measured yet ยท {{total}} in total",+ "drive.usage.unmeasuredShort": "Not measured yet",+ "drive.usage.used": "{{used}} of {{total}} used","environments.cancel": "Cancel","environments.create": "New environment","environments.createFailed": "Could not create the environment",- "environments.desc": "What a sandbox run needs around it: a repository, its setup, its variables. Each copy built from one keeps its own files between sessions.",+ "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.noRepository": "No repository",+ "environments.detail.noSetup": "No setup command","environments.detail.tabs.overview": "Overview","environments.detail.tabs.settings": "Settings","environments.duplicateName": "You already have an environment with this name",@@ -579,9 +641,13 @@"environments.files.binary": "Not a text file, so it cannot be shown here.","environments.files.browse": "Browse files","environments.files.empty": "This directory is empty",+ "environments.files.folderNotEmpty": "This folder already has files in it. Only a new or empty folder can be initialized from an environment.",+ "environments.files.folderTaken": "An environment directory with this name already exists.","environments.files.invalidPath": "The name has to stay inside this copy's directory","environments.files.listFailed": "This directory could not be listed",+ "environments.files.notFound": "That folder doesnโt exist.","environments.files.openHint": "Double-click a folder to open it, or a file to view it",+ "environments.files.readOnly": "Environment directories are read-only: only their own sessions write to them.","environments.files.readOnlyHint": "Read-only: kept in sync by the sandbox. Dependencies such as node_modules are not shown.","environments.files.truncated": "Only the first entries are shown","environments.files.unreadable": "This file could not be read",@@ -590,11 +656,12 @@"environments.form.addEnv": "New variable","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.bootstrapHint": "Runs once in the checkout, with network access, before the conversation starts.","environments.form.changeRepository": "Change repository",- "environments.form.desc": "What a copy is built from โ where the code comes from and what makes it usable.",+ "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",@@ -604,7 +671,7 @@"environments.form.envCount_other": "{{count}} variables","environments.form.envEmpty": "No variables yet","environments.form.envEmptyHint": "Add one, or paste a whole .env file in the",- "environments.form.envHint": "Non-secret values only โ these are stored as plain text and copied into every copy of this environment.",+ "environments.form.envHint": "Non-secret values only โ stored as plain text and exported while the repository is cloned and the setup command runs.","environments.form.exclude": "Regenerable paths","environments.form.excludeHint": "One per line, relative to the copy. Listing a path says it can be rebuilt, so it is kept apart from your work and may be discarded to reclaim space. Anything named here that cannot be rebuilt is work you can lose.","environments.form.filesDesc": "What this folder is called and what it holds for the agent.",@@ -628,7 +695,7 @@"environments.form.saved": "Saved","environments.form.setup": "Setup","environments.form.sources": "Source code",- "environments.form.sourcesHint": "Cloned over HTTPS before anything else runs. Private repositories are not supported yet โ a specification holds no credentials.",+ "environments.form.sourcesHint": "Cloned over HTTPS before anything else runs. A private repository clones through the GitHub App installation that grants it; the environment itself stores no credentials.","environments.github.connect": "Connect GitHub","environments.github.label": "Repository","environments.github.loadFailed": "Could not load GitHub repositories. Try again.",@@ -643,6 +710,7 @@"environments.github.repositoryPlaceholder": "Search repositories","environments.github.reviewAccess": "Review access","environments.hasInstances": "Remove its other copies first",+ "environments.inProject": "A project still uses this environment โ remove it from the project first","environments.instances.add": "New copy","environments.instances.build": "Build","environments.instances.buildConfirmTitle": "Build copy {{name}}?",@@ -662,7 +730,7 @@"environments.instances.create": "New copy","environments.instances.createFailed": "Could not create the copy","environments.instances.defaultUndeletable": "This is the environment's default copy and can't be deleted on its own โ rebuild it, or delete the environment",- "environments.instances.desc": "A copy is a working copy of this environment, with its own folder and its own installed packages. Conversations run inside a copy, and several can run side by side without touching each other.",+ "environments.instances.desc": "Folders on your drive initialized from this environment. Each keeps its own files and installed packages, so conversations in different folders never overwrite each other.","environments.instances.directoryHint": "Folder path. Cannot be changed once created.","environments.instances.directoryLabel": "Directory","environments.instances.directoryLocked": "The folder cannot be changed after the copy is built โ delete it and create another to move it.",@@ -673,12 +741,25 @@"environments.instances.hideLog": "Hide log","environments.instances.inUse": "A conversation is using this copy โ try again once that run ends","environments.instances.namePlaceholder": "Copy name",+ "environments.instances.needsDrive": "Copies are folders on a drive, and this account has no drive yet.","environments.instances.notBuilt": "Not built yet โ nothing has been cloned or installed","environments.instances.occupancyUnavailable": "Could not read which copies are running right now",+ "environments.instances.openDriveSettings": "Go to Storage settings","environments.instances.overlappingDirectory": "This folder is inside another copy's folder, or contains one",+ "environments.instances.publishPublic": "Initialize on the public drive",+ "environments.instances.publishPublicDesc": "Published to the workspace, but its folders are on your personal drive, where members cannot reach them. Members can run it once it has a folder on the public drive.",+ "environments.instances.publishPublicFailed": "Could not create a copy on the public drive",+ "environments.instances.publishPublicStarted": "Building a copy on the public drive","environments.instances.rebuild": "Rebuild","environments.instances.rebuildConfirmContent": "This clears the copy's folder, then clones the code again and runs the setup script. Everything in it now โ changes made in conversations, installed packages, reports, data โ will be lost. This cannot be undone.","environments.instances.rebuildConfirmTitle": "Rebuild copy {{name}}?",+ "environments.instances.rebuildPersonal": "Rebuild on personal drive",+ "environments.instances.rebuildPersonalDesc": "{{names}} is still on the public drive and is hidden. Private environments now keep their folders on your personal drive.",+ "environments.instances.rebuildPersonalFailed": "Could not create the copy on your personal drive",+ "environments.instances.rebuildPersonalRequired": "This directory is on the public drive. Rebuild it on your personal drive first.",+ "environments.instances.rebuildPersonalStarted": "Building a new copy on your personal drive",+ "environments.instances.rebuildPersonalTag": "Needs rebuild on personal drive",+ "environments.instances.rebuildPersonalTagHint": "Hidden on the public drive and no longer used.","environments.instances.remove": "Delete copy","environments.instances.removeConfirmContent": "Its folder and everything it kept โ installed packages, reports, data โ will be deleted. This cannot be undone.","environments.instances.removeConfirmTitle": "Delete copy {{name}}?",@@ -723,7 +804,7 @@"environments.namePlaceholder": "Environment name","environments.refresh": "Refresh","environments.remove": "Delete environment",- "environments.removeConfirmContent": "Its specification, variables, its copy's folder and the saved snapshot go with it, and cannot be recovered.",+ "environments.removeConfirmContent": "Its specification and variables are deleted and cannot be recovered. Folders it initialized keep their files; copies built by an earlier version are removed with it.","environments.removeConfirmTitle": "Delete environment {{name}}?","environments.removeFailed": "Could not delete this environment","environments.saveFailed": "Could not save this change",@@ -757,23 +838,23 @@"environments.storage.over": "Over the storage limit. Saving a file is refused until you delete something.","environments.storage.unmeasured": "Storage not measured yet ยท {{total}} available","environments.storage.used": "{{used}} of {{total}}",- "environments.unavailable.desc": "Environments describe a persistent cloud workspace, and this deployment does not provide one.",- "environments.unavailable.title": "Persistent sandbox is not available here",- "environments.upgrade.benefits.environments.desc": "Repositories, setup command and variables live in the environment; every sandbox built from it starts ready.",- "environments.upgrade.benefits.environments.title": "Sandbox setup written once",- "environments.upgrade.benefits.instances.desc": "Parallel conversations each run in their own copy of the environment, so nothing overwrites anything else.",- "environments.upgrade.benefits.instances.title": "One copy per task",- "environments.upgrade.benefits.persist.desc": "The working directory is kept when the sandbox is recycled; the next run continues where the last stopped.",+ "environments.unavailable.desc": "Drives are persistent cloud storage for sandbox runs, and this deployment does not provide them.",+ "environments.unavailable.title": "Drive storage is not available here",+ "environments.upgrade.benefits.environments.desc": "In a workspace every member shares the public drive, and each member also has a personal drive only they can reach.",+ "environments.upgrade.benefits.environments.title": "A public drive and your own",+ "environments.upgrade.benefits.instances.desc": "When creating a folder, pick a code environment to clone its repository and install what it needs.",+ "environments.upgrade.benefits.instances.title": "Folders initialized from code environments",+ "environments.upgrade.benefits.persist.desc": "The folder is kept when the sandbox is recycled; the next run continues where the last one stopped.","environments.upgrade.benefits.persist.title": "Files survive the sandbox","environments.upgrade.cta": "Upgrade to Pro",- "environments.upgrade.desc": "Give cloud-sandbox runs a persistent working directory. An environment describes what the sandbox needs โ repositories, setup, variables โ and its copies keep everything between sessions.",- "environments.upgrade.title": "Upgrade to Pro to unlock sandbox environments",+ "environments.upgrade.desc": "Give cloud-sandbox runs a drive that outlives them: conversations working in a drive folder keep their files after the sandbox is recycled.",+ "environments.upgrade.title": "Upgrade to Pro to unlock drive storage","environments.visibility.changeFailed": "Could not change this environment's visibility","environments.visibility.createPublishedConfirmTitle": "Create this environment in the workspace?","environments.visibility.publicTag": "Published","environments.visibility.publish": "Publish to Workspace","environments.visibility.publishConfirmTitle": "Publish this environment to the workspace?",- "environments.visibility.readonlyHint": "Published to this workspace by its creator: you can run in this environment, but only they can change what it builds.",+ "environments.visibility.readonlyHint": "Published to this workspace by its creator: you can initialize with this environment, but only they can change it.","environments.visibility.tabs.private": "Private","environments.visibility.tabs.workspace": "Workspace","group.aiConfig": "Agent",@@ -1785,6 +1866,7 @@"tab.connector": "Connectors","tab.creds": "Credentials","tab.devices": "Devices",+ "tab.drive": "Storage","tab.environments": "Environments","tab.experiment": "Experiment","tab.hotkey": "Hotkeys",@@ -3004,6 +3086,7 @@"workspace.invitePage.declineSubtitle": "You can close this window.","workspace.invitePage.declineTitle": "Invitation Declined","workspace.invitePage.differentEmailNotice": "You are signed in as {{currentEmail}}, but this invitation was sent to {{inviteEmail}}.",+ "workspace.invitePage.driveCleanupInProgress": "Your previous personal drive in this workspace is being cleaned up. Try again in a few minutes.","workspace.invitePage.expiredSubtitle": "This invitation has expired. Ask the team owner to send a new one.","workspace.invitePage.expiredTitle": "Invitation Expired","workspace.invitePage.expiresLabel": "Expires",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex b44cc98949d..c89a182aea7 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -693,5 +693,6 @@"usage.remaining": "Remaining","usage.storage.embeddings.used": "Vector Storage","usage.storage.file.used": "File Usage",+ "usage.storage.sandboxStorage.pool": "Sandbox drives (workspace pool)","usage.storage.sandboxStorage.used": "Sandbox Storage"}diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 56327e428e6..69d9ccc7e54 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2011,6 +2011,37 @@"runtimeEnv.mode.noneDesc": "็ฆ็จ่ฟ่กๆถ็ฏๅข","runtimeEnv.selectMode": "้ๆฉ่ฟ่ก็ฏๅข","runtimeEnv.title": "่ฟ่ก็ฏๅข",+ "sandboxDrive.browse": "้ๆฉ็ฝ็ๆไปถๅคนโฆ",+ "sandboxDrive.browseDesc": "ๅ ถไธญ็ๆไปถไผ่ทจไผ่ฏไฟ็",+ "sandboxDrive.browseOther": "้ๆฉๅ ถไปๆไปถๅคนโฆ",+ "sandboxDrive.building": "{{name}} ยท ๆๅปบไธญ",+ "sandboxDrive.environmentBuildingDesc": "็ฏๅข็ฎๅฝ ยท ๆญฃๅจๆๅปบ๏ผๅฎๆๅๅณๅฏไฝฟ็จ",+ "sandboxDrive.environmentDesc": "็ฏๅข็ฎๅฝ ยท ๅทฒๅฎ่ฃ ็ไพ่ตไนไผไฟ็",+ "sandboxDrive.fallback.directoryMissing": "่ฏฅๆไปถๅคนๅทฒไธๅญๅจ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฐ้ๆฉๆไปถๅคนใ",+ "sandboxDrive.fallback.instanceRebuildRequired": "่ฟไธช็งๆ็ฏๅข็ฎๅฝ่ฟๅจๅ ฌๅ ฑ็ฝ็ไธญ๏ผ้่ฆๅจไธชไบบ็ฝ็้ๅปบๅๆ่ฝไฝฟ็จ๏ผๆฌๆฌก่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑใ",+ "sandboxDrive.fallback.instanceUnavailable": "่ฏฅ็ฏๅข็ฎๅฝๅทฒไธๅฏ็จ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฐ้ๆฉใ",+ "sandboxDrive.fallback.rootNotAllowed": "ๅ ฌๅ ฑ็ฝ็็ๆ น็ฎๅฝไธ่ฝไฝไธบๅทฅไฝ็ฎๅฝ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฉไธไธชๆไปถๅคนใ",+ "sandboxDrive.fallbackChip.directoryMissing": "็ฎๅฝๅทฒไธๅญๅจ",+ "sandboxDrive.fallbackChip.instanceRebuildRequired": "้ๅจไธชไบบ็ฝ็้ๅปบ",+ "sandboxDrive.fallbackChip.instanceUnavailable": "็ฏๅข็ฎๅฝไธๅฏ็จ",+ "sandboxDrive.fallbackChip.rootNotAllowed": "่ฏท้ๆฉๆไปถๅคน",+ "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-CN/common.json b/locales/zh-CN/common.jsonindex 7f3cb3b9f26..844f3ac31d2 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -565,7 +565,7 @@"visibilityConfirm.makePrivate.itemLibrary": "ๅฎไปไผ็ๅจไฝ ๆพๅ ฅ็่ตๆๅบไธญ๏ผๅชๆฏๅ ถไปๆๅไธๅ็ๅพๅฐ","visibilityConfirm.makePrivate.itemLoaded": "ๅฏนๆนๅทฒๅ ่ฝฝ่ฟ็ๅ ๅฎนๆ ๆณๆถๅ","visibilityConfirm.makePrivate.itemReferences": "ๅทฒๅญๅจ็ๆถๆฏ้ไปถใๅผ็จไฝ็ฝฎไผๆพ็คบไธบใๅทฒๅคฑๆใ",- "visibilityConfirm.publish.itemCapturedState": "ๆๅๅฏไปฅ่ฟ่กๅฎ็ๅฏๆฌ๏ผๅนถ่ฎฟ้ฎๅ ถไธญๆ่ท็ไธๅ โโ ๆไปถใCLI ็ปๅฝๆใไฝ ็็ปๅฝ่บซไปฝ",+ "visibilityConfirm.publish.itemCapturedState": "็ฏๅขๆนไธบไธๆฌกๆงๅๅงๅไนๅๅๅบ็ๅฏๆฌ๏ผไผไฟ็ๅ ถไธญๆ่ท็ๅ ๅฎน โโ ๆไปถใCLI ็ปๅฝๆใไฝ ็็ปๅฝ่บซไปฝ โโ ๆๅ้ฝ่ฝ่ฎฟ้ฎ","visibilityConfirm.publish.itemLoaded": "ๆนๅ็งไบบๅๅฏนๆนๅทฒๅ ่ฝฝ็ๅ ๅฎนๆ ๆณๆถๅ","visibilityConfirm.publish.itemReversible": "ไนๅๅฏไปฅๅจๅไธ่ๅ้ๆนๅ็งไบบ","visibilityConfirm.publish.itemVisible": "ๅทฅไฝๅบๆๆๆๅไผ็ซๅณๅฏไปฅ็ๅฐ",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex e7ce6838b47..4dd83dab903 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -42,7 +42,42 @@"workingDirectory.detachedWorktree": "detached","workingDirectory.diffLineStatTooltip": "ๆฐๅข่ก {{added}} ยท ๅ ้ค่ก {{deleted}} ยท ๅๆดๆไปถ {{files}}","workingDirectory.diffStatTooltip": "ๆฐๅข {{added}} ยท ไฟฎๆน {{modified}} ยท ๅ ้ค {{deleted}}",+ "workingDirectory.drive.actionFailed": "ๆไฝๅคฑ่ดฅ๏ผ่ฏท้่ฏใ",+ "workingDirectory.drive.browseDescription": "้ๆฉ็ฝ็ไธญ็ไธไธชๆไปถๅคนใ",+ "workingDirectory.drive.buildingDesc": "่ฟไธช็ฏๅข็ฎๅฝ่ฟๅจๆๅปบไธญ๏ผๆๅปบๅฎๆๅๆ่ฝ้ๆฉ",+ "workingDirectory.drive.createCopy": "ๅๅปบๅฏๆฌ",+ "workingDirectory.drive.delete": "ๅ ้ค",+ "workingDirectory.drive.deleteConfirmContent": "่ฏฅๆไปถๅคนๅๅ ถไธญ็ๆๆๆไปถๅฐไป็ฝ็ๅ ้ค๏ผๅฏนๆๆ่ฝ็ๅฐๅฎ็ๆๅ็ๆ๏ผๅจๅ ถไธญๅทฅไฝ็่ฏ้ขๅฐๅ้ๅฐไธดๆถๆฒ็ฎฑใ",+ "workingDirectory.drive.deleteConfirmTitle": "ๅ ้คใ{{name}}ใ๏ผ",+ "workingDirectory.drive.drives.personal": "ไธชไบบ็ฝ็",+ "workingDirectory.drive.drives.public": "ๅ ฌๅ ฑ็ฝ็",+ "workingDirectory.drive.environmentBadge": "็ฏๅข",+ "workingDirectory.drive.folderNotEmpty": "่ฏฅๆไปถๅคนๅทฒๆๅ ๅฎน๏ผๅช่ฝ็จ็ฏๅขๅๅงๅๆฐๅปบๆ็ฉบ็ๆไปถๅคนใ",+ "workingDirectory.drive.folderTaken": "ๅทฒๆๅๅ็็ฏๅข็ฎๅฝใ",+ "workingDirectory.drive.foldersLoadFailed": "ๆ ๆณๅ ่ฝฝ็ฝ็ไธญ็่ฟไธชๆไปถๅคน๏ผ่ฏท้่ฏๆ่ฟๅ็ฝ็ๆ น็ฎๅฝใ",+ "workingDirectory.drive.gitRepository": "Git",+ "workingDirectory.drive.inUseDesc": "ๆญฃๅจ่ขซๅ ถไป่ฏ้ขไฝฟ็จ",+ "workingDirectory.drive.initializeHint": "ๅฐๅจ็ฝ็ๆ น็ฎๅฝๅๅปบ่ฏฅๆไปถๅคน๏ผๅนถ็จๆ้็ฏๅขๅๅงๅ๏ผๅ ้ไปๅบๅนถ่ฟ่กๅฎ่ฃ ๅฝไปคใ",+ "workingDirectory.drive.initializeWith": "็จ็ฏๅขๅๅงๅ",+ "workingDirectory.drive.moreActions": "ๆดๅคๆไฝ",+ "workingDirectory.drive.pickFailed": "ๆ ๆณๅๆขๅฐ่ฟไธชๆไปถๅคน๏ผ่ฏท้่ฏใ",+ "workingDirectory.drive.pickFolderFirst": "ๅ ้ๆฉไธไธชๆไปถๅคน",+ "workingDirectory.drive.privateBlocked": "็งๆ็ฏๅข๏ผๅ ฑไบซๅฉๆๆ ๆณไฝฟ็จ",+ "workingDirectory.drive.readOnly": "็ฏๅข็ฎๅฝๅจ่ฟ้ๆฏๅช่ฏป็ใ",+ "workingDirectory.drive.rebuildInPersonal": "็งๆ็ฏๅข็ฎๅฝ๏ผ{{names}}๏ผๅทฒๅจ่ฟ้้่๏ผๅฏ็ฑๅ่ช็ไธปไบบๅจไธชไบบ็ฝ็้ๅปบใ",+ "workingDirectory.drive.rename": "้ๅฝๅ",+ "workingDirectory.drive.renameFailed": "ๆไปถๅคน้ๅฝๅๅคฑ่ดฅ",+ "workingDirectory.drive.renameTitle": "้ๅฝๅๆไปถๅคน",+ "workingDirectory.drive.rootNotAllowed": "็ฝ็ๆ น็ฎๅฝไธ่ฝไฝไธบๅทฅไฝ็ฎๅฝ",+ "workingDirectory.drive.state.building": "ๆๅปบไธญ",+ "workingDirectory.drive.state.failed": "ๆๅปบๅคฑ่ดฅ",+ "workingDirectory.drive.state.inUse": "ไฝฟ็จไธญ",+ "workingDirectory.drive.title": "้ๆฉ็ฝ็ๆไปถๅคน","workingDirectory.enterPathManually": "ๆๅจ่พๅ ฅ่ทฏๅพ",+ "workingDirectory.environment.label": "ไปฃ็ ็ฏๅข",+ "workingDirectory.environment.none": "ไธๅ ณ่็ฏๅข",+ "workingDirectory.errorDetailHide": "ๆถ่ตท่ฏฆๆ ",+ "workingDirectory.errorDetailShow": "ๆฅ็่ฏฆๆ ","workingDirectory.filesAdded": "ๆฐๅข","workingDirectory.filesDeleted": "ๅ ้ค","workingDirectory.filesEmpty": "ๆฒกๆๆชๆไบค็ๅๆด",@@ -118,6 +153,7 @@"workingDirectory.undo": "ๆค้","workingDirectory.unselected": "ๆช้ๆฉ","workingDirectory.useFolder": "้ๆฉๆญคๆไปถๅคน",+ "workingDirectory.useFolderFailed": "ๆ ๆณไฝฟ็จๆญคๆไปถๅคนใ","workingDirectory.worktreeSearchPlaceholder": "ๆ็ดข worktree","workingDirectory.worktreeUnavailable": "ไธๅฏ็จ","workingDirectory.worktreesEmpty": "ๆชๅ็ฐ worktree",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex f145d2dd03d..b4b8bba961f 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -565,11 +565,73 @@"devices.visibilityTabs.private": "็งไบบ","devices.visibilityTabs.workspace": "ๅทฅไฝๅบ","devices.workingDirectory": "ๅทฅไฝ็ฎๅฝ๏ผ{{path}}",+ "drive.explorer.columns.kind": "็ง็ฑป",+ "drive.explorer.columns.modified": "ไฟฎๆนๆฅๆ",+ "drive.explorer.columns.name": "ๅ็งฐ",+ "drive.explorer.columns.size": "ๅคงๅฐ",+ "drive.explorer.delete": "ๅ ้ค",+ "drive.explorer.deleteFileContent": "ๆไปถไผไป็ฝ็ๅ ้คใ",+ "drive.explorer.deleteFolderContent": "ๆไปถๅคนๅๅ ถไธญๆๆๅ ๅฎน้ฝไผไป็ฝ็ๅ ้ค๏ผๅจๅ ถไธญๅทฅไฝ็ๅฏน่ฏไนๅไผๆน็จไธดๆถๆฒ็ฎฑใ",+ "drive.explorer.deleteTitle": "ๅ ้คใ{{name}}ใ๏ผ",+ "drive.explorer.empty": "่ฟไธชๆไปถๅคนๆฏ็ฉบ็",+ "drive.explorer.emptyRoot.personal": "ไธชไบบ็ฝ็่ฟๆฏ็ฉบ็ใๆฐๅปบไธไธชๆไปถๅคน๏ผๅฐฑ่ฝๅจๅฏน่ฏ้ๆๅฎ้ไฝๅทฅไฝ็ฎๅฝใ",+ "drive.explorer.emptyRoot.public": "ๅ ฌๅ ฑ็ฝ็่ฟๆฒกๆๆไปถๅคนใๆฐๅปบไธไธช๏ผๅๆๅไธ่ตทๅจ้้ขๅทฅไฝใ",+ "drive.explorer.kind.file": "ๆไปถ",+ "drive.explorer.kind.fileWithExtension": "{{extension}} ๆไปถ",+ "drive.explorer.kind.folder": "ๆไปถๅคน",+ "drive.explorer.kind.gitRepository": "Git ไปๅบ",+ "drive.explorer.loadFailed": "ๆ ๆณๅ ่ฝฝ่ฟไธชๆไปถๅคนใ",+ "drive.explorer.moreActions": "ๆดๅคๆไฝ",+ "drive.explorer.newFolder": "ๆฐๅปบๆไปถๅคน",+ "drive.explorer.readOnly": "็ฏๅข็ฎๅฝๅช่ฏป",+ "drive.explorer.readOnlyHint": "็ฏๅข็ฎๅฝๅช็ฑๅฎ่ชๅทฑ็ๆฒ็ฎฑไผ่ฏๅๅ ฅ๏ผ่ฟ้ๅฏไปฅๆต่ง๏ผไฝไธ่ฝไฟฎๆนใ",+ "drive.explorer.rename": "้ๅฝๅ",+ "drive.loadFailed": "ๆ ๆณๅ ่ฝฝๅญๅจ๏ผ่ฏทๆฃๆฅ็ฝ็ปๅ้่ฏใ",+ "drive.retained.delete": "ๅ ้ค",+ "drive.retained.deleteConfirm.desc": "็ฝ็้็ๆๆๅ ๅฎน้ฝไผ่ขซๅ ้ค๏ผๆ ๆณๆขๅคใ",+ "drive.retained.deleteConfirm.title": "ๅ ้ค {{name}} ็ไธชไบบ็ฝ็๏ผ",+ "drive.retained.deleted": "็ฝ็ๅทฒๅ ้ค",+ "drive.retained.expiresIn": "{{count}} ๅคฉๅๅ ้ค",+ "drive.retained.expiresToday": "ไปๅคฉๅ ้ค",+ "drive.retained.hint": "ๆๅ็ฆปๅผๅไฟ็ 30 ๅคฉ๏ผๅฐๆ่ชๅจๅ ้ค๏ผๅจๆญคไนๅ่ฎกๅ ฅๅทฅไฝๅบ้ ้ขๆฑ ใ่ฟ้ๅชๆพ็คบ็จ้๏ผไธๆพ็คบๆไปถใ",+ "drive.retained.lastError": "ไธๆฌกๆไฝๅคฑ่ดฅ๏ผ{{error}}",+ "drive.retained.move": "็งปๅฐๅ ฌๅ ฑ็ฝ็",+ "drive.retained.moveConfirm.desc": "ๆไปถไผ็งปๅฐๅ ฌๅ ฑ็ฝ็็ departed-members ๆไปถๅคนไธ๏ผๆๆๆๅ้ฝ่ฝๆๅผ๏ผไธชไบบ็ฝ็้ๅๆธ ็ฉบใๅช่ฝ็งปๅจ 1 MB ไปฅๅ ็ๆๆฌๆไปถ๏ผๅซๆๅ ถไปๆไปถ็็ฝ็ไธไผ่ขซๆนๅจใ",+ "drive.retained.moveConfirm.title": "ๆ {{name}} ็็ฝ็็งปๅฐๅ ฌๅ ฑ็ฝ็๏ผ",+ "drive.retained.moved": "ๅทฒ็งปๅฐๅ ฌๅ ฑ็ฝ็็ {{path}}",+ "drive.retained.title": "ๅทฒ็ฆปๅผๆๅ็ไธชไบบ็ฝ็",+ "drive.scope.personal": "ไป ไฝ ๅฏ่ง",+ "drive.scope.public": "ๆๆๆๅๅฏ่ง",+ "drive.tabs.personal": "ไธชไบบ็ฝ็",+ "drive.tabs.public": "ๅ ฌๅ ฑ็ฝ็",+ "drive.usage.enableOverage": "ๅผๅฏๆ้่ฎก่ดน",+ "drive.usage.manage": "ๅจๅญๅจ่ฎพ็ฝฎไธญ็ฎก็",+ "drive.usage.memberUnmeasured": "ๆช็ป่ฎก",+ "drive.usage.membersHint": "ๅชๆพ็คบ็จ้๏ผ็ไธๅฐๅ ๅฎน",+ "drive.usage.membersTitle": "ๆๅไธชไบบ็ฝ็",+ "drive.usage.others": "ๅ ถไปๆๅ",+ "drive.usage.over": "ๅทฒ่ถ ๅบๅญๅจ้ ้ข๏ผ้่ฆๆธ ็็ฉบ้ดๆๅ็บงๅๆ่ฝ็ปง็ปญไฟๅญๆไปถใ",+ "drive.usage.overBilled": "ๅทฒ่ถ ๅบ้ ้ข๏ผๆไปถไปๅฏ็ปง็ปญไฟๅญ๏ผ่ถ ๅบ้จๅๆ้่ฎก่ดนใ",+ "drive.usage.overBy": "่ถ ๅบ้ ้ข {{size}}",+ "drive.usage.overageAskAdmin": "่ฏทๅทฅไฝๅบ็ฎก็ๅๅผๅฏๆ้่ฎก่ดน๏ผไปฅ็ปง็ปญไฟๅญๆไปถใ",+ "drive.usage.overageModalTitle": "่ถ ๅบ้ขๅบฆๅ็ปง็ปญไฟๅญ",+ "drive.usage.poolTitle": "ๅทฅไฝๅบๅญๅจ้ ้ข",+ "drive.usage.refresh": "้ๆฐ็ป่ฎก",+ "drive.usage.remaining": "ๅฉไฝ {{size}} ยท ๅทฒ็จ {{percent}}%",+ "drive.usage.showAllMembers": "ๆพ็คบๅ จ้จ {{count}} ไฝๆๅ",+ "drive.usage.showFewerMembers": "ๆถ่ตท",+ "drive.usage.title": "ๅญๅจ็จ้",+ "drive.usage.unmeasured": "ๅฐๆช็ป่ฎก ยท ๅ ฑ {{total}}",+ "drive.usage.unmeasuredShort": "ๅฐๆชๆต้",+ "drive.usage.used": "ๅทฒ็จ {{used}} / ๅ ฑ {{total}}","environments.cancel": "ๅๆถ","environments.create": "ๆฐๅปบ็ฏๅข","environments.createFailed": "็ฏๅขๆฒก่ฝๅๅปบ",- "environments.desc": "ไธๆฌกๆฒ็ฎฑ่ฟ่ก้่ฆ็ๅจ่พน๏ผไปฃ็ ไปๅบใๅๅงๅๅฝไปคใ็ฏๅขๅ้ใ็ฑๅฎๅปบๅบๆฅ็ๆฏไธชๅฏๆฌ๏ผๆไปถ้ฝ่ฝ่ทจไผ่ฏไฟ็ใ",+ "environments.desc": "้กน็ฎ็ๅๅงๅๆนๅผ๏ผ่ฆๆๅ็ไปๅบใsetup ๅฝไปคๅ็ฏๅขๅ้ใๅจ่พๅ ฅๆกไธๆน็ใไปฃ็ ็ฏๅขใไธญ้ๆฉๅ๏ผๅฏน่ฏ็ๅทฅไฝ็ฎๅฝ๏ผไธดๆถๆฒ็ฎฑๆ็ฝ็ๆไปถๅคน๏ผไผ็จๅฎๅๅงๅไธๆฌกใ","environments.detail.close": "ๅ ณ้ญ",+ "environments.detail.initializerDesc": "ๅจๅฏน่ฏๆ้็ๅทฅไฝ็ฎๅฝไธญๆง่กไธๆฌก๏ผๅ ้ไปๅบๅนถ่ฟ่กๅๅงๅๅฝไปคใ",+ "environments.detail.noRepository": "ๆช่ฎพ็ฝฎไปๅบ",+ "environments.detail.noSetup": "ๆช่ฎพ็ฝฎๅๅงๅๅฝไปค","environments.detail.tabs.overview": "ๆฆ่ง","environments.detail.tabs.settings": "่ฎพ็ฝฎ","environments.duplicateName": "ไฝ ๅทฒ็ปๆไธไธชๅๅ็็ฏๅขไบ",@@ -579,9 +641,13 @@"environments.files.binary": "ไธๆฏๆๆฌๆไปถ๏ผๆ ๆณๅจ่ฟ้ๆฅ็ใ","environments.files.browse": "ๆต่งๆไปถ","environments.files.empty": "่ฟไธช็ฎๅฝๆฏ็ฉบ็",+ "environments.files.folderNotEmpty": "่ฏฅๆไปถๅคนๅทฒๆๅ ๅฎน๏ผๅช่ฝ็จ็ฏๅขๅๅงๅๆฐๅปบๆ็ฉบ็ๆไปถๅคนใ",+ "environments.files.folderTaken": "ๅทฒๆๅๅ็็ฏๅข็ฎๅฝใ","environments.files.invalidPath": "ๅ็งฐๆ ๆ๏ผ่ทฏๅพไธ่ฝ่ถ ๅบ่ฏฅๅฏๆฌ็็ฎๅฝ","environments.files.listFailed": "่ฟไธช็ฎๅฝๅไธๅบๆฅ",+ "environments.files.notFound": "่ฏฅๆไปถๅคนไธๅญๅจใ","environments.files.openHint": "ๅๅป็ฎๅฝ่ฟๅ ฅ๏ผๅๅปๆไปถๆฅ็",+ "environments.files.readOnly": "็ฏๅข็ฎๅฝๆฏๅช่ฏป็๏ผๅชๆๅจๅ ถไธญ่ฟ่ก็ไผ่ฏๅฏไปฅๅๅ ฅใ","environments.files.readOnlyHint": "ๅช่ฏป๏ผๅ ๅฎน็ฑๆฒ็ฎฑ่ชๅจๅๆญฅ๏ผnode_modules ็ญไพ่ต็ฎๅฝไธๅจ่ฟ้ๆพ็คบใ","environments.files.truncated": "ๅชๆพ็คบไบๅ้ขไธ้จๅๆก็ฎ","environments.files.unreadable": "่ฟไธชๆไปถ่ฏปไธๅบๆฅ",@@ -590,11 +656,12 @@"environments.form.addEnv": "ๆฐๅปบๅ้","environments.form.addSource": "ๆทปๅ ไปๅบ","environments.form.appliesOnBuild": "ๅจๆฐๅปบๅฏๆฌๆถ็ๆใๅทฒๆๅฏๆฌไผไธ็ด็จๅฎๅๅปบๆถ็้ฃไปฝๅฎไนโโ้ๅปบไนๆฏ็ งๅฎๅ่ทไธ้๏ผ่ฆ็จไธๆนๅจๅฐฑๆฐๅปบไธไธชๅฏๆฌใ",+ "environments.form.appliesOnInit": "ไธๆฌกๅฐ็ฏๅขๅบ็จๅฐๅทฅไฝ็ฎๅฝๆถ็ๆ๏ผๅทฒๅๅงๅ่ฟ็ๆไปถๅคนไฟๆๅๆ ทใ","environments.form.basics": "ๅบๆฌไฟกๆฏ","environments.form.bootstrap": "ๅๅงๅๅฝไปค","environments.form.bootstrapHint": "ๅจๅฏน่ฏๅผๅงๅ๏ผไบไปฃ็ ็ฎๅฝไธญ่็ฝๆง่กไธๆฌกใ","environments.form.changeRepository": "ๆดๆขไปๅบ",- "environments.form.desc": "ๅฏๆฌ็ฑไปไนๅปบๅบๆฅ๏ผไปฃ็ ไปๅชๆฅ๏ผไปฅๅ้ ไปไน่ฎฉๅฎ่ฝ่ท่ตทๆฅใ",+ "environments.form.desc": "ไปฃ็ ไปๅชๆฅ๏ผไปฅๅ้ ไปไน่ฎฉๅฎ่ฝ่ท่ตทๆฅใ","environments.form.description": "ๆ่ฟฐ","environments.form.descriptionPlaceholder": "่ฟไธช็ฏๅขๆฏ็จๆฅๅไปไน็","environments.form.disconnect": "ๆญๅผ",@@ -604,7 +671,7 @@"environments.form.envCount_other": "{{count}} ไธชๅ้","environments.form.envEmpty": "่ฟๆฒกๆ็ฏๅขๅ้","environments.form.envEmptyHint": "้ๆกๆทปๅ ๏ผๆๆดไปฝ .env ็ฒ่ดดๅฐ",- "environments.form.envHint": "ๅชๆพ้ๅฏๆๅ ๅฎนโโๅฎไปฌไปฅๆๆๅญๅจ๏ผๅนถไผ่ขซๅคๅถ่ฟๆฏไธไธชๅฏๆฌใ",+ "environments.form.envHint": "ไป ้้ๆๆๅผโโไปฅๆๆไฟๅญ๏ผๅจๅ ้ไปๅบๅๆง่กๅๅงๅๅฝไปคๆถๅฏผๅบใ","environments.form.exclude": "ๅฏๅ็่ทฏๅพ","environments.form.excludeHint": "ไธ่กไธไธช๏ผ็ธๅฏนไบๅฏๆฌใๅๅจ่ฟ้็ญไบๅฃฐๆๅฎๅฏไปฅ้ๅปบ๏ผไบๆฏๅฎไผ่ทไฝ ็ไบงๅบๅๅผๅญๆพใๅนถไธๅฏ่ฝ่ขซๆธ ็ๆใๅ่ฟๆฅไฝๅ ถๅฎ้ๅปบไธไบ็ไธ่ฅฟ๏ผๅฐฑๆฏไฝ ๅฏ่ฝไธขๆ็ไธ่ฅฟใ","environments.form.filesDesc": "่ฟไธชๆไปถๅคนๅซไปไนใๆพไบๅชไบ็ป agent ๅค็็ๆไปถใ",@@ -628,7 +695,7 @@"environments.form.saved": "ๅทฒไฟๅญ","environments.form.setup": "ๅๅงๅ","environments.form.sources": "ๆบไปฃ็ ",- "environments.form.sourcesHint": "ๅจๅ ถไปๆญฅ้ชคไนๅ้่ฟ HTTPS ๅ ้ใๆไธๆฏๆ็งๆไปๅบโโ่งๆ ผ้ไธๅญๆพไปปไฝๅญๆฎใ",+ "environments.form.sourcesHint": "ๅจๅ ถไปๆญฅ้ชคไนๅ้่ฟ HTTPS ๅ ้ใ็งๆไปๅบ้่ฟๅทฒๆๆ่ฏฅไปๅบ็ GitHub App ๅฎ่ฃ ๆฅๅ ้๏ผ็ฏๅขๆฌ่บซไธไฟๅญไปปไฝๅญๆฎใ","environments.github.connect": "่ฟๆฅ GitHub","environments.github.label": "ไปฃ็ ไปๅบ","environments.github.loadFailed": "ๆ ๆณๅ ่ฝฝ GitHub ไปๅบ๏ผ่ฏท้่ฏใ",@@ -643,6 +710,7 @@"environments.github.repositoryPlaceholder": "ๆ็ดขไปๅบ","environments.github.reviewAccess": "ๆฃๆฅๆๆ่ๅด","environments.hasInstances": "่ฏทๅ ๅ ๆๅฎ็ๅ ถไปๅฏๆฌ",+ "environments.inProject": "ไปๆ้กน็ฎๅจไฝฟ็จ่ฟไธช็ฏๅขโโ่ฏทๅ ๆๅฎไป้กน็ฎไธญ็งป้ค","environments.instances.add": "ๆฐๅปบๅฏๆฌ","environments.instances.build": "ๆๅปบ","environments.instances.buildConfirmTitle": "ๆๅปบๅฏๆฌ {{name}}๏ผ",@@ -662,7 +730,7 @@"environments.instances.create": "ๆฐๅปบๅฏๆฌ","environments.instances.createFailed": "ๅฏๆฌๆฒก่ฝๅๅปบ","environments.instances.defaultUndeletable": "่ฟๆฏ็ฏๅข็้ป่ฎคๅฏๆฌ๏ผไธ่ฝๅ็ฌๅ ้คใๅบ้ฎ้ขๆถ่ฏท้ๆฐๆๅปบ๏ผๆ็ดๆฅๅ ้ค็ฏๅข",- "environments.instances.desc": "ๅฏๆฌๆฏ่ฟไธช็ฏๅข็ไธไปฝๅฏ่ฟ่กๆท่ด๏ผๆ่ชๅทฑ็็ฎๅฝๅ่ฃ ๅฅฝ็ไพ่ตใๅฏน่ฏๅจๅฏๆฌ้่ฟ่ก๏ผๅคไธชๅฏๆฌๅฏไปฅๅนถ่ก่ไบไธๅฝฑๅใ",+ "environments.instances.desc": "็จ่ฟไธช็ฏๅขๅๅงๅ่ฟ็็ฝ็ๆไปถๅคนใๆฏไธชๆไปถๅคนๆ่ชๅทฑ็ๆไปถๅๅทฒๅฎ่ฃ ็ไพ่ต๏ผๅจไธๅๆไปถๅคน้ๅทฅไฝ็ๅฏน่ฏไบไธๅฝฑๅใ","environments.instances.directoryHint": "ๆไปถๅคน็ฎๅฝ๏ผๅๅปบๅไธๅฏไฟฎๆน","environments.instances.directoryLabel": "็ฎๅฝ","environments.instances.directoryLocked": "ๅฏๆฌๅปบๅฅฝไนๅ็ฎๅฝๅฐฑไธ่ฝๆนไบโโ่ฆๆข็ฎๅฝ๏ผๅ ๆๅๆฐๅปบไธไธชใ",@@ -673,12 +741,25 @@"environments.instances.hideLog": "ๆถ่ตทๆฅๅฟ","environments.instances.inUse": "ๆๅฏน่ฏๆญฃๅจไฝฟ็จ่ฟไธชๅฏๆฌ๏ผ็ญๅฎ็ปๆๅๅ่ฏ","environments.instances.namePlaceholder": "ๅฏๆฌๅ็งฐ",+ "environments.instances.needsDrive": "ๅฏๆฌๆฏ็ฝ็้็ๆไปถๅคน๏ผๅฝๅ่ดฆๅท่ฟๆฒกๆ็ฝ็ใ","environments.instances.notBuilt": "ๅฐๆชๆๅปบโโ่ฟๆฒกๆๆๅไปฃ็ ใๅฎ่ฃ ไพ่ต","environments.instances.occupancyUnavailable": "ๆๆถ่ฏปไธๅฐๅชไบๅฏๆฌๆญฃๅจ่ฟ่ก",+ "environments.instances.openDriveSettings": "ๅๅพๅญๅจ่ฎพ็ฝฎ","environments.instances.overlappingDirectory": "่ฏฅ็ฎๅฝไธๅ ถไปๅฏๆฌ็็ฎๅฝๅญๅจๅตๅฅ๏ผ่ฏทๆขไธไธช็ฎๅฝ",+ "environments.instances.publishPublic": "ๅจๅ ฌๅ ฑ็ฝ็ๅๅงๅ",+ "environments.instances.publishPublicDesc": "ๅทฒๅๅธๅฐๅทฅไฝๅบ๏ผไฝๅฎ็็ฎๅฝ้ฝๅจไฝ ็ไธชไบบ็ฝ็้๏ผๅ ถไปๆๅๆ ๆณ่ฎฟ้ฎใๅจๅ ฌๅ ฑ็ฝ็ๅๅงๅไธไธช็ฎๅฝๅ๏ผๆๅๆ่ฝไฝฟ็จๅฎใ",+ "environments.instances.publishPublicFailed": "ๆ ๆณๅจๅ ฌๅ ฑ็ฝ็ไธญๅๅปบๅฏๆฌ",+ "environments.instances.publishPublicStarted": "ๆญฃๅจๅ ฌๅ ฑ็ฝ็ไธญๆๅปบๅฏๆฌ","environments.instances.rebuild": "้ๆฐๆๅปบ","environments.instances.rebuildConfirmContent": "ไผๅ ๆธ ็ฉบ่ฟไธชๅฏๆฌ็็ฎๅฝ๏ผๅ้ๆฐๆๅไปฃ็ ใ่ฟ่กๅๅงๅ่ๆฌใ็ฎๅฝ้็ฐๆ็ไธๅโโๅฏน่ฏไธญ็ๆนๅจใ่ฃ ๅฅฝ็ไพ่ตใๆฅๅใๆฐๆฎโโ้ฝไผไธขๅคฑ๏ผๆ ๆณๆขๅคใ","environments.instances.rebuildConfirmTitle": "้ๆฐๆๅปบๅฏๆฌ {{name}}๏ผ",+ "environments.instances.rebuildPersonal": "ๅจไธชไบบ็ฝ็้ๅปบ",+ "environments.instances.rebuildPersonalDesc": "{{names}} ่ฟๅจๅ ฌๅ ฑ็ฝ็้๏ผๅทฒ้่ใ็งๆ็ฏๅข็็ฎๅฝ็ฐๅจๆพๅจไฝ ็ไธชไบบ็ฝ็ใ",+ "environments.instances.rebuildPersonalFailed": "ๆ ๆณๅจไธชไบบ็ฝ็ไธญๅๅปบๅฏๆฌ",+ "environments.instances.rebuildPersonalRequired": "่ฟไธช็ฎๅฝๅจๅ ฌๅ ฑ็ฝ็ไธญ๏ผ้่ฆๅ ๅจไธชไบบ็ฝ็้ๅปบใ",+ "environments.instances.rebuildPersonalStarted": "ๆญฃๅจไฝ ็ไธชไบบ็ฝ็ไธญๆๅปบๆฐๅฏๆฌ",+ "environments.instances.rebuildPersonalTag": "้ๅจไธชไบบ็ฝ็้ๅปบ",+ "environments.instances.rebuildPersonalTagHint": "ๅทฒๅจๅ ฌๅ ฑ็ฝ็ไธญ้่๏ผไธๅไฝฟ็จใ","environments.instances.remove": "ๅ ้คๅฏๆฌ","environments.instances.removeConfirmContent": "ๅฎ็็ฎๅฝๅ้้ข็ไธ็ไธๅโโ่ฃ ๅฅฝ็ไพ่ตใๆฅๅใๆฐๆฎโโ้ฝไผ่ขซๅ ้ค๏ผๆ ๆณๆขๅคใ","environments.instances.removeConfirmTitle": "ๅ ้คๅฏๆฌ {{name}}๏ผ",@@ -723,7 +804,7 @@"environments.namePlaceholder": "็ฏๅขๅ็งฐ","environments.refresh": "ๅทๆฐ","environments.remove": "ๅ ้ค็ฏๅข",- "environments.removeConfirmContent": "ๅฎ็้ ็ฝฎใ็ฏๅขๅ้ใๅฏๆฌ็็ฎๅฝๅไฟๅญไธๆฅ็ๅฟซ็ ง้ฝไผไธ่ตทๅ ้ค๏ผๆ ๆณๆขๅคใ",+ "environments.removeConfirmContent": "ๅฎ็้ ็ฝฎๅ็ฏๅขๅ้ไผ่ขซๅ ้ค๏ผๆ ๆณๆขๅคใ็จๅฎๅๅงๅ่ฟ็ๆไปถๅคนไผไฟ็ๅ ถไธญ็ๆไปถ๏ผๆง็ๆฌๆๅปบ็ๅฏๆฌไผไธๅนถๅ ้คใ","environments.removeConfirmTitle": "ๅ ้ค็ฏๅข {{name}}๏ผ","environments.removeFailed": "ๅ ้ค็ฏๅขๅคฑ่ดฅ","environments.saveFailed": "ๆ ๆณไฟๅญ่ฟๆฌกไฟฎๆน",@@ -757,23 +838,23 @@"environments.storage.over": "ๅทฒ่ถ ๅบๅญๅจไธ้๏ผๅ ๆไธไบๆไปถๆ่ฝ็ปง็ปญไฟๅญใ","environments.storage.unmeasured": "ๅฐๆช็ป่ฎกๅ ็จ ยท ๅ ฑ {{total}}","environments.storage.used": "ๅทฒ็จ {{used}} / ๅ ฑ {{total}}",- "environments.unavailable.desc": "็ฏๅขๆ่ฟฐ็ๆฏไธไธชๆไน ๅ็ไบ็ซฏๅทฅไฝๅบ๏ผ่ๅฝๅ้จ็ฝฒๆฒกๆๆไพๅฎใ",- "environments.unavailable.title": "ๆญค้จ็ฝฒไธๆไพๆไน ๅๆฒ็ฎฑ",- "environments.upgrade.benefits.environments.desc": "ไปๅบใๅฎ่ฃ ๅฝไปคๅๅ้ๅๅจ็ฏๅข้๏ผๆฏไธชๆๅฎๅปบๅบ็ๆฒ็ฎฑ้ฝไปๅฐฑ็ปช็ถๆๅผๅงใ",- "environments.upgrade.benefits.environments.title": "ๆฒ็ฎฑ้ ็ฝฎๅชๅไธๆฌก",- "environments.upgrade.benefits.instances.desc": "ๅนถ่ก็ๅฏน่ฏๅ่ช่ฟ่กๅจ็ฏๅข็ไธไธชๅฏๆฌ้๏ผไบไธ่ฆ็ใ",- "environments.upgrade.benefits.instances.title": "ไธไปปๅกไธๅฏๆฌ",- "environments.upgrade.benefits.persist.desc": "ๆฒ็ฎฑๅๆถๅๅทฅไฝ็ฎๅฝไปๅจ๏ผไธๆฌก่ฟ่กๆฅ็ไธๆฌก็ปง็ปญใ",+ "environments.unavailable.desc": "็ฝ็ๆฏ็ปๆฒ็ฎฑ่ฟ่ก็จ็ๆไน ๅไบ็ซฏๅญๅจ๏ผๅฝๅ้จ็ฝฒๆฒกๆๆไพใ",+ "environments.unavailable.title": "ๆญค้จ็ฝฒไธๆไพ็ฝ็ๅญๅจ",+ "environments.upgrade.benefits.environments.desc": "ๅทฅไฝๅบๆๅๅ ฑไบซไธไธชๅ ฌๅ ฑ็ฝ็๏ผๆฏไบบ่ฟๆไธไธชๅชๆ่ชๅทฑ่ฝ่ฎฟ้ฎ็ไธชไบบ็ฝ็ใ",+ "environments.upgrade.benefits.environments.title": "ๅ ฌๅ ฑ็ฝ็ไธไธชไบบ็ฝ็",+ "environments.upgrade.benefits.instances.desc": "ๆฐๅปบๆไปถๅคนๆถ้ไธไธชไปฃ็ ็ฏๅข๏ผ่ชๅจๅ ้ไปๅบๅนถ่ฃ ๅฅฝไพ่ตใ",+ "environments.upgrade.benefits.instances.title": "็จไปฃ็ ็ฏๅขๅๅงๅๆไปถๅคน",+ "environments.upgrade.benefits.persist.desc": "ๆฒ็ฎฑๅๆถๅๆไปถๅคนไปๅจ๏ผไธๆฌก่ฟ่กๆฅ็ไธๆฌก็ปง็ปญใ","environments.upgrade.benefits.persist.title": "ๆไปถไธ้ๆฒ็ฎฑๅๆถ","environments.upgrade.cta": "ๅ็บงๅฐ Pro",- "environments.upgrade.desc": "่ฎฉไบ็ซฏๆฒ็ฎฑๆฅๆๆไน ๅ็ๅทฅไฝ็ฎๅฝใ็ฏๅขๆ่ฟฐๆฒ็ฎฑ้่ฆไปไนโโไปๅบใๅฎ่ฃ ๆญฅ้ชคใๅ้๏ผ็ฑๅฎๅปบๅบ็ๅฏๆฌๅจไผ่ฏไน้ดไฟ็ไธๅใ",- "environments.upgrade.title": "ๅ็บงๅฐ Pro๏ผๅผๅฏๆฒ็ฎฑ็ฏๅข",+ "environments.upgrade.desc": "่ฎฉไบ็ซฏๆฒ็ฎฑๆฅๆ่ทจไผ่ฏไฟ็็็ฝ็๏ผๅจ็ฝ็ๆไปถๅคน้ๅทฅไฝ็ๅฏน่ฏ๏ผๆฒ็ฎฑๅๆถๅๆไปถไพ็ถไฟ็ใ",+ "environments.upgrade.title": "ๅ็บงๅฐ Pro๏ผๅผๅฏ็ฝ็ๅญๅจ","environments.visibility.changeFailed": "็ฏๅขๅฏ่งๆงๆฒก่ฝไฟฎๆน","environments.visibility.createPublishedConfirmTitle": "ๅจๅทฅไฝๅบไธญๆฐๅปบๆญค็ฏๅข๏ผ","environments.visibility.publicTag": "ๅทฒๅๅธ","environments.visibility.publish": "ๅๅธๅฐๅทฅไฝๅบ","environments.visibility.publishConfirmTitle": "ๆ่ฟไธช็ฏๅขๅๅธๅฐๅทฅไฝๅบ๏ผ",- "environments.visibility.readonlyHint": "็ฑๅๅปบ่ ๅๅธๅฐๆฌๅทฅไฝๅบ๏ผไฝ ๅฏไปฅๅจ่ฟไธช็ฏๅข้่ฟ่ก๏ผไฝๅชๆๅๅปบ่ ่ฝๆนๅฎๆๅปบๅบไปไนใ",+ "environments.visibility.readonlyHint": "็ฑๅๅปบ่ ๅๅธๅฐๆญคๅทฅไฝๅบ๏ผไฝ ๅฏไปฅ็จ่ฟไธช็ฏๅขๅๅๅงๅ๏ผไฝๅชๆๅๅปบ่ ่ฝไฟฎๆนๅฎใ","environments.visibility.tabs.private": "็งไบบ","environments.visibility.tabs.workspace": "ๅทฅไฝๅบ","group.aiConfig": "ๆบ่ฝไฝ",@@ -1785,6 +1866,7 @@"tab.connector": "่ฟๆฅๅจ","tab.creds": "ๅญ่ฏ็ฎก็","tab.devices": "่ฎพๅค",+ "tab.drive": "ๅญๅจ","tab.environments": "็ฏๅข","tab.experiment": "ๅฎ้ช","tab.hotkey": "ๅฟซๆท้ฎ",@@ -3004,6 +3086,7 @@"workspace.invitePage.declineSubtitle": "ๆจๅฏไปฅๅ ณ้ญๆญค็ชๅฃใ","workspace.invitePage.declineTitle": "้่ฏทๅทฒๆ็ป","workspace.invitePage.differentEmailNotice": "ๆจๅฝๅ็ปๅฝไธบ {{currentEmail}}๏ผไฝๆญค้่ฏทๆฏๅ้ๅฐ {{inviteEmail}}ใ",+ "workspace.invitePage.driveCleanupInProgress": "ไฝ ไนๅๅจ่ฟไธชๅทฅไฝๅบ็ไธชไบบ็ฝ็ๆญฃๅจๆธ ็ไธญ๏ผ่ฏทๅ ๅ้ๅๅ่ฏใ","workspace.invitePage.expiredSubtitle": "ๆญค้่ฏทๅทฒ่ฟๆใ่ฏทๅข้ๆๆ่ ๅ้ไธไธชๆฐ็้่ฏทใ","workspace.invitePage.expiredTitle": "้่ฏทๅทฒ่ฟๆ","workspace.invitePage.expiresLabel": "ๅฐๆ",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 1de3a23bd8c..b5c19c219ca 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -693,5 +693,6 @@"usage.remaining": "ๅฉไฝ","usage.storage.embeddings.used": "ๅ้ๅญๅจ","usage.storage.file.used": "ๆไปถไฝฟ็จ้",+ "usage.storage.sandboxStorage.pool": "ๆฒ็ฎฑ็ฝ็๏ผๅทฅไฝๅบ้ ้ขๆฑ ๏ผ","usage.storage.sandboxStorage.used": "ๆฒ็ฎฑๅญๅจ"}diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.test.tsindex a2388fb09c8..4ffe4be5187 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts@@ -58,6 +58,53 @@ describe('formatSandboxStoragePromptVariables', () => {});});+describe('the three placements a run can have', () => {+ it('names a drive folder as a folder on the network drive', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ cwd: 'reports',+ mode: 'drive',+ });++ expect(prompt).toContain("`reports`, a folder on the user's **network drive**");+ expect(prompt).toContain('Keep to this folder');+ // A drive restores nothing but files, so the model must not count on+ // installed packages being there next time.+ expect(prompt).toContain('packages you install');+ expect(prompt).not.toContain('environment directory');+ });++ it('names the drive root when no folder narrows it', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({ mode: 'drive' });++ expect(prompt).toContain("the root of the user's **network drive**");+ expect(prompt).toContain('its own subfolder');+ });++ it('names an instance as an environment directory whose packages come back', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ cwd: 'notes-env',+ mode: 'persistent',+ });++ expect(prompt).toContain('`notes-env`, an **environment directory**');+ expect(prompt).not.toContain('network drive**:');+ });++ it('persists files in both persistent placements and not in the temporary one', () => {+ const persisted = '- Files in your working directory persist across sessions';++ expect(formatSandboxStoragePromptVariables({ mode: 'drive' }).sandbox_session_files).toContain(+ persisted,+ );+ expect(+ formatSandboxStoragePromptVariables({ mode: 'persistent' }).sandbox_session_files,+ ).toContain(persisted);+ expect(+ formatSandboxStoragePromptVariables({ mode: 'ephemeral' }).sandbox_session_files,+ ).not.toContain(persisted);+ });+});+describe('the placement text the skills runtime also renders', () => {it('keeps the ephemeral default renderable without any persistence input', () => {// The skills tool now carries `{{sandbox_workspace}}` too, and its promptdiff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.tsindex dedeff28888..e823131bca1 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.ts@@ -11,9 +11,9 @@* `sandboxStorage` claim (`{ key, quotaBytes }` or none) on the trusted* client token. LobeHub is the sole authority for the key; nothing derives* it from a request body.- * 2. **Mode** โ the run asks for `'persistent'` or `'ephemeral'`. Default is- * ephemeral: persistence is an explicit choice per topic, not every task- * wants to leave files behind.+ * 2. **Mode** โ the run asks for `'drive'`, `'persistent'` or `'ephemeral'`.+ * Default is ephemeral: persistence is an explicit choice per topic, made by+ * picking a folder, not every task wants to leave files behind.** Only the AND of the two routes to the persistent runtime. Everything after* that point โ which volume, which mount root, how paths resolve against the@@ -24,17 +24,62 @@*//**- * Whether a run wants its working directory to survive the session.+ * Whether a run wants its working directory to survive the session, and how.+ *+ * - `ephemeral` โ a throwaway box; nothing survives.+ * - `drive` โ a folder on the persistent volume, used as a network drive: the+ * session works in it and restores or captures nothing else, so any number+ * of conversations can share one drive at once.+ * - `persistent` โ an environment directory (an instance): the folder plus the+ * packages its build installed, restored and captured with the session.** Positive form on purpose, and ephemeral by default: the safe state is the one* you get by saying nothing. A negative flag (`disablePersistentโฆ`) inverts* that โ a caller that forgets it opts into persistence by accident.*/-export type SandboxMode = 'ephemeral' | 'persistent';+export type SandboxMode = 'drive' | 'ephemeral' | 'persistent';++/** Whether a mode keeps its working directory on the persistent volume. */+export const isPersistentSandboxMode = (mode: SandboxMode | undefined): boolean =>+ mode === 'drive' || mode === 'persistent';++/**+ * How a topic names the drive's root as its folder. A choice of its own rather+ * than "no folder", which means the temporary sandbox. Never sent to the+ * execution plane: a drive call without a folder already works at the root.+ */+export const SANDBOX_DRIVE_ROOT = '.';export const DEFAULT_SANDBOX_MODE: SandboxMode = 'ephemeral';+/**+ * Which of a workspace's two drives a run or a request addresses:+ *+ * - `public` โ the workspace's shared drive (`ws-org-<workspaceId>`), which+ * every member browses and works in;+ * - `personal` โ the member's own drive inside the workspace+ * (`ws-mem-<workspaceId>-<userId>`), which only they can reach.+ *+ * A personal account has one drive (`ws-<userId>`) and ignores this. Both of a+ * workspace's drives draw on the workspace plan's one quota pool.+ */+export type SandboxDrive = 'personal' | 'public';++export const SANDBOX_DRIVES = ['public', 'personal'] as const satisfies readonly SandboxDrive[];++/**+ * The drive a workspace run uses when nothing chose one: the shared drive,+ * which is the only one there was before members had drives of their own โ so+ * every topic that picked a folder before then keeps meaning the same folder.+ */+export const DEFAULT_SANDBOX_DRIVE: SandboxDrive = 'public';+export interface SandboxStorageScope {+ /**+ * Which workspace drive; ignored without {@link workspaceId}, defaulting to+ * {@link DEFAULT_SANDBOX_DRIVE}.+ */+ drive?: SandboxDrive;userId: string;/** Organization workspace id when the run is workspace-scoped. */workspaceId?: string | null;@@ -78,12 +123,28 @@ const isSafeKeySegment = (value: string): boolean => /^\w[\w.-]*$/.test(value);/** Distinguishes an organization key from a personal one inside the shared namespace. */const ORG_KEY_INFIX = 'org-';+/** Distinguishes a workspace member's own drive from a personal account's. */+const MEMBER_KEY_INFIX = 'mem-';++/**+ * A workspace id a member key can carry: word characters only, which is every+ * id the platform issues. It is what makes the first `-` after the infix an+ * unambiguous separator โ user ids may contain dashes, so a workspace id that+ * did too could split two ways and name another member's drive.+ */+const MEMBER_KEY_WORKSPACE_ID = /^\w+$/;+/**- * Derive the workspace key for a principal. An organization workspace shares- * one directory across its members (`ws-org-<workspaceId>`); a personal run- * gets `ws-<userId>`. LobeHub is the sole authority for this mapping: the- * execution plane reads the key off the signed claim and never recomputes it- * from an identity of its own.+ * Derive the drive key for a principal:+ *+ * - personal account โ `ws-<userId>`;+ * - workspace, public drive โ `ws-org-<workspaceId>`, shared by every member;+ * - workspace, personal drive โ `ws-mem-<workspaceId>-<userId>`, the member's+ * own, billed to the workspace's pool like the public one.+ *+ * LobeHub is the sole authority for this mapping: the execution plane reads+ * the key off the signed claim and never recomputes it from an identity of its+ * own.** Returns `undefined` for an id that is not already a safe path segment, which* costs that principal persistence rather than risking the alternative.@@ -95,23 +156,52 @@ const ORG_KEY_INFIX = 'org-';* nothing real.*/export const deriveSandboxStorageKey = ({+ drive = DEFAULT_SANDBOX_DRIVE,userId,workspaceId,}: SandboxStorageScope): string | undefined => {- const segment = workspaceId || userId;- if (!segment || !isSafeKeySegment(segment)) return undefined;+ if (!userId || !isSafeKeySegment(userId)) return undefined;+ if (workspaceId && !isSafeKeySegment(workspaceId)) return undefined;- // The two shapes share one namespace, so a personal id starting with `org-`- // would address the organization directory of the same name. No id the- // platform issues looks like that, which is exactly why it would go unnoticed.- if (!workspaceId && userId.startsWith(ORG_KEY_INFIX)) return undefined;+ let key: string;+ if (!workspaceId) {+ // The three shapes share one namespace, so a personal id starting with+ // `org-` or `mem-` would address a workspace's drive of the same name. No+ // id the platform issues looks like that, which is exactly why it would go+ // unnoticed.+ if (userId.startsWith(ORG_KEY_INFIX) || userId.startsWith(MEMBER_KEY_INFIX)) return undefined;+ key = `ws-${userId}`;+ } else if (drive === 'personal') {+ if (!MEMBER_KEY_WORKSPACE_ID.test(workspaceId)) return undefined;+ key = `ws-${MEMBER_KEY_INFIX}${workspaceId}-${userId}`;+ } else {+ key = `ws-${ORG_KEY_INFIX}${workspaceId}`;+ }- const key = workspaceId ? `ws-${ORG_KEY_INFIX}${workspaceId}` : `ws-${userId}`;if (!SAFE_WORKSPACE_KEY.test(key)) return undefined;return key;};+/**+ * Which drive a key names, from the caller's own point of view: `public` for+ * the workspace's shared drive, `personal` for the caller's own (in a workspace+ * or a personal account), `undefined` for a drive that is neither โ another+ * member's, or another workspace's.+ */+export const sandboxDriveOfKey = (+ key: string,+ scope: Omit<SandboxStorageScope, 'drive'>,+): SandboxDrive | undefined => {+ if (!scope.workspaceId) return key === deriveSandboxStorageKey(scope) ? 'personal' : undefined;++ for (const drive of SANDBOX_DRIVES) {+ if (key === deriveSandboxStorageKey({ ...scope, drive })) return drive;+ }++ return undefined;+};+/** Workspace subtree the platform reserves for its own state. */const RESERVED_WORKSPACE_DIR = '.sandbox';@@ -198,7 +288,10 @@ export interface SandboxStoragePromptVariables {}export interface SandboxStoragePromptInput {- /** Chosen subdirectory of the workspace, relative to its root. */+ /**+ * The folder the run works in, relative to the drive's root; absent on a+ * drive run at the root itself.+ */cwd?: string;mode?: SandboxMode;/**@@ -217,7 +310,7 @@ export const formatSandboxStoragePromptVariables = ({mode = DEFAULT_SANDBOX_MODE,workingDir,}: SandboxStoragePromptInput = {}): SandboxStoragePromptVariables => {- if (mode !== 'persistent') {+ if (!isPersistentSandboxMode(mode)) {return {sandbox_session_files: '- Files from previous sessions may not persist',sandbox_workspace: [@@ -229,31 +322,40 @@ export const formatSandboxStoragePromptVariables = ({};}- // With a chosen subdirectory the model is told where it sits relative to the- // workspace, not where either lives absolutely โ the mount root stays the- // execution plane's business. It is told the root is reachable because it is:- // the fence keeps the session inside the workspace, not inside the chosen- // subdirectory, and a model that discovers this by accident is likelier to- // wander into another topic's files than one that knows the shape.- // A built instance runs in its checkout on local disk, which the session- // saves into the instance's directory on the volume โ so persistence is real- // here too, but through a copy rather than by being the volume. Saying so is- // what keeps a model from "fixing" the discrepancy it can see between `pwd`- // and the workspace path it can also see.- const placement = workingDir- ? [- `- You start in \`${workingDir}\`, this environment's checkout on the machine's own disk. The session saves it continuously into ${cwd ? `\`${cwd}\`, ` : ''}your instance's directory in a **persistent workspace**, so what you leave here is what you find in your next session, and it is what the user sees in their file browser.`,- `- The workspace is also mounted, and you may read from it, but that mounted path is the saved copy โ not where this session works. Do not move the task there.`,- ]- : cwd+ // Where the run is, in the words the user picked it by: a folder on their+ // drive, or an environment directory. The mount root stays the execution+ // plane's business, so neither names an absolute path on the volume.+ //+ // A drive keeps files and nothing else โ the machine itself starts fresh+ // every session โ so the model is told that installs do not carry over,+ // rather than discovering it when the next session's import fails.+ //+ // A built environment directory runs in its checkout on local disk, which+ // the session saves into the directory on the volume โ so persistence is+ // real there too, but through a copy rather than by being the volume. Saying+ // so is what keeps a model from "fixing" the discrepancy it can see between+ // `pwd` and the path it can also see.+ const placement =+ mode === 'drive'? [- `- Your working directory is \`${cwd}\`, a subdirectory of a **persistent workspace**: files written there survive session expiry and are still there in your next session.`,- `- The workspace root is above you. Its other subdirectories belong to this user's other topics โ reachable with relative paths, but do not write into them unless the user asks.`,+ cwd+ ? `- Your working directory is \`${cwd}\`, a folder on the user's **network drive**: files written there survive session expiry, are still there in your next session, and are what the user sees when they browse the drive.`+ : "- Your working directory is the root of the user's **network drive**: files written there survive session expiry, are still there in your next session, and are what the user sees when they browse the drive.",+ cwd+ ? '- Other conversations may use other folders on the same drive at the same time. Keep to this folder unless the user asks otherwise.'+ : '- Other conversations may use the same drive at the same time. Keep task-specific work in its own subfolder so unrelated tasks do not overwrite each other, and reuse what is already there when the user refers to earlier work.',+ '- Only files on the drive persist. The machine itself starts fresh every session: packages you install and anything outside the drive are gone next time, so reinstall what a task needs rather than assuming it is still there.',]- : [- '- Your working directory is a **persistent workspace**: files written there survive session expiry and are shared with the other conversation topics that use this workspace.',- '- Keep task-specific work in its own subdirectory so unrelated topics do not overwrite each other, and reuse what is already there when the user refers to earlier work.',- ];+ : workingDir+ ? [+ `- You start in \`${workingDir}\`, this environment's checkout on the machine's own disk. The session saves it continuously into ${cwd ? `\`${cwd}\`, ` : ''}the **environment directory** on the user's drive, so what you leave here is what you find in your next session, and it is what the user sees when they browse the drive.`,+ `- The drive is also mounted, and you may read from it, but that mounted path is the saved copy โ not where this session works. Do not move the task there.`,+ '- Packages installed by the environment are restored with it each session.',+ ]+ : [+ `- Your working directory is ${cwd ? `\`${cwd}\`, ` : ''}an **environment directory** on the user's drive: its files and the packages its setup installed survive session expiry and are restored in your next session.`,+ '- Other folders on the drive belong to other work. Do not write into them unless the user asks.',+ ];return {sandbox_session_files:@@ -263,17 +365,16 @@ export const formatSandboxStoragePromptVariables = ({// A model left to choose freely will sometimes clone or generate into a// scratch directory of its own โ reasonable in a disposable sandbox,// wrong here: the result is thrown away with the session and the user- // never sees it in the file browser, which reads this directory. Said- // once, positively, rather than as a list of directories to avoid.- '- Every call starts you in that directory, and it is where the work belongs: checkouts, generated files and notes written anywhere else โ `/root`, `/tmp`, a scratch directory of your own โ are lost with the session and never appear in the userโs file browser. Stay where you start; if a step genuinely needs scratch space, say where you put it.',- // Deliberately does NOT send installs to `/tmp`. The workspace is network+ // never sees it when browsing the drive, which reads this directory.+ // Said once, positively, rather than as a list of directories to avoid.+ '- Every call starts you in that directory, and it is where the work belongs: checkouts, generated files and notes written anywhere else โ `/root`, `/tmp`, a scratch directory of your own โ are lost with the session and never appear on the userโs drive. Stay where you start; if a step genuinely needs scratch space, say where you put it.',+ // Deliberately does NOT send installs to `/tmp`. The drive is network// storage โ an order of magnitude slower for the thousands of small files// a package install writes โ but the answer is to let them land where the// toolchain normally puts them, not to relocate them somewhere the- // platform treats as scratch. Naming a directory here would also outlive- // whatever the platform does with those files later.- '- The workspace 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. Install packages and build where the toolchain puts things by default, and keep the workspace for what is worth keeping.',- '- It has a storage quota, which covers what you leave in the workspace.',+ // 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. Install packages and build where the toolchain puts things by default, and keep the drive for what is worth keeping.',+ '- It has a storage quota, which covers what you leave on the drive.',].join('\n'),};};diff --git a/packages/const/src/apiKeyScope.test.ts b/packages/const/src/apiKeyScope.test.tsindex 0cf01d74dcd..8ea3d31165d 100644--- a/packages/const/src/apiKeyScope.test.ts+++ b/packages/const/src/apiKeyScope.test.ts@@ -182,6 +182,23 @@ describe('requiredApiKeyScopeForTrpc', () => {expect(requiredApiKeyScopeForTrpc('aiAgent.issueGatewayUserToken', 'query')).toEqual({blocked: true,});+ // the GitHub picker reads the connected account through its OAuth grant+ expect(requiredApiKeyScopeForTrpc('environment.listGithubRepositories', 'query')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('environment.listGithubBranches', 'query')).toEqual({+ blocked: true,+ });+ // publishing exposes what an environment's directories captured on the drive+ expect(requiredApiKeyScopeForTrpc('environment.setEnvironmentVisibility', 'mutation')).toEqual({+ blocked: true,+ });+ expect(requiredApiKeyScopeForTrpc('environment.updateEnvironment', 'mutation')).toEqual({+ scopes: ['agent:write'],+ });+ expect(requiredApiKeyScopeForTrpc('environment.listEnvironments', 'query')).toEqual({+ scopes: ['agent:read'],+ });// the rest of the market surface keeps its agent scopesexpect(requiredApiKeyScopeForTrpc('market.getAgentsByPlugin', 'query')).toEqual({scopes: ['agent:read'],diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 691f3a41fb1..fdbafce57ac 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -223,6 +223,10 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuledocument: rw('knowledge:read', 'knowledge:write'),documentComment: rw('knowledge:read', 'knowledge:write'),documentLike: rw('knowledge:read', 'knowledge:write'),+ // code environment definitions: the same agent domain as the project+ // environments they are bound to; what is built from them on the drive stays+ // behind `sandboxStorage`+ environment: rw('agent:read', 'agent:write'),expertise: rw('agent:read', 'agent:write'),// whole-account backup dump (settings incl. market tokens, providers, agents)exporter: 'blocked',@@ -452,6 +456,15 @@ export const TRPC_BLOCKED_PATH_PREFIXES: string[] = ['market.creds.',// marketplace OIDC auth flows carry tokens'market.oidc.',+ // the GitHub picker reads the user's connected GitHub account (private+ // repositories and branches) through their OAuth grant โ connector data+ // outside the agent domain the rest of `environment` belongs to+ 'environment.listGithub',+ // publishing decides who else can reach what an environment's directories+ // captured on the drive (a private one's left on the public drive stops+ // being hidden); that is drive state, which stays behind `sandboxStorage`+ // and so out of a restricted key's reach+ 'environment.setEnvironmentVisibility',];export type TrpcScopeDecision = { scopes: ApiKeyScope[] } | { open: true } | { blocked: true };diff --git a/packages/database/src/models/__tests__/environment.visibility.test.ts b/packages/database/src/models/__tests__/environment.visibility.test.tsindex 41869f5b29f..2f2c6932f3d 100644--- a/packages/database/src/models/__tests__/environment.visibility.test.ts+++ b/packages/database/src/models/__tests__/environment.visibility.test.ts@@ -191,6 +191,60 @@ describe('environment visibility', () => {await expect(asPublicAgent.findById(instance.id)).resolves.toMatchObject({ id: instance.id });});+ // Every environment directory on a drive is read-only to its file routes,+ // whoever may run in it, and a private one left on a public drive is hidden+ // from everyone โ owner included โ until it is rebuilt on a personal drive.+ it('lists every instance folder on a storage, marking the private ones', async () => {+ const binding = {+ kind: 'sandbox' as const,+ provider: 'test-provider',+ providerResourceId: 'workspace',+ providerScope: 'test-scope',+ };+ const privateEnv = await owner.create({ name: 'Private' });+ const publishedEnv = await owner.create({ name: 'Published', visibility: 'public' });+ const memberEnv = await member.create({ name: 'Mine' });+ const hidden = await ownerInstances.create({+ ...binding,+ environmentId: privateEnv.id,+ name: 'secret',+ workingDirectory: 'secret',+ });+ const shared = await ownerInstances.create({+ ...binding,+ environmentId: publishedEnv.id,+ name: 'shared',+ workingDirectory: 'shared',+ });+ const own = await memberInstances.create({+ ...binding,+ environmentId: memberEnv.id,+ name: 'mine',+ workingDirectory: 'mine',+ });+ // Another storage entirely: never part of this drive's answer.+ await ownerInstances.create({+ ...binding,+ environmentId: privateEnv.id,+ name: 'elsewhere',+ providerScope: 'other-scope',+ workingDirectory: 'elsewhere',+ });++ const directories = await memberInstances.listStorageDirectories(binding);++ expect(+ directories.sort((a, b) => a.workingDirectory.localeCompare(b.workingDirectory)),+ ).toEqual([+ { id: own!.id, isPrivate: true, workingDirectory: 'mine' },+ { id: hidden!.id, isPrivate: true, workingDirectory: 'secret' },+ { id: shared!.id, isPrivate: false, workingDirectory: 'shared' },+ ]);+ await expect(+ ownerInstances.listStorageDirectories({ ...binding, providerScope: 'empty-scope' }),+ ).resolves.toEqual([]);+ });+// The unique index only catches the identical path. A folder inside another// instance's, or around one, would put two captured states on one tree โ// and a colleague's private instance occupies its folder just the same.diff --git a/packages/database/src/models/environmentInstance.ts b/packages/database/src/models/environmentInstance.tsindex 8434931dbf2..36c9611c533 100644--- a/packages/database/src/models/environmentInstance.ts+++ b/packages/database/src/models/environmentInstance.ts@@ -162,16 +162,65 @@ export class EnvironmentInstanceModel {*/findByWorkingDirectory = async (workingDirectory: string,+ /** The storage to look on; every storage when omitted. */+ providerScope?: string,): Promise<EnvironmentInstanceItem | undefined> => {const [row] = await this.db.select().from(environmentInstances)- .where(and(eq(environmentInstances.workingDirectory, workingDirectory), this.visible()))+ .where(+ and(+ eq(environmentInstances.workingDirectory, workingDirectory),+ providerScope ? eq(environmentInstances.providerScope, providerScope) : undefined,+ this.visible(),+ ),+ ).limit(1);return row;};+ /**+ * Every instance directory on one storage, whoever's environment it belongs+ * to, with whether that environment is a workspace member's private one.+ *+ * Not filtered by visibility, because the question is about the folders+ * rather than the rows: every environment directory on a drive is read-only+ * to its file routes, whoever may run in it. A private one on a workspace's+ * public drive is a leftover from before members had drives of their own โ+ * its home directory can hold its owner's credentials, so it stays hidden+ * from everyone until it is rebuilt on its owner's personal drive. Only the+ * id and the directory leave โ nothing a hidden row says about itself.+ */+ listStorageDirectories = async (+ binding: Pick<EnvironmentInstanceBinding, 'provider' | 'providerResourceId' | 'providerScope'>,+ ): Promise<{ id: string; isPrivate: boolean; workingDirectory: string }[]> => {+ const rows = await this.db+ .select({+ environmentVisibility: environments.visibility,+ environmentWorkspaceId: environments.workspaceId,+ id: environmentInstances.id,+ workingDirectory: environmentInstances.workingDirectory,+ })+ .from(environmentInstances)+ .innerJoin(environments, eq(environments.id, environmentInstances.environmentId))+ .where(+ and(+ eq(environmentInstances.kind, 'sandbox'),+ isNull(environmentInstances.deviceId),+ eq(environmentInstances.provider, binding.provider ?? ''),+ eq(environmentInstances.providerScope, binding.providerScope ?? ''),+ eq(environmentInstances.providerResourceId, binding.providerResourceId ?? ''),+ ),+ );++ return rows.map(({ environmentVisibility, environmentWorkspaceId, id, workingDirectory }) => ({+ id,+ isPrivate: !!environmentWorkspaceId && environmentVisibility === 'private',+ workingDirectory,+ }));+ };+/*** One device's instance at a path, by the pair the schema makes unique.*diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 9c0be01e9e3..ca41fd1001c 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -4030,4 +4030,42 @@ export default {'userFeedbackCard.count_other': '{{count}} comments','userFeedbackCard.title': 'User feedback','you': 'You',+ 'sandboxDrive.pickerTitle': 'Working directory',+ 'sandboxDrive.pickerInfoTooltip':+ 'Pick a folder on your drive and its files are kept across conversations. Without one, the sandbox is temporary.',+ 'sandboxDrive.manageEnvironments': 'Environments',+ 'sandboxEnvironment.title': 'Environment',+ 'sandboxEnvironment.hint':+ 'Cloned and set up once in the working directory before the first command. A folder that already has files is left as it is.',+ 'sandboxEnvironment.none': 'No environment',+ 'sandboxEnvironment.noneDesc': 'Start from an empty working directory',+ 'sandboxEnvironment.empty': 'No environments yet. Create one in Environments.',+ 'sandboxEnvironment.missing': 'Environment unavailable',+ 'sandboxEnvironment.loading': 'Loading environmentโฆ',+ 'sandboxEnvironment.loadFailed': "Couldn't load environments",+ 'sandboxEnvironment.retry': 'Retry',+ 'sandboxEnvironment.saveFailed': 'Could not change the environment. Try again.',+ 'sandboxDrive.root': 'Drive root',+ 'sandboxDrive.building': '{{name}} ยท building',+ 'sandboxDrive.browse': 'Choose a folder on your driveโฆ',+ 'sandboxDrive.browseOther': 'Choose another folderโฆ',+ 'sandboxDrive.browseDesc': 'Files in it are kept across conversations',+ 'sandboxDrive.folderDesc': 'Folder on your drive ยท {{path}}',+ 'sandboxDrive.environmentDesc': 'Environment directory ยท installed packages are kept too',+ 'sandboxDrive.environmentBuildingDesc':+ 'Environment directory ยท building, usable once it finishes',+ 'sandboxDrive.upsell': 'Keep files on a drive',+ 'sandboxDrive.fallback.directoryMissing':+ 'This folder no longer exists on the drive. Runs use a temporary sandbox until you pick another folder.',+ 'sandboxDrive.fallback.instanceUnavailable':+ 'This environment directory canโt be used here any more. Runs use a temporary sandbox until you pick another one.',+ 'sandboxDrive.fallback.rootNotAllowed':+ 'The public driveโs root cannot be a working folder. This run will use a temporary sandbox; pick a folder.',+ 'sandboxDrive.fallbackChip.directoryMissing': 'Folder no longer exists',+ 'sandboxDrive.fallbackChip.instanceUnavailable': 'Environment unavailable',+ 'sandboxDrive.fallbackChip.rootNotAllowed': 'Pick a folder',+ 'sandboxDrive.fallback.instanceRebuildRequired':+ 'This private environment directory is still on the public drive and needs to be rebuilt on your personal drive. This run will use a temporary sandbox.',+ 'sandboxDrive.fallbackChip.instanceRebuildRequired': 'Rebuild on personal drive',+ 'sandboxDrive.folderOnDriveDesc': '{{drive}} ยท {{path}}',};diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 59b9dacc696..97c331a2402 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -482,7 +482,7 @@ export default {'visibilityConfirm.publish.itemReversible':'You can switch it back to private later from the same menu','visibilityConfirm.publish.itemCapturedState':- 'Members can run its copies and reach everything it has captured โ files, CLI logins, your signed-in identity',+ 'Copies made before environments became one-time setups keep what they captured โ files, CLI logins, your signed-in identity โ and members can reach them','visibilityConfirm.publish.itemLoaded':'After switching back, content others have already loaded canโt be pulled back','retry': 'Retry',diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 46037cd74dc..0ca0de5e0d6 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -3,6 +3,9 @@ export default {'workingDirectory.newFolderInvalidWindowsName':'Use a Windows folder name without reserved names (such as CON), special characters (< > : " / \\ | ? *), control characters, or a trailing space or period.','workingDirectory.addFolderFailed': 'Could not add this folder. Please try again.',+ 'workingDirectory.useFolderFailed': 'Couldnโt use this folder.',+ 'workingDirectory.errorDetailHide': 'Hide details',+ 'workingDirectory.errorDetailShow': 'Show details','workingDirectory.browseDescription': 'Choose a folder on the connected device.','workingDirectory.browseFolders': 'Browse folders','workingDirectory.enterPathManually': 'Enter path manually',@@ -136,4 +139,43 @@ export default {'workingDirectory.worktreesEmpty': 'No worktrees found','workingDirectory.worktreesHeading': 'Worktrees','workingDirectory.worktreesNoMatch': 'No matching worktrees',+ 'workingDirectory.environment.label': 'Code environment',+ 'workingDirectory.environment.none': 'No environment',+ 'workingDirectory.drive.pickFailed': 'Could not switch to this folder. Try again.',+ 'workingDirectory.drive.title': 'Choose a folder on your drive',+ 'workingDirectory.drive.rootNotAllowed': 'The driveโs root canโt be a working folder',+ 'workingDirectory.drive.browseDescription': 'Choose a folder on your drive.',+ 'workingDirectory.drive.gitRepository': 'Git',+ 'workingDirectory.drive.pickFolderFirst': 'Choose a folder first',+ 'workingDirectory.drive.environmentBadge': 'Environment',+ 'workingDirectory.drive.state.building': 'Building',+ 'workingDirectory.drive.state.failed': 'Build failed',+ 'workingDirectory.drive.state.inUse': 'In use',+ 'workingDirectory.drive.inUseDesc': 'Another conversation is using this environment directory',+ 'workingDirectory.drive.buildingDesc':+ 'This environment directory is still building. It can be picked once the build finishes',+ 'workingDirectory.drive.privateBlocked': 'Private environment โ a shared agent canโt use it',+ 'workingDirectory.drive.createCopy': 'Create copy',+ 'workingDirectory.drive.initializeWith': 'Initialize with',+ 'workingDirectory.drive.initializeHint':+ 'The folder is created at the drive root and set up from this environment: the repository is cloned and its setup runs.',+ 'workingDirectory.drive.rename': 'Rename',+ 'workingDirectory.drive.renameTitle': 'Rename folder',+ 'workingDirectory.drive.renameFailed': 'The folder couldnโt be renamed',+ 'workingDirectory.drive.delete': 'Delete',+ 'workingDirectory.drive.moreActions': 'More actions',+ 'workingDirectory.drive.deleteConfirmTitle': 'Delete โ{{name}}โ?',+ 'workingDirectory.drive.deleteConfirmContent':+ 'Everything in this folder is deleted from the drive, for everyone who can see it. Conversations working in it fall back to a temporary sandbox.',+ 'workingDirectory.drive.actionFailed': 'That didnโt work. Try again.',+ 'workingDirectory.drive.folderNotEmpty':+ 'This folder already has files in it. Only a new or empty folder can be initialized from an environment.',+ 'workingDirectory.drive.folderTaken': 'An environment directory with this name already exists.',+ 'workingDirectory.drive.foldersLoadFailed':+ 'Could not load this folder on your drive. Retry, or go back to the driveโs top level.',+ 'workingDirectory.drive.readOnly': 'Environment directories are read-only here.',+ 'workingDirectory.drive.drives.public': 'Public drive',+ 'workingDirectory.drive.drives.personal': 'Personal drive',+ 'workingDirectory.drive.rebuildInPersonal':+ 'Private environment folders ({{names}}) are hidden here. Their owners can rebuild them on their personal drives.',};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 126754a5960..44019768f11 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -3117,6 +3117,8 @@ When I am ___, I need ___'This invitation has expired. Ask the team owner to send a new one.','workspace.invitePage.expiredTitle': 'Invitation Expired','workspace.invitePage.expiresLabel': 'Expires',+ 'workspace.invitePage.driveCleanupInProgress':+ 'Your previous personal drive in this workspace is being cleaned up. Try again in a few minutes.','workspace.invitePage.featureNotEnabledNotice':'Workspaces are in a limited beta and not open to new members right now. Please try again later, or ask the person who invited you to reach out to support.','workspace.invitePage.goHome': 'Go Home',@@ -4219,7 +4221,7 @@ When I am ___, I need ___'tools.title': 'Skills','tab.environments': 'Environments','environments.desc':- 'What a sandbox run needs around it: a repository, its setup, its variables. Each copy built from one keeps its own files between sessions.',+ "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.create': 'New environment','environments.cancel': 'Cancel','environments.createFailed': 'Could not create the environment',@@ -4235,34 +4237,36 @@ When I am ___, I need ___'environments.remove': 'Delete environment','environments.removeConfirmTitle': 'Delete environment {{name}}?','environments.removeConfirmContent':- "Its specification, variables, its copy's folder and the saved snapshot go with it, and cannot be recovered.",+ 'Its specification and variables are deleted and cannot be recovered. Folders it initialized keep their files; copies built by an earlier version are removed with it.','environments.storage.used': '{{used}} of {{total}}','environments.storage.unmeasured': 'Storage not measured yet ยท {{total}} available','environments.storage.measuredAt': 'Measured {{time}}. Refresh to measure again.','environments.storage.over':'Over the storage limit. Saving a file is refused until you delete something.','environments.duplicateName': 'You already have an environment with this name',+ 'environments.inProject':+ 'A project still uses this environment โ remove it from the project first','environments.hasInstances': 'Remove its other copies first','environments.loadFailed.title': 'Could not check your plan','environments.loadFailed.desc':'We could not reach the service that says whether this account has a persistent workspace. Nothing is wrong with your environments.','environments.loadFailed.retry': 'Try again',- 'environments.unavailable.title': 'Persistent sandbox is not available here',+ 'environments.unavailable.title': 'Drive storage is not available here','environments.unavailable.desc':- 'Environments describe a persistent cloud workspace, and this deployment does not provide one.',- 'environments.upgrade.title': 'Upgrade to Pro to unlock sandbox environments',+ 'Drives are persistent cloud storage for sandbox runs, and this deployment does not provide them.',+ 'environments.upgrade.title': 'Upgrade to Pro to unlock drive storage','environments.upgrade.desc':- 'Give cloud-sandbox runs a persistent working directory. An environment describes what the sandbox needs โ repositories, setup, variables โ and its copies keep everything between sessions.',+ 'Give cloud-sandbox runs a drive that outlives them: conversations working in a drive folder keep their files after the sandbox is recycled.','environments.upgrade.cta': 'Upgrade to Pro',- 'environments.upgrade.benefits.environments.title': 'Sandbox setup written once',+ 'environments.upgrade.benefits.environments.title': 'A public drive and your own','environments.upgrade.benefits.environments.desc':- 'Repositories, setup command and variables live in the environment; every sandbox built from it starts ready.',+ 'In a workspace every member shares the public drive, and each member also has a personal drive only they can reach.','environments.upgrade.benefits.persist.title': 'Files survive the sandbox','environments.upgrade.benefits.persist.desc':- 'The working directory is kept when the sandbox is recycled; the next run continues where the last stopped.',- 'environments.upgrade.benefits.instances.title': 'One copy per task',+ 'The folder is kept when the sandbox is recycled; the next run continues where the last one stopped.',+ 'environments.upgrade.benefits.instances.title': 'Folders initialized from code environments','environments.upgrade.benefits.instances.desc':- 'Parallel conversations each run in their own copy of the environment, so nothing overwrites anything else.',+ 'When creating a folder, pick a code environment to clone its repository and install what it needs.','environments.github.refreshFailed':'Could not refresh GitHub repositories. Showing the previous list. Try again.','environments.github.loadFailed': 'Could not load GitHub repositories. Try again.',@@ -4284,7 +4288,7 @@ When I am ___, I need ___'environments.form.descriptionPlaceholder': 'What this environment is for','environments.form.sources': 'Source code','environments.form.sourcesHint':- 'Cloned over HTTPS before anything else runs. Private repositories are not supported yet โ a specification holds no credentials.',+ 'Cloned over HTTPS before anything else runs. A private repository clones through the GitHub App installation that grants it; the environment itself stores no credentials.','environments.form.ref': 'Branch or tag','environments.form.refDefault': 'Repository default branch','environments.form.path': 'Folder',@@ -4295,7 +4299,7 @@ When I am ___, I need ___'Runs once in the checkout, with network access, before the conversation starts.','environments.form.env': 'Environment variables','environments.form.envHint':- 'Non-secret values only โ these are stored as plain text and copied into every copy of this environment.',+ 'Non-secret values only โ stored as plain text and exported while the repository is cloned and the setup command runs.','environments.form.addEnv': 'New variable','environments.form.envCount_one': '{{count}} variable','environments.form.envCount_other': '{{count}} variables',@@ -4321,6 +4325,10 @@ When I am ___, I need ___'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','environments.instances.copyTitle': 'Duplicate {{name}}','environments.instances.copyFailed': 'Could not duplicate this copy',@@ -4332,7 +4340,7 @@ When I am ___, I need ___'This copy is being built, so it cannot be duplicated until the build finishes','environments.instances.title': 'Copies','environments.instances.desc':- 'A copy is a working copy of this environment, with its own folder and its own installed packages. Conversations run inside a copy, and several can run side by side without touching each other.',+ 'Folders on your drive initialized from this environment. Each keeps its own files and installed packages, so conversations in different folders never overwrite each other.','environments.instances.empty': 'No copies yet','environments.instances.emptyHint':'Create one, then pick it under "Working Directory" in the chat input.',@@ -4406,10 +4414,11 @@ When I am ___, I need ___'environments.sessions.reason.build_failed': 'Build failed','environments.sessions.reason.build_timeout': 'Build timed out','environments.sessions.reason.build_gone': 'Build interrupted',- 'environments.form.desc':- 'What a copy is built from โ where the code comes from and what makes it usable.',+ 'environments.form.desc': 'Where the code comes from and what makes it usable.','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.refresh': 'Refresh','environments.emptyPublished': 'Nothing published to this workspace yet','environments.visibility.tabs.workspace': 'Workspace',@@ -4421,7 +4430,7 @@ When I am ___, I need ___'environments.visibility.publicTag': 'Published','environments.visibility.changeFailed': "Could not change this environment's visibility",'environments.visibility.readonlyHint':- 'Published to this workspace by its creator: you can run in this environment, but only they can change what it builds.',+ 'Published to this workspace by its creator: you can initialize with this environment, but only they can change it.','environments.files.browse': 'Browse files','environments.files.back': 'Back','environments.files.empty': 'This directory is empty',@@ -4492,4 +4501,96 @@ When I am ___, I need ___'environments.files.openHint': 'Double-click a folder to open it, or a file to view it','environments.files.unusedInstance':'Nothing here yet. The code appears once the copy is built or a conversation runs in it.',+ 'environments.files.folderNotEmpty':+ 'This folder already has files in it. Only a new or empty folder can be initialized from an environment.',+ 'environments.files.folderTaken': 'An environment directory with this name already exists.',+ 'environments.files.readOnly':+ 'Environment directories are read-only: only their own sessions write to them.',+ 'environments.files.notFound': 'That folder doesnโt exist.',+ 'tab.drive': 'Storage',+ 'drive.tabs.public': 'Public drive',+ 'drive.tabs.personal': 'Personal drive',+ 'drive.scope.public': 'Visible to all members',+ 'drive.scope.personal': 'Only you',+ 'drive.usage.title': 'Storage usage',+ 'drive.usage.poolTitle': 'Workspace storage pool',+ 'drive.usage.used': '{{used}} of {{total}} used',+ 'drive.usage.unmeasured': 'Not measured yet ยท {{total}} in total',+ 'drive.usage.unmeasuredShort': 'Not measured yet',+ 'drive.usage.remaining': '{{size}} left ยท {{percent}}% used',+ 'drive.usage.overBy': '{{size}} over the quota',+ 'drive.usage.others': 'Other members',+ 'drive.usage.refresh': 'Measure again',+ 'drive.usage.membersTitle': "Members' personal drives",+ 'drive.usage.membersHint': 'Usage only โ contents stay private',+ 'drive.usage.memberUnmeasured': 'Not measured',+ 'drive.usage.showAllMembers': 'Show all {{count}} members',+ 'drive.usage.showFewerMembers': 'Show fewer',+ 'drive.usage.over':+ 'Storage is over quota. Free up space or upgrade before more files can be saved.',+ 'drive.usage.enableOverage': 'Turn on pay-as-you-go',+ 'drive.usage.overageModalTitle': 'Keep saving past the quota',+ 'drive.usage.overageAskAdmin': 'Ask a workspace admin to turn on pay-as-you-go to keep saving.',+ 'drive.usage.overBilled':+ 'Over the quota. Files keep saving, and the extra is billed as pay-as-you-go overage.',+ 'drive.retained.title': "Departed members' personal drives",+ 'drive.retained.hint':+ 'Kept for 30 days after a member leaves, then deleted automatically. They count toward the workspace pool until then. Only the amount is shown, never the files.',+ 'drive.retained.expiresIn': 'Deleted in {{count}} days',+ 'drive.retained.expiresToday': 'Deleted today',+ 'drive.retained.lastError': 'Last attempt failed: {{error}}',+ 'drive.retained.move': 'Move to public drive',+ 'drive.retained.moveConfirm.title': "Move {{name}}'s drive to the public drive?",+ 'drive.retained.moveConfirm.desc':+ 'Its files are moved into departed-members on the public drive, where every member can open them, and the personal drive is emptied. Only text files up to 1 MB can be moved; a drive holding anything else is left untouched.',+ 'drive.retained.moved': 'Moved to {{path}} on the public drive',+ 'drive.retained.delete': 'Delete',+ 'drive.retained.deleteConfirm.title': "Delete {{name}}'s personal drive?",+ 'drive.retained.deleteConfirm.desc': 'Everything on it is deleted and cannot be recovered.',+ 'drive.retained.deleted': 'Drive deleted',+ 'drive.usage.manage': 'Manage in Storage',+ 'drive.explorer.newFolder': 'New folder',+ 'drive.explorer.columns.name': 'Name',+ 'drive.explorer.columns.modified': 'Date modified',+ 'drive.explorer.columns.size': 'Size',+ 'drive.explorer.columns.kind': 'Kind',+ 'drive.explorer.kind.folder': 'Folder',+ 'drive.explorer.kind.gitRepository': 'Git repository',+ 'drive.explorer.kind.file': 'File',+ 'drive.explorer.kind.fileWithExtension': '{{extension}} file',+ 'drive.explorer.rename': 'Rename',+ 'drive.explorer.delete': 'Delete',+ 'drive.explorer.moreActions': 'More actions',+ 'drive.explorer.deleteTitle': 'Delete โ{{name}}โ?',+ 'drive.explorer.deleteFolderContent':+ 'The folder and everything in it are removed from the drive. Conversations working in it switch to a temporary sandbox.',+ 'drive.explorer.deleteFileContent': 'The file is removed from the drive.',+ 'drive.explorer.readOnly': 'Environment directories are read-only',+ 'drive.explorer.readOnlyHint':+ 'Only its own sandbox sessions write to an environment directory, so you can browse it here but not change it.',+ 'drive.explorer.empty': 'This folder is empty',+ 'drive.explorer.emptyRoot.public':+ 'No folders on the public drive yet. Create one to work in it with your team.',+ 'drive.explorer.emptyRoot.personal':+ 'Your drive is empty. Create a folder, then pick it as a conversationโs working folder.',+ 'drive.explorer.loadFailed': 'Could not load this folder.',+ 'drive.loadFailed': 'Could not load storage. Check your connection and try again.',+ 'environments.instances.needsDrive':+ 'Copies are folders on a drive, and this account has no drive yet.',+ 'environments.instances.openDriveSettings': 'Go to Storage settings',+ 'environments.instances.rebuildPersonalDesc':+ '{{names}} is still on the public drive and is hidden. Private environments now keep their folders on your personal drive.',+ 'environments.instances.rebuildPersonal': 'Rebuild on personal drive',+ 'environments.instances.publishPublic': 'Initialize on the public drive',+ 'environments.instances.publishPublicDesc':+ 'Published to the workspace, but its folders are on your personal drive, where members cannot reach them. Members can run it once it has a folder on the public drive.',+ 'environments.instances.publishPublicFailed': 'Could not create a copy on the public drive',+ 'environments.instances.publishPublicStarted': 'Building a copy on the public drive',+ 'environments.instances.rebuildPersonalStarted': 'Building a new copy on your personal drive',+ 'environments.instances.rebuildPersonalFailed':+ 'Could not create the copy on your personal drive',+ 'environments.instances.rebuildPersonalRequired':+ 'This directory is on the public drive. Rebuild it on your personal drive first.',+ 'environments.instances.rebuildPersonalTag': 'Needs rebuild on personal drive',+ 'environments.instances.rebuildPersonalTagHint': 'Hidden on the public drive and no longer used.',};diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex 960197bb2e4..a2a114a529a 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -808,5 +808,6 @@ export default {'usage.storage.embeddings.used': 'Vector Storage','usage.storage.file.used': 'File Usage','usage.storage.sandboxStorage.used': 'Sandbox Storage',+ 'usage.storage.sandboxStorage.pool': 'Sandbox drives (workspace pool)','usage.remaining': 'Remaining',};diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex 96e05c6aac9..f38c81ce9e0 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -417,7 +417,7 @@ describe('which tool counts as reaching the sandbox', () => {resolveSandboxPersistence: async () => persistence,});- expect(facts.variables.sandbox_workspace).toContain('persistent workspace');+ expect(facts.variables.sandbox_workspace).toContain('environment directory');expect(facts.variables.sandbox_workspace).toContain('`lobehub-dev`');});@@ -426,7 +426,16 @@ describe('which tool counts as reaching the sandbox', () => {resolveSandboxPersistence: async () => persistence,});- expect(facts.variables.sandbox_workspace).toContain('persistent workspace');+ expect(facts.variables.sandbox_workspace).toContain('environment directory');+ });++ it('describes a drive folder as a folder on the network drive', async () => {+ const facts = await gatherContextFacts(request({ enabledToolIds: ['lobe-cloud-sandbox'] }), {+ resolveSandboxPersistence: async () => ({ cwd: 'reports', mode: 'drive' as const }),+ });++ expect(facts.variables.sandbox_workspace).toContain('`reports`, a folder on the user');+ expect(facts.variables.sandbox_session_files).toContain('persist across sessions');});it('asks for nothing when no tool can run a command in the sandbox', async () => {diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex ff9582ac8ff..c9d2f2fe083 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -5,6 +5,7 @@ import {CloudSandboxIdentifier,formatSandboxStoragePromptVariables,formatUploadedFilesPrompt,+ isPersistentSandboxMode,} from '@lobechat/builtin-tool-cloud-sandbox';import {type ComposioServiceSummary,@@ -537,7 +538,7 @@ 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.- ...(sandboxPersistence?.mode === 'persistent'+ ...(isPersistentSandboxMode(sandboxPersistence?.mode)? formatSandboxStoragePromptVariables(sandboxPersistence): {}),topic_id: request.topicId ?? '',diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex 149657206bf..a82e99d4852 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -163,13 +163,14 @@ export interface ContextFactProviders {/** Builtin tool identifiers the user uninstalled in the current scope. */listUninstalledBuiltinIds?: () => Promise<Iterable<string> | undefined>;/**- * Whether this run's cloud sandbox keeps its working directory, and which- * subdirectory it works in. Resolved by the host because it depends on a+ * Whether this run's cloud sandbox keeps its working directory โ a folder on+ * the drive (`drive`) or an environment directory (`persistent`) โ and+ * which folder it works in. Resolved by the host because it depends on a* signed entitlement the browser cannot see; absent means the sandbox is* ephemeral, which is what every run without one gets.*/resolveSandboxPersistence?: () => Promise<- { cwd?: string; mode: 'ephemeral' | 'persistent'; workingDir?: string } | undefined+ { cwd?: string; mode: 'drive' | 'ephemeral' | 'persistent'; workingDir?: string } | undefined>;}diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 4d1bb2c92a4..3f3b0f2292c 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -23,14 +23,19 @@ export * from './modelFacts';export const initialTopicMetadataSchema = z.object({repos: z.array(z.string()).optional(),/**- * Cloud-sandbox instance the composer chose before any topic existed. The- * choice is made on a conversation that has nothing to write to yet, so it- * travels with the first send instead โ the server cannot read the client's- * pending selection, and without this the new topic would be born unbound and- * silently run at the workspace root.- */+ * Cloud-sandbox placement the composer chose before any topic existed โ an+ * instance, or a folder on the drive. The choice is made on a conversation+ * that has nothing to write to yet, so it travels with the first send+ * instead โ the server cannot read the client's pending selection, and+ * without this the new topic would be born unbound and silently run in a+ * temporary sandbox.+ */+ /** Which workspace drive the placement is on; see `ChatTopicMetadata.sandboxDrive`. */+ sandboxDrive: z.enum(['personal', 'public']).optional(),+ /** The environment to initialize the sandbox from; see `ChatTopicMetadata.sandboxEnvironmentId`. */+ sandboxEnvironmentId: z.string().max(255).optional(),sandboxInstanceId: z.string().optional(),- sandboxMode: z.enum(['ephemeral', 'persistent']).optional(),+ sandboxWorkingDirectory: z.string().max(1024).optional(),workingDirectory: z.string().optional(),workingDirectoryConfig: workingDirConfigSchema.optional(),});diff --git a/packages/types/src/agentExecution/initialTopicMetadata.test.ts b/packages/types/src/agentExecution/initialTopicMetadata.test.tsindex 09a792a4615..73642ae3e14 100644--- a/packages/types/src/agentExecution/initialTopicMetadata.test.ts+++ b/packages/types/src/agentExecution/initialTopicMetadata.test.ts@@ -11,17 +11,13 @@ describe('initialTopicMetadataSchema', () => {const metadata = {repos: ['lobehub/lobehub'],sandboxInstanceId: 'a2c1d0e4-0000-4000-8000-000000000000',- sandboxMode: 'persistent' as const,+ sandboxWorkingDirectory: 'reports',workingDirectory: 'projects/atlas',};expect(initialTopicMetadataSchema.parse(metadata)).toEqual(metadata);});- it('rejects a sandbox mode outside the pair', () => {- expect(initialTopicMetadataSchema.safeParse({ sandboxMode: 'forever' }).success).toBe(false);- });-it('accepts an empty patch โ a conversation may start with none of this', () => {expect(initialTopicMetadataSchema.parse({})).toEqual({});});diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex baf0d4cbd63..32e8cd9bccc 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -157,6 +157,11 @@ export interface WorkingDirGitState {}export interface WorkingDirConfig {+ /**+ * The code environment picked with this folder. Metadata only on a device:+ * nothing clones or bootstraps there; the association is kept for later.+ */+ environmentId?: string;git?: WorkingDirGitState;path: string;repoType?: WorkingDirRepoType;@@ -179,42 +184,7 @@ export const getWorkingDirEffectivePath = (return entry.git?.activeWorktree || entry.path;};-/**- * Derive the target directory for a new worktree: a sibling of the source repo- * named `<repoName>-<branch>` (e.g. `/code/lobehub` + `feat/x` โ- * `/code/lobehub-feat-x`), matching the convention agents already use for their- * linked worktrees. Preserves the source path's separator so Windows paths stay- * intact, and folds ref-illegal characters in the branch to `-` for the folder.- *- * Shared by the renderer (path preview + local IPC call) and the server- * (`device.addGitWorktree`), which re-derives the target from the trusted- * `path` + `branch` rather than trusting a client-supplied absolute path โ so a- * crafted web request can't ask a remote device to check out at an arbitrary- * location. Both callers must derive identically, hence the single source here.- */-const isSep = (ch: string): boolean => ch === '/' || ch === '\\';--export const deriveWorktreePath = (sourcePath: string, branch: string): string => {- const sep = sourcePath.includes('\\') && !sourcePath.includes('/') ? '\\' : '/';- // Strip trailing path separators, then the leading/trailing '-' of the folded- // branch, both with linear scans rather than anchored /[โฆ]+$/ quantifiers โ- // those are polynomial-ReDoS shapes (flagged by CodeQL) on a long crafted- // input, and this runs per request on the server with untrusted path/branch.- let te = sourcePath.length;- while (te > 0 && isSep(sourcePath[te - 1])) te -= 1;- const trimmed = sourcePath.slice(0, te);- const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));- const parent = cut >= 0 ? trimmed.slice(0, cut) : '';- const repoName = (cut >= 0 ? trimmed.slice(cut + 1) : trimmed) || 'repo';- const folded = branch.trim().replaceAll(/[\s~^:?*[\]\\/]+/g, '-');- let start = 0;- let end = folded.length;- while (start < end && folded[start] === '-') start += 1;- while (end > start && folded[end - 1] === '-') end -= 1;- const suffix = folded.slice(start, end);- const folder = suffix ? `${repoName}-${suffix}` : repoName;- return parent ? `${parent}${sep}${folder}` : folder;-};+export { deriveWorktreePath } from './worktreePath';export interface WorkingDirEntry extends WorkingDirConfig {/**@@ -982,6 +952,7 @@ const gitLinkedPullRequestSchema = z.object({});export const workingDirConfigSchema = z.object({+ environmentId: z.string().max(255).optional(),git: z.object({activeWorktree: z.string().optional(),diff --git a/packages/types/src/environment/index.test.ts b/packages/types/src/environment/index.test.tsindex 60eb9497a6a..6e38e792d21 100644--- a/packages/types/src/environment/index.test.ts+++ b/packages/types/src/environment/index.test.ts@@ -1,42 +1,6 @@import { describe, expect, it } from 'vitest';-import { type EnvironmentConfiguration, environmentKind, toExecutionConfiguration } from './index';--describe('environmentKind', () => {- it('uses the stored kind when there is one, whatever else is configured', () => {- expect(- environmentKind({- configuration: {- kind: 'files',- sources: [{ kind: 'git', url: 'https://github.com/a/b' }],- },- }),- ).toBe('files');- expect(environmentKind({ configuration: { kind: 'code' } })).toBe('code');- });-- it('reads an environment with a repository and no stored kind as code', () => {- expect(- environmentKind({- configuration: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },- }),- ).toBe('code');- });-- it('reads an environment with a setup command and no stored kind as code', () => {- expect(environmentKind({ configuration: { bootstrapCommand: 'pnpm install' } })).toBe('code');- });-- it('reads an environment with neither as files', () => {- expect(environmentKind({ configuration: {} })).toBe('files');- expect(environmentKind({ configuration: { bootstrapCommand: ' ', sources: [] } })).toBe(- 'files',- );- expect(environmentKind({ configuration: { env: { REGION: 'us' } } })).toBe('files');- expect(environmentKind({ configuration: null })).toBe('files');- expect(environmentKind(undefined)).toBe('files');- });-});+import { type EnvironmentConfiguration, toExecutionConfiguration } from './index';describe('toExecutionConfiguration', () => {const before: EnvironmentConfiguration = {@@ -50,7 +14,7 @@ describe('toExecutionConfiguration', () => {it('sends the same definition whether or not a kind was stored', () => {expect(toExecutionConfiguration({ ...before, kind: 'code' })).toEqual(before);- expect(toExecutionConfiguration({ kind: 'files' })).toEqual({});+ expect(toExecutionConfiguration({ kind: 'code' })).toEqual({});});it('leaves a definition without a kind as it was', () => {diff --git a/packages/types/src/environment/index.ts b/packages/types/src/environment/index.tsindex ad1a3fcc9b9..93152afa850 100644--- a/packages/types/src/environment/index.ts+++ b/packages/types/src/environment/index.ts@@ -19,14 +19,14 @@ export interface EnvironmentResourceRequirements {}/**- * What an environment is for, as the person who made it chose it.- *- * `files` is a folder someone hands files to for an agent to work on; `code`- * checks out a repository and runs setup. Presentation only: it decides which- * form and which entries the product shows, and never reaches the execution- * plane โ see {@link environmentKind} for how an environment without one reads.+ * What an environment is for. New environments are `code` โ checking out a+ * repository and running setup โ since a folder someone hands files to is a+ * folder on the drive, not an environment. `files` is what the previous+ * release stored for such an environment; rows keep it and an edit sends it+ * back, so it stays a value the type admits. Presentation only: it never+ * reaches the execution plane.*/-export type EnvironmentKind = 'files' | 'code';+export type EnvironmentKind = 'code' | 'files';/** Portable definition, shared by device, sandbox and cluster instances. No credentials. */export interface EnvironmentConfiguration {@@ -59,8 +59,7 @@ export interface EnvironmentConfiguration {*/internetAccess?: boolean;/**- * Chosen at creation; absent on environments made before there was a- * choice, which {@link environmentKind} reads from what they configure.+ * Stored at creation; absent on environments made before there was one.* Stored with the rest of the definition but stripped from every copy sent* to the execution plane, so adding it changes no build's digest.*/@@ -108,34 +107,6 @@ export interface EnvironmentInstanceConfiguration {*/export const DEFAULT_REGENERABLE_PATHS = ['node_modules', '.venv', 'target'] as const;-/**- * The kind an environment reads as.- *- * The stored choice when there is one. An environment made before the choice- * existed is not backfilled; it is read from what it configures instead โ a- * repository or a setup command is code work, and anything else is a folder of- * files.- */-export const environmentKind = (- environment:- | {- configuration?: Pick<- EnvironmentConfiguration,- 'bootstrapCommand' | 'kind' | 'sources'- > | null;- }- | null- | undefined,-): EnvironmentKind => {- const configuration = environment?.configuration;- if (configuration?.kind === 'files' || configuration?.kind === 'code') return configuration.kind;-- return (configuration?.sources?.length ?? 0) > 0 ||- Boolean(configuration?.bootstrapCommand?.trim())- ? 'code'- : 'files';-};-/*** A definition as the execution plane receives it: without the fields that are* only the product's own (today, {@link EnvironmentConfiguration.kind}). Thediff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.tsindex 90c9736725f..4545ec8709f 100644--- a/packages/types/src/topic/topic.test.ts+++ b/packages/types/src/topic/topic.test.ts@@ -168,12 +168,13 @@ describe('chatTopicMetadataUpdateSchema', () => {expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);});- it('carries the sandbox mode through, and rejects a mode outside the pair', () => {- for (const sandboxMode of ['ephemeral', 'persistent'] as const) {- expect(chatTopicMetadataUpdateSchema.parse({ sandboxMode })).toEqual({ sandboxMode });- }-- expect(chatTopicMetadataUpdateSchema.safeParse({ sandboxMode: 'forever' }).success).toBe(false);+ it('carries the drive folder through and drops the retired sandbox mode', () => {+ expect(chatTopicMetadataUpdateSchema.parse({ sandboxWorkingDirectory: 'reports' })).toEqual({+ sandboxWorkingDirectory: 'reports',+ });+ // Choosing a folder is the choice to persist, so a mode written by an old+ // client is stripped rather than stored next to a choice it contradicts.+ expect(chatTopicMetadataUpdateSchema.parse({ sandboxMode: 'persistent' })).toEqual({});});it('keeps the onboarding feedback comment limit at the shared contract boundary', () => {diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 5a327bed971..e4623681c2f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -351,11 +351,31 @@ export interface ChatTopicMetadata {*/runStartedAt?: string;/**- * Which CLOUD-SANDBOX INSTANCE this topic runs in: one instance of an- * environment, meaning a directory inside the persistent workspace together- * with the packages restored into it. Absent means the workspace root under- * the caller's default environment, which is what a topic that never chose- * gets and what a topic keeps if its instance is later deleted.+ * Which of a workspace's drives this topic's cloud sandbox uses: `public`,+ * the drive every member shares, or `personal`, the member's own. Absent+ * means `public`, the only drive a workspace had before members had their+ * own. Ignored outside a workspace, where there is one drive. The server+ * issues the run's storage claim for this drive and nothing else, so a+ * folder path always means a folder on the drive named here. Mirrors+ * `SandboxDrive` in `@lobechat/builtin-tool-cloud-sandbox`, inlined to keep+ * this package free of a dependency on the tool layer.+ */+ sandboxDrive?: 'personal' | 'public';+ /**+ * The code environment this topic's sandbox is initialized from: its+ * repository is cloned and its setup command run once in the working+ * directory, whichever that is. In a temporary sandbox that is once per+ * sandbox; in a drive folder, once for the folder โ a marker the script+ * leaves behind keeps it from running again. Nothing is tracked beyond that:+ * the folder is an ordinary folder afterwards.+ */+ sandboxEnvironmentId?: string;+ /**+ * Which CLOUD-SANDBOX INSTANCE this topic runs in โ an **environment+ * directory**: a folder on the drive together with the packages its build+ * installed, restored into every session. Takes precedence over+ * {@link ChatTopicMetadata.sandboxWorkingDirectory}; a picker writes one and+ * clears the other.** Two conversations that must not overwrite each other's files take two* instances of one environment rather than two directories under one, because@@ -363,11 +383,11 @@ export interface ChatTopicMetadata {* alone would leave both sharing, and overwriting, the same captured state.** A preference, not a security boundary: the directory it resolves to is- * composed onto the workspace the signed entitlement names and fenced there,- * so a value pointing outside is rejected by the execution plane rather than- * trusted here. Ignored entirely when the run has no persistent workspace,- * which is why it survives a downgrade โ resubscribing puts the conversation- * back where it was.+ * composed onto the drive the signed entitlement names and fenced there, so+ * a value pointing outside is rejected by the execution plane rather than+ * trusted here. Ignored entirely when the run has no drive, which is why it+ * survives a downgrade โ resubscribing puts the conversation back where it+ * was.** Fixed for the life of a session โ the execution plane binds the session on* its first call and refuses a snapshot under a different name โ so a change@@ -379,16 +399,14 @@ export interface ChatTopicMetadata {*/sandboxInstanceId?: string;/**- * Whether this topic's cloud sandbox should persist its working directory.- * Absent means ephemeral โ persistence is an explicit choice, since not every- * task wants to leave files behind. Mirrors `SandboxMode` in- * `@lobechat/builtin-tool-cloud-sandbox`, inlined to keep this package free of- * a dependency on the tool layer.- *- * Only half the decision: a run is persistent when this says so AND the- * caller's entitlement grants a workspace.+ * The folder on the user's drive this topic's cloud sandbox works in,+ * relative to the drive's root; `'.'` is the root itself. Choosing a folder+ * IS the choice to persist: with neither this nor `sandboxInstanceId` the+ * run is a temporary sandbox. A preference like the instance โ fenced by the+ * execution plane, and a folder deleted since it was picked sends the run to+ * a temporary sandbox (the composer says so) rather than recreating it.*/- sandboxMode?: 'ephemeral' | 'persistent';+ sandboxWorkingDirectory?: string;/*** A deferred agent run on this topic. Present iff the topic status is* `scheduled`. Set to `null` to clear it (same clear-convention as@@ -637,19 +655,20 @@ export const chatTopicMetadataUpdateSchema = z.object({}).nullable().optional(),- // The topic's own sandbox choices: where it works, which instance it works in,- // and whether anything survives. Client-writable on purpose โ the execution- // plane fences all three against the entitlement it was issued, so they are- // preferences rather than boundaries (see `TopicMetadata.sandboxCwd`).+ // The topic's own sandbox choices: which folder on the drive it works in, or+ // which instance (environment directory). Client-writable on purpose โ the+ // execution plane fences both against the entitlement it was issued, so they+ // are preferences rather than boundaries.//// A key absent here is not rejected, it is silently dropped: this is a plain// `z.object()`, and stripping unknown keys is its default. So a field that// lives only on `ChatTopicMetadata` writes nothing and still answers 200 โ// the interface and this schema are two declarations the type checker never// compares.- sandboxCwd: z.string().optional(),+ sandboxDrive: z.enum(['personal', 'public']).optional(),+ sandboxEnvironmentId: z.string().max(255).optional(),sandboxInstanceId: z.string().optional(),- sandboxMode: z.enum(['ephemeral', 'persistent']).optional(),+ sandboxWorkingDirectory: z.string().max(1024).optional(),scheduledRun: topicScheduledRunSchema.nullish(),workingDirectory: z.string().optional(),workingDirectoryConfig: workingDirConfigSchema.optional(),diff --git a/packages/types/src/worktreePath.ts b/packages/types/src/worktreePath.tsnew file mode 100644index 00000000000..8b8fcb22f41--- /dev/null+++ b/packages/types/src/worktreePath.ts@@ -0,0 +1,36 @@+/**+ * Derive the target directory for a new worktree: a sibling of the source repo+ * named `<repoName>-<branch>` (e.g. `/code/lobehub` + `feat/x` โ+ * `/code/lobehub-feat-x`), matching the convention agents already use for their+ * linked worktrees. Preserves the source path's separator so Windows paths stay+ * intact, and folds ref-illegal characters in the branch to `-` for the folder.+ *+ * Shared by the renderer (path preview + local IPC call) and the server+ * (`device.addGitWorktree`), which re-derives the target from the trusted+ * `path` + `branch` rather than trusting a client-supplied absolute path โ so a+ * crafted web request can't ask a remote device to check out at an arbitrary+ * location. Both callers must derive identically, hence the single source here.+ */+const isSep = (ch: string): boolean => ch === '/' || ch === '\\';++export const deriveWorktreePath = (sourcePath: string, branch: string): string => {+ const sep = sourcePath.includes('\\') && !sourcePath.includes('/') ? '\\' : '/';+ // Strip trailing path separators, then the leading/trailing '-' of the folded+ // branch, both with linear scans rather than anchored /[โฆ]+$/ quantifiers โ+ // those are polynomial-ReDoS shapes (flagged by CodeQL) on a long crafted+ // input, and this runs per request on the server with untrusted path/branch.+ let te = sourcePath.length;+ while (te > 0 && isSep(sourcePath[te - 1])) te -= 1;+ const trimmed = sourcePath.slice(0, te);+ const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'));+ const parent = cut >= 0 ? trimmed.slice(0, cut) : '';+ const repoName = (cut >= 0 ? trimmed.slice(cut + 1) : trimmed) || 'repo';+ const folded = branch.trim().replaceAll(/[\s~^:?*[\]\\/]+/g, '-');+ let start = 0;+ let end = folded.length;+ while (start < end && folded[start] === '-') start += 1;+ while (end > start && folded[end - 1] === '-') end -= 1;+ const suffix = folded.slice(start, end);+ const folder = suffix ? `${repoName}-${suffix}` : repoName;+ return parent ? `${parent}${sep}${folder}` : folder;+};diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex 96c53763c08..ac81e221bbe 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -545,8 +545,6 @@"src/features/ChatInput/ControlBar/ModeSelector.tsx","src/features/ChatInput/ControlBar/OptionRow.tsx","src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx",- "src/features/ChatInput/ControlBar/SandboxEnvironmentRow.tsx",- "src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx","src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx","src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx","src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx",@@ -785,18 +783,13 @@"src/features/EntityLink/Render/InternalEntityLink.tsx","src/features/EntityLink/Render/InternalEntityPreview.tsx","src/features/EntityLink/Render/LinkChip.tsx",- "src/features/EnvironmentManager/CreateEnvironmentModal.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/InstanceFileBrowser.tsx",- "src/features/EnvironmentManager/InstanceList.tsx","src/features/EnvironmentManager/PanelSection.tsx",- "src/features/EnvironmentManager/SessionHistorySection.tsx",- "src/features/EnvironmentManager/WorkspaceUsageMeter.tsx","src/features/EnvironmentManager/index.tsx","src/features/EvalCapture/CaptureContent.tsx","src/features/EvalCapture/CaptureSuccess.tsx",diff --git a/src/business/client/features/RetainedMemberDrives.tsx b/src/business/client/features/RetainedMemberDrives.tsxnew file mode 100644index 00000000000..ca2ef8d6246--- /dev/null+++ b/src/business/client/features/RetainedMemberDrives.tsx@@ -0,0 +1,18 @@+'use client';++import { memo } from 'react';++/**+ * The personal drives a workspace keeps for members who left, shown to an+ * owner or admin under the members' usage in the drive usage card.+ *+ * Nothing in the open-source build: keeping a departed member's drive for a+ * retention window, and deleting or moving it, is a hosted-service policy.+ * Downstream builds override this module through their own `@/business/...`+ * mapping.+ */+const RetainedMemberDrives = memo(() => null);++RetainedMemberDrives.displayName = 'RetainedMemberDrives';++export default RetainedMemberDrives;diff --git a/src/business/client/features/SandboxStorageOverQuotaAction.tsx b/src/business/client/features/SandboxStorageOverQuotaAction.tsxnew file mode 100644index 00000000000..39d88e08ec9--- /dev/null+++ b/src/business/client/features/SandboxStorageOverQuotaAction.tsx@@ -0,0 +1,17 @@+'use client';++import { memo } from 'react';++/**+ * What can be done about a drive that is over its quota and refusing writes,+ * shown under the over-quota notice in the drive usage card.+ *+ * Nothing in the open-source build: a quota and paying for usage past it are+ * a hosted-service policy. Downstream builds override this module through+ * their own `@/business/...` mapping.+ */+const SandboxStorageOverQuotaAction = memo(() => null);++SandboxStorageOverQuotaAction.displayName = 'SandboxStorageOverQuotaAction';++export default SandboxStorageOverQuotaAction;diff --git a/src/business/client/features/SandboxStorageUpsell.tsx b/src/business/client/features/SandboxStorageUpsell.tsxindex 201e2209ee3..c837e5fa611 100644--- a/src/business/client/features/SandboxStorageUpsell.tsx+++ b/src/business/client/features/SandboxStorageUpsell.tsx@@ -16,17 +16,27 @@ import { useTranslation } from 'react-i18next';*/export const openSandboxStorageUpsell = (): void => {};+export interface SandboxStorageUpgradeGuideProps {+ /**+ * One short block instead of a page โ for the drive picker, a dialog where a+ * full-page guide would crowd out the choice the dialog is for.+ */+ compact?: boolean;+ /** Called before the guide takes the user elsewhere, so a dialog can close first. */+ onLeave?: () => void;+}+/**- * What the environments page shows in place of its content when the account- * has no persistent workspace to build environments in. Same reasoning as+ * What stands where the drive would be, for an account without one: the+ * storage settings page, and the drive picker (compact). Same reasoning as* above: here it says the feature is not available on this deployment, and a* downstream build replaces it with its own way of getting one.*/-export const SandboxStorageUpgradeGuide = memo(() => {+export const SandboxStorageUpgradeGuide = memo<SandboxStorageUpgradeGuideProps>(({ compact }) => {const { t } = useTranslation('setting');return (- <Center style={{ minHeight: 320 }} width={'100%'}>+ <Center style={{ minHeight: compact ? 160 : 320 }} width={'100%'}><Emptydescription={t('environments.unavailable.desc')}descriptionProps={{ fontSize: 13 }}diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxnew file mode 100644index 00000000000..7d34130d2f6--- /dev/null+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -0,0 +1,311 @@+'use client';++import { cx, Flexbox, Icon, Popover, Skeleton, Text, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ ChevronDownIcon,+ FolderClockIcon,+ FolderIcon,+ FolderOpenIcon,+ HardDriveIcon,+ InfoIcon,+ PackageIcon,+ TimerIcon,+ TriangleAlertIcon,+} from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';+import { refreshProjectFiles } from '@/services/projectFile';+import { sandboxStorageService } from '@/services/sandboxStorage';++import OptionRow from './OptionRow';+import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';+import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';++const styles = stylex.create({+ header: {+ alignItems: 'center',+ display: 'flex',+ gap: 6,+ justifyContent: 'space-between',+ paddingBlock: 4,+ },+ headerInfo: {+ color: cssVar.colorTextQuaternary,+ cursor: 'help',+ },+ headerTitle: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ fontWeight: 500,+ },+ notice: {+ backgroundColor: cssVar.colorWarningBg,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorWarningText,+ fontSize: 12,+ paddingBlock: 8,+ paddingInline: 8,+ },+ // StyleX longhands outrank the row's own emotion padding.+ option: {+ paddingInline: 0,+ },+ warning: {+ color: cssVar.colorWarning,+ },+});++const optionClassName = stylex.props(styles.option).className;++interface SandboxDrivePickerProps {+ /** Whether this plan includes a drive. Without one the menu offers the way to a plan. */+ entitled: boolean;+ onChange: (selection: SandboxSelection) => Promise<void>;+ topicId?: string;+ /** Where this conversation works today. */+ value: SandboxSelection;+}++const folderName = (path: string) => path.split('/').pop() || path;++/**+ * Where a cloud-sandbox run works, offered the way the device picker offers+ * folders: the chip names the place, the menu holds the temporary sandbox and+ * the way into the drive's directory browser.+ *+ * Nothing picked is the temporary sandbox; picking a folder on the drive is+ * the choice to keep files. A pick that can no longer be honoured โ the+ * folder was deleted โ is said on the chip itself, before the next message+ * runs somewhere the person did not choose. The environment the directory is+ * initialized from is a separate choice, beside this one, and every pick here+ * carries it along unchanged.+ *+ * A conversation from before environments became initializers may still be+ * bound to an environment directory; it is shown by name until another pick+ * replaces it.+ */+const SandboxDrivePicker = memo<SandboxDrivePickerProps>(+ ({ entitled, onChange, topicId, value }) => {+ const { t } = useTranslation(['chat', 'device']);+ const [open, setOpen] = useState(false);+ const workspaceId = useActiveWorkspaceId();+ const persistent = isPersistentSelection(value);++ // A legacy environment directory's own row, for its name โ from the+ // database, so the chip never waits on a sandbox.+ const { data: instance, isLoading: instanceLoading } = useSWR(+ entitled && value.instanceId ? ['sandbox-drive-chip-instance', value.instanceId] : null,+ () => sandboxStorageService.getInstance({ id: value.instanceId! }),+ );++ // Whether the pick still holds, asked of the same resolver the run uses:+ // a folder deleted on a shared drive, or an environment directory gone,+ // sends the next run to a temporary sandbox โ and the chip says so first.+ const { data: placement, mutate: revalidatePlacement } = useSWR(+ entitled && topicId && persistent+ ? [+ 'sandbox-drive-placement',+ topicId,+ value.drive ?? '',+ value.instanceId ?? '',+ value.workingDirectory ?? '',+ ]+ : null,+ () => sandboxStorageService.resolveSessionPlacement({ topicId }),+ { revalidateOnFocus: true },+ );+ const fallback = placement?.fallback;++ // Picking the folder already held keeps the keys unchanged, so SWR would+ // go on showing the old answers โ "no longer exists" on the chip and an+ // unreadable tree in the working panel, for a folder just re-created and+ // picked again. Ask once more after every pick.+ const pick = async (placement: Omit<SandboxSelection, 'environmentId'>) => {+ // The environment is chosen beside the folder, not with it.+ const selection = { ...placement, environmentId: value.environmentId };+ await onChange(selection);+ void revalidatePlacement();+ if (topicId && !selection.instanceId && selection.workingDirectory !== undefined) {+ const folder = selection.workingDirectory === '.' ? '' : selection.workingDirectory;+ void refreshProjectFiles(`sandbox:${topicId}`, folder);+ }+ };++ const select = async (selection: Omit<SandboxSelection, 'environmentId'>) => {+ setOpen(false);+ try {+ await pick(selection);+ } catch {+ // The topic kept its old placement; said rather than left looking picked.+ toast.error(t('workingDirectory.drive.pickFailed', { ns: 'device' }));+ }+ };++ const openBrowser = () => {+ setOpen(false);+ openSandboxDirectoryModal({+ // A folder that is gone cannot be listed; start from the top instead.+ defaultPath:+ value.workingDirectory &&+ value.workingDirectory !== '.' &&+ fallback !== 'directoryMissing'+ ? value.workingDirectory+ : undefined,+ drive: value.drive,+ isWorkspace: !!workspaceId,+ onPick: pick,+ });+ };++ const currentLabel = value.instanceId+ ? (instance?.name ?? instance?.workingDirectory)+ : value.workingDirectory === '.'+ ? t('sandboxDrive.root')+ : value.workingDirectory+ ? folderName(value.workingDirectory)+ : undefined;+ const currentIcon = value.instanceId ? PackageIcon : FolderIcon;++ const fallbackMessage = fallback ? t(`sandboxDrive.fallback.${fallback}`) : undefined;+ // In a workspace a folder path means nothing without its drive.+ const driveName = workspaceId+ ? t(`workingDirectory.drive.drives.${value.drive ?? 'public'}`, { ns: 'device' })+ : undefined;++ const chipIcon = fallback ? (+ <Icon icon={TriangleAlertIcon} size={14} />+ ) : persistent ? (+ <Icon icon={currentIcon} size={14} />+ ) : (+ <Icon icon={TimerIcon} size={14} />+ );+ const chipLabel = persistent+ ? fallback+ ? t(`sandboxDrive.fallbackChip.${fallback}`)+ : currentLabel+ : t('sandboxStorage.ephemeral');++ const content = (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>+ <div {...stylex.props(styles.header)}>+ <Flexbox horizontal align={'center'} gap={4}>+ <span {...stylex.props(styles.headerTitle)}>{t('sandboxDrive.pickerTitle')}</span>+ <Tooltip title={t('sandboxDrive.pickerInfoTooltip')}>+ <span {...stylex.props(styles.headerInfo)}>+ <Icon icon={InfoIcon} size={12} />+ </span>+ </Tooltip>+ </Flexbox>+ </div>++ {fallbackMessage && (+ <Text className={stylex.props(styles.notice).className}>{fallbackMessage}</Text>+ )}++ <OptionRow+ active={!persistent}+ className={optionClassName}+ desc={t('sandboxStorage.ephemeralDesc')}+ icon={<Icon icon={TimerIcon} size={16} />}+ label={t('sandboxStorage.ephemeral')}+ onClick={() => void select({})}+ />++ {entitled && persistent && currentLabel && (+ <OptionRow+ active+ className={optionClassName}+ icon={<Icon icon={currentIcon} size={16} />}+ label={currentLabel}+ desc={+ value.instanceId+ ? t('sandboxDrive.environmentDesc')+ : driveName+ ? t('sandboxDrive.folderOnDriveDesc', {+ drive: driveName,+ path: value.workingDirectory === '.' ? '/' : `/${value.workingDirectory}`,+ })+ : t('sandboxDrive.folderDesc', {+ path: value.workingDirectory === '.' ? '/' : `/${value.workingDirectory}`,+ })+ }+ onClick={() => setOpen(false)}+ />+ )}++ {entitled && (+ <OptionRow+ className={optionClassName}+ desc={t('sandboxDrive.browseDesc')}+ icon={<Icon icon={persistent ? FolderOpenIcon : HardDriveIcon} size={16} />}+ label={t(persistent ? 'sandboxDrive.browseOther' : 'sandboxDrive.browse')}+ onClick={openBrowser}+ />+ )}++ {!entitled && (+ // The drive is part of a plan this account is not on. Offered in the+ // same list, in the same shape, so the row reads as one more place+ // files could go โ and the tag says why it is not simply selectable.+ <OptionRow+ className={optionClassName}+ desc={t('sandboxStorage.persistentUpsellDesc')}+ icon={<Icon icon={FolderClockIcon} size={16} />}+ label={t('sandboxDrive.upsell')}+ tag={t('pro', { ns: 'common' })}+ onClick={() => {+ setOpen(false);+ openSandboxStorageUpsell();+ }}+ />+ )}+ </Flexbox>+ );++ const resolving = !!value.instanceId && !instance && instanceLoading;++ // A plain div between the popover and the chip, as the device picker has:+ // the popover merges trigger props into its direct child.+ return (+ <Popover+ arrow={false}+ content={content}+ open={open}+ placement={'topLeft'}+ trigger={'click'}+ onOpenChange={setOpen}+ >+ <div>+ <Tooltip title={fallbackMessage}>+ <div+ data-testid={'sandbox-drive-chip'}+ className={cx(+ workingDirectoryChipStyles.chip,+ fallback && stylex.props(styles.warning).className,+ )}+ >+ {chipIcon}+ {resolving ? (+ <Skeleton.Text rows={1} style={{ height: 12, width: 56 }} />+ ) : (+ <span className={workingDirectoryChipStyles.label}>{chipLabel}</span>+ )}+ <Icon icon={ChevronDownIcon} size={12} />+ </div>+ </Tooltip>+ </div>+ </Popover>+ );+ },+);++SandboxDrivePicker.displayName = 'SandboxDrivePicker';++export default SandboxDrivePicker;diff --git a/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsx b/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsxnew file mode 100644index 00000000000..d427c3009b1--- /dev/null+++ b/src/features/ChatInput/ControlBar/SandboxEnvironmentPicker.tsx@@ -0,0 +1,202 @@+'use client';++import { Button, Flexbox, Icon, Popover, Text, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDownIcon, CircleSlashIcon, PackageIcon, SettingsIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { environmentService } from '@/services/environment';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';++import OptionRow from './OptionRow';+import { environmentChipState, pickableEnvironments } from './sandboxEnvironmentOptions';+import type { SandboxSelection } from './useSandboxPlacement';+import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';++const styles = stylex.create({+ header: {+ alignItems: 'center',+ display: 'flex',+ gap: 6,+ justifyContent: 'space-between',+ paddingBlock: 4,+ },+ headerTitle: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ fontWeight: 500,+ },+ hint: {+ color: cssVar.colorTextDescription,+ fontSize: 11,+ paddingBlockEnd: 4,+ },+ list: {+ maxHeight: 280,+ overflowY: 'auto',+ },+ manageButton: {+ alignItems: 'center',+ backgroundColor: 'transparent',+ borderStyle: 'none',+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorPrimary },+ cursor: 'pointer',+ display: 'flex',+ fontSize: 11,+ gap: 3,+ padding: 0,+ transition: 'color 0.2s',+ },+ // StyleX longhands outrank the row's own emotion padding.+ option: {+ paddingInline: 0,+ },+});++const optionClassName = stylex.props(styles.option).className;++interface SandboxEnvironmentPickerProps {+ onChange: (selection: SandboxSelection) => Promise<void>;+ /** Where this conversation works today, and what it is initialized from. */+ value: SandboxSelection;+}++/**+ * Which code environment a cloud-sandbox conversation starts from โ beside the+ * working-directory chip, and independent of it. An environment is a one-time+ * initializer: its repository is cloned and its setup run in the working+ * directory before the first command, once per temporary sandbox and once for+ * a folder on the drive. A folder that already holds files is left as it is.+ *+ * Picking here changes only the environment; the folder stays where it is.+ */+const SandboxEnvironmentPicker = memo<SandboxEnvironmentPickerProps>(({ onChange, value }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const navigate = useWorkspaceAwareNavigate();+ const workspaceId = useActiveWorkspaceId();++ const { data, error, mutate } = useSWR(['sandbox-environment-chip', workspaceId ?? ''], () =>+ environmentService.listEnvironments(),+ );+ const sharedAgent = useAgentStore(+ (s) => !!workspaceId && agentSelectors.currentAgentVisibility(s) === 'public',+ );+ const environments = pickableEnvironments(data?.environments ?? [], sharedAgent);+ const current = environments.find((environment) => environment.id === value.environmentId);+ // Picked once but no longer readable โ deleted, or unpublished by its owner+ // โ is said rather than hidden; a list that has not loaded says nothing.+ const state = environmentChipState({+ current,+ environmentId: value.environmentId,+ failed: !!error,+ loaded: !!data,+ });++ const select = async (environmentId: string | undefined) => {+ setOpen(false);+ try {+ // A legacy copy runs what its build made and is never initialized, so+ // picking an environment leaves it for the folder it lives in.+ await onChange({ ...value, environmentId, instanceId: undefined });+ } catch {+ // The topic kept its environment; said rather than left looking changed.+ toast.error(t('sandboxEnvironment.saveFailed'));+ }+ };++ const content = (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>+ <div {...stylex.props(styles.header)}>+ <span {...stylex.props(styles.headerTitle)}>{t('sandboxEnvironment.title')}</span>+ <button+ {...stylex.props(styles.manageButton)}+ type={'button'}+ onClick={() => {+ setOpen(false);+ navigate('/settings/environments');+ }}+ >+ <Icon icon={SettingsIcon} size={11} />+ <span>{t('sandboxDrive.manageEnvironments')}</span>+ </button>+ </div>+ <Text className={stylex.props(styles.hint).className}>{t('sandboxEnvironment.hint')}</Text>++ <OptionRow+ active={!value.environmentId}+ className={optionClassName}+ desc={t('sandboxEnvironment.noneDesc')}+ icon={<Icon icon={CircleSlashIcon} size={16} />}+ label={t('sandboxEnvironment.none')}+ onClick={() => void select(undefined)}+ />+ <div {...stylex.props(styles.list)}>+ {environments.map((environment) => (+ <OptionRow+ active={environment.id === value.environmentId}+ className={optionClassName}+ desc={environment.description || undefined}+ icon={<Icon icon={PackageIcon} size={16} />}+ key={environment.id}+ label={environment.name}+ onClick={() => void select(environment.id)}+ />+ ))}+ </div>+ {data && environments.length === 0 && (+ <Text className={stylex.props(styles.hint).className}>{t('sandboxEnvironment.empty')}</Text>+ )}+ {!data && error && (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text className={stylex.props(styles.hint).className} type={'danger'}>+ {t('sandboxEnvironment.loadFailed')}+ </Text>+ <Button onClick={() => void mutate()}>{t('sandboxEnvironment.retry')}</Button>+ </Flexbox>+ )}+ </Flexbox>+ );++ const label =+ state.kind === 'picked'+ ? state.name+ : state.kind === 'missing'+ ? t('sandboxEnvironment.missing')+ : state.kind === 'loading'+ ? t('sandboxEnvironment.loading')+ : state.kind === 'loadFailed'+ ? t('sandboxEnvironment.loadFailed')+ : t('sandboxEnvironment.none');++ // A plain div between the popover and the chip, as the device picker has:+ // the popover merges trigger props into its direct child.+ return (+ <Popover+ arrow={false}+ content={content}+ open={open}+ placement={'topLeft'}+ trigger={'click'}+ onOpenChange={setOpen}+ >+ <div>+ <div className={workingDirectoryChipStyles.chip} data-testid={'sandbox-environment-chip'}>+ <Icon icon={value.environmentId ? PackageIcon : CircleSlashIcon} size={14} />+ <span className={workingDirectoryChipStyles.label}>{label}</span>+ <Icon icon={ChevronDownIcon} size={12} />+ </div>+ </div>+ </Popover>+ );+});++SandboxEnvironmentPicker.displayName = 'SandboxEnvironmentPicker';++export default SandboxEnvironmentPicker;diff --git a/src/features/ChatInput/ControlBar/SandboxEnvironmentRow.tsx b/src/features/ChatInput/ControlBar/SandboxEnvironmentRow.tsxdeleted file mode 100644index 04064a8a83f..00000000000--- a/src/features/ChatInput/ControlBar/SandboxEnvironmentRow.tsx+++ /dev/null@@ -1,324 +0,0 @@-'use client';--import { type EnvironmentKind } from '@lobechat/types';-import { Github } from '@lobehub/icons';-import {- ActionIcon,- createStaticStyles,- cssVar,- DropdownMenu,- Flexbox,- Icon,- Popover,- Tooltip,-} from '@lobehub/ui';-import {- ChevronDownIcon,- ChevronRightIcon,- CircleStopIcon,- CopyPlusIcon,- FolderIcon,- MoreVerticalIcon,-} from 'lucide-react';-import { memo, type ReactNode, useState, useSyncExternalStore } from 'react';-import { useTranslation } from 'react-i18next';--import OptionRow from './OptionRow';-import {- copyMenuActions,- type EnvironmentRowState,- isCopyBuilding,- isCopyOccupied,- type PickerCopy,-} from './sandboxEnvironmentRows';--const styles = createStaticStyles(({ css }) => ({- desc: css`- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- `,- inlineCopies: css`- margin-inline-start: 18px;- padding-inline-start: 8px;- border-inline-start: 1px solid ${cssVar.colorBorderSecondary};- `,- option: css`- && {- padding-inline: 0;- }- `,- submenuArrow: css`- display: flex;- align-items: center;- color: ${cssVar.colorTextQuaternary};- `,- submenuTitle: css`- padding-block: 4px;- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextQuaternary};- `,-}));--/**- * Desktop pointers open a second menu on hover; touch screens and narrow- * windows have no hover and no room beside the menu, so there the row's arrow- * expands the copies in place instead.- */-const HOVER_SUBMENU_QUERY = '(hover: hover) and (pointer: fine) and (min-width: 768px)';--const subscribeHoverQuery = (onChange: () => void) => {- if (typeof window === 'undefined' || !window.matchMedia) return () => {};- const query = window.matchMedia(HOVER_SUBMENU_QUERY);- query.addEventListener('change', onChange);- return () => query.removeEventListener('change', onChange);-};--const readHoverQuery = () =>- typeof window === 'undefined' || !window.matchMedia- ? true- : window.matchMedia(HOVER_SUBMENU_QUERY).matches;--export const useHoverSubmenu = () =>- useSyncExternalStore(subscribeHoverQuery, readHoverQuery, () => true);--/** A listed copy, as the picker receives it from `listInstances`. */-export interface SandboxPickerCopy extends PickerCopy {- isDefault: boolean;- name: string;- workingDirectory: string;-}--export interface SandboxEnvironmentRowProps {- boundInstanceId?: string;- /** The environment's preparation is in flight: a lazy creation or another copy. */- busy?: boolean;- environment: { id: string; name: string };- isCreator: boolean;- kind: EnvironmentKind;- onReopen: () => void;- onSelectCopy: (copy: SandboxPickerCopy) => void;- /** Picks an environment with no copy yet โ its creator's copy is made first. */- onSelectLazy: () => void;- onStop: (copy: SandboxPickerCopy) => void;- row: EnvironmentRowState<SandboxPickerCopy>;- /** Copies whose run is being stopped from this menu. */- stopping: (id: string) => boolean;-}--/**- * One environment in the composer's picker, and โ only when it has more than- * one copy โ the copies under it.- *- * The row is what people choose. Which copy that lands the conversation in is- * decided by `describeEnvironmentRow`, and the second menu exists for the rare- * person who wants a specific one: a single copy needs no menu to choose it.- */-const SandboxEnvironmentRow = memo<SandboxEnvironmentRowProps>(- ({- boundInstanceId,- busy,- environment,- isCreator,- kind,- onReopen,- onSelectCopy,- onSelectLazy,- onStop,- row,- stopping,- }) => {- const { t } = useTranslation('chat');- const hoverSubmenu = useHoverSubmenu();- const [expanded, setExpanded] = useState(false);-- const icon = (size: number): ReactNode =>- kind === 'files' ? <Icon icon={FolderIcon} size={size} /> : <Github size={size} />;-- const statusTag = (copy: SandboxPickerCopy | undefined): ReactNode => {- if (!copy) return undefined;- if (isCopyBuilding(copy)) return t('sandboxStorage.building');- if (copy.status === 'error') return t('sandboxStorage.buildFailed');- if (!copy.inUse) return undefined;-- const occupied = isCopyOccupied(copy);- const stoppable = occupied && copyMenuActions({ copy, isCreator, kind }).includes('stop');-- // "Running" alone reads as a state, not as the reason the row cannot be- // picked โ the tooltip says how long that lasts, and, for the creator,- // that it can be ended now from the menu beside it.- return (- <Tooltip- title={t(- !occupied- ? 'sandboxStorage.runningOwnHint'- : stoppable- ? 'sandboxStorage.runningHintStoppable'- : 'sandboxStorage.runningHint',- )}- >- <span>{t('sandboxStorage.running')}</span>- </Tooltip>- );- };-- // The menu the stop shipped in, with "open another copy" below it. The same- // menu on the environment row (acting on the copy the row shows) and on- // every copy row, so the way out of a busy copy is where the person found it.- const menu = (copy: SandboxPickerCopy | undefined) => {- const actions = copyMenuActions({ copy, isCreator, kind });- if (actions.length === 0) return undefined;-- const isStopping = copy ? stopping(copy.id) : false;-- return (- <DropdownMenu- items={actions.map((action) =>- action === 'stop'- ? {- disabled: isStopping,- icon: CircleStopIcon,- key: 'stop',- label: t('sandboxStorage.stop'),- onClick: () => copy && onStop(copy),- }- : {- desc: t('sandboxStorage.reopenCopyDesc'),- disabled: busy,- icon: CopyPlusIcon,- key: 'reopen',- label: t('sandboxStorage.reopenCopy'),- onClick: onReopen,- },- )}- >- <ActionIcon- data-testid={`sandbox-env-menu-${copy?.id ?? environment.id}`}- disabled={isStopping}- icon={MoreVerticalIcon}- loading={isStopping || busy}- size={'small'}- />- </DropdownMenu>- );- };-- const copyRow = (copy: SandboxPickerCopy) => {- const active = copy.id === boundInstanceId;- const unavailable = isCopyOccupied(copy) || isCopyBuilding(copy);-- return (- <OptionRow- active={active}- className={styles.option}- desc={<span className={styles.desc}>{copy.workingDirectory}</span>}- // Already this conversation's own copy: it stays selectable however- // the lease reads โ "you cannot pick what you are already using" is- // never the right thing to say.- disabled={unavailable && !active}- extra={menu(copy)}- icon={icon(16)}- key={copy.id}- label={copy.name}- tags={[copy.isDefault ? t('sandboxStorage.defaultCopy') : null, statusTag(copy)].filter(- Boolean,- )}- onClick={() => onSelectCopy(copy)}- />- );- };-- const copyList = (- <Flexbox data-testid={`sandbox-env-copies-${environment.id}`} gap={2}>- {row.copies.map((copy) => copyRow(copy))}- </Flexbox>- );-- const displayed = row.displayed;- const desc = row.lazyCreate- ? t('sandboxStorage.noCopyYetDesc')- : row.copies.length === 0- ? t('sandboxStorage.noCopyColleagueDesc')- : row.hasSubmenu- ? `${displayed?.name} ยท ${t('sandboxStorage.copyCount', { count: row.copies.length })}`- : displayed?.workingDirectory;-- const arrow = row.hasSubmenu ? (- hoverSubmenu ? (- <span className={styles.submenuArrow}>- <Icon icon={ChevronRightIcon} size={14} />- </span>- ) : (- <ActionIcon- aria-expanded={expanded}- data-testid={`sandbox-env-expand-${environment.id}`}- icon={expanded ? ChevronDownIcon : ChevronRightIcon}- size={'small'}- title={t('sandboxStorage.showCopies')}- onClick={() => setExpanded((value) => !value)}- />- )- ) : undefined;-- const menuButton = menu(displayed);- const extra =- menuButton || arrow ? (- <>- {menuButton}- {arrow}- </>- ) : undefined;-- const environmentRow = (- <OptionRow- active={row.copies.some((copy) => copy.id === boundInstanceId)}- className={styles.option}- desc={<span className={styles.desc}>{desc}</span>}- disabled={!row.selectable || busy}- extra={extra}- icon={icon(16)}- label={environment.name}- tags={[- t(kind === 'files' ? 'sandboxStorage.kind.files' : 'sandboxStorage.kind.code'),- statusTag(displayed),- ].filter(Boolean)}- onClick={() => {- if (row.lazyCreate) onSelectLazy();- else if (row.picked) onSelectCopy(row.picked);- }}- />- );-- if (!row.hasSubmenu)- return <div data-testid={`sandbox-env-row-${environment.id}`}>{environmentRow}</div>;-- if (hoverSubmenu)- return (- <Popover- arrow={false}- placement={'rightTop'}- trigger={'hover'}- content={- <Flexbox gap={2} style={{ maxWidth: 320, minWidth: 240 }}>- <div className={styles.submenuTitle}>{t('sandboxStorage.copies')}</div>- {copyList}- </Flexbox>- }- >- <div data-testid={`sandbox-env-row-${environment.id}`}>{environmentRow}</div>- </Popover>- );-- return (- <div data-testid={`sandbox-env-row-${environment.id}`}>- {environmentRow}- {expanded && <div className={styles.inlineCopies}>{copyList}</div>}- </div>- );- },-);--SandboxEnvironmentRow.displayName = 'SandboxEnvironmentRow';--export default SandboxEnvironmentRow;diff --git a/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx b/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsxdeleted file mode 100644index 2d4a0a452a5..00000000000--- a/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx+++ /dev/null@@ -1,592 +0,0 @@-'use client';--import { Github } from '@lobehub/icons';-import {- confirmModal,- createStaticStyles,- cssVar,- cx,- Flexbox,- Icon,- Popover,- Skeleton,- Text,- toast,- Tooltip,-} from '@lobehub/ui';-import {- ChevronDownIcon,- FolderClockIcon,- FolderIcon,- InfoIcon,- LockIcon,- PlusIcon,- SettingsIcon,- TimerIcon,-} from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';-import { describeError } from '@/features/EnvironmentManager/errorMessage';-import { settleThenRefresh } from '@/features/EnvironmentManager/settleThenRefresh';-import { useCanEditEnvironment } from '@/features/EnvironmentManager/useCanEditEnvironment';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { sandboxStorageService } from '@/services/sandboxStorage';-import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';--import OptionRow from './OptionRow';-import SandboxEnvironmentRow from './SandboxEnvironmentRow';-import {- copyChipLabel,- describeEnvironmentRow,- isCopyBuilding,- isCopyOccupied,-} from './sandboxEnvironmentRows';-import { useCreateCopy } from './useCreateCopy';-import { usePendingIds } from './usePendingIds';-import type { SandboxSelection } from './useSandboxMode';-import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';--export type { SandboxSelection } from './useSandboxMode';--const styles = createStaticStyles(({ css }) => ({- /** The environment and the directory on an instance's second line. */- environmentRow: css`- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- `,- /**- * The pool caption, in the execution-target menu's own shape. The space- * above it is what makes it a section start instead of one more line: two- * grey captions stacked with even spacing read as a pair, not as a heading- * over its contents.- */- groupLabel: css`- margin-block-start: 6px;- padding-block: 4px;-- font-size: 11px;- font-weight: 500;- color: ${cssVar.colorTextQuaternary};- `,- /** Title, its explainer and the way out โ the execution-device menu's header. */- header: css`- display: flex;- gap: 6px;- align-items: center;- justify-content: space-between;-- padding-block: 4px;- `,- headerInfo: css`- cursor: help;- color: ${cssVar.colorTextQuaternary};- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorTextSecondary};- }- `,- headerTitle: css`- font-size: 12px;- font-weight: 500;- color: ${cssVar.colorTextTertiary};- `,- manageButton: css`- cursor: pointer;-- display: flex;- gap: 3px;- align-items: center;-- padding: 0;- border: none;-- font-size: 11px;- color: ${cssVar.colorTextQuaternary};-- background: none;-- transition: color 0.2s;-- &:hover {- color: ${cssVar.colorPrimary};- }- `,- notice: css`- padding-block: 8px;- font-size: 12px;- color: ${cssVar.colorTextDescription};- `,- option: css`- && {- padding-inline: 0;- }- `,- skeletonRow: css`- display: flex;- gap: 10px;- align-items: center;- padding-block: 8px;- `,- blocked: css`- color: ${cssVar.colorWarning};- `,- blockedNotice: css`- padding-block: 8px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- font-size: 12px;- color: ${cssVar.colorWarningText};-- background: ${cssVar.colorWarningBg};- `,- temporary: css`- padding-block-end: 4px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,-}));--/**- * The shape the instance list is about to take: a caption over a row. Without it the section is simply absent while- * the list loads and then snaps into either a list or a "create one" row โ and- * an empty gap where a choice belongs reads as "there is nothing here", which- * is the one thing it does not yet know.- */-const EnvironmentSectionSkeleton = memo(() => (- <Flexbox gap={2}>- <Skeleton.Text className={styles.environmentRow} rows={1} style={{ width: 96 }} />- <div className={styles.skeletonRow}>- <Skeleton.Avatar shape={'square'} size={28} />- <Flexbox flex={1} gap={4}>- <Skeleton.Text rows={1} style={{ width: 120 }} />- <Skeleton.Text rows={1} style={{ width: 180 }} />- </Flexbox>- </div>- </Flexbox>-));--EnvironmentSectionSkeleton.displayName = 'SandboxInstancePicker.EnvironmentSectionSkeleton';--interface SandboxInstancePickerProps {- /**- * Whether the conversation's agent is shared with the workspace. Such an- * agent runs on its caller's session, and a private environment's captured- * state can hold that caller's credentials โ so the server will not run it- * in one, and the menu says so rather than offering what cannot be used.- */- agentIsPublic?: boolean;- /** Whether this plan includes a persistent workspace. Without one, the menu- * offers the temporary directory and the way to a plan. */- entitled: boolean;- onChange: (selection: SandboxSelection) => Promise<void>;- /**- * Topic whose warm sandbox session serves the instance listing. Absent on a- * conversation that has not been created yet โ the call takes it as an- * optimization, never as a scope, so it simply pays a cold start.- */- topicId?: string;- /** Where this conversation keeps its files today. */- value: SandboxSelection;-}--/**- * Where a cloud-sandbox run keeps its files, offered the way the local picker- * offers folders: the chip names the slot, the menu lists the places.- *- * The temporary directory comes first because it is what a run gets by- * choosing nothing โ naming it keeps that state visible and lets a run go back- * to it. Below it, the environments: what people choose is an environment, and- * the copy (instance) of it a conversation lands in is picked for them โ the- * one it already uses, else the default, else the first free one. Copies only- * surface, in a second menu, when an environment has more than one. The topic- * still stores the copy's id, so a conversation's files never move.- *- * Names, not sizes: sizes live in the snapshot store, which needs a live sandbox- * session to answer, and a picker that takes seconds to open is a picker people- * stop opening. The settings page is where sizes are worth the wait.- */-const SandboxInstancePicker = memo<SandboxInstancePickerProps>(- ({ agentIsPublic, entitled, onChange, topicId, value }) => {- // The slot's own name comes from the device namespace on purpose: the local- // picker and this one are the same slot, and a second string meaning- // "working directory" would be one more pair to keep in step.- const { t } = useTranslation(['chat', 'device', 'setting']);- const [open, setOpen] = useState(false);- // Copies whose run is being stopped from this menu.- const stopping = usePendingIds();- const canEdit = useCanEditEnvironment();- const navigate = useWorkspaceAwareNavigate();-- const boundInstanceId = value.mode === 'persistent' ? value.instanceId : undefined;-- // Fetched while CLOSED whenever a copy is bound, because the chip names- // it by looking it up in this list: gating the list on `open` alone leaves- // the closed chip with nothing to look up.- //- // Both lists are replicas: a reload names the chip and fills the menu from- // the last answer while the network confirms it. One instance list serves- // every conversation (see `sandboxSelectors.pickerInstances`), so the first- // send, which takes the topic from none to one, never blanks the chip.- const listsEnabled = entitled && Boolean(open || boundInstanceId);- const { error: instancesError } = sandboxActions.useFetchPickerInstances(listsEnabled, topicId);- // Also while closed when a copy is bound: whether that copy is still- // usable depends on its environment's visibility.- const { error: environmentError } = sandboxActions.useFetchPickerEnvironments(listsEnabled);- const data = useSandboxStore(sandboxSelectors.pickerInstances(topicId));- const environmentData = useSandboxStore(sandboxSelectors.pickerEnvironments);- const refreshInstances = sandboxActions.mutatePickerInstances;- // "Not known yet": nothing painted (persisted or fetched) and no failure.- const instancesLoading = listsEnabled && !data && !instancesError;- const environmentsLoading = listsEnabled && !environmentData && !environmentError;-- const instances = data ?? [];- const environments = environmentData ?? [];- const current = instances.find((instance) => instance.id === boundInstanceId);- // The server's rule, mirrored: only inside a workspace, where private and- // published are two different things. A personal environment is always- // private and always the owner's own, so it stays usable.- const isBlocked = (environmentId: string) => {- if (!agentIsPublic) return false;- const environment = environments.find((item) => item.id === environmentId);- return Boolean(environment?.workspaceId) && environment?.visibility === 'private';- };- const currentBlocked = current ? isBlocked(current.environmentId) : false;-- // What this agent can actually pick. A public agent's own private- // environments are dropped rather than dimmed โ the execution-target menu- // treats a workspace agent's personal devices the same way, and for the- // same reason: a list of things that cannot be chosen reads as a fault,- // not as help. The one line below says where they went.- const selectable = environments.filter((environment) => !isBlocked(environment.id));- const hiddenPrivateCount = environments.length - selectable.length;-- const environmentById = new Map(- environments.map((environment) => [environment.id, environment]),- );- const copiesOf = (environmentId: string) =>- instances.filter((instance) => instance.environmentId === environmentId);- const currentEnvironment = current ? environmentById.get(current.environmentId) : undefined;-- // Inside a workspace an environment belongs to one of two pools, and which- // one decides who else can reach what a run leaves behind โ so the menu- // says which pool it is looking at, the way the execution-target menu- // splits private from workspace devices. A personal account has one pool- // and no such question, so it stays flat.- const inWorkspace = selectable.some((environment) => Boolean(environment.workspaceId));- const privatePool = inWorkspace- ? selectable.filter((environment) => environment.visibility === 'private')- : [];- const workspacePool = inWorkspace- ? selectable.filter((environment) => environment.visibility !== 'private')- : [];-- // Only once BOTH lists have arrived: undefined is "not known yet", not- // "none". With no environment at all there is nothing to pick, so the row- // says to set one up.- const listsReady = Boolean(environmentData) && Boolean(data);- const hasNoEnvironments = listsReady && selectable.length === 0;-- const select = async (selection: SandboxSelection) => {- setOpen(false);- await onChange(selection);- };-- const leaveTo = (action: () => void) => {- setOpen(false);- action();- };-- // The same stop the settings row offers, from the place the person found- // the copy blocked. The dialog and its outcomes are that row's own words,- // so the two surfaces cannot drift into describing it differently. Keys- // are checked per namespace, and these are the settings row's.- const translate = t as (key: string, options?: Record<string, unknown>) => string;- const tSetting = (key: string, options?: Record<string, unknown>) =>- translate(key, { ...options, ns: 'setting' });- const confirmStop = (instance: { id: string; name: string }) =>- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: tSetting('environments.instances.stopConfirmContent'),- okText: tSetting('environments.instances.stop'),- onOk: () => {- stopping.add(instance.id);- // Refreshed either way โ a refusal may land after the run ended on- // its own โ and the row stays busy until the refreshed list is in,- // so it never reads free on the toast and locked on the row.- void settleThenRefresh(- () => sandboxStorageService.stopInstance({ id: instance.id }),- refreshInstances,- )- .then(({ stopped }) =>- toast.success(- tSetting(- stopped ? 'environments.instances.stopped' : 'environments.instances.stopNothing',- { name: instance.name },- ),- ),- )- .catch((error: unknown) =>- toast.error(- describeError(error, tSetting, tSetting('environments.instances.stopFailed')),- ),- )- .finally(() => stopping.remove(instance.id));- },- title: tSetting('environments.instances.stopConfirmTitle', { name: instance.name }),- });-- // Lazily for an environment with no copy yet, or as another copy when the- // ones there are taken โ see `useCreateCopy`.- const { create: createCopy, isPreparing } = useCreateCopy({- onBuildError: (error) =>- toast.error(- describeError(error, tSetting, tSetting('environments.instances.buildStartFailed')),- ),- onChange,- refreshInstances,- topicId,- });- const createCopyAndBind = (environmentId: string, failedKey: string) =>- createCopy(environmentId, (error) =>- toast.error(describeError(error, tSetting, translate(failedKey))),- );-- const renderEnvironment = (environment: (typeof environments)[number]) => {- const isCreator = canEdit(environment);- const kind = environment.kind;- const row = describeEnvironmentRow({- boundInstanceId,- copies: copiesOf(environment.id),- isCreator,- kind,- });-- return (- <SandboxEnvironmentRow- boundInstanceId={boundInstanceId}- busy={isPreparing(environment.id)}- environment={environment}- isCreator={isCreator}- key={environment.id}- kind={kind}- row={row}- stopping={stopping.has}- onReopen={() => void createCopyAndBind(environment.id, 'sandboxStorage.reopenCopyFailed')}- onSelectCopy={(copy) => void select({ instanceId: copy.id, mode: 'persistent' })}- onStop={confirmStop}- onSelectLazy={() => {- setOpen(false);- void createCopyAndBind(environment.id, 'sandboxStorage.createCopyFailed');- }}- />- );- };-- // The chip names what was chosen โ an environment (and its copy, when it- // has several), or the temporary directory once it has been picked on- // purpose โ and otherwise the slot itself, the same words the local chip- // shows before a folder is chosen. The default is not a choice, so it does- // not get named as one.- // A node rather than an icon component, because the GitHub mark a code- // environment shows is not a lucide glyph.- const chipIcon = (() => {- if (!current) {- return value.mode === 'ephemeral' ? (- <Icon icon={TimerIcon} size={14} />- ) : (- <Icon icon={FolderIcon} size={14} />- );- }- if (currentBlocked) return <Icon icon={LockIcon} size={14} />;- return (currentEnvironment?.kind ?? 'files') === 'files' ? (- <Icon icon={FolderIcon} size={14} />- ) : (- <Github size={14} />- );- })();-- // A copy is bound and the list that names it has not arrived. The key- // carries the topic, so the first send โ the moment a conversation goes- // from none to one โ refetches it, and the fallback below would spend that- // window saying the opposite of the truth: the chip read "working- // directory", as though nothing had been chosen, seconds after the person- // chose it and while the run was already using it.- const resolvingInstance = !!boundInstanceId && !current && instancesLoading;- const chipLabel = current- ? copyChipLabel({- copy: current,- copyCount: copiesOf(current.environmentId).length,- environmentName: currentEnvironment?.name,- })- : value.mode === 'ephemeral'- ? t('sandboxStorage.ephemeral')- : t('workingDirectory.title', { ns: 'device' });-- // Built before the popover on purpose. The dev-time code inspector marks one- // file per session by appending an invisible element inside that file's FIRST- // JSX element; were that the popover, its trigger would become a list, and a- // list is not an element the popover can merge its props into โ it falls back- // to wrapping everything in a native <button>, box and all. A Flexbox with one- // more empty child is harmless.- const content = (- <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>- <div className={styles.header}>- <Flexbox horizontal align={'center'} gap={4}>- <span className={styles.headerTitle}>{t('sandboxStorage.pickerTitle')}</span>- <Tooltip title={t('sandboxStorage.pickerInfoTooltip')}>- <span className={styles.headerInfo}>- <Icon icon={InfoIcon} size={12} />- </span>- </Tooltip>- </Flexbox>- {entitled && (- <button- className={styles.manageButton}- type={'button'}- onClick={() => leaveTo(() => navigate('/settings/environments'))}- >- <Icon icon={SettingsIcon} size={11} />- <span>{t('sandboxStorage.manage')}</span>- </button>- )}- </div>-- {current && currentBlocked && (- <Text className={styles.blockedNotice}>- {t('sandboxStorage.privateInstanceBlocked', { name: current.name })}- </Text>- )}-- {/* This conversation's own instance, held by another one. It stays- bound โ the lease may well be free again by the next message โ but- saying nothing would leave a 409 to do the explaining. A copy that- is still building holds the same lease, but no conversation is- running in it: its row already says "Building". */}- {current && !currentBlocked && isCopyOccupied(current) && !isCopyBuilding(current) && (- <Text className={styles.blockedNotice}>- {t('sandboxStorage.instanceBusy', { name: current.name })}- </Text>- )}-- <Flexbox className={styles.temporary}>- <OptionRow- active={value.mode === 'ephemeral'}- className={styles.option}- desc={t('sandboxStorage.ephemeralDesc')}- icon={<Icon icon={TimerIcon} size={16} />}- label={t('sandboxStorage.ephemeral')}- onClick={() => void select({ mode: 'ephemeral' })}- />- </Flexbox>-- {!entitled && (- // Persistence is part of a plan this account is not on. Offered- // in the same list, in the same shape, so the row reads as one- // more place files could go โ and the tag says why it is not- // simply selectable.- <OptionRow- className={styles.option}- desc={t('sandboxStorage.persistentUpsellDesc')}- icon={<Icon icon={FolderClockIcon} size={16} />}- label={t('sandboxStorage.persistentUpsell')}- tag={t('pro', { ns: 'common' })}- onClick={() => leaveTo(openSandboxStorageUpsell)}- />- )}-- {entitled && (environmentsLoading || instancesLoading) && <EnvironmentSectionSkeleton />}-- {entitled && Boolean(environmentError) && (- <Text className={styles.notice}>{t('sandboxStorage.environmentsUnavailable')}</Text>- )}-- {entitled && hasNoEnvironments && (- // Nothing to choose from yet: environments are made on the- // environment page โ this menu picks, it does not author.- <OptionRow- className={styles.option}- desc={t('sandboxStorage.setUpEnvironmentDesc')}- icon={<Icon icon={PlusIcon} size={16} />}- label={t('sandboxStorage.setUpEnvironment')}- onClick={() => leaveTo(() => navigate('/settings/environments'))}- />- )}-- {entitled && listsReady && !inWorkspace && selectable.map(renderEnvironment)}-- {entitled && listsReady && inWorkspace && privatePool.length > 0 && (- <>- <div className={styles.groupLabel}>{t('sandboxStorage.privateGroup')}</div>- {privatePool.map(renderEnvironment)}- </>- )}-- {entitled && listsReady && inWorkspace && workspacePool.length > 0 && (- <>- <div className={styles.groupLabel}>{t('sandboxStorage.workspaceGroup')}</div>- {workspacePool.map(renderEnvironment)}- </>- )}-- {/* Where the hidden ones went, and how to get one back โ the device- menu's enroll hint, in this menu's terms. One line however many- were dropped; which ones is the settings page's job. */}- {entitled && hiddenPrivateCount > 0 && (- <Text className={styles.notice}>- {t('sandboxStorage.publicAgentHint', { count: hiddenPrivateCount })}- </Text>- )}- </Flexbox>- );-- // A plain div between the popover and the chip, as the local picker has.- // The popover merges trigger props โ role, open state, focus styling โ- // into its direct child; on the styled chip they drew a box around it. On- // this wrapper they land on nothing visible.- return (- <Popover- arrow={false}- content={content}- open={open}- placement={'topLeft'}- trigger={'click'}- onOpenChange={(next) => {- setOpen(next);- // Occupancy moves on its own โ a run ends, a build releases its- // lease โ and the list is not refetched on focus. Re-read it each- // time the menu opens, so a copy is not offered or refused on a- // stale answer. A Redis read on the server, never a sandbox.- if (next && data) void refreshInstances();- }}- >- <div>- <Tooltip- title={- current && currentBlocked- ? t('sandboxStorage.privateInstanceBlocked', { name: current.name })- : undefined- }- >- <div className={cx(workingDirectoryChipStyles.chip, currentBlocked && styles.blocked)}>- {chipIcon}- {resolvingInstance ? (- <Skeleton.Text rows={1} style={{ height: 12, width: 56 }} />- ) : (- <span className={workingDirectoryChipStyles.label}>{chipLabel}</span>- )}- <Icon icon={ChevronDownIcon} size={12} />- </div>- </Tooltip>- </div>- </Popover>- );- },-);--SandboxInstancePicker.displayName = 'SandboxInstancePicker';--export default SandboxInstancePicker;diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsxindex 6773c8ebc5f..fd30989d515 100644--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -3,11 +3,11 @@import { memo } from 'react';import SafeBoundary from '@/components/ErrorBoundary';-import { useAgentStore } from '@/store/agent';import { useTopicId } from '../hooks/useTopicId';-import SandboxInstancePicker from './SandboxInstancePicker';-import { useSandboxMode } from './useSandboxMode';+import SandboxDrivePicker from './SandboxDrivePicker';+import SandboxEnvironmentPicker from './SandboxEnvironmentPicker';+import { useSandboxPlacement } from './useSandboxPlacement';import { useSandboxStorageAccess } from './useSandboxStorageAccess';interface SandboxStorageSectionProps {@@ -18,33 +18,33 @@ interface SandboxStorageSectionProps {* The working directory of a cloud-sandbox run โ the counterpart of* `WorkingDirectorySection`, which covers runs on a machine, and shaped the* same way: one chip that always names the slot, whose menu holds every place- * the run could keep its files.+ * the run could work.*- * Nothing chosen means a temporary directory, cleaned up with the sandbox. The- * persistent choices are an environment's instances: a folder plus everything- * installed into it, so two conversations that must not overwrite each other- * take two instances. A persistent run always lives in one, as in Codex โ the- * server's root fallback exists for a deleted instance, not as a choice.+ * Nothing chosen means a temporary sandbox, cleaned up with the session; a+ * folder on the drive keeps its files. Beside it, the environment the working+ * directory is initialized from โ a separate choice, so a temporary sandbox+ * can start from a checkout too.*- * A plan without persistence still gets the chip: the temporary directory is+ * A plan without a drive still gets the chip: the temporary sandbox is* everyone's, and the way to a plan is a row in the same menu rather than a* different control.*/const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {const { status } = useSandboxStorageAccess(agentId);- const { selection, setSelection, topicId } = useSandboxMode(agentId, useTopicId());- const agentIsPublic = useAgentStore((s) => s.agentMap[agentId]?.visibility === 'public');+ const { selection, setSelection, topicId } = useSandboxPlacement(agentId, useTopicId());if (status === 'hidden') return null;return (- <SandboxInstancePicker- agentIsPublic={agentIsPublic}- entitled={status === 'ready'}- topicId={topicId}- value={selection}- onChange={setSelection}- />+ <>+ <SandboxDrivePicker+ entitled={status === 'ready'}+ topicId={topicId}+ value={selection}+ onChange={setSelection}+ />+ <SandboxEnvironmentPicker value={selection} onChange={setSelection} />+ </>);});diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 6a273188e56..7ec8c0029d0 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -169,7 +169,7 @@ const styles = createStaticStyles(({ css }) => ({const isValidWorkingDirEntry = (entry: WorkingDirEntry): boolean =>!!getWorkingDirectoryPathString(entry.path);-type FolderEntry = { path: string; repoType?: 'git' | 'github' };+type FolderEntry = { environmentId?: string; path: string; repoType?: 'git' | 'github' };/** This machine: browse the filesystem via the native Electron folder dialog. */const ChooseLocalFolderRow = memo<{ defaultPath?: string; onPick: (entry: FolderEntry) => void }>(@@ -209,7 +209,14 @@ const AddRemoteFolderRow = memo<{const handleClick = () => {onBeforeOpen();- openPickWorkingDirModal({ defaultPath: defaultCwd || undefined, deviceId, onPick });+ // A folder picked on a device may go with a code environment. Only the+ // association is kept โ nothing clones or sets up on the device.+ openPickWorkingDirModal({+ defaultPath: defaultCwd || undefined,+ deviceId,+ onPick,+ withEnvironment: true,+ });};return (<Flexboxdiff --git a/src/features/ChatInput/ControlBar/__tests__/sandboxEnvironmentRows.test.ts b/src/features/ChatInput/ControlBar/__tests__/sandboxEnvironmentRows.test.tsdeleted file mode 100644index e33a6afaab1..00000000000--- a/src/features/ChatInput/ControlBar/__tests__/sandboxEnvironmentRows.test.ts+++ /dev/null@@ -1,201 +0,0 @@-import { describe, expect, it } from 'vitest';--import {- copyChipLabel,- copyMenuActions,- describeEnvironmentRow,- pickCopyForEnvironment,- type PickerCopy,-} from '../sandboxEnvironmentRows';--const copy = (id: string, minute: number, overrides: Partial<PickerCopy> = {}): PickerCopy => ({- createdAt: new Date(Date.UTC(2026, 9, 1, 0, minute)),- environmentId: 'env-1',- id,- inUse: false,- inUseByThisTopic: false,- status: 'ready',- ...overrides,-});--const busy = { inUse: true, inUseByThisTopic: false };--describe('pickCopyForEnvironment', () => {- it('keeps the copy this conversation is already bound to, even when the default is free', () => {- const copies = [copy('default', 0), copy('second', 1)];-- expect(pickCopyForEnvironment(copies, 'second')?.id).toBe('second');- });-- it('keeps the bound copy even when another run holds it', () => {- const copies = [copy('default', 0), copy('second', 1, busy)];-- expect(pickCopyForEnvironment(copies, 'second')?.id).toBe('second');- });-- it('picks the default (earliest) copy when nothing here is bound', () => {- // Listed out of order on purpose: the rule reads createdAt, not position.- const copies = [copy('second', 5), copy('default', 0), copy('third', 9)];-- expect(pickCopyForEnvironment(copies, 'somewhere-else')?.id).toBe('default');- });-- it('falls through to the first free copy when the default is occupied', () => {- const copies = [copy('default', 0, busy), copy('third', 9), copy('second', 5)];-- expect(pickCopyForEnvironment(copies, undefined)?.id).toBe('second');- });-- it('skips a copy that is still building', () => {- const copies = [- copy('default', 0, busy),- copy('second', 5, { status: 'pending' }),- copy('third', 9),- ];-- expect(pickCopyForEnvironment(copies, undefined)?.id).toBe('third');- });-- it("treats this conversation's own run as free", () => {- const copies = [copy('default', 0, { inUse: true, inUseByThisTopic: true }), copy('second', 5)];-- expect(pickCopyForEnvironment(copies, undefined)?.id).toBe('default');- });-- it('picks nothing when every copy is taken', () => {- const copies = [copy('default', 0, busy), copy('second', 5, busy)];-- expect(pickCopyForEnvironment(copies, undefined)).toBeUndefined();- });-});--describe('describeEnvironmentRow', () => {- it('shows a single copy as one row with no second menu', () => {- const row = describeEnvironmentRow({- copies: [copy('only', 0)],- isCreator: true,- kind: 'code',- });-- expect(row).toMatchObject({ hasSubmenu: false, lazyCreate: false, selectable: true });- expect(row.picked?.id).toBe('only');- });-- it('offers the second menu only with several copies, default first', () => {- const row = describeEnvironmentRow({- copies: [copy('second', 5), copy('default', 0)],- isCreator: false,- kind: 'code',- });-- expect(row.hasSubmenu).toBe(true);- expect(row.copies.map((item) => item.id)).toEqual(['default', 'second']);- });-- it('never offers a second menu on a files environment, however many copies it has', () => {- const row = describeEnvironmentRow({- boundInstanceId: 'second',- copies: [copy('default', 0), copy('second', 5)],- isCreator: true,- kind: 'files',- });-- expect(row.hasSubmenu).toBe(false);- // The conversation stays on the copy it is already bound to.- expect(row.picked?.id).toBe('second');- });-- it('cannot be picked when every copy is taken, and shows the default copy state', () => {- const row = describeEnvironmentRow({- copies: [copy('default', 0, busy), copy('second', 5, busy)],- isCreator: true,- kind: 'code',- });-- expect(row.selectable).toBe(false);- expect(row.picked).toBeUndefined();- expect(row.displayed?.id).toBe('default');- });-- it('shows the state of the copy a click would bind', () => {- const row = describeEnvironmentRow({- copies: [copy('default', 0, busy), copy('second', 5, { status: 'error' })],- isCreator: true,- kind: 'code',- });-- expect(row.displayed?.id).toBe('second');- expect(row.displayed?.status).toBe('error');- });-- it('creates the copy on first pick for the creator of an environment with none', () => {- const row = describeEnvironmentRow({ copies: [], isCreator: true, kind: 'code' });-- expect(row).toMatchObject({ hasSubmenu: false, lazyCreate: true, selectable: true });- });-- it('leaves a colleague unable to pick a published environment with no copy', () => {- const row = describeEnvironmentRow({ copies: [], isCreator: false, kind: 'code' });-- expect(row).toMatchObject({ lazyCreate: false, selectable: false });- });-});--describe('copyMenuActions', () => {- it('offers stop and open-another-copy to the creator of a code environment', () => {- expect(copyMenuActions({ copy: copy('a', 0, busy), isCreator: true, kind: 'code' })).toEqual([- 'stop',- 'reopen',- ]);- });-- it('offers only stop on a files environment', () => {- expect(copyMenuActions({ copy: copy('a', 0, busy), isCreator: true, kind: 'files' })).toEqual([- 'stop',- ]);- });-- it('offers nothing to a colleague', () => {- expect(copyMenuActions({ copy: copy('a', 0, busy), isCreator: false, kind: 'code' })).toEqual(- [],- );- expect(copyMenuActions({ copy: copy('a', 0, busy), isCreator: false, kind: 'files' })).toEqual(- [],- );- });-- it('has no stop while nothing else holds the copy', () => {- expect(copyMenuActions({ copy: copy('a', 0), isCreator: true, kind: 'code' })).toEqual([- 'reopen',- ]);- expect(copyMenuActions({ copy: copy('a', 0), isCreator: true, kind: 'files' })).toEqual([]);- });-- it('cannot stop a build', () => {- expect(- copyMenuActions({- copy: copy('a', 0, { ...busy, status: 'pending' }),- isCreator: true,- kind: 'code',- }),- ).toEqual(['reopen']);- });-});--describe('copyChipLabel', () => {- it('names only the environment when it has one copy', () => {- expect(copyChipLabel({ copy: { name: 'web' }, copyCount: 1, environmentName: 'Web' })).toBe(- 'Web',- );- });-- it('names the environment and the copy when there are several', () => {- expect(copyChipLabel({ copy: { name: 'web-2' }, copyCount: 2, environmentName: 'Web' })).toBe(- 'Web ยท web-2',- );- });-- it('falls back to the copy name when the environment is unknown', () => {- expect(copyChipLabel({ copy: { name: 'web-2' }, copyCount: 2 })).toBe('web-2');- });-});diff --git a/src/features/ChatInput/ControlBar/__tests__/useCreateCopy.test.ts b/src/features/ChatInput/ControlBar/__tests__/useCreateCopy.test.tsdeleted file mode 100644index 66b81b91d25..00000000000--- a/src/features/ChatInput/ControlBar/__tests__/useCreateCopy.test.ts+++ /dev/null@@ -1,163 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { useCreateCopy } from '../useCreateCopy';--const service = vi.hoisted(() => ({- createInstanceForEnvironment: vi.fn(),- startInstanceBuild: vi.fn(),-}));--vi.mock('@/services/sandboxStorage', () => ({ sandboxStorageService: service }));--const created = {- createdAt: new Date('2026-10-01T00:05:00Z'),- environmentId: 'env',- id: 'env-2',- name: 'env-2',- workingDirectory: 'env-2',-};--interface Listed {- instances: Record<string, unknown>[];-}--const listed = (environmentId: string, id: string) => ({ environmentId, id });--const setup = (previous: Listed = { instances: [] }) => {- const onChange = vi.fn().mockResolvedValue(undefined);- const onBuildError = vi.fn();- const onCreateError = vi.fn();- let cache = previous;- const refreshInstances = vi.fn(async (update?: (value: Listed) => Listed) => {- if (update) cache = update(cache);- });-- const { result } = renderHook(() =>- useCreateCopy({- onBuildError,- onChange,- refreshInstances: refreshInstances as unknown as Parameters<- typeof useCreateCopy- >[0]['refreshInstances'],- topicId: 'topic-1',- }),- );-- return { cache: () => cache, onBuildError, onChange, onCreateError, refreshInstances, result };-};--beforeEach(() => {- vi.clearAllMocks();- service.createInstanceForEnvironment.mockResolvedValue(created);- service.startInstanceBuild.mockResolvedValue({ buildId: 'build-1' });-});--describe('useCreateCopy', () => {- it('creates the copy, binds this conversation to it, then starts its build', async () => {- const { onChange, onCreateError, result } = setup();-- await act(() => result.current.create('env', onCreateError));-- expect(service.createInstanceForEnvironment).toHaveBeenCalledWith({ environmentId: 'env' });- expect(onChange).toHaveBeenCalledWith({ instanceId: 'env-2', mode: 'persistent' });- expect(service.startInstanceBuild).toHaveBeenCalledWith({ id: 'env-2', topicId: 'topic-1' });-- const order = [- service.createInstanceForEnvironment.mock.invocationCallOrder[0],- onChange.mock.invocationCallOrder[0],- service.startInstanceBuild.mock.invocationCallOrder[0],- ];- expect(order).toEqual([...order].sort((a, b) => a - b));- expect(onCreateError).not.toHaveBeenCalled();- });-- it('lists the new copy as building before the build starts', async () => {- const { cache, onCreateError, result } = setup({- instances: [listed('env', 'env-1')],- });-- await act(() => result.current.create('env', onCreateError));-- expect(cache().instances).toHaveLength(2);- expect(cache().instances[1]).toMatchObject({- environmentId: 'env',- id: 'env-2',- inUse: false,- // A sibling exists, so the new one is not the default.- isDefault: false,- status: 'pending',- });- });-- it('marks a lazily created copy โ the only one of its environment โ as the default', async () => {- const { cache, onCreateError, result } = setup({- instances: [listed('other', 'other-1')],- });-- await act(() => result.current.create('env', onCreateError));-- expect(cache().instances[1]).toMatchObject({ id: 'env-2', isDefault: true });- });-- it('binds nothing and reports when the copy cannot be created', async () => {- const failure = new Error('NOT_FOUND');- service.createInstanceForEnvironment.mockRejectedValue(failure);- const { onChange, onCreateError, result } = setup();-- await act(() => result.current.create('env', onCreateError));-- expect(onCreateError).toHaveBeenCalledWith(failure);- expect(onChange).not.toHaveBeenCalled();- expect(service.startInstanceBuild).not.toHaveBeenCalled();- });-- it('still starts the build when binding the conversation fails', async () => {- // The copy is already on the server: left unbuilt it would read "Building"- // forever, with nothing in the picker to start it.- const failure = new Error('offline');- const { onChange, onCreateError, result } = setup();- onChange.mockRejectedValue(failure);-- await act(() => result.current.create('env', onCreateError));- await act(async () => {});-- expect(service.startInstanceBuild).toHaveBeenCalledWith({ id: 'env-2', topicId: 'topic-1' });- expect(onCreateError).toHaveBeenCalledWith(failure);- });-- it('keeps the copy bound when only its build fails to start', async () => {- const failure = new Error('build');- service.startInstanceBuild.mockRejectedValue(failure);- const { onBuildError, onChange, onCreateError, result } = setup();-- await act(() => result.current.create('env', onCreateError));- await act(async () => {});-- expect(onChange).toHaveBeenCalledWith({ instanceId: 'env-2', mode: 'persistent' });- expect(onBuildError).toHaveBeenCalledWith(failure);- expect(onCreateError).not.toHaveBeenCalled();- });-- it('marks the environment as preparing until the copy is bound', async () => {- let resolveCreate: (value: typeof created) => void = () => {};- service.createInstanceForEnvironment.mockReturnValue(- new Promise((resolve) => {- resolveCreate = resolve;- }),- );- const { onCreateError, result } = setup();-- let pending: Promise<void> = Promise.resolve();- act(() => {- pending = result.current.create('env', onCreateError);- });- expect(result.current.isPreparing('env')).toBe(true);-- await act(async () => {- resolveCreate(created);- await pending;- });- expect(result.current.isPreparing('env')).toBe(false);- });-});diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.tsnew file mode 100644index 00000000000..4a5fe096de8--- /dev/null+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { environmentChipState, pickableEnvironments } from './sandboxEnvironmentOptions';++const environments = [+ { id: 'mine', visibility: 'private' },+ { id: 'team', visibility: 'public' },+];++describe('pickableEnvironments', () => {+ it('offers a workspace-public agent the published environments only', () => {+ expect(pickableEnvironments(environments, true).map((e) => e.id)).toEqual(['team']);+ });++ it('offers everyone else every environment they can read, their own private ones included', () => {+ expect(pickableEnvironments(environments, false).map((e) => e.id)).toEqual(['mine', 'team']);+ });+});++describe('environmentChipState', () => {+ it('names the picked environment once the list has it', () => {+ expect(+ environmentChipState({+ current: { name: 'Tools' },+ environmentId: 'env',+ failed: false,+ loaded: true,+ }),+ ).toEqual({ kind: 'picked', name: 'Tools' });+ });++ it('does not call a picked environment "none" while the list loads or after it failed', () => {+ expect(environmentChipState({ environmentId: 'env', failed: false, loaded: false })).toEqual({+ kind: 'loading',+ });+ expect(environmentChipState({ environmentId: 'env', failed: true, loaded: false })).toEqual({+ kind: 'loadFailed',+ });+ });++ it('says a picked environment is unavailable only when the loaded list lacks it', () => {+ expect(environmentChipState({ environmentId: 'env', failed: false, loaded: true })).toEqual({+ kind: 'missing',+ });+ expect(environmentChipState({ failed: true, loaded: false })).toEqual({ kind: 'none' });+ });+});diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.tsnew file mode 100644index 00000000000..81c1a849ced--- /dev/null+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts@@ -0,0 +1,43 @@+/**+ * The environments a conversation may start from. A workspace-public agent runs+ * on its caller's session, so it applies published environments only โ the+ * server refuses a private one for it, and offering it here would promise a+ * setup that never runs.+ */+export const pickableEnvironments = <T extends { visibility?: string | null }>(+ environments: readonly T[],+ sharedAgent: boolean,+): T[] =>+ sharedAgent+ ? environments.filter((environment) => environment.visibility === 'public')+ : [...environments];++/**+ * 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 as+ * "none", which would read as initialization being off.+ */+export type EnvironmentChipState =+ | { kind: 'loading' }+ | { kind: 'loadFailed' }+ | { kind: 'missing' }+ | { kind: 'none' }+ | { kind: 'picked'; name: string };++export const environmentChipState = ({+ current,+ environmentId,+ failed,+ loaded,+}: {+ current?: { name: string };+ environmentId?: string;+ failed: boolean;+ loaded: boolean;+}): EnvironmentChipState => {+ if (!environmentId) return { kind: 'none' };+ if (current) return { kind: 'picked', name: current.name };+ if (loaded) return { kind: 'missing' };++ return failed ? { kind: 'loadFailed' } : { kind: 'loading' };+};diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentRows.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentRows.tsdeleted file mode 100644index 0e10e8bbee1..00000000000--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentRows.ts+++ /dev/null@@ -1,189 +0,0 @@-import { type EnvironmentKind } from '@lobechat/types';-import {- compareInstancesForDefault,- pickDefaultInstance,-} from '@lobechat/utils/environmentInstance';--/**- * How the composer's environment picker reads an environment and its copies.- *- * Kept apart from the component because these are the rules people will ask- * about โ "why did it pick that copy", "why can't I pick this one" โ and a rule- * spread across JSX is one nobody can test without rendering a menu.- *- * "Copy" is the product's word for an instance: the data layer and the API keep- * calling it an instance, and so does this file wherever it touches them.- */--/** The fields of a listed instance these rules read. */-export interface PickerCopy {- createdAt: Date | string;- environmentId: string;- id: string;- /** Held by some sandbox run, this conversation's own included. */- inUse: boolean;- /** Held by this conversation's own run. */- inUseByThisTopic: boolean;- status: string;-}--/**- * Somebody else's run holds it. The execution plane allows one writer per- * instance and answers the second with 409 INSTANCE_IN_USE, so offering it would- * offer a choice the next message refuses. This conversation's own run is the- * opposite case and never counts.- */-export const isCopyOccupied = (copy: PickerCopy) => copy.inUse && !copy.inUseByThisTopic;--/** A build holds the same single-writer lease while it publishes. */-export const isCopyBuilding = (copy: PickerCopy) => copy.status === 'pending';--/**- * Whether a conversation can start using this copy now. A failed build is- * still free: a conversation pointed at it is how someone gets back to it.- */-export const isCopyFree = (copy: PickerCopy) => !isCopyOccupied(copy) && !isCopyBuilding(copy);--/** The default copy first, then the others in the order they were made. */-export const sortCopies = <T extends PickerCopy>(copies: readonly T[]): T[] =>- copies.toSorted(compareInstancesForDefault);--/**- * The copy a click on the environment row binds, in order:- *- * 1. the copy this conversation is already bound to in this environment โ a- * click on the row it is already in must not move its files;- * 2. the default copy, when it is free;- * 3. the first free copy after it.- *- * `undefined` when every copy is held or building: the row is then not- * selectable, and the way forward is to stop a run or open another copy.- */-export const pickCopyForEnvironment = <T extends PickerCopy>(- copies: readonly T[],- boundInstanceId: string | undefined,-): T | undefined => {- const bound = boundInstanceId ? copies.find((copy) => copy.id === boundInstanceId) : undefined;- if (bound) return bound;-- const defaultCopy = pickDefaultInstance(copies);- if (defaultCopy && isCopyFree(defaultCopy)) return defaultCopy;-- return sortCopies(copies).find(isCopyFree);-};--/** The `โฎ` menu of an environment row or a copy row. */-export type CopyMenuAction = 'reopen' | 'stop';--/**- * Which actions the `โฎ` menu offers for a copy.- *- * Both are the environment creator's alone โ the server checks the same owner- * on `stopInstance` and `createInstanceForEnvironment` โ so a colleague on a- * published environment gets no menu and waits. "Open another copy" rebuilds- * from the environment's specification, and a files environment's- * specification holds no files: it would hand back an empty folder, so a files- * environment can only be stopped.- */-export const copyMenuActions = ({- copy,- isCreator,- kind,-}: {- /** The copy the menu acts on; absent on an environment with no copy yet. */- copy?: PickerCopy;- isCreator: boolean;- kind: EnvironmentKind;-}): CopyMenuAction[] => {- if (!isCreator) return [];-- const actions: CopyMenuAction[] = [];- // A build cannot be stopped from here โ it is not a conversation's run.- if (copy && isCopyOccupied(copy) && !isCopyBuilding(copy)) actions.push('stop');- if (kind === 'code') actions.push('reopen');-- return actions;-};--export interface EnvironmentRowState<T extends PickerCopy> {- /** The copies, default first. */- copies: T[];- /** The copy whose state the row shows: the one a click binds, else the default. */- displayed?: T;- /**- * Only for a code environment with several copies: one copy needs no second- * menu to choose it, and a files environment is one folder for one- * conversation at a time โ the click still lands on the copy it is bound to.- */- hasSubmenu: boolean;- /**- * No copy yet, and the person may make one: an environment from before every- * environment got a default copy. Picking it creates that copy first.- */- lazyCreate: boolean;- /** The copy a click on the row binds. */- picked?: T;- /** Whether a click on the row does anything. */- selectable: boolean;-}--/**- * Everything an environment row needs, from its copies.- *- * The row's state is the state of the copy it would bind โ the one the person- * is actually choosing โ and falls back to the default copy's when every copy- * is taken, so the row says why it is blocked.- */-export const describeEnvironmentRow = <T extends PickerCopy>({- boundInstanceId,- copies,- isCreator,- kind,-}: {- boundInstanceId?: string;- copies: readonly T[];- isCreator: boolean;- kind: EnvironmentKind;-}): EnvironmentRowState<T> => {- const sorted = sortCopies(copies);- const picked = pickCopyForEnvironment(sorted, boundInstanceId);-- if (sorted.length === 0) {- // Only the creator can make the copy; a colleague looking at a published- // environment whose creator never made one has nothing to run in.- return {- copies: sorted,- hasSubmenu: false,- lazyCreate: isCreator,- selectable: isCreator,- };- }-- return {- copies: sorted,- displayed: picked ?? sorted[0],- hasSubmenu: kind === 'code' && sorted.length > 1,- lazyCreate: false,- picked,- selectable: Boolean(picked),- };-};--/**- * The chip's words for a bound copy. The environment is what people chose, so- * it leads; the copy is named only when there is more than one to tell apart.- */-export const copyChipLabel = ({- copy,- copyCount,- environmentName,-}: {- copy: { name: string };- copyCount: number;- environmentName?: string;-}): string => {- if (!environmentName) return copy.name;- if (copyCount <= 1) return environmentName;-- return `${environmentName} ยท ${copy.name}`;-};diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex e2d206f47a2..cd85db28fc0 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -61,6 +61,9 @@ const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | und};const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({+ // Metadata only: the code environment the folder was picked with. Nothing+ // runs it on a device yet; it travels so the association is not lost.+ ...(entry.environmentId ? { environmentId: entry.environmentId } : {}),...(entry.git ? { git: entry.git } : {}),path: entry.path,...(entry.repoType ? { repoType: entry.repoType } : {}),diff --git a/src/features/ChatInput/ControlBar/useCreateCopy.ts b/src/features/ChatInput/ControlBar/useCreateCopy.tsdeleted file mode 100644index 5e8d02c4878..00000000000--- a/src/features/ChatInput/ControlBar/useCreateCopy.ts+++ /dev/null@@ -1,99 +0,0 @@-import { useCallback } from 'react';--import { sandboxStorageService } from '@/services/sandboxStorage';-import type { SandboxPickerInstanceList } from '@/store/sandbox';--import { usePendingIds } from './usePendingIds';-import type { SandboxSelection } from './useSandboxMode';--interface UseCreateCopyOptions {- /** The build could not be started; the copy exists and stays bound. */- onBuildError: (error: unknown) => void;- onChange: (selection: SandboxSelection) => Promise<void>;- /** The picker's instance-list edit (`sandboxActions.mutatePickerInstances`). */- refreshInstances: (- update?: (- previous: SandboxPickerInstanceList | undefined,- ) => SandboxPickerInstanceList | undefined,- options?: { revalidate: boolean },- ) => Promise<unknown>;- topicId?: string;-}--/**- * A new copy of an environment, bound to this conversation and built.- *- * One path for both ways the composer makes a copy: an environment from before- * every environment got a default copy, picked for the first time, and "open- * another copy" when the ones there are taken. Built from the environment's- * specification โ the busy copy's state belongs to the run holding it โ with the- * name and folder derived server-side, so there is nothing to ask.- *- * The copy is listed and bound before its build is even started, so it shows up- * as "Building" at once rather than after the build's cold start.- */-export const useCreateCopy = ({- onBuildError,- onChange,- refreshInstances,- topicId,-}: UseCreateCopyOptions) => {- // Environments a copy is being made for.- const preparing = usePendingIds();-- const create = useCallback(- /** `onCreateError`: no copy was made, or it was made and could not be bound. */- async (environmentId: string, onCreateError: (error: unknown) => void) => {- preparing.add(environmentId);- try {- const created = await sandboxStorageService.createInstanceForEnvironment({- environmentId,- });- await refreshInstances(- (previous) =>- previous && {- ...previous,- instances: [- ...previous.instances,- {- createdAt: new Date(created.createdAt).toISOString(),- environmentId: created.environmentId,- id: created.id,- inUse: false,- inUseByThisTopic: false,- // Never the default beside others: it is the newest. Alone it- // is the only one, and the next listing marks it so.- isDefault: previous.instances.every(- (instance) => instance.environmentId !== environmentId,- ),- name: created.name,- status: 'pending' as const,- workingDirectory: created.workingDirectory,- },- ],- },- { revalidate: false },- );- try {- await onChange({ instanceId: created.id, mode: 'persistent' });- } finally {- // Whether or not the binding was written: the copy exists by now, and- // one whose build never starts reads "Building" for good. A failed- // binding is still reported below โ the copy is simply left usable.- void sandboxStorageService- .startInstanceBuild({ id: created.id, topicId })- .catch(onBuildError)- .finally(() => void refreshInstances());- }- } catch (error) {- onCreateError(error);- void refreshInstances();- } finally {- preparing.remove(environmentId);- }- },- [onBuildError, onChange, preparing.add, preparing.remove, refreshInstances, topicId],- );-- return { create, isPreparing: preparing.has };-};diff --git a/src/features/ChatInput/ControlBar/usePendingIds.test.ts b/src/features/ChatInput/ControlBar/usePendingIds.test.tsdeleted file mode 100644index 5c328cb56fb..00000000000--- a/src/features/ChatInput/ControlBar/usePendingIds.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { describe, expect, it } from 'vitest';--import { usePendingIds } from './usePendingIds';--describe('usePendingIds', () => {- it('keeps a later request busy when an earlier overlapping one settles first', () => {- const { result } = renderHook(() => usePendingIds());-- act(() => result.current.add('a'));- act(() => result.current.add('b'));- expect(result.current.has('a')).toBe(true);- expect(result.current.has('b')).toBe(true);-- // A settles first; B is still in flight and must stay busy.- act(() => result.current.remove('a'));- expect(result.current.has('a')).toBe(false);- expect(result.current.has('b')).toBe(true);-- act(() => result.current.remove('b'));- expect(result.current.has('b')).toBe(false);- });-- it('ignores removing an id that is not pending', () => {- const { result } = renderHook(() => usePendingIds());-- act(() => result.current.add('a'));- act(() => result.current.remove('missing'));-- expect(result.current.has('a')).toBe(true);- });-});diff --git a/src/features/ChatInput/ControlBar/usePendingIds.ts b/src/features/ChatInput/ControlBar/usePendingIds.tsdeleted file mode 100644index c785fff1cef..00000000000--- a/src/features/ChatInput/ControlBar/usePendingIds.ts+++ /dev/null@@ -1,29 +0,0 @@-import { useCallback, useState } from 'react';--/**- * Which items have a request in flight, tracked per item.- *- * A set rather than one id: two requests can overlap, and with a single id the- * second moved the spinner off the first, and whichever settled first cleared- * the other's busy state โ re-enabling an action whose request was still- * running.- */-export const usePendingIds = () => {- const [ids, setIds] = useState<ReadonlySet<string>>(() => new Set());-- const add = useCallback((id: string) => setIds((current) => new Set(current).add(id)), []);-- const remove = useCallback(- (id: string) =>- setIds((current) => {- const next = new Set(current);- next.delete(id);- return next;- }),- [],- );-- const has = useCallback((id: string) => ids.has(id), [ids]);-- return { add, has, remove };-};diff --git a/src/features/ChatInput/ControlBar/useSandboxMode.test.ts b/src/features/ChatInput/ControlBar/useSandboxMode.test.tsdeleted file mode 100644index 04e1198196f..00000000000--- a/src/features/ChatInput/ControlBar/useSandboxMode.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';--import { useSandboxMode } from './useSandboxMode';--interface TopicSandbox {- sandboxInstanceId?: string;- sandboxMode?: 'ephemeral' | 'persistent';-}--const state = vi.hoisted(() => ({- activeTopicId: undefined as string | undefined,- topics: {} as Record<string, TopicSandbox>,- updateTopicMetadata: vi.fn(),-}));--// Store boundary: the real topic selectors run against this state.-vi.mock('@/store/chat', () => ({- useChatStore: (selector: (s: object) => unknown) =>- selector({- activeTopicId: state.activeTopicId,- topicDataMap: {},- topicDetailMap: Object.fromEntries(- Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),- ),- updateTopicMetadata: state.updateTopicMetadata,- }),-}));--beforeEach(() => {- // The main column's topic stays globally active while a side pane renders another.- state.activeTopicId = 'main-topic';- state.topics = {- 'main-topic': { sandboxInstanceId: 'main-instance', sandboxMode: 'persistent' },- 'pane-topic': { sandboxMode: 'ephemeral' },- };- state.updateTopicMetadata.mockReset();-});--describe('useSandboxMode', () => {- it('reads and writes the given topic instead of the global active topic', async () => {- const { result } = renderHook(() => useSandboxMode('agent-1', 'pane-topic'));-- expect(result.current.selection).toEqual({ instanceId: undefined, mode: 'ephemeral' });- expect(result.current.topicId).toBe('pane-topic');-- await act(() =>- result.current.setSelection({ instanceId: 'pane-instance', mode: 'persistent' }),- );-- expect(state.updateTopicMetadata).toHaveBeenCalledWith('pane-topic', {- sandboxInstanceId: 'pane-instance',- sandboxMode: 'persistent',- });- });-- it('buffers the choice for a conversation without a topic even while another topic is active', async () => {- const { result } = renderHook(() => useSandboxMode('agent-new-topic', null));-- expect(result.current.selection).toEqual({});- expect(result.current.topicId).toBeUndefined();-- await act(() => result.current.setSelection({ mode: 'persistent' }));-- expect(state.updateTopicMetadata).not.toHaveBeenCalled();- expect(getPendingSandboxSelection('agent-new-topic')).toEqual({ mode: 'persistent' });- });-- it('follows the global active topic when no topic is given', () => {- const { result } = renderHook(() => useSandboxMode('agent-1'));-- expect(result.current.selection).toEqual({- instanceId: 'main-instance',- mode: 'persistent',- });- expect(result.current.topicId).toBe('main-topic');- });-});diff --git a/src/features/ChatInput/ControlBar/useSandboxMode.ts b/src/features/ChatInput/ControlBar/useSandboxMode.tsdeleted file mode 100644index 1e6d830c986..00000000000--- a/src/features/ChatInput/ControlBar/useSandboxMode.ts+++ /dev/null@@ -1,88 +0,0 @@-import { useCallback, useSyncExternalStore } from 'react';--import { useChatStore } from '@/store/chat';-import {- getPendingSandboxSelection,- setPendingSandboxSelection,- subscribePendingSandboxSelection,-} from '@/store/chat/pendingSandboxSelection';-import { topicSelectors } from '@/store/chat/selectors';--export type SandboxMode = 'ephemeral' | 'persistent';--export interface SandboxSelection {- /** Only meaningful with `persistent`; absent means the workspace root. */- instanceId?: string;- /**- * Absent means nothing has been chosen โ which the server runs as ephemeral,- * but which the picker must not show as the temporary directory being- * PICKED. A choice is something the user made; the default is not one.- */- mode?: SandboxMode;-}--/**- * What the current conversation's cloud sandbox keeps, read and written from- * one place.- *- * Two surfaces answer this โ the execution-device menu (keep files or not) and- * the working-directory chip (which directory) โ and both must see the same- * state, or a toggle in one would not move the other. Absent means ephemeral,- * which is how the server reads it too (`sandboxMode !== 'persistent'`).- *- * Before a topic exists the choice is buffered by agent and carried by the- * first send; see `pendingSandboxSelection`.- *- * `scopeTopicId` is the conversation the caller belongs to; `null` means it has- * no topic yet. Omitted, it follows the global active topic.- */-export const useSandboxMode = (agentId: string, scopeTopicId?: string | null) => {- const activeTopicId = useChatStore((s) => s.activeTopicId);- const topicId = scopeTopicId === undefined ? activeTopicId : scopeTopicId;- const topicMetadata = useChatStore((s) =>- topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,- );- const topicInstanceId = topicMetadata?.sandboxInstanceId;- const topicMode = topicMetadata?.sandboxMode;- const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);- // The pending value lives outside React, so this subscribes to it the way a- // store would be subscribed to. Every component using this hook re-renders- // on a write, not just the one that wrote โ a local force-update here left- // the other reader showing the old value.- const pending = useSyncExternalStore(subscribePendingSandboxSelection, () =>- getPendingSandboxSelection(agentId),- );-- const selection: SandboxSelection = topicId- ? { instanceId: topicInstanceId, mode: topicMode }- : (pending ?? {});-- const setSelection = useCallback(- async (next: SandboxSelection) => {- if (!topicId) {- setPendingSandboxSelection(agentId, next);- return;- }-- // Written whole, both fields every time. Deriving the mode from "did they- // pick an instance" is what made this a one-way switch: nothing could then- // express "keep nothing", so a conversation that once touched this menu- // could never go back to a throwaway box.- await updateTopicMetadata(topicId, {- sandboxInstanceId: next.instanceId,- sandboxMode: next.mode,- });- },- [agentId, topicId, updateTopicMetadata],- );-- // Turning persistence off also drops the instance: a binding kept behind an- // ephemeral run would silently come back the next time the switch is on.- const setMode = useCallback(- (mode: SandboxMode) =>- setSelection(mode === 'persistent' ? { ...selection, mode } : { mode: 'ephemeral' }),- [selection, setSelection],- );-- return { selection, setMode, setSelection, topicId: topicId ?? undefined };-};diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.tsnew file mode 100644index 00000000000..818472a0680--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts@@ -0,0 +1,107 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';++import { isPersistentSelection, useSandboxPlacement } from './useSandboxPlacement';++interface TopicSandbox {+ sandboxDrive?: 'personal' | 'public';+ sandboxInstanceId?: string;+ sandboxWorkingDirectory?: string;+}++const state = vi.hoisted(() => ({+ activeTopicId: undefined as string | undefined,+ topics: {} as Record<string, TopicSandbox>,+ updateTopicMetadata: vi.fn(),+}));++// Store boundary: the real topic selectors run against this state.+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: object) => unknown) =>+ selector({+ activeTopicId: state.activeTopicId,+ topicDataMap: {},+ topicDetailMap: Object.fromEntries(+ Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),+ ),+ updateTopicMetadata: state.updateTopicMetadata,+ }),+}));++beforeEach(() => {+ // The main column's topic stays globally active while a side pane renders another.+ state.activeTopicId = 'main-topic';+ state.topics = {+ 'main-topic': { sandboxInstanceId: 'main-instance' },+ 'pane-topic': { sandboxDrive: 'personal', sandboxWorkingDirectory: 'reports' },+ };+ state.updateTopicMetadata.mockReset();+});++describe('useSandboxPlacement', () => {+ it('reads and writes the given topic instead of the global active topic', async () => {+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'pane-topic'));++ expect(result.current.selection).toEqual({+ drive: 'personal',+ instanceId: undefined,+ workingDirectory: 'reports',+ });+ expect(result.current.topicId).toBe('pane-topic');++ await act(() => result.current.setSelection({ drive: 'public', instanceId: 'pane-instance' }));++ // Picking an environment directory clears the folder, so the two never+ // both stand on one topic; the drive travels with whichever was picked.+ expect(state.updateTopicMetadata).toHaveBeenCalledWith('pane-topic', {+ sandboxDrive: 'public',+ sandboxInstanceId: 'pane-instance',+ sandboxWorkingDirectory: undefined,+ });+ });++ it('clears both halves when the temporary sandbox is picked', async () => {+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'pane-topic'));++ await act(() => result.current.setSelection({ drive: 'personal' }));++ expect(state.updateTopicMetadata).toHaveBeenCalledWith('pane-topic', {+ sandboxDrive: undefined,+ sandboxInstanceId: undefined,+ sandboxWorkingDirectory: undefined,+ });+ });++ it('buffers the choice for a conversation without a topic even while another topic is active', async () => {+ const { result } = renderHook(() => useSandboxPlacement('agent-new-topic', null));++ expect(result.current.selection).toEqual({});+ expect(result.current.topicId).toBeUndefined();++ await act(() => result.current.setSelection({ workingDirectory: '.' }));++ expect(state.updateTopicMetadata).not.toHaveBeenCalled();+ expect(getPendingSandboxSelection('agent-new-topic')).toEqual({ workingDirectory: '.' });+ });++ it('follows the global active topic when no topic is given', () => {+ const { result } = renderHook(() => useSandboxPlacement('agent-1'));++ expect(result.current.selection).toEqual({+ drive: undefined,+ instanceId: 'main-instance',+ workingDirectory: undefined,+ });+ expect(result.current.topicId).toBe('main-topic');+ });+});++describe('isPersistentSelection', () => {+ it('reads the drive root as a choice, and nothing as the temporary sandbox', () => {+ expect(isPersistentSelection({ workingDirectory: '.' })).toBe(true);+ expect(isPersistentSelection({ instanceId: 'i' })).toBe(true);+ expect(isPersistentSelection({})).toBe(false);+ });+});diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.tsnew file mode 100644index 00000000000..47df6b81039--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.ts@@ -0,0 +1,98 @@+import { useCallback, useSyncExternalStore } from 'react';++import { useChatStore } from '@/store/chat';+import {+ getPendingSandboxSelection,+ setPendingSandboxSelection,+ subscribePendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';+import { topicSelectors } from '@/store/chat/selectors';++/**+ * Where a conversation's cloud sandbox works, and what it starts from. Nothing+ * chosen is a temporary sandbox; choosing a folder IS the choice to keep files:+ *+ * - `workingDirectory` โ a folder on the drive, relative to its root (`.` is+ * the root itself);+ * - `environmentId` โ a code environment to initialize the working directory+ * from: its repository cloned and its setup run once there, whether that is+ * a temporary sandbox or a folder on the drive. Independent of the folder;+ * either can be set without the other.+ * - `instanceId` โ an environment directory from before environments became+ * one-time initializers. Read so an old conversation still shows where it+ * runs; never written, and any new pick clears it.+ *+ * In a workspace, `drive` says which drive the folder is on โ the public one+ * every member shares, or the member's personal one โ and absent means public.+ */+export interface SandboxSelection {+ drive?: 'personal' | 'public';+ environmentId?: string;+ instanceId?: string;+ workingDirectory?: string;+}++/** Whether a selection keeps anything โ a folder, or a legacy environment directory. */+export const isPersistentSelection = (selection: SandboxSelection) =>+ !!selection.instanceId || selection.workingDirectory !== undefined;++/**+ * What the current conversation's cloud sandbox keeps, read and written from+ * one place โ the composer's chip and the working panel's file tree must see+ * the same state, or a pick in one would not move the other.+ *+ * Before a topic exists the choice is buffered by agent and carried by the+ * first send; see `pendingSandboxSelection`.+ *+ * `scopeTopicId` is the conversation the caller belongs to; `null` means it has+ * no topic yet. Omitted, it follows the global active topic.+ */+export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | null) => {+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const topicId = scopeTopicId === undefined ? activeTopicId : scopeTopicId;+ const topicMetadata = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,+ );+ const topicInstanceId = topicMetadata?.sandboxInstanceId;+ const topicWorkingDirectory = topicMetadata?.sandboxWorkingDirectory;+ const topicDrive = topicMetadata?.sandboxDrive;+ const topicEnvironmentId = topicMetadata?.sandboxEnvironmentId;+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);+ // The pending value lives outside React, so this subscribes to it the way a+ // store would be subscribed to. Every component using this hook re-renders+ // on a write, not just the one that wrote.+ const pending = useSyncExternalStore(subscribePendingSandboxSelection, () =>+ getPendingSandboxSelection(agentId),+ );++ const selection: SandboxSelection = topicId+ ? {+ drive: topicDrive,+ environmentId: topicEnvironmentId,+ instanceId: topicInstanceId,+ workingDirectory: topicWorkingDirectory,+ }+ : (pending ?? {});++ const setSelection = useCallback(+ async (next: SandboxSelection) => {+ if (!topicId) {+ setPendingSandboxSelection(agentId, next);+ return;+ }++ // Written whole, every field every time: a stale half left behind would+ // come back the moment the other was cleared. A legacy environment+ // directory is only ever carried forward as it was, never chosen anew.+ await updateTopicMetadata(topicId, {+ sandboxDrive: isPersistentSelection(next) ? next.drive : undefined,+ sandboxEnvironmentId: next.environmentId,+ sandboxInstanceId: next.instanceId,+ sandboxWorkingDirectory: next.instanceId ? undefined : next.workingDirectory,+ });+ },+ [agentId, topicId, updateTopicMetadata],+ );++ return { selection, setSelection, topicId: topicId ?? undefined };+};diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 55d25bd3bc4..cb557c85d6f 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -46,7 +46,6 @@ import {PR_STATE_VISUAL,} from '@/features/AgentSidebar/Topic/List/Item/metaCardData';import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';-import { useSandboxMode } from '@/features/ChatInput/ControlBar/useSandboxMode';import { getPortalViewWidth } from '@/features/Portal/portalWidth';import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';import RightPanel from '@/features/RightPanel';@@ -69,7 +68,6 @@ import { deviceSelectors, useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';import DeferredSkeleton from './DeferredSkeleton';@@ -94,6 +92,7 @@ import PullRequest from './PullRequest';import { useLinkedPullRequest } from './PullRequest/useLinkedPullRequest';import ResourcesSection from './ResourcesSection';import Review from './Review';+import { useSandboxFilesDirectory } from './useSandboxFilesDirectory';import WorkspaceTab from './WorkspaceTab';import WorksSection from './WorksSection';@@ -353,35 +352,17 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })// Files/Review route a deviceId only for remote RPC; "This device" keeps Electron IPC.const remoteDeviceId = isDeviceMode ? agencyConfig.boundDeviceId : undefined;const isLocalExecution = effectiveTarget === 'local';- // A cloud-sandbox run keeps its files in the persistent workspace, so it has a- // tree to show too โ read through the topic's warm session rather than a- // device. Only when the run actually persists: a throwaway box keeps nothing,- // and pointing the panel at the workspace would let another conversation's- // files read as this one's.- // Through the same hook the composer writes with, so the panel sees a choice- // the moment it is made. Before a conversation exists the choice is buffered- // on the agent rather than stored on a topic, and reading the topic's- // metadata directly meant the panel could not see it: the composer said- // "cloud sandbox, Lobehub Dev" while the panel showed nothing and explained- // nothing. A device's tree needs no conversation either.- const { selection: sandboxSelection } = useSandboxMode(activeAgentId ?? '');- const sandboxInstanceId = sandboxSelection.instanceId;- const isSandboxExecution =- effectiveTarget === 'sandbox' && sandboxSelection.mode === 'persistent';- const sandboxTopicId = isSandboxExecution ? (topicId ?? undefined) : undefined;- // Scoped to the bound instance's directory, or the workspace root when the- // run keeps files without one. The empty string IS the root here, which is- // why the tab's gate is the topic rather than a truthy path.- // A replica, so a reload paints the directory (and the Files tab) from the- // last answer; `null` is an instance known to be gone.- const sandboxDirectoryId = isSandboxExecution ? sandboxInstanceId : undefined;- sandboxActions.useFetchInstanceDirectory(sandboxDirectoryId);- const sandboxDir = useSandboxStore(sandboxSelectors.instanceDirectory(sandboxDirectoryId));- const sandboxDirectory = sandboxDir ?? '';- // The empty string IS the workspace root, so an unresolved instance does not- // read as "no directory yet" โ it reads as "the whole workspace", and the- // tree would list every instance's folder for as long as the lookup took.- const sandboxDirectoryKnown = !sandboxInstanceId || sandboxDir !== undefined;+ // A cloud-sandbox run that keeps files has a tree on the drive to show too.+ const {+ active: isSandboxExecution,+ directory: sandboxDirectory,+ directoryKnown: sandboxDirectoryKnown,+ instanceId: sandboxInstanceId,+ topicId: sandboxTopicId,+ } = useSandboxFilesDirectory(activeAgentId ?? '', {+ isSandboxTarget: effectiveTarget === 'sandbox',+ topicId,+ });const filesystemEnvironmentAvailable = isLocalExecution || isDeviceMode;const environmentWorkingDirectory = filesystemEnvironmentAvailable ? workingDirectory : undefined;diff --git a/src/features/Conversation/WorkingSidebar/useSandboxFilesDirectory.ts b/src/features/Conversation/WorkingSidebar/useSandboxFilesDirectory.tsnew file mode 100644index 00000000000..8ec01a9aaa9--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/useSandboxFilesDirectory.ts@@ -0,0 +1,50 @@+import {+ isPersistentSelection,+ useSandboxPlacement,+} from '@/features/ChatInput/ControlBar/useSandboxPlacement';+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';++/**+ * Which directory on the drive a cloud-sandbox conversation's file tree shows.+ *+ * Only when the run actually keeps files: a temporary sandbox keeps nothing,+ * and pointing the panel at the drive would let another conversation's files+ * read as this one's. Read through the same hook the composer writes with, so+ * the panel sees a choice the moment it is made โ including one buffered on+ * the agent before the conversation exists.+ *+ * `directory` is relative to the drive's root, where `''` IS the root (a+ * folder picked as `.`). An environment directory has to be looked up first,+ * and until it is `directoryKnown` is false โ the empty string would otherwise+ * read as "the whole drive" and the tree would list every folder on it for as+ * long as the lookup took.+ */+export const useSandboxFilesDirectory = (+ agentId: string,+ { isSandboxTarget, topicId }: { isSandboxTarget: boolean; topicId?: string | null },+) => {+ const { selection } = useSandboxPlacement(agentId);+ const instanceId = selection.instanceId;+ const active = isSandboxTarget && isPersistentSelection(selection);++ // A replica, so a reload paints the directory (and the Files tab) from the+ // last answer; `null` is an instance known to be gone.+ sandboxActions.useFetchInstanceDirectory(active ? instanceId : undefined);+ const instanceDirectory = useSandboxStore(+ sandboxSelectors.instanceDirectory(active ? instanceId : undefined),+ );++ const directory = instanceId+ ? (instanceDirectory ?? '')+ : selection.workingDirectory && selection.workingDirectory !== '.'+ ? selection.workingDirectory+ : '';++ return {+ active,+ directory,+ directoryKnown: !instanceId || instanceDirectory !== undefined,+ instanceId: active ? instanceId : undefined,+ topicId: active ? (topicId ?? undefined) : undefined,+ };+};diff --git a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx b/src/features/EnvironmentManager/CreateEnvironmentModal.tsxindex 0cf546e224d..5018118baaa 100644--- a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx+++ b/src/features/EnvironmentManager/CreateEnvironmentModal.tsx@@ -1,22 +1,17 @@'use client';-import type { EnvironmentKind, EnvironmentVisibility } from '@lobechat/types';+import type { EnvironmentVisibility } from '@lobechat/types';import {Button,confirmModal,createModal,- createStaticStyles,- cssVar,- cx,Flexbox,- Icon,Input,ModalFooter,Text,useModalContext,} from '@lobehub/ui';import { t as translate } from 'i18next';-import { CodeXmlIcon, FolderIcon, type LucideIcon } from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -26,62 +21,19 @@ import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';import GithubRepositoryPicker, { type GithubRepositorySelection } from './GithubRepositoryPicker';import { type CreatedEnvironment, useEnvironmentActions } from './useEnvironmentData';-const styles = createStaticStyles(({ css }) => ({- kind: css`- cursor: pointer;-- flex: 1;-- min-width: 0;- padding: 12px;- border: 1px solid ${cssVar.colorBorder};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorFillQuaternary};-- transition:- border-color 0.2s,- background 0.2s;-- &:hover {- border-color: ${cssVar.colorTextQuaternary};- }- `,- kindActive: css`- border-color: ${cssVar.colorPrimary};- background: ${cssVar.colorPrimaryBg};-- &:hover {- border-color: ${cssVar.colorPrimary};- }- `,-}));--const KINDS: { icon: LucideIcon; kind: EnvironmentKind }[] = [- { icon: FolderIcon, kind: 'files' },- { icon: CodeXmlIcon, kind: 'code' },-];-/**- * Naming a new environment, after saying what it is for.+ * Naming a new code environment, after picking the repository it checks out.** A dialog rather than a field parked in the page: creating is one action among* several this page offers, and an input sitting in the body reads as a setting- * you are meant to fill in.+ * you are meant to fill in. Everything else about an environment is edited once+ * it exists, where the form can explain what each part does.*- * The kind comes first because it decides what else is worth asking. A folder- * of files someone hands an agent has no repository and nothing to install, so- * offering a repository picker to it would ask a question that has no answer.- * Everything else about an environment is edited once it exists, where the- * form can explain what each part does.+ * There is one kind. A folder of files someone hands an agent is a folder on+ * the drive, picked in the directory picker โ not an environment.*/interface CreateEnvironmentContentProps {- /**- * Called with the new environment once it exists, together with the default- * instance the server created alongside it. Nothing is asked about that- * instance: the caller opens the environment and starts its build, so the- * person lands on something that is already on its way to being usable.- */+ /** Called with the new environment once it exists; the caller opens it. */onCreated?: (environment: CreatedEnvironment) => void;visibility?: EnvironmentVisibility;}@@ -92,9 +44,6 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(const { close } = useModalContext();const actions = useEnvironmentActions();- // Nothing is preselected: the two kinds lead to different fields, and a- // default would skip the one question this dialog exists to ask first.- const [kind, setKind] = useState<EnvironmentKind>();const [name, setName] = useState('');// Tracks whether the name is still the one the repository suggested. A name// the person typed is theirs, and picking a different repository must not@@ -127,19 +76,18 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(// 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:- kind === 'code' && repository- ? {- kind,- sources: [- {- kind: 'git',- ref: repository.defaultBranch,- url: `https://github.com/${repository.owner}/${repository.repository}`,- },- ],- }- : { kind },+ configuration: repository+ ? {+ kind: 'code',+ sources: [+ {+ kind: 'git',+ ref: repository.defaultBranch,+ url: `https://github.com/${repository.owner}/${repository.repository}`,+ },+ ],+ }+ : { 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@@ -148,7 +96,7 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(});close();// After the dialog, not instead of it: the person sees the environment- // land with its default copy already in it.+ // land in the list.if (created?.id) onCreated?.(created);} catch (cause) {// The one failure the user can act on is a name already taken, and it is@@ -170,11 +118,11 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(// question publishing one does, with the same explanation, rather than// publishing it silently because of which tab happened to be open.const submit = () => {- if (!kind || !trimmed || creating) return;+ if (!trimmed || creating) return;if (visibility !== 'public') return void create();confirmModal({- content: <VisibilityConfirmContent capturedState variant={'publish'} />,+ content: <VisibilityConfirmContent variant={'publish'} />,okText: t('environments.create'),onOk: create,title: t('environments.visibility.createPublishedConfirmTitle'),@@ -184,86 +132,40 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(return (<><Flexbox gap={12} paddingBlock={8} paddingInline={16}>- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('environments.kind.label')}- </Text>- <Flexbox horizontal gap={8} role={'radiogroup'}>- {KINDS.map((option) => (- <Flexbox- aria-checked={kind === option.kind}- className={cx(styles.kind, kind === option.kind && styles.kindActive)}- gap={4}- key={option.kind}- role={'radio'}- tabIndex={0}- onClick={() => setKind(option.kind)}- onKeyDown={(event) => {- if (event.key === 'Enter' || event.key === ' ') {- event.preventDefault();- setKind(option.kind);- }- }}- >- <Flexbox horizontal align={'center'} gap={6}>- <Icon icon={option.icon} size={16} />- <Text weight={500}>{t(`environments.kind.${option.kind}`)}</Text>- </Flexbox>- <Text fontSize={12} type={'secondary'}>- {t(`environments.kind.${option.kind}Desc`)}- </Text>- </Flexbox>- ))}- </Flexbox>- </Flexbox>-- {/* What a files environment is for, said where the repository picker- would otherwise be: there is nothing to configure, and the reason- to make one is to hand an agent files to work on. */}- {kind === 'files' && (- <Text fontSize={12} type={'secondary'}>- {t('environments.kind.filesHint')}- </Text>- )}-{/* 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. */}- {kind === 'code' && (- <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />- )}+ <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />- {kind && (- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('environments.nameLabel')}+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('environments.nameLabel')}+ </Text>+ <Input+ autoFocus+ placeholder={t('environments.namePlaceholder')}+ value={name}+ onChange={(event) => {+ setName(event.target.value);+ setNameIsSuggested(false);+ setError(undefined);+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !isComposingRef.current) void submit();+ }}+ {...compositionProps}+ />+ {error && (+ <Text fontSize={12} type={'danger'}>+ {error}</Text>- <Input- autoFocus- placeholder={t('environments.namePlaceholder')}- value={name}- onChange={(event) => {- setName(event.target.value);- setNameIsSuggested(false);- setError(undefined);- }}- onKeyDown={(event) => {- if (event.key === 'Enter' && !isComposingRef.current) void submit();- }}- {...compositionProps}- />- {error && (- <Text fontSize={12} type={'danger'}>- {error}- </Text>- )}- </Flexbox>- )}+ )}+ </Flexbox></Flexbox><ModalFooter><Button onClick={close}>{t('environments.cancel')}</Button><Button- disabled={!kind || !trimmed}+ disabled={!trimmed}loading={creating}type={'primary'}onClick={() => void submit()}diff --git a/src/features/EnvironmentManager/CreateInstanceModal.tsx b/src/features/EnvironmentManager/CreateInstanceModal.tsxdeleted file mode 100644index bd1e283d6a6..00000000000--- a/src/features/EnvironmentManager/CreateInstanceModal.tsx+++ /dev/null@@ -1,259 +0,0 @@-'use client';--import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';-import {- Button,- createModal,- Flexbox,- Input,- ModalFooter,- Text,- useModalContext,-} from '@lobehub/ui';-import { t as translate } from 'i18next';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';--import { describeError } from './errorMessage';-import { suggestInstanceDirectory } from './instanceDirectory';-import { type SandboxInstance, useEnvironmentActions } from './useEnvironmentData';--interface CreateInstanceContentProps {- environmentId: string;- /**- * The instance being edited, or absent to make a new one.- *- * The same dialog for both because they ask the same two questions about- * the same two fields โ and because a rename done inline, in a row, could- * not show the directory at all, so the one thing that cannot be changed was- * also the one thing never explained.- */- instance?: SandboxInstance;- onCreated?: (instance: SandboxInstance) => void;- /**- * The instance to copy, when this dialog makes a copy rather than a fresh- * instance. Asks the same two questions โ what to call it, where it lives โ- * but the new folder starts with everything the source had built, so there is- * nothing to build afterwards.- */- source?: SandboxInstance;-}--/**- * Naming a new instance and choosing its directory.- *- * One dialog for both places an instance is made from โ the environment's- * panel in settings and the working-directory menu in the composer โ so the- * two never drift into asking different questions. It always asks: the- * directory is where a conversation's outputs land and the name is how it is- * told apart from its siblings, and neither is something to decide for the- * person by deriving it from the environment's name.- */-const CreateInstanceContent = memo<CreateInstanceContentProps>(- ({ environmentId, instance, onCreated, source }) => {- const { t } = useTranslation('setting');- const { close } = useModalContext();- const actions = useEnvironmentActions();-- const editing = Boolean(instance);-- const [name, setName] = useState(instance?.name ?? '');- const [workingDirectory, setWorkingDirectory] = useState(instance?.workingDirectory ?? '');- // Whether the folder is the person's own now. Until it is, it follows the- // name โ "a folder of its own, named after this instance" is the answer- // nearly every time, and a field with no right answer showing is one that- // has to be puzzled out before the dialog can be finished.- //- // Derived from the field being non-empty rather than latched on first- // keystroke. Latched, it is a one-way door: type a folder, change your- // mind, clear it, and the help never comes back. Clearing it is how you- // hand it back โ and it does not refill on the spot, since a field that- // repopulates under the cursor cannot be cleared at all. The next edit to- // the name picks it up again.- const [directoryOwned, setDirectoryOwned] = useState(false);- const [creating, setCreating] = useState(false);- // An Enter that confirms an IME candidate is still an Enter to `keydown`,- // so without this, typing a Chinese name submitted the dialog on the- // keystroke that picked the characters โ before they had even reached the- // field, which is why it looked like a creation nobody asked for.- const { compositionProps, isComposingRef } = useIMECompositionEvent();- const [error, setError] = useState<string | undefined>();-- // Checked here against the rule the execution plane applies, so a folder it- // would refuse is refused while the person is still typing rather than on- // their next message. Editing only ever changes the name, and the directory- // it came with was already accepted once.- const canCreate = editing- ? Boolean(name.trim()) && name.trim() !== instance!.name- : Boolean(name.trim()) && isSafeSandboxCwd(workingDirectory);-- const submit = async () => {- if (!canCreate || creating) return;-- setCreating(true);- setError(undefined);- try {- if (instance) {- await actions.renameInstance({ id: instance.id, name: name.trim() });- close();-- return;- }-- if (source) {- // Ready on arrival: the server copies the source's built state and- // marks the copy ready, so no build follows.- await actions.copyInstance({ id: source.id, name: name.trim(), workingDirectory });- close();-- return;- }-- const created = await actions.createInstance({- environmentId,- name: name.trim(),- workingDirectory,- });- close();- onCreated?.(created);- // After the dialog is gone, not before: materializing the instance- // clones a repository and runs an install, and the row exists either- // way โ holding the dialog open for minutes would make creating one- // feel like it might fail, when the only thing that can still fail is- // the build, which the list reports on.- void actions.buildInstance(created.id);- } catch (cause) {- // A directory another instance already uses is fixed by typing a- // different one, so it belongs next to the field rather than in a toast- // that outlives the dialog.- const code = (cause as { message?: string })?.message;- setError(- code === 'DUPLICATE_INSTANCE_DIRECTORY'- ? t('environments.instances.duplicateDirectory')- : code === 'OVERLAPPING_INSTANCE_DIRECTORY'- ? t('environments.instances.overlappingDirectory')- : describeError(- cause,- t,- t(- editing- ? 'environments.instances.renameFailed'- : source- ? 'environments.instances.copyFailed'- : 'environments.instances.createFailed',- ),- ),- );- } finally {- setCreating(false);- }- };-- return (- <>- <Flexbox gap={12} paddingBlock={8} paddingInline={16}>- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('environments.nameLabel')}- </Text>- <Input- autoFocus- placeholder={t('environments.instances.namePlaceholder')}- value={name}- onChange={(event) => {- const next = event.target.value;- setName(next);- if (!editing && !directoryOwned)- setWorkingDirectory(suggestInstanceDirectory(next));- setError(undefined);- }}- onKeyDown={(event) => {- if (event.key === 'Enter' && !isComposingRef.current) void submit();- }}- {...compositionProps}- />- </Flexbox>-- <Flexbox gap={6}>- <Text fontSize={12} type={'secondary'} weight={500}>- {t('environments.instances.directoryLabel')}- </Text>- {/* Only while editing, where the field is disabled and the reason- is the whole point of still showing it. Creating, the same- sentence is the placeholder โ one line instead of two, and it- stands exactly where the answer goes. */}- {editing && (- <Text fontSize={12} type={'secondary'}>- {t('environments.instances.directoryLocked')}- </Text>- )}- {/* Shown while editing, and not editable: the folder holds the built- state and the execution plane has no rename that carries one- folder to another. A field that would fail on save is worse than- a field that says why it cannot. */}- <Input- disabled={editing}- placeholder={t('environments.instances.directoryHint')}- value={workingDirectory}- onChange={(event) => {- const next = event.target.value;- setWorkingDirectory(next);- // Empty is not a choice, so it gives the field back rather- // than counting as one.- setDirectoryOwned(next.trim() !== '');- setError(undefined);- }}- onKeyDown={(event) => {- if (event.key === 'Enter' && !isComposingRef.current) void submit();- }}- {...compositionProps}- />- {error && (- <Text fontSize={12} type={'danger'}>- {error}- </Text>- )}- </Flexbox>- </Flexbox>- <ModalFooter>- <Button onClick={close}>{t('environments.cancel')}</Button>- <Button- disabled={!canCreate}- loading={creating}- type={'primary'}- onClick={() => void submit()}- >- {t(editing ? 'environments.instances.save' : 'environments.instances.confirm')}- </Button>- </ModalFooter>- </>- );- },-);--CreateInstanceContent.displayName = 'CreateInstanceContent';--export const openCreateInstanceModal = (params: CreateInstanceContentProps) =>- createModal({- content: <CreateInstanceContent {...params} />,- footer: null,- maskClosable: true,- styles: { content: { padding: 0 } },- title: params.source- ? translate('environments.instances.copyTitle', { name: params.source.name, ns: 'setting' })- : translate(- params.instance ? 'environments.instances.rename' : 'environments.instances.add',- { ns: 'setting' },- ),- width: 'min(90vw, 480px)',- });--/** The same dialog, making a copy of `source` beside it. */-export const openCopyInstanceModal = (source: SandboxInstance) =>- openCreateInstanceModal({ environmentId: source.environmentId, source });--/** The same dialog, opened on an instance that already exists. */-export const openEditInstanceModal = (instance: SandboxInstance) =>- openCreateInstanceModal({ environmentId: instance.environmentId, instance });diff --git a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsxindex 450e8ef3ca3..60b2062d6c3 100644--- a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx+++ b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx@@ -1,6 +1,5 @@'use client';-import { environmentKind } from '@lobechat/types';import { Github } from '@lobehub/icons';import {ActionIcon,@@ -16,25 +15,23 @@ import {} from '@lobehub/ui';import dayjs from 'dayjs';import {- FolderIcon,- HistoryIcon,+ FolderGit2Icon,KeyRoundIcon,- LayersIcon,LayoutDashboardIcon,LockIcon,SettingsIcon,+ TerminalIcon,XIcon,} from 'lucide-react';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { type CopyTab, copyTabs, resolveDetailTab } from './detailTabs';import EnvironmentForm, { type EnvironmentFormSection } from './EnvironmentForm';-import InstanceSection from './InstanceSection';-import SessionHistorySection from './SessionHistorySection';+import PanelSection from './PanelSection';+import { repositoryPath } from './repository';import TabPane from './TabPane';import { useCanEditEnvironment } from './useCanEditEnvironment';-import { type SandboxEnvironment, useEnvironmentActions, useInstances } from './useEnvironmentData';+import { type SandboxEnvironment, useEnvironmentActions } from './useEnvironmentData';const styles = createStaticStyles(({ css }) => ({container: css`@@ -71,7 +68,7 @@ const styles = createStaticStyles(({ css }) => ({`,}));-type DetailTab = CopyTab | EnvironmentFormSection;+type DetailTab = 'overview' | EnvironmentFormSection;interface EnvironmentDetailPanelProps {environment: SandboxEnvironment;@@ -82,8 +79,10 @@ interface EnvironmentDetailPanelProps {* Everything one environment is, beside the list it was picked from.** The list answers which environment; this answers what it holds โ who made it,- * what it builds from, what runs before a conversation starts, and which- * instances exist. Splitting it this way is what lets the row stay scannable:+ * 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.*@@ -94,31 +93,25 @@ interface EnvironmentDetailPanelProps {const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment, onClose }) => {const { t } = useTranslation('setting');const actions = useEnvironmentActions();- const { data } = useInstances();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';+ const configuration = environment.configuration ?? {};+ const repository = repositoryPath(configuration);- // A files environment is a folder: there is no repository, setup or runtime- // to configure, so the panel keeps its name, description and files and- // drops the tabs and fields that would only ever be empty.- const kind = environmentKind(environment);const creator =environment.creator?.fullName ||environment.creator?.username ||t('environments.meta.unknownCreator');- const instanceCount = (data?.instances ?? []).filter(- (instance) => instance.environmentId === environment.id,- ).length;- const copies = copyTabs(instanceCount);- const tab: DetailTab = resolveDetailTab(picked, instanceCount);return (<Flexbox className={styles.container} gap={20}><Flexbox horizontal align={'center'} className={styles.header} gap={12}><span className={styles.iconTile}>- {kind === 'files' ? <Icon icon={FolderIcon} size={18} /> : <Github size={18} />}+ <Github size={18} /></span><Flexbox flex={1} gap={4} style={{ minWidth: 0 }}><Text ellipsis weight={600}>@@ -131,12 +124,6 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,the list is scanned for "is this recent", the panel is readfor "when". */}<Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- <Tag size={'small'}>{t(`environments.kind.${kind}`)}</Tag>- <Tag size={'small'}>- {instanceCount === 0- ? t('environments.instances.empty')- : t('environments.instances.count', { count: instanceCount })}- </Tag>{environment.workspaceId && environment.visibility === 'public' && (<Tag size={'small'}>{t('environments.visibility.publicTag')}</Tag>)}@@ -180,53 +167,31 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,</Flexbox>)}- {/* The copies and their run history are what everyone with access- comes here for; variables and settings reshape the environment,- which only its editor may do, so a read-only panel keeps those and- drops the rest. */}<TabsactiveKey={tab}styles={{ list: { maxWidth: '100%', overflowX: 'auto' } }}- items={[- ...(copies.includes('overview')+ items={+ canEdit? [{- icon: <Icon icon={LayoutDashboardIcon} size={16} />,- key: 'overview',- label: t('environments.detail.tabs.overview'),- },- ]- : [- {- icon: <Icon icon={LayersIcon} size={16} />,- key: 'instances',- label: t('environments.instances.title'),+ icon: <Icon icon={SettingsIcon} size={16} />,+ key: 'settings',+ label: t('environments.detail.tabs.settings'),},{- icon: <Icon icon={HistoryIcon} size={16} />,- key: 'sessions',- label: t('environments.sessions.title'),+ icon: <Icon icon={KeyRoundIcon} size={16} />,+ key: 'variables',+ label: t('environments.form.env'),},- ]),- ...(canEdit- ? [- ...(kind === 'code'- ? [- {- icon: <Icon icon={KeyRoundIcon} size={16} />,- key: 'variables',- label: t('environments.form.env'),- },- ]- : []),+ ]+ : [{- icon: <Icon icon={SettingsIcon} size={16} />,- key: 'settings',- label: t('environments.detail.tabs.settings'),+ icon: <Icon icon={LayoutDashboardIcon} size={16} />,+ key: 'overview',+ label: t('environments.detail.tabs.overview'),},]- : []),- ]}+ }onChange={(key) => setTab(key as DetailTab)}/>@@ -234,31 +199,16 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,sections and meets the next one's icon exactly, so any spacebetween them would show as a break in the line. */}<Flexbox>- {/* The one copy, as the environment itself: its build state (a code- environment's only โ a files one has nothing to build), its files- and what ran in it, without a list of one to click through. */}{tab === 'overview' && (- <TabPane>- <InstanceSection single editable={canEdit} environmentId={environment.id} kind={kind} />- <Flexbox gap={8}>- <Text weight={500}>{t('environments.sessions.title')}</Text>- <Text fontSize={12} type={'secondary'}>- {t('environments.sessions.desc')}+ <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>- <SessionHistorySection environmentId={environment.id} />- </Flexbox>- </TabPane>- )}-- {tab === 'instances' && (- <TabPane desc={t('environments.instances.desc')}>- <InstanceSection editable={canEdit} environmentId={environment.id} kind={kind} />- </TabPane>- )}-- {tab === 'sessions' && (- <TabPane desc={t('environments.sessions.desc')}>- <SessionHistorySection environmentId={environment.id} />+ </PanelSection></TabPane>)}@@ -267,7 +217,6 @@ const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment,{canEdit && (tab === 'variables' || tab === 'settings') && (<EnvironmentFormenvironment={environment}- kind={kind}section={tab}onSave={(changes) => actions.updateEnvironment({ ...changes, id: environment.id })}/>diff --git a/src/features/EnvironmentManager/EnvironmentForm.tsx b/src/features/EnvironmentManager/EnvironmentForm.tsxindex ebdeac8c817..f369c1e5fc3 100644--- a/src/features/EnvironmentManager/EnvironmentForm.tsx+++ b/src/features/EnvironmentManager/EnvironmentForm.tsx@@ -1,26 +1,13 @@'use client';-import type { EnvironmentKind } from '@lobechat/types';import { Github } from '@lobehub/icons';-import {- ActionIcon,- Button,- createStaticStyles,- cssVar,- Flexbox,- Switch,- Text,- toast,-} from '@lobehub/ui';-import { FolderGit2Icon, HardDriveIcon, InfoIcon, PencilIcon, TerminalIcon } from 'lucide-react';+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 { useTranslation } from 'react-i18next';import useSWR from 'swr';-import {- type SandboxEnvironmentSpecification,- sandboxStorageService,-} from '@/services/sandboxStorage';+import { environmentService, type SandboxEnvironmentSpecification } from '@/services/environment';import EnvironmentVariables from './EnvironmentVariables';import { describeError } from './errorMessage';@@ -56,12 +43,6 @@ export type EnvironmentFormSection = 'settings' | 'variables';interface EnvironmentFormProps {environment: SandboxEnvironment;- /**- * A files environment shows its name and description only: it has no- * repository, setup, variables or runtime switches, and fields for them- * would invite configuring a build that never runs.- */- kind: EnvironmentKind;onSave: (params: {configuration?: SandboxEnvironmentSpecification;description?: string;@@ -70,12 +51,6 @@ interface EnvironmentFormProps {section: EnvironmentFormSection;}-/**- * Network access is on unless someone says otherwise, and an untouched- * specification carries nothing rather than pinning the default into storage.- */-const DEFAULT_INTERNET_ACCESS = true;-/** Drop the keys a blank value would otherwise store as empty. */const compact = (configuration: SandboxEnvironmentSpecification): SandboxEnvironmentSpecification =>Object.fromEntries(@@ -112,7 +87,7 @@ const BranchField = memo<{const [editing, setEditing] = useState(false);const { data, error, isLoading } = useSWR(editing ? ['sandbox-github-branches', owner, repository] : null,- () => sandboxStorageService.listGithubBranches({ owner, repository }),+ () => environmentService.listGithubBranches({ owner, repository }),);const canPick = !error && data?.connected !== false && !data?.truncated;@@ -133,29 +108,22 @@ BranchField.displayName = 'EnvironmentBranchField';/*** An environment's specification: where its source material comes from and- * what makes it usable. This is the record of what the environment IS; what a- * sandbox has built from it is a cache, which is why editing here marks every- * working copy as needing a rebuild rather than changing one.+ * what makes it usable. 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.** Every field saves on its own the moment it is confirmed โ Railway's settings* page is the reference. There is no draft and no save button: the old one sat* 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, kind, onSave, section }) => {+const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, section }) => {const { t } = useTranslation('setting');const configuration = (environment.configuration ?? {}) as SandboxEnvironmentSpecification;const [pickingRepository, setPickingRepository] = useState(false);const [busy, setBusy] = useState(false);- /**- * Write one change to the specification. The toast is the only trace a- * per-field save leaves, so it carries the one consequence worth knowing- * when there is one: a change to what a build depends on โ sources, the- * setup command, variables โ puts every instance behind the specification.- * The rest (maintenance command, network, regenerable paths) applies to the- * next session as it is and says only "saved".- */+ /** 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 });@@ -223,7 +191,7 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,<TabPanedesc={<>- {t('environments.form.envHint')} {t('environments.form.appliesOnBuild')}+ {t('environments.form.envHint')} {t('environments.form.appliesOnInit')}</>}>@@ -237,9 +205,8 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,const basics = (<PanelSection- desc={t(kind === 'files' ? 'environments.form.filesDesc' : 'environments.form.desc')}+ desc={t('environments.form.desc')}icon={InfoIcon}- last={kind === 'files'}title={t('environments.form.basics')}><InlineField@@ -258,8 +225,6 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,</PanelSection>);- if (kind === 'files') return <Flexbox>{basics}</Flexbox>;-return (<Flexbox>{basics}@@ -278,7 +243,7 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,cannot do it. Repeated on the setup section and the variables tab,which are governed by the same snapshot. */<Text fontSize={12} type={'secondary'}>- {t('environments.form.appliesOnBuild')}+ {t('environments.form.appliesOnInit')}</Text>}>@@ -347,15 +312,12 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,</PanelSection><PanelSection+ lasticon={TerminalIcon}title={t('environments.form.setup')}notice={- /* The setup command's half of it. The maintenance command below- runs every time work resumes, which is the whole reason the two- are separate fields โ but it is read from the same snapshot, so- an edit to it reaches new instances too. */<Text fontSize={12} type={'secondary'}>- {t('environments.form.appliesOnBuild')}+ {t('environments.form.appliesOnInit')}</Text>}>@@ -367,58 +329,6 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, kind, onSave,value={configuration.bootstrapCommand ?? ''}onSave={(bootstrapCommand) => saveConfiguration({ bootstrapCommand })}/>- <InlineField- multiline- desc={t('environments.form.maintenanceHint')}- label={t('environments.form.maintenance')}- placeholder={'git pull --ff-only'}- value={configuration.maintenanceCommand ?? ''}- onSave={(maintenanceCommand) => saveConfiguration({ maintenanceCommand })}- />- </PanelSection>-- <PanelSection last icon={HardDriveIcon} title={t('environments.form.runtime')}>- <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>- <Flexbox gap={2}>- <Text fontSize={12} weight={500}>- {t('environments.form.internetAccess')}- </Text>- <Text fontSize={12} type={'secondary'}>- {t('environments.form.internetAccessHint')}- </Text>- </Flexbox>- <Switch- checked={configuration.internetAccess ?? DEFAULT_INTERNET_ACCESS}- disabled={busy}- onChange={(internetAccess) =>- run(() =>- saveConfiguration({- // The default is not stored: an environment that never- // mentions the network must keep meaning "on".- internetAccess:- internetAccess === DEFAULT_INTERNET_ACCESS ? undefined : internetAccess,- }),- )- }- />- </Flexbox>- <InlineField- multiline- desc={t('environments.form.excludeHint')}- label={t('environments.form.exclude')}- placeholder={'dist\n.cache'}- // One path per line: a list of paths is a list of lines everywhere- // else a person meets one.- value={(configuration.excludePaths ?? []).join('\n')}- onSave={(excludePaths) =>- saveConfiguration({- excludePaths: excludePaths- .split('\n')- .map((line) => line.trim())- .filter(Boolean),- })- }- /></PanelSection></Flexbox>);diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsxindex 89e94c15378..e1f261b0d7a 100644--- a/src/features/EnvironmentManager/EnvironmentItem.tsx+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx@@ -1,6 +1,5 @@'use client';-import { environmentKind } from '@lobechat/types';import { Github } from '@lobehub/icons';import {Avatar,@@ -12,25 +11,16 @@ import {DropdownMenu,Flexbox,Icon,- Tag,Text,toast,Tooltip,} from '@lobehub/ui';import dayjs from 'dayjs';-import {- EyeOffIcon,- FolderIcon,- GlobeIcon,- MoreHorizontalIcon,- PlusIcon,- Trash2Icon,-} from 'lucide-react';+import { EyeOffIcon, GlobeIcon, MoreHorizontalIcon, Trash2Icon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';-import { formatSize } from '@/utils/format';import { describeError } from './errorMessage';import { repositoryPath } from './repository';@@ -118,233 +108,197 @@ const styles = createStaticStyles(({ css }) => ({interface EnvironmentItemProps {environment: SandboxEnvironment;- instanceCount: number;- /** Select this environment AND open its instance-create form in the panel. */- onCreateInstance: () => void;onSelect: () => void;selected?: boolean;- /**- * Bytes kept by this environment's instances, or `null` when the snapshot- * store could not be reached and the sizes are unknown rather than zero.- */- storageBytes?: number | null;}/*** One environment, as a row.** What the row answers is what someone scanning the list is asking: which- * repository is this, how many instances does it have, who put it here. Every+ * 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.*/-const EnvironmentItem = memo<EnvironmentItemProps>(- ({ environment, instanceCount, onCreateInstance, onSelect, selected, storageBytes }) => {- const { t } = useTranslation('setting');- const { t: tCommon } = useTranslation('common');- const actions = useEnvironmentActions();- const canEdit = useCanEditEnvironment()(environment);+const EnvironmentItem = memo<EnvironmentItemProps>(({ environment, onSelect, selected }) => {+ const { t } = useTranslation('setting');+ const { t: tCommon } = useTranslation('common');+ const actions = useEnvironmentActions();+ const canEdit = useCanEditEnvironment()(environment);- const repository = repositoryPath(environment.configuration);- const kind = environmentKind(environment);- const creator =- environment.creator?.fullName ||- environment.creator?.username ||- t('environments.meta.unknownCreator');+ const repository = repositoryPath(environment.configuration);+ const creator =+ environment.creator?.fullName ||+ environment.creator?.username ||+ t('environments.meta.unknownCreator');- const setVisibility = (visibility: 'private' | 'public') =>- actions- .setEnvironmentVisibility({ id: environment.id, visibility })- .catch((error: unknown) =>- toast.error(describeError(error, t, t('environments.visibility.changeFailed'))),- );+ const setVisibility = (visibility: 'private' | 'public') =>+ actions+ .setEnvironmentVisibility({ id: environment.id, visibility })+ .catch((error: unknown) =>+ toast.error(describeError(error, t, t('environments.visibility.changeFailed'))),+ );- const publish = () =>- confirmModal({- // The shared dialog, because this is the same decision a shared device- // asks about and an answer learned once should transfer โ plus the- // bullet only an environment needs, since publishing one delegates the- // captured home directory and its logins, not just the row.- content: <VisibilityConfirmContent capturedState variant={'publish'} />,- okText: t('environments.visibility.publish'),- onOk: () => setVisibility('public'),- title: t('environments.visibility.publishConfirmTitle'),- });+ const publish = () =>+ confirmModal({+ // The shared dialog, because this is the same decision a shared device+ // asks about and an answer learned once should transfer โ plus the+ // bullet only an environment needs: a copy built before environments+ // became initializers keeps its captured home directory and logins, and+ // publishing hands those to every member along with the row.+ content: <VisibilityConfirmContent capturedState variant={'publish'} />,+ okText: t('environments.visibility.publish'),+ onOk: () => setVisibility('public'),+ title: t('environments.visibility.publishConfirmTitle'),+ });- const makePrivate = () =>- confirmModal({- content: <VisibilityConfirmContent variant={'makePrivate'} />,- okButtonProps: { danger: true },- okText: tCommon('makePrivate.confirm.ok'),- onOk: () => setVisibility('private'),- title: tCommon('makePrivate.confirm.title'),- });+ const makePrivate = () =>+ confirmModal({+ content: <VisibilityConfirmContent variant={'makePrivate'} />,+ okButtonProps: { danger: true },+ okText: tCommon('makePrivate.confirm.ok'),+ onOk: () => setVisibility('private'),+ title: tCommon('makePrivate.confirm.title'),+ });- // Only a workspace row has a pool to be in, and only its creator may move- // it between pools โ demoting a colleague's published environment would- // take away instances other people are working in.- const visibilityItems =- environment.workspaceId && canEdit- ? environment.visibility === 'private'- ? [- {- icon: <Icon icon={GlobeIcon} />,- key: 'publish',- label: t('environments.visibility.publish'),- onClick: publish,- },- ]- : [- {- icon: <Icon icon={EyeOffIcon} />,- key: 'makePrivate',- label: tCommon('makePrivate'),- onClick: makePrivate,- },- ]- : [];+ // Only a workspace row has a pool to be in, and only its creator may move+ // it between pools โ demoting a colleague's published environment would+ // take away instances other people are working in.+ const visibilityItems =+ environment.workspaceId && canEdit+ ? environment.visibility === 'private'+ ? [+ {+ icon: <Icon icon={GlobeIcon} />,+ key: 'publish',+ label: t('environments.visibility.publish'),+ onClick: publish,+ },+ ]+ : [+ {+ icon: <Icon icon={EyeOffIcon} />,+ key: 'makePrivate',+ label: tCommon('makePrivate'),+ onClick: makePrivate,+ },+ ]+ : [];- const confirmRemoveEnvironment = useConfirmRemoveEnvironment();- const confirmRemove = () => confirmRemoveEnvironment(environment);+ const confirmRemoveEnvironment = useConfirmRemoveEnvironment();+ const confirmRemove = () => confirmRemoveEnvironment(environment);- return (- <Flexbox- horizontal- align={'center'}- className={cx(styles.row, selected && styles.rowActive)}- gap={16}- role={'button'}- tabIndex={0}- onClick={onSelect}- onKeyDown={(event) => {- // Mirror native button keyboard semantics for the div-as-button row.- if (event.key === 'Enter' || event.key === ' ') {- event.preventDefault();- onSelect();- }- }}- >- <div className={styles.iconTile}>- {kind === 'files' ? <Icon icon={FolderIcon} size={20} /> : <Github size={20} />}- </div>+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.row, selected && styles.rowActive)}+ gap={16}+ role={'button'}+ tabIndex={0}+ onClick={onSelect}+ onKeyDown={(event) => {+ // Mirror native button keyboard semantics for the div-as-button row.+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ onSelect();+ }+ }}+ >+ <div className={styles.iconTile}>+ <Github size={20} />+ </div>- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- {/* No "published by" badge beside the name. The avatar on the right+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ {/* No "published by" badge beside the name. The avatar on the rightalready names the author on hover, and inside the published poolevery row is published by definition โ the badge printed the samefact twice and took the width the name needed. */}- {/* The description sits after the name rather than on a line of its+ {/* The description sits after the name rather than on a line of itsown: it is a gloss on the name, not a second fact, and a thirdline made every row taller for the rows that have one. It givesway first, since the name is what the row is found by. */}- <Flexbox horizontal align={'baseline'} gap={8} style={{ minWidth: 0 }}>- <Text ellipsis fontSize={15} style={{ flex: '0 1 auto', minWidth: 0 }} weight={500}>- {environment.name}- </Text>- {/* The one word that says which of the two things this is: a- folder of files or a repository with setup. Beside the name- because it is how the list is told apart at a glance. */}- <Tag size={'small'} style={{ alignSelf: 'center', flex: 'none' }}>- {t(`environments.kind.${kind}`)}- </Tag>- {environment.description && (- /* Shrinks a thousand times more readily than the name, the same+ <Flexbox horizontal align={'baseline'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={15} style={{ flex: '0 1 auto', minWidth: 0 }} weight={500}>+ {environment.name}+ </Text>+ {environment.description && (+ /* Shrinks a thousand times more readily than the name, the sameway the repository yields to the facts on the line below. */- <Text- ellipsis- fontSize={13}- style={{ flex: '0 1000 auto', minWidth: 0 }}- type={'secondary'}- >- {environment.description}- </Text>- )}- </Flexbox>- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>- {/* The repository leads because it is what the name is usually taken+ <Text+ ellipsis+ fontSize={13}+ style={{ flex: '0 1000 auto', minWidth: 0 }}+ type={'secondary'}+ >+ {environment.description}+ </Text>+ )}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ {/* The repository leads because it is what the name is usually takenfrom, and it truncates because it is the only part of this linethat can afford to. */}- {repository && (- <>- <Text className={styles.repository} type={'secondary'}>- {repository}- </Text>- <span className={styles.metaDivider} />- </>- )}- <Text className={styles.facts} type={'secondary'}>- {instanceCount === 0- ? t('environments.instances.empty')- : t('environments.instances.count', { count: instanceCount })}- {/* Snapshot storage, not live disk: what the instances have- kept, which is what a plan's quota is spent on. Shown only- once something has been kept โ instances that were never- used add up to nothing, and "0.0 KB" reads as a fault. */}- {typeof storageBytes === 'number' && storageBytes > 0 && (- <>- {' ยท '}- {t('environments.meta.storage', { size: formatSize(storageBytes) })}- </>- )}- {' ยท '}- {t('environments.meta.createdAt', {- time: dayjs(environment.createdAt).fromNow(),- })}- </Text>- </Flexbox>+ {repository && (+ <>+ <Text className={styles.repository} type={'secondary'}>+ {repository}+ </Text>+ <span className={styles.metaDivider} />+ </>+ )}+ <Text className={styles.facts} type={'secondary'}>+ {t('environments.meta.createdAt', {+ time: dayjs(environment.createdAt).fromNow(),+ })}+ </Text></Flexbox>+ </Flexbox>- <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>- {environment.creator && (- // Who put this here, at a glance โ the same answer the device list- // gives with the enroller's avatar.- <Tooltip title={t('environments.meta.creatorTooltip', { name: creator })}>- <span onClick={(event) => event.stopPropagation()}>- {/* The name is passed as the avatar itself, not only as+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>+ {environment.creator && (+ // Who put this here, at a glance โ the same answer the device list+ // gives with the enroller's avatar.+ <Tooltip title={t('environments.meta.creatorTooltip', { name: creator })}>+ <span onClick={(event) => event.stopPropagation()}>+ {/* The name is passed as the avatar itself, not only as`title`. `Avatar` derives its fallback text from`String(avatar)` first, so an undefined picture becomes theliteral string "undefined" and every author without onerenders the same "UN" โ `title` never gets a turn. Since therow carries no badge, that placeholder would be the onlything left saying whose environment this is. */}- <Avatar avatar={environment.creator.avatar || creator} size={20} title={creator} />- </span>- </Tooltip>- )}- {/* Nothing here acts on an environment you only have the use of, so+ <Avatar avatar={environment.creator.avatar || creator} size={20} title={creator} />+ </span>+ </Tooltip>+ )}+ {/* Nothing here acts on an environment you only have the use of, sothe menu goes away rather than offering items that would berefused. */}- {canEdit && (- <span onClick={(event) => event.stopPropagation()}>- <DropdownMenu- placement={'bottomRight'}- items={[- {- icon: <Icon icon={PlusIcon} />,- key: 'create-instance',- label: t('environments.instances.create'),- onClick: onCreateInstance,- },- ...visibilityItems,- {- danger: true,- icon: <Icon icon={Trash2Icon} />,- key: 'remove',- label: t('environments.remove'),- onClick: confirmRemove,- },- ]}- >- <Button icon={MoreHorizontalIcon} />- </DropdownMenu>- </span>- )}- </Flexbox>+ {canEdit && (+ <span onClick={(event) => event.stopPropagation()}>+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ ...visibilityItems,+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'remove',+ label: t('environments.remove'),+ onClick: confirmRemove,+ },+ ]}+ >+ <Button icon={MoreHorizontalIcon} />+ </DropdownMenu>+ </span>+ )}</Flexbox>- );- },-);+ </Flexbox>+ );+});EnvironmentItem.displayName = 'EnvironmentItem';diff --git a/src/features/EnvironmentManager/EnvironmentsGate.tsx b/src/features/EnvironmentManager/EnvironmentsGate.tsxdeleted file mode 100644index 2a7e15d2b44..00000000000--- a/src/features/EnvironmentManager/EnvironmentsGate.tsx+++ /dev/null@@ -1,58 +0,0 @@-'use client';--import { Button, Center, Empty, Flexbox } from '@lobehub/ui';-import { AlertTriangleIcon } from 'lucide-react';-import { memo, type PropsWithChildren } from 'react';-import { useTranslation } from 'react-i18next';--import { SandboxStorageUpgradeGuide } from '@/business/client/features/SandboxStorageUpsell';-import { RouteLoading } from '@/components/Skeleton/RouteSegment';-import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';--/**- * Environments are specifications for a persistent workspace, so the page- * that manages them is only useful to an account that has one. Without the- * entitlement the page shows how to get one instead of a form whose result- * nothing could ever run in.- *- * The entitlement is resolved and signed server-side; asking the server is the- * only way to see the same answer the sandbox will act on. The same replica- * entry as the composer's working-directory chip โ partitioned by workspace,- * since the server resolves the answer from the active one โ so the two never- * disagree.- */-const EnvironmentsGate = memo<PropsWithChildren>(({ children }) => {- const { t } = useTranslation('setting');- const { error, revalidate } = sandboxActions.useFetchEntitlement(true);- const data = useSandboxStore(sandboxSelectors.entitlement);-- // A failed lookup is not an unentitled account, and it is not a slow one- // either: left as a spinner this page is indistinguishable from loading- // until someone thinks to reload. Say so, and offer the retry.- if (error && !data)- return (- <Center style={{ minHeight: 320 }} width={'100%'}>- <Flexbox align={'center'} gap={12}>- <Empty- description={t('environments.loadFailed.desc')}- descriptionProps={{ fontSize: 13 }}- icon={AlertTriangleIcon}- style={{ maxWidth: 400 }}- title={t('environments.loadFailed.title')}- />- <Button onClick={() => void revalidate()}>{t('environments.loadFailed.retry')}</Button>- </Flexbox>- </Center>- );-- // Nothing rather than a flash of the upgrade page at a user who turns out to- // be entitled.- if (!data) return <RouteLoading />;- if (!data.entitled) return <SandboxStorageUpgradeGuide />;-- return children;-});--EnvironmentsGate.displayName = 'EnvironmentsGate';--export default EnvironmentsGate;diff --git a/src/features/EnvironmentManager/InstanceFileBrowser.tsx b/src/features/EnvironmentManager/InstanceFileBrowser.tsxdeleted file mode 100644index 9493b4af93e..00000000000--- a/src/features/EnvironmentManager/InstanceFileBrowser.tsx+++ /dev/null@@ -1,358 +0,0 @@-'use client';--import {- ActionIcon,- createModal,- createStaticStyles,- cssVar,- Flexbox,- Icon,- Skeleton,- Text,-} from '@lobehub/ui';-import dayjs from 'dayjs';-import {- ChevronLeftIcon,- ChevronRightIcon,- CornerLeftUpIcon,- FileIcon,- FolderIcon,-} from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';-import useSWR from 'swr';--import { sandboxStorageService } from '@/services/sandboxStorage';-import { formatSize } from '@/utils/format';--const styles = createStaticStyles(({ css }) => ({- body: css`- overflow: hidden;-- /* Fixed, so the window does not resize under the pointer as folders open.- A browser whose height follows its contents moves the row you were about- to click. */- height: 420px;- border-block: 1px solid ${cssVar.colorBorderSecondary};- `,- crumb: css`- cursor: pointer;-- flex: none;-- font-family: ${cssVar.fontFamilyCode};- font-size: ${cssVar.fontSizeSM};- color: ${cssVar.colorTextSecondary};-- &:hover {- color: ${cssVar.colorText};- }- `,- crumbCurrent: css`- cursor: default;- color: ${cssVar.colorText};- `,- viewer: css`- overflow: auto;- flex: 1;-- margin: 0;-- font-family: ${cssVar.fontFamilyCode};- font-size: ${cssVar.fontSizeSM};- line-height: 1.6;- color: ${cssVar.colorText};- white-space: pre;- `,- meta: css`- flex: none;-- width: 92px;-- font-size: ${cssVar.fontSizeSM};- color: ${cssVar.colorTextTertiary};- text-align: end;- `,- name: css`- overflow: hidden;- flex: 1;-- min-width: 0;-- font-size: ${cssVar.fontSizeSM};- text-overflow: ellipsis;- white-space: nowrap;- `,- row: css`- cursor: default;- user-select: none;- padding-block: 7px;- padding-inline: 16px;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- scroll: css`- overflow-y: auto;- height: 100%;- `,- toolbar: css`- padding-block: 10px;- padding-inline: 16px;- `,-}));--/**- * A NUL byte in what came back as text is the reliable tell that it is not.- *- * Built with `fromCharCode` rather than written as an escape: the formatter- * normalizes a unicode escape in this file to the raw control character, which- * leaves a test that looks like it compares against a space.- */-const looksBinary = (content: string) => content.includes(String.fromCharCode(0));--/**- * The execution plane answers 404 for a directory that is not there, and an- * instance that has never been built or run does not have one: the row is- * created in the database, while the folder appears the first time the- * sandbox saves its work tree. That is a normal state, not a failure.- */-const isMissingDirectory = (error: unknown) =>- (error as { data?: { code?: string } })?.data?.code === 'NOT_FOUND';--interface InstanceFileBrowserProps {- /**- * The instance being browsed. Every file call names it, because the server- * confines each path to this instance's directory โ the workspace root around- * it is shared with every other instance.- */- instanceId: string;- /** The instance's directory, relative to the workspace root. */- root: string;-}--/**- * The files an instance has kept, in a window of its own โ to look at, not to- * change.- *- * This directory is the saved copy of the instance's work tree: the sandbox- * runs the checkout on its own disk and writes it here, and it is the only- * writer. An edit made here would be overwritten by the next save, or leave- * the directory disagreeing with the record the next restore reads it by โ so- * nothing here writes, and the server refuses it too. Rebuildable content such- * as `node_modules` is kept elsewhere and does not appear.- *- * Every path here is relative to the WORKSPACE root, which is the vocabulary the- * execution plane speaks โ an instance's directory is a prefix inside it, not a- * separate root. Navigation therefore carries whole paths rather than composing- * them, and the instance's own directory is simply where the walk starts and- * the breadcrumb stops going back.- *- * No `topicId` is sent: there is no conversation here to borrow a warm sandbox- * from, so the execution plane starts one to serve the call. That is the price- * of reaching these files from a settings page, and it is why the listing is- * fetched per directory rather than recursively up front.- */-const InstanceFileBrowser = memo<InstanceFileBrowserProps>(({ instanceId, root }) => {- const { t } = useTranslation('setting');-- const [cwd, setCwd] = useState(root);- const [openFile, setOpenFile] = useState<string | undefined>();-- const listing = useSWR(- ['sandbox-instance-files', cwd],- () => sandboxStorageService.listFiles({ instanceId, path: cwd }),- {- // Each listing is a sandbox round trip. A missing directory is an answer,- // not a failure to retry, and refocusing the window must not re-list.- revalidateOnFocus: false,- shouldRetryOnError: (error) => !isMissingDirectory(error),- },- );-- const file = useSWR(- openFile ? ['sandbox-instance-file', openFile] : null,- ([, path]: [string, string]) => sandboxStorageService.readFile({ instanceId, path }),- );- const content = file.data?.content ?? '';-- const entries = [...(listing.data?.entries ?? [])].sort((a, b) =>- a.isDirectory === b.isDirectory ? a.name.localeCompare(b.name) : a.isDirectory ? -1 : 1,- );-- // Only the part of the path below the instance's own directory. Above it is- // the workspace root, which this window deliberately does not offer.- const crumbs = cwd === root ? [] : cwd.slice(root.length + 1).split('/');-- const openDirectory = (path: string) => {- setCwd(path);- setOpenFile(undefined);- };-- if (openFile)- return (- <Flexbox>- <Flexbox horizontal align={'center'} className={styles.toolbar} gap={8}>- <ActionIcon- icon={ChevronLeftIcon}- size={'small'}- title={t('environments.files.back')}- onClick={() => setOpenFile(undefined)}- />- <Text className={styles.name} title={openFile}>- {openFile.slice(cwd.length + 1)}- </Text>- </Flexbox>-- <Flexbox className={styles.body} padding={16}>- {file.isLoading ? (- <Skeleton.Text rows={8} />- ) : file.error ? (- <Text fontSize={12} type={'danger'}>- {t('environments.files.unreadable')}- </Text>- ) : looksBinary(content) ? (- // Not rendered: the read path carries text, and a binary shown as- // text is noise rather than its contents.- <Text fontSize={12} type={'secondary'}>- {t('environments.files.binary')}- </Text>- ) : (- <pre className={styles.viewer}>{content}</pre>- )}- </Flexbox>- </Flexbox>- );-- return (- <Flexbox>- <Flexbox horizontal align={'center'} className={styles.toolbar} gap={8}>- <ActionIcon- disabled={cwd === root}- icon={CornerLeftUpIcon}- size={'small'}- title={t('environments.files.up')}- onClick={() => openDirectory(cwd.slice(0, cwd.lastIndexOf('/')))}- />- {/* The instance's directory is the first crumb and the floor: there is- no crumb above it, because the workspace root holds other instances'- work and this window is about one instance. */}- <Flexbox horizontal align={'center'} flex={1} gap={6} style={{ minWidth: 0 }}>- <span- className={cwd === root ? `${styles.crumb} ${styles.crumbCurrent}` : styles.crumb}- onClick={() => openDirectory(root)}- >- {root}- </span>- {crumbs.map((crumb, index) => {- const path = [root, ...crumbs.slice(0, index + 1)].join('/');- const current = index === crumbs.length - 1;-- return (- <Flexbox horizontal align={'center'} gap={6} key={path}>- <Icon- icon={ChevronRightIcon}- size={12}- style={{ color: cssVar.colorTextQuaternary }}- />- <span- className={current ? `${styles.crumb} ${styles.crumbCurrent}` : styles.crumb}- onClick={() => !current && openDirectory(path)}- >- {crumb}- </span>- </Flexbox>- );- })}- </Flexbox>- </Flexbox>-- <Flexbox className={styles.body}>- <Flexbox className={styles.scroll}>- {listing.isLoading ? (- <Flexbox gap={8} padding={16}>- <Skeleton.Text rows={5} />- </Flexbox>- ) : listing.error && !isMissingDirectory(listing.error) ? (- <Flexbox padding={16}>- <Text fontSize={12} type={'danger'}>- {t('environments.files.listFailed')}- </Text>- </Flexbox>- ) : entries.length === 0 ? (- <Flexbox padding={16}>- <Text fontSize={12} type={'secondary'}>- {t(- listing.error && cwd === root- ? 'environments.files.unusedInstance'- : 'environments.files.empty',- )}- </Text>- </Flexbox>- ) : (- entries.map((entry) => (- <Flexbox- horizontal- align={'center'}- className={styles.row}- gap={8}- key={entry.path}- // Double-click to open, the way a file manager does. A single- // click on a whole row is too easy to trigger while reading one.- onDoubleClick={() =>- entry.isDirectory ? openDirectory(entry.path) : setOpenFile(entry.path)- }- >- <Icon- icon={entry.isDirectory ? FolderIcon : FileIcon}- size={14}- style={{ color: cssVar.colorTextTertiary, flex: 'none' }}- />- <span className={styles.name}>{entry.name}</span>- <span className={styles.meta}>- {entry.isDirectory || entry.size === undefined ? '' : formatSize(entry.size)}- </span>- <span className={styles.meta}>- {entry.modifiedAt ? dayjs(entry.modifiedAt).format('MM-DD HH:mm') : ''}- </span>- </Flexbox>- ))- )}- </Flexbox>- </Flexbox>-- <Flexbox className={styles.toolbar} gap={2}>- <Text fontSize={12} type={'secondary'}>- {t('environments.files.openHint')}- </Text>- <Text fontSize={12} type={'secondary'}>- {t('environments.files.readOnlyHint')}- </Text>- </Flexbox>- </Flexbox>- );-});--InstanceFileBrowser.displayName = 'InstanceFileBrowser';--/**- * Opened as a window rather than inside the detail panel: a file listing needs- * width the panel does not have, and browsing an instance is its own errand โ- * it should not replace the environment you were reading in order to start it.- */-export const openInstanceFileBrowser = (instance: {- id: string;- name: string;- workingDirectory: string;-}) =>- createModal({- content: <InstanceFileBrowser instanceId={instance.id} root={instance.workingDirectory} />,- footer: null,- maskClosable: true,- styles: { content: { padding: 0 } },- title: instance.name,- width: 'min(92vw, 880px)',- });--export default InstanceFileBrowser;diff --git a/src/features/EnvironmentManager/InstanceList.tsx b/src/features/EnvironmentManager/InstanceList.tsxdeleted file mode 100644index 830e8a0b10e..00000000000--- a/src/features/EnvironmentManager/InstanceList.tsx+++ /dev/null@@ -1,714 +0,0 @@-'use client';--import { Github } from '@lobehub/icons';-import {- ActionIcon,- Button,- Center,- confirmModal,- createStaticStyles,- cssVar,- Empty,- Flexbox,- Icon,- Tag,- Text,- toast,- Tooltip,-} from '@lobehub/ui';-import {- CircleAlertIcon,- CircleDashedIcon,- CircleStopIcon,- CopyIcon,- FolderOpenIcon,- LayersIcon,- Loader2Icon,- PencilIcon,- PlusIcon,- RotateCcwIcon,- Trash2Icon,-} from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import {- openCopyInstanceModal,- openCreateInstanceModal,- openEditInstanceModal,-} from './CreateInstanceModal';-import { describeError } from './errorMessage';-import {- canCopyInstance,- copyBlockReason,- copyEntryTitle,- deleteEntry,- recheckCopySource,-} from './instanceActions';-import { openInstanceFileBrowser } from './InstanceFileBrowser';-import type { SandboxInstance } from './useEnvironmentData';-import { useBuildStarting, useInstanceBuild, useInstances } from './useEnvironmentData';--const styles = createStaticStyles(({ css }) => ({- /**- * One framed block with rules between its rows, rather than rows floating on- * the panel. Loose rows read as a list of unrelated lines; a frame says where- * the set begins and ends, which is what makes the "new instance" button- * below it read as an addition to that set.- */- list: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- `,- /** A build's output, when someone opens it โ usually because it failed. */- log: css`- overflow: auto;-- max-height: 220px;- margin: 0;- padding: 8px;- border-radius: ${cssVar.borderRadius};-- font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- line-height: 1.5;- color: ${cssVar.colorTextSecondary};- word-break: break-all;- white-space: pre-wrap;-- background: ${cssVar.colorFillQuaternary};- `,- /**- * A delete in flight. The row is still here because it is still there โ the- * archive is being removed and the call can still be refused โ so it is- * dimmed rather than taken away, and its own actions stop responding.- */- removing: css`- pointer-events: none;- opacity: 0.5;- `,- row: css`- padding-block: 12px;- padding-inline: 16px;-- & + & {- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- }- `,-}));--interface InstanceListProps {- /**- * Whether the caller owns the environment these belong to. A published- * environment is one a colleague can run in, not one they can add copies to- * or delete copies from, so the controls go away rather than fail.- */- editable: boolean;- environmentId: string;- instances: SandboxInstance[];- /** Nobody's occupancy could be read, so no row can claim to be free. */- occupancyUnavailable: boolean;- onBuild: (id: string) => Promise<void>;- onRemove: (id: string) => Promise<void>;- /** Deletes the whole environment; the only copy's delete entry. */- onRemoveEnvironment?: () => void;- /** Ends the run holding an instance; `stopped: false` when nothing was. */- onStop: (id: string) => Promise<{ stopped: boolean }>;- /** `owner/name` of the environment's checkout, when it builds from one. */- repository?: string;- /**- * Whether builds are this environment's business at all. A files- * environment clones and installs nothing, so a build line or a rebuild on- * its rows would describe work that never happens.- */- showBuild: boolean;- /** The environment's only copy, shown as the environment itself. */- single?: boolean;-}--interface InstanceRowProps {- editable: boolean;- instance: SandboxInstance;- occupancyUnavailable: boolean;- onBuild: (id: string) => Promise<void>;- onRemove: (id: string) => Promise<void>;- /** Deletes the whole environment; the only copy's delete entry. */- onRemoveEnvironment?: () => void;- onStop: (id: string) => Promise<{ stopped: boolean }>;- repository?: string;- showBuild: boolean;- single?: boolean;-}--/**- * What a build is doing, what it left behind when it failed, or that there has- * never been one.- *- * The log is collapsed by default and opened on demand: while everything is- * going right it is thousands of lines nobody reads, and the one time it- * matters is the time the row says it failed.- */-const BuildLine = memo<{- error?: string | null;- log: string;- /** Absent for someone who cannot build this instance; the button goes too. */- onBuild?: () => void;- /** Present when the status poll itself failed, rather than the build. */- onRetry?: () => void;- state: 'failed' | 'running' | 'stalled' | 'unbuilt';-}>(({ error, log, onBuild, onRetry, state }) => {- const { t } = useTranslation('setting');- const [open, setOpen] = useState(false);-- // The accumulated stream while it runs; the stored tail once it is over โ- // the runtime drops a finished build's log, so after a reload the row's own- // record is all there is. An instance never built has no log at all.- const text = state === 'unbuilt' ? '' : log || error || '';- const danger = state === 'failed' || state === 'stalled';-- return (- <Flexbox gap={6}>- <Flexbox horizontal align={'center'} gap={8}>- {state === 'running' ? (- <Icon spin icon={Loader2Icon} size={13} />- ) : danger ? (- <Icon icon={CircleAlertIcon} size={13} style={{ color: cssVar.colorError }} />- ) : (- <Icon icon={CircleDashedIcon} size={13} style={{ color: cssVar.colorTextTertiary }} />- )}- <Text fontSize={12} type={danger ? 'danger' : 'secondary'}>- {t(- state === 'running'- ? 'environments.instances.building'- : state === 'stalled'- ? 'environments.instances.buildStatusUnknown'- : state === 'failed'- ? 'environments.instances.buildFailed'- : 'environments.instances.notBuilt',- )}- </Text>- {state === 'stalled' && onRetry && (- <Button size={'small'} type={'text'} onClick={onRetry}>- {t('environments.instances.retryStatus')}- </Button>- )}- {text && (- <Button size={'small'} type={'text'} onClick={() => setOpen(!open)}>- {t(open ? 'environments.instances.hideLog' : 'environments.instances.showLog')}- </Button>- )}- {state !== 'running' && state !== 'stalled' && onBuild && (- <Button size={'small'} type={'text'} onClick={onBuild}>- {t(- state === 'unbuilt'- ? 'environments.instances.build'- : 'environments.instances.rebuild',- )}- </Button>- )}- </Flexbox>- {open && text && <pre className={styles.log}>{text}</pre>}- </Flexbox>- );-});--BuildLine.displayName = 'InstanceBuildLine';--/**- * One instance, as it is.- *- * Renaming opens the same dialog that made it, rather than turning the row- * into a field: the folder cannot change and the row had nowhere to say so,- * so the one thing worth explaining was the one thing an inline editor hid.- */-const InstanceRow = memo<InstanceRowProps>(- ({- editable,- instance,- occupancyUnavailable,- onBuild,- onRemove,- onRemoveEnvironment,- onStop,- repository,- showBuild,- single,- }) => {- const { t } = useTranslation('setting');- const { refreshRows } = useInstances();-- // Worth following only while something is in flight. A settled instance- // must not keep a poll running: the query writes when a build ends, so an- // idle one would be a round trip every two seconds for a row nobody is- // looking at.- const building = showBuild && instance.status === 'pending' && Boolean(instance.buildId);- const {- error: pollError,- log,- retry,- state,- } = useInstanceBuild(instance.id, building, instance.buildId);- // Made before instances built themselves, or its build request never- // arrived: pending with nothing to follow. Without saying so the row looks- // settled while the folder behind it is empty.- const unbuilt =- showBuild && instance.status === 'pending' && !instance.buildId && instance.buildable;-- // Bridges the gap between confirming and the refreshed row arriving. The- // request is not instant โ starting a build cold-starts a sandbox โ and- // without this the row would look untouched for that whole time, which is- // exactly what the dialog used to cover by staying open.- const [startingHere, setStartingHere] = useState(false);- // Or a build started from elsewhere โ the page starts a new environment's- // default copy the moment it is created, before this row even exists.- const startingElsewhere = useBuildStarting(instance.id);- const starting = startingHere || startingElsewhere;- // Same bridge for a delete, which is slower still: it cold-starts a sandbox- // and then removes the whole archive, gigabytes of it. The row says so and- // comes back if the execution plane refuses.- const [removing, setRemoving] = useState(false);- // And for a stop, which saves the run's snapshot before it ends it โ a few- // seconds at best. Until the refreshed row lands the badge still reads- // Running, so the row says the stop is under way rather than looking like- // the click did nothing.- const [stopping, setStopping] = useState(false);- // A build holds the same lease, but it is the instance's writer until it- // publishes and the execution plane will not cut it off; its own line- // already says it is building.- const stoppable = editable && instance.inUse && instance.status !== 'pending';-- const copyBlocked = copyBlockReason(instance, occupancyUnavailable);- const deletes = deleteEntry(instance, { editable, single: Boolean(single) });- const [checkingCopy, setCheckingCopy] = useState(false);- // Read again on the click rather than trusted from whenever the list was- // fetched; see `recheckCopySource`.- const startCopy = async () => {- setCheckingCopy(true);- const blocked = await recheckCopySource(instance.id, refreshRows);- setCheckingCopy(false);- if (blocked) {- toast.error(t(copyEntryTitle(blocked)));- return;- }- openCopyInstanceModal(instance);- };-- // Asked first: the run it ends may be a conversation in the middle of a- // step, and the icon sits beside the badge that only meant to explain.- const confirmStop = () =>- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('environments.instances.stopConfirmContent'),- okText: t('environments.instances.stop'),- // Not awaited, like the build and the delete: the row carries the- // progress, and a refusal comes back as a toast that says why โ most- // often that the snapshot is still saving, which is worth retrying.- onOk: () => {- setStopping(true);- void onStop(instance.id)- .then(({ stopped }) =>- toast.success(- t(- stopped ? 'environments.instances.stopped' : 'environments.instances.stopNothing',- { name: instance.name },- ),- ),- )- .catch((error: unknown) =>- toast.error(describeError(error, t, t('environments.instances.stopFailed'))),- )- .finally(() => setStopping(false));- },- title: t('environments.instances.stopConfirmTitle', { name: instance.name }),- });-- // Every build started from the row is asked first, the first one included:- // a build replaces the folder with a fresh checkout, and an instance that- // was never built may still hold what conversations wrote into it.- const confirmBuild = () =>- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('environments.instances.rebuildConfirmContent'),- okButtonProps: { danger: true },- okText: t(unbuilt ? 'environments.instances.build' : 'environments.instances.rebuild'),- // Deliberately not awaited, so the dialog closes on the click. Holding- // it until the sandbox is up made confirming feel like the thing might- // fail, which is the same reason creating an instance fires its build- // after its dialog is gone. Refusals โ "a conversation is using it" is- // the usual one โ leave the row as it was, so the toast still carries- // the reason; it now lands over the list rather than over a dialog.- onOk: () => {- setStartingHere(true);- void onBuild(instance.id)- .catch((error: unknown) =>- toast.error(describeError(error, t, t('environments.instances.buildStartFailed'))),- )- .finally(() => setStartingHere(false));- },- title: t(- unbuilt- ? 'environments.instances.buildConfirmTitle'- : 'environments.instances.rebuildConfirmTitle',- { name: instance.name },- ),- });-- return (- <Flexbox className={removing ? `${styles.row} ${styles.removing}` : styles.row} gap={6}>- <Flexbox horizontal align={'center'} gap={8}>- {/* One line: the folder after the name, the way the environment row- carries its description. It yields first when the row is narrow,- since the name is what the instance is picked by. */}- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>- {/* What this copy was cut from. On the instance and not only on the- environment header because the row is what gets browsed, renamed- and deleted, and its own folder name says nothing about the- checkout it holds. */}- {repository && (- <Tooltip title={repository}>- <Flexbox style={{ flex: 'none' }}>- <Github size={14} />- </Flexbox>- </Tooltip>- )}- <Text ellipsis fontSize={13} style={{ flex: '0 1 auto', minWidth: 0 }} weight={500}>- {instance.name}- </Text>- <Text- ellipsis- fontSize={12}- style={{ flex: '0 1000 auto', minWidth: 0 }}- type={'secondary'}- >- {instance.workingDirectory}- </Text>- </Flexbox>- {/* Whether a conversation is in this instance right now โ the one- thing about a row that changes while someone is looking at it, and what- decides whether deleting or rebuilding it will be refused.-- This slot used to carry the environment snapshot's size, which is a- property of the archive and not of the instance: an environment that- installs nothing never produces one, so the column sat at "nothing to- save" no matter how much work the instance held. The size that would- actually answer "how much is this using" โ the instance's own directory- on the volume โ is not measured per instance at all; the environment- row's total is where storage is reported.-- Shown only while held, the way the composer's own menu badges it.- Labelling every idle row "idle" would put a word on each line to say- that nothing is happening. A lease store that did not answer says- nothing here either: the line under the list reports that, rather than- each row quietly implying it is free. */}- {instance.inUse && (- // The badge says what is true; the hint says what it means for the- // person looking at it: how long the hold lasts, that the owner- // can end it now, and that Run history is where the conversation- // holding it can be found.- <Tooltip- title={t(- stoppable- ? 'environments.instances.runningHintStoppable'- : 'environments.instances.runningHint',- )}- >- <Tag color={'processing'} size={'small'}>- {t('environments.instances.running')}- </Tag>- </Tooltip>- )}- {/* Beside the badge it ends. The owner's, like a rebuild: in a- published environment the run is usually a colleague's. */}- {stoppable && (- <ActionIcon- disabled={stopping}- icon={CircleStopIcon}- loading={stopping}- size={'small'}- title={t('environments.instances.stop')}- onClick={confirmStop}- />- )}- {/* Reading what an instance kept is not an edit, so it stays- available in an environment someone else published โ that is- most of what having access to one is for. */}- {/* Named outright on the only copy: there it is how the environment's- files are reached, not one row's action among several. */}- {single ? (- <Button- icon={<Icon icon={FolderOpenIcon} />}- size={'small'}- onClick={() => openInstanceFileBrowser(instance)}- >- {t('environments.files.browse')}- </Button>- ) : (- <ActionIcon- icon={FolderOpenIcon}- size={'small'}- title={t('environments.files.browse')}- onClick={() => openInstanceFileBrowser(instance)}- />- )}- {/* Rebuilding a working copy is how it gets back to a clean checkout,- so it sits with the row's own actions once the instance is ready.- An instance a conversation holds is refused by the server, and- said so here first rather than after a confirmation. Absent when- the definition clones and installs nothing: there is nothing a- rebuild would redo. */}- {showBuild && editable && instance.status === 'ready' && instance.buildable && (- <ActionIcon- // `starting` too: the row still reads ready until the refreshed- // one lands, and a second click in that window starts a second- // build of the same instance.- disabled={instance.inUse || starting}- icon={RotateCcwIcon}- size={'small'}- title={t(- instance.inUse ? 'environments.instances.inUse' : 'environments.instances.rebuild',- )}- onClick={confirmBuild}- />- )}- {/* Copying is the owner's, like adding a copy is: a colleague who can- run in a published environment cannot take its state with them.- Greyed out rather than hidden while the source is held, with the- reason as its tooltip, so the entry does not vanish and come back- as runs start and end. */}- {canCopyInstance(editable) &&- (copyBlocked ? (- // The reason rides on a wrapper: a disabled button takes no- // pointer events, so its own tooltip would never open and the- // entry would be grey with nothing saying why.- <Tooltip title={t(copyEntryTitle(copyBlocked))}>- <span style={{ cursor: 'not-allowed', display: 'inline-flex' }}>- <ActionIcon disabled icon={CopyIcon} size={'small'} />- </span>- </Tooltip>- ) : (- <ActionIcon- disabled={checkingCopy}- icon={CopyIcon}- loading={checkingCopy}- size={'small'}- title={t(copyEntryTitle(undefined))}- onClick={() => void startCopy()}- />- ))}- {editable && (- <ActionIcon- icon={PencilIcon}- size={'small'}- title={t('environments.instances.rename')}- onClick={() => openEditInstanceModal(instance)}- />- )}- {/* The only copy's delete entry deletes the environment; the- default copy among several has none. See `deleteEntry`. */}- {deletes === 'environment' && onRemoveEnvironment && (- <ActionIcon- icon={Trash2Icon}- size={'small'}- title={t('environments.remove')}- onClick={onRemoveEnvironment}- />- )}- {deletes === 'instance' && (- <ActionIcon- disabled={removing}- icon={Trash2Icon}- size={'small'}- title={t('environments.instances.remove')}- // Asked first: the delete takes the snapshot with it, and the- // icon sits one slot from "browse", so a slip was a lost copy.- onClick={() =>- confirmModal({- content: t('environments.instances.removeConfirmContent'),- cancelText: t('cancel', { ns: 'common' }),- okButtonProps: { danger: true },- okText: t('environments.instances.remove'),- // Not awaited, for the same reason a build is not: removing- // an archive cold-starts a sandbox and then deletes- // gigabytes, and a dialog held open for that reads as a- // delete that might not be working. The row says what is- // happening instead, and stays until the row is actually- // gone.- //- // A rejected promise here used to disappear: the row stayed,- // and a refused delete was indistinguishable from a click that- // did nothing. The execution plane refuses while a- // conversation is still using the instance, and that reason- // is the one worth showing.- onOk: () => {- setRemoving(true);- void onRemove(instance.id)- .catch((error: unknown) => {- // Through the same translator the other refusals use:- // raw, the execution plane's answer names the row by- // its id ("Environment \"e299f341-โฆ\" is currently in- // use"), which is not a sentence to hand a person.- toast.error(- describeError(error, t, t('environments.instances.removeFailed')),- );- // Only on failure: a row that really went away unmounts- // with this state, and clearing it on success would- // flash the row back to normal first.- setRemoving(false);- })- .catch(() => {});- },- title: t('environments.instances.removeConfirmTitle', { name: instance.name }),- })- }- />- )}- </Flexbox>-- {/* The build, on its own line under the row rather than as a status- word beside the size. It is minutes long and it can fail, and a- failure is only useful with the log that caused it โ none of which- fits in a column. Also there for an instance never built, whose- folder is empty however settled the row looks. Absent once an- instance is ready, which is where it spends its life. */}- {(removing || stopping) && (- <Flexbox horizontal align={'center'} gap={8}>- <Icon spin icon={Loader2Icon} size={13} />- <Text fontSize={12} type={'secondary'}>- {t(removing ? 'environments.instances.removing' : 'environments.instances.stopping')}- </Text>- </Flexbox>- )}-- {showBuild &&- !removing &&- (starting || building || unbuilt || instance.status === 'error') && (- <BuildLine- error={instance.buildError}- log={log}- state={- // A poll that ran out of retries is not a running build. Left as- // one the row spins forever with nothing to click.- pollError && building && !state- ? 'stalled'- : starting || (building && state !== 'failed')- ? 'running'- : unbuilt- ? 'unbuilt'- : 'failed'- }- // Building a copy is the owner's; everyone else reads the state.- onBuild={editable ? confirmBuild : undefined}- onRetry={retry}- />- )}- </Flexbox>- );- },-);--InstanceRow.displayName = 'InstanceRow';--/**- * The instances of one environment.- *- * Two of them is the supported way to run two conversations side by side: each- * keeps its own folder and its own installed state, where a shared folder would- * have them overwrite each other's work.- */-const InstanceList = memo<InstanceListProps>(- ({- editable,- environmentId,- instances,- occupancyUnavailable,- onBuild,- onRemove,- onRemoveEnvironment,- onStop,- repository,- showBuild,- single,- }) => {- const { t } = useTranslation('setting');-- const add = () => openCreateInstanceModal({ environmentId });-- return (- <Flexbox gap={8}>- {/* A first-use empty state, not a line saying "none": it says what to- do here and where the instance is picked up afterwards, which is- the half of the story this panel cannot show. The create button- lives inside it, so an empty list has one call to action rather- than a placeholder above the same button. */}- {instances.length === 0 && (- <Center paddingBlock={16}>- <Empty- descriptionProps={{ fontSize: 13 }}- icon={LayersIcon}- style={{ maxWidth: 360 }}- title={t('environments.instances.empty')}- action={- editable ? (- <Button icon={<Icon icon={PlusIcon} />} onClick={add}>- {t('environments.instances.add')}- </Button>- ) : undefined- }- description={t(- editable- ? 'environments.instances.emptyHint'- : 'environments.instances.emptyReadonly',- )}- />- </Center>- )}-- {instances.length > 0 && (- <Flexbox className={styles.list}>- {instances.map((instance) => (- <InstanceRow- editable={editable}- instance={instance}- key={instance.id}- occupancyUnavailable={occupancyUnavailable}- repository={repository}- showBuild={showBuild}- single={single}- onBuild={onBuild}- onRemove={onRemove}- onRemoveEnvironment={onRemoveEnvironment}- onStop={onStop}- />- ))}- </Flexbox>- )}-- {/* Said once under the set rather than on each row: with occupancy- unread every row would otherwise look idle, which is the one- reading this must not offer. */}- {occupancyUnavailable && instances.length > 0 && (- <Text fontSize={12} type={'secondary'}>- {t('environments.instances.occupancyUnavailable')}- </Text>- )}-- {/* Below the framed list, as an addition to the set rather than a line- in it. The form itself opens as a dialog: the same one the composer- uses, so making an instance asks the same two questions wherever- it starts. */}- {editable && instances.length > 0 && (- <Flexbox horizontal>- <Button icon={<Icon icon={PlusIcon} />} onClick={add}>- {t('environments.instances.add')}- </Button>- </Flexbox>- )}- </Flexbox>- );- },-);--InstanceList.displayName = 'InstanceList';--export default InstanceList;diff --git a/src/features/EnvironmentManager/InstanceSection.tsx b/src/features/EnvironmentManager/InstanceSection.tsxdeleted file mode 100644index d21afd2d220..00000000000--- a/src/features/EnvironmentManager/InstanceSection.tsx+++ /dev/null@@ -1,73 +0,0 @@-'use client';--import type { EnvironmentKind } from '@lobechat/types';-import { Flexbox } from '@lobehub/ui';-import { memo } from 'react';--import InstanceList from './InstanceList';-import { repositoryPath } from './repository';-import { useConfirmRemoveEnvironment } from './useConfirmRemoveEnvironment';-import { useEnvironmentActions, useEnvironments, useInstances } from './useEnvironmentData';--interface InstanceSectionProps {- /** Whether the caller owns the environment; a published one is read-only to everyone else. */- editable: boolean;- environmentId: string;- kind: EnvironmentKind;- /**- * Shown as the environment itself rather than as a list: the panel's- * Overview, when the environment has one copy.- */- single?: boolean;-}--/**- * The copies built from one environment, as a section of its detail panel.- *- * Beside the environment rather than in a dialog of their own: an instance- * belongs to exactly one environment, so the environment's own name and- * specification are the whole context, and both stay on screen while a copy is- * made or discarded.- */-const InstanceSection = memo<InstanceSectionProps>(({ editable, environmentId, kind, single }) => {- const { data } = useInstances();- const { data: environmentData } = useEnvironments();- const actions = useEnvironmentActions();- const confirmRemoveEnvironment = useConfirmRemoveEnvironment();-- const instances = (data?.instances ?? []).filter(- (instance) => instance.environmentId === environmentId,- );-- // Read here rather than on each row: every instance in this section is built- // from the one environment, so the checkout is the section's fact, not the- // row's. The rows carry it because they are what a person points at.- const environment = (environmentData?.environments ?? []).find(- (candidate) => candidate.id === environmentId,- );- const repository = repositoryPath(environment?.configuration);-- return (- <Flexbox>- <InstanceList- editable={editable}- environmentId={environmentId}- instances={instances}- occupancyUnavailable={data?.occupancyUnavailable ?? false}- repository={repository}- // A files environment has nothing to build, so its rows carry no- // build line and no rebuild โ only the folder and what is in it.- showBuild={kind === 'code'}- single={single}- onBuild={actions.rebuildInstance}- onRemove={actions.removeInstance}- onRemoveEnvironment={environment ? () => confirmRemoveEnvironment(environment) : undefined}- onStop={actions.stopInstance}- />- </Flexbox>- );-});--InstanceSection.displayName = 'InstanceSection';--export default InstanceSection;diff --git a/src/features/EnvironmentManager/SessionHistorySection.tsx b/src/features/EnvironmentManager/SessionHistorySection.tsxdeleted file mode 100644index e67b1272d3e..00000000000--- a/src/features/EnvironmentManager/SessionHistorySection.tsx+++ /dev/null@@ -1,395 +0,0 @@-'use client';--import {- Button,- Center,- createStaticStyles,- cssVar,- Empty,- Flexbox,- Icon,- Tag,- Text,- Tooltip,-} from '@lobehub/ui';-import dayjs from 'dayjs';-import {- ActivityIcon,- AlertCircleIcon,- HammerIcon,- HistoryIcon,- MessageSquareIcon,- TerminalSquareIcon,-} from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import ListSkeleton from '@/components/ListSkeleton';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { formatSize } from '@/utils/format';--import { type SandboxSessionRecord, useInstances, useInstanceSessions } from './useEnvironmentData';--const styles = createStaticStyles(({ css }) => ({- /** The same frame the instance list uses, so the two tabs read as one panel. */- list: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};- `,- row: css`- padding-block: 12px;- padding-inline: 16px;-- & + & {- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- }- `,- /**- * The run that is going on now, framed apart from the trail below it the way- * Railway frames the active deployment, with a footer line that says what is- * happening rather than what happened. The frame stays neutral โ a solid- * info tint reads as a heavy navy block in dark mode โ and only the footer's- * status line carries the info color.- */- active: css`- overflow: hidden;- border: 1px solid ${cssVar.colorBorder};- border-radius: ${cssVar.borderRadiusLG};- background: ${cssVar.colorFillQuaternary};- `,- activeFooter: css`- padding-block: 8px;- padding-inline: 16px;- border-block-start: 1px solid ${cssVar.colorBorderSecondary};- color: ${cssVar.colorInfo};- `,- historyLabel: css`- font-size: 12px;- font-weight: 600;- color: ${cssVar.colorTextTertiary};- `,- kindIcon: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 28px;- height: 28px;- border-radius: 50%;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,-}));--/**- * How long the run lasted, or how long it has been running โ and nothing at- * all for one that was never closed and is no longer live.- *- * Measuring to `now` is right for a run in progress and wrong for an abandoned- * record: a session whose sandbox went away without a teardown has no end- * recorded, so the figure grew forever and read as twelve hours of work.- */-const duration = (session: SandboxSessionRecord, running: boolean): string | undefined => {- if (!session.endedAt && !running) return undefined;- const end = session.endedAt ? dayjs(session.endedAt) : dayjs();- const minutes = Math.max(1, Math.round(end.diff(session.startedAt, 'minute', true)));- if (minutes < 60) return `${minutes} min`;- const hours = minutes / 60;- return `${hours < 10 ? hours.toFixed(1) : Math.round(hours)} h`;-};--/**- * Where a run's conversation lives, or `undefined` when it has no page.- *- * A topic is addressed as `group/<groupId>/<topicId>` when it belongs to a- * group and `agent/<agentId>/<topicId>` otherwise โ the topic alone does not- * resolve, and a bare `/chat?topic=<id>` resolves to nothing at all, which is- * what sent the panel's one way back into a run to the 404 page.- *- * A group topic carries an agent id too โ the member that answered โ so the- * group is checked FIRST; reading the agent would open that member's own- * surface instead of the conversation the run came from. The workspace prefix- * is added by `useWorkspaceAwareNavigate`, so it is absent here on purpose.- */-export const conversationPath = (session: SandboxSessionRecord): string | undefined => {- if (session.management || !session.topicId) return undefined;- if (session.topicGroupId) return `/group/${session.topicGroupId}/${session.topicId}`;-- return session.topicAgentId ? `/agent/${session.topicAgentId}/${session.topicId}` : undefined;-};--const SessionRow = memo<{ running: boolean; session: SandboxSessionRecord }>(- ({ running, session }) => {- const { t } = useTranslation('setting');- const navigate = useWorkspaceAwareNavigate();-- const isBuild = session.kind === 'build';- /** No end recorded, and the lease says nobody is holding its instance. */- const stale = !session.endedAt && !running;- const elapsed = duration(session, running);- const conversation = conversationPath(session);- // Three kinds of run, told apart by how they were started: a build from- // the environment's specification, a console session from the file- // browser, or a conversation โ the common case, named by its topic.- const title = isBuild- ? t('environments.sessions.kind.build')- : session.management- ? t('environments.sessions.kind.console')- : session.topicTitle || t('environments.sessions.kind.conversation');- const icon = isBuild ? HammerIcon : session.management ? TerminalSquareIcon : MessageSquareIcon;-- // A build's verdict is its outcome; a session's reason is why it stopped,- // and the snapshot beside it says whether what it did was kept.- const outcome = running ? (- <Tag color={'processing'} size={'small'}>- {t('environments.sessions.running')}- </Tag>- ) : stale ? (- /* Deliberately not `reason.lost`: that is the execution plane's own word- for a session it watched disappear, and this one simply never said- anything. Claiming its reason would put words in its mouth. */- <Text fontSize={12} type={'secondary'}>- {t('environments.sessions.stale')}- </Text>- ) : session.endReason?.startsWith('build_') ? (- <Tag color={session.endReason === 'build_succeeded' ? 'success' : 'error'} size={'small'}>- {t(`environments.sessions.reason.${session.endReason}` as any)}- </Tag>- ) : (- <Text fontSize={12} type={'secondary'}>- {t(`environments.sessions.reason.${session.endReason ?? 'lost'}` as any)}- </Text>- );-- return (- <Flexbox horizontal align={'center'} className={styles.row} gap={12}>- <span className={styles.kindIcon}>- <Icon icon={icon} size={14} />- </span>- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis fontSize={13} weight={500}>- {title}- </Text>- <Text fontSize={12} type={'secondary'}>- {session.instanceName}- {' ยท '}- <Tooltip title={new Date(session.startedAt).toLocaleString()}>- <span>{dayjs(session.startedAt).fromNow()}</span>- </Tooltip>- {elapsed && ' ยท '}- {elapsed}- </Text>- </Flexbox>- {/* Snapshot outcome: only a stopped session has one, and a failed one- is the single thing on this row the person can act on. */}- {!isBuild && !running && session.snapshotError && (- <Tooltip title={session.snapshotError}>- <Flexbox horizontal align={'center'} gap={4}>- <Icon icon={AlertCircleIcon} size={14} style={{ color: cssVar.colorError }} />- <Text fontSize={12} type={'danger'}>- {t('environments.sessions.snapshotFailed')}- </Text>- </Flexbox>- </Tooltip>- )}- {!isBuild && !running && !session.snapshotError && session.snapshotBytes !== null && (- <Text fontSize={12} type={'secondary'}>- {t('environments.sessions.snapshotSaved', { size: formatSize(session.snapshotBytes) })}- </Text>- )}- {/* Railway's "View logs" on the active deployment: the one thing to do- with a run in progress is go to it. Only a conversation has somewhere- to go; a build and a console session have no page of their own.- A conversation is addressed as `agent/<agentId>/<topicId>` under the- active workspace, so the agent is required too and the navigate has- to be the workspace-aware one โ a bare `/chat?topic=<id>` resolved to- nothing and sent the one way back into a run to the 404 page. */}- {running && conversation && (- <Button size={'small'} onClick={() => navigate(conversation)}>- {t('environments.sessions.openConversation')}- </Button>- )}- {outcome}- </Flexbox>- );- },-);--SessionRow.displayName = 'SessionRow';--/**- * What has run in an environment: every session and every build of each of- * its instances, newest first. Read from the control plane's own trail, so- * it opens without waiting on a sandbox โ and it stays readable in an- * environment someone else published, since seeing what ran is not an edit.- */-/**- * Drop the session row a build rode in on.- *- * A build is written to the trail twice: once when its sandbox starts, as a- * management session, and once when the build itself does. They are the same- * machine โ same `sessionId` โ but the list showed them as two runs side by- * side, the first of them labelled "file browser", which is a thing nobody- * did. The build row is the better of the two anyway: it carries the outcome- * and the log.- *- * Only a management row is ever dropped, and only when a build in the same- * list names its session. A console session opened by the file browser has no- * build beside it and stays.- */-export const withoutBuildVehicles = (sessions: SandboxSessionRecord[]): SandboxSessionRecord[] => {- const builds = new Set(- sessions.filter((session) => session.kind === 'build').map((session) => session.sessionId),- );- if (builds.size === 0) return sessions;-- return sessions.filter(- (session) => session.kind === 'build' || !session.management || !builds.has(session.sessionId),- );-};--/**- * Which runs are still going, judged against the lease and the execution- * plane's own one-session-per-instance rule rather than against the trail.- *- * "No end recorded" was the whole test, and it is not evidence of anything: a- * sandbox that goes away without a teardown leaves its record open forever, so- * the panel showed sessions running for half a day while the composer's own- * menu offered their instance as free.- *- * Two things settle it, and one alone is not enough. The lease says whether- * anything holds the instance at all โ it is what the composer reads and the- * one signal that expires by itself. But a lease is held by an INSTANCE, not- * by a session, so gating on it alone resurrected every abandoned record the- * moment one live run touched the same instance: three sessions on one- * instance all read "running", two of them showing 55 and 61 hours. The- * execution plane runs one session per instance at a time, so of the records- * left open on one instance only the newest can be the live one; the rest were- * replaced and never written down.- *- * `unknown` is not `false`. A lease store that did not answer says nothing,- * and treating silence as "idle" would retire every live session on the page- * the moment Redis hiccuped โ so the lease gate is skipped, while the- * one-per-instance rule still applies.- */-export const runningSessionIds = (- sessions: readonly SandboxSessionRecord[],- occupancy: { held: Set<string>; unknown: boolean },-): Set<number> => {- const newestOpen = new Map<string, SandboxSessionRecord>();-- for (const session of sessions) {- if (session.endedAt) continue;- const instance = session.instanceId ?? '';- if (!occupancy.unknown && !occupancy.held.has(instance)) continue;-- const held = newestOpen.get(instance);- if (!held || Date.parse(session.startedAt) > Date.parse(held.startedAt)) {- newestOpen.set(instance, session);- }- }-- return new Set([...newestOpen.values()].map((session) => session.id));-};--const SessionHistorySection = memo<{ environmentId: string }>(({ environmentId }) => {- const { t } = useTranslation('setting');- const { data, isLoading } = useInstanceSessions(environmentId);- // The trail says whether an end was ever written down; the lease says who- // holds an instance right now. Only the second is evidence that something is- // still running โ a sandbox that went away without a teardown leaves a- // record with no end on it, and reading that alone kept sessions "running"- // for half a day while their instance sat free in the composer's own menu.- const { data: instanceData } = useInstances();-- if (isLoading && !data) return <ListSkeleton />;-- const occupancy = {- held: new Set(- (instanceData?.instances ?? []).filter((instance) => instance.inUse).map(({ id }) => id),- ),- // A lease store that did not answer is "not known", never "free" โ the- // same rule the server follows when it reads occupancy. Absent data is the- // same case: before the first response an unreachable Redis would- // otherwise quietly retire every running session on the page.- unknown: instanceData?.occupancyUnavailable ?? true,- };- const sessions = withoutBuildVehicles(data?.sessions ?? []);- const running = runningSessionIds(sessions, occupancy);- const active = sessions.filter((session) => running.has(session.id));- const history = sessions.filter((session) => !running.has(session.id));-- return (- <Flexbox gap={16}>- {data?.unavailable && (- <Text fontSize={12} type={'warning'}>- {t('environments.sessions.unavailable')}- </Text>- )}-- {active.length > 0 && (- <Flexbox gap={8}>- {active.map((session) => (- <div className={styles.active} key={`${session.kind}-${session.id}`}>- <SessionRow running session={session} />- <Flexbox horizontal align={'center'} className={styles.activeFooter} gap={8}>- <Icon icon={ActivityIcon} size={14} />- <Text fontSize={12} style={{ color: 'inherit' }}>- {t(- session.kind === 'build'- ? 'environments.sessions.activeBuild'- : 'environments.sessions.activeSession',- { instance: session.instanceName },- )}- </Text>- </Flexbox>- </div>- ))}- </Flexbox>- )}-- {sessions.length === 0 ? (- <Center paddingBlock={16}>- <Empty- description={t('environments.sessions.emptyHint')}- descriptionProps={{ fontSize: 13 }}- icon={HistoryIcon}- style={{ maxWidth: 360 }}- title={t('environments.sessions.empty')}- />- </Center>- ) : (- <Flexbox gap={8}>- {/* Labelled only once there is something above it to be "history"- relative to; alone, the list is the whole tab. */}- {active.length > 0 && (- <span className={styles.historyLabel}>{t('environments.sessions.history')}</span>- )}- {history.length === 0 ? (- <Text fontSize={12} type={'secondary'}>- {t('environments.sessions.historyEmpty')}- </Text>- ) : (- <div className={styles.list}>- {history.map((session) => (- <SessionRow- key={`${session.kind}-${session.id}`}- running={false}- session={session}- />- ))}- </div>- )}- </Flexbox>- )}- </Flexbox>- );-});--SessionHistorySection.displayName = 'SessionHistorySection';--export default SessionHistorySection;diff --git a/src/features/EnvironmentManager/WorkspaceUsageMeter.tsx b/src/features/EnvironmentManager/WorkspaceUsageMeter.tsxdeleted file mode 100644index 10cb8eac3de..00000000000--- a/src/features/EnvironmentManager/WorkspaceUsageMeter.tsx+++ /dev/null@@ -1,107 +0,0 @@-'use client';--import { createStaticStyles, cssVar, Flexbox, Text, Tooltip } from '@lobehub/ui';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import { formatSize } from '@/utils/format';--import { useWorkspaceUsage } from './useEnvironmentData';--const styles = createStaticStyles(({ css }) => ({- bar: css`- overflow: hidden;-- width: 64px;- height: 4px;- border-radius: 2px;-- background: ${cssVar.colorFillSecondary};- `,- fill: css`- height: 100%;- border-radius: 2px;- `,-}));--/**- * How much of the workspace's storage the instances on this page occupy.- *- * On the page for exactly one reason: a workspace over its limit refuses- * writes, and until now the only way to discover that was a save that failed.- * The number is what was last measured rather than a fresh walk of the volume โ- * measuring stamps the workspace as active, so it belongs on the refresh button- * beside this, not on every page load.- *- * Renders nothing without a workspace. Persistence is the paid boundary, and an- * account that has none has no meter to read; the page's own upgrade prompt is- * what speaks to that.- */-const WorkspaceUsageMeter = memo(() => {- const { t } = useTranslation('setting');- const { data, error } = useWorkspaceUsage();-- if (error || !data) return null;-- const { quotaBytes, usageBytes, usageCheckedAt } = data;-- // Never measured. Saying "0 bytes" would be a claim we have not earned, and- // on a workspace that has actually been written to it is the wrong one.- if (usageBytes === null || usageBytes === undefined) {- return (- <Text fontSize={12} style={{ whiteSpace: 'nowrap' }} type={'secondary'}>- {t('environments.storage.unmeasured', { total: formatSize(quotaBytes) })}- </Text>- );- }-- const ratio = quotaBytes > 0 ? usageBytes / quotaBytes : 0;- const over = usageBytes > quotaBytes;-- const label = (- <Flexbox horizontal align={'center'} gap={6} style={{ flex: 'none' }}>- <div className={styles.bar}>- <div- className={styles.fill}- style={{- background: over ? cssVar.colorError : cssVar.colorTextTertiary,- // Capped, so an over-quota workspace still draws a full bar rather- // than overflowing its track.- width: `${Math.min(100, Math.max(ratio * 100, usageBytes > 0 ? 2 : 0))}%`,- }}- />- </div>- <Text- fontSize={12}- style={{ whiteSpace: 'nowrap' }}- type={over ? 'danger' : 'secondary'}- weight={500}- >- {t('environments.storage.used', {- total: formatSize(quotaBytes),- used: formatSize(usageBytes),- })}- </Text>- </Flexbox>- );-- return (- <Tooltip- title={- over- ? t('environments.storage.over')- : usageCheckedAt- ? t('environments.storage.measuredAt', {- time: new Date(usageCheckedAt).toLocaleString(),- })- : undefined- }- >- {label}- </Tooltip>- );-});--WorkspaceUsageMeter.displayName = 'WorkspaceUsageMeter';--export default WorkspaceUsageMeter;diff --git a/src/features/EnvironmentManager/detailTabs.test.ts b/src/features/EnvironmentManager/detailTabs.test.tsdeleted file mode 100644index bd9d4a5a1b8..00000000000--- a/src/features/EnvironmentManager/detailTabs.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { describe, expect, it } from 'vitest';--import { copyTabs, isCopyTab, resolveDetailTab } from './detailTabs';--describe('copyTabs', () => {- it('folds a single copy into an Overview, with no Copies tab', () => {- expect(copyTabs(1)).toEqual(['overview']);- });-- it('gives an environment with no copy yet the Overview too', () => {- expect(copyTabs(0)).toEqual(['overview']);- });-- it('lists the copies, with their run history, once there is more than one', () => {- expect(copyTabs(2)).toEqual(['instances', 'sessions']);- });-});--describe('isCopyTab', () => {- it('tells the copy tabs from the form sections', () => {- expect(isCopyTab('overview')).toBe(true);- expect(isCopyTab('instances')).toBe(true);- expect(isCopyTab('settings')).toBe(false);- });-});--describe('resolveDetailTab', () => {- it('opens on Overview for a single copy, and on the Copies list for several', () => {- expect(resolveDetailTab(undefined, 1)).toBe('overview');- expect(resolveDetailTab(undefined, 2)).toBe('instances');- });-- it('moves Overview to the Copies list once a second copy exists', () => {- expect(resolveDetailTab('overview', 2)).toBe('instances');- });-- it('moves the Copies list and its history back to Overview at one copy', () => {- expect(resolveDetailTab('instances', 1)).toBe('overview');- expect(resolveDetailTab('sessions', 1)).toBe('overview');- });-- it('keeps a form tab whatever the copy count', () => {- expect(resolveDetailTab('settings', 1)).toBe('settings');- expect(resolveDetailTab('variables', 3)).toBe('variables');- });-});diff --git a/src/features/EnvironmentManager/detailTabs.ts b/src/features/EnvironmentManager/detailTabs.tsdeleted file mode 100644index cd80354cf1e..00000000000--- a/src/features/EnvironmentManager/detailTabs.ts+++ /dev/null@@ -1,33 +0,0 @@-/** The detail panel's tabs that describe an environment's copies. */-export type CopyTab = 'instances' | 'overview' | 'sessions';--export const isCopyTab = (tab: string): tab is CopyTab =>- tab === 'instances' || tab === 'overview' || tab === 'sessions';--/**- * Which copy tabs the detail panel shows, given how many copies it has.- *- * One copy โ what nearly every environment has โ is not worth a tab of its- * own: it IS the environment, so its build state, its files and its run- * history go straight into an Overview. Only once there is a second copy is- * there a list worth showing, and with it a run history that spans them.- * An environment with none yet (made before every environment came with one)- * gets the Overview too, whose empty state offers to make it.- */-export const copyTabs = (instanceCount: number): CopyTab[] =>- instanceCount > 1 ? ['instances', 'sessions'] : ['overview'];--/**- * The tab to show: the one picked, unless the copy count has since taken it- * away. A second copy made while Overview is open turns Overview into the- * Copies list; the last extra copy deleted turns the list back into Overview.- * Nothing picked yet lands on the first copy tab.- */-export const resolveDetailTab = <T extends string>(- picked: T | undefined,- instanceCount: number,-): T | CopyTab => {- const copies = copyTabs(instanceCount);-- return picked && (!isCopyTab(picked) || copies.includes(picked)) ? picked : copies[0];-};diff --git a/src/features/EnvironmentManager/environmentCreated.test.ts b/src/features/EnvironmentManager/environmentCreated.test.tsdeleted file mode 100644index 74a752be86b..00000000000--- a/src/features/EnvironmentManager/environmentCreated.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { openCreatedEnvironment } from './environmentCreated';--describe('openCreatedEnvironment', () => {- it('opens the new environment and starts its default copy, asking nothing', () => {- const select = vi.fn();- const buildInstance = vi.fn().mockResolvedValue(undefined);-- openCreatedEnvironment(- { defaultInstance: { id: 'inst-default' } as never, id: 'env-1' },- { buildInstance, select },- );-- expect(select).toHaveBeenCalledWith('env-1');- expect(buildInstance).toHaveBeenCalledWith('inst-default');- });-- it('opens the environment and builds nothing when the server sent no default copy', () => {- const select = vi.fn();- const buildInstance = vi.fn().mockResolvedValue(undefined);-- openCreatedEnvironment({ defaultInstance: undefined, id: 'env-1' }, { buildInstance, select });-- expect(select).toHaveBeenCalledWith('env-1');- expect(buildInstance).not.toHaveBeenCalled();- });-});diff --git a/src/features/EnvironmentManager/environmentCreated.ts b/src/features/EnvironmentManager/environmentCreated.tsdeleted file mode 100644index 7207527a4af..00000000000--- a/src/features/EnvironmentManager/environmentCreated.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { CreatedEnvironment } from './useEnvironmentData';--/**- * Straight after an environment is created: open it, and start its default- * copy, which the server made in the same call. Nothing is asked โ the person- * has not started any work yet, so a name and a folder would be answers made- * up on the spot; both are derived, and renaming is on the copy's row.- *- * A code environment clones and installs, so this is where that build starts,- * after the dialog has closed. A files environment has nothing to build: the- * same call is settled as ready on the server without starting a sandbox, so- * the copy never sits in a "pending" state waiting on a build that will not- * come.- */-export const openCreatedEnvironment = (- created: Pick<CreatedEnvironment, 'defaultInstance' | 'id'>,- {- buildInstance,- select,- }: { buildInstance: (instanceId: string) => Promise<void>; select: (id: string) => void },-) => {- select(created.id);- if (created.defaultInstance) void buildInstance(created.defaultInstance.id);-};diff --git a/src/features/EnvironmentManager/errorMessage.test.ts b/src/features/EnvironmentManager/errorMessage.test.tsindex 9e5fa12863e..71de73e3d21 100644--- a/src/features/EnvironmentManager/errorMessage.test.ts+++ b/src/features/EnvironmentManager/errorMessage.test.ts@@ -11,10 +11,13 @@ describe('describeError', () => {);});- it('turns the default-instance refusal into its sentence rather than the code', () => {- expect(describeError(new Error('DEFAULT_INSTANCE'), t, 'fallback')).toBe(- '<environments.instances.defaultUndeletable>',- );+ it.each([+ ['FOLDER_NOT_EMPTY', 'environments.files.folderNotEmpty'],+ ['INSTANCE_READ_ONLY', 'environments.files.readOnly'],+ ['PATH_NOT_FOUND', 'environments.files.notFound'],+ ['DUPLICATE_INSTANCE_DIRECTORY', 'environments.files.folderTaken'],+ ])('turns the drive refusal %s into its sentence rather than the code', (code, key) => {+ expect(describeError(new Error(code), t, 'fallback')).toBe(`<${key}>`);});it('turns a path the server confined to the instance into the same line', () => {diff --git a/src/features/EnvironmentManager/errorMessage.ts b/src/features/EnvironmentManager/errorMessage.tsindex a018127d315..0666d718e96 100644--- a/src/features/EnvironmentManager/errorMessage.ts+++ b/src/features/EnvironmentManager/errorMessage.ts@@ -12,17 +12,25 @@ import { isMachineErrorMessage } from '@/utils/machineErrorMessage';* sentence โ falls back to the caller's generic line.*/const CODE_KEYS: Record<string, string> = {- DEFAULT_INSTANCE: 'environments.instances.defaultUndeletable',+ DUPLICATE_INSTANCE_DIRECTORY: 'environments.files.folderTaken',ENVIRONMENT_HAS_INSTANCES: 'environments.hasInstances',// The execution plane calls this an instance now too. The old// code is kept until that rename is deployed everywhere, so a refusal from a// server still on the previous build reads as a sentence rather than a code.+ ENVIRONMENT_IN_PROJECT: 'environments.inProject',ENVIRONMENT_IN_USE: 'environments.instances.inUse',+ // Initializing a folder that already holds work would mix a checkout into it.+ FOLDER_NOT_EMPTY: 'environments.files.folderNotEmpty',INSTANCE_BUILDING: 'environments.instances.stopBuilding',INSTANCE_BUSY: 'environments.instances.stopBusy',INSTANCE_IN_USE: 'environments.instances.inUse',+ // An environment directory is written by its own sessions alone.+ INSTANCE_READ_ONLY: 'environments.files.readOnly',+ // A private environment's directory left on the public drive.+ INSTANCE_REBUILD_REQUIRED: 'environments.instances.rebuildPersonalRequired',INSTANCE_STARTING: 'environments.instances.stopStarting',INSTANCE_STOP_FAILED: 'environments.instances.stopRefused',+ PATH_NOT_FOUND: 'environments.files.notFound',PATH_OUTSIDE_INSTANCE: 'environments.files.invalidPath',// Retryable on purpose: the run is still packing its snapshot, and the// execution plane would rather leave it running than cut the save off.diff --git a/src/features/EnvironmentManager/index.tsx b/src/features/EnvironmentManager/index.tsxindex b0f83898289..08af8cb0966 100644--- a/src/features/EnvironmentManager/index.tsx+++ b/src/features/EnvironmentManager/index.tsx@@ -19,18 +19,9 @@ import AsyncBoundary from '@/components/AsyncBoundary';import ListSkeleton from '@/components/ListSkeleton';import { openCreateEnvironmentModal } from './CreateEnvironmentModal';-import { openCreateInstanceModal } from './CreateInstanceModal';-import { openCreatedEnvironment } from './environmentCreated';import EnvironmentDetailPanel from './EnvironmentDetailPanel';import EnvironmentItem from './EnvironmentItem';-import {- type CreatedEnvironment,- useEnvironmentActions,- useEnvironments,- useInstances,- useWorkspaceUsage,-} from './useEnvironmentData';-import WorkspaceUsageMeter from './WorkspaceUsageMeter';+import { type CreatedEnvironment, useEnvironments } from './useEnvironmentData';const styles = createStaticStyles(({ css }) => ({detailCol: css`@@ -70,11 +61,14 @@ const styles = createStaticStyles(({ css }) => ({const LIST_MIN_HEIGHT = 4 * 72;/**- * Environments and the copies built from them.+ * Code environments and the folders initialized from them.** An environment is a SPECIFICATION โ the sources to check out, what makes them- * usable, what they run with. What a sandbox builds from it is a cache, which is- * why a copy can be thrown away and made again rather than repaired by hand.+ * usable, what they run with. Writing one down needs no drive, so this page is+ * there for everyone; what a sandbox builds from it on the drive is a cache,+ * which is why a folder can be thrown away and made again rather than repaired+ * 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@@ -99,9 +93,6 @@ interface EnvironmentManagerProps {const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility }) => {const { t } = useTranslation('setting');const { data, error, isValidating, mutate } = useEnvironments(visibility);- const { data: instanceData, mutate: refreshInstances } = useInstances();- const { refresh: refreshUsage } = useWorkspaceUsage();- const { buildInstance } = useEnvironmentActions();const [selectedId, setSelectedId] = useState<string>();// Whether a refresh the user asked for is still running.@@ -123,7 +114,6 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })}, [isValidating]);const environments = data?.environments ?? [];- const instances = instanceData?.instances ?? [];const selected = selectedId? environments.find((environment) => environment.id === selectedId): undefined;@@ -132,56 +122,35 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })setSelectedId((current) => (current === id ? undefined : id));};- // The row's "new copy" shortcut: open the environment so the copy is seen- // landing in its list, and ask for it in the same dialog the panel's own- // button opens.- const createInstance = (id: string) => {- setSelectedId(id);- openCreateInstanceModal({ environmentId: id });- };-- // No instance dialog after creating one: see `openCreatedEnvironment`.- const onEnvironmentCreated = (created: CreatedEnvironment) =>- openCreatedEnvironment(created, { buildInstance, select: setSelectedId });+ // 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);/**- * Both lists, because the two halves of what this page shows are fetched- * separately and the slow one โ instance state, which needs the execution- * plane โ is the one worth a manual refresh.- ** The spinner is driven by this call rather than by SWR's `isValidating`,- * which is true of every fetch the page makes. Read off that flag the button- * span on a tab switch and on any background revalidation, reporting work- * nobody asked it to do and, worse, implying the click had already happened.+ * 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 {- // The storage figure rides along, because this is the one moment the- // user has asked for a fresh answer โ and re-measuring also stamps the- // workspace as active, which no page load should do on its own.- await Promise.all([mutate(), refreshInstances(), refreshUsage()]);+ await mutate();} finally {setRefreshing(false);}};/**- * The storage meter, 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.- *- * No count of environments: the list is right below it and short enough to- * take in at a glance, so the number restated what the reader could already- * see. The meter stays because it is the one number the page cannot show โ- * and the one that stops it working when it runs out.+ * 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' }}>- <WorkspaceUsageMeter /><Buttonicon={<Icon icon={RefreshCwIcon} />}loading={refreshing}@@ -251,21 +220,6 @@ const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility })environment={environment}key={environment.id}selected={environment.id === selectedId}- instanceCount={- instances.filter((instance) => instance.environmentId === environment.id).length- }- // What the environment's instances keep, summed. A brand-new- // instance has no snapshot and counts as nothing; when the- // snapshot store could not be reached the sizes are unknown,- // not zero, so the row says nothing rather than "0 B".- storageBytes={- instanceData?.snapshotsUnavailable- ? null- : instances- .filter((instance) => instance.environmentId === environment.id)- .reduce((sum, instance) => sum + (instance.snapshot?.bytes ?? 0), 0)- }- onCreateInstance={() => createInstance(environment.id)}onSelect={() => select(environment.id)}/>))}diff --git a/src/features/EnvironmentManager/instanceActions.test.ts b/src/features/EnvironmentManager/instanceActions.test.tsdeleted file mode 100644index d7d934f8524..00000000000--- a/src/features/EnvironmentManager/instanceActions.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import {- canCopyInstance,- copyBlockReason,- copyEntryTitle,- deleteEntry,- recheckCopySource,-} from './instanceActions';--const idle = { buildId: null, id: 'inst-1', inUse: false, status: 'ready' };--describe('copyBlockReason', () => {- it('allows a copy of an idle, built copy', () => {- expect(copyBlockReason(idle, false)).toBeUndefined();- });-- it('blocks a copy a run is holding โ the server answers INSTANCE_IN_USE', () => {- expect(copyBlockReason({ ...idle, inUse: true }, false)).toBe('inUse');- });-- it('does not read an unanswered lease store as free', () => {- expect(copyBlockReason(idle, true)).toBe('occupancyUnknown');- });-- it('blocks a copy whose build is replacing its folder', () => {- expect(copyBlockReason({ ...idle, buildId: 'b1', status: 'pending' }, false)).toBe('building');- });-- it('allows a never-built copy, which nothing is writing to', () => {- expect(copyBlockReason({ ...idle, status: 'pending' }, false)).toBeUndefined();- });-});--describe('copyEntryTitle', () => {- it('says why the entry is greyed out', () => {- expect(copyEntryTitle('inUse')).toBe('environments.instances.copyInUse');- expect(copyEntryTitle('occupancyUnknown')).toBe('environments.instances.copyOccupancyUnknown');- expect(copyEntryTitle('building')).toBe('environments.instances.copyBuilding');- });-- it('names the action when it is available', () => {- expect(copyEntryTitle(undefined)).toBe('environments.instances.copy');- });-});--describe('recheckCopySource', () => {- it('lets the dialog open when the fresh read still finds the source idle', async () => {- const refetch = vi.fn().mockResolvedValue({ instances: [idle], occupancyUnavailable: false });-- await expect(recheckCopySource('inst-1', refetch)).resolves.toBeUndefined();- expect(refetch).toHaveBeenCalledTimes(1);- });-- it('stops the copy when a run took the source since the list was drawn', async () => {- const refetch = vi- .fn()- .mockResolvedValue({ instances: [{ ...idle, inUse: true }], occupancyUnavailable: false });-- await expect(recheckCopySource('inst-1', refetch)).resolves.toBe('inUse');- });-- it('stops the copy when the fresh read cannot tell who holds it', async () => {- const refetch = vi.fn().mockResolvedValue({ instances: [idle], occupancyUnavailable: true });-- await expect(recheckCopySource('inst-1', refetch)).resolves.toBe('occupancyUnknown');- });-- it('leaves a failed re-read to the server, which checks again', async () => {- const refetch = vi.fn().mockRejectedValue(new Error('network'));-- await expect(recheckCopySource('inst-1', refetch)).resolves.toBeUndefined();- });-});--describe('deleteEntry', () => {- it('offers no delete on the default copy among several, even to its creator', () => {- expect(deleteEntry({ isDefault: true }, { editable: true, single: false })).toBeUndefined();- });-- it('offers to delete a copy beside the default', () => {- expect(deleteEntry({ isDefault: false }, { editable: true, single: false })).toBe('instance');- });-- it("makes the only copy's delete entry delete the environment", () => {- expect(deleteEntry({ isDefault: true }, { editable: true, single: true })).toBe('environment');- });-- it('offers no delete to anyone but the creator', () => {- expect(deleteEntry({ isDefault: false }, { editable: false, single: false })).toBeUndefined();- expect(deleteEntry({ isDefault: true }, { editable: false, single: true })).toBeUndefined();- });-});--describe('canCopyInstance', () => {- it('shows the copy entry to the environment creator only', () => {- expect(canCopyInstance(true)).toBe(true);- expect(canCopyInstance(false)).toBe(false);- });-});diff --git a/src/features/EnvironmentManager/instanceActions.ts b/src/features/EnvironmentManager/instanceActions.tsdeleted file mode 100644index 8c321dbe1c0..00000000000--- a/src/features/EnvironmentManager/instanceActions.ts+++ /dev/null@@ -1,99 +0,0 @@-/**- * What a copy's row in settings offers, decided apart from how it is drawn.- */--/**- * Why a copy cannot be taken of this instance right now, or `undefined` when it- * can.- *- * A copy captures the source's whole tree, so it is only taken of a source- * nothing is writing to. The server refuses a held source with- * `INSTANCE_IN_USE`; this answers the same question first, so the entry is- * greyed out with the reason beside it instead of failing after a dialog has- * been filled in.- *- * - `inUse`: a conversation, a build or the file browser holds it.- * - `occupancyUnknown`: the lease store did not answer. Not read as free โ- * the server refuses in that case too, for the same reason.- * - `building`: a build is replacing its folder; what a copy took now would be- * half a checkout.- */-export type CopyBlockReason = 'building' | 'inUse' | 'occupancyUnknown';--interface CopySource {- buildId?: string | null;- inUse: boolean;- status: string;-}--export const copyBlockReason = (- instance: CopySource,- occupancyUnavailable: boolean,-): CopyBlockReason | undefined => {- if (instance.inUse) return 'inUse';- if (occupancyUnavailable) return 'occupancyUnknown';- if (instance.status === 'pending' && instance.buildId) return 'building';-- return undefined;-};--/** The copy entry's tooltip: what it does, or why it cannot right now. */-export const copyEntryTitle = (reason: CopyBlockReason | undefined) =>- reason === 'inUse'- ? 'environments.instances.copyInUse'- : reason === 'occupancyUnknown'- ? 'environments.instances.copyOccupancyUnknown'- : reason === 'building'- ? 'environments.instances.copyBuilding'- : 'environments.instances.copy';--/**- * Asks again, right before the copy dialog opens, whether the source is still- * free. Occupancy changes without the page being told โ a conversation picks- * the copy up in another tab โ so the answer the list was drawn with is not- * trusted for the click.- *- * A failed re-read lets the dialog open: the check is a courtesy, and the- * server checks again and says why.- */-export const recheckCopySource = async (- instanceId: string,- refetch: () => Promise<- { instances: (CopySource & { id: string })[]; occupancyUnavailable: boolean } | undefined- >,-): Promise<CopyBlockReason | undefined> => {- try {- const fresh = await refetch();- const latest = fresh?.instances.find((row) => row.id === instanceId);-- return latest ? copyBlockReason(latest, fresh?.occupancyUnavailable ?? false) : undefined;- } catch {- return undefined;- }-};--/**- * What the row's delete entry deletes, or `undefined` when it has none.- *- * Never the default copy on its own: it is what the environment is, and the- * server refuses to delete it. A broken one is rebuilt. When it is the only- * copy, the entry is there and deletes the environment, which is how that copy- * goes. Only for the environment's creator, like every other change to its- * copies.- */-export const deleteEntry = (- instance: { isDefault: boolean },- { editable, single }: { editable: boolean; single: boolean },-): 'environment' | 'instance' | undefined => {- if (!editable) return undefined;- if (single) return 'environment';-- return instance.isDefault ? undefined : 'instance';-};--/**- * Whether the row offers to copy this copy at all โ enabled or greyed out is- * {@link copyBlockReason}'s answer. The creator's only: a colleague who can run- * in a published environment cannot take its state with them.- */-export const canCopyInstance = (editable: boolean) => editable;diff --git a/src/features/EnvironmentManager/instanceDirectory.test.ts b/src/features/EnvironmentManager/instanceDirectory.test.tsdeleted file mode 100644index 3fac6e20160..00000000000--- a/src/features/EnvironmentManager/instanceDirectory.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { describe, expect, it } from 'vitest';--import { suggestInstanceDirectory } from './instanceDirectory';--describe('suggestInstanceDirectory', () => {- it('turns a name into one path segment', () => {- expect(suggestInstanceDirectory('Lobehub Dev')).toBe('lobehub-dev');- expect(suggestInstanceDirectory(' Q3 Reports ')).toBe('q3-reports');- });-- it('never suggests a nested path', () => {- // A slash would put this instance inside another's tree, which is the one- // thing separate instances exist to prevent.- expect(suggestInstanceDirectory('reports/q3')).toBe('reports-q3');- expect(suggestInstanceDirectory('../escape')).toBe('escape');- });-- it('never suggests a hidden folder, or the reserved one', () => {- // `.sandbox` holds the environment snapshots this instance is restored- // from; a working directory there would run inside its own store.- expect(suggestInstanceDirectory('.sandbox')).toBe('sandbox');- expect(suggestInstanceDirectory('.hidden')).toBe('hidden');- });-- it('gives back nothing when nothing usable is left', () => {- // Blank leaves the field empty and the button disabled, which is better- // than proposing a folder called `-`.- expect(suggestInstanceDirectory('โโ ///')).toBe('');- expect(suggestInstanceDirectory('')).toBe('');- });-- it('keeps a name that is already a usable folder', () => {- expect(suggestInstanceDirectory('lobehub-dev')).toBe('lobehub-dev');- expect(suggestInstanceDirectory('v1.2_beta')).toBe('v1.2_beta');- });-});diff --git a/src/features/EnvironmentManager/instanceDirectory.ts b/src/features/EnvironmentManager/instanceDirectory.tsdeleted file mode 100644index 05aadfbc6de..00000000000--- a/src/features/EnvironmentManager/instanceDirectory.ts+++ /dev/null@@ -1,31 +0,0 @@-import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';--/**- * A folder name for an instance, derived from what it is called.- *- * The folder is the one field in the dialog with no obvious answer โ it is a- * name in a filesystem nobody has seen, asked for before the person has any- * reason to care where their files land. Almost always the right answer is "a- * folder of its own, named after this instance", so that is what the field- * offers; it stays editable for the times it is not.- *- * Returns an empty string when nothing usable is left, which leaves the field- * blank and the button disabled โ better than a folder called `-`.- */-export const suggestInstanceDirectory = (name: string): string => {- const slug = name- .toLowerCase()- .trim()- // Everything a single path segment should not carry, the separator- // included: a suggestion must never quietly nest one instance inside- // another's tree.- .replaceAll(/[^\da-z._-]+/gu, '-')- .replaceAll(/-{2,}/gu, '-')- // Leading dots would make it hidden, and `.sandbox` in particular is where- // environment snapshots live โ an instance rooted there would run inside- // the store it is restored from. Stripping them sidesteps both.- .replace(/^[.-]+/u, '')- .replace(/[.-]+$/u, '');-- return slug && isSafeSandboxCwd(slug) ? slug : '';-};diff --git a/src/features/EnvironmentManager/sessionHistory.test.ts b/src/features/EnvironmentManager/sessionHistory.test.tsdeleted file mode 100644index af162732997..00000000000--- a/src/features/EnvironmentManager/sessionHistory.test.ts+++ /dev/null@@ -1,188 +0,0 @@-import { describe, expect, it } from 'vitest';--import { conversationPath, runningSessionIds, withoutBuildVehicles } from './SessionHistorySection';--const session = (overrides: Partial<any>): any => ({- buildId: null,- endedAt: null,- endReason: null,- id: 1,- instanceId: 'inst-a',- instanceName: 'Lobehub Dev',- kind: 'session',- management: false,- sessionId: 'sess-1',- sessionUserId: 'user_1',- snapshotBytes: null,- startedAt: '2026-09-24T02:00:00.000Z',- topicAgentId: null,- topicGroupId: null,- topicId: null,- topicTitle: null,- ...overrides,-});--describe('withoutBuildVehicles', () => {- it('shows one run for a build, not two', () => {- // The trail records a build twice โ once when its sandbox starts, as a- // management session, once when the build does โ and the panel listed both- // side by side, the first labelled "file browser".- const rows = [- session({ buildId: 'build-1', id: 2, kind: 'build', management: true }),- session({ id: 1, management: true }),- ];-- const kept = withoutBuildVehicles(rows);-- expect(kept.map((row) => row.kind)).toEqual(['build']);- });-- it('keeps a console session that no build rode in on', () => {- // The file browser opens one of these on its own; nothing else explains it.- const rows = [session({ id: 1, management: true, sessionId: 'sess-console' })];-- expect(withoutBuildVehicles(rows)).toEqual(rows);- });-- it('keeps a console session running beside an unrelated build', () => {- const rows = [- session({ buildId: 'build-1', id: 3, kind: 'build', management: true }),- session({ id: 2, management: true, sessionId: 'sess-console' }),- ];-- expect(withoutBuildVehicles(rows).map((row) => row.sessionId)).toEqual([- 'sess-1',- 'sess-console',- ]);- });-- it("never drops a conversation's own run", () => {- // A conversation is not a management session, so even sharing a sandbox- // with a build could not remove it from the list.- const rows = [- session({ buildId: 'build-1', id: 2, kind: 'build', management: true }),- session({ id: 1, topicId: 'tpc-1', topicTitle: 'Some topic' }),- ];-- expect(withoutBuildVehicles(rows).map((row) => row.topicId)).toEqual([null, 'tpc-1']);- });-- it('leaves a list with no builds in it alone', () => {- const rows = [session({ id: 1, topicId: 'tpc-1' })];-- expect(withoutBuildVehicles(rows)).toBe(rows);- });-});--describe('runningSessionIds', () => {- const free = { held: new Set<string>(), unknown: false };- const holding = (...ids: string[]) => ({ held: new Set(ids), unknown: false });- const running = (rows: any[], occupancy: any) => [...runningSessionIds(rows, occupancy)];-- it('is running while its instance is actually held', () => {- expect(running([session({})], holding('inst-a'))).toEqual([1]);- });-- // The bug this exists for: a sandbox that went away without a teardown never- // gets an `endedAt`, so the row said "running" for twelve hours while the- // composer's own menu offered the same instance as free.- it('is not running once the lease on its instance has gone', () => {- expect(running([session({})], free)).toEqual([]);- });-- // "Not known" is not "free". A reader that collapses the two would retire- // every live session on the page the moment the lease store hiccuped.- it('stays running when the lease store did not answer', () => {- expect(running([session({})], { held: new Set<string>(), unknown: true })).toEqual([1]);- });-- it('is never running once an end was recorded, whoever holds the instance', () => {- const ended = session({ endReason: 'idle', endedAt: '2026-09-24T03:00:00.000Z' });-- expect(running([ended], holding('inst-a'))).toEqual([]);- expect(running([ended], { held: new Set(['inst-a']), unknown: true })).toEqual([]);- });-- // The second bug: the lease belongs to the INSTANCE, so one live run made- // every abandoned record on the same instance read "running" again โ three- // rows at once, two of them 55 and 61 hours old. The execution plane runs one- // session per instance, so only the newest of them can be the live one.- it('marks only the newest open run on a held instance', () => {- const rows = [- session({ id: 1, startedAt: '2026-09-22T01:00:00.000Z' }),- session({ id: 2, startedAt: '2026-09-24T09:00:00.000Z' }),- session({ id: 3, startedAt: '2026-09-23T05:00:00.000Z' }),- ];-- expect(running(rows, holding('inst-a'))).toEqual([2]);- });-- it('picks the newest per instance, not one winner for the whole page', () => {- const rows = [- session({ instanceId: 'inst-a', id: 1, startedAt: '2026-09-22T01:00:00.000Z' }),- session({ instanceId: 'inst-a', id: 2, startedAt: '2026-09-24T09:00:00.000Z' }),- session({ instanceId: 'inst-b', id: 3, startedAt: '2026-09-23T05:00:00.000Z' }),- ];-- expect(running(rows, holding('inst-a', 'inst-b')).sort()).toEqual([2, 3]);- });-- // An ended run is not a candidate at all, so it cannot shadow the open one- // behind it just by being more recent.- it('ignores ended runs when picking the newest', () => {- const rows = [- session({ id: 1, startedAt: '2026-09-22T01:00:00.000Z' }),- session({- endReason: 'idle',- endedAt: '2026-09-24T10:00:00.000Z',- id: 2,- startedAt: '2026-09-24T09:00:00.000Z',- }),- ];-- expect(running(rows, holding('inst-a'))).toEqual([1]);- });-- // A build's own record is a run like any other, and it is held by the- // instance it builds โ nothing about it should read differently here.- it('judges a build the same way', () => {- const build = session({ buildId: 'build-1', kind: 'build', management: true });-- expect(running([build], holding('inst-a'))).toEqual([1]);- expect(running([build], free)).toEqual([]);- });-- it('does not match an instance it has no id for', () => {- expect(running([session({ instanceId: null })], holding('inst-a'))).toEqual([]);- });-});--describe('conversationPath', () => {- it('addresses the conversation by its agent, not by the topic alone', () => {- // `/chat?topic=<id>` is not a route: it rendered the 404 page, so the one- // way back from a running run into the conversation went nowhere.- expect(conversationPath(session({ topicAgentId: 'agt_1', topicId: 'tpc_1' }))).toBe(- '/agent/agt_1/tpc_1',- );- });-- it('offers nothing when the agent is unknown', () => {- // The topic is another member's, or was deleted โ a link built from half- // the address would 404 exactly like the old one did.- expect(conversationPath(session({ topicAgentId: null, topicId: 'tpc_1' }))).toBeUndefined();- });-- it('sends a group run back to the group, not to the member that answered', () => {- // A group topic carries an agent id too โ the member whose turn it was.- // Reading that first opens a different conversation than the run came from.- expect(- conversationPath(session({ topicAgentId: 'agt_1', topicGroupId: 'grp_1', topicId: 'tpc_1' })),- ).toBe('/group/grp_1/tpc_1');- });-- it('offers nothing for a management session', () => {- expect(- conversationPath(session({ management: true, topicAgentId: 'agt_1', topicId: 'tpc_1' })),- ).toBeUndefined();- });-});diff --git a/src/features/EnvironmentManager/settleThenRefresh.test.ts b/src/features/EnvironmentManager/settleThenRefresh.test.tsdeleted file mode 100644index 214972a1a77..00000000000--- a/src/features/EnvironmentManager/settleThenRefresh.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { settleThenRefresh } from './settleThenRefresh';--describe('settleThenRefresh', () => {- it('returns the mutation result even when the refresh fails', async () => {- const refresh = vi.fn().mockRejectedValue(new Error('revalidation failed'));-- await expect(settleThenRefresh(async () => ({ stopped: true }), refresh)).resolves.toEqual({- stopped: true,- });- expect(refresh).toHaveBeenCalledTimes(1);- });-- it('keeps the mutation error rather than the refresh error', async () => {- const refresh = vi.fn().mockRejectedValue(new Error('revalidation failed'));-- await expect(- settleThenRefresh(() => Promise.reject(new Error('SNAPSHOT_IN_PROGRESS')), refresh),- ).rejects.toThrow('SNAPSHOT_IN_PROGRESS');- expect(refresh).toHaveBeenCalledTimes(1);- });-- it('refreshes after a failed mutation too', async () => {- const refresh = vi.fn().mockResolvedValue(undefined);-- await expect(- settleThenRefresh(() => Promise.reject(new Error('INSTANCE_IN_USE')), refresh),- ).rejects.toThrow('INSTANCE_IN_USE');- expect(refresh).toHaveBeenCalledTimes(1);- });-});diff --git a/src/features/EnvironmentManager/settleThenRefresh.ts b/src/features/EnvironmentManager/settleThenRefresh.tsdeleted file mode 100644index a7c5a835fe3..00000000000--- a/src/features/EnvironmentManager/settleThenRefresh.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * Run a mutation, then refresh the list it changed โ whichever way it went.- *- * The refresh is best-effort and must never decide the outcome. Awaited in a- * `finally`, a refresh that rejected replaced the mutation's own result: a stop- * that succeeded read as "could not stop", and a refusal worth reading- * (`SNAPSHOT_IN_PROGRESS`, "a conversation is using it") was swapped for an- * unrelated revalidation error. The list catches up on its next revalidation.- */-export const settleThenRefresh = async <T>(- mutation: () => Promise<T>,- refresh: () => Promise<unknown>,-): Promise<T> => {- try {- return await mutation();- } finally {- await refresh().catch(() => undefined);- }-};diff --git a/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.ts b/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.tsnew file mode 100644index 00000000000..e3fb377abaa--- /dev/null+++ b/src/features/EnvironmentManager/useEnvironmentActions.visibility.test.ts@@ -0,0 +1,41 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { environmentService } from '@/services/environment';++import { useEnvironmentActions } from './useEnvironmentData';++const swr = vi.hoisted(() => ({ mutate: vi.fn() }));++vi.mock('swr', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useSWRConfig: () => ({ mutate: swr.mutate }),+}));++vi.mock('@/services/environment', () => ({+ environmentService: { setEnvironmentVisibility: vi.fn() },+}));++describe('useEnvironmentActions.setEnvironmentVisibility', () => {+ beforeEach(() => {+ swr.mutate.mockReset().mockResolvedValue(undefined);+ vi.mocked(environmentService.setEnvironmentVisibility).mockResolvedValue({} as any);+ });++ it('should refresh every environment list, since publishing moves a row between them', async () => {+ const { result } = renderHook(() => useEnvironmentActions());++ await act(async () => {+ await result.current.setEnvironmentVisibility({ id: 'env-1', visibility: 'private' });+ });++ expect(environmentService.setEnvironmentVisibility).toHaveBeenCalledWith({+ id: 'env-1',+ visibility: 'private',+ });+ const [matchesKey] = swr.mutate.mock.calls[0];+ expect(matchesKey(['sandbox-environments', 'public'])).toBe(true);+ expect(matchesKey(['sandbox-environments', 'private'])).toBe(true);+ expect(matchesKey(['sandbox-drive-files'])).toBe(false);+ });+});diff --git a/src/features/EnvironmentManager/useEnvironmentData.ts b/src/features/EnvironmentManager/useEnvironmentData.tsindex 4b9f879d229..1acb896f539 100644--- a/src/features/EnvironmentManager/useEnvironmentData.ts+++ b/src/features/EnvironmentManager/useEnvironmentData.ts@@ -1,19 +1,14 @@import type { EnvironmentVisibility } from '@lobechat/types';-import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useSWRConfig } from 'swr';import { useClientDataSWR } from '@/libs/swr';import {+ environmentService,+ type NewEnvironmentSpecification,type SandboxEnvironmentSpecification,- sandboxStorageService,-} from '@/services/sandboxStorage';--import { settleThenRefresh } from './settleThenRefresh';+} from '@/services/environment';const ENVIRONMENTS_KEY = 'sandbox-environments';-const INSTANCES_KEY = 'sandbox-environment-instances';-const WORKSPACE_KEY = 'sandbox-workspace-info';-const BUILD_KEY = 'sandbox-instance-build';/*** Specifications. Answered from the database alone, so this settles fast and is@@ -31,268 +26,13 @@ const BUILD_KEY = 'sandbox-instance-build';* for whom.*/export const useEnvironments = (visibility?: EnvironmentVisibility) =>- useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listEnvironments>>>(+ useClientDataSWR<Awaited<ReturnType<typeof environmentService.listEnvironments>>>([ENVIRONMENTS_KEY, visibility ?? 'all'],- () => sandboxStorageService.listEnvironments(visibility ? { visibility } : undefined),+ () => environmentService.listEnvironments(visibility ? { visibility } : undefined),);-/**- * Working copies, in two phases.- *- * The rows themselves come from the database and settle in a few milliseconds.- * Their sizes come from the execution plane, which needs a live sandbox session- * to answer โ seconds on a cold start, every time, and it can fail on its own.- * Fetched together, the whole list waited on the slow half; so the rows are- * asked for first and the sizes catch up in a second request that never blocks- * them. While the sizes are still on their way `snapshotsPending` is true and a- * row shows neither a size nor "unused", since it does not know yet; when the- * store cannot be reached the rows still list with `snapshotsUnavailable` set.- */-export const useInstances = () => {- const rows = useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listInstances>>>(- [INSTANCES_KEY, 'rows'],- () => sandboxStorageService.listInstances({ withSizes: false }),- );- const sizes = useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listInstances>>>(- rows.data ? [INSTANCES_KEY, 'sizes'] : null,- () => sandboxStorageService.listInstances(),- // A size does not change while the user looks at the page, and each- // refetch is a sandbox round trip; refocusing the tab must not pay it.- { dedupingInterval: 30_000, revalidateOnFocus: false },- );-- const data = useMemo(() => {- if (!rows.data) return undefined;- const byId = new Map(sizes.data?.instances.map((instance) => [instance.id, instance.snapshot]));- return {- instances: rows.data.instances.map((instance) => ({- ...instance,- snapshot: byId.get(instance.id) ?? null,- })),- // Whether the lease store answered at all. Carried through because a- // reader that cannot tell "free" from "not known" would report an- // unreachable Redis as every instance being idle.- occupancyUnavailable: rows.data.occupancyUnavailable,- snapshotsPending: !sizes.data && !sizes.error,- snapshotsUnavailable: sizes.data ? sizes.data.snapshotsUnavailable : !!sizes.error,- };- }, [rows.data, sizes.data, sizes.error]);-- const mutate = useCallback(async () => {- await rows.mutate();- await sizes.mutate();- }, [rows.mutate, sizes.mutate]);-- return {- data,- error: rows.error,- isLoading: rows.isLoading,- mutate,- // Occupancy and status live on the rows. A change that touches nothing- // else must not wait on the sizes, which can take a sandbox cold start.- refreshRows: rows.mutate,- };-};--/**- * How much of the workspace's storage is used, and how much it has.- *- * Reads the stored figure rather than measuring: a page load must not walk the- * volume, and โ more to the point โ must not stamp the workspace as active,- * which is the signal a later idle sweep selects on. `refresh` is the- * measurement, and it belongs on something the user clicked.- *- * The figure can be null on a workspace nothing has measured yet; that is a- * state to render, not an error. So is the absence of a workspace entirely:- * this is a paid feature, and an account without one simply has no meter.- */-export const useWorkspaceUsage = () => {- const swr = useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.getStorage>>>(- [WORKSPACE_KEY],- () => sandboxStorageService.getStorage(),- // The number moves when a session writes, not while someone reads the- // page; refocusing the tab is not a reason to ask again.- { revalidateOnFocus: false },- );-- const refresh = useCallback(async () => {- // Optimistically publish what the measurement returns, so the meter moves- // with the click instead of after a second round trip.- await swr.mutate(() => sandboxStorageService.refreshStorageUsage(), {- revalidate: false,- });- }, [swr.mutate]);-- return { data: swr.data, error: swr.error, isLoading: swr.isLoading, refresh };-};--/**- * A build in flight, followed until it settles.- *- * Polling rather than a subscription because the runtime has no way to call- * back, and the poll is what moves the instance out of `pending` โ so it has- * to run while the panel is open, and stop the moment nothing is building.- *- * The log accumulates across polls: each reply carries only what was written- * since the offset it was asked for, which is what keeps a minutes-long- * install from resending megabytes on every tick.- */-/**- * The accumulated log of each running build, held outside React.- *- * The row unmounts whenever the panel is left โ another settings tab, another- * environment, a collapsed card โ and a log kept in component state goes with- * it. Coming back then showed a build with no log and no way to open one,- * until a poll had refetched the whole thing from the start; the log was there- * all along on the server, the UI had simply forgotten it.- *- * Keyed by BUILD, not by instance: a rebuild must not inherit the previous- * build's output. Dropped when the build ends, which is the moment the row's- * own stored record takes over โ so this never grows past the builds actually- * running.- */-const buildLogs = new Map<string, { log: string; offset: number }>();--/**- * How much of a build's output is kept in memory. A bootstrap that prints a- * progress bar can emit megabytes before it settles, and the panel that shows- * this is a tab the user may not even have open โ so only the tail is kept.- * `offset` is untouched, so the next poll still resumes where the stream left- * off rather than replaying from the start.- */-const MAX_BUILD_LOG_CHARS = 200_000;--const tailOf = (log: string) =>- log.length > MAX_BUILD_LOG_CHARS ? log.slice(-MAX_BUILD_LOG_CHARS) : log;--export const useInstanceBuild = (instanceId: string, active: boolean, buildId?: string | null) => {- // An instance being followed always has a build id; the fallback only keeps- // the key a string for the inactive case, where nothing is stored anyway.- const cacheKey = buildId ?? instanceId;- const cached = buildLogs.get(cacheKey);- const [log, setLog] = useState(cached?.log ?? '');- const offset = useRef(cached?.offset ?? 0);-- // A second build of the same instance while this row stayed mounted. Reset- // during render rather than in an effect, so the previous build's log is- // never painted under the new build's heading.- const followed = useRef(cacheKey);- if (followed.current !== cacheKey) {- followed.current = cacheKey;- const next = buildLogs.get(cacheKey);- offset.current = next?.offset ?? 0;- setLog(next?.log ?? '');- }-- const { mutate: refreshInstances } = useInstances();-- const swr = useClientDataSWR<- Awaited<ReturnType<typeof sandboxStorageService.instanceBuildStatus>>- >(- active ? [BUILD_KEY, instanceId] : null,- () => sandboxStorageService.instanceBuildStatus({ id: instanceId, logOffset: offset.current }),- {- onSuccess: (data) => {- if (data.chunk) {- // The map is the source of truth, and the state mirrors it: appending- // inside the state updater would double up under StrictMode, which- // calls updaters twice.- const next = tailOf((buildLogs.get(cacheKey)?.log ?? '') + data.chunk);- buildLogs.set(cacheKey, { log: next, offset: data.logOffset });- offset.current = data.logOffset;- setLog(next);- }- // The row settled on the server during this very call, so the list is- // now stale in the one way that matters: the instance still reads as- // building.- if (data.state !== 'running') {- buildLogs.delete(cacheKey);- void refreshInstances();- }- },- refreshInterval: (data) => (data?.state === 'running' ? 2000 : 0),- // Returning to the tab is exactly when a running build is worth a fresh- // look; the poll it would otherwise wait for is up to two seconds away,- // and the key is null unless a build is actually running.- revalidateOnFocus: active,- },- );-- // `error` is surfaced rather than swallowed: a pending instance with no- // state reads as `running` in the row, so a poll that has exhausted its- // retries would otherwise spin forever with nothing to click.- return {- error: swr.error as Error | undefined,- log,- retry: () => void swr.mutate(),- state: swr.data?.state,- };-};--/**- * Instances whose build has been asked for and not yet answered.- *- * Starting a build cold-starts a sandbox, so for a few seconds the row reads- * `pending` with no build id โ the same thing an instance that was never built- * looks like. A row opened in that window would offer "Build" for a build that- * is already on its way. Held outside React because the call is fired from the- * page (straight after an environment is created) and read by a row that may- * mount only once the refreshed list arrives.- */-const startingBuilds = new Set<string>();-const startingListeners = new Set<() => void>();--const setBuildStarting = (id: string, starting: boolean) => {- if (starting) startingBuilds.add(id);- else startingBuilds.delete(id);- for (const listener of startingListeners) listener();-};--const subscribeStartingBuilds = (listener: () => void) => {- startingListeners.add(listener);- return () => {- startingListeners.delete(listener);- };-};--/** Whether a build of this instance has been asked for and has not started yet. */-export const useBuildStarting = (instanceId: string) =>- useSyncExternalStore(- subscribeStartingBuilds,- () => startingBuilds.has(instanceId),- () => false,- );--const SESSIONS_KEY = 'sandbox-environment-sessions';--/**- * One environment's run history. Keyed by environment so opening another- * panel fetches its own rather than serving the previous one's rows.- */-export const useInstanceSessions = (environmentId: string) =>- useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listInstanceSessions>>>(- [SESSIONS_KEY, environmentId],- () => sandboxStorageService.listInstanceSessions({ environmentId }),- {- // A run that is still going changes on its own โ it ends, or a snapshot- // lands โ so the panel keeps looking while one is on screen and stops- // the moment none is.- refreshInterval: (data) => (data?.sessions.some((session) => !session.endedAt) ? 15_000 : 0),- },- );--export type SandboxSessionRecord = NonNullable<- ReturnType<typeof useInstanceSessions>['data']->['sessions'][number];--export type SandboxInstance = NonNullable<- ReturnType<typeof useInstances>['data']->['instances'][number];--/** A new environment as `createEnvironment` returns it: with its default instance. */-export type CreatedEnvironment = Awaited<- ReturnType<typeof sandboxStorageService.createEnvironment>->;+/** A new environment as `createEnvironment` returns it: the definition alone. */+export type CreatedEnvironment = Awaited<ReturnType<typeof environmentService.createEnvironment>>;export type SandboxEnvironment = NonNullable<ReturnType<typeof useEnvironments>['data']@@ -303,7 +43,6 @@ export type SandboxEnvironment = NonNullable<*/export const useEnvironmentActions = () => {const { mutate: globalMutate } = useSWRConfig();- const { mutate: refreshInstances, refreshRows } = useInstances();// Every pool and every workspace, not the one this caller happens to be// looking at: publishing an environment takes it out of one tab and puts it@@ -314,140 +53,37 @@ export const useEnvironmentActions = () => {globalMutate((key) => Array.isArray(key) && key[0] === ENVIRONMENTS_KEY);return {- copyInstance: async (params: { id: string; name: string; workingDirectory: string }) => {- await sandboxStorageService.copyInstance(params);- await refreshInstances();- },-createEnvironment: async (params: {- configuration?: SandboxEnvironmentSpecification;+ configuration?: NewEnvironmentSpecification;description?: string;name: string;visibility?: EnvironmentVisibility;}) => {- // Returned, not discarded: it carries the default instance the server- // made alongside the environment, and the caller starts its build.- const created = await sandboxStorageService.createEnvironment(params);- // The rows too: the default instance arrived with the environment, and- // the panel that opens next should show it rather than an empty list.- await Promise.all([refreshEnvironments(), refreshRows()]);+ // Returned, not discarded: the caller opens the environment it made.+ // Nothing is built โ a conversation applies it to its working directory.+ const created = await environmentService.createEnvironment(params);+ await refreshEnvironments();return created;},- /**- * Materialize an instance. Fired after the insert rather than inside it โ- * starting a build cold-starts a sandbox, and the dialog must not wait.- *- * Swallows its failure on purpose: the server has already written the- * reason onto the row, and the list is where a person looks for it. A- * toast over a dialog that is already closing would say the same thing- * somewhere it cannot be read twice.- */- buildInstance: async (id: string) => {- setBuildStarting(id, true);- try {- await sandboxStorageService.startInstanceBuild({ id });- } catch {- /* recorded on the instance; the list shows it */- }- try {- await refreshInstances();- } finally {- // After the refresh, so the row goes from "starting" straight to the- // build it now has an id for, without a beat of "not built" between.- setBuildStarting(id, false);- }- },-- /**- * Build an instance someone asked to build from its row โ a first build- * for one made before instances built themselves, or a rebuild.- *- * Unlike {@link buildInstance} this rethrows: the person is looking at the- * row and just confirmed, and a refusal such as "a conversation is using- * it" leaves the row unchanged, so the error is the only place it shows.- */- rebuildInstance: async (id: string) => {- await settleThenRefresh(- () => sandboxStorageService.startInstanceBuild({ id }),- refreshInstances,- );- },-- createInstance: async (params: {- environmentId: string;- name: string;- workingDirectory: string;- }) => {- const created = await sandboxStorageService.createInstance(params);- await refreshInstances();- return {- // No build has been asked for yet โ `buildInstance` is the next call- // โ so the row starts where the server starts it.- buildError: null,- buildId: null,- // Settled by the build that follows; until then nothing on the row- // offers one, since `buildId` is what the row waits on.- buildable: false,- createdAt: created.createdAt,- environmentId: created.environmentId,- id: created.id,- // A folder that did not exist a moment ago is held by nobody, and has- // nothing in it to report a size for.- inUse: false,- inUseByThisTopic: false,- // A copy added beside the default โ an environment's first instance- // arrives with `createEnvironment`. The refreshed list is authoritative.- isDefault: false,- name: created.name,- snapshot: null,- status: 'pending',- workingDirectory: created.workingDirectory,- } satisfies SandboxInstance;- },-setEnvironmentVisibility: async (params: { id: string; visibility: EnvironmentVisibility }) => {- await sandboxStorageService.setEnvironmentVisibility(params);+ await environmentService.setEnvironmentVisibility(params);await refreshEnvironments();},removeEnvironment: async (id: string) => {- await sandboxStorageService.removeEnvironment({ id });+ await environmentService.removeEnvironment({ id });await refreshEnvironments();},- removeInstance: async (id: string) => {- await sandboxStorageService.removeInstance({ id });- await refreshInstances();- },-- /**- * End the run holding an instance. Refreshed either way: a refusal such as- * "still saving" may land after the run did end on its own, and the row's- * Running badge is what the person is looking at.- *- * The rows only: a stop changes who holds the instance, not its size, and- * the row keeps saying "Stopping" until this returns โ waiting on a- * sandbox to measure sizes kept it there long after the run had ended.- */- stopInstance: async (id: string) =>- settleThenRefresh(() => sandboxStorageService.stopInstance({ id }), refreshRows),-- renameInstance: async (params: { id: string; name: string }) => {- await sandboxStorageService.renameInstance(params);- await refreshInstances();- },-updateEnvironment: async (params: {configuration?: SandboxEnvironmentSpecification;description?: string;id: string;name?: string;}) => {- await sandboxStorageService.updateEnvironment(params);- // Existing instances are untouched by a specification edit, so only the- // environment list has anything new to show.+ await environmentService.updateEnvironment(params);await refreshEnvironments();},};diff --git a/src/features/EnvironmentManager/useGithubRepositories.test.ts b/src/features/EnvironmentManager/useGithubRepositories.test.tsindex 3f3364432d8..38c447b2ba1 100644--- a/src/features/EnvironmentManager/useGithubRepositories.test.ts+++ b/src/features/EnvironmentManager/useGithubRepositories.test.ts@@ -3,7 +3,7 @@ import { createElement, type PropsWithChildren } from 'react';import { SWRConfig } from 'swr';import { afterEach, describe, expect, it, vi } from 'vitest';-import { sandboxStorageService } from '@/services/sandboxStorage';+import { environmentService } from '@/services/environment';import { useGithubRepositories } from './useGithubRepositories';@@ -26,7 +26,7 @@ afterEach(() => vi.restoreAllMocks());describe('GitHub repository loading', () => {it('reports a rejected request as an error and retries the real SWR fetcher', async () => {const fetcher = vi- .spyOn(sandboxStorageService, 'listGithubRepositories')+ .spyOn(environmentService, 'listGithubRepositories').mockRejectedValueOnce(new Error('HTTP 503')).mockResolvedValue({ connected: true, repositories: [] });const { result } = setup();@@ -41,7 +41,7 @@ describe('GitHub repository loading', () => {it('keeps previous repositories when retry fails and recovers without losing them', async () => {const repositories = [{ owner: 'qa', name: 'repo', defaultBranch: 'main', isPrivate: false }];const fetcher = vi- .spyOn(sandboxStorageService, 'listGithubRepositories')+ .spyOn(environmentService, 'listGithubRepositories').mockResolvedValueOnce({ connected: true, repositories }).mockRejectedValueOnce(new Error('HTTP 503')).mockResolvedValue({ connected: true, repositories });@@ -60,7 +60,7 @@ describe('GitHub repository loading', () => {});it('does not call a pending request empty', () => {- vi.spyOn(sandboxStorageService, 'listGithubRepositories').mockReturnValue(+ vi.spyOn(environmentService, 'listGithubRepositories').mockReturnValue(new Promise(() => {}),);const { result } = setup();@@ -68,7 +68,7 @@ describe('GitHub repository loading', () => {});it('keeps unavailable authorization distinct from a successful empty list', async () => {- vi.spyOn(sandboxStorageService, 'listGithubRepositories').mockResolvedValue({+ vi.spyOn(environmentService, 'listGithubRepositories').mockResolvedValue({connected: false,repositories: [],});diff --git a/src/features/EnvironmentManager/useGithubRepositories.ts b/src/features/EnvironmentManager/useGithubRepositories.tsindex 0bfe5a6502a..aa28fb95e3b 100644--- a/src/features/EnvironmentManager/useGithubRepositories.ts+++ b/src/features/EnvironmentManager/useGithubRepositories.ts@@ -1,11 +1,11 @@import useSWR from 'swr';-import { sandboxStorageService } from '@/services/sandboxStorage';+import { environmentService } from '@/services/environment';/** Keeps request failure distinct from a successful empty repository listing. */export const useGithubRepositories = () => {const swr = useSWR('sandbox-github-repositories', () =>- sandboxStorageService.listGithubRepositories(),+ environmentService.listGithubRepositories(),);const state = swr.error? 'error'diff --git a/src/features/EnvironmentManager/useInstanceBuild.test.ts b/src/features/EnvironmentManager/useInstanceBuild.test.tsdeleted file mode 100644index c6ce4869939..00000000000--- a/src/features/EnvironmentManager/useInstanceBuild.test.ts+++ /dev/null@@ -1,102 +0,0 @@-import { act, renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { useInstanceBuild } from './useEnvironmentData';--interface Options {- onSuccess?: (data: { chunk: string; logOffset: number; state: string }) => void;-}--const swrState = vi.hoisted(() => ({- data: undefined as unknown,- options: [] as any[],-}));--vi.mock('@/libs/swr', () => ({- useClientDataSWR: (_key: unknown, _fetcher: unknown, options?: Options) => {- if (options) swrState.options.push(options);- return { data: swrState.data, error: undefined, isLoading: false, mutate: vi.fn() };- },-}));--vi.mock('@/services/sandboxStorage', () => ({- sandboxStorageService: { instanceBuildStatus: vi.fn(), listInstances: vi.fn() },-}));--/** The most recent `onSuccess` SWR was handed โ this hook's whole update path. */-const poll = (data: { chunk: string; logOffset: number; state?: string }) =>- act(() => {- swrState.options.at(-1)?.onSuccess?.({ state: 'running', ...data });- });--describe('useInstanceBuild', () => {- beforeEach(() => {- swrState.data = undefined;- swrState.options = [];- });-- it('keeps the log when the row unmounts and comes back', () => {- // Leaving the settings tab and returning used to show a build with no log- // and no way to open one, until a poll had refetched the whole thing from- // the start โ the log was on the server all along, the UI had forgotten it.- const first = renderHook(() => useInstanceBuild('inst-a', true, 'build-1'));- poll({ chunk: 'cloning...\n', logOffset: 12 });- expect(first.result.current.log).toBe('cloning...\n');-- first.unmount();- const second = renderHook(() => useInstanceBuild('inst-a', true, 'build-1'));-- expect(second.result.current.log).toBe('cloning...\n');- });-- it('resumes from where it left off rather than refetching the whole log', () => {- const first = renderHook(() => useInstanceBuild('inst-b', true, 'build-2'));- poll({ chunk: 'installing...\n', logOffset: 40 });- first.unmount();-- renderHook(() => useInstanceBuild('inst-b', true, 'build-2'));- poll({ chunk: 'done\n', logOffset: 45 });-- expect(swrState.options.at(-1)).toBeDefined();- const { result } = renderHook(() => useInstanceBuild('inst-b', true, 'build-2'));- expect(result.current.log).toBe('installing...\ndone\n');- });-- it('does not let a rebuild inherit the previous build log', () => {- const first = renderHook(() => useInstanceBuild('inst-c', true, 'build-3'));- poll({ chunk: 'first build\n', logOffset: 12 });- first.unmount();-- const { result } = renderHook(() => useInstanceBuild('inst-c', true, 'build-4'));-- expect(result.current.log).toBe('');- });-- it('drops what it held once the build ends, where the row takes over', () => {- // A finished build's log is no longer the runtime's to serve, and the row- // carries its own record of a failure. Keeping it here would only grow.- const first = renderHook(() => useInstanceBuild('inst-d', true, 'build-5'));- poll({ chunk: 'boom\n', logOffset: 5 });- poll({ chunk: '', logOffset: 5, state: 'failed' });- first.unmount();-- const { result } = renderHook(() => useInstanceBuild('inst-d', true, 'build-5'));-- expect(result.current.log).toBe('');- });-- it('switches to another build while staying mounted', () => {- // The row is not remounted between a build ending and the next starting,- // so the swap has to happen on the id changing.- const { rerender, result } = renderHook(- ({ buildId }: { buildId: string }) => useInstanceBuild('inst-e', true, buildId),- { initialProps: { buildId: 'build-6' } },- );- poll({ chunk: 'old\n', logOffset: 4 });- expect(result.current.log).toBe('old\n');-- rerender({ buildId: 'build-7' });-- expect(result.current.log).toBe('');- });-});diff --git a/src/features/SandboxDrive/DriveExplorer.tsx b/src/features/SandboxDrive/DriveExplorer.tsxnew file mode 100644index 00000000000..da3ba3138ed--- /dev/null+++ b/src/features/SandboxDrive/DriveExplorer.tsx@@ -0,0 +1,439 @@+'use client';++import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import {+ ActionIcon,+ Button,+ confirmModal,+ DropdownMenu,+ Flexbox,+ Icon,+ Text,+ toast,+ Tooltip,+} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ FolderPlusIcon,+ HardDriveIcon,+ LockIcon,+ MoreHorizontalIcon,+ PencilIcon,+ RefreshCwIcon,+ Trash2Icon,+ UsersIcon,+} from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import FileIcon from '@/components/FileIcon';+import { describeError } from '@/features/EnvironmentManager/errorMessage';+import {+ DriveBreadcrumb,+ driveParentPath,+ joinDrivePath,+ NewFolderInput,+ openRenameFolderModal,+} from '@/features/WorkingDirectory';+import { sandboxStorageService } from '@/services/sandboxStorage';++import {+ entryKind,+ entryModified,+ entryModifiedRelative,+ entrySize,+ sortDriveEntries,+} from './entryColumns';+import { useDriveFiles, useRefreshDrive } from './useDriveData';++/**+ * The columns after the name โ size, kind, then date modified โ fixed so+ * every row lines up under the header, the shape of a desktop file manager's+ * list view, and set apart by a wider gap than the icon and name so each+ * reads as its own column. The date is absolute and never wraps; its relative+ * form is the tooltip.+ */+const COLUMN_GAP = 24;+const MODIFIED_WIDTH = 136;+const SIZE_WIDTH = 80;+const KIND_WIDTH = 120;+const ACTIONS_WIDTH = 28;++const styles = stylex.create({+ clickable: {+ cursor: 'pointer',+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },+ outlineOffset: { 'default': null, ':focus-visible': -2 },+ },+ entryIcon: {+ color: cssVar.colorTextSecondary,+ flex: 'none',+ },+ columnLabel: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ whiteSpace: 'nowrap',+ },+ frame: {+ backgroundColor: cssVar.colorBgContainer,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ overflow: 'hidden',+ },+ list: {+ maxHeight: 'min(560px, 60vh)',+ minHeight: 240,+ overflowY: 'auto',+ padding: 4,+ },+ header: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ paddingBlock: 6,+ paddingInline: 16,+ },+ muted: {+ color: cssVar.colorTextTertiary,+ },+ nowrap: {+ whiteSpace: 'nowrap',+ },+ row: {+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },+ borderRadius: cssVar.borderRadius,+ minHeight: 40,+ paddingBlock: 4,+ paddingInline: 12,+ },+ toolbar: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ minHeight: 48,+ paddingBlock: 8,+ paddingInline: 12,+ },+});++interface DriveExplorerProps {+ drive: SandboxDrive;+ /** In a workspace, where the drives are the public one and the member's own. */+ isWorkspace: boolean;+ /** Before the toolbar's actions โ a personal account's usage, which is this drive's alone. */+ toolbarExtra?: ReactNode;+}++/**+ * One drive, browsed like a desktop file manager's list view: a header, then+ * each folder and file with its icon, when it changed, its size and its kind;+ * a new folder, rename and delete.+ *+ * Every folder is an ordinary one. A folder a code environment initialized is+ * a checkout like any other โ environments are one-time initializers โ so+ * the only thing said about it is that it is a git repository.+ */+const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtra }) => {+ const { t } = useTranslation(['setting', 'device', 'common']);+ const [path, setPath] = useState('');+ const [creating, setCreating] = useState(false);+ const files = useDriveFiles(drive, path);+ const refreshDrive = useRefreshDrive();++ const tSetting = (key: string, options?: Record<string, unknown>) =>+ (t as (key: string, options?: Record<string, unknown>) => string)(key, {+ ...options,+ ns: 'setting',+ });++ const entries = sortDriveEntries(files.data?.entries ?? []);++ const failed = (error: unknown, fallback: string) =>+ toast.error(describeError(error, tSetting, fallback));++ const rename = (entry: { name: string; path: string }) =>+ openRenameFolderModal({+ currentName: entry.name,+ onSubmit: async (name) => {+ try {+ await sandboxStorageService.renameFile({+ drive,+ newPath: joinDrivePath(driveParentPath(entry.path) ?? '', name),+ path: entry.path,+ });+ await refreshDrive();+ } catch (error) {+ return describeError(+ error,+ tSetting,+ t('workingDirectory.drive.renameFailed', { ns: 'device' }),+ );+ }+ },+ });++ const remove = (entry: { isDirectory: boolean; name: string; path: string }) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t(+ entry.isDirectory+ ? 'drive.explorer.deleteFolderContent'+ : 'drive.explorer.deleteFileContent',+ ),+ okButtonProps: { danger: true },+ okText: t('drive.explorer.delete'),+ onOk: async () => {+ try {+ await sandboxStorageService.removeFile({+ drive,+ path: entry.path,+ recursive: entry.isDirectory,+ });+ await refreshDrive();+ } catch (error) {+ failed(error, t('workingDirectory.drive.actionFailed', { ns: 'device' }));+ }+ },+ title: t('drive.explorer.deleteTitle', { name: entry.name }),+ });++ const scope = drive === 'public' && isWorkspace ? 'public' : 'personal';++ const menuFor = (entry: { isDirectory: boolean; name: string; path: string }) => (+ <span+ role={'none'}+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ ...(entry.isDirectory+ ? [+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'rename',+ label: t('drive.explorer.rename'),+ onClick: () => rename(entry),+ },+ ]+ : []),+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'delete',+ label: t('drive.explorer.delete'),+ onClick: () => remove(entry),+ },+ ]}+ >+ <ActionIcon+ aria-label={t('drive.explorer.moreActions')}+ icon={MoreHorizontalIcon}+ size={'small'}+ />+ </DropdownMenu>+ </span>+ );++ return (+ <Flexbox className={stylex.props(styles.frame).className}>+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.toolbar).className}+ gap={12}+ >+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }} wrap={'wrap'}>+ <DriveBreadcrumb+ icon={HardDriveIcon}+ path={path}+ rootLabel={t(`drive.tabs.${drive}`)}+ onNavigate={setPath}+ />+ {/* Who else sees what is here: the one fact that tells the two drives apart. */}+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon+ className={stylex.props(styles.muted).className}+ icon={scope === 'public' ? UsersIcon : LockIcon}+ size={12}+ />+ <Text fontSize={12} type={'secondary'}>+ {t(`drive.scope.${scope}`)}+ </Text>+ </Flexbox>+ </Flexbox>+ {toolbarExtra}+ <ActionIcon+ icon={RefreshCwIcon}+ loading={files.isValidating && !files.isLoading}+ size={'small'}+ title={t('workingDirectory.refreshFolders', { ns: 'device' })}+ onClick={() => void refreshDrive()}+ />+ <Button+ disabled={!!files.error}+ icon={<Icon icon={FolderPlusIcon} />}+ type={'primary'}+ onClick={() => setCreating(true)}+ >+ {t('drive.explorer.newFolder')}+ </Button>+ </Flexbox>++ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.header).className}+ gap={10}+ >+ <Text+ className={stylex.props(styles.columnLabel).className}+ style={{ flex: 1, paddingInlineStart: 26 }}+ >+ {t('drive.explorer.columns.name')}+ </Text>+ <Flexbox horizontal align={'center'} flex={'none'} gap={COLUMN_GAP}>+ <Text+ className={stylex.props(styles.columnLabel).className}+ style={{ flex: 'none', textAlign: 'end', width: SIZE_WIDTH }}+ >+ {t('drive.explorer.columns.size')}+ </Text>+ <Text+ className={stylex.props(styles.columnLabel).className}+ style={{ flex: 'none', width: KIND_WIDTH }}+ >+ {t('drive.explorer.columns.kind')}+ </Text>+ <Text+ className={stylex.props(styles.columnLabel).className}+ style={{ flex: 'none', width: MODIFIED_WIDTH }}+ >+ {t('drive.explorer.columns.modified')}+ </Text>+ </Flexbox>+ <span style={{ flex: 'none', width: ACTIONS_WIDTH }} />+ </Flexbox>++ <Flexbox className={stylex.props(styles.list).className} gap={2}>+ {creating && (+ <Flexbox paddingInline={6}>+ <NewFolderInput+ parentPath={path}+ source={{+ createFolder: async (parentPath, name) => {+ const created = joinDrivePath(parentPath, name);+ await sandboxStorageService.createDirectory({ drive, path: created });+ return { path: created };+ },+ }}+ onCancel={() => setCreating(false)}+ onCreated={() => {+ setCreating(false);+ void refreshDrive();+ }}+ />+ </Flexbox>+ )}++ {files.isLoading ? (+ <Flexbox align={'center'} flex={1} justify={'center'} padding={24}>+ <Text type={'secondary'}>{t('workingDirectory.foldersLoading', { ns: 'device' })}</Text>+ </Flexbox>+ ) : files.error ? (+ <Flexbox align={'center'} flex={1} gap={12} justify={'center'} padding={24}>+ <Text type={'secondary'}>{t('drive.explorer.loadFailed')}</Text>+ <Button onClick={() => void files.mutate()}>{t('retry', { ns: 'common' })}</Button>+ </Flexbox>+ ) : entries.length === 0 && !creating ? (+ <Flexbox align={'center'} flex={1} gap={12} justify={'center'} padding={24}>+ <Text type={'secondary'}>+ {t(path ? 'drive.explorer.empty' : `drive.explorer.emptyRoot.${scope}`)}+ </Text>+ <Button icon={<Icon icon={FolderPlusIcon} />} onClick={() => setCreating(true)}>+ {t('drive.explorer.newFolder')}+ </Button>+ </Flexbox>+ ) : (+ entries.map((entry) => {+ const open = entry.isDirectory ? () => setPath(entry.path) : undefined;++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.row, open && styles.clickable).className}+ data-testid={'drive-entry'}+ gap={10}+ key={entry.path}+ role={open ? 'button' : undefined}+ tabIndex={open ? 0 : undefined}+ onClick={open}+ onKeyDown={+ open+ ? (event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ open();+ }+ }+ : undefined+ }+ >+ <span {...stylex.props(styles.entryIcon)}>+ <FileIcon+ fileName={entry.isGitRepository ? '.git' : entry.name}+ isDirectory={entry.isDirectory}+ size={16}+ />+ </span>+ <Text ellipsis fontSize={13} style={{ flex: 1, minWidth: 0 }}>+ {entry.name}+ </Text>+ <Flexbox horizontal align={'center'} flex={'none'} gap={COLUMN_GAP}>+ <Text+ className={stylex.props(styles.nowrap).className}+ fontSize={12}+ style={{ flex: 'none', textAlign: 'end', width: SIZE_WIDTH }}+ type={'secondary'}+ >+ {entrySize(entry)}+ </Text>+ <Text+ ellipsis+ fontSize={12}+ style={{ flex: 'none', width: KIND_WIDTH }}+ type={'secondary'}+ >+ {entryKind(entry, tSetting)}+ </Text>+ <Tooltip title={entryModifiedRelative(entry)}>+ <Text+ className={stylex.props(styles.nowrap).className}+ fontSize={12}+ style={{ flex: 'none', width: MODIFIED_WIDTH }}+ type={'secondary'}+ >+ {entryModified(entry)}+ </Text>+ </Tooltip>+ </Flexbox>+ <Flexbox flex={'none'} style={{ width: ACTIONS_WIDTH }}>+ {menuFor(entry)}+ </Flexbox>+ </Flexbox>+ );+ })+ )}+ </Flexbox>+ </Flexbox>+ );+});++DriveExplorer.displayName = 'DriveExplorer';++export default DriveExplorer;diff --git a/src/features/SandboxDrive/DriveUsage.tsx b/src/features/SandboxDrive/DriveUsage.tsxnew file mode 100644index 00000000000..27168727774--- /dev/null+++ b/src/features/SandboxDrive/DriveUsage.tsx@@ -0,0 +1,141 @@+'use client';++import { Flexbox, Icon, Popover, Skeleton, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDownIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { formatSize } from '@/utils/format';++import { UsageBreakdown } from './UsageBreakdown';+import { useDriveUsage } from './useDriveData';++export { UsageBreakdown as DriveUsageBreakdown } from './UsageBreakdown';++const styles = stylex.create({+ chevron: {+ color: cssVar.colorTextTertiary,+ },+ // A track that reads as one even when nearly empty, and a fill that never+ // shrinks below a sliver โ "almost nothing used" still shows as a start.+ meter: {+ backgroundColor: cssVar.colorFillSecondary,+ borderRadius: 2,+ display: 'inline-flex',+ flex: 'none',+ height: 4,+ overflow: 'hidden',+ width: 72,+ },+ meterFill: {+ backgroundColor: cssVar.colorPrimary,+ borderRadius: 2,+ height: '100%',+ minWidth: 4,+ },+ meterFillBilled: {+ backgroundColor: cssVar.colorWarning,+ },+ meterFillOver: {+ backgroundColor: cssVar.colorError,+ },+ meterWidth: (width: string) => ({ width }),+ trigger: {+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ borderRadius: cssVar.borderRadius,+ borderStyle: 'none',+ cursor: 'pointer',+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },+ paddingBlock: 4,+ paddingInline: 8,+ },+});++const percentOf = (bytes: number | null | undefined, quota: number) =>+ quota > 0 && bytes ? Math.min(100, (bytes / quota) * 100) : 0;++/**+ * How full the plan's storage is, as one compact meter in the page header.+ *+ * The storage page is for the folders on a drive; how much they hold is+ * second to that, so the figure takes a line's worth of room and the+ * breakdown โ each drive, each member's for an admin, departed members'+ * drives โ opens from it on demand. Over a quota the plan cannot bill past it+ * turns red, because then the next write is refused and the figure stops+ * being secondary; billed overage reads as a warning instead.+ *+ * Read from what was last measured; measuring walks the volume, so it waits+ * for the refresh in the breakdown.+ */+const DriveUsage = memo(() => {+ const { t } = useTranslation('setting');+ const { data, error, isLoading, refresh } = useDriveUsage();++ if (error) return null;+ if (isLoading || !data) return <Skeleton.Text rows={1} width={160} />;++ const { quotaBytes, totalUsageBytes } = data;+ const isWorkspace = (data.drives ?? []).length > 1;+ const over = totalUsageBytes !== null && totalUsageBytes > quotaBytes;+ const refused = over && !data.overageAllowed;++ return (+ <Popover+ content={<UsageBreakdown inPopover data={data} onRefresh={refresh} />}+ placement={'bottomRight'}+ trigger={'click'}+ >+ <Flexbox+ horizontal+ align={'center'}+ aria-label={t(isWorkspace ? 'drive.usage.poolTitle' : 'drive.usage.title')}+ as={'button'}+ className={stylex.props(styles.trigger).className}+ gap={8}+ >+ <span {...stylex.props(styles.meter)}>+ <span+ {...stylex.props(+ styles.meterFill,+ over && (refused ? styles.meterFillOver : styles.meterFillBilled),+ styles.meterWidth(`${percentOf(totalUsageBytes, quotaBytes)}%`),+ )}+ />+ </span>+ <Text+ fontSize={12}+ style={{ whiteSpace: 'nowrap' }}+ type={refused ? 'danger' : over ? 'warning' : 'secondary'}+ >+ {totalUsageBytes === null+ ? t('drive.usage.unmeasured', { total: formatSize(quotaBytes) })+ : t('drive.usage.used', {+ total: formatSize(quotaBytes),+ used: formatSize(totalUsageBytes),+ })}+ </Text>+ <Icon className={stylex.props(styles.chevron).className} icon={ChevronDownIcon} size={12} />+ </Flexbox>+ </Popover>+ );+});++DriveUsage.displayName = 'DriveUsage';++export default DriveUsage;++/**+ * The breakdown on its own, for a page that shows usage as a section of its+ * own โ the billing usage page โ rather than as a meter beside something else.+ * Nothing while loading or when there is no drive to break down.+ */+export const DriveUsageCard = memo(() => {+ const { data, error, refresh } = useDriveUsage();+ if (error || !data) return null;++ return <UsageBreakdown data={data} onRefresh={refresh} />;+});++DriveUsageCard.displayName = 'DriveUsageCard';diff --git a/src/features/SandboxDrive/UsageBreakdown.test.tsx b/src/features/SandboxDrive/UsageBreakdown.test.tsxnew file mode 100644index 00000000000..3c19ef73759--- /dev/null+++ b/src/features/SandboxDrive/UsageBreakdown.test.tsx@@ -0,0 +1,33 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { UsageBreakdown } from './UsageBreakdown';++vi.mock('@/business/client/features/RetainedMemberDrives', () => ({ default: () => null }));++const overQuota = (overageAllowed: boolean) =>+ ({+ drives: [{ drive: 'personal', usageBytes: 200, usageCheckedAt: null }],+ members: [],+ overageAllowed,+ quotaBytes: 100,+ totalUsageBytes: 200,+ }) as any;++describe('UsageBreakdown', () => {+ it('should say saves are refused over a quota the plan does not bill past', () => {+ render(<UsageBreakdown data={overQuota(false)} onRefresh={vi.fn()} />);++ expect(screen.getByText('drive.usage.over')).toBeInTheDocument();+ expect(screen.queryByText('drive.usage.overBilled')).not.toBeInTheDocument();+ });++ it('should say the overage is billed when the plan allows it', () => {+ // Pay-as-you-go keeps writes going; "free up space before saving" would+ // be untrue there.+ render(<UsageBreakdown data={overQuota(true)} onRefresh={vi.fn()} />);++ expect(screen.getByText('drive.usage.overBilled')).toBeInTheDocument();+ expect(screen.queryByText('drive.usage.over')).not.toBeInTheDocument();+ });+});diff --git a/src/features/SandboxDrive/UsageBreakdown.tsx b/src/features/SandboxDrive/UsageBreakdown.tsxnew file mode 100644index 00000000000..f1952d4f792--- /dev/null+++ b/src/features/SandboxDrive/UsageBreakdown.tsx@@ -0,0 +1,388 @@+'use client';++import { ActionIcon, Avatar, Button, Flexbox, Icon, Text, toast, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { LucideIcon } from 'lucide-react';+import { LockIcon, RefreshCwIcon, UserRoundIcon, UsersIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import RetainedMemberDrives from '@/business/client/features/RetainedMemberDrives';+import SandboxStorageOverQuotaAction from '@/business/client/features/SandboxStorageOverQuotaAction';+import { formatSize } from '@/utils/format';++import type { useDriveUsage } from './useDriveData';++type DriveUsageData = NonNullable<ReturnType<typeof useDriveUsage>['data']>;++/** How many members the ranking shows before it folds the rest away. */+const MEMBERS_FOLDED = 5;++const styles = stylex.create({+ // One bar for the whole quota; each drive is a segment of it. The 2px gap in+ // the surface colour is what separates segments โ never a stroke.+ bar: {+ backgroundColor: cssVar.colorFillTertiary,+ borderRadius: 4,+ display: 'flex',+ gap: 2,+ height: 8,+ width: '100%',+ },+ dot: {+ borderRadius: '50%',+ flex: 'none',+ height: 8,+ width: 8,+ },+ legendIcon: {+ color: cssVar.colorTextTertiary,+ },+ memberBar: {+ backgroundColor: cssVar.colorFillSecondary,+ borderRadius: 2,+ flex: 'none',+ height: 4,+ overflow: 'hidden',+ width: 96,+ },+ memberFill: {+ backgroundColor: cssVar.colorTextSecondary,+ borderRadius: 2,+ display: 'block',+ height: '100%',+ },+ memberSize: {+ flex: 'none',+ textAlign: 'end',+ width: 72,+ },+ popover: {+ maxWidth: 'min(380px, 80vw)',+ minWidth: 300,+ },+ row: {+ minHeight: 32,+ },+ segment: {+ borderEndEndRadius: { 'default': null, ':last-child': 4 },+ borderEndStartRadius: { 'default': null, ':first-child': 4 },+ borderStartEndRadius: { 'default': null, ':last-child': 4 },+ borderStartStartRadius: { 'default': null, ':first-child': 4 },+ flex: 'none',+ height: '100%',+ minWidth: 4,+ },+ shrinkable: {+ minWidth: 0,+ },+ width: (width: string) => ({ width }),+});++/**+ * Each segment's colour. Two hues carry the caller's drives (validated for+ * colour-blind separation); other members are the de-emphasised grey; over+ * the quota everything is the danger colour.+ */+const tones = stylex.create({+ others: { backgroundColor: cssVar.colorTextQuaternary },+ over: { backgroundColor: cssVar.colorError },+ personal: { backgroundColor: cssVar.purple },+ public: { backgroundColor: cssVar.geekblue },+});++interface Segment {+ bytes: number;+ icon: LucideIcon;+ key: 'others' | 'personal' | 'public';+ label: string;+}++const percent = (part: number, whole: number) =>+ whole > 0 ? Math.min(100, (part / whole) * 100) : 0;++/** Whole percents, but never "0%" for something that is there. */+const formatPercent = (value: number) =>+ value > 0 && value < 1 ? '<1' : String(Math.round(value));++/**+ * Where a drive pool goes, laid out the way consumer drives do it (Google+ * Drive, iCloud, Dropbox): the amount used as the figure you read first, the+ * room left beside it, one bar split by what fills it, a legend that names+ * every segment with its size, then โ for an owner or admin โ the members,+ * largest first.+ *+ * The segments are the caller's two drives and "other members", the rest of+ * the pool. Two hues carry the drives (validated for colour-blind separation;+ * the legend icons and values carry identity as well, never colour alone);+ * other members are the de-emphasised grey, because the caller acts on their+ * own drives and only reads the rest. Over a quota the plan does not bill past,+ * every segment turns to the danger colour, because then the bar's message is+ * "writes are refused", not "this is how it splits"; with pay-as-you-go the+ * split stays and the figures say it is being billed.+ */+export const UsageBreakdown = memo<{+ data: DriveUsageData;+ /** In a popover: a smaller figure and bounded width. Embedded: the page's width. */+ inPopover?: boolean;+ onRefresh: () => Promise<void>;+}>(({ data, inPopover, onRefresh }) => {+ const { t } = useTranslation('setting');+ const [refreshing, setRefreshing] = useState(false);+ const [showAllMembers, setShowAllMembers] = useState(false);++ const drives = data.drives ?? [];+ const members = [...(data.members ?? [])].sort(+ (a, b) => (b.usageBytes ?? -1) - (a.usageBytes ?? -1),+ );+ const isWorkspace = drives.length > 1;+ const { quotaBytes } = data;++ const bytesOf = (drive: 'public' | 'personal') =>+ drives.find((entry) => entry.drive === drive)?.usageBytes ?? 0;+ const publicBytes = isWorkspace ? bytesOf('public') : 0;+ const personalBytes = bytesOf('personal');+ const known = publicBytes + personalBytes;+ const total = data.totalUsageBytes ?? (drives.some((d) => d.usageBytes !== null) ? known : null);+ // The pool total is the execution plane's own figure; whatever it holds+ // beyond the caller's drives is other members'.+ const othersBytes = isWorkspace && total !== null ? Math.max(0, total - known) : 0;+ const over = total !== null && total > quotaBytes;+ // Over the quota is only a refusal when the plan cannot bill the overage;+ // with pay-as-you-go the writes go on and the extra is charged.+ const refused = over && !data.overageAllowed;+ const scale = Math.max(quotaBytes, total ?? 0);++ const segments: Segment[] = (+ [+ isWorkspace && {+ bytes: publicBytes,+ icon: UsersIcon,+ key: 'public',+ label: t('drive.tabs.public'),+ },+ {+ bytes: personalBytes,+ icon: LockIcon,+ key: 'personal',+ label: t('drive.tabs.personal'),+ },+ isWorkspace && {+ bytes: othersBytes,+ icon: UserRoundIcon,+ key: 'others',+ label: t('drive.usage.others'),+ },+ ] as (Segment | false)[]+ ).filter((segment): segment is Segment => !!segment);++ const visibleMembers = showAllMembers ? members : members.slice(0, MEMBERS_FOLDED);+ const largestMember = Math.max(1, ...members.map((member) => member.usageBytes ?? 0));++ const refresh = async () => {+ setRefreshing(true);+ try {+ await onRefresh();+ } catch {+ toast.error(t('workingDirectory.drive.actionFailed', { ns: 'device' }));+ } finally {+ setRefreshing(false);+ }+ };++ return (+ <Flexbox className={inPopover ? stylex.props(styles.popover).className : undefined} gap={16}>+ {/* The figure first: how much is used, against how much there is. */}+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>+ <Flexbox className={stylex.props(styles.shrinkable).className} gap={4}>+ <Text fontSize={12} type={'secondary'}>+ {t(isWorkspace ? 'drive.usage.poolTitle' : 'drive.usage.title')}+ </Text>+ <Flexbox horizontal align={'baseline'} gap={6} wrap={'wrap'}>+ <Text+ fontSize={inPopover ? 20 : 24}+ type={refused ? 'danger' : over ? 'warning' : undefined}+ weight={600}+ >+ {total === null ? 'โ' : formatSize(total)}+ </Text>+ <Text fontSize={13} type={'secondary'}>+ / {formatSize(quotaBytes)}+ </Text>+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal align={'center'} flex={'none'} gap={4}>+ <Text fontSize={12} type={refused ? 'danger' : over ? 'warning' : 'secondary'}>+ {total === null+ ? t('drive.usage.unmeasuredShort')+ : over+ ? t('drive.usage.overBy', { size: formatSize(total - quotaBytes) })+ : t('drive.usage.remaining', {+ percent: formatPercent(percent(total, quotaBytes)),+ size: formatSize(quotaBytes - total),+ })}+ </Text>+ <ActionIcon+ icon={RefreshCwIcon}+ loading={refreshing}+ size={'small'}+ title={t('drive.usage.refresh')}+ onClick={refresh}+ />+ </Flexbox>+ </Flexbox>++ <div+ aria-label={t(isWorkspace ? 'drive.usage.poolTitle' : 'drive.usage.title')}+ role={'img'}+ {...stylex.props(styles.bar)}+ >+ {segments+ .filter((segment) => segment.bytes > 0)+ .map((segment) => (+ <Tooltip+ key={segment.key}+ title={`${segment.label} ยท ${formatSize(segment.bytes)} ยท ${formatPercent(+ percent(segment.bytes, quotaBytes),+ )}%`}+ >+ <span+ {...stylex.props(+ styles.segment,+ tones[refused ? 'over' : segment.key],+ styles.width(`${percent(segment.bytes, scale)}%`),+ )}+ />+ </Tooltip>+ ))}+ </div>++ {/* A legend whenever there is more than one segment: icon, name and size+ name each one, so the split never rests on colour alone. */}+ {segments.length > 1 &&+ (inPopover ? (+ // Narrow: one row per segment, sizes aligned on the right.+ <Flexbox gap={2}>+ {segments.map((segment) => (+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.row).className}+ gap={8}+ justify={'space-between'}+ key={segment.key}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <span {...stylex.props(styles.dot, tones[segment.key])} />+ <Icon+ className={stylex.props(styles.legendIcon).className}+ icon={segment.icon}+ size={13}+ />+ <Text fontSize={13}>{segment.label}</Text>+ </Flexbox>+ <Text fontSize={13} type={'secondary'}>+ {formatSize(segment.bytes)}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ ) : (+ <Flexbox horizontal style={{ columnGap: 20, rowGap: 8 }} wrap={'wrap'}>+ {segments.map((segment) => (+ <Flexbox horizontal align={'center'} gap={6} key={segment.key}>+ <span {...stylex.props(styles.dot, tones[segment.key])} />+ <Icon+ className={stylex.props(styles.legendIcon).className}+ icon={segment.icon}+ size={13}+ />+ <Text fontSize={13}>{segment.label}</Text>+ <Text fontSize={13} type={'secondary'}>+ {formatSize(segment.bytes)}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ ))}++ {members.length > 0 && (+ <Flexbox gap={4}>+ <Flexbox horizontal align={'baseline'} gap={8} justify={'space-between'}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('drive.usage.membersTitle')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('drive.usage.membersHint')}+ </Text>+ </Flexbox>+ {visibleMembers.map((member) => (+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.row).className}+ gap={12}+ key={member.userId}+ >+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.shrinkable).className}+ flex={1}+ gap={8}+ >+ <Avatar avatar={member.avatar || member.name || member.userId} size={22} />+ <Text ellipsis fontSize={13}>+ {member.name || member.userId}+ </Text>+ </Flexbox>+ {/* Relative to the largest member, so the ranking reads at a glance. */}+ <span {...stylex.props(styles.memberBar)}>+ <span+ {...stylex.props(+ styles.memberFill,+ styles.width(`${percent(member.usageBytes ?? 0, largestMember)}%`),+ )}+ />+ </span>+ <Text+ className={stylex.props(styles.memberSize).className}+ fontSize={13}+ type={'secondary'}+ >+ {member.usageBytes === null+ ? t('drive.usage.memberUnmeasured')+ : formatSize(member.usageBytes)}+ </Text>+ </Flexbox>+ ))}+ {members.length > MEMBERS_FOLDED && (+ <Button+ size={'small'}+ style={{ alignSelf: 'flex-start' }}+ type={'text'}+ onClick={() => setShowAllMembers((value) => !value)}+ >+ {showAllMembers+ ? t('drive.usage.showFewerMembers')+ : t('drive.usage.showAllMembers', { count: members.length })}+ </Button>+ )}+ </Flexbox>+ )}++ {isWorkspace && <RetainedMemberDrives />}++ {over && (+ <Text fontSize={12} type={refused ? 'danger' : 'warning'}>+ {t(refused ? 'drive.usage.over' : 'drive.usage.overBilled')}+ </Text>+ )}+ {/* While writes are refused, the way to keep saving โ not only the fact. */}+ {refused && <SandboxStorageOverQuotaAction />}+ </Flexbox>+ );+});++UsageBreakdown.displayName = 'UsageBreakdown';diff --git a/src/features/SandboxDrive/entryColumns.test.ts b/src/features/SandboxDrive/entryColumns.test.tsnew file mode 100644index 00000000000..5b11a3469bc--- /dev/null+++ b/src/features/SandboxDrive/entryColumns.test.ts@@ -0,0 +1,55 @@+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import { describe, expect, it } from 'vitest';++import { formatSize } from '@/utils/format';++import { entryKind, entryModified, entrySize, sortDriveEntries } from './entryColumns';++// Loaded app-wide in the product.+dayjs.extend(relativeTime);++const t = (key: string, options?: Record<string, unknown>) =>+ options?.extension ? `${key}:${options.extension}` : key;++describe('entryColumns', () => {+ it('lists folders first, then by name', () => {+ const sorted = sortDriveEntries([+ { isDirectory: false, name: 'b.txt' },+ { isDirectory: true, name: 'notes' },+ { isDirectory: false, name: 'a.txt' },+ { isDirectory: true, name: 'app' },+ ]);++ expect(sorted.map((entry) => entry.name)).toEqual(['app', 'notes', 'a.txt', 'b.txt']);+ });++ it('says what each entry is: git repository, folder, or file by its extension', () => {+ expect(entryKind({ isDirectory: true, isGitRepository: true, name: 'app' }, t)).toBe(+ 'drive.explorer.kind.gitRepository',+ );+ expect(entryKind({ isDirectory: true, name: 'notes' }, t)).toBe('drive.explorer.kind.folder');+ expect(entryKind({ isDirectory: false, name: 'report.pdf' }, t)).toBe(+ 'drive.explorer.kind.fileWithExtension:PDF',+ );+ expect(entryKind({ isDirectory: false, name: 'Makefile' }, t)).toBe('drive.explorer.kind.file');+ expect(entryKind({ isDirectory: false, name: '.env' }, t)).toBe('drive.explorer.kind.file');+ });++ it('gives a folder no size, and a file under a kilobyte its size in bytes, not "0.0 KB"', () => {+ expect(entrySize({ isDirectory: true, name: 'notes' })).toBe('--');+ expect(entrySize({ isDirectory: false, name: 'a.md', size: 17 })).toBe('17 B');+ expect(entrySize({ isDirectory: false, name: 'r.pdf', size: 2048 })).toBe(formatSize(2048));+ });++ it('shows the modified time absolute, even for a file changed just now', () => {+ const shown = entryModified({+ isDirectory: false,+ modifiedAt: new Date().toISOString(),+ name: 'a.md',+ });++ // Relative wording ("a few seconds ago") wrapped in the fixed column.+ expect(shown).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/);+ });+});diff --git a/src/features/SandboxDrive/entryColumns.ts b/src/features/SandboxDrive/entryColumns.tsnew file mode 100644index 00000000000..4aa7f53a315--- /dev/null+++ b/src/features/SandboxDrive/entryColumns.ts@@ -0,0 +1,53 @@+import dayjs from 'dayjs';++import { formatSize } from '@/utils/format';++/**+ * What the storage page's list shows after each name, the way a desktop file+ * manager's list view does: modified date, size, and kind.+ */+interface DriveListEntry {+ isDirectory: boolean;+ isGitRepository?: boolean;+ modifiedAt?: string;+ name: string;+ size?: number;+}++type Translate = (key: string, options?: Record<string, unknown>) => string;++/** Folders first, then by name. */+export const sortDriveEntries = <T extends DriveListEntry>(entries: readonly T[]): T[] =>+ [...entries].sort(+ (a, b) => Number(b.isDirectory) - Number(a.isDirectory) || a.name.localeCompare(b.name),+ );++/**+ * Absolute, so it fits its column on one line: a relative "a few seconds ago"+ * wrapped there. The relative form is {@link entryModifiedRelative}, the tooltip.+ */+export const entryModified = (entry: DriveListEntry) =>+ entry.modifiedAt ? dayjs(entry.modifiedAt).format('YYYY-MM-DD HH:mm') : '';++export const entryModifiedRelative = (entry: DriveListEntry) =>+ entry.modifiedAt ? dayjs(entry.modifiedAt).fromNow() : undefined;++/** `--` for a folder, and a small file in bytes rather than "0.0 KB". */+export const entrySize = (entry: DriveListEntry) => {+ if (entry.isDirectory) return '--';+ if (entry.size === undefined) return '';++ return entry.size < 1024 ? `${entry.size} B` : formatSize(entry.size);+};++/** What an entry is, the way a file manager's Kind column says it. */+export const entryKind = (entry: DriveListEntry, t: Translate) => {+ if (entry.isGitRepository) return t('drive.explorer.kind.gitRepository');+ if (entry.isDirectory) return t('drive.explorer.kind.folder');+ const dot = entry.name.lastIndexOf('.');+ const extension = dot > 0 ? entry.name.slice(dot + 1) : '';++ return extension+ ? t('drive.explorer.kind.fileWithExtension', { extension: extension.toUpperCase() })+ : t('drive.explorer.kind.file');+};diff --git a/src/features/SandboxDrive/index.test.tsx b/src/features/SandboxDrive/index.test.tsxnew file mode 100644index 00000000000..ad9371c2248--- /dev/null+++ b/src/features/SandboxDrive/index.test.tsx@@ -0,0 +1,35 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import DriveSettings from './index';++const entitlement = vi.hoisted(() => ({ value: {} as any }));++vi.mock('@/hooks/useSandboxDriveEntitlement', () => ({+ useSandboxDriveEntitlement: () => entitlement.value,+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));+vi.mock('@/business/client/features/SandboxStorageUpsell', () => ({+ SandboxStorageUpgradeGuide: () => null,+}));+vi.mock('./DriveExplorer', () => ({ default: () => null }));+vi.mock('./DriveUsage', () => ({ default: () => null }));++describe('DriveSettings', () => {+ it('should offer a retry, not an endless spinner, when the entitlement cannot be read', () => {+ const retry = vi.fn();+ entitlement.value = { entitled: undefined, error: new Error('offline'), retry };+ render(+ <MemoryRouter>+ <DriveSettings />+ </MemoryRouter>,+ );++ expect(screen.getByText('drive.loadFailed')).toBeInTheDocument();+ fireEvent.click(screen.getByText('retry'));+ expect(retry).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/SandboxDrive/index.tsx b/src/features/SandboxDrive/index.tsxnew file mode 100644index 00000000000..1ec785e7e72--- /dev/null+++ b/src/features/SandboxDrive/index.tsx@@ -0,0 +1,96 @@+'use client';++import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { Button, Center, Flexbox, Icon, Spin, Tabs, Text } from '@lobehub/ui';+import { LockIcon, UsersIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { SandboxStorageUpgradeGuide } from '@/business/client/features/SandboxStorageUpsell';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { MAX_WIDTH } from '@/const/layoutTokens';+import { useSandboxDriveEntitlement } from '@/hooks/useSandboxDriveEntitlement';++import DriveExplorer from './DriveExplorer';+import DriveUsage from './DriveUsage';+import { useDriveTab } from './useDriveTab';++/**+ * The cloud sandbox's drives: what is on them, how much they hold, and โ for+ * an account without one โ the way to a plan that has one. The one place+ * storage is set out; the environments page keeps to definitions.+ *+ * A workspace has two drives, behind tabs: the public drive every member+ * browses and works in, and the member's own personal drive, which nobody+ * else can reach. A personal account has its personal drive alone. The open+ * drive lives in `?drive=public|personal`, so it survives a reload and links.+ */+const DriveSettings = memo(() => {+ const { t } = useTranslation(['setting', 'common']);+ const workspaceId = useActiveWorkspaceId();+ const isWorkspace = !!workspaceId;+ const { entitled, error, retry } = useSandboxDriveEntitlement();+ const drives: SandboxDrive[] = isWorkspace ? ['public', 'personal'] : ['personal'];+ const [active, setActive] = useDriveTab(drives);++ // Whether the plan has a drive could not be read: say so and offer it+ // again, rather than a spinner that never resolves.+ if (entitled === undefined && error) {+ return (+ <Center gap={12} style={{ minHeight: 320 }}>+ <Text type={'secondary'}>{t('drive.loadFailed')}</Text>+ <Button onClick={retry}>{t('retry', { ns: 'common' })}</Button>+ </Center>+ );+ }++ if (entitled === undefined) {+ return (+ <Center style={{ minHeight: 320 }}>+ <Spin />+ </Center>+ );+ }++ if (!entitled) {+ return (+ <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ <SandboxStorageUpgradeGuide />+ </Flexbox>+ );+ }++ return (+ <Flexbox gap={12} style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ {/* A workspace's drives share one pool, so its meter sits beside the+ tabs that switch between them, not inside either drive. */}+ {isWorkspace && (+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'} wrap={'wrap'}>+ <Flexbox flex={'none'}>+ <Tabs+ activeKey={active}+ items={drives.map((key) => ({+ icon: <Icon icon={key === 'public' ? UsersIcon : LockIcon} />,+ key,+ label: t(`drive.tabs.${key}`),+ }))}+ onChange={(key) => setActive(key as SandboxDrive)}+ />+ </Flexbox>+ <DriveUsage />+ </Flexbox>+ )}+ {/* Keyed on the drive, so a path browsed on one never carries to the other. */}+ <DriveExplorer+ drive={active}+ isWorkspace={isWorkspace}+ key={active}+ toolbarExtra={isWorkspace ? undefined : <DriveUsage />}+ />+ </Flexbox>+ );+});++DriveSettings.displayName = 'DriveSettings';++export default DriveSettings;diff --git a/src/features/SandboxDrive/useDriveData.test.ts b/src/features/SandboxDrive/useDriveData.test.tsnew file mode 100644index 00000000000..f2188726d4e--- /dev/null+++ b/src/features/SandboxDrive/useDriveData.test.ts@@ -0,0 +1,54 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { sandboxStorageService } from '@/services/sandboxStorage';++import { useDriveUsage } from './useDriveData';++const mutate = vi.hoisted(() => vi.fn());++vi.mock('@/libs/swr', () => ({+ useClientDataSWR: () => ({+ data: { drives: [{ drive: 'public' }, { drive: 'personal' }] },+ error: undefined,+ isLoading: false,+ mutate,+ }),+}));++vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { getDriveUsage: vi.fn(), refreshStorageUsage: vi.fn() },+}));++describe('useDriveUsage refresh', () => {+ beforeEach(() => {+ mutate.mockReset().mockResolvedValue(undefined);+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockReset();+ });++ it('should measure every drive, reload, and still report a failed one', async () => {+ // One drive measured, the other not: the caller has to hear about it+ // rather than show a mixture as if both were fresh.+ vi.mocked(sandboxStorageService.refreshStorageUsage)+ .mockResolvedValueOnce({} as any)+ .mockRejectedValueOnce(new Error('sandbox unavailable'));+ const { result } = renderHook(() => useDriveUsage());+ await waitFor(() => expect(result.current.data).toBeDefined());++ await act(async () => {+ await expect(result.current.refresh()).rejects.toThrow('sandbox unavailable');+ });++ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(2);+ expect(mutate).toHaveBeenCalledTimes(1);+ });++ it('should resolve when every drive was measured', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue({} as any);+ const { result } = renderHook(() => useDriveUsage());++ await act(async () => {+ await expect(result.current.refresh()).resolves.toBeUndefined();+ });+ });+});diff --git a/src/features/SandboxDrive/useDriveData.ts b/src/features/SandboxDrive/useDriveData.tsnew file mode 100644index 00000000000..186b61344df--- /dev/null+++ b/src/features/SandboxDrive/useDriveData.ts@@ -0,0 +1,59 @@+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { useCallback } from 'react';+import { useSWRConfig } from 'swr';++import { useClientDataSWR } from '@/libs/swr';+import { sandboxStorageService } from '@/services/sandboxStorage';++const USAGE_KEY = 'sandbox-drive-usage';+const FILES_KEY = 'sandbox-drive-files';++/**+ * Every drive's usage against the pool, and each member's for an admin.+ * `useClientDataSWR` keys it by the active workspace, so switching workspaces+ * never shows the previous one's figures.+ */+export const useDriveUsage = () => {+ const swr = useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.getDriveUsage>>>(+ [USAGE_KEY],+ () => sandboxStorageService.getDriveUsage(),+ { revalidateOnFocus: false },+ );++ // Measuring walks each of the caller's own drives; the members' figures are+ // whatever was last measured for them. Every drive is measured even when one+ // fails, and the figures are reloaded either way; then a failure is thrown,+ // so the caller can say the refresh did not fully work.+ const refresh = useCallback(async () => {+ const drives = swr.data?.drives.map((entry) => entry.drive) ?? [];+ const results = await Promise.allSettled(+ drives.map((drive) => sandboxStorageService.refreshStorageUsage({ drive })),+ );+ await swr.mutate();++ const failed = results.find(+ (result): result is PromiseRejectedResult => result.status === 'rejected',+ );+ if (failed) throw failed.reason;+ }, [swr.data, swr.mutate]);++ return { data: swr.data, error: swr.error, isLoading: swr.isLoading, refresh };+};++/** One folder's entries on one drive. */+export const useDriveFiles = (drive: SandboxDrive, path: string) =>+ useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listFiles>>>(+ [FILES_KEY, drive, path],+ () => sandboxStorageService.listFiles({ drive, path: path || undefined }),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++/** Refetch every listing of every drive, and the usage, after a write. */+export const useRefreshDrive = () => {+ const { mutate } = useSWRConfig();++ return useCallback(+ () => mutate((key) => Array.isArray(key) && (key[0] === FILES_KEY || key[0] === USAGE_KEY)),+ [mutate],+ );+};diff --git a/src/features/SandboxDrive/useDriveTab.test.ts b/src/features/SandboxDrive/useDriveTab.test.tsnew file mode 100644index 00000000000..8822b58feed--- /dev/null+++ b/src/features/SandboxDrive/useDriveTab.test.ts@@ -0,0 +1,44 @@+import { act, renderHook } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { MemoryRouter, useLocation } from 'react-router';+import { describe, expect, it } from 'vitest';++import { useDriveTab } from './useDriveTab';++const renderAt = (url: string, drives: ('public' | 'personal')[]) =>+ renderHook(() => ({ location: useLocation(), tab: useDriveTab(drives) }), {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(MemoryRouter, { initialEntries: [url] }, children),+ });++describe('useDriveTab', () => {+ it('opens the drive named in ?drive', () => {+ const { result } = renderAt('/settings/drive?drive=personal', ['public', 'personal']);++ expect(result.current.tab[0]).toBe('personal');+ });++ it('falls back to the first drive offered for a missing or unknown value', () => {+ expect(renderAt('/settings/drive', ['public', 'personal']).result.current.tab[0]).toBe(+ 'public',+ );+ expect(+ renderAt('/settings/drive?drive=nope', ['public', 'personal']).result.current.tab[0],+ ).toBe('public');+ // A personal account has no public drive to land on.+ expect(renderAt('/settings/drive?drive=public', ['personal']).result.current.tab[0]).toBe(+ 'personal',+ );+ });++ it('writes the chosen drive into the URL and keeps other params', () => {+ const { result } = renderAt('/settings/drive?keep=1', ['public', 'personal']);++ act(() => result.current.tab[1]('personal'));++ const search = new URLSearchParams(result.current.location.search);+ expect(result.current.tab[0]).toBe('personal');+ expect(search.get('drive')).toBe('personal');+ expect(search.get('keep')).toBe('1');+ });+});diff --git a/src/features/SandboxDrive/useDriveTab.ts b/src/features/SandboxDrive/useDriveTab.tsnew file mode 100644index 00000000000..6100884f422--- /dev/null+++ b/src/features/SandboxDrive/useDriveTab.ts@@ -0,0 +1,29 @@+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { useCallback } from 'react';+import { useSearchParams } from 'react-router';++/**+ * The drive tab the storage page has open, kept in `?drive=public|personal` so+ * it survives a reload and can be linked. A value naming a drive the caller+ * does not have falls back to the first one offered.+ */+export const useDriveTab = (drives: SandboxDrive[]) => {+ const [params, setParams] = useSearchParams();+ const requested = params.get('drive') as SandboxDrive | null;+ const active = requested && drives.includes(requested) ? requested : drives[0];++ const setActive = useCallback(+ (drive: SandboxDrive) =>+ setParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.set('drive', drive);+ return next;+ },+ { replace: true },+ ),+ [setParams],+ );++ return [active, setActive] as const;+};diff --git a/src/features/Settings/drive/index.tsx b/src/features/Settings/drive/index.tsxnew file mode 100644index 00000000000..22831a3a2e9--- /dev/null+++ b/src/features/Settings/drive/index.tsx@@ -0,0 +1,3 @@+'use client';++export { default } from '@/features/SandboxDrive';diff --git a/src/features/Settings/environments/index.tsx b/src/features/Settings/environments/index.tsxindex fb15340a420..4072d5b85f5 100644--- a/src/features/Settings/environments/index.tsx+++ b/src/features/Settings/environments/index.tsx@@ -5,19 +5,20 @@ import { memo } from 'react';import { MAX_WIDTH } from '@/const/layoutTokens';import EnvironmentManager from '@/features/EnvironmentManager';-import EnvironmentsGate from '@/features/EnvironmentManager/EnvironmentsGate';/*** Thin: the titled group, the list and the detail panel all live in the manager,* the way the devices page composes its own. The group repeats the page's name* on purpose, for the same reason "My Devices" appears twice there โ the header* bar scrolls away, the section heading does not.+ *+ * 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%' }}>- <EnvironmentsGate>- <EnvironmentManager />- </EnvironmentsGate>+ <EnvironmentManager /></Flexbox>));diff --git a/src/features/Settings/features/SettingsContent.tsx b/src/features/Settings/features/SettingsContent.tsxindex 94123006364..3e5f721ff08 100644--- a/src/features/Settings/features/SettingsContent.tsx+++ b/src/features/Settings/features/SettingsContent.tsx@@ -37,6 +37,7 @@ const COMPACT_HEADER_TABS = [SettingsTabs.Plans,SettingsTabs.Profile,SettingsTabs.Referral,+ SettingsTabs.Drive,SettingsTabs.Environments,SettingsTabs.ServiceModel,SettingsTabs.Stats,@@ -70,6 +71,7 @@ const SettingsContent = ({ mobile, activeTab }: SettingsContentProps) => {[SettingsTabs.Plans]: t('subscription:tab.plans'),[SettingsTabs.Profile]: t('auth:profile.title'),[SettingsTabs.Referral]: t('subscription:tab.referral'),+ [SettingsTabs.Drive]: t('setting:tab.drive'),[SettingsTabs.Environments]: t('setting:tab.environments'),[SettingsTabs.ServiceModel]: t('setting:tab.serviceModel'),[SettingsTabs.Stats]: t('auth:tab.stats'),diff --git a/src/features/Settings/features/componentMap.desktop.ts b/src/features/Settings/features/componentMap.desktop.tsindex 08010aa4d90..3f7f67f10b2 100644--- a/src/features/Settings/features/componentMap.desktop.ts+++ b/src/features/Settings/features/componentMap.desktop.ts@@ -12,6 +12,7 @@ import Appearance from '../appearance';import Connector from '../connector';import Creds from '../creds';import Devices from '../devices';+import Drive from '../drive';import Environments from '../environments';import Hotkey from '../hotkey';import Integrations from '../integrations';@@ -50,6 +51,7 @@ export const componentMap = {[SettingsTabs.Storage]: Storage,[SettingsTabs.Trash]: Trash,[SettingsTabs.Devices]: Devices,+ [SettingsTabs.Drive]: Drive,[SettingsTabs.Environments]: Environments,[SettingsTabs.Labels]: Labels,// Profile related tabsdiff --git a/src/features/Settings/features/componentMap.ts b/src/features/Settings/features/componentMap.tsindex 18038b0ce7a..e0bc627bb2e 100644--- a/src/features/Settings/features/componentMap.ts+++ b/src/features/Settings/features/componentMap.ts@@ -59,6 +59,9 @@ export const componentMap = {[SettingsTabs.Devices]: dynamic(() => import('../devices'), {loading: loading('Settings > Devices'),}),+ [SettingsTabs.Drive]: dynamic(() => import('../drive'), {+ loading: loading('Settings > Drive'),+ }),[SettingsTabs.Environments]: dynamic(() => import('../environments'), {loading: loading('Settings > Environments'),}),diff --git a/src/features/Settings/hooks/useCategory.test.tsx b/src/features/Settings/hooks/useCategory.test.tsxindex f37361fe3f5..ba49e9b8475 100644--- a/src/features/Settings/hooks/useCategory.test.tsx+++ b/src/features/Settings/hooks/useCategory.test.tsx@@ -74,9 +74,12 @@ describe('settings useCategory', () => {SettingsTabs.Appearance,SettingsTabs.Hotkey,]);+ // Environments is there with no lab switch: a code environment is a+ // definition, written down whether or not there is a drive to run it on.expect(generalGroup?.items.map((item) => item.key)).toEqual([SettingsTabs.Stats,SettingsTabs.Devices,+ SettingsTabs.Environments,]);expect(result.current.find((group) => group.key === SettingsGroupKey.Agent)?.items.map((i) => i.key),@@ -127,6 +130,27 @@ describe('settings useCategory', () => {expect(accountGroup?.items.map((item) => item.key)).toContain(SettingsTabs.Integrations);});+ // The drives are what a persistent sandbox run keeps files on, so the tab+ // that sets them out follows the same lab switch as the composer's picker.+ it('shows Storage beside Environments once persistent sandboxes are switched on', () => {+ expect(getItemKeys()).not.toContain(SettingsTabs.Drive);++ useUserStore.setState({+ preference: {+ ...initialUserStoreState.preference,+ lab: { ...initialUserStoreState.preference.lab, enablePersistentSandbox: true },+ },+ });+ const { result } = renderHook(() => useCategory(), { wrapper: createWrapper(true) });+ const generalGroup = result.current.find((group) => group.key === SettingsGroupKey.General);+ expect(generalGroup?.items.map((item) => item.key)).toEqual([+ SettingsTabs.Stats,+ SettingsTabs.Devices,+ SettingsTabs.Environments,+ SettingsTabs.Drive,+ ]);+ });+it('shows OAuth Apps when the Labs preference is enabled', () => {useUserStore.setState({preference: {diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsxindex 0eab92575d4..6824ff24255 100644--- a/src/features/Settings/hooks/useCategory.tsx+++ b/src/features/Settings/hooks/useCategory.tsx@@ -18,6 +18,7 @@ import {EthernetPort,FlaskConical,Gift,+ HardDriveIcon,Info,KeyboardIcon,KeyIcon,@@ -86,8 +87,6 @@ export const useCategory = () => {const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);const enableIntegrations = useUserStore(labPreferSelectors.enableIntegrations);- // Behind the same experiment that gates the persistent sandbox itself: a tab- // for environments nothing can run in would be a dead end.const enablePersistentSandbox = useUserStore(labPreferSelectors.enablePersistentSandbox);const avatarUrl = useMemo(() => {@@ -157,11 +156,21 @@ export const useCategory = () => {key: SettingsTabs.Devices,label: t('tab.devices'),},- enablePersistentSandbox && {+ // Always there: a code environment is a definition, written down before+ // anything runs it, and useful with or without a drive to run it on.+ {icon: ContainerIcon,key: SettingsTabs.Environments,label: t('tab.environments'),},+ // The drives a cloud-sandbox run keeps files on, with their usage and+ // the way to a plan โ behind the same lab switch the composer's folder+ // picker is, since without it no run ever touches a drive.+ enablePersistentSandbox && {+ icon: HardDriveIcon,+ key: SettingsTabs.Drive,+ label: t('tab.drive'),+ },(enableBusinessFeatures || isDesktop) && {icon: BellIcon,key: SettingsTabs.Notification,diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex 5124ebc233c..74d2d52cbeb 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -81,6 +81,7 @@ export const TAB_SEARCH_EN_KEYWORDS: Partial<Record<string, string[]>> = {[SettingsTabs.Hotkey]: ['hotkey', 'shortcut', 'keyboard'],[SettingsTabs.Labs]: ['labs', 'experiment', 'beta', 'preview', 'developer'],[SettingsTabs.Memory]: ['memory', 'memories', 'personalization'],+ [SettingsTabs.Drive]: ['storage', 'drive', 'network drive', 'files', 'quota'],[SettingsTabs.Environments]: ['sandbox','environments',diff --git a/src/features/WorkingDirectory/AddWorkingDirModal.tsx b/src/features/WorkingDirectory/AddWorkingDirModal.tsxindex d8201a79f8e..465424a55b4 100644--- a/src/features/WorkingDirectory/AddWorkingDirModal.tsx+++ b/src/features/WorkingDirectory/AddWorkingDirModal.tsx@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';import { deviceService } from '@/services/device';+import EnvironmentSelect from './EnvironmentSelect';import { RemoteDirectoryBrowser } from './RemoteDirectoryBrowser';interface AddWorkingDirContentProps {@@ -18,8 +19,13 @@ interface AddWorkingDirContentProps {* modal open; return undefined on success (the modal closes). Lets the caller* validate (e.g. statPath) and enrich (repoType) in one round-trip.*/- onSubmit: (path: string) => Promise<string | undefined>;+ onSubmit: (path: string, extra: { environmentId?: string }) => Promise<string | undefined>;placeholder?: string;+ /**+ * Offer a code environment to go with the folder. On a device that is a+ * note on the folder, nothing more: nothing is cloned or set up there.+ */+ withEnvironment?: boolean;}const AddWorkingDirContent = ({@@ -27,6 +33,7 @@ const AddWorkingDirContent = ({deviceId,onSubmit,placeholder,+ withEnvironment,}: AddWorkingDirContentProps) => {const { t: tPlugin } = useTranslation('device');const { t: tCommon } = useTranslation('common');@@ -35,6 +42,7 @@ const AddWorkingDirContent = ({const [value, setValue] = useState(defaultPath ?? '');const [loading, setLoading] = useState(false);const [error, setError] = useState<string>();+ const [environmentId, setEnvironmentId] = useState<string>();const inputRef = useRef<HTMLInputElement>(null);useEffect(() => {@@ -48,7 +56,7 @@ const AddWorkingDirContent = ({setError(undefined);setLoading(true);try {- const message = await onSubmit(next);+ const message = await onSubmit(next, { environmentId });if (message) {setError(message);return;@@ -62,12 +70,17 @@ const AddWorkingDirContent = ({}};+ const environmentSelect = withEnvironment ? (+ <EnvironmentSelect disabled={loading} value={environmentId} onChange={setEnvironmentId} />+ ) : undefined;+if (!manual && deviceId) {return (<RemoteDirectoryBrowserdefaultPath={value.trim() || undefined}deviceId={deviceId}error={error}+ footerExtra={environmentSelect}loading={loading}onCancel={close}onSelect={handleSubmit}@@ -101,7 +114,8 @@ const AddWorkingDirContent = ({/>{error ? <Text style={{ color: cssVar.colorError, fontSize: 12 }}>{error}</Text> : null}</Flexbox>- <Flexbox horizontal gap={8} justify={'flex-end'} wrap={'wrap'}>+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'} wrap={'wrap'}>+ {environmentSelect}{deviceId && (<Buttondisabled={loading}@@ -141,6 +155,8 @@ export const openAddWorkingDirModal = (options: AddWorkingDirContentProps): Moda});export interface PickedWorkingDir {+ /** The code environment picked with the folder โ metadata only on a device. */+ environmentId?: string;path: string;repoType?: 'git' | 'github';}@@ -155,21 +171,28 @@ export const openPickWorkingDirModal = ({defaultPath,deviceId,onPick,+ withEnvironment,}: {defaultPath?: string;deviceId?: string;onPick: (entry: PickedWorkingDir) => void | Promise<void>;+ withEnvironment?: boolean;}): ModalInstance =>openAddWorkingDirModal({defaultPath,deviceId,- onSubmit: async (path) => {+ onSubmit: async (path, { environmentId }) => {const result = deviceId ? await deviceService.statPath(deviceId, path) : undefined;if (result) {if (!result.exists) return t('workingDirectory.pathNotExist', { ns: 'device' });if (!result.isDirectory) return t('workingDirectory.pathNotDirectory', { ns: 'device' });}- await onPick({ path, repoType: result?.repoType });+ await onPick({+ ...(environmentId ? { environmentId } : {}),+ path,+ repoType: result?.repoType,+ });return undefined;},+ withEnvironment,});diff --git a/src/features/WorkingDirectory/DirectoryBrowser.test.tsx b/src/features/WorkingDirectory/DirectoryBrowser.test.tsxnew file mode 100644index 00000000000..b1f9a9fce6a--- /dev/null+++ b/src/features/WorkingDirectory/DirectoryBrowser.test.tsx@@ -0,0 +1,47 @@+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { DirectoryBrowser } from './DirectoryBrowser';+import type { DirectoryListing, DirectorySource } from './directorySource';++const sourceWith = (listing: Partial<DirectoryListing>): DirectorySource => ({+ createFolder: vi.fn(),+ editablePath: false,+ rootLabel: 'Drive',+ useListing: () => ({+ directory: { parentPath: null, path: '' },+ entries: [{ name: 'held', path: 'held' }],+ hasMore: false,+ isLoading: false,+ isLoadingMore: false,+ isRefreshing: false,+ loadMore: vi.fn(),+ refresh: vi.fn(),+ retry: vi.fn(),+ ...listing,+ }),+});++const renderBrowser = (source: DirectorySource) =>+ render(+ <DirectoryBrowser loading={false} source={source} onCancel={vi.fn()} onSelect={vi.fn()} />,+ );++describe('DirectoryBrowser', () => {+ it('should neither list nor allow using a folder whose listing failed', () => {+ // Folders came back but what classifies them did not: an environment+ // directory would read as a plain folder to browse into and use.+ renderBrowser(sourceWith({ error: new Error('instances unavailable') }));++ expect(screen.queryByText('held')).not.toBeInTheDocument();+ expect(screen.getByRole('alert')).toBeInTheDocument();+ expect(screen.getByText('workingDirectory.useFolder').closest('button')).toBeDisabled();+ });++ it('should list the folders and allow using the folder once it loads', () => {+ renderBrowser(sourceWith({}));++ expect(screen.getByText('held')).toBeInTheDocument();+ expect(screen.getByText('workingDirectory.useFolder').closest('button')).not.toBeDisabled();+ });+});diff --git a/src/features/WorkingDirectory/DirectoryBrowser.tsx b/src/features/WorkingDirectory/DirectoryBrowser.tsxnew file mode 100644index 00000000000..b7d50d83416--- /dev/null+++ b/src/features/WorkingDirectory/DirectoryBrowser.tsx@@ -0,0 +1,297 @@+'use client';++import { ActionIcon, Button, cssVar, Flexbox, Icon, Input, Spin, Text } from '@lobehub/ui';+import {+ ArrowUpIcon,+ CircleAlertIcon,+ FolderPlusIcon,+ HouseIcon,+ RefreshCwIcon,+} from 'lucide-react';+import type { ReactNode } from 'react';+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import NavItem from '@/features/NavPanel/components/NavItem';++import { type DirectorySource, displayedDirectoryPath } from './directorySource';+import { getFolderIcon } from './folderIcons';+import { NewFolderInput } from './NewFolderInput';+import { useDirectoryBrowserState } from './useDirectoryBrowserState';++export interface DirectoryBrowserProps {+ defaultPath?: string;+ /** Above the address bar; the device wording when absent, nothing when `null`. */+ description?: ReactNode;+ error?: string;+ /** Beside the footer's buttons โ what a pick carries along, such as an environment. */+ footerExtra?: ReactNode;+ loading: boolean;+ onCancel: () => void;+ /** Switch to typing a path; absent where a path cannot be typed. */+ onManual?: (path: string) => void;+ onSelect: (path: string) => void;+ source: DirectorySource;+}++/**+ * A refused pick: one plain sentence, with whatever the source said folded+ * behind a toggle โ the raw reason helps a report, not the person choosing.+ */+const SubmitError = ({ detail }: { detail: string }) => {+ const { t } = useTranslation('device');+ const [expanded, setExpanded] = useState(false);++ // A new refusal starts folded again.+ useEffect(() => setExpanded(false), [detail]);++ return (+ <Flexbox gap={4} role={'alert'}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorError} icon={CircleAlertIcon} size={14} />+ <Text type={'danger'}>{t('workingDirectory.useFolderFailed')}</Text>+ <Button size={'small'} type={'link'} onClick={() => setExpanded((value) => !value)}>+ {t(expanded ? 'workingDirectory.errorDetailHide' : 'workingDirectory.errorDetailShow')}+ </Button>+ </Flexbox>+ {expanded && (+ <Text fontSize={12} style={{ wordBreak: 'break-word' }} type={'secondary'}>+ {detail}+ </Text>+ )}+ </Flexbox>+ );+};++/**+ * Browse folders and pick one โ on a device or on the cloud sandbox's drive,+ * whichever the {@link DirectorySource} reads from. Navigation, the new-folder+ * row, and the loading, empty and error states are the same everywhere; what a+ * folder is, and what may be picked, is the source's business.+ */+export const DirectoryBrowser = ({+ defaultPath,+ description,+ error: submitError,+ footerExtra,+ loading,+ onCancel,+ onManual,+ onSelect,+ source,+}: DirectoryBrowserProps) => {+ const { t } = useTranslation('device');+ const { t: tCommon } = useTranslation('common');+ const {+ path,+ draft,+ creatingFolder,+ editPath,+ isPathConfirmed,+ navigate: setDirectoryPath,+ setCreatingFolder,+ } = useDirectoryBrowserState(defaultPath);+ const {+ directory,+ entries,+ error,+ hasMore,+ isLoading,+ isLoadingMore,+ isRefreshing,+ loadMore,+ notice,+ refresh,+ retry,+ } = source.useListing(path);+ // A listing that failed โ even one that brought its folders back โ says+ // nothing trustworthy about this folder, so it can be neither used nor+ // browsed from until a retry succeeds.+ const canUseDirectory = !isLoading && !error && isPathConfirmed(directory?.path);+ const blockedReason = directory ? source.selectBlockedReason?.(directory.path) : undefined;+ const displayedPath = displayedDirectoryPath({+ directoryPath: directory?.path,+ displayPath: source.displayPath,+ draft,+ requestedPath: path,+ });++ const navigate = (nextPath?: string) => {+ setDirectoryPath(nextPath);+ if (nextPath === path) void retry();+ };++ return (+ <Flexbox gap={16}>+ {description !== null && (+ <Text type={'secondary'}>{description ?? t('workingDirectory.browseDescription')}</Text>+ )}+ <Flexbox horizontal align={'center'} gap={8}>+ <Flexbox horizontal flex={'none'} gap={2}>+ <ActionIcon+ aria-label={t('workingDirectory.home')}+ disabled={loading}+ icon={HouseIcon}+ title={t('workingDirectory.home')}+ onClick={() => navigate()}+ />+ <ActionIcon+ aria-label={t('workingDirectory.parentFolder')}+ disabled={loading || typeof directory?.parentPath !== 'string'}+ icon={ArrowUpIcon}+ title={t('workingDirectory.parentFolder')}+ onClick={() =>+ typeof directory?.parentPath === 'string' &&+ navigate(directory.parentPath || undefined)+ }+ />+ <ActionIcon+ aria-label={t('workingDirectory.newFolder')}+ disabled={loading || !canUseDirectory || !!error}+ icon={FolderPlusIcon}+ title={t('workingDirectory.newFolder')}+ onClick={() => setCreatingFolder(true)}+ />+ <ActionIcon+ aria-label={t('workingDirectory.refreshFolders')}+ disabled={loading || !directory}+ icon={RefreshCwIcon}+ loading={isRefreshing}+ title={t('workingDirectory.refreshFolders')}+ onClick={() => void refresh()}+ />+ </Flexbox>+ <Input+ aria-label={t('workingDirectory.current')}+ disabled={loading}+ placeholder={t('workingDirectory.placeholder')}+ readOnly={!source.editablePath}+ style={{ flex: 1, minWidth: 0 }}+ value={displayedPath}+ onChange={(event) => editPath(event.target.value)}+ onPressEnter={() => navigate(displayedPath.trim() || undefined)}+ />+ {source.editablePath && (+ <Button disabled={loading} onClick={() => navigate(displayedPath.trim() || undefined)}>+ {t('workingDirectory.openPath')}+ </Button>+ )}+ </Flexbox>+ {directory?.roots && directory.roots.length > 1 && (+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {directory.roots.map((root) => (+ <Button disabled={loading} key={root} size={'small'} onClick={() => navigate(root)}>+ {root}+ </Button>+ ))}+ </Flexbox>+ )}+ <Flexbox+ aria-busy={isLoading}+ gap={4}+ key={directory?.path ?? path ?? 'home'}+ style={{ height: 'min(320px, 40vh)', overflow: 'auto' }}+ >+ {isLoading ? (+ <Flexbox align={'center'} flex={1} gap={8} justify={'center'}>+ <Spin size="small" />+ <Text type={'secondary'}>{t('workingDirectory.foldersLoading')}</Text>+ </Flexbox>+ ) : (+ <>+ {notice}+ {creatingFolder && canUseDirectory && directory && (+ <NewFolderInput+ parentPath={directory.path}+ source={source}+ onCancel={() => setCreatingFolder(false)}+ onCreated={(createdPath) => {+ // Refresh this listing so the new folder shows when the user+ // steps back up, then open it so it can be used directly.+ void retry();+ navigate(createdPath);+ }}+ />+ )}+ {(error ? [] : entries).map((entry) => {+ const disabled = loading || !!entry.disabled;+ const activate = () => navigate(entry.path);++ return (+ <NavItem+ actions={entry.actions}+ aria-disabled={disabled}+ description={entry.description}+ disabled={disabled}+ extra={entry.tags}+ flex={'none'}+ icon={entry.icon ?? getFolderIcon(entry.name)}+ key={entry.path + entry.name}+ role={'button'}+ tabIndex={disabled ? -1 : 0}+ title={entry.name}+ titleColor={cssVar.colorText}+ onClick={activate}+ onKeyDown={(event) => {+ if (!disabled && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault();+ activate();+ }+ }}+ />+ );+ })}+ {error ? (+ <Flexbox align={'center'} gap={8} padding={16} role={'alert'}>+ <Text style={{ textAlign: 'center', whiteSpace: 'normal' }} type={'secondary'}>+ {t(source.listErrorKey ?? 'workingDirectory.foldersLoadFailed')}+ </Text>+ <Button disabled={loading} onClick={() => void retry()}>+ {tCommon('retry')}+ </Button>+ </Flexbox>+ ) : directory && entries.length === 0 && !creatingFolder ? (+ <Flexbox align={'center'} flex={1} justify={'center'}>+ <Text type={'secondary'}>{t('workingDirectory.foldersEmpty')}</Text>+ </Flexbox>+ ) : null}+ {hasMore && !error && (+ <Button disabled={loading} loading={isLoadingMore} onClick={() => void loadMore()}>+ {t('workingDirectory.loadMoreFolders')}+ </Button>+ )}+ </>+ )}+ </Flexbox>+ {submitError && <SubmitError detail={submitError} />}+ {blockedReason && canUseDirectory && (+ <Text fontSize={12} type={'warning'}>+ {blockedReason}+ </Text>+ )}+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>+ {onManual ? (+ <Button disabled={loading} onClick={() => onManual(displayedPath)}>+ {t('workingDirectory.enterPathManually')}+ </Button>+ ) : (+ <span />+ )}+ <Flexbox horizontal align={'center'} gap={8}>+ {footerExtra}+ <Button disabled={loading} onClick={onCancel}>+ {tCommon('cancel')}+ </Button>+ <Button+ disabled={!canUseDirectory || !!blockedReason}+ loading={loading}+ type={'primary'}+ onClick={() => directory && onSelect(directory.path)}+ >+ {t('workingDirectory.useFolder')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+};diff --git a/src/features/WorkingDirectory/DriveBreadcrumb.tsx b/src/features/WorkingDirectory/DriveBreadcrumb.tsxnew file mode 100644index 00000000000..842504370ba--- /dev/null+++ b/src/features/WorkingDirectory/DriveBreadcrumb.tsx@@ -0,0 +1,143 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { LucideIcon } from 'lucide-react';+import { ChevronRightIcon } from 'lucide-react';+import { memo } from 'react';++const styles = stylex.create({+ crumb: {+ backgroundColor: 'transparent',+ borderRadius: { 'default': null, ':focus-visible': cssVar.borderRadiusSM },+ borderStyle: 'none',+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },+ cursor: 'pointer',+ fontSize: 13,+ maxWidth: 200,+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },+ overflow: 'hidden',+ padding: 0,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ current: {+ color: cssVar.colorText,+ fontSize: 13,+ fontWeight: 500,+ maxWidth: 240,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ iconCrumb: {+ display: 'inline-flex',+ },+ muted: {+ color: cssVar.colorTextTertiary,+ },+ separator: {+ color: cssVar.colorTextQuaternary,+ },+});++interface DriveBreadcrumbProps {+ /** Beside the root's name โ the drive's own mark. */+ icon?: LucideIcon;+ onNavigate: (path: string) => void;+ /** Relative to the drive's root; `''` is the root. */+ path: string;+ /**+ * Show the root as its icon alone โ where something beside the breadcrumb+ * already names the drive, such as the picker's drive switch.+ */+ rootIconOnly?: boolean;+ rootLabel: string;+}++/**+ * Where a drive listing is, read as a path: the drive's name, then each+ * folder on the way down. Every step but the last goes back up to it, so the+ * same row is both the address and the way back โ no separate "up" or+ * "home" buttons, and no read-only address field to stare at.+ */+export const DriveBreadcrumb = memo<DriveBreadcrumbProps>(+ ({ icon, onNavigate, path, rootIconOnly, rootLabel }) => {+ const segments = path ? path.split('/') : [];+ // At the root an icon-only crumb would be a lone glyph pointing nowhere;+ // the trail appears once there is somewhere to go back to.+ if (rootIconOnly && segments.length === 0) return <span />;+ const crumbs = [+ { label: rootLabel, path: '' },+ ...segments.map((segment, index) => ({+ label: segment,+ path: segments.slice(0, index + 1).join('/'),+ })),+ ];++ return (+ <Flexbox+ horizontal+ align={'center'}+ aria-label={rootLabel}+ as={'nav'}+ gap={4}+ style={{ minWidth: 0 }}+ wrap={'wrap'}+ >+ {icon && !rootIconOnly && (+ <Icon className={stylex.props(styles.muted).className} icon={icon} size={14} />+ )}+ {crumbs.map((crumb, index) => {+ const last = index === crumbs.length - 1;+ const iconRoot = index === 0 && rootIconOnly && icon;++ if (iconRoot) {+ return (+ <button+ aria-label={crumb.label}+ {...stylex.props(styles.crumb, styles.iconCrumb)}+ disabled={last}+ key={'root'}+ title={crumb.label}+ type={'button'}+ onClick={() => onNavigate('')}+ >+ <Icon icon={icon} size={14} />+ </button>+ );+ }++ return (+ <Flexbox horizontal align={'center'} gap={4} key={crumb.path || 'root'}>+ {index > 0 && (+ <Icon+ className={stylex.props(styles.separator).className}+ icon={ChevronRightIcon}+ size={12}+ />+ )}+ {last ? (+ <span aria-current={'page'} {...stylex.props(styles.current)} title={crumb.label}>+ {crumb.label}+ </span>+ ) : (+ <button+ {...stylex.props(styles.crumb)}+ title={crumb.label}+ type={'button'}+ onClick={() => onNavigate(crumb.path)}+ >+ {crumb.label}+ </button>+ )}+ </Flexbox>+ );+ })}+ </Flexbox>+ );+ },+);++DriveBreadcrumb.displayName = 'DriveBreadcrumb';diff --git a/src/features/WorkingDirectory/EnvironmentSelect.tsx b/src/features/WorkingDirectory/EnvironmentSelect.tsxnew file mode 100644index 00000000000..301cbd90839--- /dev/null+++ b/src/features/WorkingDirectory/EnvironmentSelect.tsx@@ -0,0 +1,67 @@+'use client';++import { Select } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { environmentService } from '@/services/environment';++interface EnvironmentSelectProps {+ disabled?: boolean;+ /** Narrow the list โ to the environments this member may initialize a folder from, say. */+ filter?: (+ environment: Awaited<+ ReturnType<typeof environmentService.listEnvironments>+ >['environments'][number],+ ) => boolean;+ onChange: (environmentId: string | undefined) => void;+ /** Whose environments may be offered; a public agent cannot use a private one. */+ publishedOnly?: boolean;+ value?: string;+}++/**+ * Which code environment a folder goes with โ optional, and "none" is the+ * first choice. The same list on every surface that picks a folder: what an+ * association does with it (initialize the folder on the drive, or only+ * remember it on a device) is the caller's business.+ */+const EnvironmentSelect = memo<EnvironmentSelectProps>(+ ({ disabled, filter, onChange, publishedOnly, value }) => {+ const { t } = useTranslation('device');+ const workspaceId = useActiveWorkspaceId();+ const { data, isLoading } = useSWR(['folder-environment-options', workspaceId ?? ''], () =>+ environmentService.listEnvironments(),+ );++ const environments = (data?.environments ?? []).filter(+ (environment) =>+ (!publishedOnly || !environment.workspaceId || environment.visibility === 'public') &&+ (!filter || filter(environment)),+ );++ return (+ <Select+ allowClear+ aria-label={t('workingDirectory.environment.label')}+ disabled={disabled}+ loading={isLoading}+ placeholder={t('workingDirectory.environment.none')}+ size={'small'}+ style={{ minWidth: 168 }}+ value={value}+ options={environments.map((environment) => ({+ label: environment.name,+ value: environment.id,+ }))}+ onChange={(next) => onChange((next as string | null | undefined) ?? undefined)}+ />+ );+ },+);++EnvironmentSelect.displayName = 'EnvironmentSelect';++export default EnvironmentSelect;diff --git a/src/features/WorkingDirectory/NewFolderInput.tsx b/src/features/WorkingDirectory/NewFolderInput.tsxindex 9e9db89c893..9c0a847e4dc 100644--- a/src/features/WorkingDirectory/NewFolderInput.tsx+++ b/src/features/WorkingDirectory/NewFolderInput.tsx@@ -4,26 +4,29 @@ import { Button, cssVar, Flexbox, Icon, Input, Text } from '@lobehub/ui';import { FolderPlusIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';+import type { DirectorySource } from './directorySource';import { useCreateFolder } from './useCreateFolder';interface NewFolderInputProps {- deviceId: string;onCancel: () => void;onCreated: (path: string) => void;parentPath: string;+ /** Only how a folder is made โ what a picker and a file manager have in common. */+ source: Pick<DirectorySource, 'createFolder' | 'folderErrorKey'>;}/** Inline row that names and creates a folder inside the folder being browsed. */export const NewFolderInput = ({- deviceId,onCancel,onCreated,parentPath,+ source,}: NewFolderInputProps) => {const { t } = useTranslation('device');const { t: tCommon } = useTranslation('common');const { error, name, pending, setName, submit } = useCreateFolder({- deviceId,+ create: source.createFolder,+ errorMessageKey: source.folderErrorKey,onCreated,parentPath,});diff --git a/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsxindex 3e14def6f71..b3caef453d4 100644--- a/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx+++ b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx@@ -1,219 +1,24 @@'use client';-import { ActionIcon, Button, cssVar, Flexbox, Input, Spin, Text } from '@lobehub/ui';-import { ArrowUpIcon, FolderPlusIcon, HouseIcon, RefreshCwIcon } from 'lucide-react';-import { useTranslation } from 'react-i18next';+import type { ReactNode } from 'react';-import NavItem from '@/features/NavPanel/components/NavItem';-import { useFetchDeviceDirectory } from '@/store/device/directoryHooks';--import { getFolderIcon } from './folderIcons';-import { NewFolderInput } from './NewFolderInput';-import { useDirectoryBrowserState } from './useDirectoryBrowserState';+import { DirectoryBrowser } from './DirectoryBrowser';+import { useDeviceDirectorySource } from './sources/useDeviceDirectorySource';interface RemoteDirectoryBrowserProps {defaultPath?: string;deviceId: string;error?: string;+ footerExtra?: ReactNode;loading: boolean;onCancel: () => void;onManual: (path: string) => void;onSelect: (path: string) => void;}-export const RemoteDirectoryBrowser = ({- defaultPath,- deviceId,- error: submitError,- loading,- onCancel,- onManual,- onSelect,-}: RemoteDirectoryBrowserProps) => {- const { t } = useTranslation('device');- const { t: tCommon } = useTranslation('common');- const {- path,- draft,- creatingFolder,- editPath,- isPathConfirmed,- navigate: setDirectoryPath,- setCreatingFolder,- } = useDirectoryBrowserState(defaultPath);- const {- directory,- entries,- error,- hasMore,- isLoading,- isLoadingMore,- isRefreshing,- loadMore,- refresh,- retry,- } = useFetchDeviceDirectory(deviceId, path);- const canUseDirectory = !isLoading && isPathConfirmed(directory?.path);- const displayedPath = draft ?? directory?.path ?? path ?? '';-- const navigate = (nextPath?: string) => {- setDirectoryPath(nextPath);- if (nextPath === path) void retry();- };+/** {@link DirectoryBrowser} over a connected device's folders. */+export const RemoteDirectoryBrowser = ({ deviceId, ...props }: RemoteDirectoryBrowserProps) => {+ const source = useDeviceDirectorySource(deviceId);- return (- <Flexbox gap={16}>- <Text type={'secondary'}>{t('workingDirectory.browseDescription')}</Text>- <Flexbox horizontal align={'center'} gap={8}>- <Flexbox horizontal flex={'none'} gap={2}>- <ActionIcon- aria-label={t('workingDirectory.home')}- disabled={loading}- icon={HouseIcon}- title={t('workingDirectory.home')}- onClick={() => navigate()}- />- <ActionIcon- aria-label={t('workingDirectory.parentFolder')}- disabled={loading || !directory?.parentPath}- icon={ArrowUpIcon}- title={t('workingDirectory.parentFolder')}- onClick={() => directory?.parentPath && navigate(directory.parentPath)}- />- <ActionIcon- aria-label={t('workingDirectory.newFolder')}- disabled={loading || !canUseDirectory || !!error}- icon={FolderPlusIcon}- title={t('workingDirectory.newFolder')}- onClick={() => setCreatingFolder(true)}- />- <ActionIcon- aria-label={t('workingDirectory.refreshFolders')}- disabled={loading || !directory}- icon={RefreshCwIcon}- loading={isRefreshing}- title={t('workingDirectory.refreshFolders')}- onClick={() => void refresh()}- />- </Flexbox>- <Input- aria-label={t('workingDirectory.current')}- disabled={loading}- placeholder={t('workingDirectory.placeholder')}- style={{ flex: 1, minWidth: 0 }}- value={displayedPath}- onChange={(event) => editPath(event.target.value)}- onPressEnter={() => navigate(displayedPath.trim() || undefined)}- />- <Button disabled={loading} onClick={() => navigate(displayedPath.trim() || undefined)}>- {t('workingDirectory.openPath')}- </Button>- </Flexbox>- {directory && directory.roots.length > 1 && (- <Flexbox horizontal gap={8} wrap={'wrap'}>- {directory.roots.map((root) => (- <Button disabled={loading} key={root} size={'small'} onClick={() => navigate(root)}>- {root}- </Button>- ))}- </Flexbox>- )}- <Flexbox- aria-busy={isLoading}- gap={4}- key={directory?.path ?? path ?? 'home'}- style={{ height: 'min(320px, 40vh)', overflow: 'auto' }}- >- {isLoading ? (- <Flexbox align={'center'} flex={1} gap={8} justify={'center'}>- <Spin size="small" />- <Text type={'secondary'}>{t('workingDirectory.foldersLoading')}</Text>- </Flexbox>- ) : (- <>- {creatingFolder && canUseDirectory && directory && (- <NewFolderInput- deviceId={deviceId}- parentPath={directory.path}- onCancel={() => setCreatingFolder(false)}- onCreated={(createdPath) => {- // Refresh this listing so the new folder shows when the user- // steps back up, then open it so it can be used directly.- void retry();- navigate(createdPath);- }}- />- )}- {entries.map((entry) => (- <NavItem- aria-disabled={loading || !entry.readable}- disabled={loading || !entry.readable}- flex={'none'}- icon={getFolderIcon(entry.name)}- key={entry.path + entry.name}- role={'button'}- tabIndex={loading || !entry.readable ? -1 : 0}- title={entry.name}- titleColor={cssVar.colorText}- description={- entry.readable ? undefined : (- <Text type={'secondary'}>{t('workingDirectory.folderUnreadable')}</Text>- )- }- onClick={() => navigate(entry.path)}- onKeyDown={(event) => {- if (!loading && entry.readable && (event.key === 'Enter' || event.key === ' ')) {- event.preventDefault();- navigate(entry.path);- }- }}- />- ))}- {error ? (- <Flexbox align={'center'} gap={8} padding={16} role={'alert'}>- <Text style={{ textAlign: 'center', whiteSpace: 'normal' }} type={'secondary'}>- {t('workingDirectory.foldersLoadFailed')}- </Text>- <Button disabled={loading} onClick={() => void retry()}>- {tCommon('retry')}- </Button>- </Flexbox>- ) : directory && entries.length === 0 && !creatingFolder ? (- <Flexbox align={'center'} flex={1} justify={'center'}>- <Text type={'secondary'}>{t('workingDirectory.foldersEmpty')}</Text>- </Flexbox>- ) : null}- {hasMore && !error && (- <Button disabled={loading} loading={isLoadingMore} onClick={() => void loadMore()}>- {t('workingDirectory.loadMoreFolders')}- </Button>- )}- </>- )}- </Flexbox>- {submitError && (- <Text role={'alert'} type={'danger'}>- {submitError}- </Text>- )}- <Flexbox horizontal gap={8} justify={'space-between'} wrap={'wrap'}>- <Button disabled={loading} onClick={() => onManual(displayedPath)}>- {t('workingDirectory.enterPathManually')}- </Button>- <Flexbox horizontal gap={8}>- <Button disabled={loading} onClick={onCancel}>- {tCommon('cancel')}- </Button>- <Button- disabled={!canUseDirectory}- loading={loading}- type={'primary'}- onClick={() => directory && onSelect(directory.path)}- >- {t('workingDirectory.useFolder')}- </Button>- </Flexbox>- </Flexbox>- </Flexbox>- );+ return <DirectoryBrowser {...props} source={source} />;};diff --git a/src/features/WorkingDirectory/RenameFolderModal.tsx b/src/features/WorkingDirectory/RenameFolderModal.tsxnew file mode 100644index 00000000000..9df53629414--- /dev/null+++ b/src/features/WorkingDirectory/RenameFolderModal.tsx@@ -0,0 +1,97 @@+'use client';++import { isValidDirectoryName } from '@lobechat/utils/directoryName';+import { Button, createModal, Flexbox, Input, Text, useModalContext } from '@lobehub/ui';+import { t } from 'i18next';+import { memo, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface RenameFolderContentProps {+ currentName: string;+ /** Return an error message to keep the dialog open with it, or nothing to close. */+ onSubmit: (name: string) => Promise<string | undefined>;+}++const RenameFolderContent = memo<RenameFolderContentProps>(({ currentName, onSubmit }) => {+ const { t: tDevice } = useTranslation('device');+ const { t: tCommon } = useTranslation('common');+ const { close } = useModalContext();+ const [value, setValue] = useState(currentName);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string>();+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ queueMicrotask(() => inputRef.current?.select());+ }, []);++ const trimmed = value.trim();++ const submit = async () => {+ if (loading || !trimmed || trimmed === currentName) return;+ if (!isValidDirectoryName(trimmed, '')) {+ setError(tDevice('workingDirectory.newFolderInvalidName'));+ return;+ }+ setLoading(true);+ try {+ const message = await onSubmit(trimmed);+ if (message) {+ setError(message);+ return;+ }+ close();+ } finally {+ setLoading(false);+ }+ };++ return (+ <Flexbox gap={16}>+ <Flexbox gap={8}>+ <Input+ aria-label={tDevice('workingDirectory.newFolderPlaceholder')}+ readOnly={loading}+ ref={inputRef}+ value={value}+ onPressEnter={() => void submit()}+ onChange={(event) => {+ setValue(event.target.value);+ setError(undefined);+ }}+ />+ {error && (+ <Text fontSize={12} role={'alert'} type={'danger'}>+ {error}+ </Text>+ )}+ </Flexbox>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={loading} onClick={close}>+ {tCommon('cancel')}+ </Button>+ <Button+ disabled={!trimmed || trimmed === currentName}+ loading={loading}+ type={'primary'}+ onClick={() => void submit()}+ >+ {tCommon('rename')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++RenameFolderContent.displayName = 'RenameFolderContent';++/** Rename one folder on the drive; nothing is overwritten. */+export const openRenameFolderModal = (props: RenameFolderContentProps) =>+ createModal({+ content: <RenameFolderContent {...props} />,+ footer: null,+ maskClosable: true,+ styles: { header: { borderBottom: 'none' } },+ title: t('workingDirectory.drive.renameTitle', { ns: 'device' }),+ width: 'min(90vw, 420px)',+ });diff --git a/src/features/WorkingDirectory/SandboxDirectoryModal.tsx b/src/features/WorkingDirectory/SandboxDirectoryModal.tsxnew file mode 100644index 00000000000..d469fa1d193--- /dev/null+++ b/src/features/WorkingDirectory/SandboxDirectoryModal.tsx@@ -0,0 +1,132 @@+'use client';++import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import {+ Center,+ createModal,+ Flexbox,+ Icon,+ type ModalInstance,+ Segmented,+ Spin,+ toast,+ useModalContext,+} from '@lobehub/ui';+import { t } from 'i18next';+import { LockIcon, UsersIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { SandboxStorageUpgradeGuide } from '@/business/client/features/SandboxStorageUpsell';+import { useSandboxDriveEntitlement } from '@/hooks/useSandboxDriveEntitlement';++import { confirmPick } from './confirmPick';+import { DirectoryBrowser } from './DirectoryBrowser';+import { useSandboxDirectorySource } from './sources/useSandboxDirectorySource';++/** The folder a pick on the drive binds the conversation to, and which drive it is on. */+export interface SandboxDirectoryPick {+ drive: SandboxDrive;+ workingDirectory: string;+}++interface SandboxDirectoryContentProps {+ defaultPath?: string;+ /** The drive to open on; the conversation's own, or the public one in a workspace. */+ drive?: SandboxDrive;+ /** In a workspace: a public drive beside the member's personal one. */+ isWorkspace: boolean;+ onPick: (pick: SandboxDirectoryPick) => void | Promise<void>;+}++const SandboxDirectoryContent = ({+ defaultPath,+ drive: initialDrive,+ isWorkspace,+ onPick,+}: SandboxDirectoryContentProps) => {+ const { t: tDevice } = useTranslation('device');+ const { close } = useModalContext();+ const { entitled } = useSandboxDriveEntitlement();+ const [saving, setSaving] = useState(false);+ const [drive, setDrive] = useState<SandboxDrive>(+ isWorkspace ? (initialDrive ?? 'public') : 'personal',+ );+ // A path belongs to the drive it was picked on; another drive opens at its root.+ const startPath =+ drive === (initialDrive ?? (isWorkspace ? 'public' : 'personal')) ? defaultPath : undefined;++ const source = useSandboxDirectorySource({ drive, isWorkspace });++ // Without a drive there is nothing to browse: the way to one stands where+ // the folders would be.+ if (entitled === false) return <SandboxStorageUpgradeGuide compact onLeave={close} />;+ if (entitled === undefined) {+ return (+ <Center style={{ minHeight: 240 }}>+ <Spin />+ </Center>+ );+ }++ return (+ <Flexbox gap={12}>+ {isWorkspace && (+ <Segmented+ block+ value={drive}+ options={[+ {+ icon: <Icon icon={UsersIcon} />,+ label: tDevice('workingDirectory.drive.drives.public'),+ value: 'public',+ },+ {+ icon: <Icon icon={LockIcon} />,+ label: tDevice('workingDirectory.drive.drives.personal'),+ value: 'personal',+ },+ ]}+ onChange={(value) => setDrive(value as SandboxDrive)}+ />+ )}+ {/* Keyed on the drive, so its navigation starts over: a folder on one+ drive means nothing on the other. */}+ <DirectoryBrowser+ defaultPath={startPath}+ description={tDevice('workingDirectory.drive.browseDescription')}+ key={drive}+ loading={saving}+ source={source}+ onCancel={close}+ onSelect={async (path) => {+ setSaving(true);+ await confirmPick({+ // The root is a choice of its own โ `.` โ distinct from "no+ // folder", which is the temporary sandbox.+ apply: () => onPick({ drive, workingDirectory: path || '.' }),+ close,+ fail: () => toast.error(tDevice('workingDirectory.drive.pickFailed')),+ });+ setSaving(false);+ }}+ />+ </Flexbox>+ );+};++/**+ * Pick the folder on the drive a cloud-sandbox conversation works in โ any+ * folder, or the root of a personal drive โ laid out like a device's folder+ * picker: a toolbar and the path, the folders below. In a workspace the public+ * and personal drives are switched between at the top.+ */+export const openSandboxDirectoryModal = (props: SandboxDirectoryContentProps): ModalInstance =>+ createModal({+ content: <SandboxDirectoryContent {...props} />,+ footer: null,+ maskClosable: true,+ styles: { header: { borderBottom: 'none' } },+ title: t('workingDirectory.drive.title', { ns: 'device' }),+ width: 'min(90vw, 600px)',+ });diff --git a/src/features/WorkingDirectory/confirmPick.test.ts b/src/features/WorkingDirectory/confirmPick.test.tsnew file mode 100644index 00000000000..d751bef09a6--- /dev/null+++ b/src/features/WorkingDirectory/confirmPick.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it, vi } from 'vitest';++import { confirmPick } from './confirmPick';++describe('confirmPick', () => {+ it('closes once the pick has been applied', async () => {+ const close = vi.fn();+ const fail = vi.fn();++ await confirmPick({ apply: async () => {}, close, fail });++ expect(close).toHaveBeenCalledOnce();+ expect(fail).not.toHaveBeenCalled();+ });++ it('stays open and reports the failure when applying the pick fails', async () => {+ const close = vi.fn();+ const fail = vi.fn();+ const error = new Error('offline');++ await confirmPick({ apply: () => Promise.reject(error), close, fail });++ expect(close).not.toHaveBeenCalled();+ expect(fail).toHaveBeenCalledWith(error);+ });+});diff --git a/src/features/WorkingDirectory/confirmPick.ts b/src/features/WorkingDirectory/confirmPick.tsnew file mode 100644index 00000000000..9335e2fa29a--- /dev/null+++ b/src/features/WorkingDirectory/confirmPick.ts@@ -0,0 +1,22 @@+/**+ * Apply a pick, then close โ or, if applying it failed, stay open and say so.+ * Closing first would make a failed save look like a pick that took, with the+ * old folder still in use and nothing to retry from.+ */+export const confirmPick = async ({+ apply,+ close,+ fail,+}: {+ apply: () => void | Promise<void>;+ close: () => void;+ fail: (error: unknown) => void;+}): Promise<void> => {+ try {+ await apply();+ } catch (error) {+ fail(error);+ return;+ }+ close();+};diff --git a/src/features/WorkingDirectory/directorySource.test.ts b/src/features/WorkingDirectory/directorySource.test.tsnew file mode 100644index 00000000000..c961b1a6acb--- /dev/null+++ b/src/features/WorkingDirectory/directorySource.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { displayedDirectoryPath } from './directorySource';++const drivePath = (path: string) => `/${path}`;++describe('displayedDirectoryPath', () => {+ it("shows a drive's top level as / when its listing failed, not an empty field", () => {+ expect(displayedDirectoryPath({ displayPath: drivePath })).toBe('/');+ expect(displayedDirectoryPath({ displayPath: drivePath, requestedPath: 'reports' })).toBe(+ '/reports',+ );+ });++ it('shows the listed folder, and what is being typed over it', () => {+ expect(displayedDirectoryPath({ directoryPath: 'a/b', displayPath: drivePath })).toBe('/a/b');+ expect(+ displayedDirectoryPath({ directoryPath: 'a', displayPath: drivePath, draft: '/a/c' }),+ ).toBe('/a/c');+ });++ it('leaves a device path as it is, and empty while its home is unknown', () => {+ expect(displayedDirectoryPath({ directoryPath: '/Users/me' })).toBe('/Users/me');+ expect(displayedDirectoryPath({})).toBe('');+ });+});diff --git a/src/features/WorkingDirectory/directorySource.ts b/src/features/WorkingDirectory/directorySource.tsnew file mode 100644index 00000000000..2c2ce29f2b5--- /dev/null+++ b/src/features/WorkingDirectory/directorySource.ts@@ -0,0 +1,93 @@+import type { LucideIcon } from 'lucide-react';+import type { ReactNode } from 'react';++/**+ * One folder as a directory picker lists it, whichever machine or drive it is+ * on.+ */+export interface DirectoryEntry {+ /** At the row's end: a menu of what can be done to the folder โ rename, delete. */+ actions?: ReactNode;+ /** Under the name: why it cannot be opened, or what it is. */+ description?: ReactNode;+ disabled?: boolean;+ /** In place of the folder glyph. */+ icon?: LucideIcon;+ name: string;+ path: string;+ /** Always shown on the right of the row: what it is, whether it is in use. */+ tags?: ReactNode;+}++/** One folder's listing, and the ways to move through it. */+export interface DirectoryListing {+ /** Where the listing is; absent until the first answer arrives. */+ directory?: { parentPath?: string | null; path: string; roots?: string[] };+ entries: DirectoryEntry[];+ error?: unknown;+ hasMore: boolean;+ isLoading: boolean;+ isLoadingMore: boolean;+ isRefreshing: boolean;+ loadMore: () => void;+ /** Above the entries: something about this folder worth saying before its contents. */+ notice?: ReactNode;+ refresh: () => Promise<void>;+ retry: () => void;+}++/**+ * Where a directory picker reads folders from and writes new ones to โ the+ * one difference between picking a folder on a device and on the cloud+ * sandbox's drive. The picker itself (navigation, the new-folder row, the+ * empty and error states) is the same for both.+ *+ * `useListing` is a hook: a source is made by a hook of its own, and the+ * browser calls this unconditionally on every render.+ */+export interface DirectorySource {+ /**+ * Make a folder inside `parentPath`.+ */+ createFolder: (parentPath: string, name: string) => Promise<{ path: string }>;+ /** How the path is shown in the address field; the raw path when absent. */+ displayPath?: (path: string) => string;+ /** Whether a path can be typed in by hand. A device's can; the drive is browsed. */+ editablePath: boolean;+ /** Translation key for an error the source's create threw, or `undefined` for the generic one. */+ folderErrorKey?: (error: unknown) => string | undefined;+ /**+ * Translation key for a listing that failed, when the generic one โ which+ * speaks of a device connection and a typed path โ does not fit the source.+ */+ listErrorKey?: 'workingDirectory.drive.foldersLoadFailed';+ /**+ * Why the folder being browsed cannot be chosen, or `undefined` when it+ * can. A shared drive's root is the one such folder today.+ */+ selectBlockedReason?: (path: string) => string | undefined;+ useListing: (path?: string) => DirectoryListing;+}++/**+ * What the path field shows. Without a listing โ still loading, or failed โ+ * the folder asked for is shown in the source's own form (`/` for a drive's+ * top level), not left empty for a placeholder that describes device paths.+ */+export const displayedDirectoryPath = ({+ directoryPath,+ displayPath,+ draft,+ requestedPath,+}: {+ directoryPath?: string;+ displayPath?: (path: string) => string;+ draft?: string;+ requestedPath?: string;+}): string => {+ if (draft !== undefined) return draft;+ const shown = directoryPath ?? requestedPath;+ if (shown === undefined) return displayPath?.('') ?? '';++ return displayPath?.(shown) ?? shown;+};diff --git a/src/features/WorkingDirectory/index.ts b/src/features/WorkingDirectory/index.tsindex 6e335d22f2d..1d9318f1c27 100644--- a/src/features/WorkingDirectory/index.ts+++ b/src/features/WorkingDirectory/index.ts@@ -1,2 +1,9 @@export type { PickedWorkingDir } from './AddWorkingDirModal';export { openAddWorkingDirModal, openPickWorkingDirModal } from './AddWorkingDirModal';+export type { DirectoryEntry, DirectoryListing, DirectorySource } from './directorySource';+export { DriveBreadcrumb } from './DriveBreadcrumb';+export { NewFolderInput } from './NewFolderInput';+export { openRenameFolderModal } from './RenameFolderModal';+export type { SandboxDirectoryPick } from './SandboxDirectoryModal';+export { openSandboxDirectoryModal } from './SandboxDirectoryModal';+export { displayDrivePath, driveParentPath, joinDrivePath } from './sources/driveFolders';diff --git a/src/features/WorkingDirectory/sources/driveFolders.test.ts b/src/features/WorkingDirectory/sources/driveFolders.test.tsnew file mode 100644index 00000000000..3e2f6e2b28d--- /dev/null+++ b/src/features/WorkingDirectory/sources/driveFolders.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { displayDrivePath, driveParentPath, joinDrivePath } from './driveFolders';++describe('drive paths', () => {+ it('walks up to the root and stops there', () => {+ expect(driveParentPath('a/b/c')).toBe('a/b');+ expect(driveParentPath('a')).toBe('');+ expect(driveParentPath('')).toBeNull();+ });++ it('joins at the root without a leading slash', () => {+ expect(joinDrivePath('', 'reports')).toBe('reports');+ expect(joinDrivePath('reports', 'q3')).toBe('reports/q3');+ });++ it('shows paths rooted at the drive', () => {+ expect(displayDrivePath('')).toBe('/');+ expect(displayDrivePath('reports/q3')).toBe('/reports/q3');+ });+});diff --git a/src/features/WorkingDirectory/sources/driveFolders.ts b/src/features/WorkingDirectory/sources/driveFolders.tsnew file mode 100644index 00000000000..a13ceffa200--- /dev/null+++ b/src/features/WorkingDirectory/sources/driveFolders.ts@@ -0,0 +1,19 @@+/**+ * Pure helpers for the drive's folder listing, apart from React so the rules+ * the picker draws by can be tested on their own.+ */++/** A folder's parent on the drive; `null` at the root, `''` for a top-level folder. */+export const driveParentPath = (path: string): string | null => {+ if (!path) return null;+ const index = path.lastIndexOf('/');++ return index === -1 ? '' : path.slice(0, index);+};++/** A child path on the drive, from a parent (`''` is the root) and a name. */+export const joinDrivePath = (parentPath: string, name: string) =>+ parentPath ? `${parentPath}/${name}` : name;++/** How a drive path reads in the address field: rooted, like a mount. */+export const displayDrivePath = (path: string) => `/${path}`;diff --git a/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsx b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsxnew file mode 100644index 00000000000..40cb325d77b--- /dev/null+++ b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsx@@ -0,0 +1,38 @@+import { Text } from '@lobehub/ui';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { deviceService } from '@/services/device';+import { useFetchDeviceDirectory } from '@/store/device/directoryHooks';++import type { DirectoryListing, DirectorySource } from '../directorySource';++/**+ * A connected device's folders, through the device gateway's directory RPCs.+ * Any readable folder may be picked, and a path may be typed in by hand.+ */+export const useDeviceDirectorySource = (deviceId: string): DirectorySource =>+ useMemo(+ () => ({+ createFolder: (parentPath, name) =>+ deviceService.createDirectory({ deviceId, name, parentPath }),+ editablePath: true,+ useListing: (path?: string): DirectoryListing => {+ const { t } = useTranslation('device');+ const listing = useFetchDeviceDirectory(deviceId, path);++ return {+ ...listing,+ entries: listing.entries.map((entry) => ({+ description: entry.readable ? undefined : (+ <Text type={'secondary'}>{t('workingDirectory.folderUnreadable')}</Text>+ ),+ disabled: !entry.readable,+ name: entry.name,+ path: entry.path,+ })),+ };+ },+ }),+ [deviceId],+ );diff --git a/src/features/WorkingDirectory/sources/useSandboxDirectorySource.test.tsx b/src/features/WorkingDirectory/sources/useSandboxDirectorySource.test.tsxnew file mode 100644index 00000000000..cc80594c8e7--- /dev/null+++ b/src/features/WorkingDirectory/sources/useSandboxDirectorySource.test.tsx@@ -0,0 +1,112 @@+import { renderHook, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { sandboxStorageService } from '@/services/sandboxStorage';++import { useSandboxDirectorySource } from './useSandboxDirectorySource';++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => 'ws1',+}));++vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { createDirectory: vi.fn(), listFiles: vi.fn() },+}));++const wrapper = ({ children }: { children: ReactNode }) => (+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>{children}</SWRConfig>+);++const renderSource = (drive: 'personal' | 'public' = 'personal') =>+ renderHook(() => useSandboxDirectorySource({ drive, isWorkspace: true }), { wrapper });++const renderListing = (path?: string) =>+ renderHook(+ () => useSandboxDirectorySource({ drive: 'personal', isWorkspace: true }).useListing(path),+ { wrapper },+ );++describe('useSandboxDirectorySource', () => {+ beforeEach(() => {+ vi.mocked(sandboxStorageService.listFiles)+ .mockReset()+ .mockResolvedValue({+ entries: [+ { isDirectory: true, isGitRepository: true, name: 'app', path: 'app' },+ { isDirectory: true, name: 'notes', path: 'notes' },+ { isDirectory: false, name: 'readme.md', path: 'readme.md' },+ ],+ } as any);+ vi.mocked(sandboxStorageService.createDirectory)+ .mockReset()+ .mockResolvedValue({} as any);+ });++ it('lists folders only, and marks the ones that are git repositories', async () => {+ const { result } = renderListing();++ await waitFor(() => expect(result.current.entries).toHaveLength(2));+ const [app, notes] = result.current.entries;+ expect(app).toMatchObject({ name: 'app', path: 'app' });+ expect(app.icon).toBeDefined();+ expect(app.tags).toBeDefined();+ expect(notes).toMatchObject({ name: 'notes', path: 'notes' });+ expect(notes.icon).toBeUndefined();+ expect(notes.tags).toBeUndefined();+ });++ it('treats a folder a code environment initialized as an ordinary folder', async () => {+ // No environment directory, no in-use or building state: every folder+ // opens into its contents and carries the same rename/delete menu.+ const { result } = renderListing();++ await waitFor(() => expect(result.current.entries).toHaveLength(2));+ for (const entry of result.current.entries) {+ expect(entry.actions).toBeDefined();+ expect(entry.disabled).toBeFalsy();+ expect(entry.description).toBeUndefined();+ }+ });++ it('creates a plain folder beside the ones listed, whatever is browsed', async () => {+ const { result } = renderSource();++ await expect(result.current.createFolder('projects', 'api')).resolves.toEqual({+ path: 'projects/api',+ });+ expect(sandboxStorageService.createDirectory).toHaveBeenCalledWith({+ drive: 'personal',+ path: 'projects/api',+ });+ });++ it('is laid out like the device picker: a path field, not a breadcrumb', () => {+ const { result } = renderSource();++ expect(result.current).not.toHaveProperty('rootLabel');+ expect(result.current.editablePath).toBe(false);+ expect(result.current.displayPath?.('reports')).toBe('/reports');+ });++ it("refuses the public drive's root, and only that", () => {+ const { result } = renderSource('public');++ expect(result.current.selectBlockedReason?.('')).toBe('workingDirectory.drive.rootNotAllowed');+ expect(result.current.selectBlockedReason?.('team')).toBeUndefined();+ });++ it('fails a listing whose folders cannot be read, and retries it', async () => {+ const failure = new Error('drive unavailable');+ vi.mocked(sandboxStorageService.listFiles).mockRejectedValueOnce(failure);++ const { result } = renderListing();+ await waitFor(() => expect(result.current.error).toBe(failure));+ expect(result.current.entries).toEqual([]);++ result.current.retry();++ await waitFor(() => expect(result.current.entries).toHaveLength(2));+ });+});diff --git a/src/features/WorkingDirectory/sources/useSandboxDirectorySource.tsx b/src/features/WorkingDirectory/sources/useSandboxDirectorySource.tsxnew file mode 100644index 00000000000..2513c32503e--- /dev/null+++ b/src/features/WorkingDirectory/sources/useSandboxDirectorySource.tsx@@ -0,0 +1,186 @@+'use client';++import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';+import { ActionIcon, confirmModal, DropdownMenu, Icon, Tag, toast } from '@lobehub/ui';+import { FolderGit2Icon, MoreHorizontalIcon, PencilIcon, Trash2Icon } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR, { useSWRConfig } from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { describeError } from '@/features/EnvironmentManager/errorMessage';+import { sandboxStorageService } from '@/services/sandboxStorage';++import type { DirectoryEntry, DirectoryListing, DirectorySource } from '../directorySource';+import { openRenameFolderModal } from '../RenameFolderModal';+import { displayDrivePath, driveParentPath, joinDrivePath } from './driveFolders';++const FOLDERS_KEY = 'sandbox-drive-folders';++export interface UseSandboxDirectorySourceOptions {+ /** Which of the caller's drives is browsed; a personal account's is `personal`. */+ drive: SandboxDrive;+ /**+ * The conversation is in a workspace, which has a public drive beside each+ * member's personal one. The public drive's root holds every member's+ * folders, so the root itself is not a folder anyone may work in there.+ */+ isWorkspace: boolean;+}++/**+ * The cloud sandbox's drive as a directory source, read through+ * `sandboxStorage.listFiles` and written through `createDirectory`.+ *+ * Every folder is an ordinary folder: browsed, picked, created, renamed and+ * deleted alike. One a code environment initialized is no different โ an+ * environment is a one-time initializer, and what it leaves is a checkout โ+ * so the only thing said about a folder is whether it is a git repository.+ */+export const useSandboxDirectorySource = ({+ drive,+ isWorkspace,+}: UseSandboxDirectorySourceOptions): DirectorySource => {+ const { t } = useTranslation(['device', 'setting', 'common']);+ const workspaceId = useActiveWorkspaceId();+ const { mutate: globalMutate } = useSWRConfig();++ return useMemo(() => {+ const isSharedDrive = isWorkspace && drive === 'public';+ const tSetting = (key: string, options?: Record<string, unknown>) =>+ (t as (key: string, options?: Record<string, unknown>) => string)(key, {+ ...options,+ ns: 'setting',+ });+ const refreshFolders = () =>+ globalMutate((key) => Array.isArray(key) && key[0] === FOLDERS_KEY);+ const failed = (error: unknown) =>+ toast.error(describeError(error, tSetting, t('workingDirectory.drive.actionFailed')));++ const renameFolder = (entry: { name: string; path: string }) =>+ openRenameFolderModal({+ currentName: entry.name,+ onSubmit: async (name) => {+ try {+ await sandboxStorageService.renameFile({+ drive,+ newPath: joinDrivePath(driveParentPath(entry.path) ?? '', name),+ path: entry.path,+ });+ await refreshFolders();+ } catch (error) {+ return describeError(error, tSetting, t('workingDirectory.drive.renameFailed'));+ }+ },+ });++ const deleteFolder = (entry: { name: string; path: string }) =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('workingDirectory.drive.deleteConfirmContent'),+ okButtonProps: { danger: true },+ okText: t('workingDirectory.drive.delete'),+ onOk: async () => {+ try {+ await sandboxStorageService.removeFile({ drive, path: entry.path, recursive: true });+ await refreshFolders();+ } catch (error) {+ failed(error);+ }+ },+ title: t('workingDirectory.drive.deleteConfirmTitle', { name: entry.name }),+ });++ // One menu rather than a pair of icons: the row is for picking, and what+ // else can be done to a folder stays one click away without competing.+ const folderActions = (entry: { name: string; path: string }) => (+ <span+ role={'none'}+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'rename',+ label: t('workingDirectory.drive.rename'),+ onClick: () => renameFolder(entry),+ },+ {+ danger: true,+ icon: <Icon icon={Trash2Icon} />,+ key: 'delete',+ label: t('workingDirectory.drive.delete'),+ onClick: () => deleteFolder(entry),+ },+ ]}+ >+ <ActionIcon+ aria-label={t('workingDirectory.drive.moreActions')}+ icon={MoreHorizontalIcon}+ size={'small'}+ />+ </DropdownMenu>+ </span>+ );++ return {+ createFolder: async (parentPath, name) => {+ const path = joinDrivePath(parentPath, name);+ await sandboxStorageService.createDirectory({ drive, path });++ return { path };+ },+ displayPath: displayDrivePath,+ editablePath: false,+ folderErrorKey: (error) => {+ const code = (error as { message?: string })?.message;+ if (code === 'FOLDER_NOT_EMPTY') return 'workingDirectory.drive.folderNotEmpty';+ },+ listErrorKey: 'workingDirectory.drive.foldersLoadFailed',+ selectBlockedReason: (path) =>+ isSharedDrive && !path ? t('workingDirectory.drive.rootNotAllowed') : undefined,+ useListing: (path?: string): DirectoryListing => {+ const listingPath = path ?? '';++ const folders = useSWR(+ [FOLDERS_KEY, workspaceId ?? '', drive, listingPath],+ () => sandboxStorageService.listFiles({ drive, path: listingPath || undefined }),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ const entries: DirectoryEntry[] = (folders.data?.entries ?? [])+ .filter((entry) => entry.isDirectory)+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((entry) => ({+ actions: folderActions(entry),+ name: entry.name,+ path: entry.path,+ ...(entry.isGitRepository && {+ icon: FolderGit2Icon,+ tags: <Tag size={'small'}>{t('workingDirectory.drive.gitRepository')}</Tag>,+ }),+ }));++ return {+ directory: folders.data+ ? { parentPath: driveParentPath(listingPath), path: listingPath }+ : undefined,+ entries: folders.error ? [] : entries,+ error: folders.error,+ hasMore: false,+ isLoading: folders.isLoading,+ isLoadingMore: false,+ isRefreshing: folders.isValidating && !folders.isLoading,+ loadMore: () => {},+ refresh: async () => {+ await folders.mutate();+ },+ retry: () => void folders.mutate(),+ };+ },+ } satisfies DirectorySource;+ }, [drive, globalMutate, isWorkspace, t, workspaceId]);+};diff --git a/src/features/WorkingDirectory/useCreateFolder.test.ts b/src/features/WorkingDirectory/useCreateFolder.test.tsindex aa6ba8b5926..1cf8ecf4e0d 100644--- a/src/features/WorkingDirectory/useCreateFolder.test.ts+++ b/src/features/WorkingDirectory/useCreateFolder.test.ts@@ -16,7 +16,9 @@ vi.mock('react-i18next', () => ({const setup = (parentPath = '/home/me') => {const onCreated = vi.fn();- const hook = renderHook(() => useCreateFolder({ deviceId: 'device', onCreated, parentPath }));+ const create = (parentPath: string, name: string) =>+ deviceService.createDirectory({ deviceId: 'device', name, parentPath });+ const hook = renderHook(() => useCreateFolder({ create, onCreated, parentPath }));const submitName = async (name: string) => {act(() => hook.result.current.setName(name));await act(() => hook.result.current.submit());diff --git a/src/features/WorkingDirectory/useCreateFolder.ts b/src/features/WorkingDirectory/useCreateFolder.tsindex b414c30c30c..f9ae3e4dfe8 100644--- a/src/features/WorkingDirectory/useCreateFolder.ts+++ b/src/features/WorkingDirectory/useCreateFolder.ts@@ -3,8 +3,6 @@ import { toast } from '@lobehub/ui';import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { deviceService } from '@/services/device';-export { isValidDirectoryName as isValidFolderName } from '@lobechat/utils/directoryName';const ERROR_MESSAGE_KEYS = {@@ -22,13 +20,21 @@ const getErrorMessageKey = (error: unknown) => {};interface UseCreateFolderOptions {- deviceId: string;+ /** Makes the folder wherever the picker is browsing โ a device, or the drive. */+ create: (parentPath: string, name: string) => Promise<{ path: string }>;+ /** A source's own reading of an error it threw; the generic one otherwise. */+ errorMessageKey?: (error: unknown) => string | undefined;onCreated: (path: string) => void;parentPath: string;}/** Name + create one folder inside the folder a remote picker is browsing. */-export const useCreateFolder = ({ deviceId, onCreated, parentPath }: UseCreateFolderOptions) => {+export const useCreateFolder = ({+ create,+ errorMessageKey,+ onCreated,+ parentPath,+}: UseCreateFolderOptions) => {const { t } = useTranslation('device');const mounted = useRef(false);useEffect(() => {@@ -64,12 +70,12 @@ export const useCreateFolder = ({ deviceId, onCreated, parentPath }: UseCreateFosetError(undefined);setPending(true);try {- const result = await deviceService.createDirectory({ deviceId, name: next, parentPath });+ const result = await create(parentPath, next);if (mounted.current) onCreated(result.path);else toast.success(t('workingDirectory.newFolderCreated', { path: result.path }));} catch (cause) {console.error('Failed to create folder', cause);- const message = t(getErrorMessageKey(cause));+ const message = t((errorMessageKey?.(cause) ?? getErrorMessageKey(cause)) as any);if (mounted.current) setError(message);else toast.error(message);} finally {diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.tsindex 575dd30fbf0..c8792d5c33e 100644--- a/src/features/Workspace/workspaceAwarePath.ts+++ b/src/features/Workspace/workspaceAwarePath.ts@@ -53,6 +53,7 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set(['creds','credits','devices',+ 'drive','environments','general','hotkey',diff --git a/src/features/WorkspaceSetting/Layout.tsx b/src/features/WorkspaceSetting/Layout.tsxindex 522b45e8701..eb00624fcd3 100644--- a/src/features/WorkspaceSetting/Layout.tsx+++ b/src/features/WorkspaceSetting/Layout.tsx@@ -24,6 +24,7 @@ const COMPACT_HEADER_TABS = new Set<string>([WorkspaceSettingsTabs.Creds,WorkspaceSettingsTabs.Credits,WorkspaceSettingsTabs.Devices,+ WorkspaceSettingsTabs.Drive,WorkspaceSettingsTabs.Environments,WorkspaceSettingsTabs.General,WorkspaceSettingsTabs.Hotkey,diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsxindex 05fd27c01fb..e049c215e5b 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx@@ -16,6 +16,7 @@ import {EllipsisIcon,FlaskConical,HandCoins,+ HardDriveIcon,Info,KeyboardIcon,KeyIcon,@@ -78,8 +79,6 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =const { allowed: canCreateContent } = usePermission('create_content');const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);const enableIntegrations = useUserStore(labPreferSelectors.enableIntegrations);- // Behind the same experiment that gates the persistent sandbox itself: a tab- // for environments nothing can run in would be a dead end.const enablePersistentSandbox = useUserStore(labPreferSelectors.enablePersistentSandbox);const { hideDocs } = useServerConfigStore(featureFlagsSelectors);const [avatar, username] = useUserStore((s) => [@@ -178,11 +177,20 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Devices,label: t('tab.devices'),},- enablePersistentSandbox && {+ // Always there: a code environment is a definition, written down before+ // anything runs it, and useful with or without a drive to run it on.+ {icon: ContainerIcon,key: WorkspaceSettingsTabs.Environments,label: t('tab.environments'),},+ // The public drive and the member's own, with the pool's usage โ+ // behind the same lab switch as the composer's folder picker.+ enablePersistentSandbox && {+ icon: HardDriveIcon,+ key: WorkspaceSettingsTabs.Drive,+ label: t('tab.drive'),+ },{icon: BellIcon,key: WorkspaceSettingsTabs.Notification,diff --git a/src/hooks/useSandboxDriveEntitlement.ts b/src/hooks/useSandboxDriveEntitlement.tsnew file mode 100644index 00000000000..824c3f0ed00--- /dev/null+++ b/src/hooks/useSandboxDriveEntitlement.ts@@ -0,0 +1,35 @@+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';++/**+ * Whether this account has a network drive in the active workspace โ the one+ * thing persistence in the cloud sandbox needs, and the one thing environment+ * definitions do not.+ *+ * Asked of the server rather than derived from a plan: the entitlement is+ * resolved and signed server-side, and asking is the only way to see the same+ * answer a sandbox run will act on. Keyed by workspace, because the server+ * resolves it from the active one โ a single key would hand the previous+ * workspace's answer to the next one until a reload.+ *+ * `entitled` stays `undefined` until the answer arrives, so a caller can show+ * nothing rather than flash an upgrade prompt at an entitled account.+ */+export const useSandboxDriveEntitlement = (enabled = true) => {+ // The replica entry the composer chip and the environments page read, so a+ // reload paints the storage page from the last answer and every surface+ // agrees on it.+ const { error, isHydrated, isValidating, revalidate } = sandboxActions.useFetchEntitlement(enabled, {+ revalidateOnFocus: false,+ });+ const data = useSandboxStore(sandboxSelectors.entitlement);++ return {+ entitled: data?.entitled,+ error: error as Error | undefined,+ // Loading only until there is something to show: a cached answer paints+ // at once and the revalidation behind it never blanks the page.+ isLoading: data === undefined && (!isHydrated || isValidating),+ quotaBytes: data?.quotaBytes ?? null,+ retry: () => void revalidate(),+ };+};diff --git a/src/routes/(main)/[workspaceSlug]/settings/drive/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/drive/index.tsxnew file mode 100644index 00000000000..24180ccc1b9--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/drive/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/SandboxDrive';diff --git a/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsxindex 3d217f0729a..28309d5bf0e 100644--- a/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx+++ b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next';import { MAX_WIDTH } from '@/const/layoutTokens';import EnvironmentManager from '@/features/EnvironmentManager';-import EnvironmentsGate from '@/features/EnvironmentManager/EnvironmentsGate';/*** The workspace's environments, in two pools behind tabs โ the same split the@@ -30,33 +29,31 @@ const WorkspaceEnvironmentsSetting = memo(() => {return (<Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>- <EnvironmentsGate>- {/* Keyed on the pool so the selected row and its open panel do not+ {/* Keyed on the pool so the selected row and its open panel do notsurvive a tab switch โ the environment they pointed at is not inthe list any more. */}- <EnvironmentManager- key={visibility}- visibility={visibility}- tabs={- <Tabs- activeKey={visibility}- items={[- {- icon: <Icon icon={UsersIcon} />,- key: 'public',- label: t('environments.visibility.tabs.workspace'),- },- {- icon: <Icon icon={LockIcon} />,- key: 'private',- label: t('environments.visibility.tabs.private'),- },- ]}- onChange={(key) => setVisibility(key as EnvironmentVisibility)}- />- }- />- </EnvironmentsGate>+ <EnvironmentManager+ key={visibility}+ visibility={visibility}+ tabs={+ <Tabs+ activeKey={visibility}+ items={[+ {+ icon: <Icon icon={UsersIcon} />,+ key: 'public',+ label: t('environments.visibility.tabs.workspace'),+ },+ {+ icon: <Icon icon={LockIcon} />,+ key: 'private',+ label: t('environments.visibility.tabs.private'),+ },+ ]}+ onChange={(key) => setVisibility(key as EnvironmentVisibility)}+ />+ }+ /></Flexbox>);});diff --git a/src/services/environment.ts b/src/services/environment.tsnew file mode 100644index 00000000000..1f901d61c5a--- /dev/null+++ b/src/services/environment.ts@@ -0,0 +1,96 @@+import type { EnvironmentKind, EnvironmentSource, EnvironmentVisibility } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++/**+ * The part of a specification this API accepts today, and deliberately narrower+ * than `EnvironmentConfiguration`.+ *+ * `sources` is git-only because every other transport authenticates with a key,+ * and a specification documented as carrying no credentials cannot present one.+ * `requirements` is absent because nothing schedules on it yet โ the server+ * would drop it without a word, and a field the types refuse is better than one+ * that quietly evaporates.+ */+export interface SandboxEnvironmentSpecification {+ bootstrapCommand?: string;+ env?: Record<string, string>;+ excludePaths?: string[];+ internetAccess?: boolean;+ kind?: EnvironmentKind;+ maintenanceCommand?: string;+ sources?: Extract<EnvironmentSource, { kind: 'git' }>[];+}++/** A new environment's specification: `code` only โ `files` survives on old rows and is never created. */+export type NewEnvironmentSpecification = Omit<SandboxEnvironmentSpecification, 'kind'> & {+ kind?: 'code';+};++/**+ * Renderer-side data layer for code environments: the definitions a folder+ * can be initialized from. Answered from the database alone and available+ * without a drive โ what is built from a definition lives on the drive and+ * goes through `sandboxStorageService`.+ */+class EnvironmentService {+ listEnvironments = async (params?: { visibility?: EnvironmentVisibility }) =>+ lambdaClient.environment.listEnvironments.query(params);++ /** The definition alone; a conversation applies it to its working directory. */+ createEnvironment = async (params: {+ configuration?: NewEnvironmentSpecification;+ description?: string;+ name: string;+ visibility?: EnvironmentVisibility;+ }) => lambdaClient.environment.createEnvironment.mutate(params);++ /**+ * Edits the specification. A folder it was already applied to keeps what it+ * has; the change shapes the next working directory it initializes.+ */+ updateEnvironment = async (params: {+ configuration?: SandboxEnvironmentSpecification;+ description?: string;+ id: string;+ name?: string;+ }) => lambdaClient.environment.updateEnvironment.mutate(params);++ /**+ * Publishes an environment to the workspace, or takes it back.+ *+ * Separate from {@link updateEnvironment} because it changes who else can run+ * in what this environment built, not what the environment is.+ */+ setEnvironmentVisibility = async (params: { id: string; visibility: EnvironmentVisibility }) =>+ lambdaClient.environment.setEnvironmentVisibility.mutate(params);++ /**+ * The definition alone, when nothing was ever built from it. One that still+ * has copies from before environments became initializers is removed with+ * them through the drive route, which can reach their snapshots โ the page+ * has no other way to delete a copy.+ */+ removeEnvironment = async (params: { id: string }) => {+ try {+ return await lambdaClient.environment.removeEnvironment.mutate(params);+ } catch (error) {+ if ((error as { message?: string })?.message !== 'ENVIRONMENT_HAS_INSTANCES') throw error;++ return lambdaClient.sandboxStorage.removeEnvironment.mutate(params);+ }+ };++ /**+ * Repositories this account can build an environment from. Answers+ * `connected: false` rather than failing when GitHub is not linked โ for the+ * picker that is a state to resolve, not an error.+ */+ listGithubRepositories = async () => lambdaClient.environment.listGithubRepositories.query();++ /** The branches of one repository, or `connected: false` when GitHub is not linked. */+ listGithubBranches = async (params: { owner: string; repository: string }) =>+ lambdaClient.environment.listGithubBranches.query(params);+}++export const environmentService = new EnvironmentService();diff --git a/src/services/projectFile.ts b/src/services/projectFile.tsindex b0f58905e7c..6fd32f391b1 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -163,7 +163,9 @@ class ProjectFileService {topicId?: string;}): Promise<ProjectFileIndexResult | undefined> {const [workspace, listing] = await Promise.all([- sandboxStorageService.getStorage(),+ // Rooted on the drive the conversation's folder is on, which the+ // topic names.+ sandboxStorageService.getStorage({ topicId }),// The topic still travels: it names the warm session the read can go// through, and is what lets a listing be refreshed before it is served.// The instance is the address; the topic is the route.diff --git a/src/services/sandboxStorage.ts b/src/services/sandboxStorage.tsindex 45d14560a7d..2adf4d1e050 100644--- a/src/services/sandboxStorage.ts+++ b/src/services/sandboxStorage.ts@@ -1,93 +1,44 @@-import type { EnvironmentKind, EnvironmentSource, EnvironmentVisibility } from '@lobechat/types';+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import { markDefaultInstances } from '@lobechat/utils/environmentInstance';import { lambdaClient } from '@/libs/trpc/client';+export type { SandboxDrive };+/**- * Renderer-side data layer for the persistent cloud-sandbox workspace.+ * Renderer-side data layer for the user's network drives and the environment+ * directories initialized on them.+ *+ * `drive` names which of a workspace's drives a call means โ `public`, shared+ * by every member, or `personal`, the caller's own โ and defaults to the+ * public one there; a personal account has one drive and ignores it. A call+ * about an environment directory goes to the drive that directory is on.*- * Every path is relative to the workspace root (`reports/q3.md`); the absolute+ * Every path is relative to the drive's root (`reports/q3.md`); the absolute* mount path stays server-side, so there is nothing here for a caller to point- * outside the workspace with.+ * outside the drive with.*- * `topicId` is an optimization, not a scope: the workspace belongs to the user,- * not the topic, but the volume is only reachable from inside a sandbox- * session, so naming the topic the user is already talking to reuses that warm- * session instead of cold-starting a second sandbox to list a directory.- */-/**- * The part of a specification this API accepts today, and deliberately narrower- * than `EnvironmentConfiguration`.+ * `topicId` is an optimization, not a scope: the drive belongs to the user (or+ * the team), not the topic, but some calls are only reachable from inside a+ * sandbox session, so naming the topic the user is already talking to reuses+ * that warm session instead of cold-starting a second sandbox.*- * `sources` is git-only because every other transport authenticates with a key,- * and a specification documented as carrying no credentials cannot present one.- * `requirements` is absent because nothing schedules on it yet โ the server- * would drop it without a word, and a field the types refuse is better than one- * that quietly evaporates.+ * The definitions environments are built from need no drive and live in+ * `environmentService`.*/-export interface SandboxEnvironmentSpecification {- bootstrapCommand?: string;- env?: Record<string, string>;- excludePaths?: string[];- internetAccess?: boolean;- kind?: EnvironmentKind;- maintenanceCommand?: string;- sources?: Extract<EnvironmentSource, { kind: 'git' }>[];-}-class SandboxStorageService {- /**- * Environment specifications: what an environment should contain. Answered- * from the database alone, so this returns immediately.- */- listEnvironments = async (params?: { visibility?: EnvironmentVisibility }) =>- lambdaClient.sandboxStorage.listEnvironments.query(params);-- createEnvironment = async (params: {- configuration?: SandboxEnvironmentSpecification;- description?: string;- name: string;- visibility?: EnvironmentVisibility;- }) =>- // Always with its default instance: this client has no create-instance- // dialog to follow with. The server leaves it out for clients that do.- lambdaClient.sandboxStorage.createEnvironment.mutate({ ...params, withDefaultInstance: true });-- /**- * Edits the specification. Existing instances keep the one they were created- * with; the change shapes what the next instance is built from.- */- updateEnvironment = async (params: {- configuration?: SandboxEnvironmentSpecification;- description?: string;- id: string;- name?: string;- }) => lambdaClient.sandboxStorage.updateEnvironment.mutate(params);-- /**- * Publishes an environment to the workspace, or takes it back.- *- * Separate from {@link updateEnvironment} because it changes who else can run- * in what this environment built, not what the environment is.- */- setEnvironmentVisibility = async (params: { id: string; visibility: EnvironmentVisibility }) =>- lambdaClient.sandboxStorage.setEnvironmentVisibility.mutate(params);-/*** Replaces a file's whole contents, creating it and its parents if needed.* Text only โ the execution plane carries the body as a JSON string.*/writeFile = async (params: {content: string;+ drive?: SandboxDrive;instanceId?: string;path: string;topicId?: string;}) => lambdaClient.sandboxStorage.writeFile.mutate(params);- /** Refused while instances still reference it โ those go first. */- removeEnvironment = async (params: { id: string }) =>- lambdaClient.sandboxStorage.removeEnvironment.mutate(params);-/*** Instances, each joined with the state the execution plane holds. A* brand-new instance has no snapshot yet โ that is normal, not an error, and@@ -100,7 +51,12 @@ class SandboxStorageService {* guard applies, so no caller has to re-derive which copy is the default.*/listInstances = async (- params: { environmentId?: string; topicId?: string; withSizes?: boolean } = {},+ params: {+ drive?: SandboxDrive;+ environmentId?: string;+ topicId?: string;+ withSizes?: boolean;+ } = {},) => {const result = await lambdaClient.sandboxStorage.listInstances.query(params);@@ -179,46 +135,66 @@ class SandboxStorageService {stopInstance = async (params: { id: string }) =>lambdaClient.sandboxStorage.stopInstance.mutate(params);+ /** Rename or move a file or folder; never overwrites an existing one. */+ renameFile = async (params: {+ drive?: SandboxDrive;+ newPath: string;+ path: string;+ topicId?: string;+ }) => lambdaClient.sandboxStorage.renameFile.mutate(params);+/** Create a directory (parents included, idempotent). */- createDirectory = async (params: { instanceId?: string; path: string; topicId?: string }) =>- lambdaClient.sandboxStorage.createDirectory.mutate(params);+ createDirectory = async (params: {+ drive?: SandboxDrive;+ instanceId?: string;+ path: string;+ topicId?: string;+ }) => lambdaClient.sandboxStorage.createDirectory.mutate(params);/**- * Whether this account has a persistent workspace at all. Pair it with the- * `enablePersistentSandbox` lab flag the client already holds: flag off shows- * nothing, flag on without an entitlement shows the upgrade prompt.+ * Whether this account has a drive at all. Without one, the directory+ * picker's sandbox side shows the way to a plan instead of folders.*/getEntitlement = async () => lambdaClient.sandboxStorage.getEntitlement.query();- /** Quota and last measured usage of the workspace directory. */- getStorage = async () => lambdaClient.sandboxStorage.getStorage.query();+ /** Quota and last measured usage of one drive. */+ getStorage = async (params: { drive?: SandboxDrive; topicId?: string } = {}) =>+ lambdaClient.sandboxStorage.getStorage.query(params);++ /**+ * Usage of each of the caller's drives against the plan's one quota pool โ+ * and, for a workspace owner or admin, of every member's personal drive.+ * Amounts only; nobody can browse another member's drive.+ */+ getDriveUsage = async () => lambdaClient.sandboxStorage.getDriveUsage.query();/*** Walk the workspace and answer with the fresh figure. For a refresh the* user asked for โ {@link getStorage} reads what was last measured, which* is what a page load should show.*/- refreshStorageUsage = async () => lambdaClient.sandboxStorage.refreshStorageUsage.mutate();+ refreshStorageUsage = async (params: { drive?: SandboxDrive } = {}) =>+ lambdaClient.sandboxStorage.refreshStorageUsage.mutate(params);listFiles = async (- params: { instanceId?: string; path?: string; recursive?: boolean; topicId?: string } = {},+ params: {+ drive?: SandboxDrive;+ instanceId?: string;+ path?: string;+ recursive?: boolean;+ topicId?: string;+ } = {},) => lambdaClient.sandboxStorage.listFiles.query(params);- /**- * Repositories this account can build an environment from. Answers- * `connected: false` rather than failing when GitHub is not linked โ for the- * picker that is a state to resolve, not an error.- */- listGithubRepositories = async () => lambdaClient.sandboxStorage.listGithubRepositories.query();-- /** The branches of one repository, or `connected: false` when GitHub is not linked. */- listGithubBranches = async (params: { owner: string; repository: string }) =>- lambdaClient.sandboxStorage.listGithubBranches.query(params);-- readFile = async (params: { instanceId?: string; path: string; topicId?: string }) =>- lambdaClient.sandboxStorage.readFile.query(params);+ readFile = async (params: {+ drive?: SandboxDrive;+ instanceId?: string;+ path: string;+ topicId?: string;+ }) => lambdaClient.sandboxStorage.readFile.query(params);removeFile = async (params: {+ drive?: SandboxDrive;instanceId?: string;path: string;recursive?: boolean;diff --git a/src/spa/router/workspaceSettingsRoutes.tsx b/src/spa/router/workspaceSettingsRoutes.tsxindex 8b5e2b7f10f..f6a9c1a83a0 100644--- a/src/spa/router/workspaceSettingsRoutes.tsx+++ b/src/spa/router/workspaceSettingsRoutes.tsx@@ -224,6 +224,14 @@ export const workspaceSettingsContentRoute: RouteObject = {handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },path: 'environments',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/drive'),+ 'Desktop > Workspace > Settings > Drive',+ ),+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },+ path: 'drive',+ },// Account-level tabs mirrored inside the workspace so members can// adjust user settings without leaving the workspace. Same pages// as personal `/settings/*`; only the chrome is workspace-owned.diff --git a/src/store/chat/pendingSandboxSelection.test.ts b/src/store/chat/pendingSandboxSelection.test.tsindex 88642fdf6b1..d25b31f1f01 100644--- a/src/store/chat/pendingSandboxSelection.test.ts+++ b/src/store/chat/pendingSandboxSelection.test.ts@@ -5,6 +5,7 @@ import {getPendingSandboxSelection,setPendingSandboxSelection,subscribePendingSandboxSelection,+ toSandboxTopicMetadata,} from './pendingSandboxSelection';describe('pendingSandboxSelection', () => {@@ -34,4 +35,20 @@ describe('pendingSandboxSelection', () => {expect(getPendingSandboxSelection('agent-2')).toBe(getPendingSandboxSelection('agent-2'));consumePendingSandboxSelection('agent-2');});++ it('carries the environment into the new topic beside the folder it was picked with', () => {+ expect(+ toSandboxTopicMetadata({+ drive: 'personal',+ environmentId: 'env_1',+ mode: 'persistent',+ workingDirectory: 'app',+ }),+ ).toMatchObject({+ sandboxDrive: 'personal',+ sandboxEnvironmentId: 'env_1',+ sandboxWorkingDirectory: 'app',+ });+ expect(toSandboxTopicMetadata(undefined)).toBeUndefined();+ });});diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.tsindex 4ed8291aadf..d902f681cb0 100644--- a/src/store/chat/pendingSandboxSelection.ts+++ b/src/store/chat/pendingSandboxSelection.ts@@ -1,4 +1,6 @@-import type { SandboxSelection } from '@/features/ChatInput/ControlBar/SandboxInstancePicker';+import type { ChatTopicMetadata } from '@lobechat/types';++import type { SandboxSelection } from '@/features/ChatInput/ControlBar/useSandboxPlacement';/*** Module-level singleton for a sandbox selection made before the topic exists.@@ -11,7 +13,7 @@ import type { SandboxSelection } from '@/features/ChatInput/ControlBar/SandboxIn** Deliberately not the agent's `agencyConfig`, which is where the device picker* keeps its equivalent pre-topic choice. That row is shared by every member of a- * workspace agent, while an instance belongs to one member โ writing it there+ * workspace agent, while a folder choice belongs to one member โ writing it there* would point other members at storage that is not theirs.** Deliberately not persisted either: this is a choice about the conversation@@ -66,3 +68,14 @@ export const consumePendingSandboxSelection = (agentId: string): SandboxSelectioemit();return selection;};++/** The topic metadata a pending selection becomes when the topic is created with it. */+export const toSandboxTopicMetadata = (+ selection: SandboxSelection | undefined,+): ChatTopicMetadata | undefined =>+ selection && {+ sandboxDrive: selection.drive,+ sandboxEnvironmentId: selection.environmentId,+ sandboxInstanceId: selection.instanceId,+ sandboxWorkingDirectory: selection.workingDirectory,+ };diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 133c20c117e..6646b3ba670 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -66,7 +66,10 @@ import {chatConfigByIdSelectors,} from '@/store/agent/selectors';import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';-import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';+import {+ getPendingSandboxSelection,+ toSandboxTopicMetadata,+} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import {dbMessageSelectors,@@ -1307,12 +1310,7 @@ export class ConversationLifecycleActionImpl {willCreateNewTopic && operationContext.agentId? getPendingSandboxSelection(operationContext.agentId): undefined;- const sandboxInstanceMetadata: ChatTopicMetadata | undefined = pendingSandboxSelection- ? {- sandboxInstanceId: pendingSandboxSelection.instanceId,- sandboxMode: pendingSandboxSelection.mode,- }- : undefined;+ const sandboxInstanceMetadata = toSandboxTopicMetadata(pendingSandboxSelection);/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */const optimisticTopicMetadata =newTopicReasoningSnapshot || sandboxInstanceMetadatadiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 932c9d18586..12d468e222f 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -42,6 +42,7 @@ import { chatConfigByIdSelectors } from '@/store/agent/selectors';import {consumePendingSandboxSelection,getPendingSandboxSelection,+ toSandboxTopicMetadata,} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';@@ -1028,12 +1029,7 @@ export class GatewayActionImpl {isCreateNewTopic && executionContext.agentId? getPendingSandboxSelection(executionContext.agentId): undefined;- const sandboxTopicMetadata = pendingSandboxSelection- ? {- sandboxInstanceId: pendingSandboxSelection.instanceId,- sandboxMode: pendingSandboxSelection.mode,- }- : undefined;+ const sandboxTopicMetadata = toSandboxTopicMetadata(pendingSandboxSelection);const cwdTopicMetadata =pendingRepos.length > 0? {diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 47c4c0c9be6..062e10544a2 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -77,6 +77,8 @@ export enum SettingsTabs {Credits = 'credits',Creds = 'credential',Devices = 'devices',+ /** The cloud sandbox's network drives โ labelled โStorageโ; `storage` is local data. */+ Drive = 'drive',Environments = 'environments',Hotkey = 'hotkey',/** @deprecated Use ServiceModel instead */diff --git a/src/store/sandbox/privateAction.ts b/src/store/sandbox/privateAction.tsindex 1c718e0bf3c..36e2d4a4289 100644--- a/src/store/sandbox/privateAction.ts+++ b/src/store/sandbox/privateAction.ts@@ -1,4 +1,5 @@import { createReplicaSlice, recordLens } from '@/libs/replica';+import { environmentService } from '@/services/environment';import { sandboxStorageService } from '@/services/sandboxStorage';import type { StoreSetter } from '@/store/types';@@ -56,7 +57,7 @@ export class SandboxPrivateAction {this.environments = createReplicaSlice(sandboxEnvironmentsResource, {actionPrefix: 'sandboxEnvironments',fetcher: async () => {- const { environments } = await sandboxStorageService.listEnvironments();+ const { environments } = await environmentService.listEnvironments();return environments.map(toPickerEnvironment);},get,diff --git a/src/store/sandbox/projection.ts b/src/store/sandbox/projection.tsindex 25bb0101c14..3c0262283cc 100644--- a/src/store/sandbox/projection.ts+++ b/src/store/sandbox/projection.ts@@ -1,10 +1,11 @@-import { type EnvironmentKind, environmentKind } from '@lobechat/types';+import type { EnvironmentKind } from '@lobechat/types';import { defineReplica } from '@/libs/replica';+import type { environmentService } from '@/services/environment';import type { sandboxStorageService } from '@/services/sandboxStorage';type RawEnvironment = Awaited<- ReturnType<typeof sandboxStorageService.listEnvironments>+ ReturnType<typeof environmentService.listEnvironments>>['environments'][number];type RawInstance = Awaited<ReturnType<typeof sandboxStorageService.listInstances>@@ -56,7 +57,9 @@ export interface SandboxPickerEnvironment {export const toPickerEnvironment = (environment: RawEnvironment): SandboxPickerEnvironment => ({id: environment.id,- kind: environmentKind(environment),+ // Every environment is a code environment now; the field stays so the+ // picker's shape does not change under the persisted replica rows.+ kind: 'code',name: environment.name,userId: environment.userId,visibility: environment.visibility,diff --git a/src/store/sandbox/replica.test.ts b/src/store/sandbox/replica.test.tsindex 30d94a902ee..9ea1504370f 100644--- a/src/store/sandbox/replica.test.ts+++ b/src/store/sandbox/replica.test.ts@@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope, readReplicaStoredKeys } from '@/libs/replica';import { setScopedMutate } from '@/libs/swr/mutate';+import { environmentService } from '@/services/environment';import { sandboxStorageService } from '@/services/sandboxStorage';import { sandboxActions } from './action';@@ -47,7 +48,7 @@ const wrapper = ({ children }: PropsWithChildren) =>/** Never-resolving fetch: what the store holds can only have come from storage. */const pending = () => new Promise<never>(() => {});-type ListedEnvironments = Awaited<ReturnType<typeof sandboxStorageService.listEnvironments>>;+type ListedEnvironments = Awaited<ReturnType<typeof environmentService.listEnvironments>>;type ListedInstances = Awaited<ReturnType<typeof sandboxStorageService.listInstances>>;type InstanceDetail = Awaited<ReturnType<typeof sandboxStorageService.getInstance>>;@@ -178,7 +179,7 @@ describe('sandbox replicas', () => {{ data: { workingDirectory: 'lobehub-main' }, updatedAt: 1 },);vi.spyOn(sandboxStorageService, 'getEntitlement').mockImplementation(pending);- vi.spyOn(sandboxStorageService, 'listEnvironments').mockImplementation(pending);+ vi.spyOn(environmentService, 'listEnvironments').mockImplementation(pending);vi.spyOn(sandboxStorageService, 'listInstances').mockImplementation(pending);vi.spyOn(sandboxStorageService, 'getInstance').mockImplementation(pending);@@ -205,7 +206,7 @@ describe('sandbox replicas', () => {});it('persists only the slim projections: no configuration, env, source URL or build log', async () => {- vi.spyOn(sandboxStorageService, 'listEnvironments').mockResolvedValue({+ vi.spyOn(environmentService, 'listEnvironments').mockResolvedValue({environments: [rawEnvironment],} as unknown as ListedEnvironments);vi.spyOn(sandboxStorageService, 'listInstances').mockResolvedValue(listed(rawInstance()));diff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.tsindex 846158e84f7..6cfc838f7ea 100644--- a/src/types/workspaceSettings.ts+++ b/src/types/workspaceSettings.ts@@ -18,6 +18,7 @@ export enum WorkspaceSettingsTabs {Credits = 'credits',Creds = 'credential',Devices = 'devices',+ Drive = 'drive',Environments = 'environments',General = 'general',Hotkey = 'hotkey',