๐คฏ 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(chat-input): drop the cloud sandbox Environment picker (#23766)
Rdmclin2373cd18ca6e5
diff --git a/apps/server/src/services/sandbox/__tests__/session.test.ts b/apps/server/src/services/sandbox/__tests__/session.test.tsindex c84677959c8..08a635417af 100644--- a/apps/server/src/services/sandbox/__tests__/session.test.ts+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts@@ -114,151 +114,59 @@ describe('resolveSandboxSessionConfig', () => {});});- // 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 () => {+ // T-14825: the cloud sandbox is not set up from an environment any more. A+ // conversation still bound to a legacy environment directory runs in that+ // directory as a plain folder on the drive โ its files stay where they are.+ it('runs a legacy environment directory as a folder, without its environment', async () => {await expect(resolve()).resolves.toEqual({claim: CLAIM,drive: 'personal',cwd: 'projects/atlas',- environment: INSTANCE_ID,- mode: 'persistent',+ mode: 'drive',});});- // 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.- 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',- });+ // The row outlives a folder renamed or deleted through the drive browser:+ // the run falls back like any other missing folder instead of a bad cwd.+ it("falls back when a legacy instance's folder is gone from the drive", async () => {+ mocks.driveFolderExists.mockResolvedValue(false);await expect(resolve()).resolves.toEqual({claim: CLAIM,drive: 'personal',- cwd: 'projects/atlas',- environment: INSTANCE_ID,- mode: 'persistent',- specification: { sources: [{ kind: 'git', url: 'https://github.com/a/b' }] },- workingDir: '/root/work',- });- });-- // Regression: 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',- },+ fallback: 'directoryMissing',+ mode: 'ephemeral',});+ expect(mocks.driveFolderExists).toHaveBeenCalledWith(+ expect.objectContaining({ claim: CLAIM, path: 'projects/atlas' }),+ );+ expect(mocks.ensureDriveFolder).not.toHaveBeenCalled();});- // 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 () => {+ // Neither the definition the instance was built from, nor its snapshot, nor+ // the checkout its build left on local disk come along.+ it("leaves the instance's definition, snapshot and checkout behind", async () => {findInstanceById.mockResolvedValue({configurationSnapshot: {- credentials: [{ headers: { Authorization: 'Bearer nope' }, host: 'github.com' }],+ bootstrapCommand: 'pnpm install',env: { NODE_ENV: 'production' },- requirements: { memoryGiB: 8 },+ sources: [{ kind: 'git', url: 'https://github.com/a/b' }],},id: INSTANCE_ID,+ status: 'ready',workingDirectory: 'projects/atlas',});- const { specification } = await resolve();- expect(specification).toEqual({ env: { NODE_ENV: 'production' } });- });-- // `kind` is the product's own: an instance whose environment gained one must- // send exactly what it sent before, or the execution plane would read every- // such session as running a different specification from its build.- it('sends the same specification whether or not the definition carries a kind', async () => {- const definition = {- bootstrapCommand: 'pnpm install',- env: { NODE_ENV: 'production' },- excludePaths: ['node_modules'],- internetAccess: false,- maintenanceCommand: 'git pull --ff-only',- sources: [{ kind: 'git', url: 'https://github.com/a/b' }],- };-- findInstanceById.mockResolvedValue({- configurationSnapshot: definition,- id: INSTANCE_ID,- workingDirectory: 'projects/atlas',- });- const { specification: before } = await resolve();-- findInstanceById.mockResolvedValue({- configurationSnapshot: { ...definition, kind: 'code' },- id: INSTANCE_ID,- workingDirectory: 'projects/atlas',- });- const { specification: after } = await resolve();-- expect(after).toEqual(before);- expect(after).not.toHaveProperty('kind');- });-- // 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: {} }],- ['a files environment with nothing but its kind', { kind: 'files' }],- ])('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).toEqual({+ claim: CLAIM,+ cwd: 'projects/atlas',+ drive: 'personal',+ mode: 'drive',+ });+ expect(config).not.toHaveProperty('environment');+ expect(config).not.toHaveProperty('specification');expect(config).not.toHaveProperty('workingDir');- expect(config.cwd).toBe('projects/atlas');});// Without an entitlement the execution plane routes to the ephemeral sandbox@@ -334,7 +242,7 @@ describe('resolveSandboxSessionConfig', () => {await expect(resolve({ workspaceId: 'ws1' })).resolves.toMatchObject({cwd: 'atlas',drive: 'personal',- mode: 'persistent',+ mode: 'drive',});});@@ -422,6 +330,7 @@ describe('resolveSandboxSessionConfig', () => {// checkout is made on its first run.it("creates a repository checkout's folder the drive does not have yet", async () => {findById.mockResolvedValue({+ projectId: 'project-1',metadata: {sandboxEnvironmentId: 'env-1',sandboxWorkingDirectory: 'projects/atlas/repo',@@ -440,6 +349,7 @@ describe('resolveSandboxSessionConfig', () => {it('falls back when a checkout folder cannot be created', async () => {findById.mockResolvedValue({+ projectId: 'project-1',metadata: {sandboxEnvironmentId: 'env-1',sandboxWorkingDirectory: 'projects/atlas/repo',@@ -455,6 +365,22 @@ describe('resolveSandboxSessionConfig', () => {});// A drive that could not be asked is not a folder that is gone.+ // T-14825: only a project conversation is set up from an environment, so+ // only its checkout is brought back. Anywhere else a missing folder is+ // missing, whatever environment the topic still carries.+ it('does not recreate a missing folder for an environment outside a project', async () => {+ findById.mockResolvedValue({+ metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'projects/atlas/repo' },+ });+ mocks.driveFolderExists.mockResolvedValue(false);++ await expect(resolve()).resolves.toMatchObject({+ fallback: 'directoryMissing',+ mode: 'ephemeral',+ });+ expect(mocks.ensureDriveFolder).not.toHaveBeenCalled();+ });+it('keeps the folder when the drive cannot answer', async () => {findById.mockResolvedValue({ metadata: { sandboxWorkingDirectory: 'projA' } });mocks.driveFolderExists.mockResolvedValue(undefined);@@ -495,8 +421,8 @@ describe('resolveSandboxSessionConfig', () => {});await expect(resolve()).resolves.toMatchObject({- environment: INSTANCE_ID,- mode: 'persistent',+ cwd: 'projects/atlas',+ mode: 'drive',});});});@@ -569,7 +495,7 @@ describe('resolveSandboxSessionConfig', () => {metadata: { sandboxInstanceId: INSTANCE_ID },});- await expect(resolve()).resolves.toMatchObject({ environment: INSTANCE_ID });+ await expect(resolve()).resolves.toMatchObject({ cwd: 'projects/atlas', mode: 'drive' });expect(getAgentVisibility).not.toHaveBeenCalled();expect(mocks.EnvironmentInstanceModel).toHaveBeenCalledWith(serverDB,@@ -623,6 +549,7 @@ describe('resolveSandboxSessionConfig', () => {expect(findById).not.toHaveBeenCalled();});+ // Only a project conversation is set up from an environment: its project's.describe('initializing from an environment', () => {const environment = {configuration: {@@ -642,6 +569,7 @@ describe('resolveSandboxSessionConfig', () => {resolveSandboxStorageClaim.mockResolvedValue(CLAIM);mocks.driveFolderExists.mockResolvedValue(true);findById.mockResolvedValue({+ projectId: 'project-1',metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'app' },});@@ -658,7 +586,10 @@ describe('resolveSandboxSessionConfig', () => {it('carries the clone credential a private repository needs, resolved for this run', async () => {resolveSandboxStorageClaim.mockResolvedValue(null);- findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });+ findById.mockResolvedValue({+ projectId: 'project-1',+ metadata: { sandboxEnvironmentId: 'env-1' },+ });const credential = { header: 'Authorization: Basic eA==', urlPrefix: 'https://github.com/' };mocks.resolveScmCloneCredential.mockResolvedValue(credential);@@ -672,7 +603,10 @@ describe('resolveSandboxSessionConfig', () => {it('initializes without a credential when none is granted, so a public repository still clones', async () => {resolveSandboxStorageClaim.mockResolvedValue(null);- findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });+ findById.mockResolvedValue({+ projectId: 'project-1',+ metadata: { sandboxEnvironmentId: 'env-1' },+ });const config = await resolve();@@ -682,7 +616,10 @@ describe('resolveSandboxSessionConfig', () => {it('initializes a temporary sandbox too, which has no drive at all', async () => {resolveSandboxStorageClaim.mockResolvedValue(null);- findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1' } });+ findById.mockResolvedValue({+ projectId: 'project-1',+ metadata: { sandboxEnvironmentId: 'env-1' },+ });await expect(resolve()).resolves.toMatchObject({initialization: { environmentId: 'env-1' },@@ -695,6 +632,7 @@ describe('resolveSandboxSessionConfig', () => {mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });findById.mockResolvedValue({agentId: 'agent-shared',+ projectId: 'project-1',metadata: { sandboxEnvironmentId: 'env-1' },});getAgentVisibility.mockResolvedValue('public');@@ -710,6 +648,7 @@ describe('resolveSandboxSessionConfig', () => {mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'public' });findById.mockResolvedValue({agentId: 'agent-shared',+ projectId: 'project-1',metadata: { sandboxEnvironmentId: 'env-1' },});getAgentVisibility.mockResolvedValue('public');@@ -727,6 +666,7 @@ describe('resolveSandboxSessionConfig', () => {mocks.driveFolderExists.mockResolvedValue(true);mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });findById.mockResolvedValue({+ projectId: 'project-1',metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'team' },});@@ -741,6 +681,7 @@ describe('resolveSandboxSessionConfig', () => {mocks.driveFolderExists.mockResolvedValue(true);mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });findById.mockResolvedValue({+ projectId: 'project-1',metadata: {sandboxDrive: 'personal',sandboxEnvironmentId: 'env-1',@@ -760,6 +701,7 @@ describe('resolveSandboxSessionConfig', () => {mocks.driveFolderExists.mockResolvedValue(true);mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'public' });findById.mockResolvedValue({+ projectId: 'project-1',metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'team' },});@@ -772,7 +714,10 @@ describe('resolveSandboxSessionConfig', () => {it('runs without one when the environment is no longer readable', async () => {resolveSandboxStorageClaim.mockResolvedValue(null);mocks.findEnvironmentById.mockResolvedValue(undefined);- findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-gone' } });+ findById.mockResolvedValue({+ projectId: 'project-1',+ metadata: { sandboxEnvironmentId: 'env-gone' },+ });const config = await resolve();@@ -780,16 +725,51 @@ describe('resolveSandboxSessionConfig', () => {expect(config).not.toHaveProperty('initialization');});- it('never initializes a legacy instance run, which its build already set up', async () => {+ // T-14825: the cloud sandbox is not set up from an environment outside a+ // project any more. One a conversation still carries from before is+ // ignored โ the run goes ahead without it, rather than failing.+ it.each([+ ['a temporary sandbox', {}, 'ephemeral'],+ ['a folder on the drive', { sandboxWorkingDirectory: 'app' }, 'drive'],+ ])('ignores an environment outside a project in %s', async (_, placement, mode) => {+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);+ findById.mockResolvedValue({ metadata: { sandboxEnvironmentId: 'env-1', ...placement } });++ const config = await resolve();++ expect(config.mode).toBe(mode);+ expect(config).not.toHaveProperty('initialization');+ expect(mocks.findEnvironmentById).not.toHaveBeenCalled();+ });++ it('runs a legacy instance outside a project without any environment', async () => {+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);+ findInstanceById.mockResolvedValue({ id: INSTANCE_ID, workingDirectory: 'atlas' });+ findById.mockResolvedValue({+ metadata: { sandboxEnvironmentId: 'env-1', sandboxInstanceId: INSTANCE_ID },+ });++ const config = await resolve();++ expect(config).toMatchObject({ cwd: 'atlas', mode: 'drive' });+ expect(config).not.toHaveProperty('initialization');+ expect(mocks.findEnvironmentById).not.toHaveBeenCalled();+ });++ // A project conversation keeps its project's environment, but a legacy+ // instance's folder already holds that conversation's work: cloning or+ // bootstrapping into it is not "running without the environment".+ it("never initializes a legacy instance's folder, even in a project", async () => {resolveSandboxStorageClaim.mockResolvedValue(CLAIM);findInstanceById.mockResolvedValue({ id: INSTANCE_ID, workingDirectory: 'atlas' });findById.mockResolvedValue({metadata: { sandboxEnvironmentId: 'env-1', sandboxInstanceId: INSTANCE_ID },+ projectId: 'project-1',});const config = await resolve();- expect(config.mode).toBe('persistent');+ expect(config).toMatchObject({ cwd: 'atlas', mode: 'drive' });expect(config).not.toHaveProperty('initialization');expect(mocks.findEnvironmentById).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.tsindex 59a8f4ce16b..eff148bf99c 100644--- a/apps/server/src/services/sandbox/session.ts+++ b/apps/server/src/services/sandbox/session.ts@@ -2,17 +2,13 @@ import {DEFAULT_SANDBOX_DRIVE,DEFAULT_SANDBOX_MODE,isSafeSandboxCwd,- isSafeSandboxEnvironmentId,SANDBOX_DRIVE_ROOT,- SANDBOX_LOCAL_WORK_ROOT,type SandboxDrive,sandboxDriveOfKey,type SandboxMode,type SandboxStorageClaim,} from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';-import type { EnvironmentConfiguration } from '@lobechat/types';-import { withRepositorySetup } from '@lobechat/types';import debug from 'debug';import { AgentModel } from '@/database/models/agent';@@ -57,6 +53,10 @@ export interface SandboxSessionConfig {* instance, so two instances of one environment restore separately and* capture separately.*+ * Never set by {@link resolveSandboxSessionConfig} any more: a legacy+ * instance runs as a plain folder, without its snapshot (T-14825). Kept on+ * the contract the execution plane and its callers still read.+ ** 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.@@ -69,20 +69,20 @@ export interface SandboxSessionConfig {* person did not pick:** - `directoryMissing` โ the folder is no longer on the drive;- * - `instanceUnavailable` โ the environment directory was deleted, is not- * this member's to use, or the folder sits inside one;- * - `instanceRebuildRequired` โ a private environment's directory left on- * the workspace's public drive from before members had drives of their- * own; it stays hidden there, and the environment has to be initialized- * again on the owner's personal drive;+ * - `instanceUnavailable` โ a legacy environment directory was deleted, is+ * not this member's to use, or would not survive the fence;+ * - `instanceRebuildRequired` โ a private legacy environment directory left+ * on the workspace's public drive from before members had drives of their+ * own; it stays hidden there, so it is not run in;* - `rootNotAllowed` โ the public drive's root, which every member's* folders live under, is not a folder anyone may work in.*/fallback?: SandboxPlacementFallback;/**- * The environment to initialize the working directory from, when the topic- * picked one: applied once to a folder on the drive, and once per sandbox in- * a temporary one. Never set on a legacy instance run โ its build did this.+ * The environment to initialize the working directory from โ a project+ * conversation's, its project's: applied once to a folder on the drive, and+ * once per sandbox in a temporary one. Never set outside a project, nor on a+ * legacy instance's folder.*/initialization?: SandboxInitialization;mode: SandboxMode;@@ -97,6 +97,9 @@ export interface SandboxSessionConfig {* 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.+ *+ * Never set by {@link resolveSandboxSessionConfig} any more (T-14825), like+ * {@link environment}.*/specification?: SandboxSessionSpecification;/**@@ -105,60 +108,12 @@ export interface SandboxSessionConfig {* 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.+ * reads. Never set by {@link resolveSandboxSessionConfig} any more, like+ * {@link environment}.*/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.- *- * `kind` is the clearest case of the first: it only picks which form the- * product shows, and an execution plane that saw it would digest it into every- * session of every environment that gained one.- */-const toSessionSpecification = (- stored: EnvironmentConfiguration | null | undefined,-): SandboxSessionSpecification | undefined => {- if (!stored) return undefined;- // Each repository's own setup rides in the one command the plane runs.- const configuration = withRepositorySetup(stored);-- const specification: SandboxSessionSpecification = {- ...(configuration.bootstrapCommand && { bootstrapCommand: configuration.bootstrapCommand }),- ...(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;@@ -176,12 +131,13 @@ interface SandboxSessionConfigInput {/*** Everything the sandbox layer needs to know about persistence for one run,* resolved once: the entitlement that goes on the trust token, and the topic's- * own placement that goes on each request. One of three:+ * own placement that goes on each request. One of two:*- * - **instance** (`persistent`) โ the topic is bound to an environment- * directory: its folder plus the packages its build installed;* - **drive** โ the topic picked a folder on the drive (or its root, in a- * personal account): the folder persists, nothing else does;+ * personal account): the folder persists, nothing else does. A topic still+ * bound to a legacy environment directory runs in that directory the same+ * way โ the cloud sandbox is not set up from an environment any more, so+ * neither the packages its build installed nor its definition come along;* - **temporary** (`ephemeral`) โ nothing picked, or a pick that can no* longer be honoured, which then says why in `fallback`.*@@ -307,36 +263,35 @@ const resolvePlacement = async ({}}- // The directory and the snapshot are one choice, so a bad half discards- // the whole instance rather than half of it. Running the instance's- // packages at the drive root would put one instance's files under- // another's captured state, which is the exact mixing separate instances- // exist to prevent โ and it would do it silently.+ // The directory is a folder on the drive like any other, and the run+ // works in it without the environment: no snapshot is restored and no+ // definition applied. A directory that would not survive the fence is+ // not run in at all.const { id, workingDirectory } = instance;- if (!isSafeSandboxCwd(workingDirectory) || !isSafeSandboxEnvironmentId(id)) {+ if (!isSafeSandboxCwd(workingDirectory)) {log('Ignoring unusable instance %s on topic %s: %o', id, topicId, workingDirectory);return fallBack('instanceUnavailable');}+ // Renamed or deleted through the drive browser since: the row outlives+ // the folder, and a run pointed at a missing cwd would fail rather than+ // fall back the way any other folder does.+ if (+ (await driveFolderExists({ claim, path: workingDirectory, userId, workspaceId })) === false+ ) {+ log('Legacy instance %s folder %o on topic %s is gone', id, workingDirectory, topicId);+ return fallBack('directoryMissing');+ }+log(- 'Persistent for topic %s: instance=%s cwd=%o drive=%s',+ 'Drive for topic %s in legacy instance %s, without its environment: cwd=%o drive=%s',topicId,id,workingDirectory,drive,);- const specification = toSessionSpecification(instance.configurationSnapshot);-- return {- claim,- cwd: workingDirectory,- drive,- environment: id,- mode: 'persistent',- ...(specification && { specification }),- ...(hasLocalCheckout(instance) && { workingDir: SANDBOX_LOCAL_WORK_ROOT }),- };+ return { claim, cwd: workingDirectory, drive, mode: 'drive' };}// The topic is only consulted when an entitlement exists. Without one the@@ -371,9 +326,10 @@ const resolvePlacement = async ({// an empty folder under a name someone chose to remove. A repository's// checkout is the exception: the environment fills the folder, so a// project conversation's checkout is made on its first run, and made- // again โ a fresh clone โ after someone removes it.+ // again โ a fresh clone โ after someone removes it. Only a project+ // conversation is set up from an environment (see `resolveInitialization`).if ((await driveFolderExists({ claim, path: folder, userId, workspaceId })) === false) {- const checkout = !!topic?.metadata?.sandboxEnvironmentId;+ const checkout = !!topic?.projectId && !!topic.metadata?.sandboxEnvironmentId;if (!checkout ||!(await ensureDriveFolder({ claim, path: folder, topicId, userId, workspaceId }))@@ -396,6 +352,11 @@ const resolvePlacement = async ({* The topic's environment as an initialization, or `undefined` when it picked* none, picked one the caller cannot read (deleted, or another member's* private one), or one that asks for nothing.+ *+ * Only a project conversation is set up from an environment: its project's,+ * configured on the project. The cloud sandbox is not otherwise a place for+ * coding, so an environment any other conversation still carries from before+ * is ignored โ the run goes ahead as if it had none.*/const resolveInitialization = async ({placement,@@ -414,6 +375,21 @@ const resolveInitialization = async ({);const environmentId = topic?.metadata?.sandboxEnvironmentId;if (!environmentId) return undefined;+ // A legacy environment directory runs as a plain folder, without any+ // environment โ not even its project's: setting one up there would clone+ // or bootstrap into a folder that already holds that conversation's work.+ if (topic.metadata?.sandboxInstanceId) {+ log('Not initializing legacy instance folder on topic %s', topicId);+ return undefined;+ }+ if (!topic.projectId) {+ log(+ 'Ignoring sandboxEnvironmentId outside a project on topic %s: %s',+ topicId,+ environmentId,+ );+ return undefined;+ }const environment = await new EnvironmentModel(serverDB,@@ -488,10 +464,9 @@ const resolveInitialization = async ({/*** Everything the sandbox layer needs to know about one run: where it works- * ({@link resolvePlacement}) and, when the topic picked an environment, what- * that working directory is initialized from. The environment is independent- * of the placement โ a temporary sandbox is initialized as readily as a folder- * โ except on a legacy instance run, which already has what its build made.+ * ({@link resolvePlacement}) and, for a project conversation, what that working+ * directory is initialized from. The environment is independent of the+ * placement โ a temporary sandbox is initialized as readily as a folder.** Never throws; a failed lookup degrades to the ephemeral sandbox every session* uses today, without an environment.@@ -501,7 +476,7 @@ export const resolveSandboxSessionConfig = async (): Promise<SandboxSessionConfig> => {const config = await resolvePlacement(input);const { serverDB, topicId } = input;- if (!serverDB || !topicId || config.mode === 'persistent') return config;+ if (!serverDB || !topicId) return config;const initialization = await resolveInitialization({...input,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 6d9bd4ca1e6..637e17b6d67 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2279,33 +2279,12 @@"runtimeEnv.selectMode": "Select Runtime Environment","runtimeEnv.title": "Runtime Environment","sandboxDrive.browseOther": "Choose another folderโฆ",- "sandboxDrive.building": "{{name}} ยท building",- "sandboxDrive.environmentBuildingDesc": "Environment directory ยท building, usable once it finishes","sandboxDrive.fallback.directoryMissing": "This folder no longer exists on the drive. Runs use a temporary sandbox until you pick another folder.",- "sandboxDrive.fallback.instanceRebuildRequired": "This private environment directory is still on the public drive and needs to be rebuilt on your personal drive. This run will use a temporary sandbox.",- "sandboxDrive.fallback.instanceUnavailable": "This environment directory canโt be used here any more. Runs use a temporary sandbox until you pick another one.",+ "sandboxDrive.fallback.instanceRebuildRequired": "This private folder is on the public drive and canโt be used there. This run will use a temporary sandbox; pick another folder.",+ "sandboxDrive.fallback.instanceUnavailable": "This folder canโt be used here any more. Runs use a temporary sandbox until you pick another folder.","sandboxDrive.fallback.rootNotAllowed": "The public driveโs root cannot be a working folder. This run will use a temporary sandbox; pick a folder.",- "sandboxDrive.fallbackChip.directoryMissing": "Folder no longer exists",- "sandboxDrive.fallbackChip.instanceRebuildRequired": "Rebuild on personal drive",- "sandboxDrive.fallbackChip.instanceUnavailable": "Environment unavailable",- "sandboxDrive.fallbackChip.rootNotAllowed": "Pick a folder",- "sandboxDrive.manageEnvironments": "Settings","sandboxDrive.root": "Root",- "sandboxDrive.setupSkipped": "This folder already has files, so the environment won't be set up in it.","sandboxDrive.title": "Cloud drive",- "sandboxEnvironment.add": "New environment",- "sandboxEnvironment.empty": "No environments yet. Create one to get started.",- "sandboxEnvironment.loadFailed": "Couldn't load environments",- "sandboxEnvironment.loading": "Loading environmentโฆ",- "sandboxEnvironment.missing": "Environment unavailable",- "sandboxEnvironment.noRepository": "No repository",- "sandboxEnvironment.none": "No environment",- "sandboxEnvironment.retry": "Retry",- "sandboxEnvironment.saveFailed": "Could not change the environment. Try again.",- "sandboxEnvironment.title": "Environment",- "sandboxOptions.environment": "Environment",- "sandboxOptions.folder": "Folder",- "sandboxOptions.storage": "Storage","sandboxOptions.temporary": "Temporary","sandboxStorage.allCopiesBusy": "Every copy is in use","sandboxStorage.buildFailed": "Not built",@@ -2323,8 +2302,6 @@"sandboxStorage.noCopyColleagueDesc": "Its creator has not set it up yet","sandboxStorage.noCopyYetDesc": "A copy is created the first time you pick it","sandboxStorage.persistentUpsell": "Persistent working directory",- "sandboxStorage.pickerInfoTooltip": "An environment describes what a run needs around it โ files, or repositories, setup and variables. Conversations run inside one of its copies and keep what they leave there; a second copy only appears when two conversations need the same environment at once.",- "sandboxStorage.pickerTitle": "Environment","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.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 072f04b4f02..a205a17645c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2279,33 +2279,12 @@"runtimeEnv.selectMode": "้ๆฉ่ฟ่ก็ฏๅข","runtimeEnv.title": "่ฟ่ก็ฏๅข","sandboxDrive.browseOther": "้ๆฉๅ ถไปๆไปถๅคนโฆ",- "sandboxDrive.building": "{{name}} ยท ๆๅปบไธญ",- "sandboxDrive.environmentBuildingDesc": "็ฏๅข็ฎๅฝ ยท ๆญฃๅจๆๅปบ๏ผๅฎๆๅๅณๅฏไฝฟ็จ","sandboxDrive.fallback.directoryMissing": "่ฏฅๆไปถๅคนๅทฒไธๅญๅจ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฐ้ๆฉๆไปถๅคนใ",- "sandboxDrive.fallback.instanceRebuildRequired": "่ฟไธช็งๆ็ฏๅข็ฎๅฝ่ฟๅจๅ ฌๅ ฑ็ฝ็ไธญ๏ผ้่ฆๅจไธชไบบ็ฝ็้ๅปบๅๆ่ฝไฝฟ็จ๏ผๆฌๆฌก่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑใ",- "sandboxDrive.fallback.instanceUnavailable": "่ฏฅ็ฏๅข็ฎๅฝๅทฒไธๅฏ็จ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฐ้ๆฉใ",+ "sandboxDrive.fallback.instanceRebuildRequired": "่ฟไธช็งๆๆไปถๅคนไฝไบๅ ฌๅ ฑ็ฝ็ไธญ๏ผๆ ๆณๅจๆญคไฝฟ็จ๏ผๆฌๆฌก่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฉๅ ถไปๆไปถๅคนใ",+ "sandboxDrive.fallback.instanceUnavailable": "่ฏฅๆไปถๅคนๅทฒไธๅฏ็จ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฐ้ๆฉๆไปถๅคนใ","sandboxDrive.fallback.rootNotAllowed": "ๅ ฌๅ ฑ็ฝ็็ๆ น็ฎๅฝไธ่ฝไฝไธบๅทฅไฝ็ฎๅฝ๏ผ่ฟ่กๅฐไฝฟ็จไธดๆถๆฒ็ฎฑ๏ผ่ฏท้ๆฉไธไธชๆไปถๅคนใ",- "sandboxDrive.fallbackChip.directoryMissing": "็ฎๅฝๅทฒไธๅญๅจ",- "sandboxDrive.fallbackChip.instanceRebuildRequired": "้ๅจไธชไบบ็ฝ็้ๅปบ",- "sandboxDrive.fallbackChip.instanceUnavailable": "็ฏๅข็ฎๅฝไธๅฏ็จ",- "sandboxDrive.fallbackChip.rootNotAllowed": "่ฏท้ๆฉๆไปถๅคน",- "sandboxDrive.manageEnvironments": "่ฎพ็ฝฎ","sandboxDrive.root": "ๆ น็ฎๅฝ",- "sandboxDrive.setupSkipped": "่ฏฅๆไปถๅคนๅทฒๆๅ ๅฎน๏ผ็ฏๅขไธไผๅจ่ฟ้ๅๅงๅใ","sandboxDrive.title": "ไบ็",- "sandboxEnvironment.add": "ๆฐๅปบ็ฏๅข",- "sandboxEnvironment.empty": "่ฟๆฒกๆ็ฏๅข๏ผๅ ๆฐๅปบไธไธชใ",- "sandboxEnvironment.loadFailed": "ๆ ๆณๅ ่ฝฝ็ฏๅขๅ่กจ",- "sandboxEnvironment.loading": "ๆญฃๅจๅ ่ฝฝ็ฏๅขโฆ",- "sandboxEnvironment.missing": "็ฏๅขไธๅฏ็จ",- "sandboxEnvironment.noRepository": "ๆ ไปๅบ",- "sandboxEnvironment.none": "ไธไฝฟ็จ็ฏๅข",- "sandboxEnvironment.retry": "้่ฏ",- "sandboxEnvironment.saveFailed": "ๆ ๆณๆดๆน็ฏๅข๏ผ่ฏท้่ฏใ",- "sandboxEnvironment.title": "็ฏๅข",- "sandboxOptions.environment": "็ฏๅข",- "sandboxOptions.folder": "ๆไปถๅคน",- "sandboxOptions.storage": "ๅญๅจ","sandboxOptions.temporary": "ไธดๆถ","sandboxStorage.allCopiesBusy": "ๆๆๅฏๆฌ้ฝๅจไฝฟ็จไธญ","sandboxStorage.buildFailed": "ๆชๆๅปบ",@@ -2323,8 +2302,6 @@"sandboxStorage.noCopyColleagueDesc": "ๅๅปบ่ ่ฟๆฒกๆไธบๅฎๅๅคๅฏๆฌ๏ผๆไธๅฏ็จ","sandboxStorage.noCopyYetDesc": "็ฌฌไธๆฌก้ไธญๆถไผ่ชๅจๅๅปบๅฏๆฌ","sandboxStorage.persistentUpsell": "ๆไน ๅๅทฅไฝ็ฎๅฝ",- "sandboxStorage.pickerInfoTooltip": "็ฏๅขๆ่ฟฐไธๆฌก่ฟ่ก้่ฆ็ๅจ่พนโโๆไปถ๏ผๆ่ ไปๅบใๅๅงๅๅๅ้ใๅฏน่ฏ่ทๅจๅฎ็ๆไธไปฝๅฏๆฌ้๏ผ็ไธ็ไธ่ฅฟไน็ๅจ้ฃ้๏ผๅชๆไธคไธชๅฏน่ฏ่ฆๅๆถ็จๅไธไธช็ฏๅขๆถ๏ผๆไผๅบ็ฐ็ฌฌไบไปฝๅฏๆฌใ",- "sandboxStorage.pickerTitle": "็ฏๅข","sandboxStorage.privateGroup": "็งไบบ็ฏๅข","sandboxStorage.privateInstanceBlocked": "ใ{{name}}ใๅฑไบ็งไบบ็ฏๅข๏ผๅ ฌๅ ฑ Agent ๆ ๆณไฝฟ็จ๏ผๆฌ่ฏ้ขๅทฒๆน็จไธดๆถ็ฎๅฝ่ฟ่กใ","sandboxStorage.publicAgentHint_one": "ๅทฒ้่ {{count}} ไธช็งไบบ็ฏๅข โโ ๅ ฌๅ ฑ Agent ไป ๅฏไฝฟ็จๅทฅไฝๅบ็ฏๅข๏ผๅๅธๅๅณๅฏๅจ่ฟ้ไฝฟ็จใ",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 452d62d0f46..766cbf92ad1 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1835,12 +1835,6 @@ export default {'sandboxStorage.setUpEnvironmentDesc': 'A persistent directory lives in an environment','sandboxStorage.setUpEnvironment': 'Set up an environment','sandboxStorage.manage': 'Manage',- // The menu lists environments: a person picks the environment, and which- // copy (instance) of it the conversation lands in is only asked about when- // there is more than one. "Copy" is the product's word for an instance.- 'sandboxStorage.pickerTitle': 'Environment',- 'sandboxStorage.pickerInfoTooltip':- 'An environment describes what a run needs around it โ files, or repositories, setup and variables. Conversations run inside one of its copies and keep what they leave there; a second copy only appears when two conversations need the same environment at once.','sandboxStorage.kind.files': 'Files','sandboxStorage.kind.code': 'Code','sandboxStorage.copies': 'Copies',@@ -4744,40 +4738,18 @@ export default {'The worktree is still being cleaned up. Try sending again in a moment.','worktreeRestore.waiting': 'Waiting for the worktree cleanup to finish before restoring itโฆ','you': 'You',- 'sandboxDrive.manageEnvironments': 'Settings',- 'sandboxEnvironment.none': 'No environment',- 'sandboxEnvironment.missing': 'Environment unavailable',- 'sandboxEnvironment.loading': 'Loading environmentโฆ',- 'sandboxEnvironment.title': 'Environment',- 'sandboxEnvironment.empty': 'No environments yet. Create one to get started.',- 'sandboxEnvironment.add': 'New environment',- 'sandboxEnvironment.loadFailed': "Couldn't load environments",- 'sandboxEnvironment.retry': 'Retry',- 'sandboxEnvironment.saveFailed': 'Could not change the environment. Try again.','sandboxDrive.root': 'Root',- 'sandboxOptions.storage': 'Storage','sandboxOptions.temporary': 'Temporary',- 'sandboxOptions.folder': 'Folder',- 'sandboxOptions.environment': 'Environment',- 'sandboxDrive.setupSkipped':- "This folder already has files, so the environment won't be set up in it.",- 'sandboxDrive.building': '{{name}} ยท building','sandboxDrive.title': 'Cloud drive','sandboxDrive.browseOther': 'Choose another folderโฆ',- 'sandboxDrive.environmentBuildingDesc':- 'Environment directory ยท building, usable once it finishes','sandboxDrive.fallback.directoryMissing':'This folder no longer exists on the drive. Runs use a temporary sandbox until you pick another folder.','sandboxDrive.fallback.instanceUnavailable':- 'This environment directory canโt be used here any more. Runs use a temporary sandbox until you pick another one.',+ 'This folder canโt be used here any more. Runs use a temporary sandbox until you pick another folder.','sandboxDrive.fallback.rootNotAllowed':'The public driveโs root cannot be a working folder. This run will use a temporary sandbox; pick a folder.',- 'sandboxDrive.fallbackChip.directoryMissing': 'Folder no longer exists',- 'sandboxDrive.fallbackChip.instanceUnavailable': 'Environment unavailable',- 'sandboxDrive.fallbackChip.rootNotAllowed': 'Pick a folder','sandboxDrive.fallback.instanceRebuildRequired':- 'This private environment directory is still on the public drive and needs to be rebuilt on your personal drive. This run will use a temporary sandbox.',- 'sandboxDrive.fallbackChip.instanceRebuildRequired': 'Rebuild on personal drive',+ 'This private folder is on the public drive and canโt be used there. This run will use a temporary sandbox; pick another folder.','input.costEstimate.hintUsd': 'Estimated cost: about {{amount}}','input.costEstimate.usdPerMillionTokens': '{{amount}} / 1M tokens','resource.artifacts.history.restoreFailedRetry':@@ -4818,7 +4790,6 @@ export default {'taskList.find.open': 'Find in view','taskList.find.placeholder': 'Find in viewโฆ','taskList.groupBy.labelGroup': 'Label: {{name}}',- 'sandboxEnvironment.noRepository': 'No repository','sessionGroup.createFailedRetry':"Couldn't create the category. Check your network and try again.",'shareModal.downloadFailedRetry': "Couldn't download the PDF. Check your network and try again.",diff --git a/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx b/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsxindex dc32f756662..9eb28be4719 100644--- a/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx+++ b/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx@@ -1,30 +1,19 @@'use client';-import { Flexbox, Icon, Popover, Text, toast } from '@lobehub/ui';+import { Flexbox, Text, toast } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { CircleOffIcon, ContainerIcon, FolderIcon, PackageIcon, TimerIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';-import RepositoryAvatar from '@/components/RepositoryAvatar';-import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { refreshProjectFiles } from '@/services/projectFile';import { sandboxStorageService } from '@/services/sandboxStorage';-import OptionRow from './OptionRow';import SandboxDriveMenu, { type SandboxDriveFolderPick } from './SandboxDriveMenu';-import {- environmentChipState,- environmentSettingsPath,- repositorySlug,- selectionWithEnvironment,-} from './sandboxEnvironmentOptions';-import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';+import { useSandboxFolder } from './useSandboxFolder';import type { useSandboxOptions } from './useSandboxOptions';import type { SandboxSelection } from './useSandboxPlacement';@@ -39,28 +28,6 @@ const styles = stylex.create({},});-/** A third level opens beside the second, the way the second opens beside the first. */-const SUBMENU_STYLES = {- content: { padding: 4 },- root: { height: 'auto', width: 'auto' },-};--const folderName = (path: string) => path.split('/').pop() || path;--/** What the folder of a selection is called: the root, its last segment, or a legacy directory's name. */-export const useSandboxFolderLabel = (selection: SandboxSelection, entitled: boolean) => {- const { t } = useTranslation('chat');- // A legacy environment directory's own row, for its name โ from the- // database, so the menu never waits on a sandbox.- const { data: instance } = useSWR(- entitled && selection.instanceId ? ['sandbox-drive-chip-instance', selection.instanceId] : null,- () => sandboxStorageService.getInstance({ id: selection.instanceId! }),- );- if (selection.instanceId) return instance?.name ?? instance?.workingDirectory;- if (selection.workingDirectory === '.') return t('sandboxDrive.root');- return selection.workingDirectory ? folderName(selection.workingDirectory) : undefined;-};-interface CloudSandboxOptionsProps {/** Closes the whole execution-environment menu. */onClose: () => void;@@ -70,13 +37,10 @@ interface CloudSandboxOptionsProps {}/**- * The cloud sandbox's options, one level under its row in the- * execution-environment menu:- *- * - **Storage** โ one level further: a temporary sandbox (cleaned up with the- * session), or a folder of the drive;- * - **Environment** โ one level further: none, or the environment the run is- * set up from.+ * Where the cloud sandbox keeps its files, listed directly under its row in+ * the execution-environment menu: a temporary sandbox (cleaned up with the+ * session), or a folder of the drive. The cloud sandbox is not set up from an+ * environment โ coding runs on a device โ so storage is its only option.** Picking any option also moves the conversation to the cloud sandbox. A pick* that can no longer be honoured โ the folder was deleted โ is said at the@@ -85,33 +49,21 @@ interface CloudSandboxOptionsProps {const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(({ onClose, onEnsureSandbox, options }) => {const { t } = useTranslation(['chat', 'device']);- const navigate = useWorkspaceAwareNavigate();const {driveStatus,entitled,- environmentList,onDrive,- onPublicDrive,- pick,pickFolder: saveFolder,- projectId,selection,- sharedAgent,toTemporary,topicId,workspaceId,} = options;- const {- environments,- failed: environmentsFailed,- loaded: environmentsLoaded,- refresh: refreshEnvironments,- } = environmentList;- const folderLabel = useSandboxFolderLabel(selection, entitled);+ const current = useSandboxFolder(selection, entitled);// Whether the pick still holds, asked of the same resolver the run uses:- // a folder deleted on a shared drive, or an environment directory gone,- // sends the next run to a temporary sandbox โ and the menu says so first.+ // a folder deleted on a shared drive sends the next run to a temporary+ // sandbox โ and the menu says so first.const { data: placement, mutate: revalidatePlacement } = useSWR(entitled && topicId && onDrive? [@@ -120,7 +72,6 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(selection.drive ?? '',selection.instanceId ?? '',selection.workingDirectory ?? '',- selection.environmentId ?? '',]: null,() => sandboxStorageService.resolveSessionPlacement({ topicId }),@@ -128,20 +79,6 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>();const fallback = placement?.fallback;- const pickEnvironment = async (environment?: SandboxRepositoryOption) => {- try {- await onEnsureSandbox();- await pick(selectionWithEnvironment(base, environment), { environment });- } catch {- // The topic kept its old placement; said rather than left looking picked.- toast.error(t('sandboxEnvironment.saveFailed'));- return;- }- // Picking what is already held keeps the keys unchanged, so SWR would go- // on showing the old answers. Ask once more after every pick.- void revalidatePlacement();- };-const pickTemporary = async () => {onClose();try {@@ -153,22 +90,6 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(}};- // An environment is only set up in an empty folder. Picking one that- // already holds files keeps the files and skips the setup โ said once, at- // the pick, rather than left to look applied.- const warnIfSetupSkipped = async (next: SandboxSelection) => {- if (!next.environmentId || next.workingDirectory === undefined) return;- try {- const { entries = [] } = await sandboxStorageService.listFiles({- drive: next.drive,- path: next.workingDirectory === '.' ? undefined : next.workingDirectory,- });- if (entries.length > 0) toast.info(t('sandboxDrive.setupSkipped'));- } catch {- // A folder that cannot be listed yet is created empty on the first run.- }- };-const pickFolder = async (folder: SandboxDriveFolderPick) => {onClose();let next: SandboxSelection;@@ -184,7 +105,6 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(const path = next.workingDirectory === '.' ? '' : (next.workingDirectory ?? '');void refreshProjectFiles(`sandbox:${topicId}`, path);}- void warnIfSetupSkipped(next);};const openBrowser = () => {@@ -203,49 +123,6 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(});};- // The drive state the environment is picked against: an entitlement lost- // since the folder was picked leaves the conversation off the drive.- const base: SandboxSelection = onDrive- ? selection- : selection.environmentId- ? { environmentId: selection.environmentId }- : {};-- const addEnvironment = () => {- onClose();- openCreateEnvironmentModal(- // A workspace-public agent, or a folder on the public drive, applies- // published environments only.- sharedAgent || onPublicDrive ? 'public' : undefined,- async (created) => {- await refreshEnvironments();- if (created?.id) await pickEnvironment(created);- },- t('sandboxEnvironment.add'),- );- };-- const current = environments.find((item) => item.id === selection.environmentId);- const environmentState = environmentChipState({- current,- environmentId: selection.environmentId,- failed: environmentsFailed,- loaded: environmentsLoaded,- });- const environmentLabel =- environmentState.kind === 'picked'- ? environmentState.name- : environmentState.kind === 'none'- ? t('sandboxEnvironment.none')- : environmentState.kind === 'missing'- ? t('sandboxEnvironment.missing')- : environmentState.kind === 'loadFailed'- ? t('sandboxEnvironment.loadFailed')- : t('sandboxEnvironment.loading');- const slug = current && repositorySlug(current);-- const storageLabel = onDrive ? folderLabel : t('sandboxOptions.temporary');-return (<Flexbox gap={2}>{fallback && (@@ -254,91 +131,21 @@ const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(</Text>)}- <Popover- arrow={false}- closeDelay={150}- placement={'rightTop'}- styles={SUBMENU_STYLES}- trigger={['hover', 'click']}- content={- <SandboxDriveMenu- entitled={driveStatus === 'hidden' ? undefined : driveStatus !== 'upgrade'}- selectedLabel={onDrive ? folderLabel : undefined}- temporary={!onDrive}- // A legacy environment directory is not a folder of this list.- selectedPath={- onDrive && !selection.instanceId ? selection.workingDirectory : undefined- }- onBrowse={openBrowser}- onPick={(folder) => void pickFolder(folder)}- onPickTemporary={() => void pickTemporary()}- onUpgrade={() => {- onClose();- openSandboxStorageUpsell();- }}- />- }- >- <div data-testid={'sandbox-storage-row'}>- <OptionRow- arrow- compact- hint={storageLabel}- label={t('sandboxOptions.storage')}- icon={- <Icon- icon={onDrive ? (selection.instanceId ? PackageIcon : FolderIcon) : TimerIcon}- size={16}- />- }- onClick={() => {}}- />- </div>- </Popover>-- <Popover- arrow={false}- closeDelay={150}- placement={'rightTop'}- styles={SUBMENU_STYLES}- trigger={['hover', 'click']}- content={- <SandboxRepositoryMenu- environments={environments}- failed={environmentsFailed}- loaded={environmentsLoaded}- none={{ active: !selection.environmentId, onPick: () => void pickEnvironment() }}- selectedId={selection.environmentId}- // A project has exactly one environment, edited on its settings:- // there is no second one to add from here.- onAdd={projectId ? undefined : addEnvironment}- onClose={onClose}- onPick={pickEnvironment}- onRetry={() => void refreshEnvironments()}- onManage={() => {- onClose();- navigate(environmentSettingsPath(projectId));- }}- />- }- >- <div data-testid={'sandbox-environment-row'}>- <OptionRow- arrow- compact- hint={environmentLabel}- label={t('sandboxOptions.environment')}- icon={- slug ? (- <RepositoryAvatar size={16} url={slug} />- ) : (- <Icon icon={selection.environmentId ? ContainerIcon : CircleOffIcon} size={16} />- )- }- onClick={() => {}}- />- </div>- </Popover>+ <SandboxDriveMenu+ entitled={driveStatus === 'hidden' ? undefined : driveStatus !== 'upgrade'}+ selectedLabel={onDrive ? current.label : undefined}+ // A legacy environment directory can sit on a drive this list does+ // not show, so its row names it and picks nothing.+ selectedPath={onDrive && !selection.instanceId ? current.path : undefined}+ temporary={!onDrive}+ onBrowse={openBrowser}+ onPick={(folder) => void pickFolder(folder)}+ onPickTemporary={() => void pickTemporary()}+ onUpgrade={() => {+ onClose();+ openSandboxStorageUpsell();+ }}+ /></Flexbox>);},diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex 47b74bedc55..a535ee87b2c 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -366,8 +366,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {[selectTarget],);- // The cloud sandbox's options โ storage and environment โ are picked one- // level under its row. Asked once the menu could show them.+ // The cloud sandbox's storage โ temporary, or a drive folder โ is picked one+ // level under its row. Asked once the menu could show it.const sandboxOptions = useSandboxOptions(agentId, {enabled: supportsSandbox && (open || executionTarget === 'sandbox'),topicId,@@ -727,9 +727,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {onClick={() => void handleSelect('auto')}/>)}- {/* One cloud sandbox, its options one level down: whether it keeps its- files on the drive (and where), and the environment it is set up- from. A runtime that cannot use it gets a disabled row saying why. */}+ {/* One cloud sandbox, its storage one level down: a temporary sandbox,+ or a folder on the drive. A runtime that cannot use it gets a+ disabled row saying why. */}{supportsSandbox ? (<GroupSubmenuactive={isActive('sandbox')}diff --git a/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx b/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsxindex 5e9baf8d0b3..a7eafb0ef2e 100644--- a/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx@@ -162,7 +162,7 @@ const SandboxDriveMenu = memo<SandboxDriveMenuProps>(<Text className={stylex.props(styles.hint).className} type={'danger'}>{t('workingDirectory.drive.foldersLoadFailed', { ns: 'device' })}</Text>- <Button onClick={() => void mutate()}>{t('sandboxEnvironment.retry')}</Button>+ <Button onClick={() => void mutate()}>{t('retry', { ns: 'common' })}</Button></Flexbox>)}diff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsxdeleted file mode 100644index afe95275ee9..00000000000--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx+++ /dev/null@@ -1,151 +0,0 @@-'use client';--import type { EnvironmentConfiguration } from '@lobechat/types';-import { Button, Flexbox, Icon, Text } from '@lobehub/ui';-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';-import * as stylex from '@stylexjs/stylex';-import { CircleOffIcon, ContainerIcon, PlusIcon, SettingsIcon } from 'lucide-react';-import { memo } from 'react';-import { useTranslation } from 'react-i18next';--import RepositoryAvatar from '@/components/RepositoryAvatar';--import OptionRow from './OptionRow';-import { repositoriesLabel, repositorySlug } from './sandboxEnvironmentOptions';-import SubmenuHeader from './SubmenuHeader';--const styles = stylex.create({- hint: {- paddingInline: '8px',- fontSize: '12px',- color: cssVar.colorTextDescription,- },- list: {- maxHeight: '280px',- overflowY: 'auto',- },-});--export interface SandboxRepositoryOption {- configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;- description?: string | null;- id: string;- name: string;- /** `public` once published to the workspace; anything else is its owner's alone. */- visibility?: string | null;-}--interface SandboxRepositoryMenuProps {- environments: SandboxRepositoryOption[];- failed: boolean;- loaded: boolean;- /** A first row for working without an environment. */- none?: { active: boolean; onPick: () => void };- /** Adds an environment and picks it. Absent where there is no other one to add โ a project's. */- onAdd?: () => void;- /** Closes the whole work-location menu; a final pick leaves it. */- onClose: () => void;- onManage: () => void;- onPick: (environment: SandboxRepositoryOption) => Promise<void>;- onRetry: () => void;- selectedId?: string;-}--/**- * The environments a conversation can be set up from, and the way to add one- * without leaving the composer.- */-const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(- ({- environments,- failed,- loaded,- none,- onAdd,- onClose,- onManage,- onPick,- onRetry,- selectedId,- }) => {- const { t } = useTranslation('chat');- return (- <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>- <SubmenuHeader- title={t('sandboxEnvironment.title')}- action={{- icon: SettingsIcon,- label: t('sandboxDrive.manageEnvironments'),- onClick: onManage,- }}- />-- <div {...stylex.props(styles.list)}>- {none && (- <OptionRow- compact- active={none.active}- icon={<Icon icon={CircleOffIcon} size={16} />}- label={t('sandboxEnvironment.none')}- onClick={() => {- onClose();- none.onPick();- }}- />- )}- {environments.map((environment) => (- <OptionRow- compact- active={environment.id === selectedId}- desc={environment.description || undefined}- // An environment, which checks out any number of repositories or- // none: its repositories as `owner/name +N`, said plainly when- // it has none.- hint={repositoriesLabel(environment) ?? t('sandboxEnvironment.noRepository')}- key={environment.id}- label={environment.name}- icon={- repositorySlug(environment) ? (- <RepositoryAvatar size={16} url={repositorySlug(environment)} />- ) : (- <Icon icon={ContainerIcon} size={16} />- )- }- onClick={() => {- onClose();- void onPick(environment);- }}- />- ))}- </div>-- {loaded && environments.length === 0 && (- <Text className={stylex.props(styles.hint).className}>- {t('sandboxEnvironment.empty')}- </Text>- )}- {!loaded && failed && (- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} paddingInline={8}>- <Text className={stylex.props(styles.hint).className} type={'danger'}>- {t('sandboxEnvironment.loadFailed')}- </Text>- <Button onClick={onRetry}>{t('sandboxEnvironment.retry')}</Button>- </Flexbox>- )}-- {onAdd && (- <OptionRow- compact- icon={<Icon icon={PlusIcon} size={16} />}- label={t('sandboxEnvironment.add')}- onClick={onAdd}- />- )}- </Flexbox>- );- },-);--SandboxRepositoryMenu.displayName = 'SandboxRepositoryMenu';--export default SandboxRepositoryMenu;diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsxindex c19e568fe31..db853b1b6e7 100644--- a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx@@ -26,7 +26,6 @@ const state = vi.hoisted(() => {// The agent's drive switched off for its new conversations.temporary: false,workspaceId: null as string | null,- environmentsLoaded: true,setPrefersTemporary: vi.fn(),topicId: null as string | null,userId: 'user-a' as string | undefined,@@ -38,7 +37,10 @@ const state = vi.hoisted(() => {/** The blank project draft a sidebar "+" staged. */draft: undefined as { agentId: string; projectId: string } | undefined,/** Each project's environments. */- projectEnvironments: {} as Record<string, { configuration?: unknown; id: string }[]>,+ projectEnvironments: {} as Record<+ string,+ { configuration?: unknown; id: string; visibility?: string }[]+ >,updateTopicMetadata: vi.fn(),version: 0,};@@ -98,21 +100,8 @@ vi.mock('../temporarySandboxPreference', () => ({usePrefersTemporarySandbox: () => state.temporary,}));vi.mock('../useFollowSandboxModePreference', () => ({ useFollowSandboxModePreference: () => {} }));-const ENVIRONMENTS = [- {- configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobe-chat' }] },- id: 'env_repo',- name: 'Chat',- visibility: 'private',- },-];-vi.mock('../useSandboxEnvironmentList', () => ({useIsSharedAgent: () => false,- useSandboxEnvironmentList: () => ({- environments: state.environmentsLoaded ? ENVIRONMENTS : [],- loaded: state.environmentsLoaded,- }),useProjectSandboxEnvironments: (projectId?: string) => ({environments: projectId ? (state.projectEnvironments[projectId] ?? []) : [],}),@@ -145,7 +134,9 @@ const label = (value: SandboxSelection) =>// The menu's rows are covered by their own tests; here a stand-in makes the// picks a person would through the same hook, and names the placement. The-// real menu catches a failed save and says so.+// real menu catches a failed save and says so. The menu no longer offers an+// environment: `pick-repo` stands for one a topic carries from before โ or,+// in a project, the project's own.const Options = () => {const topicId = useTopicId();const options = useSandboxOptions(AGENT, { enabled: true, topicId });@@ -163,23 +154,12 @@ const Options = () => {pick-public-folder</button><button onClick={() => toTemporary().catch(() => {})}>drive-off</button>- {/* A published environment just created: not in the list this render holds. */}- <button- onClick={() =>- pick(- { ...value, environmentId: 'env_new', workingDirectory: 'new-env' },- { environment: { id: 'env_new', name: 'New', visibility: 'public' } },- ).catch(() => {})- }- >- create-public-env- </button><buttononClick={() =>pick(value.workingDirectory === undefined- ? { environmentId: 'env_repo' }- : { ...value, environmentId: 'env_repo' },+ ? { environmentId: 'env-project' }+ : { ...value, environmentId: 'env-project' },).catch(() => {})}>@@ -211,7 +191,6 @@ const renderSection = () =>beforeEach(() => {state.temporary = false;state.workspaceId = null;- state.environmentsLoaded = true;state.setPrefersTemporary.mockReset();state.topicId = null;state.userId = 'user-a';@@ -323,10 +302,11 @@ describe('SandboxStorageSection โ T-14158', () => {});// Every member browses the workspace's public drive: a private environment- // is not carried into a folder there.- it("drops a private environment when a folder on the workspace's public drive is picked", async () => {+ // โ or one not known to be published โ is not carried into a folder there.+ it("drops a project's private environment when a folder on the workspace's public drive is picked", async () => {state.workspaceId = 'ws-1';renderSection();+ state.topicProjects['topic-1'] = 'project-1';send('topic-1');await act(async () => fireEvent.click(screen.getByText('pick-repo')));@@ -337,60 +317,66 @@ describe('SandboxStorageSection โ T-14158', () => {);});- it('drops an environment not known to be published when a public-drive folder is picked', async () => {+ it("keeps a project's published environment on a public-drive folder", async () => {state.workspaceId = 'ws-1';+ state.projectEnvironments['project-1'][0].visibility = 'public';renderSection();+ state.topicProjects['topic-1'] = 'project-1';send('topic-1');await act(async () => fireEvent.click(screen.getByText('pick-repo')));- act(() => {- state.environmentsLoaded = false;- commit();- });await act(async () => fireEvent.click(screen.getByText('pick-public-folder')));- expect(state.updateTopicMetadata).toHaveBeenLastCalledWith(- 'topic-1',- expect.objectContaining({ sandboxEnvironmentId: undefined, sandboxWorkingDirectory: 'team' }),- );- });-- it('keeps a published environment just created on a public-drive folder', async () => {- state.workspaceId = 'ws-1';- renderSection();- send('topic-1');- await act(async () => fireEvent.click(screen.getByText('pick-public-folder')));-- await act(async () => fireEvent.click(screen.getByText('create-public-env')));expect(state.updateTopicMetadata).toHaveBeenLastCalledWith('topic-1',expect.objectContaining({- sandboxEnvironmentId: 'env_new',- sandboxWorkingDirectory: 'new-env',+ sandboxEnvironmentId: 'env-project',+ sandboxWorkingDirectory: 'team',}),);});- // T-14791: storage is picked as a folder or ไธดๆถ; a folder keeps the- // environment and is where the agent's new conversations start.- it('keeps the environment when a folder is picked from a temporary sandbox', async () => {+ // T-14791: storage is picked as a folder or ไธดๆถ, and a folder is where the+ // agent's new conversations start. T-14825: the cloud sandbox is not set up+ // from an environment any more โ one a conversation carries from before is+ // dropped with the pick.+ it('drops an environment from before when a folder is picked from a temporary sandbox', async () => {renderSection();send('topic-1');await act(async () => fireEvent.click(screen.getByText('drive-off')));- await act(async () => fireEvent.click(screen.getByText('pick-repo')));+ act(() => {+ state.topics['topic-1'] = { sandboxEnvironmentId: 'env_repo' };+ commit();+ });+ expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');await act(async () => fireEvent.click(screen.getByText('pick-folder')));- expect(screen.getByTestId('chip').textContent).toBe('projects/demo+repo:env_repo');+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo');expect(state.setPrefersTemporary).toHaveBeenLastCalledWith(expect.anything(), AGENT, false);});- it('keeps the environment when the drive is switched off', async () => {+ it('drops an environment from before when the drive is switched off', async () => {renderSection();send('topic-1');+ act(() => {+ state.topics['topic-1'] = { sandboxEnvironmentId: 'env_repo', sandboxWorkingDirectory: '.' };+ commit();+ });++ await act(async () => fireEvent.click(screen.getByText('drive-off')));+ expect(screen.getByTestId('chip').textContent).toBe('temporary');+ });++ it("keeps a project's environment when the drive is switched on and off", async () => {+ renderSection();+ state.topicProjects['topic-1'] = 'project-1';+ send('topic-1');await act(async () => fireEvent.click(screen.getByText('pick-repo')));- expect(screen.getByTestId('chip').textContent).toBe('.+repo:env_repo');++ await act(async () => fireEvent.click(screen.getByText('pick-folder')));+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo+repo:env-project');await act(async () => fireEvent.click(screen.getByText('drive-off')));- expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');});// A project conversation starts off the drive, in its project's@@ -448,22 +434,6 @@ describe('SandboxStorageSection โ T-14158', () => {state.temporary = true;});- it('starts the next new conversation from the repository the last one used', async () => {- renderSection();- expect(screen.getByTestId('chip').textContent).toBe('temporary');- await send('topic-1');-- await act(async () => fireEvent.click(screen.getByText('pick-repo')));-- openNewConversation();- expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');- await send('topic-2');- expect(state.topics['topic-2']).toMatchObject({- sandboxEnvironmentId: 'env_repo',- sandboxSeeded: true,- });- });-// A project conversation runs in its project's environment, which the// agent's conversations elsewhere cannot use: picking it there must not// become where the next one starts.@@ -476,7 +446,7 @@ describe('SandboxStorageSection โ T-14158', () => {await act(async () => fireEvent.click(screen.getByText('pick-repo')));expect(state.updateTopicMetadata).toHaveBeenCalledWith('topic-1',- expect.objectContaining({ sandboxEnvironmentId: 'env_repo' }),+ expect.objectContaining({ sandboxEnvironmentId: 'env-project' }),);openNewConversation();@@ -489,10 +459,9 @@ describe('SandboxStorageSection โ T-14158', () => {it("starts a project draft on the project's environment", async () => {renderSection();await send('topic-1');- await act(async () => fireEvent.click(screen.getByText('pick-repo')));openNewConversation();- expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');+ expect(screen.getByTestId('chip').textContent).toBe('temporary');act(() => {state.draft = { agentId: AGENT, projectId: 'project-1' };diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.tsindex 9ed674c563e..b2a323ff528 100644--- a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts@@ -2,8 +2,6 @@ import { afterEach, describe, expect, it } from 'vitest';import {getRememberedSandboxDirectory,- getRememberedSandboxDirectoryEnvironment,- getRememberedSandboxRepository,rememberedSandboxDirectoryKey,rememberSandboxSelection,} from './rememberedSandboxDirectory';@@ -57,65 +55,22 @@ describe('rememberedSandboxDirectory', () => {expect(getRememberedSandboxDirectory({ workspaceId: 'ws_1' }, 'agent-1')).toBeUndefined();});- // The folder and the environment are remembered each on its own: switching- // the drive off never erases the folder.- it('remembers the environment apart from the folder', () => {- rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });-- expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });- expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBeUndefined();- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });- });-- // T-14791: a folder and an environment picked together are both remembered.- it('remembers a folder and its environment together', () => {- rememberSandboxSelection(ME, 'agent-1', {- environmentId: 'env_1',- workingDirectory: 'lobehub',- });-- expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'lobehub' });- expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBe('env_1');- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });- });-- // An environment remembered apart from the folder is not the folder's: the- // pair was never set up together.- it('pairs the folder only with an environment picked together with it', () => {- rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'notes' });- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });-- expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBeUndefined();- });-- it('remembers a pick that used no environment', () => {+ // T-14825: the cloud sandbox is not set up from an environment, so only the+ // folder is remembered; picking a temporary sandbox leaves it alone.+ it('remembers the folder alone, whatever environment the pick carried', () => {+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1', workingDirectory: 'code' });rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });- rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });-- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({});- });- it('leaves the environment alone for a folder-only memory', () => {- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });- rememberSandboxSelection(- ME,- 'agent-1',- { environmentId: 'env_project', workingDirectory: 'code' },- { folderOnly: true },- );-- expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });+ const key = rememberedSandboxDirectoryKey(ME, 'agent-1')!;+ expect(JSON.parse(localStorage.getItem(key)!)).toEqual({ workingDirectory: 'code' });+ expect(localStorage.length).toBe(1);});it('changes nothing for a legacy environment directory', () => {rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });rememberSandboxSelection(ME, 'agent-1', { instanceId: 'inst_1' });expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });});it('ignores a corrupted entry', () => {diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.tsindex cd6b5954455..58fac638ade 100644--- a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts@@ -3,13 +3,6 @@ import type { SandboxSelection } from './useSandboxPlacement';/** Prefix of every entry; each user + workspace + agent has a key of its own. */export const REMEMBERED_SANDBOX_DIRECTORY_PREFIX = 'lobechat-sandbox-last-directory';-/**- * Prefix of the environment's memory, kept apart from the folder: which- * environment the agent's last conversation was set up from โ or that it used- * none โ whether it kept its files on the drive or not.- */-export const REMEMBERED_SANDBOX_REPOSITORY_PREFIX = 'lobechat-sandbox-last-repository';-/** The folder part of a selection: which drive, and where on it. */export type RememberedSandboxDirectory = Pick<SandboxSelection, 'drive' | 'workingDirectory'>;@@ -32,9 +25,6 @@ const scopedKey = (prefix: string, { userId, workspaceId }: RememberScope, agentexport const rememberedSandboxDirectoryKey = (scope: RememberScope, agentId: string) =>scopedKey(REMEMBERED_SANDBOX_DIRECTORY_PREFIX, scope, agentId);-export const rememberedSandboxRepositoryKey = (scope: RememberScope, agentId: string) =>- scopedKey(REMEMBERED_SANDBOX_REPOSITORY_PREFIX, scope, agentId);-const readEntry = (key: string): unknown => {try {const raw = localStorage.getItem(key);@@ -68,56 +58,11 @@ export const getRememberedSandboxDirectory = (};/**- * The environment picked together with the remembered folder, if any. Kept in- * the folder's own entry rather than read from the environment memory: the two- * memories are written apart, and a folder paired with an environment it was- * never set up from would skip the setup โ it only runs in an empty folder.- */-export const getRememberedSandboxDirectoryEnvironment = (- scope: RememberScope,- agentId: string,-): string | undefined => {- const key = rememberedSandboxDirectoryKey(scope, agentId);- if (!key) return undefined;-- const value = readEntry(key);- if (!isValid(value)) return undefined;- const { environmentId } = value as { environmentId?: unknown };- return typeof environmentId === 'string' && environmentId ? environmentId : undefined;-};--/**- * What the agent's last conversation was set up from: `{ environmentId }`- * for a repository, `{}` for none picked on purpose, `undefined` when nothing- * is remembered yet.- */-export const getRememberedSandboxRepository = (- scope: RememberScope,- agentId: string,-): Pick<SandboxSelection, 'environmentId'> | undefined => {- const key = rememberedSandboxRepositoryKey(scope, agentId);- if (!key) return undefined;-- const value = readEntry(key) as { environmentId?: unknown } | undefined;- if (!value || typeof value !== 'object') return undefined;- if (value.environmentId === undefined) return {};- return typeof value.environmentId === 'string' && value.environmentId- ? { environmentId: value.environmentId }- : undefined;-};--/**- * Remember a pick so the next conversation starts where this one was put. The- * folder and the environment are two answers, each remembered on its own:- *- * - a folder on the drive is remembered as the folder, with the environment- * picked together with it; switching the drive off leaves the folder memory- * alone, for the next time it is switched on;- * - the environment โ or none, picked on purpose โ is remembered whether or- * not the drive is on. `folderOnly` skips it, for an environment that only- * means something where it was picked: a project's;- * - a legacy environment directory says nothing about either and changes- * nothing.+ * Remember a pick so the next conversation starts where this one was put: a+ * folder on the drive is remembered as the folder, and switching the drive off+ * leaves that memory alone, for the next time it is switched on. A legacy+ * environment directory changes nothing. The cloud sandbox is not set up from+ * an environment, so none is remembered.** Storage unavailable (private mode, quota) is ignored: the next conversation* starts at the plan's default, as it did before anything was remembered.@@ -126,30 +71,17 @@ export const rememberSandboxSelection = (scope: RememberScope,agentId: string,selection: SandboxSelection,- { folderOnly = false }: { folderOnly?: boolean } = {},): void => {const key = rememberedSandboxDirectoryKey(scope, agentId);- if (!key) return;-- const repositoryKey = rememberedSandboxRepositoryKey(scope, agentId)!;- if (selection.instanceId) return;+ if (!key || selection.instanceId || !selection.workingDirectory) return;try {- if (selection.workingDirectory) {- localStorage.setItem(- key,- JSON.stringify({- ...(selection.drive && { drive: selection.drive }),- ...(!folderOnly && selection.environmentId && { environmentId: selection.environmentId }),- workingDirectory: selection.workingDirectory,- }),- );- }- if (folderOnly) return;-localStorage.setItem(- repositoryKey,- JSON.stringify(selection.environmentId ? { environmentId: selection.environmentId } : {}),+ key,+ JSON.stringify({+ ...(selection.drive && { drive: selection.drive }),+ workingDirectory: selection.workingDirectory,+ }),);} catch {// Storage unavailable: nothing is remembered, as described above.diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.tsindex 6e68d545bc3..8c7358c0cd8 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts@@ -1,14 +1,10 @@import { describe, expect, it } from 'vitest';import {- environmentChipState,- environmentFolderName,- environmentSettingsPath,isOnPublicDrive,pickableEnvironments,projectStartEnvironmentId,repositorySlug,- selectionWithEnvironment,selectionWithFolder,} from './sandboxEnvironmentOptions';@@ -27,35 +23,6 @@ describe('pickableEnvironments', () => {});});-describe('environmentChipState', () => {- it('names the picked environment once the list has it', () => {- expect(- environmentChipState({- current: { name: 'Tools' },- environmentId: 'env',- failed: false,- loaded: true,- }),- ).toEqual({ kind: 'picked', name: 'Tools' });- });-- it('does not call a picked environment "none" while the list loads or after it failed', () => {- expect(environmentChipState({ environmentId: 'env', failed: false, loaded: false })).toEqual({- kind: 'loading',- });- expect(environmentChipState({ environmentId: 'env', failed: true, loaded: false })).toEqual({- kind: 'loadFailed',- });- });-- it('says a picked environment is unavailable only when the loaded list lacks it', () => {- expect(environmentChipState({ environmentId: 'env', failed: false, loaded: true })).toEqual({- kind: 'missing',- });- expect(environmentChipState({ failed: true, loaded: false })).toEqual({ kind: 'none' });- });-});-describe('repositorySlug', () => {const withUrl = (url: string) => ({configuration: { sources: [{ kind: 'git' as const, url }] },@@ -77,56 +44,6 @@ describe('repositorySlug', () => {});});-describe('environmentSettingsPath', () => {- it("manages a project conversation's environment on the project's settings", () => {- expect(environmentSettingsPath('project-1')).toBe('/project/project-1/settings/environments');- });-- it("manages any other conversation's environments in the workspace's list", () => {- expect(environmentSettingsPath()).toBe('/settings/environments');- });-});--const repoEnv = {- configuration: {- sources: [{ kind: 'git' as const, url: 'https://github.com/lobehub/lobe-write.git' }],- },- id: 'env_repo01',- name: 'Writer',-};-const plainEnv = { id: 'env_plain02', name: 'Data tools' };--describe('environmentFolderName', () => {- it("is named after the environment's repository, with a piece of its id", () => {- expect(environmentFolderName(repoEnv)).toBe('lobe-write-repo01');- });-- it('is named after the environment without a repository', () => {- expect(environmentFolderName(plainEnv)).toBe('Data tools-lain02');- });-- // Two environments of one repository must not share a folder: the setup- // only runs in an empty one, so the second would keep the first's checkout.- it('keeps two environments of the same repository apart', () => {- expect(environmentFolderName({ ...repoEnv, id: 'env_other9' })).not.toBe(- environmentFolderName(repoEnv),- );- });-- it('is always one visible path segment', () => {- expect(environmentFolderName({ id: 'x1', name: '../a/b' })).toBe('-a-b-x1');- expect(environmentFolderName({ id: 'x1', name: ' .hidden ' })).toBe('hidden-x1');- expect(environmentFolderName({ id: 'x1', name: '..' })).toBe('environment-x1');- });-- // The server refuses a working directory starting with `~`; a folder named- // that way would send every run to a temporary sandbox.- it('never produces a name the server refuses as a working directory', () => {- expect(environmentFolderName({ id: 'x1', name: '~tools' })).toBe('tools-x1');- expect(environmentFolderName({ id: '', name: '~.~' })).toBe('environment');- });-});-describe('isOnPublicDrive', () => {it('is a workspace folder on the drive every member browses', () => {expect(isOnPublicDrive({ workingDirectory: 'team' }, 'ws')).toBe(true);@@ -140,40 +57,6 @@ describe('isOnPublicDrive', () => {});});-describe('selectionWithEnvironment', () => {- it('only changes the environment off the drive', () => {- expect(selectionWithEnvironment({}, repoEnv)).toEqual({ environmentId: 'env_repo01' });- expect(selectionWithEnvironment({ environmentId: 'env_repo01' })).toEqual({});- });-- it("moves a drive conversation into the environment's own folder", () => {- expect(- selectionWithEnvironment({ drive: 'personal', workingDirectory: 'notes' }, repoEnv),- ).toEqual({- drive: 'personal',- environmentId: 'env_repo01',- workingDirectory: 'lobe-write-repo01',- });- });-- it('keeps the folder when the environment is cleared on the drive', () => {- expect(- selectionWithEnvironment({- environmentId: 'env_repo01',- workingDirectory: 'lobe-write-repo01',- }),- ).toEqual({ workingDirectory: 'lobe-write-repo01' });- });-- it('replaces a legacy environment directory', () => {- expect(selectionWithEnvironment({ instanceId: 'inst-1' }, plainEnv)).toEqual({- environmentId: 'env_plain02',- workingDirectory: 'Data tools-lain02',- });- expect(selectionWithEnvironment({ instanceId: 'inst-1' })).toEqual({});- });-});-describe('selectionWithFolder', () => {it('keeps the environment when a folder is picked', () => {expect(diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.tsindex aeec977e0d0..2b0d946daa7 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts@@ -1,8 +1,5 @@-import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';import type { EnvironmentConfiguration } from '@lobechat/types';-import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';-import type { SandboxSelection } from './useSandboxPlacement';/**@@ -49,36 +46,6 @@ export const repositoriesLabel = (environment: {return count > 1 ? `${first} +${count - 1}` : first;};-/**- * What the environment chip says. A list still loading, or one that failed to- * load, says nothing about the topic's environment โ so it is not reported as- * "none", which would read as initialization being off.- */-export type EnvironmentChipState =- | { kind: 'loading' }- | { kind: 'loadFailed' }- | { kind: 'missing' }- | { kind: 'none' }- | { kind: 'picked'; name: string };--export const environmentChipState = ({- current,- environmentId,- failed,- loaded,-}: {- current?: { name: string };- environmentId?: string;- failed: boolean;- loaded: boolean;-}): EnvironmentChipState => {- if (!environmentId) return { kind: 'none' };- if (current) return { kind: 'picked', name: current.name };- if (loaded) return { kind: 'missing' };-- return failed ? { kind: 'loadFailed' } : { kind: 'loading' };-};-/*** The environment the server applies to a project conversation nobody placed:* the project's, when it checks out a repository (see@@ -94,45 +61,6 @@ export const projectStartEnvironmentId = ((environment.configuration?.sources ?? []).some((source) => source.kind === 'git'),)?.id;-/**- * Where a conversation's environments are managed: a project's one on the- * project's settings, anything else in the workspace's list.- */-export const environmentSettingsPath = (projectId?: string) =>- projectId ? getProjectSettingsPath(projectId, 'environments') : '/settings/environments';--/**- * The folder an environment is set up in when the conversation keeps its files- * on the drive: one of its own, named after the repository it checks out (or- * the environment itself) plus a short piece of its id, at the top of the- * drive. The id keeps two environments of the same repository โ different- * refs, setup or variables โ and a folder of the person's own apart: the- * setup only runs in an empty folder, so a shared one would keep the first- * environment's checkout under the second's name. The server creates it on- * the first run, and the next conversation that picks the environment finds- * the checkout already there.- */-export const environmentFolderName = (environment: {- configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;- id: string;- name: string;-}): string => {- const base = repositorySlug(environment)?.split('/').pop() || environment.name;- const suffix = environment.id.replaceAll(/[^\dA-Za-z]/g, '').slice(-6);- // A single path segment the drive accepts: no separators, no leading dot- // (hidden, and `.`/`..` are not folders) or `~`, no surrounding whitespace.- // Checked with the server's own rule at the end: a name it refuses would- // send every run to a temporary sandbox while the chip names the folder.- const name = base- .replaceAll(/[/\\]+/g, '-')- .trim()- .replace(/^[.~]+/, '')- .slice(0, 56)- .trim();- const folder = [name || 'environment', suffix].filter(Boolean).join('-');- return isSafeSandboxCwd(folder) ? folder : 'environment';-};-/*** Whether a selection works in a folder of a workspace's public drive, which* every member can browse. In a workspace a folder with no drive named is on@@ -145,36 +73,9 @@ export const isOnPublicDrive = (selection: SandboxSelection, workspaceId?: strinselection.drive !== 'personal';/**- * The selection once an environment (or none) is picked. On the drive, an- * environment moves the conversation into that environment's own folder, so- * it is set up rather than skipped in a folder that already holds files;- * none keeps the folder. Off the drive only the environment changes. A- * legacy environment directory is replaced either way.- */-export const selectionWithEnvironment = (- selection: SandboxSelection,- environment?: Parameters<typeof environmentFolderName>[0] & { id: string },-): SandboxSelection => {- const onDrive = !!selection.instanceId || selection.workingDirectory !== undefined;- if (!onDrive) return environment ? { environmentId: environment.id } : {};-- if (!environment) {- if (selection.instanceId) return {};- return selection.drive- ? { drive: selection.drive, workingDirectory: selection.workingDirectory }- : { workingDirectory: selection.workingDirectory };- }-- return {- ...(selection.drive && { drive: selection.drive }),- environmentId: environment.id,- workingDirectory: environmentFolderName(environment),- };-};--/**- * The selection once a folder of the drive is picked: the environment stays,- * and is set up there if the folder is empty.+ * The selection once a folder of the drive is picked: a project's environment+ * stays, and is set up there if the folder is empty. A legacy environment+ * directory is replaced.*/export const selectionWithFolder = (selection: SandboxSelection,diff --git a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.ts b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.tsindex 39551fcf8cd..b0c71715e66 100644--- a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.ts+++ b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.test.ts@@ -1,15 +1,10 @@-import { renderHook, waitFor } from '@testing-library/react';+import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import {- useIsSharedAgent,- useProjectSandboxEnvironments,- useSandboxEnvironmentList,-} from './useSandboxEnvironmentList';+import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';const state = vi.hoisted(() => ({fetchEnvironments: vi.fn(),- listEnvironments: vi.fn(),}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({@@ -26,10 +21,6 @@ vi.mock('@/store/agent', () => ({},}),}));-vi.mock('@/services/environment', () => ({- environmentService: { listEnvironments: state.listEnvironments },-}));-const PROJECT_ENVIRONMENTS = [{ id: 'env-project', name: 'Lobe Write', visibility: 'private' },{ id: 'env-project-public', name: 'Lobe Write (public)', visibility: 'public' },@@ -42,9 +33,6 @@ vi.mock('@/store/projectWorkingDirectory', () => ({}));beforeEach(() => {- state.listEnvironments.mockReset().mockResolvedValue({- environments: [{ id: 'env-shared', name: 'lobe-tts', visibility: 'private' }],- });state.fetchEnvironments.mockReset().mockReturnValue({error: undefined,hasData: true,@@ -52,13 +40,9 @@ beforeEach(() => {});});-describe('useSandboxEnvironmentList', () => {- // The workspace's shared list leaves a project's environment out, so a- // project conversation showed its own environment as unavailable.- it("offers a project conversation its project's environment, not the shared list", () => {- const { result } = renderHook(() =>- useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: false }),- );+describe('useProjectSandboxEnvironments', () => {+ it("offers a project conversation its project's environment", () => {+ const { result } = renderHook(() => useProjectSandboxEnvironments('project-1', false));expect(result.current.environments.map((e) => e.id)).toEqual(['env-project',@@ -66,40 +50,30 @@ describe('useSandboxEnvironmentList', () => {]);expect(result.current.loaded).toBe(true);expect(state.fetchEnvironments).toHaveBeenCalledWith('project-1', true);- expect(state.listEnvironments).not.toHaveBeenCalled();});it('offers a workspace-public agent the published project environment only', () => {- const { result } = renderHook(() =>- useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: true }),- );+ const { result } = renderHook(() => useProjectSandboxEnvironments('project-1', true));expect(result.current.environments.map((e) => e.id)).toEqual(['env-project-public']);});it("reports the project list's failure rather than an empty list", () => {state.fetchEnvironments.mockReturnValue({ error: new Error('offline'), hasData: false });- const { result } = renderHook(() =>- useSandboxEnvironmentList({ projectId: 'project-1', sharedAgent: false }),- );+ const { result } = renderHook(() => useProjectSandboxEnvironments('project-1', false));expect(result.current.failed).toBe(true);expect(result.current.loaded).toBe(false);});- it("offers any other conversation the workspace's shared environments", async () => {- const { result } = renderHook(() =>- useSandboxEnvironmentList({ sharedAgent: false, workspaceId: 'workspace-1' }),- );+ // T-14825: the cloud sandbox outside a project has no environment to offer.+ it('offers nothing outside a project, and fetches nothing', () => {+ const { result } = renderHook(() => useProjectSandboxEnvironments(undefined, false));- await waitFor(() => expect(result.current.loaded).toBe(true));- expect(result.current.environments.map((e) => e.id)).toEqual(['env-shared']);- // No project: its list is not fetched.+ expect(result.current.environments).toEqual([]);expect(state.fetchEnvironments).toHaveBeenCalledWith(undefined, false);});-});-describe('useProjectSandboxEnvironments', () => {// The composer section renders for runs that never use the sandbox too.it('does not fetch while the run does not use the sandbox', () => {renderHook(() => useProjectSandboxEnvironments('project-1', false, false));diff --git a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.tsindex 6002605bc0d..ec35c3c5482 100644--- a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts+++ b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts@@ -1,13 +1,21 @@-import useSWR from 'swr';+import type { EnvironmentConfiguration } from '@lobechat/types';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { environmentService } from '@/services/environment';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';import { pickableEnvironments } from './sandboxEnvironmentOptions';-import type { SandboxRepositoryOption } from './SandboxRepositoryMenu';++/** An environment a project conversation can start from. */+export interface SandboxRepositoryOption {+ configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;+ description?: string | null;+ id: string;+ name: string;+ /** `public` once published to the workspace; anything else is its owner's alone. */+ visibility?: string | null;+}/*** Whether the conversation's agent is workspace-public. Such an agent runs on@@ -51,37 +59,3 @@ export const useProjectSandboxEnvironments = (refresh: sync.revalidate,};};--/**- * The environments a conversation may start from. A project conversation runs- * in its project's environment โ the workspace's shared list leaves it out โ- * so it is offered that one alone. Any other conversation is offered the- * workspace's shared environments. Only the list in use is fetched.- */-export const useSandboxEnvironmentList = ({- enabled = true,- projectId,- sharedAgent,- workspaceId,-}: {- /** Whether the list is needed yet; nothing is fetched until it is. */- enabled?: boolean;- projectId?: string;- sharedAgent: boolean;- workspaceId?: string | null;-}): SandboxEnvironmentList => {- const shared = useSWR(- enabled && !projectId ? ['sandbox-environment-chip', workspaceId ?? ''] : null,- () => environmentService.listEnvironments(),- );- const project = useProjectSandboxEnvironments(projectId, sharedAgent, enabled);-- if (projectId) return project;-- return {- environments: pickableEnvironments(shared.data?.environments ?? [], sharedAgent),- failed: !!shared.error,- loaded: !!shared.data,- refresh: () => shared.mutate(),- };-};diff --git a/src/features/ChatInput/ControlBar/useSandboxFolder.test.ts b/src/features/ChatInput/ControlBar/useSandboxFolder.test.tsnew file mode 100644index 00000000000..c44fd1b4ac9--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxFolder.test.ts@@ -0,0 +1,48 @@+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useSandboxFolder } from './useSandboxFolder';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const getInstance = vi.hoisted(() => vi.fn());+vi.mock('@/services/sandboxStorage', () => ({ sandboxStorageService: { getInstance } }));++beforeEach(() => {+ getInstance.mockReset();+});++describe('useSandboxFolder', () => {+ it('names a folder by its last segment, and the root as the root', () => {+ expect(+ renderHook(() => useSandboxFolder({ workingDirectory: 'projects/demo' }, true)).result+ .current,+ ).toEqual({ label: 'demo', path: 'projects/demo' });+ expect(+ renderHook(() => useSandboxFolder({ workingDirectory: '.' }, true)).result.current,+ ).toEqual({ label: 'sandboxDrive.root', path: '.' });+ });++ it('names nothing for a temporary sandbox', () => {+ expect(renderHook(() => useSandboxFolder({}, true)).result.current).toEqual({+ label: undefined,+ path: undefined,+ });+ });++ // T-14825: the drive menu shows no environment item any more โ a legacy+ // environment directory is the folder it is on the drive, named by its+ // folder and picked like any other row of the list.+ it('names a legacy environment directory by its folder, not by the environment', async () => {+ getInstance.mockResolvedValue({ name: 'Lobe Chat env', workingDirectory: 'envs/chat-dir' });++ const { result } = renderHook(() => useSandboxFolder({ instanceId: 'inst-1' }, true));++ await waitFor(() =>+ expect(result.current).toEqual({ label: 'chat-dir', path: 'envs/chat-dir' }),+ );+ expect(getInstance).toHaveBeenCalledWith({ id: 'inst-1' });+ });+});diff --git a/src/features/ChatInput/ControlBar/useSandboxFolder.ts b/src/features/ChatInput/ControlBar/useSandboxFolder.tsnew file mode 100644index 00000000000..8208fc5d235--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxFolder.ts@@ -0,0 +1,27 @@+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { sandboxStorageService } from '@/services/sandboxStorage';++import type { SandboxSelection } from './useSandboxPlacement';++const folderName = (path: string) => path.split('/').pop() || path;++/**+ * The folder of a selection โ its path on the drive and what it is called: the+ * root, or its last segment. A legacy environment directory is a folder like+ * any other now, named after its directory on the drive.+ */+export const useSandboxFolder = (selection: SandboxSelection, entitled: boolean) => {+ const { t } = useTranslation('chat');+ // A legacy environment directory's own row, for its path โ from the+ // database, so the menu never waits on a sandbox.+ const { data: instance } = useSWR(+ entitled && selection.instanceId ? ['sandbox-drive-chip-instance', selection.instanceId] : null,+ () => sandboxStorageService.getInstance({ id: selection.instanceId! }),+ );+ const directory = selection.instanceId ? instance?.workingDirectory : selection.workingDirectory;+ const label =+ directory === '.' ? t('sandboxDrive.root') : directory ? folderName(directory) : undefined;+ return { label, path: directory };+};diff --git a/src/features/ChatInput/ControlBar/useSandboxOptions.ts b/src/features/ChatInput/ControlBar/useSandboxOptions.tsindex 20cc6fd9203..a7ee82008bb 100644--- a/src/features/ChatInput/ControlBar/useSandboxOptions.ts+++ b/src/features/ChatInput/ControlBar/useSandboxOptions.ts@@ -9,9 +9,8 @@ import { userProfileSelectors } from '@/store/user/selectors';import { rememberSandboxSelection } from './rememberedSandboxDirectory';import type { SandboxDriveFolderPick } from './SandboxDriveMenu';import { isOnPublicDrive, selectionWithFolder } from './sandboxEnvironmentOptions';-import type { SandboxRepositoryOption } from './SandboxRepositoryMenu';import { setPrefersTemporarySandbox } from './temporarySandboxPreference';-import { useIsSharedAgent, useSandboxEnvironmentList } from './useSandboxEnvironmentList';+import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';import {isPersistentSelection,type SandboxSelection,@@ -40,11 +39,16 @@ const useSandboxDriveStatus = (enabled: boolean): SandboxDriveStatus => {};/**- * The cloud sandbox's two options โ whether it keeps its files on the drive- * (and in which folder), and the environment it is set up from โ read and- * written from one place. The execution-environment menu offers them under- * its ไบ็ซฏๆฒ็ฎฑ row and its chip names them; new conversations are seeded by- * `SandboxStorageSection`, which this hook leaves alone.+ * The cloud sandbox's one option โ whether it keeps its files on the drive,+ * and in which folder โ read and written from one place. The+ * execution-environment menu offers it under its ไบ็ซฏๆฒ็ฎฑ row; new+ * conversations are seeded by `SandboxStorageSection`, which this hook leaves+ * alone.+ *+ * The sandbox is not set up from an environment any more: only a project+ * conversation still carries one โ its project's, applied by the server โ and+ * a pick keeps it there. Anywhere else an environment left on the topic from+ * before is dropped with the next pick.** `topicId` is the conversation the caller belongs to; `null` means it has no* topic yet.@@ -61,54 +65,36 @@ export const useSandboxOptions = (const workspaceId = useActiveWorkspaceId();const userId = useUserStore(userProfileSelectors.userId);const sharedAgent = useIsSharedAgent(agentId);- const environmentList = useSandboxEnvironmentList({- enabled,- projectId,- sharedAgent,- workspaceId,- });- const { environments } = environmentList;+ // Only a project's own environment can still apply, so only its visibility+ // is asked: a private one is not carried into a public-drive folder.+ const { environments } = useProjectSandboxEnvironments(projectId, sharedAgent, enabled);- // Every pick that lands is remembered for the next conversation: the folder,- // and the environment (or none). A failed save is not, and neither is an- // environment picked inside a project: it belongs to that project, and the- // agent's next conversation elsewhere could not use it. A drive folder is- // usable anywhere.+ // Every pick that lands is remembered for the next conversation โ the+ // folder, which is usable anywhere, inside a project or not. A failed save+ // is not.//// Every member can browse the workspace's public drive, so a private// environment โ or one not known to be published โ is not carried into a- // folder there: the server would not apply it, and the menu would name a- // setup that never runs.+ // folder there: the server would not apply it.const pick = useCallback(- async (- picked: SandboxSelection,- { environment: given }: { environment?: SandboxRepositoryOption } = {},- ) => {- // An environment whose visibility is not known โ the list still loading- // or failed โ is treated as private: it is only known to be published- // once the list, or the pick itself (one just created, which this- // render's list cannot hold yet), says so.- const environment =- given?.id === picked.environmentId- ? given- : environments.find((item) => item.id === picked.environmentId);+ async (picked: SandboxSelection): Promise<SandboxSelection> => {+ const environment = environments.find((item) => item.id === picked.environmentId);const next =picked.environmentId &&- environment?.visibility !== 'public' &&- isOnPublicDrive(picked, workspaceId)+ (!projectId ||+ (environment?.visibility !== 'public' && isOnPublicDrive(picked, workspaceId)))? { ...picked, environmentId: undefined }: picked;await setSelection(next);- rememberSandboxSelection({ userId, workspaceId }, agentId, next, {- folderOnly: !!projectId,- });+ rememberSandboxSelection({ userId, workspaceId }, agentId, next);+ return next;},[agentId, environments, projectId, setSelection, userId, workspaceId],);- // Storage is picked one level under its row: a temporary sandbox, or a- // folder of the drive. Either keeps the environment. Outside a project the- // pick is also where the agent's new conversations start.+ // Storage is picked under the cloud sandbox's row: a temporary sandbox, or a+ // folder of the drive. Either keeps a project's environment. Outside a+ // project the pick is also where the agent's new conversations start.const toTemporary = useCallback(async () => {await pick(selection.environmentId ? { environmentId: selection.environmentId } : {});if (!projectId) setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);@@ -116,8 +102,7 @@ export const useSandboxOptions = (const pickFolder = useCallback(async (folder: SandboxDriveFolderPick) => {- const next = selectionWithFolder(selection, folder);- await pick(next);+ const next = await pick(selectionWithFolder(selection, folder));if (!projectId) setPrefersTemporarySandbox({ userId, workspaceId }, agentId, false);return next;},@@ -133,14 +118,11 @@ export const useSandboxOptions = (return {driveStatus,entitled,- environmentList,onDrive,- onPublicDrive: onDrive && isOnPublicDrive(selection, workspaceId),pick,pickFolder,projectId,selection,- sharedAgent,toTemporary,topicId,workspaceId,diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.tsindex 353d8fdba81..5391675de95 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts@@ -8,7 +8,10 @@ import {setPendingSandboxSelection,} from '@/store/chat/pendingSandboxSelection';-import { rememberSandboxSelection } from './rememberedSandboxDirectory';+import {+ rememberedSandboxDirectoryKey,+ rememberSandboxSelection,+} from './rememberedSandboxDirectory';import { useSeedDefaultSelection, useSeedTemporaryRepository } from './useSeedDefaultSelection';const getEntitlement = vi.hoisted(() => vi.fn());@@ -34,6 +37,13 @@ vi.mock('@/store/sandbox', () => ({const AGENT = 'agent-seed';+/** A folder an earlier version remembered together with its environment. */+const storeLegacyFolderWithEnvironment = (environmentId: string, workingDirectory: string) =>+ localStorage.setItem(+ rememberedSandboxDirectoryKey({ userId: 'user-a' }, AGENT)!,+ JSON.stringify({ environmentId, workingDirectory }),+ );+afterEach(() => {consumePendingSandboxSelection(AGENT);getEntitlement.mockReset();@@ -133,6 +143,18 @@ describe('useSeedDefaultSelection', () => {expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'projects/demo' });});++ // T-14825: the cloud sandbox is not set up from an environment any more, so+ // one remembered with the folder by an older conversation stays behind.+ it('brings back the remembered folder without its environment', () => {+ storeLegacyFolderWithEnvironment('env-repo', 'projects/demo');++ renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: true, hasTopic: false }),+ );++ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'projects/demo' });+ });});describe('useSeedTemporaryRepository โ the first-send default', () => {@@ -169,4 +191,22 @@ describe('useSeedTemporaryRepository โ the first-send default', () => {environmentId: 'env-project',});});++ it('clears an environment left as the default by an earlier render', () => {+ const { rerender } = renderHook(+ ({ project }: { project?: { environmentId: string } }) =>+ useSeedTemporaryRepository(AGENT, {+ eligible: true,+ hasTopic: false,+ project,+ temporary: true,+ }),+ { initialProps: { project: { environmentId: 'env-project' } } },+ );+ expect(getPendingSandboxSelection(AGENT)?.environmentId).toBe('env-project');++ rerender({ project: undefined });++ expect(getPendingSandboxSelection(AGENT)?.environmentId).toBeUndefined();+ });});diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.tsindex 31515157fc2..458c03c16a1 100644--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts@@ -13,34 +13,24 @@ import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';-import {- getRememberedSandboxDirectory,- getRememberedSandboxDirectoryEnvironment,- getRememberedSandboxRepository,-} from './rememberedSandboxDirectory';+import { getRememberedSandboxDirectory } from './rememberedSandboxDirectory';/**- * The drive default with the environment picked together with that folder, so- * a folder and its environment come back together โ and only together: an- * environment from elsewhere would skip its setup in a folder that has files.+ * The drive default: the folder the agent's last conversation was put in, or+ * the plan's default folder. The cloud sandbox is not set up from an+ * environment, so an environment remembered with that folder from before is+ * not brought back.*/const driveDefault = (scope: { userId?: string | null; workspaceId?: string | null },agentId: string,-) => {- const remembered = getRememberedSandboxDirectory(scope, agentId);- const folder = resolveDefaultSandboxSelection(scope.workspaceId, remembered);- const environmentId = remembered- ? getRememberedSandboxDirectoryEnvironment(scope, agentId)- : undefined;- return environmentId ? { ...folder, environmentId } : folder;-};+) =>+ resolveDefaultSandboxSelection(scope.workspaceId, getRememberedSandboxDirectory(scope, agentId));/*** Give a conversation that does not exist yet the plan's default place to* work: an account with a drive keeps its files unless it says otherwise, in the- * folder the agent's last conversation was put in when there is one, set up- * from the environment it used. Only+ * folder the agent's last conversation was put in when there is one. Only* fills an empty slot โ a pick, including the temporary sandbox, stays โ and* only before the topic exists, so a conversation already running never moves.* Sending consumes the slot, and the next new conversation is seeded again.@@ -82,19 +72,18 @@ export const useSeedDefaultSelection = (};/**- * The temporary sandbox's counterpart: a conversation that does not exist yet,- * for an agent whose new conversations start with the drive off, starts- * from the environment the agent's last conversation used โ or from none,- * which is the temporary sandbox's own default and needs nothing filled in.+ * The temporary sandbox's counterpart, for a project conversation that does not+ * exist yet: it starts from its project's environment โ the one the server+ * applies to a default nobody picked. `project.environmentId` is that+ * environment, or undefined while it loads or when the server would apply none.*- * Filled in as a default rather than a pick, the same as the folder: a pick- * stays, and a project conversation is still given its project's checkout.+ * Any other conversation starts from no environment, the temporary sandbox's+ * own default: the cloud sandbox is not set up from one, so the repository an+ * agent's earlier conversation used is not brought back, and one left as a+ * default by an earlier render is cleared.*- * A project conversation starts from its project's environment instead โ the- * one the server applies to a default nobody picked โ so the chip names what- * the conversation will run in; the agent's repository from elsewhere is not- * one this project offers. `project.environmentId` is that environment, or- * undefined while it loads or when the server would apply none.+ * Filled in as a default rather than a pick, the same as the folder: a pick+ * stays.*/export const useSeedTemporaryRepository = (agentId: string,@@ -111,38 +100,29 @@ export const useSeedTemporaryRepository = (temporary: boolean;},) => {- const workspaceId = useActiveWorkspaceId();- const userId = useUserStore(userProfileSelectors.userId);- const inProject = !!project;- const projectEnvironmentId = project?.environmentId;+ // Outside a project there is none.+ const environmentId = project?.environmentId;// Registered as soon as the run is known to use the sandbox โ before the// entitlement โ so a first send that turns out to have no drive still- // starts from the remembered repository. Cleared on unmount, like the drive+ // starts from the project's repository. Cleared on unmount, like the drive// default. Only a conversation not created yet registers one: the entry is// the agent's, and a split pane already on a topic โ a project's, say โ// would hand its environment to another pane's first send, or clear it.useEffect(() => {if (!eligible || hasTopic) return;- const environmentId = inProject- ? projectEnvironmentId- : getRememberedSandboxRepository({ userId, workspaceId }, agentId)?.environmentId;setSandboxTemporaryDefaultSelection(agentId, environmentId ? { environmentId } : undefined);return () => setSandboxTemporaryDefaultSelection(agentId);- }, [agentId, eligible, hasTopic, inProject, projectEnvironmentId, userId, workspaceId]);+ }, [agentId, eligible, environmentId, hasTopic]);useEffect(() => {if (!temporary || hasTopic) return;const pending = getPendingSandboxSelection(agentId);if (pending && !isSeededSandboxSelection(pending)) return;- const environmentId = inProject- ? projectEnvironmentId- : getRememberedSandboxRepository({ userId, workspaceId }, agentId)?.environmentId;if (environmentId) seedPendingSandboxSelection(agentId, { environmentId });- // A default environment nothing replaces is stale: the agent's repository- // from elsewhere in a project, or a project's environment once the agent's- // next conversation is not that project's. Neither is offered there.+ // A default environment nothing replaces is stale: a project's environment+ // once the agent's next conversation is not that project's.else if (pending?.environmentId) setPendingSandboxSelection(agentId);- }, [agentId, hasTopic, inProject, projectEnvironmentId, temporary, userId, workspaceId]);+ }, [agentId, environmentId, hasTopic, temporary]);};