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(project): order the project's execution environments by priority (#23532)

Rdmclin2de9b0bd4a4a2
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index 51bd9722a62..af1ca086680 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -345,6 +345,25 @@ export const projectWorkingDirectoryRouter = router({
});
return { data: await ctx.directoryRepo.bind(input), success: true };
}),
+ /** The cloud sandbox's place among the project's execution environments. */
+ executionOrder: procedure
+ .input(z.object({ projectId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.directoryRepo.executionOrder(input.projectId),
+ success: true,
+ })),
+ /** Reorder the project's execution environments: folder ids and `'sandbox'`. */
+ reorderExecutionEnvironments: write
+ .input(
+ z.object({
+ order: z.array(z.string().min(1)).min(1).max(200),
+ projectId: z.string().min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await ctx.directoryRepo.reorderExecutionEnvironments(input.projectId, input.order);
+ return { success: true };
+ }),
list: procedure
.input(z.object({ projectId: z.string().optional() }))
.query(async ({ ctx, input }) => ({
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index bcd2898edb3..2516e544329 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "متصل · {{count}} اتصالات",
"heteroAgent.executionTarget.personalGroup": "الأجهزة الخاصة",
"heteroAgent.executionTarget.presenceChecking": "جارٍ التحقق من الحالة...",
- "heteroAgent.executionTarget.projectDevicesHint": "يتم إدراج الأجهزة التي تحتوي على دليل العمل لهذا المشروع فقط. أضف دليلاً لجهاز آخر في إعدادات المشروع.",
"heteroAgent.executionTarget.reconnect": "إعادة الاتصال",
"heteroAgent.executionTarget.reconnectFailed": "تعذر إعادة الاتصال بهذا الجهاز. تأكد من تشغيل تطبيق سطح المكتب، ثم حاول مرة أخرى.",
"heteroAgent.executionTarget.sandbox": "بيئة سحابية مؤقتة",
diff --git a/locales/ar/project.json b/locales/ar/project.json
index 76d86df1acb..528d8df23d2 100644
--- a/locales/ar/project.json
+++ b/locales/ar/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "إضافة مجلد",
"settings.addDirectoryDescription": "اختر بيئة وجهازًا متصلًا، ثم أدخل المسار الكامل لمجلد موجود. تبقى الملفات على ذلك الجهاز.",
"settings.addDirectoryFailed": "تعذر إضافة دليل العمل",
- "settings.addEnvironment": "إضافة بيئة",
"settings.advanced": "متقدم",
- "settings.allEnvironments": "جميع البيئات",
- "settings.configureDirectory": "إضافة دليل عمل",
"settings.createdAt": "تاريخ الإنشاء {{date}}",
"settings.creator": "المنشئ",
"settings.creatorUnknown": "عضو سابق",
@@ -340,8 +337,6 @@
"settings.slugDescription": "يُستخدم في عنوان URL للمشروع. يؤدي تغييره إلى تحديث العنوان؛ اتركه فارغًا لاستخدام معرف المشروع.",
"settings.startDirectoryConversation": "موضوع جديد هنا",
"settings.title": "إعدادات المشروع",
- "settings.viewDirectories": "عرض المجلدات ({{count}})",
- "settings.workLocations": "أدلة العمل",
"sidebar.agentsEmpty": "لا يوجد وكلاء متصلون حتى الآن",
"sidebar.conversationsEmpty": "لا توجد مواضيع مشروع حتى الآن",
"sidebar.coordinatorTag": "القائد",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 14f2b095a3b..48b2e2922ef 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Онлайн · {{count}} връзки",
"heteroAgent.executionTarget.personalGroup": "Лични устройства",
"heteroAgent.executionTarget.presenceChecking": "Проверка на статуса...",
- "heteroAgent.executionTarget.projectDevicesHint": "Само устройства с работната директория на този проект са изброени. Добавете директория за друго устройство в настройките на проекта.",
"heteroAgent.executionTarget.reconnect": "Свържи отново",
"heteroAgent.executionTarget.reconnectFailed": "Неуспешно свързване на това устройство. Уверете се, че настолното приложение работи, след това опитайте отново.",
"heteroAgent.executionTarget.sandbox": "Облачен пясъчник",
diff --git a/locales/bg-BG/project.json b/locales/bg-BG/project.json
index c5aa9e3d9dd..0dab73fc5cd 100644
--- a/locales/bg-BG/project.json
+++ b/locales/bg-BG/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Добавяне на папка",
"settings.addDirectoryDescription": "Изберете среда и свързано устройство, след това въведете пълния път на съществуваща папка. Файловете остават на това устройство.",
"settings.addDirectoryFailed": "Неуспешно добавяне на работна директория",
- "settings.addEnvironment": "Добавяне на среда",
"settings.advanced": "Разширени",
- "settings.allEnvironments": "Всички среди",
- "settings.configureDirectory": "Добавяне на работна директория",
"settings.createdAt": "Създаден на {{date}}",
"settings.creator": "Създател",
"settings.creatorUnknown": "Бивш член",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Използва се в URL адреса на проекта. Промяната му актуализира адреса; оставете празно, за да използвате ID на проекта.",
"settings.startDirectoryConversation": "Нова тема тук",
"settings.title": "Настройки на проекта",
- "settings.viewDirectories": "Преглед на папки ({{count}})",
- "settings.workLocations": "Работни директории",
"sidebar.agentsEmpty": "Все още няма свързани агенти",
"sidebar.conversationsEmpty": "Все още няма теми за проекта",
"sidebar.coordinatorTag": "Ръководител",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 7aade5d5e4c..42ffc412a25 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} Verbindungen",
"heteroAgent.executionTarget.personalGroup": "Private Geräte",
"heteroAgent.executionTarget.presenceChecking": "Status wird überprüft…",
- "heteroAgent.executionTarget.projectDevicesHint": "Es werden nur Geräte mit dem Arbeitsverzeichnis dieses Projekts aufgelistet. Fügen Sie ein Verzeichnis für ein anderes Gerät in den Projekteinstellungen hinzu.",
"heteroAgent.executionTarget.reconnect": "Erneut verbinden",
"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",
diff --git a/locales/de-DE/project.json b/locales/de-DE/project.json
index dd8170db6ae..d8b25bbb6f4 100644
--- a/locales/de-DE/project.json
+++ b/locales/de-DE/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Ordner hinzufügen",
"settings.addDirectoryDescription": "Wählen Sie eine Umgebung und ein verbundenes Gerät aus, und geben Sie dann den vollständigen Pfad eines vorhandenen Ordners ein. Dateien bleiben auf diesem Gerät.",
"settings.addDirectoryFailed": "Arbeitsverzeichnis konnte nicht hinzugefügt werden",
- "settings.addEnvironment": "Umgebung hinzufügen",
"settings.advanced": "Erweitert",
- "settings.allEnvironments": "Alle Umgebungen",
- "settings.configureDirectory": "Ein Arbeitsverzeichnis hinzufügen",
"settings.createdAt": "Erstellt {{date}}",
"settings.creator": "Ersteller",
"settings.creatorUnknown": "Ehemaliges Mitglied",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Wird in der Projekt-URL verwendet. Änderungen aktualisieren die Adresse; leer lassen, um die Projekt-ID zu verwenden.",
"settings.startDirectoryConversation": "Neues Thema hier",
"settings.title": "Projekteinstellungen",
- "settings.viewDirectories": "Ordner anzeigen ({{count}})",
- "settings.workLocations": "Arbeitsverzeichnisse",
"sidebar.agentsEmpty": "Noch keine Agenten verbunden",
"sidebar.conversationsEmpty": "Noch keine Projektthemen",
"sidebar.coordinatorTag": "Leiter",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 682bbe3284f..6d9bd4ca1e6 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1639,7 +1639,6 @@
"heteroAgent.executionTarget.otherDevicesGroup": "Other devices",
"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.",
"heteroAgent.executionTarget.reconnect": "Reconnect",
"heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.",
"heteroAgent.executionTarget.sandbox": "Cloud Sandbox",
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 25af7a860a4..81174c7adfa 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -260,22 +260,22 @@
"createFromGithub.urlLabel": "Or paste a repository URL",
"createFromGithub.urlPlaceholder": "https://github.com/owner/repo",
"delete.confirm.continue": "Delete project",
- "delete.confirm.kept.files": "Files in the working directories on your devices",
+ "delete.confirm.kept.files": "Files in the project's device folders",
"delete.confirm.kept.work": "Tasks, goals, topics and channels",
"delete.confirm.keptLead": "These are kept, but no longer belong to a project:",
"delete.confirm.namePrompt": "Type “{{name}}” to confirm",
"delete.confirm.removed.automation": "Project widgets and their run history, Linear sync rules, review sites, dashboards and project memories",
"delete.confirm.removed.bindings": "Links to agents, groups and knowledge bases (your agents and knowledge bases are kept)",
- "delete.confirm.removed.settings": "Project settings, members, working directories and environments",
+ "delete.confirm.removed.settings": "Project settings, members, device folders and environment",
"delete.confirm.removedLead": "Deleting “{{name}}” cannot be undone. It permanently removes:",
"delete.confirm.title": "Delete project",
"delete.description": "Permanently delete this project and its settings. Tasks, goals and topics are kept but no longer belong to a project.",
- "directories.add": "Add working directory",
+ "directories.add": "Add device folder",
"directories.autoFileTopics": "All {{count}} existing topics will be linked to this project.",
"directories.bind": "Link to project",
"directories.bindDescription": "Link the folder below to a project so you can continue working from that project. Files stay on the current device.",
"directories.bindFailed": "Could not link directory",
- "directories.boundRoot": "This topic is bound to a project directory. Start a new topic to use a different directory.",
+ "directories.boundRoot": "This topic is bound to a device folder of the project. Start a new topic to use a different folder.",
"directories.boundTip": "This directory belongs to the project ({{path}}). Switch devices to use the project's directory on another device.",
"directories.chooseAgent": "Choose Agent",
"directories.conversations": "Topics",
@@ -304,7 +304,7 @@
"directories.stagedNewTopic": "A new topic will start in <project>{{name}}</project>",
"directories.start": "Start work here",
"directories.startInProject": "Start work in {{name}}",
- "directories.title": "Working directories",
+ "directories.title": "Device folders",
"directories.topicsSkipped": "Directory linked. {{count}} topics were left out because they run in another directory or on another device, belong to another project, are still running, or no longer exist.",
"directories.unavailable": "Device is offline or the directory is unavailable. Reconnect and retry.",
"directories.untitled": "Untitled topic",
@@ -420,13 +420,16 @@
"overview.agentSelect": "Choose an agent",
"overview.composerPlaceholder": "Tell the project what to move forward next…",
"overview.context.location.devices": "Devices",
- "overview.context.location.directories": "Project folders",
+ "overview.context.location.directories": "Device folders",
"overview.context.location.directoryUnavailable": "Couldn't reach this folder. Check that the device is online and the folder still exists.",
- "overview.context.location.environments": "Code environments",
- "overview.context.location.noDirectories": "No project folders on this device yet.",
- "overview.context.location.noDirectoryTooltip": "This device has no project folder yet, so the conversation starts in the device's default directory.",
- "overview.context.location.noEnvironments": "No code environments yet.",
- "overview.context.location.title": "Work location",
+ "overview.context.location.emptySandbox": "Empty sandbox",
+ "overview.context.location.emptySandboxDesc": "Starts in an empty folder, without the project environment",
+ "overview.context.location.environments": "Environment",
+ "overview.context.location.noDirectories": "No folders on this device yet.",
+ "overview.context.location.noDirectoryTooltip": "This device has no folder for the project yet, so the conversation starts in the device's default directory.",
+ "overview.context.location.noEnvironments": "The environment has no repositories yet.",
+ "overview.context.location.sandboxes": "Cloud sandbox",
+ "overview.context.location.title": "Execution environment",
"overview.context.repository.publishHint": "This agent is shared with the workspace and only uses published environments, so the repository is added as one that workspace members can see.",
"overview.context.target.device": "A connected device",
"overview.context.target.noneTooltip": "This agent has nowhere to run yet. Switch to the cloud sandbox so it can work on the code.",
@@ -535,27 +538,31 @@
"sections.knowledgeBases": "Libraries",
"sections.tasks": "Tasks",
"settings.addDirectory": "Add folder",
- "settings.addDirectoryDescription": "Select an environment and a connected device, then enter the full path of an existing folder. Files stay on that device.",
- "settings.addDirectoryFailed": "Could not add working directory",
- "settings.addEnvironment": "Add environment",
+ "settings.addDirectoryDescription": "Select a connected device, then enter the full path of an existing folder. Files stay on that device.",
+ "settings.addDirectoryFailed": "Could not add the device folder",
+ "settings.addExecutionEnvironment": "Add execution environment",
"settings.advanced": "Advanced",
- "settings.allEnvironments": "All environments",
- "settings.configureDirectory": "Add a working directory",
+ "settings.cloudSandboxGroup": "Cloud sandbox",
+ "settings.configureSandbox": "Configure",
"settings.createdAt": "Created {{date}}",
"settings.creator": "Creator",
"settings.creatorUnknown": "Former member",
"settings.description": "Description",
- "settings.deviceOffline": "Device disconnected",
- "settings.deviceOnline": "Device connected",
- "settings.directoryListDescription": "Device folders this project works in. Agents read and change files in them on that device.",
+ "settings.deviceOffline": "Offline",
+ "settings.deviceOnline": "Online",
"settings.directoryUnavailable": "The device is disconnected or the directory is unavailable. Connect the device and check the path, then retry.",
+ "settings.directoryUnavailableTag": "Unavailable",
+ "settings.directoryUnavailable_failed": "This folder couldn't be set up. Check its path, or try again later.",
+ "settings.directoryUnavailable_missing": "This folder isn't on the device. Edit its path or remove it.",
+ "settings.directoryUnavailable_needsManager": "A project manager needs to open this page while the device is online.",
+ "settings.directoryUnavailable_offline": "The device is offline. The folder becomes usable once the device is online.",
"settings.editDirectory": "Edit folder",
"settings.editDirectoryBusy": "A topic is running in this folder. Wait for it to finish and try again.",
- "settings.editDirectoryDescription": "Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.",
+ "settings.editDirectoryDescription": "Choose the device and folder this device folder points to. Its topics move to the new folder and start new sessions there.",
"settings.editDirectoryFailed": "Could not update the folder",
"settings.editDirectoryOtherEnvironment": "This folder already belongs to another environment. Choose a different folder or device.",
- "settings.environmentIntro": "Every conversation in this project runs in this environment: its repositories are cloned, the setup command runs, and its variables are set.",
- "settings.environments": "Environment",
+ "settings.environments": "Execution environments",
+ "settings.executionOrderHint": "New conversations use the first available execution environment in this order. Drag to reorder.",
"settings.general": "General",
"settings.generalDescription": "Manage the project name, address, and description.",
"settings.identifier": "Project identifier",
@@ -569,19 +576,21 @@
"settings.logoUploadFailed": "Could not upload the logo",
"settings.members": "Members",
"settings.nameHint": "Use 255 characters at most.",
- "settings.noDirectories": "No folders in this environment yet. Add an existing folder on a connected device to start working.",
+ "settings.noDirectories": "No device folders yet. Add a folder on a connected device to run this project there.",
"settings.noRepository": "No GitHub repository linked",
"settings.removeDirectory": "Remove folder",
- "settings.removeDirectoryConfirmDescription": "{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.",
+ "settings.removeDirectoryConfirmDescription": "{{path}} on {{device}} will no longer be a device folder of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.",
"settings.removeDirectoryConfirmTitle": "Remove {{name}} from this project?",
"settings.removeDirectoryFailed": "Could not remove the folder. If a topic is running here, wait for it to finish and try again.",
+ "settings.reorderFailed": "Couldn't save the new order. Try again.",
+ "settings.sandboxNoRepository": "No repository yet",
"settings.saveFailed": "Could not save the change",
"settings.saved": "Saved",
+ "settings.setDeviceDirectory": "Set folder",
+ "settings.setDirectoryDescription": "Enter the full path of an existing folder on {{device}}. Files stay on that device.",
"settings.slugDescription": "Used in the project URL. Changing it updates the address; leave blank to use the project ID.",
"settings.startDirectoryConversation": "New topic here",
"settings.title": "Project settings",
- "settings.viewDirectories": "View folders ({{count}})",
- "settings.workLocations": "Working directories",
"sidebar.agentsEmpty": "No agents are connected yet",
"sidebar.conversationsEmpty": "No project topics yet",
"sidebar.coordinatorTag": "Lead",
@@ -595,10 +604,10 @@
"sidebar.sort.updatedAt": "Recently updated",
"sidebar.title": "Projects",
"sidebar.untitledConversation": "Untitled topic",
- "topics.addLocation": "Add a working directory (optional)",
+ "topics.addLocation": "Add a device folder (optional)",
"topics.all": "All topics",
"topics.associateFailed": "Could not add topic to project",
- "topics.chooseLocation": "Choose a working directory",
+ "topics.chooseLocation": "Choose a device folder",
"topics.chooseTopic": "Choose a topic in the sidebar, or create one to start working",
"topics.complete": "Mark completed",
"topics.executionContext": "Work location",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 5a8eb6ac5b8..fb7b5fb350d 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -997,8 +997,13 @@
"environments.form.runtime": "Runtime and storage",
"environments.form.saved": "Saved",
"environments.form.setup": "Setup",
- "environments.form.sources": "Source code",
+ "environments.form.setupAndVariables": "Setup and environment variables",
+ "environments.form.setupConfigured": "Setup configured",
+ "environments.form.setupNotConfigured": "No setup",
+ "environments.form.sources": "Repositories",
"environments.form.sourcesHint": "Cloned over HTTPS before anything else runs. A private repository clones through the GitHub App installation that grants it; the environment itself stores no credentials.",
+ "environments.form.variablesCount_one": "{{count}} variable",
+ "environments.form.variablesCount_other": "{{count}} variables",
"environments.github.connect": "Connect GitHub",
"environments.github.label": "Repository",
"environments.github.loadFailed": "Could not load GitHub repositories. Try again.",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 36e7ff30f9d..04b67807345 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "En línea · {{count}} conexiones",
"heteroAgent.executionTarget.personalGroup": "Dispositivos privados",
"heteroAgent.executionTarget.presenceChecking": "Comprobando el estado…",
- "heteroAgent.executionTarget.projectDevicesHint": "Solo se enumeran los dispositivos con el directorio de trabajo de este proyecto. Agrega un directorio para otro dispositivo en la configuración del proyecto.",
"heteroAgent.executionTarget.reconnect": "Reconectar",
"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",
diff --git a/locales/es-ES/project.json b/locales/es-ES/project.json
index 9a4be60bba0..73f74632344 100644
--- a/locales/es-ES/project.json
+++ b/locales/es-ES/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Agregar carpeta",
"settings.addDirectoryDescription": "Selecciona un entorno y un dispositivo conectado, luego ingresa la ruta completa de una carpeta existente. Los archivos permanecen en ese dispositivo.",
"settings.addDirectoryFailed": "No se pudo agregar el directorio de trabajo",
- "settings.addEnvironment": "Agregar entorno",
"settings.advanced": "Avanzado",
- "settings.allEnvironments": "Todos los entornos",
- "settings.configureDirectory": "Agregar un directorio de trabajo",
"settings.createdAt": "Creado {{date}}",
"settings.creator": "Creador",
"settings.creatorUnknown": "Miembro anterior",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Usado en la URL del proyecto. Cambiarlo actualiza la dirección; déjalo en blanco para usar el ID del proyecto.",
"settings.startDirectoryConversation": "Nuevo tema aquí",
"settings.title": "Configuración del proyecto",
- "settings.viewDirectories": "Ver carpetas ({{count}})",
- "settings.workLocations": "Directorios de trabajo",
"sidebar.agentsEmpty": "Aún no hay agentes conectados",
"sidebar.conversationsEmpty": "Aún no hay temas del proyecto",
"sidebar.coordinatorTag": "Líder",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index f5b4e10949d..e9f764be7da 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "آنلاین · {{count}} اتصالات",
"heteroAgent.executionTarget.personalGroup": "دستگاه‌های خصوصی",
"heteroAgent.executionTarget.presenceChecking": "در حال بررسی وضعیت…",
- "heteroAgent.executionTarget.projectDevicesHint": "فقط دستگاه‌هایی که دارای دایرکتوری کاری این پروژه هستند فهرست شده‌اند. برای افزودن دایرکتوری برای دستگاه دیگر، به تنظیمات پروژه بروید.",
"heteroAgent.executionTarget.reconnect": "اتصال مجدد",
"heteroAgent.executionTarget.reconnectFailed": "اتصال مجدد این دستگاه امکان‌پذیر نبود. مطمئن شوید که برنامه دسکتاپ در حال اجرا است، سپس دوباره تلاش کنید.",
"heteroAgent.executionTarget.sandbox": "محیط آزمایشی ابری",
diff --git a/locales/fa-IR/project.json b/locales/fa-IR/project.json
index 37c8394212a..05d669bd430 100644
--- a/locales/fa-IR/project.json
+++ b/locales/fa-IR/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "افزودن پوشه",
"settings.addDirectoryDescription": "یک محیط و یک دستگاه متصل را انتخاب کنید، سپس مسیر کامل یک پوشه موجود را وارد کنید. فایل‌ها روی آن دستگاه باقی می‌مانند.",
"settings.addDirectoryFailed": "امکان افزودن دایرکتوری کاری وجود ندارد",
- "settings.addEnvironment": "افزودن محیط",
"settings.advanced": "پیشرفته",
- "settings.allEnvironments": "تمام محیط‌ها",
- "settings.configureDirectory": "افزودن یک دایرکتوری کاری",
"settings.createdAt": "ایجاد شده در {{date}}",
"settings.creator": "سازنده",
"settings.creatorUnknown": "عضو سابق",
@@ -340,8 +337,6 @@
"settings.slugDescription": "در آدرس پروژه استفاده می‌شود. تغییر آن آدرس را به‌روزرسانی می‌کند؛ برای استفاده از شناسه پروژه خالی بگذارید.",
"settings.startDirectoryConversation": "موضوع جدید اینجا",
"settings.title": "تنظیمات پروژه",
- "settings.viewDirectories": "مشاهده پوشه‌ها ({{count}})",
- "settings.workLocations": "دایرکتوری‌های کاری",
"sidebar.agentsEmpty": "هنوز هیچ عاملی متصل نشده است",
"sidebar.conversationsEmpty": "هنوز هیچ موضوع پروژه‌ای وجود ندارد",
"sidebar.coordinatorTag": "رهبر",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 1206f42a1ba..84b6f4991f9 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "En ligne · {{count}} connexions",
"heteroAgent.executionTarget.personalGroup": "Appareils privés",
"heteroAgent.executionTarget.presenceChecking": "Vérification du statut…",
- "heteroAgent.executionTarget.projectDevicesHint": "Seuls les appareils avec le répertoire de travail de ce projet sont listés. Ajoutez un répertoire pour un autre appareil dans les paramètres du projet.",
"heteroAgent.executionTarget.reconnect": "Reconnecter",
"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",
diff --git a/locales/fr-FR/project.json b/locales/fr-FR/project.json
index ab30befb112..6f5848f2729 100644
--- a/locales/fr-FR/project.json
+++ b/locales/fr-FR/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Ajouter un dossier",
"settings.addDirectoryDescription": "Sélectionnez un environnement et un appareil connecté, puis entrez le chemin complet d'un dossier existant. Les fichiers restent sur cet appareil.",
"settings.addDirectoryFailed": "Impossible d'ajouter le répertoire de travail",
- "settings.addEnvironment": "Ajouter un environnement",
"settings.advanced": "Avancé",
- "settings.allEnvironments": "Tous les environnements",
- "settings.configureDirectory": "Ajouter un répertoire de travail",
"settings.createdAt": "Créé le {{date}}",
"settings.creator": "Créateur",
"settings.creatorUnknown": "Ancien membre",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Utilisé dans l'URL du projet. Le modifier met à jour l'adresse ; laissez vide pour utiliser l'ID du projet.",
"settings.startDirectoryConversation": "Nouveau sujet ici",
"settings.title": "Paramètres du projet",
- "settings.viewDirectories": "Voir les dossiers ({{count}})",
- "settings.workLocations": "Répertoires de travail",
"sidebar.agentsEmpty": "Aucun agent n'est encore connecté",
"sidebar.conversationsEmpty": "Aucun sujet de projet pour le moment",
"sidebar.coordinatorTag": "Responsable",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 413b79fdf07..4cfb1d80302 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} connessioni",
"heteroAgent.executionTarget.personalGroup": "Dispositivi privati",
"heteroAgent.executionTarget.presenceChecking": "Verifica dello stato in corso…",
- "heteroAgent.executionTarget.projectDevicesHint": "Sono elencati solo i dispositivi con la directory di lavoro di questo progetto. Aggiungi una directory per un altro dispositivo nelle impostazioni del progetto.",
"heteroAgent.executionTarget.reconnect": "Riconnetti",
"heteroAgent.executionTarget.reconnectFailed": "Impossibile riconnettere questo dispositivo. Assicurati che l'app desktop sia in esecuzione, quindi riprova.",
"heteroAgent.executionTarget.sandbox": "Sandbox cloud",
diff --git a/locales/it-IT/project.json b/locales/it-IT/project.json
index 659581c7a1e..ba4e6981ec8 100644
--- a/locales/it-IT/project.json
+++ b/locales/it-IT/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Aggiungi cartella",
"settings.addDirectoryDescription": "Seleziona un ambiente e un dispositivo connesso, quindi inserisci il percorso completo di una cartella esistente. I file rimangono su quel dispositivo.",
"settings.addDirectoryFailed": "Impossibile aggiungere la directory di lavoro",
- "settings.addEnvironment": "Aggiungi ambiente",
"settings.advanced": "Avanzato",
- "settings.allEnvironments": "Tutti gli ambienti",
- "settings.configureDirectory": "Aggiungi una directory di lavoro",
"settings.createdAt": "Creato {{date}}",
"settings.creator": "Creatore",
"settings.creatorUnknown": "Ex membro",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Utilizzato nell'URL del progetto. Modificarlo aggiorna l'indirizzo; lascia vuoto per utilizzare l'ID del progetto.",
"settings.startDirectoryConversation": "Nuovo argomento qui",
"settings.title": "Impostazioni del progetto",
- "settings.viewDirectories": "Visualizza cartelle ({{count}})",
- "settings.workLocations": "Directory di lavoro",
"sidebar.agentsEmpty": "Nessun agente è ancora connesso",
"sidebar.conversationsEmpty": "Nessun argomento di progetto ancora",
"sidebar.coordinatorTag": "Guida",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 354904626d6..07a2b68579d 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "オンライン · {{count}} 接続",
"heteroAgent.executionTarget.personalGroup": "プライベートデバイス",
"heteroAgent.executionTarget.presenceChecking": "ステータスを確認中…",
- "heteroAgent.executionTarget.projectDevicesHint": "このプロジェクトの作業ディレクトリを持つデバイスのみが表示されます。プロジェクト設定で別のデバイスのディレクトリを追加してください。",
"heteroAgent.executionTarget.reconnect": "再接続",
"heteroAgent.executionTarget.reconnectFailed": "このデバイスに再接続できませんでした。デスクトップアプリが実行中であることを確認し、再試行してください。",
"heteroAgent.executionTarget.sandbox": "クラウドサンドボックス",
diff --git a/locales/ja-JP/project.json b/locales/ja-JP/project.json
index 9842fb47cd4..b565f1570a9 100644
--- a/locales/ja-JP/project.json
+++ b/locales/ja-JP/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "フォルダを追加",
"settings.addDirectoryDescription": "環境と接続されたデバイスを選択し、既存フォルダのフルパスを入力してください。ファイルはそのデバイスに残ります。",
"settings.addDirectoryFailed": "作業ディレクトリを追加できませんでした",
- "settings.addEnvironment": "環境を追加",
"settings.advanced": "詳細設定",
- "settings.allEnvironments": "すべての環境",
- "settings.configureDirectory": "作業ディレクトリを追加",
"settings.createdAt": "作成日 {{date}}",
"settings.creator": "作成者",
"settings.creatorUnknown": "元メンバー",
@@ -340,8 +337,6 @@
"settings.slugDescription": "プロジェクトURLで使用されます。変更するとアドレスが更新されます。空白のままにするとプロジェクトIDが使用されます。",
"settings.startDirectoryConversation": "ここで新しいトピックを開始",
"settings.title": "プロジェクト設定",
- "settings.viewDirectories": "フォルダを見る({{count}})",
- "settings.workLocations": "作業ディレクトリ",
"sidebar.agentsEmpty": "まだ接続されているエージェントはありません",
"sidebar.conversationsEmpty": "まだプロジェクトトピックはありません",
"sidebar.coordinatorTag": "リーダー",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index 0113fd77f46..ed08c522ad8 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "온라인 · {{count}} 연결",
"heteroAgent.executionTarget.personalGroup": "비공개 장치",
"heteroAgent.executionTarget.presenceChecking": "상태 확인 중…",
- "heteroAgent.executionTarget.projectDevicesHint": "이 프로젝트의 작업 디렉토리가 있는 장치만 나열됩니다. 프로젝트 설정에서 다른 장치에 디렉토리를 추가하세요.",
"heteroAgent.executionTarget.reconnect": "다시 연결",
"heteroAgent.executionTarget.reconnectFailed": "이 장치를 다시 연결할 수 없습니다. 데스크톱 앱이 실행 중인지 확인한 후 다시 시도하세요.",
"heteroAgent.executionTarget.sandbox": "클라우드 샌드박스",
diff --git a/locales/ko-KR/project.json b/locales/ko-KR/project.json
index 5ee58a3caec..68bc456d785 100644
--- a/locales/ko-KR/project.json
+++ b/locales/ko-KR/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "폴더 추가",
"settings.addDirectoryDescription": "환경과 연결된 장치를 선택한 다음 기존 폴더의 전체 경로를 입력하세요. 파일은 해당 장치에 남아 있습니다.",
"settings.addDirectoryFailed": "작업 디렉토리를 추가할 수 없습니다",
- "settings.addEnvironment": "환경 추가",
"settings.advanced": "고급",
- "settings.allEnvironments": "모든 환경",
- "settings.configureDirectory": "작업 디렉토리 추가",
"settings.createdAt": "생성일 {{date}}",
"settings.creator": "생성자",
"settings.creatorUnknown": "이전 멤버",
@@ -340,8 +337,6 @@
"settings.slugDescription": "프로젝트 URL에 사용됩니다. 변경하면 주소가 업데이트됩니다. 프로젝트 ID를 사용하려면 비워 두세요.",
"settings.startDirectoryConversation": "여기에서 새 주제 시작",
"settings.title": "프로젝트 설정",
- "settings.viewDirectories": "폴더 보기 ({{count}})",
- "settings.workLocations": "작업 디렉토리",
"sidebar.agentsEmpty": "아직 연결된 에이전트가 없습니다",
"sidebar.conversationsEmpty": "아직 프로젝트 주제가 없습니다",
"sidebar.coordinatorTag": "리드",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 5f8687e6072..ed0c1cc293b 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} verbindingen",
"heteroAgent.executionTarget.personalGroup": "Privéapparaten",
"heteroAgent.executionTarget.presenceChecking": "Status controleren…",
- "heteroAgent.executionTarget.projectDevicesHint": "Alleen apparaten met de werkmap van dit project worden weergegeven. Voeg een map toe voor een ander apparaat in de projectinstellingen.",
"heteroAgent.executionTarget.reconnect": "Opnieuw verbinden",
"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",
diff --git a/locales/nl-NL/project.json b/locales/nl-NL/project.json
index eaba28ee235..eff49986cbd 100644
--- a/locales/nl-NL/project.json
+++ b/locales/nl-NL/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Map toevoegen",
"settings.addDirectoryDescription": "Selecteer een omgeving en een verbonden apparaat, voer vervolgens het volledige pad van een bestaande map in. Bestanden blijven op dat apparaat.",
"settings.addDirectoryFailed": "Kon werkmap niet toevoegen",
- "settings.addEnvironment": "Omgeving toevoegen",
"settings.advanced": "Geavanceerd",
- "settings.allEnvironments": "Alle omgevingen",
- "settings.configureDirectory": "Werkmap toevoegen",
"settings.createdAt": "Aangemaakt op {{date}}",
"settings.creator": "Maker",
"settings.creatorUnknown": "Voormalig lid",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Wordt gebruikt in de project-URL. Het wijzigen ervan werkt het adres bij; laat leeg om de project-ID te gebruiken.",
"settings.startDirectoryConversation": "Nieuw onderwerp hier",
"settings.title": "Projectinstellingen",
- "settings.viewDirectories": "Bekijk mappen ({{count}})",
- "settings.workLocations": "Werkmappen",
"sidebar.agentsEmpty": "Er zijn nog geen agenten verbonden",
"sidebar.conversationsEmpty": "Nog geen projectonderwerpen",
"sidebar.coordinatorTag": "Leiding",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 0fd5ea15615..c2910701016 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} połączenia",
"heteroAgent.executionTarget.personalGroup": "Prywatne urządzenia",
"heteroAgent.executionTarget.presenceChecking": "Sprawdzanie statusu…",
- "heteroAgent.executionTarget.projectDevicesHint": "Wyświetlane są tylko urządzenia z katalogiem roboczym tego projektu. Dodaj katalog dla innego urządzenia w ustawieniach projektu.",
"heteroAgent.executionTarget.reconnect": "Połącz ponownie",
"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",
diff --git a/locales/pl-PL/project.json b/locales/pl-PL/project.json
index 2ddd2ef6aba..11005103156 100644
--- a/locales/pl-PL/project.json
+++ b/locales/pl-PL/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Dodaj folder",
"settings.addDirectoryDescription": "Wybierz środowisko i podłączone urządzenie, a następnie wprowadź pełną ścieżkę istniejącego folderu. Pliki pozostaną na tym urządzeniu.",
"settings.addDirectoryFailed": "Nie udało się dodać katalogu roboczego",
- "settings.addEnvironment": "Dodaj środowisko",
"settings.advanced": "Zaawansowane",
- "settings.allEnvironments": "Wszystkie środowiska",
- "settings.configureDirectory": "Dodaj katalog roboczy",
"settings.createdAt": "Utworzono {{date}}",
"settings.creator": "Twórca",
"settings.creatorUnknown": "Były członek",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Używane w adresie URL projektu. Zmiana aktualizuje adres; pozostaw puste, aby użyć identyfikatora projektu.",
"settings.startDirectoryConversation": "Nowy temat tutaj",
"settings.title": "Ustawienia projektu",
- "settings.viewDirectories": "Wyświetl foldery ({{count}})",
- "settings.workLocations": "Katalogi robocze",
"sidebar.agentsEmpty": "Brak podłączonych agentów",
"sidebar.conversationsEmpty": "Brak tematów projektowych",
"sidebar.coordinatorTag": "Lider",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 9483cbf26a6..79edde9a107 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} conexões",
"heteroAgent.executionTarget.personalGroup": "Dispositivos Privados",
"heteroAgent.executionTarget.presenceChecking": "Verificando status…",
- "heteroAgent.executionTarget.projectDevicesHint": "Apenas dispositivos com o diretório de trabalho deste projeto estão listados. Adicione um diretório para outro dispositivo nas configurações do projeto.",
"heteroAgent.executionTarget.reconnect": "Reconectar",
"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",
diff --git a/locales/pt-BR/project.json b/locales/pt-BR/project.json
index f199b839ec3..abd876c8665 100644
--- a/locales/pt-BR/project.json
+++ b/locales/pt-BR/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Adicionar pasta",
"settings.addDirectoryDescription": "Selecione um ambiente e um dispositivo conectado, depois insira o caminho completo de uma pasta existente. Os arquivos permanecem nesse dispositivo.",
"settings.addDirectoryFailed": "Não foi possível adicionar o diretório de trabalho",
- "settings.addEnvironment": "Adicionar ambiente",
"settings.advanced": "Avançado",
- "settings.allEnvironments": "Todos os ambientes",
- "settings.configureDirectory": "Adicionar um diretório de trabalho",
"settings.createdAt": "Criado em {{date}}",
"settings.creator": "Criador",
"settings.creatorUnknown": "Ex-membro",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Usado na URL do projeto. Alterá-lo atualiza o endereço; deixe em branco para usar o ID do projeto.",
"settings.startDirectoryConversation": "Novo tópico aqui",
"settings.title": "Configurações do projeto",
- "settings.viewDirectories": "Ver pastas ({{count}})",
- "settings.workLocations": "Diretórios de trabalho",
"sidebar.agentsEmpty": "Nenhum agente conectado ainda",
"sidebar.conversationsEmpty": "Ainda não há tópicos do projeto",
"sidebar.coordinatorTag": "Líder",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 9128dfbdbd7..18586d03423 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Онлайн · {{count}} соединений",
"heteroAgent.executionTarget.personalGroup": "Личные устройства",
"heteroAgent.executionTarget.presenceChecking": "Проверка статуса…",
- "heteroAgent.executionTarget.projectDevicesHint": "Указаны только устройства с рабочей директорией этого проекта. Добавьте директорию для другого устройства в настройках проекта.",
"heteroAgent.executionTarget.reconnect": "Переподключить",
"heteroAgent.executionTarget.reconnectFailed": "Не удалось переподключить это устройство. Убедитесь, что настольное приложение запущено, затем попробуйте снова.",
"heteroAgent.executionTarget.sandbox": "Облачная песочница",
diff --git a/locales/ru-RU/project.json b/locales/ru-RU/project.json
index 1e6f9572f24..a1dbd37fd90 100644
--- a/locales/ru-RU/project.json
+++ b/locales/ru-RU/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Добавить папку",
"settings.addDirectoryDescription": "Выберите окружение и подключенное устройство, затем введите полный путь к существующей папке. Файлы остаются на этом устройстве.",
"settings.addDirectoryFailed": "Не удалось добавить рабочую директорию",
- "settings.addEnvironment": "Добавить окружение",
"settings.advanced": "Дополнительно",
- "settings.allEnvironments": "Все окружения",
- "settings.configureDirectory": "Добавить рабочую директорию",
"settings.createdAt": "Создано {{date}}",
"settings.creator": "Создатель",
"settings.creatorUnknown": "Бывший участник",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Используется в URL проекта. Изменение обновляет адрес; оставьте пустым, чтобы использовать идентификатор проекта.",
"settings.startDirectoryConversation": "Новая тема здесь",
"settings.title": "Настройки проекта",
- "settings.viewDirectories": "Просмотр папок ({{count}})",
- "settings.workLocations": "Рабочие директории",
"sidebar.agentsEmpty": "Агенты еще не подключены",
"sidebar.conversationsEmpty": "Темы проекта пока отсутствуют",
"sidebar.coordinatorTag": "Руководитель",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index 417337f0d0c..086ebf34811 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Çevrimiçi · {{count}} bağlantı",
"heteroAgent.executionTarget.personalGroup": "Özel Cihazlar",
"heteroAgent.executionTarget.presenceChecking": "Durum kontrol ediliyor…",
- "heteroAgent.executionTarget.projectDevicesHint": "Sadece bu projenin çalışma dizinine sahip cihazlar listelenir. Proje ayarlarından başka bir cihaz için bir dizin ekleyin.",
"heteroAgent.executionTarget.reconnect": "Yeniden bağlan",
"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",
diff --git a/locales/tr-TR/project.json b/locales/tr-TR/project.json
index d8647118570..24e059d5be1 100644
--- a/locales/tr-TR/project.json
+++ b/locales/tr-TR/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Klasör ekle",
"settings.addDirectoryDescription": "Bir ortam ve bağlı bir cihaz seçin, ardından mevcut bir klasörün tam yolunu girin. Dosyalar o cihazda kalır.",
"settings.addDirectoryFailed": "Çalışma dizini eklenemedi",
- "settings.addEnvironment": "Ortam ekle",
"settings.advanced": "Gelişmiş",
- "settings.allEnvironments": "Tüm ortamlar",
- "settings.configureDirectory": "Bir çalışma dizini ekle",
"settings.createdAt": "{{date}} tarihinde oluşturuldu",
"settings.creator": "Oluşturan",
"settings.creatorUnknown": "Eski üye",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Proje URL'sinde kullanılır. Değiştirilmesi adresi günceller; boş bırakılırsa proje kimliği kullanılır.",
"settings.startDirectoryConversation": "Burada yeni bir konu",
"settings.title": "Proje ayarları",
- "settings.viewDirectories": "Klasörleri görüntüle ({{count}})",
- "settings.workLocations": "Çalışma dizinleri",
"sidebar.agentsEmpty": "Henüz bağlı ajan yok",
"sidebar.conversationsEmpty": "Henüz proje konusu yok",
"sidebar.coordinatorTag": "Lider",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 1de0e59c306..9942e1d944e 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -1539,7 +1539,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "Trực tuyến · {{count}} kết nối",
"heteroAgent.executionTarget.personalGroup": "Thiết bị riêng tư",
"heteroAgent.executionTarget.presenceChecking": "Đang kiểm tra trạng thái…",
- "heteroAgent.executionTarget.projectDevicesHint": "Chỉ các thiết bị có thư mục làm việc của dự án này được liệt kê. Thêm một thư mục cho thiết bị khác trong cài đặt dự án.",
"heteroAgent.executionTarget.reconnect": "Kết nối lại",
"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",
diff --git a/locales/vi-VN/project.json b/locales/vi-VN/project.json
index d0271b8febc..e042137cded 100644
--- a/locales/vi-VN/project.json
+++ b/locales/vi-VN/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "Thêm thư mục",
"settings.addDirectoryDescription": "Chọn một môi trường và một thiết bị được kết nối, sau đó nhập đường dẫn đầy đủ của một thư mục hiện có. Các tệp sẽ ở lại trên thiết bị đó.",
"settings.addDirectoryFailed": "Không thể thêm thư mục làm việc",
- "settings.addEnvironment": "Thêm môi trường",
"settings.advanced": "Nâng cao",
- "settings.allEnvironments": "Tất cả môi trường",
- "settings.configureDirectory": "Thêm một thư mục làm việc",
"settings.createdAt": "Đã tạo {{date}}",
"settings.creator": "Người tạo",
"settings.creatorUnknown": "Thành viên cũ",
@@ -340,8 +337,6 @@
"settings.slugDescription": "Được sử dụng trong URL dự án. Thay đổi nó sẽ cập nhật địa chỉ; để trống để sử dụng ID dự án.",
"settings.startDirectoryConversation": "Chủ đề mới tại đây",
"settings.title": "Cài đặt dự án",
- "settings.viewDirectories": "Xem thư mục ({{count}})",
- "settings.workLocations": "Thư mục làm việc",
"sidebar.agentsEmpty": "Chưa có tác nhân nào được kết nối",
"sidebar.conversationsEmpty": "Chưa có chủ đề dự án nào",
"sidebar.coordinatorTag": "Người dẫn dắt",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4509128cb71..072f04b4f02 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1639,7 +1639,6 @@
"heteroAgent.executionTarget.otherDevicesGroup": "其他设备",
"heteroAgent.executionTarget.personalGroup": "私人设备",
"heteroAgent.executionTarget.presenceChecking": "正在确认状态…",
- "heteroAgent.executionTarget.projectDevicesHint": "仅列出已绑定此项目工作目录的设备。其他设备可在项目设置中添加目录。",
"heteroAgent.executionTarget.reconnect": "重新连接",
"heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。",
"heteroAgent.executionTarget.sandbox": "云端沙箱",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index d1162b3a845..27dc482fd61 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -260,22 +260,22 @@
"createFromGithub.urlLabel": "或粘贴仓库链接",
"createFromGithub.urlPlaceholder": "https://github.com/owner/repo",
"delete.confirm.continue": "删除项目",
- "delete.confirm.kept.files": "设备上工作目录中的文件",
+ "delete.confirm.kept.files": "设备目录中的文件",
"delete.confirm.kept.work": "任务、目标、话题和频道",
"delete.confirm.keptLead": "以下内容会保留,但不再属于任何项目:",
"delete.confirm.namePrompt": "输入“{{name}}”以确认",
"delete.confirm.removed.automation": "项目组件及其运行记录、Linear 同步规则、Review 站点、看板和项目记忆",
"delete.confirm.removed.bindings": "与助理、群组和知识库的关联(你的助理和知识库会保留)",
- "delete.confirm.removed.settings": "项目设置、成员、工作目录和环境",
+ "delete.confirm.removed.settings": "项目设置、成员、设备目录和环境",
"delete.confirm.removedLead": "删除“{{name}}”后无法恢复,将永久移除:",
"delete.confirm.title": "删除项目",
"delete.description": "永久删除此项目及其设置。任务、目标和话题会保留,但不再属于任何项目。",
- "directories.add": "添加工作目录",
+ "directories.add": "添加设备目录",
"directories.autoFileTopics": "此目录已有的 {{count}} 个话题将自动关联到项目。",
"directories.bind": "关联项目",
"directories.bindDescription": "将下方文件夹绑定到项目,之后即可从项目中继续工作。文件仍保留在当前设备上。",
"directories.bindFailed": "目录关联失败",
- "directories.boundRoot": "此话题已绑定项目工作目录。要使用其他目录,请新建话题。",
+ "directories.boundRoot": "此话题已绑定项目的设备目录。要使用其他目录,请新建话题。",
"directories.boundTip": "该目录属于项目({{path}})。切换设备即可改用该设备上的项目目录。",
"directories.chooseAgent": "选择 Agent",
"directories.conversations": "已有话题",
@@ -304,7 +304,7 @@
"directories.stagedNewTopic": "将在 <project>{{name}}</project> 项目中开始新话题",
"directories.start": "在此开始工作",
"directories.startInProject": "在 {{name}} 中开始工作",
- "directories.title": "工作目录",
+ "directories.title": "设备目录",
"directories.topicsSkipped": "目录已关联。有 {{count}} 个话题未归入项目:它们在其他目录或设备上运行、已属于其他项目、仍在运行,或已不存在。",
"directories.unavailable": "设备离线或目录不可用,请重新连接后重试。",
"directories.untitled": "未命名话题",
@@ -420,13 +420,16 @@
"overview.agentSelect": "选择 Agent",
"overview.composerPlaceholder": "告诉项目接下来要推进什么…",
"overview.context.location.devices": "设备",
- "overview.context.location.directories": "项目工作目录",
- "overview.context.location.directoryUnavailable": "无法访问这个工作目录,请确认设备在线且目录仍然存在。",
- "overview.context.location.environments": "代码环境",
- "overview.context.location.noDirectories": "这台设备上还没有项目工作目录。",
- "overview.context.location.noDirectoryTooltip": "这台设备上还没有项目工作目录,对话会在设备的默认目录中开始。",
- "overview.context.location.noEnvironments": "还没有代码环境。",
- "overview.context.location.title": "工作位置",
+ "overview.context.location.directories": "设备目录",
+ "overview.context.location.directoryUnavailable": "无法访问这个设备目录,请确认设备在线且目录仍然存在。",
+ "overview.context.location.emptySandbox": "空白沙箱",
+ "overview.context.location.emptySandboxDesc": "不套用项目环境,从空文件夹开始",
+ "overview.context.location.environments": "环境",
+ "overview.context.location.noDirectories": "这台设备上还没有目录。",
+ "overview.context.location.noDirectoryTooltip": "这台设备上还没有项目的目录,对话会在设备的默认目录中开始。",
+ "overview.context.location.noEnvironments": "环境里还没有代码库。",
+ "overview.context.location.sandboxes": "云端沙箱",
+ "overview.context.location.title": "执行环境",
"overview.context.repository.publishHint": "这个助手已共享给工作区,只能使用已发布的环境,因此仓库会以工作区成员可见的环境添加。",
"overview.context.target.device": "已连接设备",
"overview.context.target.noneTooltip": "这个助手还没有可运行的位置。切换到云端沙箱后,它就能直接处理代码。",
@@ -535,27 +538,31 @@
"sections.knowledgeBases": "资料库",
"sections.tasks": "任务",
"settings.addDirectory": "添加文件夹",
- "settings.addDirectoryDescription": "选择环境和已连接的设备,再填写设备上已有文件夹的完整路径。文件保留在原设备上。",
- "settings.addDirectoryFailed": "添加工作位置失败",
- "settings.addEnvironment": "关联环境",
+ "settings.addDirectoryDescription": "选择一台已连接的设备,再填写一个已存在文件夹的完整路径。文件仍保留在这台设备上。",
+ "settings.addDirectoryFailed": "添加设备目录失败",
+ "settings.addExecutionEnvironment": "添加执行环境",
"settings.advanced": "高级设置",
- "settings.allEnvironments": "全部环境",
- "settings.configureDirectory": "添加工作目录",
+ "settings.cloudSandboxGroup": "云端沙箱",
+ "settings.configureSandbox": "配置",
"settings.createdAt": "创建于 {{date}}",
"settings.creator": "创建人",
"settings.creatorUnknown": "已离开的成员",
"settings.description": "项目说明",
- "settings.deviceOffline": "设备未连接",
- "settings.deviceOnline": "设备已连接",
- "settings.directoryListDescription": "本项目在这些设备文件夹中工作,Agent 会在对应设备上读取和修改其中的文件。",
+ "settings.deviceOffline": "离线",
+ "settings.deviceOnline": "在线",
"settings.directoryUnavailable": "设备未连接或目录不可用。连接设备并检查路径后重试。",
+ "settings.directoryUnavailableTag": "不可用",
+ "settings.directoryUnavailable_failed": "这个目录暂时无法启用,请检查路径或稍后重试。",
+ "settings.directoryUnavailable_missing": "设备上找不到这个文件夹,请编辑路径或删除。",
+ "settings.directoryUnavailable_needsManager": "需要项目管理员在设备在线时打开此页面。",
+ "settings.directoryUnavailable_offline": "设备离线,设备上线后即可使用这个目录。",
"settings.editDirectory": "修改文件夹",
"settings.editDirectoryBusy": "有话题正在此文件夹运行,请等待结束后重试。",
- "settings.editDirectoryDescription": "选择这个工作目录对应的设备和文件夹。相关话题会一起迁移到新文件夹,并在那里开始新的会话。",
+ "settings.editDirectoryDescription": "选择这个设备目录对应的设备和文件夹。相关话题会一起迁移到新文件夹,并在那里开始新的会话。",
"settings.editDirectoryFailed": "无法修改文件夹",
"settings.editDirectoryOtherEnvironment": "这个文件夹已属于其他环境,请选择别的文件夹或设备。",
- "settings.environmentIntro": "项目里的每个对话都在这个环境中运行:克隆下面的仓库、执行初始化命令,并注入环境变量。",
- "settings.environments": "环境",
+ "settings.environments": "执行环境",
+ "settings.executionOrderHint": "新对话会按列表顺序,自动使用第一个可用的执行环境,拖动可调整顺序。",
"settings.general": "基础设置",
"settings.generalDescription": "管理项目名称、链接和说明。",
"settings.identifier": "项目标识",
@@ -569,19 +576,21 @@
"settings.logoUploadFailed": "Logo 上传失败",
"settings.members": "成员",
"settings.nameHint": "最多 255 个字符。",
- "settings.noDirectories": "还没有工作目录。添加已连接设备上的文件夹后,即可在此新建对话。",
+ "settings.noDirectories": "还没有设备目录。添加已连接设备上的文件夹后,即可在那台设备上运行项目。",
"settings.noRepository": "未关联 GitHub 仓库",
"settings.removeDirectory": "移除文件夹",
- "settings.removeDirectoryConfirmDescription": "{{device}} 上的 {{path}} 将不再是本项目的工作目录。设备上的文件不会改动,相关话题仍保留在项目中,但不再关联此文件夹。",
+ "settings.removeDirectoryConfirmDescription": "{{device}} 上的 {{path}} 将不再是本项目的设备目录。设备上的文件不会改动,相关话题仍保留在项目中,但不再关联此文件夹。",
"settings.removeDirectoryConfirmTitle": "从项目中移除「{{name}}」?",
"settings.removeDirectoryFailed": "无法移除文件夹。如果有话题正在此处运行,请等待结束后重试。",
+ "settings.reorderFailed": "没能保存新的顺序,请重试。",
+ "settings.sandboxNoRepository": "未添加代码库",
"settings.saveFailed": "保存失败",
"settings.saved": "已保存",
+ "settings.setDeviceDirectory": "设置目录",
+ "settings.setDirectoryDescription": "填写 {{device}} 上一个已存在文件夹的完整路径,文件仍保留在这台设备上。",
"settings.slugDescription": "用于项目链接。修改后地址会更新,留空则使用项目 ID。",
"settings.startDirectoryConversation": "在此新建话题",
"settings.title": "项目设置",
- "settings.viewDirectories": "查看目录({{count}})",
- "settings.workLocations": "工作目录",
"sidebar.agentsEmpty": "还没有关联智能体",
"sidebar.conversationsEmpty": "还没有项目话题",
"sidebar.coordinatorTag": "主管",
@@ -595,10 +604,10 @@
"sidebar.sort.updatedAt": "最近更新",
"sidebar.title": "项目",
"sidebar.untitledConversation": "未命名话题",
- "topics.addLocation": "添加工作目录(可选)",
+ "topics.addLocation": "添加设备目录(可选)",
"topics.all": "全部话题",
"topics.associateFailed": "无法将话题归入项目",
- "topics.chooseLocation": "选择工作目录",
+ "topics.chooseLocation": "选择设备目录",
"topics.chooseTopic": "从左侧选择话题,或新建话题开始工作",
"topics.complete": "标记完成",
"topics.executionContext": "工作位置",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 59cd8933e44..84960c395b1 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -997,8 +997,13 @@
"environments.form.runtime": "运行与存储",
"environments.form.saved": "已保存",
"environments.form.setup": "初始化",
- "environments.form.sources": "源代码",
+ "environments.form.setupAndVariables": "Setup 与环境变量",
+ "environments.form.setupConfigured": "Setup 已配置",
+ "environments.form.setupNotConfigured": "未配置 Setup",
+ "environments.form.sources": "代码库",
"environments.form.sourcesHint": "在其他步骤之前通过 HTTPS 克隆。私有仓库通过已授权该仓库的 GitHub App 安装来克隆;环境本身不保存任何凭据。",
+ "environments.form.variablesCount_one": "{{count}} 个变量",
+ "environments.form.variablesCount_other": "{{count}} 个变量",
"environments.github.connect": "连接 GitHub",
"environments.github.label": "代码仓库",
"environments.github.loadFailed": "无法加载 GitHub 仓库,请重试。",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 633e2825f10..a7b1443f17b 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -1541,7 +1541,6 @@
"heteroAgent.executionTarget.onlineConnections_other": "在線 · {{count}} 個連接",
"heteroAgent.executionTarget.personalGroup": "私人裝置",
"heteroAgent.executionTarget.presenceChecking": "正在檢查狀態…",
- "heteroAgent.executionTarget.projectDevicesHint": "僅列出具有此專案工作目錄的設備。請在專案設定中為其他設備新增目錄。",
"heteroAgent.executionTarget.reconnect": "重新連接",
"heteroAgent.executionTarget.reconnectFailed": "無法重新連接此裝置。請確保桌面應用程式正在運行,然後再試一次。",
"heteroAgent.executionTarget.sandbox": "雲端沙盒",
diff --git a/locales/zh-TW/project.json b/locales/zh-TW/project.json
index 3c13fabeb6c..386da259e7a 100644
--- a/locales/zh-TW/project.json
+++ b/locales/zh-TW/project.json
@@ -306,10 +306,7 @@
"settings.addDirectory": "新增資料夾",
"settings.addDirectoryDescription": "選擇一個環境和一個已連接的設備,然後輸入現有資料夾的完整路徑。檔案將保留在該設備上。",
"settings.addDirectoryFailed": "無法新增工作目錄",
- "settings.addEnvironment": "新增環境",
"settings.advanced": "進階",
- "settings.allEnvironments": "所有環境",
- "settings.configureDirectory": "新增工作目錄",
"settings.createdAt": "建立於 {{date}}",
"settings.creator": "建立者",
"settings.creatorUnknown": "前成員",
@@ -340,8 +337,6 @@
"settings.slugDescription": "用於專案 URL。更改它會更新地址;留空則使用專案 ID。",
"settings.startDirectoryConversation": "在此開始新主題",
"settings.title": "專案設定",
- "settings.viewDirectories": "查看資料夾({{count}})",
- "settings.workLocations": "工作目錄",
"sidebar.agentsEmpty": "尚未連接代理",
"sidebar.conversationsEmpty": "尚無專案主題",
"sidebar.coordinatorTag": "負責人",
diff --git a/packages/database/src/models/projectWorkingDirectory.ts b/packages/database/src/models/projectWorkingDirectory.ts
index 8ea3a8dfe60..0d7dc8e6281 100644
--- a/packages/database/src/models/projectWorkingDirectory.ts
+++ b/packages/database/src/models/projectWorkingDirectory.ts
@@ -115,6 +115,8 @@ export class ProjectWorkingDirectoryModel {
platform: devices.platform,
path: sql<string>`coalesce(${environmentInstances.workingDirectory}, ${projectWorkingDirectories.path})`,
permission: projectWorkingDirectories.permission,
+ /** Its place among the project's execution environments; see `executionOrder`. */
+ sortOrder: projectWorkingDirectories.sortOrder,
// Whether a run can start here: the same linked, enabled and writable
// binding `resolve` requires, so a UI start affordance can match it.
runnable: sql<boolean>`coalesce(${environments.id} is not null and ${environmentInstances.enabled} and ${environments.enabled} and ${projectEnvironments.enabled} and ${projectWorkingDirectories.permission} = 'readWrite', false)`,
diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
index 056c220298c..1df4dd0907b 100644
--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
@@ -826,3 +826,77 @@ describe('ProjectDirectoryRepository.relocate', () => {
).rejects.toThrow('Project not found or access denied');
});
});
+
+// The project's execution environments — its device folders and the cloud
+// sandbox — in the order a new conversation tries them.
+describe('ProjectDirectoryRepository execution order', () => {
+ const order = async () => {
+ const { sandbox } = await repo.executionOrder(base.projectId);
+ const folders = await directoryModel.list(base.projectId);
+ return [
+ ...folders.map((folder) => ({ id: folder.path, sortOrder: folder.sortOrder })),
+ {
+ id: 'sandbox',
+ sortOrder: sandbox,
+ },
+ ]
+ .sort(
+ (a, b) =>
+ a.sortOrder - b.sortOrder || Number(a.id === 'sandbox') - Number(b.id === 'sandbox'),
+ )
+ .map((item) => item.id);
+ };
+
+ it('tries folders before the sandbox until anything is reordered', async () => {
+ await repo.bind(base);
+ await repo.bind({ ...base, path: '/work/second' });
+
+ expect(await order()).toEqual(['/work/repo', '/work/second', 'sandbox']);
+ });
+
+ it('stores a reordered priority for folders and the sandbox', async () => {
+ const first = await repo.bind(base);
+ const second = await repo.bind({ ...base, path: '/work/second' });
+
+ await repo.reorderExecutionEnvironments(base.projectId, ['sandbox', second.id, first.id]);
+
+ expect(await order()).toEqual(['sandbox', '/work/second', '/work/repo']);
+ });
+
+ it('places a new folder before the sandbox when the sandbox is last', async () => {
+ const first = await repo.bind(base);
+ await repo.reorderExecutionEnvironments(base.projectId, [first.id, 'sandbox']);
+
+ await repo.bind({ ...base, path: '/work/second' });
+
+ expect(await order()).toEqual(['/work/repo', '/work/second', 'sandbox']);
+ });
+
+ it('places a new folder last when the sandbox was moved ahead of folders', async () => {
+ const first = await repo.bind(base);
+ await repo.reorderExecutionEnvironments(base.projectId, ['sandbox', first.id]);
+
+ await repo.bind({ ...base, path: '/work/second' });
+
+ expect(await order()).toEqual(['sandbox', '/work/repo', '/work/second']);
+ });
+
+ it("refuses an order naming a folder that is not this project's", async () => {
+ await repo.bind(base);
+
+ await expect(
+ repo.reorderExecutionEnvironments(base.projectId, [
+ 'sandbox',
+ '00000000-0000-0000-0000-000000000000',
+ ]),
+ ).rejects.toThrow('Unknown project directory');
+ });
+
+ it('lets only someone who may change the project reorder it', async () => {
+ const first = await repo.bind(base);
+
+ await expect(
+ otherRepo.reorderExecutionEnvironments(base.projectId, ['sandbox', first.id]),
+ ).rejects.toThrow('Project not found or access denied');
+ });
+});
diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.ts
index 3727658eaf2..9e7b7c22c04 100644
--- a/packages/database/src/repositories/projectDirectory/index.ts
+++ b/packages/database/src/repositories/projectDirectory/index.ts
@@ -1,7 +1,7 @@
import type { ChatTopicMetadata } from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import { and, eq, inArray, isNull } from 'drizzle-orm';
+import { and, eq, inArray, isNull, max, ne } from 'drizzle-orm';
import { normalizeProjectRepository } from '../../models/environment';
import { EnvironmentInstanceModel } from '../../models/environmentInstance';
@@ -11,7 +11,14 @@ import {
ProjectWorkingDirectoryModel,
} from '../../models/projectWorkingDirectory';
import { hasLiveTaskCallbackReservation } from '../../models/topic';
-import { agents, devices, environments, projectWorkingDirectories, topics } from '../../schemas';
+import {
+ agents,
+ devices,
+ environments,
+ projectEnvironments,
+ projectWorkingDirectories,
+ topics,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -178,14 +185,19 @@ export class ProjectDirectoryRepository {
const prior = await directoryModel.findByLocation(input.projectId, device.id, path);
const directory =
prior ??
- (await directoryModel.create({
- addedByUserId: this.userId,
- deviceId: device.id,
- name: input.name.trim(),
- path,
- projectId: input.projectId,
- workspaceId: this.workspaceId,
- }));
+ (await ProjectDirectoryRepository.placeNewDirectory(
+ db,
+ input.projectId,
+ environment.id,
+ await directoryModel.create({
+ addedByUserId: this.userId,
+ deviceId: device.id,
+ name: input.name.trim(),
+ path,
+ projectId: input.projectId,
+ workspaceId: this.workspaceId,
+ }),
+ ));
const skippedTopics: SkippedProjectTopic[] = [];
if (input.topicIds?.length) {
if (!input.agentId)
@@ -476,6 +488,136 @@ export class ProjectDirectoryRepository {
* switching to that project's directory there — never to an arbitrary path.
* The cwd and CLI session only hold on the old machine, so they go with it.
*/
+ /**
+ * The cloud sandbox's place among the project's execution environments.
+ * The device folders keep theirs on their own rows (`sortOrder`); the
+ * sandbox keeps its on the link to the project's own environment. On a tie
+ * a folder comes first: a project that never reordered anything tries its
+ * folders before falling back to the sandbox.
+ */
+ async executionOrder(projectId: string): Promise<{ sandbox: number }> {
+ const project = await new ProjectModel(this.db, this.userId, this.workspaceId).findById(
+ projectId,
+ );
+ if (!project)
+ throw new ProjectDirectoryError('NOT_FOUND', 'Project not found or access denied');
+ const environment = await ProjectEnvironmentRepository.ensure(this.db, project);
+ return {
+ sandbox: await ProjectDirectoryRepository.sandboxOrder(this.db, projectId, environment.id),
+ };
+ }
+
+ /**
+ * Reorder the project's execution environments — its device folders and the
+ * cloud sandbox (`'sandbox'`) — into the given order, which is the priority
+ * a new conversation follows. Ids that are not this project's folders are
+ * refused rather than ignored, so a stale list cannot silently half-apply.
+ */
+ async reorderExecutionEnvironments(projectId: string, order: string[]) {
+ const project = await this.assertManageableProject(projectId);
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const environment = await ProjectEnvironmentRepository.ensure(db, project);
+ const directoryIds = order.filter((id) => id !== 'sandbox');
+ if (directoryIds.length > 0) {
+ const owned = await db
+ .select({ id: projectWorkingDirectories.id })
+ .from(projectWorkingDirectories)
+ .where(
+ and(
+ eq(projectWorkingDirectories.projectId, projectId),
+ inArray(projectWorkingDirectories.id, directoryIds),
+ ),
+ );
+ if (owned.length !== new Set(directoryIds).size)
+ throw new ProjectDirectoryError('BAD_REQUEST', 'Unknown project directory in order');
+ }
+ for (const [index, id] of order.entries()) {
+ if (id === 'sandbox')
+ await db
+ .update(projectEnvironments)
+ .set({ sortOrder: index, updatedAt: new Date() })
+ .where(
+ and(
+ eq(projectEnvironments.projectId, projectId),
+ eq(projectEnvironments.environmentId, environment.id),
+ ),
+ );
+ else
+ await db
+ .update(projectWorkingDirectories)
+ .set({ sortOrder: index })
+ .where(
+ and(
+ eq(projectWorkingDirectories.projectId, projectId),
+ eq(projectWorkingDirectories.id, id),
+ ),
+ );
+ }
+ });
+ }
+
+ private static async sandboxOrder(
+ db: LobeChatDatabase,
+ projectId: string,
+ environmentId: string,
+ ): Promise<number> {
+ const [link] = await db
+ .select({ sortOrder: projectEnvironments.sortOrder })
+ .from(projectEnvironments)
+ .where(
+ and(
+ eq(projectEnvironments.projectId, projectId),
+ eq(projectEnvironments.environmentId, environmentId),
+ ),
+ );
+ return link?.sortOrder ?? 0;
+ }
+
+ /**
+ * Give a folder just added its place: before the cloud sandbox when the
+ * sandbox is last — the fallback stays the fallback — and otherwise at the
+ * end, after whatever the person put ahead of it.
+ */
+ private static async placeNewDirectory<T extends { id: string; sortOrder: number }>(
+ db: LobeChatDatabase,
+ projectId: string,
+ environmentId: string,
+ directory: T,
+ ): Promise<T> {
+ const sandbox = await ProjectDirectoryRepository.sandboxOrder(db, projectId, environmentId);
+ const [{ last }] = await db
+ .select({ last: max(projectWorkingDirectories.sortOrder) })
+ .from(projectWorkingDirectories)
+ .where(
+ and(
+ eq(projectWorkingDirectories.projectId, projectId),
+ ne(projectWorkingDirectories.id, directory.id),
+ ),
+ );
+ const lastFolder = last ?? 0;
+ // Nothing reordered yet: every place is 0, and a tie puts folders first.
+ if (sandbox === 0 && lastFolder === 0) return directory;
+
+ const sortOrder = sandbox > lastFolder ? sandbox : lastFolder + 1;
+ if (sandbox > lastFolder)
+ await db
+ .update(projectEnvironments)
+ .set({ sortOrder: sandbox + 1, updatedAt: new Date() })
+ .where(
+ and(
+ eq(projectEnvironments.projectId, projectId),
+ eq(projectEnvironments.environmentId, environmentId),
+ ),
+ );
+ const [placed] = await db
+ .update(projectWorkingDirectories)
+ .set({ sortOrder })
+ .where(eq(projectWorkingDirectories.id, directory.id))
+ .returning();
+ return { ...directory, sortOrder: placed.sortOrder };
+ }
+
async moveTopic(topicId: string, directoryId: string) {
return this.db.transaction(async (tx) => {
const db = tx as LobeChatDatabase;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 6b4acec754f..452d62d0f46 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1016,8 +1016,6 @@ export default {
'heteroAgent.executionTarget.onlineConnections_one': 'Online · {{count}} connection',
'heteroAgent.executionTarget.onlineConnections_other': 'Online · {{count}} connections',
'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.",
'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.reconnect': 'Reconnect',
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 04f385d8025..46fc5b97b95 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -7,16 +7,15 @@ export default {
'settings.editDirectoryOtherEnvironment':
'This folder already belongs to another environment. Choose a different folder or device.',
'settings.editDirectoryDescription':
- 'Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.',
+ 'Choose the device and folder this device folder points to. Its topics move to the new folder and start new sessions there.',
'settings.editDirectoryFailed': 'Could not update the folder',
'settings.removeDirectory': 'Remove folder',
'settings.removeDirectoryConfirmDescription':
- '{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.',
+ '{{path}} on {{device}} will no longer be a device folder of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.',
'settings.removeDirectoryConfirmTitle': 'Remove {{name}} from this project?',
'settings.removeDirectoryFailed':
'Could not remove the folder. If a topic is running here, wait for it to finish and try again.',
- 'settings.configureDirectory': 'Add a working directory',
- 'settings.addDirectoryFailed': 'Could not add working directory',
+ 'settings.addDirectoryFailed': 'Could not add the device folder',
'settings.identifier': 'Project identifier',
'settings.identifierDescription':
'Prefix for this project’s task numbers, set when the project is created. Projects without one use the default prefix.',
@@ -24,26 +23,21 @@ export default {
'Used in the project URL. Changing it updates the address; leave blank to use the project ID.',
'settings.description': 'Description',
'settings.generalDescription': 'Manage the project name, address, and description.',
- 'settings.workLocations': 'Working directories',
- 'settings.directoryListDescription':
- 'Device folders this project works in. Agents read and change files in them on that device.',
- 'settings.allEnvironments': 'All environments',
- 'settings.viewDirectories': 'View folders ({{count}})',
'directories.noEnvironment': 'No environment linked',
'directories.sourceSummary': 'Existing directory',
'directories.keepFiles':
'Files stay on {{device}}. Linking only organizes the topics in this directory.',
'directories.bindFailed': 'Could not link directory',
'topics.associateFailed': 'Could not add topic to project',
- 'topics.chooseLocation': 'Choose a working directory',
- 'topics.addLocation': 'Add a working directory (optional)',
+ 'topics.chooseLocation': 'Choose a device folder',
+ 'topics.addLocation': 'Add a device folder (optional)',
'topics.complete': 'Mark completed',
'topics.resume': 'Resume work',
'topics.gatewayUnavailable': 'Enable Agent Gateway before using this project work location.',
- 'settings.deviceOnline': 'Device connected',
- 'settings.deviceOffline': 'Device disconnected',
+ 'settings.deviceOnline': 'Online',
+ 'settings.deviceOffline': 'Offline',
'topics.title': 'Topics',
'topics.groupBy': 'Group topics',
'topics.group.status': 'By status',
@@ -70,7 +64,7 @@ export default {
'topics.subGroup.byStatus': 'By status',
'settings.addDirectory': 'Add folder',
'settings.addDirectoryDescription':
- 'Select an environment and a connected device, then enter the full path of an existing folder. Files stay on that device.',
+ 'Select a connected device, then enter the full path of an existing folder. Files stay on that device.',
'settings.directoryUnavailable':
'The device is disconnected or the directory is unavailable. Connect the device and check the path, then retry.',
@@ -94,10 +88,9 @@ export default {
'settings.advanced': 'Advanced',
'settings.noRepository': 'No GitHub repository linked',
'settings.noDirectories':
- 'No folders in this environment yet. Add an existing folder on a connected device to start working.',
+ 'No device folders yet. Add a folder on a connected device to run this project there.',
'settings.title': 'Project settings',
- 'settings.environments': 'Environment',
- 'settings.addEnvironment': 'Add environment',
+ 'settings.environments': 'Execution environments',
'directories.environmentName': 'Environment name',
'directories.editEnvironment': 'Configure environment',
@@ -108,14 +101,14 @@ export default {
'directories.boundTip':
"This directory belongs to the project ({{path}}). Switch devices to use the project's directory on another device.",
'directories.boundRoot':
- 'This topic is bound to a project directory. Start a new topic to use a different directory.',
+ 'This topic is bound to a device folder of the project. Start a new topic to use a different folder.',
'directories.detectRepository': 'Detect GitHub repository',
'directories.stagedNewTopic': 'A new topic will start in <project>{{name}}</project>',
'directories.unavailable':
'Device is offline or the directory is unavailable. Reconnect and retry.',
- 'directories.title': 'Working directories',
- 'directories.add': 'Add working directory',
+ 'directories.title': 'Device folders',
+ 'directories.add': 'Add device folder',
'directories.bind': 'Link to project',
'directories.bindDescription':
'Link the folder below to a project so you can continue working from that project. Files stay on the current device.',
@@ -227,7 +220,7 @@ export default {
'disabled.action': 'Enable in Labs',
'disabled.title': 'Project workspaces are an Alpha experiment',
'delete.confirm.continue': 'Delete project',
- 'delete.confirm.kept.files': 'Files in the working directories on your devices',
+ 'delete.confirm.kept.files': "Files in the project's device folders",
'delete.confirm.kept.work': 'Tasks, goals, topics and channels',
'delete.confirm.keptLead': 'These are kept, but no longer belong to a project:',
'delete.confirm.namePrompt': 'Type “{{name}}” to confirm',
@@ -235,8 +228,7 @@ export default {
'Project widgets and their run history, Linear sync rules, review sites, dashboards and project memories',
'delete.confirm.removed.bindings':
'Links to agents, groups and knowledge bases (your agents and knowledge bases are kept)',
- 'delete.confirm.removed.settings':
- 'Project settings, members, working directories and environments',
+ 'delete.confirm.removed.settings': 'Project settings, members, device folders and environment',
'delete.confirm.removedLead': 'Deleting “{{name}}” cannot be undone. It permanently removes:',
'delete.confirm.title': 'Delete project',
'delete.description':
@@ -307,15 +299,15 @@ export default {
'rename.success': 'Project renamed',
'rename.title': 'Rename project',
'overview.context.location.devices': 'Devices',
- 'overview.context.location.directories': 'Project folders',
+ 'overview.context.location.directories': 'Device folders',
'overview.context.location.directoryUnavailable':
"Couldn't reach this folder. Check that the device is online and the folder still exists.",
- 'overview.context.location.noDirectories': 'No project folders on this device yet.',
+ 'overview.context.location.noDirectories': 'No folders on this device yet.',
'overview.context.location.noDirectoryTooltip':
- "This device has no project folder yet, so the conversation starts in the device's default directory.",
- 'overview.context.location.environments': 'Code environments',
- 'overview.context.location.noEnvironments': 'No code environments yet.',
- 'overview.context.location.title': 'Work location',
+ "This device has no folder for the project yet, so the conversation starts in the device's default directory.",
+ 'overview.context.location.environments': 'Environment',
+ 'overview.context.location.noEnvironments': 'The environment has no repositories yet.',
+ 'overview.context.location.title': 'Execution environment',
'overview.openTasks': 'Open task workspace',
'overview.composerPlaceholder': 'Tell the project what to move forward next…',
'overview.context.repository.publishHint':
@@ -680,8 +672,6 @@ export default {
'artboard.question.hint': 'Your answer goes to the agent with the next send.',
'create.failedRetry': "Couldn't create the project. Check your network and try again.",
'environment.configure': 'Configure environment',
- 'settings.environmentIntro':
- 'Every conversation in this project runs in this environment: its repositories are cloned, the setup command runs, and its variables are set.',
'createFromGithub.addRepository': 'Add',
'createFromGithub.removeRepository': 'Remove',
'createFromGithub.openIntegrations': 'Open GitHub settings',
@@ -695,4 +685,27 @@ export default {
'createFromGithub.extraRepositoriesLabel': 'More repositories',
'createFromGithub.chooseFromGithub': 'Choose from GitHub',
'knowledgeBases.addFailedRetry': "Couldn't add this library. Check your network and try again.",
+ 'overview.context.location.sandboxes': 'Cloud sandbox',
+ 'overview.context.location.emptySandbox': 'Empty sandbox',
+ 'overview.context.location.emptySandboxDesc':
+ 'Starts in an empty folder, without the project environment',
+ 'settings.cloudSandboxGroup': 'Cloud sandbox',
+ 'settings.addExecutionEnvironment': 'Add execution environment',
+ 'settings.configureSandbox': 'Configure',
+ 'settings.executionOrderHint':
+ 'New conversations use the first available execution environment in this order. Drag to reorder.',
+ 'settings.sandboxNoRepository': 'No repository yet',
+ 'settings.reorderFailed': "Couldn't save the new order. Try again.",
+ 'settings.setDeviceDirectory': 'Set folder',
+ 'settings.setDirectoryDescription':
+ 'Enter the full path of an existing folder on {{device}}. Files stay on that device.',
+ 'settings.directoryUnavailableTag': 'Unavailable',
+ 'settings.directoryUnavailable_offline':
+ 'The device is offline. The folder becomes usable once the device is online.',
+ 'settings.directoryUnavailable_missing':
+ "This folder isn't on the device. Edit its path or remove it.",
+ 'settings.directoryUnavailable_failed':
+ "This folder couldn't be set up. Check its path, or try again later.",
+ 'settings.directoryUnavailable_needsManager':
+ 'A project manager needs to open this page while the device is online.',
};
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index c6903a96ac8..90b2c60c7fb 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4894,7 +4894,7 @@ When I am ___, I need ___
'environments.instances.create': 'New copy',
'environments.form.description': 'Description',
'environments.form.descriptionPlaceholder': 'What this environment is for',
- 'environments.form.sources': 'Source code',
+ 'environments.form.sources': 'Repositories',
'environments.form.sourcesHint':
'Cloned over HTTPS before anything else runs. A private repository clones through the GitHub App installation that grants it; the environment itself stores no credentials.',
'environments.form.ref': 'Branch or tag',
@@ -5489,6 +5489,11 @@ When I am ___, I need ___
'environments.form.editRepositorySettings': 'Edit branch, folder and setup',
'environments.form.repositorySetupHint':
"Runs inside this repository's folder after it's cloned, before the environment's setup command.",
+ 'environments.form.setupAndVariables': 'Setup and environment variables',
+ 'environments.form.setupConfigured': 'Setup configured',
+ 'environments.form.setupNotConfigured': 'No setup',
+ 'environments.form.variablesCount_one': '{{count}} variable',
+ 'environments.form.variablesCount_other': '{{count}} variables',
'environments.form.bootstrapAfterRepositories':
"Runs at the top of the working directory, after each repository's own setup. Setup for a single repository goes on that repository.",
'environments.form.duplicateFolder': 'Another repository already uses this folder.',
diff --git a/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
index 68f23d1fd5e..fb677bedf6c 100644
--- a/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
@@ -3,9 +3,12 @@
import { confirmModal, toast } from '@lobehub/ui';
import { useTranslation } from 'react-i18next';
+import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
import { useChatStore } from '@/store/chat';
-import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { useTopicId } from '../hooks/useTopicId';
import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';
import ProjectDeviceSwitcher from './ProjectDeviceSwitcher';
import { type ProjectDeviceTarget } from './projectDeviceTargets';
@@ -53,23 +56,94 @@ const ProjectTopicDeviceSwitcher = ({ agentId, topicId }: { agentId: string; top
agentId={agentId}
directories={directories}
directoryId={directoryId}
+ // A conversation bound to a folder keeps a folder: moving it to the
+ // sandbox is not something a started conversation can do.
+ sandbox={{ active: false }}
onSelect={handleSelect}
/>
);
};
+/** The project a conversation without a folder belongs to: its topic's, or its blank draft's. */
+const useProjectWithoutFolder = (agentId: string) => {
+ const topicId = useTopicId();
+ const topicProjectId = useChatStore((s) => {
+ if (!topicId) return undefined;
+ const topic = topicSelectors.getTopicById(topicId)(s);
+ return topic?.projectId && !topic.projectWorkingDirectoryId ? topic.projectId : undefined;
+ });
+ const draftProjectId = useChatStore((s) => {
+ const pending = s.pendingNewTopicDirectory;
+ return !topicId && pending?.agentId === agentId && 'projectId' in pending
+ ? pending.projectId
+ : undefined;
+ });
+ if (topicProjectId) return { projectId: topicProjectId, started: true };
+ if (draftProjectId) return { projectId: draftProjectId, started: false };
+ return undefined;
+};
+
+/**
+ * A project conversation in the cloud sandbox. A blank one can still move to
+ * one of the project's folders — it is only restaged there — while a started
+ * one stays in the sandbox it began in.
+ */
+const ProjectSandboxSwitcher = ({
+ agentId,
+ projectId,
+ started,
+}: {
+ agentId: string;
+ projectId: string;
+ started: boolean;
+}) => {
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const directories = useProjectDirectories(projectId);
+
+ return (
+ <ProjectDeviceSwitcher
+ agentId={agentId}
+ directories={directories}
+ projectId={projectId}
+ sandbox={{ active: true }}
+ onSelect={
+ started
+ ? undefined
+ : ({ directory }) =>
+ useChatStore
+ .getState()
+ .setPendingNewTopicDirectory({ agentId, projectWorkingDirectoryId: directory.id })
+ }
+ />
+ );
+};
+
/**
* A blank conversation staged in a project directory has nothing persisted
* yet, so switching devices just restages it in that device's directory.
*/
const StagedProjectDeviceSwitcher = ({ agentId }: { agentId: string }) => {
const { directories, directoryId } = useStagedProjectDirectory(agentId);
+ const selectExecutionTarget = useSelectExecutionTarget(agentId);
+ const projectId = directories.find((d) => d.id === directoryId)?.projectId;
return (
<ProjectDeviceSwitcher
agentId={agentId}
directories={directories}
directoryId={directoryId}
+ projectId={projectId}
+ sandbox={{
+ active: false,
+ // Restaged on the project alone, in the cloud sandbox: the first send
+ // starts it there with the project's environment.
+ onSelect: projectId
+ ? () => {
+ useChatStore.getState().setPendingNewTopicDirectory({ agentId, projectId });
+ void selectExecutionTarget('sandbox');
+ }
+ : undefined,
+ }}
onSelect={({ directory }) =>
useChatStore
.getState()
@@ -80,20 +154,28 @@ const StagedProjectDeviceSwitcher = ({ agentId }: { agentId: string }) => {
};
/**
- * The execution-device control for whichever conversation is open. A
- * project-directory conversation — or a blank one a project group's "+"
- * staged in a directory — runs in its project's directory, so it only
- * chooses among the project's devices; everything else gets the general
- * execution-target picker. Every bar that shows a device control mounts this,
+ * The execution-device control for whichever conversation is open. A project
+ * conversation — in one of its folders or in the cloud sandbox, started or
+ * still blank — only chooses among the project's own execution environments;
+ * everything else gets the general execution-target picker. Every bar that shows a device control mounts this,
* so no surface can fall back to the general picker for a project topic.
*/
const DeviceSwitcher = ({ agentId }: DeviceSwitcherProps) => {
const projectTopicId = useActiveProjectDirectoryTopicId();
const stagedDirectoryId = useStagedProjectDirectoryId(agentId);
+ const sandboxProject = useProjectWithoutFolder(agentId);
if (projectTopicId)
return <ProjectTopicDeviceSwitcher agentId={agentId} topicId={projectTopicId} />;
if (stagedDirectoryId) return <StagedProjectDeviceSwitcher agentId={agentId} />;
+ if (sandboxProject)
+ return (
+ <ProjectSandboxSwitcher
+ agentId={agentId}
+ projectId={sandboxProject.projectId}
+ started={sandboxProject.started}
+ />
+ );
return <HeteroDeviceSwitcher agentId={agentId} />;
};
diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
index 087398bfb52..78486e8ac5e 100644
--- a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
@@ -3,17 +3,25 @@
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { ChevronDownIcon } from 'lucide-react';
+import { ChevronDownIcon, SettingsIcon } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import RepositoryAvatar from '@/components/RepositoryAvatar';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import DeviceLoadMeter, { useDeviceLoad } from '@/features/DeviceManager/DeviceLoadMeter';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';
+import { useProjectExecutionEnvironments } from '@/features/Projects/WorkingDirectories/useProjectExecutionEnvironments';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useDeviceList } from '@/store/device';
-import { type ProjectDirectory } from '@/store/projectWorkingDirectory';
+import {
+ type ProjectDirectory,
+ useProjectDirectoryStore,
+ useProjectEnvironments,
+} from '@/store/projectWorkingDirectory';
import DeviceDetailPopover from './DeviceDetailPopover';
import OptionRow from './OptionRow';
@@ -22,22 +30,35 @@ import {
type ProjectDeviceTarget,
projectDirectoryDeviceName,
} from './projectDeviceTargets';
+import { repositoriesLabel, repositorySlug } from './sandboxEnvironmentOptions';
import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
const styles = stylex.create({
// Picking a device here really picks an environment, and the path is what
// tells them apart, so it wraps in full instead of truncating.
desc: { minWidth: '0', overflowWrap: 'anywhere' },
- hint: {
- paddingBlock: '6px',
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingBlock: '4px',
paddingInline: '8px',
+ },
+ manage: {
+ cursor: 'pointer',
+ display: 'flex',
+ gap: '3px',
+ alignItems: 'center',
+ padding: '0',
+ borderStyle: 'none',
fontSize: '11px',
- color: cssVar.colorTextDescription,
+ color: { 'default': cssVar.colorTextQuaternary, ':hover': cssVar.colorPrimary },
+ backgroundColor: 'transparent',
+ backgroundImage: 'none',
+ transition: 'color 0.2s',
},
status: { flex: 'none', whiteSpace: 'nowrap' },
title: {
- paddingBlock: '4px',
- paddingInline: '8px',
fontSize: '12px',
fontWeight: 500,
color: cssVar.colorTextTertiary,
@@ -50,19 +71,27 @@ interface ProjectDeviceSwitcherProps {
agentId: string;
directories: ProjectDirectory[];
directoryId?: string;
- /** Picked another device's project directory. */
- onSelect: (target: ProjectDeviceTarget) => void;
+ /** Picked another device's project directory; absent when folders can't be picked here. */
+ onSelect?: (target: ProjectDeviceTarget) => void;
+ /** The project whose execution environments are offered, in its priority order. */
+ projectId?: string;
+ /**
+ * The cloud sandbox's row: whether the conversation runs there, and how to
+ * move it there — absent when it can't be (a conversation already bound to
+ * a folder keeps its folder).
+ */
+ sandbox?: { active: boolean; onSelect?: () => void };
}
/**
- * Device switcher for a conversation that runs in a project directory.
+ * The execution-environment picker of a project conversation: only the
+ * project's own execution environments — the cloud sandbox and the device
+ * folders someone added — in the project's priority order, and a shortcut to
+ * manage them on the project's settings.
*
- * The directory belongs to the project, so the only choice left is which
- * device to run on — and each device brings the project's own directory there.
- * Only devices the project has a directory on are offered; picking one moves
- * the conversation to that directory rather than to an arbitrary path. The
- * directory itself has no chip of its own; its path rides on this trigger's
- * tooltip.
+ * A folder belongs to the project, so picking a device moves the
+ * conversation to that device's folder rather than to an arbitrary path. The
+ * folder has no chip of its own; its path rides on this trigger's tooltip.
*/
const ProjectDeviceSwitcher = ({
activeTag,
@@ -70,11 +99,20 @@ const ProjectDeviceSwitcher = ({
directories,
directoryId,
onSelect,
+ projectId: projectIdProp,
+ sandbox,
}: ProjectDeviceSwitcherProps) => {
const { t } = useTranslation('chat');
+ const navigate = useWorkspaceAwareNavigate();
const [open, setOpen] = useState(false);
const { canUseResource } = useChatInputResourceAccess();
const directory = directories.find((d) => d.id === directoryId);
+ const projectId = projectIdProp ?? directories[0]?.projectId;
+ const { ordered } = useProjectExecutionEnvironments(projectId, !!projectId);
+ useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId, !!projectId);
+ // Without a project this would read the scope-wide list, so it is ignored.
+ const [scopedEnvironment] = useProjectEnvironments(projectId);
+ const projectEnvironment = projectId ? scopedEnvironment : undefined;
const { data: devices } = useDeviceList();
const load = useDeviceLoad(devices?.find((d) => d.deviceId === directory?.deviceId));
// The shared row, not the topic-pinned effective config: a fixed target is
@@ -88,73 +126,134 @@ const ProjectDeviceSwitcher = ({
if (!canUseResource) return null;
const targets = listProjectDeviceTargets(directories, devices, directoryId, fixedDeviceId);
+ const targetById = new Map(targets.map((target) => [target.directory.id, target]));
+ // The project's order, the cloud sandbox included; a list still loading
+ // keeps the folders' own order with the sandbox first.
+ const rows = ordered.some((item) => item.kind === 'directory')
+ ? ordered
+ : [
+ { id: 'sandbox', kind: 'sandbox' as const },
+ ...targets.map((target) => ({ id: target.directory.id, kind: 'directory' as const })),
+ ];
const handleSelect = (target: ProjectDeviceTarget) => {
setOpen(false);
- if (!target.active) onSelect(target);
+ if (!target.active) onSelect?.(target);
+ };
+
+ // Named after the repositories it clones, as on the project's settings.
+ const sandboxLabel = projectEnvironment ? repositoriesLabel(projectEnvironment) : undefined;
+ const sandboxSlug = projectEnvironment ? repositorySlug(projectEnvironment) : undefined;
+ const sandboxRow = sandbox ? (
+ <OptionRow
+ active={sandbox.active}
+ desc={sandboxLabel ? t('heteroAgent.executionTarget.sandbox') : undefined}
+ disabled={!sandbox.onSelect}
+ key="sandbox"
+ label={sandboxLabel || t('heteroAgent.executionTarget.sandbox')}
+ tags={sandbox.active && activeTag ? [activeTag] : []}
+ icon={
+ sandboxSlug ? (
+ <RepositoryAvatar size={16} url={sandboxSlug} />
+ ) : (
+ <ExecutionTargetIcon target={'sandbox'} />
+ )
+ }
+ onClick={() => {
+ if (!sandbox.onSelect || sandbox.active) return;
+ setOpen(false);
+ sandbox.onSelect();
+ }}
+ />
+ ) : null;
+
+ const renderTarget = (target: ProjectDeviceTarget) => {
+ const selectable = !!onSelect && target.online && target.allowed;
+ const row = (
+ <OptionRow
+ active={target.active}
+ disabled={!selectable}
+ icon={<ExecutionTargetIcon devicePlatform={target.directory.platform} target={'device'} />}
+ key={target.directory.id}
+ label={target.label}
+ tags={target.active && activeTag ? [activeTag] : []}
+ desc={
+ target.allowed ? (
+ <>
+ <span {...stylex.props(styles.desc)}>{target.directory.path}</span>
+ <span {...stylex.props(styles.status)}>
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t('heteroAgent.executionTarget.offline')}
+ online={target.online}
+ onlineLabel={t('heteroAgent.executionTarget.online')}
+ unknown={target.onlineUnknown}
+ unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
+ />
+ </span>
+ </>
+ ) : (
+ <span {...stylex.props(styles.desc)}>{t('heteroAgent.executionTarget.fixedTip')}</span>
+ )
+ }
+ onClick={() => (selectable ? handleSelect(target) : undefined)}
+ />
+ );
+ // Same hover details as the regular device picker: the label alone
+ // can't tell two machines' specs or last-seen time apart.
+ return target.device ? (
+ <DeviceDetailPopover device={target.device} key={target.directory.id}>
+ <div>{row}</div>
+ </DeviceDetailPopover>
+ ) : (
+ row
+ );
};
const content = (
<Flexbox style={{ maxWidth: 400, minWidth: 280 }}>
- <div {...stylex.props(styles.title)}>{t('heteroAgent.executionTarget.title')}</div>
- {targets.map((target) => {
- const selectable = target.online && target.allowed;
- const row = (
- <OptionRow
- active={target.active}
- disabled={!selectable}
- key={target.directory.id}
- label={target.label}
- tags={target.active && activeTag ? [activeTag] : []}
- desc={
- target.allowed ? (
- <>
- <span {...stylex.props(styles.desc)}>{target.directory.path}</span>
- <span {...stylex.props(styles.status)}>
- <ExecutionTargetDeviceStatus
- offlineLabel={t('heteroAgent.executionTarget.offline')}
- online={target.online}
- onlineLabel={t('heteroAgent.executionTarget.online')}
- unknown={target.onlineUnknown}
- unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
- />
- </span>
- </>
- ) : (
- <span {...stylex.props(styles.desc)}>
- {t('heteroAgent.executionTarget.fixedTip')}
- </span>
- )
- }
- icon={
- <ExecutionTargetIcon devicePlatform={target.directory.platform} target={'device'} />
- }
- onClick={() => (selectable ? handleSelect(target) : undefined)}
- />
- );
- // Same hover details as the regular device picker: the label alone
- // can't tell two machines' specs or last-seen time apart.
- return target.device ? (
- <DeviceDetailPopover device={target.device} key={target.directory.id}>
- <div>{row}</div>
- </DeviceDetailPopover>
- ) : (
- row
- );
- })}
- <div {...stylex.props(styles.hint)}>
- {t('heteroAgent.executionTarget.projectDevicesHint')}
+ <div {...stylex.props(styles.header)}>
+ <span {...stylex.props(styles.title)}>{t('heteroAgent.executionTarget.title')}</span>
+ {projectId && (
+ <button
+ {...stylex.props(styles.manage)}
+ type="button"
+ onClick={() => {
+ setOpen(false);
+ navigate(getProjectSettingsPath(projectId, 'environments'));
+ }}
+ >
+ <Icon icon={SettingsIcon} size={11} />
+ <span>{t('heteroAgent.executionTarget.manage')}</span>
+ </button>
+ )}
</div>
+ {rows.map((item) => {
+ if (item.kind === 'sandbox') return sandboxRow;
+ const target = targetById.get(item.id);
+ return target ? renderTarget(target) : null;
+ })}
</Flexbox>
);
+ const onSandbox = !!sandbox?.active;
const trigger = (
<div {...stylex.props(workingDirectoryChipStyles.chip)}>
- <ExecutionTargetIcon devicePlatform={directory?.platform} target={'device'} />
+ {/* On the sandbox the chip names it as the menu does: its repositories
+ and the first one's logo, once it has any. */}
+ {onSandbox && sandboxSlug ? (
+ <RepositoryAvatar size={14} url={sandboxSlug} />
+ ) : (
+ <ExecutionTargetIcon
+ devicePlatform={onSandbox ? undefined : directory?.platform}
+ target={onSandbox ? 'sandbox' : 'device'}
+ />
+ )}
<span {...stylex.props(workingDirectoryChipStyles.label)}>
- {directory
- ? projectDirectoryDeviceName(directory, devices)
- : t('heteroAgent.executionTarget.unknownDevice')}
+ {onSandbox
+ ? sandboxLabel || t('heteroAgent.executionTarget.sandbox')
+ : directory
+ ? projectDirectoryDeviceName(directory, devices)
+ : t('heteroAgent.executionTarget.unknownDevice')}
</span>
{load && <DeviceLoadMeter load={load} />}
<Icon icon={ChevronDownIcon} size={12} />
@@ -162,12 +261,13 @@ const ProjectDeviceSwitcher = ({
);
// The tooltip's body lays its children out in a row; stack the two lines.
- const tooltip = directory ? (
- <Flexbox gap={4}>
- <span>{t('directories.boundTip', { ns: 'project', path: directory.path })}</span>
- {load && <span>{load.summary}</span>}
- </Flexbox>
- ) : undefined;
+ const tooltip =
+ directory && !onSandbox ? (
+ <Flexbox gap={4}>
+ <span>{t('directories.boundTip', { ns: 'project', path: directory.path })}</span>
+ {load && <span>{load.summary}</span>}
+ </Flexbox>
+ ) : undefined;
return (
<Popover
diff --git a/src/features/EnvironmentManager/EnvironmentForm.tsx b/src/features/EnvironmentManager/EnvironmentForm.tsx
index 672eeeb0971..e50a8b9fc88 100644
--- a/src/features/EnvironmentManager/EnvironmentForm.tsx
+++ b/src/features/EnvironmentManager/EnvironmentForm.tsx
@@ -14,6 +14,8 @@ import {
toast,
} from '@lobehub/ui';
import {
+ ChevronDownIcon,
+ ChevronRightIcon,
ChevronUpIcon,
FolderIcon,
GitBranchIcon,
@@ -57,12 +59,23 @@ export type EnvironmentFormValue = Pick<SandboxEnvironment, 'configuration' | 'n
};
interface EnvironmentFormProps {
+ /**
+ * Folds the setup command and the variables into one row with a summary.
+ * They are set once and rarely touched, so on a page that also lists the
+ * project's devices they should not push those out of view.
+ */
+ collapseSetup?: boolean;
environment: EnvironmentFormValue;
/**
* Hides the name and description: a project's environment is named after
* the project and edited as part of it.
*/
hideBasics?: boolean;
+ /**
+ * Leaves out how repositories are cloned and when an edit takes effect: a
+ * project's page keeps to the repositories themselves.
+ */
+ hideRepositoryHints?: boolean;
onSave: (params: {
configuration?: SandboxEnvironmentSpecification;
description?: string;
@@ -279,195 +292,228 @@ BranchField.displayName = 'EnvironmentBranchField';
* at the bottom of four sections, and changes typed above it were lost to a
* tab switch before anyone scrolled down to it.
*/
-const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, hideBasics, onSave }) => {
- const { t } = useTranslation('setting');
- const configuration = (environment.configuration ?? {}) as SandboxEnvironmentSpecification;
- const [pickingRepository, setPickingRepository] = useState(false);
- const [busy, setBusy] = useState(false);
- /**
- * Failure of a repository add / remove, shown in the Sources section: the page stays open and
- * the control that failed has no confirm step of its own to hang an error on.
- */
- const [repositoryError, setRepositoryError] = useState('');
-
- // Every field saves the whole specification, so two saves in flight at once
- // would each start from the same snapshot and the later one would undo the
- // earlier. Saves run one after another, each on top of the last one saved;
- // while none is running, the snapshot follows what the server returned.
- const latest = useRef(configuration);
- const pending = useRef(0);
- const queue = useRef<Promise<unknown> | undefined>(undefined);
- const stored = environment.configuration;
- useEffect(() => {
- if (pending.current === 0) latest.current = (stored ?? {}) as SandboxEnvironmentSpecification;
- }, [stored]);
-
- type Changes = Partial<SandboxEnvironmentSpecification>;
-
- /** Write one change to the specification; the toast is the only trace a per-field save leaves. */
- const saveConfiguration = async (
- changes: Changes | ((current: SandboxEnvironmentSpecification) => Changes),
- ) => {
- pending.current++;
- const task = (queue.current ?? Promise.resolve())
- .catch(() => {})
- .then(async () => {
- const current = latest.current;
- const next = compact({
- ...current,
- ...(typeof changes === 'function' ? changes(current) : changes),
+const EnvironmentForm = memo<EnvironmentFormProps>(
+ ({ collapseSetup, environment, hideBasics, hideRepositoryHints, onSave }) => {
+ const { t } = useTranslation('setting');
+ const [setupOpen, setSetupOpen] = useState(false);
+ const configuration = (environment.configuration ?? {}) as SandboxEnvironmentSpecification;
+ const [pickingRepository, setPickingRepository] = useState(false);
+ const [busy, setBusy] = useState(false);
+ /**
+ * Failure of a repository add / remove, shown in the Sources section: the page stays open and
+ * the control that failed has no confirm step of its own to hang an error on.
+ */
+ const [repositoryError, setRepositoryError] = useState('');
+
+ // Every field saves the whole specification, so two saves in flight at once
+ // would each start from the same snapshot and the later one would undo the
+ // earlier. Saves run one after another, each on top of the last one saved;
+ // while none is running, the snapshot follows what the server returned.
+ const latest = useRef(configuration);
+ const pending = useRef(0);
+ const queue = useRef<Promise<unknown> | undefined>(undefined);
+ const stored = environment.configuration;
+ useEffect(() => {
+ if (pending.current === 0) latest.current = (stored ?? {}) as SandboxEnvironmentSpecification;
+ }, [stored]);
+
+ type Changes = Partial<SandboxEnvironmentSpecification>;
+
+ /** Write one change to the specification; the toast is the only trace a per-field save leaves. */
+ const saveConfiguration = async (
+ changes: Changes | ((current: SandboxEnvironmentSpecification) => Changes),
+ ) => {
+ pending.current++;
+ const task = (queue.current ?? Promise.resolve())
+ .catch(() => {})
+ .then(async () => {
+ const current = latest.current;
+ const next = compact({
+ ...current,
+ ...(typeof changes === 'function' ? changes(current) : changes),
+ });
+ await onSave({ configuration: next });
+ latest.current = next;
+ })
+ .finally(() => {
+ pending.current--;
});
- await onSave({ configuration: next });
- latest.current = next;
- })
- .finally(() => {
- pending.current--;
+ queue.current = task;
+ await task;
+ toast.success(t('environments.form.saved'));
+ };
+
+ /** For controls with no confirm step of their own: a switch, a disconnect. */
+ const run = async (action: () => Promise<void>) => {
+ setBusy(true);
+ setRepositoryError('');
+ try {
+ await action();
+ } catch (error) {
+ console.error('[EnvironmentForm] Save failed:', error);
+ setRepositoryError(describeError(error, t, t('environments.saveFailedRetry')));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // Every repository, in the order they are checked out; anything that is
+ // not a git source (an old `files` one) is kept as it is.
+ const sources = configuration.sources ?? [];
+ const repositories = sources.filter((source): source is GitSource => source.kind === 'git');
+ /** Rewrites the repositories as they stand when the save runs, keeping other sources. */
+ const saveRepositories = (update: (current: GitSource[]) => GitSource[]) =>
+ saveConfiguration((current) => {
+ const all = current.sources ?? [];
+ const git = all.filter((source): source is GitSource => source.kind === 'git');
+ return { sources: [...update(git), ...all.filter((source) => source.kind !== 'git')] };
});
- queue.current = task;
- await task;
- toast.success(t('environments.form.saved'));
- };
-
- /** For controls with no confirm step of their own: a switch, a disconnect. */
- const run = async (action: () => Promise<void>) => {
- setBusy(true);
- setRepositoryError('');
- try {
- await action();
- } catch (error) {
- console.error('[EnvironmentForm] Save failed:', error);
- setRepositoryError(describeError(error, t, t('environments.saveFailedRetry')));
- } finally {
- setBusy(false);
- }
- };
-
- // Every repository, in the order they are checked out; anything that is
- // not a git source (an old `files` one) is kept as it is.
- const sources = configuration.sources ?? [];
- const repositories = sources.filter((source): source is GitSource => source.kind === 'git');
- /** Rewrites the repositories as they stand when the save runs, keeping other sources. */
- const saveRepositories = (update: (current: GitSource[]) => GitSource[]) =>
- saveConfiguration((current) => {
- const all = current.sources ?? [];
- const git = all.filter((source): source is GitSource => source.kind === 'git');
- return { sources: [...update(git), ...all.filter((source) => source.kind !== 'git')] };
- });
-
- const folderOf = (path: string | undefined) =>
- path
- ?.trim()
- .replace(/^\.?\/+/, '')
- .replace(/\/+$/, '') || undefined;
-
- const updateRepository = (url: string, changes: Partial<Omit<GitSource, 'kind' | 'url'>>) => {
- // Two checkouts in one folder would merge into each other.
- const folder = changes.path === undefined ? undefined : folderOf(changes.path);
- if (
- folder &&
- repositories.some((source) => source.url !== url && folderOf(source.path) === folder)
- )
- return Promise.reject(new Error(t('environments.form.duplicateFolder')));
-
- return saveRepositories((current) =>
- current.map((source) => {
- if (source.url !== url) return source;
- const next = { ...source, ...changes };
- // A blank field means "the default", which is the key left out.
- if (!next.ref) delete next.ref;
- if (!next.path) delete next.path;
- if (!next.setupCommand?.trim()) delete next.setupCommand;
- return next;
- }),
- );
- };
-
- // The last repository left goes back to the top of the working directory
- // when its folder was only the one it got for sitting beside another.
- const removeRepository = (url: string) =>
- run(() =>
- saveRepositories((current) => {
- const rest = current.filter((source) => source.url !== url);
- if (rest.length === 1 && rest[0].path === repositoryFolderName(rest[0].url)) {
- const { path: _path, ...only } = rest[0];
- return [only];
- }
- return rest;
- }),
- );
- const [pastedUrl, setPastedUrl] = useState('');
-
- const pasted = parseGithubRepository(pastedUrl);
-
- const pastedInvalid = Boolean(pastedUrl.trim()) && !pasted;
-
- const addPasted = () => {
- if (!pasted) return;
-
- const [owner, repository] = pasted.fullName.split('/');
-
- addRepository({ owner, repository });
+ const folderOf = (path: string | undefined) =>
+ path
+ ?.trim()
+ .replace(/^\.?\/+/, '')
+ .replace(/\/+$/, '') || undefined;
+
+ const updateRepository = (url: string, changes: Partial<Omit<GitSource, 'kind' | 'url'>>) => {
+ // Two checkouts in one folder would merge into each other.
+ const folder = changes.path === undefined ? undefined : folderOf(changes.path);
+ if (
+ folder &&
+ repositories.some((source) => source.url !== url && folderOf(source.path) === folder)
+ )
+ return Promise.reject(new Error(t('environments.form.duplicateFolder')));
+
+ return saveRepositories((current) =>
+ current.map((source) => {
+ if (source.url !== url) return source;
+ const next = { ...source, ...changes };
+ // A blank field means "the default", which is the key left out.
+ if (!next.ref) delete next.ref;
+ if (!next.path) delete next.path;
+ if (!next.setupCommand?.trim()) delete next.setupCommand;
+ return next;
+ }),
+ );
+ };
+
+ // The last repository left goes back to the top of the working directory
+ // when its folder was only the one it got for sitting beside another.
+ const removeRepository = (url: string) =>
+ run(() =>
+ saveRepositories((current) => {
+ const rest = current.filter((source) => source.url !== url);
+ if (rest.length === 1 && rest[0].path === repositoryFolderName(rest[0].url)) {
+ const { path: _path, ...only } = rest[0];
+ return [only];
+ }
+ return rest;
+ }),
+ );
+
+ const [pastedUrl, setPastedUrl] = useState('');
+
+ const pasted = parseGithubRepository(pastedUrl);
+
+ const pastedInvalid = Boolean(pastedUrl.trim()) && !pasted;
+
+ const addPasted = () => {
+ if (!pasted) return;
+
+ const [owner, repository] = pasted.fullName.split('/');
+
+ addRepository({ owner, repository });
+
+ setPastedUrl('');
+ };
+
+ const addRepository = (picked: GithubRepositorySelection | undefined) => {
+ if (!picked) return;
+ setPickingRepository(false);
+ const url = `https://github.com/${picked.owner}/${picked.repository}`;
+ if (
+ repositories.some(
+ (source) =>
+ repositoryPathOf(source.url)?.repository === picked.repository &&
+ repositoryPathOf(source.url)?.owner === picked.owner,
+ )
+ )
+ return;
+ // One repository is checked out at the top of the working directory;
+ // several sit side by side, each in a folder named after it.
+ void run(() =>
+ saveRepositories(
+ (current) =>
+ layoutRepositorySources([
+ ...current,
+ {
+ kind: 'git' as const,
+ url,
+ ...(picked.defaultBranch && { ref: picked.defaultBranch }),
+ },
+ ]) as GitSource[],
+ ),
+ );
+ };
+
+ // The setup that runs after the repositories, and the variables every
+ // command sees.
+ const setupSections = (
+ <>
+ <PanelSection
+ title={t('environments.form.setup')}
+ desc={
+ repositories.length > 0 ? t('environments.form.bootstrapAfterRepositories') : undefined
+ }
+ >
+ <InlineField
+ multiline
+ desc={t('environments.form.bootstrapHint')}
+ label={t('environments.form.bootstrap')}
+ value={configuration.bootstrapCommand ?? ''}
+ onSave={(bootstrapCommand) => saveConfiguration({ bootstrapCommand })}
+ />
+ </PanelSection>
- setPastedUrl('');
- };
+ {/* Said plainly because the shape cannot enforce it: a text field
+ cannot tell a region from a token. */}
+ <PanelSection desc={t('environments.form.envHint')} title={t('environments.form.env')}>
+ <EnvironmentVariables
+ entries={Object.entries(configuration.env ?? {})}
+ onSave={(entries) => saveConfiguration({ env: Object.fromEntries(entries) })}
+ />
+ </PanelSection>
+ </>
+ );
- const addRepository = (picked: GithubRepositorySelection | undefined) => {
- if (!picked) return;
- setPickingRepository(false);
- const url = `https://github.com/${picked.owner}/${picked.repository}`;
- if (
- repositories.some(
- (source) =>
- repositoryPathOf(source.url)?.repository === picked.repository &&
- repositoryPathOf(source.url)?.owner === picked.owner,
- )
- )
- return;
- // One repository is checked out at the top of the working directory;
- // several sit side by side, each in a folder named after it.
- void run(() =>
- saveRepositories(
- (current) =>
- layoutRepositorySources([
- ...current,
- {
- kind: 'git' as const,
- url,
- ...(picked.defaultBranch && { ref: picked.defaultBranch }),
- },
- ]) as GitSource[],
- ),
+ const basics = (
+ <PanelSection title={t('environments.form.basics')}>
+ <InlineField
+ required
+ label={t('environments.nameLabel')}
+ placeholder={t('environments.namePlaceholder')}
+ value={environment.name}
+ onSave={(name) => onSave({ name })}
+ />
+ <InlineField
+ label={t('environments.form.description')}
+ placeholder={t('environments.form.descriptionPlaceholder')}
+ value={environment.description ?? ''}
+ onSave={(description) => onSave({ description })}
+ />
+ </PanelSection>
);
- };
-
- const basics = (
- <PanelSection title={t('environments.form.basics')}>
- <InlineField
- required
- label={t('environments.nameLabel')}
- placeholder={t('environments.namePlaceholder')}
- value={environment.name}
- onSave={(name) => onSave({ name })}
- />
- <InlineField
- label={t('environments.form.description')}
- placeholder={t('environments.form.descriptionPlaceholder')}
- value={environment.description ?? ''}
- onSave={(description) => onSave({ description })}
- />
- </PanelSection>
- );
- return (
- <Flexbox>
- {!hideBasics && basics}
-
- <PanelSection
- desc={t('environments.form.sourcesHint')}
- title={t('environments.form.sources')}
- notice={
- /* When an edit here reaches an instance, which is the question this
+ return (
+ <Flexbox>
+ {!hideBasics && basics}
+
+ <PanelSection
+ desc={hideRepositoryHints ? undefined : t('environments.form.sourcesHint')}
+ title={t('environments.form.sources')}
+ notice={
+ hideRepositoryHints ? undefined : (
+ /* When an edit here reaches an instance, which is the question this
panel otherwise leaves open. An instance keeps the definition it
was created with — `configurationSnapshot`, taken once at creation
— and a rebuild replays that one rather than reading the
@@ -475,104 +521,121 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, hideBasics, o
saying "rebuild to apply" would send people to a button that
cannot do it. Said once, here at the top: setup and variables are
governed by the same snapshot. */
- <Text fontSize={12} type={'secondary'}>
- {t('environments.form.appliesOnInit')}
- </Text>
- }
- >
- {repositories.length === 0 && !pickingRepository && (
- <Text fontSize={13} type={'secondary'}>
- {t('environments.form.noRepositories')}
- </Text>
- )}
- {repositories.length > 0 && (
- <Flexbox gap={8}>
- {repositories.map((source) => (
- <RepositoryRow
- busy={busy}
- key={source.url}
- source={source}
- onChange={(changes) => updateRepository(source.url, changes)}
- onRemove={() => removeRepository(source.url)}
- />
- ))}
- </Flexbox>
- )}
- {repositoryError && <InlineErrorText>{repositoryError}</InlineErrorText>}
- {pickingRepository ? (
- <Flexbox gap={8}>
- <GithubRepositoryPicker onChange={addRepository} />
- {/* Any public repository, whether or not GitHub is connected —
- the same fallback the create dialog offers. */}
- <Flexbox gap={6}>
<Text fontSize={12} type={'secondary'}>
- {t('environments.form.pasteRepository')}
+ {t('environments.form.appliesOnInit')}
</Text>
- <Flexbox horizontal gap={8}>
- <Input
- aria-invalid={pastedInvalid}
- placeholder={'https://github.com/owner/repo'}
- style={pastedInvalid ? { borderColor: cssVar.colorError } : undefined}
- value={pastedUrl}
- onChange={(event) => setPastedUrl(event.target.value)}
- onPressEnter={addPasted}
+ )
+ }
+ >
+ {repositories.length === 0 && !pickingRepository && (
+ <Text fontSize={13} type={'secondary'}>
+ {t('environments.form.noRepositories')}
+ </Text>
+ )}
+ {repositories.length > 0 && (
+ <Flexbox gap={8}>
+ {repositories.map((source) => (
+ <RepositoryRow
+ busy={busy}
+ key={source.url}
+ source={source}
+ onChange={(changes) => updateRepository(source.url, changes)}
+ onRemove={() => removeRepository(source.url)}
/>
- <Button disabled={!pasted} onClick={addPasted}>
- {t('environments.form.addPastedRepository')}
+ ))}
+ </Flexbox>
+ )}
+ {repositoryError && <InlineErrorText>{repositoryError}</InlineErrorText>}
+ {pickingRepository ? (
+ <Flexbox gap={8}>
+ <GithubRepositoryPicker onChange={addRepository} />
+ {/* Any public repository, whether or not GitHub is connected —
+ the same fallback the create dialog offers. */}
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('environments.form.pasteRepository')}
+ </Text>
+ <Flexbox horizontal gap={8}>
+ <Input
+ aria-invalid={pastedInvalid}
+ placeholder={'https://github.com/owner/repo'}
+ style={pastedInvalid ? { borderColor: cssVar.colorError } : undefined}
+ value={pastedUrl}
+ onChange={(event) => setPastedUrl(event.target.value)}
+ onPressEnter={addPasted}
+ />
+ <Button disabled={!pasted} onClick={addPasted}>
+ {t('environments.form.addPastedRepository')}
+ </Button>
+ </Flexbox>
+ {pastedInvalid && (
+ <Text fontSize={12} type={'danger'}>
+ {t('environments.form.repositoryUrlInvalid')}
+ </Text>
+ )}
+ </Flexbox>
+ <Flexbox horizontal>
+ <Button size={'small'} onClick={() => setPickingRepository(false)}>
+ {t('cancel', { ns: 'common' })}
</Button>
</Flexbox>
- {pastedInvalid && (
- <Text fontSize={12} type={'danger'}>
- {t('environments.form.repositoryUrlInvalid')}
- </Text>
- )}
</Flexbox>
+ ) : (
<Flexbox horizontal>
- <Button size={'small'} onClick={() => setPickingRepository(false)}>
- {t('cancel', { ns: 'common' })}
+ <Button
+ icon={<Icon icon={PlusIcon} />}
+ loading={busy}
+ size={'small'}
+ onClick={() => setPickingRepository(true)}
+ >
+ {t('environments.form.addRepository')}
</Button>
</Flexbox>
- </Flexbox>
- ) : (
- <Flexbox horizontal>
- <Button
- icon={<Icon icon={PlusIcon} />}
- loading={busy}
- size={'small'}
- onClick={() => setPickingRepository(true)}
+ )}
+ </PanelSection>
+
+ {collapseSetup ? (
+ <Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-expanded={setupOpen}
+ gap={8}
+ paddingBlock={16}
+ role={'button'}
+ style={{ cursor: 'pointer' }}
+ tabIndex={0}
+ onClick={() => setSetupOpen((open) => !open)}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ setSetupOpen((open) => !open);
+ }}
>
- {t('environments.form.addRepository')}
- </Button>
+ <Icon icon={setupOpen ? ChevronDownIcon : ChevronRightIcon} size={14} />
+ <Text weight={500}>{t('environments.form.setupAndVariables')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {[
+ t(
+ configuration.bootstrapCommand?.trim()
+ ? 'environments.form.setupConfigured'
+ : 'environments.form.setupNotConfigured',
+ ),
+ t('environments.form.variablesCount', {
+ count: Object.keys(configuration.env ?? {}).length,
+ }),
+ ].join(' · ')}
+ </Text>
+ </Flexbox>
+ {setupOpen && setupSections}
</Flexbox>
+ ) : (
+ setupSections
)}
- </PanelSection>
-
- <PanelSection
- title={t('environments.form.setup')}
- desc={
- repositories.length > 0 ? t('environments.form.bootstrapAfterRepositories') : undefined
- }
- >
- <InlineField
- multiline
- desc={t('environments.form.bootstrapHint')}
- label={t('environments.form.bootstrap')}
- value={configuration.bootstrapCommand ?? ''}
- onSave={(bootstrapCommand) => saveConfiguration({ bootstrapCommand })}
- />
- </PanelSection>
-
- {/* Said plainly because the shape cannot enforce it: a text field
- cannot tell a region from a token. */}
- <PanelSection desc={t('environments.form.envHint')} title={t('environments.form.env')}>
- <EnvironmentVariables
- entries={Object.entries(configuration.env ?? {})}
- onSave={(entries) => saveConfiguration({ env: Object.fromEntries(entries) })}
- />
- </PanelSection>
- </Flexbox>
- );
-});
+ </Flexbox>
+ );
+ },
+);
EnvironmentForm.displayName = 'EnvironmentForm';
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index 22724661801..1415313eabf 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -28,8 +28,7 @@ export const getProjectDashboardPath = (projectId: string, dashboardId?: string)
? `/project/${projectId}/dashboard/${dashboardId}`
: `/project/${projectId}/dashboard`;
-export type ProjectSettingsSection =
- 'directories' | 'environments' | 'general' | 'knowledge' | 'members' | 'sites';
+export type ProjectSettingsSection = 'environments' | 'general' | 'knowledge' | 'members' | 'sites';
export const getProjectSettingsPath = (projectId: string, section: ProjectSettingsSection) =>
`/project/${projectId}/settings/${section}`;
diff --git a/src/features/Projects/Onboarding/useOnboardingActions.ts b/src/features/Projects/Onboarding/useOnboardingActions.ts
index 0babf31c310..59d48db9d2e 100644
--- a/src/features/Projects/Onboarding/useOnboardingActions.ts
+++ b/src/features/Projects/Onboarding/useOnboardingActions.ts
@@ -27,7 +27,7 @@ export const useOnboardingActions = (detail: ProjectDetail, refreshSites: () =>
const openConnection = (item: OnboardingConnection) => {
switch (item.key) {
case 'directory': {
- if (item.done) navigate(getProjectSettingsPath(routeId, 'directories'));
+ if (item.done) navigate(getProjectSettingsPath(routeId, 'environments'));
else openAddDirectoryModal(project.id);
return;
}
diff --git a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx
index 89c3656f61d..12c13613898 100644
--- a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx
+++ b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx
@@ -13,6 +13,7 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
import { deviceService } from '@/services/device';
import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';
@@ -39,8 +40,16 @@ function AddDirectoryContent({
const devices = useDeviceStore(deviceSelectors.deviceList);
const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
const environments = useProjectEnvironments(projectId);
- const [environmentId, setEnvironment] = useState(initialEnvironmentId ?? '');
+ // A project has one environment, made with it: nothing to choose.
+ const environmentId = initialEnvironmentId ?? environments[0]?.id ?? '';
const [deviceId, setDevice] = useState(initialDeviceId ?? '');
+ // Opened from a device's own row: the machine is decided, only its folder is asked.
+ const fixedDevice = initialDeviceId
+ ? devices.find((device) => device.deviceId === initialDeviceId)
+ : undefined;
+ const fixedDeviceName = initialDeviceId
+ ? fixedDevice?.friendlyName || fixedDevice?.hostname || initialDeviceId
+ : undefined;
const [path, setPath] = useState('');
const [pending, setPending] = useState(false);
const [error, setError] = useState<unknown>();
@@ -71,31 +80,35 @@ function AddDirectoryContent({
};
return (
<Flexbox gap={16}>
- <Text type="secondary">{t('settings.addDirectoryDescription')}</Text>
- <Text>{t('directories.environment')}</Text>
- <Select
- aria-label={t('directories.environment')}
- disabled={pending}
- options={environments.map((env) => ({ value: env.id, label: env.name }))}
- placeholder={t('directories.environment')}
- value={environmentId}
- onChange={(id) => {
- setEnvironment(id ?? '');
- setError(undefined);
- }}
- />
- <Text>{t('directories.device')}</Text>
- <Select
- aria-label={t('directories.device')}
- disabled={pending}
- options={devices.map((d) => ({ value: d.deviceId, label: d.friendlyName || d.deviceId }))}
- placeholder={t('directories.device')}
- value={deviceId}
- onChange={(id) => {
- setDevice(id ?? '');
- setError(undefined);
- }}
- />
+ <Text type="secondary">
+ {fixedDeviceName
+ ? t('settings.setDirectoryDescription', { device: fixedDeviceName })
+ : t('settings.addDirectoryDescription')}
+ </Text>
+ {fixedDeviceName ? (
+ <Flexbox horizontal align="center" gap={8}>
+ {getDeviceIcon(fixedDevice?.platform, 16)}
+ <Text weight={500}>{fixedDeviceName}</Text>
+ </Flexbox>
+ ) : (
+ <>
+ <Text>{t('directories.device')}</Text>
+ <Select
+ aria-label={t('directories.device')}
+ disabled={pending}
+ placeholder={t('directories.device')}
+ value={deviceId}
+ options={devices.map((d) => ({
+ value: d.deviceId,
+ label: d.friendlyName || d.deviceId,
+ }))}
+ onChange={(id) => {
+ setDevice(id ?? '');
+ setError(undefined);
+ }}
+ />
+ </>
+ )}
<Text>{t('directories.path')}</Text>
<Input
aria-label={t('directories.path')}
@@ -133,7 +146,7 @@ function AddDirectoryContent({
type="primary"
onClick={save}
>
- {t('settings.addDirectory')}
+ {t(initialDeviceId ? 'settings.setDeviceDirectory' : 'settings.addDirectory')}
</Button>
</Flexbox>
</Flexbox>
@@ -145,7 +158,9 @@ export const openAddDirectoryModal = (
options: AddDirectoryOptions = {},
) =>
createModal({
- title: t('settings.addDirectory', { ns: 'project' }),
+ title: t(options.deviceId ? 'settings.setDeviceDirectory' : 'settings.addDirectory', {
+ ns: 'project',
+ }),
content: (
<AddDirectoryContent {...options} environmentId={environmentId} projectId={projectId} />
),
diff --git a/src/features/Projects/WorkingDirectories/ExecutionEnvironments.tsx b/src/features/Projects/WorkingDirectories/ExecutionEnvironments.tsx
new file mode 100644
index 00000000000..6aec88346ba
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/ExecutionEnvironments.tsx
@@ -0,0 +1,401 @@
+import type { DeviceListItem } from '@lobechat/types';
+import {
+ ActionIcon,
+ Button,
+ confirmModal,
+ cssVar,
+ Flexbox,
+ Icon,
+ SortableList,
+ Tag,
+ Text,
+ toast,
+ Tooltip,
+} from '@lobehub/ui';
+import {
+ BoxIcon,
+ ChevronDownIcon,
+ ChevronRightIcon,
+ PencilIcon,
+ PlusIcon,
+ Trash2Icon,
+} from 'lucide-react';
+import { type ReactNode, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import RepositoryAvatar from '@/components/RepositoryAvatar';
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+import { useSingleton } from '@/hooks/useSingleton';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import { openAddDirectoryModal } from './AddDirectoryModal';
+import {
+ type DirectoryEnableAttempt,
+ directoryUnavailableReason,
+ isMissingDirectoryError,
+} from './directoryAvailability';
+import { openEditDirectoryModal } from './EditDirectoryModal';
+import type { ProjectExecutionEnvironment } from './executionEnvironments';
+import { useProjectExecutionEnvironments } from './useProjectExecutionEnvironments';
+
+/**
+ * Presence as a dot — green online, gray offline — with the word on hover. A
+ * device restored from the persisted list (`onlineUnknown`) has not been
+ * confirmed yet, so it shows no dot until `listDevices` answers.
+ */
+const DevicePresence = ({ device }: { device?: DeviceListItem }) => {
+ const { t } = useTranslation('project');
+ if (device?.onlineUnknown) return null;
+ const online = !!device?.online;
+ const label = t(online ? 'settings.deviceOnline' : 'settings.deviceOffline');
+ // A plain element with its own title: a tooltip trigger inside a sortable
+ // row renders as a bordered button.
+ return (
+ <div
+ aria-label={label}
+ role="img"
+ title={label}
+ style={{
+ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary,
+ borderRadius: '50%',
+ flex: 'none',
+ height: 8,
+ width: 8,
+ }}
+ />
+ );
+};
+
+interface ExecutionEnvironmentsProps {
+ canManage: boolean;
+ /** The project's environment, which a new folder is linked to. */
+ environmentId?: string;
+ projectId: string;
+ /** What the cloud sandbox row unfolds into: the project environment's form. */
+ sandboxDetails: ReactNode;
+ /**
+ * The repositories the cloud sandbox clones: `owner/name` (`+N` for more)
+ * as its card's name, and the first one's slug for its logo.
+ */
+ sandboxRepository?: { label?: string; slug?: string };
+}
+
+/**
+ * Where the project's conversations run, as one list in priority order: the
+ * cloud sandbox, and every device folder someone added. Dragging a row
+ * changes the order a new conversation follows — the first folder that is
+ * ready on an online device, or the cloud sandbox, which always is. A project
+ * starts with only the sandbox; a folder is added on purpose, device by
+ * device.
+ */
+export function ExecutionEnvironments({
+ canManage,
+ environmentId,
+ projectId,
+ sandboxDetails,
+ sandboxRepository,
+}: ExecutionEnvironmentsProps) {
+ const { t } = useTranslation('project');
+ const { error, loaded, ordered, reorder, revalidate } =
+ useProjectExecutionEnvironments(projectId);
+ const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);
+ const devices = useDeviceStore(deviceSelectors.deviceList);
+ const isDeviceListLoaded = useDeviceStore(deviceSelectors.isDeviceListLoaded);
+ const removeDirectory = useProjectDirectoryStore((s) => s.removeDirectory);
+ const bind = useProjectDirectoryStore((s) => s.bind);
+ const [sandboxOpen, setSandboxOpen] = useState<boolean>();
+ // The order being dragged, shown at once; the saved one replaces it.
+ const [pendingOrder, setPendingOrder] = useState<string[]>();
+
+ const directories = ordered.flatMap((item) =>
+ item.kind === 'directory' ? [item.directory] : [],
+ );
+ // The sandbox's configuration is open until folded when it is the only
+ // execution environment: there is nothing else on the page to look at.
+ const isSandboxOpen = sandboxOpen ?? directories.length === 0;
+
+ // A folder registered before environments existed is not enabled for the
+ // project's environment yet, so nothing can start in it. There is nothing to
+ // choose — a project has one environment — so it is enabled here, once,
+ // while its device is online, by someone who may change the project.
+ const [attempts, setAttempts] = useState<Record<string, DirectoryEnableAttempt>>({});
+ // Tried once per page visit; a folder whose enable is in flight shows nothing.
+ const tried = useSingleton(() => new Set<string>());
+ useEffect(() => {
+ if (!canManage || !environmentId) return;
+ for (const directory of directories) {
+ if (directory.instanceId || tried.has(directory.id)) continue;
+ const device = devices.find((item) => item.deviceId === directory.deviceId);
+ if (!device?.online || device.onlineUnknown) continue;
+ tried.add(directory.id);
+ bind({
+ deviceId: directory.deviceId,
+ environmentId,
+ name: directory.name,
+ path: directory.path,
+ projectId,
+ }).catch((error: unknown) => {
+ console.error('Failed to enable project directory', error);
+ setAttempts((current) => ({
+ ...current,
+ [directory.id]: isMissingDirectoryError(error) ? 'missing' : 'failed',
+ }));
+ });
+ }
+ }, [bind, canManage, devices, directories, environmentId, projectId, tried]);
+
+ const remove = (directory: ProjectDirectory) =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('settings.removeDirectoryConfirmDescription', {
+ device: directory.deviceName || directory.deviceId,
+ path: directory.path,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('settings.removeDirectory'),
+ onOk: async () => {
+ try {
+ await removeDirectory(projectId, directory.id);
+ } catch (error) {
+ console.error('Failed to remove project directory', error);
+ toast.error(t('settings.removeDirectoryFailed'));
+ }
+ },
+ title: t('settings.removeDirectoryConfirmTitle', { name: directory.name }),
+ });
+
+ const save = async (order: string[]) => {
+ setPendingOrder(order);
+ try {
+ await reorder(order);
+ } catch (error) {
+ console.error('Failed to reorder execution environments', error);
+ toast.error(t('settings.reorderFailed'));
+ } finally {
+ setPendingOrder(undefined);
+ }
+ };
+
+ // A folder nothing can start in yet, said only when it needs something from
+ // the person: a device to come online, a path to fix, or someone who may.
+ const unavailableBadge = (directory: ProjectDirectory, device?: DeviceListItem) => {
+ const reason = directoryUnavailableReason({
+ attempt: attempts[directory.id],
+ canManage,
+ enabled: !!directory.instanceId,
+ online: !!device?.online,
+ presenceUnknown: !!device?.onlineUnknown,
+ });
+ if (!reason) return null;
+ return (
+ <Tooltip title={t(`settings.directoryUnavailable_${reason}`)}>
+ <Tag color="warning" size="small">
+ {t('settings.directoryUnavailableTag')}
+ </Tag>
+ </Tooltip>
+ );
+ };
+
+ /**
+ * One execution environment as a card: an icon tile, its name with any
+ * state tag, a quiet line saying where it works, and its actions.
+ */
+ // The drag handle sits at the right end of each card's header row, after its
+ // actions — the same place on every card, an unfolded sandbox included.
+ const handle = canManage ? <SortableList.DragHandle /> : null;
+
+ const card = ({
+ actions,
+ icon,
+ meta,
+ tags,
+ title,
+ }: {
+ actions?: ReactNode;
+ icon: ReactNode;
+ meta?: ReactNode;
+ tags?: ReactNode;
+ title: string;
+ }) => (
+ <Flexbox horizontal align="center" flex={1} gap={12} style={{ minWidth: 0 }}>
+ <Flexbox
+ align="center"
+ justify="center"
+ style={{
+ background: cssVar.colorFillTertiary,
+ borderRadius: 10,
+ flex: 'none',
+ height: 40,
+ width: 40,
+ }}
+ >
+ {icon}
+ </Flexbox>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>
+ <Text ellipsis fontSize={15} weight={500}>
+ {title}
+ </Text>
+ {tags}
+ </Flexbox>
+ {meta && (
+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>
+ {meta}
+ </Flexbox>
+ )}
+ </Flexbox>
+ {(actions || handle) && (
+ <Flexbox horizontal align="center" gap={4} style={{ flex: 'none' }}>
+ {actions}
+ {handle}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+
+ const metaText = (text: string) => (
+ <Text ellipsis={{ tooltip: text, tooltipWhenOverflow: true }} fontSize={12} type="secondary">
+ {text}
+ </Text>
+ );
+
+ const renderSandbox = () => (
+ <Flexbox flex={1} gap={12} style={{ minWidth: 0 }}>
+ {card({
+ actions: (
+ <ActionIcon
+ icon={isSandboxOpen ? ChevronDownIcon : ChevronRightIcon}
+ size="small"
+ title={t('settings.configureSandbox')}
+ onClick={() => setSandboxOpen(!isSandboxOpen)}
+ />
+ ),
+ icon: sandboxRepository?.slug ? (
+ <RepositoryAvatar size={24} url={sandboxRepository.slug} />
+ ) : (
+ <Icon icon={BoxIcon} size={20} />
+ ),
+ // Named after its repositories once it has some, so two sandboxes
+ // would never read alike; "cloud sandbox" then says what it is.
+ meta: metaText(
+ sandboxRepository?.label
+ ? t('settings.cloudSandboxGroup')
+ : t('settings.sandboxNoRepository'),
+ ),
+ title: sandboxRepository?.label || t('settings.cloudSandboxGroup'),
+ })}
+ {isSandboxOpen && <div style={{ paddingBlockEnd: 4 }}>{sandboxDetails}</div>}
+ </Flexbox>
+ );
+
+ const renderDirectory = (directory: ProjectDirectory) => {
+ const device = devices.find((item) => item.deviceId === directory.deviceId);
+ const presence = device?.onlineUnknown
+ ? undefined
+ : t(device?.online ? 'settings.deviceOnline' : 'settings.deviceOffline');
+ return card({
+ actions: canManage ? (
+ <>
+ <ActionIcon
+ icon={PencilIcon}
+ size="small"
+ title={t('settings.editDirectory')}
+ onClick={() => openEditDirectoryModal(projectId, directory)}
+ />
+ <ActionIcon
+ icon={Trash2Icon}
+ size="small"
+ title={t('settings.removeDirectory')}
+ onClick={() => remove(directory)}
+ />
+ </>
+ ) : undefined,
+ icon: getDeviceIcon(device?.platform ?? directory.platform ?? undefined, 20),
+ meta: (
+ <>
+ <DevicePresence device={device} />
+ {presence && (
+ <Text fontSize={12} style={{ flex: 'none' }} type="secondary">
+ {presence}
+ </Text>
+ )}
+ <Text fontSize={12} style={{ flex: 'none' }} type="secondary">
+ ·
+ </Text>
+ {metaText(directory.path)}
+ </>
+ ),
+ tags: unavailableBadge(directory, device),
+ title: device?.friendlyName || device?.hostname || directory.deviceName || directory.deviceId,
+ });
+ };
+
+ const render = (item: ProjectExecutionEnvironment) =>
+ item.kind === 'sandbox' ? renderSandbox() : renderDirectory(item.directory);
+
+ if (error || deviceRequest.error)
+ return (
+ <AsyncError
+ error={error || deviceRequest.error}
+ onRetry={() => Promise.all([revalidate(), deviceRequest.revalidate()])}
+ />
+ );
+ if (!loaded || !isDeviceListLoaded)
+ return <Text type="secondary">{t('loading', { ns: 'common' })}</Text>;
+
+ const byId = new Map(ordered.map((item) => [item.id, item]));
+ const items = (pendingOrder ?? ordered.map((item) => item.id)).flatMap((id) => {
+ const item = byId.get(id);
+ return item ? [item] : [];
+ });
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align="center" gap={16} justify="space-between">
+ <Text fontSize={13} type="secondary">
+ {t('settings.executionOrderHint')}
+ </Text>
+ {canManage && (
+ <Button
+ icon={<Icon icon={PlusIcon} />}
+ style={{ flex: 'none' }}
+ type="primary"
+ onClick={() => openAddDirectoryModal(projectId, environmentId)}
+ >
+ {t('settings.addExecutionEnvironment')}
+ </Button>
+ )}
+ </Flexbox>
+ {canManage ? (
+ <SortableList
+ items={items}
+ renderItem={(item: ProjectExecutionEnvironment) => (
+ <SortableList.Item
+ id={item.id}
+ style={{ borderRadius: 16, padding: 16 }}
+ variant="filled"
+ >
+ {render(item)}
+ </SortableList.Item>
+ )}
+ onChange={(next: ProjectExecutionEnvironment[]) => void save(next.map((item) => item.id))}
+ />
+ ) : (
+ items.map((item) => (
+ <Flexbox
+ horizontal
+ align="center"
+ key={item.id}
+ padding={16}
+ style={{ background: cssVar.colorFillQuaternary, borderRadius: 16 }}
+ >
+ {render(item)}
+ </Flexbox>
+ ))
+ )}
+ </Flexbox>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsx
index 151e2a8cd41..005cda35741 100644
--- a/src/features/Projects/WorkingDirectories/Page.tsx
+++ b/src/features/Projects/WorkingDirectories/Page.tsx
@@ -18,7 +18,6 @@ import { useCanManageProject } from '../useCanManageProject';
import { AdvancedSettings } from './AdvancedSettings';
import { GeneralSettings } from './GeneralSettings';
import { ProjectWorkingDirectories } from './index';
-import { WorkingDirectorySettings } from './WorkingDirectorySettings';
interface SectionItem {
key: string;
@@ -66,11 +65,6 @@ export function ProjectDirectoriesPage() {
<ProjectWorkingDirectories canManage={canManage} projectId={detail.project.id} />
),
},
- {
- key: 'directories',
- label: t('settings.workLocations'),
- render: () => <WorkingDirectorySettings projectId={detail.project.id} />,
- },
{
key: 'sites',
label: t('review.sites.title'),
@@ -87,7 +81,10 @@ export function ProjectDirectoriesPage() {
]
: []),
];
- const activeSection = sections.find((item) => item.key === section) ?? sections[0];
+ // Local folders were their own tab before they joined the environment; an old
+ // link to that tab opens the environment, where they now are.
+ const sectionKey = section === 'directories' ? 'environments' : section;
+ const activeSection = sections.find((item) => item.key === sectionKey) ?? sections[0];
return (
<Flexbox flex={1} padding={isMobile ? 16 : 32} style={{ overflow: 'auto' }}>
diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
index adc0754669f..afb09427c98 100644
--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
@@ -33,6 +33,7 @@ import {
import { useOnlyMineTopics, useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';
import { useSectionTriggerStyle } from '@/features/NavPanel/components/SectionTitle';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useDeviceList } from '@/store/device';
import {
useProjectDirectories,
useProjectDirectoryStore,
@@ -40,8 +41,13 @@ import {
} from '@/store/projectWorkingDirectory';
import { filterTopics, type TopicListFilter } from '@/utils/client/topic';
+import { pickExecutionEnvironment } from './executionEnvironments';
import { canStageDraftOn } from './startProjectTopicDraft';
import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';
+import {
+ isExecutionDirectoryAvailable,
+ useProjectExecutionEnvironments,
+} from './useProjectExecutionEnvironments';
import { useProjectTopicReveal } from './useProjectTopicReveal';
import { useStartProjectTopic } from './useStartProjectTopic';
@@ -99,6 +105,8 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDir
);
const startTopic = useStartProjectTopic(projectId);
const fixedDeviceId = useAgentFixedDeviceId(coordinatorAgentId);
+ const { ordered } = useProjectExecutionEnvironments(projectId);
+ const { data: devices } = useDeviceList();
return (
<AccordionItem value={itemKey}>
<AccordionHeader>
@@ -125,14 +133,22 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDir
icon={PlusIcon}
size="small"
title={t('sidebar.newConversation')}
- onClick={() =>
+ onClick={() => {
// Same habit as an agent's "+": straight into the coordinator's
- // conversation, on the first directory it can run in when there is one.
+ // conversation, in the project's first execution environment that
+ // can take it now — a ready folder on an online device the agent
+ // may use — or the cloud sandbox.
+ const picked = pickExecutionEnvironment(
+ ordered,
+ (directory) =>
+ canStageDraftOn(directory, fixedDeviceId) &&
+ isExecutionDirectoryAvailable(directory, devices),
+ );
startTopic({
agentId: coordinatorAgentId,
- directoryId: directories.find((d) => canStageDraftOn(d, fixedDeviceId))?.id,
- })
- }
+ directoryId: picked.kind === 'directory' ? picked.id : undefined,
+ });
+ }}
/>
</Flexbox>
</AccordionHeader>
diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
deleted file mode 100644
index 97335385982..00000000000
--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-import type { DeviceListItem } from '@lobechat/types';
-import {
- ActionIcon,
- Button,
- confirmModal,
- cssVar,
- Flexbox,
- Icon,
- Select,
- Text,
- toast,
-} from '@lobehub/ui';
-import { FolderIcon, LinkIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-import { useSearchParams } from 'react-router';
-
-import AsyncError from '@/components/AsyncError';
-import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { deviceSelectors, useDeviceStore } from '@/store/device';
-import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
-import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
-import {
- useProjectDirectories,
- useProjectDirectoryStore,
- useProjectEnvironments,
-} from '@/store/projectWorkingDirectory';
-import { useDensityTokens } from '@/styles/density';
-
-import { openAddDirectoryModal } from './AddDirectoryModal';
-import { openBindDirectoryModal } from './BindDirectoryModal';
-import { openEditDirectoryModal } from './EditDirectoryModal';
-
-/**
- * A device row restored from the persisted list (`onlineUnknown`) has not been
- * confirmed yet, so its presence is left unsaid until `listDevices` answers.
- */
-const DevicePresence = ({ device }: { device?: DeviceListItem }) => {
- const { t } = useTranslation('project');
- if (device?.onlineUnknown) return null;
- return (
- <Text fontSize={12} type="secondary">
- {t(device?.online ? 'settings.deviceOnline' : 'settings.deviceOffline')}
- </Text>
- );
-};
-
-export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
- const { t } = useTranslation('project');
- const { pageTitleFontSize } = useDensityTokens();
- const navigate = useWorkspaceAwareNavigate();
- const [params, setParams] = useSearchParams();
- const environmentId = params.get('environment') ?? '';
- useProjectStore((s) => s.useFetchProjectDetail)(projectId);
- const project = useCurrentProjectDetail(projectId);
- const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
- const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
- const environments = useProjectEnvironments(projectId);
- const directories = useProjectDirectories(projectId);
- const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);
- const devices = useDeviceStore(deviceSelectors.deviceList);
- const isDeviceListLoaded = useDeviceStore(deviceSelectors.isDeviceListLoaded);
- const items = directories.filter((d) => !environmentId || d.environmentId === environmentId);
- const error = environmentsRequest.error || directoriesRequest.error || deviceRequest.error;
- const removeDirectory = useProjectDirectoryStore((s) => s.removeDirectory);
- const canManage = project?.permissions?.canManage ?? false;
- const remove = (directory: ProjectDirectory) =>
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('settings.removeDirectoryConfirmDescription', {
- device: directory.deviceName || directory.deviceId,
- path: directory.path,
- }),
- okButtonProps: { danger: true },
- okText: t('settings.removeDirectory'),
- onOk: async () => {
- try {
- await removeDirectory(projectId, directory.id);
- } catch (error) {
- console.error('Failed to remove project directory', error);
- toast.error(t('settings.removeDirectoryFailed'));
- }
- },
- title: t('settings.removeDirectoryConfirmTitle', { name: directory.name }),
- });
- return (
- <Flexbox gap={20}>
- <Flexbox gap={6}>
- <Text fontSize={pageTitleFontSize} weight={600}>
- {t('settings.workLocations')}
- </Text>
- <Text type="secondary">{t('settings.directoryListDescription')}</Text>
- </Flexbox>
- <Flexbox horizontal gap={12} justify="space-between">
- <Select
- aria-label={t('directories.environment')}
- value={environmentId || '__all__'}
- options={[
- { label: t('settings.allEnvironments'), value: '__all__' },
- ...environments.map((env) => ({ label: env.name, value: env.id })),
- ]}
- onChange={(id) => setParams(id && id !== '__all__' ? { environment: id } : {})}
- />
- <Button
- icon={PlusIcon}
- type="primary"
- onClick={() =>
- environments.length
- ? openAddDirectoryModal(projectId, environmentId || undefined)
- : navigate(`/project/${projectId}/settings/environments`)
- }
- >
- {t('settings.addDirectory')}
- </Button>
- </Flexbox>
- {error ? (
- <AsyncError
- error={error}
- onRetry={() =>
- Promise.all([
- environmentsRequest.revalidate(),
- directoriesRequest.revalidate(),
- deviceRequest.revalidate(),
- ])
- }
- />
- ) : null}
- {error ? null : !directoriesRequest.hasData ||
- !environmentsRequest.hasData ||
- !isDeviceListLoaded ? (
- <Text>{t('loading', { ns: 'common' })}</Text>
- ) : !items.length ? (
- <Flexbox gap={12} paddingBlock={24}>
- <Text type="secondary">{t('settings.noDirectories')}</Text>
- {!environments.length && (
- <Button onClick={() => navigate(`/project/${projectId}/settings/environments`)}>
- {t('settings.addEnvironment')}
- </Button>
- )}
- </Flexbox>
- ) : (
- <Flexbox>
- {items.map((directory, index) => (
- <Flexbox
- key={directory.id}
- paddingBlock={12}
- style={index ? { borderTop: `1px solid ${cssVar.colorBorderSecondary}` } : undefined}
- >
- <Flexbox horizontal align="center" gap={16} justify="space-between">
- <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
- <Flexbox horizontal align="center" gap={8}>
- <Icon icon={FolderIcon} size={18} />
- <Text style={{ overflowWrap: 'anywhere' }} weight={500}>
- {directory.path}
- </Text>
- </Flexbox>
- <Flexbox horizontal align="center" gap={8} wrap="wrap">
- {getDeviceIcon(
- devices.find((d) => d.deviceId === directory.deviceId)?.platform,
- 14,
- )}
- <Text fontSize={12}>{directory.deviceName || directory.deviceId}</Text>
- <DevicePresence
- device={devices.find((d) => d.deviceId === directory.deviceId)}
- />
- </Flexbox>
- </Flexbox>
- <Flexbox horizontal align="center" gap={8}>
- {/* A legacy row has no environment yet, so linking it is still its next step. */}
- {!directory.instanceId && (
- <Button
- icon={LinkIcon}
- size="small"
- onClick={() =>
- openBindDirectoryModal({
- projectId,
- deviceId: directory.deviceId,
- path: directory.path,
- })
- }
- >
- {t('directories.bind')}
- </Button>
- )}
- {canManage && (
- <ActionIcon
- icon={PencilIcon}
- size="small"
- title={t('settings.editDirectory')}
- onClick={() => openEditDirectoryModal(projectId, directory)}
- />
- )}
- {canManage && (
- <ActionIcon
- icon={Trash2Icon}
- size="small"
- title={t('settings.removeDirectory')}
- onClick={() => remove(directory)}
- />
- )}
- </Flexbox>
- </Flexbox>
- </Flexbox>
- ))}
- </Flexbox>
- )}
- </Flexbox>
- );
-}
diff --git a/src/features/Projects/WorkingDirectories/directoryAvailability.test.ts b/src/features/Projects/WorkingDirectories/directoryAvailability.test.ts
new file mode 100644
index 00000000000..5a79d6b7001
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/directoryAvailability.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { directoryUnavailableReason, isMissingDirectoryError } from './directoryAvailability';
+
+const base = { canManage: true, enabled: false, online: true, presenceUnknown: false };
+
+describe('directoryUnavailableReason', () => {
+ it('says nothing for a folder that is enabled, or still being enabled', () => {
+ expect(directoryUnavailableReason({ ...base, enabled: true, online: false })).toBeUndefined();
+ expect(directoryUnavailableReason({ ...base, attempt: 'pending' })).toBeUndefined();
+ });
+
+ it('enables an online folder on sight for someone who may, so there is nothing to show', () => {
+ expect(directoryUnavailableReason(base)).toBeUndefined();
+ });
+
+ it('waits for the device to come online', () => {
+ expect(directoryUnavailableReason({ ...base, online: false })).toBe('offline');
+ });
+
+ it('says why an enable failed', () => {
+ expect(directoryUnavailableReason({ ...base, attempt: 'missing' })).toBe('missing');
+ expect(directoryUnavailableReason({ ...base, attempt: 'failed' })).toBe('failed');
+ });
+
+ it('leaves it to someone who may change the project', () => {
+ expect(directoryUnavailableReason({ ...base, canManage: false })).toBe('needsManager');
+ });
+
+ it('holds back until presence is known', () => {
+ expect(
+ directoryUnavailableReason({ ...base, online: false, presenceUnknown: true }),
+ ).toBeUndefined();
+ });
+});
+
+describe('isMissingDirectoryError', () => {
+ it('reads the server refusal for a folder that is not on the device', () => {
+ expect(
+ isMissingDirectoryError(new Error('Working directory does not exist on this device')),
+ ).toBe(true);
+ expect(isMissingDirectoryError(new Error('Project not found or access denied'))).toBe(false);
+ expect(isMissingDirectoryError(new Error('Environment instance is disabled'))).toBe(false);
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/directoryAvailability.ts b/src/features/Projects/WorkingDirectories/directoryAvailability.ts
new file mode 100644
index 00000000000..f6540bb3f28
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/directoryAvailability.ts
@@ -0,0 +1,38 @@
+/** Why a project folder cannot be worked in yet, or nothing when it can. */
+export type DirectoryUnavailableReason = 'failed' | 'missing' | 'needsManager' | 'offline';
+
+/** What became of enabling a folder: still running, or why it could not be. */
+export type DirectoryEnableAttempt = 'failed' | 'missing' | 'pending';
+
+/**
+ * Whether a project folder can be worked in, and when not, why — in words a
+ * person can act on. A folder becomes usable once it is enabled for the
+ * project's environment; that is done for them while its device is online, so
+ * the only states left to show are the ones that need something from them.
+ */
+export const directoryUnavailableReason = ({
+ attempt,
+ canManage,
+ enabled,
+ online,
+ presenceUnknown,
+}: {
+ /** The automatic enable for this folder, when one was tried. */
+ attempt?: DirectoryEnableAttempt;
+ canManage: boolean;
+ enabled: boolean;
+ online: boolean;
+ /** The device list has not confirmed presence yet: say nothing until it does. */
+ presenceUnknown: boolean;
+}): DirectoryUnavailableReason | undefined => {
+ if (enabled || presenceUnknown || attempt === 'pending') return;
+ if (attempt === 'missing' || attempt === 'failed') return attempt;
+ if (!online) return 'offline';
+ // Online, never tried: one who may change the project enables it on sight.
+ return canManage ? undefined : 'needsManager';
+};
+
+/** A refused enable that means the folder is not on the device (any more). */
+export const isMissingDirectoryError = (error: unknown) =>
+ error instanceof Error &&
+ /does not exist|working directory is unavailable|not a directory/i.test(error.message);
diff --git a/src/features/Projects/WorkingDirectories/executionEnvironments.test.ts b/src/features/Projects/WorkingDirectories/executionEnvironments.test.ts
new file mode 100644
index 00000000000..c9c5060b499
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/executionEnvironments.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+
+import { orderExecutionEnvironments, pickExecutionEnvironment } from './executionEnvironments';
+
+const folder = (id: string, sortOrder = 0) => ({ id, sortOrder }) as unknown as ProjectDirectory;
+const ids = (items: { id: string }[]) => items.map((item) => item.id);
+
+describe('orderExecutionEnvironments', () => {
+ it('puts folders before the sandbox until anything is reordered', () => {
+ expect(ids(orderExecutionEnvironments([folder('a'), folder('b')]))).toEqual([
+ 'a',
+ 'b',
+ 'sandbox',
+ ]);
+ });
+
+ it('follows the stored order of folders and the sandbox', () => {
+ expect(ids(orderExecutionEnvironments([folder('a', 2), folder('b', 1)], 0))).toEqual([
+ 'sandbox',
+ 'b',
+ 'a',
+ ]);
+ });
+
+ it('is only the sandbox for a project without folders', () => {
+ expect(ids(orderExecutionEnvironments([]))).toEqual(['sandbox']);
+ });
+});
+
+describe('pickExecutionEnvironment', () => {
+ const ordered = orderExecutionEnvironments([folder('a', 0), folder('b', 1)], 2);
+
+ it('picks the first folder that is available now', () => {
+ expect(pickExecutionEnvironment(ordered, (d) => d.id === 'b').id).toBe('b');
+ });
+
+ it('falls back to the sandbox when no folder is available', () => {
+ expect(pickExecutionEnvironment(ordered, () => false).id).toBe('sandbox');
+ });
+
+ it('never picks a folder placed after the sandbox', () => {
+ const sandboxFirst = orderExecutionEnvironments([folder('a', 1)], 0);
+ expect(pickExecutionEnvironment(sandboxFirst, () => true).id).toBe('sandbox');
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/executionEnvironments.ts b/src/features/Projects/WorkingDirectories/executionEnvironments.ts
new file mode 100644
index 00000000000..42ef7d7e64f
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/executionEnvironments.ts
@@ -0,0 +1,56 @@
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+
+/** The id the cloud sandbox takes in a project's execution-environment order. */
+export const SANDBOX_EXECUTION_ENVIRONMENT = 'sandbox';
+
+/** One of a project's execution environments: the cloud sandbox, or a device folder. */
+export type ProjectExecutionEnvironment =
+ | { id: typeof SANDBOX_EXECUTION_ENVIRONMENT; kind: 'sandbox' }
+ | { directory: ProjectDirectory; id: string; kind: 'directory' };
+
+const SANDBOX_ENTRY: ProjectExecutionEnvironment = {
+ id: SANDBOX_EXECUTION_ENVIRONMENT,
+ kind: 'sandbox',
+};
+
+/**
+ * A project's execution environments in priority order: by their stored place,
+ * a folder before the sandbox on a tie — so a project nobody reordered tries
+ * its folders first and falls back to the sandbox — and folders among
+ * themselves in the order they came (the list's own order).
+ */
+export const orderExecutionEnvironments = (
+ directories: readonly ProjectDirectory[],
+ sandboxOrder = 0,
+): ProjectExecutionEnvironment[] =>
+ [
+ ...directories.map((directory, index) => ({
+ index,
+ item: { directory, id: directory.id, kind: 'directory' } as ProjectExecutionEnvironment,
+ sortOrder: directory.sortOrder ?? 0,
+ })),
+ {
+ index: directories.length,
+ item: SANDBOX_ENTRY,
+ sortOrder: sandboxOrder,
+ },
+ ]
+ .sort((a, b) => a.sortOrder - b.sortOrder || a.index - b.index)
+ .map(({ item }) => item);
+
+/**
+ * Where a new conversation starts: the first execution environment in the
+ * order that can take it now — a folder on a device that is online and ready
+ * — or the cloud sandbox, which always can. A folder after the sandbox is
+ * never picked automatically; it is still there to choose by hand.
+ */
+export const pickExecutionEnvironment = (
+ ordered: readonly ProjectExecutionEnvironment[],
+ isAvailable: (directory: ProjectDirectory) => boolean,
+): ProjectExecutionEnvironment => {
+ for (const environment of ordered) {
+ if (environment.kind === 'sandbox') return environment;
+ if (isAvailable(environment.directory)) return environment;
+ }
+ return SANDBOX_ENTRY;
+};
diff --git a/src/features/Projects/WorkingDirectories/index.tsx b/src/features/Projects/WorkingDirectories/index.tsx
index 6b8b8856781..dd2add2099f 100644
--- a/src/features/Projects/WorkingDirectories/index.tsx
+++ b/src/features/Projects/WorkingDirectories/index.tsx
@@ -1,22 +1,19 @@
-import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
-import { FolderIcon } from 'lucide-react';
import { type ReactNode } from 'react';
-import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
+import {
+ repositoriesLabel,
+ repositorySlug,
+} from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';
import EnvironmentForm, {
type EnvironmentFormValue,
} from '@/features/EnvironmentManager/EnvironmentForm';
import EnvironmentSummary from '@/features/EnvironmentManager/EnvironmentSummary';
import { EnvironmentListSkeleton } from '@/features/EnvironmentManager/Skeleton';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { SandboxEnvironmentSpecification } from '@/services/environment';
-import {
- useProjectDirectories,
- useProjectDirectoryStore,
- useProjectEnvironments,
-} from '@/store/projectWorkingDirectory';
-import { useDensityTokens } from '@/styles/density';
+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';
+
+import { ExecutionEnvironments } from './ExecutionEnvironments';
interface ProjectWorkingDirectoriesProps {
/** Whether the caller may change the project, and so its environment. */
@@ -25,24 +22,18 @@ interface ProjectWorkingDirectoriesProps {
}
/**
- * The project's environment, laid out in full and flat — the same form an
- * environment's own page shows: the repositories it checks out (any number, or
- * none, each with its own setup), the setup that runs after, and the variables
- * every command sees. Every project has exactly one, made with it — there is nothing
- * to link, pick or create here, only the environment itself to fill in.
+ * The project's execution environments, in the priority a new conversation
+ * follows: the cloud sandbox — whose row unfolds into the project's
+ * environment, the repositories it clones, the setup that runs and the
+ * variables every command sees — and the device folders someone added.
*/
export function ProjectWorkingDirectories({
canManage,
projectId,
}: ProjectWorkingDirectoriesProps) {
- const { t } = useTranslation(['project', 'setting']);
- const { pageTitleFontSize } = useDensityTokens();
- const navigate = useWorkspaceAwareNavigate();
const request = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
- const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
const updateEnvironment = useProjectDirectoryStore((s) => s.updateProjectEnvironment);
const [environment] = useProjectEnvironments(projectId);
- const directories = useProjectDirectories(projectId);
const save = async (changes: {
configuration?: SandboxEnvironmentSpecification;
@@ -55,43 +46,39 @@ export function ProjectWorkingDirectories({
});
};
- let content: ReactNode;
+ let cloud: ReactNode;
if (request.error && !environment) {
- content = <AsyncError error={request.error} onRetry={() => request.revalidate()} />;
+ cloud = <AsyncError error={request.error} onRetry={() => request.revalidate()} />;
} else if (!request.hasData || !environment) {
- content = <EnvironmentListSkeleton />;
+ cloud = <EnvironmentListSkeleton />;
} else {
const value: EnvironmentFormValue = environment;
- content = canManage ? (
- <EnvironmentForm hideBasics environment={value} onSave={save} />
+ cloud = canManage ? (
+ <EnvironmentForm
+ collapseSetup
+ hideBasics
+ hideRepositoryHints
+ environment={value}
+ onSave={save}
+ />
) : (
<EnvironmentSummary environment={value} />
);
}
- const folderCount = directoriesRequest.hasData ? directories.length : undefined;
+ // The sandbox is told apart by the repositories it clones: their name and
+ // the first one's logo on its card.
+ const sandboxRepository = environment
+ ? { label: repositoriesLabel(environment), slug: repositorySlug(environment) }
+ : undefined;
return (
- <Flexbox gap={16}>
- <Flexbox gap={8}>
- <Flexbox horizontal align="center" gap={12} justify="space-between" wrap="wrap">
- <Text fontSize={pageTitleFontSize} weight={600}>
- {t('settings.environments')}
- </Text>
- {folderCount !== undefined && (
- <Button
- icon={<Icon icon={FolderIcon} />}
- onClick={() => navigate(`/project/${projectId}/settings/directories`)}
- >
- {t(folderCount ? 'settings.viewDirectories' : 'settings.configureDirectory', {
- count: folderCount,
- })}
- </Button>
- )}
- </Flexbox>
- <Text type="secondary">{t('settings.environmentIntro')}</Text>
- </Flexbox>
- {content}
- </Flexbox>
+ <ExecutionEnvironments
+ canManage={!!canManage}
+ environmentId={environment?.id}
+ projectId={projectId}
+ sandboxDetails={cloud}
+ sandboxRepository={sandboxRepository}
+ />
);
}
diff --git a/src/features/Projects/WorkingDirectories/useProjectExecutionEnvironments.ts b/src/features/Projects/WorkingDirectories/useProjectExecutionEnvironments.ts
new file mode 100644
index 00000000000..333706529fd
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useProjectExecutionEnvironments.ts
@@ -0,0 +1,77 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { useCallback, useMemo } from 'react';
+import useSWR from 'swr';
+
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import {
+ orderExecutionEnvironments,
+ type ProjectExecutionEnvironment,
+} from './executionEnvironments';
+
+const executionOrderKey = (projectId?: string) =>
+ projectId ? ['project-execution-order', projectId] : null;
+
+/**
+ * Whether a folder can take a new conversation now: its device is online and
+ * the folder is ready to run (linked to the project's environment, writable).
+ */
+export const isExecutionDirectoryAvailable = (
+ directory: ProjectDirectory,
+ devices: readonly DeviceListItem[] | undefined,
+) => {
+ const device = devices?.find((item) => item.deviceId === directory.deviceId);
+ return !!directory.runnable && !!device?.online && !device.onlineUnknown;
+};
+
+/**
+ * A project's execution environments in priority order — its device folders
+ * and the cloud sandbox — and the way to reorder them. The order is the
+ * priority a new conversation follows; the folders come from the project's
+ * directory list, the sandbox's place from `executionOrder`.
+ */
+export const useProjectExecutionEnvironments = (projectId?: string, enabled = true) => {
+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(
+ projectId,
+ enabled && !!projectId,
+ );
+ const directories = useProjectDirectories(projectId);
+ const orderRequest = useSWR(enabled ? executionOrderKey(projectId) : null, async () => {
+ const result = await projectWorkingDirectoryService.executionOrder(projectId!);
+ return result.data;
+ });
+
+ const ordered: ProjectExecutionEnvironment[] = useMemo(
+ () => orderExecutionEnvironments(directories, orderRequest.data?.sandbox ?? 0),
+ [directories, orderRequest.data?.sandbox],
+ );
+
+ const reorder = useCallback(
+ async (order: string[]) => {
+ if (!projectId) return;
+ // The sandbox's new place, shown at once; the folders' places come back
+ // with the list.
+ const sandbox = order.indexOf('sandbox');
+ await orderRequest.mutate(
+ async () => {
+ await projectWorkingDirectoryService.reorderExecutionEnvironments({ order, projectId });
+ await directoriesRequest.revalidate();
+ return { sandbox };
+ },
+ { optimisticData: { sandbox }, rollbackOnError: true },
+ );
+ },
+ [directoriesRequest, orderRequest, projectId],
+ );
+
+ return {
+ directories,
+ error: directoriesRequest.error || orderRequest.error,
+ loaded: directoriesRequest.hasData && orderRequest.data !== undefined,
+ ordered,
+ reorder,
+ revalidate: () => Promise.all([directoriesRequest.revalidate(), orderRequest.mutate()]),
+ };
+};
diff --git a/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx
index 7211ff5e9bc..4d9d7042d4e 100644
--- a/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx
+++ b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx
@@ -4,8 +4,8 @@ import type { DeviceExecutionTarget } from '@lobechat/types';
import { Flexbox, Icon, Popover, Text, toast, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { ChevronDownIcon, CircleOffIcon, FolderIcon, PlusIcon, SettingsIcon } from 'lucide-react';
-import { type ReactNode, useState } from 'react';
+import { ChevronDownIcon, FolderIcon, PlusIcon, SettingsIcon } from 'lucide-react';
+import { Fragment, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RepositoryAvatar from '@/components/RepositoryAvatar';
@@ -17,10 +17,11 @@ import {
import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
import { environmentRepositoryUrl } from '../environmentSource';
import { openAddDirectoryModal } from '../WorkingDirectories/AddDirectoryModal';
-import { addedFolderTarget, type useProjectDirectory } from './useProjectDirectory';
+import { addedFolderTarget } from './useProjectDirectory';
import { NO_ENVIRONMENT, type useProjectRepository } from './useProjectRepository';
import type { useProjectWorkLocation } from './useProjectWorkLocation';
@@ -74,14 +75,21 @@ interface ProjectWorkLocationPickerProps {
/** Icon only, the place in the tooltip — for a narrow composer. */
compact?: boolean;
/** The project folder a run on a device starts in. */
- directoryState: ReturnType<typeof useProjectDirectory>;
+ directoryState: {
+ directory?: ProjectDirectory;
+ directoriesOn: (deviceId: string) => ProjectDirectory[];
+ setPickedId: (directoryId: string) => void;
+ };
disabled?: boolean;
/** Where the agent runs and where it can be moved to. */
location: ReturnType<typeof useProjectWorkLocation>;
projectId: string;
/** A task starts no conversation, so it has no code environment or folder to pick. */
showRepositories?: boolean;
- state: ReturnType<typeof useProjectRepository>;
+ state: Pick<
+ ReturnType<typeof useProjectRepository>,
+ 'repositories' | 'repository' | 'withoutEnvironment'
+ > & { setPickedId: (environmentId: string) => void };
}
/**
@@ -119,6 +127,8 @@ const ProjectWorkLocationPicker = ({
const { repositories, repository, setPickedId, withoutEnvironment } = state;
const repositoryShown = showRepositories && onSandbox && !!repository;
+ // The chip sits at the composer's right edge, so the second level opens inward.
+ const submenuPlacement = 'leftTop';
const select = async (next: DeviceExecutionTarget, deviceId?: string) => {
setOpen(false);
@@ -203,43 +213,41 @@ const ProjectWorkLocationPicker = ({
!!location.machineDeviceId &&
(machineFolders.length > 1 || canManage)));
- const repositoryMenu = (
- <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 260 }}>
- <div {...stylex.props(styles.header)}>{t('overview.context.location.environments')}</div>
+ // An execution environment is one thing to pick: a cloud sandbox set up
+ // from the project's environment (its repositories, setup and variables),
+ // an empty one — or, below, a device with its local folder.
+ const sandboxEntities = (
+ <>
+ <div {...stylex.props(styles.header)}>{t('overview.context.location.sandboxes')}</div>
<div {...stylex.props(styles.list)}>
- {/* Not every conversation needs the checkout: this one starts in an
- empty working directory. */}
- {repositories.length > 0 && (
- <OptionRow
- compact
- active={onSandbox && withoutEnvironment}
- icon={<Icon icon={CircleOffIcon} size={16} />}
- label={t('environment.none')}
- onClick={() => pickRepository(NO_ENVIRONMENT)}
- />
- )}
{repositories.map((environment) => (
<OptionRow
compact
+ active={onSandbox && environment.id === repository?.id}
+ desc={repositoriesLabel(environment) ?? undefined}
icon={<RepositoryAvatar size={16} url={environmentRepositoryUrl(environment)} />}
key={environment.id}
label={environment.name}
onClick={() => pickRepository(environment.id)}
- active={onSandbox && environment.id === repository?.id}
- // A name that already is the slug needs no second copy of it.
- hint={
- repositoriesLabel(environment) === environment.name
- ? undefined
- : repositoriesLabel(environment)
- }
/>
))}
+ {/* Not every conversation needs the checkout: an empty sandbox starts
+ in an empty working directory. */}
+ <OptionRow
+ compact
+ active={onSandbox && (withoutEnvironment || repositories.length === 0)}
+ desc={t('overview.context.location.emptySandboxDesc')}
+ icon={<ExecutionTargetIcon target={'sandbox'} />}
+ label={t('overview.context.location.emptySandbox')}
+ onClick={() =>
+ repositories.length > 0
+ ? pickRepository(NO_ENVIRONMENT)
+ : switchable
+ ? void select('sandbox')
+ : setOpen(false)
+ }
+ />
</div>
- {repositories.length === 0 && (
- <Text className={stylex.props(styles.hint).className}>
- {t('overview.context.location.noEnvironments')}
- </Text>
- )}
{canManage && (
<OptionRow
compact
@@ -248,7 +256,7 @@ const ProjectWorkLocationPicker = ({
onClick={configureEnvironment}
/>
)}
- </Flexbox>
+ </>
);
/** One machine's folders: the second level of its row. */
@@ -300,7 +308,7 @@ const ProjectWorkLocationPicker = ({
closeDelay={150}
content={directoryMenu(next, deviceId)}
key={deviceId ?? next}
- placement={'leftTop'}
+ placement={submenuPlacement}
styles={SUBMENU_STYLES}
trigger={['hover', 'click']}
>
@@ -313,74 +321,98 @@ const ProjectWorkLocationPicker = ({
const sandboxRow = (
<OptionRow
active={onSandbox}
- arrow={showRepositories}
disabled={!switchable && !onSandbox}
icon={<ExecutionTargetIcon target={'sandbox'} />}
label={tChat('heteroAgent.executionTarget.sandbox')}
onClick={() => {
if (switchable) void select('sandbox');
+ else setOpen(false);
}}
/>
);
+ /** A machine as places to run: one row per local folder, or the machine itself without one. */
+ const machineEntities = (next: 'device' | 'local', device?: (typeof deviceRows)[number]) => {
+ const deviceId = device?.deviceId;
+ const folders = showRepositories
+ ? directoriesOn((next === 'local' ? currentDeviceId : deviceId) ?? '')
+ : [];
+ const onThisMachine =
+ next === 'local'
+ ? target === 'local'
+ : target === 'device' && deviceId === boundDevice?.deviceId;
+ const name =
+ next === 'local'
+ ? tChat('heteroAgent.executionTarget.local')
+ : device?.friendlyName || device?.hostname || deviceId || '';
+ const icon =
+ next === 'local' ? (
+ <ExecutionTargetIcon target={'local'} />
+ ) : (
+ <ExecutionTargetIcon devicePlatform={device?.platform} target={'device'} />
+ );
+ const status = device && (
+ <ExecutionTargetDeviceStatus
+ offlineLabel={tChat('heteroAgent.executionTarget.offline')}
+ online={device.online}
+ onlineLabel={tChat('heteroAgent.executionTarget.online')}
+ unknown={device.onlineUnknown}
+ unknownLabel={tChat('heteroAgent.executionTarget.presenceChecking')}
+ />
+ );
+ if (folders.length > 0)
+ return folders.map((folder) => (
+ <OptionRow
+ active={onThisMachine && folder.id === directory?.id}
+ // The path on its own line, so the machine's name stays whole.
+ desc={folder.path}
+ hint={status}
+ icon={icon}
+ key={folder.id}
+ label={name}
+ onClick={() => pickDirectory(folder.id, next, deviceId)}
+ />
+ ));
+ return machineRow(
+ <OptionRow
+ active={onThisMachine}
+ arrow={showRepositories}
+ hint={status}
+ icon={icon}
+ label={name}
+ onClick={() => void select(next, deviceId)}
+ />,
+ next,
+ deviceId,
+ );
+ };
+
const content = (
- <Flexbox gap={2} style={{ maxWidth: 360, minWidth: 280 }}>
+ <Flexbox gap={2} style={{ maxWidth: 380, minWidth: 300 }}>
<div {...stylex.props(styles.header)}>{t('overview.context.location.title')}</div>
{(sandboxAvailable || onSandbox) &&
(showRepositories ? (
- <Popover
- arrow={false}
- closeDelay={150}
- content={repositoryMenu}
- // The chip sits at the composer's right edge, so the second level
- // opens inward rather than off the side of the window.
- placement={'leftTop'}
- styles={SUBMENU_STYLES}
- trigger={['hover', 'click']}
- >
- <div data-testid={'project-location-sandbox'}>{sandboxRow}</div>
- </Popover>
+ sandboxEntities
) : (
- sandboxRow
+ <div data-testid={'project-location-sandbox'}>{sandboxRow}</div>
))}
{(localAvailable || deviceRows.length > 0) && (
<>
<div {...stylex.props(styles.header)}>{t('overview.context.location.devices')}</div>
- {localAvailable &&
- machineRow(
- <OptionRow
- active={target === 'local'}
- arrow={showRepositories}
- icon={<ExecutionTargetIcon target={'local'} />}
- label={tChat('heteroAgent.executionTarget.local')}
- onClick={() => void select('local')}
- />,
- 'local',
- )}
<div {...stylex.props(styles.list)}>
- {deviceRows.map((device) =>
- machineRow(
- <OptionRow
- active={target === 'device' && device.deviceId === boundDevice?.deviceId}
- arrow={showRepositories}
- icon={<ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />}
- label={device.friendlyName || device.hostname || device.deviceId}
- hint={
- <ExecutionTargetDeviceStatus
- offlineLabel={tChat('heteroAgent.executionTarget.offline')}
- online={device.online}
- onlineLabel={tChat('heteroAgent.executionTarget.online')}
- unknown={device.onlineUnknown}
- unknownLabel={tChat('heteroAgent.executionTarget.presenceChecking')}
- />
- }
- onClick={() => void select('device', device.deviceId)}
- />,
- 'device',
- device.deviceId,
- ),
- )}
+ {localAvailable && machineEntities('local')}
+ {deviceRows.map((device) => (
+ <Fragment key={device.deviceId}>{machineEntities('device', device)}</Fragment>
+ ))}
</div>
+ {showRepositories && canManage && (
+ <OptionRow
+ compact
+ icon={<Icon icon={PlusIcon} size={16} />}
+ label={t('settings.addDirectory')}
+ onClick={() => addDirectory('device')}
+ />
+ )}
</>
)}
</Flexbox>
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
index 35b8260ea24..bc371719ea4 100644
--- a/src/services/projectWorkingDirectory.ts
+++ b/src/services/projectWorkingDirectory.ts
@@ -21,6 +21,12 @@ class ProjectWorkingDirectoryService {
bind = (input: BindProjectDirectoryInput) =>
lambdaClient.projectWorkingDirectory.bind.mutate(input);
list = (projectId?: string) => lambdaClient.projectWorkingDirectory.list.query({ projectId });
+
+ executionOrder = (projectId: string) =>
+ lambdaClient.projectWorkingDirectory.executionOrder.query({ projectId });
+
+ reorderExecutionEnvironments = (input: { order: string[]; projectId: string }) =>
+ lambdaClient.projectWorkingDirectory.reorderExecutionEnvironments.mutate(input);
listTopics = (id: string) => lambdaClient.projectWorkingDirectory.listTopics.query({ id });
listEnvironmentTopics = async (directoryIds: string[]) => {
const responses = await Promise.all(directoryIds.map((id) => this.listTopics(id)));
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.newTopicRefresh.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.newTopicRefresh.test.ts
new file mode 100644
index 00000000000..c8eebb56a4b
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.newTopicRefresh.test.ts
@@ -0,0 +1,259 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConstVersion from '@/const/version';
+import { aiAgentService } from '@/services/aiAgent';
+
+import type { GatewayConnection } from '../transports/gateway/gateway';
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: {
+ execAgentTask: vi.fn(),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/shareChat', () => ({
+ shareChatService: {
+ execAgentTask: vi.fn(),
+ getTopics: vi.fn().mockResolvedValue([]),
+ interruptTask: vi.fn(),
+ refreshGatewayToken: vi.fn(),
+ },
+}));
+
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: {
+ // Defaults to "no detail readable" so the silent-end reconcile stays
+ // fail-safe unless a test opts in by returning a row.
+ getTopicDetail: vi.fn().mockResolvedValue(null),
+ settleRunningOperation: vi.fn().mockResolvedValue(undefined),
+ updateTopicMetadata: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const moveChatComposerAttachments = vi.hoisted(() => vi.fn());
+vi.mock('@/store/file/store', () => ({
+ getFileStoreState: () => ({ moveChatComposerAttachments }),
+}));
+
+const mockUserDefaultConfig = vi.hoisted(() => ({
+ disableGatewayMode: undefined as boolean | undefined,
+}));
+const mockToolInterventionConfig = vi.hoisted(() => ({
+ allowList: [] as string[],
+ approvalMode: 'manual' as 'allow-list' | 'auto-run' | 'manual',
+}));
+const mockUserState = vi.hoisted(() => ({
+ profile: { id: 'user-1' },
+ workspaceUserPreference: { agentDeviceOverrides: {} as Record<string, any> },
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: {
+ getState: vi.fn(() => mockUserState),
+ },
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ settingsSelectors: {
+ defaultAgentConfig: () => ({
+ chatConfig: { disableGatewayMode: mockUserDefaultConfig.disableGatewayMode },
+ }),
+ },
+ toolInterventionSelectors: {
+ allowList: () => mockToolInterventionConfig.allowList,
+ approvalMode: () => mockToolInterventionConfig.approvalMode,
+ },
+ userProfileSelectors: {
+ userId: (state: typeof mockUserState) => state.profile.id,
+ },
+}));
+
+// ─── Local-device activation (本机) test seams ───
+// Controlled per-test; default off so the rest of the suite runs as web (no
+// device resolution, no electron IPC).
+const mockEnv = vi.hoisted(() => ({ isDesktop: false }));
+const mockGateway = vi.hoisted(() => ({ getDeviceInfo: vi.fn() }));
+// Effective runtime mode === 'local' (what isLocalSystemEnabledById returns)
+// and chat mode (what isChatModeById returns).
+const mockRuntime = vi.hoisted(() => ({ isChatMode: false, isLocal: false }));
+const mockAgentStore = vi.hoisted(() => ({
+ state: { activeAgentId: undefined, agentMap: {} } as any,
+}));
+
+vi.mock('@/const/version', async (importOriginal) => {
+ const actual = await importOriginal<typeof ConstVersion>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockEnv.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: mockGateway.getDeviceInfo },
+}));
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mockAgentStore.state }));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.agencyConfig,
+ getAgentModelById: (agentId: string) => (state: any) => state.agentMap?.[agentId]?.model ?? '',
+ getAgentById: (agentId: string) => (state: any) => state.agentMap?.[agentId],
+ },
+ agentSelectors: { currentAgentWorkingDirectory: () => () => undefined },
+ chatConfigByIdSelectors: {
+ getChatConfigById: (agentId: string) => (state: any) =>
+ state.agentMap?.[agentId]?.chatConfig ?? {},
+ isChatModeById: () => () => mockRuntime.isChatMode,
+ isLocalSystemEnabledById: () => () => mockRuntime.isLocal,
+ },
+}));
+
+// ─── Mock Client Factory ───
+
+function createMockClient(): GatewayConnection['client'] & {
+ emitEvent: (event: string, ...args: any[]) => void;
+} {
+ const listeners = new Map<string, Set<(...args: any[]) => void>>();
+
+ return {
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ emitEvent(event: string, ...args: any[]) {
+ listeners.get(event)?.forEach((listener) => listener(...args));
+ },
+ on: vi.fn((event: string, listener: (...args: any[]) => void) => {
+ let set = listeners.get(event);
+ if (!set) {
+ set = new Set();
+ listeners.set(event, set);
+ }
+ set.add(listener);
+ }),
+ reconnect: vi.fn(async () => {}),
+ sendToolResult: vi.fn(() => true),
+ updateToken: vi.fn(),
+ };
+}
+
+describe('GatewayActionImpl new topic refresh', () => {
+ function createExecuteTestAction() {
+ const mockClient = createMockClient();
+ const moveQueuedMessages = vi.fn();
+ const moveVoiceMessages = vi.fn();
+ const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };
+ const associateMessageWithOperation = vi.fn();
+ const connectToGateway = vi.fn();
+ const internalDispatchTopic = vi.fn();
+ const internalReplaceTopicId = vi.fn();
+ const onOperationCancel = vi.fn();
+ const replaceMessages = vi.fn();
+ const refreshTopic = vi.fn().mockResolvedValue(undefined);
+ const refreshTopicDetail = vi.fn().mockResolvedValue(undefined);
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));
+ const switchTopic = vi.fn();
+ const updateTopicStatus = vi.fn();
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') {
+ Object.assign(state, updater(state));
+ } else {
+ Object.assign(state, updater);
+ }
+ });
+
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation,
+ connectToGateway,
+ internal_dispatchTopic: internalDispatchTopic,
+ internal_replaceTopicId: internalReplaceTopicId,
+ moveQueuedMessages,
+ moveVoiceMessages,
+ onOperationCancel,
+ replaceMessages,
+ refreshTopic,
+ refreshTopicDetail,
+ startOperation,
+ switchTopic,
+ updateTopicStatus,
+ })) as any;
+
+ // Set up window.global_serverConfigStore
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({
+ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' },
+ }),
+ },
+ };
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => mockClient);
+
+ return {
+ action,
+ associateMessageWithOperation,
+ connectToGateway,
+ get,
+ internalDispatchTopic,
+ internalReplaceTopicId,
+ mockClient,
+ moveQueuedMessages,
+ moveVoiceMessages,
+ onOperationCancel,
+ replaceMessages,
+ refreshTopic,
+ refreshTopicDetail,
+ set,
+ startOperation,
+ state,
+ switchTopic,
+ updateTopicStatus,
+ };
+ }
+
+ afterEach(() => {
+ delete (globalThis as any).window;
+ });
+
+ // A project home is not the agent's page: refreshing the active bucket left
+ // the new row without the environment the server applied until a reload.
+ it("refreshes the new topic's own list, not the page's, after the server creates it", async () => {
+ const { action, refreshTopic, state } = createExecuteTestAction();
+ state.activeAgentId = 'page-agent';
+
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-created',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', threadId: null, topicId: null },
+ message: 'Hello',
+ });
+
+ expect(refreshTopic).toHaveBeenCalledWith('agent_agent-1');
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 54e36f3065b..ee44725d2cc 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1334,15 +1334,15 @@ export class GatewayActionImpl {
topicId: result.topicId,
});
- // Refresh the topic list so the new topic appears in topicDataMap (sidebar).
- // Unlike the direct-API sendMessage path (which receives topics[] in the
- // response and calls internal_updateTopics), the gateway path only gets a
- // topicId — we must explicitly refetch so the sidebar shows the new topic.
- // Share visitors have no owner topic sidebar — their list refreshes via
- // the share feature's own SWR hook, and refreshTopic is owner-scoped.
+ // The gateway only returns a topicId: refetch the topic's OWN bucket (not the
+ // page's, which differs on a project home) for the row and what only the
+ // server adds, such as the project environment. Share visitors have no
+ // owner topic sidebar; refreshTopic is owner-scoped.
if (!agentShareId)
topicRefresh = this.#get()
- .refreshTopic()
+ .refreshTopic(
+ topicMapKey({ agentId: messageContext.agentId, groupId: messageContext.groupId }),
+ )
.catch((err) =>
console.error('[Gateway] refreshTopic after topic creation failed:', err),
);