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: add home usage widget slot and refine execution target (#18791)

Rdmclin2893327044a35
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index a5d08b91383..377857e0112 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -302,7 +302,11 @@ describe('AiAgentService.execAgent - model/provider override', () => {
expect(callArgs.agentConfig.chatConfig.enableAgentMode).toBe(false);
});
- it('ignores member overrides for the Agent author and uses the shared model and target', async () => {
+ // Model / mode overrides stay member-only, but the caller's own DEVICE
+ // override applies to the author too: a `local` pick binds their personal
+ // desktop, which the shared row must never reference (the server rejects
+ // it), so the author's pick lives in the same override slot members use.
+ it("ignores member model/mode overrides for the Agent author but applies the author's own device override", async () => {
mockGetAgentConfig.mockResolvedValue({
...defaultAgentConfig,
agencyConfig: {
@@ -330,7 +334,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.agentConfig).toMatchObject({
- agencyConfig: { executionTarget: 'sandbox' },
+ agencyConfig: { boundDeviceId: 'member-device', executionTarget: 'local' },
chatConfig: { enableAgentMode: true },
model: 'gpt-4',
provider: 'openai',
@@ -418,11 +422,11 @@ describe('AiAgentService.execAgent - model/provider override', () => {
expect(callArgs.agentConfig.provider).toBe('openai');
});
- it('ignores member device policy and overrides while the workspace Agent is private', async () => {
+ it("applies the owner's own device override while the workspace Agent is private, stripping the policy", async () => {
mockGetAgentConfig.mockResolvedValue({
...defaultAgentConfig,
agencyConfig: {
- boundDeviceId: 'owner-device',
+ boundDeviceId: 'shared-device',
executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
},
@@ -430,7 +434,7 @@ describe('AiAgentService.execAgent - model/provider override', () => {
});
mockGetPreference.mockResolvedValue({
agentDeviceOverrides: {
- 'agent-1': { boundDeviceId: 'stale-member-device', executionTarget: 'local' },
+ 'agent-1': { boundDeviceId: 'owner-desktop', executionTarget: 'local' },
},
});
service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
@@ -439,8 +443,8 @@ describe('AiAgentService.execAgent - model/provider override', () => {
const callArgs = mockCreateOperation.mock.calls[0][0];
expect(callArgs.agentConfig.agencyConfig).toEqual({
- boundDeviceId: 'owner-device',
- executionTarget: 'device',
+ boundDeviceId: 'owner-desktop',
+ executionTarget: 'local',
});
});
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index 3df2a52b3e1..325daee776c 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "عرض حصة Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} مكتسب إجمالاً",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} مكتسب إجمالاً",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "تلقائي",
"heteroAgent.executionTarget.autoDesc": "استخدام جهاز متصل تلقائيًا، واختيار واحد عند توفر عدة أجهزة",
"heteroAgent.executionTarget.downloadDesktop": "احصل على تطبيق سطح المكتب",
@@ -1633,7 +1632,8 @@
"textSelection.added": "تمت الإضافة إلى سياق المحادثة",
"textSelection.title": "اختيار الرسالة",
"thread.closeSubagentThread": "طي محادثة الوكيل الفرعي",
- "thread.divider": "موضوع فرعي",
+ "thread.dividerContinuation": "تم التشعب هنا، مع وراثة سياق الدردشة الرئيسي حتى الآن",
+ "thread.dividerStandalone": "تم التشعب هنا، مع وراثة الرسالة أعلاه فقط",
"thread.openSubagentThread": "عرض محادثة الوكيل الفرعي كاملة",
"thread.subagentMetrics.modelLabel": "النموذج",
"thread.subagentMetrics.tokens": "{{count}} رمز",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "فشل التحميل",
"upload.preview.status.pending": "جارٍ التحضير للرفع...",
"upload.preview.status.processing": "جارٍ معالجة الملف...",
+ "upload.validation.mediaNotSupported": "النموذج الحالي لا يمكنه قراءة ملفات الوسائط هذه، لذلك لم يتم إضافتها: {{files}}. قم بالتبديل إلى نموذج يدعمها، أو قم بتحميل نوع ملف مختلف.",
"upload.validation.unsupportedFileType": "نوع الملف غير مدعوم: {{files}}. الصور المدعومة: JPG، PNG، GIF، WebP. المستندات المدعومة تشمل PDF، Word، Excel، PowerPoint، Markdown، النص، CSV، JSON، وملفات التعليمات البرمجية.",
"upload.validation.videoSizeExceeded": "يجب ألا يتجاوز حجم ملف الفيديو {{maxSize}}. الحجم الحالي هو {{actualSize}}.",
"verifyConfig.addCriterion": "إضافة معيار",
diff --git a/locales/ar/home.json b/locales/ar/home.json
index e7339c54ad3..4cc88b6b105 100644
--- a/locales/ar/home.json
+++ b/locales/ar/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "الاقتراحات",
"dashboard.customize.widget.tasks": "المهام",
"dashboard.customize.widget.unread": "غير مقروء",
+ "dashboard.customize.widget.usage": "الاستخدام",
"dashboard.empty.plan.description": "قسّم النتيجة إلى خطوات واضحة",
"dashboard.empty.plan.prompt": "ساعدني في إنشاء خطة عملية لـ:",
"dashboard.empty.plan.title": "ضع خطة",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "رد للمتابعة في هذه المحادثة...",
"inbox.unread.title": "غير مقروء",
"inbox.unread.viewChat": "عرض المحادثة",
+ "inbox.usage.title": "الاستخدام",
"project.create": "مشروع جديد",
"project.deleteConfirm": "سيتم حذف هذا المشروع ولن يمكن استعادته. أكد للمتابعة.",
"recommendations.heteroAgent.cta": "أضف الوكيل",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 7ef938a961d..df6943b8cc3 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Преглед на квотата за Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} спечелен общо",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} спечелени общо",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Автоматично",
"heteroAgent.executionTarget.autoDesc": "Автоматично използване на онлайн устройство, избирайки едно, когато има няколко налични",
"heteroAgent.executionTarget.downloadDesktop": "Изтеглете десктоп приложението",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Добавено към контекста на разговора",
"textSelection.title": "Избор на съобщение",
"thread.closeSubagentThread": "Свиване на разговора със субагента",
- "thread.divider": "Подтема",
+ "thread.dividerContinuation": "Разклонено тук, наследявайки основния контекст на чата досега",
+ "thread.dividerStandalone": "Разклонено тук, наследявайки само горното съобщение",
"thread.openSubagentThread": "Преглед на пълния разговор със субагента",
"thread.subagentMetrics.modelLabel": "Модел",
"thread.subagentMetrics.tokens": "{{count}} токени",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Качването не бе успешно",
"upload.preview.status.pending": "Подготовка за качване...",
"upload.preview.status.processing": "Обработка на файла...",
+ "upload.validation.mediaNotSupported": "Текущият модел не може да чете тези медийни файлове, затова те не бяха добавени: {{files}}. Превключете към модел, който ги поддържа, или качете друг тип файл.",
"upload.validation.unsupportedFileType": "Неподдържан тип файл: {{files}}. Поддържани изображения: JPG, PNG, GIF, WebP. Поддържани документи включват PDF, Word, Excel, PowerPoint, Markdown, текст, CSV, JSON и файлове с код.",
"upload.validation.videoSizeExceeded": "Размерът на видеофайла не трябва да надвишава {{maxSize}}. Текущият размер е {{actualSize}}.",
"verifyConfig.addCriterion": "Добавяне на критерий",
diff --git a/locales/bg-BG/home.json b/locales/bg-BG/home.json
index 5e4e70033c0..287dd54698f 100644
--- a/locales/bg-BG/home.json
+++ b/locales/bg-BG/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Предложения",
"dashboard.customize.widget.tasks": "Задачи",
"dashboard.customize.widget.unread": "Непрочетени",
+ "dashboard.customize.widget.usage": "Използване",
"dashboard.empty.plan.description": "Разделете резултата на ясни следващи стъпки",
"dashboard.empty.plan.prompt": "Помогнете ми да създам практичен план за:",
"dashboard.empty.plan.title": "Създайте план",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Отговорете, за да продължите този разговор...",
"inbox.unread.title": "Непрочетено",
"inbox.unread.viewChat": "Преглед на чата",
+ "inbox.usage.title": "Използване",
"project.create": "Нов проект",
"project.deleteConfirm": "Този проект ще бъде изтрит и не може да бъде възстановен. Потвърдете, за да продължите.",
"recommendations.heteroAgent.cta": "Добавяне на агент",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 84f3732b39f..99abab2f914 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Codex-Kontingent anzeigen",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} insgesamt verdient",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} insgesamt verdient",
- "heteroAgent.defaultName": "{{owner}}s {{product}}",
"heteroAgent.executionTarget.auto": "Automatisch",
"heteroAgent.executionTarget.autoDesc": "Automatisch ein Online-Gerät verwenden, wobei eines ausgewählt wird, wenn mehrere verfügbar sind",
"heteroAgent.executionTarget.downloadDesktop": "Desktop-App herunterladen",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Zum Unterhaltungskontext hinzugefügt",
"textSelection.title": "Nachrichtenauswahl",
"thread.closeSubagentThread": "Unteragenten-Unterhaltung einklappen",
- "thread.divider": "Unterthema",
+ "thread.dividerContinuation": "Hier verzweigt, wobei der bisherige Hauptchat-Kontext übernommen wird",
+ "thread.dividerStandalone": "Hier verzweigt, wobei nur die obige Nachricht übernommen wird",
"thread.openSubagentThread": "Komplette Unteragenten-Unterhaltung anzeigen",
"thread.subagentMetrics.modelLabel": "Modell",
"thread.subagentMetrics.tokens": "{{count}} Tokens",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Upload fehlgeschlagen",
"upload.preview.status.pending": "Vorbereitung zum Hochladen...",
"upload.preview.status.processing": "Datei wird verarbeitet...",
+ "upload.validation.mediaNotSupported": "Das aktuelle Modell kann diese Mediendateien nicht lesen, daher wurden sie nicht hinzugefügt: {{files}}. Wechseln Sie zu einem Modell, das sie unterstützt, oder laden Sie eine andere Dateityp hoch.",
"upload.validation.unsupportedFileType": "Nicht unterstützter Dateityp: {{files}}. Unterstützte Bilder: JPG, PNG, GIF, WebP. Unterstützte Dokumente umfassen PDF, Word, Excel, PowerPoint, Markdown, Text, CSV, JSON und Code-Dateien.",
"upload.validation.videoSizeExceeded": "Die Videodatei darf {{maxSize}} nicht überschreiten. Aktuelle Größe: {{actualSize}}.",
"verifyConfig.addCriterion": "Kriterium hinzufügen",
diff --git a/locales/de-DE/home.json b/locales/de-DE/home.json
index 0396417b1e5..398297398da 100644
--- a/locales/de-DE/home.json
+++ b/locales/de-DE/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Vorschläge",
"dashboard.customize.widget.tasks": "Aufgaben",
"dashboard.customize.widget.unread": "Ungelesen",
+ "dashboard.customize.widget.usage": "Nutzung",
"dashboard.empty.plan.description": "Teilen Sie ein Ergebnis in klare nächste Schritte auf",
"dashboard.empty.plan.prompt": "Hilf mir, einen praktischen Plan zu erstellen für:",
"dashboard.empty.plan.title": "Einen Plan erstellen",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Antworten, um diesen Vorgang fortzusetzen…",
"inbox.unread.title": "Ungelesen",
"inbox.unread.viewChat": "Chat anzeigen",
+ "inbox.usage.title": "Nutzung",
"project.create": "Neues Projekt",
"project.deleteConfirm": "Dieses Projekt wird gelöscht und kann nicht wiederhergestellt werden. Bestätigen Sie, um fortzufahren.",
"recommendations.heteroAgent.cta": "Agent hinzufügen",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index aab2ccf05af..64a39d6e77c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1885,6 +1885,7 @@
"upload.preview.status.error": "Upload failed",
"upload.preview.status.pending": "Preparing to upload...",
"upload.preview.status.processing": "Processing file...",
+ "upload.validation.mediaNotSupported": "The current model cannot read these media files, so they were not added: {{files}}. Switch to a model that supports them, or upload a different file type.",
"upload.validation.unsupportedFileType": "Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.",
"upload.validation.videoSizeExceeded": "Video file size must not exceed {{maxSize}}. Current file size is {{actualSize}}.",
"verifyConfig.addCriterion": "Add criterion",
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index c9b27fcd154..979fa33521b 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Suggestions",
"dashboard.customize.widget.tasks": "Recent tasks",
"dashboard.customize.widget.unread": "Unread",
+ "dashboard.customize.widget.usage": "Usage",
"dashboard.empty.plan.description": "Break an outcome into clear next steps",
"dashboard.empty.plan.prompt": "Help me create a practical plan for:",
"dashboard.empty.plan.title": "Make a plan",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Reply to continue this run…",
"inbox.unread.title": "Unread",
"inbox.unread.viewChat": "View chat",
+ "inbox.usage.title": "Usage",
"project.create": "New project",
"project.deleteConfirm": "This project will be deleted and can't be recovered. Confirm to continue.",
"recommendations.heteroAgent.cta": "Add Agent",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 9a15d18ee3c..b4d983bc1d3 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Ver cuota de Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} ganado en total",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} ganados en total",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Automático",
"heteroAgent.executionTarget.autoDesc": "Usar un dispositivo en línea automáticamente, eligiendo uno cuando haya varios disponibles",
"heteroAgent.executionTarget.downloadDesktop": "Obtener la aplicación de escritorio",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Agregado al contexto de la conversación",
"textSelection.title": "Selección de mensaje",
"thread.closeSubagentThread": "Contraer conversación del subagente",
- "thread.divider": "Subtema",
+ "thread.dividerContinuation": "Dividido aquí, heredando el contexto principal del chat hasta ahora",
+ "thread.dividerStandalone": "Dividido aquí, heredando solo el mensaje anterior",
"thread.openSubagentThread": "Ver conversación completa del subagente",
"thread.subagentMetrics.modelLabel": "Modelo",
"thread.subagentMetrics.tokens": "{{count}} tokens",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "La carga falló",
"upload.preview.status.pending": "Preparando para subir...",
"upload.preview.status.processing": "Procesando archivo...",
+ "upload.validation.mediaNotSupported": "El modelo actual no puede leer estos archivos multimedia, por lo que no se añadieron: {{files}}. Cambia a un modelo que los soporte o sube un tipo de archivo diferente.",
"upload.validation.unsupportedFileType": "Tipo de archivo no compatible: {{files}}. Imágenes compatibles: JPG, PNG, GIF, WebP. Documentos compatibles incluyen PDF, Word, Excel, PowerPoint, Markdown, texto, CSV, JSON y archivos de código.",
"upload.validation.videoSizeExceeded": "El tamaño del archivo de video no debe superar los {{maxSize}}. Tamaño actual: {{actualSize}}.",
"verifyConfig.addCriterion": "Agregar criterio",
diff --git a/locales/es-ES/home.json b/locales/es-ES/home.json
index 0a6178e218c..d71090066d4 100644
--- a/locales/es-ES/home.json
+++ b/locales/es-ES/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Sugerencias",
"dashboard.customize.widget.tasks": "Tareas",
"dashboard.customize.widget.unread": "No leído",
+ "dashboard.customize.widget.usage": "Uso",
"dashboard.empty.plan.description": "Divide un resultado en pasos claros",
"dashboard.empty.plan.prompt": "Ayúdame a crear un plan práctico para:",
"dashboard.empty.plan.title": "Crear un plan",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Responde para continuar con esta conversación…",
"inbox.unread.title": "Sin leer",
"inbox.unread.viewChat": "Ver chat",
+ "inbox.usage.title": "Uso",
"project.create": "Nuevo proyecto",
"project.deleteConfirm": "Este proyecto se eliminará y no se podrá recuperar. Confirma para continuar.",
"recommendations.heteroAgent.cta": "Agregar agente",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index c951cdcb4e1..fc175f36608 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "مشاهده سهمیه Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} در مجموع کسب شده",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} در مجموع کسب شده",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "خودکار",
"heteroAgent.executionTarget.autoDesc": "به طور خودکار از یک دستگاه آنلاین استفاده کنید و یکی را در صورت موجود بودن چندین دستگاه انتخاب کنید",
"heteroAgent.executionTarget.downloadDesktop": "دریافت اپلیکیشن دسکتاپ",
@@ -1633,7 +1632,8 @@
"textSelection.added": "به زمینه مکالمه اضافه شد",
"textSelection.title": "انتخاب پیام",
"thread.closeSubagentThread": "بستن گفتگوی عامل فرعی",
- "thread.divider": "زیرموضوع",
+ "thread.dividerContinuation": "اینجا منشعب شده است و زمینه اصلی گفتگو تا اینجا به ارث برده شده است",
+ "thread.dividerStandalone": "اینجا منشعب شده است و فقط پیام بالا به ارث برده شده است",
"thread.openSubagentThread": "مشاهده کامل گفتگوی عامل فرعی",
"thread.subagentMetrics.modelLabel": "مدل",
"thread.subagentMetrics.tokens": "{{count}} توکن",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "بارگذاری ناموفق بود",
"upload.preview.status.pending": "در حال آماده‌سازی برای بارگذاری...",
"upload.preview.status.processing": "در حال پردازش فایل...",
+ "upload.validation.mediaNotSupported": "مدل فعلی نمی‌تواند این فایل‌های رسانه‌ای را بخواند، بنابراین آنها اضافه نشدند: {{files}}. به مدلی که از آنها پشتیبانی می‌کند تغییر دهید یا نوع فایل دیگری را بارگذاری کنید.",
"upload.validation.unsupportedFileType": "نوع فایل پشتیبانی نشده: {{files}}. تصاویر پشتیبانی شده: JPG، PNG، GIF، WebP. اسناد پشتیبانی شده شامل PDF، Word، Excel، PowerPoint، Markdown، متن، CSV، JSON و فایل‌های کد هستند.",
"upload.validation.videoSizeExceeded": "حجم فایل ویدیو نباید بیش از {{maxSize}} باشد. حجم فعلی: {{actualSize}}.",
"verifyConfig.addCriterion": "افزودن معیار",
diff --git a/locales/fa-IR/home.json b/locales/fa-IR/home.json
index d9500eae0c5..fd0c346f300 100644
--- a/locales/fa-IR/home.json
+++ b/locales/fa-IR/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "پیشنهادات",
"dashboard.customize.widget.tasks": "وظایف",
"dashboard.customize.widget.unread": "خوانده‌نشده",
+ "dashboard.customize.widget.usage": "استفاده",
"dashboard.empty.plan.description": "یک نتیجه را به مراحل واضح بعدی تقسیم کنید",
"dashboard.empty.plan.prompt": "به من کمک کنید یک برنامه عملی برای این موضوع ایجاد کنم:",
"dashboard.empty.plan.title": "یک برنامه بسازید",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "پاسخ دهید تا این مکالمه ادامه یابد…",
"inbox.unread.title": "خوانده نشده",
"inbox.unread.viewChat": "مشاهده چت",
+ "inbox.usage.title": "استفاده",
"project.create": "پروژه جدید",
"project.deleteConfirm": "این پروژه حذف خواهد شد و امکان بازیابی آن وجود ندارد. برای ادامه تأیید کنید.",
"recommendations.heteroAgent.cta": "افزودن عامل",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index a43b3969a6a..53237955489 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Voir le quota Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} gagné au total",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} gagnés au total",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Auto",
"heteroAgent.executionTarget.autoDesc": "Utiliser automatiquement un appareil en ligne, en choisissant un lorsqu'il y en a plusieurs disponibles",
"heteroAgent.executionTarget.downloadDesktop": "Obtenir l'application de bureau",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Ajouté au contexte de la conversation",
"textSelection.title": "Sélection de message",
"thread.closeSubagentThread": "Réduire la conversation du sous-agent",
- "thread.divider": "Sous-sujet",
+ "thread.dividerContinuation": "Divisé ici, en héritant du contexte principal du chat jusqu'à présent",
+ "thread.dividerStandalone": "Divisé ici, en héritant uniquement du message ci-dessus",
"thread.openSubagentThread": "Afficher la conversation complète du sous-agent",
"thread.subagentMetrics.modelLabel": "Modèle",
"thread.subagentMetrics.tokens": "{{count}} jetons",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Échec du téléchargement",
"upload.preview.status.pending": "Préparation au téléversement...",
"upload.preview.status.processing": "Traitement du fichier...",
+ "upload.validation.mediaNotSupported": "Le modèle actuel ne peut pas lire ces fichiers multimédias, ils n'ont donc pas été ajoutés : {{files}}. Passez à un modèle qui les prend en charge ou téléchargez un autre type de fichier.",
"upload.validation.unsupportedFileType": "Type de fichier non pris en charge : {{files}}. Images prises en charge : JPG, PNG, GIF, WebP. Les documents pris en charge incluent PDF, Word, Excel, PowerPoint, Markdown, texte, CSV, JSON et fichiers de code.",
"upload.validation.videoSizeExceeded": "La taille du fichier vidéo ne doit pas dépasser {{maxSize}}. Taille actuelle : {{actualSize}}.",
"verifyConfig.addCriterion": "Ajouter un critère",
diff --git a/locales/fr-FR/home.json b/locales/fr-FR/home.json
index 4df22e04449..8ba8e259c87 100644
--- a/locales/fr-FR/home.json
+++ b/locales/fr-FR/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Suggestions",
"dashboard.customize.widget.tasks": "Tâches",
"dashboard.customize.widget.unread": "Non lus",
+ "dashboard.customize.widget.usage": "Utilisation",
"dashboard.empty.plan.description": "Divisez un objectif en étapes claires",
"dashboard.empty.plan.prompt": "Aidez-moi à créer un plan pratique pour :",
"dashboard.empty.plan.title": "Élaborer un plan",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Répondez pour continuer cette conversation…",
"inbox.unread.title": "Non lu",
"inbox.unread.viewChat": "Voir la discussion",
+ "inbox.usage.title": "Utilisation",
"project.create": "Nouveau projet",
"project.deleteConfirm": "Ce projet sera supprimé et ne pourra pas être récupéré. Confirmez pour continuer.",
"recommendations.heteroAgent.cta": "Ajouter un agent",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 2b793b035c9..ba3f12870ad 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Visualizza la quota di Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} guadagnato in totale",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} guadagnati in totale",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Automatico",
"heteroAgent.executionTarget.autoDesc": "Usa automaticamente un dispositivo online, scegliendone uno quando ce ne sono diversi disponibili",
"heteroAgent.executionTarget.downloadDesktop": "Scarica l'App Desktop",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Aggiunto al contesto della conversazione",
"textSelection.title": "Selezione del messaggio",
"thread.closeSubagentThread": "Comprimi conversazione subagente",
- "thread.divider": "Sottotema",
+ "thread.dividerContinuation": "Derivato qui, ereditando il contesto principale della chat fino ad ora",
+ "thread.dividerStandalone": "Derivato qui, ereditando solo il messaggio sopra",
"thread.openSubagentThread": "Mostra conversazione completa del subagente",
"thread.subagentMetrics.modelLabel": "Modello",
"thread.subagentMetrics.tokens": "{{count}} token",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Caricamento fallito",
"upload.preview.status.pending": "Preparazione al caricamento...",
"upload.preview.status.processing": "Elaborazione file...",
+ "upload.validation.mediaNotSupported": "Il modello attuale non può leggere questi file multimediali, quindi non sono stati aggiunti: {{files}}. Passa a un modello che li supporta o carica un tipo di file diverso.",
"upload.validation.unsupportedFileType": "Tipo di file non supportato: {{files}}. Immagini supportate: JPG, PNG, GIF, WebP. Documenti supportati includono PDF, Word, Excel, PowerPoint, Markdown, testo, CSV, JSON e file di codice.",
"upload.validation.videoSizeExceeded": "La dimensione del file video non deve superare i {{maxSize}}. Dimensione attuale: {{actualSize}}.",
"verifyConfig.addCriterion": "Aggiungi criterio",
diff --git a/locales/it-IT/home.json b/locales/it-IT/home.json
index d01243e5c7b..1087bc42fae 100644
--- a/locales/it-IT/home.json
+++ b/locales/it-IT/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Suggerimenti",
"dashboard.customize.widget.tasks": "Attività",
"dashboard.customize.widget.unread": "Non letti",
+ "dashboard.customize.widget.usage": "Utilizzo",
"dashboard.empty.plan.description": "Scomponi un obiettivo in passaggi chiari",
"dashboard.empty.plan.prompt": "Aiutami a creare un piano pratico per:",
"dashboard.empty.plan.title": "Crea un piano",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Rispondi per continuare questa conversazione…",
"inbox.unread.title": "Non letti",
"inbox.unread.viewChat": "Visualizza chat",
+ "inbox.usage.title": "Utilizzo",
"project.create": "Nuovo progetto",
"project.deleteConfirm": "Questo progetto verrà eliminato e non potrà essere recuperato. Conferma per continuare.",
"recommendations.heteroAgent.cta": "Aggiungi Agente",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index 31ed5420790..f8d60e2421f 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Codexのクォータを表示",
"heteroAgent.codexQuota.totalEarned_one": "合計で{{count}}獲得",
"heteroAgent.codexQuota.totalEarned_other": "合計で{{count}}獲得",
- "heteroAgent.defaultName": "{{owner}}の{{product}}",
"heteroAgent.executionTarget.auto": "自動",
"heteroAgent.executionTarget.autoDesc": "複数のオンラインデバイスが利用可能な場合、自動的に選択して使用",
"heteroAgent.executionTarget.downloadDesktop": "デスクトップアプリを取得",
@@ -1633,7 +1632,8 @@
"textSelection.added": "会話コンテキストに追加されました",
"textSelection.title": "メッセージ選択",
"thread.closeSubagentThread": "サブエージェント会話を折りたたむ",
- "thread.divider": "サブトピック",
+ "thread.dividerContinuation": "ここで分岐しました。これまでのメインチャットコンテキストを継承しています。",
+ "thread.dividerStandalone": "ここで分岐しました。上記のメッセージのみを継承しています。",
"thread.openSubagentThread": "サブエージェント会話をすべて表示",
"thread.subagentMetrics.modelLabel": "モデル",
"thread.subagentMetrics.tokens": "{{count}} トークン",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "アップロードに失敗しました",
"upload.preview.status.pending": "アップロードの準備中…",
"upload.preview.status.processing": "ファイル処理中…",
+ "upload.validation.mediaNotSupported": "現在のモデルはこれらのメディアファイルを読み取ることができないため、追加されませんでした: {{files}}。対応するモデルに切り替えるか、別のファイル形式をアップロードしてください。",
"upload.validation.unsupportedFileType": "サポートされていないファイルタイプ: {{files}}。サポートされている画像形式: JPG、PNG、GIF、WebP。サポートされているドキュメント形式: PDF、Word、Excel、PowerPoint、Markdown、テキスト、CSV、JSON、コードファイル。",
"upload.validation.videoSizeExceeded": "ビデオファイルは {{maxSize}} を超えることはできません。現在は {{actualSize}} です",
"verifyConfig.addCriterion": "基準を追加",
diff --git a/locales/ja-JP/home.json b/locales/ja-JP/home.json
index e533c96239e..d133a79f564 100644
--- a/locales/ja-JP/home.json
+++ b/locales/ja-JP/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "提案",
"dashboard.customize.widget.tasks": "タスク",
"dashboard.customize.widget.unread": "未読",
+ "dashboard.customize.widget.usage": "使用状況",
"dashboard.empty.plan.description": "成果を明確な次のステップに分解する",
"dashboard.empty.plan.prompt": "実用的な計画を作成する手助けをしてください:",
"dashboard.empty.plan.title": "計画を立てる",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "返信してこのランを続行してください…",
"inbox.unread.title": "未読",
"inbox.unread.viewChat": "チャットを見る",
+ "inbox.usage.title": "使用状況",
"project.create": "新しいプロジェクトを作成",
"project.deleteConfirm": "このプロジェクトは削除され、復元できません。続行するには確認してください。",
"recommendations.heteroAgent.cta": "エージェントを追加",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index c980fc9fb80..1e3bc57d092 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Codex 할당량 보기",
"heteroAgent.codexQuota.totalEarned_one": "총 {{count}} 획득",
"heteroAgent.codexQuota.totalEarned_other": "총 {{count}} 획득",
- "heteroAgent.defaultName": "{{owner}}의 {{product}}",
"heteroAgent.executionTarget.auto": "자동",
"heteroAgent.executionTarget.autoDesc": "온라인 장치를 자동으로 사용하며, 여러 장치가 있을 경우 하나를 선택합니다",
"heteroAgent.executionTarget.downloadDesktop": "데스크톱 앱 받기",
@@ -1633,7 +1632,8 @@
"textSelection.added": "대화 컨텍스트에 추가됨",
"textSelection.title": "메시지 선택",
"thread.closeSubagentThread": "하위 에이전트 대화 숨기기",
- "thread.divider": "하위 주제",
+ "thread.dividerContinuation": "여기서 분기되었습니다. 지금까지의 주요 채팅 컨텍스트를 계승합니다.",
+ "thread.dividerStandalone": "여기서 분기되었습니다. 위의 메시지만 계승합니다.",
"thread.openSubagentThread": "전체 하위 에이전트 대화 보기",
"thread.subagentMetrics.modelLabel": "모델",
"thread.subagentMetrics.tokens": "{{count}} 토큰",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "업로드 실패",
"upload.preview.status.pending": "업로드 준비 중…",
"upload.preview.status.processing": "파일 처리 중…",
+ "upload.validation.mediaNotSupported": "현재 모델은 이러한 미디어 파일을 읽을 수 없으므로 추가되지 않았습니다: {{files}}. 지원되는 모델로 전환하거나 다른 파일 유형을 업로드하세요.",
"upload.validation.unsupportedFileType": "지원되지 않는 파일 형식: {{files}}. 지원되는 이미지: JPG, PNG, GIF, WebP. 지원되는 문서: PDF, Word, Excel, PowerPoint, Markdown, 텍스트, CSV, JSON 및 코드 파일.",
"upload.validation.videoSizeExceeded": "비디오 파일은 {{maxSize}}를 초과할 수 없습니다. 현재 {{actualSize}}입니다",
"verifyConfig.addCriterion": "기준 추가",
diff --git a/locales/ko-KR/home.json b/locales/ko-KR/home.json
index 0adb08ed8f4..6ebbb6727a3 100644
--- a/locales/ko-KR/home.json
+++ b/locales/ko-KR/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "제안",
"dashboard.customize.widget.tasks": "작업",
"dashboard.customize.widget.unread": "읽지 않음",
+ "dashboard.customize.widget.usage": "사용량",
"dashboard.empty.plan.description": "결과를 명확한 다음 단계로 나누세요",
"dashboard.empty.plan.prompt": "실용적인 계획을 세우는 데 도움을 주세요:",
"dashboard.empty.plan.title": "계획 세우기",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "이 실행을 계속하려면 답장하세요…",
"inbox.unread.title": "읽지 않음",
"inbox.unread.viewChat": "채팅 보기",
+ "inbox.usage.title": "사용량",
"project.create": "새 프로젝트 만들기",
"project.deleteConfirm": "이 프로젝트는 삭제되며 복구할 수 없습니다. 계속하려면 확인하세요.",
"recommendations.heteroAgent.cta": "에이전트 추가",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 693ce892438..33ec0b7613d 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Bekijk Codex-quota",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} in totaal verdiend",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} in totaal verdiend",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Auto",
"heteroAgent.executionTarget.autoDesc": "Gebruik automatisch een online apparaat, waarbij er één wordt gekozen als er meerdere beschikbaar zijn",
"heteroAgent.executionTarget.downloadDesktop": "Download Desktop App",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Toegevoegd aan gesprekscontext",
"textSelection.title": "Berichtselectie",
"thread.closeSubagentThread": "Subagentgesprek samenvouwen",
- "thread.divider": "Subonderwerp",
+ "thread.dividerContinuation": "Hier vertakt, waarbij de hoofdchatcontext tot nu toe wordt overgenomen",
+ "thread.dividerStandalone": "Hier vertakt, waarbij alleen het bovenstaande bericht wordt overgenomen",
"thread.openSubagentThread": "Volledig subagentgesprek bekijken",
"thread.subagentMetrics.modelLabel": "Model",
"thread.subagentMetrics.tokens": "{{count}} tokens",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Upload mislukt",
"upload.preview.status.pending": "Voorbereiden op upload...",
"upload.preview.status.processing": "Bestand verwerken...",
+ "upload.validation.mediaNotSupported": "Het huidige model kan deze mediabestanden niet lezen, dus ze zijn niet toegevoegd: {{files}}. Schakel over naar een model dat ze ondersteunt, of upload een ander bestandstype.",
"upload.validation.unsupportedFileType": "Niet-ondersteund bestandstype: {{files}}. Ondersteunde afbeeldingen: JPG, PNG, GIF, WebP. Ondersteunde documenten zijn onder andere PDF, Word, Excel, PowerPoint, Markdown, tekst, CSV, JSON en codebestanden.",
"upload.validation.videoSizeExceeded": "De bestandsgrootte van de video mag niet groter zijn dan {{maxSize}}. Huidige grootte is {{actualSize}}.",
"verifyConfig.addCriterion": "Criterium toevoegen",
diff --git a/locales/nl-NL/home.json b/locales/nl-NL/home.json
index f07c0781792..d5e1b661f27 100644
--- a/locales/nl-NL/home.json
+++ b/locales/nl-NL/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Suggesties",
"dashboard.customize.widget.tasks": "Taken",
"dashboard.customize.widget.unread": "Ongelezen",
+ "dashboard.customize.widget.usage": "Gebruik",
"dashboard.empty.plan.description": "Splits een resultaat op in duidelijke volgende stappen",
"dashboard.empty.plan.prompt": "Help me een praktisch plan te maken voor:",
"dashboard.empty.plan.title": "Maak een plan",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Antwoord om deze sessie voort te zetten…",
"inbox.unread.title": "Ongelezen",
"inbox.unread.viewChat": "Bekijk chat",
+ "inbox.usage.title": "Gebruik",
"project.create": "Nieuw project",
"project.deleteConfirm": "Dit project wordt verwijderd en kan niet worden hersteld. Bevestig om door te gaan.",
"recommendations.heteroAgent.cta": "Agent toevoegen",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 5288a33a390..3c5dc72fa05 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Zobacz limit Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} zdobyty w sumie",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} zdobytych w sumie",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Automatycznie",
"heteroAgent.executionTarget.autoDesc": "Automatycznie użyj urządzenia online, wybierając jedno, gdy dostępnych jest kilka",
"heteroAgent.executionTarget.downloadDesktop": "Pobierz aplikację na komputer",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Dodano do kontekstu rozmowy",
"textSelection.title": "Wybór wiadomości",
"thread.closeSubagentThread": "Zwiń rozmowę subagenta",
- "thread.divider": "Podtemat",
+ "thread.dividerContinuation": "Rozpoczęto tutaj, dziedzicząc dotychczasowy główny kontekst czatu",
+ "thread.dividerStandalone": "Rozpoczęto tutaj, dziedzicząc tylko powyższą wiadomość",
"thread.openSubagentThread": "Pokaż pełną rozmowę subagenta",
"thread.subagentMetrics.modelLabel": "Model",
"thread.subagentMetrics.tokens": "{{count}} tokenów",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Przesyłanie nie powiodło się",
"upload.preview.status.pending": "Przygotowywanie do przesłania...",
"upload.preview.status.processing": "Przetwarzanie pliku...",
+ "upload.validation.mediaNotSupported": "Obecny model nie może odczytać tych plików multimedialnych, więc nie zostały dodane: {{files}}. Przełącz się na model, który je obsługuje, lub prześlij inny typ pliku.",
"upload.validation.unsupportedFileType": "Nieobsługiwany typ pliku: {{files}}. Obsługiwane obrazy: JPG, PNG, GIF, WebP. Obsługiwane dokumenty obejmują PDF, Word, Excel, PowerPoint, Markdown, tekst, CSV, JSON i pliki kodu.",
"upload.validation.videoSizeExceeded": "Rozmiar pliku wideo nie może przekraczać {{maxSize}}. Obecny rozmiar pliku to {{actualSize}}.",
"verifyConfig.addCriterion": "Dodaj kryterium",
diff --git a/locales/pl-PL/home.json b/locales/pl-PL/home.json
index 1965b4a170b..764e6309fac 100644
--- a/locales/pl-PL/home.json
+++ b/locales/pl-PL/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Sugestie",
"dashboard.customize.widget.tasks": "Zadania",
"dashboard.customize.widget.unread": "Nieprzeczytane",
+ "dashboard.customize.widget.usage": "Użycie",
"dashboard.empty.plan.description": "Podziel wynik na jasne, kolejne kroki",
"dashboard.empty.plan.prompt": "Pomóż mi stworzyć praktyczny plan dla:",
"dashboard.empty.plan.title": "Stwórz plan",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Odpowiedz, aby kontynuować ten wątek…",
"inbox.unread.title": "Nieprzeczytane",
"inbox.unread.viewChat": "Zobacz czat",
+ "inbox.usage.title": "Użycie",
"project.create": "Nowy projekt",
"project.deleteConfirm": "Ten projekt zostanie usunięty i nie będzie można go odzyskać. Potwierdź, aby kontynuować.",
"recommendations.heteroAgent.cta": "Dodaj agenta",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 45ce8ed7cb2..f643e81ae47 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Ver cota do Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} ganho no total",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} ganhos no total",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Automático",
"heteroAgent.executionTarget.autoDesc": "Use um dispositivo online automaticamente, escolhendo um quando vários estiverem disponíveis",
"heteroAgent.executionTarget.downloadDesktop": "Obter Aplicativo para Desktop",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Adicionado ao contexto da conversa",
"textSelection.title": "Seleção de mensagem",
"thread.closeSubagentThread": "Recolher conversa do subagente",
- "thread.divider": "Subtópico",
+ "thread.dividerContinuation": "Ramal iniciado aqui, herdando o contexto principal do chat até agora",
+ "thread.dividerStandalone": "Ramal iniciado aqui, herdando apenas a mensagem acima",
"thread.openSubagentThread": "Ver conversa completa do subagente",
"thread.subagentMetrics.modelLabel": "Modelo",
"thread.subagentMetrics.tokens": "{{count}} tokens",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Falha no upload",
"upload.preview.status.pending": "Preparando para envio...",
"upload.preview.status.processing": "Processando arquivo...",
+ "upload.validation.mediaNotSupported": "O modelo atual não consegue ler esses arquivos de mídia, então eles não foram adicionados: {{files}}. Mude para um modelo que os suporte ou envie um tipo de arquivo diferente.",
"upload.validation.unsupportedFileType": "Tipo de arquivo não suportado: {{files}}. Imagens suportadas: JPG, PNG, GIF, WebP. Documentos suportados incluem PDF, Word, Excel, PowerPoint, Markdown, texto, CSV, JSON e arquivos de código.",
"upload.validation.videoSizeExceeded": "O tamanho do vídeo não deve exceder {{maxSize}}. Tamanho atual: {{actualSize}}.",
"verifyConfig.addCriterion": "Adicionar critério",
diff --git a/locales/pt-BR/home.json b/locales/pt-BR/home.json
index 3e573919324..e055f59eadf 100644
--- a/locales/pt-BR/home.json
+++ b/locales/pt-BR/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Sugestões",
"dashboard.customize.widget.tasks": "Tarefas",
"dashboard.customize.widget.unread": "Não lidos",
+ "dashboard.customize.widget.usage": "Uso",
"dashboard.empty.plan.description": "Divida um objetivo em etapas claras",
"dashboard.empty.plan.prompt": "Ajude-me a criar um plano prático para:",
"dashboard.empty.plan.title": "Crie um plano",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Responda para continuar esta conversa…",
"inbox.unread.title": "Não lido",
"inbox.unread.viewChat": "Ver chat",
+ "inbox.usage.title": "Uso",
"project.create": "Novo projeto",
"project.deleteConfirm": "Este projeto será excluído e não poderá ser recuperado. Confirme para continuar.",
"recommendations.heteroAgent.cta": "Adicionar Agente",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 4c4ee23dfec..6329e93593f 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Просмотреть квоту Codex",
"heteroAgent.codexQuota.totalEarned_one": "Всего заработано: {{count}}",
"heteroAgent.codexQuota.totalEarned_other": "Всего заработано: {{count}}",
- "heteroAgent.defaultName": "{{owner}}'s {{product}}",
"heteroAgent.executionTarget.auto": "Авто",
"heteroAgent.executionTarget.autoDesc": "Автоматически использовать онлайн-устройство, выбирая одно из нескольких доступных",
"heteroAgent.executionTarget.downloadDesktop": "Скачать приложение для компьютера",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Добавлено в контекст беседы",
"textSelection.title": "Выбор сообщения",
"thread.closeSubagentThread": "Свернуть диалог с субагентом",
- "thread.divider": "Подтема",
+ "thread.dividerContinuation": "Разделено здесь, наследуя основной контекст чата до этого момента",
+ "thread.dividerStandalone": "Разделено здесь, наследуя только сообщение выше",
"thread.openSubagentThread": "Показать весь диалог с субагентом",
"thread.subagentMetrics.modelLabel": "Модель",
"thread.subagentMetrics.tokens": "{{count}} токенов",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Ошибка загрузки",
"upload.preview.status.pending": "Подготовка к загрузке...",
"upload.preview.status.processing": "Обработка файла...",
+ "upload.validation.mediaNotSupported": "Текущая модель не может читать эти медиафайлы, поэтому они не были добавлены: {{files}}. Переключитесь на модель, которая поддерживает их, или загрузите файл другого типа.",
"upload.validation.unsupportedFileType": "Неподдерживаемый тип файла: {{files}}. Поддерживаемые изображения: JPG, PNG, GIF, WebP. Поддерживаемые документы: PDF, Word, Excel, PowerPoint, Markdown, текст, CSV, JSON и файлы кода.",
"upload.validation.videoSizeExceeded": "Размер видеофайла не должен превышать {{maxSize}}. Текущий размер: {{actualSize}}.",
"verifyConfig.addCriterion": "Добавить критерий",
diff --git a/locales/ru-RU/home.json b/locales/ru-RU/home.json
index 3aea22a9d36..be0004ec8cf 100644
--- a/locales/ru-RU/home.json
+++ b/locales/ru-RU/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Предложения",
"dashboard.customize.widget.tasks": "Задачи",
"dashboard.customize.widget.unread": "Непрочитанные",
+ "dashboard.customize.widget.usage": "Использование",
"dashboard.empty.plan.description": "Разбейте результат на четкие следующие шаги",
"dashboard.empty.plan.prompt": "Помогите мне создать практический план для:",
"dashboard.empty.plan.title": "Составить план",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Ответьте, чтобы продолжить этот разговор…",
"inbox.unread.title": "Непрочитанные",
"inbox.unread.viewChat": "Просмотреть чат",
+ "inbox.usage.title": "Использование",
"project.create": "Новый проект",
"project.deleteConfirm": "Этот проект будет удален и не может быть восстановлен. Подтвердите, чтобы продолжить.",
"recommendations.heteroAgent.cta": "Добавить агента",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index d60e98297b2..eff6469373a 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Codex kotasını görüntüle",
"heteroAgent.codexQuota.totalEarned_one": "Toplamda {{count}} kazanıldı",
"heteroAgent.codexQuota.totalEarned_other": "Toplamda {{count}} kazanıldı",
- "heteroAgent.defaultName": "{{owner}}'in {{product}}",
"heteroAgent.executionTarget.auto": "Otomatik",
"heteroAgent.executionTarget.autoDesc": "Birden fazla cihaz mevcut olduğunda, otomatik olarak bir çevrimiçi cihaz seçin",
"heteroAgent.executionTarget.downloadDesktop": "Masaüstü Uygulamasını Edinin",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Sohbet bağlamına eklendi",
"textSelection.title": "Mesaj seçimi",
"thread.closeSubagentThread": "Alt ajan konuşmasını daralt",
- "thread.divider": "Alt Konu",
+ "thread.dividerContinuation": "Buradan çatallandı, şu ana kadar ana sohbet bağlamını devralıyor",
+ "thread.dividerStandalone": "Buradan çatallandı, yalnızca yukarıdaki mesajı devralıyor",
"thread.openSubagentThread": "Alt ajan konuşmasının tamamını görüntüle",
"thread.subagentMetrics.modelLabel": "Model",
"thread.subagentMetrics.tokens": "{{count}} token",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Yükleme başarısız oldu",
"upload.preview.status.pending": "Yüklemeye hazırlanıyor...",
"upload.preview.status.processing": "Dosya işleniyor...",
+ "upload.validation.mediaNotSupported": "Mevcut model bu medya dosyalarını okuyamıyor, bu yüzden eklenmedi: {{files}}. Destekleyen bir modele geçin veya farklı bir dosya türü yükleyin.",
"upload.validation.unsupportedFileType": "Desteklenmeyen dosya türü: {{files}}. Desteklenen görseller: JPG, PNG, GIF, WebP. Desteklenen belgeler: PDF, Word, Excel, PowerPoint, Markdown, metin, CSV, JSON ve kod dosyaları.",
"upload.validation.videoSizeExceeded": "Video dosya boyutu {{maxSize}}'ı geçmemelidir. Mevcut dosya boyutu {{actualSize}}.",
"verifyConfig.addCriterion": "Kriter ekle",
diff --git a/locales/tr-TR/home.json b/locales/tr-TR/home.json
index feb8830c5d3..c9bb9c02ae3 100644
--- a/locales/tr-TR/home.json
+++ b/locales/tr-TR/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Öneriler",
"dashboard.customize.widget.tasks": "Görevler",
"dashboard.customize.widget.unread": "Okunmamış",
+ "dashboard.customize.widget.usage": "Kullanım",
"dashboard.empty.plan.description": "Bir sonucu net adımlara ayırın",
"dashboard.empty.plan.prompt": "Bana şu konuda pratik bir plan oluştur: ",
"dashboard.empty.plan.title": "Bir plan yap",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Bu çalışmaya devam etmek için yanıt verin…",
"inbox.unread.title": "Okunmamış",
"inbox.unread.viewChat": "Sohbeti görüntüle",
+ "inbox.usage.title": "Kullanım",
"project.create": "Yeni proje",
"project.deleteConfirm": "Bu proje silinecek ve geri alınamaz. Devam etmek için onaylayın.",
"recommendations.heteroAgent.cta": "Aracı Ekle",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index f8e35fc5b67..661149caed8 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "Xem hạn mức Codex",
"heteroAgent.codexQuota.totalEarned_one": "{{count}} đã kiếm được tổng cộng",
"heteroAgent.codexQuota.totalEarned_other": "{{count}} đã kiếm được tổng cộng",
- "heteroAgent.defaultName": "{{product}} của {{owner}}",
"heteroAgent.executionTarget.auto": "Tự động",
"heteroAgent.executionTarget.autoDesc": "Tự động sử dụng một thiết bị trực tuyến, chọn một thiết bị khi có nhiều thiết bị khả dụng",
"heteroAgent.executionTarget.downloadDesktop": "Tải ứng dụng máy tính",
@@ -1633,7 +1632,8 @@
"textSelection.added": "Đã thêm vào ngữ cảnh cuộc trò chuyện",
"textSelection.title": "Chọn tin nhắn",
"thread.closeSubagentThread": "Thu gọn hội thoại tác tử phụ",
- "thread.divider": "Chủ đề phụ",
+ "thread.dividerContinuation": "Được tách ra tại đây, kế thừa ngữ cảnh chính của cuộc trò chuyện cho đến nay",
+ "thread.dividerStandalone": "Được tách ra tại đây, chỉ kế thừa tin nhắn phía trên",
"thread.openSubagentThread": "Xem toàn bộ hội thoại tác tử phụ",
"thread.subagentMetrics.modelLabel": "Mô hình",
"thread.subagentMetrics.tokens": "{{count}} token",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "Tải lên thất bại",
"upload.preview.status.pending": "Đang chuẩn bị tải lên...",
"upload.preview.status.processing": "Đang xử lý tệp...",
+ "upload.validation.mediaNotSupported": "Mô hình hiện tại không thể đọc các tệp phương tiện này, vì vậy chúng không được thêm vào: {{files}}. Chuyển sang một mô hình hỗ trợ chúng, hoặc tải lên một loại tệp khác.",
"upload.validation.unsupportedFileType": "Loại tệp không được hỗ trợ: {{files}}. Hình ảnh được hỗ trợ: JPG, PNG, GIF, WebP. Các tài liệu được hỗ trợ bao gồm PDF, Word, Excel, PowerPoint, Markdown, văn bản, CSV, JSON và tệp mã.",
"upload.validation.videoSizeExceeded": "Kích thước tệp video không được vượt quá {{maxSize}}. Kích thước hiện tại là {{actualSize}}.",
"verifyConfig.addCriterion": "Thêm tiêu chí",
diff --git a/locales/vi-VN/home.json b/locales/vi-VN/home.json
index e366c021fd1..40711c7f0ef 100644
--- a/locales/vi-VN/home.json
+++ b/locales/vi-VN/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "Gợi ý",
"dashboard.customize.widget.tasks": "Nhiệm vụ",
"dashboard.customize.widget.unread": "Chưa đọc",
+ "dashboard.customize.widget.usage": "Sử dụng",
"dashboard.empty.plan.description": "Chia nhỏ một kết quả thành các bước tiếp theo rõ ràng",
"dashboard.empty.plan.prompt": "Giúp tôi tạo một kế hoạch thực tế cho:",
"dashboard.empty.plan.title": "Lập kế hoạch",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "Trả lời để tiếp tục cuộc trò chuyện này…",
"inbox.unread.title": "Chưa đọc",
"inbox.unread.viewChat": "Xem trò chuyện",
+ "inbox.usage.title": "Sử dụng",
"project.create": "Dự án mới",
"project.deleteConfirm": "Dự án này sẽ bị xóa và không thể khôi phục. Xác nhận để tiếp tục.",
"recommendations.heteroAgent.cta": "Thêm Agent",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index c8f441651f8..86bc39f9570 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1885,6 +1885,7 @@
"upload.preview.status.error": "上传失败",
"upload.preview.status.pending": "准备上传…",
"upload.preview.status.processing": "文件处理中…",
+ "upload.validation.mediaNotSupported": "当前模型无法解析以下媒体文件,未添加:{{files}}。请切换到支持该媒体的模型,或改用其他文件类型。",
"upload.validation.unsupportedFileType": "不支持的文件类型:{{files}}。支持的图片格式:JPG、PNG、GIF、WebP。支持的文档包括PDF、Word、Excel、PowerPoint、Markdown、文本、CSV、JSON和代码文件。",
"upload.validation.videoSizeExceeded": "视频文件不能超过 {{maxSize}}。当前为 {{actualSize}}",
"verifyConfig.addCriterion": "添加验收项",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index d6764378f98..ad8743ea838 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "推荐",
"dashboard.customize.widget.tasks": "最近任务",
"dashboard.customize.widget.unread": "未读",
+ "dashboard.customize.widget.usage": "用量",
"dashboard.empty.plan.description": "把目标拆解为清晰、可执行的下一步",
"dashboard.empty.plan.prompt": "帮我为以下目标制定一份切实可行的计划:",
"dashboard.empty.plan.title": "制定计划",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "回复以继续这次运行…",
"inbox.unread.title": "未读",
"inbox.unread.viewChat": "查看对话",
+ "inbox.usage.title": "用量",
"project.create": "新建项目",
"project.deleteConfirm": "此项目将被删除且无法恢复。确认继续操作。",
"recommendations.heteroAgent.cta": "添加助手",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 1bc492c914b..254f59b5c5a 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -673,7 +673,6 @@
"heteroAgent.codexQuota.tooltip": "查看 Codex 配額",
"heteroAgent.codexQuota.totalEarned_one": "總共獲得 {{count}}",
"heteroAgent.codexQuota.totalEarned_other": "總共獲得 {{count}}",
- "heteroAgent.defaultName": "{{owner}} 的 {{product}}",
"heteroAgent.executionTarget.auto": "自動",
"heteroAgent.executionTarget.autoDesc": "自動使用在線設備,當有多個可用時選擇一個",
"heteroAgent.executionTarget.downloadDesktop": "下載桌面應用程式",
@@ -1633,7 +1632,8 @@
"textSelection.added": "已添加到對話上下文",
"textSelection.title": "訊息選擇",
"thread.closeSubagentThread": "收合子代理對話",
- "thread.divider": "子話題",
+ "thread.dividerContinuation": "從這裡分叉,繼承至今的主要聊天上下文",
+ "thread.dividerStandalone": "從這裡分叉,只繼承上方的訊息",
"thread.openSubagentThread": "查看完整子代理對話",
"thread.subagentMetrics.modelLabel": "模型",
"thread.subagentMetrics.tokens": "{{count}} 個 Token",
@@ -1798,6 +1798,7 @@
"upload.preview.status.error": "上傳失敗",
"upload.preview.status.pending": "準備上傳...",
"upload.preview.status.processing": "檔案處理中...",
+ "upload.validation.mediaNotSupported": "目前的模型無法讀取這些媒體檔案,因此未添加:{{files}}。請切換到支援這些檔案的模型,或上傳其他類型的檔案。",
"upload.validation.unsupportedFileType": "不支援的檔案類型:{{files}}。支援的圖片格式:JPG、PNG、GIF、WebP。支援的文件包括 PDF、Word、Excel、PowerPoint、Markdown、文字檔、CSV、JSON 和程式碼檔案。",
"upload.validation.videoSizeExceeded": "影片檔案大小不能超過 {{maxSize}},當前檔案大小為 {{actualSize}}",
"verifyConfig.addCriterion": "新增條件",
diff --git a/locales/zh-TW/home.json b/locales/zh-TW/home.json
index 70b0e0f15b0..4fb777ce1f9 100644
--- a/locales/zh-TW/home.json
+++ b/locales/zh-TW/home.json
@@ -73,6 +73,7 @@
"dashboard.customize.widget.suggestions": "建議",
"dashboard.customize.widget.tasks": "任務",
"dashboard.customize.widget.unread": "未讀",
+ "dashboard.customize.widget.usage": "使用情況",
"dashboard.empty.plan.description": "將結果分解為清晰的下一步",
"dashboard.empty.plan.prompt": "幫我為以下內容制定一個實用的計劃:",
"dashboard.empty.plan.title": "制定計劃",
@@ -134,6 +135,7 @@
"inbox.unread.followUpPlaceholder": "回覆以繼續此流程…",
"inbox.unread.title": "未讀",
"inbox.unread.viewChat": "查看聊天",
+ "inbox.usage.title": "使用情況",
"project.create": "新增專案",
"project.deleteConfirm": "此專案將被刪除且無法恢復。確認繼續。",
"recommendations.heteroAgent.cta": "新增代理",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3070cd4a62c..7c6f39b7153 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2162,6 +2162,8 @@ export default {
'upload.preview.status.error': 'Upload failed',
'upload.preview.status.pending': 'Preparing to upload...',
'upload.preview.status.processing': 'Processing file...',
+ 'upload.validation.mediaNotSupported':
+ 'The current model cannot read these media files, so they were not added: {{files}}. Switch to a model that supports them, or upload a different file type.',
'upload.validation.unsupportedFileType':
'Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.',
'upload.validation.videoSizeExceeded':
diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.ts
index d9c28c3ab29..a33a867e270 100644
--- a/packages/locales/src/default/home.ts
+++ b/packages/locales/src/default/home.ts
@@ -79,6 +79,7 @@ export default {
'dashboard.customize.widget.suggestions': 'Suggestions',
'dashboard.customize.widget.tasks': 'Recent tasks',
'dashboard.customize.widget.unread': 'Unread',
+ 'dashboard.customize.widget.usage': 'Usage',
'dashboard.empty.plan.description': 'Break an outcome into clear next steps',
'dashboard.empty.plan.prompt': 'Help me create a practical plan for:',
'dashboard.empty.plan.title': 'Make a plan',
@@ -138,6 +139,7 @@ export default {
'inbox.unread.followUpPlaceholder': 'Reply to continue this run…',
'inbox.unread.title': 'Unread',
'inbox.unread.viewChat': 'View chat',
+ 'inbox.usage.title': 'Usage',
'project.create': 'New project',
'project.deleteConfirm':
"This project will be deleted and can't be recovered. Confirm to continue.",
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index c827299358b..a9a0bc21165 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -944,21 +944,25 @@ describe('resolveAgentAgencyConfig', () => {
).toEqual(shared);
});
- it('ignores member policy and overrides while a Workspace Agent is private', () => {
+ // A `local` / this-machine pick is per-user even for the owner: the shared
+ // row must never reference a personal device (the server rejects it), so the
+ // owner's pick lives in the same override slot members use and must merge
+ // back at read time — bypassing `fixed`, which constrains members only.
+ it("applies the owner's own override on a private Workspace Agent, stripping the member policy", () => {
expect(
resolveAgentAgencyConfig(
{
- boundDeviceId: 'owner-device',
+ boundDeviceId: 'shared-device',
executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
},
- { boundDeviceId: 'stale-member-device', executionTarget: 'local' },
+ { boundDeviceId: 'owner-desktop', executionTarget: 'local' },
{ visibility: 'private', workspaceId: 'workspace-1' },
),
- ).toEqual({ boundDeviceId: 'owner-device', executionTarget: 'device' });
+ ).toEqual({ boundDeviceId: 'owner-desktop', executionTarget: 'local' });
});
- it('ignores member policy and overrides for an author or Workspace admin', () => {
+ it("applies an author's or Workspace admin's own override on a public Workspace Agent", () => {
expect(
resolveAgentAgencyConfig(
{
@@ -966,11 +970,35 @@ describe('resolveAgentAgencyConfig', () => {
executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
},
- { boundDeviceId: 'member-device', executionTarget: 'local' },
+ { boundDeviceId: 'manager-desktop', executionTarget: 'local' },
+ { canManage: true, visibility: 'public', workspaceId: 'workspace-1' },
+ ),
+ ).toEqual({ boundDeviceId: 'manager-desktop', executionTarget: 'local' });
+ });
+
+ it('keeps the shared config (policy stripped) for an owner without an override', () => {
+ expect(
+ resolveAgentAgencyConfig(
+ {
+ boundDeviceId: 'shared-device',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ undefined,
{ canManage: true, visibility: 'public', workspaceId: 'workspace-1' },
),
).toEqual({ boundDeviceId: 'shared-device', executionTarget: 'device' });
});
+
+ it('never applies an override on a personal agent', () => {
+ expect(
+ resolveAgentAgencyConfig(
+ { executionTarget: 'sandbox' },
+ { boundDeviceId: 'stale-device', executionTarget: 'local' },
+ { workspaceId: null },
+ ),
+ ).toEqual({ executionTarget: 'sandbox' });
+ });
});
describe('resolveAgentTopicSharePolicy', () => {
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index 15bbf224c29..d83e3db9815 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -1012,6 +1012,41 @@ export const canPublishAgentTopicLink = (
return !!agent.userId && agent.userId === viewer.userId;
};
+/**
+ * The raw override merge behind {@link resolveAgencyConfig}, without the
+ * `fixed`-policy short-circuit. The owner path of
+ * {@link resolveAgentAgencyConfig} needs it directly: the stored selection
+ * policy constrains members, not the owner, so the owner's own override
+ * applies even while the shared policy is `fixed`.
+ */
+const applyAgencyConfigOverride = (
+ base: LobeAgentAgencyConfig | undefined,
+ override:
+ | Pick<
+ LobeAgentAgencyConfig,
+ 'boundDeviceId' | 'executionTarget' | 'localSandbox' | 'localSandboxNetwork'
+ >
+ | null
+ | undefined,
+): LobeAgentAgencyConfig | undefined => {
+ if (!override) return base;
+ const hasTarget = override.executionTarget !== undefined;
+ const hasDevice = override.boundDeviceId !== undefined;
+ // `false` is a real value here — a member turning the sandbox (or its network
+ // allowance) back off must override a shared `true`, so test for presence,
+ // not truthiness.
+ const hasLocalSandbox = override.localSandbox !== undefined;
+ const hasLocalSandboxNetwork = override.localSandboxNetwork !== undefined;
+ if (!hasTarget && !hasDevice && !hasLocalSandbox && !hasLocalSandboxNetwork) return base;
+ return {
+ ...base,
+ ...(hasTarget ? { executionTarget: override.executionTarget } : {}),
+ ...(hasDevice ? { boundDeviceId: override.boundDeviceId } : {}),
+ ...(hasLocalSandbox ? { localSandbox: override.localSandbox } : {}),
+ ...(hasLocalSandboxNetwork ? { localSandboxNetwork: override.localSandboxNetwork } : {}),
+ };
+};
+
/**
* The workspace-shared `agencyConfig` on the agent row is one row per agent —
* inherently a *single* execution decision for the whole workspace. Real users
@@ -1047,22 +1082,7 @@ export const resolveAgencyConfig = (
): LobeAgentAgencyConfig | undefined => {
const base = normalizeAgencyConfigHeterogeneousProvider(agencyConfig);
if (base?.executionTargetSelectionPolicy === 'fixed') return base;
- if (!override) return base;
- const hasTarget = override.executionTarget !== undefined;
- const hasDevice = override.boundDeviceId !== undefined;
- // `false` is a real value here — a member turning the sandbox (or its network
- // allowance) back off must override a shared `true`, so test for presence,
- // not truthiness.
- const hasLocalSandbox = override.localSandbox !== undefined;
- const hasLocalSandboxNetwork = override.localSandboxNetwork !== undefined;
- if (!hasTarget && !hasDevice && !hasLocalSandbox && !hasLocalSandboxNetwork) return base;
- return {
- ...base,
- ...(hasTarget ? { executionTarget: override.executionTarget } : {}),
- ...(hasDevice ? { boundDeviceId: override.boundDeviceId } : {}),
- ...(hasLocalSandbox ? { localSandbox: override.localSandbox } : {}),
- ...(hasLocalSandboxNetwork ? { localSandboxNetwork: override.localSandboxNetwork } : {}),
- };
+ return applyAgencyConfigOverride(base, override);
};
export interface AgentAgencyConfigContext {
@@ -1075,10 +1095,15 @@ export interface AgentAgencyConfigContext {
/**
* Resolve an Agent's effective agency config in its ownership context.
*
- * Member execution-target policies and overrides apply only after a Workspace
- * Agent is public. A Private Agent remains owner-configurable: its shared
- * execution target is used directly, while the stored selection policy is
- * retained only as the policy that will take effect if the Agent is published.
+ * Member execution-target policies apply only after a Workspace Agent is
+ * public. The caller's per-user override, however, merges for EVERY workspace
+ * agent — member, manager, or private owner alike: a `local` / this-machine
+ * pick is inherently per-user (the shared row must never carry a personal
+ * device — the server rejects it), so managers and private-agent owners store
+ * that pick in the same `agentDeviceOverrides` slot members use. The owner
+ * path bypasses the `fixed` short-circuit (the policy constrains members, not
+ * the owner) and keeps stripping the stored selection policy, which is
+ * retained only as the policy that takes effect once the Agent is published.
*/
export const resolveAgentAgencyConfig = (
agencyConfig: LobeAgentAgencyConfig | null | undefined,
@@ -1097,10 +1122,12 @@ export const resolveAgentAgencyConfig = (
if (isPublicWorkspaceAgent) return resolveAgencyConfig(base, override);
- if (!base?.executionTargetSelectionPolicy) return base;
+ const merged = context.workspaceId ? applyAgencyConfigOverride(base, override) : base;
+
+ if (!merged?.executionTargetSelectionPolicy) return merged;
- const { executionTargetSelectionPolicy, ...ownerConfig } = base;
- return executionTargetSelectionPolicy ? ownerConfig : base;
+ const { executionTargetSelectionPolicy, ...ownerConfig } = merged;
+ return executionTargetSelectionPolicy ? ownerConfig : merged;
};
/**
diff --git a/src/business/client/features/HomeUsageWidget.ts b/src/business/client/features/HomeUsageWidget.ts
new file mode 100644
index 00000000000..63423300b3d
--- /dev/null
+++ b/src/business/client/features/HomeUsageWidget.ts
@@ -0,0 +1,16 @@
+import type { ReactNode } from 'react';
+
+/**
+ * Whether the home usage widget exists for this deployment/viewer. Gates the
+ * customize-panel switch and the rail-visibility math, so an unavailable
+ * widget never leaves a dead toggle or an empty rail behind.
+ */
+export const useHomeUsageWidgetActive = (): boolean => false;
+
+/**
+ * The usage widget's content, rendered as the last card of Home's rail.
+ * `enabled` is false while the widget is switched off or its column is not on
+ * the page, so implementations can skip fetching; returning `undefined`
+ * renders no card at all.
+ */
+export const useHomeUsageWidget = (_enabled: boolean): ReactNode | undefined => undefined;
diff --git a/src/components/DragUploadZone/useUploadFiles.test.ts b/src/components/DragUploadZone/useUploadFiles.test.ts
new file mode 100644
index 00000000000..18bd4d4d8d7
--- /dev/null
+++ b/src/components/DragUploadZone/useUploadFiles.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { partitionFilesByMediaAbility } from './useUploadFiles';
+
+const file = (name: string, type: string): File => new File(['x'], name, { type });
+
+const allAllowed = { canUploadAudio: true, canUploadImage: true, canUploadVideo: true };
+
+describe('partitionFilesByMediaAbility', () => {
+ it('accepts everything when the model can receive all media', () => {
+ const files = [
+ file('a.png', 'image/png'),
+ file('b.mp4', 'video/mp4'),
+ file('c.txt', 'text/plain'),
+ ];
+ const { accepted, rejected } = partitionFilesByMediaAbility(files, allAllowed);
+ expect(accepted).toEqual(files);
+ expect(rejected).toEqual([]);
+ });
+
+ it('rejects media the model cannot receive and keeps the rest', () => {
+ const image = file('a.png', 'image/png');
+ const audio = file('b.mp3', 'audio/mpeg');
+ const doc = file('c.pdf', 'application/pdf');
+ const { accepted, rejected } = partitionFilesByMediaAbility([image, audio, doc], {
+ canUploadAudio: false,
+ canUploadImage: false,
+ canUploadVideo: true,
+ });
+ expect(accepted).toEqual([doc]);
+ expect(rejected).toEqual([image, audio]);
+ });
+
+ it('non-media files are never rejected', () => {
+ const doc = file('c.md', 'text/markdown');
+ const { accepted, rejected } = partitionFilesByMediaAbility([doc], {
+ canUploadAudio: false,
+ canUploadImage: false,
+ canUploadVideo: false,
+ });
+ expect(accepted).toEqual([doc]);
+ expect(rejected).toEqual([]);
+ });
+});
diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.ts
index 6baed49d500..89afdceeae7 100644
--- a/src/components/DragUploadZone/useUploadFiles.ts
+++ b/src/components/DragUploadZone/useUploadFiles.ts
@@ -1,4 +1,6 @@
+import { toast } from '@lobehub/ui/base-ui';
import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';
import { usePermission } from '@/hooks/usePermission';
@@ -11,6 +13,42 @@ interface UseUploadFilesOptions {
provider?: string;
}
+interface MediaUploadAbilityFlags {
+ canUploadAudio: boolean;
+ canUploadImage: boolean;
+ canUploadVideo: boolean;
+}
+
+interface PartitionedMediaFiles {
+ accepted: File[];
+ rejected: File[];
+}
+
+/**
+ * Split files into uploadable ones and media the model cannot receive directly
+ * or via the multimodal-understanding fallback. Non-media files always pass.
+ */
+export const partitionFilesByMediaAbility = (
+ files: File[],
+ { canUploadAudio, canUploadImage, canUploadVideo }: MediaUploadAbilityFlags,
+): PartitionedMediaFiles => {
+ const accepted: File[] = [];
+ const rejected: File[] = [];
+
+ for (const file of files) {
+ const allowed = file.type.startsWith('image')
+ ? canUploadImage
+ : file.type.startsWith('video')
+ ? canUploadVideo
+ : file.type.startsWith('audio')
+ ? canUploadAudio
+ : true;
+ (allowed ? accepted : rejected).push(file);
+ }
+
+ return { accepted, rejected };
+};
+
/**
* Hook to handle file uploads with multimodal media support filtering.
* Filters out image/video files if the model cannot receive them directly or via fallback.
@@ -20,6 +58,7 @@ interface UseUploadFilesOptions {
*/
export const useUploadFiles = (options: UseUploadFilesOptions) => {
const { agentId, model = '', provider = '' } = options;
+ const { t } = useTranslation('chat');
const { canUploadImage, canUploadVideo, canUploadAudio } = useMediaUploadAbility(
model,
@@ -34,18 +73,27 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {
if (!canUpload) return;
// Filter out media files if the model cannot receive them directly or via fallback.
- const filteredFiles = files.filter((file) => {
- if (file.type.startsWith('image')) return canUploadImage;
- if (file.type.startsWith('video')) return canUploadVideo;
- if (file.type.startsWith('audio')) return canUploadAudio;
- return true;
+ const { accepted, rejected } = partitionFilesByMediaAbility(files, {
+ canUploadAudio,
+ canUploadImage,
+ canUploadVideo,
});
- if (filteredFiles.length > 0) {
- uploadFiles(filteredFiles, agentId);
+ // Dropping a pasted/dragged file with no feedback reads as "the app ate
+ // my file" — surface which ones the model cannot receive.
+ if (rejected.length > 0) {
+ toast.warning(
+ t('upload.validation.mediaNotSupported', {
+ files: rejected.map((file) => file.name).join(', '),
+ }),
+ );
+ }
+
+ if (accepted.length > 0) {
+ uploadFiles(accepted, agentId);
}
},
- [agentId, canUpload, canUploadImage, canUploadVideo, canUploadAudio, uploadFiles],
+ [agentId, canUpload, canUploadImage, canUploadVideo, canUploadAudio, t, uploadFiles],
);
return { canUploadImage, canUploadVideo, canUploadAudio, handleUploadFiles };
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
index 043e0f91922..7bd1975522e 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -47,6 +47,14 @@ vi.mock('@lobechat/const', () => ({
},
}));
+vi.mock('@lobehub/ui/base-ui', () => ({
+ toast: { error: vi.fn() },
+}));
+
+vi.mock('i18next', () => ({
+ t: (key: string) => key,
+}));
+
vi.mock('@/services/electron/gatewayConnection', () => ({
gatewayConnectionService: {
getDeviceInfo: () => testState.getDeviceInfo(),
@@ -99,9 +107,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('sandbox');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'device-1', executionTarget: 'sandbox' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'device-1', executionTarget: 'sandbox' },
+ },
+ { rethrow: true },
+ );
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
@@ -110,9 +122,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('device', 'device-2');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'device-2', executionTarget: 'device' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'device-2', executionTarget: 'device' },
+ },
+ { rethrow: true },
+ );
});
it("stores 'local' verbatim (not pre-resolved to 'device') to preserve the in-process IPC path", async () => {
@@ -123,9 +139,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('local');
expect(testState.getDeviceInfo).not.toHaveBeenCalled();
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ },
+ { rethrow: true },
+ );
});
it('falls back to the gateway connection service when no gateway deviceId is cached yet', async () => {
@@ -136,9 +156,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('local');
expect(testState.getDeviceInfo).toHaveBeenCalled();
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'resolved-device', executionTarget: 'local' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'resolved-device', executionTarget: 'local' },
+ },
+ { rethrow: true },
+ );
});
it('keeps the previous boundDeviceId when the local device cannot be resolved for a non-hetero agent', async () => {
@@ -148,9 +172,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('local');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'stale-device', executionTarget: 'local' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'stale-device', executionTarget: 'local' },
+ },
+ { rethrow: true },
+ );
});
// automatic corrections must not trigger phantom save-error toasts: the device switcher defaults an unset target to `local` on
@@ -167,7 +195,7 @@ describe('useSelectExecutionTarget', () => {
expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
'agent-id',
{ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' } },
- { showErrorMessage: false },
+ { rethrow: true, showErrorMessage: false },
);
});
@@ -178,9 +206,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('local');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ },
+ { rethrow: true },
+ );
});
it('records the sandbox choice alongside a local pick', async () => {
@@ -190,13 +222,17 @@ describe('useSelectExecutionTarget', () => {
await result.current('local', undefined, { localSandbox: true });
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: {
- boundDeviceId: 'this-machine',
- executionTarget: 'local',
- localSandbox: true,
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: true,
+ },
},
- });
+ { rethrow: true },
+ );
});
it('clears the sandbox when the plain local row is picked', async () => {
@@ -209,13 +245,17 @@ describe('useSelectExecutionTarget', () => {
await result.current('local', undefined, { localSandbox: false });
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: {
- boundDeviceId: 'this-machine',
- executionTarget: 'local',
- localSandbox: false,
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: false,
+ },
},
- });
+ { rethrow: true },
+ );
});
it('leaves the stored sandbox choice dormant when switching to another environment', async () => {
@@ -226,9 +266,13 @@ describe('useSelectExecutionTarget', () => {
await result.current('sandbox');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: { executionTarget: 'sandbox', localSandbox: true },
- });
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { executionTarget: 'sandbox', localSandbox: true },
+ },
+ { rethrow: true },
+ );
});
it('does not switch a heterogeneous agent to local when no device can be resolved', async () => {
@@ -362,13 +406,181 @@ describe('useSelectExecutionTarget', () => {
await result.current('sandbox');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: {
- boundDeviceId: 'fixed-device',
- executionTarget: 'sandbox',
- executionTargetSelectionPolicy: 'fixed',
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: {
+ boundDeviceId: 'fixed-device',
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ },
+ },
+ { rethrow: true },
+ );
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("workspace agent — a manager's or owner's `local` pick stays per-user", () => {
+ // The regression behind "用户在 Workspace 中无法切换个人的本地设备": a `local`
+ // pick binds this member's PERSONAL desktop device, which the shared row
+ // must never reference — the server rejects it with
+ // `WorkspaceAgentRequiresWorkspaceDevice` and the picker surfaces
+ // "Failed to save agent settings". So even callers who manage the shared
+ // config route `local` into their per-user override.
+ it("routes a manager's 'local' pick into the per-user override, never the shared config", async () => {
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentDeviceOverrides: {
+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },
},
});
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it("routes a private Workspace agent owner's 'local' pick into the per-user override", async () => {
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'private', workspaceId: 'ws-1' },
+ };
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentDeviceOverrides: {
+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ },
+ });
+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it("clears the manager's own routing override when they pick a shared target", async () => {
+ // Without this, the earlier `local` override would keep shadowing the
+ // shared target the manager just wrote. The sandbox fence stays dormant —
+ // it qualifies their machine, not this pick.
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.user.workspaceUserPreference = {
+ agentDeviceOverrides: {
+ 'agent-id': {
+ boundDeviceId: 'this-machine',
+ executionTarget: 'local',
+ localSandbox: true,
+ },
+ },
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { executionTarget: 'sandbox' },
+ },
+ { rethrow: true },
+ );
+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({
+ agentDeviceOverrides: {
+ 'agent-id': { localSandbox: true },
+ },
+ });
+ });
+
+ it('keeps the routing override intact when the shared save fails', async () => {
+ // The store rolls the optimistic config back and toasts on failure; the
+ // caller's previously valid `local` pick must survive it — clearing the
+ // override for a save that never happened would silently reroute them to
+ // the old shared target.
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.agent.updateAgentConfigById = vi.fn().mockRejectedValue(new Error('save failed'));
+ testState.user.workspaceUserPreference = {
+ agentDeviceOverrides: {
+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ },
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledTimes(1);
+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
+ });
+
+ it('restores the shared config when clearing the override fails after a successful save', async () => {
+ // The shared save persisted but the override clear rolled back — the old
+ // `local` override would shadow the new shared target (split state), so
+ // the hook compensates by writing the previous shared config back.
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ testState.agent.agencyConfig = { executionTarget: 'device', boundDeviceId: 'ws-device' };
+ testState.user.updateWorkspaceUserPreference = vi
+ .fn()
+ .mockRejectedValue(new Error('clear failed'));
+ testState.user.workspaceUserPreference = {
+ agentDeviceOverrides: {
+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ },
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenNthCalledWith(
+ 1,
+ 'agent-id',
+ {
+ agencyConfig: {
+ boundDeviceId: 'ws-device',
+ executionTarget: 'sandbox',
+ },
+ },
+ { rethrow: true },
+ );
+ expect(testState.agent.updateAgentConfigById).toHaveBeenNthCalledWith(
+ 2,
+ 'agent-id',
+ {
+ agencyConfig: { boundDeviceId: 'ws-device', executionTarget: 'device' },
+ },
+ { showErrorMessage: false },
+ );
+ });
+
+ it('leaves the preference untouched when a manager picks a shared target with no override', async () => {
+ testState.access.canManageAgent = true;
+ testState.agent.agentMap = {
+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },
+ };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('sandbox');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: { executionTarget: 'sandbox' },
+ },
+ { rethrow: true },
+ );
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
});
@@ -387,13 +599,17 @@ describe('useSelectExecutionTarget', () => {
await result.current('sandbox');
- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
- agencyConfig: {
- boundDeviceId: 'owner-device',
- executionTarget: 'sandbox',
- executionTargetSelectionPolicy: 'fixed',
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ {
+ agencyConfig: {
+ boundDeviceId: 'owner-device',
+ executionTarget: 'sandbox',
+ executionTargetSelectionPolicy: 'fixed',
+ },
},
- });
+ { rethrow: true },
+ );
expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();
});
});
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
index 4c8a9d6b360..1fb4783ac98 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -2,6 +2,8 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceExecutionTarget } from '@lobechat/types';
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
import { useCallback } from 'react';
import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';
@@ -58,6 +60,13 @@ export interface SelectExecutionTargetOptions {
* - **Private Workspace agent** — like a personal agent, writes go directly to
* `agents.agencyConfig`; the member-selection policy takes effect only after
* the Agent is published.
+ * - **`local` on ANY workspace agent** — always the per-user override, even for
+ * managers and private-agent owners who otherwise write the shared row: a
+ * `local` pick binds this member's personal desktop device, and the server
+ * rejects a workspace agent whose shared config references a device not
+ * enrolled in the workspace (`WorkspaceAgentRequiresWorkspaceDevice`).
+ * Conversely, a manager's shared-target pick clears their own override's
+ * routing keys so a previous `local` pick cannot keep shadowing it.
*
* `local` is stored verbatim (`{ executionTarget: 'local', boundDeviceId: <me> }`)
* so both desktop dispatch (in-process IPC — the fast path) and web dispatch
@@ -69,6 +78,7 @@ export interface SelectExecutionTargetOptions {
export const useSelectExecutionTarget = (agentId: string) => {
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
+ const isWorkspaceAgent = useAgentStore((s) => Boolean(s.agentMap[agentId]?.workspaceId));
const isPublicWorkspaceAgent = useAgentStore((s) => {
const agent = s.agentMap[agentId];
return !!agent?.workspaceId && agent.visibility !== 'private';
@@ -142,7 +152,11 @@ export const useSelectExecutionTarget = (agentId: string) => {
: { localSandboxNetwork: options.localSandboxNetwork }),
};
- if (usesWorkspaceMemberSelection) {
+ // A `local` pick on a workspace agent is always this caller's own
+ // machine — a personal device the workspace-shared row must never
+ // reference (the server rejects it) — so it routes to the per-user
+ // override even for managers and private-agent owners.
+ if (usesWorkspaceMemberSelection || (isWorkspaceAgent && target === 'local')) {
const nextOverrides = {
...workspaceUserPreference.agentDeviceOverrides,
[agentId]: {
@@ -168,12 +182,53 @@ export const useSelectExecutionTarget = (agentId: string) => {
// A silent caller is defaulting the target on mount, not answering a
// pick — telling the user "your change was not applied" would be
// reporting a change they never made (automatic corrections must not trigger phantom save-error toasts).
- if (options?.silent) {
- await updateAgentConfigById(agentId, nextConfig, { showErrorMessage: false });
+ //
+ // `rethrow` so a failed shared save (network error, server validation)
+ // stops here: the store already rolled the optimistic config back and
+ // toasted, and clearing the caller's override below would additionally
+ // destroy their previously valid personal target over a save that never
+ // happened.
+ try {
+ await updateAgentConfigById(agentId, nextConfig, {
+ rethrow: true,
+ ...(options?.silent ? { showErrorMessage: false } : {}),
+ });
+ } catch {
return;
}
- await updateAgentConfigById(agentId, nextConfig);
+ // A manager's earlier `local` pick lives in their own override and would
+ // keep shadowing the shared target they just wrote — drop the override's
+ // routing keys. The sandbox fence stays: it qualifies their machine, not
+ // this pick.
+ const prevOverride = workspaceUserPreference.agentDeviceOverrides?.[agentId];
+ if (
+ isWorkspaceAgent &&
+ prevOverride &&
+ (prevOverride.executionTarget !== undefined || prevOverride.boundDeviceId !== undefined)
+ ) {
+ const { boundDeviceId: _device, executionTarget: _target, ...dormant } = prevOverride;
+ try {
+ await updateWorkspaceUserPreference({
+ agentDeviceOverrides: {
+ ...workspaceUserPreference.agentDeviceOverrides,
+ [agentId]: dormant,
+ },
+ });
+ } catch {
+ // The preference store rolled the override back, so the old `local`
+ // pick would keep shadowing the shared target that DID persist —
+ // split state. Compensate by restoring the previous shared config
+ // (best effort, no double toast) so the surviving override shadows
+ // the same target the user had before this pick.
+ await updateAgentConfigById(
+ agentId,
+ { agencyConfig: { ...agencyConfig } },
+ { showErrorMessage: false },
+ );
+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));
+ }
+ }
},
[
agentId,
@@ -181,6 +236,7 @@ export const useSelectExecutionTarget = (agentId: string) => {
currentDeviceId,
isHetero,
isAccessLoading,
+ isWorkspaceAgent,
updateAgentConfigById,
updateWorkspaceUserPreference,
usesWorkspaceMemberSelection,
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index fcdefdd8eb0..8058750caa4 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -16,6 +16,10 @@ import { MESSAGE_CANCEL_FLAT } from '@/const/index';
import { saveDraft } from '@/features/ChatInput/draftStorage';
import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';
import { getEffectiveConversationModel } from '@/features/Conversation/store/utils/effectiveModel';
+import {
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+} from '@/helpers/agentManagementAccess';
import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';
import { resolveWorkspaceScoped } from '@/helpers/executionTarget';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
@@ -99,21 +103,51 @@ const settleGenerationEntry = (
notify?.();
};
+/**
+ * Resolve management access from the server before `getEffectiveAgencyConfig`
+ * runs on a cold cache (page reload straight into regenerate/continue) — an
+ * admin must not be downgraded to member just because the picker's hook never
+ * mounted. No-ops for authors, members-with-resolved-answers, and non-workspace
+ * agents; a failed fetch falls back to authorship for this run.
+ */
+const ensureEffectiveAgencyAccess = async (agentId: string) => {
+ const agentState = getAgentStoreState();
+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
+ await ensureAgentManagementAccess({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId: userProfileSelectors.userId(getUserStoreState()),
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ });
+};
+
const getEffectiveAgencyConfig = (agentId: string) => {
const agentState = getAgentStoreState();
const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
const currentUserId = userProfileSelectors.userId(getUserStoreState());
- const isAuthor = !!currentUserId && agent?.userId === currentUserId;
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
+ // server (`isResourceAuthorOrAdmin`) — an admin's own override must survive
+ // a `fixed` selection policy just like the author's does.
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
const usesWorkspaceMemberSelection =
- !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;
- const deviceOverride = usesWorkspaceMemberSelection
+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
+ // Every workspace caller's override matters — a manager's / private owner's
+ // `local` pick also lives in `agentDeviceOverrides` (the shared row must
+ // never reference a personal device); `resolveAgentAgencyConfig` decides how
+ // it applies per role.
+ const deviceOverride = agent?.workspaceId
? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
: undefined;
return {
agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {
- canManage: isAuthor,
+ canManage,
visibility: agent?.visibility,
workspaceId: agent?.workspaceId,
}),
@@ -207,6 +241,7 @@ const runHeterogeneousFromExistingMessage = async (
const agentId = context.agentId;
if (!agentId) throw new Error('agentId is required for heterogeneous agent');
+ await ensureEffectiveAgencyAccess(agentId);
const { cwdChanged, reason, resumeBindingKey, resumeSessionId, workingDirectory } =
resolveHeteroRunContext(chatStore, context, agentId);
if (cwdChanged) toast.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));
@@ -383,6 +418,7 @@ const regenerateUserMessageFromSource = async (
const postSwitchOp = operationSelectors.getOperationById(operationId)(useChatStore.getState());
if (postSwitchOp && postSwitchOp.status !== 'running') return;
+ await ensureEffectiveAgencyAccess(context.agentId);
const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(
context.agentId,
);
@@ -772,6 +808,7 @@ export const generationSlice: StateCreator<
if (shouldProceed === false) return false;
}
+ await ensureEffectiveAgencyAccess(context.agentId);
const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(
context.agentId,
);
@@ -862,6 +899,7 @@ export const generationSlice: StateCreator<
// tool/provider error on a grouped reply is not resumable this way.
if (!isHeterogeneousAgentStatusGuideError(erroredStep.error?.body)) return;
+ await ensureEffectiveAgencyAccess(context.agentId);
const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(
context.agentId,
);
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index ca90008707c..9075540e384 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -334,7 +334,10 @@ describe('continueHeteroAfterError', () => {
expect(mockExecuteHeterogeneousAgent).not.toHaveBeenCalled();
});
- it('ignores a retained member device override while the Workspace Agent is private', async () => {
+ // The owner's own `local` pick lives in the per-user override even on a
+ // private Workspace Agent (the shared row must never reference a personal
+ // device — the server rejects it), so it must keep applying here.
+ it("applies the owner's own local override while the Workspace Agent is private", async () => {
mockAgentVisibility = 'private';
mockIsWorkspaceAgent = true;
mockSharedExecutionTarget = 'device';
@@ -353,8 +356,8 @@ describe('continueHeteroAfterError', () => {
expect(mockSelectRuntimeType).toHaveBeenCalledWith(
expect.objectContaining({
- boundDeviceId: 'workspace-device',
- executionTarget: 'device',
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
isWorkspaceAgent: true,
workspaceScoped: false,
}),
diff --git a/src/features/Conversation/useLocalPathReference.ts b/src/features/Conversation/useLocalPathReference.ts
new file mode 100644
index 00000000000..7aa292d75a9
--- /dev/null
+++ b/src/features/Conversation/useLocalPathReference.ts
@@ -0,0 +1,54 @@
+import { isDesktop } from '@lobechat/const';
+import { useCallback } from 'react';
+
+import type { DroppedLocalPath } from '@/components/DragUploadZone';
+import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';
+import {
+ canExecutionTargetReadLocalPaths,
+ resolveExecutionTarget,
+} from '@/helpers/executionTarget';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { useElectronStore } from '@/store/electron';
+
+/**
+ * Whether a drag-dropped local path should become a `<localFile>` reference for
+ * this agent's next run, plus the insert handler for the drop zone.
+ *
+ * A dropped path only makes sense when THIS run executes somewhere that can
+ * read this machine's filesystem. Resolve the effective execution target
+ * (member override + workspace coercion included) instead of trusting
+ * "hetero / local-system" alone — a Claude Code agent whose run lands in the
+ * cloud sandbox must fall back to attachment upload, or the agent receives a
+ * `/Users/...` path that does not exist in its container.
+ */
+export const useLocalPathReference = (agentId: string, topicId?: string | null) => {
+ const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
+ const isLocalSystemEnabled = useAgentStore(
+ chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),
+ );
+ const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
+ const executionTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ isHetero: isHeterogeneous,
+ workspaceScoped,
+ });
+ const enableLocalPathReference =
+ isDesktop &&
+ !!workingDirectory &&
+ (isHeterogeneous || isLocalSystemEnabled) &&
+ canExecutionTargetReadLocalPaths(executionTarget, agencyConfig, currentDeviceId);
+
+ const handleLocalPaths = useCallback((paths: DroppedLocalPath[]) => {
+ const editor = useChatStore.getState().mainInputEditor?.instance;
+ if (!editor) return;
+ insertLocalPathTags(editor, paths);
+ }, []);
+
+ return { enableLocalPathReference, handleLocalPaths };
+};
diff --git a/src/features/Home/CustomizeModal/Content.tsx b/src/features/Home/CustomizeModal/Content.tsx
index c6042259994..1137df6a4fa 100644
--- a/src/features/Home/CustomizeModal/Content.tsx
+++ b/src/features/Home/CustomizeModal/Content.tsx
@@ -46,6 +46,7 @@ const CustomizeModalContent = memo(() => {
taskCount,
togglePortrait,
toggleWidget,
+ usageActive,
} = useHomeCustomization();
return (
@@ -93,20 +94,24 @@ const CustomizeModalContent = memo(() => {
<Text fontSize={12} type={'secondary'} weight={600}>
{t(`dashboard.customize.group.${group.key}`)}
</Text>
- {group.widgets.map((key) => (
- <SettingRow key={key} title={t(`dashboard.customize.widget.${key}`)}>
- <Switch
- aria-label={t(`dashboard.customize.widget.${key}`)}
- checked={!isWidgetHidden(key)}
- // The scheduled block is the second half of the task overview,
- // so there is nothing for it to switch on while the first half
- // is off.
- disabled={key === 'scheduledTasks' && isWidgetHidden('tasks')}
- size={'small'}
- onChange={() => toggleWidget(key)}
- />
- </SettingRow>
- ))}
+ {/* The usage widget is a business slot: a deployment without it
+ must not show a switch that toggles nothing. */}
+ {group.widgets
+ .filter((key) => key !== 'usage' || usageActive)
+ .map((key) => (
+ <SettingRow key={key} title={t(`dashboard.customize.widget.${key}`)}>
+ <Switch
+ aria-label={t(`dashboard.customize.widget.${key}`)}
+ checked={!isWidgetHidden(key)}
+ // The scheduled block is the second half of the task overview,
+ // so there is nothing for it to switch on while the first half
+ // is off.
+ disabled={key === 'scheduledTasks' && isWidgetHidden('tasks')}
+ size={'small'}
+ onChange={() => toggleWidget(key)}
+ />
+ </SettingRow>
+ ))}
</Flexbox>
))}
diff --git a/src/features/Home/CustomizeModal/config.ts b/src/features/Home/CustomizeModal/config.ts
index 456f6538705..cd10b33d9e8 100644
--- a/src/features/Home/CustomizeModal/config.ts
+++ b/src/features/Home/CustomizeModal/config.ts
@@ -7,6 +7,7 @@ export const HOME_INBOX_WIDGET_KEYS = [
'unread',
'running',
'news',
+ 'usage',
'suggestions',
] as const;
@@ -39,7 +40,7 @@ export type HomeWidgetKey = (typeof HOME_WIDGET_KEYS)[number];
export const HOME_WIDGET_GROUPS = [
{ key: 'agent', widgets: ['unread', 'needsYou', 'running', 'recents'] },
{ key: 'task', widgets: ['tasks', 'scheduledTasks'] },
- { key: 'rail', widgets: ['goals', 'news', 'suggestions'] },
+ { key: 'rail', widgets: ['goals', 'news', 'usage', 'suggestions'] },
] as const satisfies ReadonlyArray<{ key: string; widgets: readonly HomeWidgetKey[] }>;
export type HomeWidgetGroupKey = (typeof HOME_WIDGET_GROUPS)[number]['key'];
@@ -82,6 +83,16 @@ interface HomeVisibilityState {
showPortrait: boolean;
}
+/**
+ * `usage` is a business-slot widget (`useHomeUsageWidgetActive`): deployments
+ * without it must not count the key anywhere — not in the customize panel, not
+ * in preset/minimal math, not in "can the rail host anything". Otherwise a key
+ * the viewer can neither see nor toggle breaks their stored minimal/full
+ * preset the day it ships.
+ */
+export const effectiveHomeWidgetKeys = (usageActive: boolean): readonly HomeWidgetKey[] =>
+ usageActive ? HOME_WIDGET_KEYS : HOME_WIDGET_KEYS.filter((key) => key !== 'usage');
+
/**
* `scheduledTasks` rides on `tasks`: the two are one task overview split in
* half, so switching the main list off must not leave the other half standing
@@ -93,19 +104,26 @@ interface HomeVisibilityState {
export const isHomeWidgetHidden = (key: HomeWidgetKey, hiddenWidgets: string[]): boolean =>
hiddenWidgets.includes(key) || (key === 'scheduledTasks' && hiddenWidgets.includes('tasks'));
-const hiddenKeySet = ({ hiddenWidgets }: HomeVisibilityState): Set<string> =>
- new Set(HOME_WIDGET_KEYS.filter((key) => isHomeWidgetHidden(key, hiddenWidgets)));
+const hiddenKeySet = ({ hiddenWidgets }: HomeVisibilityState, usageActive: boolean): Set<string> =>
+ new Set(
+ effectiveHomeWidgetKeys(usageActive).filter((key) => isHomeWidgetHidden(key, hiddenWidgets)),
+ );
-export const resolveHomePreset = (state: HomeVisibilityState): HomePresetKey | undefined => {
- const hidden = hiddenKeySet(state);
+export const resolveHomePreset = (
+ state: HomeVisibilityState,
+ usageActive = false,
+): HomePresetKey | undefined => {
+ const hidden = hiddenKeySet(state, usageActive);
+ const available = new Set<string>(effectiveHomeWidgetKeys(usageActive));
return HOME_PRESET_KEYS.find((key) => {
const preset = HOME_PRESETS[key];
+ const presetHidden = preset.hiddenWidgets.filter((widget) => available.has(widget));
return (
preset.showPortrait === state.showPortrait &&
- preset.hiddenWidgets.length === hidden.size &&
- preset.hiddenWidgets.every((widget) => hidden.has(widget))
+ presetHidden.length === hidden.size &&
+ presetHidden.every((widget) => hidden.has(widget))
);
});
};
@@ -113,9 +131,9 @@ export const resolveHomePreset = (state: HomeVisibilityState): HomePresetKey | u
// Nothing is left to stack under the composer, so the page stops being a
// dashboard: the greeting and the composer become one centered block. Derived
// from the switches rather than stored, so it can never disagree with them.
-export const isHomeMinimalLayout = (state: HomeVisibilityState): boolean =>
+export const isHomeMinimalLayout = (state: HomeVisibilityState, usageActive = false): boolean =>
!state.showPortrait &&
- HOME_WIDGET_KEYS.every((key) => isHomeWidgetHidden(key, state.hiddenWidgets));
+ effectiveHomeWidgetKeys(usageActive).every((key) => isHomeWidgetHidden(key, state.hiddenWidgets));
// An error banner covers every widget whose content it reports on, not just the
// one it is named after: the topic feed powers unread AND running, and the briefs
diff --git a/src/features/Home/CustomizeModal/useHomeCustomization.test.ts b/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
index 445571ba2c0..12fb08c1ad1 100644
--- a/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
+++ b/src/features/Home/CustomizeModal/useHomeCustomization.test.ts
@@ -75,6 +75,35 @@ describe('resolveHomePreset', () => {
it('tells the presets apart by the portrait alone', () => {
expect(resolveHomePreset({ hiddenWidgets: [], showPortrait: false })).toBeUndefined();
});
+
+ // The usage widget is a business slot: where it doesn't exist, its key must
+ // not count, or shipping it would silently break every stored preset.
+ describe('usage availability', () => {
+ const legacyMinimal = HOME_WIDGET_KEYS.filter((key) => key !== 'usage');
+
+ it('keeps a pre-usage minimal selection minimal where the slot is empty', () => {
+ expect(resolveHomePreset({ hiddenWidgets: [...legacyMinimal], showPortrait: false })).toBe(
+ 'minimal',
+ );
+ });
+
+ it('keeps an empty hidden set full where the slot is empty', () => {
+ expect(resolveHomePreset({ hiddenWidgets: [], showPortrait: true }, false)).toBe('full');
+ });
+
+ it('requires the usage switch too once the slot is active', () => {
+ expect(
+ resolveHomePreset({ hiddenWidgets: [...legacyMinimal], showPortrait: false }, true),
+ ).toBeUndefined();
+ expect(
+ resolveHomePreset({ hiddenWidgets: [...HOME_WIDGET_KEYS], showPortrait: false }, true),
+ ).toBe('minimal');
+ });
+
+ it('counts a visible usage widget toward full once the slot is active', () => {
+ expect(resolveHomePreset({ hiddenWidgets: [], showPortrait: true }, true)).toBe('full');
+ });
+ });
});
describe('isHomeMinimalLayout', () => {
@@ -90,6 +119,17 @@ describe('isHomeMinimalLayout', () => {
);
});
+ it('ignores the usage key where its slot is empty, but demands it where active', () => {
+ const legacyAllHidden = HOME_WIDGET_KEYS.filter((key) => key !== 'usage');
+
+ expect(isHomeMinimalLayout({ hiddenWidgets: [...legacyAllHidden], showPortrait: false })).toBe(
+ true,
+ );
+ expect(
+ isHomeMinimalLayout({ hiddenWidgets: [...legacyAllHidden], showPortrait: false }, true),
+ ).toBe(false);
+ });
+
it('keeps the dashboard while one section still has something to stack', () => {
expect(
isHomeMinimalLayout({
@@ -115,7 +155,7 @@ describe('HOME_WIDGET_GROUPS', () => {
it.each([
['agent', ['unread', 'needsYou', 'running', 'recents']],
['task', ['tasks', 'scheduledTasks']],
- ['rail', ['goals', 'news', 'suggestions']],
+ ['rail', ['goals', 'news', 'usage', 'suggestions']],
])('groups %s by where those sections render on Home', (key, widgets) => {
expect(HOME_WIDGET_GROUPS.find((group) => group.key === key)?.widgets).toEqual(widgets);
});
diff --git a/src/features/Home/CustomizeModal/useHomeCustomization.ts b/src/features/Home/CustomizeModal/useHomeCustomization.ts
index f0162d62009..04d1ba598b9 100644
--- a/src/features/Home/CustomizeModal/useHomeCustomization.ts
+++ b/src/features/Home/CustomizeModal/useHomeCustomization.ts
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
+import { useHomeUsageWidgetActive } from '@/business/client/features/HomeUsageWidget';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -34,16 +35,20 @@ interface HomeCustomization {
taskCount: number;
togglePortrait: () => void;
toggleWidget: (key: HomeWidgetKey) => void;
+ /** Whether the business usage widget exists here — gates its switch. */
+ usageActive: boolean;
}
export const useHomeMinimalLayout = (): boolean => {
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
const showPortrait = useGlobalStore(systemStatusSelectors.showHomePortrait);
+ const usageActive = useHomeUsageWidgetActive();
- return isHomeMinimalLayout({ hiddenWidgets, showPortrait });
+ return isHomeMinimalLayout({ hiddenWidgets, showPortrait }, usageActive);
};
export const useHomeCustomization = (): HomeCustomization => {
+ const usageActive = useHomeUsageWidgetActive();
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
const recentsCount = useGlobalStore(systemStatusSelectors.homeRecentsCount);
const taskCount = useGlobalStore(systemStatusSelectors.homeTaskCount);
@@ -108,7 +113,7 @@ export const useHomeCustomization = (): HomeCustomization => {
applyPreset,
hiddenWidgets,
isWidgetHidden,
- preset: resolveHomePreset({ hiddenWidgets, showPortrait }),
+ preset: resolveHomePreset({ hiddenWidgets, showPortrait }, usageActive),
recentsCount,
reset,
setRecentsCount,
@@ -117,5 +122,6 @@ export const useHomeCustomization = (): HomeCustomization => {
taskCount,
toggleWidget,
togglePortrait,
+ usageActive,
};
};
diff --git a/src/features/Home/HomeNavHeader.tsx b/src/features/Home/HomeNavHeader.tsx
index d33d121b62f..a4f957081d1 100644
--- a/src/features/Home/HomeNavHeader.tsx
+++ b/src/features/Home/HomeNavHeader.tsx
@@ -2,6 +2,7 @@ import { Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
+import { useHomeUsageWidgetActive } from '@/business/client/features/HomeUsageWidget';
import NavHeader from '@/features/NavHeader';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -31,6 +32,7 @@ const HomeNavHeader = memo(() => {
systemStatusSelectors.isStatusInit(s),
]);
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
+ const usageActive = useHomeUsageWidgetActive();
return (
<NavHeader
@@ -39,7 +41,7 @@ const HomeNavHeader = memo(() => {
isLogin && isStatusInit ? (
<Flexbox horizontal align={'center'} gap={4}>
<CustomizeButton />
- {canHostRail(hiddenWidgets) && (
+ {canHostRail(hiddenWidgets, usageActive) && (
<RailToggle railVisible={showHomeRail} onToggle={toggleHomeRail} />
)}
</Flexbox>
diff --git a/src/features/Home/index.tsx b/src/features/Home/index.tsx
index e025c79610a..78c58f97240 100644
--- a/src/features/Home/index.tsx
+++ b/src/features/Home/index.tsx
@@ -4,6 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cx } from 'antd-style';
import { lazy, memo, Suspense, useCallback, useEffect, useState } from 'react';
+import { useHomeUsageWidgetActive } from '@/business/client/features/HomeUsageWidget';
import { useHomePromoLine } from '@/business/client/features/useHomePromoLine';
import HomeInbox from '@/features/HomeInbox';
import { useChatStore } from '@/store/chat';
@@ -300,7 +301,11 @@ const Home = memo(() => {
const showHomePortrait = useGlobalStore(systemStatusSelectors.showHomePortrait);
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
const promo = useHomePromoLine();
- const minimal = isHomeMinimalLayout({ hiddenWidgets, showPortrait: showHomePortrait });
+ const usageActive = useHomeUsageWidgetActive();
+ const minimal = isHomeMinimalLayout(
+ { hiddenWidgets, showPortrait: showHomePortrait },
+ usageActive,
+ );
const [mode, setMode] = useState<HomeMode>(() =>
resolveInitialHomeMode(typeof window === 'undefined' ? '' : window.location.search),
);
@@ -315,7 +320,7 @@ const Home = memo(() => {
if (drawerTopicId && !drawerMounted) setDrawerMounted(true);
const [acceptanceDrawerMounted, setAcceptanceDrawerMounted] = useState(false);
if (acceptancePortalOpen && !acceptanceDrawerMounted) setAcceptanceDrawerMounted(true);
- const railVisible = resolveRailVisibility({ hiddenWidgets, isLogin, showHomeRail });
+ const railVisible = resolveRailVisibility({ hiddenWidgets, isLogin, showHomeRail, usageActive });
const railCollapsed = !railVisible;
const portraitVisible = Boolean(isLogin && showHomePortrait);
diff --git a/src/features/Home/railVisibility.ts b/src/features/Home/railVisibility.ts
index f0f19c3925f..4b53e8aaad2 100644
--- a/src/features/Home/railVisibility.ts
+++ b/src/features/Home/railVisibility.ts
@@ -10,13 +10,16 @@ interface RailVisibilityInput {
hiddenWidgets: string[];
isLogin?: boolean | null;
showHomeRail?: boolean;
+ usageActive?: boolean;
}
-export const canHostRail = (hiddenWidgets: string[]): boolean =>
- hasVisibleRailWidget({ ...RAIL_INBOX_PROPS, hiddenWidgets });
+export const canHostRail = (hiddenWidgets: string[], usageActive?: boolean): boolean =>
+ hasVisibleRailWidget({ ...RAIL_INBOX_PROPS, hiddenWidgets, usageActive });
export const resolveRailVisibility = ({
hiddenWidgets,
isLogin,
showHomeRail,
-}: RailVisibilityInput): boolean => Boolean(isLogin && showHomeRail && canHostRail(hiddenWidgets));
+ usageActive,
+}: RailVisibilityInput): boolean =>
+ Boolean(isLogin && showHomeRail && canHostRail(hiddenWidgets, usageActive));
diff --git a/src/features/HomeInbox/hiddenWidgets.test.ts b/src/features/HomeInbox/hiddenWidgets.test.ts
index 8183342abcf..f2acadd0947 100644
--- a/src/features/HomeInbox/hiddenWidgets.test.ts
+++ b/src/features/HomeInbox/hiddenWidgets.test.ts
@@ -98,6 +98,29 @@ describe('hasVisibleRailWidget', () => {
it('keeps a column that hosts needs-you and unread on the same hidden set', () => {
expect(hasVisibleRailWidget({ hiddenWidgets: ['running', 'news', 'suggestions'] })).toBe(true);
});
+
+ // The usage widget is a business slot: it must hold the rail open only where
+ // the slot actually renders something, or an OSS page hiding the other rail
+ // widgets would keep an empty rail on screen.
+ it('counts the usage widget only while its slot is active', () => {
+ const everythingElseHidden = {
+ ...railColumn,
+ hiddenWidgets: ['goals', 'running', 'news', 'suggestions'],
+ };
+
+ expect(hasVisibleRailWidget(everythingElseHidden)).toBe(false);
+ expect(hasVisibleRailWidget({ ...everythingElseHidden, usageActive: true })).toBe(true);
+ });
+
+ it('drops the rail once an active usage widget is switched off with the rest', () => {
+ expect(
+ hasVisibleRailWidget({
+ ...railColumn,
+ hiddenWidgets: ['goals', 'running', 'news', 'suggestions', 'usage'],
+ usageActive: true,
+ }),
+ ).toBe(false);
+ });
});
describe('resolveInboxScopeToggleSection', () => {
diff --git a/src/features/HomeInbox/hiddenWidgets.ts b/src/features/HomeInbox/hiddenWidgets.ts
index 33ada34f8f1..9b634e2f719 100644
--- a/src/features/HomeInbox/hiddenWidgets.ts
+++ b/src/features/HomeInbox/hiddenWidgets.ts
@@ -13,6 +13,8 @@ interface ColumnWidgetInput {
hideNeedsYou?: boolean;
hideRunning?: boolean;
hideUnread?: boolean;
+ /** Business-slot widget: only counts once the slot says it exists here. */
+ usageActive?: boolean;
}
export const hasVisibleRailWidget = ({
@@ -20,11 +22,13 @@ export const hasVisibleRailWidget = ({
hideNeedsYou,
hideRunning,
hideUnread,
+ usageActive,
}: ColumnWidgetInput): boolean =>
HOME_INBOX_WIDGET_KEYS.some((key) => {
if (hideNeedsYou && key === 'needsYou') return false;
if (hideRunning && key === 'running') return false;
if (hideUnread && key === 'unread') return false;
+ if (!usageActive && key === 'usage') return false;
return !hiddenWidgets.includes(key);
});
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index 8004eb89ab1..50bc239b307 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -6,6 +6,10 @@ import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { Fragment, memo, type ReactNode, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import {
+ useHomeUsageWidget,
+ useHomeUsageWidgetActive,
+} from '@/business/client/features/HomeUsageWidget';
import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';
import AsyncError from '@/components/AsyncError';
import { BriefCardSkeleton } from '@/features/DailyBrief/BriefCardSkeleton';
@@ -187,6 +191,13 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
const recommendationsVisible = useRecommendationsVisible();
const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);
+ // Business-slot widget: `enabled` false while it's toggled off or its column
+ // isn't on the page, so the slot implementation can skip its fetches.
+ const usageActive = useHomeUsageWidgetActive();
+ const usageNode = useHomeUsageWidget(
+ isLogin === true && usageActive && showRailSections && !hiddenWidgets.includes('usage'),
+ );
+
// A team context is a workspace with more than the viewer in it. In personal
// mode this map is empty, so `isTeam` is false and the whole mine/team layer
// stays dark — the inbox is byte-for-byte the personal one.
@@ -492,15 +503,27 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
});
}
+ // The rail's LAST card, below even the suggestions: usage is passive
+ // reference data, glanceable but never urgent, so it sits under everything
+ // that reports actual work. Same shell as every other rail widget.
+ const usageCard =
+ usageNode &&
+ (isRail ? (
+ <RailCard title={t('inbox.usage.title')}>{usageNode}</RailCard>
+ ) : (
+ <GroupBlock title={t('inbox.usage.title')}>{usageNode}</GroupBlock>
+ ));
+
const visibleSections = filterHiddenWidgetSections(sections, hiddenWidgets);
if (visibleSections.length === 0) {
if (isMain) return null;
if (isRail)
- return recommendationsVisible ? (
+ return recommendationsVisible || usageCard ? (
<Flexbox gap={12}>
- <Recommendations variant={'rail'} />
+ {recommendationsVisible && <Recommendations variant={'rail'} />}
+ {usageCard}
</Flexbox>
) : null;
@@ -514,6 +537,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
<Recommendations />
</Flexbox>
)}
+ {usageCard}
</>
);
}
@@ -584,6 +608,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {
)}
{!isMain && <Recommendations variant={variant} />}
+ {usageCard}
</Flexbox>
);
});
diff --git a/src/features/ResourcePermission/useAgentManagementAccess.ts b/src/features/ResourcePermission/useAgentManagementAccess.ts
index cee02bdeaea..814c10bab55 100644
--- a/src/features/ResourcePermission/useAgentManagementAccess.ts
+++ b/src/features/ResourcePermission/useAgentManagementAccess.ts
@@ -1,7 +1,12 @@
+import { useEffect } from 'react';
+
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
+import { rememberAgentManagementAccess } from '@/helpers/agentManagementAccess';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
/**
* Resolve whether the current caller manages an Agent rather than merely
@@ -23,10 +28,20 @@ export const useAgentManagementAccess = (agentId?: string) => {
isPublicWorkspaceAgent ? agentId : undefined,
);
- return {
- canManageAgent:
- !isAgentLoading &&
- (!isPublicWorkspaceAgent || (isAccessResolved && canEditContent && canManageResource)),
- isAccessLoading: isAgentLoading || (isPublicWorkspaceAgent && (isLoading || !isAccessResolved)),
- };
+ const canManageAgent =
+ !isAgentLoading &&
+ (!isPublicWorkspaceAgent || (isAccessResolved && canEditContent && canManageResource));
+ const isAccessLoading =
+ isAgentLoading || (isPublicWorkspaceAgent && (isLoading || !isAccessResolved));
+
+ // Publish every resolved answer for the runtime resolvers (store actions
+ // can't run this hook) so send/regenerate route with the same
+ // manager-vs-member decision the picker rendered.
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ useEffect(() => {
+ if (!agentId || !currentUserId || isAccessLoading) return;
+ rememberAgentManagementAccess(currentUserId, agentId, canManageAgent);
+ }, [agentId, currentUserId, canManageAgent, isAccessLoading]);
+
+ return { canManageAgent, isAccessLoading };
};
diff --git a/src/helpers/agentManagementAccess.test.ts b/src/helpers/agentManagementAccess.test.ts
new file mode 100644
index 00000000000..1e44215a752
--- /dev/null
+++ b/src/helpers/agentManagementAccess.test.ts
@@ -0,0 +1,124 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ clearAgentManagementAccessCache,
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+ rememberAgentManagementAccess,
+} from './agentManagementAccess';
+
+const getGeneralAccess = vi.hoisted(() => vi.fn());
+
+vi.mock('@/services/resourcePermission', () => ({
+ resourcePermissionService: { getGeneralAccess },
+}));
+
+describe('agentManagementAccess', () => {
+ beforeEach(() => {
+ clearAgentManagementAccessCache();
+ getGeneralAccess.mockReset();
+ });
+
+ it('treats the author as managing without any resolved answer', () => {
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u1' }),
+ ).toBe(true);
+ });
+
+ it('falls back to non-manager for an unresolved non-author', () => {
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(false);
+ });
+
+ it('promotes a non-author once the server confirmed management access', () => {
+ rememberAgentManagementAccess('u2', 'a1', true);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(true);
+ });
+
+ it('keeps a resolved non-manager answer non-managing', () => {
+ rememberAgentManagementAccess('u2', 'a1', false);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(false);
+ });
+
+ it('never lets one user inherit another user’s resolved answer', () => {
+ rememberAgentManagementAccess('u2', 'a1', true);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u3' }),
+ ).toBe(false);
+ });
+
+ it('ignores the cache entirely when the caller is unauthenticated', () => {
+ rememberAgentManagementAccess('u2', 'a1', true);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: undefined }),
+ ).toBe(false);
+ });
+
+ describe('ensureAgentManagementAccess', () => {
+ const publicWorkspaceAgent = {
+ agentId: 'a1',
+ agentUserId: 'u1',
+ currentUserId: 'u2',
+ visibility: 'public' as const,
+ workspaceId: 'ws-1',
+ };
+
+ it('resolves an unprimed non-author from the server before dispatch', async () => {
+ getGeneralAccess.mockResolvedValue({ canManage: true });
+
+ await ensureAgentManagementAccess(publicWorkspaceAgent);
+
+ expect(getGeneralAccess).toHaveBeenCalledWith('agent', 'a1');
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(true);
+ });
+
+ it('skips the request for authors, private agents, and cached entries', async () => {
+ await ensureAgentManagementAccess({ ...publicWorkspaceAgent, currentUserId: 'u1' });
+ await ensureAgentManagementAccess({ ...publicWorkspaceAgent, visibility: 'private' });
+ await ensureAgentManagementAccess({ ...publicWorkspaceAgent, workspaceId: undefined });
+ rememberAgentManagementAccess('u2', 'a1', false);
+ await ensureAgentManagementAccess(publicWorkspaceAgent);
+
+ expect(getGeneralAccess).not.toHaveBeenCalled();
+ });
+
+ it('shares one in-flight request between concurrent dispatches', async () => {
+ let release!: (value: { canManage: boolean }) => void;
+ getGeneralAccess.mockReturnValue(new Promise((resolve) => (release = resolve)));
+
+ const first = ensureAgentManagementAccess(publicWorkspaceAgent);
+ const second = ensureAgentManagementAccess(publicWorkspaceAgent);
+ release({ canManage: true });
+ await Promise.all([first, second]);
+
+ expect(getGeneralAccess).toHaveBeenCalledTimes(1);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(true);
+ });
+
+ it('falls back to authorship and leaves the entry uncached when the fetch fails', async () => {
+ getGeneralAccess.mockRejectedValue(new Error('offline'));
+
+ await ensureAgentManagementAccess(publicWorkspaceAgent);
+
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(false);
+
+ // The next dispatch retries instead of trusting the failure.
+ getGeneralAccess.mockResolvedValue({ canManage: true });
+ await ensureAgentManagementAccess(publicWorkspaceAgent);
+ expect(
+ getRuntimeCanManageAgent({ agentId: 'a1', agentUserId: 'u1', currentUserId: 'u2' }),
+ ).toBe(true);
+ });
+ });
+});
diff --git a/src/helpers/agentManagementAccess.ts b/src/helpers/agentManagementAccess.ts
new file mode 100644
index 00000000000..b7c420510e5
--- /dev/null
+++ b/src/helpers/agentManagementAccess.ts
@@ -0,0 +1,96 @@
+/**
+ * Client-side mirror of the server's management-access decision for an Agent
+ * (`getGeneralAccess().canManage` — its author, or a workspace admin holding
+ * `:all` on the resource; see `isResourceAuthorOrAdmin` on the server).
+ *
+ * The picker UI resolves this through `useAgentManagementAccess` (SWR), but
+ * runtime resolution happens inside store actions where hooks can't run. The
+ * hook publishes every resolved answer here so the send/regenerate/gateway
+ * paths make the SAME manager-vs-member decision the picker made — otherwise a
+ * workspace admin's own `local` pick would be discarded as a member override
+ * under a `fixed` selection policy and the run would silently route to the
+ * gateway or sandbox instead.
+ *
+ * Entries are keyed per user so a stale answer can never leak across an
+ * account switch. When no answer has been resolved yet (e.g. a dispatch path
+ * that never mounted the picker), callers fall back to authorship — the
+ * historical behavior, and the correct one for every non-admin.
+ */
+
+import { resourcePermissionService } from '@/services/resourcePermission';
+
+const resolvedAccess = new Map<string, boolean>();
+const inflight = new Map<string, Promise<void>>();
+
+const cacheKey = (userId: string, agentId: string) => `${userId}:${agentId}`;
+
+/**
+ * Resolve management access from the server before a dispatch that has to
+ * decide manager-vs-member — the cold-load / direct-mention path where the
+ * picker's hook never ran and the cache is still empty. No-ops (and costs no
+ * request) for authors, personal or private agents, unauthenticated callers,
+ * and already-resolved entries; concurrent callers share one in-flight fetch.
+ * A failed fetch is swallowed and left uncached — the caller falls back to
+ * authorship for this run and the next dispatch retries.
+ */
+export const ensureAgentManagementAccess = async (params: {
+ agentId: string;
+ agentUserId?: string | null;
+ currentUserId?: string | null;
+ visibility?: 'private' | 'public';
+ workspaceId?: string | null;
+}): Promise<void> => {
+ const { agentId, agentUserId, currentUserId, visibility, workspaceId } = params;
+ if (!workspaceId || visibility === 'private') return;
+ if (!currentUserId) return;
+ if (!!agentUserId && agentUserId === currentUserId) return;
+
+ const key = cacheKey(currentUserId, agentId);
+ if (resolvedAccess.has(key)) return;
+ const pending = inflight.get(key);
+ if (pending) return pending;
+
+ const request = resourcePermissionService
+ .getGeneralAccess('agent', agentId)
+ .then((access) => {
+ resolvedAccess.set(key, access?.canManage === true);
+ })
+ .catch(() => {})
+ .finally(() => {
+ inflight.delete(key);
+ });
+ inflight.set(key, request);
+ return request;
+};
+
+/** Record a server-resolved management-access answer for this user + agent. */
+export const rememberAgentManagementAccess = (
+ userId: string,
+ agentId: string,
+ canManage: boolean,
+) => {
+ resolvedAccess.set(cacheKey(userId, agentId), canManage);
+};
+
+/**
+ * The management-access decision runtime resolvers should feed
+ * `resolveAgentAgencyConfig` / `resolveAgentModelConfig` as `canManage`.
+ * Authors always manage; otherwise only a server-confirmed `true` (published
+ * by the picker's `useAgentManagementAccess`) promotes the caller to manager.
+ */
+export const getRuntimeCanManageAgent = (params: {
+ agentId: string;
+ agentUserId?: string | null;
+ currentUserId?: string | null;
+}): boolean => {
+ const { agentId, agentUserId, currentUserId } = params;
+ const isAuthor = !!currentUserId && !!agentUserId && agentUserId === currentUserId;
+ if (isAuthor) return true;
+ if (!currentUserId) return false;
+ return resolvedAccess.get(cacheKey(currentUserId, agentId)) === true;
+};
+
+/** Test-only escape hatch so suites don't observe each other's entries. */
+export const clearAgentManagementAccessCache = () => {
+ resolvedAccess.clear();
+};
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 4172f679093..248ca1e3bb4 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -3,6 +3,7 @@ import { RequestTrigger } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
+ canExecutionTargetReadLocalPaths,
type ExecutionPlan,
executionPlanToManifestExecutionEnv,
executionTargetToRuntimeMode,
@@ -1237,3 +1238,36 @@ describe('isLocalSandboxEnabled', () => {
expect(isLocalSandboxEnabled(undefined, 'local')).toBe(false);
});
});
+
+describe('canExecutionTargetReadLocalPaths', () => {
+ it('local runs read this machine directly', () => {
+ expect(canExecutionTargetReadLocalPaths('local', cfg(), 'device-1')).toBe(true);
+ expect(canExecutionTargetReadLocalPaths('local', undefined, undefined)).toBe(true);
+ });
+
+ it('a device run bound to THIS machine reads local paths', () => {
+ expect(
+ canExecutionTargetReadLocalPaths('device', cfg({ boundDeviceId: 'device-1' }), 'device-1'),
+ ).toBe(true);
+ });
+
+ it('a device run bound to ANOTHER machine cannot read paths dragged from here', () => {
+ expect(
+ canExecutionTargetReadLocalPaths('device', cfg({ boundDeviceId: 'device-2' }), 'device-1'),
+ ).toBe(false);
+ });
+
+ it('an unbound device run or unknown current device stays off', () => {
+ expect(canExecutionTargetReadLocalPaths('device', cfg(), 'device-1')).toBe(false);
+ expect(
+ canExecutionTargetReadLocalPaths('device', cfg({ boundDeviceId: 'device-1' }), undefined),
+ ).toBe(false);
+ });
+
+ it('sandbox / auto / none never read the user filesystem', () => {
+ const config = cfg({ boundDeviceId: 'device-1' });
+ expect(canExecutionTargetReadLocalPaths('sandbox', config, 'device-1')).toBe(false);
+ expect(canExecutionTargetReadLocalPaths('auto', config, 'device-1')).toBe(false);
+ expect(canExecutionTargetReadLocalPaths('none', config, 'device-1')).toBe(false);
+ });
+});
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 107ea1eb7de..87ff162a082 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -248,6 +248,24 @@ export const isLocalSandboxEnabled = (
effectiveTarget: DeviceExecutionTarget,
): boolean => effectiveTarget === 'local' && agencyConfig?.localSandbox === true;
+/**
+ * Whether a run resolved to `target` executes somewhere that can read absolute
+ * paths on THIS machine — the gate for inserting `<localFile>` path references
+ * (drag-drop) instead of uploading the file. Only `local` (in-process on this
+ * desktop) or a `device` target whose bound device IS this machine qualifies.
+ * `sandbox` runs in a cloud container where the user's filesystem does not
+ * exist, and `auto` / a foreign `device` may land on another machine — a path
+ * reference dragged from here would be unreadable there, so those runs must
+ * fall back to attachment upload.
+ */
+export const canExecutionTargetReadLocalPaths = (
+ target: DeviceExecutionTarget,
+ agencyConfig: LobeAgentAgencyConfig | undefined,
+ currentDeviceId: string | undefined,
+): boolean =>
+ target === 'local' ||
+ (target === 'device' && !!currentDeviceId && agencyConfig?.boundDeviceId === currentDeviceId);
+
/**
* Derive the `runtimeMode` tool gate from the unified execution target:
* `local` → local-system tools, `sandbox` → cloud sandbox, `device`/`auto` →
diff --git a/src/helpers/localSandbox.ts b/src/helpers/localSandbox.ts
index 35f0c8ec972..f065dd44965 100644
--- a/src/helpers/localSandbox.ts
+++ b/src/helpers/localSandbox.ts
@@ -2,10 +2,12 @@ import { isDesktop } from '@lobechat/const';
import type { LobeAgentAgencyConfig } from '@lobechat/types';
import { resolveAgentAgencyConfig } from '@lobechat/types';
+import { getRuntimeCanManageAgent } from '@/helpers/agentManagementAccess';
import { isLocalSandboxEnabled, resolveExecutionTarget } from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
export interface ClientLocalSandboxDecision {
/** Confine this command (writes scoped to the working directory). */
@@ -38,17 +40,21 @@ const isFenced = (agencyConfig: LobeAgentAgencyConfig | undefined): boolean =>
* it reads the two stores `useEffectiveAgencyConfig` composes: the shared
* `agents.agencyConfig` plus this member's `agentDeviceOverrides` entry, merged
* through the same `resolveAgentAgencyConfig` the picker and server dispatch
- * use — a plain `resolveAgencyConfig` would apply a member override on a
- * private Agent, where every other layer ignores it.
+ * use — a plain `resolveAgencyConfig` would apply an override on a personal
+ * Agent, where every other layer ignores it.
*
- * One input is genuinely unavailable here: `canManage` comes from a permission
- * hook with no store to read synchronously. It only changes the answer for an
- * author/admin of a *public workspace* Agent carrying a stale member override,
- * so rather than guess, both readings are computed and a disagreement resolves
- * toward fencing. Over-fencing fails loudly and recoverably — a write outside
- * the working directory is refused with a clear error — while under-fencing
- * would run unconfined beneath a chip that claims otherwise, which is the one
- * outcome this whole feature exists to prevent.
+ * `canManage` follows the actual management decision the picker resolved
+ * (`getRuntimeCanManageAgent`, published by `useAgentManagementAccess`), so a
+ * fixed-policy manager's Local Sandbox pick — network allowance included — is
+ * honored the way their picker rendered it. The cache can still be cold when
+ * an executor fires before any dispatch resolved access; the fence itself
+ * therefore stays conservative — if EITHER role reading says fenced, the
+ * command is fenced. Over-fencing fails loudly and recoverably — a write
+ * outside the working directory is refused with a clear error — while
+ * under-fencing would run unconfined beneath a chip that claims otherwise,
+ * which is the one outcome this whole feature exists to prevent. The network
+ * relaxation, by contrast, follows only the resolved reading: it widens what
+ * a fenced command can reach, so it must match what the user's picker showed.
*/
export const resolveClientLocalSandbox = (agentId?: string): ClientLocalSandboxDecision => {
if (!isDesktop || !agentId) return unfenced;
@@ -56,24 +62,29 @@ export const resolveClientLocalSandbox = (agentId?: string): ClientLocalSandboxD
const state = useAgentStore.getState();
const sharedAgencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(state);
const agent = agentByIdSelectors.getAgentById(agentId)(state);
- const override = useUserStore.getState().workspaceUserPreference.agentDeviceOverrides?.[agentId];
+ const userState = useUserStore.getState();
+ const override = userState.workspaceUserPreference.agentDeviceOverrides?.[agentId];
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId: userProfileSelectors.userId(userState),
+ });
const context = { visibility: agent?.visibility, workspaceId: agent?.workspaceId ?? undefined };
- const asMember = resolveAgentAgencyConfig(sharedAgencyConfig, override, context);
- const asManager = resolveAgentAgencyConfig(sharedAgencyConfig, override, {
+ const resolved = resolveAgentAgencyConfig(sharedAgencyConfig, override, {
+ ...context,
+ canManage,
+ });
+ const otherRole = resolveAgentAgencyConfig(sharedAgencyConfig, override, {
...context,
- canManage: true,
+ canManage: !canManage,
});
- const fenced = isFenced(asMember) || isFenced(asManager);
+ const fenced = isFenced(resolved) || isFenced(otherRole);
if (!fenced) return unfenced;
- // Network is a relaxation of the fence, so it needs agreement rather than
- // either-or: opening the allowlist on the strength of a reading the user may
- // never have seen would widen what a fenced command can reach.
return {
localSandbox: true,
- localSandboxNetwork:
- asMember?.localSandboxNetwork === true && asManager?.localSandboxNetwork === true,
+ localSandboxNetwork: resolved?.localSandboxNetwork === true,
};
};
diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.ts
index cbb681813a6..d0f91751bff 100644
--- a/src/hooks/useEffectiveAgencyConfig.test.ts
+++ b/src/hooks/useEffectiveAgencyConfig.test.ts
@@ -109,15 +109,18 @@ describe('useEffectiveAgencyConfig', () => {
expect(result.current.workspaceScoped).toBe(true);
});
- it('ignores member overrides and policy while the Workspace Agent is private', () => {
+ // The owner's own `local` / this-machine pick also lives in the per-user
+ // override (the shared row must never reference a personal device — the
+ // server rejects it), so it must merge back even on a private Workspace
+ // Agent, with the member policy stripped for the owner's own surfaces.
+ it("applies the owner's override and strips the policy while the Workspace Agent is private", () => {
setupStores({
agencyConfig: {
- boundDeviceId: 'owner-device',
+ boundDeviceId: 'shared-device',
executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
},
- isLoading: true,
- override: { boundDeviceId: 'member-device', executionTarget: 'local' },
+ override: { boundDeviceId: 'owner-desktop', executionTarget: 'local' },
visibility: 'private',
workspaceId: 'ws-1',
});
@@ -125,7 +128,7 @@ describe('useEffectiveAgencyConfig', () => {
const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
expect(result.current).toEqual({
- agencyConfig: { boundDeviceId: 'owner-device', executionTarget: 'device' },
+ agencyConfig: { boundDeviceId: 'owner-desktop', executionTarget: 'local' },
canDisplayExecutionTarget: true,
canSelectExecutionTarget: true,
isPreferenceLoading: false,
@@ -133,7 +136,21 @@ describe('useEffectiveAgencyConfig', () => {
});
});
- it('ignores member overrides and policy for the author or Workspace admin', () => {
+ it('waits for the preference fetch even when the caller manages the agent', () => {
+ setupStores({
+ agencyConfig: { executionTarget: 'device' },
+ isLoading: true,
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.isPreferenceLoading).toBe(true);
+ expect(result.current.canDisplayExecutionTarget).toBe(false);
+ });
+
+ it("applies the author's or Workspace admin's own override on a public Workspace Agent", () => {
managementAccess.canManageAgent = true;
setupStores({
agencyConfig: {
@@ -141,7 +158,7 @@ describe('useEffectiveAgencyConfig', () => {
executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
},
- override: { boundDeviceId: 'member-device', executionTarget: 'local' },
+ override: { boundDeviceId: 'manager-desktop', executionTarget: 'local' },
visibility: 'public',
workspaceId: 'ws-1',
});
@@ -149,7 +166,7 @@ describe('useEffectiveAgencyConfig', () => {
const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
expect(result.current).toEqual({
- agencyConfig: { boundDeviceId: 'shared-device', executionTarget: 'device' },
+ agencyConfig: { boundDeviceId: 'manager-desktop', executionTarget: 'local' },
canDisplayExecutionTarget: true,
canSelectExecutionTarget: true,
isPreferenceLoading: false,
diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.ts
index 5e2c7255e81..bf503a08f87 100644
--- a/src/hooks/useEffectiveAgencyConfig.ts
+++ b/src/hooks/useEffectiveAgencyConfig.ts
@@ -41,9 +41,11 @@ export interface UseEffectiveAgencyConfigResult {
* Reading the shared row alone shows whichever device landed there (usually
* the creator's machine) instead of this member's choice.
*
- * Personal and Private Workspace Agents have a single owner whose choice IS
- * the shared config, so the override and member policy are applied only for
- * public Workspace Agents — mirroring the write side (`useSelectExecutionTarget`).
+ * The member policy applies only to public Workspace Agents, but the caller's
+ * override merges for every workspace agent: managers and private-agent
+ * owners also keep their `local` / this-machine pick in the override (the
+ * shared row must never reference a personal device) — mirroring the write
+ * side (`useSelectExecutionTarget`).
*
* Self-populates the workspace preference cache (SWR dedupes across callers;
* personal mode short-circuits without a network call).
@@ -78,7 +80,10 @@ export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyCo
visibility: agent?.visibility,
workspaceId: agent?.workspaceId,
});
- const isPreferenceLoading = isAccessLoading || (usesWorkspaceMemberSelection && isLoading);
+ // Managers and private-agent owners also keep their `local` pick in the
+ // per-user override, so any workspace agent must wait for the preference
+ // fetch — not just the member-selection case.
+ const isPreferenceLoading = isAccessLoading || (!!agent?.workspaceId && isLoading);
return {
agencyConfig,
diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsx
index 1e6a0df2421..500a1d80d5c 100644
--- a/src/routes/(main)/agent/features/Conversation/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/index.tsx
@@ -1,20 +1,13 @@
-import { isDesktop } from '@lobechat/const';
import { Flexbox, TooltipGroup } from '@lobehub/ui';
-import React, { memo, Suspense, useCallback } from 'react';
+import React, { memo, Suspense } from 'react';
-import DragUploadZone, { type DroppedLocalPath, useUploadFiles } from '@/components/DragUploadZone';
+import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';
-import { insertLocalPathTags } from '@/features/ChatInput/InputEditor/insertLocalFileTags';
import { useAgentContext } from '@/features/Conversation/useAgentContext';
+import { useLocalPathReference } from '@/features/Conversation/useLocalPathReference';
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
-import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useAgentStore } from '@/store/agent';
-import {
- agentByIdSelectors,
- builtinAgentSelectors,
- chatConfigByIdSelectors,
-} from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
+import { agentByIdSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import ConversationArea from './ConversationArea';
@@ -29,10 +22,6 @@ const ChatConversation = memo(() => {
const { agentId, topicId } = useAgentContext();
const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));
const provider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));
- const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
- const isLocalSystemEnabled = useAgentStore(
- chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),
- );
// Drag-drop upload bypasses the (view-only-disabled) input editor, so the
// drop zone itself follows the same per-resource General-access rules as the
@@ -46,16 +35,7 @@ const ChatConversation = memo(() => {
const { canUseResource } = useResourceAccess('agent', gatedResourceId);
const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
- const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });
-
- const enableLocalPathReference =
- isDesktop && !!workingDirectory && (isHeterogeneous || isLocalSystemEnabled);
-
- const handleLocalPaths = useCallback((paths: DroppedLocalPath[]) => {
- const editor = useChatStore.getState().mainInputEditor?.instance;
- if (!editor) return;
- insertLocalPathTags(editor, paths);
- }, []);
+ const { enableLocalPathReference, handleLocalPaths } = useLocalPathReference(agentId, topicId);
const content = (
<Flexbox flex={1} height={'100%'} style={{ minWidth: 0 }}>
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index 5f484cd1048..c7708ba65ab 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -18,6 +18,7 @@ import {
import debug from 'debug';
import { produce } from 'immer';
+import { getRuntimeCanManageAgent } from '@/helpers/agentManagementAccess';
import { getAgentStoreState } from '@/store/agent';
import {
agentByIdSelectors,
@@ -202,16 +203,23 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
const sharedAgentConfig = agentSelectors.getAgentConfigById(agentId)(agentStoreState);
const agent = agentByIdSelectors.getAgentById(agentId)(agentStoreState);
const currentUserId = userProfileSelectors.userId(useUserStore.getState());
- const isAuthor = !!currentUserId && agent?.userId === currentUserId;
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
+ // server (`isResourceAuthorOrAdmin`) — an admin reads the shared row like
+ // the author does, so client and gateway execution resolve the same config.
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
const isPublicWorkspaceAgent = !!agent?.workspaceId && agent.visibility !== 'private';
// A collaborative builtin has no real author (the row is provisioned by
// whoever opened the feature first), so its *model* stays personal even for
// that member — see `AgentModelConfig.personalModelSelection`. Chat/Agent mode
// keeps the ordinary author rule.
const personalModelSelection = isCollaborativeBuiltinAgentRow(agent ?? {});
- const usesWorkspaceMemberSelection = isPublicWorkspaceAgent && !isAuthor;
+ const usesWorkspaceMemberSelection = isPublicWorkspaceAgent && !canManage;
const memberModelOverride =
- isPublicWorkspaceAgent && (personalModelSelection || !isAuthor)
+ isPublicWorkspaceAgent && (personalModelSelection || !canManage)
? useUserStore.getState().workspaceUserPreference.agentModelOverrides?.[agentId]
: undefined;
const memberModeOverride = usesWorkspaceMemberSelection
@@ -222,7 +230,7 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
...resolveAgentModelConfig(
{
...sharedAgentConfig,
- canManage: isAuthor,
+ canManage,
personalModelSelection,
visibility: agent?.visibility,
workspaceId: agent?.workspaceId,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index fabb3887eb4..536e663464a 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -51,6 +51,11 @@ vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({
executeHeterogeneousAgent: (...args: any[]) => executeHeterogeneousAgentMock(...args),
}));
+const getGeneralAccessMock = vi.hoisted(() => vi.fn());
+vi.mock('@/services/resourcePermission', () => ({
+ resourcePermissionService: { getGeneralAccess: getGeneralAccessMock },
+}));
+
vi.mock('@/services/electron/localFileService', () => ({
localFileService: mockLocalFileService,
}));
@@ -3816,13 +3821,17 @@ describe('ConversationLifecycle actions', () => {
expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();
});
- it('uses the owner target and ignores a retained member override for a private Workspace Agent', async () => {
+ // The owner's own `local` pick lives in the per-user override even on a
+ // private Workspace Agent (the shared row must never reference a
+ // personal device — the server rejects it), so a `local` override must
+ // keep routing the owner's run to the in-process desktop runtime.
+ it("applies the owner's own local override for a private Workspace Agent", async () => {
mockConstEnv.isDesktop = true;
setupMockSelectors({
agentConfig: {
agencyConfig: {
- boundDeviceId: 'owner-device',
- executionTarget: 'local',
+ boundDeviceId: 'shared-workspace-device',
+ executionTarget: 'device',
executionTargetSelectionPolicy: 'fixed',
heterogeneousProvider: { command: 'codex', type: 'codex' },
},
@@ -3833,8 +3842,8 @@ describe('ConversationLifecycle actions', () => {
workspaceUserPreference: {
agentDeviceOverrides: {
[TEST_IDS.SESSION_ID]: {
- boundDeviceId: 'stale-workspace-device',
- executionTarget: 'device',
+ boundDeviceId: 'owner-desktop',
+ executionTarget: 'local',
},
},
},
@@ -3868,6 +3877,146 @@ describe('ConversationLifecycle actions', () => {
expect(executeGatewayAgent).not.toHaveBeenCalled();
});
+ // A workspace admin who is not the author can store a personal `local`
+ // override (the picker and server both recognize management access), and
+ // runtime resolution must honor it even under a `fixed` selection
+ // policy — otherwise the send silently routes to the gateway instead of
+ // the admin's own desktop.
+ it("applies a workspace admin's local override under a fixed selection policy", async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: 'shared-workspace-device',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ },
+ },
+ });
+ const { agentByIdSelectors } = await import('@/store/agent/selectors');
+ vi.spyOn(agentByIdSelectors, 'getAgentById').mockReturnValue(
+ () =>
+ ({ userId: 'author-user', visibility: 'public', workspaceId: 'workspace-1' }) as any,
+ );
+ const { rememberAgentManagementAccess, clearAgentManagementAccessCache } =
+ await import('@/helpers/agentManagementAccess');
+ useUserStore.setState({
+ user: { id: 'admin-user' } as any,
+ workspaceUserPreference: {
+ agentDeviceOverrides: {
+ [TEST_IDS.SESSION_ID]: {
+ boundDeviceId: 'admin-desktop',
+ executionTarget: 'local',
+ },
+ },
+ },
+ });
+ rememberAgentManagementAccess('admin-user', TEST_IDS.SESSION_ID, true);
+
+ const executeGatewayAgent = vi.fn().mockResolvedValue(undefined);
+ act(() => {
+ useChatStore.setState({ executeGatewayAgent });
+ });
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topicId: TEST_IDS.TOPIC_ID,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);
+
+ try {
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: createTestContext(),
+ });
+ });
+
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledTimes(1);
+ expect(executeGatewayAgent).not.toHaveBeenCalled();
+ } finally {
+ clearAgentManagementAccessCache();
+ useUserStore.setState({ user: undefined as any });
+ }
+ });
+
+ // Same scenario on a COLD cache: the picker's hook never ran, so the
+ // send path must resolve management access from the server itself
+ // before choosing a runtime.
+ it("resolves an unprimed admin's access from the server before dispatch", async () => {
+ mockConstEnv.isDesktop = true;
+ setupMockSelectors({
+ agentConfig: {
+ agencyConfig: {
+ boundDeviceId: 'shared-workspace-device',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'fixed',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ },
+ },
+ });
+ const { agentByIdSelectors } = await import('@/store/agent/selectors');
+ vi.spyOn(agentByIdSelectors, 'getAgentById').mockReturnValue(
+ () =>
+ ({ userId: 'author-user', visibility: 'public', workspaceId: 'workspace-1' }) as any,
+ );
+ const { clearAgentManagementAccessCache } = await import('@/helpers/agentManagementAccess');
+ clearAgentManagementAccessCache();
+ getGeneralAccessMock.mockResolvedValue({ canManage: true });
+ useUserStore.setState({
+ user: { id: 'admin-user' } as any,
+ workspaceUserPreference: {
+ agentDeviceOverrides: {
+ [TEST_IDS.SESSION_ID]: {
+ boundDeviceId: 'admin-desktop',
+ executionTarget: 'local',
+ },
+ },
+ },
+ });
+
+ const executeGatewayAgent = vi.fn().mockResolvedValue(undefined);
+ act(() => {
+ useChatStore.setState({ executeGatewayAgent });
+ });
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topicId: TEST_IDS.TOPIC_ID,
+ topics: [],
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);
+
+ try {
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: createTestContext(),
+ });
+ });
+
+ expect(getGeneralAccessMock).toHaveBeenCalledWith('agent', TEST_IDS.SESSION_ID);
+ expect(executeHeterogeneousAgentMock).toHaveBeenCalledTimes(1);
+ expect(executeGatewayAgent).not.toHaveBeenCalled();
+ } finally {
+ clearAgentManagementAccessCache();
+ getGeneralAccessMock.mockReset();
+ useUserStore.setState({ user: undefined as any });
+ }
+ });
+
it('should route new-topic heterogeneous streaming updates to the persisted topic key', async () => {
mockConstEnv.isDesktop = true;
setupMockSelectors({
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index a99b122a237..4de4bc48ba6 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -27,6 +27,10 @@ import { toast } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
import { type ChatInputEditor } from '@/features/ChatInput';
+import {
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+} from '@/helpers/agentManagementAccess';
import {
resolveAgentWorkingDirectory,
resolveAgentWorkingDirectoryConfig,
@@ -407,10 +411,31 @@ export class ConversationLifecycleActionImpl {
}
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
const currentUserId = userProfileSelectors.userId(getUserStoreState());
- const isAuthor = !!currentUserId && agent?.userId === currentUserId;
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and
+ // the server (`isResourceAuthorOrAdmin`) — an admin's own override must
+ // survive a `fixed` selection policy just like the author's does. On a
+ // cold load or a direct mention the picker's hook may never have run, so
+ // resolve access from the server first (no-op for authors and members
+ // whose answer is already cached).
+ await ensureAgentManagementAccess({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ });
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
const usesWorkspaceMemberSelection =
- !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;
- const deviceOverride = usesWorkspaceMemberSelection
+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
+ // Every workspace caller's override matters — a manager's / private owner's
+ // `local` pick also lives in `agentDeviceOverrides` (the shared row must
+ // never reference a personal device); `resolveAgentAgencyConfig` decides
+ // how it applies per role.
+ const deviceOverride = agent?.workspaceId
? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
: undefined;
const workspaceScoped = resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride);
@@ -418,7 +443,7 @@ export class ConversationLifecycleActionImpl {
// switcher. A workspace-local pick is intentionally private to this member
// and is therefore safe to execute in-process on their desktop.
const agencyConfig = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {
- canManage: isAuthor,
+ canManage,
visibility: agent?.visibility,
workspaceId: agent?.workspaceId,
});
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 3c3a136d631..e8fd4e477bb 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -16,6 +16,10 @@ import type {
import { resolveAgentAgencyConfig } from '@lobechat/types';
import { isDesktop } from '@/const/version';
+import {
+ ensureAgentManagementAccess,
+ getRuntimeCanManageAgent,
+} from '@/helpers/agentManagementAccess';
import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';
import {
aiAgentService,
@@ -84,17 +88,37 @@ const resolveDesktopDeviceHints = async (
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
const userState = useUserStore.getState();
const currentUserId = userProfileSelectors.userId(userState);
- const isAuthor = !!currentUserId && agent?.userId === currentUserId;
+ // Author-or-admin, mirroring the picker (`useAgentManagementAccess`) and the
+ // server (`isResourceAuthorOrAdmin`) — an admin's own override must survive
+ // a `fixed` selection policy just like the author's does. Resolve from the
+ // server first when the picker's hook never primed the cache (cold load /
+ // direct mention); no-op for authors and cached answers.
+ await ensureAgentManagementAccess({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ visibility: agent?.visibility,
+ workspaceId: agent?.workspaceId,
+ });
+ const canManage = getRuntimeCanManageAgent({
+ agentId,
+ agentUserId: agent?.userId,
+ currentUserId,
+ });
const usesWorkspaceMemberSelection =
- !!agent?.workspaceId && agent.visibility !== 'private' && !isAuthor;
- const deviceOverride = usesWorkspaceMemberSelection
+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;
+ // Every workspace caller's override matters — a manager's / private owner's
+ // `local` pick also lives in `agentDeviceOverrides` (the shared row must
+ // never reference a personal device); `resolveAgentAgencyConfig` decides how
+ // it applies per role.
+ const deviceOverride = agent?.workspaceId
? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]
: undefined;
const agencyConfig = resolveAgentAgencyConfig(
agentByIdSelectors.getAgencyConfigById(agentId)(agentState),
deviceOverride,
{
- canManage: isAuthor,
+ canManage,
visibility: agent?.visibility,
workspaceId: agent?.workspaceId,
},