๐คฏ 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): a persistent working directory, and environments to define it (#19783)
Rdmclin21293e9e450d3
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 684c8e729e4..08f512be60d 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -8,6 +8,11 @@ import type {CopyAssetForPublishResult,ExternalAssetForPublishParams,ExternalAssetForPublishResult,+ // The DEVICE's index shape, not the renderer's. The renderer union also+ // covers the cloud sandbox as a source, which nothing on a machine produces,+ // so declaring that wider type here would over-claim what this returns โ and+ // the gateway handler bag, typed by what a device sends, would reject it.+ ProjectFileIndexResult as DeviceProjectFileIndexResult,SkillDirectoryDeps,} from '@lobechat/device-control';import {@@ -51,7 +56,6 @@ import {type ProjectDirectoryListParams,type ProjectDirectoryListResult,type ProjectFileIndexParams,- type ProjectFileIndexResult,type ProjectFileSearchParams,type ProjectFileSearchResult,type RenameLocalFileResult,@@ -841,7 +845,9 @@ export default class LocalFileCtr extends ControllerModule {// ==================== Search & Find ====================@IpcMethod()- async getProjectFileIndex(params: ProjectFileIndexParams = {}): Promise<ProjectFileIndexResult> {+ async getProjectFileIndex(+ params: ProjectFileIndexParams = {},+ ): Promise<DeviceProjectFileIndexResult> {const startedAt = Date.now();const result = await defaultGetProjectFileIndex(params);diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.test.tsindex 513924322cc..1c29a7703c6 100644--- a/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/BrowserControlCtr.test.ts@@ -19,6 +19,9 @@ const createGuest = (capturePage: ReturnType<typeof vi.fn>) => ({capturePage,executeJavaScript: vi.fn().mockResolvedValue(undefined),isDestroyed: () => false,+ // Scripts run against the main frame, not the WebContents โ the latter+ // defers until loading stops, which on a never-settling page is never.+ mainFrame: { executeJavaScript: vi.fn().mockResolvedValue(undefined) },});describe('BrowserControlCtr.screenshot', () => {diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex 44d92af5045..ade958553b7 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -188,6 +188,46 @@ describe('serverMessagesEngine', () => {expect(result[0].content).toBe(systemRole + '\n\n' + getCurrentDateContent());});+ it('renders the cloud-sandbox workspace placeholders to the ephemeral wording unless the builder supplies them', async () => {+ const messages = createBasicMessages();+ const systemRole =+ '<env>{{sandbox_workspace}}</env><session>{{sandbox_session_files}}</session>';++ // No additionalVariables โ the run got no persistent workspace: the+ // original ephemeral-session wording must render, never the literal tokens.+ const { messages: fallback } = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole,+ });+ expect(fallback[0].content).not.toContain('{{sandbox_workspace}}');+ expect(fallback[0].content).not.toContain('{{sandbox_session_files}}');+ expect(fallback[0].content).toContain(+ 'Files created here are temporary and session-specific',+ );+ expect(fallback[0].content).toContain('Files from previous sessions may not persist');++ // The builder's persistent-workspace guidance overrides both fallbacks.+ const { messages: resolved } = await serverMessagesEngine({+ additionalVariables: {+ sandbox_session_files: '- Files in your working directory persist',+ sandbox_workspace: '- Your working directory is a persistent workspace',+ },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole,+ });+ expect(resolved[0].content).toContain(+ '<env>- Your working directory is a persistent workspace</env>',+ );+ expect(resolved[0].content).toContain(+ '<session>- Files in your working directory persist</session>',+ );+ expect(resolved[0].content).not.toContain('temporary and session-specific');+ });+it('renders {{workingDirectory}} to a fallback instead of leaking the literal ', async () => {const messages = createBasicMessages();const systemRole = '<working-directory>{{workingDirectory}}</working-directory>';diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex 04f3dffb2f2..b9fb42ebf52 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -29,6 +29,7 @@ import { buildPostProcessUrl, log } from '@/server/modules/AgentRuntime/executorimport { AgentDocumentsService } from '@/server/services/agentDocuments';import { MarketService } from '@/server/services/market';import { OnboardingService } from '@/server/services/onboarding';+import { resolveSandboxSessionConfig } from '@/server/services/sandbox';import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';export interface ServerContextFactSource {@@ -331,6 +332,28 @@ export const createServerContextFactProviders = ({listSandboxFiles: async (topicId) =>new FileModel(db, userId).findFilesToInitInSandbox(topicId),+ // Resolved from the same inputs the cloud-sandbox runtime uses, so the model+ // is never told its files persist while its tools write to a directory that+ // does not โ or the reverse. Keyed on `ctx.workspaceId` for the same reason+ // the runtime is: that is the workspace the trust token carries, and the+ // entitlement has to agree with the token that presents it.+ resolveSandboxPersistence: async () => {+ const { mode, cwd, claim, workingDir } = await resolveSandboxSessionConfig({+ isShareVisitorRun: Boolean(ctx.agentShareVisitor),+ serverDB: db,+ topicId: ctx.topicId ?? state.origin?.topicId,+ userId,+ // The run's workspace, the same one every other fact here is scoped to.+ // Reading the raw context instead looked the topic up in the personal+ // scope on any path that does not carry the id, found nothing, and+ // described a disposable sandbox to a run that had a persistent one โ+ // so the model was told its files would not survive and worked in /tmp.+ workspaceId,+ });++ return claim ? { cwd, mode, workingDir } : undefined;+ },+listTopicMessages: async (topic) => {const messages = await new MessageModel(db, userId, ctx.workspaceId).query({diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.tsindex 8995de0cf88..8912b53c799 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts@@ -23,6 +23,14 @@ const {pluginQuery: vi.fn(),}));+const mockResolveSandboxSessionConfig = vi.hoisted(() =>+ vi.fn(async () => ({ claim: null, mode: 'ephemeral' as const })),+);++vi.mock('@/server/services/sandbox', () => ({+ resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,+}));+vi.mock('@/database/models/user', () => ({UserModel: Object.assign(class {@@ -250,4 +258,33 @@ describe('createServerContextFactProviders', () => {},);});++ describe('resolveSandboxPersistence', () => {+ // Regression: this provider read the raw context id while every other fact+ // here is scoped to the run's workspace. On the paths that do not carry it,+ // the topic was looked up in the personal scope and came back missing, so a+ // run with a persistent instance was described to the model as disposable โ+ // and the model, told its files would not survive, worked in /tmp.+ it('scopes the lookup to the run workspace, not the raw context', async () => {+ mockResolveSandboxSessionConfig.mockResolvedValueOnce({+ claim: { key: 'ws-org-ws-from-origin', quotaBytes: 1024 },+ cwd: 'lobehub-dev',+ mode: 'persistent',+ } as never);++ const providers = createServerContextFactProviders({+ ctx: { serverDB: {}, topicId: 'tpc_1', userId: 'owner-1' } as never,+ state: { origin: { workspaceId: 'ws-from-origin' } } as never,+ });++ await expect(providers.resolveSandboxPersistence!()).resolves.toEqual({+ cwd: 'lobehub-dev',+ mode: 'persistent',+ workingDir: undefined,+ });+ expect(mockResolveSandboxSessionConfig).toHaveBeenLastCalledWith(+ expect.objectContaining({ topicId: 'tpc_1', workspaceId: 'ws-from-origin' }),+ );+ });+ });});diff --git a/apps/server/src/routers/lambda/__tests__/environmentDirectorySlug.test.ts b/apps/server/src/routers/lambda/__tests__/environmentDirectorySlug.test.tsnew file mode 100644index 00000000000..a260ff212d8--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/environmentDirectorySlug.test.ts@@ -0,0 +1,43 @@+import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';+import { describe, expect, it } from 'vitest';++import { environmentDirectorySlug } from '../sandboxStorage';++describe('environmentDirectorySlug', () => {+ it('keeps letters of any script, because a Chinese name must not become dashes', () => {+ expect(environmentDirectorySlug('Python ๆฐๆฎๅๆ')).toBe('python-ๆฐๆฎๅๆ');+ });++ it('collapses runs of punctuation and whitespace into one dash', () => {+ expect(environmentDirectorySlug('Node /// tools')).toBe('node-tools');+ });++ it('strips leading dots, which is also what keeps the reserved .sandbox out of reach', () => {+ expect(environmentDirectorySlug('.sandbox')).toBe('sandbox');+ });++ it('falls back to a word when nothing survives, rather than to an empty path', () => {+ for (const name of ['...', '---', '!!!']) {+ expect(environmentDirectorySlug(name)).toBe('environment');+ }+ });++ it('never trails a dash after the length cap', () => {+ const slug = environmentDirectorySlug(`${'a'.repeat(47)} tail`);++ expect(slug).toHaveLength(47);+ expect(slug.endsWith('-')).toBe(false);+ });++ it('produces a directory the runtime accepts, for every shape above', () => {+ for (const name of [+ 'Python ๆฐๆฎๅๆ',+ 'Node /// tools',+ '.sandbox',+ '...',+ 'a'.repeat(200),+ ]) {+ expect(isSafeSandboxCwd(environmentDirectorySlug(name))).toBe(true);+ }+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.tsnew file mode 100644index 00000000000..b39813c8fe0--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts@@ -0,0 +1,1067 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++// serverDatabase middleware calls getServerDB(); stub it (the model mock+// ignores the db handle anyway).+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++const mockCreate = vi.fn();+const mockFindById = vi.fn();+// Separate from `findById` on purpose: the two answer different questions now,+// and a test that stubs the readable lookup must not accidentally satisfy a+// path that is supposed to demand ownership.+const mockFindOwnedById = vi.fn();+const mockUpdate = vi.fn();++vi.mock('@/database/models/environment', () => ({+ EnvironmentModel: vi.fn(function () {+ return {+ create: mockCreate,+ delete: vi.fn(),+ findById: mockFindById,+ findOwnedById: mockFindOwnedById,+ query: vi.fn(),+ setVisibility: vi.fn(),+ update: mockUpdate,+ };+ }),+}));++const mockInstanceCreate = vi.fn();+const mockInstanceDelete = vi.fn();+const mockInstanceFindById = vi.fn();+const mockInstanceFindOwnedById = vi.fn();+const mockInstanceQuery = vi.fn();+const mockInstanceUpdate = vi.fn();+const mockInstanceRecordBuildResult = vi.fn();++vi.mock('@/database/models/environmentInstance', () => ({+ InstanceDirectoryOverlapError: class InstanceDirectoryOverlapError extends Error {},+ EnvironmentInstanceModel: vi.fn(function () {+ return {+ create: mockInstanceCreate,+ delete: mockInstanceDelete,+ findById: mockInstanceFindById,+ findOwnedById: mockInstanceFindOwnedById,+ findByWorkingDirectory: vi.fn(),+ query: mockInstanceQuery,+ recordBuildResult: mockInstanceRecordBuildResult,+ update: mockInstanceUpdate,+ };+ }),+}));++const mockTopicFindByIds = vi.fn();+const mockTopicModel = vi.hoisted(() => vi.fn());++vi.mock('@/database/models/topic', () => ({+ TopicModel: mockTopicModel,+}));++const mockCopyEnvironment = vi.fn();+const mockDeleteEnvironment = vi.fn();+const mockListEnvironmentSessions = vi.fn();+const mockWriteFile = vi.fn();+const mockListFiles = vi.fn();+const mockReadFile = vi.fn();+const mockGetWorkspace = vi.fn();+const mockRefreshUsage = vi.fn();+const mockReadOccupancy = vi.fn();+const mockBuildInstance = vi.fn();+const mockBuildStatus = vi.fn();+const mockListEnvironments = vi.fn();++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(function () {+ return {+ getSandboxStorageClient: () => ({+ buildInstance: mockBuildInstance,+ buildStatus: mockBuildStatus,+ copyInstance: mockCopyEnvironment,+ deleteInstance: mockDeleteEnvironment,+ getStorage: mockGetWorkspace,+ listEnvironmentSessions: mockListEnvironmentSessions,+ listInstances: mockListEnvironments,+ listFiles: mockListFiles,+ readFile: mockReadFile,+ readOccupancy: mockReadOccupancy,+ refreshUsage: mockRefreshUsage,+ writeFile: mockWriteFile,+ }),+ };+ }),+}));++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', () => ({+ resolveSandboxSessionConfig: mockResolveSessionConfig,+ resolveSandboxStorageClaim: mockResolveClaim,+}));++const mockResolveCloneCredential = vi.hoisted(() => vi.fn());++vi.mock('@/server/services/scm/cloneCredential', () => ({+ resolveScmCloneCredential: mockResolveCloneCredential,+}));++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) => {+ const error = new Error('duplicate key value violates unique constraint');+ (error as any).cause = { code: '23505', constraint };+ return error;+};++const environmentId = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';+const buildInstanceId = '7b1e9c2a-5d43-4f8a-9c21-8f0e6a3b1d77';++describe('sandboxStorageRouter', () => {+ const ctx: any = { serverDB: {}, userId: 'user-1', workspaceId: 'ws-1' };++ beforeEach(() => {+ vi.clearAllMocks();+ mockResolveClaim.mockResolvedValue({ key: 'ws-org-1', quotaBytes: 1024 });+ mockInstanceRecordBuildResult.mockResolvedValue(undefined);+ });++ describe('createInstance', () => {+ 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+ // the request โ otherwise two members could be told they share a folder.+ mockInstanceCreate.mockResolvedValue({ id: 'instance-1' });++ await sandboxStorageRouter.createCaller(ctx).createInstance({+ environmentId,+ name: 'Atlas',+ workingDirectory: 'projects/atlas',+ });++ expect(mockInstanceCreate).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'sandbox', providerScope: 'ws-org-1' }),+ );+ });++ it('reports an environment it may not use as missing', async () => {+ // The model answers `undefined` for "not yours" and "not there" alike.+ // Telling them apart here would confirm that an id exists.+ mockInstanceCreate.mockResolvedValue(undefined);++ await expect(+ sandboxStorageRouter.createCaller(ctx).createInstance({+ environmentId,+ name: 'Atlas',+ workingDirectory: 'projects/atlas',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('maps a directory already taken by another copy to CONFLICT', async () => {+ mockInstanceCreate.mockRejectedValue(+ uniqueViolation('environment_instances_provider_path_unique'),+ );++ await expect(+ sandboxStorageRouter.createCaller(ctx).createInstance({+ environmentId,+ name: 'Atlas',+ workingDirectory: 'projects/atlas',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT', message: 'DUPLICATE_INSTANCE_DIRECTORY' });+ });+ });++ describe('removeInstance', () => {+ const instanceId = '0726286c-f1a1-4c9e-980d-80a8e837321d';++ beforeEach(() => {+ mockInstanceFindOwnedById.mockResolvedValue({ id: instanceId });+ });++ it('deletes the row when the execution plane has no snapshot for it', async () => {+ // An instance nothing has ever run in has nothing on the far side, so a+ // 404 is this step's goal already met. Treating it as a failure strands+ // the row: the environment holding it refuses to go while it is there.+ mockDeleteEnvironment.mockRejectedValue(new SandboxStorageFilesError('gone', 404));++ await sandboxStorageRouter.createCaller(ctx).removeInstance({ id: instanceId });++ expect(mockInstanceDelete).toHaveBeenCalledWith(instanceId);+ });++ it('keeps the row when a session is still using the snapshot', async () => {+ // The one refusal the user can act on, and the reason the snapshot is+ // deleted first: dropping the row here would leave storage nobody can+ // see, name or reclaim.+ mockDeleteEnvironment.mockRejectedValue(new SandboxStorageFilesError('in use', 409));++ await expect(+ sandboxStorageRouter.createCaller(ctx).removeInstance({ id: instanceId }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });++ expect(mockInstanceDelete).not.toHaveBeenCalled();+ });+ });++ describe('writeFile', () => {+ const instanceId = '9b2c7e1a-4d3f-4a8b-9c1d-2e3f4a5b6c7d';++ beforeEach(() => {+ mockInstanceFindOwnedById.mockResolvedValue({ id: instanceId, workingDirectory: 'work' });+ });++ // An instance's directory is the saved copy of its sandbox's work tree and+ // is written by the sandbox alone (LOBE-14364): a write from here would be+ // overwritten by the next save, or leave the directory disagreeing with+ // the record the next restore reads it by. Refused on the server, not only+ // hidden in the browser โ and before the lookup, even for the owner.+ it.each([+ ['writeFile', { content: '# notes', path: 'work/notes.md' }],+ ['createDirectory', { path: 'work/reports' }],+ ['removeFile', { path: 'work/notes.md' }],+ ] as const)('refuses %s into an instance, even for its owner', async (route, input) => {+ await expect(+ (sandboxStorageRouter.createCaller(ctx) as any)[route]({ ...input, instanceId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN', message: 'INSTANCE_READ_ONLY' });++ expect(mockInstanceFindOwnedById).not.toHaveBeenCalled();+ expect(mockWriteFile).not.toHaveBeenCalled();+ });++ it('refuses a path that climbs out of the workspace', async () => {+ await expect(+ sandboxStorageRouter+ .createCaller(ctx)+ .writeFile({ content: 'x', instanceId, path: '../../etc/passwd' }),+ ).rejects.toThrow();++ expect(mockWriteFile).not.toHaveBeenCalled();+ });++ it('counts the size ceiling in UTF-8 bytes, not UTF-16 units', async () => {+ // A megabyte of CJK is ~3 MiB on the wire. Measured as string length it+ // would pass the guard it is supposed to fail.+ await expect(+ sandboxStorageRouter.createCaller(ctx).writeFile({+ content: '\u4E2D'.repeat(400_000),+ instanceId,+ path: 'work/cjk.txt',+ }),+ ).rejects.toThrow();++ expect(mockWriteFile).not.toHaveBeenCalled();+ });++ it('refuses a body past the size ceiling before it reaches the plane', async () => {+ await expect(+ sandboxStorageRouter.createCaller(ctx).writeFile({+ content: 'x'.repeat(1024 * 1024 + 1),+ instanceId,+ path: 'work/big.txt',+ }),+ ).rejects.toThrow();++ expect(mockWriteFile).not.toHaveBeenCalled();+ });+ });++ // 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.+ describe('file routes', () => {+ const instanceId = '9b2c7e1a-4d3f-4a8b-9c1d-2e3f4a5b6c7d';++ it('refuses a workspace write that names no instance', async () => {+ await expect(+ sandboxStorageRouter.createCaller(ctx).writeFile({ content: 'x', path: 'work/a.txt' }),+ ).rejects.toThrow('INSTANCE_REQUIRED');+ expect(mockWriteFile).not.toHaveBeenCalled();+ });++ it("refuses a read outside the instance's directory", async () => {+ mockInstanceFindById.mockResolvedValue({ id: instanceId, workingDirectory: 'work' });++ for (const path of ['other/a.txt', 'workshop/a.txt']) {+ await expect(+ sandboxStorageRouter.createCaller(ctx).readFile({ instanceId, path }),+ ).rejects.toThrow('PATH_OUTSIDE_INSTANCE');+ }+ expect(mockReadFile).not.toHaveBeenCalled();+ });++ it("lists the instance's own directory when no path is given", async () => {+ mockInstanceFindById.mockResolvedValue({ id: instanceId, workingDirectory: 'work' });+ mockListFiles.mockResolvedValue({ entries: [] });++ await sandboxStorageRouter.createCaller(ctx).listFiles({ instanceId });++ expect(mockInstanceFindById).toHaveBeenCalledWith(instanceId);+ 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: '' });++ 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');++ 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();+ });+ });++ describe('copyInstance', () => {+ it('arrives ready, because a copy has everything the source built', async () => {+ // Left at the insert's default it would sit in `pending` with no build+ // to wait for โ which reads as "never built" and offers a rebuild that+ // would throw the copy away.+ mockResolveSessionConfig.mockResolvedValue({ claim: { key: 'ws-org-1' } });+ mockInstanceFindById.mockResolvedValue({+ environmentId,+ id: buildInstanceId,+ workingDirectory: 'src',+ });+ mockInstanceCreate.mockResolvedValue({ id: 'copy-1', workingDirectory: 'copy' });+ mockCopyEnvironment.mockResolvedValue({});++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .copyInstance({ id: buildInstanceId, name: 'copy', workingDirectory: 'copy' });++ expect(mockInstanceUpdate).toHaveBeenCalledWith('copy-1', { status: 'ready' });+ expect(result.status).toBe('ready');+ });+ });++ describe('startInstanceBuild', () => {+ const spec = { bootstrapCommand: 'pnpm i', sources: [{ kind: 'git', url: 'https://x/y' }] };++ beforeEach(() => {+ mockResolveSessionConfig.mockResolvedValue({ claim: { key: 'ws-org-1' } });+ mockReadOccupancy.mockResolvedValue({ held: [], unavailable: false });+ mockResolveCloneCredential.mockResolvedValue(null);+ });++ it('builds from the definition the instance was created from', async () => {+ // Not the environment's current one: a build has to produce what the+ // instance says it is, and the two differ exactly when it moved on.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ workingDirectory: 'atlas',+ });+ mockBuildInstance.mockResolvedValue({ buildId: 'b-1' });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 'tpc-1' });++ // The instance's own folder is where the checkout lands on the volume,+ // which is what its file browser opens (LOBE-14362).+ expect(mockBuildInstance).toHaveBeenCalledWith({+ credentials: undefined,+ instanceDir: 'atlas',+ name: buildInstanceId,+ specification: spec,+ topicId: 'tpc-1',+ });+ expect(result.buildId).toBe('b-1');+ expect(mockInstanceUpdate).toHaveBeenLastCalledWith(buildInstanceId, { buildId: 'b-1' });+ });++ it('carries the App installation credential when one could be minted', async () => {+ // Resolved on this side because the App's private key lives here; the+ // execution plane is handed the result and never the inputs.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ });+ mockBuildInstance.mockResolvedValue({ buildId: 'b-2' });+ const credential = { header: 'Authorization: Basic x', urlPrefix: 'https://github.com/' };+ mockResolveCloneCredential.mockResolvedValue(credential);++ await sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockResolveCloneCredential).toHaveBeenCalledWith({+ configuration: spec,+ db: ctx.serverDB,+ userId: 'user-1',+ workspaceId: 'ws-1',+ });+ expect(mockBuildInstance).toHaveBeenCalledWith(+ expect.objectContaining({ credentials: [credential] }),+ );+ });++ it('builds without a credential rather than refusing when none can be minted', async () => {+ // The execution plane still has its own connection, and a clone that+ // fails says so in the build log where someone can act on it.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ });+ mockBuildInstance.mockResolvedValue({ buildId: 'b-3' });+ mockResolveCloneCredential.mockResolvedValue(null);++ await sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockBuildInstance).toHaveBeenCalledWith(+ expect.objectContaining({ credentials: undefined }),+ );+ });++ it('settles an instance with nothing to build without touching the sandbox', async () => {+ // Cold-starting a microVM to clone nothing and install nothing would+ // leave an empty archive behind and minutes on the clock.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: {},+ id: buildInstanceId,+ });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockBuildInstance).not.toHaveBeenCalled();+ expect(result.buildId).toBeNull();+ expect(mockInstanceUpdate).toHaveBeenCalledWith(buildInstanceId, { status: 'ready' });+ });++ it('records a refused build on the row, not only in the response', async () => {+ // The client that asked may already be gone, and an instance left+ // saying "pending" forever is the one state nothing recovers from.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ });+ mockBuildInstance.mockRejectedValue(new Error('environment in use'));++ await expect(+ sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 't' }),+ ).rejects.toThrow('environment in use');++ expect(mockInstanceUpdate).toHaveBeenLastCalledWith(buildInstanceId, {+ buildError: 'environment in use',+ status: 'error',+ });+ });++ it('refuses to rebuild an instance a conversation is holding, leaving the row alone', async () => {+ // A rebuild replaces the folder that conversation is writing in.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ status: 'ready',+ });+ mockReadOccupancy.mockResolvedValue({+ held: [{ id: buildInstanceId, own: false }],+ unavailable: false,+ });++ await expect(+ sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 't' }),+ ).rejects.toThrow('INSTANCE_IN_USE');++ expect(mockBuildInstance).not.toHaveBeenCalled();+ expect(mockInstanceUpdate).not.toHaveBeenCalled();+ });++ it('puts a ready instance back to ready when its rebuild never starts', async () => {+ // Nothing was published, so everything the last build left is still+ // there โ reading "failed" would send someone to fix a working copy.+ mockInstanceFindOwnedById.mockResolvedValue({+ configurationSnapshot: spec,+ id: buildInstanceId,+ status: 'ready',+ });+ mockBuildInstance.mockRejectedValue(new Error('environment in use'));++ await expect(+ sandboxStorageRouter+ .createCaller(ctx)+ .startInstanceBuild({ id: buildInstanceId, topicId: 't' }),+ ).rejects.toThrow('environment in use');++ expect(mockInstanceUpdate).toHaveBeenLastCalledWith(buildInstanceId, { status: 'ready' });+ });+ });++ describe('instanceBuildStatus', () => {+ beforeEach(() => {+ mockResolveSessionConfig.mockResolvedValue({ claim: { key: 'ws-org-1' } });+ });++ it('clears the build id with the verdict', async () => {+ // The runtime drops a finished build's log on its own schedule, and an+ // id that outlives it has the UI polling for a log that never comes.+ mockInstanceFindById.mockResolvedValue({+ buildId: 'b-1',+ id: buildInstanceId,+ status: 'pending',+ });+ mockBuildStatus.mockResolvedValue({ chunk: 'done', logOffset: 4, state: 'succeeded' });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .instanceBuildStatus({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(result.state).toBe('succeeded');+ expect(mockInstanceRecordBuildResult).toHaveBeenCalledWith(buildInstanceId, 'b-1', {+ buildError: null,+ status: 'ready',+ });+ });++ it('keeps the failure log on the row so the reason outlives the build', async () => {+ mockInstanceFindById.mockResolvedValue({+ buildId: 'b-1',+ id: buildInstanceId,+ status: 'pending',+ });+ mockBuildStatus.mockResolvedValue({ chunk: 'npm ERR! 404', logOffset: 12, state: 'failed' });++ await sandboxStorageRouter+ .createCaller(ctx)+ .instanceBuildStatus({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockInstanceRecordBuildResult).toHaveBeenCalledWith(buildInstanceId, 'b-1', {+ buildError: 'npm ERR! 404',+ status: 'error',+ });+ });++ it('records the verdict against the build it polled, not whoever polled it', async () => {+ // A viewer of a published environment can be the one whose poll receives+ // the terminal status. The write goes through the visibility-scoped+ // recorder and names the build, so the owner's row still settles and a+ // superseded build cannot clobber a newer one.+ mockInstanceFindById.mockResolvedValue({+ buildId: 'b-7',+ id: buildInstanceId,+ status: 'pending',+ });+ mockBuildStatus.mockResolvedValue({ chunk: 'done', logOffset: 4, state: 'succeeded' });++ await sandboxStorageRouter+ .createCaller(ctx)+ .instanceBuildStatus({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockInstanceRecordBuildResult).toHaveBeenCalledWith(buildInstanceId, 'b-7', {+ buildError: null,+ status: 'ready',+ });+ expect(mockInstanceUpdate).not.toHaveBeenCalled();+ });++ it('asks the execution plane nothing when no build is in flight', async () => {+ mockInstanceFindById.mockResolvedValue({+ buildId: null,+ id: buildInstanceId,+ status: 'ready',+ });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .instanceBuildStatus({ id: buildInstanceId, topicId: 'tpc-1' });++ expect(mockBuildStatus).not.toHaveBeenCalled();+ expect(result.state).toBe('idle');+ });+ });++ describe('listInstances', () => {+ const instance = (id: string) => ({+ createdAt: new Date(0),+ environmentId,+ id,+ name: id,+ workingDirectory: id,+ });++ beforeEach(() => {+ mockResolveSessionConfig.mockResolvedValue({ claim: { key: 'ws-org-1' } });+ mockReadOccupancy.mockResolvedValue({ held: [], unavailable: false });+ });++ it('settles a build that finished while nobody had the panel open', async () => {+ // The per-build poll only runs while the Instances tab is mounted. Switch+ // tabs mid-build and the verdict never lands, so the row stays pending+ // against a build the runtime has discarded. The listing settles it.+ mockInstanceQuery.mockResolvedValue([+ { ...instance('inst-built'), buildId: 'b-9', status: 'pending' },+ ]);+ mockBuildStatus.mockResolvedValue({ chunk: 'ok', logOffset: 2, state: 'succeeded' });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstances({ topicId: 'tpc-1', withSizes: false });++ expect(mockInstanceRecordBuildResult).toHaveBeenCalledWith('inst-built', 'b-9', {+ buildError: null,+ status: 'ready',+ });+ expect(result.instances[0]).toMatchObject({ buildId: null, status: 'ready' });+ });++ it('leaves a still-running build alone', async () => {+ mockInstanceQuery.mockResolvedValue([+ { ...instance('inst-building'), buildId: 'b-10', status: 'pending' },+ ]);+ mockBuildStatus.mockResolvedValue({ chunk: '', logOffset: 0, state: 'running' });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstances({ topicId: 'tpc-1', withSizes: false });++ expect(mockInstanceRecordBuildResult).not.toHaveBeenCalled();+ expect(result.instances[0]).toMatchObject({ buildId: 'b-10', status: 'pending' });+ });++ it('marks an instance another conversation holds, and tells its own run apart', async () => {+ // The execution plane allows one session per instance and answers the+ // second writer with 409, so a picker that cannot tell these apart+ // either offers a choice the next message refuses, or takes an instance+ // away from the conversation that is running in it.+ mockInstanceQuery.mockResolvedValue([+ instance('inst-a'),+ instance('inst-b'),+ instance('inst-c'),+ ]);+ mockReadOccupancy.mockResolvedValue({+ held: [+ { id: 'inst-a', own: false },+ { id: 'inst-b', own: true },+ ],+ unavailable: false,+ });++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstances({ topicId: 'tpc-1', withSizes: false });++ expect(mockReadOccupancy).toHaveBeenCalledWith({+ names: ['inst-a', 'inst-b', 'inst-c'],+ topicId: 'tpc-1',+ });+ expect(result.instances.map((i: any) => [i.id, i.inUse, i.inUseByThisTopic])).toEqual([+ ['inst-a', true, false],+ ['inst-b', true, true],+ ['inst-c', false, false],+ ]);+ expect(result.occupancyUnavailable).toBe(false);+ });++ it('reports occupancy as unknown rather than free when the lease store fails', async () => {+ // "Free" on the strength of a call that did not answer would let a+ // picker offer an instance another conversation is actively writing.+ mockInstanceQuery.mockResolvedValue([instance('inst-a')]);+ mockReadOccupancy.mockRejectedValue(new Error('market down'));++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstances({ topicId: 'tpc-1', withSizes: false });++ expect(result.occupancyUnavailable).toBe(true);+ expect(result.instances[0].inUse).toBe(false);+ });++ it('asks nothing of the execution plane when there are no instances', async () => {+ mockInstanceQuery.mockResolvedValue([]);++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstances({ topicId: 'tpc-1', withSizes: false });++ expect(mockReadOccupancy).not.toHaveBeenCalled();+ expect(result.occupancyUnavailable).toBe(false);+ });+ });++ 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' });++ 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 () => {+ // The execution plane would reject these anyway. Failing here keeps a+ // client that renders the panel too eagerly from looking like a server+ // fault, and keeps an unentitled caller from reaching the market at all.+ mockResolveClaim.mockResolvedValue(null);+ const caller = sandboxStorageRouter.createCaller(ctx);++ await expect(caller.createEnvironment({ name: 'Data analysis' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockCreate).not.toHaveBeenCalled();+ });+ });++ describe('workspace storage', () => {+ const info = {+ dir: '/mnt/workspace/ws-user_1',+ key: 'ws-user_1',+ quotaBytes: 8_589_934_592,+ status: 'active',+ usageBytes: 166_731,+ usageCheckedAt: '2026-09-23T05:11:00.767Z',+ };++ it('reads the stored figure without measuring', async () => {+ // A page load must not walk the volume, and must not stamp the workspace+ // as active โ that is the signal an idle sweep selects on.+ mockGetWorkspace.mockResolvedValue(info);+ const caller = sandboxStorageRouter.createCaller(ctx);++ await expect(caller.getStorage()).resolves.toMatchObject({ usageBytes: 166_731 });+ expect(mockRefreshUsage).not.toHaveBeenCalled();+ });++ it('measures only when the caller asks', async () => {+ mockRefreshUsage.mockResolvedValue({ ...info, usageBytes: 4_096 });+ const caller = sandboxStorageRouter.createCaller(ctx);++ await expect(caller.refreshStorageUsage()).resolves.toMatchObject({ usageBytes: 4_096 });+ expect(mockRefreshUsage).toHaveBeenCalledTimes(1);+ });++ it('refuses to measure without a workspace claim', async () => {+ mockResolveClaim.mockResolvedValue(null);+ const caller = sandboxStorageRouter.createCaller(ctx);++ await expect(caller.refreshStorageUsage()).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mockRefreshUsage).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(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',+ id: environmentId,+ name: 'Atlas',+ workingDirectory: 'projects/atlas',+ };++ it('forks the copy off the same environment and copies the built state', async () => {+ mockInstanceFindOwnedById.mockResolvedValue(source);+ mockInstanceCreate.mockResolvedValue({+ id: 'copy-id',+ workingDirectory: 'projects/atlas-copy',+ });+ mockCopyEnvironment.mockResolvedValue(undefined);++ await sandboxStorageRouter.createCaller(ctx).copyInstance({+ id: environmentId,+ name: 'Atlas (copy)',+ workingDirectory: 'projects/atlas-copy',+ });++ expect(mockInstanceCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ environmentId: source.environmentId,+ name: 'Atlas (copy)',+ workingDirectory: 'projects/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',+ to: 'copy-id',+ });+ });++ it('removes the row again when the built state fails to copy', async () => {+ // Otherwise the copy is an instance the UI shows as ready while its+ // directory holds nothing โ the person would find out by running in it.+ mockInstanceFindOwnedById.mockResolvedValue(source);+ mockInstanceCreate.mockResolvedValue({ id: 'copy-id' });+ mockCopyEnvironment.mockRejectedValue(new Error('upstream down'));++ await expect(+ sandboxStorageRouter.createCaller(ctx).copyInstance({+ id: environmentId,+ name: 'Atlas (copy)',+ workingDirectory: 'projects/atlas-copy',+ }),+ ).rejects.toThrow();+ expect(mockInstanceDelete).toHaveBeenCalledWith('copy-id');+ });+ });++ describe('listInstanceSessions', () => {+ const instanceA = '0726286c-f1a1-4c9e-980d-80a8e837321d';+ const instanceB = '5a1a0d2e-3b7c-4e2f-9d1a-2c3b4a5d6e7f';++ const record = (overrides: Record<string, unknown>) => ({+ buildId: null,+ endReason: 'idle',+ endedAt: '2026-09-20T11:00:00.000Z',+ environment: instanceA,+ id: 1,+ kind: 'session',+ management: false,+ sessionId: 's',+ sessionUserId: 'user-1',+ snapshotBytes: 10,+ snapshotError: null,+ startedAt: '2026-09-20T10:00:00.000Z',+ topicId: 'topic-1',+ ...overrides,+ });++ beforeEach(() => {+ mockInstanceQuery.mockResolvedValue([+ { environmentId, id: instanceA, name: 'Data' },+ { environmentId, id: instanceB, name: 'Web' },+ ]);+ mockTopicModel.mockImplementation(function () {+ return { findByIds: mockTopicFindByIds };+ });+ mockTopicFindByIds.mockResolvedValue([+ { id: 'topic-1', title: 'Quarterly report', userId: 'user-1' },+ ]);+ });++ // In the personal scope a workspace topic never matches, so every row of a+ // workspace environment would lose its title. The workspace scope also+ // reaches colleagues' topics, which keep their id only.+ it('names the workspace topics the caller started, and only those', async () => {+ mockListEnvironmentSessions.mockImplementation(async ({ name }: { name: string }) => ({+ nextBefore: null,+ sessions:+ name === instanceA+ ? [+ record({ id: 1, topicId: 'topic-1' }),+ record({ id: 2, sessionUserId: 'user-2', topicId: 'topic-2' }),+ ]+ : [],+ }));+ mockTopicFindByIds.mockResolvedValue([+ { id: 'topic-1', title: 'Quarterly report', userId: 'user-1' },+ { id: 'topic-2', title: 'A colleague topic', userId: 'user-2' },+ ]);++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstanceSessions({ environmentId });++ expect(mockTopicModel).toHaveBeenCalledWith(ctx.serverDB, 'user-1', 'ws-1');+ expect(Object.fromEntries(result.sessions.map((s) => [s.topicId, s.topicTitle]))).toEqual({+ 'topic-1': 'Quarterly report',+ 'topic-2': null,+ });+ });++ it('merges every instance history newest first, naming the instance and the topic', async () => {+ // One environment has several instances and the execution plane keys+ // history by instance, so the panel's tab is the union of them.+ mockListEnvironmentSessions.mockImplementation(async ({ name }: { name: string }) => ({+ nextBefore: null,+ sessions:+ name === instanceA+ ? [record({ id: 1, startedAt: '2026-09-20T10:00:00.000Z' })]+ : [+ record({+ environment: instanceB,+ id: 2,+ startedAt: '2026-09-21T10:00:00.000Z',+ topicId: 'sandbox-workspace-console',+ }),+ ],+ }));++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstanceSessions({ environmentId });++ expect(result.unavailable).toBe(false);+ expect(result.sessions.map((s) => [s.id, s.instanceName, s.topicTitle])).toEqual([+ [2, 'Web', null],+ [1, 'Data', 'Quarterly report'],+ ]);+ // Keyed by the instance id: that is the name the snapshot store uses.+ expect(mockListEnvironmentSessions).toHaveBeenCalledWith(+ expect.objectContaining({ name: instanceA }),+ );+ expect(mockTopicFindByIds).toHaveBeenCalledWith(['topic-1']);+ });++ it('reports the history as unavailable rather than empty when the control plane fails', async () => {+ mockListEnvironmentSessions.mockRejectedValue(new SandboxStorageFilesError('down', 502));++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstanceSessions({ environmentId });++ expect(result).toEqual({ sessions: [], unavailable: true });+ });++ it('answers an environment without instances from the database alone', async () => {+ mockInstanceQuery.mockResolvedValue([]);++ const result = await sandboxStorageRouter+ .createCaller(ctx)+ .listInstanceSessions({ environmentId });++ expect(result).toEqual({ sessions: [], unavailable: false });+ 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/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 57304d80f3c..10108d3a68b 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -16,13 +16,13 @@ import type {import {CreateThreadWithMessageSchema,entityIdPattern,+ initialTopicMetadataSchema,isServerDefaultHeterogeneousRelayInvocation,LocalHeterogeneousAgentTypeSchema,RequestTrigger,ThreadStatus,ThreadType,UserInterventionConfigSchema,- workingDirConfigSchema,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -1072,13 +1072,10 @@ const ExecAgentSchema = z/** The group being edited when scope is 'group_agent_builder' (not a group chat turn). */editingGroupId: z.string().optional(),groupId: z.string().nullish(),- initialTopicMetadata: z- .object({- repos: z.array(z.string()).optional(),- workingDirectory: z.string().optional(),- workingDirectoryConfig: workingDirConfigSchema.optional(),- })- .optional(),+ // The shared declaration, not a copy of it: a local `z.object()` here+ // silently strips whatever the type gained and the call still answers+ // 200, so the two must be one thing.+ initialTopicMetadata: initialTopicMetadataSchema.optional(),/*** Branch this run into a new thread (subtopic) under the resolved topic.* The gateway path never calls `aiChat.sendMessageInServer`, so this isdiff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex ac739b8ead0..d7f404e7cc6 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -85,6 +85,7 @@ import { ragEvalRouter } from './ragEval';import { recentRouter } from './recent';import { resourcePermissionRouter } from './resourcePermission';import { resourceTransferRequestRouter } from './resourceTransferRequest';+import { sandboxStorageRouter } from './sandboxStorage';import { scmRouter } from './scm';import { searchRouter } from './search';import { sessionRouter } from './session';@@ -120,6 +121,7 @@ export const lambdaRouter = router({agentEvalExternal: agentEvalExternalRouter,agentLabel: agentLabelRouter,agentSkills: agentSkillsRouter,+ sandboxStorage: sandboxStorageRouter,agentTrace: agentTraceRouter,expertise: expertiseRouter,agentSignal: agentSignalRouter,diff --git a/apps/server/src/routers/lambda/sandboxStorage.ts b/apps/server/src/routers/lambda/sandboxStorage.tsnew file mode 100644index 00000000000..674be48082c--- /dev/null+++ b/apps/server/src/routers/lambda/sandboxStorage.ts@@ -0,0 +1,1324 @@+import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';+import { ConnectorDataError } from '@lobechat/connector-data';+import { MAX_REPOSITORY_BRANCHES } from '@lobechat/connector-data/github';+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';+import { z } from 'zod';++import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { EnvironmentModel } from '@/database/models/environment';+import {+ EnvironmentInstanceModel,+ InstanceDirectoryOverlapError,+} from '@/database/models/environmentInstance';+import { TopicModel } from '@/database/models/topic';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { ConnectorDataService } from '@/server/services/connectorData';+import { MarketService } from '@/server/services/market';+import { resolveSandboxSessionConfig, resolveSandboxStorageClaim } from '@/server/services/sandbox';+import { SandboxStorageFilesError } from '@/server/services/sandbox/storageFiles';+import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';++/**+ * Browsing and managing the persistent sandbox workspace.+ *+ * 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.+ */++/** Relative workspace path, validated with the same rule the runtime applies. */+const relativePathSchema = z.string().refine(isSafeSandboxCwd, {+ message: 'Path must be a relative path inside the workspace',+});++/**+ * Topic whose warm sandbox session should serve the call, so listing a+ * directory does not cold-start a second sandbox next to the one the user is+ * already talking to.+ */+const topicIdSchema = z.string().min(1).max(255).optional();++/**+ * 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;++/**+ * 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+ .string()+ .refine((value) => Buffer.byteLength(value, 'utf8') <= MAX_FILE_CONTENT_BYTES, {+ message: `File content exceeds ${MAX_FILE_CONTENT_BYTES} bytes`,+ });++/**+ * "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;++/**+ * Whether building from this definition does anything: an environment that+ * clones nothing and installs nothing is already everything it will ever be.+ * Shared by the build itself, which settles such an instance without starting+ * a sandbox, and the listing, which is how the row knows a rebuild would be a+ * no-op rather than a folder thrown away.+ */+const isBuildable = (+ specification: { bootstrapCommand?: string | null; sources?: unknown[] | null } | null,+): boolean => (specification?.sources?.length ?? 0) > 0 || Boolean(specification?.bootstrapCommand);++/**+ * 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.+ *+ * `409` is the one worth naming: it means a conversation is still using this+ * 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']> = {+ 400: 'BAD_REQUEST',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+ 409: 'CONFLICT',+ // The workspace is out of quota โ the user frees space or upgrades.+ 507: 'PAYLOAD_TOO_LARGE',+};++const mapStorageError = (error: unknown): never => {+ if (error instanceof SandboxStorageFilesError) {+ throw new TRPCError({+ code: WORKSPACE_ERROR_CODES[error.status] ?? 'BAD_GATEWAY',+ // The machine code when the market sent one, the way this router's own+ // refusals travel (`ENVIRONMENT_HAS_INSTANCES`): the client turns a code+ // into a sentence in the reader's language. The description beside it+ // names the row by its id, so forwarding it verbatim put a UUID in a+ // toast โ accurate, and useless to the person reading it.+ message: error.code || error.message,+ });+ }++ throw error;+};++/**+ * Resolves the caller's sandbox-storage claim: 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.+ *+ * 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+ * โ so there is no share-visitor case to suppress.+ */+const storageClaimProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const workspaceId = ctx.workspaceId ?? undefined;++ const claim = await resolveSandboxStorageClaim({+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ workspaceId,+ });++ return opts.next({+ ctx: {+ claim,+ marketService: new MarketService({+ userInfo: { sandboxStorage: claim, userId: ctx.userId, workspaceId },+ }),+ },+ });+});++/**+ * Everything past the entitlement check. Without a claim there is no directory+ * to address โ the execution plane would reject the call anyway, and failing+ * here keeps a client that renders the panel too eagerly from looking like a+ * server fault.+ */+const entitledProcedure = storageClaimProcedure.use(async (opts) => {+ const { claim, marketService } = opts.ctx;+ if (!claim) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This account has no persistent sandbox workspace',+ });+ }++ return opts.next({ ctx: { claim, client: marketService.getSandboxStorageClient() } });+});++/**+ * A user-facing environment name. Distinct from the row's id, which is what the+ * execution plane stores the snapshot under and never changes โ this is the+ * part a rename is allowed to move.+ */+const nameSchema = z.string().trim().min(1).max(255);++/**+ * 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';++/**+ * An environment or instance id. Checked for shape rather than left to the+ * lookup, because the lookup cannot answer: a non-UUID compared against a+ * `uuid` column is a Postgres type error, so the caller would get a server+ * fault where "no such environment" was the answer.+ *+ * An instance's id doubles as the name its snapshot is stored under, which is+ * why it never changes.+ */+const idSchema = z.string().uuid();++/**+ * Who an environment resolves for inside a workspace. Personal environments+ * have no pool to join, so the server stores `private` for them whatever a+ * client sends.+ */+const visibilitySchema = z.enum(['private', 'public']);++/** The indexes that make a name identify one environment for one member. */+const ENVIRONMENT_NAME_CONSTRAINTS = new Set([+ 'environments_user_name_unique',+ 'environments_workspace_user_name_unique',+]);++/** The index that keeps two instances out of the same directory. */+const INSTANCE_DIRECTORY_CONSTRAINT = 'environment_instances_provider_path_unique';++/**+ * 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(),+ 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(),+});++/** Postgres surfaces the driver error somewhere down the `cause` chain. */+const getPostgresErrorField = (error: unknown, field: string): string | undefined => {+ let current: unknown = error;++ while (current && typeof current === 'object') {+ const value = (current as Record<string, unknown>)[field];+ if (typeof value === 'string') return value;++ current = (current as { cause?: unknown }).cause;+ }+};++/**+ * The name is the one thing the person chose, and a collision is fixed by+ * typing a different one โ so it has to arrive as CONFLICT next to the field,+ * not as the generic failure a raw driver error would produce. A code rather+ * than prose because this one is shown inline and has to be translated.+ */+const rethrowDuplicateEnvironmentName = (error: unknown): never => {+ if (+ getPostgresErrorField(error, 'code') === '23505' &&+ ENVIRONMENT_NAME_CONSTRAINTS.has(getPostgresErrorField(error, 'constraint') ?? '')+ ) {+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'DUPLICATE_ENVIRONMENT_NAME' });+ }++ throw error;+};++/**+ * Two instances in one directory would restore two package sets over each+ * other's files, so the database refuses it and the person picks another+ * directory. Same reasoning as a duplicate name, different fix.+ */+const isDuplicateInstanceDirectory = (error: unknown): boolean =>+ getPostgresErrorField(error, 'code') === '23505' &&+ getPostgresErrorField(error, 'constraint') === INSTANCE_DIRECTORY_CONSTRAINT;++const rethrowDuplicateInstanceDirectory = (error: unknown): never => {+ // The same fix for the person โ pick another folder โ but a different+ // sentence, since the folder itself is not taken.+ if (error instanceof InstanceDirectoryOverlapError) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'OVERLAPPING_INSTANCE_DIRECTORY',+ });+ }++ if (isDuplicateInstanceDirectory(error)) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'DUPLICATE_INSTANCE_DIRECTORY',+ });+ }++ throw error;+};++/**+ * How many derived directories to try before giving up.+ *+ * A bound rather than a loop until success: the only way to exhaust it is a+ * member who already holds fifty directories under one name, and at that point+ * the honest answer is to say so rather than keep probing the index.+ */+const MAX_DERIVED_DIRECTORY_ATTEMPTS = 50;++/**+ * A directory name derived from an environment's name.+ *+ * Letters and digits of any script survive โ a Chinese environment name should+ * not become a row of dashes โ while everything else collapses to `-`, because+ * this name is handed to a shell as a path. Interior spaces are legal in a+ * workspace path and still not worth minting: every command the agent writes+ * would need to quote them.+ *+ * Leading dots are stripped rather than escaped, which also puts `.sandbox`+ * (the reserved platform directory) out of reach without naming it here.+ */+export const environmentDirectorySlug = (name: string): string => {+ const slug = name+ .normalize('NFKC')+ .toLowerCase()+ .replaceAll(/[^\p{L}\p{N}._-]+/gu, '-')+ .slice(0, 48)+ .replaceAll(/^[.-]+|[.-]+$/g, '');++ // Every character was punctuation, or the name was dots. Nothing is derivable+ // from it, so fall back to a word rather than to an empty path.+ return slug || 'environment';+};++/**+ * An environment with instances still on it. The reference is `restrict`+ * on purpose โ deleting the specification out from under them would leave+ * directories and captured state nothing describes.+ */+const rethrowEnvironmentInUse = (error: unknown): never => {+ if (getPostgresErrorField(error, 'code') === '23503') {+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: 'ENVIRONMENT_HAS_INSTANCES' });+ }++ throw error;+};++/**+ * An environment is a specification plus whatever has been built from it. This+ * layer owns the specification; the snapshot belongs to the execution plane and+ * is addressed by the row's id.+ *+ * An environment that was created but never used has no snapshot yet, which is+ * a normal state and not an error: it becomes real the first time a session+ * using it ends.+ */+const environmentProcedure = entitledProcedure.use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ environmentModel: new EnvironmentModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++/**+ * 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.+ */+const sandboxBinding = (workspaceKey: string) => ({+ deviceId: null,+ kind: 'sandbox' as const,+ provider: 'market',+ providerResourceId: 'workspace',+ providerScope: workspaceKey,+});++const instanceProcedure = environmentProcedure.use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ instanceModel: new EnvironmentInstanceModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++/**+ * 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 (LOBE-14364): 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 sandboxStorageRouter = router({+ createDirectory: instanceProcedure+ .input(+ z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),+ )+ .mutation(async ({ ctx, input: { instanceId, ...input } }) => {+ assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));++ return ctx.client.createDirectory(input).catch(mapStorageError);+ }),++ /**+ * Whether this caller has a persistent workspace at all. The client pairs it+ * with the lab flag it already holds: flag off renders nothing, flag on+ * without an entitlement renders the upgrade prompt, and both renders the+ * workspace.+ */+ getEntitlement: storageClaimProcedure.query(async ({ ctx }) => ({+ entitled: Boolean(ctx.claim),+ quotaBytes: ctx.claim?.quotaBytes ?? null,+ })),++ /**+ * Where this topic's commands will run, for the prompt that describes it.+ *+ * The browser assembles the system role on the client-executor path, and it+ * cannot resolve this itself: the placement follows an entitlement that is+ * signed server-side. Without it the prompt fell back to the disposable+ * wording โ "files created here are temporary" โ while the run had a+ * persistent directory, and the model worked in /tmp on the strength of what+ * it had been told.+ *+ * Returns the placement only. The claim stays on this side; a browser has no+ * use for an entitlement it cannot sign anything with, and every sandbox call+ * it makes is routed through a server that resolves the claim again.+ */+ resolveSessionPlacement: storageClaimProcedure+ .input(z.object({ topicId: z.string().optional() }))+ .query(async ({ ctx, input }) => {+ const { claim, cwd, mode, workingDir } = await resolveSandboxSessionConfig({+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ topicId: input.topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ return claim ? { cwd, mode, workingDir } : null;+ }),++ /**+ * Fork an instance: a second directory that starts with everything the+ * first one had installed. The point of copying rather than creating is to+ * skip the rebuild โ the specification alone would give an empty directory+ * and a fresh bootstrap.+ */+ copyInstance: instanceProcedure+ .input(+ z.object({+ id: idSchema,+ name: nameSchema,+ workingDirectory: relativePathSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const source = await ctx.instanceModel.findOwnedById(input.id);+ if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ // Row first: a copy whose snapshot succeeded but whose row is missing+ // would be captured state nobody can name, and therefore nobody can+ // delete. The reverse โ a row whose snapshot never arrived โ is the same+ // state as a brand-new instance, which the UI already handles.+ const created = await ctx.instanceModel+ .create({+ ...sandboxBinding(ctx.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.+ configurationSnapshot: source.configurationSnapshot,+ environmentId: source.environmentId,+ name: input.name,+ workingDirectory: input.workingDirectory,+ })+ .catch(rethrowDuplicateInstanceDirectory);++ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ await ctx.client+ .copyInstance({+ from: source.id,+ // The copy's own folder. Sharing the source's would let either+ // instance's next save delete files the other still lists.+ instanceDir: created.workingDirectory,+ to: created.id,+ })+ .catch(async (error) => {+ await ctx.instanceModel.delete(created.id);+ return mapStorageError(error);+ });++ // A copy starts life with everything the source had built, so it is+ // ready by arrival โ there is nothing to clone and nothing to install.+ // Left at the insert's default it would sit in `pending` with no build+ // to wait for, which reads as "never built" and offers a rebuild that+ // would throw the copy away.+ await ctx.instanceModel.update(created.id, { status: 'ready' });++ return { ...created, status: 'ready' as const };+ }),++ /**+ * A new instance of an environment, with its directory derived rather than+ * asked for.+ *+ * The person picked an environment, not a folder. Under the agreed split the+ * checkout and its installed packages live on local disk and travel in the+ * snapshot, so this directory holds the outputs worth keeping โ which is+ * rarely something anyone has an opinion about before the work exists. Asking+ * would make them invent an answer to start a conversation.+ *+ * The directory is searched rather than computed in one shot: the unique+ * index spans the whole workspace, not one environment, so a name that is+ * free inside this environment can still be taken outside it. The index stays+ * the authority โ the pre-check only keeps the common case out of the error+ * path, and a lost race falls through to the next suffix.+ */+ createInstanceForEnvironment: instanceProcedure+ .input(z.object({ environmentId: idSchema }))+ .mutation(async ({ ctx, input }) => {+ // Owner-scoped: an environment a colleague published is one you can run+ // in, not one you can add copies to.+ const environment = await ctx.environmentModel.findOwnedById(input.environmentId);+ if (!environment)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ const base = environmentDirectorySlug(environment.name);++ for (let attempt = 1; attempt <= MAX_DERIVED_DIRECTORY_ATTEMPTS; attempt += 1) {+ const workingDirectory = attempt === 1 ? base : `${base}-${attempt}`;++ if (await ctx.instanceModel.findByWorkingDirectory(workingDirectory)) continue;++ const created = await ctx.instanceModel+ .create({+ ...sandboxBinding(ctx.claim.key),+ 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 label+ // until the person renames it.+ name: workingDirectory,+ workingDirectory,+ })+ .catch((error: unknown) => {+ // Someone else took this directory between the check and the+ // insert, or it nests with another instance's. Not a conflict the+ // caller can act on โ try the next one.+ if (isDuplicateInstanceDirectory(error)) return undefined;+ if (error instanceof InstanceDirectoryOverlapError) return undefined;+ throw error;+ });++ if (created) return created;+ }++ throw new TRPCError({+ code: 'CONFLICT',+ message: 'DUPLICATE_INSTANCE_DIRECTORY',+ });+ }),++ /**+ * An instance of an environment: its own directory, its own captured+ * state. Created empty โ nothing is built until a conversation runs in it.+ */+ createInstance: instanceProcedure+ .input(+ z.object({+ environmentId: idSchema,+ name: nameSchema,+ workingDirectory: relativePathSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const created = await ctx.instanceModel+ .create({+ ...sandboxBinding(ctx.claim.key),+ environmentId: input.environmentId,+ name: input.name,+ workingDirectory: input.workingDirectory,+ })+ .catch(rethrowDuplicateInstanceDirectory);++ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return created;+ }),++ /**+ * Materialize an instance: clone the environment's sources and run its+ * bootstrap, into the instance's own stored generation.+ *+ * Its own mutation rather than part of `createInstance`, because starting a+ * build attaches a sandbox session and that is a cold start โ seconds, with+ * a dialog open in front of it. The dialog closes on the insert; the list+ * shows the instance as pending and this is what the client fires next.+ *+ * Returns as soon as the build has started: a bootstrap running an install+ * is minutes long, and `instanceBuildStatus` is what follows it.+ */+ startInstanceBuild: instanceProcedure+ .input(z.object({ id: idSchema, topicId: topicIdSchema }))+ .mutation(async ({ ctx, input }) => {+ const instance = await ctx.instanceModel.findOwnedById(input.id);+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ // 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+ // the two differ exactly when the environment moved on.+ const specification = instance.configurationSnapshot;+ const buildable = isBuildable(specification);++ // An environment that clones nothing and installs nothing is already+ // everything it is ever going to be. Building it would cold-start a+ // sandbox to do nothing and leave an empty archive behind.+ if (!buildable) {+ await ctx.instanceModel.update(input.id, { status: 'ready' });++ return { buildId: null };+ }++ // A rebuild replaces the folder a conversation may be writing in right+ // 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+ .readOccupancy({ names: [input.id], topicId: input.topicId })+ .catch(() => ({ held: [], unavailable: true }));+ if (occupancy.held.some((entry) => entry.id === input.id)) {+ throw new TRPCError({ code: 'CONFLICT', message: 'INSTANCE_IN_USE' });+ }++ // What to fall back to if the build never starts. An instance that was+ // ready still has everything its last build published โ a refused start+ // takes none of it away, so it must not come back reading "failed".+ const previousStatus = instance.status;++ await ctx.instanceModel.update(input.id, { buildError: null, status: 'pending' });++ // Preferred over the execution plane's own GitHub connection, which it+ // falls back to when this answers null: an App installation is granted+ // one repository at a time by whoever administers the account, and the+ // token minted from it is narrower still โ this repository, read-only,+ // expiring within the hour. It is resolved here because the App's+ // private key lives on this side; the execution plane is handed the+ // result and never the inputs, the same way it is handed the workspace+ // claim.+ const credential = await resolveScmCloneCredential({+ configuration: specification,+ db: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++ try {+ const { buildId } = await ctx.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.+ instanceDir: instance.workingDirectory,+ name: input.id,+ specification,+ topicId: input.topicId,+ });+ await ctx.instanceModel.update(input.id, { buildId });++ return { buildId };+ } catch (error) {+ // Recorded on the row rather than only thrown: the client that asked+ // may already be gone, and an instance left saying "pending" forever+ // is the one state nothing recovers from.+ await ctx.instanceModel.update(+ input.id,+ previousStatus === 'ready'+ ? { status: 'ready' }+ : {+ buildError: (error as Error)?.message || 'Could not start the build',+ status: 'error',+ },+ );+ throw error;+ }+ }),++ /**+ * Follow a build, and settle the instance once it ends.+ *+ * A query that writes, deliberately: the runtime is the only thing that+ * knows a build finished, nothing calls back, and the row has to end up+ * right whether or not anyone is still watching. Polling it is what moves+ * the instance out of `pending`.+ */+ instanceBuildStatus: instanceProcedure+ .input(+ z.object({+ id: idSchema,+ /** Resume the log from here; the reply says where to go next. */+ logOffset: z.number().int().min(0).optional(),+ topicId: topicIdSchema,+ }),+ )+ .query(async ({ ctx, input }) => {+ const instance = await ctx.instanceModel.findById(input.id);+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ if (!instance.buildId) {+ return {+ chunk: '',+ logOffset: input.logOffset ?? 0,+ state: instance.status === 'error' ? ('failed' as const) : ('idle' as const),+ };+ }++ const status = await ctx.client+ .buildStatus({+ buildId: instance.buildId,+ logOffset: input.logOffset,+ name: input.id,+ topicId: input.topicId,+ })+ .catch(mapStorageError);++ if (status.state !== 'running') {+ // The id is cleared with the verdict: the runtime drops a finished+ // build's log on its own schedule, and an id that outlives it has the+ // UI polling for a log that will never come back. Written through the+ // visibility-scoped recorder, because the poll that happens to receive+ // the terminal status can be a viewer's rather than the owner's.+ await ctx.instanceModel.recordBuildResult(input.id, instance.buildId, {+ buildError:+ status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,+ status: status.state === 'succeeded' ? 'ready' : 'error',+ });+ }++ return { chunk: status.chunk, logOffset: status.logOffset, state: status.state };+ }),++ createEnvironment: environmentProcedure+ .input(+ z.object({+ configuration: configurationSchema.optional(),+ description: z.string().max(2000).optional(),+ name: nameSchema,+ visibility: visibilitySchema.optional(),+ }),+ )+ .mutation(async ({ ctx, input }) =>+ ctx.environmentModel.create(input).catch(rethrowDuplicateEnvironmentName),+ ),++ /**+ * One instance, from the database alone. Separate from `listInstances`+ * because the composer only needs to know where the conversation is pointed,+ * 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),++ getStorage: entitledProcedure.query(async ({ ctx }) =>+ ctx.client.getStorage().catch(mapStorageError),+ ),++ /**+ * Re-measure the workspace and answer with the fresh figure.+ *+ * 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.+ */+ refreshStorageUsage: entitledProcedure.mutation(async ({ ctx }) =>+ ctx.client.refreshUsage().catch(mapStorageError),+ ),++ /** 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),+ })),++ /**+ * Instances, each joined with the state the execution plane actually+ * holds for it. An instance that was created but never used has no snapshot+ * yet, which is a normal state and not an error.+ */+ listInstances: instanceProcedure+ .input(+ z.object({+ environmentId: idSchema.optional(),+ topicId: topicIdSchema,+ /**+ * Sizes come from the snapshot store, which is reachable only through a+ * sandbox session and pays a cold start to answer. A settings page is+ * worth that wait; a picker in the composer is not, and asks for names+ * alone.+ */+ withSizes: z.boolean().default(true),+ }),+ )+ .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)+ : [],+ // 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 },+ ]);++ // 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+ // never lands, leaving the row `pending` against a build the runtime+ // has since discarded and an instance the composer will not offer. So+ // every listing settles the builds it finds already finished. Bounded+ // by how many instances can be building at once, and never fatal: an+ // unreachable execution plane just leaves the row as it was.+ const settled = await pMap(+ instances.filter((instance) => instance.buildId),+ async (instance) => {+ const status = await ctx.client+ .buildStatus({ buildId: instance.buildId!, name: instance.id, topicId: input.topicId })+ .catch(() => null);+ if (!status || status.state === 'running') return null;++ const next = {+ buildError:+ status.state === 'failed' ? status.chunk.slice(-2000) || 'Build failed' : null,+ status: status.state === 'succeeded' ? ('ready' as const) : ('error' as const),+ };+ await ctx.instanceModel+ .recordBuildResult(instance.id, instance.buildId!, next)+ .catch(() => undefined);++ return [instance.id, next] as const;+ },+ { concurrency: 5 },+ );+ 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]));++ return {+ instances: instances.map((instance) => ({+ /** Set only while a build is worth polling; cleared with its verdict. */+ buildId: settledById.has(instance.id) ? null : instance.buildId,+ // From the definition the instance was made from, which is what a+ // build uses โ the environment may have moved on since.+ buildable: isBuildable(instance.configurationSnapshot),+ buildError: settledById.get(instance.id)?.buildError ?? instance.buildError,+ createdAt: instance.createdAt,+ environmentId: instance.environmentId,+ id: instance.id,+ // Held by a running sandbox, and by whom. `own` is this topic's own+ // run, which its own picker must keep offering; anything else is+ // another conversation and is what a picker refuses.+ inUse: heldBy.has(instance.id),+ inUseByThisTopic: heldBy.get(instance.id) === true,+ name: instance.name,+ snapshot: byId.get(instance.id) ?? null,+ status: settledById.get(instance.id)?.status ?? instance.status,+ workingDirectory: instance.workingDirectory,+ })),+ occupancyUnavailable: occupancy.unavailable,+ snapshotsUnavailable: snapshots === null,+ };+ }),++ /**+ * The run history of every instance of one environment, newest first.+ *+ * The execution plane keys its trail by instance โ that is the name the+ * snapshot is stored under โ while the panel shows one environment, so this+ * is the union of the instances' histories with the instance named on each+ * row. Read from the control plane's own records: unlike `listInstances`+ * it starts no sandbox and pays no cold start.+ *+ * Topic titles are looked up for the caller's own topics; a run another+ * member started in a published environment keeps its id only.+ */+ listInstanceSessions: instanceProcedure+ .input(+ z.object({+ environmentId: idSchema,+ /** Per instance, not in total: each instance's page is fetched on its own. */+ limit: z.number().int().min(1).max(100).default(20),+ }),+ )+ .query(async ({ ctx, input }) => {+ const instances = await ctx.instanceModel.query({ environmentId: input.environmentId });+ if (instances.length === 0) return { sessions: [], unavailable: false };++ // Bounded: an environment's instance count is whatever the member made,+ // and one request per instance all at once would put that number on the+ // execution plane in a single burst.+ const pages = await pMap(+ instances,+ (instance) =>+ ctx.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),+ { concurrency: 5 },+ );++ const merged = instances+ .flatMap((instance, index) =>+ (pages[index]?.sessions ?? []).map((session) => ({+ ...session,+ instanceId: instance.id,+ instanceName: instance.name,+ })),+ )+ .sort((a, b) => b.startedAt.localeCompare(a.startedAt));++ const topicIds = [+ ...new Set(+ merged+ .map((session) => session.topicId)+ .filter((id): id is string => !!id && id !== MANAGEMENT_TOPIC_ID),+ ),+ ];+ // Read in the workspace's scope โ the personal scope matches no+ // workspace topic at all โ and then narrowed to the caller's own, since+ // a workspace scope also reaches what other members may see.+ const topics =+ topicIds.length > 0+ ? await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)+ .findByIds(topicIds)+ .catch(() => [])+ : [];+ const titles = new Map(+ topics+ .filter((topic) => topic.userId === ctx.userId)+ .map((topic) => [topic.id, topic.title]),+ );++ return {+ sessions: merged.map((session) => ({+ ...session,+ topicTitle: (session.topicId && titles.get(session.topicId)) || null,+ })),+ unavailable: pages.includes(null),+ };+ }),++ listFiles: instanceProcedure+ .input(+ z.object({+ 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);+ }),++ readFile: instanceProcedure+ .input(+ z.object({ instanceId: instanceIdSchema, path: relativePathSchema, topicId: topicIdSchema }),+ )+ .query(async ({ ctx, input: { instanceId, ...input } }) => {+ assertWithinRoot(+ input.path,+ await resolveFileRoot(ctx, { instanceId, topicId: input.topicId }, 'read'),+ );++ return ctx.client.readFile(input).catch(mapStorageError);+ }),++ /**+ * Write a file's whole contents, creating it and its parents if needed.+ *+ * Text only, because the execution plane's endpoint carries the body as a+ * JSON string with no encoding field. The cap is this layer's own: the+ * endpoint declares none, and an unbounded string arrives in memory on both+ * sides before anything touches a disk.+ */+ writeFile: instanceProcedure+ .input(+ z.object({+ content: fileContentSchema,+ instanceId: instanceIdSchema,+ path: relativePathSchema,+ topicId: topicIdSchema,+ }),+ )+ .mutation(async ({ ctx, input: { instanceId, ...input } }) => {+ assertWithinRoot(input.path, await resolveFileRoot(ctx, { instanceId }, 'write'));++ return ctx.client.writeFile(input).catch(mapStorageError);+ }),++ /** Refused while instances still reference it โ those go first. */+ removeEnvironment: environmentProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ const removed = await ctx.environmentModel.delete(input.id).catch(rethrowEnvironmentInUse);+ if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });++ return removed;+ }),++ removeInstance: instanceProcedure+ .input(z.object({ id: idSchema, topicId: topicIdSchema }))+ .mutation(async ({ ctx, input }) => {+ const instance = await ctx.instanceModel.findOwnedById(input.id);+ if (!instance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ // 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 ctx.client+ .deleteInstance({ name: instance.id, topicId: input.topicId })+ .catch((error: unknown) => {+ // No snapshot there is the state this call exists to reach, so a 404+ // is this step succeeding, not failing. An instance nothing has ever+ // run in has nothing on the execution plane โ and treating that as an+ // error strands the row permanently, because the environment holding+ // it cannot be deleted either while an instance references it.+ if (error instanceof SandboxStorageFilesError && error.status === 404) return;++ return mapStorageError(error);+ });++ return ctx.instanceModel.delete(input.id);+ }),++ /**+ * 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;+ }+ }),++ removeFile: instanceProcedure+ .input(+ z.object({+ 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' });+ }++ return ctx.client.deleteFile(input).catch(mapStorageError);+ }),++ /**+ * 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;+ }),++ renameInstance: instanceProcedure+ .input(z.object({ id: idSchema, name: nameSchema }))+ .mutation(async ({ ctx, input }) => {+ const { id, ...changes } = input;+ const updated = await ctx.instanceModel.update(id, changes);+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Instance not found' });++ return updated;+ }),+});++export type SandboxStorageRouter = typeof sandboxStorageRouter;diff --git a/apps/server/src/routers/tools/market.test.ts b/apps/server/src/routers/tools/market.test.tsindex 697000b0070..98745955047 100644--- a/apps/server/src/routers/tools/market.test.ts+++ b/apps/server/src/routers/tools/market.test.ts@@ -12,6 +12,9 @@ const mockCreateSandboxService = vi.hoisted(() =>};}),);+const mockResolveSandboxSessionConfig = vi.hoisted(() =>+ vi.fn(async () => ({ claim: null, mode: 'ephemeral' as const })),+);const mockMarketSDK = vi.hoisted(() => ({skills: {callTool: vi.fn(),@@ -54,6 +57,7 @@ vi.mock('@/server/services/file', () => ({vi.mock('@/server/services/sandbox', () => ({createSandboxService: mockCreateSandboxService,+ resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,}));vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({@@ -102,6 +106,79 @@ describe('tools marketRouter', () => {});});+ // Regression: this route opened the sandbox session with no mode, no+ // directory and no claim, so a conversation whose topic had chosen a+ // persistent instance still ran in the disposable `/workspace` โ the+ // composer said one thing and `pwd` another. The client-side executor+ // reaches the sandbox through here, so the feature was absent for every run+ // that is not dispatched server-side.+ it('opens the session with the persistence the topic resolved', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: 'ws-1',+ } as any);+ mockResolveSandboxSessionConfig.mockResolvedValueOnce({+ claim: { key: 'ws-org-ws-1', quotaBytes: 1024 },+ cwd: 'lobehub-dev',+ environment: 'env-1',+ mode: 'persistent',+ } as never);+ mockSandboxCallTool.mockResolvedValue({ result: { ok: true }, success: true });++ await caller.execInSandbox({+ params: { command: 'pwd' },+ toolName: 'runCommand',+ topicId: 'topic-1',+ });++ expect(mockResolveSandboxSessionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic-1', userId: 'caller-user', workspaceId: 'ws-1' }),+ );+ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxCwd: 'lobehub-dev',+ sandboxInstanceId: 'env-1',+ sandboxMode: 'persistent',+ }),+ );+ });++ // Regression: the same route, and the same reason as above. The environment's+ // definition is what exports its variables, runs its maintenance command and+ // cuts its network โ all of it inert for a conversation that reaches the+ // sandbox through here, which is every run not dispatched server-side.+ it('opens the session with the definition the instance was built from', async () => {+ const caller = marketRouter.createCaller({+ serverDB: {},+ userId: 'caller-user',+ workspaceId: 'ws-1',+ } as any);+ const specification = {+ env: { NODE_ENV: 'production' },+ internetAccess: false,+ maintenanceCommand: 'git pull --ff-only',+ };+ mockResolveSandboxSessionConfig.mockResolvedValueOnce({+ claim: { key: 'ws-org-ws-1', quotaBytes: 1024 },+ cwd: 'lobehub-dev',+ environment: 'env-1',+ mode: 'persistent',+ specification,+ } as never);+ mockSandboxCallTool.mockResolvedValue({ result: { ok: true }, success: true });++ await caller.execInSandbox({+ params: { command: 'env' },+ toolName: 'runCommand',+ topicId: 'topic-1',+ });++ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({ sandboxSpecification: specification }),+ );+ });+// Regression: `input.userId` used to override `ctx.userId`, so any// authenticated caller could make the server mint another user's JWT into a// sandbox command they control (and read their skills/files).diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.tsindex e151d38735e..59f1322238c 100644--- a/apps/server/src/routers/tools/market.ts+++ b/apps/server/src/routers/tools/market.ts@@ -14,7 +14,7 @@ import { type ToolCallContent } from '@/libs/mcp';import { authedProcedure, router } from '@/libs/trpc/lambda';import { marketUserInfo, serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';import { marketSDK, requireMarketAuth } from '@/libs/trpc/lambda/middleware/marketSDK';-import { isTrustedClientEnabled } from '@/libs/trusted-client';+import { isTrustedClientEnabled, type TrustedClientUserInfo } from '@/libs/trusted-client';import { DiscoverService } from '@/server/services/discover';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';@@ -23,7 +23,7 @@ import {contentBlocksToString,processContentBlocks,} from '@/server/services/mcp/contentProcessor';-import { createSandboxService } from '@/server/services/sandbox';+import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';import { scheduleToolCallReport } from './_helpers';@@ -196,7 +196,9 @@ const execInSandboxHandler = async ({}: {ctx: {fileService: FileService;+ marketAccessToken?: string;marketService: MarketService;+ marketUserInfo?: TrustedClientUserInfo;serverDB: any;userId: string;workspaceId?: string | null;@@ -286,9 +288,40 @@ const execInSandboxHandler = async ({}}+ // The persistent workspace, resolved the same way the server runtimes do.+ // This route is the client-side executor's way into the sandbox โ the one a+ // conversation uses when its tool calls are not dispatched server-side โ+ // and it used to open a session with no mode, no directory and no claim.+ // Every run through here was therefore ephemeral: the composer showed the+ // instance the topic had chosen while `pwd` answered `/workspace`, and+ // whatever the run wrote went nowhere the file browser reads.+ const sandbox = await resolveSandboxSessionConfig({+ // Direct client call, so the caller is always acting as themselves.+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ topicId,+ userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });++ // The claim has to ride on the identity this call is signed with, not just+ // on the request: the execution plane reads the entitlement off the trusted+ // client token, and `ctx.marketService` was built before it was known.+ const marketService = sandbox.claim+ ? new MarketService({+ accessToken: ctx.marketAccessToken,+ userInfo: { ...ctx.marketUserInfo, sandboxStorage: sandbox.claim, userId: ctx.userId },+ })+ : ctx.marketService;+const sandboxService = createSandboxService({fileService: ctx.fileService,- marketService: ctx.marketService,+ marketService,+ sandboxCwd: sandbox.cwd,+ sandboxInstanceId: sandbox.environment,+ sandboxMode: sandbox.mode,+ sandboxSpecification: sandbox.specification,+ sandboxWorkingDir: sandbox.workingDir,serverDB: ctx.serverDB,topicId,userId,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 35da99bed6e..d066d9419ae 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1,5 +1,6 @@import type { AgentState } from '@lobechat/agent-runtime';import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';import type {ExecAgentResult,@@ -218,8 +219,11 @@ export class AiAgentService {};}- private async getMarketService(runFacts?: RunFacts): Promise<MarketService> {- if (this._marketService) return this._marketService;+ private async getMarketService(+ runFacts?: RunFacts,+ options?: { sandboxStorage: SandboxStorageClaim },+ ): Promise<MarketService> {+ if (!options && this._marketService) return this._marketService;// The turn's fact reader already holds this row when a run is underway// (`execAgent` asks it for the memory / timezone settings too); callers@@ -230,6 +234,21 @@ export class AiAgentService {).catch(() => undefined);const accessToken = (settings?.market as any)?.accessToken;+ // A sandbox-workspace claim is signed into the trust token, so a service+ // carrying one is built for that run and kept out of the shared cache.+ if (options) {+ return new MarketService({+ accessToken,+ userInfo: {+ sandboxStorage: options.sandboxStorage,+ userId: this.userId,+ // The claim resolves against the workspace's mirrored organization,+ // not the member's personal account, so the scope has to travel with it.+ workspaceId: this.workspaceId,+ },+ });+ }+this._marketService = new MarketService({accessToken,userInfo: { userId: this.userId },@@ -1279,7 +1298,7 @@ export class AiAgentService {{bindTopicWorkingDirectory: (p) => this.bindTopicWorkingDirectory(p),db: this.db,- getMarketService: () => this.getMarketService(runFacts),+ getMarketService: (options) => this.getMarketService(runFacts, options),messageModel: this.messageModel,resolveDeviceWorkspaceId: (deviceId) => this.resolveDeviceWorkspaceId(deviceId),topicModel: this.topicModel,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex b2cf8fbce91..87560218181 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -44,6 +44,10 @@ import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgimport { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';import type { MarketService } from '@/server/services/market';+import {+ resolveSandboxSessionConfig,+ type SandboxSessionConfig,+} from '@/server/services/sandbox/session';import {type DeviceDispatchRoute,@@ -65,7 +69,14 @@ const log = debug('lobe-server:ai-agent-service');export interface HeteroDispatchDeps {bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;db: LobeChatDatabase;- getMarketService: () => Promise<MarketService>;+ /**+ * With a `sandboxStorage` claim, a service whose trust token carries the+ * entitlement a persistent sandbox run needs โ built for that run rather+ * than taken from the cache, because the claim is signed into the token.+ */+ getMarketService: (options?: {+ sandboxStorage: NonNullable<SandboxSessionConfig['claim']>;+ }) => Promise<MarketService>;messageModel: MessageModel;resolveDeviceWorkspaceId: (deviceId: string | undefined) => Promise<string | undefined>;topicModel: TopicModel;@@ -470,6 +481,22 @@ export const dispatchHeteroAgent = async (}}+ // Where a cloud-sandbox run keeps its files: the same resolution the plain+ // cloud-sandbox runtime does, so a hetero topic bound to an environment+ // instance runs in that instance rather than in a throwaway box. Only for+ // providers the cloud sandbox can host at all; device-only providers never+ // read it. Never throws โ a failed lookup is the ephemeral sandbox.+ const sandbox = supportsCloudHeterogeneousSandbox(heteroType)+ ? await resolveSandboxSessionConfig({+ isShareVisitorRun: !!ctx.shareGate,+ serverDB: deps.db,+ topicId,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ })+ : undefined;+ const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };+// Build the primary context without conversation history. If native resume// fails, the CLI switches to the complete fallback prompt on its fresh// retry; successful same-session runs never consume the duplicate history.@@ -484,6 +511,7 @@ export const dispatchHeteroAgent = async (conversationHistory: resumeSessionId ? undefined : conversationHistory,githubToken,repos: topicRepos,+ sandbox: sandboxPlacement,});const resumeFallbackSystemContext =resumeSessionId && conversationHistory@@ -492,6 +520,7 @@ export const dispatchHeteroAgent = async (conversationHistory,githubToken,repos: topicRepos,+ sandbox: sandboxPlacement,}): undefined;@@ -1140,7 +1169,11 @@ export const dispatchHeteroAgent = async (// `aiAgent` import. Only this cloud-CLI branch needs it.const { spawnHeteroSandbox } =await import('@/server/services/heterogeneousAgent/sandboxRunner');- const marketService = await deps.getMarketService();+ // The entitlement rides on the trust token; without it the execution+ // plane routes to the ephemeral sandbox whatever the request says.+ const marketService = await deps.getMarketService(+ sandbox?.claim ? { sandboxStorage: sandbox.claim } : undefined,+ );// The sandbox authenticates its nested `lh` calls with this JWT. The// narrow `hetero-operation` token (used for the device-dispatch path// above) is rejected by `oidcAuth`, so CC capabilities that hit@@ -1156,6 +1189,16 @@ export const dispatchHeteroAgent = async (args: heteroExecArgs,jwt: sandboxJwt,marketService,+ sandbox: sandbox && {+ cwd: sandbox.cwd,+ environment: sandbox.environment,+ mode: sandbox.mode,+ // The environment's variables, network access, maintenance command+ // and sources all ride here; dropping it starts the run with none+ // of them, and nothing reports that they were ignored.+ specification: sandbox.specification,+ workingDir: sandbox.workingDir,+ },workspaceId: deps.workspaceId,}).catch(async (err) => {// Fire-and-forget: execAgent has already returned `autoStarted`, anddiff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex d89db1d773d..bfed214ac8b 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -511,6 +511,10 @@ export const setupTurn = async (...(editingGroupId && { editingGroupId }),taskId: operationTaskId,...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),+ ...(initialTopicMeta?.sandboxInstanceId && {+ sandboxInstanceId: initialTopicMeta.sandboxInstanceId,+ }),+ ...(initialTopicMeta?.sandboxMode && { sandboxMode: initialTopicMeta.sandboxMode }),...(initialTopicMeta?.workingDirectory && {workingDirectory: initialTopicMeta.workingDirectory,}),diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.tsnew file mode 100644index 00000000000..45e1485dd55--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/cloudHeteroContext.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { buildCloudHeteroContext } from '../cloudHeteroContext';++describe('buildCloudHeteroContext', () => {+ it('describes the ephemeral box at /workspace when no placement is given', () => {+ const context = buildCloudHeteroContext({ repos: ['lobehub/lobehub'] });++ expect(context).toContain('Your working directory is `/workspace`');+ expect(context).toContain('This sandbox is **ephemeral**');+ expect(context).toContain('- `/workspace/lobehub`');+ });++ it('renders an explicit ephemeral placement exactly like no placement', () => {+ const repos = ['lobehub/lobehub'];++ expect(buildCloudHeteroContext({ repos, sandbox: { mode: 'ephemeral' } })).toBe(+ buildCloudHeteroContext({ repos }),+ );+ });++ it('describes a persistent instance by its place in the workspace, never by an absolute path', () => {+ const context = buildCloudHeteroContext({+ repos: ['lobehub/lobehub'],+ sandbox: { cwd: 'lobehub-main', mode: 'persistent' },+ });++ expect(context).toContain('Your working directory is `lobehub-main`');+ expect(context).toContain('persistent workspace');+ 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**');+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.tsindex 0c3d2d79e48..669a5b0b6a2 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sandboxRunner.test.ts@@ -18,18 +18,70 @@ vi.mock('@/envs/app', () => ({appEnv: { APP_URL: 'https://app.example.com' },}));+const { mockCreateSandboxService } = vi.hoisted(() => ({+ mockCreateSandboxService: vi.fn(() => ({ callTool: mockCallTool })),+}));+vi.mock('@/server/services/sandbox', () => ({- createSandboxService: vi.fn(() => ({- callTool: mockCallTool,- })),+ createSandboxService: mockCreateSandboxService,}));describe('spawnHeteroSandbox', () => {beforeEach(() => {mockCallTool.mockClear();+ mockCreateSandboxService.mockClear();mockCallTool.mockResolvedValue({ success: true });});+ it('pins an ephemeral run to /workspace and asks for no persistence', async () => {+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockCallTool.mock.calls[0][1].command).toContain("'--cwd' '/workspace'");+ expect(mockCreateSandboxService).toHaveBeenCalledWith({+ marketService: {},+ sandboxCwd: undefined,+ sandboxInstanceId: undefined,+ sandboxMode: undefined,+ topicId: 'topic-1',+ userId: 'user-1',+ });+ });++ it('runs a persistent topic in its instance and leaves the cwd to the execution plane', async () => {+ // Regression: a topic bound to an environment instance used to run in the+ // throwaway box at /workspace, because the runner never forwarded the+ // topic's persistence and hard-coded the directory.+ await spawnHeteroSandbox({+ agentType: 'claude-code',+ assistantMessageId: 'msg-1',+ jwt: 'jwt',+ marketService: {} as any,+ operationId: 'op-1',+ prompt: 'hi',+ sandbox: { cwd: 'lobehub-main', environment: 'inst-1', mode: 'persistent' },+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(mockCallTool.mock.calls[0][1].command).not.toContain('--cwd');+ expect(mockCreateSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxCwd: 'lobehub-main',+ sandboxInstanceId: 'inst-1',+ sandboxMode: 'persistent',+ }),+ );+ });+it('forwards resolved selector args to lh hetero exec', async () => {await spawnHeteroSandbox({agentType: 'claude-code',diff --git a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.tsindex 9b884d50196..6730590c22f 100644--- a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts+++ b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts@@ -1,3 +1,5 @@+import type { SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';+export interface ConversationHistoryEntry {content: string;role: 'assistant' | 'user';@@ -17,6 +19,18 @@ export interface ConversationHistoryEntry {* via sandboxRunner โ spawnHeteroSandbox. If nothing meaningful to inject,* returns undefined so no extra block is added.*/+/**+ * 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.+ */+export interface CloudHeteroSandboxPlacement {+ /** Chosen subdirectory of the workspace, relative to its root. */+ cwd?: string;+ mode?: SandboxMode;+}+export function buildCloudHeteroContext(params: {repos: string[];/** Static systemContext from HeterogeneousProviderConfig.systemContext (agent-level). */@@ -29,8 +43,10 @@ export function buildCloudHeteroContext(params: {conversationHistory?: ConversationHistoryEntry[];/** GitHub OAuth token injected as GITHUB_TOKEN env var in the sandbox. */githubToken?: string;+ sandbox?: CloudHeteroSandboxPlacement;}): string {- const { repos, agentSystemContext, conversationHistory, githubToken } = params;+ const { repos, agentSystemContext, conversationHistory, githubToken, sandbox } = params;+ const persistent = sandbox?.mode === 'persistent';const parts: string[] = [];@@ -40,23 +56,48 @@ export function buildCloudHeteroContext(params: {}// --- Cloud workspace context ---+ // A persistent run is told what survives and what its neighbours are; the+ // push discipline stays, because a workspace on network storage is still not+ // where the source of truth for code lives.+ 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.",+ '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',+ 'Files in your working directory persist across sessions; anything written outside it may not.',+ 'The remote GitHub repository is still the source of truth for code:',+ '',+ '1. **Always commit and push** โ after making changes, run `git add`, `git commit`, and `git push`.',+ ' Never leave code changes uncommitted at the end of a task.',+ '2. **Confirm push success** โ verify with `git log --oneline origin/<branch>`',+ ' before reporting a task as complete.',+ '',+ ]+ : [+ '## Cloud Workspace',+ 'You are running inside a LobeHub cloud sandbox. Your working directory is `/workspace`.',+ '',+ '## Sandbox Persistence โ CRITICAL',+ 'This sandbox is **ephemeral**: it will be destroyed after ~1 hour of inactivity.',+ '**Any file changes that are not pushed to a remote will be permanently lost.**',+ '',+ 'Rules you MUST follow for every code change:',+ '',+ '1. **Always commit and push** โ after making changes, run `git add`, `git commit`, and `git push`.',+ ' Never leave code changes uncommitted at the end of a task.',+ '2. **Confirm push success** โ verify with `git log --oneline origin/<branch>`',+ ' before reporting a task as complete.',+ '3. **Never rely on local-only state** โ treat every file in `/workspace` as temporary.',+ ' The source of truth is the remote GitHub repository.',+ '',+ ];const workspaceLines: string[] = [- '## Cloud Workspace',- 'You are running inside a LobeHub cloud sandbox. Your working directory is `/workspace`.',- '',- '## Sandbox Persistence โ CRITICAL',- 'This sandbox is **ephemeral**: it will be destroyed after ~1 hour of inactivity.',- '**Any file changes that are not pushed to a remote will be permanently lost.**',- '',- 'Rules you MUST follow for every code change:',- '',- '1. **Always commit and push** โ after making changes, run `git add`, `git commit`, and `git push`.',- ' Never leave code changes uncommitted at the end of a task.',- '2. **Confirm push success** โ verify with `git log --oneline origin/<branch>`',- ' before reporting a task as complete.',- '3. **Never rely on local-only state** โ treat every file in `/workspace` as temporary.',- ' The source of truth is the remote GitHub repository.',- '',+ ...placementLines,'## Pushing to GitHub โ Public vs Private Repos','','Before pushing, check whether the repo is public or private:',@@ -115,21 +156,25 @@ export function buildCloudHeteroContext(params: {);}+ // Repos are cloned into the working directory, wherever that is: an absolute+ // path is only known for the ephemeral box.+ const repoRoot = persistent ? '.' : '/workspace';+ const repoRootLabel = persistent ? 'your working directory' : '`/workspace`';if (repos.length > 0) {workspaceLines.push('','## GitHub Repositories',- 'The following repositories were pre-cloned into `/workspace` before this conversation started:',+ `The following repositories were pre-cloned into ${repoRootLabel} before this conversation started:`,...repos.map((repo) => {const dir = repoToLocalDir(repo);const url = toGithubUrl(repo);- return `- \`/workspace/${dir}\` (${url})`;+ return `- \`${repoRoot}/${dir}\` (${url})`;}),'','You can start working in any of these directories immediately.',githubToken? 'If a directory is missing (clone may have failed), you can recover it yourself using the available GITHUB_TOKEN.'- : 'If a directory is missing (clone may have failed), you can run `git clone <url> /workspace/<dir>` yourself to recover it.',+ : `If a directory is missing (clone may have failed), you can run \`git clone <url> ${repoRoot}/<dir>\` yourself to recover it.`,);} else {workspaceLines.push(@@ -137,7 +182,7 @@ export function buildCloudHeteroContext(params: {'No GitHub repositories have been pre-cloned for this conversation.',githubToken? 'If you need a repository, you can clone it yourself using the available GITHUB_TOKEN.'- : 'If you need a repository, ask the user to add it in the repo selector, or clone it yourself with `git clone <url> /workspace/<dir>`.',+ : `If you need a repository, ask the user to add it in the repo selector, or clone it yourself with \`git clone <url> ${repoRoot}/<dir>\`.`,);}diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex e6aca1684e6..ce4cddfd316 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -11,6 +11,7 @@ import debug from 'debug';import { appEnv } from '@/envs/app';import type { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';+import type { SandboxSessionConfig } from '@/server/services/sandbox/session';const log = debug('lobe-server:hetero-sandbox-runner');@@ -43,6 +44,16 @@ export interface SandboxRunParams {/** Full system context used only by the automatic retry without native resume. */resumeFallbackSystemContext?: string;resumeSessionId?: string;+ /**+ * Where this run keeps its files โ the topic's persistence preferences as+ * `resolveSandboxSessionConfig` resolved them. Absent means the throwaway+ * sandbox every run used before persistence existed. The entitlement itself+ * travels on `marketService`'s trust token, not here.+ */+ sandbox?: Pick<+ SandboxSessionConfig,+ 'cwd' | 'environment' | 'mode' | 'specification' | 'workingDir'+ >;/*** Optional context injected as a text block BEFORE the user's prompt.* Useful for priming CC with workspace state (cloned repos, env info, etc.).@@ -145,16 +156,26 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidprompt,repos,resumeSessionId,+ sandbox,topicId,userId,workspaceId,} = params;- // For cloud sandbox, default cwd is /workspace โ must be explicit so CC stores and- // finds session files at the same path on every invocation (session files live under- // ~/.claude/projects/<encoded-cwd>/). Without a consistent --cwd the session id stored- // in topic.metadata.heteroSessionId can't be resolved on --resume after a page reload.- const cwd = params.cwd ?? '/workspace';+ // For the ephemeral sandbox the cwd is /workspace, and it must be explicit so+ // CC stores and finds session files at the same path on every invocation+ // (session files live under ~/.claude/projects/<encoded-cwd>/). Without a+ // 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+ // 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 cwd = params.cwd ?? (persistent ? undefined : '/workspace');// Build the `lh hetero exec` command string.// Prompt is passed via --input-json stdin ('-') to avoid shell quoting issues@@ -177,7 +198,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidif (resumeSessionId) {args.push('--resume', resumeSessionId);}- args.push('--cwd', cwd);+ if (cwd) args.push('--cwd', cwd);args.push(...(extraArgs ?? []));// Encode the prompt as base64 to avoid all shell quoting issues.@@ -224,7 +245,16 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidtopicId,);- const sandboxService = createSandboxService({ marketService, topicId, userId });+ const sandboxService = createSandboxService({+ marketService,+ sandboxCwd: sandbox?.cwd,+ sandboxInstanceId: sandbox?.environment,+ sandboxMode: sandbox?.mode,+ sandboxSpecification: sandbox?.specification,+ sandboxWorkingDir: sandbox?.workingDir,+ topicId,+ userId,+ });const result = await sandboxService.callTool('runCommand', {background: true,command: shellCommand,diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.tsindex 6d5c452166a..3680087fdc5 100644--- a/apps/server/src/services/market/index.ts+++ b/apps/server/src/services/market/index.ts@@ -7,6 +7,10 @@ import pMap from 'p-map';import { type TrustedClientUserInfo } from '@/libs/trusted-client';import { generateTrustedClientToken, getTrustedClientTokenForSession } from '@/libs/trusted-client';+import {+ createSandboxStorageClient,+ type SandboxStorageClient,+} from '@/server/services/sandbox/storageFiles';import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';import {@@ -948,6 +952,21 @@ export class MarketService {return result;}+ /**+ * Client for the persistent sandbox workspace's file API.+ *+ * Not on the SDK yet, so it is hand-written against the same endpoints; it+ * lives in its own module and only borrows this service's auth headers, so+ * replacing it with the generated client later is a deletion. The workspace it+ * addresses is always the one the caller's signed entitlement names.+ */+ getSandboxStorageClient(): SandboxStorageClient {+ return createSandboxStorageClient({+ baseURL: MARKET_BASE_URL,+ headers: this.oauthProxyHeaders,+ });+ }+// ============================== Direct SDK Access ==============================/**diff --git a/apps/server/src/services/sandbox/__tests__/entitlement.test.ts b/apps/server/src/services/sandbox/__tests__/entitlement.test.tsnew file mode 100644index 00000000000..92671cd0abe--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/entitlement.test.ts@@ -0,0 +1,133 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const resolveSandboxStorageEntitlement = vi.fn();+const getUserPreference = vi.fn();++vi.mock('@/business/server/sandboxStorage', () => ({+ resolveSandboxStorageEntitlement: (...args: unknown[]) =>+ resolveSandboxStorageEntitlement(...args),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function () {+ return { getUserPreference };+ }),+}));++const { resolveSandboxStorageClaim } = await import('../entitlement');++const serverDB = {} as LobeChatDatabase;++const resolve = (overrides: Record<string, unknown> = {}) =>+ resolveSandboxStorageClaim({+ isShareVisitorRun: false,+ serverDB,+ userId: 'user_1',+ ...overrides,+ });++describe('resolveSandboxStorageClaim', () => {+ beforeEach(() => {+ resolveSandboxStorageEntitlement.mockReset();+ getUserPreference.mockReset();+ getUserPreference.mockResolvedValue({ lab: { enablePersistentSandbox: true } });+ resolveSandboxStorageEntitlement.mockResolvedValue({ quotaBytes: 2048 });+ });++ it('pairs the derived key with the plan quota', async () => {+ await expect(resolve()).resolves.toEqual({ key: 'ws-user_1', quotaBytes: 2048 });+ });++ it('passes the overage licence through, and only when granted', async () => {+ // The execution plane is told the answer, never the inputs โ and absent+ // has to read as no, so a deployment that says nothing cannot bill anyone.+ resolveSandboxStorageEntitlement.mockResolvedValue({+ overageAllowed: true,+ quotaBytes: 2048,+ });++ await expect(+ resolveSandboxStorageClaim({ isShareVisitorRun: false, serverDB: {} as any, userId: 'u1' }),+ ).resolves.toMatchObject({ overageAllowed: true });++ resolveSandboxStorageEntitlement.mockResolvedValue({ quotaBytes: 2048 });++ expect(+ await resolveSandboxStorageClaim({+ isShareVisitorRun: false,+ serverDB: {} as any,+ userId: 'u1',+ }),+ ).not.toHaveProperty('overageAllowed');+ });++ it('judges an organization run by its workspace', async () => {+ resolveSandboxStorageEntitlement.mockResolvedValue({ quotaBytes: 4096 });++ await expect(resolve({ workspaceId: 'wsp_42' })).resolves.toEqual({+ key: 'ws-org-wsp_42',+ quotaBytes: 4096,+ });+ expect(resolveSandboxStorageEntitlement).toHaveBeenCalledWith({+ userId: 'user_1',+ workspaceId: 'wsp_42',+ });+ });++ // The lab flag is the whole feature's gate: without a claim the execution+ // plane routes to the ephemeral sandbox whatever mode the request asks for.+ it('issues nothing until the lab experiment is switched on', async () => {+ for (const lab of [undefined, {}, { enablePersistentSandbox: false }]) {+ getUserPreference.mockResolvedValue(lab === undefined ? undefined : { lab });+ await expect(resolve()).resolves.toBeNull();+ }++ expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();+ });++ // A share visitor's run executes under the CREATOR's identity, so every input+ // here describes the creator. A claim would hand the visitor the creator's+ // working directory.+ it('issues nothing for a share-visitor run, without reading the creator at all', async () => {+ await expect(resolve({ isShareVisitorRun: true })).resolves.toBeNull();++ expect(getUserPreference).not.toHaveBeenCalled();+ expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();+ });++ it('is null for a plan with no persistence', async () => {+ resolveSandboxStorageEntitlement.mockResolvedValue(null);++ await expect(resolve()).resolves.toBeNull();+ });++ // A key with no quota is not an entitlement. The receiving end rejects the+ // WHOLE token on a malformed claim, so a zero or fractional quota must never+ // leave here.+ it('rejects a quota that is not a usable size', async () => {+ for (const quota of [0, -1, 1.5, Number.NaN, Number.MAX_SAFE_INTEGER + 2, '2048']) {+ resolveSandboxStorageEntitlement.mockResolvedValue(quota);+ await expect(resolve()).resolves.toBeNull();+ }+ });++ // An unsafe id costs persistence, not the whole request.+ it('skips both lookups when no safe key can be derived', async () => {+ await expect(resolve({ userId: '../etc/passwd' })).resolves.toBeNull();++ expect(getUserPreference).not.toHaveBeenCalled();+ expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();+ });++ // Losing either lookup must degrade to an ephemeral sandbox โ the behaviour+ // every session has today โ not fail the tool call.+ it('degrades to no entitlement when a lookup throws', async () => {+ getUserPreference.mockRejectedValue(new Error('db down'));+ await expect(resolve()).resolves.toBeNull();++ getUserPreference.mockResolvedValue({ lab: { enablePersistentSandbox: true } });+ resolveSandboxStorageEntitlement.mockRejectedValue(new Error('entitlement lookup failed'));+ await expect(resolve()).resolves.toBeNull();+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/session.test.ts b/apps/server/src/services/sandbox/__tests__/session.test.tsnew file mode 100644index 00000000000..c1a794d4e00--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts@@ -0,0 +1,338 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ EnvironmentInstanceModel: vi.fn(),+ TopicModel: vi.fn(),+ findById: vi.fn(),+ getAgentVisibility: vi.fn(),+ findInstanceById: vi.fn(),+ resolveSandboxStorageClaim: vi.fn(),+}));++const { findById, findInstanceById, getAgentVisibility, resolveSandboxStorageClaim } = mocks;++vi.mock('../entitlement', () => ({+ resolveSandboxStorageClaim: mocks.resolveSandboxStorageClaim,+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: mocks.TopicModel,+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(function () {+ return { getAgentVisibility: mocks.getAgentVisibility };+ }),+}));++vi.mock('@/database/models/environmentInstance', () => ({+ EnvironmentInstanceModel: mocks.EnvironmentInstanceModel,+}));++const { resolveSandboxSessionConfig } = await import('../session');++const serverDB = {} as LobeChatDatabase;+const CLAIM = { key: 'ws-user_1', quotaBytes: 2048 };+const INSTANCE_ID = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';++const resolve = (overrides: Record<string, unknown> = {}) =>+ resolveSandboxSessionConfig({+ isShareVisitorRun: false,+ serverDB,+ topicId: 'topic-1',+ userId: 'user_1',+ ...overrides,+ });++describe('resolveSandboxSessionConfig', () => {+ beforeEach(() => {+ resolveSandboxStorageClaim.mockReset();+ findById.mockReset();+ findInstanceById.mockReset();+ getAgentVisibility.mockReset();+ mocks.EnvironmentInstanceModel.mockReset();+ mocks.TopicModel.mockReset();+ mocks.TopicModel.mockImplementation(function () {+ return { findById };+ });+ mocks.EnvironmentInstanceModel.mockImplementation(function () {+ return { findById: findInstanceById };+ });+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);+ findById.mockResolvedValue({+ metadata: { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'persistent' },+ });+ findInstanceById.mockResolvedValue({+ id: INSTANCE_ID,+ workingDirectory: 'projects/atlas',+ });+ });++ // The instance is one choice with two halves: the directory it works in and+ // the state restored into it. The snapshot is addressed by the instance's own+ // id, which is why two copies of one environment never read each other's.+ it('carries the claim, the mode and the chosen instance', async () => {+ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ cwd: 'projects/atlas',+ environment: INSTANCE_ID,+ mode: 'persistent',+ });+ });++ // A built instance's checkout lives on the sandbox's local disk, so commands+ // run there โ while `cwd` keeps naming the instance's directory on the+ // volume, which is what the call belongs to and may see (LOBE-14363).+ it('runs a built repository instance on local disk, scoped to its directory', async () => {+ findInstanceById.mockResolvedValue({+ configurationSnapshot: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },+ id: INSTANCE_ID,+ status: 'ready',+ workingDirectory: 'projects/atlas',+ });++ await expect(resolve()).resolves.toEqual({+ claim: CLAIM,+ cwd: 'projects/atlas',+ environment: INSTANCE_ID,+ mode: 'persistent',+ specification: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },+ workingDir: '/root/work',+ });+ });++ // Regression (LOBE-14442): the definition never reached a conversation, so+ // the declared variables were missing from the agent's shell, the+ // maintenance command never ran once, and the environment's network switch+ // could not cut anything. All three are the execution plane acting on this+ // object, and it only ever received it for a build.+ it('carries the definition the instance was built from', async () => {+ findInstanceById.mockResolvedValue({+ configurationSnapshot: {+ env: { API_URL: 'https://example.com', NODE_ENV: 'production' },+ excludePaths: ['node_modules'],+ internetAccess: false,+ maintenanceCommand: 'git pull --ff-only',+ },+ id: INSTANCE_ID,+ workingDirectory: 'projects/atlas',+ });++ await expect(resolve()).resolves.toMatchObject({+ specification: {+ env: { API_URL: 'https://example.com', NODE_ENV: 'production' },+ excludePaths: ['node_modules'],+ internetAccess: false,+ maintenanceCommand: 'git pull --ff-only',+ },+ });+ });++ // The column is `jsonb`: its type says "no credentials", but it holds+ // whatever was written to it, and this object now leaves the server on every+ // tool call. So the pick is by name โ a key nobody here chose does not+ // travel just because it turned up in the row.+ it('sends only the named fields, whatever else the row holds', async () => {+ findInstanceById.mockResolvedValue({+ configurationSnapshot: {+ credentials: [{ headers: { Authorization: 'Bearer nope' }, host: 'github.com' }],+ env: { NODE_ENV: 'production' },+ requirements: { memoryGiB: 8 },+ },+ id: INSTANCE_ID,+ workingDirectory: 'projects/atlas',+ });++ const { specification } = await resolve();+ expect(specification).toEqual({ env: { NODE_ENV: 'production' } });+ });++ // An empty pick is not an empty object: the runtime adopts whatever it is+ // handed, so a definition with nothing to say must send nothing and leave+ // the session's own defaults alone.+ it.each([+ ['no definition at all', undefined],+ ['a definition with nothing this session acts on', { requirements: { cpu: 2 } }],+ ['an empty variable map', { env: {} }],+ ])('sends no specification for %s', async (_, configurationSnapshot) => {+ findInstanceById.mockResolvedValue({+ configurationSnapshot,+ id: INSTANCE_ID,+ workingDirectory: 'projects/atlas',+ });++ expect(await resolve()).not.toHaveProperty('specification');+ });++ it.each([+ ['not built yet', { status: 'pending' }],+ ['a failed build', { status: 'error' }],+ ['nothing to clone', { configurationSnapshot: { bootstrapCommand: 'echo' }, status: 'ready' }],+ ])('keeps an instance with %s on the volume', async (_, fields) => {+ findInstanceById.mockResolvedValue({+ configurationSnapshot: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },+ id: INSTANCE_ID,+ workingDirectory: 'projects/atlas',+ ...fields,+ });++ const config = await resolve();+ expect(config).not.toHaveProperty('workingDir');+ expect(config.cwd).toBe('projects/atlas');+ });++ // Without an entitlement the execution plane routes to the ephemeral sandbox+ // 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 () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);++ await expect(resolve()).resolves.toEqual({ claim: null, mode: 'ephemeral' });+ expect(findById).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' }]) {+ findById.mockResolvedValue({ metadata });+ await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'ephemeral' });+ }+ });++ // 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' } });++ await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'persistent' });+ expect(findInstanceById).not.toHaveBeenCalled();+ });++ // 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 () => {+ findInstanceById.mockResolvedValue(undefined);++ await expect(resolve()).resolves.toEqual({ claim: CLAIM, mode: 'persistent' });+ });++ // 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.+ 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' });+ });++ // A workspace-public agent runs on its caller's session; a private+ // environment's captured state can hold that caller's credentials. The+ // instance is looked up as the public agent, so a private one does not+ // resolve. The run falls back to a temporary directory, never to the shared+ // workspace root, where the private instance's directory would still be+ // reachable โ and the composer tells the person why.+ it('looks the instance up as a public agent inside a workspace', async () => {+ findById.mockResolvedValue({+ agentId: 'agent-shared',+ metadata: { sandboxInstanceId: INSTANCE_ID, sandboxMode: 'persistent' },+ });+ getAgentVisibility.mockResolvedValue('public');+ findInstanceById.mockResolvedValue(undefined);++ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({+ claim: CLAIM,+ mode: 'ephemeral',+ });+ // The topic is read in the workspace's scope; in the personal scope a+ // workspace topic does not resolve and the run would lose its instance.+ expect(mocks.TopicModel).toHaveBeenCalledWith(serverDB, 'user_1', 'ws-1');+ expect(getAgentVisibility).toHaveBeenCalledWith('agent-shared');+ expect(mocks.EnvironmentInstanceModel).toHaveBeenCalledWith(+ serverDB,+ 'user_1',+ 'ws-1',+ 'public',+ );+ });++ // 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' },+ });++ await expect(resolve()).resolves.toMatchObject({ environment: INSTANCE_ID });+ expect(getAgentVisibility).not.toHaveBeenCalled();+ expect(mocks.EnvironmentInstanceModel).toHaveBeenCalledWith(+ serverDB,+ 'user_1',+ undefined,+ null,+ );+ });++ it('stays ephemeral for a share-visitor run', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(null);++ await expect(resolve({ isShareVisitorRun: true })).resolves.toEqual({+ claim: null,+ mode: 'ephemeral',+ });+ expect(resolveSandboxStorageClaim).toHaveBeenCalledWith(+ expect.objectContaining({ isShareVisitorRun: true }),+ );+ });++ // A topic read that fails must not fail the tool call; it costs persistence+ // for this turn, which is what every session does today anyway.+ 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' });+ });++ 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' });+ });++ it('needs no topic to resolve the entitlement', async () => {+ await expect(resolve({ topicId: undefined })).resolves.toEqual({+ claim: CLAIM,+ mode: 'ephemeral',+ });+ expect(findById).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/storageFiles.test.ts b/apps/server/src/services/sandbox/__tests__/storageFiles.test.tsnew file mode 100644index 00000000000..e3ea4d88952--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/storageFiles.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createSandboxStorageClient, SandboxStorageFilesError } from '../storageFiles';++const client = createSandboxStorageClient({ baseURL: 'http://market.test', headers: {} });++const respond = (status: number, body: unknown) =>+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ headers: { 'Content-Type': 'application/json' },+ status,+ }),+ ),+ );++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('createSandboxStorageClient', () => {+ it('should surface the market reason when a request fails', async () => {+ // The market answers a failed file operation with OAuth-style+ // `error` / `error_description`, not `message`.+ respond(500, {+ error: 'tool_execution_failed',+ error_description: 'Could not delete: reports',+ });++ const error = await client.deleteFile({ path: 'reports', recursive: true }).catch((e) => e);++ expect(error).toBeInstanceOf(SandboxStorageFilesError);+ expect(error.status).toBe(500);+ expect(error.message).toBe('Could not delete: reports');+ });++ it('should fall back to the status when the body carries no reason', async () => {+ respond(500, { error: 'workspace_delete_failed' });++ const error = await client.deleteFile({ path: 'reports' }).catch((e) => e);++ expect(error.message).toBe('Workspace request failed with status 500');+ });++ it('should send a build its specification as JSON', async () => {+ // Without the content type the market parses no body at all and answers+ // every build with "specification: Required".+ respond(200, { data: { buildId: 'build-1' } });++ await client.buildInstance({+ instanceDir: 'app-dev',+ name: 'env-1',+ specification: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },+ });++ const [url, init] = (fetch as any).mock.calls[0];+ expect(url).toBe('http://market.test/api/v1/sandbox/storages/current/instances/env-1/build');+ expect(init.headers['Content-Type']).toBe('application/json');+ expect(JSON.parse(init.body).specification.sources[0].url).toBe('https://github.com/a/b');+ expect(JSON.parse(init.body).instanceDir).toBe('app-dev');+ });++ it('should read one environment run history from the control plane', async () => {+ const page = { nextBefore: null, sessions: [] };+ respond(200, { data: page });++ const result = await client.listEnvironmentSessions({+ before: '2026-09-01T00:00:00.000Z',+ limit: 5,+ name: 'env id',+ });++ expect(result).toEqual(page);+ const [url] = (fetch as any).mock.calls[0];+ expect(url).toBe(+ 'http://market.test/api/v1/sandbox/storages/current/instances/env%20id/sessions?limit=5&before=2026-09-01T00%3A00%3A00.000Z',+ );+ });+});diff --git a/apps/server/src/services/sandbox/__tests__/workspace.test.ts b/apps/server/src/services/sandbox/__tests__/workspace.test.tsnew file mode 100644index 00000000000..032da65751e--- /dev/null+++ b/apps/server/src/services/sandbox/__tests__/workspace.test.ts@@ -0,0 +1,218 @@+import {+ DEFAULT_SANDBOX_MODE,+ deriveSandboxStorageKey,+ formatSandboxStoragePrompt,+ formatSandboxStoragePromptVariables,+ isSafeSandboxCwd,+ isSafeSandboxEnvironmentId,+ type SandboxStoragePromptVariables,+ systemPrompt,+} from '@lobechat/builtin-tool-cloud-sandbox';+import { describe, expect, it } from 'vitest';++describe('deriveSandboxStorageKey', () => {+ it('uses the personal key when no workspace is scoped', () => {+ expect(deriveSandboxStorageKey({ userId: 'user_abc' })).toBe('ws-user_abc');+ expect(deriveSandboxStorageKey({ userId: 'user_abc', workspaceId: null })).toBe('ws-user_abc');+ });++ it('shares one key across an organization workspace', () => {+ expect(deriveSandboxStorageKey({ userId: 'user_abc', workspaceId: 'wsp_42' })).toBe(+ 'ws-org-wsp_42',+ );+ });++ // The key names a directory on a shared volume and is signed into the claim.+ // Refusing beats sanitizing: `user_a/b` and `user_a-b` would both reduce to+ // `ws-user_a-b`, and a length cap aliases every id sharing a prefix โ either+ // way two principals land in ONE directory and read each other's files.+ it('refuses an id that is not already a safe path segment', () => {+ expect(deriveSandboxStorageKey({ userId: '../etc/passwd' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: '$(rm -rf /)' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: 'user a' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: 'รฉvil' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: '' })).toBeUndefined();+ expect(deriveSandboxStorageKey({ userId: 'u', workspaceId: 'wsp/42' })).toBeUndefined();+ // Over the 128-char ceiling the receiving end enforces.+ expect(deriveSandboxStorageKey({ userId: 'x'.repeat(200) })).toBeUndefined();+ });++ // Two ids that differ at all must never produce the same key.+ it('is injective for the id shapes the platform issues', () => {+ const keys = ['user_a_b', 'user_a-b', 'user_ab', 'user_A_B'].map((userId) =>+ deriveSandboxStorageKey({ userId }),+ );++ expect(keys.every(Boolean)).toBe(true);+ expect(new Set(keys).size).toBe(keys.length);+ });++ // Both shapes share one namespace, so `ws-<userId>` with a userId of+ // `org-wsp_42` would address the very directory the workspace `wsp_42` uses.+ 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();+ });+});++describe('formatSandboxStoragePromptVariables', () => {+ const placeholders = ['{{sandbox_workspace}}', '{{sandbox_session_files}}'];+ const render = (vars: SandboxStoragePromptVariables) =>+ placeholders.reduce(+ (acc, key) => acc.replaceAll(key, vars[key.slice(2, -2) as keyof typeof vars]),+ systemPrompt,+ );++ it('defaults to ephemeral', () => {+ expect(DEFAULT_SANDBOX_MODE).toBe('ephemeral');+ expect(formatSandboxStoragePromptVariables()).toEqual(+ formatSandboxStoragePromptVariables({ mode: 'ephemeral' }),+ );+ expect(formatSandboxStoragePrompt()).toBe(+ formatSandboxStoragePromptVariables().sandbox_workspace,+ );+ });++ // Persistence is not enabled yet: until an entitlement claim is issued every+ // run renders this branch, so it has to reproduce the pre-placeholder prompt+ // exactly โ including the lines surrounding the two spliced sections.+ it('renders the original ephemeral wording, byte for byte', () => {+ const vars = formatSandboxStoragePromptVariables();+ const rendered = render(vars);++ for (const key of placeholders) expect(rendered).not.toContain(key);+ expect(rendered).toContain(+ '- Files created here are temporary and session-specific\n- Each conversation topic has its own isolated session\n- Sessions may expire after inactivity; files will be recreated if needed\n- The sandbox has its own isolated file system starting at the root directory\n- Commands will time out',+ );+ expect(rendered).toContain(+ '- If a session expires, it will be automatically recreated\n- Files from previous sessions may not persist\n- The sessionExpiredAndRecreated flag',+ );+ });++ it('describes a persistent workspace without naming a directory', () => {+ const vars = formatSandboxStoragePromptVariables({ mode: 'persistent' });+ const rendered = render(vars);++ for (const key of placeholders) expect(rendered).not.toContain(key);+ expect(vars.sandbox_workspace).toContain('persistent workspace');+ // 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.+ expect(vars.sandbox_workspace).toContain('network storage');+ // The copy does name `/tmp` and `/root`, on purpose: as the places whose+ // contents are lost, never as somewhere to work. What has to hold is that+ // they are always paired with that loss, so naming one cannot read as an+ // invitation. The mount path itself is covered by its own case below.+ expect(vars.sandbox_workspace).toContain('lost with the session');+ expect(rendered).not.toContain('temporary and session-specific');+ expect(rendered).not.toContain('Files from previous sessions may not persist');+ });++ it('names the chosen subdirectory and places it under the workspace root', () => {+ const vars = formatSandboxStoragePromptVariables({+ cwd: 'projects/atlas',+ mode: 'persistent',+ });++ expect(vars.sandbox_workspace).toContain('`projects/atlas`');+ expect(vars.sandbox_workspace).toContain('workspace root is above you');+ // 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');+ });++ it('ignores a subdirectory on an ephemeral run', () => {+ expect(+ formatSandboxStoragePromptVariables({ cwd: 'projects/atlas', mode: 'ephemeral' }),+ ).toEqual(formatSandboxStoragePromptVariables());+ });++ // The mount root belongs to the execution plane. Spelling an absolute path+ // out here would be a second source of truth that can only drift, and a+ // model that wrote one down would keep using it after the root moved.+ it('never hardcodes a mount path', () => {+ for (const input of [+ { mode: 'persistent' } as const,+ { cwd: 'a/b', mode: 'persistent' } as const,+ ]) {+ const vars = formatSandboxStoragePromptVariables(input);+ expect(vars.sandbox_workspace).not.toContain('/mnt/');+ expect(vars.sandbox_workspace).not.toContain('ws-');+ expect(vars.sandbox_session_files).not.toContain('/mnt/');+ }+ });+});++describe('isSafeSandboxCwd', () => {+ it('accepts a relative subdirectory', () => {+ expect(isSafeSandboxCwd('projects/atlas')).toBe(true);+ expect(isSafeSandboxCwd('a')).toBe(true);+ // A space is a legal directory name, not something to tidy away.+ expect(isSafeSandboxCwd('my notes/draft 1')).toBe(true);+ // Only the TOP-level `.sandbox` is reserved โ one the user made deeper in+ // their own tree is an ordinary directory.+ expect(isSafeSandboxCwd('projects/.sandbox')).toBe(true);+ // Interior whitespace is an ordinary directory name, not a hazard.+ expect(isSafeSandboxCwd('a b/c d')).toBe(true);+ });++ // Rejecting, never repairing: collapsing `..` lexically disagrees with the+ // filesystem across a symlink, so a "cleaned" path can resolve somewhere+ // other than where it was judged safe.+ it('rejects traversal, absolute and shell-expanded paths', () => {+ for (const value of [+ '',+ '..',+ '../other-user',+ 'projects/../../etc',+ './projects',+ '/mnt/workspace/ws-other',+ '~/secrets',+ 'projects//atlas',+ 'projects/atlas/',+ '/',+ // The runtime strips the directory string while the shell `cd` keeps+ // its quotes, so these would leave the session disagreeing with itself+ // about where it is.+ 'drafts ',+ ' drafts',+ 'projects/atlas ',+ // The platform's own state lives here; a working directory pointed at it+ // would let an agent trample the store its environment is restored from.+ '.sandbox',+ '.sandbox/envs',+ 'x'.repeat(1025),+ ]) {+ expect(isSafeSandboxCwd(value)).toBe(false);+ }+ });+});++describe('isSafeSandboxEnvironmentId', () => {+ it('accepts the identifiers this platform issues', () => {+ expect(isSafeSandboxEnvironmentId('env_9aB3xQ')).toBe(true);+ expect(isSafeSandboxEnvironmentId('default')).toBe(true);+ // A uuid, in case environments are ever keyed by one.+ expect(isSafeSandboxEnvironmentId('0f8c1e2a-4b6d-4c9e-8a1f-2d3e4f5a6b7c')).toBe(true);+ });++ // Checked on this side as well as the far one because of WHERE the far one+ // fails: the session runs to completion and the snapshot is refused at the+ // end, so the work is done and there is nowhere to put it.+ it('refuses what the execution plane would reject at snapshot time', () => {+ for (const value of [+ '',+ // A leading underscore is fine in a workspace key and not here โ the two+ // rules are deliberately different.+ '_leading',+ '.hidden',+ '-dash',+ 'has/slash',+ 'has space',+ 'รฉvil',+ 'x'.repeat(65),+ ]) {+ expect(isSafeSandboxEnvironmentId(value)).toBe(false);+ }+ });+});diff --git a/apps/server/src/services/sandbox/entitlement.ts b/apps/server/src/services/sandbox/entitlement.tsnew file mode 100644index 00000000000..fda4b409dc6--- /dev/null+++ b/apps/server/src/services/sandbox/entitlement.ts@@ -0,0 +1,83 @@+import {+ deriveSandboxStorageKey,+ type SandboxStorageClaim,+ type SandboxStorageScope,+} from '@lobechat/builtin-tool-cloud-sandbox';+import type { LobeChatDatabase } from '@lobechat/database';+import debug from 'debug';++import { resolveSandboxStorageEntitlement } from '@/business/server/sandboxStorage';+import { UserModel } from '@/database/models/user';++const log = debug('lobe-server:sandbox:entitlement');++export interface SandboxStorageClaimInput extends SandboxStorageScope {+ /**+ * Whether this run is an Agent Share visitor's. Required rather than optional:+ * such a run executes under the CREATOR's identity, so every input this+ * function reads โ the lab flag, the plan, the key โ describes the creator,+ * not the person at the keyboard. Issuing a claim would hand a visitor the+ * creator's working directory, with everything their other conversations left+ * in it, to read and overwrite. Making the caller state it means a new call+ * site cannot inherit the dangerous answer by saying nothing.+ */+ isShareVisitorRun: boolean;+ serverDB: LobeChatDatabase;+}++/**+ * Resolve the persistent-workspace entitlement for a principal into the claim+ * that gets signed onto the trusted-client token.+ *+ * Three things must all hold, and the order is deliberate โ cheapest and most+ * selective first:+ *+ * 1. The run is the principal's own (not a share visitor's).+ * 2. Their identity yields a safe directory name.+ * 3. They opted into the `enablePersistentSandbox` lab experiment, and their+ * plan entitles them to storage.+ *+ * Returns `null` for "no persistent workspace", which is the shape the+ * execution plane reads as free tier. Without a claim its routing sends the run+ * to the ephemeral sandbox no matter what mode the request asks for, so this is+ * the single gate for the whole feature: nothing a client sends can open it.+ *+ * Never throws: a preference or subscription lookup that fails must not take+ * the sandbox down with it. The run degrades to an ephemeral sandbox, which is+ * what every session does today.+ */+export const resolveSandboxStorageClaim = async ({+ isShareVisitorRun,+ serverDB,+ userId,+ workspaceId,+}: SandboxStorageClaimInput): Promise<SandboxStorageClaim | null> => {+ if (isShareVisitorRun) return null;++ const key = deriveSandboxStorageKey({ userId, workspaceId });+ if (!key) return null;++ try {+ // Opt-in is per USER even for an organization run, like every other lab+ // experiment. The consequence is worth knowing: in a workspace where only+ // some members have switched it on, the shared directory is there for their+ // runs and absent for everyone else's.+ const preference = await new UserModel(serverDB, userId).getUserPreference();+ if (preference?.lab?.enablePersistentSandbox !== true) return null;++ const entitlement = await resolveSandboxStorageEntitlement({ userId, workspaceId });+ const quotaBytes = entitlement?.quotaBytes;+ if (typeof quotaBytes !== 'number' || !Number.isSafeInteger(quotaBytes) || quotaBytes <= 0) {+ return null;+ }++ // Only when true. An entitlement that says nothing about overage means the+ // quota is a hard limit โ the reading that cannot bill anyone by accident.+ return entitlement?.overageAllowed+ ? { key, overageAllowed: true, quotaBytes }+ : { key, quotaBytes };+ } catch (error) {+ log('Failed to resolve the sandbox workspace entitlement for %s: %O', key, error);+ return null;+ }+};diff --git a/apps/server/src/services/sandbox/index.ts b/apps/server/src/services/sandbox/index.tsindex 9031b0440ec..77e380aaedf 100644--- a/apps/server/src/services/sandbox/index.ts+++ b/apps/server/src/services/sandbox/index.ts@@ -1,7 +1,10 @@+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 { resolveSandboxSessionConfig } from './session';export type {SandboxFileExporter,SandboxProvider,@@ -9,4 +12,5 @@ export type {SandboxService,SandboxServiceOptions,SandboxSessionContext,+ SandboxSessionSpecification,} from './types';diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.tsindex 924f6353f98..7290ad25282 100644--- a/apps/server/src/services/sandbox/providers/market.test.ts+++ b/apps/server/src/services/sandbox/providers/market.test.ts@@ -44,6 +44,32 @@ describe('MarketSandboxProvider', () => {});});+ // The instance the call belongs to and where it runs travel together: the+ // execution plane scopes a shared workspace by the first and runs commands+ // in the second (LOBE-14363).+ it('forwards the instance directory and the local working directory together', async () => {+ const runBuildInTool = vi.fn(async () => ({ data: { result: {} }, success: true }));+ const marketService = {+ getSDK: vi.fn(() => ({ plugins: { runBuildInTool } })),+ } as unknown as MarketService;+ const provider = new MarketSandboxProvider({+ marketService,+ sandboxCwd: 'projects/atlas',+ sandboxMode: 'persistent',+ sandboxWorkingDir: '/root/work',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ await provider.callTool('runCommand', { command: 'pwd' });++ expect(runBuildInTool).toHaveBeenCalledWith(+ 'runCommand',+ { command: 'pwd' },+ expect.objectContaining({ sandboxCwd: 'projects/atlas', sandboxWorkingDir: '/root/work' }),+ );+ });+it('keeps the previous Market sandbox callTool error mapping', async () => {const marketService = createMarketService({error: {diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex 59c7c378a3e..8698bd21d5f 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -52,22 +52,43 @@ export class MarketSandboxProvider implements SandboxProvider {toolName: string,params: Record<string, unknown>,): Promise<SandboxCallToolResult> {- const { marketService, topicId, userId } = this.options;+ const {+ marketService,+ sandboxCwd,+ sandboxInstanceId,+ sandboxMode,+ sandboxSpecification,+ sandboxWorkingDir,+ topicId,+ userId,+ } = this.options;log(- 'Calling sandbox tool: %s with params: %O, topicId: %s',+ 'Calling sandbox tool: %s with params: %O, topicId: %s, mode: %s',toolName,redactSandboxParams(params),topicId,+ sandboxMode ?? 'ephemeral',);try {- const response = await marketService- .getSDK()- .plugins.runBuildInTool(toolName as CodeInterpreterToolName, params as never, {+ const response = await marketService.getSDK().plugins.runBuildInTool(+ toolName as CodeInterpreterToolName,+ params as never,+ {+ // Cast: the published SDK's context type predates both fields. Market+ // validates the request body with a non-strict schema, so a field it+ // does not know yet is dropped rather than rejected โ which is what+ // `sandboxCwd` relies on until the execution plane consumes it.+ ...(sandboxMode && { sandboxMode }),+ ...(sandboxCwd && { sandboxCwd }),+ ...(sandboxWorkingDir && { sandboxWorkingDir }),+ ...(sandboxInstanceId && { sandboxInstanceId }),+ ...(sandboxSpecification && { sandboxSpecification }),topicId,userId,- });+ } as never,+ );log('Sandbox tool %s response: %O', toolName, response);diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.tsnew file mode 100644index 00000000000..9d83f0ebcd1--- /dev/null+++ b/apps/server/src/services/sandbox/session.ts@@ -0,0 +1,268 @@+import {+ DEFAULT_SANDBOX_MODE,+ isSafeSandboxCwd,+ isSafeSandboxEnvironmentId,+ SANDBOX_LOCAL_WORK_ROOT,+ type SandboxMode,+ type SandboxStorageClaim,+} from '@lobechat/builtin-tool-cloud-sandbox';+import type { LobeChatDatabase } from '@lobechat/database';+import type { EnvironmentConfiguration } from '@lobechat/types';+import debug from 'debug';++import { AgentModel } from '@/database/models/agent';+import { EnvironmentInstanceModel } from '@/database/models/environmentInstance';+import { TopicModel } from '@/database/models/topic';++import { resolveSandboxStorageClaim } from './entitlement';+import type { SandboxSessionSpecification } from './types';++const log = debug('lobe-server:sandbox:session');++export interface SandboxSessionConfig {+ /**+ * The signed entitlement, or `null` when this run gets no persistent+ * workspace. Independent of {@link 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.+ */+ claim: SandboxStorageClaim | null;+ /**+ * Chosen subdirectory of the workspace, relative to its root. Only ever set+ * on a run that is actually persistent.+ */+ cwd?: string;+ /**+ * 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+ * instance, so two instances of one environment restore separately and+ * capture separately.+ *+ * Carries the same invariant as {@link SandboxSessionConfig.mode}: a session+ * is bound to one of these on its first call, so every call for a topic has+ * to agree or the snapshot at the end is refused.+ */+ environment?: string;+ mode: SandboxMode;+ /**+ * What the instance was built from, for the execution plane to act on while+ * the session runs. Absent on an ephemeral run, which has no instance and+ * therefore no definition to honour.+ *+ * The instance's own snapshot of the definition, not the environment's+ * current one โ the same object its build used. So the variables a command+ * sees are the ones its packages were installed under, and the digest the+ * execution plane records for a session matches the digest of the build it+ * restored. Editing the environment therefore takes effect on rebuild, which+ * is the same rule the checkout and the installed packages already follow.+ */+ specification?: SandboxSessionSpecification;+ /**+ * Where commands run, when that is not {@link cwd}: the sandbox's local+ * disk, for an instance that has been built from a repository. The checkout+ * lives there and installs only work there; {@link cwd} stays the+ * instance's directory on the volume, which is what the call belongs to โ+ * what a shared workspace narrows its view to, and what the file browser+ * reads.+ */+ workingDir?: string;+}++/**+ * The run-time half of a stored definition, named field by field.+ *+ * Everything this omits is either not the execution plane's business during a+ * session or has no business leaving the server at all; see+ * {@link SandboxSessionSpecification}. Absent when the pick is empty, so a+ * definition that says nothing sends nothing rather than an empty object the+ * runtime would still adopt.+ */+const toSessionSpecification = (+ configuration: EnvironmentConfiguration | null | undefined,+): SandboxSessionSpecification | undefined => {+ if (!configuration) return undefined;++ const specification: SandboxSessionSpecification = {+ ...(configuration.bootstrapCommand && { bootstrapCommand: configuration.bootstrapCommand }),+ ...(configuration.env &&+ Object.keys(configuration.env).length > 0 && { env: configuration.env }),+ ...(configuration.excludePaths?.length && { excludePaths: configuration.excludePaths }),+ ...(configuration.internetAccess !== undefined && {+ internetAccess: configuration.internetAccess,+ }),+ ...(configuration.maintenanceCommand && {+ maintenanceCommand: configuration.maintenanceCommand,+ }),+ ...(configuration.sources?.length && { sources: configuration.sources }),+ };++ return Object.keys(specification).length > 0 ? specification : undefined;+};++/**+ * Whether an instance's checkout is on the sandbox's local disk: it has been+ * built, from a definition that clones something. An instance with nothing to+ * clone has no checkout to run in, and one not built yet has nothing there.+ */+const hasLocalCheckout = (instance: {+ configurationSnapshot?: { sources?: { kind?: string }[] } | null;+ status?: string | null;+}): boolean =>+ instance.status === 'ready' &&+ !!instance.configurationSnapshot?.sources?.some((source) => source.kind === 'git');++interface SandboxSessionConfigInput {+ /** See `resolveSandboxStorageClaim` โ a visitor run never gets an entitlement. */+ isShareVisitorRun: boolean;+ /**+ * Optional because some runtimes are constructed without one. No database+ * means no plan and no preferences to read, which is exactly the shape of+ * "not entitled" โ so the run stays ephemeral rather than half-configured.+ */+ serverDB?: LobeChatDatabase;+ topicId?: string;+ userId: string;+ workspaceId?: string | null;+}++/**+ * 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.+ *+ * 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.+ *+ * Never throws; a failed lookup degrades to the ephemeral sandbox every session+ * uses today.+ */+export const resolveSandboxSessionConfig = async ({+ isShareVisitorRun,+ serverDB,+ topicId,+ userId,+ workspaceId,+}: SandboxSessionConfigInput): Promise<SandboxSessionConfig> => {+ if (!serverDB) return { claim: null, mode: DEFAULT_SANDBOX_MODE };++ const claim = await resolveSandboxStorageClaim({+ isShareVisitorRun,+ serverDB,+ userId,+ workspaceId,+ });++ if (!claim || !topicId) {+ log(+ 'Ephemeral for topic %s: claim=%s topicId=%s userId=%s workspaceId=%s',+ topicId,+ !!claim,+ !!topicId,+ userId,+ workspaceId,+ );++ return { claim, 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.+ const topic = await new TopicModel(serverDB, userId, workspaceId ?? undefined).findById(+ topicId,+ );+ if (topic?.metadata?.sandboxMode !== 'persistent') {+ log(+ 'Ephemeral for topic %s: found=%s mode=%o instance=%o (scope user=%s workspace=%s)',+ topicId,+ !!topic,+ topic?.metadata?.sandboxMode,+ topic?.metadata?.sandboxInstanceId,+ userId,+ workspaceId,+ );++ return { claim, mode: DEFAULT_SANDBOX_MODE };+ }++ // 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' };++ const instanceId = topic.metadata.sandboxInstanceId;+ if (!instanceId) {+ log('Falling back for topic %s: persistent with no instance bound', topicId);++ return fallback;+ }++ // 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(+ 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;+ }++ // 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;+ }++ log('Persistent for topic %s: instance=%s cwd=%o', topicId, id, workingDirectory);++ const specification = toSessionSpecification(instance.configurationSnapshot);++ return {+ claim,+ cwd: workingDirectory,+ environment: id,+ mode: 'persistent',+ ...(specification && { specification }),+ ...(hasLocalCheckout(instance) && { workingDir: SANDBOX_LOCAL_WORK_ROOT }),+ };+ } catch (error) {+ log('Failed to read sandbox preferences for topic %s: %O', topicId, error);+ return { claim, mode: DEFAULT_SANDBOX_MODE };+ }+};diff --git a/apps/server/src/services/sandbox/storageFiles.ts b/apps/server/src/services/sandbox/storageFiles.tsnew file mode 100644index 00000000000..0d7e656e3a9--- /dev/null+++ b/apps/server/src/services/sandbox/storageFiles.ts@@ -0,0 +1,438 @@+import type { EnvironmentConfiguration } from '@lobechat/types';+import debug from 'debug';++const log = debug('lobe-server:sandbox:workspace-files');++/**+ * Client for the execution plane's persistent-workspace file API.+ *+ * Hand-written rather than taken from the market SDK, which does not carry+ * these endpoints yet. It is deliberately small and replaceable: same paths,+ * same shapes, so swapping it for the generated client later is a deletion.+ *+ * Every `path` is RELATIVE to the workspace root (`reports/q3.md`). The+ * absolute mount path never crosses this boundary โ which keeps the mount+ * layout an implementation detail and makes the server-side fence unambiguous,+ * since there is no absolute path for a caller to smuggle in.+ */+export interface SandboxStorageFileEntry {+ isDirectory: boolean;+ modifiedAt?: string;+ name: string;+ /** Relative to the workspace root. */+ path: string;+ size?: number;+}++export interface SandboxStorageFileList {+ entries: SandboxStorageFileEntry[];+ path: string;+ /** True when the listing hit the server-side entry cap. */+ truncated: boolean;+}++export interface SandboxStorageInfo {+ dir: string;+ key: string;+ lastActiveAt: string | null;+ /**+ * Outcome of the most recent environment snapshot. Snapshots happen when a+ * session is torn down, with no request left to fail, so this is the only+ * place a user can learn their environments stopped being saved.+ */+ lastSnapshotAt: string | null;+ lastSnapshotError: string | null;+ quotaBytes: number;+ status: 'active' | 'archived';+ usageBytes: number | null;+ usageCheckedAt: string | null;+}++/**+ * A snapshot the execution plane holds. Only instances that have actually been+ * captured appear โ one created but never used has metadata here and no+ * snapshot there, which is why the two are joined rather than assumed to match.+ */+export interface SandboxInstanceSnapshot {+ /** Size of the snapshot archive itself; exact, not a directory walk. */+ bytes: number;+ /** Files in the archive, or `null` when the sidecar metadata disagrees with it. */+ files: number | null;+ /** This platform's `environment_instances` row id. */+ id: string;+ updatedAt: string;+}++/** One run of an instance, as the execution plane's trail records it. */+export interface SandboxSessionRecord {+ /** Set on builds: what the build status endpoint is polled with. */+ buildId: string | null;+ endedAt: string | null;+ /** Null while the run is still going. */+ endReason:+ | 'build_failed'+ | 'build_gone'+ | 'build_succeeded'+ | 'build_timeout'+ | 'expired'+ | 'explicit'+ | 'idle'+ | 'lost'+ | 'switched'+ | null;+ id: number;+ /** The instance id, which is what the snapshot is stored under. */+ instanceId: string | null;+ kind: 'build' | 'session';+ /**+ * Not a conversation's session. The file browser opens one, and so does a+ * build โ its sandbox is a management session too, which is why a build+ * appears in the trail twice, once under each `kind`, with one `sessionId`.+ */+ management: boolean;+ sessionId: string;+ sessionUserId: string;+ /** Archive size after the teardown snapshot; null when it failed or has not run. */+ snapshotBytes: number | null;+ snapshotError: string | null;+ startedAt: string;+ topicId: string | null;+}++/**+ * Who holds which instance right now. Its own call rather than a field on the+ * environment listing: occupancy is a Redis read, while a listing reads the+ * volume, and a composer menu that only wants to mark a row "running" must not+ * be the reason a sandbox starts on a deployment without a files function.+ */+/** A build in flight, or the verdict on one that finished. */+export interface SandboxBuildStatus {+ buildId: string;+ /** Log since the requested offset; empty when nothing new has been written. */+ chunk: string;+ /** The process's exit status once it has one; null while running. */+ exitCode: number | null;+ instanceId: string;+ /** Where to resume the log from on the next poll. */+ logOffset: number;+ seconds: number;+ /**+ * Which revision of the specification the finished instance was built+ * from, read back from the manifest the runtime published. Null while+ * running and on a failure: nothing is published on that path, so there is+ * no revision to record.+ */+ specDigest: string | null;+ state: 'running' | 'succeeded' | 'failed';+}++export interface SandboxOccupancy {+ /** Held right now. An instance nobody holds is absent. */+ held: { id: string; own: boolean }[];+ /** The lease store did not answer, so `held` is empty for want of one. */+ unavailable: boolean;+}++export interface SandboxSessionList {+ /** Pass as `before` to fetch the next page; null on the last one. */+ nextBefore: string | null;+ sessions: SandboxSessionRecord[];+}++export interface SandboxStorageClientOptions {+ baseURL: string;+ headers: Record<string, string>;+}++interface RequestContext {+ /**+ * Topic whose warm sandbox session should serve the call. The volume is+ * mounted into the sandbox, not into the market service, so every file+ * operation runs inside a session; reusing the one the user is already+ * working in avoids cold-starting a second sandbox just to list a directory.+ */+ topicId?: string;+}++/**+ * `current` resolves to whatever workspace the caller's signed entitlement+ * names. Sending a literal key would be the only way for a caller to ask for+ * someone else's directory, so we never do.+ */+const CURRENT_STORAGE = 'current';++export class SandboxStorageFilesError extends Error {+ /**+ * The market's machine code for the refusal (`error` in its OAuth-shaped+ * body), when it sent one. The description beside it names the row by its+ * id โ fine in a log, not a sentence to put in front of a person โ so the+ * code is what the UI translates and the description is only the fallback.+ */+ readonly code?: string;+ readonly status: number;++ constructor(message: string, status: number, code?: string) {+ super(message);+ this.name = 'SandboxStorageFilesError';+ this.code = code;+ this.status = status;+ }+}++export const createSandboxStorageClient = ({ baseURL, headers }: SandboxStorageClientOptions) => {+ const request = async <T>(path: string, init?: RequestInit): Promise<T> => {+ const response = await fetch(`${baseURL}/api/v1/sandbox/storages/${path}`, {+ ...init,+ headers: { ...headers, ...init?.headers },+ });++ if (!response.ok) {+ const body = await response+ .json()+ .catch(() => ({}) as { error?: string; error_description?: string; message?: string });+ log('workspace file request failed: %s %d %O', path, response.status, body);+ // The market answers in the OAuth shape โ `error` for the code and+ // `error_description` for the reason โ so reading `message` alone+ // reduced every refusal ("could not delete", "outside the workspace")+ // to the status number, which is the one thing the user cannot act on.+ throw new SandboxStorageFilesError(+ body.error_description ||+ body.message ||+ `Workspace request failed with status ${response.status}`,+ response.status,+ body.error,+ );+ }++ const payload = (await response.json()) as { data: T };+ return payload.data;+ };++ const withTopic = (query: URLSearchParams, { topicId }: RequestContext) => {+ if (topicId) query.set('topicId', topicId);+ return query;+ };++ return {+ /**+ * Create a directory, parents included. Idempotent โ an existing directory+ * is a success, so a picker can offer "new folder" without first proving+ * the name is free.+ */+ createDirectory: async (params: RequestContext & { path: string }): Promise<{ path: string }> =>+ request(`${CURRENT_STORAGE}/directory`, {+ body: JSON.stringify({ path: params.path, topicId: params.topicId }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ }),++ copyInstance: async (+ params: RequestContext & {+ from: string;+ /** The copy's own directory; the runtime writes its work tree there. */+ instanceDir?: string;+ to: string;+ },+ ): Promise<{ name: string }> =>+ request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.from)}/copy`, {+ body: JSON.stringify({+ instanceDir: params.instanceDir,+ to: params.to,+ topicId: params.topicId,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ }),++ deleteInstance: async (+ params: RequestContext & { name: string },+ ): Promise<{ name: string }> => {+ const query = withTopic(new URLSearchParams(), params);+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}${suffix}`, {+ method: 'DELETE',+ });+ },++ deleteFile: async (+ params: RequestContext & { path: string; recursive?: boolean },+ ): Promise<{ path: string }> => {+ const query = withTopic(new URLSearchParams({ path: params.path }), params);+ if (params.recursive) query.set('recursive', 'true');++ return request(`${CURRENT_STORAGE}/file?${query.toString()}`, { method: 'DELETE' });+ },++ getStorage: async (params: RequestContext = {}): Promise<SandboxStorageInfo> => {+ const query = withTopic(new URLSearchParams(), params);+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(`${CURRENT_STORAGE}${suffix}`);+ },++ /**+ * Re-measure the directory and return the workspace with the fresh figure.+ *+ * Separate from {@link getStorage}, which reads the stored number: this+ * one walks the volume, and it also stamps the workspace as active. So it+ * belongs on something the user asked for โ a refresh button โ and never+ * on a page load, where it would keep every workspace it displays+ * permanently young and hide the idle ones from any later sweep.+ */+ refreshUsage: async (params: RequestContext = {}): Promise<SandboxStorageInfo> =>+ request(`${CURRENT_STORAGE}/usage`, {+ body: JSON.stringify({ topicId: params.topicId }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ }),++ /**+ * Needs a live sandbox session, so it can take seconds on a cold start โ+ * a caller rendering this must show it is loading rather than treat it as+ * data it already has.+ */+ listInstances: async (+ params: RequestContext = {},+ ): Promise<{ instances: SandboxInstanceSnapshot[] }> => {+ const query = withTopic(new URLSearchParams(), params);+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(`${CURRENT_STORAGE}/instances${suffix}`);+ },++ /**+ * One environment's run history, newest first. Answered from the control+ * plane's own trail, so unlike the listings above it needs no sandbox+ * session and costs no cold start.+ */+ listEnvironmentSessions: async (params: {+ before?: string;+ limit?: number;+ name: string;+ }): Promise<SandboxSessionList> => {+ const query = new URLSearchParams();+ if (params.limit !== undefined) query.set('limit', String(params.limit));+ if (params.before) query.set('before', params.before);+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(+ `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/sessions${suffix}`,+ );+ },++ /**+ * Which of `names` a running sandbox holds, and whether the holder is this+ * topic's own session. Control plane only โ no sandbox, no volume.+ */+ readOccupancy: async (params: {+ names: string[];+ topicId?: string;+ }): Promise<SandboxOccupancy> => {+ const query = new URLSearchParams({ names: params.names.join(',') });+ if (params.topicId) query.set('topicId', params.topicId);++ return request(`${CURRENT_STORAGE}/instances/occupancy?${query.toString()}`);+ },++ /**+ * Start building an environment from its specification.+ *+ * Returns as soon as the build has started: a bootstrap running an install+ * is minutes long, so it is polled through {@link buildStatus} rather than+ * awaited.+ *+ * `credentials` is the ONE thing in this call that may be a secret, and it+ * is separate from the specification on purpose: the stored configuration+ * has no such field and must never gain one. A token here is scoped to the+ * repository being cloned and expires on its own; the execution plane+ * forwards it and the runtime strips it before anything is remembered.+ * Omitted, the execution plane falls back to its own GitHub connection, so+ * a caller that cannot mint one takes nothing away.+ *+ * Never log this argument.+ */+ buildInstance: async (params: {+ credentials?: { header: string; urlPrefix: string }[];+ /**+ * The instance's directory, relative to the workspace. The runtime writes+ * the checkout there, so it is what the file browser shows, and keeps+ * using it for every later save of this environment.+ */+ instanceDir?: string;+ name: string;+ specification: EnvironmentConfiguration;+ topicId?: string;+ }): Promise<{ buildId: string }> =>+ request(`${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}/build`, {+ body: JSON.stringify({+ credentials: params.credentials,+ instanceDir: params.instanceDir,+ specification: params.specification,+ topicId: params.topicId,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ }),++ /** Poll a build, pulling its log from `logOffset` on. */+ buildStatus: async (params: {+ buildId: string;+ logOffset?: number;+ name: string;+ topicId?: string;+ }): Promise<SandboxBuildStatus> => {+ const query = new URLSearchParams();+ if (params.logOffset !== undefined) query.set('logOffset', String(params.logOffset));+ if (params.topicId) query.set('topicId', params.topicId);+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(+ `${CURRENT_STORAGE}/instances/${encodeURIComponent(params.name)}` ++ `/build/${encodeURIComponent(params.buildId)}${suffix}`,+ );+ },++ listFiles: async (+ params: RequestContext & { path?: string; recursive?: boolean } = {},+ ): Promise<SandboxStorageFileList> => {+ const query = withTopic(new URLSearchParams(), params);+ if (params.path) query.set('path', params.path);+ if (params.recursive) query.set('recursive', 'true');+ const suffix = query.size > 0 ? `?${query.toString()}` : '';++ return request(`${CURRENT_STORAGE}/files${suffix}`);+ },++ readFile: async (+ params: RequestContext & { path: string },+ ): Promise<{ content: string; mimeType?: string; path: string }> => {+ const query = withTopic(new URLSearchParams({ path: params.path }), params);++ return request(`${CURRENT_STORAGE}/file?${query.toString()}`);+ },++ /**+ * Write a file, creating it and its parents when they do not exist.+ *+ * Text only: the endpoint carries `content` as a JSON string with no+ * encoding field, so there is no way to round-trip bytes through it. A+ * caller holding binary has to wait for an upload path rather than+ * smuggling it through as text.+ */+ writeFile: async (+ params: RequestContext & { content: string; path: string },+ ): Promise<{ path: string }> =>+ request(`${CURRENT_STORAGE}/file`, {+ body: JSON.stringify({+ content: params.content,+ path: params.path,+ topicId: params.topicId,+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'PUT',+ }),+ };+};++export type SandboxStorageClient = ReturnType<typeof createSandboxStorageClient>;diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.tsindex 319587fb1b0..2d7c07f8cd7 100644--- a/apps/server/src/services/sandbox/types.ts+++ b/apps/server/src/services/sandbox/types.ts@@ -1,6 +1,7 @@import type {ISandboxService,SandboxExportFileResult,+ SandboxMode,} from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';@@ -9,7 +10,69 @@ import type { MarketService } from '@/server/services/market';export type SandboxProviderKind = 'market' | 'onlyboxes';+/**+ * The part of an environment's definition the execution plane acts on while a+ * session runs, as opposed to while it is being built.+ *+ * A deliberate pick rather than the stored object passed through. Two reasons,+ * and the first is the one that matters: `EnvironmentConfiguration` is typed+ * without credentials, but it is `jsonb` โ the column accepts whatever was+ * written to it, and this object now travels to the execution plane on every+ * tool call. Naming the fields means a key that appears in the database later+ * cannot start leaving the server just because someone added it upstream.+ *+ * The second is that `bootstrapCommand` and `sources` are here even though a+ * session never runs either: they are two of the three keys the execution+ * plane digests to decide which build a snapshot belongs to. Dropping them+ * would make every session disagree with the build it restored.+ */+export interface SandboxSessionSpecification {+ bootstrapCommand?: string;+ env?: Record<string, string>;+ excludePaths?: string[];+ internetAccess?: boolean;+ maintenanceCommand?: string;+ sources?: { kind: string; path?: string; ref?: string; uri?: string; url?: string }[];+}+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'`.+ */+ sandboxCwd?: string;+ /**+ * Named environment to restore for this run; absent means the caller's+ * default. Like `sandboxMode`, every call for a topic must carry the same+ * value โ the session binds to one environment on its first call.+ */+ sandboxInstanceId?: string;+ /**+ * Whether this run wants its working directory to survive the session.+ * Absent means ephemeral. Half the decision โ the execution plane also+ * requires an entitlement on the trust token, which is minted upstream of+ * this service.+ */+ sandboxMode?: SandboxMode;+ /**+ * The instance's definition, so the execution plane can act on the half of+ * it that belongs to a run rather than to a build: exporting the declared+ * variables, running the maintenance command once, cutting the network when+ * the environment asks for it, and routing the regenerable paths on capture.+ *+ * Carried on every call for the same reason {@link sandboxInstanceId} is โ+ * the runtime adopts it per invocation and a call that omitted it would run+ * with whatever the previous one happened to set.+ */+ sandboxSpecification?: SandboxSessionSpecification;+ /**+ * Where commands run, on the sandbox's local disk, for an instance whose+ * checkout lives there. Sent alongside {@link sandboxCwd}, which keeps+ * naming the instance the call belongs to on the volume.+ */+ sandboxWorkingDir?: string;topicId: string;userId: string;}diff --git a/apps/server/src/services/scm/__tests__/cloneCredential.test.ts b/apps/server/src/services/scm/__tests__/cloneCredential.test.tsnew file mode 100644index 00000000000..b5545fe7616--- /dev/null+++ b/apps/server/src/services/scm/__tests__/cloneCredential.test.ts@@ -0,0 +1,167 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ScmInstallationModel } from '@/database/models/scm';+import { scmInstallations, users } from '@/database/schemas';++import { githubRepositoryOf, resolveScmCloneCredential } from '../cloneCredential';++const mintGitHubRepositoryToken = vi.hoisted(() => vi.fn());++vi.mock('../github/app', () => ({ mintGitHubRepositoryToken }));++const serverDB = await getTestDB();+const userId = 'scm-clone-credential-user';++const install = (params: {+ accountLogin: string;+ installationId: string;+ repositories?: string[];+ repositorySelection?: 'all' | 'selected';+ suspended?: boolean;+}) =>+ ScmInstallationModel.bind(serverDB, {+ accountExternalId: `ext-${params.installationId}`,+ accountLogin: params.accountLogin,+ accountType: 'organization',+ installationId: params.installationId,+ provider: 'github',+ repositories: (params.repositories ?? []).map((fullName, index) => ({+ externalId: `${params.installationId}-${index}`,+ fullName,+ })),+ repositorySelection: params.repositorySelection ?? 'selected',+ suspendedAt: params.suspended ? new Date() : null,+ userId,+ });++const resolve = (url: string) =>+ resolveScmCloneCredential({+ configuration: { sources: [{ kind: 'git', url }] },+ db: serverDB,+ userId,+ });++beforeEach(async () => {+ mintGitHubRepositoryToken.mockReset();+ mintGitHubRepositoryToken.mockResolvedValue({+ expiresAt: '2026-01-01T00:00:00Z',+ token: 'ghs_minted',+ });+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+});++afterEach(async () => {+ await serverDB.delete(scmInstallations).where(eq(scmInstallations.userId, userId));+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('githubRepositoryOf', () => {+ it('reads owner/name off a github https source', () => {+ expect(githubRepositoryOf({ sources: [{ kind: 'git', url: 'https://github.com/o/r' }] })).toBe(+ 'o/r',+ );+ expect(+ githubRepositoryOf({ sources: [{ kind: 'git', url: 'https://github.com/o/r.git' }] }),+ ).toBe('o/r');+ });++ it('ignores a source that is not a github https checkout', () => {+ // A credential attached to a host nobody checked is the one outcome worth+ // preventing here, so anything unrecognized yields no repository at all.+ expect(+ githubRepositoryOf({ sources: [{ kind: 'git', url: 'https://gitlab.com/o/r' }] }),+ ).toBeUndefined();+ expect(+ githubRepositoryOf({ sources: [{ kind: 'archive', url: 'https://github.com/o/r' }] }),+ ).toBeUndefined();+ expect(+ githubRepositoryOf({ sources: [{ kind: 'git', url: 'https://github.com/o/r/extra' }] }),+ ).toBeUndefined();+ expect(githubRepositoryOf(undefined)).toBeUndefined();+ });+});++describe('resolveScmCloneCredential', () => {+ it('mints a repository-scoped token from the installation that was granted it', async () => {+ await install({+ accountLogin: 'acme',+ installationId: '100',+ repositories: ['acme/app'],+ });++ const credential = await resolve('https://github.com/acme/app');++ expect(mintGitHubRepositoryToken).toHaveBeenCalledWith({+ installationId: '100',+ repoFullName: 'acme/app',+ });+ expect(credential).toEqual({+ header: `Authorization: Basic ${Buffer.from('x-access-token:ghs_minted').toString('base64')}`,+ urlPrefix: 'https://github.com/',+ });+ });++ it('matches an all-repositories installation by its account', async () => {+ // GitHub does not enumerate repositories for an `all` installation, so the+ // owner segment is the only thing there is to compare.+ await install({ accountLogin: 'acme', installationId: '101', repositorySelection: 'all' });++ expect(await resolve('https://github.com/acme/anything')).not.toBeNull();+ expect(await resolve('https://github.com/other/thing')).toBeNull();+ });++ it('does not answer for a repository the installation was not granted', async () => {+ await install({+ accountLogin: 'acme',+ installationId: '102',+ repositories: ['acme/other'],+ });++ expect(await resolve('https://github.com/acme/app')).toBeNull();+ expect(mintGitHubRepositoryToken).not.toHaveBeenCalled();+ });++ it('skips a suspended installation rather than minting a token it cannot use', async () => {+ await install({+ accountLogin: 'acme',+ installationId: '103',+ repositories: ['acme/app'],+ suspended: true,+ });++ expect(await resolve('https://github.com/acme/app')).toBeNull();+ expect(mintGitHubRepositoryToken).not.toHaveBeenCalled();+ });++ it('falls through when the App cannot mint, instead of failing the build', async () => {+ // An App without `contents: read` lands here; the caller then uses the+ // other credential path and the clone reports itself in the build log.+ await install({+ accountLogin: 'acme',+ installationId: '104',+ repositories: ['acme/app'],+ });+ mintGitHubRepositoryToken.mockResolvedValue(null);++ expect(await resolve('https://github.com/acme/app')).toBeNull();+ });++ it('never throws when the installation lookup fails', async () => {+ const db = {+ select: () => {+ throw new Error('database is down');+ },+ } as never;++ await expect(+ resolveScmCloneCredential({+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/acme/app' }] },+ db,+ userId,+ }),+ ).resolves.toBeNull();+ });+});diff --git a/apps/server/src/services/scm/cloneCredential.ts b/apps/server/src/services/scm/cloneCredential.tsnew file mode 100644index 00000000000..94086c834ef--- /dev/null+++ b/apps/server/src/services/scm/cloneCredential.ts@@ -0,0 +1,132 @@+import debug from 'debug';++import { ScmInstallationModel } from '@/database/models/scm';+import type { ScmInstallationItem } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { mintGitHubRepositoryToken } from './github/app';++const log = debug('lobe-server:scm:clone-credential');++/** The only checkout host the sandbox build knows how to authenticate. */+export const GITHUB_HTTPS_PREFIX = 'https://github.com/';++/**+ * One per-host header the build's clone sends, shaped the way the execution+ * plane already accepts it. Deliberately not a url and not part of a source:+ * a credential in either is written into `.git/config` under the build root,+ * which is snapshotted and restored for everyone the environment is published+ * to.+ */+export interface ScmCloneCredential {+ header: string;+ urlPrefix: string;+}++interface SourcedConfiguration {+ sources?: { kind?: string; url?: string }[];+}++/**+ * The GitHub repository a specification builds from, as `owner/name`.+ *+ * Only a github.com https url counts. The runtime refuses anything else at+ * clone time anyway, and a credential must never be attached to a host nobody+ * checked.+ */+export const githubRepositoryOf = (+ configuration: SourcedConfiguration | undefined,+): string | undefined => {+ const url = configuration?.sources?.find(+ (source) => source.kind === 'git' && source.url?.startsWith(GITHUB_HTTPS_PREFIX),+ )?.url;+ if (!url) return undefined;++ const path = url+ .slice(GITHUB_HTTPS_PREFIX.length)+ .replace(/\.git$/, '')+ .replace(/\/$/, '');++ return /^[\w.-]+\/[\w.-]+$/.test(path) ? path : undefined;+};++/**+ * The installation that may read `repository`, among the ones this scope has.+ *+ * `all` selection is matched by account rather than by list: GitHub does not+ * enumerate repositories for an all-repositories installation, so the granted+ * set is "whatever that account owns" and the owner segment is the only thing+ * to compare. A suspended installation is skipped โ its tokens are refused,+ * and falling through to the other credential path beats minting one that+ * cannot clone.+ */+const installationFor = (+ installations: ScmInstallationItem[],+ repository: string,+): ScmInstallationItem | undefined => {+ const wanted = repository.toLowerCase();+ const owner = wanted.split('/')[0];++ return installations.find((installation) => {+ if (installation.provider !== 'github' || installation.suspendedAt) return false;+ if (installation.repositorySelection === 'all') {+ return installation.accountLogin.toLowerCase() === owner;+ }++ return installation.repositories.some((repo) => repo.fullName.toLowerCase() === wanted);+ });+};++/**+ * A clone credential for this build, from the GitHub App installation that was+ * granted the repository โ or `null` when there is no such installation.+ *+ * Preferred over the caller's own OAuth connection wherever it answers, and+ * for one reason: an installation is granted per repository by whoever+ * administers the account, while a user-to-server token carries everything+ * that person can see. The narrower grant is also the more durable one โ it+ * survives the person who set it up revoking their own authorization, or+ * leaving.+ *+ * Never throws. A build with no credential still runs: public sources clone,+ * and a private one fails in the build log, naming the repository, which is+ * where someone can act on it. Refusing the build instead would take away the+ * only place that explains itself.+ */+export const resolveScmCloneCredential = async (params: {+ configuration: SourcedConfiguration | undefined;+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}): Promise<ScmCloneCredential | null> => {+ const repository = githubRepositoryOf(params.configuration);+ if (!repository) return null;++ try {+ const installations = await ScmInstallationModel.listByScope(params.db, {+ userId: params.userId,+ workspaceId: params.workspaceId,+ });+ const installation = installationFor(installations, repository);+ if (!installation) {+ log('no installation in scope grants %s', repository);+ return null;+ }++ const minted = await mintGitHubRepositoryToken({+ installationId: installation.installationId,+ repoFullName: repository,+ });+ if (!minted) return null;++ return {+ // Basic with the token as the password is what git speaks to GitHub over+ // HTTPS; the username is ignored and conventionally this one.+ header: `Authorization: Basic ${Buffer.from(`x-access-token:${minted.token}`).toString('base64')}`,+ urlPrefix: GITHUB_HTTPS_PREFIX,+ };+ } catch (error) {+ log('could not resolve a clone credential for %s: %s', repository, (error as Error)?.message);+ return null;+ }+};diff --git a/apps/server/src/services/scm/github/app.ts b/apps/server/src/services/scm/github/app.tsindex f18dac7a7a8..299d2fc8543 100644--- a/apps/server/src/services/scm/github/app.ts+++ b/apps/server/src/services/scm/github/app.ts@@ -122,6 +122,51 @@ export const fetchGitHubInstallation = async (return snapshot;};+/**+ * Mint an installation token narrowed to ONE repository and ONE permission,+ * for a build that is about to clone it.+ *+ * `app.getInstallationOctokit` would hand back the installation's full grant โ+ * every repository it was given, every permission the App declares. A build+ * only ever reads one checkout, so the token it carries is scoped down to+ * exactly that: a request that names `repositories` and `permissions` gets a+ * token that can do nothing else, and it expires within the hour on its own.+ *+ * Narrowing can only ever subtract. Asking for `contents: read` on an App that+ * was not granted it fails here rather than producing a token that fails later+ * inside a sandbox, which is why this returns null instead of throwing: the+ * caller falls back to the other credential path, and the clone still reports+ * its own failure in the build log where someone can read it.+ *+ * Never log the returned token.+ */+export const mintGitHubRepositoryToken = async (params: {+ installationId: string;+ repoFullName: string;+}): Promise<{ expiresAt: string; token: string } | null> => {+ const app = getGitHubApp();+ if (!app) return null;++ try {+ const { data } = await app.octokit.request(+ 'POST /app/installations/{installation_id}/access_tokens',+ {+ installation_id: Number(params.installationId),+ permissions: { contents: 'read' },+ // The short name, not `owner/name`: this endpoint scopes by repository+ // within the installation's own account.+ repositories: [parseRepo(params.repoFullName).repo],+ },+ );++ return { expiresAt: data.expires_at, token: data.token };+ } catch (error) {+ // By shape, never by content โ the one path here that holds a credential.+ log('could not mint a clone token for %s: %s', params.repoFullName, (error as Error)?.message);+ return null;+ }+};+export const listGitHubInstallationRepositories = async (installationId: string,): Promise<ScmInstallationRepository[]> => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.tsindex da51887be99..95d259d4632 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => {return {createSandboxService: vi.fn(),+ resolveSandboxSessionConfig: vi.fn(),FakeSandboxService,MarketService: vi.fn(function () {return {};@@ -31,6 +32,7 @@ vi.mock('@/server/services/market', () => ({vi.mock('@/server/services/sandbox', () => ({createSandboxService: mocks.createSandboxService,+ resolveSandboxSessionConfig: mocks.resolveSandboxSessionConfig,}));vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({@@ -55,6 +57,7 @@ describe('cloudSandboxRuntime', () => {beforeEach(() => {vi.clearAllMocks();mocks.createSandboxService.mockReturnValue(mocks.sandboxService);+ mocks.resolveSandboxSessionConfig.mockResolvedValue({ claim: null, mode: 'ephemeral' });mocks.sandboxService.callTool.mockResolvedValue({result: { exitCode: 0, output: 'ok', stdout: 'ok', success: true },success: true,@@ -109,7 +112,7 @@ describe('cloudSandboxRuntime', () => {expect(mocks.MarketService).toHaveBeenCalledWith(expect.objectContaining({- userInfo: { userId: 'user-1', workspaceId: 'ws-42' },+ userInfo: expect.objectContaining({ userId: 'user-1', workspaceId: 'ws-42' }),}),);});@@ -218,4 +221,49 @@ describe('cloudSandboxRuntime', () => {undefined,);});++ // ---- Persistence: entitlement on the token, preferences on the request ----++ it('signs the entitlement onto the market token and passes the topic preferences down', async () => {+ mocks.resolveSandboxSessionConfig.mockResolvedValue({+ claim: { key: 'ws-user-1', quotaBytes: 2048 },+ cwd: 'projects/atlas',+ mode: 'persistent',+ });++ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ await cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));++ expect(mocks.MarketService).toHaveBeenCalledWith(+ expect.objectContaining({+ userInfo: expect.objectContaining({+ sandboxStorage: { key: 'ws-user-1', quotaBytes: 2048 },+ }),+ }),+ );+ expect(mocks.createSandboxService).toHaveBeenCalledWith(+ expect.objectContaining({ sandboxCwd: 'projects/atlas', sandboxMode: 'persistent' }),+ );+ });++ // The claim must be keyed on the SAME workspace the token carries; signing an+ // organization key onto a token market reads as personal would mount that+ // organization's directory inside a personal session.+ it('keys the entitlement on the workspace the token carries', async () => {+ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ await cloudSandboxRuntime.factory(buildContext({ workspaceId: 'ws-42' }));++ expect(mocks.resolveSandboxSessionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user-1', workspaceId: 'ws-42' }),+ );+ });++ it('marks a share-visitor run so no entitlement is resolved for the creator', async () => {+ const { cloudSandboxRuntime } = await import('../cloudSandbox');+ await cloudSandboxRuntime.factory(buildContext({ agentShareVisitor: { agentId: 'agent-1' } }));++ expect(mocks.resolveSandboxSessionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ isShareVisitorRun: true }),+ );+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.tsindex cb8a1e807bd..3d8c19f753f 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts@@ -38,7 +38,7 @@ describe('credsRuntime', () => {expect(getMember).toHaveBeenCalledWith('workspace-1', 'user-1');expect(MarketService).toHaveBeenCalledWith({- userInfo: { userId: 'user-1', workspaceId: 'workspace-1' },+ userInfo: expect.objectContaining({ userId: 'user-1', workspaceId: 'workspace-1' }),});});@@ -77,7 +77,7 @@ describe('credsRuntime', () => {expect(getMember).not.toHaveBeenCalled();expect(MarketService).toHaveBeenCalledWith({- userInfo: { userId: 'user-1', workspaceId: undefined },+ userInfo: expect.objectContaining({ userId: 'user-1', workspaceId: undefined }),});});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.tsindex eb94bd53c44..94954323424 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.test.ts@@ -323,7 +323,12 @@ describe('skillsRuntime', () => {}));mocks.isLhCommand.mockReturnValue(false);mocks.buildDeviceLhEnv.mockReturnValue(undefined);- mocks.resolveContentWorkspaceId.mockResolvedValue(undefined);+ // Mirrors the real helper: the context's own id when it has one, the+ // agent's workspace when the dispatch path dropped it. Tests that exercise+ // the recovery override this with a value of their own.+ mocks.resolveContentWorkspaceId.mockImplementation(+ async (ctx?: { workspaceId?: string }) => ctx?.workspaceId,+ );mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);mocks.sandboxService.callTool.mockResolvedValue({result: {@@ -1376,6 +1381,11 @@ describe('skillsRuntime', () => {const { MarketService } = await import('@/server/services/market');const { skillsRuntime } = await import('../skills');+ // The id now comes from the recovery helper, which answers with the+ // context's own value when it has one and with the agent's workspace when+ // the dispatch path dropped it.+ mocks.resolveContentWorkspaceId.mockResolvedValueOnce('workspace-1');+await skillsRuntime.factory({serverDB: {} as never,toolManifestMap: {},@@ -1386,20 +1396,50 @@ describe('skillsRuntime', () => {expect(MarketService).toHaveBeenLastCalledWith(expect.objectContaining({- userInfo: { userId: 'user-1', workspaceId: 'workspace-1' },+ userInfo: expect.objectContaining({ userId: 'user-1', workspaceId: 'workspace-1' }),+ }),+ );++ await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(MarketService).toHaveBeenLastCalledWith(+ expect.objectContaining({+ userInfo: expect.objectContaining({ userId: 'user-1', workspaceId: undefined }),}),);+ });++ // The dispatch and resume paths reach this runtime without `workspaceId`, and+ // a workspace topic resolved in the personal scope came back as "no such+ // topic" โ the run went ephemeral, `pwd` answered `/workspace`, and whatever+ // the conversation wrote was thrown away with the session.+ it('recovers the workspace from the agent when the context lost it', async () => {+ const { MarketService } = await import('@/server/services/market');+ const { skillsRuntime } = await import('../skills');++ mocks.resolveContentWorkspaceId.mockImplementation(async () => 'workspace-1');await skillsRuntime.factory({+ agentId: 'agt-1',serverDB: {} as never,toolManifestMap: {},topicId: 'topic-1',userId: 'user-1',});+ // The same id the session is keyed by, so the sandbox this runtime reaches+ // is the workspace's and not the member's personal one.+ expect(mocks.resolveContentWorkspaceId).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agt-1' }),+ );expect(MarketService).toHaveBeenLastCalledWith(expect.objectContaining({- userInfo: { userId: 'user-1', workspaceId: undefined },+ userInfo: expect.objectContaining({ workspaceId: 'workspace-1' }),}),);});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.tsindex 2fa00bdfe6d..81e2c90474d 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts@@ -5,7 +5,7 @@ import debug from 'debug';import { UserModel } from '@/database/models/user';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';-import { createSandboxService } from '@/server/services/sandbox';+import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';import {isDirectLhInvocation,isLhCommand,@@ -126,27 +126,56 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {// non-fatal โ MarketService will fall back to trustedClientToken}+ // The workspace this run belongs to. `context.workspaceId` is empty on the+ // dispatch and resume paths, which is most of them: a workspace agent's+ // tool call then resolved its topic in the personal scope, found nothing,+ // and ran ephemeral โ the conversation said "Lobehub Dev" while `pwd`+ // answered `/workspace` and the clone went somewhere nothing reads.+ //+ // Recovered once and used for everything this runtime builds, because the+ // danger is not the recovery but a disagreement: the claim signs a+ // directory that the token's identity must also name, or an organization's+ // files mount inside a personal session. `creds.ts` recovers the same way.+ const workspaceId = await resolveContentWorkspaceId(context);++ // Persistence for this run: the entitlement that goes on the trust token,+ // and the topic's own preferences that go on each request.+ const sandbox = await resolveSandboxSessionConfig({+ isShareVisitorRun: Boolean(context.agentShareVisitor),+ serverDB: context.serverDB,+ topicId: context.topicId,+ userId: context.userId,+ workspaceId,+ });+const marketService = new MarketService({accessToken,- userInfo: { userId: context.userId, workspaceId: context.workspaceId },+ userInfo: {+ sandboxStorage: sandbox.claim,+ userId: context.userId,+ workspaceId,+ },});- const fileService = new FileService(context.serverDB, context.userId, context.workspaceId);+ const fileService = new FileService(context.serverDB, context.userId, workspaceId);const sandboxService = createSandboxService({fileService,marketService,+ sandboxCwd: sandbox.cwd,+ sandboxInstanceId: sandbox.environment,+ sandboxSpecification: sandbox.specification,+ sandboxWorkingDir: sandbox.workingDir,+ sandboxMode: sandbox.mode,serverDB: context.serverDB,topicId: context.topicId,userId: context.userId,});- let workspaceIdPromise: Promise<string | undefined> | undefined;-return new CloudSandboxExecutionRuntime(withLhPreprocessing(sandboxService, {isShareVisitor: Boolean(context.agentShareVisitor),userId: context.userId,- workspaceId: () => (workspaceIdPromise ??= resolveContentWorkspaceId(context)),- workspaceIdHint: context.workspaceId,+ workspaceId: async () => workspaceId,+ workspaceIdHint: workspaceId,}),);},diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex 7d35a5dcaa1..6010cc16c99 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -5,7 +5,9 @@ import debug from 'debug';import { UserModel } from '@/database/models/user';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import { MarketService } from '@/server/services/market';+import { resolveSandboxSessionConfig } from '@/server/services/sandbox';+import { resolveContentWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:creds-runtime');@@ -197,13 +199,18 @@ export const credsRuntime: ServerRuntimeRegistration = {throw new Error('userId is required for Creds execution');}- if (context.workspaceId) {+ // Recovered, not read off the context: the dispatch and resume paths drop+ // it, and credentials must be injected into the SAME sandbox session the+ // commands run in โ the sandbox runtimes recover it the same way.+ const workspaceId = await resolveContentWorkspaceId(context);++ if (workspaceId) {if (!context.serverDB) {throw new Error('serverDB is required for workspace Creds execution');}const membership = await new WorkspaceMemberModel(context.serverDB, context.userId).getMember(- context.workspaceId,+ workspaceId,context.userId,);if (!membership) {@@ -215,7 +222,7 @@ export const credsRuntime: ServerRuntimeRegistration = {'Creating CredsExecutionRuntime for userId=%s, topicId=%s, workspaceId=%s',context.userId,context.topicId,- context.workspaceId,+ workspaceId,);// Read market accessToken from DB so server-side creds runtime can authenticate.@@ -230,14 +237,31 @@ export const credsRuntime: ServerRuntimeRegistration = {}}+ // Credentials are injected INTO a sandbox, so this call has to agree with+ // the cloud-sandbox and skills runtimes about which one. A token without the+ // entitlement routes to the ephemeral runtime, and the injection lands in a+ // different sandbox than the commands that need it โ or tears down the live+ // one on the way.+ const sandbox = await resolveSandboxSessionConfig({+ isShareVisitorRun: Boolean(context.agentShareVisitor),+ serverDB: context.serverDB,+ topicId: context.topicId,+ userId: context.userId,+ workspaceId,+ });+const marketService = new MarketService({accessToken,- userInfo: { userId: context.userId, workspaceId: context.workspaceId },+ userInfo: {+ sandboxStorage: sandbox.claim,+ userId: context.userId,+ workspaceId,+ },});const credsService = new ServerCredsService(marketService,- context.workspaceId,+ workspaceId,Boolean(context.agentShareVisitor),);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex aaf503e40fd..c1cd8b15079 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -1,4 +1,5 @@import { builtinSkills } from '@lobechat/builtin-skills';+import type { SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import { LocalSystemApiName, LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';// Note: only `readFile` is wired through deviceGateway. Directory enumeration is// left to the model via `local-system.globFiles` so we don't double-fetch.@@ -36,7 +37,12 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { executeAuthorizedDeviceToolCall } from '@/server/services/deviceGateway/authorizedToolCall';import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';-import { createSandboxService, normalizeSandboxCommandResult } from '@/server/services/sandbox';+import {+ createSandboxService,+ normalizeSandboxCommandResult,+ resolveSandboxSessionConfig,+ type SandboxSessionSpecification,+} from '@/server/services/sandbox';import { SkillResourceService } from '@/server/services/skill/resource';import { getToolAccessDeniedError } from '@/server/services/toolExecution/errorClassification';import {@@ -139,6 +145,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {private topicId?: string;private userId: string;private workspaceId?: string;+ private sandboxCwd?: string;+ private sandboxWorkingDir?: string;+ private sandboxInstanceId?: string;+ private sandboxMode?: SandboxMode;+ private sandboxSpecification?: SandboxSessionSpecification;private device?: SkillDeviceExecution;private disabledSkillIds: Set<string>;private isSkillGranted?: (identifier: string) => boolean;@@ -164,6 +175,18 @@ class SkillServerRuntimeService implements SkillRuntimeService {isSkillGranted?: (identifier: string) => boolean;marketService: MarketService;resourceService: SkillResourceService;+ /**+ * Persistence for this run, resolved once by the factory. Every sandbox+ * this service creates MUST carry the same values the cloud-sandbox runtime+ * uses: a topic has one sandbox, and a call that disagrees about the mode+ * routes to the other runtime and tears the live one down, taking installed+ * CLIs, injected credentials and anything outside the workspace with it.+ */+ sandboxCwd?: string;+ sandboxInstanceId?: string;+ sandboxMode?: SandboxMode;+ sandboxSpecification?: SandboxSessionSpecification;+ sandboxWorkingDir?: string;serverDB: LobeChatDatabase;/** Agent Share only: `lh` must not mint a creator-scoped token for a visitor. */shareVisitorBlocked?: boolean;@@ -182,6 +205,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {this.topicId = options.topicId;this.userId = options.userId;this.workspaceId = options.workspaceId;+ this.sandboxCwd = options.sandboxCwd;+ this.sandboxWorkingDir = options.sandboxWorkingDir;+ this.sandboxInstanceId = options.sandboxInstanceId;+ this.sandboxMode = options.sandboxMode;+ this.sandboxSpecification = options.sandboxSpecification;this.device = options.device;this.disabledSkillIds = options.disabledSkillIds ?? new Set();this.isSkillGranted = options.isSkillGranted;@@ -315,6 +343,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {const sandboxService = createSandboxService({fileService: this.fileService,marketService: this.marketService,+ sandboxCwd: this.sandboxCwd,+ sandboxInstanceId: this.sandboxInstanceId,+ sandboxMode: this.sandboxMode,+ sandboxSpecification: this.sandboxSpecification,+ sandboxWorkingDir: this.sandboxWorkingDir,serverDB: this.serverDB,topicId: this.topicId,userId: this.userId,@@ -668,6 +701,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {const sandboxService = createSandboxService({fileService: this.fileService,marketService: this.marketService,+ sandboxCwd: this.sandboxCwd,+ sandboxInstanceId: this.sandboxInstanceId,+ sandboxMode: this.sandboxMode,+ sandboxSpecification: this.sandboxSpecification,+ sandboxWorkingDir: this.sandboxWorkingDir,serverDB: this.serverDB,topicId: this.topicId,userId: this.userId,@@ -726,6 +764,11 @@ class SkillServerRuntimeService implements SkillRuntimeService {const sandboxService = createSandboxService({fileService: this.fileService,marketService: this.marketService,+ sandboxCwd: this.sandboxCwd,+ sandboxInstanceId: this.sandboxInstanceId,+ sandboxMode: this.sandboxMode,+ sandboxSpecification: this.sandboxSpecification,+ sandboxWorkingDir: this.sandboxWorkingDir,topicId: this.topicId,userId: this.userId,});@@ -824,12 +867,19 @@ export const skillsRuntime: ServerRuntimeRegistration = {const isSkillReachable = (identifier: string) =>!disabledSkillIds.has(identifier) && (isSkillGranted?.(identifier) ?? true);- const skillModel = new AgentSkillModel(context.serverDB, context.userId, context.workspaceId);- const resourceService = new SkillResourceService(- context.serverDB,- context.userId,- context.workspaceId,- );+ /**+ * The workspace everything this runtime touches belongs to โ the skills it+ * can see, the files it writes, and the sandbox session it reaches.+ *+ * Recovered rather than read off the context: the dispatch and resume paths+ * do not carry it, and there a workspace topic resolved in the personal+ * scope, came back "no such topic", and ran ephemeral โ `pwd` answered+ * `/workspace` while the conversation showed a persistent instance.+ */+ const workspaceId = await resolveContentWorkspaceId(context);++ const skillModel = new AgentSkillModel(context.serverDB, context.userId, workspaceId);+ const resourceService = new SkillResourceService(context.serverDB, context.userId, workspaceId);/*** `workspaceId` decides which sandbox session this runtime reaches: the* session is keyed by the acting account, so a token without it acts as the@@ -837,12 +887,26 @@ export const skillsRuntime: ServerRuntimeRegistration = {* pass it โ act as the workspace. Omitting it split one workspace topic* across two sandboxes, leaving injected credentials invisible here.*/+ // Same resolution, same inputs as the cloud-sandbox runtime โ see the+ // `sandboxMode` note on the service options for what a disagreement costs.+ const sandbox = await resolveSandboxSessionConfig({+ isShareVisitorRun: Boolean(context.agentShareVisitor),+ serverDB: context.serverDB,+ topicId: context.topicId,+ userId: context.userId,+ workspaceId,+ });+const marketService = new MarketService({accessToken: marketAccessToken,- userInfo: { userId: context.userId, workspaceId: context.workspaceId },+ userInfo: {+ sandboxStorage: sandbox.claim,+ userId: context.userId,+ workspaceId,+ },});- const fileService = new FileService(context.serverDB, context.userId, context.workspaceId);- const fileModel = new FileModel(context.serverDB, context.userId, context.workspaceId);+ const fileService = new FileService(context.serverDB, context.userId, workspaceId);+ const fileModel = new FileModel(context.serverDB, context.userId, workspaceId);// `activeDeviceId` presence is the device-branch switch: execScript then// runs on the device instead of the cloud sandbox. The executors filter@@ -874,12 +938,19 @@ export const skillsRuntime: ServerRuntimeRegistration = {isSkillGranted,marketService,resourceService,+ sandboxCwd: sandbox.cwd,+ sandboxInstanceId: sandbox.environment,+ sandboxMode: sandbox.mode,+ sandboxSpecification: sandbox.specification,+ sandboxWorkingDir: sandbox.workingDir,serverDB: context.serverDB,shareVisitorBlocked: !!shareVisitor,skillModel,topicId: context.topicId,userId: context.userId,- workspaceId: context.workspaceId,+ // The recovered id, so the `lh` prelude names the same workspace the+ // sandbox session was opened under rather than looking it up again.+ workspaceId,});// Surface this agent's skill-bundle documents as `BuiltinSkill`-shapeddiff --git a/apps/server/src/services/understanding/providers/github.test.ts b/apps/server/src/services/understanding/providers/github.test.tsindex adf9c83413d..468c8f22eb0 100644--- a/apps/server/src/services/understanding/providers/github.test.ts+++ b/apps/server/src/services/understanding/providers/github.test.ts@@ -19,6 +19,8 @@ describe('githubUnderstandingProvider', () => {const client = {getUserProfile: vi.fn(() => profile),getUserProfileReadme: supplemental('readme', undefined),+ listAccessibleRepositories: vi.fn(async () => []),+ listRepositoryBranches: vi.fn(async () => []),listContributedRepositories: supplemental('contributedRepositories', []),listInfluentialRepositories: supplemental('influentialRepositories', []),listPinnedRepositories: supplemental('pinned', []),@@ -70,6 +72,8 @@ describe('githubUnderstandingProvider', () => {retryable: false,});}),+ listAccessibleRepositories: vi.fn(async () => []),+ listRepositoryBranches: vi.fn(async () => []),listContributedRepositories: empty,listInfluentialRepositories: empty,listPinnedRepositories: empty,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b77001a5cdc..f2589058686 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1191,7 +1191,7 @@"heteroAgent.executionTarget.reconnect": "Reconnect","heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.","heteroAgent.executionTarget.sandbox": "Cloud Sandbox",- "heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox",+ "heteroAgent.executionTarget.sandboxDesc": "Runs in the cloud, no machine needed","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device","heteroAgent.executionTarget.switchTopic.content": "This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.","heteroAgent.executionTarget.switchTopic.ok": "Switch",@@ -1700,6 +1700,27 @@"runtimeEnv.mode.noneDesc": "Disable runtime environment","runtimeEnv.selectMode": "Select Runtime Environment","runtimeEnv.title": "Runtime Environment",+ "sandboxStorage.buildFailed": "Not built",+ "sandboxStorage.building": "Building",+ "sandboxStorage.environmentsUnavailable": "Environments could not be loaded",+ "sandboxStorage.ephemeral": "Temporary working directory",+ "sandboxStorage.ephemeralDesc": "Cleaned up when the sandbox is recycled",+ "sandboxStorage.instanceBusy": "{{name}} is running in another conversation. This one keeps it, and picks it up when that run ends.",+ "sandboxStorage.manage": "Manage",+ "sandboxStorage.noInstances": "Create an instance",+ "sandboxStorage.noInstancesDesc": "Your environments have no working copy yet",+ "sandboxStorage.persistentUpsell": "Persistent working directory",+ "sandboxStorage.persistentUpsellDesc": "Keep files across runs and topics",+ "sandboxStorage.pickerInfoTooltip": "An environment describes what a run needs around it โ repositories, setup, variables. An instance is one working copy of it, with its own folder and its own installed packages; conversations run inside an instance and keep what they leave there.",+ "sandboxStorage.pickerTitle": "Environment Instance",+ "sandboxStorage.privateGroup": "Private Environments",+ "sandboxStorage.privateInstanceBlocked": "โ{{name}}โ is in a private environment, which a public agent cannot use. This topic runs in a temporary working directory instead.",+ "sandboxStorage.publicAgentHint_one": "{{count}} private environment is hidden โ a public agent can only use workspace environments. Publish it to use it here.",+ "sandboxStorage.publicAgentHint_other": "{{count}} private environments are hidden โ a public agent can only use workspace environments. Publish one to use it here.",+ "sandboxStorage.running": "Running",+ "sandboxStorage.setUpEnvironment": "Set up an environment",+ "sandboxStorage.setUpEnvironmentDesc": "A persistent directory lives in an environment",+ "sandboxStorage.workspaceGroup": "Workspace Environments","search.grounding.imageSearchQueries": "Image Search Keywords","search.grounding.imageTitle": "Found {{count}} images","search.grounding.searchQueries": "Search Keywords",@@ -2729,6 +2750,7 @@"workingPanel.files.filters.title": "Filter Files","workingPanel.files.noSearchResults": "No matching files","workingPanel.files.open": "Open File",+ "workingPanel.files.openNeedsTopic": "Send a message first โ this environmentโs files open once the conversation has a session.","workingPanel.files.search": "Search Files","workingPanel.files.searchPlaceholder": "Filter files...","workingPanel.files.showInReview": "Show in Review",@@ -2738,6 +2760,7 @@"workingPanel.files.trashName.mac": "Trash","workingPanel.files.trashName.windows": "Recycle Bin","workingPanel.files.truncatedNotice": "Some expanded folders are too large to list fully โ only the first entries are shown",+ "workingPanel.files.unreadable": "Couldn't read this workspace โ it may not exist yet, or the listing failed","workingPanel.files.validation.empty": "A file or folder name must be provided","workingPanel.files.validation.exists": "\"{{name}}\" already exists here. Choose a different name.","workingPanel.files.validation.invalidChars": "Names can't contain < > : \" / \\ | ? * or control characters",diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 21bf47567af..cb8ca2aceb3 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -518,6 +518,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 instances and reach everything it has captured โ files, CLI logins, your signed-in identity","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/labs.json b/locales/en-US/labs.jsonindex 8445b21c387..b102bb598eb 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -36,6 +36,8 @@"features.messageTextSelectionActions.title": "Message Text Selection Actions","features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.","features.oauthApps.title": "OAuth Apps",+ "features.persistentSandbox.desc": "Keep files the cloud sandbox writes. Its working directory survives session recycling and is shared across your topics, instead of being discarded with the sandbox. Requires a paid plan; large downloads and dependencies still belong in /tmp.",+ "features.persistentSandbox.title": "Persistent Sandbox","features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.","features.projects.title": "Project Workspaces","features.selfLearning.desc": "Learn from practice: the rounds you send back become rules, and each agent picks up lessons from its own runs โ both go with the agent into every run. See them all under Memory โ Self-evolving.",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 0103fad6c44..904a76910aa 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -518,6 +518,182 @@"devices.visibilityTabs.private": "Private","devices.visibilityTabs.workspace": "Workspace","devices.workingDirectory": "Working dir: {{path}}",+ "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 instance built from one keeps its own files between sessions.",+ "environments.detail.close": "Close",+ "environments.detail.tabs.settings": "Settings",+ "environments.duplicateName": "You already have an environment with this name",+ "environments.empty": "No environments yet",+ "environments.emptyPublished": "Nothing published to this workspace yet",+ "environments.files.back": "Back",+ "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.invalidPath": "The name has to stay inside this instance's directory",+ "environments.files.listFailed": "This directory could not be listed",+ "environments.files.openHint": "Double-click a folder to open it, or a file to view it",+ "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",+ "environments.files.unusedInstance": "Nothing here yet. The code appears once the instance is built or a conversation runs in it.",+ "environments.files.up": "Up one level",+ "environments.form.addEnv": "New variable",+ "environments.form.addSource": "Add repository",+ "environments.form.appliesOnBuild": "Applied when an instance is created. Existing instances keep the definition they were made with โ a rebuild replays that one, so use a new instance to pick this up.",+ "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 an instance is built from โ where the code comes from and what makes it usable.",+ "environments.form.description": "Description",+ "environments.form.descriptionPlaceholder": "What this environment is for",+ "environments.form.disconnect": "Disconnect",+ "environments.form.editEnv": "Edit variable",+ "environments.form.env": "Environment variables",+ "environments.form.envCount_one": "{{count}} variable",+ "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 instance.",+ "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.internetAccess": "Agent internet access",+ "environments.form.internetAccessHint": "Setup always has network access. This controls the conversation itself.",+ "environments.form.maintenance": "Maintenance command",+ "environments.form.maintenanceHint": "Runs each time work resumes in an instance โ refreshing a checkout, reapplying a migration. Not the setup command again: that one is expensive and is meant to run once.",+ "environments.form.path": "Folder",+ "environments.form.rawEditor": "Raw editor",+ "environments.form.rawEditorHint": "One KEY=value per line, the way a .env file reads. Blank lines and # comments are ignored; saving replaces every variable.",+ "environments.form.rawInvalid": "Line {{line}} is not KEY=value",+ "environments.form.ref": "Branch or tag",+ "environments.form.refDefault": "Repository default branch",+ "environments.form.removeEnv": "Remove variable",+ "environments.form.removeSource": "Remove repository",+ "environments.form.runtime": "Runtime and storage",+ "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.github.connect": "Connect GitHub",+ "environments.github.label": "Repository",+ "environments.github.noRepositories": "This connection cannot see any repositories yet",+ "environments.github.notConnected": "No GitHub connection yet โ connect one to build an environment from a repository",+ "environments.github.optional": "optional",+ "environments.github.organization": "Organization",+ "environments.github.organizationPlaceholder": "Search organizations",+ "environments.github.repository": "Repository",+ "environments.github.repositoryPending": "Choose an organization first",+ "environments.github.repositoryPlaceholder": "Search repositories",+ "environments.github.reviewAccess": "Review access",+ "environments.hasInstances": "Remove its instances first",+ "environments.instances.add": "New instance",+ "environments.instances.build": "Build",+ "environments.instances.buildConfirmTitle": "Build instance {{name}}?",+ "environments.instances.buildFailed": "Build failed",+ "environments.instances.buildStartFailed": "Could not start the build",+ "environments.instances.buildStatusUnknown": "Lost track of this build",+ "environments.instances.building": "Building โ cloning and installing",+ "environments.instances.confirm": "Create",+ "environments.instances.count_one": "{{count}} instance",+ "environments.instances.count_other": "{{count}} instances",+ "environments.instances.create": "New instance",+ "environments.instances.createFailed": "Could not create the instance",+ "environments.instances.desc": "An instance is a working copy of this environment, with its own folder and its own installed packages. Conversations run inside an instance, and several can run side by side without touching 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 instance is built โ delete it and create another to move it.",+ "environments.instances.duplicateDirectory": "Another instance already uses this folder",+ "environments.instances.empty": "No instances yet",+ "environments.instances.emptyHint": "Create one, then pick it under \"Working Directory\" in the chat input.",+ "environments.instances.emptyReadonly": "Nobody has created an instance of this environment yet. Only its owner can add one.",+ "environments.instances.hideLog": "Hide log",+ "environments.instances.inUse": "A conversation is using this instance โ try again once that run ends",+ "environments.instances.namePlaceholder": "Instance name",+ "environments.instances.notBuilt": "Not built yet โ nothing has been cloned or installed",+ "environments.instances.occupancyUnavailable": "Could not read which instances are running right now",+ "environments.instances.overlappingDirectory": "This folder is inside another instance's folder, or contains one",+ "environments.instances.rebuild": "Rebuild",+ "environments.instances.rebuildConfirmContent": "This clears the instance'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 instance {{name}}?",+ "environments.instances.remove": "Delete instance",+ "environments.instances.removeConfirmContent": "Its folder and everything it kept โ installed packages, reports, data โ will be deleted. This cannot be undone.",+ "environments.instances.removeConfirmTitle": "Delete instance {{name}}?",+ "environments.instances.removeFailed": "Could not delete this instance",+ "environments.instances.removing": "Deleting โ removing its folder and everything in it",+ "environments.instances.rename": "Rename instance",+ "environments.instances.renameFailed": "Could not rename this instance",+ "environments.instances.retryStatus": "Check again",+ "environments.instances.running": "Running",+ "environments.instances.save": "Save",+ "environments.instances.showLog": "Show log",+ "environments.instances.title": "Instances",+ "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.loadFailed.title": "Could not check your plan",+ "environments.meta.createdAt": "Created {{time}}",+ "environments.meta.creatorTooltip": "Created by {{name}}",+ "environments.meta.storage": "Using {{size}}",+ "environments.meta.unknownCreator": "Unknown",+ "environments.mine": "My environments",+ "environments.nameLabel": "Name",+ "environments.namePlaceholder": "Environment name",+ "environments.refresh": "Refresh",+ "environments.remove": "Delete environment",+ "environments.removeConfirmContent": "Its specification, variables and saved snapshot go with it, and cannot be recovered.",+ "environments.removeConfirmTitle": "Delete environment {{name}}?",+ "environments.removeFailed": "Could not delete this environment",+ "environments.saveFailed": "Could not save this change",+ "environments.sessions.activeBuild": "{{instance}} is being built right now",+ "environments.sessions.activeSession": "A sandbox is running in {{instance}} right now",+ "environments.sessions.desc": "The most recent sessions that ran in these instances and the builds of them, newest first, with how each ended and whether what it installed was saved.",+ "environments.sessions.empty": "Nothing has run here yet",+ "environments.sessions.emptyHint": "Every conversation and build in one of its instances will show up here.",+ "environments.sessions.history": "History",+ "environments.sessions.historyEmpty": "No finished runs yet",+ "environments.sessions.kind.build": "Build",+ "environments.sessions.kind.console": "File browser",+ "environments.sessions.kind.conversation": "Conversation",+ "environments.sessions.openConversation": "Open conversation",+ "environments.sessions.reason.build_failed": "Build failed",+ "environments.sessions.reason.build_gone": "Build interrupted",+ "environments.sessions.reason.build_succeeded": "Built",+ "environments.sessions.reason.build_timeout": "Build timed out",+ "environments.sessions.reason.expired": "Reached its time limit",+ "environments.sessions.reason.explicit": "Stopped",+ "environments.sessions.reason.idle": "Stopped after idling",+ "environments.sessions.reason.lost": "Ended unexpectedly",+ "environments.sessions.reason.switched": "Replaced by another environment",+ "environments.sessions.running": "Running",+ "environments.sessions.snapshotFailed": "Not saved",+ "environments.sessions.snapshotSaved": "Saved {{size}}",+ "environments.sessions.stale": "No end recorded",+ "environments.sessions.title": "Run history",+ "environments.sessions.unavailable": "Part of the history could not be read โ some instances are missing from this list",+ "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.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 instance of the environment, so nothing overwrites anything else.",+ "environments.upgrade.benefits.instances.title": "One instance 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.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 instances keep everything between sessions.",+ "environments.upgrade.title": "Upgrade to Pro to unlock sandbox environments",+ "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.tabs.private": "Private",+ "environments.visibility.tabs.workspace": "Workspace","group.aiConfig": "Agent","group.common": "General","group.developer": "Developer",@@ -1389,10 +1565,16 @@"storageOverage.disabled": "Storage pay-as-you-go disabled.","storageOverage.enableFailed": "Failed to enable storage pay-as-you-go.","storageOverage.enabled": "Storage pay-as-you-go enabled.",+ "storageOverage.mobileManaged.desc": "Your plan was purchased in an app store, so storage pay-as-you-go cannot be enabled here. Manage this subscription where you bought it.","storageOverage.monthlyCap": "Monthly Spending Cap","storageOverage.monthlyCapDesc": "Leave empty for unlimited. Uploads will be blocked when the cap is reached.","storageOverage.noPaymentMethod": "Please add a payment method to enable storage pay-as-you-go.","storageOverage.rate": "About {{limitedMonthlyRate}}/GB/month for a limited time (regular {{regularMonthlyRate}}).",+ "storageOverage.sandbox.consent.rate": "About {{regularMonthlyRate}}/GB/month.",+ "storageOverage.sandbox.desc": "Bill for sandbox workspace storage beyond your plan's included size, instead of stopping at it.",+ "storageOverage.sandbox.disableConfirm.blockWrites": "If your workspace is still above the included size, agents will be unable to write to it.",+ "storageOverage.sandbox.rate": "About {{regularMonthlyRate}}/GB/month.",+ "storageOverage.sandbox.title": "Sandbox Storage Pay-as-you-go","storageOverage.subscriptionRequired.action": "View plans","storageOverage.subscriptionRequired.desc": "Subscribe to a plan to enable storage pay-as-you-go for overage usage.","storageOverage.title": "File Storage Pay-as-you-go",@@ -1502,6 +1684,7 @@"tab.connector": "Connectors","tab.creds": "Credentials","tab.devices": "Devices",+ "tab.environments": "Environments","tab.experiment": "Experiment","tab.hotkey": "Hotkeys","tab.image": "Image Generation",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex 5e5dee5f46c..c21cf328055 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -516,6 +516,8 @@"plansModal.messengerWechat.title": "Connect WeChat after upgrading","plansModal.modelAccess.desc": "This model is available on paid plans. Upgrade to use the full model lineup.","plansModal.modelAccess.title": "Unlock all models",+ "plansModal.persistentSandbox.desc": "Files your agent writes in the cloud sandbox are discarded when the session ends. Upgrade to keep a persistent working directory that survives sessions and is shared across your topics.",+ "plansModal.persistentSandbox.title": "Keep your sandbox files","qa.desc": "If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.","qa.detail": "View Details","qa.list.credit.a": "Credits are how {{cloud}} measures AI model usage. Different AI models consume different amounts of credits.",@@ -673,5 +675,6 @@"usage.overview.title": "Overview","usage.remaining": "Remaining","usage.storage.embeddings.used": "Vector Storage",- "usage.storage.file.used": "File Usage"+ "usage.storage.file.used": "File Usage",+ "usage.storage.sandboxStorage.used": "Sandbox Storage"}diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 73a0351b4e7..042633b6d03 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1191,7 +1191,7 @@"heteroAgent.executionTarget.reconnect": "้ๆฐ่ฟๆฅ","heteroAgent.executionTarget.reconnectFailed": "ๆ ๆณ้ๆฐ่ฟๆฅๆญค่ฎพๅคใ่ฏท็กฎ่ฎคๆก้ข็ซฏๆญฃๅจ่ฟ่ก๏ผ็ถๅ้่ฏใ","heteroAgent.executionTarget.sandbox": "ไบ็ซฏๆฒ็ฎฑ",- "heteroAgent.executionTarget.sandboxDesc": "ๅจไธดๆถไบ็ซฏๆฒ็ฎฑไธญ่ฟ่ก",+ "heteroAgent.executionTarget.sandboxDesc": "ไบ็ซฏ่ฟ่ก๏ผไธๅ ็จๆบๅจ","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} ็ฎๅไป ๆฏๆๅจๆฌๅฐ่ฎพๅคๆๅทฒ่ฟๆฅ่ฎพๅคไธ่ฟ่ก","heteroAgent.executionTarget.switchTopic.content": "ๆฌ่ฏ้ขไธ็ดๅจใ{{name}}ใไธ่ฟ่ก๏ผๅทฅไฝ็ฎๅฝๅไผ่ฏ้ฝไฟๅญๅจ้ฃ้ใๅๆขๅ๏ผไธไธ่ฝฎไผๅจๆฐ็ฏๅขไธญๅผๅฏๆฐไผ่ฏ๏ผไนๅ็ๆฐ่ฏ้ขไนไผไฝฟ็จ่ฟไธช้ๆฉใ","heteroAgent.executionTarget.switchTopic.ok": "ๅๆข",@@ -1700,6 +1700,27 @@"runtimeEnv.mode.noneDesc": "็ฆ็จ่ฟ่กๆถ็ฏๅข","runtimeEnv.selectMode": "้ๆฉ่ฟ่ก็ฏๅข","runtimeEnv.title": "่ฟ่ก็ฏๅข",+ "sandboxStorage.buildFailed": "ๆชๆๅปบ",+ "sandboxStorage.building": "ๆๅปบไธญ",+ "sandboxStorage.environmentsUnavailable": "็ฏๅขๅ่กจๆฒก่ฝ่ฏปๅ",+ "sandboxStorage.ephemeral": "ไธดๆถๅทฅไฝ็ฎๅฝ",+ "sandboxStorage.ephemeralDesc": "ๆฒ็ฎฑๅๆถๆถไผ่ขซๆธ ็",+ "sandboxStorage.instanceBusy": "{{name}} ๆญฃๅจๅฆไธไธชๅฏน่ฏ้่ฟ่กใ่ฟไธชๅฏน่ฏไป็ถ็ป็ๅฎ๏ผ็ญ้ฃ่พน็ปๆๅๆฅ็็จใ",+ "sandboxStorage.manage": "็ฎก็",+ "sandboxStorage.noInstances": "ๅๅปบ็ฏๅขๅฎไพ",+ "sandboxStorage.noInstancesDesc": "ไฝ ็็ฏๅข่ฟๆฒกๆๅทฅไฝๅฏๆฌ",+ "sandboxStorage.persistentUpsell": "ๆไน ๅๅทฅไฝ็ฎๅฝ",+ "sandboxStorage.persistentUpsellDesc": "่ทจ่ฟ่กใ่ทจ่ฏ้ขไฟ็ๆไปถ",+ "sandboxStorage.pickerInfoTooltip": "็ฏๅขๆ่ฟฐไธๆฌก่ฟ่ก้่ฆ็ๅจ่พนโโไปๅบใๅๅงๅใๅ้ใๅฎไพๆฏๅฎ็ไธไปฝๅทฅไฝๅฏๆฌ๏ผๆ่ชๅทฑ็็ฎๅฝๅ่ชๅทฑ่ฃ ็ๅ ๏ผๅฏน่ฏ่ทๅจๅฎไพ้๏ผ็ไธ็ไธ่ฅฟไน็ๅจๅฎไพ้ใ",+ "sandboxStorage.pickerTitle": "็ฏๅขๅฎไพ",+ "sandboxStorage.privateGroup": "็งไบบ็ฏๅข",+ "sandboxStorage.privateInstanceBlocked": "ใ{{name}}ใๅฑไบ็งไบบ็ฏๅข๏ผๅ ฌๅ ฑ Agent ๆ ๆณไฝฟ็จ๏ผๆฌ่ฏ้ขๅทฒๆน็จไธดๆถ็ฎๅฝ่ฟ่กใ",+ "sandboxStorage.publicAgentHint_one": "ๅทฒ้่ {{count}} ไธช็งไบบ็ฏๅข โโ ๅ ฌๅ ฑ Agent ไป ๅฏไฝฟ็จๅทฅไฝๅบ็ฏๅข๏ผๅๅธๅๅณๅฏๅจ่ฟ้ไฝฟ็จใ",+ "sandboxStorage.publicAgentHint_other": "ๅทฒ้่ {{count}} ไธช็งไบบ็ฏๅข โโ ๅ ฌๅ ฑ Agent ไป ๅฏไฝฟ็จๅทฅไฝๅบ็ฏๅข๏ผๅๅธๅๅณๅฏๅจ่ฟ้ไฝฟ็จใ",+ "sandboxStorage.running": "่ฟ่กไธญ",+ "sandboxStorage.setUpEnvironment": "ๅปๅๅปบ็ฏๅข",+ "sandboxStorage.setUpEnvironmentDesc": "ๆไน ๅ็ฎๅฝ้่ฆๅ ๆไธไธช็ฏๅข",+ "sandboxStorage.workspaceGroup": "ๅทฅไฝๅบ็ฏๅข","search.grounding.imageSearchQueries": "ๅพ็ๆ็ดขๅ ณ้ฎ่ฏ","search.grounding.imageTitle": "ๆพๅฐ {{count}} ๅผ ๅพ็","search.grounding.searchQueries": "ๆ็ดขๅ ณ้ฎ่ฏ",@@ -2729,6 +2750,7 @@"workingPanel.files.filters.title": "็ญ้ๆไปถ","workingPanel.files.noSearchResults": "ๆฒกๆๅน้ ็ๆไปถ","workingPanel.files.open": "ๆๅผๆไปถ",+ "workingPanel.files.openNeedsTopic": "ๅ ๅไธๆกๆถๆฏ โโ ่ฏฅ็ฏๅข็ๆไปถ่ฆๅจๅฏน่ฏๅปบ็ซไผ่ฏๅๆ่ฝๆๅผใ","workingPanel.files.search": "ๆ็ดขๆไปถ","workingPanel.files.searchPlaceholder": "็ญ้ๆไปถ...","workingPanel.files.showInReview": "ๅจๅฎกๆฅไธญๆฅ็",@@ -2738,6 +2760,7 @@"workingPanel.files.trashName.mac": "ๅบ็บธ็ฏ","workingPanel.files.trashName.windows": "ๅๆถ็ซ","workingPanel.files.truncatedNotice": "้จๅๅฑๅผ็ๆไปถๅคนๅ ๅฎน่ฟๅค๏ผไป ๆพ็คบๅ้จๅๆก็ฎ",+ "workingPanel.files.unreadable": "่ฏปไธๅฐ่ฟไธชๅทฅไฝๅบโโๅฎๅฏ่ฝ่ฟไธๅญๅจ๏ผๆ่ ๅ็ฎๅฝๅคฑ่ดฅไบ","workingPanel.files.validation.empty": "่ฏท่พๅ ฅๆไปถๆๆไปถๅคนๅ็งฐ","workingPanel.files.validation.exists": "ๆญคไฝ็ฝฎๅทฒๅญๅจใ{{name}}ใ๏ผ่ฏทๆขไธไธชๅ็งฐ","workingPanel.files.validation.invalidChars": "ๅ็งฐไธ่ฝๅ ๅซ < > : \" / \\ | ? * ๆๆงๅถๅญ็ฌฆ",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 768113ce284..b90771c2d32 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -518,6 +518,7 @@"visibilityConfirm.makePrivate.itemLibrary": "ๅฎไปไผ็ๅจไฝ ๆพๅ ฅ็่ตๆๅบไธญ๏ผๅชๆฏๅ ถไปๆๅไธๅ็ๅพๅฐ","visibilityConfirm.makePrivate.itemLoaded": "ๅฏนๆนๅทฒๅ ่ฝฝ่ฟ็ๅ ๅฎนๆ ๆณๆถๅ","visibilityConfirm.makePrivate.itemReferences": "ๅทฒๅญๅจ็ๆถๆฏ้ไปถใๅผ็จไฝ็ฝฎไผๆพ็คบไธบใๅทฒๅคฑๆใ",+ "visibilityConfirm.publish.itemCapturedState": "ๆๅๅฏไปฅ่ฟ่กๅฎ็ๅฎไพ๏ผๅนถ่ฎฟ้ฎๅ ถไธญๆ่ท็ไธๅ โโ ๆไปถใCLI ็ปๅฝๆใไฝ ็็ปๅฝ่บซไปฝ","visibilityConfirm.publish.itemLoaded": "ๆนๅ็งไบบๅๅฏนๆนๅทฒๅ ่ฝฝ็ๅ ๅฎนๆ ๆณๆถๅ","visibilityConfirm.publish.itemReversible": "ไนๅๅฏไปฅๅจๅไธ่ๅ้ๆนๅ็งไบบ","visibilityConfirm.publish.itemVisible": "ๅทฅไฝๅบๆๆๆๅไผ็ซๅณๅฏไปฅ็ๅฐ",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex b3cb1f9712b..ac6d86595f3 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -36,6 +36,8 @@"features.messageTextSelectionActions.title": "ๆถๆฏๆๆฌ้ๆฉๆไฝ","features.oauthApps.desc": "ๅจไธชไบบๅๅทฅไฝๅบ่ฎพ็ฝฎไธญๆพ็คบ OAuth ๅบ็จ็ฎก็ๅ ฅๅฃใๆญคๅ่ฝ้ป่ฎค้่ใ","features.oauthApps.title": "OAuth ๅบ็จ",+ "features.persistentSandbox.desc": "่ฎฉไบ็ซฏๆฒ็ฎฑๅไธ็ๆไปถ็ๅญใๅทฅไฝ็ฎๅฝๅจไผ่ฏๅๆถๅไพ็ถๅญๅจ๏ผๅนถๅจไฝ ็ๅไธช่ฏ้ข้ดๅ ฑไบซ๏ผ่ไธๆฏ้ๆฒ็ฎฑไธ่ตทไธขๅผใ้่ฆไป่ดนๅฅ้ค๏ผไฝ็งฏๅคง็ไพ่ตๅๆฐๆฎ้ไปๅบๆพๅจ /tmpใ",+ "features.persistentSandbox.title": "ๆไน ๅๆฒ็ฎฑ","features.projects.desc": "ๅฐ้ฟๆ็ฎๆ ็ป็ปๅฐ็ฌ็ซๅทฅไฝ็ฉบ้ดไธญ๏ผๅนถ้ไธญ็ฎก็็ธๅ ณๆบ่ฝไฝใ่ตๆๅบไธไปปๅกใ","features.projects.title": "้กน็ฎๅทฅไฝ็ฉบ้ด","features.selfLearning.desc": "ไปๅฎ่ทตไธญๅญฆไน ๏ผไฝ ๆๅ็้ชๆถไผๆฒๆทๆ่ง็ฉ๏ผๆฏไธช Agent ไนไผไป่ชๅทฑ็่ฟ่ก้ๅญฆๅฐ็ป้ช๏ผ่ฟ่กๆถ้ฝไผๅธฆ็ป Agentใๅจใ่ฎฐๅฟ โ ่ช่ฟๅใ้็ปไธๆฅ็ใ",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 718fb499f29..b063c540d90 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -518,6 +518,182 @@"devices.visibilityTabs.private": "็งไบบ","devices.visibilityTabs.workspace": "ๅทฅไฝๅบ","devices.workingDirectory": "ๅทฅไฝ็ฎๅฝ๏ผ{{path}}",+ "environments.cancel": "ๅๆถ",+ "environments.create": "ๆฐๅปบ็ฏๅข",+ "environments.createFailed": "็ฏๅขๆฒก่ฝๅๅปบ",+ "environments.desc": "ไธๆฌกๆฒ็ฎฑ่ฟ่ก้่ฆ็ๅจ่พน๏ผไปฃ็ ไปๅบใๅๅงๅๅฝไปคใ็ฏๅขๅ้ใ็ฑๅฎๅปบๅบๆฅ็ๆฏไธชๅฎไพ๏ผๆไปถ้ฝ่ฝ่ทจไผ่ฏไฟ็ใ",+ "environments.detail.close": "ๅ ณ้ญ",+ "environments.detail.tabs.settings": "่ฎพ็ฝฎ",+ "environments.duplicateName": "ไฝ ๅทฒ็ปๆไธไธชๅๅ็็ฏๅขไบ",+ "environments.empty": "่ฟๆฒกๆ็ฏๅข",+ "environments.emptyPublished": "่ฟๆฒกๆ็ฏๅขๅๅธๅฐ่ฟไธชๅทฅไฝๅบ",+ "environments.files.back": "่ฟๅ",+ "environments.files.binary": "ไธๆฏๆๆฌๆไปถ๏ผๆ ๆณๅจ่ฟ้ๆฅ็ใ",+ "environments.files.browse": "ๆต่งๆไปถ",+ "environments.files.empty": "่ฟไธช็ฎๅฝๆฏ็ฉบ็",+ "environments.files.invalidPath": "ๅ็งฐๆ ๆ๏ผ่ทฏๅพไธ่ฝ่ถ ๅบ่ฏฅๅฎไพ็็ฎๅฝ",+ "environments.files.listFailed": "่ฟไธช็ฎๅฝๅไธๅบๆฅ",+ "environments.files.openHint": "ๅๅป็ฎๅฝ่ฟๅ ฅ๏ผๅๅปๆไปถๆฅ็",+ "environments.files.readOnlyHint": "ๅช่ฏป๏ผๅ ๅฎน็ฑๆฒ็ฎฑ่ชๅจๅๆญฅ๏ผnode_modules ็ญไพ่ต็ฎๅฝไธๅจ่ฟ้ๆพ็คบใ",+ "environments.files.truncated": "ๅชๆพ็คบไบๅ้ขไธ้จๅๆก็ฎ",+ "environments.files.unreadable": "่ฟไธชๆไปถ่ฏปไธๅบๆฅ",+ "environments.files.unusedInstance": "่ฟ้่ฟๆฒกๆๅ ๅฎนใๅฎไพๆๅปบๅฎๆๆๅจๅ ถไธญ่ฟ่ก่ฟๅฏน่ฏๅ๏ผไปฃ็ ไผๅบ็ฐๅจ่ฟ้ใ",+ "environments.files.up": "่ฟๅไธไธ็บง",+ "environments.form.addEnv": "ๆฐๅปบๅ้",+ "environments.form.addSource": "ๆทปๅ ไปๅบ",+ "environments.form.appliesOnBuild": "ๅจๆฐๅปบๅฎไพๆถ็ๆใๅทฒๆๅฎไพไผไธ็ด็จๅฎๅๅปบๆถ็้ฃไปฝๅฎไนโโ้ๅปบไนๆฏ็ งๅฎๅ่ทไธ้๏ผ่ฆ็จไธๆนๅจๅฐฑๆฐๅปบไธไธชๅฎไพใ",+ "environments.form.basics": "ๅบๆฌไฟกๆฏ",+ "environments.form.bootstrap": "ๅๅงๅๅฝไปค",+ "environments.form.bootstrapHint": "ๅจๅฏน่ฏๅผๅงๅ๏ผไบไปฃ็ ็ฎๅฝไธญ่็ฝๆง่กไธๆฌกใ",+ "environments.form.changeRepository": "ๆดๆขไปๅบ",+ "environments.form.desc": "ๅฎไพ็ฑไปไนๅปบๅบๆฅ๏ผไปฃ็ ไปๅชๆฅ๏ผไปฅๅ้ ไปไน่ฎฉๅฎ่ฝ่ท่ตทๆฅใ",+ "environments.form.description": "ๆ่ฟฐ",+ "environments.form.descriptionPlaceholder": "่ฟไธช็ฏๅขๆฏ็จๆฅๅไปไน็",+ "environments.form.disconnect": "ๆญๅผ",+ "environments.form.editEnv": "็ผ่พๅ้",+ "environments.form.env": "็ฏๅขๅ้",+ "environments.form.envCount_one": "{{count}} ไธชๅ้",+ "environments.form.envCount_other": "{{count}} ไธชๅ้",+ "environments.form.envEmpty": "่ฟๆฒกๆ็ฏๅขๅ้",+ "environments.form.envEmptyHint": "้ๆกๆทปๅ ๏ผๆๆดไปฝ .env ็ฒ่ดดๅฐ",+ "environments.form.envHint": "ๅชๆพ้ๅฏๆๅ ๅฎนโโๅฎไปฌไปฅๆๆๅญๅจ๏ผๅนถไผ่ขซๅคๅถ่ฟๆฏไธไธชๅฎไพใ",+ "environments.form.exclude": "ๅฏๅ็่ทฏๅพ",+ "environments.form.excludeHint": "ไธ่กไธไธช๏ผ็ธๅฏนไบๅฏๆฌใๅๅจ่ฟ้็ญไบๅฃฐๆๅฎๅฏไปฅ้ๅปบ๏ผไบๆฏๅฎไผ่ทไฝ ็ไบงๅบๅๅผๅญๆพใๅนถไธๅฏ่ฝ่ขซๆธ ็ๆใๅ่ฟๆฅไฝๅ ถๅฎ้ๅปบไธไบ็ไธ่ฅฟ๏ผๅฐฑๆฏไฝ ๅฏ่ฝไธขๆ็ไธ่ฅฟใ",+ "environments.form.internetAccess": "ๅฏน่ฏ่็ฝ",+ "environments.form.internetAccessHint": "ๅๅงๅๅฝไปคๅง็ปๅฏไปฅ่็ฝ๏ผ่ฟ้ๆงๅถ็ๆฏๅฏน่ฏๆฌ่บซใ",+ "environments.form.maintenance": "็ปดๆคๅฝไปค",+ "environments.form.maintenanceHint": "ๆฏๆฌกๅๅฐ่ฟไธชๅฏๆฌ็ปง็ปญๅทฅไฝๆถๆง่กโโๆดๆฐไปฃ็ ใ่กฅไธๆฌก่ฟ็งปใๅฎไธๆฏๅ่ทไธ้ๅๅงๅๅฝไปค๏ผ้ฃไธชๅพ่ดต๏ผๆฌๆฅๅฐฑๅช่ฏฅ่ทไธๆฌกใ",+ "environments.form.path": "็ฎๅฝ",+ "environments.form.rawEditor": "ๅๅง็ผ่พๅจ",+ "environments.form.rawEditorHint": "ๆฏ่กไธๆก KEY=value๏ผๅ .env ๆไปถไธๆ ทใ็ฉบ่กๅ # ๆณจ้ไผ่ขซๅฟฝ็ฅ๏ผไฟๅญไผๆฟๆขๅ จ้จๅ้ใ",+ "environments.form.rawInvalid": "็ฌฌ {{line}} ่กไธๆฏ KEY=value ๆ ผๅผ",+ "environments.form.ref": "ๅๆฏๆๆ ็ญพ",+ "environments.form.refDefault": "ไปๅบ้ป่ฎคๅๆฏ",+ "environments.form.removeEnv": "็งป้คๅ้",+ "environments.form.removeSource": "็งป้คไปๅบ",+ "environments.form.runtime": "่ฟ่กไธๅญๅจ",+ "environments.form.saved": "ๅทฒไฟๅญ",+ "environments.form.setup": "ๅๅงๅ",+ "environments.form.sources": "ๆบไปฃ็ ",+ "environments.form.sourcesHint": "ๅจๅ ถไปๆญฅ้ชคไนๅ้่ฟ HTTPS ๅ ้ใๆไธๆฏๆ็งๆไปๅบโโ่งๆ ผ้ไธๅญๆพไปปไฝๅญๆฎใ",+ "environments.github.connect": "่ฟๆฅ GitHub",+ "environments.github.label": "ไปฃ็ ไปๅบ",+ "environments.github.noRepositories": "่ฟไธช่ฟๆฅ่ฟ็ไธๅฐไปปไฝไปๅบ",+ "environments.github.notConnected": "่ฟๆฒกๆ่ฟๆฅ GitHubโโ่ฟๆฅๅๅณๅฏๆไปๅบๅๅปบ็ฏๅข",+ "environments.github.optional": "ๅฏไธ้",+ "environments.github.organization": "็ป็ป",+ "environments.github.organizationPlaceholder": "ๆ็ดข็ป็ป",+ "environments.github.repository": "ไปๅบ",+ "environments.github.repositoryPending": "่ฏทๅ ้ๆฉ็ป็ป",+ "environments.github.repositoryPlaceholder": "ๆ็ดขไปๅบ",+ "environments.github.reviewAccess": "ๆฃๆฅๆๆ่ๅด",+ "environments.hasInstances": "่ฏทๅ ๅ ๆๅฎ็ๅฎไพ",+ "environments.instances.add": "ๆฐๅปบๅฎไพ",+ "environments.instances.build": "ๆๅปบ",+ "environments.instances.buildConfirmTitle": "ๆๅปบๅฎไพ {{name}}๏ผ",+ "environments.instances.buildFailed": "ๆๅปบๅคฑ่ดฅ",+ "environments.instances.buildStartFailed": "ๆฒก่ฝๅผๅงๆๅปบ",+ "environments.instances.buildStatusUnknown": "ๆๆถ่ฏปไธๅฐ่ฟๆฌกๆๅปบ็็ถๆ",+ "environments.instances.building": "ๆๅปบไธญโโๆญฃๅจๆๅไปฃ็ ๅนถๅฎ่ฃ ไพ่ต",+ "environments.instances.confirm": "ๅๅปบ",+ "environments.instances.count_one": "{{count}} ไธชๅฎไพ",+ "environments.instances.count_other": "{{count}} ไธชๅฎไพ",+ "environments.instances.create": "ๅๅปบๅฎไพ",+ "environments.instances.createFailed": "ๅฎไพๆฒก่ฝๅๅปบ",+ "environments.instances.desc": "ๅฎไพๆฏ่ฟไธช็ฏๅข็ไธไปฝๅฏ่ฟ่กๅฏๆฌ๏ผๆ่ชๅทฑ็็ฎๅฝๅ่ฃ ๅฅฝ็ไพ่ตใๅฏน่ฏๅจๅฎไพ้่ฟ่ก๏ผๅคไธชๅฎไพๅฏไปฅๅนถ่ก่ไบไธๅฝฑๅใ",+ "environments.instances.directoryHint": "ๆไปถๅคน็ฎๅฝ๏ผๅๅปบๅไธๅฏไฟฎๆน",+ "environments.instances.directoryLabel": "็ฎๅฝ",+ "environments.instances.directoryLocked": "ๅฎไพๅปบๅฅฝไนๅ็ฎๅฝๅฐฑไธ่ฝๆนไบโโ่ฆๆข็ฎๅฝ๏ผๅ ๆๅๆฐๅปบไธไธชใ",+ "environments.instances.duplicateDirectory": "ๅทฒ็ปๆๅฆไธไธชๅฎไพๅจ็จ่ฟไธช็ฎๅฝไบ",+ "environments.instances.empty": "่ฟๆฒกๆๅฎไพ",+ "environments.instances.emptyHint": "ๆฐๅปบๅ๏ผๅจๅฏน่ฏ่พๅ ฅๆก็ใๅทฅไฝ็ฎๅฝใ้้ไธญๅณๅฏไฝฟ็จใ",+ "environments.instances.emptyReadonly": "่ฟไธช็ฏๅข่ฟๆฒกๆไบบๅปบ่ฟๅฎไพ๏ผๅชๆๅฎ็ๅๅปบ่ ๅฏไปฅๆฐๅปบใ",+ "environments.instances.hideLog": "ๆถ่ตทๆฅๅฟ",+ "environments.instances.inUse": "ๆๅฏน่ฏๆญฃๅจไฝฟ็จ่ฟไธชๅฎไพ๏ผ็ญๅฎ็ปๆๅๅ่ฏ",+ "environments.instances.namePlaceholder": "ๅฎไพๅ็งฐ",+ "environments.instances.notBuilt": "ๅฐๆชๆๅปบโโ่ฟๆฒกๆๆๅไปฃ็ ใๅฎ่ฃ ไพ่ต",+ "environments.instances.occupancyUnavailable": "ๆๆถ่ฏปไธๅฐๅชไบๅฎไพๆญฃๅจ่ฟ่ก",+ "environments.instances.overlappingDirectory": "่ฏฅ็ฎๅฝไธๅ ถไปๅฎไพ็็ฎๅฝๅญๅจๅตๅฅ๏ผ่ฏทๆขไธไธช็ฎๅฝ",+ "environments.instances.rebuild": "้ๆฐๆๅปบ",+ "environments.instances.rebuildConfirmContent": "ไผๅ ๆธ ็ฉบ่ฟไธชๅฎไพ็็ฎๅฝ๏ผๅ้ๆฐๆๅไปฃ็ ใ่ฟ่กๅๅงๅ่ๆฌใ็ฎๅฝ้็ฐๆ็ไธๅโโๅฏน่ฏไธญ็ๆนๅจใ่ฃ ๅฅฝ็ไพ่ตใๆฅๅใๆฐๆฎโโ้ฝไผไธขๅคฑ๏ผๆ ๆณๆขๅคใ",+ "environments.instances.rebuildConfirmTitle": "้ๆฐๆๅปบๅฎไพ {{name}}๏ผ",+ "environments.instances.remove": "ๅ ้คๅฎไพ",+ "environments.instances.removeConfirmContent": "ๅฎ็็ฎๅฝๅ้้ข็ไธ็ไธๅโโ่ฃ ๅฅฝ็ไพ่ตใๆฅๅใๆฐๆฎโโ้ฝไผ่ขซๅ ้ค๏ผๆ ๆณๆขๅคใ",+ "environments.instances.removeConfirmTitle": "ๅ ้คๅฎไพ {{name}}๏ผ",+ "environments.instances.removeFailed": "ๅ ้คๅฎไพๅคฑ่ดฅ",+ "environments.instances.removing": "ๅ ้คไธญโโๆญฃๅจ็งป้คๅฎ็็ฎๅฝๅ้้ข็ไธๅ",+ "environments.instances.rename": "้ๅฝๅๅฎไพ",+ "environments.instances.renameFailed": "้ๅฝๅๅฎไพๅคฑ่ดฅ",+ "environments.instances.retryStatus": "้ๆฐๆฃๆฅ",+ "environments.instances.running": "่ฟ่กไธญ",+ "environments.instances.save": "ไฟๅญ",+ "environments.instances.showLog": "ๆฅ็ๆฅๅฟ",+ "environments.instances.title": "็ฏๅขๅฎไพ",+ "environments.loadFailed.desc": "ๆๆถ่็ณปไธไธๅคๆญๆฌ่ดฆๅทๆฏๅฆๆๆไน ๅทฅไฝๅบ็ๆๅกใไฝ ็็ฏๅขๆฌ่บซๆฒกๆ้ฎ้ขใ",+ "environments.loadFailed.retry": "้่ฏ",+ "environments.loadFailed.title": "ๆ ๆณ็กฎ่ฎคไฝ ็ๅฅ้ค",+ "environments.meta.createdAt": "ๅๅปบไบ {{time}}",+ "environments.meta.creatorTooltip": "็ฑ {{name}} ๅๅปบ",+ "environments.meta.storage": "ๅ ็จ {{size}}",+ "environments.meta.unknownCreator": "ๆช็ฅ",+ "environments.mine": "ๆ็็ฏๅข",+ "environments.nameLabel": "ๅ็งฐ",+ "environments.namePlaceholder": "็ฏๅขๅ็งฐ",+ "environments.refresh": "ๅทๆฐ",+ "environments.remove": "ๅ ้ค็ฏๅข",+ "environments.removeConfirmContent": "ๅฎ็้ ็ฝฎใ็ฏๅขๅ้ๅไฟๅญไธๆฅ็ๅฟซ็ ง้ฝไผไธ่ตทๅ ้ค๏ผๆ ๆณๆขๅคใ",+ "environments.removeConfirmTitle": "ๅ ้ค็ฏๅข {{name}}๏ผ",+ "environments.removeFailed": "ๅ ้ค็ฏๅขๅคฑ่ดฅ",+ "environments.saveFailed": "ๆ ๆณไฟๅญ่ฟๆฌกไฟฎๆน",+ "environments.sessions.activeBuild": "{{instance}} ๆญฃๅจๆๅปบ",+ "environments.sessions.activeSession": "ๆฒ็ฎฑๆญฃๅจ {{instance}} ไธญ่ฟ่ก",+ "environments.sessions.desc": "่ฟไบๅฎไพๆ่ฟ็่ฟ่กไผ่ฏๅๆๅปบ๏ผๆๆฐ็ๅจๅ๏ผๅซๅ่ช็็ปๆๆนๅผ๏ผไปฅๅๅฎ่ฃ ็ๅ ๅฎนๆฏๅฆ่ขซไฟๅญใ",+ "environments.sessions.empty": "่ฟๆฒกๆ่ฟ่ก่ฟ",+ "environments.sessions.emptyHint": "ๅฎไพไธญ่ฟ่ก่ฟ็ๅฏน่ฏๅๆๅปบ้ฝไผ่ฎฐๅฝๅจ่ฟ้ใ",+ "environments.sessions.history": "ๅๅฒ่ฎฐๅฝ",+ "environments.sessions.historyEmpty": "่ฟๆฒกๆ็ปๆ็่ฟ่ก",+ "environments.sessions.kind.build": "ๆๅปบ",+ "environments.sessions.kind.console": "ๆไปถๆต่ง",+ "environments.sessions.kind.conversation": "ๅฏน่ฏ",+ "environments.sessions.openConversation": "ๆๅผๅฏน่ฏ",+ "environments.sessions.reason.build_failed": "ๆๅปบๅคฑ่ดฅ",+ "environments.sessions.reason.build_gone": "ๆๅปบไธญๆญ",+ "environments.sessions.reason.build_succeeded": "ๆๅปบๅฎๆ",+ "environments.sessions.reason.build_timeout": "ๆๅปบ่ถ ๆถ",+ "environments.sessions.reason.expired": "ๅฐ่พพๆถ้ฟไธ้",+ "environments.sessions.reason.explicit": "ๅทฒๅๆญข",+ "environments.sessions.reason.idle": "้ฒ็ฝฎๅๅๆญข",+ "environments.sessions.reason.lost": "ๆๅค็ปๆ",+ "environments.sessions.reason.switched": "่ขซๅๆขๅฐๅ ถไป็ฏๅข",+ "environments.sessions.running": "่ฟ่กไธญ",+ "environments.sessions.snapshotFailed": "ๆชไฟๅญ",+ "environments.sessions.snapshotSaved": "ๅทฒไฟๅญ {{size}}",+ "environments.sessions.stale": "ๆฒกๆ็ปๆ่ฎฐๅฝ",+ "environments.sessions.title": "่ฟ่ก่ฎฐๅฝ",+ "environments.sessions.unavailable": "ๆไธ้จๅ่ฎฐๅฝๆฒก่ฏปๅฐ๏ผๅ่กจ้็ผบไบๆไบๅฎไพ็่ฟ่ก",+ "environments.storage.measuredAt": "็ป่ฎกไบ {{time}}๏ผ็นๅทๆฐๅฏ้ๆฐ็ป่ฎก",+ "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.upgrade.benefits.persist.title": "ๆไปถไธ้ๆฒ็ฎฑๅๆถ",+ "environments.upgrade.cta": "ๅ็บงๅฐ 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.tabs.private": "็งไบบ",+ "environments.visibility.tabs.workspace": "ๅทฅไฝๅบ","group.aiConfig": "ๆบ่ฝไฝ","group.common": "้็จ","group.developer": "ๅผๅ่ ",@@ -1389,10 +1565,16 @@"storageOverage.disabled": "ๅญๅจๆ้ไป่ดนๅทฒๅ ณ้ญใ","storageOverage.enableFailed": "ๅญๅจๆ้ไป่ดนๅฏ็จๅคฑ่ดฅใ","storageOverage.enabled": "ๅญๅจๆ้ไป่ดนๅทฒๅฏ็จใ",+ "storageOverage.mobileManaged.desc": "ไฝ ็ๅฅ้คๆฏๅจๅบ็จๅๅบ่ดญไนฐ็๏ผๆ ๆณๅจ่ฟ้ๅผๅฏๅญๅจๆ้ไป่ดนใ่ฏทๅฐ่ดญไนฐๆธ ้็ฎก็่ฏฅ่ฎข้ ใ","storageOverage.monthlyCap": "ๆๅบฆๆถ่ดนไธ้","storageOverage.monthlyCapDesc": "็็ฉบ่กจ็คบๆ ้ๅถใๅฝ่พพๅฐไธ้ๆถ๏ผไธไผ ๅฐ่ขซ้ปๆญขใ","storageOverage.noPaymentMethod": "่ฏทๅ ๆทปๅ ๆฏไปๆนๅผ๏ผๅๅฏ็จๅญๅจๆ้ไป่ดนใ","storageOverage.rate": "้ๆถ็บฆ {{limitedMonthlyRate}}/GB/ๆ๏ผๅไปท {{regularMonthlyRate}}๏ผใ",+ "storageOverage.sandbox.consent.rate": "็บฆ {{regularMonthlyRate}}/GB/ๆใ",+ "storageOverage.sandbox.desc": "ๆฒ็ฎฑๅทฅไฝๅบ่ถ ๅบๅฅ้ค่ชๅธฆๅฎน้็้จๅๆ้่ฎก่ดน๏ผ่ไธๆฏๅฐๆญคไธบๆญขใ",+ "storageOverage.sandbox.disableConfirm.blockWrites": "ๅฆๆๅทฅไฝๅบไป่ถ ๅบ่ชๅธฆๅฎน้๏ผagent ๅฐๆ ๆณๅๅๅ ถๅๅ ฅใ",+ "storageOverage.sandbox.rate": "็บฆ {{regularMonthlyRate}}/GB/ๆใ",+ "storageOverage.sandbox.title": "ๆฒ็ฎฑๅญๅจๆ้ไป่ดน","storageOverage.subscriptionRequired.action": "ๆฅ็ๅฅ้ค","storageOverage.subscriptionRequired.desc": "่ฎข้ ๅฅ้คๅ๏ผๅฏไธบ่ถ ๅบ้ขๅบฆ็ๆไปถๅญๅจๅฏ็จๆ้ไป่ดนใ","storageOverage.title": "ๆไปถๅญๅจๆ้ไป่ดน",@@ -1502,6 +1684,7 @@"tab.connector": "่ฟๆฅๅจ","tab.creds": "ๅญ่ฏ็ฎก็","tab.devices": "่ฎพๅค",+ "tab.environments": "็ฏๅข","tab.experiment": "ๅฎ้ช","tab.hotkey": "ๅฟซๆท้ฎ","tab.image": "็ป็ปๆๅก",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 33145e4c649..83b9cf9a822 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -516,6 +516,8 @@"plansModal.messengerWechat.title": "ๅ็บงๅ่ฟๆฅๅพฎไฟก","plansModal.modelAccess.desc": "่ฏฅๆจกๅไธบไป่ดนๆนๆกไธไบซ๏ผๅ็บงๅณๅฏไฝฟ็จๅ จ้จๆจกๅใ","plansModal.modelAccess.title": "่งฃ้ๅ จ้จๆจกๅ",+ "plansModal.persistentSandbox.desc": "ไบ็ซฏๆฒ็ฎฑ้ๅไธ็ๆไปถไผๅจไผ่ฏ็ปๆๅไธขๅผใๅ็บงๅๅฏ่ทๅพๆไน ๅๅทฅไฝ็ฎๅฝ๏ผ่ทจไผ่ฏไฟ็ใๅนถๅจๅไธช่ฏ้ข้ดๅ ฑไบซใ",+ "plansModal.persistentSandbox.title": "ไฟ็ๆฒ็ฎฑไธญ็ๆไปถ","qa.desc": "ๅฆๆๆจ็้ฎ้ขๆช่ขซ่งฃ็ญ๏ผ่ฏทๆฅ็ <1>ไบงๅๆๆกฃ</1> ่ทๅๆดๅคๅธธ่ง้ฎ้ข๏ผๆ่็ณปๆไปฌใ","qa.detail": "ๆฅ็่ฏฆๆ ","qa.list.credit.a": "็งฏๅๆฏ {{cloud}} ็จไบ่กก้ AI ๆจกๅ่ฐ็จ็จ้็ๆๆ ใไธๅๆจกๅๆถ่็็งฏๅไธๅใ",@@ -673,5 +675,6 @@"usage.overview.title": "ๆป่ง","usage.remaining": "ๅฉไฝ","usage.storage.embeddings.used": "ๅ้ๅญๅจ",- "usage.storage.file.used": "ๆไปถไฝฟ็จ้"+ "usage.storage.file.used": "ๆไปถไฝฟ็จ้",+ "usage.storage.sandboxStorage.used": "ๆฒ็ฎฑๅญๅจ"}diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.tsindex 22c87a25fec..2c7fafee514 100644--- a/packages/builtin-tool-cloud-sandbox/src/index.ts+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts@@ -2,3 +2,4 @@ export * from './manifest';export * from './systemRole';export * from './types';export * from './uploadedFiles';+export * from './workspace';diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.tsindex ccd95674d23..0034d753e9e 100644--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts@@ -5,10 +5,7 @@ export const systemPrompt = `You have access to a Cloud Sandbox that provides a<sandbox_environment>**Important:** This is a CLOUD SANDBOX environment, NOT the user's local file system.-- Files created here are temporary and session-specific-- Each conversation topic has its own isolated session-- Sessions may expire after inactivity; files will be recreated if needed-- The sandbox has its own isolated file system starting at the root directory+{{sandbox_workspace}}- Commands will time out after 120 seconds by default- **Default shell is /bin/sh** (typically dash or ash), NOT bash. Some commands may need bash-specific features โ wrap with \`bash -c "your_command"\` if needed.@@ -223,7 +220,7 @@ When generating PDFs with Chinese text, you MUST:<session_behavior>- Your sandbox session is automatically managed per conversation topic- If a session expires, it will be automatically recreated-- Files from previous sessions may not persist+{{sandbox_session_files}}- The sessionExpiredAndRecreated flag in responses indicates if this occurred</session_behavior>diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.test.tsnew file mode 100644index 00000000000..a2388fb09c8--- /dev/null+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import { formatSandboxStoragePromptVariables } from './workspace';++describe('formatSandboxStoragePromptVariables', () => {+ it('leaves the ephemeral wording exactly as a run without persistence has always had it', () => {+ // The ordinary sandbox is every free run and every topic that never asked+ // for persistence; its prompt must not drift because the persistent one+ // gained a rule.+ expect(formatSandboxStoragePromptVariables()).toEqual({+ sandbox_session_files: '- Files from previous sessions may not persist',+ sandbox_workspace: [+ '- Files created here are temporary and session-specific',+ '- Each conversation topic has its own isolated session',+ '- Sessions may expire after inactivity; files will be recreated if needed',+ '- The sandbox has its own isolated file system starting at the root directory',+ ].join('\n'),+ });+ expect(formatSandboxStoragePromptVariables({ mode: 'ephemeral' })).toEqual(+ formatSandboxStoragePromptVariables(),+ );+ });++ it('tells a persistent run to work where it starts rather than in scratch space', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ cwd: 'hello-dev',+ mode: 'persistent',+ });++ expect(prompt).toContain('`hello-dev`');+ expect(prompt).toContain('Every call starts you in that directory');+ expect(prompt).toContain('scratch directory');+ });++ it('says the same about placement when no subdirectory was chosen', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ mode: 'persistent',+ });++ expect(prompt).toContain('Every call starts you in that directory');+ });++ it('describes a built instance by where its commands actually start', () => {+ // The checkout lives on local disk and the session saves it into the+ // instance's directory, so a prompt that names the volume directory as the+ // working directory disagrees with `pwd` โ and a model that notices goes+ // hunting for the "real" one.+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ cwd: 'r18-copy',+ mode: 'persistent',+ workingDir: '/root/work',+ });++ expect(prompt).toContain('You start in `/root/work`');+ expect(prompt).toContain('`r18-copy`');+ expect(prompt).toContain('Do not move the task there');+ expect(prompt).not.toContain('Your working directory is `r18-copy`');+ });+});++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 prompt+ // is assembled for every run โ including the ones with no entitlement, where+ // the variable generators call this with nothing.+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables();++ expect(prompt).toContain('Files created here are temporary and session-specific');+ expect(prompt).not.toContain('{{');+ });+});diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.tsnew file mode 100644index 00000000000..dedeff28888--- /dev/null+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.ts@@ -0,0 +1,283 @@+/**+ * Persistent sandbox workspace: the vocabulary LobeHub needs to ASK for one and+ * to tell the model it has one.+ *+ * The cloud sandbox is a per-topic, disposable runtime. A persistent workspace+ * is a directory on a volume mounted into it that outlives the session and is+ * shared across the user's topics. Two independent inputs decide whether a run+ * actually gets one:+ *+ * 1. **Entitlement** โ LobeHub resolves the caller's plan into a signed+ * `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.+ *+ * 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+ * directory โ belongs to the execution plane, NOT here. This module therefore+ * contains no path handling at all: deriving a directory on this side would+ * reintroduce exactly the combination the routing is built to make impossible,+ * an ephemeral sandbox addressed with persistent-looking absolute paths.+ */++/**+ * Whether a run wants its working directory to survive 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 const DEFAULT_SANDBOX_MODE: SandboxMode = 'ephemeral';++export interface SandboxStorageScope {+ userId: string;+ /** Organization workspace id when the run is workspace-scoped. */+ workspaceId?: string | null;+}++/**+ * The entitlement itself, as it travels on the trusted-client token. `null` (or+ * absent) is the free-tier shape and means "no persistent workspace".+ */+export interface SandboxStorageClaim {+ /** Directory name inside the volume โ see {@link deriveSandboxStorageKey}. */+ key: string;+ /**+ * Whether this subject may write past {@link quotaBytes} and be billed for+ * what it goes over, the way file storage already works.+ *+ * The decision belongs to LobeHub because only LobeHub knows it: it turns on+ * a plan, a consent, a payment method and a monthly cap. The execution plane+ * knows none of those, so it is told the answer rather than the inputs.+ *+ * Absent means no โ an old token, or a deployment that has not adopted this,+ * enforces the quota as a hard limit, which is the behaviour that cannot+ * charge anyone by mistake.+ */+ overageAllowed?: boolean;+ /** Soft quota for the directory. The execution plane may cap it further, never raise it. */+ quotaBytes: number;+}++/**+ * Keys the execution plane accepts as a directory name: a word character, then+ * up to 127 more of `[A-Za-z0-9_.-]`. No separators or traversal, no leading+ * dot or dash (which would make a hidden or option-looking directory), bounded+ * length. Kept identical to the receiving end's check โ a key that fails it+ * there rejects the whole token, not just the claim.+ */+const SAFE_WORKSPACE_KEY = /^\w[\w.-]{0,127}$/;++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-';++/**+ * 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.+ *+ * Returns `undefined` for an id that is not already a safe path segment, which+ * costs that principal persistence rather than risking the alternative.+ * SANITIZING would be worse than refusing: `user_a/b` and `user_a-b` both+ * reduce to `ws-user_a-b`, and truncating a long id aliases every id sharing+ * its prefix โ in both cases two different principals silently land in ONE+ * directory and read each other's files. Every id the platform actually issues+ * (Clerk's `user_<base58>`, workspace ids) is already safe, so this rejects+ * nothing real.+ */+export const deriveSandboxStorageKey = ({+ userId,+ workspaceId,+}: SandboxStorageScope): string | undefined => {+ const segment = workspaceId || userId;+ if (!segment || !isSafeKeySegment(segment)) 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;++ const key = workspaceId ? `ws-${ORG_KEY_INFIX}${workspaceId}` : `ws-${userId}`;+ if (!SAFE_WORKSPACE_KEY.test(key)) return undefined;++ return key;+};++/** Workspace subtree the platform reserves for its own state. */+const RESERVED_WORKSPACE_DIR = '.sandbox';++/**+ * Where a built instance's checkout lives in the sandbox: on the machine's own+ * disk, not the volume, because installs cannot run on the volume. The+ * instance's directory on the volume is this tree's saved copy.+ */+export const SANDBOX_LOCAL_WORK_ROOT = '/root/work';++/** Longest `sandboxCwd` worth sending; far past any real directory nesting. */+const MAX_SANDBOX_CWD_LENGTH = 1024;++/**+ * Whether a chosen working directory is safe to send as a relative path.+ *+ * Shared by the picker that writes it and the server that forwards it, so a+ * directory the execution plane would reject is refused at the moment the user+ * picks it rather than on every tool call afterwards.+ *+ * It REJECTS rather than repairs. Collapsing `..` lexically disagrees with the+ * filesystem as soon as a symlink is involved, so a "cleaned" path can resolve+ * somewhere other than where it was judged safe.+ *+ * Interior whitespace is fine โ `my notes` is an ordinary directory. Leading or+ * trailing whitespace is not, and not as a matter of taste: the execution plane+ * strips the directory string while the shell `cd` keeps its quotes, so+ * `drafts ` would put the interpreter in `drafts` and the shell in `drafts ` and+ * the session would disagree with itself about where it is. The test is exactly+ * what would be silently rewritten.+ */+export const isSafeSandboxCwd = (value: string): boolean => {+ if (!value || value.length > MAX_SANDBOX_CWD_LENGTH) return false;+ if (value !== value.trim()) return false;+ if (value.startsWith('/') || value.startsWith('~')) return false;+ // The platform keeps its own state inside the workspace (environment+ // snapshots live under `.sandbox/`). Listing APIs hide it, but hiding is not+ // the same as refusing: a working directory pointed here would put an agent+ // inside the store its own environment is restored from, and a delete would+ // take every environment this user has with it. Only the top level is+ // reserved โ a `.sandbox` the user made deeper in their own tree is theirs.+ if (value === RESERVED_WORKSPACE_DIR || value.startsWith(`${RESERVED_WORKSPACE_DIR}/`)) {+ return false;+ }++ // Rejects `..` traversal, `.` no-ops, and the empty segments produced by a+ // leading, trailing or doubled slash โ none of which come from the picker.+ return value.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..');+};++/**+ * Identifiers the execution plane accepts for a named environment: a leading+ * alphanumeric, then `[A-Za-z0-9._-]`, at most 64 characters.+ *+ * Deliberately stricter than the workspace key's rule, and checked on this side+ * as well as the far one, because of WHERE the far one fails: a session runs to+ * completion and the snapshot is refused at the end, so the work is done and+ * there is nowhere to put it. Refusing at the point the identifier is chosen+ * costs nothing by comparison.+ */+const SAFE_ENVIRONMENT_ID = /^[A-Z0-9][\w.-]{0,63}$/i;++export const isSafeSandboxEnvironmentId = (value: string): boolean =>+ SAFE_ENVIRONMENT_ID.test(value);++/**+ * Prompt variables the cloud-sandbox system role consumes:+ * - `sandbox_workspace` fills the `<sandbox_environment>` file-system bullets+ * - `sandbox_session_files` fills the `<session_behavior>` persistence bullet+ *+ * An ephemeral run renders the ORIGINAL wording, byte for byte, so a deployment+ * where persistence is not enabled keeps the exact prompt it had before and+ * never leaks a raw placeholder.+ *+ * The persistent wording carries no absolute path on purpose. The mount root is+ * the execution plane's to choose, the runtime already starts every call inside+ * the workspace (including `executeCode`), and a path spelled out here would be+ * a second source of truth that can only ever drift out of agreement with the+ * first one.+ */+export interface SandboxStoragePromptVariables {+ sandbox_session_files: string;+ sandbox_workspace: string;+}++export interface SandboxStoragePromptInput {+ /** Chosen subdirectory of the workspace, relative to its root. */+ cwd?: string;+ mode?: SandboxMode;+ /**+ * Where commands actually start when that is not {@link cwd}: the checkout+ * on the machine's own disk, for an instance built from a repository. The+ * model is told this one absolutely because it can read it back from `pwd`;+ * describing that session as sitting in `cwd` makes the prompt disagree with+ * the shell, and a model that catches the prompt being wrong goes looking+ * for the "real" directory instead of working where it is.+ */+ workingDir?: string;+}++export const formatSandboxStoragePromptVariables = ({+ cwd,+ mode = DEFAULT_SANDBOX_MODE,+ workingDir,+}: SandboxStoragePromptInput = {}): SandboxStoragePromptVariables => {+ if (mode !== 'persistent') {+ return {+ sandbox_session_files: '- Files from previous sessions may not persist',+ sandbox_workspace: [+ '- Files created here are temporary and session-specific',+ '- Each conversation topic has its own isolated session',+ '- Sessions may expire after inactivity; files will be recreated if needed',+ '- The sandbox has its own isolated file system starting at the root directory',+ ].join('\n'),+ };+ }++ // 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+ ? [+ `- 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.`,+ ]+ : [+ '- 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.',+ ];++ return {+ sandbox_session_files:+ '- Files in your working directory persist across sessions; anything written outside it may not',+ sandbox_workspace: [+ ...placement,+ // 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+ // 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.',+ ].join('\n'),+ };+};++/** The `{{sandbox_workspace}}` section alone โ see {@link formatSandboxStoragePromptVariables}. */+export const formatSandboxStoragePrompt = (input?: SandboxStoragePromptInput): string =>+ formatSandboxStoragePromptVariables(input).sandbox_workspace;diff --git a/packages/builtin-tool-cloud-sandbox/vitest.config.mts b/packages/builtin-tool-cloud-sandbox/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-cloud-sandbox/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.tsindex f7477753c45..4200d2bae94 100644--- a/packages/builtin-tool-skills/src/systemRole.ts+++ b/packages/builtin-tool-skills/src/systemRole.ts@@ -70,6 +70,15 @@ export const systemPrompt = `You have access to a Skills tool that can activate3. Skill content instructs to run a bundled script (e.g., \`python scripts/init.py\`) โ use execScript</runcommand_vs_execscript>+<sandbox_environment>+\`runCommand\` and \`execScript\` run in the same cloud sandbox session as every other+sandbox tool in this conversation, in the same working directory. What that+directory is, and whether what you leave there survives the session, is below โ+and it decides where a checkout or a generated file belongs.+{{sandbox_workspace}}+</sandbox_environment>++<best_practices>- Only activate skills when the user's task clearly matches the skill's purpose- Follow the skill's instructions carefully once loadeddiff --git a/packages/business-server/src/sandboxStorage.ts b/packages/business-server/src/sandboxStorage.tsnew file mode 100644index 00000000000..2cad5acf001--- /dev/null+++ b/packages/business-server/src/sandboxStorage.ts@@ -0,0 +1,32 @@+/**+ * What this caller is entitled to in a persistent sandbox workspace, or `null`+ * for no persistent workspace at all โ the sandbox stays ephemeral, which is+ * the default and the only behaviour the open-source build has.+ *+ * A deployment that offers persistent workspaces overrides this module to+ * answer from whatever it uses to decide entitlements.+ *+ * Only the entitlement lives behind this slot. The directory NAME comes from+ * the caller's identity via `deriveSandboxStorageKey`; it is not a deployment+ * decision and must stay identical on both sides of the claim.+ */+export interface SandboxStorageEntitlement {+ /**+ * Whether writes past {@link quotaBytes} are allowed and billed, rather than+ * refused. Whatever decides that โ a plan, a consent, a payment method, a+ * spending cap โ is the deployment's business; the execution plane is told+ * the answer, never the inputs.+ *+ * Omitted means no, which is the answer that cannot charge anyone by+ * mistake.+ */+ overageAllowed?: boolean;+ /** How much storage the caller may keep, in bytes. */+ quotaBytes: number;+}++export const resolveSandboxStorageEntitlement = async (_params: {+ userId: string;+ /** Organization workspace the run is scoped to; it is judged, not the acting member. */+ workspaceId?: string | null;+}): Promise<SandboxStorageEntitlement | null> => null;diff --git a/packages/connector-data/src/github/client-market.test.ts b/packages/connector-data/src/github/client-market.test.tsindex d9c53216be1..0a54a193dea 100644--- a/packages/connector-data/src/github/client-market.test.ts+++ b/packages/connector-data/src/github/client-market.test.ts@@ -20,6 +20,9 @@ const createProxy = () =>if (input.endpoint === '/repos/lobehub/lobehub/contributors') {return { data: [{ contributions: 12, login: 'octocat' }], status: 200 };}+ if (input.endpoint === '/repos/lobehub/lobehub/branches') {+ return { data: [{ name: 'canary', protected: true }, { name: 'main' }, {}], status: 200 };+ }if (input.endpoint === '/graphql') {const body = input.body as { query?: string };if (body.query?.includes('ConnectorDataGitHubProfile')) {@@ -103,4 +106,21 @@ describe('createGitHubMarketConnectorClient', () => {websiteUrl: 'https://lobehub.com',});});++ it('lists a repository branches through the REST proxy', async () => {+ const proxyOAuthRequest = createProxy();+ const transport = createGitHubMarketTransport({ market: { proxyOAuthRequest } });++ await expect(+ transport.listRepositoryBranches({ owner: 'lobehub', perPage: 100, repository: 'lobehub' }),+ ).resolves.toEqual([{ name: 'canary' }, { name: 'main' }, { name: null }]);++ expect(proxyOAuthRequest).toHaveBeenCalledWith(+ expect.objectContaining({+ endpoint: '/repos/lobehub/lobehub/branches',+ method: 'GET',+ parameters: [{ in: 'query', name: 'per_page', value: 100 }],+ }),+ );+ });});diff --git a/packages/connector-data/src/github/client-market.ts b/packages/connector-data/src/github/client-market.tsindex 36cee62b4f9..9daeed137bf 100644--- a/packages/connector-data/src/github/client-market.ts+++ b/packages/connector-data/src/github/client-market.ts@@ -114,6 +114,54 @@ export const createGitHubMarketTransport = ({};});},+ listAccessibleRepositories: async ({ page, perPage }) => {+ // `/user/repos` already spans the organizations the token belongs to, so+ // one call answers the whole picker. Listing per organization would be+ // one request per organization for the same set.+ const data = await proxy({+ endpoint: '/user/repos',+ method: 'GET',+ parameters: [+ { in: 'query', name: 'page', value: page },+ { in: 'query', name: 'per_page', value: perPage },+ { in: 'query', name: 'sort', value: 'updated' },+ ],+ });+ if (!Array.isArray(data)) {+ throw new Error('GitHub Market repository response is invalid');+ }++ return data.map((item) => {+ const record = toRecord(item);+ const owner = toRecord(record?.owner);++ return {+ defaultBranch: typeof record?.default_branch === 'string' ? record.default_branch : null,+ isPrivate: record?.private === true,+ name: typeof record?.name === 'string' ? record.name : null,+ owner: typeof owner?.login === 'string' ? owner.login : null,+ };+ });+ },+ listRepositoryBranches: async ({ owner, page, perPage, repository }) => {+ const data = await proxy({+ endpoint: `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}/branches`,+ method: 'GET',+ parameters: [+ { in: 'query', name: 'per_page', value: perPage },+ ...(page ? [{ in: 'query' as const, name: 'page', value: page }] : []),+ ],+ });+ if (!Array.isArray(data)) {+ throw new Error('GitHub Market branch response is invalid');+ }++ return data.map((item) => {+ const record = toRecord(item);++ return { name: typeof record?.name === 'string' ? record.name : null };+ });+ },listUserOrganizations: async ({ perPage }) => {const data = await proxy({endpoint: '/user/orgs',diff --git a/packages/connector-data/src/github/client.test.ts b/packages/connector-data/src/github/client.test.tsindex 6fd562e7474..1072484f2b1 100644--- a/packages/connector-data/src/github/client.test.ts+++ b/packages/connector-data/src/github/client.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { createGitHubConnectorClient } from './client';+import { createGitHubConnectorClient, MAX_REPOSITORY_BRANCHES } from './client';import { createGitHubOAuthConnectorClient } from './client-oauth';import type { GitHubConnectorTransport } from './graphql/client';@@ -55,6 +55,8 @@ const createTransport = () => {]);const transport: GitHubConnectorTransport = {getAuthenticatedUser: async () => ({ id: 98_765, login: 'octocat' }),+ listAccessibleRepositories: async () => [],+ listRepositoryBranches: async () => [],listRepositoryContributors,listUserOrganizations,request: async ({ operation, variables }) => {@@ -435,6 +437,8 @@ describe('createGitHubConnectorClient', () => {});const transport: GitHubConnectorTransport = {getAuthenticatedUser: async () => ({ id: 98_765, login: 'octocat' }),+ listAccessibleRepositories: async () => [],+ listRepositoryBranches: async () => [],listRepositoryContributors: async () => [],listUserOrganizations: async () => [],request,@@ -451,6 +455,38 @@ describe('createGitHubConnectorClient', () => {expect(request).toHaveBeenCalledTimes(4);});+ // GitHub pages branches at 100. A repository with more used to lose every+ // branch past the first page, with no way to pick them.+ it('walks branch pages until a short one, up to the ceiling', async () => {+ const page = (count: number, prefix: string) =>+ Array.from({ length: count }, (_, index) => ({ name: `${prefix}-${index}` }));+ const listRepositoryBranches = vi.fn(async ({ page: n }: { page?: number }) =>+ n === 1 ? page(100, 'a') : page(30, 'b'),+ );+ const { transport } = createTransport();+ const client = createGitHubConnectorClient({+ transport: { ...transport, listRepositoryBranches },+ });++ await expect(client.listRepositoryBranches('acme', 'atlas')).resolves.toHaveLength(130);+ expect(listRepositoryBranches).toHaveBeenCalledTimes(2);+ expect(listRepositoryBranches).toHaveBeenLastCalledWith({+ owner: 'acme',+ page: 2,+ perPage: 100,+ repository: 'atlas',+ });++ const endless = vi.fn(async () => page(100, 'c'));+ const bounded = createGitHubConnectorClient({+ transport: { ...transport, listRepositoryBranches: endless },+ });+ await expect(bounded.listRepositoryBranches('acme', 'atlas')).resolves.toHaveLength(+ MAX_REPOSITORY_BRANCHES,+ );+ expect(endless).toHaveBeenCalledTimes(MAX_REPOSITORY_BRANCHES / 100);+ });+it('normalizes and bounds repository contributors in the loader', async () => {const { listRepositoryContributors, transport } = createTransport();const client = createGitHubConnectorClient({ transport });@@ -477,6 +513,8 @@ describe('createGitHubConnectorClient', () => {const sensitiveRepository = 'token-sensitive-owner/private-repository';const transport: GitHubConnectorTransport = {getAuthenticatedUser: async () => ({ id: 98_765, login: 'octocat' }),+ listAccessibleRepositories: async () => [],+ listRepositoryBranches: async () => [],listRepositoryContributors: vi.fn().mockRejectedValue({ status: 401 }),listUserOrganizations: async () => [],request: vi.fn(),@@ -590,4 +628,24 @@ describe('createGitHubConnectorClient', () => {'https://api.github.com/users/octocat/orgs?per_page=20',]);});++ it('lists branch names and drops entries the API returned without one', async () => {+ const transport: GitHubConnectorTransport = {+ getAuthenticatedUser: async () => ({ id: 98_765, login: 'octocat' }),+ listAccessibleRepositories: async () => [],+ listRepositoryBranches: async ({ owner, repository }) =>+ owner === 'lobehub' && repository === 'lobehub'+ ? [{ name: 'canary' }, { name: null }, { name: 'main' }]+ : [],+ listRepositoryContributors: async () => [],+ listUserOrganizations: async () => [],+ request: async () => ({}),+ };+ const client = createGitHubConnectorClient({ transport });++ await expect(client.listRepositoryBranches('lobehub', 'lobehub')).resolves.toEqual([+ 'canary',+ 'main',+ ]);+ });});diff --git a/packages/connector-data/src/github/client.ts b/packages/connector-data/src/github/client.tsindex d3de70f02ac..b6ef8bcd6f7 100644--- a/packages/connector-data/src/github/client.ts+++ b/packages/connector-data/src/github/client.ts@@ -15,15 +15,33 @@ import type {GitHubContribution,GitHubContributionCollectionOptions,GitHubOrganization,+ GitHubOwnerRepository,GitHubPullRequest,GitHubRepository,GitHubRepositoryContributor,GitHubUserProfile,} from './types';+const BRANCH_PAGE_SIZE = 100;+const REPOSITORY_PAGE_SIZE = 100;++/**+ * The most repositories {@link GitHubConnectorClient.listAccessibleRepositories}+ * returns. A list of exactly this length may be partial.+ */+export const MAX_ACCESSIBLE_REPOSITORIES = 1000;++/**+ * The most branches {@link GitHubConnectorClient.listRepositoryBranches}+ * returns. A list of exactly this length may be partial.+ */+export const MAX_REPOSITORY_BRANCHES = 1000;+export interface GitHubConnectorClient {getUserProfile: () => Promise<GitHubUserProfile>;getUserProfileReadme: () => Promise<string | undefined>;+ /** Every repository this account can reach, newest activity first. */+ listAccessibleRepositories: () => Promise<GitHubOwnerRepository[]>;/** Lists repositories associated with the user during the configured contribution window. */listContributedRepositories: () => Promise<GitHubContributedRepository[]>;/** Lists high-star repositories with contribution evidence in the configured window. */@@ -34,6 +52,8 @@ export interface GitHubConnectorClient {listRecentContributions: () => Promise<GitHubContribution[]>;listRecentPullRequests: () => Promise<GitHubPullRequest[]>;listRecentRepositories: () => Promise<GitHubRepository[]>;+ /** Branch names of one repository, in the order GitHub lists them. */+ listRepositoryBranches: (owner: string, repository: string) => Promise<string[]>;listRepositoryContributors: (repository: string) => Promise<GitHubRepositoryContributor[]>;listUserOrganizations: () => Promise<GitHubOrganization[]>;}@@ -102,7 +122,57 @@ export function createGitHubConnectorClient({listRecentContributions: async () => (await getContributionOverview()).contributions,listRecentPullRequests: async () => (await getRepositories()).pulls,listRecentRepositories: async () => (await getRepositories()).recent,+ listRepositoryBranches: async (owner, repository) => {+ // GitHub pages at 100. Walked to a ceiling rather than to the end: a+ // repository with thousands of branches would otherwise be thousands of+ // requests behind one picker. A caller that gets exactly the ceiling back+ // should treat the list as partial.+ const names: string[] = [];+ for (let page = 1; page <= MAX_REPOSITORY_BRANCHES / BRANCH_PAGE_SIZE; page += 1) {+ const branches = await transport.listRepositoryBranches({+ owner,+ page,+ perPage: BRANCH_PAGE_SIZE,+ repository,+ });+ for (const { name } of branches) if (name) names.push(name);+ if (branches.length < BRANCH_PAGE_SIZE) break;+ }++ return names;+ },listRepositoryContributors: (repository) => loadRepositoryContributors(transport, repository),+ listAccessibleRepositories: async () => {+ // Walked the same way the branch listing is: GitHub pages at 100, and a+ // single page silently hides every repository past the first hundred+ // from a picker that only filters what it was handed. The ceiling keeps+ // an account with thousands of them from becoming thousands of requests.+ const repositories: Awaited<ReturnType<typeof transport.listAccessibleRepositories>> = [];+ for (let page = 1; page <= MAX_ACCESSIBLE_REPOSITORIES / REPOSITORY_PAGE_SIZE; page += 1) {+ const batch = await transport.listAccessibleRepositories({+ page,+ perPage: REPOSITORY_PAGE_SIZE,+ });+ repositories.push(...batch);+ if (batch.length < REPOSITORY_PAGE_SIZE) break;+ }++ // A repository the caller cannot address โ missing either half of+ // `owner/name` โ is dropped rather than rendered as a row that cannot be+ // turned into a checkout URL.+ return repositories.flatMap(({ defaultBranch, isPrivate, name, owner: login }) =>+ name && login+ ? [+ {+ defaultBranch: defaultBranch ?? undefined,+ isPrivate: isPrivate === true,+ name,+ owner: login,+ },+ ]+ : [],+ );+ },listUserOrganizations: () => loadOrganizations(transport),};}diff --git a/packages/connector-data/src/github/graphql/client.test.ts b/packages/connector-data/src/github/graphql/client.test.tsindex ed338569df0..a6c93689ff0 100644--- a/packages/connector-data/src/github/graphql/client.test.ts+++ b/packages/connector-data/src/github/graphql/client.test.ts@@ -34,6 +34,8 @@ const createTransport = (request: GitHubConnectorTransport['request'],): GitHubConnectorTransport => ({getAuthenticatedUser: async () => ({ id: 1, login: 'neko' }),+ listAccessibleRepositories: async () => [],+ listRepositoryBranches: async () => [],listRepositoryContributors: async () => [],listUserOrganizations: async () => [],request,diff --git a/packages/connector-data/src/github/graphql/client.ts b/packages/connector-data/src/github/graphql/client.tsindex 9f48cb39662..0c308f11584 100644--- a/packages/connector-data/src/github/graphql/client.ts+++ b/packages/connector-data/src/github/graphql/client.ts@@ -36,6 +36,28 @@ export interface GitHubGraphQLRequest<Variables extends Record<string, unknown>>/** @internal Test seam and protocol adapter. */export interface GitHubConnectorTransport {getAuthenticatedUser: () => Promise<{ id: number | string; login: string }>;+ /**+ * Every repository the token can reach, across the owner's own account and+ * the organizations they belong to โ not the contribution-shaped listings+ * above, which rank by evidence of work and would hide a repository the+ * person has never touched but wants to build in.+ */+ listAccessibleRepositories: (input: { page: number; perPage: number }) => Promise<+ Array<{+ defaultBranch?: string | null;+ isPrivate?: boolean;+ name?: string | null;+ owner?: string | null;+ }>+ >;+ /** The branches of one repository, for choosing what an environment checks out. */+ listRepositoryBranches: (input: {+ owner: string;+ /** 1-based page of `perPage` branches. Omitted means the first. */+ page?: number;+ perPage: number;+ repository: string;+ }) => Promise<Array<{ name?: string | null }>>;listRepositoryContributors: (input: {owner: string;perPage: number;@@ -187,6 +209,30 @@ export const createOctokitTransport = (accessToken: string): GitHubConnectorTranlogin,}));},+ listRepositoryBranches: async ({ owner, page, perPage, repository }) => {+ const response = await octokit.rest.repos.listBranches({+ owner,+ page,+ per_page: perPage,+ repo: repository,+ });++ return response.data.map(({ name }) => ({ name }));+ },+ listAccessibleRepositories: async ({ page, perPage }) => {+ const response = await octokit.rest.repos.listForAuthenticatedUser({+ page,+ per_page: perPage,+ sort: 'updated',+ });++ return response.data.map(({ default_branch, name, owner, private: isPrivate }) => ({+ defaultBranch: default_branch,+ isPrivate,+ name,+ owner: owner?.login,+ }));+ },listUserOrganizations: async ({ perPage }) => {let response;try {diff --git a/packages/connector-data/src/github/types.ts b/packages/connector-data/src/github/types.tsindex 7e4bcf46967..6d4b8496287 100644--- a/packages/connector-data/src/github/types.ts+++ b/packages/connector-data/src/github/types.ts@@ -9,6 +9,20 @@ export interface GitHubUserProfile {websiteUrl?: string;}+/**+ * A repository as the environment picker needs it: enough to name it, show+ * whether it is private, and know which branch to check out by default.+ * Deliberately not {@link GitHubRepository}, which carries contribution+ * evidence this list has no use for.+ */+export interface GitHubOwnerRepository {+ defaultBranch?: string;+ isPrivate: boolean;+ name: string;+ /** The account the repository belongs to โ the `owner` half of `owner/name`. */+ owner: string;+}+export interface GitHubOrganization {description?: string;followerCount?: number;diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex ee3e215d54d..04cd5ccc34b 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -264,6 +264,12 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule// Member-to-member ownership handover: accepting/declining is an interactive// human decision, not something a restricted key should automate.resourceTransferRequest: 'blocked',+ // Reads and DELETES files in the caller's persistent sandbox working+ // directory. No existing scope honestly describes that store: granting it+ // under `file:*` would let a key given knowledge-base write access delete+ // working files too, which is not what that grant means. Blocked until the+ // feature ships with a scope of its own (full-access keys still reach it).+ sandboxStorage: 'blocked',search: rw('chat:read', null),// source-control integration wiring (installations, linked identities,// tracked pull requests) is configured from Settings, not from keysdiff --git a/packages/database/src/models/__tests__/environment.test.ts b/packages/database/src/models/__tests__/environment.test.tsindex 8b837260a11..337f548494c 100644--- a/packages/database/src/models/__tests__/environment.test.ts+++ b/packages/database/src/models/__tests__/environment.test.ts@@ -19,6 +19,30 @@ afterEach(async () => {});describe('EnvironmentModel', () => {+ it('seeds the regenerable paths a new environment cannot be useful without', async () => {+ // Without these the sandbox runtime puts node_modules in the snapshot layer,+ // where it counts against an allowance sized for source โ the exact thing+ // that makes a small plan unusable for the projects it is sold for.+ const env = await model.create({ name: 'Seeded' });+ expect(env.configuration.excludePaths).toEqual(['node_modules', '.venv', 'target']);+ });++ it('leaves an explicitly chosen list alone, including an empty one', async () => {+ // The field is the author's promise about what can be rebuilt. Once they+ // have decided, the platform must not put its own entries back.+ const chosen = await model.create({+ configuration: { excludePaths: ['dist'] },+ name: 'Chosen',+ });+ expect(chosen.configuration.excludePaths).toEqual(['dist']);++ const cleared = await model.create({+ configuration: { excludePaths: [] },+ name: 'Cleared',+ });+ expect(cleared.configuration.excludePaths).toEqual([]);+ });+it('creates, lists and updates environments in the owner scope', async () => {const env = await model.save({name: 'Shared GitHub',diff --git a/packages/database/src/models/__tests__/environment.visibility.test.ts b/packages/database/src/models/__tests__/environment.visibility.test.tsnew file mode 100644index 00000000000..9fd9200c422--- /dev/null+++ b/packages/database/src/models/__tests__/environment.visibility.test.ts@@ -0,0 +1,262 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { environmentInstances, environments, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { EnvironmentModel } from '../environment';+import { EnvironmentInstanceModel, InstanceDirectoryOverlapError } from '../environmentInstance';++const serverDB: LobeChatDatabase = await getTestDB();++const ownerId = 'environment-visibility-owner';+const memberId = 'environment-visibility-member';+const workspaceId = 'environment-visibility-workspace';++const owner = new EnvironmentModel(serverDB, ownerId, workspaceId);+const member = new EnvironmentModel(serverDB, memberId, workspaceId);+const ownerInstances = new EnvironmentInstanceModel(serverDB, ownerId, workspaceId);+const memberInstances = new EnvironmentInstanceModel(serverDB, memberId, workspaceId);++/** One instance of the given environment, bound to a sandbox rather than a device. */+const addInstance = async (environmentId: string, workingDirectory: string) => {+ const [row] = await serverDB+ .insert(environmentInstances)+ .values({+ configurationSnapshot: {},+ environmentId,+ kind: 'sandbox',+ name: workingDirectory,+ provider: 'test-provider',+ providerResourceId: workingDirectory,+ providerScope: 'test-scope',+ workingDirectory,+ })+ .returning();++ return row;+};++// Both foreign keys restrict, so the teardown has to unwind in the order the+// rows were built: instances, then environments, then the workspace and users.+const reset = async () => {+ await serverDB.delete(environmentInstances);+ await serverDB.delete(environments);+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await serverDB.delete(users).where(inArray(users.id, [ownerId, 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 }]);+});++afterEach(reset);++describe('environment creator', () => {+ it('keeps the creator of a row whose author has no avatar', async () => {+ // Regression: the creator was selected as a nested object across the join,+ // and drizzle nullifies such an object when its FIRST field is null. Sorted+ // alphabetically that field was `avatar`, so every author without one+ // vanished from the listing and their rows rendered as "Unknown".+ await serverDB+ .update(users)+ .set({ avatar: null, fullName: 'No Avatar Owner' })+ .where(eq(users.id, ownerId));+ await owner.create({ name: 'Analysis' });++ const [row] = await owner.query();+ expect(row.creator).toMatchObject({ avatar: null, fullName: 'No Avatar Owner', id: ownerId });+ });++ it('carries the avatar through when the author has one', async () => {+ await serverDB+ .update(users)+ .set({ avatar: 'https://example.com/a.png' })+ .where(eq(users.id, ownerId));+ await owner.create({ name: 'Analysis' });++ const [row] = await owner.query();+ expect(row.creator).toMatchObject({ avatar: 'https://example.com/a.png', id: ownerId });+ });+});++describe('environment visibility', () => {+ it('keeps a new environment private, so nothing is shared by being created', async () => {+ const created = await owner.create({ name: 'Analysis' });++ expect(created.visibility).toBe('private');+ await expect(member.query()).resolves.toEqual([]);+ });++ it('shows a published environment to another member, and hides it again', async () => {+ const created = await owner.create({ name: 'Analysis' });++ await owner.setVisibility(created.id, 'public');+ const visible = await member.query();+ expect(visible.map((row) => row.id)).toEqual([created.id]);++ await owner.setVisibility(created.id, 'private');+ await expect(member.query()).resolves.toEqual([]);+ });++ it('narrows the listing to one pool, where private still means your own', async () => {+ const mine = await owner.create({ name: 'Mine' });+ const theirs = await member.create({ name: 'Theirs' });+ await member.setVisibility(theirs.id, 'public');++ const published = await owner.query('public');+ expect(published.map((row) => row.id)).toEqual([theirs.id]);++ const privatePool = await owner.query('private');+ expect(privatePool.map((row) => row.id)).toEqual([mine.id]);+ });++ it('refuses every write on an environment the caller does not own', async () => {+ const created = await owner.create({ name: 'Analysis' });+ await owner.setVisibility(created.id, 'public');++ // Readable โ that is what publishing means.+ await expect(member.findById(created.id)).resolves.toMatchObject({ id: created.id });++ // And nothing more than readable.+ await expect(member.findOwnedById(created.id)).resolves.toBeUndefined();+ await expect(member.update(created.id, { name: 'Renamed' })).resolves.toBeUndefined();+ await expect(member.setVisibility(created.id, 'private')).resolves.toBeUndefined();+ await expect(member.delete(created.id)).resolves.toBeUndefined();++ const [row] = await serverDB.select().from(environments).where(eq(environments.id, created.id));+ expect(row).toMatchObject({ name: 'Analysis', visibility: 'public' });+ });++ it('lets a member read the instances of a published environment but not destroy them', async () => {+ const created = await owner.create({ name: 'Analysis' });+ const instance = await addInstance(created.id, 'work');++ // Private: the instance is not even visible.+ await expect(memberInstances.findById(instance.id)).resolves.toBeUndefined();++ await owner.setVisibility(created.id, 'public');++ // Published: readable, because running in it is the point.+ await expect(memberInstances.findById(instance.id)).resolves.toMatchObject({ id: instance.id });+ await expect(memberInstances.query()).resolves.toHaveLength(1);++ // The destructive paths resolve through the owner-scoped lookup instead, so+ // a member cannot reach the execution plane's delete with a row it may not+ // remove โ which would leave captured state nobody can name.+ await expect(memberInstances.findOwnedById(instance.id)).resolves.toBeUndefined();+ await expect(memberInstances.delete(instance.id)).resolves.toBeUndefined();+ await expect(ownerInstances.findOwnedById(instance.id)).resolves.toMatchObject({+ id: instance.id,+ });+ });++ // A workspace-public agent runs on its caller's session. Even the creator's+ // own private instance is out of its reach, since what a session left in it+ // can include the creator's credentials; a published one stays usable.+ it('keeps even your own private instances out of reach of a public agent', async () => {+ const privateEnv = await owner.create({ name: 'Private' });+ const privateInstance = await addInstance(privateEnv.id, 'secret');+ const publishedEnv = await owner.create({ name: 'Published', visibility: 'public' });+ const publishedInstance = await addInstance(publishedEnv.id, 'shared');++ const asPublicAgent = new EnvironmentInstanceModel(serverDB, ownerId, workspaceId, 'public');+ const asPrivateAgent = new EnvironmentInstanceModel(serverDB, ownerId, workspaceId, 'private');++ await expect(asPublicAgent.findById(privateInstance.id)).resolves.toBeUndefined();+ await expect(asPublicAgent.findById(publishedInstance.id)).resolves.toMatchObject({+ id: publishedInstance.id,+ });+ await expect(asPublicAgent.query()).resolves.toHaveLength(1);++ await expect(asPrivateAgent.findById(privateInstance.id)).resolves.toMatchObject({+ id: privateInstance.id,+ });+ });++ // Personal agents carry 'public' by default without it meaning anything, and+ // every personal environment is private โ narrowing there would hide them all.+ it('leaves personal environments reachable whatever the agent says', async () => {+ const personal = new EnvironmentModel(serverDB, ownerId);+ const created = await personal.create({ name: 'Personal' });+ const instance = await addInstance(created.id, 'personal');++ const asPublicAgent = new EnvironmentInstanceModel(serverDB, ownerId, undefined, 'public');+ await expect(asPublicAgent.findById(instance.id)).resolves.toMatchObject({ id: instance.id });+ });++ // 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.+ it('refuses a directory nested with any other instance on the same storage', async () => {+ const binding = {+ kind: 'sandbox' as const,+ provider: 'test-provider',+ providerResourceId: 'workspace',+ providerScope: 'test-scope',+ };+ const privateEnv = await owner.create({ name: 'Private' });+ await ownerInstances.create({+ ...binding,+ environmentId: privateEnv.id,+ name: 'Parent',+ workingDirectory: 'projects/atlas',+ });++ const memberEnv = await member.create({ name: 'Mine' });+ for (const workingDirectory of ['projects/atlas/web', 'projects']) {+ await expect(+ memberInstances.create({+ ...binding,+ environmentId: memberEnv.id,+ name: workingDirectory,+ workingDirectory,+ }),+ ).rejects.toBeInstanceOf(InstanceDirectoryOverlapError);+ }++ // A sibling, and a name that merely shares a prefix, are separate trees.+ for (const workingDirectory of ['projects/web', 'projects/atlas-2']) {+ await expect(+ memberInstances.create({+ ...binding,+ environmentId: memberEnv.id,+ name: workingDirectory,+ workingDirectory,+ }),+ ).resolves.toMatchObject({ workingDirectory });+ }+ });++ it('refuses to publish a personal environment, which has nobody to publish to', async () => {+ const personal = new EnvironmentModel(serverDB, ownerId);+ const created = await personal.create({ name: 'Personal', visibility: 'public' });++ expect(created.visibility).toBe('private');+ await expect(personal.setVisibility(created.id, 'public')).resolves.toBeUndefined();+ });++ it('answers the published pool with nothing when there is no workspace to publish to', async () => {+ const personal = new EnvironmentModel(serverDB, ownerId);+ await personal.create({ name: 'Personal' });++ // Not "every row", which is what an ignored filter would have returned โ+ // and what would make two tabs look like the same list.+ await expect(personal.query('public')).resolves.toEqual([]);+ await expect(personal.query('private')).resolves.toHaveLength(1);+ });++ it('keeps a workspace listing clear of your own personal environments', async () => {+ const personal = new EnvironmentModel(serverDB, ownerId);+ await personal.create({ name: 'Personal' });+ const inWorkspace = await owner.create({ name: 'In workspace' });++ const rows = await owner.query();+ expect(rows.map((row) => row.id)).toEqual([inWorkspace.id]);+ });+});diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.tsindex 0a2305f472c..11045a7a7ae 100644--- a/packages/database/src/models/environment.ts+++ b/packages/database/src/models/environment.ts@@ -1,9 +1,31 @@-import type { EnvironmentConfiguration } from '@lobechat/types';-import { and, eq } from 'drizzle-orm';+import type { EnvironmentConfiguration, EnvironmentVisibility } from '@lobechat/types';+import { DEFAULT_REGENERABLE_PATHS } from '@lobechat/types';+import { and, asc, eq, isNull, sql } from 'drizzle-orm';-import { environmentInstances, environments } from '../schemas';+import type { EnvironmentItem, NewEnvironment } from '../schemas';+import { environments, users } from '../schemas';import type { LobeChatDatabase } from '../type';-import { buildWorkspaceWhere } from '../utils/workspace';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++export interface EnvironmentCreator {+ avatar: string | null;+ fullName: string | null;+ id: string | null;+ username: string | null;+}++export type EnvironmentWithCreator = Pick<+ EnvironmentItem,+ | 'configuration'+ | 'createdAt'+ | 'description'+ | 'id'+ | 'name'+ | 'updatedAt'+ | 'userId'+ | 'visibility'+ | 'workspaceId'+> & { creator: EnvironmentCreator | null };/** Canonical GitHub source only; credentials and arbitrary clone transports are never persisted. */export const normalizeProjectRepository = (value: string): string => {@@ -30,6 +52,64 @@ export const normalizeProjectRepository = (value: string): string => {* upserts environment + instance + project link in one transaction) live in* `repositories/projectDirectory` and compose this model with a tx handle.*/+/**+ * Rows this member OWNS โ the filter every write goes through. A public+ * environment is usable by the workspace but editable only by the member who+ * made it, the same split the device rows draw.+ */+export const environmentOwnership = (userId: string, workspaceId?: string) =>+ and(+ eq(environments.userId, userId),+ workspaceId ? eq(environments.workspaceId, workspaceId) : isNull(environments.workspaceId),+ );++/**+ * Rows this member may SEE: their own, plus whatever the workspace publishes.+ *+ * Exported because instances have no owner column and inherit their scope from+ * the environment, so every instance read has to reach visibility through here.+ * That inheritance is the whole reason publishing is a deliberate act: an+ * instance carries what a session left in it, so a published environment hands+ * over its captured state too โ a bargain identical to sharing a device, and+ * one the confirmation dialog spells out before anyone makes it.+ *+ * `callerAgentVisibility: 'public'` narrows it to the published rows alone: 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 must not reach it. Personal mode is unaffected โ there every row is the+ * owner's own.+ */+export const environmentVisibility = (+ userId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+) => buildWorkspaceWhere({ callerAgentVisibility, userId, workspaceId }, environments);++/**+ * The declarative half of an environment: what it should contain, not what it+ * currently does. `configuration` is the specification โ the sources to check+ * out, what to run to make them usable, what the work needs to run on โ and+ * every materialization of it (a sandbox snapshot, a folder on a device) is a+ * cache that can be rebuilt from this row and thrown away.+ *+ * Writes are scoped to the MEMBER, including inside a workspace where `user_id`+ * merely records the creator. Reads follow `visibility`, which defaults to+ * private and starts there for every row that predates the column โ so nothing+ * became visible to anyone by the act of adding it.+ *+ * Publishing one is a real decision, by one step of reasoning worth spelling+ * out: an instance has no owner column and inherits its scope from here, and an+ * instance's captured state carries whatever a session left in a home directory+ * โ including the token a CLI logged in with. So a published environment is an+ * identity a colleague can borrow, and the borrower would see nothing unusual,+ * only a CLI that happens to be signed in. That is the same bargain a shared+ * device makes, which is why it is offered the same way: private by default,+ * published only through a dialog that names the consequence.+ *+ * `project_environments` remains the path for referencing a specification+ * WITHOUT handing over anything built from it. Taking it needs instances to+ * carry an owner of their own first.+ */export class EnvironmentModel {constructor(private readonly db: LobeChatDatabase,@@ -119,7 +199,12 @@ export class EnvironmentModel {* binding that meant to create its own. The indexes let both exist precisely* because the name belongs to the member, not to the workspace.*/- async findEnabledByName(name: string) {+ /**+ * Looks a name up over the exact scope the (user, scope, name) unique indexes+ * cover โ disabled rows included. Filtering them out here would report a free+ * name that the index still refuses to let anyone insert.+ */+ async findByName(name: string) {const [row] = await this.db.select().from(environments)@@ -128,37 +213,201 @@ export class EnvironmentModel {eq(environments.name, name.trim()),eq(environments.userId, this.userId),buildWorkspaceWhere(this.scope(), environments),- eq(environments.enabled, true),),);return row;}- /** Device instances are unique per (device, workingDirectory) โ see the schema constraint. */- async findDeviceInstance(deviceId: string, workingDirectory: string) {+ private ownership = () => environmentOwnership(this.userId, this.workspaceId);++ private visible = () => environmentVisibility(this.userId, this.workspaceId);++ /**+ * Narrows a listing to one pool.+ *+ * Personal rows have no pool to be in โ they are all private to their owner,+ * and there is no workspace for anything to be published to. So asking for+ * the published pool outside a workspace is answered with nothing rather than+ * ignored: a filter that silently does not apply makes two tabs show the same+ * list, which reads as "these are the same rows" when it means "the question+ * did not reach anything".+ */+ private pool = (visibility?: EnvironmentVisibility) => {+ if (!visibility) return undefined;+ if (this.workspaceId) return eq(environments.visibility, visibility);++ return visibility === 'private' ? undefined : sql`false`;+ };++ /**+ * Environments with the member who made them.+ *+ * `user_id` is the creator, and in a workspace two colleagues each keep their+ * own โ so a list that shows only names cannot say whose is whose. The join+ * is left because a removed account must not take its environments out of+ * the listing with it.+ *+ * `visibility` narrows to one pool, which is how the workspace page's two+ * tabs are served. Narrowing to `private` still means "mine": the visibility+ * filter already excludes everyone else's private rows, so the tab shows the+ * caller's own unpublished environments rather than every unpublished one.+ */+ query = async (visibility?: EnvironmentVisibility): Promise<EnvironmentWithCreator[]> => {+ // Flat columns, assembled below โ NOT a nested `creator: { โฆ }` selection.+ // Drizzle decides whether a joined object is null from the FIRST field it+ // sees: a null there marks the whole object absent, and a later non-null+ // field from the same table does not undo it (`mapResultRow`). Sorted+ // alphabetically, the first field was `avatar` โ so every creator without+ // one came back as no creator at all, and their rows rendered as "Unknown".+ const rows = await this.db+ .select({+ configuration: environments.configuration,+ createdAt: environments.createdAt,+ creatorAvatar: users.avatar,+ creatorFullName: users.fullName,+ creatorId: users.id,+ creatorUsername: users.username,+ description: environments.description,+ id: environments.id,+ name: environments.name,+ updatedAt: environments.updatedAt,+ userId: environments.userId,+ visibility: environments.visibility,+ workspaceId: environments.workspaceId,+ })+ .from(environments)+ .leftJoin(users, eq(environments.userId, users.id))+ .where(and(this.visible(), this.pool(visibility)))+ .orderBy(asc(environments.createdAt));++ return rows.map(({ creatorAvatar, creatorFullName, creatorId, creatorUsername, ...row }) => ({+ ...row,+ // The id is what says a creator was found; a deleted account leaves the+ // join empty and the row keeps its place in the listing with no creator.+ creator: creatorId+ ? {+ avatar: creatorAvatar,+ fullName: creatorFullName,+ id: creatorId,+ username: creatorUsername,+ }+ : null,+ }));+ };++ /** Readable, not necessarily writable โ a published environment resolves here for every member. */+ findById = async (id: string): Promise<EnvironmentItem | undefined> => {const [row] = await this.db.select()- .from(environmentInstances)- .where(- and(- eq(environmentInstances.deviceId, deviceId),- eq(environmentInstances.workingDirectory, workingDirectory),- ),- );+ .from(environments)+ .where(and(eq(environments.id, id), this.visible()))+ .limit(1);+return row;- }+ };++ /**+ * The caller's own row, or nothing. Every write goes through this, so a+ * member who can see a published environment still cannot rename, respecify+ * or delete it โ the request fails closed as NOT_FOUND, exactly like an id+ * that does not exist.+ */+ findOwnedById = async (id: string): Promise<EnvironmentItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(environments)+ .where(and(eq(environments.id, id), this.ownership()))+ .limit(1);- async createDeviceInstance(input: {- configurationSnapshot: EnvironmentConfiguration;- deviceId: string;- environmentId: string;+ return row;+ };++ create = async (params: {+ configuration?: EnvironmentConfiguration;+ description?: string | null;name: string;- workingDirectory: string;- }) {+ visibility?: EnvironmentVisibility;+ }): Promise<EnvironmentItem> => {const [row] = await this.db- .insert(environmentInstances)- .values({ ...input, kind: 'device' })+ .insert(environments)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ // An environment with nothing declared yet is a normal state: it is+ // named first and specified once the person knows what they want in+ // it. The column stays NOT NULL so a reader never has to tell+ // "declared nothing" apart from "declared, but the row predates the+ // column".+ // Seeded only here, never on update: the list is the author's+ // promise about what can be rebuilt, so once they have edited it โ+ // including down to nothing โ the platform must not put its own+ // entries back. `?? ` and not a merge, for the same reason: an+ // explicit empty list is a decision.+ configuration: {+ ...params.configuration,+ excludePaths: params.configuration?.excludePaths ?? [...DEFAULT_REGENERABLE_PATHS],+ },+ description: params.description ?? null,+ name: params.name,+ // Private unless the caller says otherwise, and a personal+ // environment has no other state to be in.+ visibility: this.workspaceId ? (params.visibility ?? 'private') : 'private',+ },+ ),+ ).returning();+return row;- }+ };++ update = async (+ id: string,+ params: Partial<Pick<NewEnvironment, 'configuration' | 'description' | 'enabled' | 'name'>>,+ ): Promise<EnvironmentItem | undefined> => {+ const [row] = await this.db+ .update(environments)+ .set({ ...params, updatedAt: new Date() })+ .where(and(eq(environments.id, id), this.ownership()))+ .returning();++ return row;+ };++ /**+ * Publishing to the workspace, or taking it back.+ *+ * Owner-only and workspace-only: a personal environment has nobody to be+ * visible to, and a member who merely uses a published one must not be able+ * to unpublish it out from under everyone.+ */+ setVisibility = async (+ id: string,+ visibility: EnvironmentVisibility,+ ): Promise<EnvironmentItem | undefined> => {+ if (!this.workspaceId) return undefined;++ const [row] = await this.db+ .update(environments)+ .set({ updatedAt: new Date(), visibility })+ .where(and(eq(environments.id, id), this.ownership()))+ .returning();++ return row;+ };++ /**+ * Removes only the specification. Anything materialized from it belongs to+ * the execution plane, and the caller deletes it there first โ dropping this+ * row while a snapshot lives on would leave storage nobody can name, and+ * therefore nobody can reclaim.+ */+ delete = async (id: string): Promise<EnvironmentItem | undefined> => {+ const [row] = await this.db+ .delete(environments)+ .where(and(eq(environments.id, id), this.ownership()))+ .returning();++ return row;+ };}diff --git a/packages/database/src/models/environmentInstance.ts b/packages/database/src/models/environmentInstance.tsnew file mode 100644index 00000000000..98ad6374083--- /dev/null+++ b/packages/database/src/models/environmentInstance.ts@@ -0,0 +1,371 @@+import type { EnvironmentConfiguration, EnvironmentInstanceConfiguration } from '@lobechat/types';+import { and, asc, eq, getTableColumns, inArray, isNull, or, sql } from 'drizzle-orm';++import type { EnvironmentInstanceItem, NewEnvironmentInstance } from '../schemas';+import { environmentInstances, environments } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { environmentOwnership, environmentVisibility } from './environment';++/** The binding that says which machine, account or volume an instance lives in. */+export type EnvironmentInstanceBinding = Pick<+ NewEnvironmentInstance,+ 'kind' | 'deviceId' | 'provider' | 'providerScope' | 'providerResourceId'+>;++export interface CreateEnvironmentInstanceParams extends EnvironmentInstanceBinding {+ configuration?: EnvironmentInstanceConfiguration;+ /**+ * The definition this instance was actually built from. Defaults to the+ * environment's current one, which is right for a new instance; a copy+ * passes the source's, because its files are the source's and the+ * environment may have moved on since.+ */+ configurationSnapshot?: EnvironmentConfiguration;+ environmentId: string;+ name: string;+ workingDirectory: string;+}++/**+ * A materialization of an environment: one instance, in one place, with one+ * directory. Two of them off the same specification is the supported way to run+ * two conversations side by side โ each keeps its own files and its own+ * captured state, where a shared directory would have them overwrite each+ * other's work.+ *+ * `configurationSnapshot` is the specification as it stood when this instance+ * was built, deliberately not refreshed on its own. It is what makes the built+ * state a cache rather than the only record: when it no longer matches the+ * environment's `configuration`, this instance is out of date and can be+ * rebuilt from the specification instead of being repaired by hand.+ *+ * Ownership is inherited, not stored โ there is no owner column here, so every+ * statement reaches through the environment. That is load-bearing rather than+ * incidental: an instance's captured state includes a home directory, and a+ * home directory holds credentials.+ *+ * Which is why the two directions differ. READS follow the environment's+ * visibility, so a member can run in an environment a colleague published โ+ * that is what publishing one means. WRITES stay with the creator: using a+ * shared environment must not let anyone reshape it, add copies to it, or+ * delete the copies other people are working in.+ */+/**+ * A new instance's directory would sit inside another instance's, or contain+ * one. Two instances on overlapping trees restore their captured state over+ * each other's files, which is the mixing separate instances exist to prevent โ+ * the unique index only catches the identical path.+ */+export class InstanceDirectoryOverlapError extends Error {+ constructor(readonly workingDirectory: string) {+ super('OVERLAPPING_INSTANCE_DIRECTORY');+ this.name = 'InstanceDirectoryOverlapError';+ }+}++export class EnvironmentInstanceModel {+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;+ /** See {@link environmentVisibility}: a public agent reads published environments only. */+ private callerAgentVisibility?: 'private' | 'public' | null;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+ ) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.callerAgentVisibility = callerAgentVisibility;+ }++ /** Environments this member owns, as a subquery the write statements filter through. */+ private ownedEnvironments = () =>+ this.db+ .select({ id: environments.id })+ .from(environments)+ .where(environmentOwnership(this.userId, this.workspaceId));++ /** Environments this member may see โ their own, plus the workspace's published ones. */+ private visibleEnvironments = () =>+ this.db+ .select({ id: environments.id })+ .from(environments)+ .where(environmentVisibility(this.userId, this.workspaceId, this.callerAgentVisibility));++ private ownership = () => inArray(environmentInstances.environmentId, this.ownedEnvironments());++ private visible = () => inArray(environmentInstances.environmentId, this.visibleEnvironments());++ /**+ * Every instance the caller can see. Each carries the specification as it+ * stood when it was created (`configurationSnapshot`); editing the+ * environment afterwards changes what NEW instances are built from and+ * leaves existing ones exactly as they are.+ */+ query = async (params: { environmentId?: string } = {}): Promise<EnvironmentInstanceItem[]> =>+ this.db+ .select(getTableColumns(environmentInstances))+ .from(environmentInstances)+ .innerJoin(environments, eq(environments.id, environmentInstances.environmentId))+ .where(+ and(+ environmentVisibility(this.userId, this.workspaceId, this.callerAgentVisibility),+ params.environmentId+ ? eq(environmentInstances.environmentId, params.environmentId)+ : undefined,+ ),+ )+ .orderBy(asc(environmentInstances.createdAt));++ /** Readable: this is what a run resolves through, including in a published environment. */+ findById = async (id: string): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(environmentInstances)+ .where(and(eq(environmentInstances.id, id), this.visible()))+ .limit(1);++ return row;+ };++ /**+ * The same row, but only when the caller owns the environment behind it.+ *+ * Every destructive path looks the instance up through this rather than+ * {@link findById}, because those paths act on the execution plane BEFORE+ * they touch the row: a member of a published environment who could pass the+ * read check would delete the snapshot and only then be refused the row,+ * leaving captured state nobody can name.+ */+ findOwnedById = async (id: string): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(environmentInstances)+ .where(and(eq(environmentInstances.id, id), this.ownership()))+ .limit(1);++ return row;+ };++ /**+ * The instance that already occupies this directory, if any. One instance+ * per directory is a database constraint, so this is how a caller that only+ * knows where it wants to work finds out whether that is a new copy or an+ * existing one.+ */+ findByWorkingDirectory = async (+ workingDirectory: string,+ ): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(environmentInstances)+ .where(and(eq(environmentInstances.workingDirectory, workingDirectory), this.visible()))+ .limit(1);++ return row;+ };++ /**+ * One device's instance at a path, by the pair the schema makes unique.+ *+ * Unlike {@link findByWorkingDirectory} this does not filter by what the+ * caller can see: it answers inside `ProjectDirectoryRepository.bind`, which+ * has already resolved the device through the caller's own scope, and a+ * second filter there would only hide a row whose directory is about to be+ * bound anyway โ turning "already bound" into a duplicate insert.+ */+ findByDeviceAndDirectory = async (+ deviceId: string,+ workingDirectory: string,+ ): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .select()+ .from(environmentInstances)+ .where(+ and(+ eq(environmentInstances.deviceId, deviceId),+ eq(environmentInstances.workingDirectory, workingDirectory),+ ),+ );+ return row;+ };++ /**+ * The insert `bind` makes, once it has decided there is one to make.+ *+ * Deliberately thinner than {@link create}: ownership of the environment and+ * of the device are both settled by the caller, inside the transaction that+ * locked the device row, so repeating those reads here would re-ask a+ * question already answered under a weaker lock.+ */+ createForDeviceBinding = async (input: {+ configurationSnapshot: EnvironmentConfiguration;+ deviceId: string;+ environmentId: string;+ name: string;+ workingDirectory: string;+ }): Promise<EnvironmentInstanceItem> => {+ const [row] = await this.db+ .insert(environmentInstances)+ .values({ ...input, kind: 'device' })+ .returning();+ return row;+ };++ /**+ * Returns `undefined` when the environment is not this member's, which is the+ * same answer as "no such environment" on purpose: the caller has no business+ * learning that an id it cannot use exists.+ */+ create = async (+ params: CreateEnvironmentInstanceParams,+ ): Promise<EnvironmentInstanceItem | undefined> => {+ const {+ configuration,+ configurationSnapshot,+ environmentId,+ name,+ workingDirectory,+ ...binding+ } = params;++ const [environment] = await this.db+ .select()+ .from(environments)+ .where(+ and(+ eq(environments.id, environmentId),+ environmentOwnership(this.userId, this.workspaceId),+ ),+ )+ .limit(1);++ if (!environment) return undefined;++ const bindingScope = binding.deviceId+ ? eq(environmentInstances.deviceId, binding.deviceId)+ : and(+ isNull(environmentInstances.deviceId),+ eq(environmentInstances.provider, binding.provider ?? ''),+ eq(environmentInstances.providerScope, binding.providerScope ?? ''),+ eq(environmentInstances.providerResourceId, binding.providerResourceId ?? ''),+ );++ // The unique index covers exact duplicates only, so `foo` and `foo/bar`+ // are rejected by the query below rather than by a constraint โ which+ // makes this a read before a write, and two concurrent creations would+ // otherwise both pass it and end up sharing a worktree. Serialize the+ // pair on the storage they are competing for.+ const lockKey = `environment_instance_dir:${binding.kind}:${+ binding.deviceId ??+ `${binding.provider ?? ''}/${binding.providerScope ?? ''}/${binding.providerResourceId ?? ''}`+ }`;++ return this.db.transaction(async (tx) => {+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${lockKey}))`);++ // Across every instance on the same storage, not only the ones this+ // member can see: a colleague's private instance occupies its directory+ // just the same. Only whether one overlaps is read, never which.+ const [overlapping] = await tx+ .select({ id: environmentInstances.id })+ .from(environmentInstances)+ .where(+ and(+ eq(environmentInstances.kind, binding.kind),+ bindingScope,+ or(+ sql`starts_with(${environmentInstances.workingDirectory}, ${`${workingDirectory}/`})`,+ sql`starts_with(${workingDirectory}, ${environmentInstances.workingDirectory} || '/')`,+ ),+ ),+ )+ .limit(1);++ if (overlapping) throw new InstanceDirectoryOverlapError(workingDirectory);++ const [row] = await tx+ .insert(environmentInstances)+ .values({+ ...binding,+ configuration,+ // Taken here rather than read through the environment at use time:+ // this is the definition this instance was actually built from, and+ // keeping it is what lets a later comparison say "the specification+ // moved".+ configurationSnapshot: configurationSnapshot ?? environment.configuration,+ environmentId,+ name,+ workingDirectory,+ })+ .returning();++ return row;+ });+ };++ /**+ * Writes the verdict the execution plane returned for one build.+ *+ * Scoped by {@link visible} rather than ownership on purpose: a member+ * watching a published environment build can be the one whose poll receives+ * the terminal status, and an ownership-scoped write would silently drop it+ * and leave the owner's row `pending` against a build the runtime has since+ * discarded. The verdict is the runtime's, not the caller's, so recording it+ * is not a user edit โ and `buildId` must still match, so a late reply from+ * a superseded build cannot overwrite a newer one.+ */+ recordBuildResult = async (+ id: string,+ buildId: string,+ params: Pick<NewEnvironmentInstance, 'buildError' | 'status'>,+ ): Promise<void> => {+ await this.db+ .update(environmentInstances)+ .set({ ...params, buildId: null, updatedAt: new Date() })+ .where(+ and(+ eq(environmentInstances.id, id),+ eq(environmentInstances.buildId, buildId),+ this.visible(),+ ),+ );+ };++ update = async (+ id: string,+ params: Partial<+ Pick<+ NewEnvironmentInstance,+ 'buildError' | 'buildId' | 'configuration' | 'enabled' | 'name' | 'status'+ >+ >,+ ): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .update(environmentInstances)+ .set({ ...params, updatedAt: new Date() })+ .where(and(eq(environmentInstances.id, id), this.ownership()))+ .returning();++ return row;+ };++ /**+ * Removes only the row. Whatever the execution plane built belongs to it, and+ * the caller deletes it there first โ dropping this row while the built state+ * lives on would leave storage nobody can name, and therefore nobody can+ * reclaim.+ */+ delete = async (id: string): Promise<EnvironmentInstanceItem | undefined> => {+ const [row] = await this.db+ .delete(environmentInstances)+ .where(and(eq(environmentInstances.id, id), this.ownership()))+ .returning();++ return row;+ };+}diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.tsindex 9be196aa303..1b61127e606 100644--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts@@ -168,6 +168,13 @@ describe('ProjectDirectoryRepository.bind', () => {expect(after.configurationSnapshot).toEqual(before.configurationSnapshot);});+ it('reports a disabled environment of the same name instead of hitting its unique index', async () => {+ const env = await new EnvironmentModel(db, userId).save({ name: base.name });+ await db.update(environments).set({ enabled: false }).where(eq(environments.id, env.id));+ await expect(repo.bind(base)).rejects.toThrow('Environment is disabled');+ expect(await db.select().from(environments)).toHaveLength(1);+ });+it('rejects filing conversations for an agent fixed to another execution target', async () => {await db.update(agents)diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.tsindex 3a4af781880..7c205c6a763 100644--- a/packages/database/src/repositories/projectDirectory/index.ts+++ b/packages/database/src/repositories/projectDirectory/index.ts@@ -2,6 +2,7 @@ import { getWorkingDirSourcePath } from '@lobechat/types';import { and, eq, inArray, isNull } from 'drizzle-orm';import { EnvironmentModel, normalizeProjectRepository } from '../../models/environment';+import { EnvironmentInstanceModel } from '../../models/environmentInstance';import { ProjectModel } from '../../models/project';import {normalizeProjectDirectory,@@ -55,6 +56,7 @@ export class ProjectDirectoryRepository {return this.db.transaction(async (tx) => {const db = tx as LobeChatDatabase;const environmentModel = new EnvironmentModel(db, this.userId, this.workspaceId);+ const instanceModel = new EnvironmentInstanceModel(db, this.userId, this.workspaceId);const projectModel = new ProjectModel(db, this.userId, this.workspaceId);const directoryModel = new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId);// Serialize bindings of the same device, including bindings from different projects.@@ -70,7 +72,7 @@ export class ProjectDirectoryRepository {const repositoryUrl = input.repositoryUrl? normalizeProjectRepository(input.repositoryUrl): undefined;- const existing = await environmentModel.findDeviceInstance(device.id, path);+ const existing = await instanceModel.findByDeviceAndDirectory(device.id, path);let instance = existing;let environment;// An environment is the definition; an instance is one materialization of@@ -79,12 +81,15 @@ export class ProjectDirectoryRepository {// second environment under the same name โ which is both what the// (user, scope, name) unique indexes require and what the two concepts// already meant.- const environmentId =- existing?.environmentId ??- input.environmentId ??- (await environmentModel.findEnabledByName(input.name))?.id;+ const knownId = existing?.environmentId ?? input.environmentId;+ const named = knownId ? undefined : await environmentModel.findByName(input.name);+ const environmentId = knownId ?? named?.id;if (environmentId) {environment = await environmentModel.findEnabledById(environmentId);+ // The name lookup deliberately sees disabled rows, because the unique+ // indexes do: a disabled environment of this name still owns the name,+ // so minting a replacement would only hit the constraint.+ if (!environment && named) throw new Error('Environment is disabled');if (!environment || (input.environmentId && input.environmentId !== environment.id))throw new Error('This directory belongs to another environment');if (@@ -101,7 +106,7 @@ export class ProjectDirectoryRepository {});}if (!instance) {- instance = await environmentModel.createDeviceInstance({+ instance = await instanceModel.createForDeviceBinding({configurationSnapshot: environment.configuration,deviceId: device.id,environmentId: environment.id,diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 193f6afce75..98ebd9898f7 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -358,7 +358,13 @@ export interface ProjectFileIndexResult {entries: ProjectFileIndexEntry[];indexedAt: string;root: string;- source: 'git' | 'glob';+ source: 'git' | 'glob' | 'sandbox';+ /**+ * The host stopped short of the whole tree. Set only by hosts that cap a+ * listing; a tree that is missing entries and does not say so is worse than+ * one that refuses, because it reads as complete.+ */+ truncated?: boolean;}export interface ProjectDirectoryListParams {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 8264d43bd9f..1aea946b873 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -721,7 +721,7 @@ export default {'Could not reconnect this device. Make sure the desktop app is running, then try again.','heteroAgent.executionTarget.personalGroup': 'Private Devices','heteroAgent.executionTarget.sandbox': 'Cloud Sandbox',- 'heteroAgent.executionTarget.sandboxDesc': 'Run in an ephemeral cloud sandbox',+ 'heteroAgent.executionTarget.sandboxDesc': 'Runs in the cloud, no machine needed','heteroAgent.executionTarget.workspaceGroup': 'Workspace Devices','heteroAgent.executionTarget.downloadDesktop': 'Get Desktop App','heteroAgent.executionTarget.downloadDesktopDesc': 'Run agents with access to your computer',@@ -1353,6 +1353,52 @@ export default {'gatewayMode.cardTitle': 'Agent Gateway Mode','gatewayMode.desc':"Run agents in the cloud through LobeHub's Agent Gateway. Tasks keep running even after you close the page.",+ 'sandboxStorage.ephemeral': 'Temporary working directory',+ 'sandboxStorage.ephemeralDesc': 'Cleaned up when the sandbox is recycled',+ 'sandboxStorage.persistentUpsell': 'Persistent working directory',+ 'sandboxStorage.persistentUpsellDesc': 'Keep files across runs and topics',+ 'sandboxStorage.setUpEnvironmentDesc': 'A persistent directory lives in an environment',+ 'sandboxStorage.setUpEnvironment': 'Set up an environment',+ // The other empty state: environments exist, none has been materialized+ // into a working copy yet. Naming the environment page rather than opening+ // a dialog here โ this menu picks between instances, it does not make them.+ 'sandboxStorage.noInstances': 'Create an instance',+ 'sandboxStorage.noInstancesDesc': 'Your environments have no working copy yet',+ 'sandboxStorage.manage': 'Manage',+ // The menu names the thing it picks โ an instance of an environment โ+ // rather than the slot it fills. The explainer carries the distinction,+ // because "environment" and "instance of one" is the whole model.+ 'sandboxStorage.pickerTitle': 'Environment Instance',+ 'sandboxStorage.pickerInfoTooltip':+ 'An environment describes what a run needs around it โ repositories, setup, variables. An instance is one working copy of it, with its own folder and its own installed packages; conversations run inside an instance and keep what they leave there.',+ 'sandboxStorage.environmentsUnavailable': 'Environments could not be loaded',+ // One conversation at a time per instance: the execution plane takes a+ // lease and answers the second writer with 409 INSTANCE_IN_USE, because+ // two runs snapshotting one folder means whichever ends last silently+ // discards the other's work. The tag says which rows that applies to before+ // the first message meets the refusal.+ 'sandboxStorage.running': 'Running',+ // A build holds the same single-writer lease a run does, so it is refused+ // for the same reason โ but it is not a conversation, and saying "running"+ // would send someone looking for one.+ 'sandboxStorage.building': 'Building',+ 'sandboxStorage.buildFailed': 'Not built',+ 'sandboxStorage.instanceBusy':+ '{{name}} is running in another conversation. This one keeps it, and picks it up when that run ends.',+ // Pool captions inside a workspace, in the execution-target menu's words:+ // which pool an environment is in decides who else can reach what a run+ // leaves behind. A personal account has one pool and needs neither.+ 'sandboxStorage.privateGroup': 'Private Environments',+ 'sandboxStorage.workspaceGroup': 'Workspace Environments',+ // Says where the hidden ones went. Dropped from the list rather than+ // dimmed, the way the execution-target menu drops a workspace agent's+ // personal devices, so this is the only place they are accounted for.+ 'sandboxStorage.publicAgentHint_one':+ '{{count}} private environment is hidden โ a public agent can only use workspace environments. Publish it to use it here.',+ 'sandboxStorage.publicAgentHint_other':+ '{{count}} private environments are hidden โ a public agent can only use workspace environments. Publish one to use it here.',+ 'sandboxStorage.privateInstanceBlocked':+ 'โ{{name}}โ is in a private environment, which a public agent cannot use. This topic runs in a temporary working directory instead.','search.grounding.imageSearchQueries': 'Image Search Keywords','search.grounding.imageTitle': 'Found {{count}} images','chatMode.agent': 'Agent',@@ -3198,6 +3244,8 @@ export default {'workingPanel.skills.section.project': 'Project skills','workingPanel.skills.section.user': 'User skills','workingPanel.skills.title': 'Skills',+ 'workingPanel.files.openNeedsTopic':+ 'Send a message first โ this environmentโs files open once the conversation has a session.','workingPanel.files.copyAbsolutePath': 'Copy Path','workingPanel.files.copyRelativePath': 'Copy Relative Path','workingPanel.files.actions.copy': 'Copy',@@ -3252,6 +3300,8 @@ export default {'workingPanel.files.validation.whitespace': "Names can't start or end with a space",'workingPanel.files.collapseAll': 'Collapse Folders in Explorer','workingPanel.files.empty': 'No files in this workspace',+ 'workingPanel.files.unreadable':+ "Couldn't read this workspace โ it may not exist yet, or the listing failed",'workingPanel.files.filters.changedOnly': 'Show Git Changes Only','workingPanel.files.filters.hideIgnored': 'Exclude Ignored Files','workingPanel.files.filters.title': 'Filter Files',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex cf18a7a3cb1..6ffc2912362 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -54,6 +54,9 @@ export default {'features.oauthApps.desc':'Show OAuth app management in personal and workspace settings. This feature is hidden by default.','features.oauthApps.title': 'OAuth Apps',+ 'features.persistentSandbox.desc':+ 'Keep files the cloud sandbox writes. Its working directory survives session recycling and is shared across your topics, instead of being discarded with the sandbox. Requires a paid plan; large downloads and dependencies still belong in /tmp.',+ 'features.persistentSandbox.title': 'Persistent Sandbox','features.projects.desc':'Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.','features.projects.title': 'Project Workspaces',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 60325209113..d8ff0495dea 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1618,6 +1618,8 @@ When I am ___, I need ___'storageOverage.consent.rate':'About {{limitedMonthlyRate}}/GB/month for a limited time (regular {{regularMonthlyRate}}).','storageOverage.consent.title': 'Enable Storage Pay-as-you-go',+ 'storageOverage.mobileManaged.desc':+ 'Your plan was purchased in an app store, so storage pay-as-you-go cannot be enabled here. Manage this subscription where you bought it.','storageOverage.currentPlanLocked.desc':'Your current plan does not support storage pay-as-you-go. After it ends, subscribe to a plan to enable it.','storageOverage.desc':@@ -1642,6 +1644,17 @@ When I am ___, I need ___'storageOverage.noPaymentMethod': 'Please add a payment method to enable storage pay-as-you-go.','storageOverage.rate':'About {{limitedMonthlyRate}}/GB/month for a limited time (regular {{regularMonthlyRate}}).',+ // The sandbox workspace is the same bargain on different storage, so only+ // what actually differs is restated: what it is, what it costs, and what+ // stops when it is turned off. Everything else โ consent terms, cap,+ // payment-method prompt โ is shared word for word.+ 'storageOverage.sandbox.title': 'Sandbox Storage Pay-as-you-go',+ 'storageOverage.sandbox.desc':+ "Bill for sandbox workspace storage beyond your plan's included size, instead of stopping at it.",+ 'storageOverage.sandbox.rate': 'About {{regularMonthlyRate}}/GB/month.',+ 'storageOverage.sandbox.consent.rate': 'About {{regularMonthlyRate}}/GB/month.',+ 'storageOverage.sandbox.disableConfirm.blockWrites':+ 'If your workspace is still above the included size, agents will be unable to write to it.','storageOverage.subscriptionRequired.action': 'View plans','storageOverage.subscriptionRequired.desc':'Subscribe to a plan to enable storage pay-as-you-go for overage usage.',@@ -3895,4 +3908,224 @@ When I am ___, I need ___'tools.tabs.all': 'All','tools.tabs.installed': 'Enabled','tools.title': 'Skills',+ 'tab.environments': 'Environments',+ 'environments.desc':+ 'What a sandbox run needs around it: a repository, its setup, its variables. Each instance built from one keeps its own files between sessions.',+ 'environments.create': 'New environment',+ 'environments.cancel': 'Cancel',+ 'environments.createFailed': 'Could not create the environment',+ 'environments.namePlaceholder': 'Environment name',+ 'environments.empty': 'No environments yet',+ 'environments.removeFailed': 'Could not delete this environment',+ 'environments.saveFailed': 'Could not save this change',+ 'environments.instances.removeFailed': 'Could not delete this instance',+ 'environments.instances.removing': 'Deleting โ removing its folder and everything in it',+ 'environments.instances.removeConfirmTitle': 'Delete instance {{name}}?',+ 'environments.instances.removeConfirmContent':+ 'Its folder and everything it kept โ installed packages, reports, data โ will be deleted. This cannot be undone.',+ 'environments.remove': 'Delete environment',+ 'environments.removeConfirmTitle': 'Delete environment {{name}}?',+ 'environments.removeConfirmContent':+ 'Its specification, variables and saved snapshot go with it, and cannot be recovered.',+ '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.hasInstances': 'Remove its instances 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.desc':+ 'Environments describe a persistent cloud workspace, and this deployment does not provide one.',+ 'environments.upgrade.title': 'Upgrade to Pro to unlock sandbox environments',+ 'environments.upgrade.desc':+ 'Give cloud-sandbox runs a persistent working directory. An environment describes what the sandbox needs โ repositories, setup, variables โ and its instances keep everything between sessions.',+ 'environments.upgrade.cta': 'Upgrade to Pro',+ 'environments.upgrade.benefits.environments.title': 'Sandbox setup written once',+ 'environments.upgrade.benefits.environments.desc':+ 'Repositories, setup command and variables live in the environment; every sandbox built from it starts ready.',+ '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 instance per task',+ 'environments.upgrade.benefits.instances.desc':+ 'Parallel conversations each run in their own instance of the environment, so nothing overwrites anything else.',+ 'environments.github.label': 'Repository',+ 'environments.github.notConnected':+ 'No GitHub connection yet โ connect one to build an environment from a repository',+ 'environments.nameLabel': 'Name',+ 'environments.github.optional': 'optional',+ 'environments.github.organization': 'Organization',+ 'environments.github.organizationPlaceholder': 'Search organizations',+ 'environments.github.repository': 'Repository',+ 'environments.github.repositoryPlaceholder': 'Search repositories',+ 'environments.github.repositoryPending': 'Choose an organization first',+ 'environments.github.noRepositories': 'This connection cannot see any repositories yet',+ 'environments.github.connect': 'Connect GitHub',+ 'environments.github.reviewAccess': 'Review access',+ 'environments.instances.create': 'New instance',+ 'environments.form.description': 'Description',+ '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.',+ 'environments.form.ref': 'Branch or tag',+ 'environments.form.refDefault': 'Repository default branch',+ 'environments.form.path': 'Folder',+ 'environments.form.addSource': 'Add repository',+ 'environments.form.removeSource': 'Remove repository',+ 'environments.form.bootstrap': 'Setup command',+ 'environments.form.bootstrapHint':+ '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 instance.',+ 'environments.form.addEnv': 'New variable',+ 'environments.form.envCount_one': '{{count}} variable',+ '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.rawEditor': 'Raw editor',+ 'environments.form.rawEditorHint':+ 'One KEY=value per line, the way a .env file reads. Blank lines and # comments are ignored; saving replaces every variable.',+ 'environments.form.rawInvalid': 'Line {{line}} is not KEY=value',+ 'environments.form.removeEnv': 'Remove variable',+ 'environments.form.internetAccess': 'Agent internet access',+ 'environments.form.internetAccessHint':+ 'Setup always has network access. This controls the conversation itself.',+ 'environments.form.saved': 'Saved',+ 'environments.form.editEnv': 'Edit variable',+ 'environments.form.changeRepository': 'Change repository',+ 'environments.form.disconnect': 'Disconnect',+ 'environments.instances.title': 'Instances',+ 'environments.instances.desc':+ 'An instance is a working copy of this environment, with its own folder and its own installed packages. Conversations run inside an instance, and several can run side by side without touching each other.',+ 'environments.instances.empty': 'No instances yet',+ 'environments.instances.emptyHint':+ 'Create one, then pick it under "Working Directory" in the chat input.',+ 'environments.instances.emptyReadonly':+ 'Nobody has created an instance of this environment yet. Only its owner can add one.',+ 'environments.instances.count_one': '{{count}} instance',+ 'environments.instances.count_other': '{{count}} instances',+ 'environments.instances.add': 'New instance',+ 'environments.instances.namePlaceholder': 'Instance name',+ // One line, because the field fills itself in from the name: almost nobody+ // has a decision to make here, and a paragraph over a solved field reads as+ // a warning that something is about to go wrong.+ 'environments.instances.directoryHint': 'Folder path. Cannot be changed once created.',+ 'environments.sessions.stale': 'No end recorded',+ 'environments.instances.remove': 'Delete instance',+ 'environments.instances.rename': 'Rename instance',+ 'environments.instances.renameFailed': 'Could not rename this instance',+ 'environments.instances.directoryLocked':+ 'The folder cannot be changed after the instance is built โ delete it and create another to move it.',+ 'environments.instances.duplicateDirectory': 'Another instance already uses this folder',+ 'environments.instances.overlappingDirectory':+ "This folder is inside another instance's folder, or contains one",+ 'environments.instances.createFailed': 'Could not create the instance',+ 'environments.form.maintenance': 'Maintenance command',+ 'environments.form.maintenanceHint':+ 'Runs each time work resumes in an instance โ refreshing a checkout, reapplying a migration. Not the setup command again: that one is expensive and is meant to run once.',+ '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.meta.creatorTooltip': 'Created by {{name}}',+ 'environments.meta.unknownCreator': 'Unknown',+ 'environments.meta.createdAt': 'Created {{time}}',+ 'environments.meta.storage': 'Using {{size}}',+ 'environments.detail.close': 'Close',+ 'environments.detail.tabs.settings': 'Settings',+ 'environments.sessions.title': 'Run history',+ 'environments.sessions.desc':+ 'The most recent sessions that ran in these instances and the builds of them, newest first, with how each ended and whether what it installed was saved.',+ 'environments.sessions.empty': 'Nothing has run here yet',+ 'environments.sessions.emptyHint':+ 'Every conversation and build in one of its instances will show up here.',+ 'environments.sessions.unavailable':+ 'Part of the history could not be read โ some instances are missing from this list',+ 'environments.sessions.running': 'Running',+ 'environments.sessions.activeSession': 'A sandbox is running in {{instance}} right now',+ 'environments.sessions.activeBuild': '{{instance}} is being built right now',+ 'environments.sessions.openConversation': 'Open conversation',+ 'environments.sessions.history': 'History',+ 'environments.sessions.historyEmpty': 'No finished runs yet',+ 'environments.sessions.kind.build': 'Build',+ 'environments.sessions.kind.console': 'File browser',+ 'environments.sessions.kind.conversation': 'Conversation',+ 'environments.sessions.snapshotSaved': 'Saved {{size}}',+ 'environments.sessions.snapshotFailed': 'Not saved',+ 'environments.sessions.reason.idle': 'Stopped after idling',+ 'environments.sessions.reason.expired': 'Reached its time limit',+ 'environments.sessions.reason.switched': 'Replaced by another environment',+ 'environments.sessions.reason.explicit': 'Stopped',+ 'environments.sessions.reason.lost': 'Ended unexpectedly',+ 'environments.sessions.reason.build_succeeded': 'Built',+ '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 an instance is built from โ where the code comes from and what makes it usable.',+ 'environments.form.appliesOnBuild':+ 'Applied when an instance is created. Existing instances keep the definition they were made with โ a rebuild replays that one, so use a new instance to pick this up.',+ 'environments.refresh': 'Refresh',+ 'environments.emptyPublished': 'Nothing published to this workspace yet',+ 'environments.visibility.tabs.workspace': 'Workspace',+ 'environments.visibility.tabs.private': 'Private',+ 'environments.visibility.publish': 'Publish to Workspace',+ 'environments.visibility.createPublishedConfirmTitle':+ 'Create this environment in the workspace?',+ 'environments.visibility.publishConfirmTitle': 'Publish this environment to the workspace?',+ '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.',+ 'environments.files.browse': 'Browse files',+ 'environments.files.back': 'Back',+ 'environments.files.empty': 'This directory is empty',+ 'environments.files.binary': 'Not a text file, so it cannot be shown here.',+ 'environments.files.unreadable': 'This file could not be read',+ 'environments.files.listFailed': 'This directory could not be listed',+ 'environments.files.invalidPath': "The name has to stay inside this instance's directory",+ 'environments.files.truncated': 'Only the first entries are shown',+ 'environments.mine': 'My environments',+ 'environments.form.basics': 'Basics',+ 'environments.form.setup': 'Setup',+ 'environments.form.runtime': 'Runtime and storage',+ 'environments.instances.confirm': 'Create',+ 'environments.instances.save': 'Save',+ // Materializing an instance: the clone and the bootstrap. Minutes long by+ // nature, which is why it is a state of the row rather than a spinner on a+ // button, and why the log is one click away instead of gone.+ 'environments.instances.building': 'Building โ cloning and installing',+ 'environments.instances.buildStatusUnknown': 'Lost track of this build',+ 'environments.instances.retryStatus': 'Check again',+ 'environments.instances.buildFailed': 'Build failed',+ 'environments.instances.rebuild': 'Rebuild',+ 'environments.instances.build': 'Build',+ 'environments.instances.buildConfirmTitle': 'Build instance {{name}}?',+ 'environments.instances.buildStartFailed': 'Could not start the build',+ // Context-free on purpose: the same code refuses a rebuild and a delete, so+ // a sentence that only mentions rebuilding was wrong half the time.+ 'environments.instances.running': 'Running',+ 'environments.instances.occupancyUnavailable':+ 'Could not read which instances are running right now',+ 'environments.instances.inUse':+ 'A conversation is using this instance โ try again once that run ends',+ 'environments.instances.notBuilt': 'Not built yet โ nothing has been cloned or installed',+ 'environments.instances.rebuildConfirmContent':+ "This clears the instance'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 instance {{name}}?',+ 'environments.instances.showLog': 'Show log',+ 'environments.instances.hideLog': 'Hide log',+ 'environments.instances.directoryLabel': 'Directory',+ 'environments.files.up': 'Up one level',+ 'environments.files.readOnlyHint':+ 'Read-only: kept in sync by the sandbox. Dependencies such as node_modules are not shown.',+ '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 instance is built or a conversation runs in it.',};diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex 3d1127f036e..33f6dd14833 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -579,6 +579,9 @@ export default {'plans.workspace.freeMembers': 'Up to 3 members (including you)','plans.target': 'Target Plan','plans.unlimited': 'Unlimited',+ 'plansModal.persistentSandbox.desc':+ 'Files your agent writes in the cloud sandbox are discarded when the session ends. Upgrade to keep a persistent working directory that survives sessions and is shared across your topics.',+ 'plansModal.persistentSandbox.title': 'Keep your sandbox files','plansModal.artifactDeploymentLimit.desc':'Your Artifact hosting capacity has been reached. Upgrade to increase active deployments and per-site size limits.','plansModal.artifactDeploymentLimit.title': 'Increase Artifact hosting capacity',@@ -784,5 +787,6 @@ export default {'usage.overview.title': 'Overview','usage.storage.embeddings.used': 'Vector Storage','usage.storage.file.used': 'File Usage',+ 'usage.storage.sandboxStorage.used': 'Sandbox Storage','usage.remaining': 'Remaining',};diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex 8ecd902fcd1..8f59d3f8e37 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -31,6 +31,7 @@"@lobechat/builtin-tool-message": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*","@lobechat/builtin-tool-remote-device": "workspace:*",+ "@lobechat/builtin-tool-skills": "workspace:*","@lobechat/builtin-tool-task": "workspace:*","@lobechat/builtin-tool-video-generation": "workspace:*","@lobechat/builtin-tool-web-browsing": "workspace:*",diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex 9f099e6605e..96e05c6aac9 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -404,3 +404,37 @@ describe('gatherContextFacts', () => {});});});++describe('which tool counts as reaching the sandbox', () => {+ const persistence = { cwd: 'lobehub-dev', mode: 'persistent' as const };++ it('describes the persistent workspace for a run that only has the always-on skills tool', async () => {+ // `lobe-skills` runCommand opens the same session in the same directory as+ // the cloud-sandbox tool, and it ships with every run. Gating the placement+ // on the optional tool left a skills-driven run reading the ephemeral+ // wording while its commands ran in a persistent workspace.+ const facts = await gatherContextFacts(request({ enabledToolIds: ['lobe-skills'] }), {+ resolveSandboxPersistence: async () => persistence,+ });++ expect(facts.variables.sandbox_workspace).toContain('persistent workspace');+ expect(facts.variables.sandbox_workspace).toContain('`lobehub-dev`');+ });++ it('still describes it for the cloud-sandbox tool on its own', async () => {+ const facts = await gatherContextFacts(request({ enabledToolIds: ['lobe-cloud-sandbox'] }), {+ resolveSandboxPersistence: async () => persistence,+ });++ expect(facts.variables.sandbox_workspace).toContain('persistent workspace');+ });++ it('asks for nothing when no tool can run a command in the sandbox', async () => {+ const resolveSandboxPersistence = vi.fn(async () => persistence);+ await gatherContextFacts(request({ enabledToolIds: ['lobe-agent'] }), {+ resolveSandboxPersistence,+ });++ expect(resolveSandboxPersistence).not.toHaveBeenCalled();+ });+});diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex d9ad42a2891..ff9582ac8ff 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -3,6 +3,7 @@ import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';import {CloudSandboxIdentifier,+ formatSandboxStoragePromptVariables,formatUploadedFilesPrompt,} from '@lobechat/builtin-tool-cloud-sandbox';import {@@ -15,6 +16,7 @@ import {} from '@lobechat/builtin-tool-creds';import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';import { COMPOSIO_APP_TYPES } from '@lobechat/const';import {@@ -448,6 +450,13 @@ export const gatherContextFacts = async (): Promise<GatheredContextFacts> => {const docsAgentId = documentsAgentId(request);const sandboxEnabled = request.enabledToolIds.includes(CloudSandboxIdentifier);+ // Two tools reach the sandbox, and the optional one is not the common case:+ // `lobe-skills` is always on, and its runCommand / execScript open the SAME+ // session in the SAME directory as the cloud-sandbox tool. Asking only+ // whether the optional tool is enabled told a skills-driven run the+ // ephemeral wording while its commands ran in a persistent workspace โ so it+ // cloned into /tmp and the user's file browser stayed empty.+ const sandboxShellEnabled = sandboxEnabled || request.enabledToolIds.includes(SkillsIdentifier);const tasks = [() =>@@ -467,6 +476,10 @@ export const gatherContextFacts = async (? providers.listSandboxFiles?.(request.topicId): undefined,),+ () =>+ attempt('sandboxPersistence', () =>+ sandboxShellEnabled ? providers.resolveSandboxPersistence?.() : undefined,+ ),() =>attempt('topic', () =>request.topicId ? providers.findTopic?.(request.topicId) : undefined,@@ -486,6 +499,7 @@ export const gatherContextFacts = async (onboardingContext,planTodo,sandboxFiles,+ sandboxPersistence,topic,topicReferences,userInfo,@@ -520,6 +534,12 @@ export const gatherContextFacts = async (memory_effort: String(request.agent.chatConfig?.memory?.effort ?? ''),sandbox_enabled: String(sandboxEnabled),sandbox_uploaded_files: sandboxFiles ? formatUploadedFilesPrompt(sandboxFiles) : '',+ // 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'+ ? formatSandboxStoragePromptVariables(sandboxPersistence)+ : {}),topic_id: request.topicId ?? '',topic_title: topic?.title ?? '',username: userInfo?.username ?? '',diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex 1801bf23ae4..149657206bf 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -162,6 +162,15 @@ export interface ContextFactProviders {) => Promise<{ content: string; role: string }[] | undefined>;/** 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+ * 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+ >;}export interface GatheredContextFacts {diff --git a/packages/mecha/src/contextEngineering/variableGenerators.ts b/packages/mecha/src/contextEngineering/variableGenerators.tsindex 6d35627e09c..5a9bc65bbdb 100644--- a/packages/mecha/src/contextEngineering/variableGenerators.ts+++ b/packages/mecha/src/contextEngineering/variableGenerators.ts@@ -1,3 +1,4 @@+import { formatSandboxStoragePromptVariables } from '@lobechat/builtin-tool-cloud-sandbox';import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import type { VariableGenerators } from '@lobechat/context-engine';@@ -93,6 +94,13 @@ export const createVariableGenerators = ({userDataPath: () => '(not reported)',videosPath: () => '(not reported)',workingDirectory: () => '(not specified, use user Home directory as default)',+ // Leak-guards for the cloud-sandbox `{{sandbox_workspace}}` /+ // `{{sandbox_session_files}}` sections. The persistent-workspace wording+ // arrives through `variables` only for a run that actually got one+ // (entitlement claim AND persistent mode); every other run renders the+ // original ephemeral-session text rather than leaking the literal tokens.+ sandbox_session_files: () => formatSandboxStoragePromptVariables().sandbox_session_files,+ sandbox_workspace: () => formatSandboxStoragePromptVariables().sandbox_workspace,};return {diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex daa6e3d85d3..6090ae1e0a0 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -1,12 +1,42 @@+import { z } from 'zod';+import type { LobeAgentChatConfig } from '../agent/chatConfig';import type { CreateThreadWithMessageParams } from '../aiChat';-import type { DeviceUnavailableErrorData, WorkingDirConfig } from '../device';+import type { DeviceUnavailableErrorData } from '../device';+import { workingDirConfigSchema } from '../device';import type { TaskDetail, UIChatMessage } from '../message';import type { ChatTopic } from '../topic';export * from './credentialFacts';export * from './modelFacts';+/**+ * Metadata a client resolved before the topic existed, carried by the first+ * send so the SERVER topic is born with it.+ *+ * The schema is the declaration and the type is derived from it, deliberately.+ * Written as two independent declarations โ an interface here and a+ * `z.object()` at the router โ they drift silently: `z.object()` strips keys it+ * does not know, so a field added to the interface alone is dropped mid-flight+ * and the call still answers 200.+ */+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.+ */+ sandboxInstanceId: z.string().optional(),+ sandboxMode: z.enum(['ephemeral', 'persistent']).optional(),+ workingDirectory: z.string().optional(),+ workingDirectoryConfig: workingDirConfigSchema.optional(),+});++export type InitialTopicMetadata = z.infer<typeof initialTopicMetadataSchema>;+export type AgentSignalOperationKind ='memory' | 'nightly-review' | 'self-feedback-intent' | 'self-reflection' | 'skill';@@ -107,11 +137,7 @@ export interface ExecAgentAppContext {* Initial metadata to merge into the topic when a new topic is created for* this execution. Ignored when a topicId is already provided (existing topic).*/- initialTopicMetadata?: {- repos?: string[];- workingDirectory?: string;- workingDirectoryConfig?: WorkingDirConfig;- };+ initialTopicMetadata?: InitialTopicMetadata;/*** Whether this operation runs inside an isolation thread spawned by another* operation on the same topic (callAgent / callSubAgent / group member).diff --git a/packages/types/src/agentExecution/initialTopicMetadata.test.ts b/packages/types/src/agentExecution/initialTopicMetadata.test.tsnew file mode 100644index 00000000000..09a792a4615--- /dev/null+++ b/packages/types/src/agentExecution/initialTopicMetadata.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { initialTopicMetadataSchema } from './index';++describe('initialTopicMetadataSchema', () => {+ it('carries every field a first send needs to be born with', () => {+ // These travel because the server cannot read the client's pre-topic state.+ // A key this schema does not know is stripped without a word and the call+ // still answers 200, so the loss is invisible from both ends โ which is why+ // the assertion is on the parse rather than on any caller.+ const metadata = {+ repos: ['lobehub/lobehub'],+ sandboxInstanceId: 'a2c1d0e4-0000-4000-8000-000000000000',+ sandboxMode: 'persistent' as const,+ 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/environment/index.ts b/packages/types/src/environment/index.tsindex 3311dc5f723..26522d71bb5 100644--- a/packages/types/src/environment/index.ts+++ b/packages/types/src/environment/index.ts@@ -1,3 +1,12 @@+/**+ * Who, inside a workspace, an environment resolves for.+ *+ * `private` is the default and the only meaning a personal environment has.+ * `public` lets every member of the workspace run in it โ and therefore in its+ * instances, which carry whatever a session left in them.+ */+export type EnvironmentVisibility = 'private' | 'public';+/** Abstract source material; paths are relative destinations within an instance. */export type EnvironmentSource =| { kind: 'git'; path?: string; ref?: string; url: string }@@ -12,6 +21,43 @@ export interface EnvironmentResourceRequirements {/** Portable definition, shared by device, sandbox and cluster instances. No credentials. */export interface EnvironmentConfiguration {bootstrapCommand?: string;+ /**+ * Non-secret values exported before anything else runs โ a region, a mirror,+ * a feature switch. Credentials are excluded by the same rule that governs+ * the rest of this object: it is stored in plain text and copied into every+ * instance snapshot, so a token written here is a token in the database and+ * in every copy of it. Secrets are resolved by the runtime at use time.+ */+ env?: Record<string, string>;+ /**+ * Paths the author declares REGENERABLE, relative to an instance's own root.+ *+ * Not merely "skip these". What is named here is kept apart from the work+ * that cannot be remade, and what is kept apart may be discarded to reclaim+ * space โ so a path listed here that cannot in fact be rebuilt is work its+ * owner can lose. Read it as a promise about the path, not an optimization.+ *+ * Declarative rather than a cleanup command run just before capture, which+ * deletes unattended and then immediately makes the result permanent.+ */+ excludePaths?: string[];+ /**+ * Whether work in this environment may reach the network. Omitted means the+ * adapter decides, which is not uniform: a sandbox runs connected so that a+ * bootstrap can install anything, while a device simply has whatever network+ * the machine has and cannot enforce a restriction at all.+ */+ internetAccess?: boolean;+ /**+ * Run every time work resumes in an instance, after whatever was built is+ * restored โ refreshing a checkout, reapplying a migration.+ *+ * Emphatically not {@link EnvironmentConfiguration.bootstrapCommand} run+ * again: bootstrap is what makes an empty instance usable and is expensive by+ * nature, so running it per task would discard the whole point of building+ * once. This is the short reconciliation that follows.+ */+ maintenanceCommand?: string;/** Requirements, not a selection of a particular machine or provider. */requirements?: EnvironmentResourceRequirements;sources?: EnvironmentSource[];@@ -29,3 +75,18 @@ export interface EnvironmentInstanceConfiguration {image?: string;resources?: EnvironmentResourceRequirements;}++/**+ * What a new environment declares regenerable before anyone edits it.+ *+ * The sandbox runtime keeps these out of the snapshot layer and therefore out+ * of the quota: they are rebuilt from the specification, so charging a+ * multi-gigabyte `node_modules` against an allowance sized for source would+ * make the allowance unusable for the projects it is sold for.+ *+ * A default rather than a built-in rule, because the field is a PROMISE by the+ * environment's author that the path can be rebuilt โ and a promise the+ * platform makes silently is one the author cannot withdraw. Seeded into the+ * form at creation, visible, and removable.+ */+export const DEFAULT_REGENERABLE_PATHS = ['node_modules', '.venv', 'target'] as const;diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.tsindex 17992e7abaa..90c9736725f 100644--- a/packages/types/src/topic/topic.test.ts+++ b/packages/types/src/topic/topic.test.ts@@ -162,6 +162,20 @@ describe('chatTopicMetadataUpdateSchema', () => {expect(result.success).toBe(false);});+ it('carries the sandbox binding through โ a stripped key writes nothing and still answers 200', () => {+ const metadata = { sandboxInstanceId: 'a2c1d0e4-0000-4000-8000-000000000000' };++ 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('keeps the onboarding feedback comment limit at the shared contract boundary', () => {const result = chatTopicMetadataUpdateSchema.safeParse({onboardingFeedback: {diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 3ddec6d6a69..08ba69bc7d9 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -315,6 +315,45 @@ export interface ChatTopicMetadata {* runs keep using their operation row, which is the more faithful record.*/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.+ *+ * Two conversations that must not overwrite each other's files take two+ * instances of one environment rather than two directories under one, because+ * what was installed follows the directory โ separating them at the directory+ * 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.+ *+ * 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+ * takes effect the next time the sandbox starts.+ *+ * The desktop counterpart is {@link ChatTopicMetadata.workingDirectory}; the+ * two never interact, one addresses the user's machine and the other a+ * directory inside a remote volume.+ */+ 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.+ */+ sandboxMode?: 'ephemeral' | 'persistent';/*** A deferred agent run on this topic. Present iff the topic status is* `scheduled`. Set to `null` to clear it (same clear-convention as@@ -562,6 +601,19 @@ 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`).+ //+ // 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(),+ sandboxInstanceId: z.string().optional(),+ sandboxMode: z.enum(['ephemeral', 'persistent']).optional(),scheduledRun: topicScheduledRunSchema.nullish(),workingDirectory: z.string().optional(),workingDirectoryConfig: workingDirConfigSchema.optional(),diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 129583e41bc..011d549aa7f 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -233,6 +233,12 @@ export const UserLabSchema = z.object({* running there can be opened from this UI*/enableDeviceTunnel: z.boolean().optional(),+ /**+ * opt this user's cloud-sandbox runs into a persistent workspace: the working+ * directory survives session recycling and is shared across their topics,+ * instead of being thrown away with the sandbox+ */+ enablePersistentSandbox: z.boolean().optional(),});export type UserLab = z.infer<typeof UserLabSchema>;diff --git a/src/business/client/features/SandboxStorageUpsell.tsx b/src/business/client/features/SandboxStorageUpsell.tsxnew file mode 100644index 00000000000..201e2209ee3--- /dev/null+++ b/src/business/client/features/SandboxStorageUpsell.tsx@@ -0,0 +1,41 @@+'use client';++import { Center, Empty } from '@lobehub/ui';+import { ContainerIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * Opens whatever explains, to a user whose plan has no persistent sandbox, how+ * to get one. Called from the working-directory menu of a cloud-sandbox run,+ * which offers persistence as a tagged row for such a plan; the row calls this.+ *+ * A no-op in the open-source build: persistence there is a deployment decision,+ * not a purchase, so there is nothing to sell. Downstream builds override this+ * module through their own `@/business/...` mapping.+ */+export const openSandboxStorageUpsell = (): 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+ * 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(() => {+ const { t } = useTranslation('setting');++ return (+ <Center style={{ minHeight: 320 }} width={'100%'}>+ <Empty+ description={t('environments.unavailable.desc')}+ descriptionProps={{ fontSize: 13 }}+ icon={ContainerIcon}+ style={{ maxWidth: 400 }}+ title={t('environments.unavailable.title')}+ />+ </Center>+ );+});++SandboxStorageUpgradeGuide.displayName = 'SandboxStorageUpgradeGuide';diff --git a/src/features/AgentTasks/features/useTaskRunTarget.ts b/src/features/AgentTasks/features/useTaskRunTarget.tsindex 75d63c0fe69..086be2933e2 100644--- a/src/features/AgentTasks/features/useTaskRunTarget.ts+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts@@ -179,7 +179,9 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task[agencyConfig, deviceDefaultCwd, deviceId, legacyAgentWorkingDirectory, workspaceScoped],);- const surface = resolveWorkspaceSurface({+ // A list since the sandbox landed: more than one surface can apply to the+ // same run, so membership rather than equality.+ const surfaces = resolveWorkspaceSurface({agencyConfig,alwaysShowWorkspace: isHetero,clientExecutionAvailable: isDesktop,@@ -196,7 +198,7 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task// a directory without one.const directoryKind: TaskDirectoryKind = deviceId? 'device'- : surface === 'cloudRepo'+ : surfaces.includes('cloudRepo')? 'repo': 'none';diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex 3a8d6daba27..6a4ee28872a 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -7,7 +7,6 @@ import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';import { Button, confirmModal, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import {- CheckIcon,ChevronDownIcon,ExternalLinkIcon,InfoIcon,@@ -49,6 +48,7 @@ import { useElectronStore } from '@/store/electron';import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';import { moveTopicToTarget } from './moveTopicToTarget';+import OptionRow from './OptionRow';import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';const styles = createStaticStyles(({ css }) => ({@@ -89,11 +89,6 @@ const styles = createStaticStyles(({ css }) => ({background: transparent;}`,- check: css`- flex: none;- margin-inline-start: auto;- color: ${cssVar.colorPrimary};- `,desc: css`display: flex;gap: 6px;@@ -102,18 +97,6 @@ const styles = createStaticStyles(({ css }) => ({font-size: 11px;color: ${cssVar.colorTextDescription};`,- extra: css`- display: flex;- flex: none;- gap: 4px;- align-items: center;-- margin-inline-start: auto;-- /* A disabled row dims itself, but its trailing action is the way OUT of- that state โ dimming the setup button would read as "also unavailable". */- opacity: 1;- `,extraInfo: css`cursor: help;@@ -166,34 +149,6 @@ const styles = createStaticStyles(({ css }) => ({margin-inline-start: auto;color: ${cssVar.colorTextQuaternary};`,- option: css`- cursor: pointer;-- display: flex;- gap: 10px;- align-items: center;-- padding-block: 8px;- padding-inline: 8px;- border-radius: ${cssVar.borderRadius};-- transition: background-color 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- optionActive: css`- background: ${cssVar.colorFillSecondary};- `,- optionDisabled: css`- cursor: not-allowed;- opacity: 0.55;-- &:hover {- background: transparent;- }- `,optionIcon: css`display: flex;flex: none;@@ -232,19 +187,6 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;`,- tag: css`- flex: none;-- padding-block: 0;- padding-inline: 5px;- border-radius: 4px;-- font-size: 10px;- line-height: 16px;- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillSecondary};- `,header: css`display: flex;gap: 6px;@@ -314,65 +256,6 @@ const styles = createStaticStyles(({ css }) => ({`,}));-interface OptionRowProps {- active: boolean;- desc?: ReactNode;- disabled?: boolean;- /**- * Trailing controls that belong to the row but are not the row's selection โ- * rendered before the checkmark, with clicks kept from selecting the row so a- * setting can be adjusted without switching environment.- */- extra?: ReactNode;- icon: ReactNode;- label: string;- onClick: () => void;- tags?: ReactNode[];-}--const OptionRow = memo<OptionRowProps>(- ({ active, desc, disabled, extra, icon, label, onClick, tags }) => {- return (- <div- className={cx(- styles.option,- active && styles.optionActive,- disabled && styles.optionDisabled,- )}- onClick={() => {- if (!disabled) onClick();- }}- >- <div className={styles.optionIcon}>{icon}</div>- <div className={styles.optionMeta}>- <Flexbox horizontal align={'center'} gap={6}>- <span className={styles.optionTitle}>{label}</span>- {tags?.map((tag, index) => (- <span className={styles.tag} key={index}>- {tag}- </span>- ))}- </Flexbox>- {desc ? <div className={styles.desc}>{desc}</div> : null}- </div>- {extra ? (- <div- className={styles.extra}- onClick={(event) => {- event.stopPropagation();- }}- >- {extra}- </div>- ) : null}- {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}- </div>- );- },-);--OptionRow.displayName = 'HeteroDeviceSwitcher.OptionRow';-interface HeteroDeviceSwitcherProps {agentId: string;}diff --git a/src/features/ChatInput/ControlBar/OptionRow.tsx b/src/features/ChatInput/ControlBar/OptionRow.tsxnew file mode 100644index 00000000000..ae4e199e909--- /dev/null+++ b/src/features/ChatInput/ControlBar/OptionRow.tsx@@ -0,0 +1,174 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { CheckIcon } from 'lucide-react';+import { memo, type ReactNode } from 'react';++/**+ * One choice in a composer menu: framed icon, title over a description, and a+ * check when it is the current one.+ *+ * Shared rather than copied because these menus sit next to each other in the+ * same bar and are read as one control surface โ a second copy of the styles+ * would drift into looking like a different kind of thing.+ */+const styles = createStaticStyles(({ css }) => ({+ check: css`+ flex: none;+ margin-inline-start: auto;+ color: ${cssVar.colorPrimary};+ `,+ desc: css`+ display: flex;+ gap: 6px;+ align-items: center;++ font-size: 11px;+ color: ${cssVar.colorTextDescription};+ `,+ extra: css`+ display: flex;+ flex: none;+ gap: 4px;+ align-items: center;++ margin-inline-start: auto;++ /* A disabled row dims itself, but its trailing action is the way OUT of+ that state โ dimming the setup button would read as "also unavailable". */+ opacity: 1;+ `,+ option: css`+ cursor: pointer;++ display: flex;+ gap: 10px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ transition: background-color 0.2s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ optionActive: css`+ background: ${cssVar.colorFillSecondary};+ `,+ optionDisabled: css`+ cursor: not-allowed;+ opacity: 0.55;++ &:hover {+ background: transparent;+ }+ `,+ optionIcon: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorText};++ background: ${cssVar.colorBgElevated};+ `,+ optionMeta: css`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 1px;++ min-width: 0;+ `,+ optionTitle: css`+ overflow: hidden;++ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ tag: css`+ flex: none;++ padding-block: 0;+ padding-inline: 5px;+ border-radius: 4px;++ font-size: 10px;+ line-height: 16px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillSecondary};+ `,+}));++export interface OptionRowProps {+ active?: boolean;+ desc?: ReactNode;+ disabled?: boolean;+ /** Trailing action, kept live while the row itself is disabled. */+ extra?: ReactNode;+ icon: ReactNode;+ label: ReactNode;+ onClick: () => void;+ /** One trailing tag. Use {@link OptionRowProps.tags} for several. */+ tag?: ReactNode;+ /** Several tags, each in its own pill rather than one pill holding them all. */+ tags?: ReactNode[];+}++const OptionRow = memo<OptionRowProps>(+ ({ active, desc, disabled, extra, icon, label, onClick, tag, tags }) => (+ <div+ className={cx(+ styles.option,+ active && styles.optionActive,+ disabled && styles.optionDisabled,+ )}+ onClick={() => {+ if (!disabled) onClick();+ }}+ >+ <div className={styles.optionIcon}>{icon}</div>+ <div className={styles.optionMeta}>+ <Flexbox horizontal align={'center'} gap={6}>+ <span className={styles.optionTitle}>{label}</span>+ {tag ? <span className={styles.tag}>{tag}</span> : null}+ {tags?.map((item, index) => (+ <span className={styles.tag} key={index}>+ {item}+ </span>+ ))}+ </Flexbox>+ {desc ? <div className={styles.desc}>{desc}</div> : null}+ </div>+ {extra ? (+ <div+ className={styles.extra}+ onClick={(event) => {+ event.stopPropagation();+ }}+ >+ {extra}+ </div>+ ) : null}+ {active ? <Icon className={styles.check} icon={CheckIcon} size={14} /> : null}+ </div>+ ),+);++OptionRow.displayName = 'ControlBar.OptionRow';++export default OptionRow;diff --git a/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx b/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsxnew file mode 100644index 00000000000..e106bae7d70--- /dev/null+++ b/src/features/ChatInput/ControlBar/SandboxInstancePicker.tsx@@ -0,0 +1,555 @@+'use client';++import { Github } from '@lobehub/icons';+import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';+import { Skeleton, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ AppWindowMacIcon,+ ChevronDownIcon,+ FolderClockIcon,+ FolderIcon,+ InfoIcon,+ LockIcon,+ PlusIcon,+ SettingsIcon,+ TimerIcon,+} 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 { repositoryPath } from '@/features/EnvironmentManager/repository';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { sandboxStorageService } from '@/services/sandboxStorage';++import OptionRow from './OptionRow';+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;+ padding-inline: 8px;++ 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;+ padding-inline: 8px;+ `,+ 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;+ padding-inline: 8px;+ font-size: 12px;+ color: ${cssVar.colorTextDescription};+ `,+ skeletonRow: css`+ display: flex;+ gap: 10px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 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;+}++const INSTANCE_ICON = AppWindowMacIcon;++/**+ * 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 instances themselves, flat: an instance is the only+ * thing here files can actually go into, and nesting each one under its+ * environment spent a line per environment to say what the instance's own+ * second line already says. Environments are named there, and made on the+ * environment page โ this menu picks, it does not author.+ *+ * 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']);+ const [open, setOpen] = useState(false);+ const navigate = useWorkspaceAwareNavigate();++ const boundInstanceId = value.mode === 'persistent' ? value.instanceId : undefined;++ // Fetched while CLOSED whenever an instance 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.+ const { data, isLoading: instancesLoading } = useSWR(+ entitled && (open || boundInstanceId) ? ['sandbox-instances', topicId] : null,+ () => sandboxStorageService.listInstances({ topicId, withSizes: false }),+ // The topic is in the key because occupancy is answered per conversation+ // โ "in use by another one" is a different answer here than there. The+ // instances themselves are the same list either way, so the first send,+ // which takes the topic from none to one, must not blank the chip: it+ // would flash a skeleton for a name that never changed. Kept until the+ // refetch lands; a moment of last-known occupancy is not worth that.+ { keepPreviousData: true, revalidateOnFocus: false },+ );+ const {+ data: environmentData,+ error: environmentError,+ isLoading: environmentsLoading,+ // Also while closed when an instance is bound: whether that instance+ // is still usable depends on its environment's visibility.+ } = useSWR(entitled && (open || boundInstanceId) ? 'sandbox-environments' : null, () =>+ sandboxStorageService.listEnvironments(),+ );++ const instances = data?.instances ?? [];+ const environments = environmentData?.environments ?? [];+ 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]),+ );++ // The menu lists instances, not environments. An environment is what an+ // instance was made from โ it names the instance and supplies its icon โ+ // but it is not itself a place files can go, so it no longer gets a row of+ // its own to nest under. Making one is the environment page's job.+ const selectableInstances = instances.filter((instance) => {+ const environment = environmentById.get(instance.environmentId);+ return Boolean(environment) && !isBlocked(instance.environmentId);+ });++ // Inside a workspace an instance belongs to one of two pools, through its+ // environment, 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 poolOf = (instance: (typeof instances)[number]) =>+ environmentById.get(instance.environmentId)?.visibility === 'private'+ ? 'private'+ : 'workspace';+ const privatePool = inWorkspace+ ? selectableInstances.filter((instance) => poolOf(instance) === 'private')+ : [];+ const workspacePool = inWorkspace+ ? selectableInstances.filter((instance) => poolOf(instance) === 'workspace')+ : [];++ // Only once BOTH lists have arrived: undefined is "not known yet", not+ // "none", and instances alone cannot be judged โ an instance whose+ // environment is hidden from this agent is not one of this menu's choices.+ const listsReady = Boolean(environmentData) && Boolean(data);+ const hasNoInstances = listsReady && selectableInstances.length === 0;+ // Which of the two empty states this is. With no environment at all there+ // is nothing to make an instance of, so the row says to set one up; with+ // an environment but no instance, the environment page is where the copy+ // gets made.+ const hasNoEnvironments = hasNoInstances && selectable.length === 0;++ const select = async (selection: SandboxSelection) => {+ setOpen(false);+ await onChange(selection);+ };++ const leaveTo = (action: () => void) => {+ setOpen(false);+ action();+ };++ const renderInstance = (instance: (typeof instances)[number]) => {+ const environment = environmentById.get(instance.environmentId);+ // What the environment builds from, marked the way the settings list+ // marks it. Read from the environment because that is where a checkout+ // is declared, but shown here, because an instance is the row a person+ // picks between and "which repo is this" is what they are asking. The+ // instance's own directory cannot answer it: that is a folder inside the+ // workspace, which a repository icon would misread.+ const repository = repositoryPath(environment?.configuration);+ // Somebody else's run. The execution plane allows one session per+ // instance โ the second writer meets a 409 INSTANCE_IN_USE โ so+ // offering it would be offering a choice the next message refuses. Its+ // own topic's run is the opposite case: that conversation is the one+ // running, and taking its instance away mid-run is the last thing to do.+ const occupied = instance.inUse && !instance.inUseByThisTopic;+ // A build holds the very same lease โ it is the exclusive writer while+ // it publishes โ so it needs no rule of its own here, only its own word.+ // "Running" on an instance that is still being assembled would send+ // someone looking for the conversation that is using it.+ const preparing = instance.status === 'pending';+ // Nothing has been cloned or installed into it yet. Selectable all the+ // same: a build that failed is retried from the settings page, and a+ // conversation pointed at the instance is how someone gets back to it.+ const unbuilt = instance.status === 'error';++ return (+ <OptionRow+ active={instance.id === boundInstanceId}+ // Already this conversation's own instance: it stays selectable+ // however the lease reads, because "you cannot pick what you are+ // already using" is never the right thing to tell someone.+ disabled={(occupied || preparing) && instance.id !== boundInstanceId}+ icon={repository ? <Github size={16} /> : <Icon icon={INSTANCE_ICON} size={16} />}+ key={instance.id}+ label={instance.name}+ desc={+ <span className={styles.environmentRow}>+ {environment+ ? `${environment.name} ยท ${instance.workingDirectory}`+ : instance.workingDirectory}+ </span>+ }+ tag={+ preparing+ ? t('sandboxStorage.building')+ : unbuilt+ ? t('sandboxStorage.buildFailed')+ : instance.inUse+ ? t('sandboxStorage.running')+ : undefined+ }+ onClick={() => void select({ instanceId: instance.id, mode: 'persistent' })}+ />+ );+ };++ // The chip names what was chosen โ an instance, 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 repository mark is not+ // a lucide glyph and the chip has to be able to show it: the chip names the+ // instance the menu named, so a row that reads as a checkout cannot+ // collapse back into a generic window once the menu closes.+ 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 repositoryPath(environmentById.get(current.environmentId)?.configuration) ? (+ <Github size={14} />+ ) : (+ <Icon icon={INSTANCE_ICON} size={14} />+ );+ })();++ // An instance 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+ ? current.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. */}+ {current && !currentBlocked && current.inUse && !current.inUseByThisTopic && (+ <Text className={styles.blockedNotice}>+ {t('sandboxStorage.instanceBusy', { name: current.name })}+ </Text>+ )}++ <Flexbox className={styles.temporary}>+ <OptionRow+ active={value.mode === 'ephemeral'}+ 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+ 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 && environmentError && (+ <Text className={styles.notice}>{t('sandboxStorage.environmentsUnavailable')}</Text>+ )}++ {entitled && hasNoInstances && (+ // Nothing to choose from yet. Both roads lead to the same page โ+ // the row only changes which step it names, because "set up an+ // environment" reads as a dead end to someone who already has one.+ <OptionRow+ icon={<Icon icon={PlusIcon} size={16} />}+ desc={t(+ hasNoEnvironments+ ? 'sandboxStorage.setUpEnvironmentDesc'+ : 'sandboxStorage.noInstancesDesc',+ )}+ label={t(+ hasNoEnvironments ? 'sandboxStorage.setUpEnvironment' : 'sandboxStorage.noInstances',+ )}+ onClick={() => leaveTo(() => navigate('/settings/environments'))}+ />+ )}++ {entitled &&+ !inWorkspace &&+ selectableInstances.map((instance) => renderInstance(instance))}++ {entitled && inWorkspace && privatePool.length > 0 && (+ <>+ <div className={styles.groupLabel}>{t('sandboxStorage.privateGroup')}</div>+ {privatePool.map((instance) => renderInstance(instance))}+ </>+ )}++ {entitled && inWorkspace && workspacePool.length > 0 && (+ <>+ <div className={styles.groupLabel}>{t('sandboxStorage.workspaceGroup')}</div>+ {workspacePool.map((instance) => renderInstance(instance))}+ </>+ )}++ {/* 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={setOpen}+ >+ <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.tsxnew file mode 100644index 00000000000..94097a22aed--- /dev/null+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -0,0 +1,60 @@+'use client';++import { memo } from 'react';++import SafeBoundary from '@/components/ErrorBoundary';+import { useAgentStore } from '@/store/agent';++import SandboxInstancePicker from './SandboxInstancePicker';+import { useSandboxMode } from './useSandboxMode';+import { useSandboxStorageAccess } from './useSandboxStorageAccess';++interface SandboxStorageSectionProps {+ agentId: string;+}++/**+ * 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.+ *+ * 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.+ *+ * A plan without persistence still gets the chip: the temporary directory 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);+ const agentIsPublic = useAgentStore((s) => s.agentMap[agentId]?.visibility === 'public');++ if (status === 'hidden') return null;++ return (+ <SandboxInstancePicker+ agentIsPublic={agentIsPublic}+ entitled={status === 'ready'}+ topicId={topicId}+ value={selection}+ onChange={setSelection}+ />+ );+});++SandboxStorageSectionInner.displayName = 'SandboxStorageSectionInner';++const SandboxStorageSection = memo<SandboxStorageSectionProps>(({ agentId }) => (+ <SafeBoundary minHeight={22} resetKeys={[agentId]}>+ <SandboxStorageSectionInner agentId={agentId} />+ </SafeBoundary>+));++SandboxStorageSection.displayName = 'SandboxStorageSection';++export default SandboxStorageSection;diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 7708d86920b..92fd757cec0 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -43,6 +43,7 @@ import DashedFolderIcon from './DashedFolderIcon';import DirIcon from './DirIcon';import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';import { useMigrateDeviceRecents } from './useMigrateDeviceRecents';+import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';// Show the in-place search box only once the list is long enough that scanning// gets tedious โ a short list doesn't need the extra chrome.@@ -61,34 +62,6 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorFillSecondary};`,- button: css`- cursor: pointer;-- display: flex;- flex: none;- gap: 6px;- align-items: center;-- padding-block: 2px;- padding-inline: 4px;- border-radius: 4px;-- font-size: 12px;- color: ${cssVar.colorTextSecondary};- white-space: nowrap;-- transition: background 0.2s;-- &:hover {- background: ${cssVar.colorFillTertiary};- }- `,- buttonLabel: css`- overflow: hidden;- max-width: 140px;- text-overflow: ellipsis;- white-space: nowrap;- `,chooseFolderItem: css`cursor: pointer;@@ -543,13 +516,13 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =: t('workingDirectory.unselected');const trigger = (- <div className={styles.button}>+ <div className={workingDirectoryChipStyles.chip}>{selectedDir ? (<DirIcon repoType={recents.find((r) => r.path === selectedDir)?.repoType} />) : (<DashedFolderIcon size={14} />)}- <span className={styles.buttonLabel}>{displayName}</span>+ <span className={workingDirectoryChipStyles.label}>{displayName}</span><Icon icon={ChevronDownIcon} size={12} /></div>);diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsxindex 5f8c522b6a8..08eabc46275 100644--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx@@ -1,14 +1,15 @@'use client';import { Tooltip } from '@lobehub/ui';-import { memo } from 'react';+import { Fragment, memo } from 'react';import { useTranslation } from 'react-i18next';import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';import CloudRepoSwitcher from './CloudRepoSwitcher';import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';-import { useWorkspaceSurface } from './useWorkspaceSurface';+import SandboxStorageSection from './SandboxStorageSection';+import { useWorkspaceSurface, type WorkspaceSurface } from './useWorkspaceSurface';import WorkingDirectorySection from './WorkingDirectorySection';interface WorkspaceControlsProps {@@ -36,10 +37,10 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(const { t } = useTranslation('setting');const { canConfigureResource, canUseResource } = useChatInputResourceAccess();// Resolved from the effective (override-merged) execution target so the- // surface follows the device THIS member's run actually targets.- const surface = useWorkspaceSurface(agentId, alwaysShowWorkspace);+ // surfaces follow the device THIS member's run actually targets.+ const surfaces = useWorkspaceSurface(agentId, alwaysShowWorkspace);- const renderWorkspace = () => {+ const renderSurface = (surface: WorkspaceSurface) => {switch (surface) {case 'workingDirectory': {return <WorkingDirectorySection agentId={agentId} />;@@ -47,48 +48,56 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(case 'cloudRepo': {return <CloudRepoSwitcher agentId={agentId} />;}- default: {- return null;+ case 'sandbox': {+ return <SandboxStorageSection agentId={agentId} />;}}};// The directory picker and git controls write shared agent config / run- // device git mutations, so members without edit access see the whole- // cluster disabled. The device switcher handles its own use-level gate.- const workspace = renderWorkspace();+ // device git mutations, so members without edit access see that cluster+ // disabled. The device switcher handles its own use-level gate.+ //+ // The sandbox is exempt: its choice lands in the topic's own metadata, not+ // in the shared agent row, so a member who may use the agent may choose+ // where their own run keeps its files. Gated one surface at a time, so a+ // run that shows both keeps the sandbox chip live while the repo switcher+ // is inert.+ const withAccessGate = (surface: WorkspaceSurface) => {+ const node = renderSurface(surface);+ if (canConfigureResource || surface === 'sandbox') return node;++ return (+ <Tooltip+ title={t(+ canUseResource ? 'permission.accessTag.useOnlyTip' : 'permission.accessTag.viewOnlyTip',+ )}+ >+ {/* Outer div catches hover for the tooltip; the inner one makes+ the controls inert. */}+ <div style={{ alignItems: 'center', display: 'flex', gap: 4 }}>+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ gap: 4,+ opacity: 0.5,+ pointerEvents: 'none',+ }}+ >+ {node}+ </div>+ </div>+ </Tooltip>+ );+ };return (<><HeteroDeviceSwitcher agentId={agentId} />- {workspace &&- (canConfigureResource ? (- workspace- ) : (- <Tooltip- title={t(- canUseResource- ? 'permission.accessTag.useOnlyTip'- : 'permission.accessTag.viewOnlyTip',- )}- >- {/* Outer div catches hover for the tooltip; the inner one makes- the controls inert. */}- <div style={{ alignItems: 'center', display: 'flex', gap: 4 }}>- <div- style={{- alignItems: 'center',- display: 'flex',- gap: 4,- opacity: 0.5,- pointerEvents: 'none',- }}- >- {workspace}- </div>- </div>- </Tooltip>- ))}+ {surfaces.map((surface) => (+ <Fragment key={surface}>{withAccessGate(surface)}</Fragment>+ ))}</>);},diff --git a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.tsindex 20d8e8db923..79e765d88ce 100644--- a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts+++ b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts@@ -70,7 +70,7 @@ describe('useWorkspaceSurface (desktop)', () => {const { result } = renderHook(() => useWorkspaceSurface(AGENT_ID));- expect(result.current).toBe('workingDirectory');+ expect(result.current).toEqual(['workingDirectory']);},);@@ -85,10 +85,10 @@ describe('useWorkspaceSurface (desktop)', () => {const { result } = renderHook(() => useWorkspaceSurface(AGENT_ID));- expect(result.current).toBe('workingDirectory');+ expect(result.current).toEqual(['workingDirectory']);});- it('hides the picker when the member override targets the cloud sandbox', () => {+ it('gives the cloud sandbox its own working directory when the member override targets it', () => {setSharedAgent({agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'local' },workspaceId: 'ws-1',@@ -98,7 +98,10 @@ describe('useWorkspaceSurface (desktop)', () => {const { result } = renderHook(() => useWorkspaceSurface(AGENT_ID));- expect(result.current).toBeUndefined();+ // The device-scoped picker is still hidden โ this run touches no device.+ // What it gets instead is the sandbox's own directory, which is where its+ // files actually land.+ expect(result.current).toEqual(['sandbox']);});it('shows the picker for a personal agent running locally', () => {@@ -108,7 +111,7 @@ describe('useWorkspaceSurface (desktop)', () => {const { result } = renderHook(() => useWorkspaceSurface(AGENT_ID));- expect(result.current).toBe('workingDirectory');+ expect(result.current).toEqual(['workingDirectory']);});it('always shows the picker for a heterogeneous agent, even on a sandbox target', () => {@@ -121,7 +124,7 @@ describe('useWorkspaceSurface (desktop)', () => {const { result } = renderHook(() => useWorkspaceSurface(AGENT_ID, true));- expect(result.current).toBe('workingDirectory');+ expect(result.current).toEqual(['workingDirectory']);});});@@ -140,17 +143,17 @@ describe('resolveWorkspaceSurface (web)', () => {...web,agencyConfig: { boundDeviceId: 'desktop-device', executionTarget: 'local' },}),- ).toBe('workingDirectory');+ ).toEqual(['workingDirectory']);});- it('offers the cloud repo switcher to heterogeneous agents', () => {+ it('offers the cloud repo switcher to a heterogeneous agent bound to a device', () => {expect(resolveWorkspaceSurface({...web,- agencyConfig: { executionTarget: 'sandbox' },+ agencyConfig: { boundDeviceId: undefined, executionTarget: 'device' },isHetero: true,}),- ).toBe('cloudRepo');+ ).toEqual(['cloudRepo']);});it('offers the cloud repo switcher when the workspace is forced on', () => {@@ -160,12 +163,36 @@ describe('resolveWorkspaceSurface (web)', () => {agencyConfig: { executionTarget: 'sandbox' },alwaysShowWorkspace: true,}),- ).toBe('cloudRepo');+ ).toEqual(['cloudRepo', 'sandbox']);+ });++ it('gives a heterogeneous sandbox run the repo switcher AND the sandbox directory, in that order', () => {+ // Both are relevant to such a run โ which repository, and which instance it+ // runs in. Taking the repo switcher away would lose the repository; leaving+ // the sandbox out would leave the run in a throwaway box with no way to+ // choose otherwise.+ expect(+ resolveWorkspaceSurface({+ ...web,+ agencyConfig: { executionTarget: 'sandbox' },+ isHetero: true,+ }),+ ).toEqual(['cloudRepo', 'sandbox']);+ });++ it('gives a plain web run on the cloud sandbox the sandbox surface', () => {+ expect(+ resolveWorkspaceSurface({ ...web, agencyConfig: { executionTarget: 'sandbox' } }),+ ).toEqual(['sandbox']);});- it('shows nothing for a plain agent without a bound device', () => {- expect(resolveWorkspaceSurface({ ...web, agencyConfig: { executionTarget: 'local' } })).toBe(- undefined,+ it('gives a plain web agent the sandbox surface, because that is where it runs', () => {+ // On web a `local` target coerces to `sandbox` โ there is no client to run+ // on. The run therefore keeps its files in the sandbox, so that is the+ // working directory it gets a say over. The device-scoped picker stays+ // hidden either way: no device is involved.+ expect(resolveWorkspaceSurface({ ...web, agencyConfig: { executionTarget: 'local' } })).toEqual(+ ['sandbox'],);});});diff --git a/src/features/ChatInput/ControlBar/useSandboxMode.ts b/src/features/ChatInput/ControlBar/useSandboxMode.tsnew file mode 100644index 00000000000..fcad0d4a53e--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxMode.ts@@ -0,0 +1,83 @@+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`.+ */+export const useSandboxMode = (agentId: string) => {+ const topicId = useChatStore((s) => s.activeTopicId);+ const topicInstanceId = useChatStore(+ (s) => topicSelectors.currentTopicMetadata(s)?.sandboxInstanceId,+ );+ const topicMode = useChatStore((s) => topicSelectors.currentTopicMetadata(s)?.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/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.tsnew file mode 100644index 00000000000..f0b28795e43--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts@@ -0,0 +1,83 @@+import { isDesktop } from '@lobechat/const';+import useSWR from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { sandboxStorageService } from '@/services/sandboxStorage';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++/**+ * What the composer should show where the sandbox working directory goes:+ *+ * - `hidden` โ the run does not use the cloud sandbox, or the user has not+ * opted into the experiment. Nothing is rendered; a switch the user never+ * flipped should not start advertising itself in their composer.+ * - `upgrade` โ opted in, but this account has no persistent workspace.+ * - `ready` โ opted in and entitled.+ */+export type SandboxStorageAccess = 'hidden' | 'ready' | 'upgrade';++export interface SandboxStorageAccessResult {+ /** Soft storage quota of the workspace, once known. */+ quotaBytes: number | null;+ status: SandboxStorageAccess;+}++/**+ * Whether this agent's runs touch the cloud sandbox at all. A run bound to a+ * device or the local machine has its own working directory and its own picker;+ * showing a second one for a sandbox it never starts would be noise at best and+ * a lie about where files land at worst.+ */+const useRunsInSandbox = (agentId: string): boolean => {+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);++ return (+ resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ deviceRoutingAvailable,+ isHetero,+ workspaceScoped,+ }) === 'sandbox'+ );+};++/**+ * The entitlement is deliberately NOT derived on the client from a plan: it is+ * resolved and signed server-side, and asking the server is the only way to see+ * the same answer the sandbox will act on. The lab flag is the cheap local half,+ * so the request is not made at all until the user has opted in.+ */+export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessResult => {+ const labEnabled = useUserStore(labPreferSelectors.enablePersistentSandbox);+ const runsInSandbox = useRunsInSandbox(agentId);+ const workspaceId = useActiveWorkspaceId();+ const shouldAsk = labEnabled && runsInSandbox;++ // Keyed by workspace, because the server resolves the entitlement from the+ // active one. A single global key with focus revalidation off would hand the+ // previous workspace's answer and quota to the next one until a reload โ+ // offering persistence where there is none, or hiding one there is.+ const { data } = useSWR(+ shouldAsk ? ['sandbox-storage-entitlement', workspaceId ?? ''] : null,+ () => sandboxStorageService.getEntitlement(),+ { revalidateOnFocus: false },+ );++ if (!shouldAsk) return { quotaBytes: null, status: 'hidden' };+ // Until the answer arrives, show nothing rather than flashing an upgrade+ // prompt at a user who turns out to be entitled.+ if (!data) return { quotaBytes: null, status: 'hidden' };++ return {+ quotaBytes: data.quotaBytes,+ status: data.entitled ? 'ready' : 'upgrade',+ };+};diff --git a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts b/src/features/ChatInput/ControlBar/useWorkspaceSurface.tsindex 4aedf77f635..15fa97f2d16 100644--- a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts+++ b/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts@@ -8,14 +8,23 @@ import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';/**- * Which workspace control sits next to the device switcher:+ * Which workspace controls sit next to the device switcher, in order:** - `workingDirectory` โ directory picker + git status, for a run on this* machine or on a bound device* - `cloudRepo` โ cloud repo switcher (web has no local filesystem)- * - `undefined` โ nothing; the run has no browsable workspace here+ * - `sandbox` โ the cloud sandbox's own working directory: a throwaway+ * box or an environment instance+ *+ * An empty list means the run has no browsable workspace here. One resolver+ * for the whole slot, so what may appear together is decided in one place: the+ * sandbox case used to render outside this and gate itself, which left "these+ * never both appear" as a claim about two independent conditions rather than+ * something the shape of the code enforces. The one pair that does appear+ * together is a heterogeneous run in the cloud sandbox โ which repository, and+ * which instance it runs in, are two different questions.*/-export type WorkspaceSurface = 'cloudRepo' | 'workingDirectory' | undefined;+export type WorkspaceSurface = 'cloudRepo' | 'sandbox' | 'workingDirectory';export interface ResolveWorkspaceSurfaceParams {/** The EFFECTIVE config โ shared row merged with this member's device override. */@@ -37,7 +46,7 @@ export const resolveWorkspaceSurface = ({deviceRoutingAvailable,isHetero,workspaceScoped,-}: ResolveWorkspaceSurfaceParams): WorkspaceSurface => {+}: ResolveWorkspaceSurfaceParams): WorkspaceSurface[] => {const effectiveTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable,deviceRoutingAvailable,@@ -46,23 +55,40 @@ export const resolveWorkspaceSurface = ({});// Remote device runs get the device-scoped picker, whatever else is set.- if (effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId) return 'workingDirectory';+ if (effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId) return ['workingDirectory'];// Web has no local filesystem โ cloud / heterogeneous agents browse the repo// through the cloud repo switcher instead.if (!clientExecutionAvailable) {- return isHetero || alwaysShowWorkspace ? 'cloudRepo' : undefined;+ // A heterogeneous run in the cloud sandbox gets both: the repository it+ // works on, and the instance it keeps its files in. The repo switcher comes+ // first because it was there first. A forced-on workspace that is not a+ // sandbox run has only the repository to talk about.+ if (isHetero || alwaysShowWorkspace) {+ return effectiveTarget === 'sandbox' ? ['cloudRepo', 'sandbox'] : ['cloudRepo'];+ }++ return effectiveTarget === 'sandbox' ? ['sandbox'] : [];}// Desktop: local working directory + git branch / diff / PR. Shown when the// run is local, or always for heterogeneous agents (they always have a cwd).- if (alwaysShowWorkspace || effectiveTarget === 'local') return 'workingDirectory';+ if (alwaysShowWorkspace || effectiveTarget === 'local') return ['workingDirectory'];++ // Last, so no run that already has a surface loses it: a sandbox target is+ // also what a web `local` pick coerces to. This claims only the case that had+ // nothing โ a plain run in the cloud sandbox, whose working directory is the+ // instance it runs in.+ //+ // Whether the member may actually use one (lab flag, entitlement) is the+ // section's own business; this resolver answers about targets.+ if (effectiveTarget === 'sandbox') return ['sandbox'];- return undefined;+ return [];};/**- * The workspace surface for an agent, resolved from the EFFECTIVE execution+ * The workspace surfaces for an agent, resolved from the EFFECTIVE execution* target (shared row + this member's per-user device override).** Deliberately not `chatConfigByIdSelectors.getRuntimeModeById`: that store@@ -74,7 +100,7 @@ export const resolveWorkspaceSurface = ({export const useWorkspaceSurface = (agentId: string,alwaysShowWorkspace = false,-): WorkspaceSurface => {+): WorkspaceSurface[] => {const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);diff --git a/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.tsnew file mode 100644index 00000000000..5eb96f900d6--- /dev/null+++ b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts@@ -0,0 +1,38 @@+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * The composer's working-directory chip โ for a run on a machine and for one in+ * the cloud sandbox. One declaration, because the two stand in the same slot+ * and are read as one control: a second copy drifts (a darker hover here, a+ * wider gap there) into looking like a different kind of thing.+ */+export const workingDirectoryChipStyles = createStaticStyles(({ css }) => ({+ chip: css`+ cursor: pointer;++ display: flex;+ flex: none;+ gap: 6px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 4px;+ border-radius: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ white-space: nowrap;++ transition: background 0.2s;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ label: css`+ overflow: hidden;+ max-width: 140px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));diff --git a/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsxindex 344bf485103..60de058102a 100644--- a/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/fileContextMenu.tsx@@ -41,6 +41,13 @@ export interface FileMenuEnv {/** The in-app terminal is available (desktop, local workspace). */canUseTerminal: boolean;isRemote: boolean;+ /**+ * The tree can be read but not changed. True for a persistent sandbox+ * instance: its files live in the execution plane, and the mutation helpers+ * here only speak to the local or device filesystem โ offering New or Trash+ * would act on the wrong machine, or fail outright on web.+ */+ readOnly?: boolean;/** Platform name of the trash, already localized ("Trash" / "Recycle Bin"). */trashName: string;}@@ -127,6 +134,7 @@ export const buildFileContextMenu = (} as Item;};const local = !env.isRemote;+ const writable = !env.readOnly;const copyPathItem = item('copy-absolute-path',@@ -136,15 +144,18 @@ export const buildFileContextMenu = (const pasteItem = item('paste', 'paste', t('workingPanel.files.actions.paste'), {disabled: !env.canPaste,} as Partial<Item>);- const newItems = [- item('new-file', 'newFile', t('workingPanel.files.actions.newFile')),- item('new-folder', 'newFolder', t('workingPanel.files.actions.newFolder')),- ];+ const pasteItems = writable ? [pasteItem] : [];+ const newItems = writable+ ? [+ item('new-file', 'newFile', t('workingPanel.files.actions.newFile')),+ item('new-folder', 'newFolder', t('workingPanel.files.actions.newFolder')),+ ]+ : [];if (target.kind === 'root') {return joinGroups([newItems,- [pasteItem],+ pasteItems,[item('refresh', 'refresh', t('workingPanel.files.actions.refresh')),item('collapse-all', 'collapseAll', t('workingPanel.files.collapseAll')),@@ -203,23 +214,27 @@ export const buildFileContextMenu = (return joinGroups([openGroup,systemGroup,- [- item('cut', 'cut', t('workingPanel.files.actions.cut')),- item('copy', 'copy', t('workingPanel.files.actions.copy')),- pasteItem,- item('duplicate', 'duplicate', t('workingPanel.files.actions.duplicate')),- ],+ writable+ ? [+ item('cut', 'cut', t('workingPanel.files.actions.cut')),+ item('copy', 'copy', t('workingPanel.files.actions.copy')),+ pasteItem,+ item('duplicate', 'duplicate', t('workingPanel.files.actions.duplicate')),+ ]+ : [],pathItems,- [- item('rename', 'rename', t('workingPanel.files.actions.rename')),- item(- 'trash',- 'trash',- t('workingPanel.files.actions.moveToTrash', { trash: env.trashName }),- {- danger: true,- } as Partial<Item>,- ),- ],+ writable+ ? [+ item('rename', 'rename', t('workingPanel.files.actions.rename')),+ item(+ 'trash',+ 'trash',+ t('workingPanel.files.actions.moveToTrash', { trash: env.trashName }),+ {+ danger: true,+ } as Partial<Item>,+ ),+ ]+ : [],]);};diff --git a/src/features/Conversation/WorkingSidebar/Files/index.tsx b/src/features/Conversation/WorkingSidebar/Files/index.tsxindex fca0372817b..625acd032a8 100644--- a/src/features/Conversation/WorkingSidebar/Files/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Files/index.tsx@@ -11,6 +11,7 @@ import {EllipsisIcon,FileIcon,FilePlusIcon,+ FileWarningIcon,FolderPlusIcon,FolderTreeIcon,FoldVerticalIcon,@@ -25,6 +26,7 @@ import { useTranslation } from 'react-i18next';import type { ExplorerTreeNode } from '@/features/ExplorerTree';import { ExplorerTree, getExplorerTreeStyleVars } from '@/features/ExplorerTree';import type { ExplorerTreeHandle } from '@/features/ExplorerTree/types';+import { useClientDataSWR } from '@/libs/swr';import { projectFileService } from '@/services/projectFile';import { useGlobalStore } from '@/store/global';@@ -45,6 +47,16 @@ interface FilesProps {* hidden for remote โ there's no local filesystem to act on.*/deviceId?: string;+ /**+ * Serves the tree from a sandbox INSTANCE, with no conversation involved โ+ * the environment panel browsing an instance nobody is talking to.+ */+ sandboxInstanceId?: string;+ /**+ * Serves the tree from the cloud sandbox's workspace instead of a machine.+ * The topic names the warm session the read goes through; it is not a scope.+ */+ sandboxTopicId?: string;workingDirectory: string;}@@ -190,382 +202,418 @@ const FilesSearchBar = memo<FilesSearchBarProps>(({ onClose, onDebouncedChange }FilesSearchBar.displayName = 'FilesSearchBar';-const Files = memo<FilesProps>(({ deviceId, workingDirectory }) => {- const { t } = useTranslation('chat');- const { data, isLoading } = useProjectFiles(deviceId, workingDirectory);- const { data: gitFiles } = useGitWorkingTreeFiles(- deviceId,- workingDirectory,- data?.source === 'git',- );- const projectSource = data?.source;- const projectRoot = data?.root ?? workingDirectory;-- const entries = useMemo(() => data?.entries ?? [], [data]);- const [viewMode, setViewMode] = useState<FileViewMode>('project');- const [hideIgnored, setHideIgnored] = useState(false);- const [searchExpanded, setSearchExpanded] = useState(false);- const [debouncedQuery, setDebouncedQuery] = useState('');- const [searchEntries, setSearchEntries] = useState<ProjectFileIndexEntry[] | undefined>();- const [isSearching, setIsSearching] = useState(false);- const [expandedIds, setExpandedIds] = useState<string[]>([]);- const projectRootName = getProjectRootName(projectRoot);- const normalizedDebouncedQuery = debouncedQuery.trim();- const isFiltering = normalizedDebouncedQuery.length > 0;- const changedOnly = viewMode === 'changes';- const hasDisplayFilter = isFiltering || changedOnly || hideIgnored;- const workingTreeGitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);- const dirtyFilePaths = useMemo(- () => new Set(workingTreeGitStatus.map((entry) => entry.path)),- [workingTreeGitStatus],- );- // The index delivers fully git-ignored folders as childless collapsed rows;- // their children stream in here as the user expands them.- const {- children: collapsedChildren,- invalidate: invalidateCollapsedChildren,- truncatedCount,- } = useCollapsedDirectoryChildren({- deviceId,- entries,- expandedIds,- projectRoot,- });- const displayEntries = useMemo(() => {- const indexedEntries = isFiltering ? (searchEntries ?? []) : [...entries, ...collapsedChildren];- const entriesWithDeleted = mergeMissingDeletedEntries(- indexedEntries,- isFiltering ? [] : (gitFiles?.deleted ?? []),- projectRoot,+const Files = memo<FilesProps>(+ ({ deviceId, sandboxInstanceId, sandboxTopicId, workingDirectory }) => {+ const { t } = useTranslation('chat');+ // Nothing here runs on this machine's filesystem: a remote device and the+ // sandbox both answer over the network, and neither can be handed to Electron+ // to reveal in a file manager.+ const isSandbox = !!sandboxTopicId || !!sandboxInstanceId;+ const { data, error, isLoading } = useProjectFiles(deviceId, workingDirectory, {+ instanceId: sandboxInstanceId,+ topicId: sandboxTopicId,+ });+ const { data: gitFiles } = useGitWorkingTreeFiles(+ deviceId,+ workingDirectory,+ data?.source === 'git',);- const visibleEntries = entriesWithDeleted.filter((entry) => !isExcludedProjectFileEntry(entry));-- return filterProjectFileEntries(visibleEntries, dirtyFilePaths, {- changedOnly,- hideIgnored,+ const projectSource = data?.source;+ const projectRoot = data?.root ?? workingDirectory;++ const entries = useMemo(() => data?.entries ?? [], [data]);+ const [viewMode, setViewMode] = useState<FileViewMode>('project');+ const [hideIgnored, setHideIgnored] = useState(false);+ const [searchExpanded, setSearchExpanded] = useState(false);+ const [debouncedQuery, setDebouncedQuery] = useState('');+ const [expandedIds, setExpandedIds] = useState<string[]>([]);+ const projectRootName = getProjectRootName(projectRoot);+ const normalizedDebouncedQuery = debouncedQuery.trim();+ const isFiltering = normalizedDebouncedQuery.length > 0;+ const changedOnly = viewMode === 'changes';+ const hasDisplayFilter = isFiltering || changedOnly || hideIgnored;+ const workingTreeGitStatus = useMemo(() => buildGitStatusEntries(gitFiles), [gitFiles]);+ const dirtyFilePaths = useMemo(+ () => new Set(workingTreeGitStatus.map((entry) => entry.path)),+ [workingTreeGitStatus],+ );+ // The index delivers fully git-ignored folders as childless collapsed rows;+ // their children stream in here as the user expands them.+ const {+ children: collapsedChildren,+ invalidate: invalidateCollapsedChildren,+ truncatedCount,+ } = useCollapsedDirectoryChildren({+ deviceId,+ entries,+ expandedIds,+ projectRoot,});- }, [- changedOnly,- collapsedChildren,- dirtyFilePaths,- entries,- gitFiles?.deleted,- hideIgnored,- isFiltering,- projectRoot,- searchEntries,- ]);- const nodes = useMemo(- () => buildTreeNodes(displayEntries, projectRootName),- [displayEntries, projectRootName],- );- const gitStatus = useMemo(- () =>- prefixGitStatusPaths(- [...buildIgnoredGitStatusEntries(displayEntries), ...workingTreeGitStatus],- projectRootName,- ),- [displayEntries, projectRootName, workingTreeGitStatus],- );- // Pre-expand top-level directories so the user sees something useful on first- // paint without having to click through every folder.- const defaultExpandedIds = useMemo(- () =>- nodes- .filter(- (node) =>- node.id === PROJECT_ROOT_NODE_ID || (node.isFolder && (isFiltering || changedOnly)),- )- .map((node) => node.id),- [changedOnly, isFiltering, nodes],- );- const treeStyleVars = useMemo(- () => getExplorerTreeStyleVars({ reserveChevronSlot: nodes.some((node) => node.isFolder) }),- [nodes],- );-- useEffect(() => {- setViewMode('project');- }, [deviceId, workingDirectory]);-- useEffect(() => {- if (projectSource && projectSource !== 'git') setViewMode('project');- }, [projectSource]);-- useEffect(() => {- if (!normalizedDebouncedQuery) {- setIsSearching(false);- setSearchEntries(undefined);- return;- }-- let cancelled = false;- setIsSearching(true);- setSearchEntries(undefined);+ // The sandbox index arrives whole, so matching it here costs one pass and+ // needs no third search transport. Matching on the path, not the name,+ // keeps `reports/q3` finding the file inside `reports`.+ const sandboxMatches = useMemo(() => {+ if (!isSandbox || !normalizedDebouncedQuery) return undefined;+ const needle = normalizedDebouncedQuery.toLowerCase();++ return entries+ .filter((entry) => !entry.isDirectory && entry.relativePath.toLowerCase().includes(needle))+ .slice(0, PROJECT_FILE_TREE_SEARCH_LIMIT);+ }, [entries, isSandbox, normalizedDebouncedQuery]);++ // Everything else searches over the wire. Through SWR rather than an+ // effect, so the query is deduped and cached โ and, more to the point, so+ // it stops re-firing every time the file index refreshes, which an effect+ // reading `entries` did on each poll.+ const { data: remoteMatches, isLoading: isSearchingRemote } = useClientDataSWR(+ isSandbox || !normalizedDebouncedQuery+ ? null+ : [+ 'project-file-search',+ deviceId,+ workingDirectory,+ normalizedDebouncedQuery,+ changedOnly,+ hideIgnored,+ ],+ () =>+ projectFileService+ .searchProjectFiles({+ changedOnly,+ deviceId,+ excludeIgnored: hideIgnored,+ limit: PROJECT_FILE_TREE_SEARCH_LIMIT,+ query: normalizedDebouncedQuery,+ scope: workingDirectory,+ })+ .then((result) => result?.entries ?? [])+ .catch((error) => {+ console.error('[Files] Failed to search project files:', error);+ return [] as ProjectFileIndexEntry[];+ }),+ );- void Promise.resolve(- projectFileService.searchProjectFiles({+ const searchEntries = isSandbox ? sandboxMatches : remoteMatches;+ const isSearching = !isSandbox && !!normalizedDebouncedQuery && isSearchingRemote;++ const displayEntries = useMemo(() => {+ const indexedEntries = isFiltering+ ? (searchEntries ?? [])+ : [...entries, ...collapsedChildren];+ const entriesWithDeleted = mergeMissingDeletedEntries(+ indexedEntries,+ isFiltering ? [] : (gitFiles?.deleted ?? []),+ projectRoot,+ );+ const visibleEntries = entriesWithDeleted.filter(+ (entry) => !isExcludedProjectFileEntry(entry),+ );++ return filterProjectFileEntries(visibleEntries, dirtyFilePaths, {changedOnly,- deviceId,- excludeIgnored: hideIgnored,- limit: PROJECT_FILE_TREE_SEARCH_LIMIT,- query: normalizedDebouncedQuery,- scope: workingDirectory,- }),- )- .then((result) => {- if (cancelled) return;- setSearchEntries(result?.entries ?? []);- })- .catch((error) => {- if (cancelled) return;- console.error('[Files] Failed to search project files:', error);- setSearchEntries([]);- })- .finally(() => {- if (!cancelled) setIsSearching(false);+ hideIgnored,});+ }, [+ changedOnly,+ collapsedChildren,+ dirtyFilePaths,+ entries,+ gitFiles?.deleted,+ hideIgnored,+ isFiltering,+ projectRoot,+ searchEntries,+ ]);+ const nodes = useMemo(+ () => buildTreeNodes(displayEntries, projectRootName),+ [displayEntries, projectRootName],+ );+ const gitStatus = useMemo(+ () =>+ prefixGitStatusPaths(+ [...buildIgnoredGitStatusEntries(displayEntries), ...workingTreeGitStatus],+ projectRootName,+ ),+ [displayEntries, projectRootName, workingTreeGitStatus],+ );+ // Pre-expand top-level directories so the user sees something useful on first+ // paint without having to click through every folder.+ const defaultExpandedIds = useMemo(+ () =>+ nodes+ .filter(+ (node) =>+ node.id === PROJECT_ROOT_NODE_ID || (node.isFolder && (isFiltering || changedOnly)),+ )+ .map((node) => node.id),+ [changedOnly, isFiltering, nodes],+ );+ const treeStyleVars = useMemo(+ () => getExplorerTreeStyleVars({ reserveChevronSlot: nodes.some((node) => node.isFolder) }),+ [nodes],+ );- return () => {- cancelled = true;- };- }, [changedOnly, deviceId, hideIgnored, normalizedDebouncedQuery, workingDirectory]);-- // Skip resyncs when defaultExpandedIds is structurally unchanged so the user's expansions survive re-renders.- const prevDefaultRef = useRef<string[]>([]);- useEffect(() => {- const next = defaultExpandedIds.join('\0');- const prev = prevDefaultRef.current.join('\0');- if (next === prev) return;- prevDefaultRef.current = defaultExpandedIds;- setExpandedIds(defaultExpandedIds);- }, [defaultExpandedIds]);-- const treeRef = useRef<ExplorerTreeHandle>(null);-- const handleCollapseAll = useCallback(() => {- treeRef.current?.setExpanded([]);- setExpandedIds([]);- }, []);-- const viewItems = useMemo(- () => [- {- extra: viewMode === 'project' ? <CheckIcon size={14} /> : undefined,- icon: <FolderTreeIcon size={14} />,- key: 'project',- label: t('workingPanel.files.views.project'),- onClick: () => setViewMode('project'),- },- {- disabled: data?.source !== 'git',- extra: viewMode === 'changes' ? <CheckIcon size={14} /> : undefined,- icon: <GitCompareArrowsIcon size={14} />,- key: 'changes',- label: t('workingPanel.files.views.changes'),- onClick: () => setViewMode('changes'),- },- ],- [data?.source, t, viewMode],- );+ useEffect(() => {+ setViewMode('project');+ }, [deviceId, workingDirectory]);++ useEffect(() => {+ if (projectSource && projectSource !== 'git') setViewMode('project');+ }, [projectSource]);++ // Skip resyncs when defaultExpandedIds is structurally unchanged so the user's expansions survive re-renders.+ const prevDefaultRef = useRef<string[]>([]);+ useEffect(() => {+ const next = defaultExpandedIds.join('\0');+ const prev = prevDefaultRef.current.join('\0');+ if (next === prev) return;+ prevDefaultRef.current = defaultExpandedIds;+ setExpandedIds(defaultExpandedIds);+ }, [defaultExpandedIds]);++ const treeRef = useRef<ExplorerTreeHandle>(null);++ const handleCollapseAll = useCallback(() => {+ treeRef.current?.setExpanded([]);+ setExpandedIds([]);+ }, []);++ const viewItems = useMemo(+ () => [+ {+ extra: viewMode === 'project' ? <CheckIcon size={14} /> : undefined,+ icon: <FolderTreeIcon size={14} />,+ key: 'project',+ label: t('workingPanel.files.views.project'),+ onClick: () => setViewMode('project'),+ },+ {+ disabled: data?.source !== 'git',+ extra: viewMode === 'changes' ? <CheckIcon size={14} /> : undefined,+ icon: <GitCompareArrowsIcon size={14} />,+ key: 'changes',+ label: t('workingPanel.files.views.changes'),+ onClick: () => setViewMode('changes'),+ },+ ],+ [data?.source, t, viewMode],+ );- useEffect(() => {- if (!isFiltering) return;- treeRef.current?.setExpanded(defaultExpandedIds);- }, [defaultExpandedIds, isFiltering]);+ useEffect(() => {+ if (!isFiltering) return;+ treeRef.current?.setExpanded(defaultExpandedIds);+ }, [defaultExpandedIds, isFiltering]);++ const revealRequest = useGlobalStore((s) => s.status.workingSidebarRevealRequest);++ useEffect(() => {+ if (!revealRequest) return;+ const { path, nonce: _nonce } = revealRequest;++ const nodeIds = new Set(nodes.map((n) => n.id));+ if (!nodeIds.has(path)) return;++ const ancestors = [PROJECT_ROOT_NODE_ID, ...getAncestorIds(path)];+ const nextExpanded = Array.from(new Set([...expandedIds, ...ancestors]));+ treeRef.current?.setExpanded(nextExpanded);+ treeRef.current?.select(path);+ treeRef.current?.focus(path);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [revealRequest?.nonce, nodes]);++ const clearDisplayFilter = useCallback(() => {+ setSearchExpanded(false);+ setDebouncedQuery('');+ setViewMode('project');+ setHideIgnored(false);+ }, []);+ const knownEntries = useMemo(+ () => [...entries, ...collapsedChildren],+ [collapsedChildren, entries],+ );+ const deletedPaths = useMemo(() => new Set(gitFiles?.deleted ?? []), [gitFiles?.deleted]);+ const actions = useFileTreeActions({+ deletedPaths,+ deviceId,+ dirtyFilePaths,+ expandedIds,+ hasDisplayFilter,+ invalidateCollapsedChildren,+ knownEntries,+ nodes,+ onClearDisplayFilter: clearDisplayFilter,+ onCollapseAll: handleCollapseAll,+ projectRoot,+ sandboxInstanceId,+ sandboxTopicId,+ treeRef,+ workingDirectory,+ });- const revealRequest = useGlobalStore((s) => s.status.workingSidebarRevealRequest);+ // Tree-level actions live behind "โฆ" so the header keeps room: creating at+ // the project root, refresh, then the ignored-files filter.+ const moreItems = useMemo(+ () => [+ // Absent for a read-only tree (a persistent sandbox instance), whose+ // files the mutation helpers cannot reach.+ ...(actions.startCreateFromHeader+ ? [+ {+ icon: <FilePlusIcon size={14} />,+ key: 'new-file',+ label: t('workingPanel.files.actions.newFile'),+ onClick: () => actions.startCreateFromHeader?.('file'),+ },+ {+ icon: <FolderPlusIcon size={14} />,+ key: 'new-folder',+ label: t('workingPanel.files.actions.newFolder'),+ onClick: () => actions.startCreateFromHeader?.('folder'),+ },+ { key: 'divider-refresh', type: 'divider' as const },+ ]+ : []),+ {+ disabled: actions.refreshing,+ icon: <RotateCwIcon size={14} />,+ key: 'refresh',+ label: t('workingPanel.files.actions.refresh'),+ onClick: () => void actions.refresh(),+ },+ { key: 'divider-filters', type: 'divider' as const },+ {+ checked: hideIgnored,+ key: 'hide-ignored',+ label: t('workingPanel.files.filters.hideIgnored'),+ onCheckedChange: setHideIgnored,+ type: 'checkbox' as const,+ },+ ],+ [actions, hideIgnored, t],+ );- useEffect(() => {- if (!revealRequest) return;- const { path, nonce: _nonce } = revealRequest;-- const nodeIds = new Set(nodes.map((n) => n.id));- if (!nodeIds.has(path)) return;-- const ancestors = [PROJECT_ROOT_NODE_ID, ...getAncestorIds(path)];- const nextExpanded = Array.from(new Set([...expandedIds, ...ancestors]));- treeRef.current?.setExpanded(nextExpanded);- treeRef.current?.select(path);- treeRef.current?.focus(path);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [revealRequest?.nonce, nodes]);-- const clearDisplayFilter = useCallback(() => {- setSearchExpanded(false);- setDebouncedQuery('');- setViewMode('project');- setHideIgnored(false);- }, []);- const knownEntries = useMemo(- () => [...entries, ...collapsedChildren],- [collapsedChildren, entries],- );- const deletedPaths = useMemo(() => new Set(gitFiles?.deleted ?? []), [gitFiles?.deleted]);- const actions = useFileTreeActions({- deletedPaths,- deviceId,- dirtyFilePaths,- expandedIds,- hasDisplayFilter,- invalidateCollapsedChildren,- knownEntries,- nodes,- onClearDisplayFilter: clearDisplayFilter,- onCollapseAll: handleCollapseAll,- projectRoot,- treeRef,- workingDirectory,- });-- // Tree-level actions live behind "โฆ" so the header keeps room: creating at- // the project root, refresh, then the ignored-files filter.- const moreItems = useMemo(- () => [- {- icon: <FilePlusIcon size={14} />,- key: 'new-file',- label: t('workingPanel.files.actions.newFile'),- onClick: () => actions.startCreateFromHeader('file'),- },- {- icon: <FolderPlusIcon size={14} />,- key: 'new-folder',- label: t('workingPanel.files.actions.newFolder'),- onClick: () => actions.startCreateFromHeader('folder'),- },- { key: 'divider-refresh', type: 'divider' as const },- {- disabled: actions.refreshing,- icon: <RotateCwIcon size={14} />,- key: 'refresh',- label: t('workingPanel.files.actions.refresh'),- onClick: () => void actions.refresh(),- },- { key: 'divider-filters', type: 'divider' as const },- {- checked: hideIgnored,- key: 'hide-ignored',- label: t('workingPanel.files.filters.hideIgnored'),- onCheckedChange: setHideIgnored,- type: 'checkbox' as const,- },- ],- [actions, hideIgnored, t],- );+ const isEmpty = displayEntries.length === 0;- const isEmpty = displayEntries.length === 0;+ if (!data && isLoading) {+ return (+ <Center flex={1}>+ <Spin size="large" />+ </Center>+ );+ }- if (!data && isLoading) {return (- <Center flex={1}>- <Spin size="large" />- </Center>- );- }-- return (- <Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>- <div className={styles.subheader}>- {searchExpanded ? (- <div className={styles.search}>- <FilesSearchBar- onClose={() => setSearchExpanded(false)}- onDebouncedChange={setDebouncedQuery}+ <Flexbox height={'100%'} style={{ overflow: 'hidden' }} width={'100%'}>+ <div className={styles.subheader}>+ {searchExpanded ? (+ <div className={styles.search}>+ <FilesSearchBar+ onClose={() => setSearchExpanded(false)}+ onDebouncedChange={setDebouncedQuery}+ />+ </div>+ ) : (+ <>+ <DropdownMenu items={viewItems} placement={'bottomLeft'}>+ <Button+ icon={viewMode === 'project' ? FolderTreeIcon : GitCompareArrowsIcon}+ size={'small'}+ style={{ maxWidth: 'calc(100% - 84px)' }}+ title={t('workingPanel.files.views.title')}+ type={'text'}+ >+ {t(+ viewMode === 'project'+ ? 'workingPanel.files.views.project'+ : 'workingPanel.files.views.changes',+ )}+ <ChevronDownIcon size={12} />+ </Button>+ </DropdownMenu>+ <div style={{ flex: 1 }} />+ </>+ )}+ {!searchExpanded && (+ <ActionIcon+ icon={SearchIcon}+ size={'small'}+ title={t('workingPanel.files.search')}+ onClick={() => setSearchExpanded(true)}/>- </div>- ) : (- <>- <DropdownMenu items={viewItems} placement={'bottomLeft'}>- <Button- icon={viewMode === 'project' ? FolderTreeIcon : GitCompareArrowsIcon}- size={'small'}- style={{ maxWidth: 'calc(100% - 84px)' }}- title={t('workingPanel.files.views.title')}- type={'text'}- >- {t(- viewMode === 'project'- ? 'workingPanel.files.views.project'- : 'workingPanel.files.views.changes',- )}- <ChevronDownIcon size={12} />- </Button>- </DropdownMenu>- <div style={{ flex: 1 }} />- </>- )}- {!searchExpanded && (- <ActionIcon- icon={SearchIcon}- size={'small'}- title={t('workingPanel.files.search')}- onClick={() => setSearchExpanded(true)}- />- )}- <ActionIcon- disabled={nodes.length === 0}- icon={FoldVerticalIcon}- size={'small'}- title={t('workingPanel.files.collapseAll')}- onClick={handleCollapseAll}- />- <DropdownMenu items={moreItems} placement={'bottomRight'}>+ )}<ActionIcon- active={hideIgnored}- icon={EllipsisIcon}- loading={actions.refreshing}+ disabled={nodes.length === 0}+ icon={FoldVerticalIcon}size={'small'}- title={t('workingPanel.files.actions.more')}- />- </DropdownMenu>- </div>- {isEmpty && isFiltering && isSearching ? (- <Center flex={1}>- <Spin size="large" />- </Center>- ) : isEmpty && !actions.pendingCreate ? (- <Center flex={1} gap={8} paddingBlock={24}>- <Empty- icon={FileIcon}- description={t(- hasDisplayFilter ? 'workingPanel.files.noSearchResults' : 'workingPanel.files.empty',- )}- />- </Center>- ) : (- <div className={styles.tree} style={treeStyleVars}>- <ExplorerTree<ProjectFileIndexEntry>- iconsColored- canDrag={actions.canDrag}- canDrop={actions.canDrop}- canRename={actions.canRename}- defaultExpandedIds={defaultExpandedIds}- getBlankContextMenuItems={actions.getBlankContextMenuItems}- getContextMenuItems={actions.getContextMenuItems}- gitStatus={gitStatus}- iconSet="complete"- nodes={nodes}- ref={treeRef}- style={{ height: '100%' }}- unsafeCSS={FILE_TREE_UNSAFE_CSS}- validateName={actions.validateName}- onCommitCreate={actions.onCommitCreate}- onCommitRename={actions.onCommitRename}- onExpandedChange={setExpandedIds}- onMove={actions.onMove}- onNodeClick={actions.handleNodeClick}- onNodeDragStart={actions.handleNodeDragStart}- onTreeKeyDown={actions.handleTreeKeyDown}+ title={t('workingPanel.files.collapseAll')}+ onClick={handleCollapseAll}/>+ <DropdownMenu items={moreItems} placement={'bottomRight'}>+ <ActionIcon+ active={hideIgnored}+ icon={EllipsisIcon}+ loading={actions.refreshing}+ size={'small'}+ title={t('workingPanel.files.actions.more')}+ />+ </DropdownMenu></div>- )}- {truncatedCount > 0 && (- <div className={styles.truncated}>{t('workingPanel.files.truncatedNotice')}</div>- )}- </Flexbox>- );-});+ {isEmpty && isFiltering && isSearching ? (+ <Center flex={1}>+ <Spin size="large" />+ </Center>+ ) : isEmpty && !actions.pendingCreate ? (+ <Center flex={1} gap={8} paddingBlock={24}>+ {/* A failed read and an empty directory look identical once the tree+ is empty, and they are not the same thing to act on: one is+ "nothing here yet", the other is "we could not find out". Saying+ the workspace is empty when the listing failed is the worse of the+ two lies โ it invites the user to conclude their files are gone. */}+ <Empty+ icon={error ? FileWarningIcon : FileIcon}+ description={t(+ error+ ? 'workingPanel.files.unreadable'+ : hasDisplayFilter+ ? 'workingPanel.files.noSearchResults'+ : 'workingPanel.files.empty',+ )}+ />+ </Center>+ ) : (+ <div className={styles.tree} style={treeStyleVars}>+ <ExplorerTree<ProjectFileIndexEntry>+ iconsColored+ canDrag={actions.canDrag}+ canDrop={actions.canDrop}+ canRename={actions.canRename}+ defaultExpandedIds={defaultExpandedIds}+ getBlankContextMenuItems={actions.getBlankContextMenuItems}+ getContextMenuItems={actions.getContextMenuItems}+ gitStatus={gitStatus}+ iconSet="complete"+ nodes={nodes}+ ref={treeRef}+ style={{ height: '100%' }}+ unsafeCSS={FILE_TREE_UNSAFE_CSS}+ validateName={actions.validateName}+ onCommitCreate={actions.onCommitCreate}+ onCommitRename={actions.onCommitRename}+ onExpandedChange={setExpandedIds}+ onMove={actions.onMove}+ onNodeClick={actions.handleNodeClick}+ onNodeDragStart={actions.handleNodeDragStart}+ onTreeKeyDown={actions.handleTreeKeyDown}+ />+ </div>+ )}+ {truncatedCount > 0 && (+ <div className={styles.truncated}>{t('workingPanel.files.truncatedNotice')}</div>+ )}+ </Flexbox>+ );+ },+);Files.displayName = 'AgentWorkingSidebarFiles';diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.tsindex 75b6088691a..8ad61f6c88a 100644--- a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts+++ b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.test.ts@@ -274,11 +274,11 @@ describe('useFileTreeActions โ create', () => {expect(handle.startCreating).toHaveBeenLastCalledWith(PROJECT_ROOT_NODE_ID, 'folder');handle.getSelectedIds.mockReturnValue(['src/app.ts']);- act(() => view.result.current.startCreateFromHeader('file'));+ act(() => view.result.current.startCreateFromHeader!('file'));expect(handle.startCreating).toHaveBeenLastCalledWith('src/', 'file');handle.getSelectedIds.mockReturnValue([]);- act(() => view.result.current.startCreateFromHeader('folder'));+ act(() => view.result.current.startCreateFromHeader!('folder'));expect(handle.startCreating).toHaveBeenLastCalledWith(PROJECT_ROOT_NODE_ID, 'folder');});diff --git a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.tsindex 661e88baaf9..7657fe8dbc4 100644--- a/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts+++ b/src/features/Conversation/WorkingSidebar/Files/useFileTreeActions.ts@@ -39,6 +39,10 @@ interface UseFileTreeActionsParams {onClearDisplayFilter: () => void;onCollapseAll: () => void;projectRoot: string;+ /** Set when the tree is showing a sandbox instance nobody is talking to. */+ sandboxInstanceId?: string;+ /** Set when the tree is showing a cloud sandbox's workspace rather than a disk. */+ sandboxTopicId?: string;treeRef: RefObject<ExplorerTreeHandle | null>;workingDirectory: string;}@@ -77,11 +81,14 @@ export const useFileTreeActions = ({onClearDisplayFilter,onCollapseAll,projectRoot,+ sandboxInstanceId,+ sandboxTopicId,treeRef,workingDirectory,}: UseFileTreeActionsParams) => {const { t } = useTranslation('chat');- const isRemote = !!deviceId;+ const isSandbox = !!sandboxTopicId || !!sandboxInstanceId;+ const isRemote = !!deviceId || isSandbox;const openLocalFile = useChatStore((s) => s.openLocalFile);const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);const { canOfferFile, publishFile } = usePublishWorkspaceHtmlFromFile({@@ -136,9 +143,22 @@ export const useFileTreeActions = ({if (!isRemote) void ops.openInSystem(node.data);return;}- openLocalFile({ deviceId, filePath: node.data.path, workingDirectory: projectRoot });+ // An instance picked before the first message has no topic yet, and the+ // portal reads sandbox files through the topic's session. Opening anyway+ // would give the web preview no source at all and send desktop looking+ // for a local path that is not the instance's โ so say so instead.+ if (sandboxInstanceId && !sandboxTopicId) {+ toast.info(t('workingPanel.files.openNeedsTopic'));+ return;+ }+ openLocalFile({+ deviceId,+ filePath: node.data.path,+ sandboxTopicId,+ workingDirectory: projectRoot,+ });},- [deviceId, isRemote, openLocalFile, ops, projectRoot],+ [deviceId, isRemote, openLocalFile, ops, projectRoot, sandboxInstanceId, sandboxTopicId, t],);const handleNodeClick = useCallback(@@ -278,9 +298,10 @@ export const useFileTreeActions = ({canPublish,canUseTerminal: ops.canUseTerminal,isRemote,+ readOnly: isSandbox,trashName: ops.trashName,}),- [isRemote, ops.canPaste, ops.canUseTerminal, ops.trashName],+ [isRemote, isSandbox, ops.canPaste, ops.canUseTerminal, ops.trashName],);const getBlankContextMenuItems = useCallback(@@ -343,25 +364,29 @@ export const useFileTreeActions = ({);return true;}+ // Every mutating shortcut is off for a read-only tree, for the same+ // reason the menu items are: these helpers reach the local or device+ // filesystem, so Delete on a sandbox row would act on the wrong host+ // rather than on the instance the row names.case 'delete': {- if (entries.length === 0) return false;+ if (isSandbox || entries.length === 0) return false;ops.trash(entries);return true;}case 'copy':case 'cut': {- if (entries.length === 0) return false;+ if (isSandbox || entries.length === 0) return false;ops.putOnClipboard(entries, shortcut);return true;}case 'paste': {- if (!ops.canPaste) return false;+ if (isSandbox || !ops.canPaste) return false;void ops.paste(folderRel(targetFolderId(focusedNode)));return true;}}},- [deletedPaths, expandedIds, isMac, openNode, ops, treeRef],+ [deletedPaths, expandedIds, isMac, isSandbox, openNode, ops, treeRef],);// Header "New" menu: into the selected folder, next to a selected file, or at the root.@@ -373,10 +398,14 @@ export const useFileTreeActions = ({[nodeById, startCreate, treeRef],);+ // A persistent sandbox instance's files live in the execution plane, and+ // every mutation helper below speaks only to the local or device filesystem+ // โ so until they are routed, the tree reads rather than lies about where a+ // rename or a delete would land.return {- canDrag: (node: Node) => !!node.data && !isDeletedNode(node, deletedPaths),- canDrop: ops.canDrop,- canRename: (node: Node) => !!node.data && !isDeletedNode(node, deletedPaths),+ canDrag: (node: Node) => !isSandbox && !!node.data && !isDeletedNode(node, deletedPaths),+ canDrop: (...args: Parameters<typeof ops.canDrop>) => !isSandbox && ops.canDrop(...args),+ canRename: (node: Node) => !isSandbox && !!node.data && !isDeletedNode(node, deletedPaths),getBlankContextMenuItems,getContextMenuItems,handleNodeClick,@@ -388,7 +417,7 @@ export const useFileTreeActions = ({pendingCreate: !!pendingCreate,refresh: ops.refresh,refreshing: ops.refreshing,- startCreateFromHeader,+ startCreateFromHeader: isSandbox ? undefined : startCreateFromHeader,validateName: ops.validateName,};};diff --git a/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts b/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.tsindex 5babfca0939..5655393ca11 100644--- a/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts+++ b/src/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts@@ -1,27 +1,78 @@import { isDesktop } from '@lobechat/const';import type { ProjectFileIndexResult } from '@lobechat/electron-client-ipc';+import { useEffect, useRef } from 'react';import { useClientDataSWR } from '@/libs/swr';import { localFileKeys } from '@/libs/swr/keys';import { projectFileService } from '@/services/projectFile';+import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/selectors';++/**+ * How often the sandbox tree re-reads itself while an agent run is writing+ * into it. The listing asks the session to save its work tree before serving,+ * so a poll costs a walk of what changed โ worth it while a run is producing+ * files, wasteful when nothing is happening, which is why it only runs then.+ */+const SANDBOX_LIVE_REFRESH_INTERVAL = 15 * 1000;/*** Project file tree for a working directory. Transport-agnostic: `fileService`- * dispatches Electron IPC (local) vs `device.getProjectFileIndex` RPC (remote,- * `deviceId` set). Disabled until a `dirPath` is available, and on web (no- * `isDesktop`) until a `deviceId` is too.+ * dispatches Electron IPC (local), `device.getProjectFileIndex` RPC (remote,+ * `deviceId` set), or the cloud sandbox's workspace API (`sandbox` set).+ *+ * Disabled until a directory is available โ for the sandbox that is the+ * workspace root, which is the empty string, so its gate is the source rather+ * than the path. On web without either host there is nothing to read.*/-export const useProjectFiles = (deviceId: string | undefined, dirPath: string | undefined) => {- const enabled = Boolean(dirPath) && (!!deviceId || isDesktop);- const key = enabled ? localFileKeys.projectIndex(deviceId, dirPath!) : null;+export const useProjectFiles = (+ deviceId: string | undefined,+ dirPath: string | undefined,+ sandbox?: { instanceId?: string; topicId?: string },+) => {+ const isSandbox = !!sandbox?.instanceId || !!sandbox?.topicId;+ const enabled = isSandbox ? dirPath !== undefined : Boolean(dirPath) && (!!deviceId || isDesktop);+ // The host is part of the identity: the same path on a device and in the+ // sandbox are different trees, and `undefined` already means "this machine".+ // Keyed by the INSTANCE where there is one โ two conversations running the+ // same instance are looking at one tree, and keying by topic would fetch it+ // twice and let one go stale while the other refreshed.+ const host = isSandbox ? `sandbox:${sandbox?.instanceId ?? sandbox?.topicId}` : deviceId;+ const key = enabled ? localFileKeys.projectIndex(host, dirPath!) : null;- return useClientDataSWR<ProjectFileIndexResult | undefined>(+ // The sandbox tree is a mirror of a directory nobody in this browser is+ // touching: the writer is the agent, on the other side of the network.+ // Refetching on focus alone means a user watching a run in progress sees a+ // tree from before it started, so a run is what makes this tree live.+ const isRunning = useChatStore(operationSelectors.isAgentRuntimeRunning);+ const live = isSandbox && isRunning;++ const swr = useClientDataSWR<ProjectFileIndexResult | undefined>(key,- () => projectFileService.getProjectFileIndex({ deviceId, scope: dirPath! }),+ () =>+ projectFileService.getProjectFileIndex({+ deviceId,+ sandboxInstanceId: sandbox?.instanceId,+ sandboxTopicId: sandbox?.topicId,+ scope: dirPath!,+ }),{focusThrottleInterval: 30 * 1000,+ refreshInterval: live ? SANDBOX_LIVE_REFRESH_INTERVAL : 0,revalidateOnFocus: true,shouldRetryOnError: false,},);++ // The interval stops with the run, so the last writes of a turn can land in+ // the gap between the final poll and the end. One read on the way down is+ // what makes the tree agree with the answer the user is reading.+ const { mutate } = swr;+ const wasLive = useRef(live);+ useEffect(() => {+ if (wasLive.current && !live) mutate();+ wasLive.current = live;+ }, [live, mutate]);++ return swr;};diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 4790e97df41..9daff27e579 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -38,6 +38,7 @@ import {useState,} from 'react';import { useTranslation } from 'react-i18next';+import useSWR from 'swr';import { useBusinessWorkingSidebarTabs } from '@/business/client/features/WorkingSidebarTabs';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';@@ -48,6 +49,7 @@ 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 SkeletonList from '@/features/NavPanel/components/SkeletonList';import { getPortalViewWidth } from '@/features/Portal/portalWidth';import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';@@ -61,6 +63,7 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useLocalStorageState } from '@/hooks/useLocalStorageState';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';+import { sandboxStorageService } from '@/services/sandboxStorage';import { useAgentStore } from '@/store/agent';import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -373,12 +376,60 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })// actions enabled.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.+ const { data: sandboxInstances } = useSWR(+ isSandboxExecution && sandboxInstanceId ? ['sandbox-instance-dir', sandboxInstanceId] : null,+ () => sandboxStorageService.getInstance({ id: sandboxInstanceId! }),+ );+ const sandboxDirectory = sandboxInstances?.workingDirectory ?? '';+ // 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 || sandboxInstances !== undefined;+const filesystemEnvironmentAvailable = isLocalExecution || isDeviceMode;const environmentWorkingDirectory = filesystemEnvironmentAvailable ? workingDirectory : undefined;const environmentRepoType = filesystemEnvironmentAvailable ? repoType : undefined;// Files tab is an agent-mode affordance โ in plain chat mode the working// directory is irrelevant to the user, so hide the tab even when one resolves.- const filesAvailable = !isChatMode && (isLocalExecution || isDeviceMode) && !!workingDirectory;+ // Which directory the tree shows, and therefore whether there is a tree at+ // all. Kept as one value rather than a pair of conditions: the sandbox's root+ // is the empty string, so "has a directory" and "is truthy" part ways here,+ // and the tab's availability has to follow the value it will render.+ // A directory is only showable when something can actually read it: the+ // sandbox through its workspace API, a device or this machine through the+ // filesystem. A topic can carry a path persisted on a desktop the web client+ // has no way to reach, and that path is not a tree โ it is a string.+ // An instance is what makes a sandbox tree addressable. Persistent mode with+ // none picked is the workspace root, which the execution plane can only+ // resolve through a conversation โ so that one still waits for the topic.+ const filesDirectory =+ isSandboxExecution && (sandboxInstanceId || sandboxTopicId)+ ? sandboxDirectoryKnown+ ? sandboxDirectory+ : undefined+ : filesystemEnvironmentAvailable+ ? workingDirectory+ : undefined;+ const filesAvailable = !isChatMode && filesDirectory !== undefined;const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;const snapshotConfig =(topicDeviceId ? topicDeviceId === targetDeviceId : isLocalExecution) &&@@ -1130,7 +1181,12 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth }){filesAvailable && (<Activity mode={showRightPanel && activeTab === 'files' ? 'visible' : 'hidden'}><Flexbox className={styles.pane}>- <Files deviceId={remoteDeviceId} workingDirectory={workingDirectory} />+ <Files+ deviceId={remoteDeviceId}+ sandboxInstanceId={isSandboxExecution ? sandboxInstanceId : undefined}+ sandboxTopicId={sandboxTopicId}+ workingDirectory={filesDirectory}+ /></Flexbox></Activity>)}diff --git a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx b/src/features/EnvironmentManager/CreateEnvironmentModal.tsxnew file mode 100644index 00000000000..aa64d5499cc--- /dev/null+++ b/src/features/EnvironmentManager/CreateEnvironmentModal.tsx@@ -0,0 +1,181 @@+'use client';++import type { EnvironmentVisibility } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import {+ Button,+ confirmModal,+ createModal,+ Input,+ ModalFooter,+ Text,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { t as translate } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';+import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';++import GithubRepositoryPicker, { type GithubRepositorySelection } from './GithubRepositoryPicker';+import { useEnvironmentActions } from './useEnvironmentData';++/**+ * Naming a new environment.+ *+ * 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. The name is the only thing asked for โ everything+ * else about an environment is edited once it exists, where the form can+ * explain what each part does.+ */+interface CreateEnvironmentContentProps {+ visibility?: EnvironmentVisibility;+}++const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(({ visibility }) => {+ const { t } = useTranslation('setting');+ const { close } = useModalContext();+ const actions = useEnvironmentActions();++ 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+ // overwrite it; a suggested one is just a default and follows the pick.+ const [nameIsSuggested, setNameIsSuggested] = useState(true);+ const [repository, setRepository] = useState<GithubRepositorySelection | undefined>();+ const [creating, setCreating] = useState(false);+ // The Enter that confirms an IME candidate reaches `keydown` as an Enter,+ // so a Chinese name would submit the dialog on the keystroke that picked it.+ const { compositionProps, isComposingRef } = useIMECompositionEvent();+ const [error, setError] = useState<string | undefined>();++ const trimmed = name.trim();++ const pickRepository = (selection: GithubRepositorySelection | undefined) => {+ setRepository(selection);+ setError(undefined);+ // Naming a thing that does not exist yet is the harder half of this dialog,+ // so the repository answers it: an environment for a repository is almost+ // always called after it.+ if (nameIsSuggested) setName(selection?.repository ?? '');+ };++ const create = async () => {+ setCreating(true);+ setError(undefined);+ try {+ await actions.createEnvironment({+ // The repository is the environment's one source. Every repository+ // carries the owner GitHub reported for it, so the checkout URL is+ // built from the pair rather than from whichever owner the list was+ // filtered by โ those differ for a repository reached as a collaborator.+ configuration: repository+ ? {+ sources: [+ {+ kind: 'git',+ ref: repository.defaultBranch,+ url: `https://github.com/${repository.owner}/${repository.repository}`,+ },+ ],+ }+ : undefined,+ 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+ // shared list would be a publication nobody asked for.+ visibility,+ });+ close();+ } catch (cause) {+ // The one failure the user can act on is a name already taken, and it is+ // fixed by typing a different one โ so it belongs next to the field+ // rather than in a toast that outlives the dialog.+ setError(+ (cause as { message?: string })?.message === 'DUPLICATE_ENVIRONMENT_NAME'+ ? t('environments.duplicateName')+ : t('environments.createFailed'),+ );+ } finally {+ setCreating(false);+ }+ };++ // Created in the workspace's pool, an environment is published from its+ // first instance on โ and an instance keeps whatever a session leaves in its+ // home directory, credentials included. So creating one there asks the same+ // question publishing one does, with the same explanation, rather than+ // publishing it silently because of which tab happened to be open.+ const submit = () => {+ if (!trimmed || creating) return;+ if (visibility !== 'public') return void create();++ confirmModal({+ content: <VisibilityConfirmContent capturedState variant={'publish'} />,+ okText: t('environments.create'),+ onOk: create,+ title: t('environments.visibility.createPublishedConfirmTitle'),+ });+ };++ return (+ <>+ {/* Repository first, name second. The name is the harder question and the+ repository usually answers it, so asking for the name first makes the+ person invent something they are about to be handed. */}+ <Flexbox gap={12} paddingBlock={8} paddingInline={16}>+ <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />++ <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>+ )}+ </Flexbox>+ </Flexbox>+ <ModalFooter>+ <Button onClick={close}>{t('environments.cancel')}</Button>+ <Button+ disabled={!trimmed}+ loading={creating}+ type={'primary'}+ onClick={() => void submit()}+ >+ {t('environments.create')}+ </Button>+ </ModalFooter>+ </>+ );+});++CreateEnvironmentContent.displayName = 'CreateEnvironmentContent';++export const openCreateEnvironmentModal = (visibility?: EnvironmentVisibility) =>+ createModal({+ content: <CreateEnvironmentContent visibility={visibility} />,+ footer: null,+ maskClosable: true,+ styles: { content: { padding: 0 } },+ title: translate('environments.create', { ns: 'setting' }),+ width: 'min(90vw, 480px)',+ });diff --git a/src/features/EnvironmentManager/CreateInstanceModal.tsx b/src/features/EnvironmentManager/CreateInstanceModal.tsxnew file mode 100644index 00000000000..3b2b4a076d6--- /dev/null+++ b/src/features/EnvironmentManager/CreateInstanceModal.tsx@@ -0,0 +1,235 @@+'use client';++import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';+import { Flexbox } from '@lobehub/ui';+import {+ Button,+ createModal,+ Input,+ ModalFooter,+ Text,+ useModalContext,+} from '@lobehub/ui/base-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;+}++/**+ * 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 }) => {+ 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;+ }++ 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'+ : '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: translate(+ params.instance ? 'environments.instances.rename' : 'environments.instances.add',+ { ns: 'setting' },+ ),+ width: 'min(90vw, 480px)',+ });++/** 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.tsxnew file mode 100644index 00000000000..016ca50e4af--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx@@ -0,0 +1,233 @@+'use client';++import { Github } from '@lobehub/icons';+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { ActionIcon, Avatar, Tabs, Tag, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import {+ ContainerIcon,+ HistoryIcon,+ KeyRoundIcon,+ LayersIcon,+ LockIcon,+ SettingsIcon,+ XIcon,+} from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import EnvironmentForm, { type EnvironmentFormSection } from './EnvironmentForm';+import InstanceSection from './InstanceSection';+import { repositoryPath } from './repository';+import SessionHistorySection from './SessionHistorySection';+import TabPane from './TabPane';+import { useCanEditEnvironment } from './useCanEditEnvironment';+import { type SandboxEnvironment, useEnvironmentActions, useInstances } from './useEnvironmentData';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ padding-block: 16px;+ padding-inline: 20px;+ `,+ header: css`+ padding-block-end: 16px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ /** The same dot the row uses between its facts. */+ metaDivider: css`+ flex: none;++ width: 3px;+ height: 3px;+ border-radius: 50%;++ background: ${cssVar.colorTextQuaternary};+ `,+ iconTile: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+}));++type DetailTab = 'instances' | 'sessions' | EnvironmentFormSection;++interface EnvironmentDetailPanelProps {+ environment: SandboxEnvironment;+ onClose: () => void;+}++/**+ * Everything one environment is, beside the list it was picked from.+ *+ * The list answers which environment; this answers what it holds โ who made it,+ * 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:+ * a setup command is worth reading about one environment and worth nothing when+ * comparing six.+ *+ * Read by id from the list rather than handed a snapshot: the form writes+ * through to the same SWR entry, so a copy taken at open time would go stale+ * the moment someone saved.+ */+const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment, onClose }) => {+ const { t } = useTranslation('setting');+ const actions = useEnvironmentActions();+ const { 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 instances.+ const [tab, setTab] = useState<DetailTab>('instances');++ const repository = repositoryPath(environment.configuration);+ const creator =+ environment.creator?.fullName ||+ environment.creator?.username ||+ t('environments.meta.unknownCreator');+ const instanceCount = (data?.instances ?? []).filter(+ (instance) => instance.environmentId === environment.id,+ ).length;++ return (+ <Flexbox className={styles.container} gap={20}>+ <Flexbox horizontal align={'center'} className={styles.header} gap={12}>+ <span className={styles.iconTile}>+ {repository ? <Github size={18} /> : <Icon icon={ContainerIcon} size={18} />}+ </span>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Text ellipsis weight={600}>+ {environment.name}+ </Text>+ {/* One line of facts under the name, the way the row does it,+ rather than a labelled block of its own below the header: who+ made it and when are context for the name, not fields to+ fill in. The absolute time here, the relative one in the row:+ the list is scanned for "is this recent", the panel is read+ for "when". */}+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <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>+ )}+ <Flexbox horizontal align={'center'} gap={6}>+ {/* Name as the avatar value โ see EnvironmentItem for why `title` alone does not reach the fallback text. */}+ <Avatar avatar={environment.creator?.avatar || creator} size={16} title={creator} />+ <Text fontSize={12} type={'secondary'}>+ {creator}+ </Text>+ </Flexbox>+ <span className={styles.metaDivider} />+ {/* The same relative phrasing as the row, so the panel does not+ answer "when" in a different voice; the exact instant is a+ hover away. */}+ <Tooltip title={new Date(environment.createdAt).toLocaleString()}>+ <Text fontSize={12} type={'secondary'}>+ {t('environments.meta.createdAt', {+ time: dayjs(environment.createdAt).fromNow(),+ })}+ </Text>+ </Tooltip>+ </Flexbox>+ </Flexbox>+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('environments.detail.close')}+ onClick={onClose}+ />+ </Flexbox>++ {/* Said plainly, rather than letting someone discover it by typing into+ a field whose save would be refused. A published environment is one+ you can run in; reshaping it stays with whoever made it. */}+ {!canEdit && (+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={LockIcon} size={14} style={{ color: cssVar.colorTextTertiary }} />+ <Text fontSize={12} type={'secondary'}>+ {t('environments.visibility.readonlyHint')}+ </Text>+ </Flexbox>+ )}++ {/* Instances 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 the first+ two tabs and drops the rest. */}+ <Tabs+ activeKey={tab}+ items={[+ {+ icon: <Icon icon={LayersIcon} size={16} />,+ key: 'instances',+ label: t('environments.instances.title'),+ },+ {+ icon: <Icon icon={HistoryIcon} size={16} />,+ key: 'sessions',+ label: t('environments.sessions.title'),+ },+ ...(canEdit+ ? [+ {+ 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'),+ },+ ]+ : []),+ ]}+ onChange={(key) => setTab(key as DetailTab)}+ />++ {/* One column with no gap: the settings rail is drawn by each of its+ sections and meets the next one's icon exactly, so any space+ between them would show as a break in the line. */}+ <Flexbox>+ {tab === 'instances' && (+ <TabPane desc={t('environments.instances.desc')}>+ <InstanceSection editable={canEdit} environmentId={environment.id} />+ </TabPane>+ )}++ {tab === 'sessions' && (+ <TabPane desc={t('environments.sessions.desc')}>+ <SessionHistorySection environmentId={environment.id} />+ </TabPane>+ )}++ {/* Every field saves itself, so nothing is lost by unmounting the+ form on a tab switch and each tab mounts only what it shows. */}+ {canEdit && (tab === 'variables' || tab === 'settings') && (+ <EnvironmentForm+ environment={environment}+ section={tab}+ onSave={(changes) => actions.updateEnvironment({ ...changes, id: environment.id })}+ />+ )}+ </Flexbox>+ </Flexbox>+ );+});++EnvironmentDetailPanel.displayName = 'EnvironmentDetailPanel';++export default EnvironmentDetailPanel;diff --git a/src/features/EnvironmentManager/EnvironmentForm.tsx b/src/features/EnvironmentManager/EnvironmentForm.tsxnew file mode 100644index 00000000000..a4384a67b05--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentForm.tsx@@ -0,0 +1,408 @@+'use client';++import { Github } from '@lobehub/icons';+import { Flexbox } from '@lobehub/ui';+import { ActionIcon, Button, Switch, Text, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { FolderGit2Icon, HardDriveIcon, 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 EnvironmentVariables from './EnvironmentVariables';+import { describeError } from './errorMessage';+import GithubRepositoryPicker, { type GithubRepositorySelection } from './GithubRepositoryPicker';+import InlineField from './InlineField';+import PanelSection from './PanelSection';+import TabPane from './TabPane';+import type { SandboxEnvironment } from './useEnvironmentData';++const styles = createStaticStyles(({ css }) => ({+ /** The same box every other value sits in; here it holds a repository. */+ box: css`+ display: flex;+ gap: 10px;+ align-items: center;++ min-height: 36px;+ padding-block: 6px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillQuaternary};+ `,+}));++/**+ * Which part of the specification the form is showing. The panel splits it+ * across two tabs; every field saves on its own, so the split is only about+ * what is on screen.+ */+export type EnvironmentFormSection = 'settings' | 'variables';++interface EnvironmentFormProps {+ environment: SandboxEnvironment;+ onSave: (params: {+ configuration?: SandboxEnvironmentSpecification;+ description?: string;+ name?: string;+ }) => Promise<void>;+ 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(+ Object.entries(configuration).filter(([, value]) => {+ if (value === undefined || value === '') return false;+ if (Array.isArray(value)) return value.length > 0;+ if (value && typeof value === 'object') return Object.keys(value).length > 0;+ return true;+ }),+ ) as SandboxEnvironmentSpecification;++/**+ * The branch an environment checks out, picked from the repository's own+ * list. Choosing beats typing here: a branch name is not something anyone+ * remembers exactly, and a typo is a build that fails minutes later.+ *+ * At rest it is the same box every other value sits in, and the list is+ * fetched only once the pencil is clicked โ a hundred branches are not worth+ * a request to show the one that is set. Empty means the repository's default+ * branch, which is what the build checks out when none is named.+ *+ * Falls back to typing when GitHub is not connected, the list could not be+ * read, or the list is only part of the repository's branches โ the branch may+ * still be reachable to the build, and a field that refuses to accept a value+ * would block it for nothing.+ */+const BranchField = memo<{+ onSave: (ref: string) => Promise<void>;+ owner: string;+ repository: string;+ value: string;+}>(({ onSave, owner, repository, value }) => {+ const { t } = useTranslation('setting');+ const [editing, setEditing] = useState(false);+ const { data, error, isLoading } = useSWR(+ editing ? ['sandbox-github-branches', owner, repository] : null,+ () => sandboxStorageService.listGithubBranches({ owner, repository }),+ );++ const canPick = !error && data?.connected !== false && !data?.truncated;++ return (+ <InlineField+ label={t('environments.form.ref')}+ placeholder={t('environments.form.refDefault')}+ select={canPick ? { loading: isLoading, options: data?.branches ?? [] } : undefined}+ value={value}+ onEditingChange={setEditing}+ onSave={onSave}+ />+ );+});++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.+ *+ * 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, 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".+ */+ const saveConfiguration = async (changes: Partial<SandboxEnvironmentSpecification>) => {+ const next = compact({ ...configuration, ...changes });+ await onSave({ configuration: next });+ toast.success(t('environments.form.saved'));+ };++ /** For controls with no confirm step of their own: a switch, a disconnect. */+ const run = async (action: () => Promise<void>) => {+ setBusy(true);+ try {+ await action();+ } catch (error) {+ toast.error(describeError(error, t, t('environments.saveFailed')));+ } finally {+ setBusy(false);+ }+ };++ const source = configuration.sources?.[0];+ const setSource = (next: Partial<{ path: string; ref: string; url: string }> | undefined) =>+ saveConfiguration({+ sources:+ next === undefined+ ? []+ : [+ {+ kind: 'git' as const,+ url: next.url ?? source?.url ?? '',+ ...((next.path ?? source?.path) && { path: next.path ?? source?.path }),+ ...((next.ref ?? source?.ref) && { ref: next.ref ?? source?.ref }),+ },+ ],+ });++ // The picker speaks in owner/name; the specification stores a checkout URL.+ const repositoryPath = source?.url.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '');+ const selection = (() => {+ const [owner, repository] = repositoryPath?.split('/') ?? [];+ return owner && repository ? { defaultBranch: source?.ref, owner, repository } : undefined;+ })();++ const pickRepository = (picked: GithubRepositorySelection | undefined) => {+ if (!picked) return;+ setPickingRepository(false);+ // A repository just chosen keeps whatever folder was set, but takes the+ // new repository's default branch โ the old branch belonged to the old one.+ void run(() =>+ saveConfiguration({+ sources: [+ {+ kind: 'git' as const,+ ...(source?.path && { path: source.path }),+ ...(picked.defaultBranch && { ref: picked.defaultBranch }),+ url: `https://github.com/${picked.owner}/${picked.repository}`,+ },+ ],+ }),+ );+ };++ if (section === 'variables') {+ return (+ /* Said plainly because the shape cannot enforce it: a text field cannot+ tell a region from a token. */+ <TabPane+ desc={+ <>+ {t('environments.form.envHint')} {t('environments.form.appliesOnBuild')}+ </>+ }+ >+ <EnvironmentVariables+ entries={Object.entries(configuration.env ?? {})}+ onSave={(entries) => saveConfiguration({ env: Object.fromEntries(entries) })}+ />+ </TabPane>+ );+ }++ return (+ <Flexbox>+ <PanelSection+ desc={t('environments.form.desc')}+ icon={InfoIcon}+ title={t('environments.form.basics')}+ >+ <InlineField+ required+ label={t('environments.nameLabel')}+ placeholder={t('environments.namePlaceholder')}+ value={environment.name}+ onSave={(name) => onSave({ name })}+ />+ <InlineField+ label={t('environments.form.description')}+ placeholder={t('environments.form.descriptionPlaceholder')}+ value={environment.description ?? ''}+ onSave={(description) => onSave({ description })}+ />+ </PanelSection>++ <PanelSection+ desc={t('environments.form.sourcesHint')}+ icon={FolderGit2Icon}+ title={t('environments.form.sources')}+ notice={+ /* When an edit here reaches an instance, which is the question this+ panel otherwise leaves open. An instance keeps the definition it+ was created with โ `configurationSnapshot`, taken once at creation+ โ and a rebuild replays that one rather than reading the+ environment again. So an edit reaches new instances only, and+ saying "rebuild to apply" would send people to a button that+ cannot do it. Repeated on the setup section and the variables tab,+ which are governed by the same snapshot. */+ <Text fontSize={12} type={'secondary'}>+ {t('environments.form.appliesOnBuild')}+ </Text>+ }+ >+ {/* One repository, so no list and no way to add a second. At rest it+ is a box naming the repository with a pencil and a disconnect,+ the way Railway shows a service's source; the same picker the+ create dialog uses takes over while a different one is chosen. */}+ {selection && !pickingRepository ? (+ <div className={styles.box}>+ <Github size={16} />+ <Text ellipsis style={{ flex: 1 }} weight={500}>+ {repositoryPath}+ </Text>+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('environments.form.changeRepository')}+ onClick={() => setPickingRepository(true)}+ />+ <Button loading={busy} size={'small'} onClick={() => run(() => setSource(undefined))}>+ {t('environments.form.disconnect')}+ </Button>+ </div>+ ) : (+ <Flexbox gap={8}>+ <GithubRepositoryPicker value={selection} onChange={pickRepository} />+ {selection && (+ <Flexbox horizontal>+ <Button size={'small'} onClick={() => setPickingRepository(false)}>+ {t('cancel', { ns: 'common' })}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ )}++ {source && (+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <div style={{ flex: 1 }}>+ {selection ? (+ <BranchField+ owner={selection.owner}+ repository={selection.repository}+ value={source.ref ?? ''}+ onSave={(ref) => setSource({ ref })}+ />+ ) : (+ <InlineField+ label={t('environments.form.ref')}+ placeholder={'main'}+ value={source.ref ?? ''}+ onSave={(ref) => setSource({ ref })}+ />+ )}+ </div>+ <div style={{ flex: 1 }}>+ <InlineField+ label={t('environments.form.path')}+ placeholder={'/'}+ value={source.path ?? ''}+ onSave={(path) => setSource({ path })}+ />+ </div>+ </Flexbox>+ )}+ </PanelSection>++ <PanelSection+ icon={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')}+ </Text>+ }+ >+ <InlineField+ multiline+ desc={t('environments.form.bootstrapHint')}+ label={t('environments.form.bootstrap')}+ placeholder={'pnpm install'}+ 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>+ );+});++EnvironmentForm.displayName = 'EnvironmentForm';++export default EnvironmentForm;diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsxnew file mode 100644index 00000000000..95890497ddd--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx@@ -0,0 +1,350 @@+'use client';++import { Github } from '@lobehub/icons';+import { DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Avatar, Button, confirmModal, Text, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import dayjs from 'dayjs';+import {+ ContainerIcon,+ EyeOffIcon,+ GlobeIcon,+ MoreHorizontalIcon,+ PlusIcon,+ 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';+import { useCanEditEnvironment } from './useCanEditEnvironment';+import { type SandboxEnvironment, useEnvironmentActions } from './useEnvironmentData';++const styles = createStaticStyles(({ css }) => ({+ /**+ * The counts. They shrink last: a long repository path gives way first+ * (its shrink weight is far higher), but with the panel open the list is a+ * third of the frame and even the facts alone can outrun it, so they+ * truncate rather than run under the avatar and the menu.+ */+ facts: css`+ overflow: hidden;+ flex: 0 1 auto;++ min-width: 0;++ font-size: ${cssVar.fontSizeSM};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ iconTile: css`+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;++ width: 48px;+ height: 48px;+ border-radius: 12px;++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillTertiary};+ `,+ metaDivider: css`+ flex: none;+ width: 1px;+ height: 10px;+ background: ${cssVar.colorBorderSecondary};+ `,+ repository: css`+ overflow: hidden;+ flex: 0 1000 auto;++ min-width: 0;++ font-size: ${cssVar.fontSizeSM};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ row: css`+ cursor: pointer;++ padding-block: 12px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};++ transition: background 0.15s ease;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -1px;+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ rowActive: css`+ background: ${cssVar.colorFillSecondary};++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+}));++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+ * 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 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 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 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,+ },+ ]+ : [];++ const remove = () =>+ actions+ .removeEnvironment(environment.id)+ // A refusal has to reach the person. An environment still holding+ // instances is refused on purpose, and that is what they need to read.+ .catch((error: unknown) =>+ toast.error(describeError(error, t, t('environments.removeFailed'))),+ );++ // Asked for, like deleting an instance is โ the row is emptied of+ // instances by then, but the environment still carries its specification,+ // its variables and the snapshot built from them, and none of that comes+ // back. A single click in a menu was the whole gesture.+ const confirmRemove = () =>+ confirmModal({+ cancelText: tCommon('cancel'),+ content: t('environments.removeConfirmContent'),+ okButtonProps: { danger: true },+ okText: t('environments.remove'),+ onOk: remove,+ title: t('environments.removeConfirmTitle', { name: environment.name }),+ });++ 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}>+ {repository ? <Github size={20} /> : <Icon icon={ContainerIcon} size={20} />}+ </div>++ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ {/* No "published by" badge beside the name. The avatar on the right+ already names the author on hover, and inside the published pool+ every row is published by definition โ the badge printed the same+ fact twice and took the width the name needed. */}+ {/* The description sits after the name rather than on a line of its+ own: it is a gloss on the name, not a second fact, and a third+ line made every row taller for the rows that have one. It gives+ way 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>+ {environment.description && (+ /* Shrinks a thousand times more readily than the name, the same+ way 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+ from, and it truncates because it is the only part of this line+ that 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>+ </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+ `title`. `Avatar` derives its fallback text from+ `String(avatar)` first, so an undefined picture becomes the+ literal string "undefined" and every author without one+ renders the same "UN" โ `title` never gets a turn. Since the+ row carries no badge, that placeholder would be the only+ thing 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+ the menu goes away rather than offering items that would be+ refused. */}+ {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>+ </Flexbox>+ );+ },+);++EnvironmentItem.displayName = 'EnvironmentItem';++export default EnvironmentItem;diff --git a/src/features/EnvironmentManager/EnvironmentVariables.test.ts b/src/features/EnvironmentManager/EnvironmentVariables.test.tsnew file mode 100644index 00000000000..70a72e107ab--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentVariables.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { formatDotenv, parseDotenv } from './EnvironmentVariables';++describe('parseDotenv', () => {+ it('should read KEY=value lines and skip blanks and comments', () => {+ expect(+ parseDotenv('# comment\n\nNODE_ENV=production\nexport API_URL = https://x.dev\n'),+ ).toEqual({+ entries: [+ ['NODE_ENV', 'production'],+ ['API_URL', 'https://x.dev'],+ ],+ });+ });++ it('should strip a matching pair of quotes and let later lines win', () => {+ expect(parseDotenv('A="with space"\nB=\'x\'\nA=second')).toEqual({+ entries: [+ ['A', 'second'],+ ['B', 'x'],+ ],+ });+ });++ it('should name the first line that is not a pair', () => {+ expect(parseDotenv('OK=1\nnot a pair\nALSO=2')).toEqual({ line: 2 });+ expect(parseDotenv('1BAD=x')).toEqual({ line: 1 });+ });++ it('should round-trip through formatDotenv', () => {+ const entries: [string, string][] = [+ ['PLAIN', 'value'],+ ['SPACED', 'two words'],+ ['HASH', 'a#b'],+ ];+ expect(parseDotenv(formatDotenv(entries))).toEqual({ entries });+ });+});diff --git a/src/features/EnvironmentManager/EnvironmentVariables.tsx b/src/features/EnvironmentManager/EnvironmentVariables.tsxnew file mode 100644index 00000000000..2807f4abde7--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentVariables.tsx@@ -0,0 +1,370 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Button, Input, Text, TextArea, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { BracesIcon, CheckIcon, PencilIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';++import { describeError } from './errorMessage';++const styles = createStaticStyles(({ css }) => ({+ /** Railway's variables list: a framed block with a rule between rows. */+ list: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ `,+ row: css`+ padding-block: 8px;+ padding-inline: 12px;++ & + & {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ mono: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 13px;+ word-break: break-all;+ `,+ /**+ * Dashed, the way Railway frames "no variables": the outline says a list+ * belongs here, and the dashes say it has not been filled in, without the+ * weight a solid box would give an absence.+ */+ empty: css`+ padding-block: 32px;+ padding-inline: 16px;+ border: 1px dashed ${cssVar.colorBorder};+ border-radius: ${cssVar.borderRadiusLG};+ `,+ editor: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: ${cssVar.fontSizeSM};+ `,+}));++type Entry = [string, string];++/**+ * Parse `.env`-style text: one `KEY=value` per line, blank lines and `#`+ * comments skipped, an optional `export ` prefix and a matching pair of quotes+ * around the value dropped. Later lines win over earlier ones with the same+ * key, as they would when a shell sources the file.+ *+ * @returns the entries, or the 1-based number of the first line that is not a+ * `KEY=value` pair+ */+export const parseDotenv = (text: string): { entries: Entry[] } | { line: number } => {+ const entries = new Map<string, string>();+ const lines = text.split(/\r?\n/);+ for (const [index, raw] of lines.entries()) {+ const line = raw.trim();+ if (!line || line.startsWith('#')) continue;+ const match = line.match(/^(?:export\s+)?([A-Za-z_]\w*)\s*=(.*)$/);+ if (!match) return { line: index + 1 };+ let value = match[2].trim();+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) {+ value = value.slice(1, -1);+ }+ entries.set(match[1], value);+ }+ return { entries: [...entries.entries()] };+};++/** The inverse, for the raw editor's starting text. */+export const formatDotenv = (entries: Entry[]) =>+ entries+ .map(([key, value]) => `${key}=${/[\s#"']/.test(value) ? JSON.stringify(value) : value}`)+ .join('\n');++/**+ * One variable, either as a row or open for editing. Key and value edit+ * together: a variable is one thing, and confirming half of it is not a state+ * anyone wants stored.+ */+const EnvRow = memo<{+ entry: Entry;+ onRemove: () => Promise<void>;+ onSave: (entry: Entry) => Promise<void>;+}>(({ entry, onRemove, onSave }) => {+ const { t } = useTranslation('setting');+ const { t: tCommon } = useTranslation('common');+ const [draft, setDraft] = useState<Entry | null>(null);+ const [busy, setBusy] = useState(false);+ const { compositionProps, isComposingRef } = useIMECompositionEvent();++ const run = async (action: () => Promise<void>) => {+ setBusy(true);+ try {+ await action();+ setDraft(null);+ } catch (error) {+ toast.error(describeError(error, t, t('environments.saveFailed')));+ } finally {+ setBusy(false);+ }+ };++ if (draft) {+ return (+ <Flexbox horizontal align={'center'} className={styles.row} gap={8}>+ <Input+ autoFocus+ placeholder={'NODE_ENV'}+ style={{ flex: 1 }}+ value={draft[0]}+ onChange={(event) => setDraft([event.target.value, draft[1]])}+ />+ <Input+ placeholder={'production'}+ style={{ flex: 1 }}+ value={draft[1]}+ onChange={(event) => setDraft([draft[0], event.target.value])}+ onKeyDown={(event) => {+ if (event.key === 'Escape') setDraft(null);+ // Not the Enter that confirms an IME candidate: a value typed in+ // Chinese would otherwise save on the keystroke that picked it.+ if (event.key === 'Enter' && !isComposingRef.current && draft[0].trim()) {+ void run(() => onSave([draft[0].trim(), draft[1]]));+ }+ }}+ {...compositionProps}+ />+ <ActionIcon+ disabled={!draft[0].trim()}+ icon={CheckIcon}+ loading={busy}+ size={'small'}+ title={tCommon('save')}+ onClick={() => run(() => onSave([draft[0].trim(), draft[1]]))}+ />+ <ActionIcon+ disabled={busy}+ icon={XIcon}+ size={'small'}+ title={tCommon('cancel')}+ onClick={() => setDraft(null)}+ />+ </Flexbox>+ );+ }++ return (+ <Flexbox horizontal align={'center'} className={styles.row} gap={8}>+ <span className={styles.mono} style={{ flex: 1 }}>+ {entry[0]}+ </span>+ {/* Shown, not starred out: the hint above says these are stored in the+ clear and copied into every instance, and a mask would promise a+ secrecy the storage does not keep. */}+ <span className={styles.mono} style={{ color: cssVar.colorTextSecondary, flex: 1 }}>+ {entry[1]}+ </span>+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('environments.form.editEnv')}+ onClick={() => setDraft([entry[0], entry[1]])}+ />+ <ActionIcon+ icon={Trash2Icon}+ loading={busy}+ size={'small'}+ title={t('environments.form.removeEnv')}+ onClick={() => run(onRemove)}+ />+ </Flexbox>+ );+});++EnvRow.displayName = 'EnvironmentVariableRow';++interface EnvironmentVariablesProps {+ entries: Entry[];+ /** Writes the whole set; every change here is one specification save. */+ onSave: (entries: Entry[]) => Promise<void>;+}++/**+ * An environment's variables, laid out the way Railway lays out a service's.+ *+ * A heading that counts them, with the two ways in on the right: a new row for+ * one variable, or the raw editor for a whole `.env` at once. New rows open at+ * the top of the list so the field is where the button was, not below a list+ * that may be long.+ */+const EnvironmentVariables = memo<EnvironmentVariablesProps>(({ entries, onSave }) => {+ const { t } = useTranslation('setting');+ const [adding, setAdding] = useState<Entry | null>(null);+ const [raw, setRaw] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const { compositionProps, isComposingRef } = useIMECompositionEvent();++ const run = async (action: () => Promise<void>) => {+ setBusy(true);+ try {+ await action();+ } catch (error) {+ toast.error(describeError(error, t, t('environments.saveFailed')));+ } finally {+ setBusy(false);+ }+ };++ const openRaw = () => {+ setAdding(null);+ setRaw(formatDotenv(entries));+ };++ const saveRaw = () => {+ if (raw === null) return;+ const parsed = parseDotenv(raw);+ if ('line' in parsed) {+ toast.error(t('environments.form.rawInvalid', { line: parsed.line }));+ return;+ }+ void run(async () => {+ await onSave(parsed.entries);+ setRaw(null);+ });+ };++ const addNew = () =>+ run(async () => {+ if (!adding) return;+ const key = adding[0].trim();+ await onSave([...entries.filter(([k]) => k !== key), [key, adding[1]]]);+ setAdding(null);+ });++ return (+ <Flexbox gap={12}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text weight={600}>+ {entries.length === 0+ ? t('environments.form.env')+ : t('environments.form.envCount', { count: entries.length })}+ </Text>+ <Flexbox horizontal align={'center'} gap={4}>+ {raw === null ? (+ <>+ <Button+ icon={<Icon icon={BracesIcon} />}+ size={'small'}+ type={'text'}+ onClick={openRaw}+ >+ {t('environments.form.rawEditor')}+ </Button>+ <Button+ disabled={adding !== null}+ icon={<Icon icon={PlusIcon} />}+ size={'small'}+ type={'primary'}+ onClick={() => setAdding(['', ''])}+ >+ {t('environments.form.addEnv')}+ </Button>+ </>+ ) : (+ <>+ <Button disabled={busy} size={'small'} onClick={() => setRaw(null)}>+ {t('cancel', { ns: 'common' })}+ </Button>+ <Button loading={busy} size={'small'} type={'primary'} onClick={saveRaw}>+ {t('save', { ns: 'common' })}+ </Button>+ </>+ )}+ </Flexbox>+ </Flexbox>++ {raw !== null ? (+ <Flexbox gap={6}>+ <TextArea+ autoFocus+ classNames={{ input: styles.editor }}+ placeholder={'NODE_ENV=production\nAPI_URL=https://example.com'}+ rows={Math.min(16, Math.max(6, raw.split('\n').length + 1))}+ value={raw}+ onChange={(event) => setRaw(event.target.value)}+ />+ <Text fontSize={12} type={'secondary'}>+ {t('environments.form.rawEditorHint')}+ </Text>+ </Flexbox>+ ) : entries.length === 0 && !adding ? (+ <Flexbox align={'center'} className={styles.empty} gap={4}>+ <Text weight={500}>{t('environments.form.envEmpty')}</Text>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text fontSize={12} type={'secondary'}>+ {t('environments.form.envEmptyHint')}+ </Text>+ <Button size={'small'} type={'link'} onClick={openRaw}>+ {t('environments.form.rawEditor')}+ </Button>+ </Flexbox>+ </Flexbox>+ ) : (+ <div className={styles.list}>+ {adding && (+ <Flexbox horizontal align={'center'} className={styles.row} gap={8}>+ <Input+ autoFocus+ placeholder={'NODE_ENV'}+ style={{ flex: 1 }}+ value={adding[0]}+ onChange={(event) => setAdding([event.target.value, adding[1]])}+ />+ <Input+ placeholder={'production'}+ style={{ flex: 1 }}+ value={adding[1]}+ onChange={(event) => setAdding([adding[0], event.target.value])}+ onKeyDown={(event) => {+ if (event.key === 'Escape') setAdding(null);+ if (event.key === 'Enter' && !isComposingRef.current && adding[0].trim()) {+ void addNew();+ }+ }}+ {...compositionProps}+ />+ <ActionIcon+ disabled={!adding[0].trim()}+ icon={CheckIcon}+ loading={busy}+ size={'small'}+ title={t('save', { ns: 'common' })}+ onClick={addNew}+ />+ <ActionIcon+ disabled={busy}+ icon={XIcon}+ size={'small'}+ title={t('cancel', { ns: 'common' })}+ onClick={() => setAdding(null)}+ />+ </Flexbox>+ )}+ {entries.map(([key, value]) => (+ <EnvRow+ entry={[key, value]}+ key={key}+ onRemove={() => onSave(entries.filter(([k]) => k !== key))}+ onSave={(entry) => onSave(entries.map(([k, v]) => (k === key ? entry : [k, v])))}+ />+ ))}+ </div>+ )}+ </Flexbox>+ );+});++EnvironmentVariables.displayName = 'EnvironmentVariables';++export default EnvironmentVariables;diff --git a/src/features/EnvironmentManager/EnvironmentsGate.tsx b/src/features/EnvironmentManager/EnvironmentsGate.tsxnew file mode 100644index 00000000000..115b43789d7--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentsGate.tsx@@ -0,0 +1,63 @@+'use client';++import { Center, Empty, Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { AlertTriangleIcon } from 'lucide-react';+import { memo, type PropsWithChildren } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { SandboxStorageUpgradeGuide } from '@/business/client/features/SandboxStorageUpsell';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { RouteLoading } from '@/components/Skeleton/RouteSegment';+import { sandboxStorageService } from '@/services/sandboxStorage';++/**+ * 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. Same key as the+ * composer's working-directory chip โ workspace included, 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 workspaceId = useActiveWorkspaceId();+ const { data, error, isLoading, mutate } = useSWR(+ ['sandbox-storage-entitlement', workspaceId ?? ''],+ () => sandboxStorageService.getEntitlement(),+ );++ // 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 mutate()}>{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 (isLoading || !data) return <RouteLoading />;+ if (!data.entitled) return <SandboxStorageUpgradeGuide />;++ return children;+});++EnvironmentsGate.displayName = 'EnvironmentsGate';++export default EnvironmentsGate;diff --git a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx b/src/features/EnvironmentManager/GithubRepositoryPicker.tsxnew file mode 100644index 00000000000..738847c47ca--- /dev/null+++ b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx@@ -0,0 +1,242 @@+'use client';++import { Github } from '@lobehub/icons';+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Select, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRightIcon, LockIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { sandboxStorageService } from '@/services/sandboxStorage';++const styles = createStaticStyles(({ css }) => ({+ field: css`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 6px;++ min-width: 0;+ `,+ label: css`+ font-size: 12px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ `,+ guide: css`+ display: flex;+ gap: 10px;+ align-items: center;++ padding-block: 12px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillQuaternary};+ `,+ guideText: css`+ flex: 1;+ min-width: 0;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ option: css`+ display: flex;+ gap: 6px;+ align-items: center;+ min-width: 0;+ `,+ optionName: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ private: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ `,+}));++export interface GithubRepositorySelection {+ defaultBranch?: string;+ /** The account the repository belongs to, as GitHub reports it. */+ owner: string;+ repository: string;+}++interface GithubRepositoryPickerProps {+ onChange: (selection: GithubRepositorySelection | undefined) => void;+ /**+ * Run before navigating away from this picker. The picker lives in a dialog,+ * and leaving it open behind the credentials page would strand whatever the+ * person had already typed.+ */+ onLeave?: () => void;+ value?: GithubRepositorySelection;+}++/**+ * The one repository an environment builds from, chosen in two steps:+ * organization, then repository within it.+ *+ * Both lists come from a single `/user/repos` call, which already spans every+ * organization the account belongs to. The organizations are derived from what+ * came back rather than fetched separately: an organization holding nothing+ * this account can reach is not a choice, and listing per organization would+ * be one request per organization for a set already in hand โ switching+ * organizations costs nothing here.+ *+ * Both are searchable, because either half can be the one the person+ * remembers: sometimes the organization, sometimes the project.+ *+ * Choosing nothing is a choice: an environment with no repository is a blank+ * working directory, which is a reasonable thing to want.+ *+ * No GitHub connection is not an error and not a dead end โ it is one click+ * from being resolved, so the picker offers that click rather than reporting+ * a state and leaving the person to find the page themselves.+ */+const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, onLeave, value }) => {+ const { t } = useTranslation('setting');+ const navigate = useWorkspaceAwareNavigate();+ const [owner, setOwner] = useState<string | undefined>(value?.owner);++ const connectGithub = () => {+ onLeave?.();+ navigate('/settings/credential');+ };++ const { data, isLoading } = useSWR('sandbox-github-repositories', () =>+ sandboxStorageService.listGithubRepositories(),+ );++ // Memoised, not a bare `??` fallback: a fresh `[]` on every render would+ // make both lists below recompute every time, which is exactly what they are+ // memoised to avoid.+ const repositories = useMemo(() => data?.repositories ?? [], [data]);++ // Listing order is "most recently updated first", so the owner whose work is+ // freshest leads โ the same ranking the flat list had.+ const owners = useMemo(+ () => [...new Set(repositories.map((item) => item.owner))],+ [repositories],+ );++ const owned = useMemo(+ () => (owner ? repositories.filter((item) => item.owner === owner) : []),+ [owner, repositories],+ );++ // Both of these are the same kind of answer โ "there is nothing to pick from+ // yet, and here is what to do about it" โ so they share one shape. An empty+ // list on a live connection usually means the connection cannot see the+ // organization the person is thinking of, which is fixed in the same place.+ const guide =+ data?.connected === false+ ? { action: 'connect', text: t('environments.github.notConnected') }+ : !isLoading && repositories.length === 0+ ? { action: 'review', text: t('environments.github.noRepositories') }+ : undefined;++ if (guide)+ return (+ <Flexbox gap={6}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Github size={13} />+ <span className={styles.label}>{t('environments.github.label')}</span>+ </Flexbox>+ <div className={styles.guide}>+ <span className={styles.guideText}>{guide.text}</span>+ <Button size={'small'} onClick={connectGithub}>+ {t(+ guide.action === 'connect'+ ? 'environments.github.connect'+ : 'environments.github.reviewAccess',+ )}+ <Icon icon={ArrowRightIcon} size={12} />+ </Button>+ </div>+ </Flexbox>+ );++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} gap={6}>+ <Github size={13} />+ <span className={styles.label}>{t('environments.github.label')}</span>+ <Text fontSize={11} type={'secondary'}>+ {t('environments.github.optional')}+ </Text>+ </Flexbox>++ <Flexbox horizontal gap={8}>+ <div className={styles.field}>+ <Text fontSize={11} type={'secondary'}>+ {t('environments.github.organization')}+ </Text>+ <Select+ allowClear+ showSearch+ loading={isLoading}+ options={owners.map((login) => ({ label: login, value: login }))}+ placeholder={t('environments.github.organizationPlaceholder')}+ value={owner ?? null}+ onChange={(next) => {+ const login = typeof next === 'string' && next ? next : undefined;+ setOwner(login);+ // The same name under a different owner is a different+ // repository, so the pick cannot survive the switch.+ onChange(undefined);+ }}+ />+ </div>++ <div className={styles.field}>+ <Text fontSize={11} type={'secondary'}>+ {t('environments.github.repository')}+ </Text>+ <Select+ allowClear+ showSearch+ disabled={!owner}+ value={value?.repository ?? null}+ options={owned.map((repository) => ({+ label: (+ <span className={styles.option}>+ <span className={styles.optionName}>{repository.name}</span>+ {repository.isPrivate && (+ <Icon className={styles.private} icon={LockIcon} size={12} />+ )}+ </span>+ ),+ value: repository.name,+ }))}+ placeholder={t(+ owner+ ? 'environments.github.repositoryPlaceholder'+ : 'environments.github.repositoryPending',+ )}+ onChange={(next) => {+ const name = typeof next === 'string' && next ? next : undefined;+ const picked = owned.find((repository) => repository.name === name);++ onChange(+ picked && owner+ ? { defaultBranch: picked.defaultBranch, owner, repository: picked.name }+ : undefined,+ );+ }}+ />+ </div>+ </Flexbox>+ </Flexbox>+ );+});++GithubRepositoryPicker.displayName = 'GithubRepositoryPicker';++export default GithubRepositoryPicker;diff --git a/src/features/EnvironmentManager/InlineField.tsx b/src/features/EnvironmentManager/InlineField.tsxnew file mode 100644index 00000000000..1c19554415f--- /dev/null+++ b/src/features/EnvironmentManager/InlineField.tsx@@ -0,0 +1,233 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { ActionIcon, Input, Select, Text, TextArea, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';+import { type KeyboardEvent, memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';++import { describeError } from './errorMessage';++const styles = createStaticStyles(({ css }) => ({+ /**+ * The value at rest looks like a field, not like prose: a bordered box the+ * same height the input will have, so entering edit mode changes what is in+ * the box and not where everything below it sits.+ */+ display: css`+ display: flex;+ gap: 8px;+ align-items: center;++ min-height: 36px;+ padding-block: 6px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillQuaternary};+ `,+ multiline: css`+ align-items: flex-start;+ `,+ value: css`+ flex: 1;++ min-width: 0;++ font-size: 13px;+ line-height: 22px;+ word-break: break-word;+ white-space: pre-wrap;+ `,+ placeholder: css`+ color: ${cssVar.colorTextQuaternary};+ `,+}));++interface InlineFieldProps {+ desc?: ReactNode;+ label: ReactNode;+ /** Multi-line values โ commands and path lists โ edit in a text area. */+ multiline?: boolean;+ /** Told when the field opens or closes, so a caller can fetch options only while it is open. */+ onEditingChange?: (editing: boolean) => void;+ /**+ * Write the confirmed value. Rejecting keeps the field open with the+ * person's text still in it, and the reason goes to a toast.+ */+ onSave: (value: string) => Promise<void>;+ /** Shown in place of an empty value, muted. */+ placeholder: string;+ /** Refuse an empty value instead of saving it โ for the one field that has no sensible blank. */+ required?: boolean;+ /**+ * Pick from a list instead of typing. Choosing is the confirmation: the+ * field saves on selection, so โ is not shown. The current value is always+ * selectable, even when the list does not carry it.+ */+ select?: { loading?: boolean; options: string[] };+ value: string;+}++/**+ * One setting that saves on its own.+ *+ * The panel used to hold every field as one draft behind one save button at+ * the very bottom, which is where nobody looked: changes were typed, the tab+ * was switched, and they were gone. Railway's settings page is the reference โ+ * every value sits in its own box with a pencil, and confirming the edit is+ * the save. There is nothing to remember to do afterwards.+ */+const InlineField = memo<InlineFieldProps>(+ ({ desc, label, multiline, onEditingChange, onSave, placeholder, required, select, value }) => {+ const { t } = useTranslation('common');+ const { t: tSetting } = useTranslation('setting');+ const [draft, setDraft] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);+ const { compositionProps, isComposingRef } = useIMECompositionEvent();++ const editing = draft !== null;++ const open = () => {+ setDraft(value);+ onEditingChange?.(true);+ };+ const cancel = () => {+ setDraft(null);+ onEditingChange?.(false);+ };+ const commit = async (raw: string) => {+ const next = raw.trim();+ if (required && !next) return;+ if (next === value) {+ cancel();+ return;+ }+ setSaving(true);+ try {+ await onSave(next);+ cancel();+ } catch (error) {+ toast.error(describeError(error, tSetting, String(error)));+ } finally {+ setSaving(false);+ }+ };+ const save = () => (draft === null ? Promise.resolve() : commit(draft));++ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ cancel();+ }+ // Enter confirms a single-line value; in a text area it is a newline,+ // and โ/Ctrl+Enter confirms instead.+ // `isComposingRef` too: the Enter that confirms an IME candidate is an+ // Enter here as well, and it would save the half-typed value.+ if (+ event.key === 'Enter' &&+ !isComposingRef.current &&+ (!multiline || event.metaKey || event.ctrlKey)+ ) {+ event.preventDefault();+ void save();+ }+ };++ return (+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {label}+ </Text>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>+ )}+ {editing && select ? (+ <Flexbox horizontal align={'center'} gap={8}>+ <Select+ autoFocus+ defaultOpen+ showSearch+ disabled={saving}+ loading={select.loading || saving}+ placeholder={placeholder}+ style={{ flex: 1 }}+ value={draft || null}+ options={(draft && !select.options.includes(draft)+ ? [draft, ...select.options]+ : select.options+ ).map((name) => ({ label: name, value: name }))}+ onChange={(next) => {+ if (typeof next === 'string' && next) void commit(next);+ }}+ />+ <ActionIcon+ disabled={saving}+ icon={XIcon}+ size={'small'}+ title={t('cancel')}+ onClick={cancel}+ />+ </Flexbox>+ ) : editing ? (+ <Flexbox horizontal align={multiline ? 'flex-start' : 'center'} gap={8}>+ {multiline ? (+ <TextArea+ autoFocus+ autoSize={{ maxRows: 10, minRows: 2 }}+ placeholder={placeholder}+ style={{ flex: 1 }}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={onKeyDown}+ {...compositionProps}+ />+ ) : (+ <Input+ autoFocus+ placeholder={placeholder}+ style={{ flex: 1 }}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={onKeyDown}+ {...compositionProps}+ />+ )}+ <ActionIcon+ disabled={required && !draft.trim()}+ icon={CheckIcon}+ loading={saving}+ size={'small'}+ title={t('save')}+ onClick={save}+ />+ <ActionIcon+ disabled={saving}+ icon={XIcon}+ size={'small'}+ title={t('cancel')}+ onClick={cancel}+ />+ </Flexbox>+ ) : (+ <div className={cx(styles.display, multiline && styles.multiline)}>+ <span className={cx(styles.value, !value && styles.placeholder)}>+ {value || placeholder}+ </span>+ <ActionIcon icon={PencilIcon} size={'small'} title={t('edit')} onClick={open} />+ </div>+ )}+ </Flexbox>+ );+ },+);++InlineField.displayName = 'InlineField';++export default InlineField;diff --git a/src/features/EnvironmentManager/InstanceFileBrowser.tsx b/src/features/EnvironmentManager/InstanceFileBrowser.tsxnew file mode 100644index 00000000000..38df755e73c--- /dev/null+++ b/src/features/EnvironmentManager/InstanceFileBrowser.tsx@@ -0,0 +1,351 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, createModal, Skeleton, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+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 (LOBE-14364).+ *+ * 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.tsxnew file mode 100644index 00000000000..b4dd10888b5--- /dev/null+++ b/src/features/EnvironmentManager/InstanceList.tsx@@ -0,0 +1,510 @@+'use client';++import { Github } from '@lobehub/icons';+import { Center, Empty, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { ActionIcon, Button, confirmModal, Tag, Text, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import {+ CircleAlertIcon,+ CircleDashedIcon,+ FolderOpenIcon,+ LayersIcon,+ Loader2Icon,+ PencilIcon,+ PlusIcon,+ RotateCcwIcon,+ Trash2Icon,+} from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { openCreateInstanceModal, openEditInstanceModal } from './CreateInstanceModal';+import { describeError } from './errorMessage';+import { openInstanceFileBrowser } from './InstanceFileBrowser';+import type { SandboxInstance } from './useEnvironmentData';+import { useInstanceBuild } 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>;+ /** `owner/name` of the environment's checkout, when it builds from one. */+ repository?: string;+}++interface InstanceRowProps {+ editable: boolean;+ instance: SandboxInstance;+ onBuild: (id: string) => Promise<void>;+ onRemove: (id: string) => Promise<void>;+ repository?: string;+}++/**+ * 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, onBuild, onRemove, repository }) => {+ const { t } = useTranslation('setting');++ // 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 = 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 = 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 [starting, setStarting] = useState(false);+ // 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);++ // 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: () => {+ setStarting(true);+ void onBuild(instance.id)+ .catch((error: unknown) =>+ toast.error(describeError(error, t, t('environments.instances.buildStartFailed'))),+ )+ .finally(() => setStarting(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 && (+ <Tag color={'processing'} size={'small'}>+ {t('environments.instances.running')}+ </Tag>+ )}+ {/* 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. */}+ <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. */}+ {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}+ />+ )}+ {editable && (+ <ActionIcon+ icon={PencilIcon}+ size={'small'}+ title={t('environments.instances.rename')}+ onClick={() => openEditInstanceModal(instance)}+ />+ )}+ {editable && (+ <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 && (+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon spin icon={Loader2Icon} size={13} />+ <Text fontSize={12} type={'secondary'}>+ {t('environments.instances.removing')}+ </Text>+ </Flexbox>+ )}++ {!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, repository }) => {+ 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}+ repository={repository}+ onBuild={onBuild}+ onRemove={onRemove}+ />+ ))}+ </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.tsxnew file mode 100644index 00000000000..5e22fce220c--- /dev/null+++ b/src/features/EnvironmentManager/InstanceSection.tsx@@ -0,0 +1,58 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';++import InstanceList from './InstanceList';+import { repositoryPath } from './repository';+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;+}++/**+ * The instances 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 }) => {+ const { data } = useInstances();+ const { data: environmentData } = useEnvironments();+ const actions = useEnvironmentActions();++ 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 repository = repositoryPath(+ environmentData?.environments.find((environment) => environment.id === environmentId)+ ?.configuration,+ );++ return (+ <Flexbox>+ <InstanceList+ editable={editable}+ environmentId={environmentId}+ instances={instances}+ occupancyUnavailable={data?.occupancyUnavailable ?? false}+ repository={repository}+ onBuild={actions.rebuildInstance}+ onRemove={actions.removeInstance}+ />+ </Flexbox>+ );+});++InstanceSection.displayName = 'InstanceSection';++export default InstanceSection;diff --git a/src/features/EnvironmentManager/PanelSection.tsx b/src/features/EnvironmentManager/PanelSection.tsxnew file mode 100644index 00000000000..f5d022f9758--- /dev/null+++ b/src/features/EnvironmentManager/PanelSection.tsx@@ -0,0 +1,92 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import type { LucideIcon } from 'lucide-react';+import { memo, type ReactNode } from 'react';++const styles = createStaticStyles(({ css }) => ({+ icon: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 50%;++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ /**+ * The connector, as its own element in the icon's column rather than a border+ * on the content beside it. A border there began below the icon row and ended+ * with the content, so every heading left a gap the width of its own icon and+ * the rail arrived in pieces. Stretched to fill what the content leaves over,+ * it meets the next section's icon exactly.+ */+ line: css`+ flex: 1;+ width: 1px;+ margin-block: 4px;+ background: ${cssVar.colorBorderSecondary};+ `,+}));++interface PanelSectionProps {+ children: ReactNode;+ desc?: ReactNode;+ icon: LucideIcon;+ /** Drops the connector below this section, which would otherwise dangle. */+ last?: boolean;+ /** Sits under the description, for something true of this section only. */+ notice?: ReactNode;+ title: ReactNode;+}++/**+ * One titled part of the detail panel, on a rail of its own.+ *+ * The panel used to be a single column of eight fields with nothing between+ * them, so finding the setup command meant reading every label on the way. The+ * rail gives each part a heading you can skip to and an icon to recognise it+ * by, without the nested cards that grouping usually costs โ this panel is+ * already a card, and boxes inside boxes were how it got crowded before.+ *+ * Railway's settings page is the reference. Its right-hand jump list is not,+ * because this panel is half a page wide and that nav would take the half that+ * holds the fields.+ */+const PanelSection = memo<PanelSectionProps>(({ children, desc, icon, last, notice, title }) => (+ <Flexbox horizontal align={'stretch'} gap={12}>+ <Flexbox align={'center'} style={{ flex: 'none' }}>+ <span className={styles.icon}>+ <Icon icon={icon} size={15} />+ </span>+ {!last && <div className={styles.line} />}+ </Flexbox>++ <Flexbox flex={1} gap={12} paddingBlock={'4px 24px'} style={{ minWidth: 0 }}>+ <Text weight={600}>{title}</Text>+ {(desc || notice) && (+ <Flexbox gap={4}>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>+ )}+ {notice}+ </Flexbox>+ )}+ <Flexbox gap={16}>{children}</Flexbox>+ </Flexbox>+ </Flexbox>+));++PanelSection.displayName = 'PanelSection';++export default PanelSection;diff --git a/src/features/EnvironmentManager/SessionHistorySection.tsx b/src/features/EnvironmentManager/SessionHistorySection.tsxnew file mode 100644index 00000000000..a619fbe9fd0--- /dev/null+++ b/src/features/EnvironmentManager/SessionHistorySection.tsx@@ -0,0 +1,361 @@+'use client';++import { Center, Empty, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Button, Tag, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import {+ ActivityIcon,+ AlertCircleIcon,+ HammerIcon,+ HistoryIcon,+ MessageSquareIcon,+ TerminalSquareIcon,+} from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';++import ListSkeleton from '@/components/ListSkeleton';+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`;+};++const SessionRow = memo<{ running: boolean; session: SandboxSessionRecord }>(+ ({ running, session }) => {+ const { t } = useTranslation('setting');+ const navigate = useNavigate();++ 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);+ // 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. */}+ {running && session.topicId && !session.management && (+ <Button size={'small'} onClick={() => navigate(`/chat?topic=${session.topicId}`)}>+ {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/TabPane.tsx b/src/features/EnvironmentManager/TabPane.tsxnew file mode 100644index 00000000000..5cef136fec9--- /dev/null+++ b/src/features/EnvironmentManager/TabPane.tsx@@ -0,0 +1,32 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { memo, type ReactNode } from 'react';++interface TabPaneProps {+ children: ReactNode;+ desc?: ReactNode;+}++/**+ * The body of a tab that holds one thing.+ *+ * The tab strip already names it, so a rail heading under the strip said the+ * same words twice with an icon between them. Only the settings tab keeps the+ * rail, because it holds several sections and the rail is what tells them apart.+ */+const TabPane = memo<TabPaneProps>(({ children, desc }) => (+ <Flexbox gap={16} paddingBlock={'4px 24px'}>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>+ )}+ {children}+ </Flexbox>+));++TabPane.displayName = 'TabPane';++export default TabPane;diff --git a/src/features/EnvironmentManager/WorkspaceUsageMeter.tsx b/src/features/EnvironmentManager/WorkspaceUsageMeter.tsxnew file mode 100644index 00000000000..11c62e9f8ed--- /dev/null+++ b/src/features/EnvironmentManager/WorkspaceUsageMeter.tsx@@ -0,0 +1,109 @@+'use client';++import { Flexbox, Tooltip } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+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/errorMessage.test.ts b/src/features/EnvironmentManager/errorMessage.test.tsnew file mode 100644index 00000000000..d893a678a4f--- /dev/null+++ b/src/features/EnvironmentManager/errorMessage.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';++import { describeError } from './errorMessage';++const t = (key: string) => `<${key}>`;++describe('describeError', () => {+ it('turns the has-instances refusal code into its sentence', () => {+ expect(describeError(new Error('ENVIRONMENT_HAS_INSTANCES'), t, 'fallback')).toBe(+ '<environments.hasInstances>',+ );+ });++ it('turns a path the server confined to the instance into the same line', () => {+ expect(describeError(new Error('PATH_OUTSIDE_INSTANCE'), t, 'fallback')).toBe(+ '<environments.files.invalidPath>',+ );+ });++ it('turns a path validation issue list into the localized line instead of raw JSON', () => {+ const issues = JSON.stringify([+ {+ code: 'custom',+ message: 'Path must be a relative path inside the workspace',+ path: ['path'],+ },+ ]);+ expect(describeError(new Error(issues), t, 'fallback')).toBe(+ '<environments.files.invalidPath>',+ );+ });++ it('joins other validation issues into one readable message', () => {+ const issues = JSON.stringify([+ {+ code: 'too_big',+ message: 'Too big: expected string to have <=1048576 characters',+ path: ['content'],+ },+ ]);+ expect(describeError(new Error(issues), t, 'fallback')).toBe(+ 'Too big: expected string to have <=1048576 characters',+ );+ });++ it('drops a drizzle query dump rather than showing SQL and row values', () => {+ // A missing column surfaced in the create dialog as a screenful of SQL with+ // the instance's own values in it; the caller's line at least says which+ // action failed.+ const drizzle = new Error(+ 'Failed query: insert into "environment_instances" ("id", "name") values ' ++ '(default, $1) returning "id", "name" params: 7e3e4ab0,Lobehub Dev',+ );+ expect(describeError(drizzle, t, 'fallback')).toBe('fallback');+ });++ it('drops a message that dragged a stack trace along', () => {+ const stack = new Error('something broke\n at Object.<anonymous> (/app/server.js:1:1)');+ expect(describeError(stack, t, 'fallback')).toBe('fallback');+ });++ it('keeps an ordinary message and falls back when there is none', () => {+ expect(describeError(new Error('could not delete'), t, 'fallback')).toBe('could not delete');+ expect(describeError({}, t, 'fallback')).toBe('fallback');+ expect(describeError(new Error('[not json'), t, 'fallback')).toBe('[not json');+ });+});++describe('refusals that arrive from the execution plane', () => {+ it("translates the market's in-use code instead of the sentence naming a row id", () => {+ // The market answers `{ error: ENVIRONMENT_IN_USE, error_description: 'Environment+ // "e299f341-โฆ" is currently in use by an active session' }`; forwarding the+ // description put that uuid in a toast.+ expect(describeError({ message: 'ENVIRONMENT_IN_USE' }, t, 'fallback')).toBe(+ '<environments.instances.inUse>',+ );+ });++ it('falls back rather than printing a code it has no sentence for', () => {+ expect(describeError({ message: 'WORKSPACE_NOT_CONFIGURED' }, t, 'fallback')).toBe('fallback');+ });++ it('still shows a refusal written as a sentence', () => {+ expect(describeError({ message: 'The folder is not empty' }, t, 'fallback')).toBe(+ 'The folder is not empty',+ );+ });+});diff --git a/src/features/EnvironmentManager/errorMessage.ts b/src/features/EnvironmentManager/errorMessage.tsnew file mode 100644index 00000000000..c555245fccc--- /dev/null+++ b/src/features/EnvironmentManager/errorMessage.ts@@ -0,0 +1,86 @@+/**+ * What a failed environment action should say to the person.+ *+ * The server answers refusals in two shapes neither of which is a sentence:+ * a bare code such as `ENVIRONMENT_HAS_INSTANCES`, and, for input the router+ * rejected, the JSON of the validation issues. Both reached the toast verbatim,+ * so a refusal made on purpose read like a crash. Each is turned into the+ * message it stands for here; anything else is shown as it came, and an error+ * with no message at all โ or one that is plainly machine output rather than a+ * sentence โ falls back to the caller's generic line.+ */+const CODE_KEYS: Record<string, string> = {+ ENVIRONMENT_HAS_INSTANCES: 'environments.hasInstances',+ // The execution plane calls this an instance now too (LOBE-14539). 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_USE: 'environments.instances.inUse',+ INSTANCE_IN_USE: 'environments.instances.inUse',+ PATH_OUTSIDE_INSTANCE: 'environments.files.invalidPath',+};++/**+ * A refusal that arrived as a bare machine code this build has no sentence for+ * โ a newer server, or a code only another surface handles. Printing it puts+ * `WORKSPACE_NOT_CONFIGURED` in front of someone; the caller's own line at+ * least names the action that failed.+ */+const isUntranslatedCode = (message: string): boolean => /^[A-Z][\dA-Z_]{2,}$/.test(message);++/**+ * A message the server never wrote for anyone to read.+ *+ * Drizzle raises a failed insert with the whole statement and its parameters in+ * `message`, and tRPC forwards that verbatim, so a missing column surfaced in a+ * dialog as a screenful of SQL โ with the row's values in it. Anything of that+ * shape is dropped in favour of the caller's own line, which at least says+ * which action failed.+ *+ * Matched narrowly on purpose. The fallthrough below exists so that refusals+ * written as sentences still reach the person, and widening this to "anything+ * long" would swallow those too.+ */+const isMachineMessage = (message: string): boolean =>+ message.startsWith('Failed query:') ||+ // A stack trace that came along for the ride.+ /\n\s+at\s/.test(message);++const readIssues = (message: string): string[] | undefined => {+ if (!message.startsWith('[')) return;+ try {+ const parsed = JSON.parse(message) as unknown;+ if (+ Array.isArray(parsed) &&+ parsed.length > 0 &&+ parsed.every((issue) => typeof (issue as { message?: unknown })?.message === 'string')+ ) {+ return parsed.map((issue) => (issue as { message: string }).message);+ }+ } catch {+ // not JSON: an ordinary message that happens to start with a bracket+ }+};++export const describeError = (+ error: unknown,+ t: (key: any, options?: any) => string,+ fallback: string,+): string => {+ const message = (error as { message?: unknown })?.message;+ if (typeof message !== 'string' || !message) return fallback;++ const key = CODE_KEYS[message];+ if (key) return t(key);++ if (isMachineMessage(message) || isUntranslatedCode(message)) return fallback;++ const issues = readIssues(message);+ if (issues) {+ if (issues.some((issue) => /relative path inside the workspace/i.test(issue))) {+ return t('environments.files.invalidPath');+ }+ return issues.join('; ');+ }++ return message;+};diff --git a/src/features/EnvironmentManager/index.tsx b/src/features/EnvironmentManager/index.tsxnew file mode 100644index 00000000000..9cc9c27c5c8--- /dev/null+++ b/src/features/EnvironmentManager/index.tsx@@ -0,0 +1,296 @@+'use client';++import type { EnvironmentVisibility } from '@lobechat/types';+import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ContainerIcon, PlusIcon, RefreshCwIcon } from 'lucide-react';+import { memo, type ReactNode, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import ListSkeleton from '@/components/ListSkeleton';++import { openCreateEnvironmentModal } from './CreateEnvironmentModal';+import { openCreateInstanceModal } from './CreateInstanceModal';+import EnvironmentDetailPanel from './EnvironmentDetailPanel';+import EnvironmentItem from './EnvironmentItem';+import { useEnvironments, useInstances, useWorkspaceUsage } from './useEnvironmentData';+import WorkspaceUsageMeter from './WorkspaceUsageMeter';++const styles = createStaticStyles(({ css }) => ({+ detailCol: css`+ align-self: stretch;++ min-width: 0;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};+ `,+ /**+ * One frame around the list, on the page's own surface. A settings group+ * would nest a card inside a card and inset every row by its own padding,+ * which left each row's hover and selection background floating in a gutter+ * instead of filling the panel.+ */+ listCol: css`+ overflow: hidden;++ min-width: 0;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};+ `,+ listScroll: css`+ overflow-y: auto;++ /* Cap the list so a long shelf of environments stays scrollable rather than+ pushing the page down past the panel sitting beside it. */+ max-height: 480px;+ `,+}));++/** What the list occupies before it knows its length โ the skeleton's own rows. */+const LIST_MIN_HEIGHT = 4 * 72;++/**+ * Environments and the instances built 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.+ *+ * List beside detail, the shape the device manager uses: the rows carry only+ * what tells one environment from another, and picking one opens everything+ * else about it next to the list rather than in place of it.+ */+interface EnvironmentManagerProps {+ /**+ * Put beside the actions rather than above them, so the page has one header+ * row instead of two. Passed in rather than built here because only a page+ * with more than one pool has anything to put in it, and that page is the one+ * that owns which pool is selected.+ */+ tabs?: ReactNode;+ /**+ * Workspace pages only: which pool to manage โ `public` (published to the+ * workspace) or `private` (the caller's own). Omitted on the personal page,+ * where an environment has no pool to belong to.+ */+ visibility?: EnvironmentVisibility;+}++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 [selectedId, setSelectedId] = useState<string>();+ // Whether a refresh the user asked for is still running.+ const [refreshing, setRefreshing] = useState(false);+ /**+ * Whether the first fetch of THIS mount has come back.+ *+ * A pool visited earlier is still in SWR's cache, so switching back to it+ * rendered last time's answer instantly and revalidated behind the scenes โ+ * no skeleton, no sign anything was happening, and a list that may already+ * have been wrong. Switching tabs is the question being asked again, so it+ * waits for the new answer. Only the first fetch after a mount gates; later+ * background revalidations must not throw away a list the reader is using.+ */+ const [ready, setReady] = useState(false);++ useEffect(() => {+ if (!isValidating) setReady(true);+ }, [isValidating]);++ const environments = data?.environments ?? [];+ const instances = instanceData?.instances ?? [];+ const selected = selectedId+ ? environments.find((environment) => environment.id === selectedId)+ : undefined;++ const select = (id: string) => {+ setSelectedId((current) => (current === id ? undefined : id));+ };++ // The row's shortcut: open the environment so the new instance is seen+ // landing in its list, and ask for the instance in the same dialog the+ // panel's own button opens.+ const createInstance = (id: string) => {+ setSelectedId(id);+ openCreateInstanceModal({ environmentId: 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.+ */+ 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()]);+ } 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.+ */+ 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 />+ <Button+ icon={<Icon icon={RefreshCwIcon} />}+ loading={refreshing}+ title={t('environments.refresh')}+ onClick={refresh}+ />+ <Button+ icon={<Icon icon={PlusIcon} />}+ type={'primary'}+ onClick={() => openCreateEnvironmentModal(visibility)}+ >+ {t('environments.create')}+ </Button>+ </Flexbox>+ );++ const list = (+ <AsyncBoundary+ // Both gated on the same signal, because the boundary reads `data` as+ // "has anything settled": handing it the cache while saying the fetch is+ // still running would show that cache, which is the thing being avoided.+ data={ready ? data : undefined}+ error={error}+ errorVariant={'block'}+ isEmpty={environments.length === 0}+ isLoading={!ready}+ empty={+ // Inside the same frame the rows land in, sized to the skeleton's+ // rows: loading, empty and loaded are one surface whose contents+ // change, not three surfaces of three different heights.+ <Flexbox className={styles.listCol}>+ <Center style={{ minHeight: LIST_MIN_HEIGHT }} width={'100%'}>+ <Empty+ description={t('environments.desc')}+ descriptionProps={{ fontSize: 13 }}+ icon={ContainerIcon}+ style={{ maxWidth: 360 }}+ action={+ <Button+ icon={<Icon icon={PlusIcon} />}+ onClick={() => openCreateEnvironmentModal(visibility)}+ >+ {t('environments.create')}+ </Button>+ }+ title={t(+ visibility === 'public' ? 'environments.emptyPublished' : 'environments.empty',+ )}+ />+ </Center>+ </Flexbox>+ }+ loading={+ <Flexbox className={styles.listCol}>+ <Flexbox padding={4}>+ <ListSkeleton />+ </Flexbox>+ </Flexbox>+ }+ onRetry={refresh}+ >+ <Flexbox horizontal align={'flex-start'} gap={16}>+ <Flexbox className={styles.listCol} flex={1}>+ <Flexbox className={styles.listScroll} gap={2} padding={4}>+ {environments.map((environment) => (+ <EnvironmentItem+ 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)}+ />+ ))}+ </Flexbox>+ </Flexbox>+ {/* Twice the list's share. A row carries a name and two facts; the panel+ carries a form, so an even split starved the half doing the work and+ left the other half mostly empty. */}+ {selected && (+ <Flexbox className={styles.detailCol} flex={2}>+ {/* Keyed on the environment so the form's draft state resets when+ the selection changes โ a description typed for one+ environment must not survive into another. */}+ <EnvironmentDetailPanel+ environment={selected}+ key={selected.id}+ onClose={() => setSelectedId(undefined)}+ />+ </Flexbox>+ )}+ </Flexbox>+ </AsyncBoundary>+ );++ /**+ * One layout for both pages. What sits on the left of the header is the only+ * difference: tabs where there is a pool to choose, and the section's own+ * name where there is not.+ */+ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>+ {tabs ?? (+ <Text fontSize={16} weight={600}>+ {t('environments.mine')}+ </Text>+ )}+ {actions}+ </Flexbox>+ {list}+ </Flexbox>+ );+});++EnvironmentManager.displayName = 'EnvironmentManager';++export default EnvironmentManager;diff --git a/src/features/EnvironmentManager/instanceDirectory.test.ts b/src/features/EnvironmentManager/instanceDirectory.test.tsnew file mode 100644index 00000000000..3fac6e20160--- /dev/null+++ b/src/features/EnvironmentManager/instanceDirectory.test.ts@@ -0,0 +1,36 @@+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.tsnew file mode 100644index 00000000000..05aadfbc6de--- /dev/null+++ b/src/features/EnvironmentManager/instanceDirectory.ts@@ -0,0 +1,31 @@+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/repository.ts b/src/features/EnvironmentManager/repository.tsnew file mode 100644index 00000000000..efd3407b73f--- /dev/null+++ b/src/features/EnvironmentManager/repository.ts@@ -0,0 +1,24 @@+/**+ * Only what naming a repository needs. Typed structurally rather than against+ * either configuration type, because the stored shape and the service's own+ * specification type disagree on the rest of the object and neither difference+ * matters to a checkout URL.+ */+interface SourcedConfiguration {+ sources?: { kind?: string; url?: string }[];+}++/**+ * The one repository an environment builds from, as `owner/name`.+ *+ * A specification stores a checkout URL because that is what the execution+ * plane clones; `owner/name` is what the repository is called everywhere a+ * person meets it, so the translation happens here rather than in each surface+ * that shows one.+ */+export const repositoryPath = (configuration?: SourcedConfiguration): string | undefined => {+ const url = configuration?.sources?.find((source) => source.kind === 'git')?.url;+ const path = url?.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '');++ return path || undefined;+};diff --git a/src/features/EnvironmentManager/sessionHistory.test.ts b/src/features/EnvironmentManager/sessionHistory.test.tsnew file mode 100644index 00000000000..0079b3b1fb4--- /dev/null+++ b/src/features/EnvironmentManager/sessionHistory.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from 'vitest';++import { 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',+ 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([]);+ });+});diff --git a/src/features/EnvironmentManager/useCanEditEnvironment.ts b/src/features/EnvironmentManager/useCanEditEnvironment.tsnew file mode 100644index 00000000000..6c43cba2f4a--- /dev/null+++ b/src/features/EnvironmentManager/useCanEditEnvironment.ts@@ -0,0 +1,34 @@+import { useCallback } from 'react';++import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import type { SandboxEnvironment } from './useEnvironmentData';++/**+ * Can the caller mutate this environment's row?+ *+ * Mirrors the server's `environmentOwnership` filter exactly, so the UI only+ * offers rename / respecify / publish / delete where the matching request would+ * actually succeed. Creator-only, with no workspace-owner escalation โ unlike+ * devices, because editing an environment rewrites what somebody else's next+ * instances are built from, and an owner has no way to know what that would+ * cost them.+ *+ * A published environment a colleague made is therefore readable and runnable,+ * but not editable. That is the whole shape of publishing one.+ */+export const useCanEditEnvironment = () => {+ const currentUserId = useUserStore(userProfileSelectors.userId);++ return useCallback(+ (environment: SandboxEnvironment): boolean => {+ // Personal environments have no other member to belong to.+ if (!environment.workspaceId) return true;+ if (!currentUserId) return false;++ return environment.userId === currentUserId;+ },+ [currentUserId],+ );+};diff --git a/src/features/EnvironmentManager/useEnvironmentData.ts b/src/features/EnvironmentManager/useEnvironmentData.tsnew file mode 100644index 00000000000..1c0ae3569b2--- /dev/null+++ b/src/features/EnvironmentManager/useEnvironmentData.ts@@ -0,0 +1,378 @@+import type { EnvironmentVisibility } from '@lobechat/types';+import { useCallback, useMemo, useRef, useState } from 'react';+import { useSWRConfig } from 'swr';++import { useClientDataSWR } from '@/libs/swr';+import {+ type SandboxEnvironmentSpecification,+ sandboxStorageService,+} from '@/services/sandboxStorage';++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+ * safe to render the page on.+ *+ * Keyed by pool, so the workspace page's two tabs do not overwrite each other's+ * cache โ and so switching back to one shows what it held rather than a+ * skeleton. A mutation refreshes every pool, because publishing moves a row+ * from one to the other.+ *+ * `useClientDataSWR` rather than plain SWR, because it adds the active+ * workspace to the key. Without that dimension a list fetched in one workspace+ * keeps being served after switching to another โ the same trap the device list+ * documents, and a worse one here, where the answer is which environments exist+ * for whom.+ */+export const useEnvironments = (visibility?: EnvironmentVisibility) =>+ useClientDataSWR<Awaited<ReturnType<typeof sandboxStorageService.listEnvironments>>>(+ [ENVIRONMENTS_KEY, visibility ?? 'all'],+ () => sandboxStorageService.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 };+};++/**+ * 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,+ };+};++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];++export type SandboxEnvironment = NonNullable<+ ReturnType<typeof useEnvironments>['data']+>['environments'][number];++/**+ * Mutations, each refreshing exactly the lists it can have changed.+ */+export const useEnvironmentActions = () => {+ const { mutate: globalMutate } = useSWRConfig();+ const { mutate: refreshInstances } = 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+ // in the other, so refreshing only the current key leaves the other tab+ // showing a row that moved. The workspace id the key carries is part of what+ // is matched loosely here, for the same reason.+ const refreshEnvironments = () =>+ 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;+ description?: string;+ name: string;+ visibility?: EnvironmentVisibility;+ }) => {+ await sandboxStorageService.createEnvironment(params);+ await refreshEnvironments();+ },++ /**+ * 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) => {+ try {+ await sandboxStorageService.startInstanceBuild({ id });+ } catch {+ /* recorded on the instance; the list shows it */+ }+ await refreshInstances();+ },++ /**+ * 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) => {+ try {+ await sandboxStorageService.startInstanceBuild({ id });+ } finally {+ await 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,+ name: created.name,+ snapshot: null,+ status: 'pending',+ workingDirectory: created.workingDirectory,+ } satisfies SandboxInstance;+ },++ setEnvironmentVisibility: async (params: { id: string; visibility: EnvironmentVisibility }) => {+ await sandboxStorageService.setEnvironmentVisibility(params);+ await refreshEnvironments();+ },++ removeEnvironment: async (id: string) => {+ await sandboxStorageService.removeEnvironment({ id });+ await refreshEnvironments();+ },++ removeInstance: async (id: string) => {+ await sandboxStorageService.removeInstance({ id });+ await refreshInstances();+ },++ 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 refreshEnvironments();+ },+ };+};diff --git a/src/features/EnvironmentManager/useInstanceBuild.test.ts b/src/features/EnvironmentManager/useInstanceBuild.test.tsnew file mode 100644index 00000000000..c6ce4869939--- /dev/null+++ b/src/features/EnvironmentManager/useInstanceBuild.test.ts@@ -0,0 +1,102 @@+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/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsxindex 1cbb5026c36..9c645264126 100644--- a/src/features/Portal/LocalFile/Body.test.tsx+++ b/src/features/Portal/LocalFile/Body.test.tsx@@ -160,6 +160,11 @@ vi.mock('@/store/chat/selectors', () => {(state.localFileBuffers as Record<string, string> | undefined)?.[tabId],openLocalFiles,},+ // The HTML preview reaches the project-file index, which only keeps itself+ // live while a run is writing to the tree. No run in these cases.+ operationSelectors: {+ isAgentRuntimeRunning: () => false,+ },};});diff --git a/src/features/Settings/environments/index.tsx b/src/features/Settings/environments/index.tsxnew file mode 100644index 00000000000..fb15340a420--- /dev/null+++ b/src/features/Settings/environments/index.tsx@@ -0,0 +1,26 @@+'use client';++import { Flexbox } from '@lobehub/ui';+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.+ */+const Page = memo(() => (+ <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ <EnvironmentsGate>+ <EnvironmentManager />+ </EnvironmentsGate>+ </Flexbox>+));++Page.displayName = 'EnvironmentsSetting';++export default Page;diff --git a/src/features/Settings/features/SettingsContent.tsx b/src/features/Settings/features/SettingsContent.tsxindex bec4f9f0f64..6697ac2ef54 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.Environments,SettingsTabs.ServiceModel,SettingsTabs.Stats,SettingsTabs.Storage,@@ -69,6 +70,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.Environments]: t('setting:tab.environments'),[SettingsTabs.ServiceModel]: t('setting:tab.serviceModel'),[SettingsTabs.Stats]: t('auth:tab.stats'),[SettingsTabs.Storage]: t('setting:tab.storage'),diff --git a/src/features/Settings/features/componentMap.desktop.ts b/src/features/Settings/features/componentMap.desktop.tsindex 2f7bc0192f8..08010aa4d90 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 Environments from '../environments';import Hotkey from '../hotkey';import Integrations from '../integrations';import Labels from '../labels';@@ -49,6 +50,7 @@ export const componentMap = {[SettingsTabs.Storage]: Storage,[SettingsTabs.Trash]: Trash,[SettingsTabs.Devices]: Devices,+ [SettingsTabs.Environments]: Environments,[SettingsTabs.Labels]: Labels,// Profile related tabs[SettingsTabs.Profile]: Profile,diff --git a/src/features/Settings/features/componentMap.ts b/src/features/Settings/features/componentMap.tsindex 7c1c88406c2..a4f5862cabe 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.Environments]: dynamic(() => import('../environments'), {+ loading: loading('Settings > Environments'),+ }),[SettingsTabs.Labels]: dynamic(() => import('../labels'), {loading: loading('Settings > Labels'),}),diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsxindex 0b3a43f30c0..f2e6a5eaa5b 100644--- a/src/features/Settings/hooks/useCategory.tsx+++ b/src/features/Settings/hooks/useCategory.tsx@@ -11,6 +11,7 @@ import {BrainCircuit,ChartColumnBigIcon,Coins,+ ContainerIcon,CreditCard,Database,EllipsisIcon,@@ -85,6 +86,9 @@ 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(() => {if (!avatar) return undefined;@@ -151,6 +155,11 @@ export const useCategory = () => {key: SettingsTabs.Devices,label: t('tab.devices'),},+ enablePersistentSandbox && {+ icon: ContainerIcon,+ key: SettingsTabs.Environments,+ label: t('tab.environments'),+ },(enableBusinessFeatures || isDesktop) && {icon: BellIcon,key: SettingsTabs.Notification,@@ -320,6 +329,7 @@ export const useCategory = () => {isDevMode,enableOAuthApps,enableIntegrations,+ enablePersistentSandbox,avatarUrl,username,]);diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex 8b698f10e95..3d42f32e943 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -26,6 +26,7 @@ type LabFeatureI18nKey =| 'integrations'| 'messageTextSelectionActions'| 'oauthApps'+ | 'persistentSandbox'| 'projects'| 'selfLearning';@@ -116,6 +117,12 @@ export const LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['integrations', 'github', 'github app', 'pull request'],stage: 'alpha',},+ {+ flag: 'enablePersistentSandbox',+ i18nKey: 'persistentSandbox',+ searchKeywords: ['persistent sandbox', 'workspace', 'sandbox storage'],+ stage: 'alpha',+ },{flag: 'enableArtifactDeployment',i18nKey: 'artifactDeployment',diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex 3aebc70ad34..fcd563da5fb 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -69,6 +69,13 @@ export const TAB_SEARCH_EN_KEYWORDS: Partial<Record<SettingsTabs, string[]>> = {[SettingsTabs.Hotkey]: ['hotkey', 'shortcut', 'keyboard'],[SettingsTabs.Labs]: ['labs', 'experiment', 'beta', 'preview', 'developer'],[SettingsTabs.Memory]: ['memory', 'memories', 'personalization'],+ [SettingsTabs.Environments]: [+ 'sandbox',+ 'environments',+ 'instances',+ 'setup script',+ 'repository',+ ],[SettingsTabs.Messenger]: ['messenger','chat platform',diff --git a/src/features/VisibilityConfirmContent/index.tsx b/src/features/VisibilityConfirmContent/index.tsxindex 1a7fb9eadf7..a6c9175bea5 100644--- a/src/features/VisibilityConfirmContent/index.tsx+++ b/src/features/VisibilityConfirmContent/index.tsx@@ -8,6 +8,7 @@ import {EyeOffIcon,FolderIcon,InfoIcon,+ KeyRoundIcon,type LucideIcon,UsersIcon,} from 'lucide-react';@@ -17,6 +18,14 @@ import { useTranslation } from 'react-i18next';export type VisibilityConfirmVariant = 'makePrivate' | 'publish';export interface VisibilityConfirmContentProps {+ /**+ * The resource carries state captured from a running session โ an+ * environment's home directory, its CLI logins, whatever a setup command+ * left behind. Publishing it does not only make the row visible: members+ * can run instances of it and reach that state. "Members will see this"+ * does not say any of it, so the caller has to ask for the bullet that does.+ */+ capturedState?: boolean;/*** The resource sits in a library. Going private does not pull it out of one* โ the row stays filed where the author put it and simply stops resolving@@ -41,6 +50,14 @@ interface VariantConfig {items: readonly Item[];}+/** Appended to `publish` when the caller says the resource carries captured session state. */+const CAPTURED_STATE_ITEM: Item = {+ emphasis: true,+ icon: KeyRoundIcon,+ key: 'visibilityConfirm.publish.itemCapturedState',+ tone: 'danger',+};+/** Appended to `makePrivate` when the caller says the resource is filed in a library. */const LIBRARY_ITEM: Item = {icon: FolderIcon,@@ -167,36 +184,45 @@ const rowIconClass = (tone: Tone) => {* carried by the destructive vs primary button colour, so we don't need a* separate hero icon here.*/-const VisibilityConfirmContent = memo<VisibilityConfirmContentProps>(({ inLibrary, variant }) => {- const { t } = useTranslation('common');- const config = CONFIG[variant];- const irreversibleSuffix = t('visibilityConfirm.irreversible');- // Second-to-last, so the irreversible tail keeps the closing position it- // holds in both variants.- const items =- variant === 'makePrivate' && inLibrary- ? [...config.items.slice(0, -1), LIBRARY_ITEM, ...config.items.slice(-1)]+const VisibilityConfirmContent = memo<VisibilityConfirmContentProps>(+ ({ capturedState, inLibrary, variant }) => {+ const { t } = useTranslation('common');+ const config = CONFIG[variant];+ const irreversibleSuffix = t('visibilityConfirm.irreversible');+ // Second-to-last, so the irreversible tail keeps the closing position it+ // holds in both variants.+ const extra =+ variant === 'makePrivate' && inLibrary+ ? LIBRARY_ITEM+ : variant === 'publish' && capturedState+ ? CAPTURED_STATE_ITEM+ : undefined;+ const items = extra+ ? [...config.items.slice(0, -1), extra, ...config.items.slice(-1)]: config.items;- return (- <ul className={styles.list}>- {items.map((item) => {- const ItemIcon = item.icon;- return (- <li className={styles.row} key={item.key}>- <span className={`${styles.rowIcon} ${rowIconClass(item.tone)}`}>- <Icon icon={ItemIcon} size={14} />- </span>- <span className={item.emphasis ? styles.emphasis : undefined}>- {t(item.key as any)}- {item.showIrreversible && <span className={styles.suffix}>{irreversibleSuffix}</span>}- </span>- </li>- );- })}- </ul>- );-});+ return (+ <ul className={styles.list}>+ {items.map((item) => {+ const ItemIcon = item.icon;+ return (+ <li className={styles.row} key={item.key}>+ <span className={`${styles.rowIcon} ${rowIconClass(item.tone)}`}>+ <Icon icon={ItemIcon} size={14} />+ </span>+ <span className={item.emphasis ? styles.emphasis : undefined}>+ {t(item.key as any)}+ {item.showIrreversible && (+ <span className={styles.suffix}>{irreversibleSuffix}</span>+ )}+ </span>+ </li>+ );+ })}+ </ul>+ );+ },+);VisibilityConfirmContent.displayName = 'VisibilityConfirmContent';diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.tsindex 42209929f3c..2532ed8ea71 100644--- a/src/features/Workspace/workspaceAwarePath.ts+++ b/src/features/Workspace/workspaceAwarePath.ts@@ -49,6 +49,7 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set(['creds','credits','devices',+ 'environments','general','hotkey',// Third-party integrations bind to the workspace that connected them.diff --git a/src/features/WorkspaceSetting/Layout.test.tsx b/src/features/WorkspaceSetting/Layout.test.tsxindex 714a6c091ca..d87a84f02ce 100644--- a/src/features/WorkspaceSetting/Layout.test.tsx+++ b/src/features/WorkspaceSetting/Layout.test.tsx@@ -24,6 +24,7 @@ vi.mock('./hooks/useCategory', () => ({{ key: 'general', label: 'General' },{ key: 'members', label: 'Members' },{ key: 'devices', label: 'Devices' },+ { key: 'environments', label: 'Environments' },{ key: 'plans', label: 'Plans' },{ key: 'billing', label: 'Billing' },{ key: 'credits', label: 'Credits' },@@ -62,6 +63,7 @@ describe('WorkspaceSettingsContentLayout', () => {['general', 'General'],['members', 'Members'],['devices', 'Devices'],+ ['environments', 'Environments'],['plans', 'Plans'],['billing', 'Billing'],['credits', 'Credits'],diff --git a/src/features/WorkspaceSetting/Layout.tsx b/src/features/WorkspaceSetting/Layout.tsxindex b06c7bc37ec..85c306d778f 100644--- a/src/features/WorkspaceSetting/Layout.tsx+++ b/src/features/WorkspaceSetting/Layout.tsx@@ -22,6 +22,7 @@ const COMPACT_HEADER_TABS = new Set<string>([WorkspaceSettingsTabs.Creds,WorkspaceSettingsTabs.Credits,WorkspaceSettingsTabs.Devices,+ WorkspaceSettingsTabs.Environments,WorkspaceSettingsTabs.General,WorkspaceSettingsTabs.Hotkey,WorkspaceSettingsTabs.Integrations,diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsxindex 72cf80e3cc2..76328d8f117 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx@@ -10,6 +10,7 @@ import {Building2,ChartColumnBigIcon,Coins,+ ContainerIcon,CreditCard,Database,EllipsisIcon,@@ -75,6 +76,9 @@ 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) => [userProfileSelectors.userAvatar(s),@@ -159,6 +163,11 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Devices,label: t('tab.devices'),},+ enablePersistentSandbox && {+ icon: ContainerIcon,+ key: WorkspaceSettingsTabs.Environments,+ label: t('tab.environments'),+ },{icon: BellIcon,key: WorkspaceSettingsTabs.Notification,@@ -169,7 +178,7 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Stats,label: tAuth('tab.stats'),},- ],+ ].filter(Boolean) as WorkspaceSettingCategoryItem[],key: WorkspaceSettingsGroupKey.General,title: t('workspaceSetting.group.workspace'),},@@ -320,6 +329,7 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =tSubscription,enableOAuthApps,enableIntegrations,+ enablePersistentSandbox,canManageWorkspace,canViewBilling,canCreateContent,diff --git a/src/libs/trusted-client/index.test.ts b/src/libs/trusted-client/index.test.tsindex 1bf6106c552..67a2f855a94 100644--- a/src/libs/trusted-client/index.test.ts+++ b/src/libs/trusted-client/index.test.ts@@ -51,4 +51,42 @@ describe('generateTrustedClientToken', () => {);expect(createTrustedClientToken).toHaveBeenCalledWith(expect.anything(), 'client-secret');});++ // The claim is what the execution plane routes a persistent sandbox on, so it+ // has to be covered by the signature โ a caller must not be able to supply it+ // alongside the token.+ it('signs the sandbox workspace claim into the payload', () => {+ generateTrustedClientToken({+ email: '[email protected]',+ sandboxStorage: { key: 'ws-user_real', quotaBytes: 2048 },+ userId: 'user_real',+ });++ expect(createTrustedClientToken).toHaveBeenCalledWith(+ expect.objectContaining({ sandboxStorage: { key: 'ws-user_real', quotaBytes: 2048 } }),+ 'client-secret',+ );+ });++ // The published SDK builder has no parameter for it, so the field is attached+ // afterwards; passing it in would be silently dropped.+ it('does not route the claim through the SDK payload builder', () => {+ generateTrustedClientToken({+ sandboxStorage: { key: 'ws-user_real', quotaBytes: 2048 },+ userId: 'user_real',+ });++ expect(buildTrustedClientPayload).toHaveBeenCalledWith(+ expect.not.objectContaining({ sandboxStorage: expect.anything() }),+ );+ });++ // Free tier is the overwhelming majority of tokens; leaving the key out keeps+ // them exactly as they are today rather than carrying an explicit null.+ it('omits the claim entirely when there is no entitlement', () => {+ generateTrustedClientToken({ sandboxStorage: null, userId: 'user_real' });++ const [payload] = vi.mocked(createTrustedClientToken).mock.calls[0];+ expect(payload).not.toHaveProperty('sandboxStorage');+ });});diff --git a/src/libs/trusted-client/index.ts b/src/libs/trusted-client/index.tsindex 9c2fdb9f3b6..3703300f41d 100644--- a/src/libs/trusted-client/index.ts+++ b/src/libs/trusted-client/index.ts@@ -1,10 +1,24 @@-import { buildTrustedClientPayload, createTrustedClientToken } from '@lobehub/market-sdk';+import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';+import {+ buildTrustedClientPayload,+ createTrustedClientToken,+ type TrustedClientPayload,+} from '@lobehub/market-sdk';import { appEnv } from '@/envs/app';export interface TrustedClientUserInfo {email?: string;name?: string;+ /**+ * Persistent-sandbox entitlement for this principal, resolved by+ * `resolveSandboxStorageClaim`. Absent โ the shape every caller that does+ * not create sandboxes leaves it in โ means the sandbox stays ephemeral.+ *+ * It rides the token rather than the request body on purpose: it is the one+ * thing the execution plane must not let a caller choose for itself.+ */+ sandboxStorage?: SandboxStorageClaim | null;userId: string;/*** Cloud workspace id the request acts on behalf of. When set, Market treats@@ -67,7 +81,19 @@ export const generateTrustedClientToken = (userInfo: TrustedClientUserInfo): strworkspaceId: userInfo.workspaceId,});- return createTrustedClientToken(payload, MARKET_TRUSTED_CLIENT_SECRET);+ // Attached after the builder rather than through it: the published SDK's+ // `buildTrustedClientPayload` still has a fixed parameter list that predates+ // this claim, while Market's verifier already reads it off the decrypted+ // payload. `createTrustedClientToken` signs whatever object it is handed, so+ // the field is covered by the signature exactly like the built-in ones.+ // Omitted when there is no entitlement, which is the free-tier shape and+ // leaves today's tokens unchanged.+ // TODO: pass through buildTrustedClientPayload once the SDK carries it.+ const signedPayload: TrustedClientPayload = userInfo.sandboxStorage+ ? ({ ...payload, sandboxStorage: userInfo.sandboxStorage } as TrustedClientPayload)+ : payload;++ return createTrustedClientToken(signedPayload, MARKET_TRUSTED_CLIENT_SECRET);} catch (error) {console.error('Failed to generate trusted client token:', error);return undefined;diff --git a/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsxnew file mode 100644index 00000000000..bfd8f39a624--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx@@ -0,0 +1,67 @@+'use client';++import type { EnvironmentVisibility } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Tabs } from '@lobehub/ui/base-ui';+import { LockIcon, UsersIcon } from 'lucide-react';+import { memo, useState } from 'react';+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+ * workspace device page draws, for the same reason.+ *+ * - Workspace: what members have published. Running in one means running in its+ * instances, which carry whatever a session left in them.+ * - Private: the caller's own, which is where every environment starts.+ *+ * The tab also decides where a new environment lands, so creating one from the+ * Private tab cannot quietly publish it.+ *+ * The tabs are handed to the manager rather than rendered above it: they belong+ * on the same row as the actions, and the manager owns that row.+ */+const WorkspaceEnvironmentsSetting = memo(() => {+ const { t } = useTranslation('setting');+ const [visibility, setVisibility] = useState<EnvironmentVisibility>('public');++ return (+ <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ <EnvironmentsGate>+ {/* Keyed on the pool so the selected row and its open panel do not+ survive a tab switch โ the environment they pointed at is not in+ the list any more. */}+ <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>+ </Flexbox>+ );+});++WorkspaceEnvironmentsSetting.displayName = 'WorkspaceEnvironmentsSetting';++export default WorkspaceEnvironmentsSetting;diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex 920769160ff..76317a8af7d 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -310,6 +310,21 @@ describe('contextEngineering', () => {});});+ it('renders the cloud-sandbox workspace placeholders to the ephemeral wording on the client', async () => {+ const output = await contextEngineering({+ messages: [{ content: 'Hello', role: 'user' }] as UIChatMessage[],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '<env>{{sandbox_workspace}}</env><session>{{sandbox_session_files}}</session>',+ });++ const content = String(output[0].content);+ expect(content).not.toContain('{{sandbox_workspace}}');+ expect(content).not.toContain('{{sandbox_session_files}}');+ expect(content).toContain('Files created here are temporary and session-specific');+ expect(content).toContain('<session>- Files from previous sessions may not persist</session>');+ });+describe('handle with files content in server mode', () => {it('should includes files', async () => {runtimeFlags.isServerMode = true;diff --git a/src/services/chat/mecha/contextFactProviders.ts b/src/services/chat/mecha/contextFactProviders.tsindex c6becbfb8e9..56aca85ade1 100644--- a/src/services/chat/mecha/contextFactProviders.ts+++ b/src/services/chat/mecha/contextFactProviders.ts@@ -7,6 +7,7 @@ import { lambdaClient } from '@/libs/trpc/client';import { agentService } from '@/services/agent';import { messageService } from '@/services/message';import { notebookService } from '@/services/notebook';+import { sandboxStorageService } from '@/services/sandboxStorage';import { userService } from '@/services/user';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';@@ -226,6 +227,16 @@ export const createBrowserContextFactProviders = ({.currentUserFiles(getChatStoreState()).map((file) => ({ name: file.name, size: file.size })),+ // Asked of the server, because the placement follows an entitlement only it+ // can resolve. Left unimplemented, the prompt described a disposable sandbox+ // to a run that had a persistent directory, and the model โ told its files+ // would not survive โ cloned into /tmp.+ resolveSandboxPersistence: async () => {+ const topicId = getChatStoreState().activeTopicId ?? undefined;+ const placement = await sandboxStorageService.resolveSessionPlacement({ topicId });+ return placement ?? undefined;+ },+listTopicMessages: async (topic) => {const msgs = await messageService.getMessages({agentId,diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.tsindex 9e595fe6316..c32f63ce3a6 100644--- a/src/services/projectFile.test.ts+++ b/src/services/projectFile.test.ts@@ -18,6 +18,11 @@ const mockDeviceClient = vi.hoisted(() => ({searchProjectFiles: { query: vi.fn() },}));+const mockSandboxStorageService = vi.hoisted(() => ({+ getStorage: vi.fn(),+ listFiles: vi.fn(),+}));+const mockLocalFileService = vi.hoisted(() => ({copyAssetForPublish: vi.fn(),copyLocalFiles: vi.fn(),@@ -53,6 +58,10 @@ vi.mock('@/services/electron/localFileService', () => ({localFileService: mockLocalFileService,}));+vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: mockSandboxStorageService,+}));+describe('projectFileService', () => {afterEach(() => {vi.clearAllMocks();@@ -410,4 +419,46 @@ describe('projectFileService', () => {]);});});++ it('marks sandbox directories with a trailing slash so the tree can nest them', async () => {+ const { projectFileService } = await import('./projectFile');++ mockSandboxStorageService.getStorage.mockResolvedValue({ dir: '/mnt/workspace/ws-1' });+ // One flat recursive listing, the way the workspace API answers: every+ // path relative to the workspace root, directories with no trailing slash.+ mockSandboxStorageService.listFiles.mockResolvedValue({+ entries: [+ { isDirectory: true, name: 'Spoon-Knife', path: 'hello-dev/Spoon-Knife' },+ { isDirectory: false, name: 'README.md', path: 'hello-dev/Spoon-Knife/README.md' },+ { isDirectory: false, name: 'README', path: 'hello-dev/README' },+ ],+ truncated: false,+ });++ const index = await projectFileService.getProjectFileIndex({+ sandboxInstanceId: 'inst-1',+ scope: 'hello-dev',+ });++ expect(index?.entries).toEqual([+ {+ isDirectory: true,+ name: 'Spoon-Knife',+ path: '/mnt/workspace/ws-1/hello-dev/Spoon-Knife',+ relativePath: 'Spoon-Knife/',+ },+ {+ isDirectory: false,+ name: 'README.md',+ path: '/mnt/workspace/ws-1/hello-dev/Spoon-Knife/README.md',+ relativePath: 'Spoon-Knife/README.md',+ },+ {+ isDirectory: false,+ name: 'README',+ path: '/mnt/workspace/ws-1/hello-dev/README',+ relativePath: 'README',+ },+ ]);+ });});diff --git a/src/services/projectFile.ts b/src/services/projectFile.tsindex e760386732f..10d1a53acdc 100644--- a/src/services/projectFile.ts+++ b/src/services/projectFile.ts@@ -19,6 +19,7 @@ import { mutate } from '@/libs/swr';import { localFileKeys } from '@/libs/swr/keys';import { lambdaClient } from '@/libs/trpc/client';import { type LocalFilePreview, localFileService } from '@/services/electron/localFileService';+import { sandboxStorageService } from '@/services/sandboxStorage';export type { LocalFilePreview } from '@/services/electron/localFileService';@@ -101,19 +102,107 @@ export const refreshProjectFiles = async (* electron-vs-lambda decision never leaks up. (Parallels `gitService`.)*/class ProjectFileService {- /** Project file index (tree) for a working directory. */+ /**+ * Project file index (tree) for a working directory.+ *+ * A third host, alongside the device RPC and Electron: the cloud sandbox's+ * persistent workspace, which is reached over the workspace API and named by+ * the topic whose warm session should serve it.+ */async getProjectFileIndex({deviceId,+ sandboxInstanceId,+ sandboxTopicId,scope,}: {deviceId?: string;+ /**+ * Which instance's directory to read. Addressed directly rather than left+ * for the server to derive from the topic, so a tree can be shown before+ * the conversation exists โ the way a device's tree needs no conversation+ * either.+ */+ sandboxInstanceId?: string;+ sandboxTopicId?: string;scope: string;}): Promise<ProjectFileIndexResult | undefined> {+ if (sandboxTopicId || sandboxInstanceId) {+ return this.getSandboxFileIndex({+ instanceId: sandboxInstanceId,+ scope,+ topicId: sandboxTopicId,+ });+ }+return deviceId? ((await lambdaClient.device.getProjectFileIndex.query({ deviceId, scope })) ?? undefined): localFileService.getProjectFileIndex({ scope });}+ /**+ * The sandbox workspace as a file index.+ *+ * Assembled here rather than server-side because the workspace API answers in+ * its own vocabulary โ one flat recursive listing of paths relative to the+ * workspace root โ and the tree wants a project root with paths relative to+ * it. Nothing on that side knows about git, so there are no ignore rules to+ * report and no collapsed directories to expand: the index is a plain walk,+ * and says so.+ */+ private async getSandboxFileIndex({+ instanceId,+ scope,+ topicId,+ }: {+ instanceId?: string;+ scope: string;+ topicId?: string;+ }): Promise<ProjectFileIndexResult | undefined> {+ const [workspace, listing] = await Promise.all([+ sandboxStorageService.getStorage(),+ // 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.+ sandboxStorageService.listFiles({+ instanceId,+ path: scope || undefined,+ recursive: true,+ topicId,+ }),+ ]);++ if (!workspace?.dir) return undefined;++ const prefix = scope ? `${scope}/` : '';+ const root = scope ? `${workspace.dir}/${scope}` : workspace.dir;++ return {+ entries: listing.entries.map((entry) => {+ // The workspace speaks in paths relative to ITS root; the tree resolves+ // everything against the project root it was given.+ const relative = entry.path.startsWith(prefix)+ ? entry.path.slice(prefix.length)+ : entry.path;++ return {+ isDirectory: entry.isDirectory,+ name: entry.name,+ path: `${workspace.dir}/${entry.path}`,+ // A directory's path carries a trailing slash, which is how every+ // consumer of this index tells a directory row from a file row by+ // its id alone: the tree derives each row's parent by trimming the+ // last segment and looking the result up. Without it nothing finds+ // its parent, and a whole checkout lands flat at the project root.+ relativePath: entry.isDirectory ? `${relative}/` : relative,+ };+ }),+ indexedAt: new Date().toISOString(),+ root,+ source: 'sandbox',+ truncated: listing.truncated,+ };+ }+/** Search files within a project working directory. Matching runs on the file host. */async searchProjectFiles({changedOnly,diff --git a/src/services/sandboxStorage.ts b/src/services/sandboxStorage.tsnew file mode 100644index 00000000000..95a00be916e--- /dev/null+++ b/src/services/sandboxStorage.ts@@ -0,0 +1,208 @@+import type { EnvironmentSource, EnvironmentVisibility } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++/**+ * Renderer-side data layer for the persistent cloud-sandbox workspace.+ *+ * Every path is relative to the workspace 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.+ *+ * `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`.+ *+ * `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;+ 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;+ }) => lambdaClient.sandboxStorage.createEnvironment.mutate(params);++ /**+ * 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;+ 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+ * the UI shows it as unused rather than missing.+ *+ * Reaching the snapshot store needs a live sandbox session, so this can take+ * seconds on a cold start and callers should render a loading state.+ */+ listInstances = async (+ params: { environmentId?: string; topicId?: string; withSizes?: boolean } = {},+ ) => lambdaClient.sandboxStorage.listInstances.query(params);++ /**+ * The run history of every instance of one environment, newest first: each+ * sandbox session that ran it and each build of it, with how it ended and+ * whether its snapshot was saved. Read from the control plane's records โ+ * no sandbox session, no wait.+ */+ listInstanceSessions = async (params: { environmentId: string; limit?: number }) =>+ lambdaClient.sandboxStorage.listInstanceSessions.query(params);++ /** One instance, from the database alone โ no sandbox session, no wait. */+ getInstance = async (params: { id: string }) =>+ lambdaClient.sandboxStorage.getInstance.query(params);++ createInstance = async (params: {+ environmentId: string;+ name: string;+ workingDirectory: string;+ }) => lambdaClient.sandboxStorage.createInstance.mutate(params);++ /**+ * Materializes an instance: clones the environment's sources and runs its+ * bootstrap. Returns as soon as the build has started.+ *+ * Separate from {@link createInstance} because starting one attaches a+ * sandbox session, which is a cold start โ the dialog closes on the insert+ * and this follows it.+ */+ startInstanceBuild = async (params: { id: string; topicId?: string }) =>+ lambdaClient.sandboxStorage.startInstanceBuild.mutate(params);++ /** Follows a build, and settles the instance once it ends. */+ instanceBuildStatus = async (params: { id: string; logOffset?: number; topicId?: string }) =>+ lambdaClient.sandboxStorage.instanceBuildStatus.query(params);++ /**+ * A new instance of an environment, with its directory derived server-side.+ *+ * What the composer calls: someone picking an environment has not chosen a+ * folder, and the folder holds outputs that do not exist yet, so asking would+ * make them invent an answer before the work.+ */+ createInstanceForEnvironment = async (params: { environmentId: string }) =>+ lambdaClient.sandboxStorage.createInstanceForEnvironment.mutate(params);++ /** Only the label. The directory does not move โ the built state sits in it. */+ renameInstance = async (params: { id: string; name: string }) =>+ lambdaClient.sandboxStorage.renameInstance.mutate(params);++ /** A second directory that starts with everything the first one had installed. */+ /**+ * Where this topic's sandbox commands run, for the prompt that describes it.+ * The placement only โ the entitlement it follows never leaves the server.+ */+ resolveSessionPlacement = async (params: { topicId?: string }) =>+ lambdaClient.sandboxStorage.resolveSessionPlacement.query(params);++ copyInstance = async (params: { id: string; name: string; workingDirectory: string }) =>+ lambdaClient.sandboxStorage.copyInstance.mutate(params);++ /** Refused while a conversation is still using it โ the caller surfaces that. */+ removeInstance = async (params: { id: string; topicId?: string }) =>+ lambdaClient.sandboxStorage.removeInstance.mutate(params);++ /** Create a directory (parents included, idempotent). */+ createDirectory = async (params: { 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.+ */+ getEntitlement = async () => lambdaClient.sandboxStorage.getEntitlement.query();++ /** Quota and last measured usage of the workspace directory. */+ getStorage = async () => lambdaClient.sandboxStorage.getStorage.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();++ listFiles = async (+ params: { 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);++ removeFile = async (params: {+ instanceId?: string;+ path: string;+ recursive?: boolean;+ topicId?: string;+ }) => lambdaClient.sandboxStorage.removeFile.mutate(params);+}++export const sandboxStorageService = new SandboxStorageService();diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex 923f8e51275..312096a3ed0 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -1456,6 +1456,14 @@ const createMainAreaChildrenDefinition = (options: MainAreaRouteOptions = {}): Rhandle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },path: 'devices',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/environments'),+ 'Desktop > Workspace > Settings > Environments',+ ),+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },+ path: 'environments',+ },// 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.tsnew file mode 100644index 00000000000..88642fdf6b1--- /dev/null+++ b/src/store/chat/pendingSandboxSelection.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';++import {+ consumePendingSandboxSelection,+ getPendingSandboxSelection,+ setPendingSandboxSelection,+ subscribePendingSandboxSelection,+} from './pendingSandboxSelection';++describe('pendingSandboxSelection', () => {+ it('notifies a subscriber on set and on consume โ a second reader must move too', () => {+ // Two components read this: the switch that writes and the chip that only+ // reads. A Map cannot tell React it changed, so a write that told only its+ // own component left the chip on the old value.+ const listener = vi.fn();+ const unsubscribe = subscribePendingSandboxSelection(listener);++ setPendingSandboxSelection('agent-1', { mode: 'persistent' });+ expect(listener).toHaveBeenCalledTimes(1);+ expect(getPendingSandboxSelection('agent-1')).toEqual({ mode: 'persistent' });++ consumePendingSandboxSelection('agent-1');+ expect(listener).toHaveBeenCalledTimes(2);+ expect(getPendingSandboxSelection('agent-1')).toBeUndefined();++ unsubscribe();+ setPendingSandboxSelection('agent-1', { mode: 'ephemeral' });+ expect(listener).toHaveBeenCalledTimes(2);+ consumePendingSandboxSelection('agent-1');+ });++ it('returns a stable value between writes, as useSyncExternalStore requires', () => {+ setPendingSandboxSelection('agent-2', { instanceId: 'i', mode: 'persistent' });+ expect(getPendingSandboxSelection('agent-2')).toBe(getPendingSandboxSelection('agent-2'));+ consumePendingSandboxSelection('agent-2');+ });+});diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.tsnew file mode 100644index 00000000000..4ed8291aadf--- /dev/null+++ b/src/store/chat/pendingSandboxSelection.ts@@ -0,0 +1,68 @@+import type { SandboxSelection } from '@/features/ChatInput/ControlBar/SandboxInstancePicker';++/**+ * Module-level singleton for a sandbox selection made before the topic exists.+ *+ * The composer's picker is offered on a conversation that has not been created+ * yet, so there is nothing to write the choice to. Buffering it here keyed by+ * agentId lets the first send carry it: `conversationLifecycle` reads it into+ * the optimistic topic's metadata and `gateway.ts` sends it as+ * `initialTopicMetadata`, so the SERVER topic is born with it.+ *+ * 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+ * would point other members at storage that is not theirs.+ *+ * Deliberately not persisted either: this is a choice about the conversation+ * being started right now, and a reload before the first message is a new start.+ *+ * Shaped after `pendingTopicRepos`, which solves the same problem for GitHub+ * repositories. Kept separate rather than generalized so that path, which+ * already works, is not disturbed.+ */++const map = new Map<string, SandboxSelection>();++// More than one component reads this โ the execution-device switch and the+// working-directory chip โ and a Map cannot tell React that it changed. A+// write notifies every subscriber, so a flip in one place moves the other;+// without this, whichever component did not do the writing kept rendering the+// old value until something unrelated re-rendered it.+const listeners = new Set<() => void>();++const emit = () => {+ for (const listener of listeners) listener();+};++/** Subscribe to writes; returns the unsubscribe. Shaped for `useSyncExternalStore`. */+export const subscribePendingSandboxSelection = (listener: () => void): (() => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+};++/** Record the pending selection for an agent; `undefined` clears it. */+export const setPendingSandboxSelection = (agentId: string, selection?: SandboxSelection): void => {+ if (selection) map.set(agentId, selection);+ else map.delete(agentId);+ emit();+};++/** Read without consuming โ what the closed chip names itself after. */+export const getPendingSandboxSelection = (agentId: string): SandboxSelection | undefined =>+ map.get(agentId);++/**+ * Consume the pending selection for an agent. Cleared so the NEXT conversation+ * starts at the default: the choice was made for the topic that has now been+ * created, and carrying it forward would silently bind conversations nobody+ * chose it for.+ */+export const consumePendingSandboxSelection = (agentId: string): SandboxSelection | undefined => {+ const selection = map.get(agentId);+ map.delete(agentId);+ emit();+ return selection;+};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex a1f102d55df..5ccb7ac2dab 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -61,6 +61,7 @@ import {chatConfigByIdSelectors,} from '@/store/agent/selectors';import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';+import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';import { getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import {dbMessageSelectors,@@ -1303,10 +1304,28 @@ export class ConversationLifecycleActionImpl {newTopicDeviceId? { boundDeviceId: newTopicDeviceId }: undefined;+ // Chosen in the composer while no topic existed to write it to. Not gated+ // on runtime: the map is only ever filled by the sandbox picker, which only+ // renders under a cloud-sandbox target.+ const pendingSandboxSelection =+ willCreateNewTopic && operationContext.agentId+ ? getPendingSandboxSelection(operationContext.agentId)+ : undefined;+ const sandboxInstanceMetadata: ChatTopicMetadata | undefined = pendingSandboxSelection+ ? {+ sandboxInstanceId: pendingSandboxSelection.instanceId,+ sandboxMode: pendingSandboxSelection.mode,+ }+ : undefined;/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */- const optimisticTopicMetadata = newTopicReasoningSnapshot- ? { ...workingDirectoryMetadata, ...newTopicReasoningSnapshot }- : workingDirectoryMetadata;+ const optimisticTopicMetadata =+ newTopicReasoningSnapshot || sandboxInstanceMetadata+ ? {+ ...workingDirectoryMetadata,+ ...sandboxInstanceMetadata,+ ...newTopicReasoningSnapshot,+ }+ : workingDirectoryMetadata;// The sidebar row was already inserted (title + model) before the awaits// above; the cwd/repos metadata only resolves here, so patch it on now.diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 7db40824735..7102eddcd1e 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -49,6 +49,10 @@ import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import {+ consumePendingSandboxSelection,+ getPendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';@@ -907,7 +911,20 @@ export class GatewayActionImpl {// it โ the server can't read client-local state, and without this a// workspace hetero run's first send would fall back to the device default// cwd instead of the member's pick.- const initialTopicMetadata =+ // The instance the composer bound before any topic existed. Merged rather+ // than folded into the branches below: it is orthogonal to the cwd, and a+ // conversation can start with one, the other, or both.+ const pendingSandboxSelection =+ isCreateNewTopic && executionContext.agentId+ ? getPendingSandboxSelection(executionContext.agentId)+ : undefined;+ const sandboxTopicMetadata = pendingSandboxSelection+ ? {+ sandboxInstanceId: pendingSandboxSelection.instanceId,+ sandboxMode: pendingSandboxSelection.mode,+ }+ : undefined;+ const cwdTopicMetadata =pendingRepos.length > 0? {repos: pendingRepos,@@ -921,6 +938,10 @@ export class GatewayActionImpl {workingDirectoryConfig: optimisticTopic.metadata.workingDirectoryConfig,}: undefined;+ const initialTopicMetadata =+ cwdTopicMetadata || sandboxTopicMetadata+ ? { ...cwdTopicMetadata, ...sandboxTopicMetadata }+ : undefined;// Honour user-initiated cancel during phase-1 init: while we await the// execAgentTask round-trip the caller's loading state (e.g. `sendMessage`)@@ -1169,8 +1190,11 @@ export class GatewayActionImpl {}if (isCreateNewTopic && result.topicId) {- // Topic created successfully โ now safe to clear the pending repo selection.- if (messageContext.agentId) consumePendingTopicRepos(messageContext.agentId);+ // Topic created successfully โ now safe to clear the pending selections.+ if (messageContext.agentId) {+ consumePendingTopicRepos(messageContext.agentId);+ consumePendingSandboxSelection(messageContext.agentId);+ }if (optimisticTopic) {const topicMetadata = optimisticTopic.metadata ?? initialTopicMetadata;this.#get().internal_replaceTopicId({diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 2bd4c0d01b4..8c85372dbf8 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -71,6 +71,7 @@ export enum SettingsTabs {Credits = 'credits',Creds = 'credential',Devices = 'devices',+ Environments = 'environments',Hotkey = 'hotkey',/** @deprecated Use ServiceModel instead */Image = 'image',diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 40c972d249c..6c795e21c64 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -26,6 +26,8 @@ export const labPreferSelectors = {DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??false,enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,+ enablePersistentSandbox: (s: UserState): boolean =>+ s.preference.lab?.enablePersistentSandbox ?? false,enableSelfLearning: (s: UserState): boolean => s.preference.lab?.enableSelfLearning ?? false,enableProjects: (s: UserState): boolean => s.preference.lab?.enableProjects ?? false,// `updateLab` writes both keys, but older clients only write the legacydiff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.tsindex 88ba10521cd..e65a03fae89 100644--- a/src/types/workspaceSettings.ts+++ b/src/types/workspaceSettings.ts@@ -17,6 +17,7 @@ export enum WorkspaceSettingsTabs {Credits = 'credits',Creds = 'credential',Devices = 'devices',+ Environments = 'environments',General = 'general',Hotkey = 'hotkey',Integrations = 'integrations',