Skip to content

🤯 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.

✨ feat(sandbox): one cloud sandbox with drive and environment options (#23732)

Rdmclin2e2c70b2e4ea9
diff --git a/apps/server/src/services/sandbox/__tests__/session.test.ts b/apps/server/src/services/sandbox/__tests__/session.test.ts
index 345f02f9813..c84677959c8 100644
--- a/apps/server/src/services/sandbox/__tests__/session.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts
@@ -719,6 +719,56 @@ describe('resolveSandboxSessionConfig', () => {
});
});
+ // T-14791: a folder and an environment can now be picked together, so a
+ // private environment could otherwise be checked out where every member
+ // of the workspace can browse it.
+ it("keeps a private environment out of a folder on the workspace's public drive", async () => {
+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);
+ mocks.driveFolderExists.mockResolvedValue(true);
+ mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });
+ findById.mockResolvedValue({
+ metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'team' },
+ });
+
+ const config = await resolve({ workspaceId: 'ws-1' });
+
+ expect(config).toMatchObject({ cwd: 'team', drive: 'public', mode: 'drive' });
+ expect(config).not.toHaveProperty('initialization');
+ });
+
+ it("applies a private environment in a folder on the member's personal drive", async () => {
+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);
+ mocks.driveFolderExists.mockResolvedValue(true);
+ mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'private' });
+ findById.mockResolvedValue({
+ metadata: {
+ sandboxDrive: 'personal',
+ sandboxEnvironmentId: 'env-1',
+ sandboxWorkingDirectory: 'mine',
+ },
+ });
+
+ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({
+ drive: 'personal',
+ initialization: { environmentId: 'env-1' },
+ mode: 'drive',
+ });
+ });
+
+ it('applies a published environment in a folder on the public drive', async () => {
+ resolveSandboxStorageClaim.mockResolvedValue(CLAIM);
+ mocks.driveFolderExists.mockResolvedValue(true);
+ mocks.findEnvironmentById.mockResolvedValue({ ...environment, visibility: 'public' });
+ findById.mockResolvedValue({
+ metadata: { sandboxEnvironmentId: 'env-1', sandboxWorkingDirectory: 'team' },
+ });
+
+ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({
+ drive: 'public',
+ initialization: { environmentId: 'env-1' },
+ });
+ });
+
it('runs without one when the environment is no longer readable', async () => {
resolveSandboxStorageClaim.mockResolvedValue(null);
mocks.findEnvironmentById.mockResolvedValue(undefined);
diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.ts
index 1222f43a314..59a8f4ce16b 100644
--- a/apps/server/src/services/sandbox/session.ts
+++ b/apps/server/src/services/sandbox/session.ts
@@ -398,14 +398,16 @@ const resolvePlacement = async ({
* private one), or one that asks for nothing.
*/
const resolveInitialization = async ({
+ placement,
serverDB,
topicId,
userId,
workspaceId,
}: Required<Pick<SandboxSessionConfigInput, 'serverDB' | 'topicId'>> &
- Pick<SandboxSessionConfigInput, 'userId' | 'workspaceId'>): Promise<
- SandboxInitialization | undefined
-> => {
+ Pick<SandboxSessionConfigInput, 'userId' | 'workspaceId'> & {
+ /** Where the run works, as {@link resolvePlacement} decided. */
+ placement: Pick<SandboxSessionConfig, 'drive' | 'mode'>;
+ }): Promise<SandboxInitialization | undefined> => {
try {
const topic = await new TopicModel(serverDB, userId, workspaceId ?? undefined).findById(
topicId,
@@ -443,6 +445,23 @@ const resolveInitialization = async ({
}
}
+ // Every member can browse the workspace's public drive, so a private
+ // environment's checkout and setup output must not land in a folder there:
+ // it is applied on a personal drive or in a temporary sandbox only.
+ if (
+ workspaceId &&
+ placement.mode === 'drive' &&
+ placement.drive === 'public' &&
+ environment.visibility !== 'public'
+ ) {
+ log(
+ 'Not applying private environment %s in a public-drive folder on topic %s',
+ environmentId,
+ topicId,
+ );
+ return undefined;
+ }
+
const initialization = toSandboxInitialization(environment);
if (!initialization || initialization.sources.length === 0) return initialization;
@@ -484,7 +503,12 @@ export const resolveSandboxSessionConfig = async (
const { serverDB, topicId } = input;
if (!serverDB || !topicId || config.mode === 'persistent') return config;
- const initialization = await resolveInitialization({ ...input, serverDB, topicId });
+ const initialization = await resolveInitialization({
+ ...input,
+ placement: config,
+ serverDB,
+ topicId,
+ });
return initialization ? { ...config, initialization } : config;
};
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index d55420250dd..bcd2898edb3 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "تعذر إعادة الاتصال بهذا الجهاز. تأكد من تشغيل تطبيق سطح المكتب، ثم حاول مرة أخرى.",
"heteroAgent.executionTarget.sandbox": "بيئة سحابية مؤقتة",
"heteroAgent.executionTarget.sandboxDesc": "تشغيل في بيئة سحابية مؤقتة",
- "heteroAgent.executionTarget.sandboxGroup": "بيئات الحماية",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} يعمل حاليًا فقط على جهاز محلي أو متصل",
"heteroAgent.executionTarget.switchProjectTopic.content": "سيتم تشغيل هذا الموضوع في دليل المشروع \"{{directory}}\" على {{device}}. تبدأ دورته التالية بجلسة جديدة هناك.",
"heteroAgent.executionTarget.switchTopic.content": "تم تشغيل هذا الموضوع على {{name}}، حيث يتم الاحتفاظ بدليل العمل وجلسة الوكيل. بعد التبديل، يبدأ دوره التالي جلسة جديدة في البيئة الجديدة. ستستخدم المواضيع الجديدة هذا الاختيار أيضًا.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "مجلد على محرك الأقراص الخاص بك · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "البيئات",
- "sandboxDrive.pickerTitle": "دليل العمل",
"sandboxDrive.root": "جذر محرك الأقراص",
"sandboxDrive.upsell": "احتفظ بالملفات على محرك الأقراص",
"sandboxEnvironment.loadFailed": "تعذر تحميل البيئات",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "لم يتم تجهيز هذه البيئة",
"sandboxStorage.defaultCopy": "الافتراضي",
"sandboxStorage.environmentsUnavailable": "تعذر تحميل البيئات",
- "sandboxStorage.ephemeral": "دليل عمل مؤقت",
"sandboxStorage.ephemeralDesc": "يتم تنظيفه عند إعادة تدوير الصندوق",
"sandboxStorage.instanceBusy": "{{name}} يعمل في محادثة أخرى. يحتفظ هذا به، ويلتقطه عند انتهاء التشغيل.",
"sandboxStorage.kind.code": "كود",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 849dadaec06..14f2b095a3b 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Неуспешно свързване на това устройство. Уверете се, че настолното приложение работи, след това опитайте отново.",
"heteroAgent.executionTarget.sandbox": "Облачен пясъчник",
"heteroAgent.executionTarget.sandboxDesc": "Изпълнява се в временен облачен пясъчник",
- "heteroAgent.executionTarget.sandboxGroup": "Пясъчници",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} в момента работи само на локално или свързано устройство",
"heteroAgent.executionTarget.switchProjectTopic.content": "Тази тема ще се изпълнява в директорията на проекта \"{{directory}}\" на {{device}}. Следващият й ход започва нова сесия там.",
"heteroAgent.executionTarget.switchTopic.content": "Тази тема се изпълнява на {{name}}, където се съхраняват нейната работна директория и сесията на агента. След превключване, следващият ѝ ход започва нова сесия в новата среда. Новите теми също ще използват този избор.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "Папка на вашия диск · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Среда",
- "sandboxDrive.pickerTitle": "Работна директория",
"sandboxDrive.root": "Корен на диска",
"sandboxDrive.upsell": "Запазете файлове на диск",
"sandboxEnvironment.loadFailed": "Не можа да се заредят среди",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "Тази среда не можа да бъде подготвена",
"sandboxStorage.defaultCopy": "По подразбиране",
"sandboxStorage.environmentsUnavailable": "Средите не можаха да бъдат заредени",
- "sandboxStorage.ephemeral": "Временна работна директория",
"sandboxStorage.ephemeralDesc": "Изчиства се, когато пясъчникът се рециклира",
"sandboxStorage.instanceBusy": "{{name}} работи в друг разговор. Този го запазва и го поема, когато това изпълнение приключи.",
"sandboxStorage.kind.code": "Код",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 119d57c449a..7aade5d5e4c 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Dieses Gerät konnte nicht erneut verbunden werden. Stellen Sie sicher, dass die Desktop-App läuft, und versuchen Sie es dann erneut.",
"heteroAgent.executionTarget.sandbox": "Cloud-Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "In einer temporären Cloud-Sandbox ausführen",
- "heteroAgent.executionTarget.sandboxGroup": "Sandboxes",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} läuft derzeit nur auf einem lokalen oder verbundenen Gerät",
"heteroAgent.executionTarget.switchProjectTopic.content": "Dieses Thema wird im Projektverzeichnis \"{{directory}}\" auf {{device}} ausgeführt. Der nächste Durchlauf startet dort eine neue Sitzung.",
"heteroAgent.executionTarget.switchTopic.content": "Dieses Thema wurde auf {{name}} ausgeführt, wo sein Arbeitsverzeichnis und die Agentensitzung gespeichert sind. Nach dem Wechsel beginnt der nächste Zug eine neue Sitzung in der neuen Umgebung. Neue Themen verwenden ebenfalls diese Wahl.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Ordner auf Ihrem Laufwerk · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Umgebungen",
- "sandboxDrive.pickerTitle": "Arbeitsverzeichnis",
"sandboxDrive.root": "Laufwerksstamm",
"sandboxDrive.upsell": "Dateien auf einem Laufwerk speichern",
"sandboxEnvironment.loadFailed": "Konnte Umgebungen nicht laden",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Diese Umgebung konnte nicht vorbereitet werden",
"sandboxStorage.defaultCopy": "Standard",
"sandboxStorage.environmentsUnavailable": "Umgebungen konnten nicht geladen werden",
- "sandboxStorage.ephemeral": "Temporäres Arbeitsverzeichnis",
"sandboxStorage.ephemeralDesc": "Wird bereinigt, wenn die Sandbox recycelt wird",
"sandboxStorage.instanceBusy": "{{name}} wird in einem anderen Gespräch ausgeführt. Dieses behält es und übernimmt es, wenn dieser Lauf endet.",
"sandboxStorage.kind.code": "Code",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 2c0106bd59f..ab68f7527b2 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1634,8 +1634,6 @@
"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.",
@@ -1643,14 +1641,11 @@
"heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.",
"heteroAgent.executionTarget.sandbox": "Cloud Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Runs in the cloud, no machine needed",
- "heteroAgent.executionTarget.sandboxGroup": "Sandboxes",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",
"heteroAgent.executionTarget.switchProjectTopic.content": "This topic will run in the project directory \"{{directory}}\" on {{device}}. Its next turn starts a fresh session there.",
"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.temporarySandbox": "Temporary Sandbox",
- "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",
@@ -2292,14 +2287,11 @@
"sandboxDrive.fallbackChip.instanceUnavailable": "Environment unavailable",
"sandboxDrive.fallbackChip.rootNotAllowed": "Pick a folder",
"sandboxDrive.manageEnvironments": "Settings",
- "sandboxDrive.openStorage": "Sandbox Storage",
- "sandboxDrive.pickerInfoTooltip": "A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. An environment is set up before the first command.",
- "sandboxDrive.pickerTitle": "Work location",
"sandboxDrive.root": "Root",
+ "sandboxDrive.setupSkipped": "This folder already has files, so the environment won't be set up in it.",
"sandboxDrive.title": "Cloud drive",
"sandboxEnvironment.add": "New environment",
"sandboxEnvironment.empty": "No environments yet. Create one to get started.",
- "sandboxEnvironment.hint": "Its repositories are cloned, setup runs and its variables are set before the first command.",
"sandboxEnvironment.loadFailed": "Couldn't load environments",
"sandboxEnvironment.loading": "Loading environment…",
"sandboxEnvironment.missing": "Environment unavailable",
@@ -2308,6 +2300,10 @@
"sandboxEnvironment.retry": "Retry",
"sandboxEnvironment.saveFailed": "Could not change the environment. Try again.",
"sandboxEnvironment.title": "Environment",
+ "sandboxOptions.environment": "Environment",
+ "sandboxOptions.folder": "Folder",
+ "sandboxOptions.storage": "Storage",
+ "sandboxOptions.temporary": "Temporary",
"sandboxStorage.allCopiesBusy": "Every copy is in use",
"sandboxStorage.buildFailed": "Not built",
"sandboxStorage.building": "Building",
@@ -2317,7 +2313,6 @@
"sandboxStorage.createCopyFailed": "This environment could not be prepared",
"sandboxStorage.defaultCopy": "Default",
"sandboxStorage.environmentsUnavailable": "Environments could not be loaded",
- "sandboxStorage.ephemeral": "Temporary working directory",
"sandboxStorage.instanceBusy": "{{name}} is running in another conversation. This one keeps it, and picks it up when that run ends.",
"sandboxStorage.kind.code": "Code",
"sandboxStorage.kind.files": "Files",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index ea8f9054b47..36e7ff30f9d 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "No se pudo reconectar este dispositivo. Asegúrate de que la aplicación de escritorio esté funcionando, luego inténtalo de nuevo.",
"heteroAgent.executionTarget.sandbox": "Sandbox en la nube",
"heteroAgent.executionTarget.sandboxDesc": "Ejecutar en un sandbox efímero en la nube",
- "heteroAgent.executionTarget.sandboxGroup": "Sandboxes",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} actualmente solo se ejecuta en un dispositivo local o conectado",
"heteroAgent.executionTarget.switchProjectTopic.content": "Este tema se ejecutará en el directorio del proyecto \"{{directory}}\" en {{device}}. Su próximo turno comenzará una nueva sesión allí.",
"heteroAgent.executionTarget.switchTopic.content": "Este tema se ha estado ejecutando en {{name}}, donde se mantienen su directorio de trabajo y sesión del agente. Después de cambiar, su próximo turno comienza una nueva sesión en el nuevo entorno. Los nuevos temas también usarán esta elección.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Carpeta en tu unidad · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Entornos",
- "sandboxDrive.pickerTitle": "Directorio de trabajo",
"sandboxDrive.root": "Raíz de la unidad",
"sandboxDrive.upsell": "Mantén archivos en una unidad",
"sandboxEnvironment.loadFailed": "No se pudieron cargar los entornos",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Este entorno no pudo ser preparado",
"sandboxStorage.defaultCopy": "Predeterminado",
"sandboxStorage.environmentsUnavailable": "No se pudieron cargar los entornos",
- "sandboxStorage.ephemeral": "Directorio de trabajo temporal",
"sandboxStorage.ephemeralDesc": "Se limpia cuando se recicla el sandbox",
"sandboxStorage.instanceBusy": "{{name}} está en ejecución en otra conversación. Esta lo mantiene y lo retoma cuando esa ejecución termina.",
"sandboxStorage.kind.code": "Código",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 66ccd296fd6..f5b4e10949d 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "اتصال مجدد این دستگاه امکان‌پذیر نبود. مطمئن شوید که برنامه دسکتاپ در حال اجرا است، سپس دوباره تلاش کنید.",
"heteroAgent.executionTarget.sandbox": "محیط آزمایشی ابری",
"heteroAgent.executionTarget.sandboxDesc": "در یک محیط آزمایشی ابری موقت اجرا شود",
- "heteroAgent.executionTarget.sandboxGroup": "سندباکس‌ها",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} در حال حاضر فقط روی یک دستگاه محلی یا متصل اجرا می‌شود",
"heteroAgent.executionTarget.switchProjectTopic.content": "این موضوع در دایرکتوری پروژه \"{{directory}}\" روی {{device}} اجرا خواهد شد. نوبت بعدی آن یک جلسه جدید را در آنجا آغاز می‌کند.",
"heteroAgent.executionTarget.switchTopic.content": "این موضوع در حال اجرا روی {{name}} است، جایی که دایرکتوری کاری و جلسه اجنت آن نگهداری می‌شود. پس از تغییر، نوبت بعدی آن یک جلسه جدید در محیط جدید شروع می‌کند. موضوعات جدید نیز از این انتخاب استفاده خواهند کرد.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "پوشه در درایو شما · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "محیط‌ها",
- "sandboxDrive.pickerTitle": "دایرکتوری کاری",
"sandboxDrive.root": "ریشه درایو",
"sandboxDrive.upsell": "فایل‌ها را در یک درایو نگه دارید",
"sandboxEnvironment.loadFailed": "محیط‌ها بارگذاری نشدند",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "این محیط نمی‌تواند آماده شود",
"sandboxStorage.defaultCopy": "پیش‌فرض",
"sandboxStorage.environmentsUnavailable": "محیط‌ها بارگذاری نشدند",
- "sandboxStorage.ephemeral": "دایرکتوری کاری موقت",
"sandboxStorage.ephemeralDesc": "هنگام بازیافت سندباکس پاک می‌شود",
"sandboxStorage.instanceBusy": "{{name}} در حال اجرا در مکالمه دیگری است. این یکی آن را نگه می‌دارد و وقتی آن اجرا به پایان رسید، آن را انتخاب می‌کند.",
"sandboxStorage.kind.code": "کد",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index ebf7ec629f6..1206f42a1ba 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Impossible de reconnecter cet appareil. Assurez-vous que l'application de bureau est en cours d'exécution, puis réessayez.",
"heteroAgent.executionTarget.sandbox": "Bac à sable cloud",
"heteroAgent.executionTarget.sandboxDesc": "Exécuter dans un bac à sable cloud éphémère",
- "heteroAgent.executionTarget.sandboxGroup": "Bacs à sable",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} fonctionne actuellement uniquement sur un appareil local ou connecté",
"heteroAgent.executionTarget.switchProjectTopic.content": "Ce sujet s'exécutera dans le répertoire du projet \"{{directory}}\" sur {{device}}. Son prochain tour commencera une nouvelle session là-bas.",
"heteroAgent.executionTarget.switchTopic.content": "Ce sujet s'exécute sur {{name}}, où son répertoire de travail et sa session d'agent sont conservés. Après le changement, son prochain tour démarre une nouvelle session dans le nouvel environnement. Les nouveaux sujets utiliseront également ce choix.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "Dossier sur votre disque · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Environnements",
- "sandboxDrive.pickerTitle": "Répertoire de travail",
"sandboxDrive.root": "Racine du disque",
"sandboxDrive.upsell": "Conserver les fichiers sur un disque",
"sandboxEnvironment.loadFailed": "Impossible de charger les environnements",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "Cet environnement n'a pas pu être préparé",
"sandboxStorage.defaultCopy": "Par défaut",
"sandboxStorage.environmentsUnavailable": "Les environnements n'ont pas pu être chargés",
- "sandboxStorage.ephemeral": "Répertoire de travail temporaire",
"sandboxStorage.ephemeralDesc": "Nettoyé lorsque le bac à sable est recyclé",
"sandboxStorage.instanceBusy": "{{name}} est en cours d'exécution dans une autre conversation. Celle-ci le conserve et le reprend lorsque cette exécution se termine.",
"sandboxStorage.kind.code": "Code",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index e3a8da977ef..413b79fdf07 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Impossibile riconnettere questo dispositivo. Assicurati che l'app desktop sia in esecuzione, quindi riprova.",
"heteroAgent.executionTarget.sandbox": "Sandbox cloud",
"heteroAgent.executionTarget.sandboxDesc": "Esegui in un sandbox cloud temporaneo",
- "heteroAgent.executionTarget.sandboxGroup": "Sandbox",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} attualmente funziona solo su un dispositivo locale o connesso",
"heteroAgent.executionTarget.switchProjectTopic.content": "Questo argomento verrà eseguito nella directory del progetto \"{{directory}}\" su {{device}}. Il prossimo turno inizierà una nuova sessione lì.",
"heteroAgent.executionTarget.switchTopic.content": "Questo argomento è stato eseguito su {{name}}, dove sono conservati la directory di lavoro e la sessione dell'agente. Dopo il cambio, il prossimo turno inizierà una nuova sessione nel nuovo ambiente. Anche i nuovi argomenti utilizzeranno questa scelta.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "Cartella sul tuo drive · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Ambienti",
- "sandboxDrive.pickerTitle": "Directory di lavoro",
"sandboxDrive.root": "Radice del drive",
"sandboxDrive.upsell": "Mantieni i file su un drive",
"sandboxEnvironment.loadFailed": "Impossibile caricare gli ambienti",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "Questo ambiente non può essere preparato",
"sandboxStorage.defaultCopy": "Predefinito",
"sandboxStorage.environmentsUnavailable": "Impossibile caricare gli ambienti",
- "sandboxStorage.ephemeral": "Directory di lavoro temporanea",
"sandboxStorage.ephemeralDesc": "Pulita quando il sandbox viene riciclato",
"sandboxStorage.instanceBusy": "{{name}} è in esecuzione in un'altra conversazione. Questa la mantiene e la riprende quando quell'esecuzione termina.",
"sandboxStorage.kind.code": "Codice",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 6c7f415830f..354904626d6 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "このデバイスに再接続できませんでした。デスクトップアプリが実行中であることを確認し、再試行してください。",
"heteroAgent.executionTarget.sandbox": "クラウドサンドボックス",
"heteroAgent.executionTarget.sandboxDesc": "一時的なクラウドサンドボックスで実行",
- "heteroAgent.executionTarget.sandboxGroup": "サンドボックス",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} は現在、ローカルまたは接続されたデバイスでのみ動作します",
"heteroAgent.executionTarget.switchProjectTopic.content": "このトピックはプロジェクトディレクトリ「{{directory}}」で{{device}}上で実行されます。次のターンではそこで新しいセッションが開始されます。",
"heteroAgent.executionTarget.switchTopic.content": "このトピックは {{name}} で実行されており、その作業ディレクトリとエージェントセッションが保持されています。切り替え後、次のターンは新しい環境で新しいセッションを開始します。新しいトピックもこの選択を使用します。",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "ドライブ上のフォルダ · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "環境",
- "sandboxDrive.pickerTitle": "作業ディレクトリ",
"sandboxDrive.root": "ドライブのルート",
"sandboxDrive.upsell": "ファイルをドライブに保持",
"sandboxEnvironment.loadFailed": "環境を読み込めませんでした",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "この環境を準備できませんでした",
"sandboxStorage.defaultCopy": "デフォルト",
"sandboxStorage.environmentsUnavailable": "環境を読み込めませんでした",
- "sandboxStorage.ephemeral": "一時的な作業ディレクトリ",
"sandboxStorage.ephemeralDesc": "サンドボックスが再利用されるとクリーンアップされます",
"sandboxStorage.instanceBusy": "{{name}} は別の会話で実行中です。この会話はそれを保持し、その実行が終了すると引き継ぎます。",
"sandboxStorage.kind.code": "コード",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index bcd7c6e3346..0113fd77f46 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "이 장치를 다시 연결할 수 없습니다. 데스크톱 앱이 실행 중인지 확인한 후 다시 시도하세요.",
"heteroAgent.executionTarget.sandbox": "클라우드 샌드박스",
"heteroAgent.executionTarget.sandboxDesc": "임시 클라우드 샌드박스에서 실행",
- "heteroAgent.executionTarget.sandboxGroup": "샌드박스",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}}은 현재 로컬 또는 연결된 장치에서만 실행됩니다.",
"heteroAgent.executionTarget.switchProjectTopic.content": "이 주제는 {{device}}의 프로젝트 디렉토리 \"{{directory}}\"에서 실행됩니다. 다음 턴은 그곳에서 새 세션을 시작합니다.",
"heteroAgent.executionTarget.switchTopic.content": "이 주제는 {{name}}에서 실행 중이며, 해당 작업 디렉토리와 에이전트 세션이 유지됩니다. 전환 후, 다음 턴은 새 환경에서 새 세션을 시작합니다. 새 주제도 이 선택을 사용합니다.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "드라이브의 폴더 · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "환경 관리",
- "sandboxDrive.pickerTitle": "작업 디렉토리",
"sandboxDrive.root": "드라이브 루트",
"sandboxDrive.upsell": "드라이브에 파일 유지",
"sandboxEnvironment.loadFailed": "환경을 로드할 수 없습니다",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "이 환경을 준비할 수 없습니다",
"sandboxStorage.defaultCopy": "기본값",
"sandboxStorage.environmentsUnavailable": "환경을 불러올 수 없습니다",
- "sandboxStorage.ephemeral": "임시 작업 디렉토리",
"sandboxStorage.ephemeralDesc": "샌드박스가 재활용될 때 정리됩니다",
"sandboxStorage.instanceBusy": "{{name}}이(가) 다른 대화에서 실행 중입니다. 이 대화는 이를 유지하며 해당 실행이 종료되면 이를 가져옵니다.",
"sandboxStorage.kind.code": "코드",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 1d2750c408e..5f8687e6072 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Kan dit apparaat niet opnieuw verbinden. Zorg ervoor dat de desktop-app actief is en probeer het opnieuw.",
"heteroAgent.executionTarget.sandbox": "Cloud-sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Voer uit in een tijdelijke cloud-sandbox",
- "heteroAgent.executionTarget.sandboxGroup": "Sandboxes",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} werkt momenteel alleen op een lokaal of verbonden apparaat",
"heteroAgent.executionTarget.switchProjectTopic.content": "Dit onderwerp wordt uitgevoerd in de projectmap \"{{directory}}\" op {{device}}. De volgende beurt start daar een nieuwe sessie.",
"heteroAgent.executionTarget.switchTopic.content": "Dit onderwerp is uitgevoerd op {{name}}, waar zijn werkmap en agentsessie worden bewaard. Na overschakelen start de volgende beurt een nieuwe sessie in de nieuwe omgeving. Nieuwe onderwerpen zullen ook deze keuze gebruiken.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "Map op uw schijf · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Omgevingen",
- "sandboxDrive.pickerTitle": "Werkmap",
"sandboxDrive.root": "Schijfroot",
"sandboxDrive.upsell": "Bestanden op een schijf bewaren",
"sandboxEnvironment.loadFailed": "Kon omgevingen niet laden",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "Deze omgeving kon niet worden voorbereid",
"sandboxStorage.defaultCopy": "Standaard",
"sandboxStorage.environmentsUnavailable": "Omgevingen konden niet worden geladen",
- "sandboxStorage.ephemeral": "Tijdelijke werkmap",
"sandboxStorage.ephemeralDesc": "Wordt opgeruimd wanneer de sandbox wordt gerecycled",
"sandboxStorage.instanceBusy": "{{name}} draait in een ander gesprek. Dit gesprek houdt het vast en pakt het op wanneer die run eindigt.",
"sandboxStorage.kind.code": "Code",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 0fe1da6a559..0fd5ea15615 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Nie udało się ponownie połączyć tego urządzenia. Upewnij się, że aplikacja na komputerze działa, a następnie spróbuj ponownie.",
"heteroAgent.executionTarget.sandbox": "Chmurowa piaskownica",
"heteroAgent.executionTarget.sandboxDesc": "Uruchom w efemerycznej chmurowej piaskownicy",
- "heteroAgent.executionTarget.sandboxGroup": "Piaskownice",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} działa obecnie tylko na urządzeniu lokalnym lub podłączonym",
"heteroAgent.executionTarget.switchProjectTopic.content": "Ten temat będzie działał w katalogu projektu \"{{directory}}\" na {{device}}. Jego następna tura rozpocznie nową sesję tam.",
"heteroAgent.executionTarget.switchTopic.content": "Ten temat działa na {{name}}, gdzie przechowywany jest jego katalog roboczy i sesja agenta. Po przełączeniu jego następna tura rozpocznie nową sesję w nowym środowisku. Nowe tematy również będą korzystać z tego wyboru.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Folder na Twoim dysku · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Środowiska",
- "sandboxDrive.pickerTitle": "Katalog roboczy",
"sandboxDrive.root": "Katalog główny dysku",
"sandboxDrive.upsell": "Zachowaj pliki na dysku",
"sandboxEnvironment.loadFailed": "Nie udało się załadować środowisk",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Nie udało się przygotować tego środowiska",
"sandboxStorage.defaultCopy": "Domyślna",
"sandboxStorage.environmentsUnavailable": "Nie udało się załadować środowisk",
- "sandboxStorage.ephemeral": "Tymczasowy katalog roboczy",
"sandboxStorage.ephemeralDesc": "Czyszczony, gdy piaskownica jest odświeżana",
"sandboxStorage.instanceBusy": "{{name}} działa w innej rozmowie. Ta zachowuje go i przejmuje, gdy tamto uruchomienie się zakończy.",
"sandboxStorage.kind.code": "Kod",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 0063de1f086..9483cbf26a6 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Não foi possível reconectar este dispositivo. Certifique-se de que o aplicativo de desktop está em execução e tente novamente.",
"heteroAgent.executionTarget.sandbox": "Sandbox na nuvem",
"heteroAgent.executionTarget.sandboxDesc": "Executar em um sandbox efêmero na nuvem",
- "heteroAgent.executionTarget.sandboxGroup": "Sandboxes",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} atualmente funciona apenas em um dispositivo local ou conectado",
"heteroAgent.executionTarget.switchProjectTopic.content": "Este tópico será executado no diretório do projeto \"{{directory}}\" em {{device}}. Sua próxima execução iniciará uma nova sessão lá.",
"heteroAgent.executionTarget.switchTopic.content": "Este tópico está sendo executado em {{name}}, onde seu diretório de trabalho e sessão do agente são mantidos. Após a troca, sua próxima etapa iniciará uma nova sessão no novo ambiente. Novos tópicos também usarão esta escolha.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Pasta no seu drive · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Ambientes",
- "sandboxDrive.pickerTitle": "Diretório de trabalho",
"sandboxDrive.root": "Raiz do drive",
"sandboxDrive.upsell": "Mantenha arquivos em um drive",
"sandboxEnvironment.loadFailed": "Não foi possível carregar os ambientes",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Este ambiente não pôde ser preparado",
"sandboxStorage.defaultCopy": "Padrão",
"sandboxStorage.environmentsUnavailable": "Os ambientes não puderam ser carregados",
- "sandboxStorage.ephemeral": "Diretório de trabalho temporário",
"sandboxStorage.ephemeralDesc": "Limpado quando o sandbox é reciclado",
"sandboxStorage.instanceBusy": "{{name}} está sendo executado em outra conversa. Esta o mantém e o assume quando essa execução termina.",
"sandboxStorage.kind.code": "Código",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index dbf08f4e2f0..9128dfbdbd7 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Не удалось переподключить это устройство. Убедитесь, что настольное приложение запущено, затем попробуйте снова.",
"heteroAgent.executionTarget.sandbox": "Облачная песочница",
"heteroAgent.executionTarget.sandboxDesc": "Запуск в временной облачной песочнице",
- "heteroAgent.executionTarget.sandboxGroup": "Песочницы",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} в настоящее время работает только на локальном или подключенном устройстве",
"heteroAgent.executionTarget.switchProjectTopic.content": "Эта тема будет выполняться в директории проекта \"{{directory}}\" на {{device}}. Следующий ход начнет новую сессию там.",
"heteroAgent.executionTarget.switchTopic.content": "Эта тема выполняется на {{name}}, где сохраняются ее рабочая директория и сессия агента. После переключения следующий ход начнет новую сессию в новой среде. Новые темы также будут использовать этот выбор.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Папка на вашем диске · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Окружения",
- "sandboxDrive.pickerTitle": "Рабочая директория",
"sandboxDrive.root": "Корень диска",
"sandboxDrive.upsell": "Сохраняйте файлы на диске",
"sandboxEnvironment.loadFailed": "Не удалось загрузить окружения",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Эта среда не могла быть подготовлена",
"sandboxStorage.defaultCopy": "По умолчанию",
"sandboxStorage.environmentsUnavailable": "Не удалось загрузить среды",
- "sandboxStorage.ephemeral": "Временная рабочая директория",
"sandboxStorage.ephemeralDesc": "Удаляется при переработке песочницы",
"sandboxStorage.instanceBusy": "{{name}} работает в другом разговоре. Этот разговор сохраняет его и продолжает, когда выполнение завершится.",
"sandboxStorage.kind.code": "Код",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index db085117506..417337f0d0c 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -1546,7 +1546,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Bu cihaza yeniden bağlanılamadı. Masaüstü uygulamasının çalıştığından emin olun ve tekrar deneyin.",
"heteroAgent.executionTarget.sandbox": "Bulut sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Geçici bir bulut sandbox'ında çalıştır",
- "heteroAgent.executionTarget.sandboxGroup": "Sandbox'lar",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} şu anda yalnızca yerel veya bağlı bir cihazda çalışıyor",
"heteroAgent.executionTarget.switchProjectTopic.content": "Bu konu, \"{{directory}}\" proje dizininde {{device}} üzerinde çalışacak. Bir sonraki adımda orada yeni bir oturum başlatılacak.",
"heteroAgent.executionTarget.switchTopic.content": "Bu konu {{name}} üzerinde çalışıyor, burada çalışma dizini ve ajan oturumu tutuluyor. Geçişten sonra, bir sonraki tur yeni ortamda yeni bir oturum başlatır. Yeni konular da bu seçimi kullanır.",
@@ -2123,7 +2122,6 @@
"sandboxDrive.folderDesc": "Sürücünüzdeki klasör · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Ortamlar",
- "sandboxDrive.pickerTitle": "Çalışma dizini",
"sandboxDrive.root": "Sürücü kökü",
"sandboxDrive.upsell": "Dosyaları bir sürücüde saklayın",
"sandboxEnvironment.loadFailed": "Ortamlar yüklenemedi",
@@ -2141,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "Bu ortam hazırlanamadı",
"sandboxStorage.defaultCopy": "Varsayılan",
"sandboxStorage.environmentsUnavailable": "Ortamlar yüklenemedi",
- "sandboxStorage.ephemeral": "Geçici çalışma dizini",
"sandboxStorage.ephemeralDesc": "Kum havuzu geri dönüştürüldüğünde temizlenir",
"sandboxStorage.instanceBusy": "{{name}} başka bir sohbette çalışıyor. Bu sohbet onu tutar ve o çalıştırma sona erdiğinde devralır.",
"sandboxStorage.kind.code": "Kod",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 802daa6ded1..1de0e59c306 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -1544,7 +1544,6 @@
"heteroAgent.executionTarget.reconnectFailed": "Không thể kết nối lại thiết bị này. Hãy đảm bảo ứng dụng trên máy tính đang chạy, sau đó thử lại.",
"heteroAgent.executionTarget.sandbox": "Hộp cát đám mây",
"heteroAgent.executionTarget.sandboxDesc": "Chạy trong hộp cát đám mây tạm thời",
- "heteroAgent.executionTarget.sandboxGroup": "Hộp cát",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} hiện chỉ chạy trên thiết bị cục bộ hoặc được kết nối",
"heteroAgent.executionTarget.switchProjectTopic.content": "Chủ đề này sẽ chạy trong thư mục dự án \"{{directory}}\" trên {{device}}. Lần tiếp theo sẽ bắt đầu một phiên mới tại đó.",
"heteroAgent.executionTarget.switchTopic.content": "Chủ đề này đang chạy trên {{name}}, nơi thư mục làm việc và phiên agent của nó được giữ. Sau khi chuyển đổi, lượt tiếp theo của nó sẽ bắt đầu một phiên mới trong môi trường mới. Các chủ đề mới cũng sẽ sử dụng lựa chọn này.",
@@ -2121,7 +2120,6 @@
"sandboxDrive.folderDesc": "Thư mục trên ổ đĩa của bạn · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "Môi trường",
- "sandboxDrive.pickerTitle": "Thư mục làm việc",
"sandboxDrive.root": "Gốc ổ đĩa",
"sandboxDrive.upsell": "Giữ tệp trên ổ đĩa",
"sandboxEnvironment.loadFailed": "Không thể tải môi trường",
@@ -2139,7 +2137,6 @@
"sandboxStorage.createCopyFailed": "Môi trường này không thể được chuẩn bị",
"sandboxStorage.defaultCopy": "Mặc định",
"sandboxStorage.environmentsUnavailable": "Không thể tải môi trường",
- "sandboxStorage.ephemeral": "Thư mục làm việc tạm thời",
"sandboxStorage.ephemeralDesc": "Được dọn dẹp khi sandbox được tái chế",
"sandboxStorage.instanceBusy": "{{name}} đang chạy trong một cuộc trò chuyện khác. Cuộc trò chuyện này sẽ giữ nó và tiếp tục khi chạy đó kết thúc.",
"sandboxStorage.kind.code": "Mã",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index d97690d528c..d7d249416cb 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1634,8 +1634,6 @@
"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": "仅列出已绑定此项目工作目录的设备。其他设备可在项目设置中添加目录。",
@@ -1643,14 +1641,11 @@
"heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。",
"heteroAgent.executionTarget.sandbox": "云端沙箱",
"heteroAgent.executionTarget.sandboxDesc": "云端运行,不占用机器",
- "heteroAgent.executionTarget.sandboxGroup": "沙箱",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",
"heteroAgent.executionTarget.switchProjectTopic.content": "本话题将改到「{{device}}」上的项目目录「{{directory}}」运行,下一轮会在那里开启新会话。",
"heteroAgent.executionTarget.switchTopic.content": "本话题一直在「{{name}}」上运行,工作目录和会话都保存在那里。切换后,下一轮会在新环境中开启新会话;之后的新话题也会使用这个选择。",
"heteroAgent.executionTarget.switchTopic.ok": "切换",
"heteroAgent.executionTarget.switchTopic.title": "将本话题切换到其他执行环境?",
- "heteroAgent.executionTarget.temporarySandbox": "临时沙箱",
- "heteroAgent.executionTarget.temporarySandboxDesc": "即用即销毁,适合编程和临时数据处理",
"heteroAgent.executionTarget.title": "执行环境",
"heteroAgent.executionTarget.topicTag": "本话题",
"heteroAgent.executionTarget.unknownDevice": "未知设备",
@@ -2292,14 +2287,11 @@
"sandboxDrive.fallbackChip.instanceUnavailable": "环境目录不可用",
"sandboxDrive.fallbackChip.rootNotAllowed": "请选择文件夹",
"sandboxDrive.manageEnvironments": "设置",
- "sandboxDrive.openStorage": "沙箱存储",
- "sandboxDrive.pickerInfoTooltip": "临时工作目录随沙箱清理;云盘文件夹跨会话保留;环境在第一条命令前初始化好。",
- "sandboxDrive.pickerTitle": "工作位置",
"sandboxDrive.root": "根目录",
+ "sandboxDrive.setupSkipped": "该文件夹已有内容,环境不会在这里初始化。",
"sandboxDrive.title": "云盘",
"sandboxEnvironment.add": "新建环境",
"sandboxEnvironment.empty": "还没有环境,先新建一个。",
- "sandboxEnvironment.hint": "在第一条命令前克隆环境里的仓库、执行初始化并注入环境变量。",
"sandboxEnvironment.loadFailed": "无法加载环境列表",
"sandboxEnvironment.loading": "正在加载环境…",
"sandboxEnvironment.missing": "环境不可用",
@@ -2308,6 +2300,10 @@
"sandboxEnvironment.retry": "重试",
"sandboxEnvironment.saveFailed": "无法更改环境,请重试。",
"sandboxEnvironment.title": "环境",
+ "sandboxOptions.environment": "环境",
+ "sandboxOptions.folder": "文件夹",
+ "sandboxOptions.storage": "存储",
+ "sandboxOptions.temporary": "临时",
"sandboxStorage.allCopiesBusy": "所有副本都在使用中",
"sandboxStorage.buildFailed": "未构建",
"sandboxStorage.building": "构建中",
@@ -2317,7 +2313,6 @@
"sandboxStorage.createCopyFailed": "没能为这个环境准备副本",
"sandboxStorage.defaultCopy": "默认",
"sandboxStorage.environmentsUnavailable": "环境列表没能读取",
- "sandboxStorage.ephemeral": "临时工作目录",
"sandboxStorage.instanceBusy": "{{name}} 正在另一个对话里运行。这个对话仍然绑着它,等那边结束后接着用。",
"sandboxStorage.kind.code": "代码",
"sandboxStorage.kind.files": "文件",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 3115826b716..633e2825f10 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -1546,13 +1546,11 @@
"heteroAgent.executionTarget.reconnectFailed": "無法重新連接此裝置。請確保桌面應用程式正在運行,然後再試一次。",
"heteroAgent.executionTarget.sandbox": "雲端沙盒",
"heteroAgent.executionTarget.sandboxDesc": "在臨時雲端沙盒中運行",
- "heteroAgent.executionTarget.sandboxGroup": "沙盒",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前僅能在本地或連接的設備上運行",
"heteroAgent.executionTarget.switchProjectTopic.content": "此主題將在 {{device}} 的專案目錄 \"{{directory}}\" 中運行。其下一回合將在那裡開始一個新的會話。",
"heteroAgent.executionTarget.switchTopic.content": "此主題已在 {{name}} 上運行,其工作目錄和代理會話已保留。切換後,其下一回合將在新環境中啟動一個新會話。新主題也將使用此選擇。",
"heteroAgent.executionTarget.switchTopic.ok": "切換",
"heteroAgent.executionTarget.switchTopic.title": "將此主題移至另一個環境?",
- "heteroAgent.executionTarget.temporarySandbox": "臨時沙盒",
"heteroAgent.executionTarget.title": "執行環境",
"heteroAgent.executionTarget.topicTag": "此主題",
"heteroAgent.executionTarget.unknownDevice": "未知設備",
@@ -2124,7 +2122,6 @@
"sandboxDrive.folderDesc": "您的磁碟上的資料夾 · {{path}}",
"sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}",
"sandboxDrive.manageEnvironments": "環境",
- "sandboxDrive.pickerTitle": "工作目錄",
"sandboxDrive.root": "磁碟根目錄",
"sandboxDrive.upsell": "將檔案保存在磁碟上",
"sandboxEnvironment.loadFailed": "無法載入環境",
@@ -2142,7 +2139,6 @@
"sandboxStorage.createCopyFailed": "無法準備此環境",
"sandboxStorage.defaultCopy": "預設",
"sandboxStorage.environmentsUnavailable": "無法加載環境",
- "sandboxStorage.ephemeral": "臨時工作目錄",
"sandboxStorage.ephemeralDesc": "沙盒回收時清理",
"sandboxStorage.instanceBusy": "{{name}} 正在另一個對話中運行。此對話保留它,並在該運行結束時接管。",
"sandboxStorage.kind.code": "程式碼",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ff061a20752..b63e6f63b4a 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1024,15 +1024,8 @@ 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.temporarySandbox': 'Temporary Sandbox',
- 'heteroAgent.executionTarget.temporarySandboxDesc':
- 'Discarded after use, for coding and one-off data processing',
'heteroAgent.executionTarget.workspaceGroup': 'Workspace Devices',
'heteroAgent.executionTarget.myDevicesGroup': 'My devices',
- 'heteroAgent.executionTarget.sandboxGroup': 'Sandboxes',
'heteroAgent.executionTarget.downloadDesktop': 'Get Desktop App',
'heteroAgent.executionTarget.downloadDesktopDesc': 'Run agents with access to your computer',
'heteroAgent.executionTarget.downloadDesktopTitle': 'Get the desktop app',
@@ -1834,7 +1827,6 @@ export default {
'gatewayMode.cardTitle': 'Agent Gateway Mode',
'gatewayMode.desc':
"Run agents in the cloud through LobeHub's Agent Gateway. Tasks keep running even after you close the page.",
- 'sandboxStorage.ephemeral': 'Temporary working directory',
'sandboxStorage.persistentUpsell': 'Persistent working directory',
'sandboxStorage.setUpEnvironmentDesc': 'A persistent directory lives in an environment',
'sandboxStorage.setUpEnvironment': 'Set up an environment',
@@ -4749,22 +4741,22 @@ export default {
'worktreeRestore.waiting': 'Waiting for the worktree cleanup to finish before restoring it…',
'you': 'You',
'sandboxDrive.manageEnvironments': 'Settings',
- 'sandboxDrive.openStorage': 'Sandbox Storage',
'sandboxEnvironment.none': 'No environment',
'sandboxEnvironment.missing': 'Environment unavailable',
'sandboxEnvironment.loading': 'Loading environment…',
- 'sandboxDrive.pickerTitle': 'Work location',
- 'sandboxDrive.pickerInfoTooltip':
- 'A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. An environment is set up before the first command.',
'sandboxEnvironment.title': 'Environment',
- 'sandboxEnvironment.hint':
- 'Its repositories are cloned, setup runs and its variables are set before the first command.',
'sandboxEnvironment.empty': 'No environments yet. Create one to get started.',
'sandboxEnvironment.add': 'New environment',
'sandboxEnvironment.loadFailed': "Couldn't load environments",
'sandboxEnvironment.retry': 'Retry',
'sandboxEnvironment.saveFailed': 'Could not change the environment. Try again.',
'sandboxDrive.root': 'Root',
+ 'sandboxOptions.storage': 'Storage',
+ 'sandboxOptions.temporary': 'Temporary',
+ 'sandboxOptions.folder': 'Folder',
+ 'sandboxOptions.environment': 'Environment',
+ 'sandboxDrive.setupSkipped':
+ "This folder already has files, so the environment won't be set up in it.",
'sandboxDrive.building': '{{name}} · building',
'sandboxDrive.title': 'Cloud drive',
'sandboxDrive.browseOther': 'Choose another folder…',
diff --git a/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx b/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx
new file mode 100644
index 00000000000..dc32f756662
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/CloudSandboxOptions.tsx
@@ -0,0 +1,349 @@
+'use client';
+
+import { Flexbox, Icon, Popover, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CircleOffIcon, ContainerIcon, FolderIcon, PackageIcon, TimerIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';
+import RepositoryAvatar from '@/components/RepositoryAvatar';
+import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';
+import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { refreshProjectFiles } from '@/services/projectFile';
+import { sandboxStorageService } from '@/services/sandboxStorage';
+
+import OptionRow from './OptionRow';
+import SandboxDriveMenu, { type SandboxDriveFolderPick } from './SandboxDriveMenu';
+import {
+ environmentChipState,
+ environmentSettingsPath,
+ repositorySlug,
+ selectionWithEnvironment,
+} from './sandboxEnvironmentOptions';
+import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';
+import type { useSandboxOptions } from './useSandboxOptions';
+import type { SandboxSelection } from './useSandboxPlacement';
+
+const styles = stylex.create({
+ notice: {
+ backgroundColor: cssVar.colorWarningBg,
+ borderRadius: cssVar.borderRadius,
+ color: cssVar.colorWarningText,
+ fontSize: 12,
+ paddingBlock: 8,
+ paddingInline: 8,
+ },
+});
+
+/** A third level opens beside the second, the way the second opens beside the first. */
+const SUBMENU_STYLES = {
+ content: { padding: 4 },
+ root: { height: 'auto', width: 'auto' },
+};
+
+const folderName = (path: string) => path.split('/').pop() || path;
+
+/** What the folder of a selection is called: the root, its last segment, or a legacy directory's name. */
+export const useSandboxFolderLabel = (selection: SandboxSelection, entitled: boolean) => {
+ const { t } = useTranslation('chat');
+ // A legacy environment directory's own row, for its name — from the
+ // database, so the menu never waits on a sandbox.
+ const { data: instance } = useSWR(
+ entitled && selection.instanceId ? ['sandbox-drive-chip-instance', selection.instanceId] : null,
+ () => sandboxStorageService.getInstance({ id: selection.instanceId! }),
+ );
+ if (selection.instanceId) return instance?.name ?? instance?.workingDirectory;
+ if (selection.workingDirectory === '.') return t('sandboxDrive.root');
+ return selection.workingDirectory ? folderName(selection.workingDirectory) : undefined;
+};
+
+interface CloudSandboxOptionsProps {
+ /** Closes the whole execution-environment menu. */
+ onClose: () => void;
+ /** Moves the conversation to the cloud sandbox before an option is applied, when it is elsewhere. */
+ onEnsureSandbox: () => Promise<void>;
+ options: ReturnType<typeof useSandboxOptions>;
+}
+
+/**
+ * The cloud sandbox's options, one level under its row in the
+ * execution-environment menu:
+ *
+ * - **Storage** — one level further: a temporary sandbox (cleaned up with the
+ * session), or a folder of the drive;
+ * - **Environment** — one level further: none, or the environment the run is
+ * set up from.
+ *
+ * Picking any option also moves the conversation to the cloud sandbox. A pick
+ * that can no longer be honoured — the folder was deleted — is said at the
+ * top, before the next message runs somewhere the person did not choose.
+ */
+const CloudSandboxOptions = memo<CloudSandboxOptionsProps>(
+ ({ onClose, onEnsureSandbox, options }) => {
+ const { t } = useTranslation(['chat', 'device']);
+ const navigate = useWorkspaceAwareNavigate();
+ const {
+ driveStatus,
+ entitled,
+ environmentList,
+ onDrive,
+ onPublicDrive,
+ pick,
+ pickFolder: saveFolder,
+ projectId,
+ selection,
+ sharedAgent,
+ toTemporary,
+ topicId,
+ workspaceId,
+ } = options;
+ const {
+ environments,
+ failed: environmentsFailed,
+ loaded: environmentsLoaded,
+ refresh: refreshEnvironments,
+ } = environmentList;
+ const folderLabel = useSandboxFolderLabel(selection, entitled);
+
+ // Whether the pick still holds, asked of the same resolver the run uses:
+ // a folder deleted on a shared drive, or an environment directory gone,
+ // sends the next run to a temporary sandbox — and the menu says so first.
+ const { data: placement, mutate: revalidatePlacement } = useSWR(
+ entitled && topicId && onDrive
+ ? [
+ 'sandbox-drive-placement',
+ topicId,
+ selection.drive ?? '',
+ selection.instanceId ?? '',
+ selection.workingDirectory ?? '',
+ selection.environmentId ?? '',
+ ]
+ : null,
+ () => sandboxStorageService.resolveSessionPlacement({ topicId }),
+ { revalidateOnFocus: true },
+ );
+ const fallback = placement?.fallback;
+
+ const pickEnvironment = async (environment?: SandboxRepositoryOption) => {
+ try {
+ await onEnsureSandbox();
+ await pick(selectionWithEnvironment(base, environment), { environment });
+ } catch {
+ // The topic kept its old placement; said rather than left looking picked.
+ toast.error(t('sandboxEnvironment.saveFailed'));
+ return;
+ }
+ // Picking what is already held keeps the keys unchanged, so SWR would go
+ // on showing the old answers. Ask once more after every pick.
+ void revalidatePlacement();
+ };
+
+ const pickTemporary = async () => {
+ onClose();
+ try {
+ await onEnsureSandbox();
+ await toTemporary();
+ void revalidatePlacement();
+ } catch {
+ toast.error(t('workingDirectory.drive.pickFailed', { ns: 'device' }));
+ }
+ };
+
+ // An environment is only set up in an empty folder. Picking one that
+ // already holds files keeps the files and skips the setup — said once, at
+ // the pick, rather than left to look applied.
+ const warnIfSetupSkipped = async (next: SandboxSelection) => {
+ if (!next.environmentId || next.workingDirectory === undefined) return;
+ try {
+ const { entries = [] } = await sandboxStorageService.listFiles({
+ drive: next.drive,
+ path: next.workingDirectory === '.' ? undefined : next.workingDirectory,
+ });
+ if (entries.length > 0) toast.info(t('sandboxDrive.setupSkipped'));
+ } catch {
+ // A folder that cannot be listed yet is created empty on the first run.
+ }
+ };
+
+ const pickFolder = async (folder: SandboxDriveFolderPick) => {
+ onClose();
+ let next: SandboxSelection;
+ try {
+ await onEnsureSandbox();
+ next = await saveFolder(folder);
+ } catch {
+ toast.error(t('workingDirectory.drive.pickFailed', { ns: 'device' }));
+ return;
+ }
+ void revalidatePlacement();
+ if (topicId) {
+ const path = next.workingDirectory === '.' ? '' : (next.workingDirectory ?? '');
+ void refreshProjectFiles(`sandbox:${topicId}`, path);
+ }
+ void warnIfSetupSkipped(next);
+ };
+
+ const openBrowser = () => {
+ onClose();
+ openSandboxDirectoryModal({
+ // A folder that is gone cannot be listed; start from the top instead.
+ defaultPath:
+ selection.workingDirectory &&
+ selection.workingDirectory !== '.' &&
+ fallback !== 'directoryMissing'
+ ? selection.workingDirectory
+ : undefined,
+ drive: selection.drive,
+ isWorkspace: !!workspaceId,
+ onPick: pickFolder,
+ });
+ };
+
+ // The drive state the environment is picked against: an entitlement lost
+ // since the folder was picked leaves the conversation off the drive.
+ const base: SandboxSelection = onDrive
+ ? selection
+ : selection.environmentId
+ ? { environmentId: selection.environmentId }
+ : {};
+
+ const addEnvironment = () => {
+ onClose();
+ openCreateEnvironmentModal(
+ // A workspace-public agent, or a folder on the public drive, applies
+ // published environments only.
+ sharedAgent || onPublicDrive ? 'public' : undefined,
+ async (created) => {
+ await refreshEnvironments();
+ if (created?.id) await pickEnvironment(created);
+ },
+ t('sandboxEnvironment.add'),
+ );
+ };
+
+ const current = environments.find((item) => item.id === selection.environmentId);
+ const environmentState = environmentChipState({
+ current,
+ environmentId: selection.environmentId,
+ failed: environmentsFailed,
+ loaded: environmentsLoaded,
+ });
+ const environmentLabel =
+ environmentState.kind === 'picked'
+ ? environmentState.name
+ : environmentState.kind === 'none'
+ ? t('sandboxEnvironment.none')
+ : environmentState.kind === 'missing'
+ ? t('sandboxEnvironment.missing')
+ : environmentState.kind === 'loadFailed'
+ ? t('sandboxEnvironment.loadFailed')
+ : t('sandboxEnvironment.loading');
+ const slug = current && repositorySlug(current);
+
+ const storageLabel = onDrive ? folderLabel : t('sandboxOptions.temporary');
+
+ return (
+ <Flexbox gap={2}>
+ {fallback && (
+ <Text className={stylex.props(styles.notice).className}>
+ {t(`sandboxDrive.fallback.${fallback}`)}
+ </Text>
+ )}
+
+ <Popover
+ arrow={false}
+ closeDelay={150}
+ placement={'rightTop'}
+ styles={SUBMENU_STYLES}
+ trigger={['hover', 'click']}
+ content={
+ <SandboxDriveMenu
+ entitled={driveStatus === 'hidden' ? undefined : driveStatus !== 'upgrade'}
+ selectedLabel={onDrive ? folderLabel : undefined}
+ temporary={!onDrive}
+ // A legacy environment directory is not a folder of this list.
+ selectedPath={
+ onDrive && !selection.instanceId ? selection.workingDirectory : undefined
+ }
+ onBrowse={openBrowser}
+ onPick={(folder) => void pickFolder(folder)}
+ onPickTemporary={() => void pickTemporary()}
+ onUpgrade={() => {
+ onClose();
+ openSandboxStorageUpsell();
+ }}
+ />
+ }
+ >
+ <div data-testid={'sandbox-storage-row'}>
+ <OptionRow
+ arrow
+ compact
+ hint={storageLabel}
+ label={t('sandboxOptions.storage')}
+ icon={
+ <Icon
+ icon={onDrive ? (selection.instanceId ? PackageIcon : FolderIcon) : TimerIcon}
+ size={16}
+ />
+ }
+ onClick={() => {}}
+ />
+ </div>
+ </Popover>
+
+ <Popover
+ arrow={false}
+ closeDelay={150}
+ placement={'rightTop'}
+ styles={SUBMENU_STYLES}
+ trigger={['hover', 'click']}
+ content={
+ <SandboxRepositoryMenu
+ environments={environments}
+ failed={environmentsFailed}
+ loaded={environmentsLoaded}
+ none={{ active: !selection.environmentId, onPick: () => void pickEnvironment() }}
+ selectedId={selection.environmentId}
+ // A project has exactly one environment, edited on its settings:
+ // there is no second one to add from here.
+ onAdd={projectId ? undefined : addEnvironment}
+ onClose={onClose}
+ onPick={pickEnvironment}
+ onRetry={() => void refreshEnvironments()}
+ onManage={() => {
+ onClose();
+ navigate(environmentSettingsPath(projectId));
+ }}
+ />
+ }
+ >
+ <div data-testid={'sandbox-environment-row'}>
+ <OptionRow
+ arrow
+ compact
+ hint={environmentLabel}
+ label={t('sandboxOptions.environment')}
+ icon={
+ slug ? (
+ <RepositoryAvatar size={16} url={slug} />
+ ) : (
+ <Icon icon={selection.environmentId ? ContainerIcon : CircleOffIcon} size={16} />
+ )
+ }
+ onClick={() => {}}
+ />
+ </div>
+ </Popover>
+ </Flexbox>
+ );
+ },
+);
+
+CloudSandboxOptions.displayName = 'CloudSandboxOptions';
+
+export default CloudSandboxOptions;
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 36033aa6d69..47b74bedc55 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -4,14 +4,12 @@ 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, Tag, toast, Tooltip } from '@lobehub/ui';
+import { Button, Flexbox, Icon, Popover, toast, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import {
- BoxesIcon,
ChevronDownIcon,
ExternalLinkIcon,
- HardDriveIcon,
InfoIcon,
MonitorDownIcon,
SettingsIcon,
@@ -20,7 +18,6 @@ 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 +50,7 @@ import { useElectronStore } from '@/store/electron';
import { useTopicId } from '../hooks/useTopicId';
import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';
+import CloudSandboxOptions from './CloudSandboxOptions';
import DeviceGroupSubmenu from './DeviceGroupSubmenu';
import DeviceOptionRow from './DeviceOptionRow';
import { getDevicePoolStatus } from './devicePoolStatus';
@@ -60,8 +58,8 @@ import GroupSubmenu from './GroupSubmenu';
import OptionRow from './OptionRow';
import { reconnectDevice } from './reconnectDevice';
import { isThisComputerDevice, splitThisComputerDevices } from './thisComputerDevices';
-import { useSandboxModeSelect } from './useSandboxModeSelect';
import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';
+import { useSandboxOptions } from './useSandboxOptions';
import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
const styles = stylex.create({
@@ -368,30 +366,17 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
[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, {
+ // The cloud sandbox's options — storage and environment — are picked one
+ // level under its row. Asked once the menu could show them.
+ const sandboxOptions = useSandboxOptions(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],
- );
+ // An option picked while the conversation runs elsewhere moves it to the
+ // cloud sandbox first; the menu stays open for the other option.
+ const ensureSandbox = useCallback(async () => {
+ if (executionTarget !== 'sandbox') await selectTarget('sandbox');
+ }, [executionTarget, selectTarget]);
// 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
@@ -567,19 +552,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// Compute chip
let chipIcon: ReactNode = <ExecutionTargetIcon target={'sandbox'} />;
- // Next to the persistent sandbox the plain one is named for what sets it
- // apart: it is discarded after use. Without a drive on offer there is only
- // one sandbox, and it keeps its usual name.
- const sandboxLabel = t(
- offersPersistentSandbox
- ? 'heteroAgent.executionTarget.temporarySandbox'
- : 'heteroAgent.executionTarget.sandbox',
- );
- let chipLabel = sandboxLabel;
- if (chipExecutionTarget === 'sandbox' && sandboxMode.persistent) {
- chipIcon = <Icon icon={HardDriveIcon} size={14} />;
- chipLabel = t('heteroAgent.executionTarget.persistentSandbox');
- } else if (chipExecutionTarget === 'none') {
+ // One cloud sandbox: whether it keeps files on the drive, and what it is set
+ // up from, are its options on the chips beside this one.
+ let chipLabel = t('heteroAgent.executionTarget.sandbox');
+ if (chipExecutionTarget === 'none') {
chipIcon = <ExecutionTargetIcon target={'none'} />;
chipLabel = t('heteroAgent.executionTarget.none');
} else if (chipExecutionTarget === 'auto') {
@@ -645,17 +621,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
return executionTarget === target;
};
- // The sandboxes share one first-level row, which names the one in use.
const isLocalSandboxActive = executionTarget === 'local' && localSandboxEnabled;
- const isPersistentSandboxActive = isActive('sandbox') && sandboxMode.persistent;
- const isTemporarySandboxActive = isActive('sandbox') && !sandboxMode.persistent;
- const activeSandboxLabel = isLocalSandboxActive
- ? t('heteroAgent.executionTarget.localSandbox')
- : isPersistentSandboxActive
- ? t('heteroAgent.executionTarget.persistentSandbox')
- : isTemporarySandboxActive
- ? sandboxLabel
- : undefined;
const showLocalRow = isDesktop && (!ownWorkspaceDevice || isActive('local'));
const activeDeviceId = executionTarget === 'device' ? boundDeviceId : undefined;
@@ -740,9 +706,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
never both read "This computer". */}
{thisComputerDevices.map((d) => renderDeviceRow(d, { thisComputer: !showLocalRow }))}
{/* The first level is one plain list with no section labels: the choices
- that run nowhere in particular (no device, auto), then a row per group
- — sandboxes, then devices — whose choices open beside it. The rows
- are titles only; what each choice means is said one level down. A
+ that run nowhere in particular (no device, auto), the sandboxes, then
+ a row per device group whose choices open beside it. A
heterogeneous agent has neither of the first two rows. */}
{isHetero ? null : (
<OptionRow
@@ -762,115 +727,87 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
onClick={() => void handleSelect('auto')}
/>
)}
- <GroupSubmenu
- active={!!activeSandboxLabel}
- hint={activeSandboxLabel}
- icon={<Icon icon={BoxesIcon} size={14} />}
- label={t('heteroAgent.executionTarget.sandboxGroup')}
- testId={'sandbox-group'}
- >
- {/* This machine, fenced: writes confined to the working
- directory, network denied unless the switch opens the registry
- allowlist. Shown even when the host can't provide a sandbox — disabled,
- carrying the real reason, because "unavailable" here usually means
- "not installed yet" and silently hiding the feature would strand the
- user with no way to find out why. */}
- {isDesktop ? (
- <OptionRow
- compact
- active={isLocalSandboxActive}
- disabled={!canUseLocalSandbox}
- icon={<Icon icon={ShieldCheckIcon} size={14} />}
- label={t('heteroAgent.executionTarget.localSandbox')}
- tags={tagsFor(isLocalSandboxActive)}
- desc={
- canUseLocalSandbox
- ? t(
- localSandboxNetwork
- ? 'heteroAgent.executionTarget.localSandboxDescNetwork'
- : 'heteroAgent.executionTarget.localSandboxDesc',
- )
- : // Prefer the actionable instruction (Linux's "install this
- // package") over the backend's raw diagnostic when we have one.
- (sandboxCapability?.instructions ??
- t('heteroAgent.executionTarget.localSandboxUnavailable', {
- reason: sandboxCapability?.reason ?? '',
- }))
- }
- extra={
- canUseLocalSandbox ? (
- <>
- <InstantSwitch
- enabled={localSandboxNetwork}
- size={'small'}
- onChange={handleToggleSandboxNetwork}
- />
- <Tooltip title={t('heteroAgent.executionTarget.localSandboxNetworkTip')}>
- <span {...stylex.props(styles.extraInfo)}>
- <Icon icon={InfoIcon} size={12} />
- </span>
- </Tooltip>
- </>
- ) : sandboxCapability?.canInstall ? (
- // The backend is missing but we can provision it — a dead-end row
- // would leave the user to discover a CLI incantation on their own.
- <Button loading={isInstallingSandbox} size={'small'} onClick={handleInstallSandbox}>
- {t('heteroAgent.executionTarget.localSandboxSetUp')}
- </Button>
- ) : undefined
- }
- 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
- compact
- active={isPersistentSandboxActive}
- 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);
- }}
+ {/* One cloud sandbox, its options one level down: whether it keeps its
+ files on the drive (and where), and the environment it is set up
+ from. A runtime that cannot use it gets a disabled row saying why. */}
+ {supportsSandbox ? (
+ <GroupSubmenu
+ active={isActive('sandbox')}
+ icon={<ExecutionTargetIcon target={'sandbox'} />}
+ label={t('heteroAgent.executionTarget.sandbox')}
+ testId={'cloud-sandbox-row'}
+ >
+ <CloudSandboxOptions
+ options={sandboxOptions}
+ onClose={() => setOpen(false)}
+ onEnsureSandbox={ensureSandbox}
/>
- ) : null}
+ </GroupSubmenu>
+ ) : (
<OptionRow
compact
- active={isTemporarySandboxActive}
- disabled={!supportsSandbox}
+ disabled
icon={<ExecutionTargetIcon target={'sandbox'} />}
- label={sandboxLabel}
- desc={t(
- !supportsSandbox
- ? 'heteroAgent.executionTarget.sandboxUnsupported'
- : offersPersistentSandbox
- ? 'heteroAgent.executionTarget.temporarySandboxDesc'
- : 'heteroAgent.executionTarget.sandboxDesc',
- { name: heteroType ? HETEROGENEOUS_TYPE_LABELS[heteroType] : undefined },
- )}
- onClick={() => void selectSandbox(false)}
+ label={t('heteroAgent.executionTarget.sandbox')}
+ desc={t('heteroAgent.executionTarget.sandboxUnsupported', {
+ name: heteroType ? HETEROGENEOUS_TYPE_LABELS[heteroType] : undefined,
+ })}
+ onClick={() => {}}
+ />
+ )}
+ {/* This machine, fenced: writes confined to the working
+ directory, network denied unless the switch opens the registry
+ allowlist. Shown even when the host can't provide a sandbox — disabled,
+ carrying the real reason, because "unavailable" here usually means
+ "not installed yet" and silently hiding the feature would strand the
+ user with no way to find out why. */}
+ {isDesktop ? (
+ <OptionRow
+ compact
+ active={isLocalSandboxActive}
+ disabled={!canUseLocalSandbox}
+ icon={<Icon icon={ShieldCheckIcon} size={14} />}
+ label={t('heteroAgent.executionTarget.localSandbox')}
+ tags={tagsFor(isLocalSandboxActive)}
+ desc={
+ canUseLocalSandbox
+ ? t(
+ localSandboxNetwork
+ ? 'heteroAgent.executionTarget.localSandboxDescNetwork'
+ : 'heteroAgent.executionTarget.localSandboxDesc',
+ )
+ : // Prefer the actionable instruction (Linux's "install this
+ // package") over the backend's raw diagnostic when we have one.
+ (sandboxCapability?.instructions ??
+ t('heteroAgent.executionTarget.localSandboxUnavailable', {
+ reason: sandboxCapability?.reason ?? '',
+ }))
+ }
+ extra={
+ canUseLocalSandbox ? (
+ <>
+ <InstantSwitch
+ enabled={localSandboxNetwork}
+ size={'small'}
+ onChange={handleToggleSandboxNetwork}
+ />
+ <Tooltip title={t('heteroAgent.executionTarget.localSandboxNetworkTip')}>
+ <span {...stylex.props(styles.extraInfo)}>
+ <Icon icon={InfoIcon} size={12} />
+ </span>
+ </Tooltip>
+ </>
+ ) : sandboxCapability?.canInstall ? (
+ // The backend is missing but we can provision it — a dead-end row
+ // would leave the user to discover a CLI incantation on their own.
+ <Button loading={isInstallingSandbox} size={'small'} onClick={handleInstallSandbox}>
+ {t('heteroAgent.executionTarget.localSandboxSetUp')}
+ </Button>
+ ) : undefined
+ }
+ onClick={() => void handleSelect('local', undefined, true)}
/>
- </GroupSubmenu>
+ ) : null}
{/* Devices sit one level down too, a row per group: the list keeps
growing, and the environments above should not scroll away with it. */}
{showDeviceGroups && privateDevices.length > 0 ? (
diff --git a/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx b/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx
index e64a6c976ed..5e9baf8d0b3 100644
--- a/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxDriveMenu.tsx
@@ -2,10 +2,10 @@
import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
import { SANDBOX_DRIVE_ROOT } from '@lobechat/builtin-tool-cloud-sandbox';
-import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { FolderIcon, FolderOpenIcon, HomeIcon, ServerIcon } from 'lucide-react';
+import { FolderIcon, FolderOpenIcon, HardDriveIcon, HomeIcon, TimerIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
@@ -14,9 +14,14 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { sandboxStorageService } from '@/services/sandboxStorage';
import OptionRow from './OptionRow';
-import SubmenuHeader from './SubmenuHeader';
const styles = stylex.create({
+ divider: {
+ height: 1,
+ marginBlock: 4,
+ marginInline: 8,
+ backgroundColor: cssVar.colorBorderSecondary,
+ },
hint: {
paddingInline: '8px',
fontSize: '12px',
@@ -34,32 +39,50 @@ export interface SandboxDriveFolderPick {
}
interface SandboxDriveMenuProps {
+ /**
+ * Whether this plan includes a drive. Without one the folders are replaced by
+ * a single drive row leading to a plan; `undefined` hides the drive entirely
+ * (a deployment without one).
+ */
+ entitled?: boolean;
/** Opens the full directory browser, for folders this short list does not reach. */
onBrowse: () => void;
- /** Leaves the menu for Sandbox Storage, where the drives are browsed and managed. */
- onOpenStorage: () => void;
onPick: (pick: SandboxDriveFolderPick) => void;
+ onPickTemporary: () => void;
+ onUpgrade: () => void;
/** The label of a pick the list cannot show: a nested folder, or another drive. */
selectedLabel?: string;
/** The folder the conversation is on, when it is on one. */
selectedPath?: string;
+ /** Whether the conversation runs in a temporary sandbox. */
+ temporary: boolean;
}
/**
- * The second level of the work-location menu: the top of the conversation's own
- * drive, and the way into the full browser. The list lives here so it is only
- * fetched once the row is opened.
+ * Where the cloud sandbox keeps its files, one level under its storage option:
+ * a temporary sandbox, or a folder of the conversation's own drive — its top
+ * folders, and the way into the full browser. The list lives here so it is
+ * only fetched once it is opened.
*/
const SandboxDriveMenu = memo<SandboxDriveMenuProps>(
- ({ onBrowse, onOpenStorage, onPick, selectedLabel, selectedPath }) => {
- const { t } = useTranslation(['chat', 'device']);
+ ({
+ entitled,
+ onBrowse,
+ onPick,
+ onPickTemporary,
+ onUpgrade,
+ selectedLabel,
+ selectedPath,
+ temporary,
+ }) => {
+ const { t } = useTranslation(['chat', 'device', 'common']);
const workspaceId = useActiveWorkspaceId();
// The public drive's root is not a place to work, so a workspace starts on
// the member's own drive, as a new conversation does.
const drive: SandboxDrive | undefined = workspaceId ? 'personal' : undefined;
const { data, error, mutate } = useSWR(
- ['sandbox-drive-menu-folders', workspaceId ?? '', drive ?? ''],
+ entitled ? ['sandbox-drive-menu-folders', workspaceId ?? '', drive ?? ''] : null,
() => sandboxStorageService.listFiles({ drive }),
{ revalidateOnFocus: false, shouldRetryOnError: false },
);
@@ -71,62 +94,86 @@ const SandboxDriveMenu = memo<SandboxDriveMenuProps>(
selectedPath === SANDBOX_DRIVE_ROOT || folders.some((item) => item.path === selectedPath);
return (
- <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>
- <SubmenuHeader
- title={t('sandboxDrive.title')}
- action={{
- icon: ServerIcon,
- label: t('sandboxDrive.openStorage'),
- onClick: onOpenStorage,
- }}
+ <Flexbox gap={2} style={{ maxWidth: 320, minWidth: 220 }}>
+ <OptionRow
+ compact
+ active={temporary}
+ icon={<Icon icon={TimerIcon} size={16} />}
+ label={t('sandboxOptions.temporary')}
+ onClick={onPickTemporary}
/>
- <div {...stylex.props(styles.list)}>
- {selectedLabel && !listed && (
- <OptionRow
- active
- compact
- icon={<Icon icon={FolderIcon} size={16} />}
- label={selectedLabel}
- onClick={() => {
- if (selectedPath) onPick({ drive, workingDirectory: selectedPath });
- }}
- />
- )}
+ {entitled === false && (
<OptionRow
compact
- active={selectedPath === SANDBOX_DRIVE_ROOT}
- icon={<Icon icon={HomeIcon} size={16} />}
- label={t('sandboxDrive.root')}
- onClick={() => onPick({ drive, workingDirectory: SANDBOX_DRIVE_ROOT })}
+ icon={<Icon icon={HardDriveIcon} size={16} />}
+ label={t('sandboxDrive.title')}
+ badge={
+ <Tag color={'gold'} size={'small'} style={{ borderRadius: 999, paddingInline: 8 }}>
+ {t('pro', { ns: 'common' })}
+ </Tag>
+ }
+ onClick={onUpgrade}
/>
- {folders.map((folder) => (
+ )}
+
+ {entitled && (
+ <>
+ <div {...stylex.props(styles.divider)} />
+ <div {...stylex.props(styles.list)}>
+ {selectedLabel && !listed && (
+ <OptionRow
+ active
+ compact
+ icon={<Icon icon={FolderIcon} size={16} />}
+ label={selectedLabel}
+ onClick={() => {
+ if (selectedPath) onPick({ drive, workingDirectory: selectedPath });
+ }}
+ />
+ )}
+ <OptionRow
+ compact
+ active={selectedPath === SANDBOX_DRIVE_ROOT}
+ icon={<Icon icon={HomeIcon} size={16} />}
+ label={t('sandboxDrive.root')}
+ onClick={() => onPick({ drive, workingDirectory: SANDBOX_DRIVE_ROOT })}
+ />
+ {folders.map((folder) => (
+ <OptionRow
+ compact
+ active={folder.path === selectedPath}
+ icon={<Icon icon={FolderIcon} size={16} />}
+ key={folder.path}
+ label={folder.name}
+ onClick={() => onPick({ drive, workingDirectory: folder.path })}
+ />
+ ))}
+ </div>
+
+ {error && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ justify={'space-between'}
+ paddingInline={8}
+ >
+ <Text className={stylex.props(styles.hint).className} type={'danger'}>
+ {t('workingDirectory.drive.foldersLoadFailed', { ns: 'device' })}
+ </Text>
+ <Button onClick={() => void mutate()}>{t('sandboxEnvironment.retry')}</Button>
+ </Flexbox>
+ )}
+
<OptionRow
compact
- active={folder.path === selectedPath}
- icon={<Icon icon={FolderIcon} size={16} />}
- key={folder.path}
- label={folder.name}
- onClick={() => onPick({ drive, workingDirectory: folder.path })}
+ icon={<Icon icon={FolderOpenIcon} size={16} />}
+ label={t('sandboxDrive.browseOther')}
+ onClick={onBrowse}
/>
- ))}
- </div>
-
- {error && (
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} paddingInline={8}>
- <Text className={stylex.props(styles.hint).className} type={'danger'}>
- {t('workingDirectory.drive.foldersLoadFailed', { ns: 'device' })}
- </Text>
- <Button onClick={() => void mutate()}>{t('sandboxEnvironment.retry')}</Button>
- </Flexbox>
+ </>
)}
-
- <OptionRow
- compact
- icon={<Icon icon={FolderOpenIcon} size={16} />}
- label={t('sandboxDrive.browseOther')}
- onClick={onBrowse}
- />
</Flexbox>
);
},
diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx
deleted file mode 100644
index bb945b20ec2..00000000000
--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx
+++ /dev/null
@@ -1,492 +0,0 @@
-'use client';
-
-import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
-import { Flexbox, Icon, Popover, Skeleton, Tag, Text, toast, Tooltip } from '@lobehub/ui';
-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
-import * as stylex from '@stylexjs/stylex';
-import {
- ChevronDownIcon,
- ContainerIcon,
- FolderIcon,
- HardDriveIcon,
- InfoIcon,
- PackageIcon,
- TimerIcon,
- TriangleAlertIcon,
-} from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import useSWR from 'swr';
-
-import { openSandboxStorageUpsell } from '@/business/client/features/SandboxStorageUpsell';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import RepositoryAvatar from '@/components/RepositoryAvatar';
-import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';
-import { SANDBOX_STORAGE_PATH } from '@/features/ResourceHome/paths';
-import { openSandboxDirectoryModal } from '@/features/WorkingDirectory';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { refreshProjectFiles } from '@/services/projectFile';
-import { sandboxStorageService } from '@/services/sandboxStorage';
-
-import OptionRow from './OptionRow';
-import SandboxDriveMenu from './SandboxDriveMenu';
-import {
- environmentChipState,
- environmentSettingsPath,
- repositoriesLabel,
- repositorySelection,
- repositorySlug,
-} from './sandboxEnvironmentOptions';
-import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';
-import { useSandboxEnvironmentList } from './useSandboxEnvironmentList';
-import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';
-import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
-
-const styles = stylex.create({
- header: {
- alignItems: 'center',
- display: 'flex',
- gap: 6,
- justifyContent: 'space-between',
- paddingBlock: 4,
- paddingInline: 8,
- },
- headerInfo: {
- color: cssVar.colorTextQuaternary,
- cursor: 'help',
- },
- headerTitle: {
- color: cssVar.colorTextTertiary,
- fontSize: 12,
- fontWeight: 500,
- },
- notice: {
- backgroundColor: cssVar.colorWarningBg,
- borderRadius: cssVar.borderRadius,
- color: cssVar.colorWarningText,
- fontSize: 12,
- paddingBlock: 8,
- paddingInline: 8,
- },
- warning: {
- color: cssVar.colorWarning,
- },
-});
-
-/**
- * A submenu's list can arrive after it opens. Left to size itself, its positioner
- * keeps the size it was first measured at, so the popup would grow off the screen
- * instead of being placed again.
- */
-const SUBMENU_STYLES = {
- content: { padding: 4 },
- root: { height: 'auto', width: 'auto' },
-};
-
-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 this conversation belongs to. It runs in the project's own
- * environment, so that is the only one offered, and managed on the
- * project's settings rather than in the workspace's list.
- */
- projectId?: string;
- /** Whether the conversation's agent is workspace-public; it applies published environments only. */
- sharedAgent?: boolean;
- topicId?: string;
- /** Where this conversation works today. */
- value: SandboxSelection;
-}
-
-const folderName = (path: string) => path.split('/').pop() || path;
-
-/**
- * Where a cloud-sandbox run works, offered the way the device picker offers
- * folders: the chip names the place. 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 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,
- modeInEnvironmentMenu = true,
- onChange,
- projectId,
- sharedAgent = false,
- 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 {
- environments,
- failed: environmentsFailed,
- loaded: environmentsLoaded,
- refresh: refreshEnvironments,
- } = useSandboxEnvironmentList({ projectId, sharedAgent, workspaceId });
- const repository = environments.find((item) => item.id === value.environmentId);
- // Picked once but no longer readable — deleted, or unpublished by its owner
- // — is said rather than hidden; a list that has not loaded says nothing.
- const repositoryState = environmentChipState({
- current: repository,
- environmentId: value.environmentId,
- failed: environmentsFailed,
- loaded: environmentsLoaded,
- });
-
- // A legacy environment directory's own row, for its name — from the
- // database, so the chip never waits on a sandbox.
- const { data: instance, isLoading: instanceLoading } = useSWR(
- entitled && value.instanceId ? ['sandbox-drive-chip-instance', value.instanceId] : null,
- () => sandboxStorageService.getInstance({ id: value.instanceId! }),
- );
-
- // Whether the pick still holds, asked of the same resolver the run uses:
- // a folder deleted on a shared drive, or an environment directory gone,
- // sends the next run to a temporary sandbox — and the chip says so first.
- const { data: placement, mutate: revalidatePlacement } = useSWR(
- entitled && topicId && persistent
- ? [
- 'sandbox-drive-placement',
- topicId,
- value.drive ?? '',
- value.instanceId ?? '',
- value.workingDirectory ?? '',
- ]
- : null,
- () => sandboxStorageService.resolveSessionPlacement({ topicId }),
- { revalidateOnFocus: true },
- );
- const fallback = placement?.fallback;
-
- // Picking the folder already held keeps the keys unchanged, so SWR would
- // go on showing the old answers — "no longer exists" on the chip and an
- // unreadable tree in the working panel, for a folder just re-created and
- // picked again. Ask once more after every pick.
- const pick = async (selection: SandboxSelection) => {
- await onChange(selection);
- void revalidatePlacement();
- if (topicId && !selection.instanceId && selection.workingDirectory !== undefined) {
- const folder = selection.workingDirectory === '.' ? '' : selection.workingDirectory;
- void refreshProjectFiles(`sandbox:${topicId}`, folder);
- }
- };
-
- const select = async (selection: SandboxSelection) => {
- setOpen(false);
- try {
- await pick(selection);
- } catch {
- // The topic kept its old placement; said rather than left looking picked.
- toast.error(t('workingDirectory.drive.pickFailed', { ns: 'device' }));
- }
- };
-
- const pickRepository = async (environment: SandboxRepositoryOption) => {
- try {
- await onChange(repositorySelection(environment));
- void revalidatePlacement();
- } catch {
- // The topic kept its place; said rather than left looking changed.
- toast.error(t('sandboxEnvironment.saveFailed'));
- }
- };
-
- const addRepository = () => {
- setOpen(false);
- openCreateEnvironmentModal(
- // A workspace-public agent applies published environments only.
- sharedAgent ? 'public' : undefined,
- async (created) => {
- await refreshEnvironments();
- if (created?.id) await pickRepository(created);
- },
- t('sandboxEnvironment.add'),
- );
- };
-
- const openBrowser = () => {
- setOpen(false);
- openSandboxDirectoryModal({
- // A folder that is gone cannot be listed; start from the top instead.
- defaultPath:
- value.workingDirectory &&
- value.workingDirectory !== '.' &&
- fallback !== 'directoryMissing'
- ? value.workingDirectory
- : undefined,
- drive: value.drive,
- isWorkspace: !!workspaceId,
- onPick: pick,
- });
- };
-
- const currentLabel = value.instanceId
- ? (instance?.name ?? instance?.workingDirectory)
- : value.workingDirectory === '.'
- ? t('sandboxDrive.root')
- : value.workingDirectory
- ? folderName(value.workingDirectory)
- : undefined;
- const currentIcon = value.instanceId ? PackageIcon : FolderIcon;
- const showFolder = persistent && !onRepository;
-
- const fallbackMessage = fallback ? t(`sandboxDrive.fallback.${fallback}`) : undefined;
- const chipIcon = fallback ? (
- <Icon icon={TriangleAlertIcon} size={14} />
- ) : onRepository && repository && repositorySlug(repository) ? (
- <RepositoryAvatar size={14} url={repositorySlug(repository)} />
- ) : onRepository ? (
- <Icon icon={ContainerIcon} size={14} />
- ) : persistent ? (
- <Icon icon={currentIcon} size={14} />
- ) : repositoryOnly ? (
- <Icon icon={ContainerIcon} size={14} />
- ) : (
- <Icon icon={TimerIcon} size={14} />
- );
- const repositoryLabel =
- repositoryState.kind === 'picked'
- ? repositoryState.name
- : repositoryState.kind === 'missing'
- ? t('sandboxEnvironment.missing')
- : repositoryState.kind === 'loadFailed'
- ? t('sandboxEnvironment.loadFailed')
- : t('sandboxEnvironment.loading');
- const chipLabel = fallback
- ? t(`sandboxDrive.fallbackChip.${fallback}`)
- : onRepository
- ? repositoryLabel
- : persistent
- ? currentLabel
- : repositoryOnly
- ? t('sandboxEnvironment.none')
- : t('sandboxStorage.ephemeral');
-
- 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: environmentsFailed,
- loaded: environmentsLoaded,
- // A project has exactly one environment, edited on its settings: there
- // is no second one to add from here.
- onAdd: projectId ? undefined : addRepository,
- onClose: () => setOpen(false),
- onManage: () => {
- setOpen(false);
- navigate(environmentSettingsPath(projectId));
- },
- 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 ? repositoriesLabel(repository) : undefined}
- icon={
- onRepository && repository && repositorySlug(repository) ? (
- <RepositoryAvatar size={16} url={repositorySlug(repository)} />
- ) : (
- <Icon icon={ContainerIcon} size={16} />
- )
- }
- label={
- // The environment 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}>
- <span {...stylex.props(styles.headerTitle)}>{t('sandboxDrive.pickerTitle')}</span>
- <Tooltip title={t('sandboxDrive.pickerInfoTooltip')}>
- <span {...stylex.props(styles.headerInfo)}>
- <Icon icon={InfoIcon} size={12} />
- </span>
- </Tooltip>
- </Flexbox>
- </div>
-
- {notice}
-
- <OptionRow
- compact
- active={!persistent && !onRepository}
- icon={<Icon icon={TimerIcon} size={16} />}
- label={t('sandboxStorage.ephemeral')}
- onClick={() => void select({})}
- />
-
- {/* No environment menu to switch sandboxes in: the drive stays a row here. */}
- {ENABLE_BUSINESS_FEATURES &&
- (entitled ? (
- <Popover
- arrow={false}
- closeDelay={150}
- content={driveMenu}
- placement={'rightBottom'}
- styles={SUBMENU_STYLES}
- trigger={['hover', 'click']}
- >
- <div data-testid={'sandbox-drive-row'}>
- <OptionRow
- arrow
- compact
- active={showFolder}
- icon={<Icon icon={HardDriveIcon} size={16} />}
- label={t('sandboxDrive.title')}
- onClick={() => {}}
- />
- </div>
- </Popover>
- ) : (
- <OptionRow
- compact
- icon={<Icon icon={HardDriveIcon} size={16} />}
- label={t('sandboxDrive.title')}
- badge={
- <Tag color={'gold'} size={'small'} style={{ borderRadius: 999, paddingInline: 8 }}>
- {t('pro', { ns: 'common' })}
- </Tag>
- }
- onClick={() => {
- setOpen(false);
- openSandboxStorageUpsell();
- }}
- />
- ))}
-
- {repositoryRow}
- </Flexbox>
- );
-
- const resolving = !!value.instanceId && !instance && instanceLoading;
-
- // A plain div between the popover and the chip, as the device picker has:
- // the popover merges trigger props into its direct child.
- return (
- <Popover
- arrow={false}
- content={content}
- open={open}
- placement={'topLeft'}
- styles={{ content: { padding: 4 } }}
- trigger={'click'}
- onOpenChange={setOpen}
- >
- <div>
- <Tooltip title={fallbackMessage}>
- <div
- data-testid={'sandbox-drive-chip'}
- {...stylex.props(workingDirectoryChipStyles.chip, fallback && styles.warning)}
- >
- {chipIcon}
- {resolving ? (
- <Skeleton.Text rows={1} style={{ height: 12, width: 56 }} />
- ) : (
- <span {...stylex.props(workingDirectoryChipStyles.label)}>{chipLabel}</span>
- )}
- <Icon icon={ChevronDownIcon} size={12} />
- </div>
- </Tooltip>
- </div>
- </Popover>
- );
- },
-);
-
-SandboxDrivePicker.displayName = 'SandboxDrivePicker';
-
-export default SandboxDrivePicker;
diff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx
index 146337f592e..afe95275ee9 100644
--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx
@@ -31,17 +31,15 @@ export interface SandboxRepositoryOption {
description?: string | null;
id: string;
name: string;
+ /** `public` once published to the workspace; anything else is its owner's alone. */
+ visibility?: string | null;
}
interface SandboxRepositoryMenuProps {
environments: SandboxRepositoryOption[];
failed: boolean;
loaded: boolean;
- /**
- * A first row for working without 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.
- */
+ /** A first row for working without an environment. */
none?: { active: boolean; onPick: () => void };
/** Adds an environment and picks it. Absent where there is no other one to add — a project's. */
onAdd?: () => void;
@@ -54,9 +52,8 @@ interface SandboxRepositoryMenuProps {
}
/**
- * 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.
+ * The environments a conversation can be set up from, and the way to add one
+ * without leaving the composer.
*/
const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(
({
@@ -82,7 +79,6 @@ const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(
onClick: onManage,
}}
/>
- <Text className={stylex.props(styles.hint).className}>{t('sandboxEnvironment.hint')}</Text>
<div {...stylex.props(styles.list)}>
{none && (
diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
index 0aafbd7abf6..4fadc65e276 100644
--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
@@ -1,26 +1,18 @@
'use client';
-import { memo, useCallback } from 'react';
+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 { rememberSandboxSelection } from './rememberedSandboxDirectory';
-import SandboxDrivePicker from './SandboxDrivePicker';
import { projectStartEnvironmentId } from './sandboxEnvironmentOptions';
import { usePrefersTemporarySandbox } from './temporarySandboxPreference';
import { useFollowSandboxModePreference } from './useFollowSandboxModePreference';
import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';
-import {
- isPersistentSelection,
- type SandboxSelection,
- useSandboxPlacement,
-} from './useSandboxPlacement';
+import { useSandboxPlacement } from './useSandboxPlacement';
import { useSandboxStorageAccess } from './useSandboxStorageAccess';
import { useSeedDefaultSelection, useSeedTemporaryRepository } from './useSeedDefaultSelection';
@@ -29,31 +21,23 @@ interface SandboxStorageSectionProps {
}
/**
- * The working directory of a cloud-sandbox run — the counterpart of
- * `WorkingDirectorySection`, which covers runs on a machine, and shaped the
- * same way: one chip that always names the slot, whose menu holds every place
- * the run could work.
+ * Where a new conversation's cloud sandbox starts, kept in step while the run
+ * uses the sandbox. It renders nothing: the sandbox's options — the drive and
+ * the environment — are picked under the 云端沙箱 row of the
+ * execution-environment menu, whose chip is the only control under the input.
*
- * 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 in the folder the agent's
- * last conversation was put in, or on its default folder rather than nothing —
- * unless the execution-environment menu moved the agent to the
- * temporary cloud sandbox, which new conversations then keep, initialized from
- * the repository the last temporary sandbox used (or none).
- *
- * A plan without a drive still gets the chip: the temporary sandbox is
- * everyone's, and the way to a plan is a row in the same menu rather than a
- * different control.
+ * A plan with a drive starts each new conversation on it — in the folder the
+ * agent's last conversation was put in, or its default folder, with the
+ * environment picked together with that folder — unless the drive was
+ * switched off for this agent, which new conversations then keep, set up from
+ * the environment the last one used. A project conversation starts off the
+ * drive, in its project's environment, unless the person switches the drive
+ * on.
*/
const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {
const { eligible, status } = useSandboxStorageAccess(agentId);
const scopeTopicId = useTopicId();
- // A project conversation runs in its project's environment.
- const { projectId, selection, setSelection, topicId } = useSandboxPlacement(
- agentId,
- scopeTopicId,
- );
+ const { projectId, topicId } = useSandboxPlacement(agentId, scopeTopicId);
const workspaceId = useActiveWorkspaceId();
const sharedAgent = useIsSharedAgent(agentId);
// Only a run in the sandbox needs the project's environment.
@@ -62,48 +46,25 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }
sharedAgent,
eligible,
);
- // 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,
- { topicId: scopeTopicId },
- );
- const modeInEnvironmentMenu =
- canUseResource && canDisplayExecutionTarget && canSelectExecutionTarget;
const userId = useUserStore(userProfileSelectors.userId);
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;
+ // A project conversation starts off the drive, in its project's environment;
+ // the agent's drive preference is about its conversations elsewhere.
+ const temporary = prefersTemporary || !!projectId;
useFollowSandboxModePreference(agentId, {
- enabled: modeInEnvironmentMenu,
+ enabled: !projectId,
hasTopic: !!topicId,
scopeKey: `${userId ?? ''}:${workspaceId ?? ''}:${agentId}`,
temporary: prefersTemporary,
});
- // Every pick that lands is remembered for the next conversation: the folder
- // for the persistent sandbox, the repository (or none) for the temporary
- // one. A failed save is not, and neither is an environment picked inside a
- // project: it belongs to that project, and the agent's next conversation
- // elsewhere could not use it. A drive folder is usable anywhere.
- const pick = useCallback(
- async (next: SandboxSelection) => {
- await setSelection(next);
- if (!projectId || isPersistentSelection(next))
- rememberSandboxSelection({ userId, workspaceId }, agentId, next);
- },
- [agentId, projectId, setSelection, userId, workspaceId],
- );
useSeedDefaultSelection(agentId, {
eligible: eligible && !temporary,
entitled: status === 'ready' && !temporary,
hasTopic: !!topicId,
});
- // Where new conversations start in the temporary sandbox — picked in the
- // environment menu, or the only one a plan without a drive has — they start
- // from the repository the last one used.
+ // Where new conversations start off the drive — switched off, a project's,
+ // or the only one a plan without a drive has — they start from the
+ // environment the last one used.
useSeedTemporaryRepository(agentId, {
eligible,
hasTopic: !!topicId,
@@ -113,25 +74,13 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }
temporary: eligible && (temporary || status === 'upgrade'),
});
- if (status === 'hidden') return null;
-
- return (
- <SandboxDrivePicker
- entitled={status === 'ready'}
- modeInEnvironmentMenu={modeInEnvironmentMenu}
- projectId={projectId}
- sharedAgent={sharedAgent}
- topicId={topicId}
- value={selection}
- onChange={pick}
- />
- );
+ return null;
});
SandboxStorageSectionInner.displayName = 'SandboxStorageSectionInner';
const SandboxStorageSection = memo<SandboxStorageSectionProps>(({ agentId }) => (
- <SafeBoundary minHeight={22} resetKeys={[agentId]}>
+ <SafeBoundary minHeight={0} resetKeys={[agentId]}>
<SandboxStorageSectionInner agentId={agentId} />
</SafeBoundary>
));
diff --git a/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx b/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx
index df848666630..f4b8614c5bd 100644
--- a/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/HeteroDeviceSwitcher.sandboxMode.test.tsx
@@ -6,12 +6,7 @@ import HeteroDeviceSwitcher from '../HeteroDeviceSwitcher';
const state = vi.hoisted(() => ({
devices: [] as object[],
- 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', () => ({
@@ -19,7 +14,7 @@ vi.mock('react-i18next', () => ({
}));
// The menu, open: which rows it offers and what they do is the question. The
-// sandbox submenu is a popover too, so the first `chip` is the composer's.
+// first `chip` is the composer's.
vi.mock('@lobehub/ui', async (importOriginal) => ({
...(await importOriginal<object>()),
Popover: ({ children, content }: { children: ReactNode; content: ReactNode }) => (
@@ -35,9 +30,6 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
isDesktop: false,
}));
-vi.mock('@/business/client/features/SandboxStorageUpsell', () => ({
- openSandboxStorageUpsell: state.openUpsell,
-}));
vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
useChatInputResourceAccess: () => ({ canUseResource: true }),
}));
@@ -94,124 +86,47 @@ vi.mock('../useSandboxNetworkToggle', () => ({ useSandboxNetworkToggle: () => vi
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,
- }),
+vi.mock('../useSandboxOptions', () => ({ useSandboxOptions: () => ({}) }));
+// The options are covered by their own tests; here one stands in for any pick.
+vi.mock('../CloudSandboxOptions', () => ({
+ default: ({ onEnsureSandbox }: { onEnsureSandbox: () => Promise<void> }) => (
+ <button onClick={() => void onEnsureSandbox()}>pick-option</button>
+ ),
}));
const SANDBOX = 'heteroAgent.executionTarget.sandbox';
-const TEMPORARY = 'heteroAgent.executionTarget.temporarySandbox';
-const PERSISTENT = 'heteroAgent.executionTarget.persistentSandbox';
beforeEach(() => {
state.devices = [];
- 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);
+ state.selectTarget.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(TEMPORARY).length).toBeGreaterThan(0);
- expect(screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc')).toBeTruthy();
- });
-
- // Next to the persistent sandbox, the plain one is called the temporary
- // sandbox, on its row and on the chip.
- it('names the plain sandbox temporary next to the persistent one', () => {
- render(<HeteroDeviceSwitcher agentId="agent-1" />);
-
- expect(screen.getAllByTestId('chip')[0].textContent).toContain(TEMPORARY);
- expect(screen.queryByText(SANDBOX)).toBeNull();
- });
-
- // 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();
- expect(screen.getAllByText(SANDBOX).length).toBeGreaterThan(0);
- expect(screen.queryByText(TEMPORARY)).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.getAllByTestId('chip')[0].textContent).toContain(PERSISTENT);
- });
-
- it('switches to the sandbox and onto the drive when the persistent row is picked', async () => {
+// T-14791: one cloud sandbox. Whether it keeps files on the drive and what it
+// is set up from are options below the input, not rows of this menu.
+describe('HeteroDeviceSwitcher — cloud sandbox', () => {
+ it('names only the cloud sandbox on the chip and offers it as one row', () => {
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();
+ expect(screen.getAllByTestId('chip')[0].textContent).toBe(SANDBOX);
+ expect(screen.getByTestId('cloud-sandbox-row')).toBeInTheDocument();
+ expect(screen.queryByText('heteroAgent.executionTarget.persistentSandbox')).toBeNull();
+ expect(screen.queryByText('heteroAgent.executionTarget.temporarySandbox')).toBeNull();
+ expect(screen.queryByTestId('sandbox-group')).toBeNull();
});
- it('shows a plan without a drive the way to one instead', () => {
- state.driveStatus = 'upgrade';
+ // Its options live one level down; picking one is picking the sandbox.
+ it('keeps a conversation already in the cloud sandbox where it is when an option is picked', async () => {
render(<HeteroDeviceSwitcher agentId="agent-1" />);
- fireEvent.click(screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc'));
+ fireEvent.click(screen.getByText('pick-option'));
+ await Promise.resolve();
- 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();
- });
});
// T-14345: the first level is a plain list of titles, without section labels
-// or descriptions; the sandboxes sit one level down, as the device groups do.
+// or descriptions.
describe('HeteroDeviceSwitcher — first level', () => {
const follows = (a: Element, b: Element) =>
!!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
@@ -243,29 +158,16 @@ describe('HeteroDeviceSwitcher — first level', () => {
expect(screen.getByText('heteroAgent.executionTarget.auto')).toBeTruthy();
expect(screen.queryByText('heteroAgent.executionTarget.noneDesc')).toBeNull();
expect(screen.queryByText('heteroAgent.executionTarget.autoDesc')).toBeNull();
- expect(screen.getByTestId('sandbox-group').textContent).not.toContain('Desc');
+ expect(screen.queryByText('heteroAgent.executionTarget.sandboxDesc')).toBeNull();
});
- it('puts the sandboxes in a submenu after auto and before the device groups', () => {
+ it('lists the cloud sandbox after auto and before the device groups', () => {
render(<HeteroDeviceSwitcher agentId="agent-1" />);
- const group = screen.getByTestId('sandbox-group');
- expect(group.textContent).toContain('heteroAgent.executionTarget.sandboxGroup');
- // The row itself lists no sandbox; they are the submenu's.
- expect(group.textContent).not.toContain('persistentSandboxDesc');
-
const auto = screen.getByText('heteroAgent.executionTarget.auto');
- const persistent = screen.getByText('heteroAgent.executionTarget.persistentSandboxDesc');
+ const sandbox = screen.getAllByText(SANDBOX).at(-1)!;
const devices = screen.getByText('heteroAgent.executionTarget.myDevicesGroup');
- expect(follows(auto, group)).toBe(true);
- expect(follows(group, persistent)).toBe(true);
- expect(follows(persistent, devices)).toBe(true);
- });
-
- it('names the sandbox in use on the group row', () => {
- state.persistent = true;
- render(<HeteroDeviceSwitcher agentId="agent-1" />);
-
- expect(screen.getByTestId('sandbox-group').textContent).toContain(PERSISTENT);
+ expect(follows(auto, sandbox)).toBe(true);
+ expect(follows(sandbox, devices)).toBe(true);
});
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxDriveMenu.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxDriveMenu.test.tsx
index fbc433b3cd0..aa1b365c409 100644
--- a/src/features/ChatInput/ControlBar/__tests__/SandboxDriveMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxDriveMenu.test.tsx
@@ -15,22 +15,44 @@ vi.mock('@/services/sandboxStorage', () => ({
sandboxStorageService: { listFiles: vi.fn(async () => ({ entries: [] })) },
}));
+const props = {
+ onBrowse: vi.fn(),
+ onPick: vi.fn(),
+ onPickTemporary: vi.fn(),
+ onUpgrade: vi.fn(),
+};
+
+// T-14791: storage is one level under the cloud sandbox — a temporary
+// sandbox, or a folder of the drive.
describe('SandboxDriveMenu', () => {
- const onOpenStorage = vi.fn();
- const onPick = vi.fn();
-
beforeEach(() => {
- onOpenStorage.mockClear();
- onPick.mockClear();
+ for (const fn of Object.values(props)) fn.mockClear();
});
- it('links to Sandbox Storage from the header without picking a folder', () => {
- render(<SandboxDriveMenu onBrowse={vi.fn()} onOpenStorage={onOpenStorage} onPick={onPick} />);
+ it('offers the temporary sandbox above the drive folders', async () => {
+ render(<SandboxDriveMenu entitled temporary {...props} />);
+
+ fireEvent.click(screen.getByText('sandboxOptions.temporary'));
+ expect(props.onPickTemporary).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(await screen.findByText('sandboxDrive.root'));
+ expect(props.onPick).toHaveBeenCalledWith({ drive: undefined, workingDirectory: '.' });
+ expect(screen.getByText('sandboxDrive.browseOther')).toBeInTheDocument();
+ });
+
+ it('leads a plan without a drive to one instead of listing folders', () => {
+ render(<SandboxDriveMenu temporary entitled={false} {...props} />);
+
+ expect(screen.queryByText('sandboxDrive.root')).toBeNull();
+ fireEvent.click(screen.getByText('sandboxDrive.title'));
+ expect(props.onUpgrade).toHaveBeenCalledTimes(1);
+ });
- expect(screen.getByText('sandboxDrive.title')).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'sandboxDrive.openStorage' }));
+ it('offers only the temporary sandbox without a drive service', () => {
+ render(<SandboxDriveMenu temporary {...props} />);
- expect(onOpenStorage).toHaveBeenCalledTimes(1);
- expect(onPick).not.toHaveBeenCalled();
+ expect(screen.getByText('sandboxOptions.temporary')).toBeInTheDocument();
+ expect(screen.queryByText('sandboxDrive.title')).toBeNull();
+ expect(screen.queryByText('sandboxDrive.root')).toBeNull();
});
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx
deleted file mode 100644
index 66b17c2ac4e..00000000000
--- a/src/features/ChatInput/ControlBar/__tests__/SandboxDrivePicker.test.tsx
+++ /dev/null
@@ -1,129 +0,0 @@
-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 () => ({})),
- },
-}));
-// A project's environment lives only in the project's own list.
-vi.mock('@/store/projectWorkingDirectory', () => ({
- useProjectDirectoryStore: (selector: (s: object) => unknown) =>
- selector({ useFetchEnvironments: (projectId?: string) => ({ hasData: !!projectId }) }),
- useProjectEnvironments: (projectId?: string) =>
- projectId ? [{ id: 'env-project', name: 'Lobe Write', visibility: 'private' }] : [],
-}));
-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; projectId?: string } = {},
-) => 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 project conversation starts in its project's environment, which the
- // workspace's shared list leaves out: the chip read "unavailable".
- it("names a project conversation's own environment on the chip", () => {
- renderPicker({ environmentId: 'env-project' }, { projectId: 'project-1' });
-
- expect(screen.getByTestId('sandbox-drive-chip').textContent).toContain('Lobe Write');
- expect(screen.queryByText('sandboxEnvironment.missing')).toBeNull();
- });
-
- // 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/__tests__/SandboxStorageSection.test.tsx b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx
index 9b255f43fe8..c19e568fe31 100644
--- a/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/SandboxStorageSection.test.tsx
@@ -7,7 +7,9 @@ import {
toSandboxTopicMetadata,
} from '@/store/chat/pendingSandboxSelection';
+import { useTopicId } from '../../hooks/useTopicId';
import SandboxStorageSection from '../SandboxStorageSection';
+import { useSandboxOptions } from '../useSandboxOptions';
import type { SandboxSelection } from '../useSandboxPlacement';
const AGENT = 'agent-remember';
@@ -21,10 +23,11 @@ const state = vi.hoisted(() => {
notify: () => {
for (const listener of listeners) listener();
},
- // The execution-environment menu: usable, and the agent moved to the
- // temporary sandbox there.
- inMenu: false,
+ // The agent's drive switched off for its new conversations.
temporary: false,
+ workspaceId: null as string | null,
+ environmentsLoaded: true,
+ setPrefersTemporary: vi.fn(),
topicId: null as string | null,
userId: 'user-a' as string | undefined,
topics: {} as Record<string, Record<string, unknown>>,
@@ -81,7 +84,7 @@ vi.mock('../useSandboxStorageAccess', () => ({
useSandboxStorageAccess: () => ({ eligible: true, status: 'ready' }),
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
- useActiveWorkspaceId: () => null,
+ useActiveWorkspaceId: () => state.workspaceId,
}));
vi.mock('@/store/user', () => ({
@@ -90,24 +93,26 @@ vi.mock('@/store/user', () => ({
return selector({ user: { id: state.userId } });
},
}));
-// The execution-environment menu and its temporary/persistent preference are
-// covered by their own tests; here the member cannot use that menu, so the
-// folder chip is the only place the sandbox is chosen.
-vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
- useChatInputResourceAccess: () => ({ canConfigureResource: true, canUseResource: state.inMenu }),
-}));
-vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
- useEffectiveAgencyConfig: () => ({
- canDisplayExecutionTarget: state.inMenu,
- canSelectExecutionTarget: state.inMenu,
- }),
-}));
vi.mock('../temporarySandboxPreference', () => ({
+ setPrefersTemporarySandbox: state.setPrefersTemporary,
usePrefersTemporarySandbox: () => state.temporary,
}));
vi.mock('../useFollowSandboxModePreference', () => ({ useFollowSandboxModePreference: () => {} }));
+const ENVIRONMENTS = [
+ {
+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobe-chat' }] },
+ id: 'env_repo',
+ name: 'Chat',
+ visibility: 'private',
+ },
+];
+
vi.mock('../useSandboxEnvironmentList', () => ({
useIsSharedAgent: () => false,
+ useSandboxEnvironmentList: () => ({
+ environments: state.environmentsLoaded ? ENVIRONMENTS : [],
+ loaded: state.environmentsLoaded,
+ }),
useProjectSandboxEnvironments: (projectId?: string) => ({
environments: projectId ? (state.projectEnvironments[projectId] ?? []) : [],
}),
@@ -115,44 +120,99 @@ vi.mock('../useSandboxEnvironmentList', () => ({
vi.mock('@/services/sandboxStorage', () => ({
sandboxStorageService: { getEntitlement: vi.fn() },
}));
-vi.mock('@/store/sandbox', () => ({
- sandboxSelectors: { entitlement: () => ({ entitled: true }) },
- useSandboxStore: { getState: () => ({}) },
+vi.mock('@lobechat/business-const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ENABLE_BUSINESS_FEATURES: true,
}));
+vi.mock('@/store/sandbox', () => {
+ const useSandboxStore = (selector: (s: object) => unknown) => selector({});
+ useSandboxStore.getState = () => ({});
+ return {
+ sandboxActions: { useFetchEntitlement: () => undefined },
+ sandboxSelectors: { entitlement: () => ({ entitled: true }) },
+ useSandboxStore,
+ };
+});
-// The picker's menu is covered by its own tests; here it only names the
-// current folder and makes the picks a person would.
-vi.mock('../SandboxDrivePicker', () => ({
- default: ({
- onChange,
- projectId,
- value,
- }: {
- onChange: (s: SandboxSelection) => Promise<void>;
- projectId?: string;
- value: SandboxSelection;
- }) => (
+const label = (value: SandboxSelection) =>
+ value.workingDirectory !== undefined
+ ? value.environmentId
+ ? `${value.workingDirectory}+repo:${value.environmentId}`
+ : value.workingDirectory
+ : value.environmentId
+ ? `repo:${value.environmentId}`
+ : 'temporary';
+
+// The menu's rows are covered by their own tests; here a stand-in makes the
+// picks a person would through the same hook, and names the placement. The
+// real menu catches a failed save and says so.
+const Options = () => {
+ const topicId = useTopicId();
+ const options = useSandboxOptions(AGENT, { enabled: true, topicId });
+ const { pick, pickFolder, projectId, selection: value, toTemporary } = options;
+ return (
<div>
+ <span data-testid="chip">{label(value)}</span>
<span data-testid="project">{projectId ?? ''}</span>
- <span data-testid="chip">
- {value.workingDirectory ??
- (value.environmentId ? `repo:${value.environmentId}` : 'temporary')}
- </span>
- <button onClick={() => onChange({ environmentId: 'env_repo' }).catch(() => {})}>
+ <button onClick={() => pickFolder({ workingDirectory: 'projects/demo' }).catch(() => {})}>
+ pick-folder
+ </button>
+ <button
+ onClick={() => pickFolder({ drive: 'public', workingDirectory: 'team' }).catch(() => {})}
+ >
+ pick-public-folder
+ </button>
+ <button onClick={() => toTemporary().catch(() => {})}>drive-off</button>
+ {/* A published environment just created: not in the list this render holds. */}
+ <button
+ onClick={() =>
+ pick(
+ { ...value, environmentId: 'env_new', workingDirectory: 'new-env' },
+ { environment: { id: 'env_new', name: 'New', visibility: 'public' } },
+ ).catch(() => {})
+ }
+ >
+ create-public-env
+ </button>
+ <button
+ onClick={() =>
+ pick(
+ value.workingDirectory === undefined
+ ? { environmentId: 'env_repo' }
+ : { ...value, environmentId: 'env_repo' },
+ ).catch(() => {})
+ }
+ >
pick-repo
</button>
- {/* The real picker catches a failed save and says so. */}
- <button onClick={() => onChange({ workingDirectory: 'projects/demo' }).catch(() => {})}>
- pick-folder
+ <button
+ onClick={() =>
+ pick(
+ value.workingDirectory === undefined
+ ? {}
+ : { workingDirectory: value.workingDirectory },
+ ).catch(() => {})
+ }
+ >
+ pick-none
</button>
- <button onClick={() => onChange({}).catch(() => {})}>pick-temporary</button>
</div>
- ),
-}));
+ );
+};
+
+const renderSection = () =>
+ render(
+ <>
+ <SandboxStorageSection agentId={AGENT} />
+ <Options />
+ </>,
+ );
beforeEach(() => {
- state.inMenu = false;
state.temporary = false;
+ state.workspaceId = null;
+ state.environmentsLoaded = true;
+ state.setPrefersTemporary.mockReset();
state.topicId = null;
state.userId = 'user-a';
state.topics = {};
@@ -201,7 +261,7 @@ const openNewConversation = () =>
describe('SandboxStorageSection — T-14158', () => {
it('starts the next new conversation in the folder picked in the last one', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
// A first conversation starts at the drive's root.
expect(screen.getByTestId('chip').textContent).toBe('.');
@@ -229,20 +289,138 @@ describe('SandboxStorageSection — T-14158', () => {
// Using the temporary sandbox once does not erase the persistent sandbox's
// folder: the next conversation on the drive still starts there.
it('keeps the folder after a temporary sandbox is used once', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
await act(async () => fireEvent.click(screen.getByText('pick-folder')));
await send('topic-1');
- await act(async () => fireEvent.click(screen.getByText('pick-temporary')));
+ await act(async () => fireEvent.click(screen.getByText('drive-off')));
+ expect(state.setPrefersTemporary).toHaveBeenCalledWith(expect.anything(), AGENT, true);
+ act(() => {
+ state.temporary = false;
+ commit();
+ });
openNewConversation();
expect(screen.getByTestId('chip').textContent).toBe('projects/demo');
});
+ // The folder and the environment are remembered apart, so a new
+ // conversation must not pair a folder with an environment it was never set
+ // up from: in a folder that holds files the setup would be skipped.
+ it('does not pair the remembered folder with an environment picked off the drive', async () => {
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('pick-folder')));
+ await act(async () => fireEvent.click(screen.getByText('drive-off')));
+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));
+
+ act(() => {
+ state.temporary = false;
+ commit();
+ });
+ openNewConversation();
+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo');
+ });
+
+ // Every member browses the workspace's public drive: a private environment
+ // is not carried into a folder there.
+ it("drops a private environment when a folder on the workspace's public drive is picked", async () => {
+ state.workspaceId = 'ws-1';
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));
+
+ await act(async () => fireEvent.click(screen.getByText('pick-public-folder')));
+ expect(state.updateTopicMetadata).toHaveBeenLastCalledWith(
+ 'topic-1',
+ expect.objectContaining({ sandboxEnvironmentId: undefined, sandboxWorkingDirectory: 'team' }),
+ );
+ });
+
+ it('drops an environment not known to be published when a public-drive folder is picked', async () => {
+ state.workspaceId = 'ws-1';
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));
+ act(() => {
+ state.environmentsLoaded = false;
+ commit();
+ });
+
+ await act(async () => fireEvent.click(screen.getByText('pick-public-folder')));
+ expect(state.updateTopicMetadata).toHaveBeenLastCalledWith(
+ 'topic-1',
+ expect.objectContaining({ sandboxEnvironmentId: undefined, sandboxWorkingDirectory: 'team' }),
+ );
+ });
+
+ it('keeps a published environment just created on a public-drive folder', async () => {
+ state.workspaceId = 'ws-1';
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('pick-public-folder')));
+
+ await act(async () => fireEvent.click(screen.getByText('create-public-env')));
+ expect(state.updateTopicMetadata).toHaveBeenLastCalledWith(
+ 'topic-1',
+ expect.objectContaining({
+ sandboxEnvironmentId: 'env_new',
+ sandboxWorkingDirectory: 'new-env',
+ }),
+ );
+ });
+
+ // T-14791: storage is picked as a folder or 临时; a folder keeps the
+ // environment and is where the agent's new conversations start.
+ it('keeps the environment when a folder is picked from a temporary sandbox', async () => {
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('drive-off')));
+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));
+
+ await act(async () => fireEvent.click(screen.getByText('pick-folder')));
+ expect(screen.getByTestId('chip').textContent).toBe('projects/demo+repo:env_repo');
+ expect(state.setPrefersTemporary).toHaveBeenLastCalledWith(expect.anything(), AGENT, false);
+ });
+
+ it('keeps the environment when the drive is switched off', async () => {
+ renderSection();
+ send('topic-1');
+ await act(async () => fireEvent.click(screen.getByText('pick-repo')));
+ expect(screen.getByTestId('chip').textContent).toBe('.+repo:env_repo');
+
+ await act(async () => fireEvent.click(screen.getByText('drive-off')));
+ expect(screen.getByTestId('chip').textContent).toBe('repo:env_repo');
+ });
+
+ // A project conversation starts off the drive, in its project's
+ // environment, whatever the agent's drive preference elsewhere.
+ it("starts a project draft off the drive on the project's environment", () => {
+ renderSection();
+ expect(screen.getByTestId('chip').textContent).toBe('.');
+
+ act(() => {
+ state.draft = { agentId: AGENT, projectId: 'project-1' };
+ commit();
+ });
+ expect(screen.getByTestId('chip').textContent).toBe('repo:env-project');
+ });
+
+ // Switching the drive in a project is about that conversation, not where
+ // the agent's conversations elsewhere start.
+ it('does not move the agent preference from a project conversation', async () => {
+ renderSection();
+ state.topicProjects['topic-1'] = 'project-1';
+ send('topic-1');
+
+ await act(async () => fireEvent.click(screen.getByText('pick-folder')));
+ expect(state.setPrefersTemporary).not.toHaveBeenCalled();
+ });
+
// A drive folder is usable anywhere, so one picked in a project is kept for
// the agent's next conversation like any other.
it('remembers a drive folder picked in a project conversation', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
state.topicProjects['topic-1'] = 'project-1';
send('topic-1');
@@ -253,7 +431,7 @@ describe('SandboxStorageSection — T-14158', () => {
});
it('does not remember a pick that failed to save', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
send('topic-1');
state.updateTopicMetadata.mockRejectedValueOnce(new Error('offline'));
@@ -267,12 +445,11 @@ describe('SandboxStorageSection — T-14158', () => {
describe('in the temporary sandbox', () => {
beforeEach(() => {
- state.inMenu = true;
state.temporary = true;
});
it('starts the next new conversation from the repository the last one used', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
expect(screen.getByTestId('chip').textContent).toBe('temporary');
await send('topic-1');
@@ -291,7 +468,7 @@ describe('SandboxStorageSection — T-14158', () => {
// agent's conversations elsewhere cannot use: picking it there must not
// become where the next one starts.
it("does not carry a project conversation's environment to the next conversation", async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
state.topicProjects['topic-1'] = 'project-1';
await send('topic-1');
expect(screen.getByTestId('project').textContent).toBe('project-1');
@@ -310,7 +487,7 @@ describe('SandboxStorageSection — T-14158', () => {
// A project's blank draft starts where the server will put it — the
// project's environment — not on the agent's repository from elsewhere.
it("starts a project draft on the project's environment", async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
await send('topic-1');
await act(async () => fireEvent.click(screen.getByText('pick-repo')));
@@ -337,7 +514,7 @@ describe('SandboxStorageSection — T-14158', () => {
// outside the project then, the composer re-seeded the agent's repository
// from elsewhere, and the conversation started in it.
it("keeps a project draft's default while its first send creates the topic", async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
await send('topic-1');
await act(async () => fireEvent.click(screen.getByText('pick-repo')));
openNewConversation();
@@ -361,7 +538,7 @@ describe('SandboxStorageSection — T-14158', () => {
// The draft's default is kept by agent, not by project: the agent's next
// conversation outside the project must not inherit the project's.
it("does not carry a project draft's environment to the agent's next conversation", async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
act(() => {
state.draft = { agentId: AGENT, projectId: 'project-1' };
commit();
@@ -377,7 +554,7 @@ describe('SandboxStorageSection — T-14158', () => {
});
it('starts a project draft on no environment when the project checks out no repository', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
await send('topic-1');
await act(async () => fireEvent.click(screen.getByText('pick-repo')));
openNewConversation();
@@ -390,10 +567,10 @@ describe('SandboxStorageSection — T-14158', () => {
});
it('starts the next new conversation without a repository when the last one used none', async () => {
- render(<SandboxStorageSection agentId={AGENT} />);
+ renderSection();
await send('topic-1');
await act(async () => fireEvent.click(screen.getByText('pick-repo')));
- await act(async () => fireEvent.click(screen.getByText('pick-temporary')));
+ await act(async () => fireEvent.click(screen.getByText('pick-none')));
openNewConversation();
expect(screen.getByTestId('chip').textContent).toBe('temporary');
diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts
index 45bc15a95b6..9ed674c563e 100644
--- a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts
+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest';
import {
getRememberedSandboxDirectory,
+ getRememberedSandboxDirectoryEnvironment,
getRememberedSandboxRepository,
rememberedSandboxDirectoryKey,
rememberSandboxSelection,
@@ -56,27 +57,56 @@ describe('rememberedSandboxDirectory', () => {
expect(getRememberedSandboxDirectory({ workspaceId: 'ws_1' }, 'agent-1')).toBeUndefined();
});
- // The persistent sandbox remembers its folder and the temporary one its
- // repository, each on its own: using one never erases the other.
- it('remembers the temporary sandbox repository apart from the folder', () => {
+ // The folder and the environment are remembered each on its own: switching
+ // the drive off never erases the folder.
+ it('remembers the environment apart from the folder', () => {
rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });
rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });
expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });
+ expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBeUndefined();
expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });
});
- it('remembers a temporary sandbox that used no repository', () => {
+ // T-14791: a folder and an environment picked together are both remembered.
+ it('remembers a folder and its environment together', () => {
+ rememberSandboxSelection(ME, 'agent-1', {
+ environmentId: 'env_1',
+ workingDirectory: 'lobehub',
+ });
+
+ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'lobehub' });
+ expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBe('env_1');
+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });
+ });
+
+ // An environment remembered apart from the folder is not the folder's: the
+ // pair was never set up together.
+ it('pairs the folder only with an environment picked together with it', () => {
+ rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'notes' });
rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });
- rememberSandboxSelection(ME, 'agent-1', {});
- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({});
+ expect(getRememberedSandboxDirectoryEnvironment(ME, 'agent-1')).toBeUndefined();
});
- it('remembers nothing for the temporary sandbox until one is used', () => {
+ it('remembers a pick that used no environment', () => {
+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });
rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'code' });
- expect(getRememberedSandboxRepository(ME, 'agent-1')).toBeUndefined();
+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({});
+ });
+
+ it('leaves the environment alone for a folder-only memory', () => {
+ rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_1' });
+ rememberSandboxSelection(
+ ME,
+ 'agent-1',
+ { environmentId: 'env_project', workingDirectory: 'code' },
+ { folderOnly: true },
+ );
+
+ expect(getRememberedSandboxDirectory(ME, 'agent-1')).toEqual({ workingDirectory: 'code' });
+ expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_1' });
});
it('changes nothing for a legacy environment directory', () => {
diff --git a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts
index 4a68e5e9338..cd6b5954455 100644
--- a/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts
+++ b/src/features/ChatInput/ControlBar/rememberedSandboxDirectory.ts
@@ -4,9 +4,9 @@ import type { SandboxSelection } from './useSandboxPlacement';
export const REMEMBERED_SANDBOX_DIRECTORY_PREFIX = 'lobechat-sandbox-last-directory';
/**
- * Prefix of the temporary sandbox's memory, kept apart from the folder: the
- * persistent sandbox remembers which folder of the drive, the temporary one
- * which repository it was initialized from — or that it used none.
+ * Prefix of the environment's memory, kept apart from the folder: which
+ * environment the agent's last conversation was set up from — or that it used
+ * none — whether it kept its files on the drive or not.
*/
export const REMEMBERED_SANDBOX_REPOSITORY_PREFIX = 'lobechat-sandbox-last-repository';
@@ -68,7 +68,26 @@ export const getRememberedSandboxDirectory = (
};
/**
- * What the agent's last temporary sandbox was initialized from: `{ environmentId }`
+ * The environment picked together with the remembered folder, if any. Kept in
+ * the folder's own entry rather than read from the environment memory: the two
+ * memories are written apart, and a folder paired with an environment it was
+ * never set up from would skip the setup — it only runs in an empty folder.
+ */
+export const getRememberedSandboxDirectoryEnvironment = (
+ scope: RememberScope,
+ agentId: string,
+): string | undefined => {
+ const key = rememberedSandboxDirectoryKey(scope, agentId);
+ if (!key) return undefined;
+
+ const value = readEntry(key);
+ if (!isValid(value)) return undefined;
+ const { environmentId } = value as { environmentId?: unknown };
+ return typeof environmentId === 'string' && environmentId ? environmentId : undefined;
+};
+
+/**
+ * What the agent's last conversation was set up from: `{ environmentId }`
* for a repository, `{}` for none picked on purpose, `undefined` when nothing
* is remembered yet.
*/
@@ -88,13 +107,15 @@ export const getRememberedSandboxRepository = (
};
/**
- * Remember a pick so the next conversation starts where this one was put:
+ * Remember a pick so the next conversation starts where this one was put. The
+ * folder and the environment are two answers, each remembered on its own:
*
- * - a folder on the drive — the persistent sandbox — is remembered as its
- * folder;
- * - the temporary sandbox is remembered as the repository it starts from, or
- * as none; the folder memory stays, for the next time the persistent
- * sandbox is used;
+ * - a folder on the drive is remembered as the folder, with the environment
+ * picked together with it; switching the drive off leaves the folder memory
+ * alone, for the next time it is switched on;
+ * - the environment — or none, picked on purpose — is remembered whether or
+ * not the drive is on. `folderOnly` skips it, for an environment that only
+ * means something where it was picked: a project's;
* - a legacy environment directory says nothing about either and changes
* nothing.
*
@@ -105,6 +126,7 @@ export const rememberSandboxSelection = (
scope: RememberScope,
agentId: string,
selection: SandboxSelection,
+ { folderOnly = false }: { folderOnly?: boolean } = {},
): void => {
const key = rememberedSandboxDirectoryKey(scope, agentId);
if (!key) return;
@@ -116,14 +138,14 @@ export const rememberSandboxSelection = (
if (selection.workingDirectory) {
localStorage.setItem(
key,
- JSON.stringify(
- selection.drive
- ? { drive: selection.drive, workingDirectory: selection.workingDirectory }
- : { workingDirectory: selection.workingDirectory },
- ),
+ JSON.stringify({
+ ...(selection.drive && { drive: selection.drive }),
+ ...(!folderOnly && selection.environmentId && { environmentId: selection.environmentId }),
+ workingDirectory: selection.workingDirectory,
+ }),
);
- return;
}
+ if (folderOnly) return;
localStorage.setItem(
repositoryKey,
diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
index ee5dce09204..6e68d545bc3 100644
--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
@@ -2,11 +2,14 @@ import { describe, expect, it } from 'vitest';
import {
environmentChipState,
+ environmentFolderName,
environmentSettingsPath,
+ isOnPublicDrive,
pickableEnvironments,
projectStartEnvironmentId,
- repositorySelection,
repositorySlug,
+ selectionWithEnvironment,
+ selectionWithFolder,
} from './sandboxEnvironmentOptions';
const environments = [
@@ -84,11 +87,104 @@ describe('environmentSettingsPath', () => {
});
});
-describe('repositorySelection', () => {
- const repo = { id: 'env-repo', name: 'lobehub-biz/agent-mail' };
+const repoEnv = {
+ configuration: {
+ sources: [{ kind: 'git' as const, url: 'https://github.com/lobehub/lobe-write.git' }],
+ },
+ id: 'env_repo01',
+ name: 'Writer',
+};
+const plainEnv = { id: 'env_plain02', name: 'Data tools' };
+
+describe('environmentFolderName', () => {
+ it("is named after the environment's repository, with a piece of its id", () => {
+ expect(environmentFolderName(repoEnv)).toBe('lobe-write-repo01');
+ });
+
+ it('is named after the environment without a repository', () => {
+ expect(environmentFolderName(plainEnv)).toBe('Data tools-lain02');
+ });
+
+ // Two environments of one repository must not share a folder: the setup
+ // only runs in an empty one, so the second would keep the first's checkout.
+ it('keeps two environments of the same repository apart', () => {
+ expect(environmentFolderName({ ...repoEnv, id: 'env_other9' })).not.toBe(
+ environmentFolderName(repoEnv),
+ );
+ });
+
+ it('is always one visible path segment', () => {
+ expect(environmentFolderName({ id: 'x1', name: '../a/b' })).toBe('-a-b-x1');
+ expect(environmentFolderName({ id: 'x1', name: ' .hidden ' })).toBe('hidden-x1');
+ expect(environmentFolderName({ id: 'x1', name: '..' })).toBe('environment-x1');
+ });
+
+ // The server refuses a working directory starting with `~`; a folder named
+ // that way would send every run to a temporary sandbox.
+ it('never produces a name the server refuses as a working directory', () => {
+ expect(environmentFolderName({ id: 'x1', name: '~tools' })).toBe('tools-x1');
+ expect(environmentFolderName({ id: '', name: '~.~' })).toBe('environment');
+ });
+});
+
+describe('isOnPublicDrive', () => {
+ it('is a workspace folder on the drive every member browses', () => {
+ expect(isOnPublicDrive({ workingDirectory: 'team' }, 'ws')).toBe(true);
+ expect(isOnPublicDrive({ drive: 'public', workingDirectory: 'team' }, 'ws')).toBe(true);
+ });
+
+ it("is not a member's personal drive, a temporary sandbox or a personal account", () => {
+ expect(isOnPublicDrive({ drive: 'personal', workingDirectory: 'mine' }, 'ws')).toBe(false);
+ expect(isOnPublicDrive({ environmentId: 'env' }, 'ws')).toBe(false);
+ expect(isOnPublicDrive({ workingDirectory: 'notes' }, null)).toBe(false);
+ });
+});
- it('clones a repository into a temporary sandbox', () => {
- expect(repositorySelection(repo)).toEqual({ environmentId: 'env-repo' });
+describe('selectionWithEnvironment', () => {
+ it('only changes the environment off the drive', () => {
+ expect(selectionWithEnvironment({}, repoEnv)).toEqual({ environmentId: 'env_repo01' });
+ expect(selectionWithEnvironment({ environmentId: 'env_repo01' })).toEqual({});
+ });
+
+ it("moves a drive conversation into the environment's own folder", () => {
+ expect(
+ selectionWithEnvironment({ drive: 'personal', workingDirectory: 'notes' }, repoEnv),
+ ).toEqual({
+ drive: 'personal',
+ environmentId: 'env_repo01',
+ workingDirectory: 'lobe-write-repo01',
+ });
+ });
+
+ it('keeps the folder when the environment is cleared on the drive', () => {
+ expect(
+ selectionWithEnvironment({
+ environmentId: 'env_repo01',
+ workingDirectory: 'lobe-write-repo01',
+ }),
+ ).toEqual({ workingDirectory: 'lobe-write-repo01' });
+ });
+
+ it('replaces a legacy environment directory', () => {
+ expect(selectionWithEnvironment({ instanceId: 'inst-1' }, plainEnv)).toEqual({
+ environmentId: 'env_plain02',
+ workingDirectory: 'Data tools-lain02',
+ });
+ expect(selectionWithEnvironment({ instanceId: 'inst-1' })).toEqual({});
+ });
+});
+
+describe('selectionWithFolder', () => {
+ it('keeps the environment when a folder is picked', () => {
+ expect(
+ selectionWithFolder(
+ { environmentId: 'env_repo01', instanceId: 'inst-1' },
+ {
+ drive: 'public',
+ workingDirectory: 'team',
+ },
+ ),
+ ).toEqual({ drive: 'public', environmentId: 'env_repo01', workingDirectory: 'team' });
});
});
diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
index 704212b9946..aeec977e0d0 100644
--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
@@ -1,3 +1,4 @@
+import { isSafeSandboxCwd } from '@lobechat/builtin-tool-cloud-sandbox';
import type { EnvironmentConfiguration } from '@lobechat/types';
import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';
@@ -101,12 +102,85 @@ export const environmentSettingsPath = (projectId?: string) =>
projectId ? getProjectSettingsPath(projectId, 'environments') : '/settings/environments';
/**
- * 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.
+ * The folder an environment is set up in when the conversation keeps its files
+ * on the drive: one of its own, named after the repository it checks out (or
+ * the environment itself) plus a short piece of its id, at the top of the
+ * drive. The id keeps two environments of the same repository — different
+ * refs, setup or variables — and a folder of the person's own apart: the
+ * setup only runs in an empty folder, so a shared one would keep the first
+ * environment's checkout under the second's name. The server creates it on
+ * the first run, and the next conversation that picks the environment finds
+ * the checkout already there.
*/
-export const repositorySelection = (environment: { id: string }): SandboxSelection => ({
- environmentId: environment.id,
+export const environmentFolderName = (environment: {
+ configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;
+ id: string;
+ name: string;
+}): string => {
+ const base = repositorySlug(environment)?.split('/').pop() || environment.name;
+ const suffix = environment.id.replaceAll(/[^\dA-Za-z]/g, '').slice(-6);
+ // A single path segment the drive accepts: no separators, no leading dot
+ // (hidden, and `.`/`..` are not folders) or `~`, no surrounding whitespace.
+ // Checked with the server's own rule at the end: a name it refuses would
+ // send every run to a temporary sandbox while the chip names the folder.
+ const name = base
+ .replaceAll(/[/\\]+/g, '-')
+ .trim()
+ .replace(/^[.~]+/, '')
+ .slice(0, 56)
+ .trim();
+ const folder = [name || 'environment', suffix].filter(Boolean).join('-');
+ return isSafeSandboxCwd(folder) ? folder : 'environment';
+};
+
+/**
+ * Whether a selection works in a folder of a workspace's public drive, which
+ * every member can browse. In a workspace a folder with no drive named is on
+ * the public one.
+ */
+export const isOnPublicDrive = (selection: SandboxSelection, workspaceId?: string | null) =>
+ !!workspaceId &&
+ !selection.instanceId &&
+ selection.workingDirectory !== undefined &&
+ selection.drive !== 'personal';
+
+/**
+ * The selection once an environment (or none) is picked. On the drive, an
+ * environment moves the conversation into that environment's own folder, so
+ * it is set up rather than skipped in a folder that already holds files;
+ * none keeps the folder. Off the drive only the environment changes. A
+ * legacy environment directory is replaced either way.
+ */
+export const selectionWithEnvironment = (
+ selection: SandboxSelection,
+ environment?: Parameters<typeof environmentFolderName>[0] & { id: string },
+): SandboxSelection => {
+ const onDrive = !!selection.instanceId || selection.workingDirectory !== undefined;
+ if (!onDrive) return environment ? { environmentId: environment.id } : {};
+
+ if (!environment) {
+ if (selection.instanceId) return {};
+ return selection.drive
+ ? { drive: selection.drive, workingDirectory: selection.workingDirectory }
+ : { workingDirectory: selection.workingDirectory };
+ }
+
+ return {
+ ...(selection.drive && { drive: selection.drive }),
+ environmentId: environment.id,
+ workingDirectory: environmentFolderName(environment),
+ };
+};
+
+/**
+ * The selection once a folder of the drive is picked: the environment stays,
+ * and is set up there if the folder is empty.
+ */
+export const selectionWithFolder = (
+ selection: SandboxSelection,
+ folder: Pick<SandboxSelection, 'drive' | 'workingDirectory'>,
+): SandboxSelection => ({
+ ...(folder.drive && { drive: folder.drive }),
+ ...(selection.environmentId && { environmentId: selection.environmentId }),
+ workingDirectory: folder.workingDirectory,
});
diff --git a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts
index 56077458285..175ae36d422 100644
--- a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts
+++ b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.test.ts
@@ -51,8 +51,9 @@ describe('useFollowSandboxModePreference', () => {
expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: 'notes' });
});
- it('drops a bare temporary sandbox when the agent turns persistent', () => {
- setPendingSandboxSelection(AGENT, {});
+ // T-14791: the temporary default now carries the agent's environment too.
+ it('drops the seeded temporary default when the agent turns persistent', () => {
+ seedPendingSandboxSelection(AGENT, { environmentId: 'env-1' });
const { rerender } = renderFollow(true);
rerender({ hasTopic: false, temporary: false });
@@ -60,6 +61,15 @@ describe('useFollowSandboxModePreference', () => {
expect(getPendingSandboxSelection(AGENT)).toBeUndefined();
});
+ it('keeps the drive switched off for this conversation', () => {
+ setPendingSandboxSelection(AGENT, {});
+ const { rerender } = renderFollow(true);
+
+ rerender({ hasTopic: false, temporary: false });
+
+ expect(getPendingSandboxSelection(AGENT)).toEqual({});
+ });
+
it('keeps a repository picked for this conversation', () => {
setPendingSandboxSelection(AGENT, { environmentId: 'env-1' });
const { rerender } = renderFollow(true);
diff --git a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts
index 9304100fcde..e5b82745d5a 100644
--- a/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts
+++ b/src/features/ChatInput/ControlBar/useFollowSandboxModePreference.ts
@@ -9,28 +9,24 @@ import {
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:
+ * What a conversation not started yet should drop when the agent's drive
+ * preference changes under it — typically from another tab, whose switch only
+ * reaches this one through the storage event: a default seeded the other way
+ * — on the drive while it is now off, or off it while it is now on.
*
- * - 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.
+ * Anything picked for this conversation (the drive switch, a folder, an
+ * environment) 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;
+ isSeededSandboxSelection(pending) && isPersistentSelection(pending) === temporary;
/**
* 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
+ * cannot pick the mode is not moved by it either. Must
* run before the default is seeded, so an emptied slot is filled in the same
* pass.
*/
@@ -42,7 +38,7 @@ export const useFollowSandboxModePreference = (
scopeKey,
temporary,
}: {
- /** Whether the mode is picked in the environment menu for this member. */
+ /** Whether this member can switch the drive. */
enabled: boolean;
hasTopic: boolean;
/** Whose preference `temporary` is: user, workspace and agent. */
diff --git a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts
index 4cd5346508a..6002605bc0d 100644
--- a/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxEnvironmentList.ts
@@ -59,18 +59,22 @@ export const useProjectSandboxEnvironments = (
* workspace's shared environments. Only the list in use is fetched.
*/
export const useSandboxEnvironmentList = ({
+ enabled = true,
projectId,
sharedAgent,
workspaceId,
}: {
+ /** Whether the list is needed yet; nothing is fetched until it is. */
+ enabled?: boolean;
projectId?: string;
sharedAgent: boolean;
workspaceId?: string | null;
}): SandboxEnvironmentList => {
- const shared = useSWR(projectId ? null : ['sandbox-environment-chip', workspaceId ?? ''], () =>
- environmentService.listEnvironments(),
+ const shared = useSWR(
+ enabled && !projectId ? ['sandbox-environment-chip', workspaceId ?? ''] : null,
+ () => environmentService.listEnvironments(),
);
- const project = useProjectSandboxEnvironments(projectId, sharedAgent);
+ const project = useProjectSandboxEnvironments(projectId, sharedAgent, enabled);
if (projectId) return project;
diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts
deleted file mode 100644
index e1ab91ed5d7..00000000000
--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.test.ts
+++ /dev/null
@@ -1,333 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- getRememberedSandboxRepository,
- rememberSandboxSelection,
-} from './rememberedSandboxDirectory';
-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',
- projectId: undefined as string | undefined,
- /** Whether the project's environment list has loaded, and what a refetch brings. */
- projectLoaded: true,
- refreshProject: vi.fn(),
- storeEnvironments: {} as Record<string, unknown[]>,
- seedPendingSandboxSelection: vi.fn(),
- setPendingSandboxSelection: 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,
- setPendingSandboxSelection: state.setPendingSandboxSelection,
-}));
-const PROJECT_ENVIRONMENTS: Record<string, { configuration: unknown; id: string }[]> = {
- 'project-1': [
- {
- configuration: { sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobe-write' }] },
- id: 'env-project',
- },
- ],
- 'project-empty': [{ configuration: { sources: [] }, id: 'env-empty' }],
-};
-vi.mock('./useSandboxEnvironmentList', () => ({
- useIsSharedAgent: () => false,
- useProjectSandboxEnvironments: (projectId?: string) => ({
- environments: projectId && state.projectLoaded ? (PROJECT_ENVIRONMENTS[projectId] ?? []) : [],
- loaded: state.projectLoaded,
- refresh: state.refreshProject,
- }),
-}));
-vi.mock('@/store/projectWorkingDirectory', () => ({
- useProjectDirectoryStore: { getState: () => ({ environmentsMap: state.storeEnvironments }) },
-}));
-vi.mock('./useSandboxStorageAccess', () => ({
- useSandboxDriveStatus: () => state.driveStatus,
-}));
-vi.mock('./useSandboxPlacement', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- useSandboxPlacement: () => ({
- projectId: state.projectId,
- 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.clear();
- state.driveStatus = 'ready';
- state.projectId = undefined;
- state.projectLoaded = true;
- state.storeEnvironments = {};
- state.refreshProject.mockReset().mockResolvedValue(undefined);
- state.selection = {};
- state.topicId = undefined;
- state.workspaceId = null;
- state.seedPendingSandboxSelection.mockReset();
- state.setPendingSandboxSelection.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: '.',
- });
- });
-
- // T-14158: switching back to the persistent sandbox starts in the folder the
- // agent's last conversation used, like a new conversation does.
- it('gives a conversation back the remembered folder', async () => {
- rememberSandboxSelection(ME, 'agent-1', { workingDirectory: 'projects/demo' });
-
- const { result } = renderMode();
- await act(() => result.current.toPersistent());
-
- expect(state.seedPendingSandboxSelection).toHaveBeenCalledWith('agent-1', {
- workingDirectory: 'projects/demo',
- });
- });
-
- // Leaving the drive, a conversation starts from the repository the agent's
- // last temporary sandbox used.
- it('moves a conversation off the drive onto the remembered repository', async () => {
- state.topicId = 'topic-1';
- state.selection = { workingDirectory: 'notes' } satisfies SandboxSelection;
- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_repo' });
-
- const { result } = renderMode();
- await act(() => result.current.toTemporary());
-
- expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env_repo' });
- });
-
- it('remembers the repository a conversation leaves the drive with', async () => {
- state.topicId = 'topic-1';
- state.selection = {
- environmentId: 'env_old',
- workingDirectory: 'notes',
- } satisfies SandboxSelection;
-
- const { result } = renderMode();
- await act(() => result.current.toTemporary());
-
- expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env_old' });
- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_old' });
- });
-
- 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);
- });
-});
-
-// A project conversation leaving the drive starts from its project's
-// environment, never the agent's repository from elsewhere — which the chip,
-// listing the project's environment only, would call unavailable.
-describe('useSandboxModeSelect in a project conversation', () => {
- beforeEach(() => {
- rememberSandboxSelection(ME, 'agent-1', { environmentId: 'env_repo' });
- state.selection = { workingDirectory: 'notes' };
- });
-
- it("moves an open conversation onto the project's environment and remembers nothing", async () => {
- state.projectId = 'project-1';
- state.topicId = 'topic-1';
- const { result } = renderMode();
-
- await act(() => result.current.toTemporary());
-
- expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env-project' });
- expect(getRememberedSandboxRepository(ME, 'agent-1')).toEqual({ environmentId: 'env_repo' });
- });
-
- // An open topic keeps what is written now; the server applies the project's
- // environment only when it creates one, so "none" is not written on a guess.
- it("waits for the project's environment before moving an open conversation", async () => {
- state.projectId = 'project-1';
- state.topicId = 'topic-1';
- state.projectLoaded = false;
- state.refreshProject.mockImplementation(async () => {
- state.storeEnvironments['project-1'] = PROJECT_ENVIRONMENTS['project-1'];
- });
- const { result } = renderMode();
-
- await act(() => result.current.toTemporary());
-
- expect(state.refreshProject).toHaveBeenCalled();
- expect(state.setSelection).toHaveBeenCalledWith({ environmentId: 'env-project' });
- });
-
- it("keeps an open conversation on the drive when the project's environment cannot load", async () => {
- state.projectId = 'project-1';
- state.topicId = 'topic-1';
- state.projectLoaded = false;
- const { result } = renderMode();
-
- await expect(act(() => result.current.toTemporary())).rejects.toThrow('could not be loaded');
-
- expect(state.setSelection).not.toHaveBeenCalled();
- expect(prefersTemporarySandbox(ME, 'agent-1')).toBe(false);
- });
-
- it('moves an open conversation onto no environment when the project checks out none', async () => {
- state.projectId = 'project-empty';
- state.topicId = 'topic-1';
- const { result } = renderMode();
-
- await act(() => result.current.toTemporary());
-
- expect(state.setSelection).toHaveBeenCalledWith({});
- });
-
- // Before a topic exists, a default rather than a pick: the server still
- // applies the project's environment.
- it("gives a project draft the project's environment as a default", async () => {
- state.projectId = 'project-1';
- const { result } = renderMode();
-
- await act(() => result.current.toTemporary());
-
- expect(state.seedPendingSandboxSelection).toHaveBeenCalledWith('agent-1', {
- environmentId: 'env-project',
- });
- expect(state.setSelection).not.toHaveBeenCalled();
- });
-
- it('leaves a project draft to the server when the project checks out none', async () => {
- state.projectId = 'project-empty';
- const { result } = renderMode();
-
- await act(() => result.current.toTemporary());
-
- expect(state.setPendingSandboxSelection).toHaveBeenCalledWith('agent-1');
- expect(state.setSelection).not.toHaveBeenCalled();
- });
-});
diff --git a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts b/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts
deleted file mode 100644
index d245eab5775..00000000000
--- a/src/features/ChatInput/ControlBar/useSandboxModeSelect.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { useCallback } from 'react';
-
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import {
- seedPendingSandboxSelection,
- setPendingSandboxSelection,
-} from '@/store/chat/pendingSandboxSelection';
-import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-
-import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';
-import {
- getRememberedSandboxDirectory,
- getRememberedSandboxRepository,
- rememberSandboxSelection,
-} from './rememberedSandboxDirectory';
-import { pickableEnvironments, projectStartEnvironmentId } from './sandboxEnvironmentOptions';
-import { setPrefersTemporarySandbox } from './temporarySandboxPreference';
-import { useIsSharedAgent, useProjectSandboxEnvironments } from './useSandboxEnvironmentList';
-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 {
- projectId,
- selection,
- setSelection,
- topicId: scopeTopicId,
- } = useSandboxPlacement(agentId, topicId);
- const onDrive = isPersistentSelection(selection);
- const sharedAgent = useIsSharedAgent(agentId);
- const {
- environments: projectEnvironments,
- loaded: projectEnvironmentsLoaded,
- refresh: refreshProjectEnvironments,
- } = useProjectSandboxEnvironments(projectId, sharedAgent, enabled);
- const projectEnvironmentId = projectStartEnvironmentId(projectEnvironments);
-
- // A topic that exists keeps whatever is written now: the server applies the
- // project's environment only when it creates one. Until the project's list
- // has loaded, "none" is not known to be right, so it is asked for once more;
- // still unknown, the move fails and the conversation stays on the drive.
- const resolveProjectEnvironmentId = useCallback(async () => {
- if (projectEnvironmentsLoaded || !projectId) return projectEnvironmentId;
- await refreshProjectEnvironments();
- const rows = useProjectDirectoryStore.getState().environmentsMap[projectId];
- if (!rows) throw new Error(`The environment of project ${projectId} could not be loaded`);
- return projectStartEnvironmentId(pickableEnvironments(rows, sharedAgent));
- }, [
- projectEnvironmentId,
- projectEnvironmentsLoaded,
- projectId,
- refreshProjectEnvironments,
- sharedAgent,
- ]);
-
- 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.
- // Leaving the drive, the conversation starts from the repository the
- // agent's last temporary sandbox used, or none.
- if (onDrive && projectId) {
- // A project conversation starts from its project's environment, never the
- // agent's repository from elsewhere, and is not remembered for it. Before
- // a topic exists it is a default, so the server still applies the
- // project's; with none, the server decides.
- if (scopeTopicId) {
- const environmentId = await resolveProjectEnvironmentId();
- await setSelection(environmentId ? { environmentId } : {});
- } else if (projectEnvironmentId)
- seedPendingSandboxSelection(agentId, { environmentId: projectEnvironmentId });
- else setPendingSandboxSelection(agentId);
- } else if (onDrive) {
- const next =
- getRememberedSandboxRepository({ userId, workspaceId }, agentId) ??
- temporarySelection(selection);
- await setSelection(next);
- // What the conversation now runs on is what the next temporary sandbox
- // starts from, as a pick in the chip would be.
- rememberSandboxSelection({ userId, workspaceId }, agentId, next);
- }
- setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);
- }, [
- agentId,
- driveStatus,
- onDrive,
- projectEnvironmentId,
- projectId,
- resolveProjectEnvironmentId,
- scopeTopicId,
- selection,
- setSelection,
- userId,
- workspaceId,
- ]);
-
- const toPersistent = useCallback(async () => {
- if (!onDrive) {
- // Back on the drive in the folder the agent's last conversation used,
- // the same default a new conversation gets.
- const next = resolveDefaultSandboxSelection(
- workspaceId,
- getRememberedSandboxDirectory({ userId, workspaceId }, agentId),
- );
- // 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);
- rememberSandboxSelection({ userId, workspaceId }, agentId, 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/useSandboxOptions.ts b/src/features/ChatInput/ControlBar/useSandboxOptions.ts
new file mode 100644
index 00000000000..20cc6fd9203
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useSandboxOptions.ts
@@ -0,0 +1,148 @@
+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
+import { useCallback } from 'react';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { rememberSandboxSelection } from './rememberedSandboxDirectory';
+import type { SandboxDriveFolderPick } from './SandboxDriveMenu';
+import { isOnPublicDrive, selectionWithFolder } from './sandboxEnvironmentOptions';
+import type { SandboxRepositoryOption } from './SandboxRepositoryMenu';
+import { setPrefersTemporarySandbox } from './temporarySandboxPreference';
+import { useIsSharedAgent, useSandboxEnvironmentList } from './useSandboxEnvironmentList';
+import {
+ isPersistentSelection,
+ type SandboxSelection,
+ useSandboxPlacement,
+} from './useSandboxPlacement';
+
+/**
+ * Whether the plan includes a drive, asked whenever the cloud sandbox's options
+ * could be shown — before the sandbox is picked, not only once it runs there.
+ *
+ * - `hidden` — no drive service in this deployment (self-hosted);
+ * - `loading` — not known yet: a pick still moves the conversation as asked;
+ * - `upgrade` — no drive on this plan; the drive option leads to one;
+ * - `ready` — entitled.
+ */
+export type SandboxDriveStatus = 'hidden' | 'loading' | 'ready' | 'upgrade';
+
+const useSandboxDriveStatus = (enabled: boolean): SandboxDriveStatus => {
+ const shouldAsk = ENABLE_BUSINESS_FEATURES && enabled;
+ sandboxActions.useFetchEntitlement(shouldAsk, { revalidateOnFocus: false });
+ const data = useSandboxStore(sandboxSelectors.entitlement);
+
+ if (!shouldAsk) return 'hidden';
+ if (!data) return 'loading';
+ return data.entitled ? 'ready' : 'upgrade';
+};
+
+/**
+ * The cloud sandbox's two options — whether it keeps its files on the drive
+ * (and in which folder), and the environment it is set up from — read and
+ * written from one place. The execution-environment menu offers them under
+ * its 云端沙箱 row and its chip names them; new conversations are seeded by
+ * `SandboxStorageSection`, which this hook leaves alone.
+ *
+ * `topicId` is the conversation the caller belongs to; `null` means it has no
+ * topic yet.
+ */
+export const useSandboxOptions = (
+ agentId: string,
+ { enabled, topicId: scopeTopicId }: { enabled: boolean; topicId: string | null },
+) => {
+ const driveStatus = useSandboxDriveStatus(enabled);
+ const { projectId, selection, setSelection, topicId } = useSandboxPlacement(
+ agentId,
+ scopeTopicId,
+ );
+ const workspaceId = useActiveWorkspaceId();
+ const userId = useUserStore(userProfileSelectors.userId);
+ const sharedAgent = useIsSharedAgent(agentId);
+ const environmentList = useSandboxEnvironmentList({
+ enabled,
+ projectId,
+ sharedAgent,
+ workspaceId,
+ });
+ const { environments } = environmentList;
+
+ // Every pick that lands is remembered for the next conversation: the folder,
+ // and the environment (or none). A failed save is not, and neither is an
+ // environment picked inside a project: it belongs to that project, and the
+ // agent's next conversation elsewhere could not use it. A drive folder is
+ // usable anywhere.
+ //
+ // Every member can browse the workspace's public drive, so a private
+ // environment — or one not known to be published — is not carried into a
+ // folder there: the server would not apply it, and the menu would name a
+ // setup that never runs.
+ const pick = useCallback(
+ async (
+ picked: SandboxSelection,
+ { environment: given }: { environment?: SandboxRepositoryOption } = {},
+ ) => {
+ // An environment whose visibility is not known — the list still loading
+ // or failed — is treated as private: it is only known to be published
+ // once the list, or the pick itself (one just created, which this
+ // render's list cannot hold yet), says so.
+ const environment =
+ given?.id === picked.environmentId
+ ? given
+ : environments.find((item) => item.id === picked.environmentId);
+ const next =
+ picked.environmentId &&
+ environment?.visibility !== 'public' &&
+ isOnPublicDrive(picked, workspaceId)
+ ? { ...picked, environmentId: undefined }
+ : picked;
+ await setSelection(next);
+ rememberSandboxSelection({ userId, workspaceId }, agentId, next, {
+ folderOnly: !!projectId,
+ });
+ },
+ [agentId, environments, projectId, setSelection, userId, workspaceId],
+ );
+
+ // Storage is picked one level under its row: a temporary sandbox, or a
+ // folder of the drive. Either keeps the environment. Outside a project the
+ // pick is also where the agent's new conversations start.
+ const toTemporary = useCallback(async () => {
+ await pick(selection.environmentId ? { environmentId: selection.environmentId } : {});
+ if (!projectId) setPrefersTemporarySandbox({ userId, workspaceId }, agentId, true);
+ }, [agentId, pick, projectId, selection.environmentId, userId, workspaceId]);
+
+ const pickFolder = useCallback(
+ async (folder: SandboxDriveFolderPick) => {
+ const next = selectionWithFolder(selection, folder);
+ await pick(next);
+ if (!projectId) setPrefersTemporarySandbox({ userId, workspaceId }, agentId, false);
+ return next;
+ },
+ [agentId, pick, projectId, selection, userId, workspaceId],
+ );
+
+ const entitled = driveStatus === 'ready';
+ // While the entitlement loads, the placement the conversation already has
+ // is still what it runs on — said as such rather than as temporary.
+ const onDrive =
+ (driveStatus === 'ready' || driveStatus === 'loading') && isPersistentSelection(selection);
+
+ return {
+ driveStatus,
+ entitled,
+ environmentList,
+ onDrive,
+ onPublicDrive: onDrive && isOnPublicDrive(selection, workspaceId),
+ pick,
+ pickFolder,
+ projectId,
+ selection,
+ sharedAgent,
+ toTemporary,
+ topicId,
+ workspaceId,
+ };
+};
diff --git a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
index 5ed412a615d..5aa07d78129 100644
--- a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
@@ -83,20 +83,3 @@ export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessRe
status: 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/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
index cf839de1071..31515157fc2 100644
--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
@@ -15,13 +15,32 @@ import { userProfileSelectors } from '@/store/user/selectors';
import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';
import {
getRememberedSandboxDirectory,
+ getRememberedSandboxDirectoryEnvironment,
getRememberedSandboxRepository,
} from './rememberedSandboxDirectory';
+/**
+ * The drive default with the environment picked together with that folder, so
+ * a folder and its environment come back together — and only together: an
+ * environment from elsewhere would skip its setup in a folder that has files.
+ */
+const driveDefault = (
+ scope: { userId?: string | null; workspaceId?: string | null },
+ agentId: string,
+) => {
+ const remembered = getRememberedSandboxDirectory(scope, agentId);
+ const folder = resolveDefaultSandboxSelection(scope.workspaceId, remembered);
+ const environmentId = remembered
+ ? getRememberedSandboxDirectoryEnvironment(scope, agentId)
+ : undefined;
+ return environmentId ? { ...folder, environmentId } : folder;
+};
+
/**
* Give a conversation that does not exist yet the plan's default place to
* work: an account with a drive keeps its files unless it says otherwise, in the
- * folder the agent's last conversation was put in when there is one. Only
+ * folder the agent's last conversation was put in when there is one, set up
+ * from the environment it used. Only
* fills an empty slot — a pick, including the temporary sandbox, stays — and
* only before the topic exists, so a conversation already running never moves.
* Sending consumes the slot, and the next new conversation is seeded again.
@@ -46,13 +65,7 @@ export const useSeedDefaultSelection = (
useEffect(() => {
if (!eligible) return;
- setSandboxDefaultSelection(
- agentId,
- resolveDefaultSandboxSelection(
- workspaceId,
- getRememberedSandboxDirectory({ userId, workspaceId }, agentId),
- ),
- );
+ setSandboxDefaultSelection(agentId, driveDefault({ userId, workspaceId }, agentId));
return () => setSandboxDefaultSelection(agentId);
}, [agentId, eligible, hasTopic, userId, workspaceId]);
@@ -64,20 +77,14 @@ export const useSeedDefaultSelection = (
const pending = getPendingSandboxSelection(agentId);
if (pending && !isSeededSandboxSelection(pending)) return;
- seedPendingSandboxSelection(
- agentId,
- resolveDefaultSandboxSelection(
- workspaceId,
- getRememberedSandboxDirectory({ userId, workspaceId }, agentId),
- ),
- );
+ seedPendingSandboxSelection(agentId, driveDefault({ userId, workspaceId }, agentId));
}, [agentId, entitled, hasTopic, userId, workspaceId]);
};
/**
* The temporary sandbox's counterpart: a conversation that does not exist yet,
- * for an agent whose new conversations start in the temporary sandbox, starts
- * from the repository the agent's last temporary sandbox used — or from none,
+ * for an agent whose new conversations start with the drive off, starts
+ * from the environment the agent's last conversation used — or from none,
* which is the temporary sandbox's own default and needs nothing filled in.
*
* Filled in as a default rather than a pick, the same as the folder: a pick