🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(sandbox): graduate persistent sandbox and default paid users to their drive (#22032)
Rdmclin2e8cb69c538f7
diff --git a/apps/server/src/routers/lambda/sandboxStorage/procedures.ts b/apps/server/src/routers/lambda/sandboxStorage/procedures.tsindex dc552a4e01b..7e32d1dd2e2 100644--- a/apps/server/src/routers/lambda/sandboxStorage/procedures.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/procedures.ts@@ -87,7 +87,6 @@ export const storageClaimProcedure = wsCompatProcedure.use(serverDatabase).use(aconst drives = createDriveAccess({resolveClaim: resolveSandboxStorageClaim,- serverDB: ctx.serverDB,userId: ctx.userId,workspaceId,});diff --git a/apps/server/src/services/sandbox/__tests__/entitlement.test.ts b/apps/server/src/services/sandbox/__tests__/entitlement.test.tsindex 92671cd0abe..20255540269 100644--- a/apps/server/src/services/sandbox/__tests__/entitlement.test.ts+++ b/apps/server/src/services/sandbox/__tests__/entitlement.test.ts@@ -1,28 +1,17 @@-import type { LobeChatDatabase } from '@lobechat/database';import { beforeEach, describe, expect, it, vi } from 'vitest';const resolveSandboxStorageEntitlement = vi.fn();-const getUserPreference = vi.fn();vi.mock('@/business/server/sandboxStorage', () => ({resolveSandboxStorageEntitlement: (...args: unknown[]) =>resolveSandboxStorageEntitlement(...args),}));-vi.mock('@/database/models/user', () => ({- UserModel: vi.fn(function () {- return { getUserPreference };- }),-}));-const { resolveSandboxStorageClaim } = await import('../entitlement');-const serverDB = {} as LobeChatDatabase;-const resolve = (overrides: Record<string, unknown> = {}) =>resolveSandboxStorageClaim({isShareVisitorRun: false,- serverDB,userId: 'user_1',...overrides,});@@ -30,8 +19,6 @@ const resolve = (overrides: Record<string, unknown> = {}) =>describe('resolveSandboxStorageClaim', () => {beforeEach(() => {resolveSandboxStorageEntitlement.mockReset();- getUserPreference.mockReset();- getUserPreference.mockResolvedValue({ lab: { enablePersistentSandbox: true } });resolveSandboxStorageEntitlement.mockResolvedValue({ quotaBytes: 2048 });});@@ -48,7 +35,7 @@ describe('resolveSandboxStorageClaim', () => {});await expect(- resolveSandboxStorageClaim({ isShareVisitorRun: false, serverDB: {} as any, userId: 'u1' }),+ resolveSandboxStorageClaim({ isShareVisitorRun: false, userId: 'u1' }),).resolves.toMatchObject({ overageAllowed: true });resolveSandboxStorageEntitlement.mockResolvedValue({ quotaBytes: 2048 });@@ -56,7 +43,6 @@ describe('resolveSandboxStorageClaim', () => {expect(await resolveSandboxStorageClaim({isShareVisitorRun: false,- serverDB: {} as any,userId: 'u1',}),).not.toHaveProperty('overageAllowed');@@ -75,15 +61,14 @@ describe('resolveSandboxStorageClaim', () => {});});- // The lab flag is the whole feature's gate: without a claim the execution- // plane routes to the ephemeral sandbox whatever mode the request asks for.- it('issues nothing until the lab experiment is switched on', async () => {- for (const lab of [undefined, {}, { enablePersistentSandbox: false }]) {- getUserPreference.mockResolvedValue(lab === undefined ? undefined : { lab });- await expect(resolve()).resolves.toBeNull();- }+ // The plan is the whole feature's gate: no opt-in stands between an entitled+ // account and its drive, and without a claim the execution plane routes to+ // the ephemeral sandbox whatever mode the request asks for.+ it('is decided by the plan alone, with no opt-in', async () => {+ await expect(resolve()).resolves.toEqual({ key: 'ws-user_1', quotaBytes: 2048 });- expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();+ resolveSandboxStorageEntitlement.mockResolvedValue(undefined);+ await expect(resolve()).resolves.toBeNull();});// A share visitor's run executes under the CREATOR's identity, so every input@@ -92,7 +77,6 @@ describe('resolveSandboxStorageClaim', () => {it('issues nothing for a share-visitor run, without reading the creator at all', async () => {await expect(resolve({ isShareVisitorRun: true })).resolves.toBeNull();- expect(getUserPreference).not.toHaveBeenCalled();expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();});@@ -113,20 +97,15 @@ describe('resolveSandboxStorageClaim', () => {});// An unsafe id costs persistence, not the whole request.- it('skips both lookups when no safe key can be derived', async () => {+ it('skips the lookup when no safe key can be derived', async () => {await expect(resolve({ userId: '../etc/passwd' })).resolves.toBeNull();- expect(getUserPreference).not.toHaveBeenCalled();expect(resolveSandboxStorageEntitlement).not.toHaveBeenCalled();});- // Losing either lookup must degrade to an ephemeral sandbox — the behaviour- // every session has today — not fail the tool call.- it('degrades to no entitlement when a lookup throws', async () => {- getUserPreference.mockRejectedValue(new Error('db down'));- await expect(resolve()).resolves.toBeNull();-- getUserPreference.mockResolvedValue({ lab: { enablePersistentSandbox: true } });+ // Losing the lookup must degrade to an ephemeral sandbox — the behaviour+ // every free session has — not fail the tool call.+ it('degrades to no entitlement when the lookup throws', async () => {resolveSandboxStorageEntitlement.mockRejectedValue(new Error('entitlement lookup failed'));await expect(resolve()).resolves.toBeNull();});diff --git a/apps/server/src/services/sandbox/driveAccess.ts b/apps/server/src/services/sandbox/driveAccess.tsindex 27bb21832ce..c1a1356ac73 100644--- a/apps/server/src/services/sandbox/driveAccess.ts+++ b/apps/server/src/services/sandbox/driveAccess.ts@@ -4,7 +4,6 @@ import {sandboxDriveOfKey,type SandboxStorageClaim,} from '@lobechat/builtin-tool-cloud-sandbox';-import type { LobeChatDatabase } from '@lobechat/database';import { MarketService } from '@/server/services/market';@@ -13,7 +12,6 @@ import type { resolveSandboxStorageClaim } from './entitlement';interface DriveAccessInput {/** Handed in rather than imported, so a caller's own seam for it is the one used. */resolveClaim: typeof resolveSandboxStorageClaim;- serverDB: LobeChatDatabase;userId: string;workspaceId?: string;}@@ -26,12 +24,7 @@ interface DriveAccessInput {* drive out of every other member's reach — they would need a claim for its* key, and nothing built on this issues one.*/-export const createDriveAccess = ({- resolveClaim,- serverDB,- userId,- workspaceId,-}: DriveAccessInput) => {+export const createDriveAccess = ({ resolveClaim, userId, workspaceId }: DriveAccessInput) => {const claims = new Map<SandboxDrive, Promise<SandboxStorageClaim | null>>();const claim = (drive: SandboxDrive) => {@@ -41,7 +34,6 @@ export const createDriveAccess = ({const pending = resolveClaim({drive,isShareVisitorRun: false,- serverDB,userId,workspaceId,});diff --git a/apps/server/src/services/sandbox/entitlement.ts b/apps/server/src/services/sandbox/entitlement.tsindex 825e7a327bf..dc29cc45c1d 100644--- a/apps/server/src/services/sandbox/entitlement.ts+++ b/apps/server/src/services/sandbox/entitlement.ts@@ -3,11 +3,9 @@ import {type SandboxStorageClaim,type SandboxStorageScope,} from '@lobechat/builtin-tool-cloud-sandbox';-import type { LobeChatDatabase } from '@lobechat/database';import debug from 'debug';import { resolveSandboxStorageEntitlement } from '@/business/server/sandboxStorage';-import { UserModel } from '@/database/models/user';const log = debug('lobe-server:sandbox:entitlement');@@ -15,14 +13,13 @@ export interface SandboxStorageClaimInput extends SandboxStorageScope {/*** Whether this run is an Agent Share visitor's. Required rather than optional:* such a run executes under the CREATOR's identity, so every input this- * function reads — the lab flag, the plan, the key — describes the creator,- * not the person at the keyboard. Issuing a claim would hand a visitor the+ * function reads — the plan, the key — describes the creator, not the+ * person at the keyboard. Issuing a claim would hand a visitor the* creator's working directory, with everything their other conversations left* in it, to read and overwrite. Making the caller state it means a new call* site cannot inherit the dangerous answer by saying nothing.*/isShareVisitorRun: boolean;- serverDB: LobeChatDatabase;}/**@@ -34,22 +31,21 @@ export interface SandboxStorageClaimInput extends SandboxStorageScope {** 1. The run is the principal's own (not a share visitor's).* 2. Their identity yields a safe directory name.- * 3. They opted into the `enablePersistentSandbox` lab experiment, and their- * plan entitles them to storage.+ * 3. Their plan entitles them to storage. A deployment without the business+ * slot entitles nobody, so self-hosting never reaches the drive.** Returns `null` for "no persistent workspace", which is the shape the* execution plane reads as free tier. Without a claim its routing sends the run* to the ephemeral sandbox no matter what mode the request asks for, so this is* the single gate for the whole feature: nothing a client sends can open it.*- * Never throws: a preference or subscription lookup that fails must not take- * the sandbox down with it. The run degrades to an ephemeral sandbox, which is+ * Never throws: a subscription lookup that fails must not take the sandbox+ * down with it. The run degrades to an ephemeral sandbox, which is* what every session does today.*/export const resolveSandboxStorageClaim = async ({drive,isShareVisitorRun,- serverDB,userId,workspaceId,}: SandboxStorageClaimInput): Promise<SandboxStorageClaim | null> => {@@ -63,13 +59,6 @@ export const resolveSandboxStorageClaim = async ({if (!key) return null;try {- // Opt-in is per USER even for an organization run, like every other lab- // experiment. The consequence is worth knowing: in a workspace where only- // some members have switched it on, the shared directory is there for their- // runs and absent for everyone else's.- const preference = await new UserModel(serverDB, userId).getUserPreference();- if (preference?.lab?.enablePersistentSandbox !== true) return null;-const entitlement = await resolveSandboxStorageEntitlement({ userId, workspaceId });const quotaBytes = entitlement?.quotaBytes;if (typeof quotaBytes !== 'number' || !Number.isSafeInteger(quotaBytes) || quotaBytes <= 0) {diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.tsindex 508a56af772..afee652eb28 100644--- a/apps/server/src/services/sandbox/session.ts+++ b/apps/server/src/services/sandbox/session.ts@@ -207,7 +207,7 @@ const resolvePlacement = async ({// One claim per drive, and each is resolved at most once: the topic decides// which drive the run addresses, and a run only ever addresses one.const claimFor = (drive: SandboxDrive) =>- resolveSandboxStorageClaim({ drive, isShareVisitorRun, serverDB, userId, workspaceId });+ resolveSandboxStorageClaim({ drive, isShareVisitorRun, userId, workspaceId });if (!topicId) {const claim = await claimFor(defaultDrive);diff --git a/locales/ar/labs.json b/locales/ar/labs.jsonindex 8301474daf9..bf566cb2279 100644--- a/locales/ar/labs.json+++ b/locales/ar/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "إجراءات تحديد نص الرسالة","features.oauthApps.desc": "عرض إدارة تطبيقات OAuth في الإعدادات الشخصية وإعدادات مساحة العمل. هذه الميزة مخفية بشكل افتراضي.","features.oauthApps.title": "تطبيقات OAuth",- "features.persistentSandbox.desc": "احتفظ بالملفات التي يكتبها صندوق السحابة. يبقى دليل العمل الخاص به بعد إعادة تدوير الجلسة ويتم مشاركته عبر مواضيعك، بدلاً من التخلص منه مع الصندوق. يتطلب خطة مدفوعة؛ التنزيلات الكبيرة والاعتمادات لا تزال تنتمي إلى /tmp.",- "features.persistentSandbox.title": "صندوق الرمل الدائم","features.projects.desc": "نظم الأهداف طويلة المدى في مساحات عمل مخصصة تحتوي على وكلاء خاصين بها وقواعد معرفية ومهام.","features.projects.title": "مساحات عمل المشاريع","features.selfLearning.desc": "عرض ما تعلمه كل وكيل من الممارسة الفعلية — قاعدة القواعد الخاصة به، القواعد التي يتم استخدامها فعليًا، والطبقات التي لا تزال فارغة.",diff --git a/locales/bg-BG/labs.json b/locales/bg-BG/labs.jsonindex 8b9e0b56029..b36694f5692 100644--- a/locales/bg-BG/labs.json+++ b/locales/bg-BG/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Действия при избиране на текст в съобщения","features.oauthApps.desc": "Показване на управление на OAuth приложения в лични и работни настройки. Тази функция е скрита по подразбиране.","features.oauthApps.title": "OAuth приложения",- "features.persistentSandbox.desc": "Запазете файловете, които облачната пясъчникова среда създава. Работната директория оцелява при рециклиране на сесията и се споделя между вашите теми, вместо да бъде изтрита заедно с пясъчника. Изисква платен план; големите изтегляния и зависимости все още принадлежат в /tmp.",- "features.persistentSandbox.title": "Постоянна пясъчникова среда","features.projects.desc": "Организирайте дългосрочни цели в специални работни пространства със собствени агенти, бази знания и задачи.","features.projects.title": "Работни пространства за проекти","features.selfLearning.desc": "Показва какво всеки агент е научил от реалната практика — неговата база от правила, кои правила всъщност се използват и кои слоеве все още са празни.",diff --git a/locales/de-DE/labs.json b/locales/de-DE/labs.jsonindex 7c12f6cd0f9..829f61fb227 100644--- a/locales/de-DE/labs.json+++ b/locales/de-DE/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Aktionen zur Textauswahl in Nachrichten","features.oauthApps.desc": "Zeige die Verwaltung von OAuth-Apps in den persönlichen und Arbeitsbereichseinstellungen. Diese Funktion ist standardmäßig ausgeblendet.","features.oauthApps.title": "OAuth-Apps",- "features.persistentSandbox.desc": "Behalten Sie Dateien, die die Cloud-Sandbox schreibt. Ihr Arbeitsverzeichnis überlebt das Recycling von Sitzungen und wird über Ihre Themen hinweg geteilt, anstatt mit der Sandbox verworfen zu werden. Erfordert einen kostenpflichtigen Plan; große Downloads und Abhängigkeiten gehören weiterhin in /tmp.",- "features.persistentSandbox.title": "Persistente Sandbox","features.projects.desc": "Organisieren Sie langfristige Ziele in dedizierten Arbeitsbereichen mit eigenen Agenten, Wissensdatenbanken und Aufgaben.","features.projects.title": "Projektarbeitsbereiche","features.selfLearning.desc": "Zeigen Sie, was jeder Agent aus der Praxis gelernt hat – seine Regelbasis, welche Regeln tatsächlich verwendet werden und welche Ebenen noch leer sind.",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 8a493d58eca..29f033ff8a7 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Message Text Selection Actions","features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.","features.oauthApps.title": "OAuth Apps",- "features.persistentSandbox.desc": "Keep files the cloud sandbox writes. Its working directory survives session recycling and is shared across your topics, instead of being discarded with the sandbox. Requires a paid plan; large downloads and dependencies still belong in /tmp.",- "features.persistentSandbox.title": "Persistent Sandbox","features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.","features.projects.title": "Project Workspaces","features.selfLearning.desc": "Let every agent learn from your conversations in the background: it remembers facts, refines skills, collects lessons, and reviews its day each night. Rounds you send back become rules. Each nightly review covers at most 50 conversations. See it all under Memory → Self-evolving.",diff --git a/locales/es-ES/labs.json b/locales/es-ES/labs.jsonindex 2475001c33b..b5fbabef6d7 100644--- a/locales/es-ES/labs.json+++ b/locales/es-ES/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Acciones de Selección de Texto en Mensajes","features.oauthApps.desc": "Mostrar la gestión de aplicaciones OAuth en la configuración personal y del espacio de trabajo. Esta función está oculta por defecto.","features.oauthApps.title": "Aplicaciones OAuth",- "features.persistentSandbox.desc": "Conserva los archivos que la sandbox en la nube escribe. Su directorio de trabajo sobrevive al reciclaje de sesiones y se comparte entre tus temas, en lugar de descartarse con la sandbox. Requiere un plan de pago; las descargas grandes y las dependencias aún pertenecen a /tmp.",- "features.persistentSandbox.title": "Sandbox Persistente","features.projects.desc": "Organiza objetivos a largo plazo en espacios de trabajo dedicados con sus propios agentes, bases de conocimiento y tareas.","features.projects.title": "Espacios de Trabajo de Proyectos","features.selfLearning.desc": "Muestra lo que cada agente ha aprendido de la práctica real: su base de reglas, qué reglas se utilizan realmente y qué capas aún están en blanco.",diff --git a/locales/fa-IR/labs.json b/locales/fa-IR/labs.jsonindex 0659bc851ed..89a6c42c95f 100644--- a/locales/fa-IR/labs.json+++ b/locales/fa-IR/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "اقدامات انتخاب متن پیام","features.oauthApps.desc": "نمایش مدیریت برنامههای OAuth در تنظیمات شخصی و فضای کاری. این ویژگی بهطور پیشفرض مخفی است.","features.oauthApps.title": "برنامههای OAuth",- "features.persistentSandbox.desc": "فایلهایی که سندباکس ابری مینویسد را نگه دارید. دایرکتوری کاری آن از بازیافت جلسهها زنده میماند و بین موضوعات شما به اشتراک گذاشته میشود، به جای اینکه با سندباکس حذف شود. نیاز به یک طرح پولی دارد؛ دانلودهای بزرگ و وابستگیها همچنان در /tmp قرار میگیرند.",- "features.persistentSandbox.title": "سندباکس پایدار","features.projects.desc": "اهداف بلندمدت را در فضایهای کاری اختصاصی با عوامل، پایگاههای دانش و وظایف خود سازماندهی کنید.","features.projects.title": "فضاهای کاری پروژه","features.selfLearning.desc": "نمایش آنچه هر عامل از تمرین واقعی آموخته است — پایگاه قوانین آن، قوانینی که واقعاً استفاده میشوند و لایههایی که هنوز خالی هستند.",diff --git a/locales/fr-FR/labs.json b/locales/fr-FR/labs.jsonindex 199355ab9d6..99ffd544239 100644--- a/locales/fr-FR/labs.json+++ b/locales/fr-FR/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Actions de sélection de texte dans les messages","features.oauthApps.desc": "Afficher la gestion des applications OAuth dans les paramètres personnels et de l'espace de travail. Cette fonctionnalité est masquée par défaut.","features.oauthApps.title": "Applications OAuth",- "features.persistentSandbox.desc": "Conservez les fichiers écrits par le bac à sable cloud. Son répertoire de travail survit au recyclage des sessions et est partagé entre vos sujets, au lieu d'être supprimé avec le bac à sable. Nécessite un plan payant ; les téléchargements volumineux et les dépendances restent dans /tmp.",- "features.persistentSandbox.title": "Bac à Sable Persistant","features.projects.desc": "Organisez des objectifs à long terme dans des espaces de travail dédiés avec leurs propres agents, bases de connaissances et tâches.","features.projects.title": "Espaces de travail de projet","features.selfLearning.desc": "Montrez ce que chaque agent a appris de la pratique réelle — sa base de règles, les règles effectivement utilisées et les couches encore vides.",diff --git a/locales/it-IT/labs.json b/locales/it-IT/labs.jsonindex fbd440cb73c..0ee983afc27 100644--- a/locales/it-IT/labs.json+++ b/locales/it-IT/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Azioni di Selezione del Testo nei Messaggi","features.oauthApps.desc": "Mostra la gestione delle app OAuth nelle impostazioni personali e del workspace. Questa funzione è nascosta per impostazione predefinita.","features.oauthApps.title": "App OAuth",- "features.persistentSandbox.desc": "Conserva i file scritti dal sandbox cloud. La sua directory di lavoro sopravvive al riciclo della sessione ed è condivisa tra i tuoi argomenti, invece di essere eliminata con il sandbox. Richiede un piano a pagamento; i download di grandi dimensioni e le dipendenze appartengono comunque a /tmp.",- "features.persistentSandbox.title": "Sandbox Persistente","features.projects.desc": "Organizza obiettivi a lungo termine in spazi di lavoro dedicati con i propri agenti, basi di conoscenza e attività.","features.projects.title": "Spazi di lavoro per progetti","features.selfLearning.desc": "Mostra ciò che ogni agente ha imparato dalla pratica reale: la sua base di regole, quali regole vengono effettivamente utilizzate e quali livelli sono ancora vuoti.",diff --git a/locales/ja-JP/labs.json b/locales/ja-JP/labs.jsonindex 562eca21d75..b08752c2c17 100644--- a/locales/ja-JP/labs.json+++ b/locales/ja-JP/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "メッセージテキスト選択アクション","features.oauthApps.desc": "個人およびワークスペース設定でOAuthアプリ管理を表示します。この機能はデフォルトでは非表示です。","features.oauthApps.title": "OAuthアプリ",- "features.persistentSandbox.desc": "クラウドサンドボックスが書き込むファイルを保持します。その作業ディレクトリはセッションのリサイクル後も維持され、トピック間で共有されます。サンドボックスと共に破棄されることはありません。有料プランが必要です。大規模なダウンロードや依存関係は依然として/tmpに属します。",- "features.persistentSandbox.title": "永続的なサンドボックス","features.projects.desc": "長期的な目標を専用のワークスペースに整理し、それぞれに専用のエージェント、知識ベース、タスクを設定できます。","features.projects.title": "プロジェクトワークスペース","features.selfLearning.desc": "各エージェントが実際の実践から学んだ内容を表示します—そのルールベース、実際に使用されるルール、およびまだ空白のレイヤー。",diff --git a/locales/ko-KR/labs.json b/locales/ko-KR/labs.jsonindex d44cb6272d4..f143ebda3b5 100644--- a/locales/ko-KR/labs.json+++ b/locales/ko-KR/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "메시지 텍스트 선택 작업","features.oauthApps.desc": "개인 및 워크스페이스 설정에서 OAuth 앱 관리를 표시합니다. 이 기능은 기본적으로 숨겨져 있습니다.","features.oauthApps.title": "OAuth 앱",- "features.persistentSandbox.desc": "클라우드 샌드박스가 작성한 파일을 유지합니다. 작업 디렉토리는 세션 재활용 후에도 유지되며, 샌드박스와 함께 삭제되지 않고 주제 간에 공유됩니다. 유료 플랜이 필요하며, 대규모 다운로드 및 종속성은 여전히 /tmp에 속합니다.",- "features.persistentSandbox.title": "영구 샌드박스","features.projects.desc": "장기적인 목표를 전용 작업 공간으로 구성하여 고유한 에이전트, 지식 베이스 및 작업을 관리하세요.","features.projects.title": "프로젝트 작업 공간","features.selfLearning.desc": "각 에이전트가 실제 연습을 통해 학습한 내용을 보여줍니다 — 규칙 기반, 실제로 사용된 규칙, 그리고 아직 비어 있는 레이어를 확인할 수 있습니다.",diff --git a/locales/nl-NL/labs.json b/locales/nl-NL/labs.jsonindex f0ef76d53ad..df3e85e349e 100644--- a/locales/nl-NL/labs.json+++ b/locales/nl-NL/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Acties voor Tekstselectie in Berichten","features.oauthApps.desc": "Toon OAuth-appbeheer in persoonlijke en werkruimte-instellingen. Deze functie is standaard verborgen.","features.oauthApps.title": "OAuth-apps",- "features.persistentSandbox.desc": "Bewaar bestanden die de cloud-sandbox schrijft. De werkmap blijft behouden na het hergebruiken van sessies en wordt gedeeld tussen je onderwerpen, in plaats van te worden verwijderd met de sandbox. Vereist een betaald abonnement; grote downloads en afhankelijkheden horen nog steeds in /tmp.",- "features.persistentSandbox.title": "Persistente Sandbox","features.projects.desc": "Organiseer langlopende doelen in speciale werkruimtes met eigen agenten, kennisbanken en taken.","features.projects.title": "Projectwerkruimtes","features.selfLearning.desc": "Toon wat elke agent heeft geleerd uit echte praktijk — zijn regelbasis, welke regels daadwerkelijk worden gebruikt en welke lagen nog leeg zijn.",diff --git a/locales/pl-PL/labs.json b/locales/pl-PL/labs.jsonindex 337060c9765..782382ac8c9 100644--- a/locales/pl-PL/labs.json+++ b/locales/pl-PL/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Akcje zaznaczania tekstu wiadomości","features.oauthApps.desc": "Pokaż zarządzanie aplikacjami OAuth w ustawieniach osobistych i przestrzeni roboczej. Ta funkcja jest domyślnie ukryta.","features.oauthApps.title": "Aplikacje OAuth",- "features.persistentSandbox.desc": "Zachowaj pliki zapisane przez chmurę sandbox. Jego katalog roboczy przetrwa recykling sesji i jest współdzielony między Twoimi tematami, zamiast być usuwanym wraz z sandboxem. Wymaga płatnego planu; duże pliki do pobrania i zależności nadal należą do /tmp.",- "features.persistentSandbox.title": "Trwały Sandbox","features.projects.desc": "Organizuj długoterminowe cele w dedykowanych przestrzeniach roboczych z własnymi agentami, bazami wiedzy i zadaniami.","features.projects.title": "Przestrzenie Robocze Projektów","features.selfLearning.desc": "Pokaż, czego każdy agent nauczył się z rzeczywistej praktyki — jego bazę reguł, które reguły są faktycznie używane, oraz które warstwy są nadal puste.",diff --git a/locales/pt-BR/labs.json b/locales/pt-BR/labs.jsonindex a3712b7d4a5..6c75974da4e 100644--- a/locales/pt-BR/labs.json+++ b/locales/pt-BR/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Ações de Seleção de Texto em Mensagens","features.oauthApps.desc": "Exibir gerenciamento de aplicativos OAuth nas configurações pessoais e do espaço de trabalho. Este recurso está oculto por padrão.","features.oauthApps.title": "Aplicativos OAuth",- "features.persistentSandbox.desc": "Mantenha os arquivos que o sandbox na nuvem escreve. Seu diretório de trabalho sobrevive à reciclagem de sessões e é compartilhado entre seus tópicos, em vez de ser descartado com o sandbox. Requer um plano pago; downloads grandes e dependências ainda pertencem a /tmp.",- "features.persistentSandbox.title": "Sandbox Persistente","features.projects.desc": "Organize objetivos de longo prazo em espaços de trabalho dedicados com seus próprios agentes, bases de conhecimento e tarefas.","features.projects.title": "Espaços de Trabalho de Projetos","features.selfLearning.desc": "Mostre o que cada agente aprendeu com a prática real — sua base de regras, quais regras são realmente utilizadas e quais camadas ainda estão em branco.",diff --git a/locales/ru-RU/labs.json b/locales/ru-RU/labs.jsonindex a2fda9797c7..3cfbeabd604 100644--- a/locales/ru-RU/labs.json+++ b/locales/ru-RU/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Действия при выделении текста сообщения","features.oauthApps.desc": "Показать управление OAuth-приложениями в личных и рабочих настройках. Эта функция скрыта по умолчанию.","features.oauthApps.title": "OAuth-приложения",- "features.persistentSandbox.desc": "Сохраняйте файлы, которые облачная песочница записывает. Её рабочая директория сохраняется при перезапуске сессии и используется для всех ваших тем, вместо того чтобы удаляться вместе с песочницей. Требуется платный план; крупные загрузки и зависимости всё равно должны находиться в /tmp.",- "features.persistentSandbox.title": "Постоянная песочница","features.projects.desc": "Организуйте долгосрочные цели в специализированных рабочих пространствах с собственными агентами, базами знаний и задачами.","features.projects.title": "Рабочие пространства проектов","features.selfLearning.desc": "Показывает, чему каждый агент научился на практике — его базу правил, какие правила действительно используются и какие слои остаются пустыми.",diff --git a/locales/tr-TR/labs.json b/locales/tr-TR/labs.jsonindex fa1e494755c..1aeec9cf7ab 100644--- a/locales/tr-TR/labs.json+++ b/locales/tr-TR/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Mesaj Metni Seçim Eylemleri","features.oauthApps.desc": "Kişisel ve çalışma alanı ayarlarında OAuth uygulama yönetimini göster. Bu özellik varsayılan olarak gizlidir.","features.oauthApps.title": "OAuth Uygulamaları",- "features.persistentSandbox.desc": "Bulut sandbox'ının yazdığı dosyaları saklayın. Çalışma dizini oturum yenilemelerinden kurtulur ve konularınız arasında paylaşılır, sandbox ile birlikte silinmez. Ücretli bir plan gerektirir; büyük indirmeler ve bağımlılıklar hala /tmp içinde olmalıdır.",- "features.persistentSandbox.title": "Kalıcı Sandbox","features.projects.desc": "Uzun vadeli hedefleri, kendi ajanları, bilgi tabanları ve görevleriyle özel çalışma alanlarında organize edin.","features.projects.title": "Proje Çalışma Alanları","features.selfLearning.desc": "Her bir ajanın gerçek uygulamalardan ne öğrendiğini gösterin — kural tabanı, hangi kuralların gerçekten kullanıldığını ve hangi katmanların hâlâ boş olduğunu.",diff --git a/locales/vi-VN/labs.json b/locales/vi-VN/labs.jsonindex 5bdc284bc89..b1ca16d36d3 100644--- a/locales/vi-VN/labs.json+++ b/locales/vi-VN/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "Hành Động Chọn Văn Bản Tin Nhắn","features.oauthApps.desc": "Hiển thị quản lý ứng dụng OAuth trong cài đặt cá nhân và không gian làm việc. Tính năng này bị ẩn theo mặc định.","features.oauthApps.title": "Ứng dụng OAuth",- "features.persistentSandbox.desc": "Giữ lại các tệp mà sandbox đám mây ghi. Thư mục làm việc của nó sẽ tồn tại qua các lần tái chế phiên và được chia sẻ giữa các chủ đề của bạn, thay vì bị loại bỏ cùng với sandbox. Yêu cầu gói trả phí; các tệp tải xuống lớn và phụ thuộc vẫn thuộc về /tmp.",- "features.persistentSandbox.title": "Sandbox Bền Vững","features.projects.desc": "Tổ chức các mục tiêu dài hạn thành các không gian làm việc riêng biệt với các tác nhân, cơ sở kiến thức và nhiệm vụ riêng.","features.projects.title": "Không gian Làm việc Dự án","features.selfLearning.desc": "Hiển thị những gì mỗi tác nhân đã học từ thực tiễn thực tế — cơ sở quy tắc của nó, các quy tắc thực sự được sử dụng và các lớp nào vẫn còn trống.",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex e1c74f61d01..f89752e980b 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "消息文本选择操作","features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。","features.oauthApps.title": "OAuth 应用",- "features.persistentSandbox.desc": "让云端沙箱写下的文件留存。工作目录在会话回收后依然存在,并在你的各个话题间共享,而不是随沙箱一起丢弃。需要付费套餐;体积大的依赖和数据集仍应放在 /tmp。",- "features.persistentSandbox.title": "持久化沙箱","features.projects.desc": "将长期目标组织到独立工作空间中,并集中管理相关智能体、资料库与任务。","features.projects.title": "项目工作空间","features.selfLearning.desc": "让所有 Agent 在后台从对话中学习:记住信息、完善技能、积累经验,并在每晚复盘。你打回的验收会沉淀成规矩。每晚复盘最多覆盖 50 个话题。在「记忆 → 自进化」里统一查看。",diff --git a/locales/zh-TW/labs.json b/locales/zh-TW/labs.jsonindex 4b3fd6bb86a..f3e5b850bec 100644--- a/locales/zh-TW/labs.json+++ b/locales/zh-TW/labs.json@@ -36,8 +36,6 @@"features.messageTextSelectionActions.title": "訊息文字選取操作","features.oauthApps.desc": "在個人和工作區設定中顯示 OAuth 應用程式管理。此功能預設為隱藏。","features.oauthApps.title": "OAuth 應用程式",- "features.persistentSandbox.desc": "保留雲端沙盒寫入的檔案。其工作目錄在會話回收後仍然存在,並且在您的主題間共享,而不是隨沙盒一起丟棄。需要付費方案;大型下載和依賴項仍然屬於 /tmp。",- "features.persistentSandbox.title": "持久沙盒","features.projects.desc": "將長期目標組織到專屬工作空間中,這些空間擁有自己的代理、知識庫和任務。","features.projects.title": "專案工作空間","features.selfLearning.desc": "展示每個代理從實際操作中學到的內容——其規則庫、實際使用的規則,以及哪些層仍然是空白的。",diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 996d7b01f4a..ade5f455a56 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -54,9 +54,6 @@ export default {'features.oauthApps.desc':'Show OAuth app management in personal and workspace settings. This feature is hidden by default.','features.oauthApps.title': 'OAuth Apps',- 'features.persistentSandbox.desc':- 'Keep files the cloud sandbox writes. Its working directory survives session recycling and is shared across your topics, instead of being discarded with the sandbox. Requires a paid plan; large downloads and dependencies still belong in /tmp.',- 'features.persistentSandbox.title': 'Persistent Sandbox','features.projects.desc':'Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.','features.projects.title': 'Project Workspaces',diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 152be7da035..a77f7efa35a 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -251,12 +251,6 @@ export const UserLabSchema = z.object({* running there can be opened from this UI*/enableDeviceTunnel: z.boolean().optional(),- /**- * opt this user's cloud-sandbox runs into a persistent workspace: the working- * directory survives session recycling and is shared across their topics,- * instead of being thrown away with the sandbox- */- enablePersistentSandbox: z.boolean().optional(),});export type UserLab = z.infer<typeof UserLabSchema>;diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsxindex fd30989d515..f60a5b1f4b0 100644--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx@@ -9,6 +9,7 @@ import SandboxDrivePicker from './SandboxDrivePicker';import SandboxEnvironmentPicker from './SandboxEnvironmentPicker';import { useSandboxPlacement } from './useSandboxPlacement';import { useSandboxStorageAccess } from './useSandboxStorageAccess';+import { useSeedDefaultSelection } from './useSeedDefaultSelection';interface SandboxStorageSectionProps {agentId: string;@@ -21,17 +22,23 @@ interface SandboxStorageSectionProps {* the run could work.** Nothing chosen means a temporary sandbox, cleaned up with the session; a- * folder on the drive keeps its files. Beside it, the environment the working- * directory is initialized from — a separate choice, so a temporary sandbox- * can start from a checkout too.+ * folder on the drive keeps its files. A plan with a drive starts each new+ * conversation on its default folder rather than nothing. Beside it, the+ * environment the working directory is initialized from — a separate choice,+ * so a temporary sandbox can start from a checkout too.** A plan without a drive still gets the chip: the temporary sandbox is* everyone's, and the way to a plan is a row in the same menu rather than a* different control.*/const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {- const { status } = useSandboxStorageAccess(agentId);+ const { eligible, status } = useSandboxStorageAccess(agentId);const { selection, setSelection, topicId } = useSandboxPlacement(agentId, useTopicId());+ useSeedDefaultSelection(agentId, {+ eligible,+ entitled: status === 'ready',+ hasTopic: !!topicId,+ });if (status === 'hidden') return null;diff --git a/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.ts b/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.tsnew file mode 100644index 00000000000..289a509e9c3--- /dev/null+++ b/src/features/ChatInput/ControlBar/defaultSandboxSelection.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';++describe('resolveDefaultSandboxSelection', () => {+ it('starts a personal account at the root of its own drive', () => {+ expect(resolveDefaultSandboxSelection()).toEqual({ workingDirectory: '.' });+ expect(resolveDefaultSandboxSelection(null)).toEqual({ workingDirectory: '.' });+ });++ // The public drive's root is refused as a working directory, so every agent+ // in a workspace — shared or not — starts on the member's own drive.+ it("starts a workspace run at the root of the member's personal drive", () => {+ expect(resolveDefaultSandboxSelection('ws_1')).toEqual({+ drive: 'personal',+ workingDirectory: '.',+ });+ });+});diff --git a/src/features/ChatInput/ControlBar/defaultSandboxSelection.ts b/src/features/ChatInput/ControlBar/defaultSandboxSelection.tsnew file mode 100644index 00000000000..c0c6d631ab1--- /dev/null+++ b/src/features/ChatInput/ControlBar/defaultSandboxSelection.ts@@ -0,0 +1,19 @@+import { SANDBOX_DRIVE_ROOT } from '@lobechat/builtin-tool-cloud-sandbox';++import type { SandboxSelection } from './useSandboxPlacement';++/**+ * Where a new conversation's cloud sandbox works when the person has not+ * picked anything, for an account whose plan includes a drive: the root of a+ * drive that is theirs alone.+ *+ * - personal account — the root of their own drive;+ * - workspace — the root of the member's personal drive, for every agent. The+ * public drive's root holds every member's folders and is not a folder+ * anyone may work in, so a shared agent starts on the member's own drive too;+ * moving to a folder on the public drive is an explicit pick.+ */+export const resolveDefaultSandboxSelection = (workspaceId?: string | null): SandboxSelection =>+ workspaceId+ ? { drive: 'personal', workingDirectory: SANDBOX_DRIVE_ROOT }+ : { workingDirectory: SANDBOX_DRIVE_ROOT };diff --git a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.tsindex ce33dde9253..5aa07d78129 100644--- a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts@@ -1,3 +1,4 @@+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import { isDesktop } from '@lobechat/const';import { resolveExecutionTarget } from '@/helpers/executionTarget';@@ -6,23 +7,25 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandbox';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { useTopicId } from '../hooks/useTopicId';/*** What the composer should show where the sandbox working directory goes:*- * - `hidden` — the run does not use the cloud sandbox, or the user has not- * opted into the experiment. Nothing is rendered; a switch the user never- * flipped should not start advertising itself in their composer.- * - `upgrade` — opted in, but this account has no persistent workspace.- * - `ready` — opted in and entitled.+ * - `hidden` — the run does not use the cloud sandbox, or the deployment has+ * no drive service at all (self-hosted). Nothing is rendered.+ * - `upgrade` — this account has no persistent workspace.+ * - `ready` — entitled.*/export type SandboxStorageAccess = 'hidden' | 'ready' | 'upgrade';export interface SandboxStorageAccessResult {+ /**+ * Whether this run could have a drive at all — a business deployment, an+ * agent that runs in the cloud sandbox — known before the entitlement is.+ */+ eligible: boolean;/** Soft storage quota of the workspace, once known. */quotaBytes: number | null;status: SandboxStorageAccess;@@ -53,13 +56,13 @@ const useRunsInSandbox = (agentId: string): boolean => {/*** The entitlement is deliberately NOT derived on the client from a plan: it is* resolved and signed server-side, and asking the server is the only way to see- * the same answer the sandbox will act on. The lab flag is the cheap local half,- * so the request is not made at all until the user has opted in.+ * the same answer the sandbox will act on. Only a deployment with business+ * features has a drive to ask about; anywhere else nobody is entitled, and an+ * upgrade prompt would point at plans that do not exist.*/export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessResult => {- const labEnabled = useUserStore(labPreferSelectors.enablePersistentSandbox);const runsInSandbox = useRunsInSandbox(agentId);- const shouldAsk = labEnabled && runsInSandbox;+ const shouldAsk = ENABLE_BUSINESS_FEATURES && runsInSandbox;// A replica partitioned by the cache scope (user + workspace), because the// server resolves the entitlement from the active workspace: one workspace's@@ -69,12 +72,13 @@ export const useSandboxStorageAccess = (agentId: string): SandboxStorageAccessResandboxActions.useFetchEntitlement(shouldAsk, { revalidateOnFocus: false });const data = useSandboxStore(sandboxSelectors.entitlement);- if (!shouldAsk) return { quotaBytes: null, status: 'hidden' };+ if (!shouldAsk) return { eligible: false, quotaBytes: null, status: 'hidden' };// Until the answer arrives, show nothing rather than flashing an upgrade// prompt at a user who turns out to be entitled.- if (!data) return { quotaBytes: null, status: 'hidden' };+ if (!data) return { eligible: true, quotaBytes: null, status: 'hidden' };return {+ eligible: true,quotaBytes: data.quotaBytes,status: data.entitled ? 'ready' : 'upgrade',};diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.tsnew file mode 100644index 00000000000..2fc22852ae4--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.test.ts@@ -0,0 +1,79 @@+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ consumePendingSandboxSelection,+ getPendingSandboxSelection,+ resolvePendingSandboxSelection,+ setPendingSandboxSelection,+} from '@/store/chat/pendingSandboxSelection';++import { useSeedDefaultSelection } from './useSeedDefaultSelection';++const getEntitlement = vi.hoisted(() => vi.fn());++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => null,+}));++vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { getEntitlement },+}));++vi.mock('@/store/sandbox', () => ({+ sandboxSelectors: { entitlement: () => undefined },+ useSandboxStore: { getState: () => ({}) },+}));++const AGENT = 'agent-seed';++afterEach(() => {+ consumePendingSandboxSelection(AGENT);+ getEntitlement.mockReset();+});++describe('useSeedDefaultSelection', () => {+ it('fills the empty slot once the plan is known to include a drive', () => {+ renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: true, hasTopic: false }),+ );++ expect(getPendingSandboxSelection(AGENT)).toEqual({ workingDirectory: '.' });+ });++ it('never overwrites a pick, including the temporary sandbox', () => {+ setPendingSandboxSelection(AGENT, {});++ renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: true, hasTopic: false }),+ );++ expect(getPendingSandboxSelection(AGENT)).toEqual({});+ });++ // The default registered while the entitlement loads must not outlive the+ // sandbox surface: a run moved to a machine would otherwise wait on the+ // entitlement at its first send and be born with a sandbox folder.+ it('withdraws the registered default when the surface unmounts', async () => {+ getEntitlement.mockResolvedValue({ entitled: true });+ const { unmount } = renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: false, hasTopic: false }),+ );++ unmount();++ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toBeUndefined();+ expect(getEntitlement).not.toHaveBeenCalled();+ });++ it('keeps the default registered while the surface stays mounted', async () => {+ getEntitlement.mockResolvedValue({ entitled: true });+ renderHook(() =>+ useSeedDefaultSelection(AGENT, { eligible: true, entitled: false, hasTopic: false }),+ );++ await expect(resolvePendingSandboxSelection(AGENT)).resolves.toEqual({+ workingDirectory: '.',+ });+ });+});diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.tsnew file mode 100644index 00000000000..f59336fe1d4--- /dev/null+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts@@ -0,0 +1,45 @@+import { useEffect } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import {+ getPendingSandboxSelection,+ setPendingSandboxSelection,+ setSandboxDefaultSelection,+} from '@/store/chat/pendingSandboxSelection';++import { resolveDefaultSandboxSelection } from './defaultSandboxSelection';++/**+ * 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. 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.+ *+ * Two halves, because the entitlement loads after the composer does. The+ * default is registered as soon as the run is known to use the sandbox, and+ * the first send settles it against the entitlement — so a message sent before+ * the answer arrives still starts on the drive. Once the answer is in, the+ * slot is filled here too, which is what the chip names.+ */+export const useSeedDefaultSelection = (+ agentId: string,+ { eligible, entitled, hasTopic }: { eligible: boolean; entitled: boolean; hasTopic: boolean },+) => {+ const workspaceId = useActiveWorkspaceId();++ // Cleared on unmount as well: once the run moves off the sandbox, nothing+ // should hand a sandbox folder to a conversation on a machine.+ useEffect(() => {+ if (!eligible) return;++ setSandboxDefaultSelection(agentId, resolveDefaultSandboxSelection(workspaceId));+ return () => setSandboxDefaultSelection(agentId);+ }, [agentId, eligible, workspaceId]);++ useEffect(() => {+ if (!entitled || hasTopic || getPendingSandboxSelection(agentId)) return;++ setPendingSandboxSelection(agentId, resolveDefaultSandboxSelection(workspaceId));+ }, [agentId, entitled, hasTopic, workspaceId]);+};diff --git a/src/features/Settings/hooks/useCategory.test.tsx b/src/features/Settings/hooks/useCategory.test.tsxindex ba49e9b8475..f3ea378593c 100644--- a/src/features/Settings/hooks/useCategory.test.tsx+++ b/src/features/Settings/hooks/useCategory.test.tsx@@ -130,25 +130,21 @@ describe('settings useCategory', () => {expect(accountGroup?.items.map((item) => item.key)).toContain(SettingsTabs.Integrations);});- // The drives are what a persistent sandbox run keeps files on, so the tab- // that sets them out follows the same lab switch as the composer's picker.- it('shows Storage beside Environments once persistent sandboxes are switched on', () => {+ // The drives are what a persistent sandbox run keeps files on. Every Cloud+ // account can reach them with no opt-in; a self-hosted deployment has no+ // drive service, so it gets no tab.+ it('shows Storage beside Environments wherever business features are on', () => {expect(getItemKeys()).not.toContain(SettingsTabs.Drive);- useUserStore.setState({- preference: {- ...initialUserStoreState.preference,- lab: { ...initialUserStoreState.preference.lab, enablePersistentSandbox: true },- },+ const { result } = renderHook(() => useCategory(), {+ wrapper: createWrapper(true, true),});- const { result } = renderHook(() => useCategory(), { wrapper: createWrapper(true) });const generalGroup = result.current.find((group) => group.key === SettingsGroupKey.General);- expect(generalGroup?.items.map((item) => item.key)).toEqual([- SettingsTabs.Stats,- SettingsTabs.Devices,- SettingsTabs.Environments,- SettingsTabs.Drive,- ]);+ expect(generalGroup?.items.map((item) => item.key)).toEqual(+ expect.arrayContaining([SettingsTabs.Environments, SettingsTabs.Drive]),+ );+ const keys = generalGroup!.items.map((item) => item.key);+ expect(keys.indexOf(SettingsTabs.Drive)).toBe(keys.indexOf(SettingsTabs.Environments) + 1);});it('shows OAuth Apps when the Labs preference is enabled', () => {diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsxindex 6824ff24255..9b01f9edfd5 100644--- a/src/features/Settings/hooks/useCategory.tsx+++ b/src/features/Settings/hooks/useCategory.tsx@@ -87,7 +87,6 @@ export const useCategory = () => {const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);const enableIntegrations = useUserStore(labPreferSelectors.enableIntegrations);- const enablePersistentSandbox = useUserStore(labPreferSelectors.enablePersistentSandbox);const avatarUrl = useMemo(() => {if (!avatar) return undefined;@@ -164,9 +163,9 @@ export const useCategory = () => {label: t('tab.environments'),},// The drives a cloud-sandbox run keeps files on, with their usage and- // the way to a plan — behind the same lab switch the composer's folder- // picker is, since without it no run ever touches a drive.- enablePersistentSandbox && {+ // the way to a plan. A self-hosted deployment has no drive service, so+ // the tab would only ever lead to an empty page there.+ enableBusinessFeatures && {icon: HardDriveIcon,key: SettingsTabs.Drive,label: t('tab.drive'),@@ -340,7 +339,6 @@ export const useCategory = () => {isDevMode,enableOAuthApps,enableIntegrations,- enablePersistentSandbox,avatarUrl,username,]);diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex 3983fb31870..74e7129b716 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -28,7 +28,6 @@ type LabFeatureI18nKey =| 'integrations'| 'messageTextSelectionActions'| 'oauthApps'- | 'persistentSandbox'| 'projects'| 'selfLearning'| 'topicBugReport';@@ -128,12 +127,6 @@ const ALL_LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['integrations', 'github', 'github app', 'pull request'],stage: 'alpha',},- {- flag: 'enablePersistentSandbox',- i18nKey: 'persistentSandbox',- searchKeywords: ['persistent sandbox', 'workspace', 'sandbox storage'],- stage: 'alpha',- },{flag: 'enableArtifactDeployment',i18nKey: 'artifactDeployment',diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsxindex cec30d710af..222bd82d68d 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx@@ -111,7 +111,9 @@ describe('workspace settings useCategory', () => {]);});- it('groups devices, subscription accounts and environments under Resources', () => {+ // The drives need no opt-in: every member sees the tab, which shows the+ // public drive, their own, and the way to a plan when the workspace has none.+ it('groups devices, subscription accounts, environments and drives under Resources', () => {const { result } = renderHook(() => useWorkspaceSettingCategory(), { wrapper });const keys = result.current.map((group) => group.key);const resourceGroup = result.current.find(@@ -128,6 +130,7 @@ describe('workspace settings useCategory', () => {WorkspaceSettingsTabs.Devices,WorkspaceSettingsTabs.SubscriptionAccounts,WorkspaceSettingsTabs.Environments,+ WorkspaceSettingsTabs.Drive,]);expect(generalGroup?.items.map((item) => item.key)).not.toContain(WorkspaceSettingsTabs.Devices,diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsxindex 51d7f42ca36..0df601c58ab 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx@@ -82,7 +82,6 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =const { allowed: canCreateContent } = usePermission('create_content');const enableOAuthApps = useUserStore(labPreferSelectors.enableOAuthApps);const enableIntegrations = useUserStore(labPreferSelectors.enableIntegrations);- const enablePersistentSandbox = useUserStore(labPreferSelectors.enablePersistentSandbox);const { hideDocs } = useServerConfigStore(featureFlagsSelectors);const [avatar, username] = useUserStore((s) => [userProfileSelectors.userAvatar(s),@@ -213,9 +212,8 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Environments,label: t('tab.environments'),},- // The public drive and the member's own, with the pool's usage —- // behind the same lab switch as the composer's folder picker.- enablePersistentSandbox && {+ // The public drive and the member's own, with the pool's usage.+ {icon: HardDriveIcon,key: WorkspaceSettingsTabs.Drive,label: t('tab.drive'),@@ -377,7 +375,6 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =tSubscription,enableOAuthApps,enableIntegrations,- enablePersistentSandbox,canManageWorkspace,canViewBilling,canCreateContent,diff --git a/src/store/chat/pendingSandboxSelection.test.ts b/src/store/chat/pendingSandboxSelection.test.tsindex d25b31f1f01..c988a06cc03 100644--- a/src/store/chat/pendingSandboxSelection.test.ts+++ b/src/store/chat/pendingSandboxSelection.test.ts@@ -1,13 +1,29 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import {consumePendingSandboxSelection,getPendingSandboxSelection,+ resolvePendingSandboxSelection,setPendingSandboxSelection,+ setSandboxDefaultSelection,subscribePendingSandboxSelection,toSandboxTopicMetadata,} from './pendingSandboxSelection';+const mocks = vi.hoisted(() => ({+ cachedEntitlement: undefined as { entitled: boolean } | undefined,+ getEntitlement: vi.fn(),+}));++vi.mock('@/services/sandboxStorage', () => ({+ sandboxStorageService: { getEntitlement: mocks.getEntitlement },+}));++vi.mock('@/store/sandbox', () => ({+ sandboxSelectors: { entitlement: () => mocks.cachedEntitlement },+ useSandboxStore: { getState: () => ({}) },+}));+describe('pendingSandboxSelection', () => {it('notifies a subscriber on set and on consume — a second reader must move too', () => {// Two components read this: the switch that writes and the chip that only@@ -51,4 +67,84 @@ describe('pendingSandboxSelection', () => {});expect(toSandboxTopicMetadata(undefined)).toBeUndefined();});++ // The entitlement loads after the composer does. A first message sent while+ // it is still in flight used to be born with no folder — the paid default+ // silently became a temporary sandbox.+ describe('resolvePendingSandboxSelection', () => {+ const root = { workingDirectory: '.' };++ beforeEach(() => {+ mocks.cachedEntitlement = undefined;+ mocks.getEntitlement.mockReset();+ });++ it('settles the default against the server when the entitlement has not loaded', async () => {+ mocks.getEntitlement.mockResolvedValue({ entitled: true });+ setSandboxDefaultSelection('agent-cold', root);++ await expect(resolvePendingSandboxSelection('agent-cold')).resolves.toEqual(root);+ // It becomes the pick, so the transport reading it next sees the same.+ expect(getPendingSandboxSelection('agent-cold')).toEqual(root);++ consumePendingSandboxSelection('agent-cold');+ setSandboxDefaultSelection('agent-cold');+ });++ it('leaves a plan without a drive on the temporary sandbox', async () => {+ mocks.getEntitlement.mockResolvedValue({ entitled: false });+ setSandboxDefaultSelection('agent-free', root);++ await expect(resolvePendingSandboxSelection('agent-free')).resolves.toBeUndefined();+ expect(getPendingSandboxSelection('agent-free')).toBeUndefined();++ setSandboxDefaultSelection('agent-free');+ });++ it('uses the cached answer without asking the server again', async () => {+ mocks.cachedEntitlement = { entitled: true };+ setSandboxDefaultSelection('agent-warm', root);++ await expect(resolvePendingSandboxSelection('agent-warm')).resolves.toEqual(root);+ expect(mocks.getEntitlement).not.toHaveBeenCalled();++ consumePendingSandboxSelection('agent-warm');+ setSandboxDefaultSelection('agent-warm');+ });++ // The cache is persisted: an account that has just upgraded still reads+ // "no drive" until its revalidation lands, so a cached no is confirmed.+ it('confirms a cached negative with the server before declining the drive', async () => {+ mocks.cachedEntitlement = { entitled: false };+ mocks.getEntitlement.mockResolvedValue({ entitled: true });+ setSandboxDefaultSelection('agent-upgraded', root);++ await expect(resolvePendingSandboxSelection('agent-upgraded')).resolves.toEqual(root);+ expect(mocks.getEntitlement).toHaveBeenCalledTimes(1);++ consumePendingSandboxSelection('agent-upgraded');+ setSandboxDefaultSelection('agent-upgraded');+ });++ it('keeps an explicit pick, including the temporary sandbox', async () => {+ mocks.cachedEntitlement = { entitled: true };+ setSandboxDefaultSelection('agent-picked', root);+ setPendingSandboxSelection('agent-picked', {});++ await expect(resolvePendingSandboxSelection('agent-picked')).resolves.toEqual({});++ consumePendingSandboxSelection('agent-picked');+ setSandboxDefaultSelection('agent-picked');+ });++ it('reads a failed lookup, or an agent without a default, as no drive', async () => {+ mocks.getEntitlement.mockRejectedValue(new Error('offline'));+ setSandboxDefaultSelection('agent-offline', root);++ await expect(resolvePendingSandboxSelection('agent-offline')).resolves.toBeUndefined();+ await expect(resolvePendingSandboxSelection('agent-none')).resolves.toBeUndefined();++ setSandboxDefaultSelection('agent-offline');+ });+ });});diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.tsindex d902f681cb0..9617914734a 100644--- a/src/store/chat/pendingSandboxSelection.ts+++ b/src/store/chat/pendingSandboxSelection.ts@@ -1,6 +1,11 @@import type { ChatTopicMetadata } from '@lobechat/types';+import debug from 'debug';import type { SandboxSelection } from '@/features/ChatInput/ControlBar/useSandboxPlacement';+import { sandboxStorageService } from '@/services/sandboxStorage';+import { sandboxSelectors, useSandboxStore } from '@/store/sandbox';++const log = debug('lobe-client:sandbox:pending-selection');/*** Module-level singleton for a sandbox selection made before the topic exists.@@ -52,6 +57,62 @@ export const setPendingSandboxSelection = (agentId: string, selection?: SandboxSemit();};+/**+ * The place an agent's next conversation starts when nobody picks one, and+ * the plan turns out to include a drive. Registered by the composer as soon as+ * it knows the agent runs in the sandbox — before the entitlement has loaded —+ * so a message sent while that request is still in flight is not born without+ * a folder. Kept apart from the pending pick: it is a candidate, and only+ * becomes the pick once the entitlement is confirmed.+ */+const defaults = new Map<string, SandboxSelection>();++/** Register an agent's default placement; `undefined` clears it. */+export const setSandboxDefaultSelection = (agentId: string, selection?: SandboxSelection): void => {+ if (selection) defaults.set(agentId, selection);+ else defaults.delete(agentId);+};++/**+ * Whether the active workspace's plan includes a drive. A cached yes is taken+ * as is; a cached no is confirmed with the server first, because the cache is+ * persisted — an account that has just upgraded still reads no until its+ * revalidation lands, and its first conversation would otherwise lose the+ * drive. A failed lookup reads as no — the run goes to the temporary sandbox,+ * as it would have anyway.+ */+const isDriveEntitled = async (): Promise<boolean> => {+ const cached = sandboxSelectors.entitlement(useSandboxStore.getState());+ if (cached?.entitled) return true;++ try {+ return (await sandboxStorageService.getEntitlement()).entitled;+ } catch (error) {+ log('Failed to resolve the drive entitlement for a first send: %O', error);+ return false;+ }+};++/**+ * The selection the first send carries: the pick, if one was made; otherwise+ * the registered default, once the plan is confirmed to include a drive. The+ * default then becomes the pick, so every later reader of this send sees it.+ */+export const resolvePendingSandboxSelection = async (+ agentId: string,+): Promise<SandboxSelection | undefined> => {+ const picked = map.get(agentId);+ if (picked) return picked;++ const fallback = defaults.get(agentId);+ if (!fallback || !(await isDriveEntitled())) return undefined;++ // A pick made while the entitlement was in flight wins over the default.+ if (!map.has(agentId)) setPendingSandboxSelection(agentId, fallback);++ return map.get(agentId);+};+/** Read without consuming — what the closed chip names itself after. */export const getPendingSandboxSelection = (agentId: string): SandboxSelection | undefined =>map.get(agentId);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 31e7022808e..87ff7d594e1 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -63,7 +63,7 @@ import {} from '@/store/agent/selectors';import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';import {- getPendingSandboxSelection,+ resolvePendingSandboxSelection,toSandboxTopicMetadata,} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';@@ -1257,7 +1257,7 @@ export class ConversationLifecycleActionImpl {// renders under a cloud-sandbox target.const pendingSandboxSelection =willCreateNewTopic && operationContext.agentId- ? getPendingSandboxSelection(operationContext.agentId)+ ? await resolvePendingSandboxSelection(operationContext.agentId): undefined;const sandboxInstanceMetadata = toSandboxTopicMetadata(pendingSandboxSelection);/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 6adf226fed9..d0faca709d1 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -26,8 +26,6 @@ export const labPreferSelectors = {DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??false,enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,- enablePersistentSandbox: (s: UserState): boolean =>- s.preference.lab?.enablePersistentSandbox ?? false,enableSelfLearning: (s: UserState): boolean => s.preference.lab?.enableSelfLearning ?? false,enableProjects: (s: UserState): boolean => s.preference.lab?.enableProjects ?? false,// `updateLab` writes both keys, but older clients only write the legacy