🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(sandbox): Persistent Sandbox in the execution environment, Cloud Sandbox for coding (#23126)
Rdmclin27369706cbe17
diff --git a/apps/server/src/services/aiAgent/pipeline/topicProject.ts b/apps/server/src/services/aiAgent/pipeline/topicProject.tsindex 96284ad5dbd..c1bd31a500f 100644--- a/apps/server/src/services/aiAgent/pipeline/topicProject.ts+++ b/apps/server/src/services/aiAgent/pipeline/topicProject.ts@@ -79,8 +79,8 @@ export const withProjectSandbox = async (const { agentId, hasDirectory, projectId } = input;// Creation-time markers, never stored. `sandboxTemporary`: the composer chose// a temporary sandbox on purpose, so nothing is applied over it.- // `sandboxSeeded`: the placement is the plan's default nobody chose, so a- // project's checkout takes its place.+ // `sandboxSeeded`: the placement is the plan's default nobody chose, so the+ // project's repository, cloned into a temporary sandbox, takes its place.const { sandboxSeeded, sandboxTemporary, ...rest } = input.metadata ?? {};const metadata =sandboxSeeded === undefined && sandboxTemporary === undefined@@ -100,7 +100,7 @@ export const withProjectSandbox = async (const sandbox = await resolveProjectTopicSandbox({ ...deps, agentId, projectId });if (Object.keys(sandbox).length === 0) return metadata;- // The checkout replaces a default placement whole, drive included.+ // The repository replaces a default placement whole, drive folder included.const {sandboxDrive: _drive,sandboxEnvironmentId: _environment,diff --git a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.tsindex 72fc6c68f02..fa44423111c 100644--- a/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts+++ b/apps/server/src/services/heterogeneousAgent/cloudHeteroContext.ts@@ -81,7 +81,10 @@ export function buildCloudHeteroContext(params: {: "You are running inside a LobeHub cloud sandbox. Your working directory is the root of the user's **network drive**: files written there survive session expiry and are still there in your next session. The machine itself starts fresh every session, so installed packages do not carry over.": `You are running inside a LobeHub cloud sandbox. Your working directory is ${sandbox?.cwd ? `\`${sandbox.cwd}\`, ` : ''}an **environment directory** on the user's drive: its files and the packages its setup installed survive session expiry and are restored in your next session.`,'Other folders on the drive belong to other work — reachable with relative paths, but do not write into them unless the user asks.',- 'The workspace is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes. Install packages and build where the toolchain puts things by default.',+ 'The workspace is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes.',+ // The persistent sandbox is for everyday work whose results should+ // stay; coding is what the temporary Cloud Sandbox is for.+ "This persistent sandbox is meant for everyday tasks, not coding: a repository's dependencies, virtual environments, caches and build output would take up a lot of the user's drive space. Keep those outside the working directory, and when the task is mainly programming on a codebase, suggest the user switch this conversation to the Cloud Sandbox, which is discarded after use.",'','## Sandbox Persistence','Files in your working directory persist across sessions; anything written outside it may not.',diff --git a/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.tsindex 1aaa353d7ca..5cbde2bf76f 100644--- a/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts+++ b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts@@ -49,25 +49,17 @@ describe('resolveProjectTopicSandbox', () => {mocks.getAgentVisibility.mockReset().mockResolvedValue('private');});- it("works in the project's repository, checked out in the project's folder", async () => {- await expect(resolve()).resolves.toEqual({- sandboxEnvironmentId: 'env-repo',- sandboxWorkingDirectory: 'projects/proj_1/env-repo',- });- });-- // The public drive is every member's; a private checkout stays on the member's own.- it('puts a private repository on the personal drive in a workspace', async () => {- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({- sandboxDrive: 'personal',- });+ // Coding belongs in the temporary sandbox: the repository is cloned into a+ // fresh one, never checked out in a folder on the drive.+ it("clones the project's repository into a temporary sandbox", async () => {+ await expect(resolve()).resolves.toEqual({ sandboxEnvironmentId: 'env-repo' });});- it('puts a published repository on the public drive', async () => {+ it('names no drive or folder in a workspace either', async () => {mocks.findEnvironmentById.mockResolvedValue({ ...repository, visibility: 'public' });- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({- sandboxDrive: 'public',+ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({+ sandboxEnvironmentId: 'env-repo',});});@@ -88,7 +80,6 @@ describe('resolveProjectTopicSandbox', () => {await expect(resolve({ environmentId: 'env-other' })).resolves.toEqual({sandboxEnvironmentId: 'env-other',- sandboxWorkingDirectory: 'projects/proj_1/env-other',});});@@ -110,8 +101,7 @@ describe('resolveProjectTopicSandbox', () => {mocks.listEnvironments.mockResolvedValue([repository, published]);mocks.findEnvironmentById.mockResolvedValue(published);- await expect(resolve({ agentId: 'agt-shared', workspaceId: 'ws-1' })).resolves.toMatchObject({- sandboxDrive: 'public',+ await expect(resolve({ agentId: 'agt-shared', workspaceId: 'ws-1' })).resolves.toEqual({sandboxEnvironmentId: 'env-pub',});});diff --git a/apps/server/src/services/sandbox/__tests__/workspace.test.ts b/apps/server/src/services/sandbox/__tests__/workspace.test.tsindex 446a9f3d566..1d0ba32ba03 100644--- a/apps/server/src/services/sandbox/__tests__/workspace.test.ts+++ b/apps/server/src/services/sandbox/__tests__/workspace.test.ts@@ -110,16 +110,19 @@ describe('formatSandboxStoragePromptVariables', () => {);});- // Persistence is not enabled yet: until an entitlement claim is issued every- // run renders this branch, so it has to reproduce the pre-placeholder prompt- // exactly — including the lines surrounding the two spliced sections.- it('renders the original ephemeral wording, byte for byte', () => {+ // Every run without an entitlement renders this branch: the original lines,+ // then what the temporary sandbox is for — spliced cleanly between the lines+ // around the placeholder.+ it('renders the ephemeral wording, with what the temporary sandbox suits', () => {const vars = formatSandboxStoragePromptVariables();const rendered = render(vars);for (const key of placeholders) expect(rendered).not.toContain(key);expect(rendered).toContain(- '- Files created here are temporary and session-specific\n- Each conversation topic has its own isolated session\n- Sessions may expire after inactivity; files will be recreated if needed\n- The sandbox has its own isolated file system starting at the root directory\n- Commands will time out',+ '- Files created here are temporary and session-specific\n- Each conversation topic has its own isolated session\n- Sessions may expire after inactivity; files will be recreated if needed\n- The sandbox has its own isolated file system starting at the root directory\n- This is a temporary sandbox, discarded after use',+ );+ expect(rendered).toContain(+ 'export finished files with `exportFile`.\n- Commands will time out',);expect(rendered).toContain('- If a session expires, it will be automatically recreated\n- Files from previous sessions may not persist\n- The sessionExpiredAndRecreated flag',diff --git a/apps/server/src/services/sandbox/projectPlacement.ts b/apps/server/src/services/sandbox/projectPlacement.tsindex 5325911cc80..78ef7fcf94c 100644--- a/apps/server/src/services/sandbox/projectPlacement.ts+++ b/apps/server/src/services/sandbox/projectPlacement.ts@@ -1,4 +1,3 @@-import { projectCheckoutDirectory, type SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';import type { ChatTopicMetadata } from '@lobechat/types';import debug from 'debug';@@ -9,10 +8,7 @@ import { ProjectModel } from '@/database/models/project';const log = debug('lobe-server:sandbox:project-placement');-export type ProjectTopicSandbox = Pick<- ChatTopicMetadata,- 'sandboxDrive' | 'sandboxEnvironmentId' | 'sandboxWorkingDirectory'->;+export type ProjectTopicSandbox = Pick<ChatTopicMetadata, 'sandboxEnvironmentId'>;export interface ProjectTopicSandboxInput {/** The agent the conversation runs; a workspace-public one applies published environments only. */@@ -30,18 +26,13 @@ const hasGitSource = (configuration: { sources?: { kind?: string }[] } | null |/*** The sandbox a new project conversation starts in: the project's repository,- * checked out in the project's own folder on the drive.+ * cloned into a temporary Cloud Sandbox.*- * The folder is what makes it persistent. The sandbox initializes an empty- * folder from the environment and leaves a filled one alone, so the first- * conversation clones and every later one picks up the same checkout. Nothing- * is created here — the run creates the folder when it first needs it (see- * `resolvePlacement`), so starting a conversation never waits on a sandbox.- * Without a storage entitlement the run goes to a temporary sandbox, where the- * repository still applies.- *- * A private repository goes on the member's personal drive: the public drive- * is every member's, and the checkout can hold its owner's credentials.+ * Coding belongs in the temporary sandbox, which is discarded after use: a+ * repository's dependencies and build output would only fill the drive, and+ * the remote repository is where the code is kept. So the conversation names+ * the repository and no folder — each conversation clones it afresh — and+ * a person who wants the drive picks it in the composer.** A workspace-public agent runs on its caller's session and applies published* environments only (see `resolveInitialization`), so for one a private@@ -74,13 +65,7 @@ export const resolveProjectTopicSandbox = async ({const environment = await new EnvironmentModel(db, userId, workspaceId).findById(picked.id);if (!environment) return {};- const drive: SandboxDrive = environment.visibility === 'public' ? 'public' : 'personal';-- return {- ...(workspaceId && { sandboxDrive: drive }),- sandboxEnvironmentId: environment.id,- sandboxWorkingDirectory: projectCheckoutDirectory(projectId, environment.id),- };+ return { sandboxEnvironmentId: environment.id };} catch (error) {log('Failed to resolve the sandbox for a topic in project %s: %O', projectId, error);return {};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 39ceac9ab19..0d7b6ac2152 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1576,6 +1576,8 @@"heteroAgent.executionTarget.onlineConnections_one": "Online · {{count}} connection","heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} connections","heteroAgent.executionTarget.otherDevicesGroup": "Other devices",+ "heteroAgent.executionTarget.persistentSandbox": "Persistent Sandbox",+ "heteroAgent.executionTarget.persistentSandboxDesc": "Keeps results and work on your drive, for everyday tasks","heteroAgent.executionTarget.personalGroup": "Private Devices","heteroAgent.executionTarget.presenceChecking": "Checking status…","heteroAgent.executionTarget.projectDevicesHint": "Only devices with this project's working directory are listed. Add a directory for another device in the project settings.",@@ -1588,6 +1590,7 @@"heteroAgent.executionTarget.switchTopic.content": "This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.","heteroAgent.executionTarget.switchTopic.ok": "Switch","heteroAgent.executionTarget.switchTopic.title": "Move this topic to another environment?",+ "heteroAgent.executionTarget.temporarySandboxDesc": "Discarded after use, for coding and one-off data processing","heteroAgent.executionTarget.title": "Execution Environment","heteroAgent.executionTarget.topicTag": "This topic","heteroAgent.executionTarget.unknownDevice": "Unknown device",@@ -2182,6 +2185,7 @@"sandboxEnvironment.loadFailed": "Couldn't load environments","sandboxEnvironment.loading": "Loading environment…","sandboxEnvironment.missing": "Environment unavailable",+ "sandboxEnvironment.none": "No repository","sandboxEnvironment.retry": "Retry","sandboxEnvironment.saveFailed": "Could not change the environment. Try again.","sandboxEnvironment.title": "Repository",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3ec298de977..d3365ea0b54 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1576,6 +1576,8 @@"heteroAgent.executionTarget.onlineConnections_one": "在线 · {{count}} 个连接","heteroAgent.executionTarget.onlineConnections_other": "在线 · {{count}} 个连接","heteroAgent.executionTarget.otherDevicesGroup": "其他设备",+ "heteroAgent.executionTarget.persistentSandbox": "持久化沙箱",+ "heteroAgent.executionTarget.persistentSandboxDesc": "产物和过程保存到云盘,适合日常任务","heteroAgent.executionTarget.personalGroup": "私人设备","heteroAgent.executionTarget.presenceChecking": "正在确认状态…","heteroAgent.executionTarget.projectDevicesHint": "仅列出已绑定此项目工作目录的设备。其他设备可在项目设置中添加目录。",@@ -1588,6 +1590,7 @@"heteroAgent.executionTarget.switchTopic.content": "本话题一直在「{{name}}」上运行,工作目录和会话都保存在那里。切换后,下一轮会在新环境中开启新会话;之后的新话题也会使用这个选择。","heteroAgent.executionTarget.switchTopic.ok": "切换","heteroAgent.executionTarget.switchTopic.title": "将本话题切换到其他执行环境?",+ "heteroAgent.executionTarget.temporarySandboxDesc": "即用即销毁,适合编程和临时数据处理","heteroAgent.executionTarget.title": "执行环境","heteroAgent.executionTarget.topicTag": "本话题","heteroAgent.executionTarget.unknownDevice": "未知设备",@@ -2182,6 +2185,7 @@"sandboxEnvironment.loadFailed": "无法加载环境列表","sandboxEnvironment.loading": "正在加载环境…","sandboxEnvironment.missing": "环境不可用",+ "sandboxEnvironment.none": "不使用仓库","sandboxEnvironment.retry": "重试","sandboxEnvironment.saveFailed": "无法更改环境,请重试。","sandboxEnvironment.title": "代码仓库",diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.tsindex fcde1ee640d..5732f4fa1ef 100644--- a/packages/builtin-tool-cloud-sandbox/src/index.ts+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts@@ -1,6 +1,5 @@export * from './interventionAudit';export * from './manifest';-export * from './projectCheckout';export * from './systemRole';export * from './types';export * from './uploadedFiles';diff --git a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.ts b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.tsdeleted file mode 100644index adf9f42a364..00000000000--- a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from 'vitest';--import { projectCheckoutDirectory } from './projectCheckout';-import { isSafeSandboxCwd } from './workspace';--describe('projectCheckoutDirectory', () => {- const ENV_ID = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';-- it('keeps one folder per project and environment', () => {- expect(projectCheckoutDirectory('proj_1', ENV_ID)).toBe(`projects/proj_1/${ENV_ID}`);- });-- // A filled folder is never initialized again, so a shared folder would run- // the second repository against the first one's checkout.- it('keeps two repositories apart whatever they are called', () => {- expect(projectCheckoutDirectory('proj_1', 'env-a')).not.toBe(- projectCheckoutDirectory('proj_1', 'env-b'),- );- });-- it('turns anything but an id character into a plain one, so no segment escapes', () => {- const folder = projectCheckoutDirectory('../proj', '..');-- expect(folder).toBe('projects/___proj/__');- expect(isSafeSandboxCwd(folder)).toBe(true);- });-- it('stays a usable working directory', () => {- expect(isSafeSandboxCwd(projectCheckoutDirectory('proj_1', ENV_ID))).toBe(true);- });-});diff --git a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.ts b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.tsdeleted file mode 100644index 637f602eab5..00000000000--- a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.ts+++ /dev/null@@ -1,24 +0,0 @@-/** Where every project keeps its repository checkouts on the drive. */-export const PROJECT_DRIVE_ROOT = 'projects';--/**- * One path segment from an id. Ids are already path-safe (`prj_…`, UUIDs); any- * other character becomes `_`, which also rules out `.`/`..` segments. One- * character class, no anchored repetition, so it runs in linear time on any input.- */-const toSegment = (value: string) => value.replaceAll(/[^\w-]/g, '_');--/**- * A project's checkout of one repository on the drive: one folder per project- * and environment, shared by every conversation in the project, so work done in- * one is there for the next — the way a local clone is.- *- * Derived from ids alone. A name in the path would move the checkout whenever- * the project or the environment is renamed, and the next conversation would- * clone afresh beside the work already done; a repository's name alone would- * also put `orgA/api` and `orgB/api` in one folder, and a filled folder is never- * initialized again. Where the folder is shown, it is shown by the repository's- * name, not its path.- */-export const projectCheckoutDirectory = (projectId: string, environmentId: string) =>- `${PROJECT_DRIVE_ROOT}/${toSegment(projectId)}/${toSegment(environmentId)}`;diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.test.tsindex ece2a527188..44feca851ca 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts@@ -3,10 +3,9 @@ import { describe, expect, it } from 'vitest';import { formatSandboxStoragePromptVariables } from './workspace';describe('formatSandboxStoragePromptVariables', () => {- it('leaves the ephemeral wording exactly as a run without persistence has always had it', () => {+ it('tells a temporary run it is discarded after use, and what it suits', () => {// The ordinary sandbox is every free run and every topic that never asked- // for persistence; its prompt must not drift because the persistent one- // gained a rule.+ // for persistence; it keeps its original lines and adds what it is for.expect(formatSandboxStoragePromptVariables()).toEqual({sandbox_session_files: '- Files from previous sessions may not persist',sandbox_workspace: [@@ -14,8 +13,11 @@ describe('formatSandboxStoragePromptVariables', () => {'- Each conversation topic has its own isolated session','- Sessions may expire after inactivity; files will be recreated if needed','- The sandbox has its own isolated file system starting at the root directory',+ '- This is a temporary sandbox, discarded after use: results and intermediate files are not kept once it is gone. It suits coding on a repository and one-off data processing, where nothing along the way needs keeping. Anything the user wants to keep has to leave the sandbox — export finished files with `exportFile`.',].join('\n'),});+ // A deployment without persistence must not be pointed at a drive.+ expect(formatSandboxStoragePromptVariables().sandbox_workspace).not.toMatch(/drive/i);expect(formatSandboxStoragePromptVariables({ mode: 'ephemeral' })).toEqual(formatSandboxStoragePromptVariables(),);@@ -80,6 +82,19 @@ describe('the three placements a run can have', () => {expect(prompt).toContain('its own subfolder');});+ // The persistent sandbox is for everyday work; coding belongs in the+ // temporary one, where dependencies and build output cost no drive space.+ it('tells a drive run it is for everyday tasks, and to send coding to the Cloud Sandbox', () => {+ const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({+ cwd: 'reports',+ mode: 'drive',+ });++ expect(prompt).toContain('meant for everyday tasks');+ expect(prompt).toContain('It is not meant for coding');+ expect(prompt).toContain('switch this conversation to the Cloud Sandbox');+ });+it('names an instance as an environment directory whose packages come back', () => {const { sandbox_workspace: prompt } = formatSandboxStoragePromptVariables({cwd: 'notes-env',diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.tsindex e823131bca1..a8390bad882 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.ts@@ -272,9 +272,11 @@ export const isSafeSandboxEnvironmentId = (value: string): boolean =>* - `sandbox_workspace` fills the `<sandbox_environment>` file-system bullets* - `sandbox_session_files` fills the `<session_behavior>` persistence bullet*- * An ephemeral run renders the ORIGINAL wording, byte for byte, so a deployment- * where persistence is not enabled keeps the exact prompt it had before and- * never leaks a raw placeholder.+ * An ephemeral run is told the sandbox is discarded after use, and what that+ * makes it for: coding on a repository and one-off data processing, with+ * anything worth keeping exported before the session ends. Nothing in it+ * mentions a drive, so a deployment where persistence is not enabled is not+ * pointed at one it does not have.** The persistent wording carries no absolute path on purpose. The mount root is* the execution plane's to choose, the runtime already starts every call inside@@ -318,6 +320,9 @@ export const formatSandboxStoragePromptVariables = ({'- Each conversation topic has its own isolated session','- Sessions may expire after inactivity; files will be recreated if needed','- The sandbox has its own isolated file system starting at the root directory',+ // What the disposable sandbox is FOR, so the model neither treats it as+ // somewhere to keep things nor apologizes for it on a coding task.+ '- This is a temporary sandbox, discarded after use: results and intermediate files are not kept once it is gone. It suits coding on a repository and one-off data processing, where nothing along the way needs keeping. Anything the user wants to keep has to leave the sandbox — export finished files with `exportFile`.',].join('\n'),};}@@ -345,6 +350,11 @@ export const formatSandboxStoragePromptVariables = ({? '- Other conversations may use other folders on the same drive at the same time. Keep to this folder unless the user asks otherwise.': '- Other conversations may use the same drive at the same time. Keep task-specific work in its own subfolder so unrelated tasks do not overwrite each other, and reuse what is already there when the user refers to earlier work.','- Only files on the drive persist. The machine itself starts fresh every session: packages you install and anything outside the drive are gone next time, so reinstall what a task needs rather than assuming it is still there.',+ // The persistent sandbox is for everyday work whose results should+ // stay; coding is what the temporary one is for. A repository's+ // dependencies and build output on the drive cost the user quota+ // and nothing else.+ "- This is the persistent sandbox, meant for everyday tasks: the results you produce and the work behind them stay on the drive for the user. It is not meant for coding — a repository's dependencies, virtual environments, caches and build output would take up a lot of the user's drive space. Keep those off the drive (outside the working directory) when a task needs them, and when the task is mainly programming on a codebase, suggest the user switch this conversation to the Cloud Sandbox, which is discarded after use.",]: workingDir? [@@ -367,13 +377,13 @@ export const formatSandboxStoragePromptVariables = ({// wrong here: the result is thrown away with the session and the user// never sees it when browsing the drive, which reads this directory.// Said once, positively, rather than as a list of directories to avoid.- '- Every call starts you in that directory, and it is where the work belongs: checkouts, generated files and notes written anywhere else — `/root`, `/tmp`, a scratch directory of your own — are lost with the session and never appear on the user’s drive. Stay where you start; if a step genuinely needs scratch space, say where you put it.',+ '- Every call starts you in that directory, and it is where the work belongs: results, generated files and notes written anywhere else — `/root`, `/tmp`, a scratch directory of your own — are lost with the session and never appear on the user’s drive. Stay where you start; if a step genuinely needs scratch space, say where you put it.',// Deliberately does NOT send installs to `/tmp`. The drive is network// storage — an order of magnitude slower for the thousands of small files// a package install writes — but the answer is to let them land where the// toolchain normally puts them, not to relocate them somewhere the// platform treats as scratch.- '- The drive is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes. Install packages and build where the toolchain puts things by default, and keep the drive for what is worth keeping.',+ '- The drive is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes. Keep the drive for what is worth keeping.','- It has a storage quota, which covers what you leave on the drive.',].join('\n'),};diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex bc724bfa7c6..a3182125f95 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -975,6 +975,11 @@ export default {'heteroAgent.executionTarget.personalGroup': 'Private Devices','heteroAgent.executionTarget.sandbox': 'Cloud Sandbox','heteroAgent.executionTarget.sandboxDesc': 'Runs in the cloud, no machine needed',+ 'heteroAgent.executionTarget.persistentSandbox': 'Persistent Sandbox',+ 'heteroAgent.executionTarget.persistentSandboxDesc':+ 'Keeps results and work on your drive, for everyday tasks',+ 'heteroAgent.executionTarget.temporarySandboxDesc':+ 'Discarded after use, for coding and one-off data processing','heteroAgent.executionTarget.workspaceGroup': 'Workspace Devices','heteroAgent.executionTarget.downloadDesktop': 'Get Desktop App','heteroAgent.executionTarget.downloadDesktopDesc': 'Run agents with access to your computer',@@ -4445,6 +4450,7 @@ export default {'you': 'You','sandboxDrive.manageEnvironments': 'Settings','sandboxDrive.openStorage': 'Sandbox Storage',+ 'sandboxEnvironment.none': 'No repository','sandboxEnvironment.missing': 'Environment unavailable','sandboxEnvironment.loading': 'Loading environment…','sandboxDrive.pickerTitle': 'Work location',diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex 2a211048937..dd810ecc86c 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -4,12 +4,13 @@ import { isDesktop } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { DeviceExecutionTarget, DeviceListItem } from '@lobechat/types';import { isManagedCloudDevice } from '@lobechat/types';-import { Button, Flexbox, Icon, Popover, toast, Tooltip } from '@lobehub/ui';+import { Button, Flexbox, Icon, Popover, Tag, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import {ChevronDownIcon,ExternalLinkIcon,+ HardDriveIcon,InfoIcon,MonitorDownIcon,SettingsIcon,@@ -18,6 +19,7 @@ import {import { memo, type ReactNode, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';import InstantSwitch from '@/components/InstantSwitch';import { DOWNLOAD_URL } from '@/const/url';import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';@@ -53,6 +55,7 @@ import { getDevicePoolStatus } from './devicePoolStatus';import OptionRow from './OptionRow';import { reconnectDevice } from './reconnectDevice';import { isThisComputerDevice, splitThisComputerDevices } from './thisComputerDevices';+import { useSandboxModeSelect } from './useSandboxModeSelect';import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';@@ -360,13 +363,43 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {});const handleSelect = useCallback(- async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {+ async (+ target: DeviceExecutionTarget,+ deviceId?: string,+ localSandbox?: boolean,+ afterApply?: () => Promise<void>,+ ) => {setOpen(false);- await selectTarget(target, deviceId, localSandbox);+ await selectTarget(target, deviceId, localSandbox, afterApply);},[selectTarget],);+ // The cloud sandbox comes as two rows — temporary, and persistent on the+ // drive — that share the `sandbox` target and differ in where this+ // conversation keeps its files. The drive is asked about once the menu could+ // show it, or the chip has to name it.+ const sandboxMode = useSandboxModeSelect(agentId, {+ enabled: supportsSandbox && (open || executionTarget === 'sandbox'),+ topicId,+ });+ const offersPersistentSandbox =+ supportsSandbox &&+ (sandboxMode.driveStatus === 'ready' || sandboxMode.driveStatus === 'upgrade');+ const selectSandbox = useCallback(+ (persistent: boolean) =>+ handleSelect('sandbox', undefined, undefined, async () => {+ try {+ await (persistent ? sandboxMode.toPersistent() : sandboxMode.toTemporary());+ } catch {+ // The target moved but the conversation kept its folder; said rather+ // than left looking switched.+ toast.error(t('sandboxEnvironment.saveFailed'));+ }+ }),+ [handleSelect, sandboxMode, t],+ );+// Setting up the backend raises an elevation prompt and creates a dedicated// OS account, so it only ever happens on this explicit click. The popover// stays open throughout — the user came here to pick an environment, and the@@ -528,7 +561,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {// Compute chiplet chipIcon: ReactNode = <ExecutionTargetIcon target={'sandbox'} />;let chipLabel = t('heteroAgent.executionTarget.sandbox');- if (chipExecutionTarget === 'none') {+ if (chipExecutionTarget === 'sandbox' && sandboxMode.persistent) {+ chipIcon = <Icon icon={HardDriveIcon} size={14} />;+ chipLabel = t('heteroAgent.executionTarget.persistentSandbox');+ } else if (chipExecutionTarget === 'none') {chipIcon = <ExecutionTargetIcon target={'none'} />;chipLabel = t('heteroAgent.executionTarget.none');} else if (chipExecutionTarget === 'auto') {@@ -743,18 +779,51 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {onClick={() => void handleSelect('local', undefined, true)}/>) : null}+ {/* Two sandboxes on one `sandbox` target, the persistent one first: it is+ where everyday work belongs, keeping its results and the work behind+ them on the drive. The temporary one is discarded after use, which+ suits coding and one-off data processing — a repository's+ dependencies and build output would only fill the drive. A plan+ without a drive sees the persistent row in the same place, tagged,+ as the way to one; with no drive at all only the temporary row is+ left, described as it always was. */}+ {offersPersistentSandbox ? (+ <OptionRow+ active={isActive('sandbox') && sandboxMode.persistent}+ desc={t('heteroAgent.executionTarget.persistentSandboxDesc')}+ icon={<Icon icon={HardDriveIcon} size={14} />}+ label={t('heteroAgent.executionTarget.persistentSandbox')}+ badge={+ sandboxMode.driveStatus === 'upgrade' ? (+ <Tag color={'gold'} size={'small'} style={{ borderRadius: 999, paddingInline: 8 }}>+ {t('pro', { ns: 'common' })}+ </Tag>+ ) : undefined+ }+ onClick={() => {+ if (sandboxMode.driveStatus === 'upgrade') {+ setOpen(false);+ openSandboxStorageUpsell();+ return;+ }+ void selectSandbox(true);+ }}+ />+ ) : null}<OptionRow- active={isActive('sandbox')}+ active={isActive('sandbox') && !sandboxMode.persistent}disabled={!supportsSandbox}icon={<ExecutionTargetIcon target={'sandbox'} />}label={t('heteroAgent.executionTarget.sandbox')}desc={t(- supportsSandbox- ? 'heteroAgent.executionTarget.sandboxDesc'- : 'heteroAgent.executionTarget.sandboxUnsupported',+ !supportsSandbox+ ? 'heteroAgent.executionTarget.sandboxUnsupported'+ : offersPersistentSandbox+ ? 'heteroAgent.executionTarget.temporarySandboxDesc'+ : 'heteroAgent.executionTarget.sandboxDesc',{ name: heteroType ? HETEROGENEOUS_TYPE_LABELS[heteroType] : undefined },)}- onClick={() => void handleSelect('sandbox')}+ onClick={() => void selectSandbox(false)}/>{deviceRows.length > 0 ? (showDeviceGroups ? (diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxindex ea2c41ef064..765bd2b5587 100644--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -87,9 +87,14 @@ const SUBMENU_STYLES = {interface SandboxDrivePickerProps {/** Whether this plan includes a drive. Without one the menu offers the way to a plan. */entitled: boolean;+ /**+ * Whether the execution-environment menu offers the temporary and the+ * persistent sandbox. When it cannot — the author fixed the target, so a+ * member sees it read-only — this menu keeps both, since the placement is+ * still the member's own per conversation.+ */+ modeInEnvironmentMenu?: boolean;onChange: (selection: SandboxSelection) => Promise<void>;- /** The project the conversation belongs to; its repositories have a checkout there. */- projectId?: string;topicId?: string;/** Where this conversation works today. */value: SandboxSelection;@@ -99,31 +104,41 @@ const folderName = (path: string) => path.split('/').pop() || path;/*** Where a cloud-sandbox run works, offered the way the device picker offers- * folders: the chip names the place, the menu holds the temporary sandbox and- * the way into the drive's directory browser.+ * folders: the chip names the place. Which sandbox it is — temporary, or+ * persistent on the drive — is picked in the execution-environment menu, so+ * the menu here is the drive's folders on the persistent sandbox, and only the+ * repository to clone, or none, on the temporary one — whose folder is always+ * a fresh empty one, nothing to pick. A repository belongs to the temporary+ * sandbox alone: the persistent one is for keeping a folder of the drive.** Nothing picked is the temporary sandbox; picking a folder on the drive is* the choice to keep files. A pick that can no longer be honoured — the* folder was deleted — is said on the chip itself, before the next message* runs somewhere the person did not choose.*- * A repository is the third kind of place, one level down: temporary, a folder- * or a repository, one at a time. A checkout only lands in an empty folder, so- * offering it beside a folder that holds files would let a pick silently do- * nothing.+ * A folder and a repository are one choice, not two: a checkout only lands in+ * an empty folder, so offering it beside a folder that holds files would let a+ * pick silently do nothing. Where the execution-environment menu cannot be+ * used, this menu keeps all three places in one list.** A conversation from before environments became initializers may still be* bound to an environment directory; it is shown by name until another pick* replaces it.*/const SandboxDrivePicker = memo<SandboxDrivePickerProps>(- ({ entitled, onChange, projectId, topicId, value }) => {+ ({ entitled, modeInEnvironmentMenu = true, onChange, topicId, value }) => {const { t } = useTranslation(['chat', 'device']);const [open, setOpen] = useState(false);const workspaceId = useActiveWorkspaceId();const navigate = useWorkspaceAwareNavigate();const persistent = isPersistentSelection(value);const onRepository = !!value.environmentId;+ // The persistent sandbox: the conversation keeps its files on the drive.+ const onDrive = ENABLE_BUSINESS_FEATURES && entitled && persistent && modeInEnvironmentMenu;+ // The temporary sandbox, picked in the execution-environment menu: its+ // folder is always a fresh empty one, so the only question left is whether+ // a repository is cloned into it.+ const repositoryOnly = modeInEnvironmentMenu && !onDrive;const {data: environmentList,@@ -196,14 +211,7 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(const pickRepository = async (environment: SandboxRepositoryOption) => {try {- await onChange(- repositorySelection(environment, {- projectId,- published:- environments.find((item) => item.id === environment.id)?.visibility === 'public',- workspace: !!workspaceId,- }),- );+ await onChange(repositorySelection(environment));void revalidatePlacement();} catch {// The topic kept its place; said rather than left looking changed.@@ -257,6 +265,8 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(<RepositoryAvatar size={14} url={repository && repositorySlug(repository)} />) : persistent ? (<Icon icon={currentIcon} size={14} />+ ) : repositoryOnly ? (+ <Github size={14} />) : (<Icon icon={TimerIcon} size={14} />);@@ -274,9 +284,95 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(? repositoryLabel: persistent? currentLabel- : t('sandboxStorage.ephemeral');+ : repositoryOnly+ ? t('sandboxEnvironment.none')+ : t('sandboxStorage.ephemeral');- const content = (+ const driveMenu = (+ <SandboxDriveMenu+ selectedLabel={showFolder ? currentLabel : undefined}+ selectedPath={showFolder ? value.workingDirectory : undefined}+ onBrowse={openBrowser}+ onPick={(folder) => void select(folder)}+ onOpenStorage={() => {+ setOpen(false);+ navigate(SANDBOX_STORAGE_PATH);+ }}+ />+ );++ const repositoryMenuProps = {+ environments,+ failed: !!environmentsError,+ loaded: !!environmentList,+ onAdd: addRepository,+ onClose: () => setOpen(false),+ onManage: () => {+ setOpen(false);+ navigate('/settings/environments');+ },+ onPick: pickRepository,+ onRetry: () => void refreshEnvironments(),+ selectedId: value.environmentId,+ };++ const repositoryRow = (+ <Popover+ arrow={false}+ closeDelay={150}+ content={<SandboxRepositoryMenu {...repositoryMenuProps} />}+ placement={'rightBottom'}+ styles={SUBMENU_STYLES}+ trigger={['hover', 'click']}+ >+ <div data-testid={'sandbox-repository-row'}>+ <OptionRow+ arrow+ compact+ active={onRepository}+ hint={onRepository && repository ? repositorySlug(repository) : undefined}+ icon={+ onRepository && repository ? (+ <RepositoryAvatar size={16} url={repositorySlug(repository)} />+ ) : (+ <Github size={16} />+ )+ }+ label={+ // The repository the conversation works in, by name; the+ // generic title only while none is picked.+ onRepository && repositoryState.kind === 'picked'+ ? repositoryState.name+ : t('sandboxEnvironment.title')+ }+ onClick={() => {}}+ />+ </div>+ </Popover>+ );++ const notice = fallbackMessage && (+ <Text className={stylex.props(styles.notice).className}>{fallbackMessage}</Text>+ );++ // The execution-environment menu already said which sandbox this is, so the+ // menu here only asks the question left: on the persistent sandbox, which+ // folder of the drive; on the temporary one, whether to clone a repository+ // at all.+ const content = onDrive ? (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>+ {notice}+ {driveMenu}+ </Flexbox>+ ) : repositoryOnly ? (+ <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>+ {notice}+ <SandboxRepositoryMenu+ {...repositoryMenuProps}+ none={{ active: !onRepository, onPick: () => void select({}) }}+ />+ </Flexbox>+ ) : (<Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}><div {...stylex.props(styles.header)}><Flexbox horizontal align={'center'} gap={4}>@@ -289,9 +385,7 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(</Flexbox></div>- {fallbackMessage && (- <Text className={stylex.props(styles.notice).className}>{fallbackMessage}</Text>- )}+ {notice}<OptionRowcompact@@ -301,26 +395,16 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(onClick={() => void select({})}/>+ {/* No environment menu to switch sandboxes in: the drive stays a row here. */}{ENABLE_BUSINESS_FEATURES &&(entitled ? (<Popoverarrow={false}closeDelay={150}+ content={driveMenu}placement={'rightBottom'}styles={SUBMENU_STYLES}trigger={['hover', 'click']}- content={- <SandboxDriveMenu- selectedLabel={showFolder ? currentLabel : undefined}- selectedPath={showFolder ? value.workingDirectory : undefined}- onBrowse={openBrowser}- onPick={(folder) => void select(folder)}- onOpenStorage={() => {- setOpen(false);- navigate(SANDBOX_STORAGE_PATH);- }}- />- }><div data-testid={'sandbox-drive-row'}><OptionRow@@ -334,9 +418,6 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(</div></Popover>) : (- // The drive is part of a plan this account is not on. Offered in the- // same list, in the same shape, so the row reads as one more place- // files could go — and the tag says why it is not simply selectable.<OptionRowcompacticon={<Icon icon={HardDriveIcon} size={16} />}@@ -353,53 +434,7 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(/>))}- <Popover- arrow={false}- closeDelay={150}- placement={'rightBottom'}- styles={SUBMENU_STYLES}- trigger={['hover', 'click']}- content={- <SandboxRepositoryMenu- environments={environments}- failed={!!environmentsError}- loaded={!!environmentList}- selectedId={value.environmentId}- onAdd={addRepository}- onClose={() => setOpen(false)}- onPick={pickRepository}- onRetry={() => void refreshEnvironments()}- onManage={() => {- setOpen(false);- navigate('/settings/environments');- }}- />- }- >- <div data-testid={'sandbox-repository-row'}>- <OptionRow- arrow- compact- active={onRepository}- hint={onRepository && repository ? repositorySlug(repository) : undefined}- icon={- onRepository && repository ? (- <RepositoryAvatar size={16} url={repositorySlug(repository)} />- ) : (- <Github size={16} />- )- }- label={- // The repository the conversation works in, by name; the- // generic title only while none is picked.- onRepository && repositoryState.kind === 'picked'- ? repositoryState.name- : t('sandboxEnvironment.title')- }- onClick={() => {}}- />- </div>- </Popover>+ {repositoryRow}</Flexbox>);diff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsxindex e373ba6dfe3..47673e734c2 100644--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx+++ b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx@@ -4,7 +4,7 @@ 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 { PlusIcon, SettingsIcon } from 'lucide-react';+import { CircleOffIcon, PlusIcon, SettingsIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -37,6 +37,12 @@ interface SandboxRepositoryMenuProps {environments: SandboxRepositoryOption[];failed: boolean;loaded: boolean;+ /**+ * A first row for working without a repository. Offered where this menu is+ * the whole choice — the temporary sandbox, whose folder is always a fresh+ * empty one — rather than one level under a list of places.+ */+ none?: { active: boolean; onPick: () => void };onAdd: () => void;/** Closes the whole work-location menu; a final pick leaves it. */onClose: () => void;@@ -47,11 +53,23 @@ interface SandboxRepositoryMenuProps {}/**- * The second level of the work-location menu: the repositories a conversation- * can work on, and the way to add one without leaving the composer.+ * The repositories a conversation can work on, and the way to add one without+ * leaving the composer: the whole menu on the temporary sandbox, one level+ * under the drive's folders on the persistent one.*/const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(- ({ environments, failed, loaded, onAdd, onClose, onManage, onPick, onRetry, selectedId }) => {+ ({+ environments,+ failed,+ loaded,+ none,+ onAdd,+ onClose,+ onManage,+ onPick,+ onRetry,+ selectedId,+ }) => {const { t } = useTranslation('chat');return (<Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>@@ -66,6 +84,18 @@ const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(<Text className={stylex.props(styles.hint).className}>{t('sandboxEnvironment.hint')}</Text><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) => (<OptionRowcompactdiff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsxindex 6f95dc6b742..a6617434988 100644--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -2,10 +2,17 @@import { memo } from 'react';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import SafeBoundary from '@/components/ErrorBoundary';+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';import { useTopicId } from '../hooks/useTopicId';import SandboxDrivePicker from './SandboxDrivePicker';+import { usePrefersTemporarySandbox } from './temporarySandboxPreference';+import { useFollowSandboxModePreference } from './useFollowSandboxModePreference';import { useSandboxPlacement } from './useSandboxPlacement';import { useSandboxStorageAccess } from './useSandboxStorageAccess';import { useSeedDefaultSelection } from './useSeedDefaultSelection';@@ -23,7 +30,8 @@ interface SandboxStorageSectionProps {* Nothing chosen means a temporary sandbox, cleaned up with the session; a* folder on the drive keeps its files, and a repository starts from a checkout.* A plan with a drive starts each new conversation on its default folder rather- * than nothing.+ * than nothing — unless the execution-environment menu moved the agent to the+ * temporary cloud sandbox, which new conversations then keep.** A plan without a drive still gets the chip: the temporary sandbox is* everyone's, and the way to a plan is a row in the same menu rather than a@@ -31,13 +39,33 @@ interface SandboxStorageSectionProps {*/const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {const { eligible, status } = useSandboxStorageAccess(agentId);- const { projectId, selection, setSelection, topicId } = useSandboxPlacement(+ const scopeTopicId = useTopicId();+ const { selection, setSelection, topicId } = useSandboxPlacement(agentId, scopeTopicId);+ // The temporary and persistent sandboxes are picked in the execution+ // environment menu — when this member can use it. A target the author fixed+ // leaves that menu read-only, so the choice stays in this one.+ const { canUseResource } = useChatInputResourceAccess();+ const { canDisplayExecutionTarget, canSelectExecutionTarget } = useEffectiveAgencyConfig(agentId,- useTopicId(),+ { topicId: scopeTopicId },);+ const modeInEnvironmentMenu =+ canUseResource && canDisplayExecutionTarget && canSelectExecutionTarget;+ const userId = useUserStore(userProfileSelectors.userId);+ const workspaceId = useActiveWorkspaceId();+ const prefersTemporary = usePrefersTemporarySandbox({ userId, workspaceId }, agentId);+ // Only a pick made in that menu counts; a member who cannot make it is not+ // held to one made before the target was fixed.+ const temporary = prefersTemporary && modeInEnvironmentMenu;+ useFollowSandboxModePreference(agentId, {+ enabled: modeInEnvironmentMenu,+ hasTopic: !!topicId,+ scopeKey: `${userId ?? ''}:${workspaceId ?? ''}:${agentId}`,+ temporary: prefersTemporary,+ });useSeedDefaultSelection(agentId, {- eligible,- entitled: status === 'ready',+ eligible: eligible && !temporary,+ entitled: status === 'ready' && !temporary,hasTopic: !!topicId,});@@ -46,7 +74,7 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }return (<SandboxDrivePickerentitled={status === 'ready'}- projectId={projectId}+ modeInEnvironmentMenu={modeInEnvironmentMenu}topicId={topicId}value={selection}onChange={setSelection}diff --git a/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx b/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsxnew file mode 100644index 00000000000..891b984385b--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx@@ -0,0 +1,191 @@+import { fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import HeteroDeviceSwitcher from '../HeteroDeviceSwitcher';++const state = vi.hoisted(() => ({+ driveStatus: 'ready' as 'hidden' | 'loading' | 'ready' | 'upgrade',+ openUpsell: vi.fn(),+ persistent: false,+ selectTarget: vi.fn(),+ toPersistent: vi.fn(),+ toTemporary: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// The menu, open: which rows it offers and what they do is the question.+vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ Popover: ({ children, content }: { children: ReactNode; content: ReactNode }) => (+ <div>+ <div data-testid="chip">{children}</div>+ {content}+ </div>+ ),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ isDesktop: false,+}));++vi.mock('@/business/client/features/SandboxStorageUpsell', () => ({+ openSandboxStorageUpsell: state.openUpsell,+}));+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({+ useChatInputResourceAccess: () => ({ canUseResource: true }),+}));+vi.mock('@/features/ChatInput/hooks/useLocalSandboxCapability', () => ({+ useLocalSandboxCapability: () => ({ data: undefined, mutate: vi.fn() }),+}));+vi.mock('@/features/ChatInput/hooks/useSelectExecutionTarget', () => ({+ useSelectExecutionTarget: () => vi.fn(),+}));+vi.mock('@/features/DeviceManager/DeviceLoadMeter', () => ({+ default: () => null,+ useDeviceLoad: () => null,+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: { executionTarget: 'sandbox' },+ canDisplayExecutionTarget: true,+ canSelectExecutionTarget: true,+ isPreferenceLoading: false,+ topicDeviceUnknown: false,+ workspaceScoped: false,+ }),+}));+vi.mock('@/hooks/useLocalMachineDeviceIds', () => ({ useLocalMachineDeviceIds: () => [] }));+vi.mock('@/services/device', () => ({ deviceService: {} }));+vi.mock('@/services/electron/localFileService', () => ({ localFileService: {} }));+vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: object) => unknown) => selector({ agentMap: {} }),+}));+vi.mock('@/store/device', () => ({+ useDeviceList: () => ({+ data: [],+ error: undefined,+ isConfirmed: true,+ isValidating: false,+ mutate: vi.fn(),+ }),+}));+vi.mock('@/store/electron', () => ({+ useElectronStore: (selector: (s: object) => unknown) =>+ selector({ gatewayDeviceInfo: undefined, useFetchGatewayDeviceInfo: () => () => undefined }),+}));+vi.mock('../../hooks/useTopicId', () => ({ useTopicId: () => 'topic-1' }));+vi.mock('../useSandboxNetworkToggle', () => ({ useSandboxNetworkToggle: () => vi.fn() }));+vi.mock('../useTopicAwareTargetSelect', () => ({+ useTopicAwareTargetSelect: () => ({ selectTarget: state.selectTarget, topicDeviceId: undefined }),+}));+vi.mock('../useSandboxModeSelect', () => ({+ useSandboxModeSelect: () => ({+ driveStatus: state.driveStatus,+ persistent: state.persistent,+ toPersistent: state.toPersistent,+ toTemporary: state.toTemporary,+ }),+}));++const SANDBOX = 'heteroAgent.executionTarget.sandbox';+const PERSISTENT = 'heteroAgent.executionTarget.persistentSandbox';++beforeEach(() => {+ state.driveStatus = 'ready';+ state.persistent = false;+ state.openUpsell.mockReset();+ state.selectTarget.mockReset().mockImplementation(async (...args: unknown[]) => {+ const afterApply = args[3] as (() => Promise<void>) | undefined;+ await afterApply?.();+ });+ state.toPersistent.mockReset().mockResolvedValue(undefined);+ state.toTemporary.mockReset().mockResolvedValue(undefined);+});++// T-14161: the persistent sandbox is a row of its own in the execution+// environment, not a folder picked after "Cloud sandbox".+describe('HeteroDeviceSwitcher — persistent sandbox', () => {+ it('offers the persistent sandbox next to the temporary one', () => {+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ expect(screen.getAllByText(SANDBOX).length).toBeGreaterThan(0);+ expect(screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc')).toBeTruthy();+ });++ // The persistent sandbox is where everyday work belongs, so it comes first;+ // the temporary one is described as the place for coding and one-off work.+ it('lists the persistent sandbox above the temporary one', () => {+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ const persistent = screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc');+ const temporary = screen.getByText('heteroAgent.executionTarget.temporarySandboxDesc');++ expect(+ persistent.compareDocumentPosition(temporary) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(screen.queryByText('heteroAgent.executionTarget.sandboxDesc')).toBeNull();+ });++ it('describes the cloud sandbox as before where there is no drive at all', () => {+ state.driveStatus = 'hidden';+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ expect(screen.getByText('heteroAgent.executionTarget.sandboxDesc')).toBeTruthy();+ expect(screen.queryByText('heteroAgent.executionTarget.temporarySandboxDesc')).toBeNull();+ });++ it('names the persistent sandbox on the chip when the conversation keeps its files', () => {+ state.persistent = true;+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ expect(screen.getByTestId('chip').textContent).toContain(PERSISTENT);+ });++ it('switches to the sandbox and onto the drive when the persistent row is picked', async () => {+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ fireEvent.click(screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc'));+ await vi.waitFor(() => expect(state.toPersistent).toHaveBeenCalledTimes(1));++ expect(state.selectTarget.mock.calls[0][0]).toBe('sandbox');+ expect(state.toTemporary).not.toHaveBeenCalled();+ });++ it('switches to the temporary sandbox from the plain row', async () => {+ state.persistent = true;+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ fireEvent.click(screen.getByText('heteroAgent.executionTarget.temporarySandboxDesc'));+ await vi.waitFor(() => expect(state.toTemporary).toHaveBeenCalledTimes(1));++ expect(state.selectTarget.mock.calls[0][0]).toBe('sandbox');+ expect(state.toPersistent).not.toHaveBeenCalled();+ });++ it('shows a plan without a drive the way to one instead', () => {+ state.driveStatus = 'upgrade';+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ fireEvent.click(screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc'));++ expect(screen.getByText('pro')).toBeTruthy();+ expect(state.openUpsell).toHaveBeenCalledTimes(1);+ expect(state.selectTarget).not.toHaveBeenCalled();+ });++ it.each(['hidden', 'loading'] as const)('hides the row while the drive is %s', (driveStatus) => {+ state.driveStatus = driveStatus;+ render(<HeteroDeviceSwitcher agentId="agent-1" />);++ expect(screen.queryByText(PERSISTENT)).toBeNull();+ });+});diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsxnew file mode 100644index 00000000000..47cc4c6919c--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx@@ -0,0 +1,111 @@+import { render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import { describe, expect, it, vi } from 'vitest';++import SandboxDrivePicker from '../SandboxDrivePicker';+import type { SandboxSelection } from '../useSandboxPlacement';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@lobechat/business-const', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ ENABLE_BUSINESS_FEATURES: true,+}));++// Every menu, open: what each layout offers is the question, not how it opens.+vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ Popover: ({ children, content }: { children: ReactNode; content: ReactNode }) => (+ <div>+ {children}+ {content}+ </div>+ ),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => undefined,+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => vi.fn(),+}));+vi.mock('@/features/EnvironmentManager/CreateEnvironmentModal', () => ({+ openCreateEnvironmentModal: vi.fn(),+}));+vi.mock('@/features/WorkingDirectory', () => ({ openSandboxDirectoryModal: vi.fn() }));+vi.mock('@/components/RepositoryAvatar', () => ({ default: () => null }));+vi.mock('@/services/environment', () => ({+ environmentService: { listEnvironments: vi.fn(async () => ({ environments: [] })) },+}));+vi.mock('@/services/projectFile', () => ({ refreshProjectFiles: vi.fn() }));+vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: {+ getInstance: vi.fn(),+ resolveSessionPlacement: vi.fn(async () => ({})),+ },+}));+vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: object) => unknown) => selector({}),+}));+vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: { currentAgentVisibility: () => 'private' },+}));+vi.mock('../SandboxDriveMenu', () => ({+ default: ({ selectedPath }: { selectedPath?: string }) => (+ <div data-testid="drive-folders">{selectedPath}</div>+ ),+}));+vi.mock('../SandboxRepositoryMenu', () => ({+ default: ({ none }: { none?: { active: boolean } }) =>+ none ? <div data-testid="repository-menu">{none.active ? 'none-active' : 'none'}</div> : null,+}));++const renderPicker = (value: SandboxSelection, props: { modeInEnvironmentMenu?: boolean } = {}) =>+ render(<SandboxDrivePicker entitled value={value} onChange={vi.fn()} {...props} />);++// T-14161: the sandbox kind is picked in the execution-environment menu, so+// this menu only asks what is left for that kind.+describe('SandboxDrivePicker', () => {+ // A repository belongs to the temporary sandbox; the persistent one only+ // asks which folder of the drive to keep.+ it('lists only the drive folders on the persistent sandbox', () => {+ renderPicker({ workingDirectory: 'notes' });++ expect(screen.getByTestId('drive-folders').textContent).toBe('notes');+ expect(screen.queryByText('sandboxStorage.ephemeral', { selector: 'div *' })).toBeNull();+ expect(screen.queryByTestId('sandbox-drive-row')).toBeNull();+ expect(screen.queryByTestId('sandbox-repository-row')).toBeNull();+ expect(screen.queryByTestId('repository-menu')).toBeNull();+ });++ // The temporary sandbox's folder is always a fresh empty one: nothing to+ // pick there, only whether a repository is cloned into it.+ it('asks only for a repository on the temporary sandbox', () => {+ renderPicker({});++ expect(screen.queryByTestId('drive-folders')).toBeNull();+ expect(screen.queryByTestId('sandbox-drive-row')).toBeNull();+ expect(screen.queryByTestId('sandbox-repository-row')).toBeNull();+ expect(screen.queryByText('sandboxStorage.ephemeral')).toBeNull();+ expect(screen.getByTestId('repository-menu').textContent).toBe('none-active');+ expect(screen.getByText('sandboxEnvironment.none')).toBeInTheDocument();+ });++ it('marks the picked repository rather than none on the temporary sandbox', () => {+ renderPicker({ environmentId: 'env-1' });++ expect(screen.getByTestId('repository-menu').textContent).toBe('none');+ });++ // A member of a workspace agent whose author fixed the target sees the+ // execution environment read-only; the placement is still theirs to change.+ it('keeps temporary and drive side by side when the environment menu is locked', () => {+ renderPicker({ workingDirectory: 'notes' }, { modeInEnvironmentMenu: false });++ expect(screen.getByTestId('sandbox-drive-row')).toBeInTheDocument();+ expect(screen.getByTestId('sandbox-repository-row')).toBeInTheDocument();+ expect(screen.getByText('sandboxStorage.ephemeral')).toBeInTheDocument();+ });+});diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.tsindex c4a5c0af673..d2f660ea98f 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts@@ -75,29 +75,7 @@ describe('repositorySlug', () => {describe('repositorySelection', () => {const repo = { id: 'env-repo', name: 'lobehub-biz/agent-mail' };- it('starts a repository outside a project in a temporary sandbox', () => {- expect(repositorySelection(repo, { published: false, workspace: true })).toEqual({- environmentId: 'env-repo',- });- });-- // A pick in a project conversation used to drop the project's shared- // checkout and start over in a temporary sandbox.- it("keeps a project conversation in the project's checkout of the repository", () => {- expect(- repositorySelection(repo, { projectId: 'proj_1', published: false, workspace: false }),- ).toEqual({- environmentId: 'env-repo',- workingDirectory: 'projects/proj_1/env-repo',- });- });-- it('puts a private checkout on the personal drive and a published one on the public drive', () => {- expect(- repositorySelection(repo, { projectId: 'proj_1', published: false, workspace: true }),- ).toMatchObject({ drive: 'personal' });- expect(- repositorySelection(repo, { projectId: 'proj_1', published: true, workspace: true }),- ).toMatchObject({ drive: 'public' });+ it('clones a repository into a temporary sandbox', () => {+ expect(repositorySelection(repo)).toEqual({ environmentId: 'env-repo' });});});diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.tsindex e87f108e1c3..223197af8ed 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts@@ -1,4 +1,3 @@-import { projectCheckoutDirectory } from '@lobechat/builtin-tool-cloud-sandbox';import type { EnvironmentConfiguration } from '@lobechat/types';import type { SandboxSelection } from './useSandboxPlacement';@@ -62,25 +61,12 @@ export const environmentChipState = ({};/**- * Where a conversation works once a repository is picked. A repository is only- * cloned into an empty folder, so it never inherits the folder the- * conversation was on: it starts in a temporary sandbox — or, in a project, in- * the project's own checkout of it, which every conversation there shares (the- * run makes the folder when it first needs it). A private checkout stays on the- * member's own drive; the public one is every member's.+ * Where a conversation works once a repository is picked: a fresh temporary+ * sandbox the repository is cloned into. A repository is only cloned into an+ * empty folder, so it never inherits the folder the conversation was on, and+ * it is never checked out on the drive — the persistent sandbox is for keeping+ * a folder of the drive, not a repository.*/-export const repositorySelection = (- environment: { id: string; name: string },- {- projectId,- published,- workspace,- }: { projectId?: string; published: boolean; workspace: boolean },-): SandboxSelection =>- projectId- ? {- ...(workspace && { drive: published ? 'public' : 'personal' }),- environmentId: environment.id,- workingDirectory: projectCheckoutDirectory(projectId, environment.id),- }- : { environmentId: environment.id };+export const repositorySelection = (environment: { id: string }): SandboxSelection => ({+ environmentId: environment.id,+});diff --git a/src/features/ChatInput/ControlBar/temporarySandboxPreference.test.ts b/src/features/ChatInput/ControlBar/temporarySandboxPreference.test.tsnew file mode 100644index 00000000000..df6e989b884--- /dev/null+++ b/src/features/ChatInput/ControlBar/temporarySandboxPreference.test.ts@@ -0,0 +1,74 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import {+ prefersTemporarySandbox,+ setPrefersTemporarySandbox,+ TEMPORARY_SANDBOX_PREFERENCE_KEY,+ usePrefersTemporarySandbox,+} from './temporarySandboxPreference';++const ME = { userId: 'user-1', workspaceId: null };+const ME_WS = { userId: 'user-1', workspaceId: 'ws_1' };++afterEach(() => {+ localStorage.removeItem(TEMPORARY_SANDBOX_PREFERENCE_KEY);+});++describe('temporarySandboxPreference', () => {+ it('is off until the temporary sandbox is picked', () => {+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);++ setPrefersTemporarySandbox(ME, 'agent-1', true);+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(true);++ setPrefersTemporarySandbox(ME, 'agent-1', false);+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);+ });++ it('keeps each workspace and agent apart', () => {+ setPrefersTemporarySandbox(ME_WS, 'agent-1', true);++ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);+ expect(prefersTemporarySandbox(ME_WS, 'agent-2')).toBe(false);+ expect(prefersTemporarySandbox(ME_WS, 'agent-1')).toBe(true);+ });++ it('reads a corrupted store as nothing remembered', () => {+ localStorage.setItem(TEMPORARY_SANDBOX_PREFERENCE_KEY, '[not json');++ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);+ });++ it('re-renders a reader when another component writes', () => {+ const { result } = renderHook(() => usePrefersTemporarySandbox(ME, 'agent-1'));+ expect(result.current).toBe(false);++ act(() => setPrefersTemporarySandbox(ME, 'agent-1', true));+ expect(result.current).toBe(true);+ });++ it('re-renders a reader when another tab writes', () => {+ const { result } = renderHook(() => usePrefersTemporarySandbox(ME, 'agent-1'));+ expect(result.current).toBe(false);++ act(() => {+ // What the browser does for a write made in another tab.+ localStorage.setItem(+ TEMPORARY_SANDBOX_PREFERENCE_KEY,+ JSON.stringify({ 'user-1:personal:agent-1': true }),+ );+ window.dispatchEvent(new StorageEvent('storage', { key: TEMPORARY_SANDBOX_PREFERENCE_KEY }));+ });+ expect(result.current).toBe(true);+ });++ // A shared workspace agent has the same id for every member signing in here.+ it('keeps each signed-in member apart', () => {+ setPrefersTemporarySandbox(ME_WS, 'agent-1', true);++ expect(prefersTemporarySandbox({ userId: 'user-2', workspaceId: 'ws_1' }, 'agent-1')).toBe(+ false,+ );+ });+});diff --git a/src/features/ChatInput/ControlBar/temporarySandboxPreference.ts b/src/features/ChatInput/ControlBar/temporarySandboxPreference.tsnew file mode 100644index 00000000000..adf847c5cb5--- /dev/null+++ b/src/features/ChatInput/ControlBar/temporarySandboxPreference.ts@@ -0,0 +1,98 @@+import { useSyncExternalStore } from 'react';++export const TEMPORARY_SANDBOX_PREFERENCE_KEY = 'lobechat-sandbox-temporary-agents';++/**+ * Which agents the person moved to the temporary cloud sandbox from the+ * execution-environment menu. A plan with a drive otherwise starts every new+ * conversation on a drive folder; picking "Cloud sandbox" over "Persistent+ * sandbox" is a choice about the agent, so it has to outlive the conversation+ * it was made in. Per member and per device, like the folder a conversation+ * starts in — the agent's shared config is every member's.+ */+type Store = Record<string, true>;++/**+ * Whose choice it is. The browser is shared by whoever signs in on it, and a+ * workspace agent has the same id for every member, so the signed-in user is+ * part of the key; the drive is per account, so a workspace and the personal+ * space are kept apart too.+ */+export interface TemporarySandboxScope {+ userId?: string | null;+ workspaceId?: string | null;+}++const keyOf = ({ userId, workspaceId }: TemporarySandboxScope, agentId: string) =>+ `${userId || 'anonymous'}:${workspaceId || 'personal'}:${agentId}`;++const listeners = new Set<() => void>();++const readStore = (): Store => {+ try {+ const raw = localStorage.getItem(TEMPORARY_SANDBOX_PREFERENCE_KEY);+ if (!raw) return {};+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};+ } catch {+ return {};+ }+};++const writeStore = (store: Store) => {+ try {+ localStorage.setItem(TEMPORARY_SANDBOX_PREFERENCE_KEY, JSON.stringify(store));+ } catch {+ // Storage unavailable (private mode, quota): new conversations start on the+ // plan's default, as they did before anything was remembered.+ }+ for (const listener of listeners) listener();+};++// Another tab writing the same key only reaches this one through the browser's+// `storage` event; without it, a tab left open keeps seeding the old choice.+const onStorage = (event: StorageEvent) => {+ if (event.key !== null && event.key !== TEMPORARY_SANDBOX_PREFERENCE_KEY) return;+ for (const listener of listeners) listener();+};++const subscribe = (listener: () => void) => {+ if (listeners.size === 0 && typeof window !== 'undefined')+ window.addEventListener('storage', onStorage);+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && typeof window !== 'undefined')+ window.removeEventListener('storage', onStorage);+ };+};++/** Whether this agent's new conversations start in a temporary sandbox. */+export const prefersTemporarySandbox = (scope: TemporarySandboxScope, agentId: string): boolean =>+ readStore()[keyOf(scope, agentId)] === true;++/** Remember the execution-environment pick: temporary (`true`) or persistent (`false`). */+export const setPrefersTemporarySandbox = (+ scope: TemporarySandboxScope,+ agentId: string,+ temporary: boolean,+): void => {+ const store = readStore();+ const key = keyOf(scope, agentId);+ if (temporary === (store[key] === true)) return;++ if (temporary) store[key] = true;+ else delete store[key];+ writeStore(store);+};++/** The same answer, re-rendering whichever component reads it when any other one writes it. */+export const usePrefersTemporarySandbox = (+ scope: TemporarySandboxScope,+ agentId: string,+): boolean =>+ useSyncExternalStore(+ subscribe,+ () => prefersTemporarySandbox(scope, agentId),+ () => false,+ );diff --git a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.tsnew file mode 100644index 00000000000..56077458285--- /dev/null+++ b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts@@ -0,0 +1,102 @@+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import {+ getPendingSandboxSelection,+ seedPendingSandboxSelection,+ setPendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';++import { useFollowSandboxModePreference } from './useFollowSandboxModePreference';++const AGENT = 'agent-follow';++const SCOPE = `user-1::${AGENT}`;++interface Props {+ agentId?: string;+ enabled?: boolean;+ hasTopic: boolean;+ scopeKey?: string;+ temporary: boolean;+}++const renderFollow = (temporary: boolean, hasTopic = false) =>+ renderHook(+ ({ agentId = AGENT, enabled = true, scopeKey = SCOPE, ...rest }: Props) =>+ useFollowSandboxModePreference(agentId, { enabled, scopeKey, ...rest }),+ { initialProps: { hasTopic, temporary } as Props },+ );++afterEach(() => setPendingSandboxSelection(AGENT));++// T-14161: another tab switching the agent's sandbox reaches this one only+// through the storage event; a conversation not started here follows it.+describe('useFollowSandboxModePreference', () => {+ it('drops the seeded drive default when the agent turns temporary', () => {+ seedPendingSandboxSelection(AGENT, { workingDirectory: '.' });+ const { rerender } = renderFollow(false);++ rerender({ hasTopic: false, temporary: true });++ expect(getPendingSandboxSelection(AGENT)).toBeUndefined();+ });++ it('keeps a folder picked for this conversation', () => {+ setPendingSandboxSelection(AGENT, { workingDirectory: 'notes' });+ const { rerender } = renderFollow(false);++ rerender({ hasTopic: false, temporary: true });++ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'notes' });+ });++ it('drops a bare temporary sandbox when the agent turns persistent', () => {+ setPendingSandboxSelection(AGENT, {});+ const { rerender } = renderFollow(true);++ rerender({ hasTopic: false, temporary: false });++ expect(getPendingSandboxSelection(AGENT)).toBeUndefined();+ });++ it('keeps a repository picked for this conversation', () => {+ setPendingSandboxSelection(AGENT, { environmentId: 'env-1' });+ const { rerender } = renderFollow(true);++ rerender({ hasTopic: false, temporary: false });++ expect(getPendingSandboxSelection(AGENT)).toEqual({ environmentId: 'env-1' });+ });++ it('changes nothing on mount, or for a conversation already started', () => {+ seedPendingSandboxSelection(AGENT, { workingDirectory: '.' });+ renderFollow(true);+ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: '.' });++ const { rerender } = renderFollow(false, true);+ rerender({ hasTopic: true, temporary: true });+ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: '.' });+ });++ // The same composer reused for another agent (or workspace, or user) reads a+ // different preference; that is not this agent's mode changing.+ it('moves the baseline instead of acting when whose preference it is changes', () => {+ setPendingSandboxSelection(AGENT, {});+ const { rerender } = renderFollow(true);++ rerender({ hasTopic: false, scopeKey: 'user-1::other-agent', temporary: false });+ rerender({ hasTopic: false, scopeKey: SCOPE, temporary: true });++ expect(getPendingSandboxSelection(AGENT)).toEqual({});+ });++ it('leaves a member who cannot pick the mode where they are', () => {+ setPendingSandboxSelection(AGENT, {});+ const { rerender } = renderFollow(true);++ rerender({ enabled: false, hasTopic: false, temporary: false });++ expect(getPendingSandboxSelection(AGENT)).toEqual({});+ });+});diff --git a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.tsnew file mode 100644index 00000000000..9304100fcde--- /dev/null+++ b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts@@ -0,0 +1,65 @@+import { useEffect, useRef } from 'react';++import {+ getPendingSandboxSelection,+ isSeededSandboxSelection,+ setPendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';++import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';++/**+ * What a conversation not started yet should drop when the agent's sandbox+ * mode changes under it — typically from another tab, whose pick only reaches+ * this one through the storage event:+ *+ * - now temporary — the drive default seeded here before the change;+ * - now persistent — a bare temporary sandbox, which is all the temporary+ * mode ever leaves behind.+ *+ * Anything else was picked for this conversation (a folder, a repository) and+ * stays. Dropping the slot lets the seeding that follows fill it the new way.+ */+export const staleForMode = (pending: SandboxSelection, temporary: boolean): boolean =>+ temporary+ ? isSeededSandboxSelection(pending) && isPersistentSelection(pending)+ : !isPersistentSelection(pending) && !pending.environmentId;++/**+ * Keep a conversation that has not started yet in step with the agent's+ * sandbox mode. Acts on a change of the preference only — never on mount, and+ * never when what changed is whose preference it is (another agent, workspace+ * or user reusing this composer), which only moves the baseline. A member who+ * cannot pick the mode in the environment menu is not moved by it either. Must+ * run before the default is seeded, so an emptied slot is filled in the same+ * pass.+ */+export const useFollowSandboxModePreference = (+ agentId: string,+ {+ enabled,+ hasTopic,+ scopeKey,+ temporary,+ }: {+ /** Whether the mode is picked in the environment menu for this member. */+ enabled: boolean;+ hasTopic: boolean;+ /** Whose preference `temporary` is: user, workspace and agent. */+ scopeKey: string;+ /** The stored preference itself, not gated by `enabled`. */+ temporary: boolean;+ },+) => {+ const previous = useRef({ scopeKey, temporary });++ useEffect(() => {+ const before = previous.current;+ previous.current = { scopeKey, temporary };+ if (before.scopeKey !== scopeKey || before.temporary === temporary) return;+ if (!enabled || hasTopic) return;++ const pending = getPendingSandboxSelection(agentId);+ if (pending && staleForMode(pending, temporary)) setPendingSandboxSelection(agentId);+ }, [agentId, enabled, hasTopic, scopeKey, temporary]);+};diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.tsnew file mode 100644index 00000000000..9018e4577de--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts@@ -0,0 +1,172 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ prefersTemporarySandbox,+ TEMPORARY_SANDBOX_PREFERENCE_KEY,+} from './temporarySandboxPreference';+import { temporarySelection, useSandboxModeSelect } from './useSandboxModeSelect';+import type { SandboxSelection } from './useSandboxPlacement';++const state = vi.hoisted(() => ({+ driveStatus: 'ready' as 'hidden' | 'loading' | 'ready' | 'upgrade',+ seedPendingSandboxSelection: vi.fn(),+ selection: {} as Record<string, unknown>,+ setSelection: vi.fn(),+ topicId: undefined as string | undefined,+ workspaceId: null as string | null,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => state.workspaceId,+}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: object) => unknown) => selector({ user: { id: 'user-1' } }),+}));+vi.mock('@/store/chat/pendingSandboxSelection', () => ({+ seedPendingSandboxSelection: state.seedPendingSandboxSelection,+}));+vi.mock('./useSandboxStorageAccess', () => ({+ useSandboxDriveStatus: () => state.driveStatus,+}));+vi.mock('./useSandboxPlacement', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useSandboxPlacement: () => ({+ selection: state.selection,+ setSelection: state.setSelection,+ topicId: state.topicId,+ }),+}));++const ME = { userId: 'user-1', workspaceId: null };++const renderMode = () =>+ renderHook(() =>+ useSandboxModeSelect('agent-1', { enabled: true, topicId: state.topicId ?? null }),+ );++beforeEach(() => {+ localStorage.removeItem(TEMPORARY_SANDBOX_PREFERENCE_KEY);+ state.driveStatus = 'ready';+ state.selection = {};+ state.topicId = undefined;+ state.workspaceId = null;+ state.seedPendingSandboxSelection.mockReset();+ state.setSelection.mockReset().mockResolvedValue(undefined);+});++describe('temporarySelection', () => {+ it('drops the folder and keeps the repository it starts from', () => {+ expect(temporarySelection({ workingDirectory: 'notes' })).toEqual({});+ expect(+ temporarySelection({ environmentId: 'env-1', workingDirectory: '.lobe/projects/p/env-1' }),+ ).toEqual({ environmentId: 'env-1' });+ });+});++describe('useSandboxModeSelect', () => {+ it('reads a drive folder as the persistent sandbox, only with a drive', () => {+ state.selection = { workingDirectory: 'notes' };+ expect(renderMode().result.current.persistent).toBe(true);++ state.driveStatus = 'upgrade';+ expect(renderMode().result.current.persistent).toBe(false);++ state.driveStatus = 'ready';+ state.selection = {};+ expect(renderMode().result.current.persistent).toBe(false);+ });++ it('moves an open conversation off the drive and remembers the pick', async () => {+ state.topicId = 'topic-1';+ state.selection = { workingDirectory: 'notes' };++ const { result } = renderMode();+ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({});+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(true);+ });++ it('puts an open conversation on the default drive folder', async () => {+ state.topicId = 'topic-1';+ state.workspaceId = 'ws_1';+ localStorage.setItem(+ TEMPORARY_SANDBOX_PREFERENCE_KEY,+ JSON.stringify({ 'user-1:ws_1:agent-1': true }),+ );++ const { result } = renderMode();+ await act(() => result.current.toPersistent());++ expect(state.setSelection).toHaveBeenCalledWith({ drive: 'personal', workingDirectory: '.' });+ expect(prefersTemporarySandbox({ ...ME, workspaceId: 'ws_1' }, 'agent-1')).toBe(false);+ });++ it('keeps the folder a conversation already works in', async () => {+ state.topicId = 'topic-1';+ state.selection = { workingDirectory: 'notes' } satisfies SandboxSelection;++ const { result } = renderMode();+ await act(() => result.current.toPersistent());++ expect(state.setSelection).not.toHaveBeenCalled();+ });++ // Seeded rather than picked: a project conversation still takes its checkout.+ it('gives a conversation not started yet the default as a default', async () => {+ const { result } = renderMode();+ await act(() => result.current.toPersistent());++ expect(state.setSelection).not.toHaveBeenCalled();+ expect(state.seedPendingSandboxSelection).toHaveBeenCalledWith('agent-1', {+ workingDirectory: '.',+ });+ });++ it('remembers nothing without a drive service', async () => {+ state.driveStatus = 'hidden';++ const { result } = renderMode();+ await act(() => result.current.toTemporary());++ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);+ expect(state.setSelection).not.toHaveBeenCalled();+ });++ // A failed move leaves the conversation where it was, so new ones must not+ // start in the other mode either.+ it('keeps the preference when moving the conversation fails', async () => {+ state.topicId = 'topic-1';+ state.selection = { workingDirectory: 'notes' };+ state.setSelection.mockRejectedValue(new Error('offline'));++ const { result } = renderMode();+ await expect(act(() => result.current.toTemporary())).rejects.toThrow('offline');+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);++ state.selection = {};+ localStorage.setItem(+ TEMPORARY_SANDBOX_PREFERENCE_KEY,+ JSON.stringify({ 'user-1:personal:agent-1': true }),+ );+ const { result: again } = renderMode();+ await expect(act(() => again.current.toPersistent())).rejects.toThrow('offline');+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(true);+ });++ // Not yet known is not "no drive": the pick still has to take the+ // conversation off the drive, or it flips back once the answer arrives.+ it('moves the conversation off the drive while the entitlement loads', async () => {+ state.driveStatus = 'loading';+ state.topicId = 'topic-1';+ state.selection = { workingDirectory: 'notes' };++ const { result } = renderMode();+ expect(result.current.persistent).toBe(true);+ await act(() => result.current.toTemporary());++ expect(state.setSelection).toHaveBeenCalledWith({});+ expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(true);+ });+});diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.tsnew file mode 100644index 00000000000..f8f59895512--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts@@ -0,0 +1,80 @@+import { useCallback } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { seedPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';+import { setPrefersTemporarySandbox } from './temporarySandboxPreference';+import {+ isPersistentSelection,+ type SandboxSelection,+ useSandboxPlacement,+} from './useSandboxPlacement';+import { useSandboxDriveStatus } from './useSandboxStorageAccess';++/**+ * Where a conversation leaving the drive works: the temporary sandbox, still+ * initialized from the repository it was on. A repository checkout only lands+ * in an empty folder, which a fresh temporary sandbox always is.+ */+export const temporarySelection = (selection: SandboxSelection): SandboxSelection =>+ selection.environmentId ? { environmentId: selection.environmentId } : {};++/**+ * The two cloud-sandbox rows of the execution-environment menu. Both run on the+ * `sandbox` target; what tells them apart is whether the conversation keeps its+ * files on the drive, so the rows read and write the same selection the+ * working-directory chip does:+ *+ * - **Cloud sandbox** — temporary. The conversation leaves its drive folder,+ * and the agent's new conversations stop starting on one.+ * - **Persistent sandbox** — the drive. A conversation not on it yet starts at+ * the plan's default folder, and the working-directory chip then lists the+ * drive's folders directly.+ *+ * Only offered with a plan that includes a drive (`driveStatus: 'ready'`); an+ * account without one is shown the way to a plan instead.+ */+export const useSandboxModeSelect = (+ agentId: string,+ { enabled, topicId }: { enabled: boolean; topicId: string | null },+) => {+ const workspaceId = useActiveWorkspaceId();+ const userId = useUserStore(userProfileSelectors.userId);+ const driveStatus = useSandboxDriveStatus(enabled);+ const { selection, setSelection, topicId: scopeTopicId } = useSandboxPlacement(agentId, topicId);+ const onDrive = isPersistentSelection(selection);++ const toTemporary = useCallback(async () => {+ // Without a drive there is only one sandbox, and nothing to remember.+ if (driveStatus === 'hidden') return;++ // Remembered only once the conversation has moved: a failed write leaves+ // it where it was, and new conversations must not start elsewhere.+ if (onDrive) await setSelection(temporarySelection(selection));+ setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);+ }, [agentId, driveStatus, onDrive, selection, setSelection, userId, workspaceId]);++ const toPersistent = useCallback(async () => {+ if (!onDrive) {+ const next = resolveDefaultSandboxSelection(workspaceId);+ // A conversation not started yet gets the default as a default, not as a+ // pick: a project conversation is then still given its repository checkout.+ if (scopeTopicId) await setSelection(next);+ else seedPendingSandboxSelection(agentId, next);+ }+ // After the move, as above: a failed write keeps the old preference too.+ setPrefersTemporarySandbox({ userId, workspaceId }, agentId, false);+ }, [agentId, onDrive, scopeTopicId, setSelection, userId, workspaceId]);++ return {+ driveStatus,+ // While the entitlement loads, the placement the conversation already has+ // is still what it runs on — said as such rather than as temporary.+ persistent: (driveStatus === 'ready' || driveStatus === 'loading') && onDrive,+ toPersistent,+ toTemporary,+ };+};diff --git a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.tsindex 5aa07d78129..5ed412a615d 100644--- a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts@@ -83,3 +83,20 @@ export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessRestatus: data.entitled ? 'ready' : 'upgrade',};};++/**+ * Whether the plan includes a drive, for the execution-environment menu: asked+ * whenever the agent could run in the cloud sandbox, not only once it does, so+ * the persistent sandbox can be offered before it is picked.+ */+export const useSandboxDriveStatus = (enabled: boolean): SandboxStorageAccess | 'loading' => {+ const shouldAsk = ENABLE_BUSINESS_FEATURES && enabled;+ sandboxActions.useFetchEntitlement(shouldAsk, { revalidateOnFocus: false });+ const data = useSandboxStore(sandboxSelectors.entitlement);++ if (!shouldAsk) return 'hidden';+ // Not yet known is not "no drive": a pick made meanwhile must still move the+ // conversation off the drive it is on.+ if (!data) return 'loading';+ return data.entitled ? 'ready' : 'upgrade';+};diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.tsindex e77af228259..525c5e26e44 100644--- a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts@@ -178,4 +178,39 @@ describe('useTopicAwareTargetSelect', () => {boundDeviceId: 'stable-this-desktop',});});++ // T-14161: the persistent-sandbox row moves the conversation onto the drive+ // only once the target is really switched.+ describe('afterApply', () => {+ it('runs once the target is saved', async () => {+ const afterApply = vi.fn(async () => {});+ const { result } = renderSelect(null);++ await act(() => result.current.selectTarget('sandbox', undefined, undefined, afterApply));++ expect(afterApply).toHaveBeenCalledTimes(1);+ });++ it('does not run when the target was not saved', async () => {+ state.selectExecutionTarget.mockResolvedValue(false);+ const afterApply = vi.fn(async () => {});+ const { result } = renderSelect(null);++ await act(() => result.current.selectTarget('sandbox', undefined, undefined, afterApply));++ expect(afterApply).not.toHaveBeenCalled();+ });++ it('waits for a topic on another machine to be moved, and not before', async () => {+ const afterApply = vi.fn(async () => {});+ const { result } = renderSelect('pane-topic');++ await act(() => result.current.selectTarget('sandbox', undefined, undefined, afterApply));+ // Asked first; a cancelled move changes nothing.+ expect(afterApply).not.toHaveBeenCalled();++ await act(() => state.confirmModal.mock.calls[0][0].onOk());+ expect(afterApply).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.tsindex abf69cc6073..ef659aaa60d 100644--- a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts@@ -98,7 +98,14 @@ export const useTopicAwareTargetSelect = ({const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);const selectTarget = useCallback(- async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {+ async (+ target: DeviceExecutionTarget,+ deviceId?: string,+ localSandbox?: boolean,+ // Runs once the target is saved — and, for a topic on another machine,+ // only once the move is confirmed — so a cancelled switch changes nothing.+ afterApply?: () => Promise<void>,+ ) => {const apply = async () => {if (localSandbox) await ensureSandboxWorkingDirectory();return selectExecutionTarget(target, deviceId, { localSandbox });@@ -111,6 +118,7 @@ export const useTopicAwareTargetSelect = ({const machineKnown = target !== 'local' || !!currentDeviceId;if (!topicId || !topicDeviceId || !machineKnown || nextMachineId === topicDeviceId) {const saved = await apply();+ if (saved) await afterApply?.();// A topic whose cwd never recorded its machine: this pick is the user// naming it, so pin it — nothing on another machine is left behind.// Only once the target saved, or topic and agent would disagree; and@@ -158,6 +166,7 @@ export const useTopicAwareTargetSelect = ({});// A refused/failed target save already toasted inside the hook.if (result === 'topic-not-saved') toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ if (result === 'moved') await afterApply?.();},title: t('heteroAgent.executionTarget.switchTopic.title'),});diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.tsindex be117cf0501..78198a71410 100644--- a/src/store/chat/pendingSandboxSelection.ts+++ b/src/store/chat/pendingSandboxSelection.ts@@ -66,6 +66,10 @@ export const setPendingSandboxSelection = (agentId: string, selection?: SandboxS*/const seeded = new WeakSet<SandboxSelection>();+/** Whether a selection is the composer's default rather than anyone's pick. */+export const isSeededSandboxSelection = (selection: SandboxSelection): boolean =>+ seeded.has(selection);+/** Fill an agent's empty slot with the default placement, marked as not chosen by anyone. */export const seedPendingSandboxSelection = (agentId: string, selection: SandboxSelection): void => {seeded.add(selection);