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(channel): inherit each Agent's device and directory when creating a channel (#21782)

AmAzing-82cadfc010d5
diff --git a/apps/server/src/services/channel/ChannelService.environment.test.ts b/apps/server/src/services/channel/ChannelService.environment.test.ts
index 8f2ba206c31..f3e9a6a1791 100644
--- a/apps/server/src/services/channel/ChannelService.environment.test.ts
+++ b/apps/server/src/services/channel/ChannelService.environment.test.ts
@@ -3,21 +3,32 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChannelService } from './ChannelService';
-const { agentEnvironment, getAgent, findDevice, notify, statPath, update, wake } = vi.hoisted(
- () => ({
- agentEnvironment: vi.fn(),
- findDevice: vi.fn(),
- getAgent: vi.fn(),
- notify: vi.fn(),
- statPath: vi.fn(),
- update: vi.fn(),
- wake: vi.fn(),
- }),
-);
+const {
+ agentEnvironment,
+ create,
+ getAgent,
+ findDevice,
+ notify,
+ querySystemInfo,
+ statPath,
+ update,
+ wake,
+} = vi.hoisted(() => ({
+ agentEnvironment: vi.fn(),
+ create: vi.fn(),
+ findDevice: vi.fn(),
+ getAgent: vi.fn(),
+ notify: vi.fn(),
+ querySystemInfo: vi.fn(),
+ statPath: vi.fn(),
+ update: vi.fn(),
+ wake: vi.fn(),
+}));
vi.mock('@/database/repositories/channel', async (original) => ({
...(await original<object>()),
ChannelRepository: class {
agentEnvironment = agentEnvironment;
+ create = create;
updateAgentEnvironment = update;
},
}));
@@ -31,7 +42,9 @@ vi.mock('@/server/services/agent', () => ({
getAgentConfigById = getAgent;
},
}));
-vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: { statPath } }));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { queryDeviceSystemInfo: querySystemInfo, statPath },
+}));
vi.mock('@/server/services/file', () => ({ FileService: class {} }));
vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));
vi.mock('./notify', () => ({ notifyChannel: notify }));
@@ -77,4 +90,33 @@ describe('changing an Agent member’s channel environment', () => {
expect(wake).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
+
+ it('creates a member in the device home folder when the Agent has no directory there', async () => {
+ querySystemInfo.mockResolvedValue({ homePath: '/Users/me' });
+ statPath.mockResolvedValue({ canonicalPath: '/Users/me', isDirectory: true });
+
+ await service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' });
+
+ expect(querySystemInfo).toHaveBeenCalledWith('owner', 'mac', undefined);
+ expect(statPath).toHaveBeenCalledWith(expect.objectContaining({ path: '/Users/me' }));
+ expect(create).toHaveBeenCalledWith({
+ agents: [
+ {
+ agentId: 'agent-1',
+ config: { deviceId: 'mac', deviceOwnerId: 'owner', workingDirectory: '/Users/me' },
+ },
+ ],
+ projectId: undefined,
+ title: 'c',
+ });
+ });
+
+ it('still asks for a directory when the device cannot report its home folder', async () => {
+ querySystemInfo.mockResolvedValue(undefined);
+
+ await expect(
+ service().create({ agents: [{ agentId: 'agent-1', deviceId: 'mac' }], title: 'c' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(create).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index e2c55709d7e..0c363541cae 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -70,11 +70,17 @@ export class ChannelService {
'BAD_REQUEST',
'Native Channel execution is not supported on Windows devices yet',
);
- if (!input.workingDirectory?.trim())
+ // An Agent without its own directory on this device runs in the device's home folder,
+ // the same fallback an ordinary conversation uses.
+ const workingDirectory =
+ input.workingDirectory?.trim() ||
+ (await deviceGateway.queryDeviceSystemInfo(this.userId, input.deviceId, this.workspaceId))
+ ?.homePath;
+ if (!workingDirectory)
throw new ChannelError('BAD_REQUEST', 'Choose a working directory for this device');
const path = await deviceGateway.statPath({
deviceId: input.deviceId,
- path: input.workingDirectory,
+ path: workingDirectory,
userId: this.userId,
workspaceId: this.workspaceId,
});
diff --git a/locales/ar/channel.json b/locales/ar/channel.json
index 46b3362359d..22b00c86857 100644
--- a/locales/ar/channel.json
+++ b/locales/ar/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "هذا الوكيل لم يعد متاحًا. قم بإزالته واختر آخر.",
"environment.checkingDevice": "جارٍ التحقق من الحالة",
"environment.chooseDevice": "اختر جهازًا",
- "environment.completeRequired": "أكمل الإعدادات المميزة قبل المتابعة.",
"environment.configurationFailed": "تعذر تحميل إعدادات هذا الوكيل. حاول مرة أخرى.",
"environment.configurationLoading": "جارٍ تحميل إعدادات هذا الوكيل…",
"environment.defaultsHint": "يستخدم كل وكيل جهازه الخاص ودليل العمل الخاص به. يمكنك تغييرها لهذه القناة لاحقًا من قائمة الأعضاء.",
diff --git a/locales/bg-BG/channel.json b/locales/bg-BG/channel.json
index c397b25f0fb..e8f15c95712 100644
--- a/locales/bg-BG/channel.json
+++ b/locales/bg-BG/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Този агент вече не е наличен. Премахнете го и изберете друг.",
"environment.checkingDevice": "Проверка на състоянието",
"environment.chooseDevice": "Изберете устройство",
- "environment.completeRequired": "Завършете маркираните настройки преди да продължите.",
"environment.configurationFailed": "Не може да се заредят настройките на този агент. Опитайте отново.",
"environment.configurationLoading": "Зареждане на настройките на този агент…",
"environment.defaultsHint": "Всеки агент използва собствено устройство и работна директория. Можете да ги промените за този канал по-късно от списъка с членове.",
diff --git a/locales/de-DE/channel.json b/locales/de-DE/channel.json
index aea292ba0cf..870a794a905 100644
--- a/locales/de-DE/channel.json
+++ b/locales/de-DE/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Dieser Agent ist nicht mehr verfügbar. Entfernen Sie ihn und wählen Sie einen anderen.",
"environment.checkingDevice": "Status wird überprüft",
"environment.chooseDevice": "Gerät auswählen",
- "environment.completeRequired": "Vervollständigen Sie die hervorgehobenen Einstellungen, bevor Sie fortfahren.",
"environment.configurationFailed": "Die Einstellungen dieses Agenten konnten nicht geladen werden. Versuchen Sie es erneut.",
"environment.configurationLoading": "Einstellungen dieses Agenten werden geladen…",
"environment.defaultsHint": "Jeder Agent verwendet sein eigenes Gerät und Arbeitsverzeichnis. Sie können diese später für diesen Kanal in der Mitgliederliste ändern.",
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index e9263cf40ba..316a23a9c10 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "This Agent is no longer available. Remove it and choose another.",
"environment.checkingDevice": "Checking status",
"environment.chooseDevice": "Choose a device",
- "environment.completeRequired": "Complete the highlighted settings before continuing.",
"environment.configurationFailed": "Could not load this Agent’s settings. Try again.",
"environment.configurationLoading": "Loading this Agent’s settings…",
"environment.defaultsHint": "Each Agent uses its own device and working directory. You can change them for this channel later from the member list.",
@@ -63,7 +62,11 @@
"environment.directoryUnavailable": "Could not verify the directory. Check the device connection and choose the directory again.",
"environment.editNamed": "Change where {{name}} runs",
"environment.executionRequired": "Choose an online device and working directory for every coding Agent.",
+ "environment.inherited.deviceOffline": "This Agent’s device is offline. Reconnect the device, or remove the Agent.",
+ "environment.inherited.deviceRequired": "This coding Agent has no default device. Choose one in its settings, or remove the Agent.",
+ "environment.inherited.deviceUnavailable": "This Agent’s device is unavailable in the current space. Change it in the Agent’s settings, or remove the Agent.",
"environment.permissionRequired": "You do not have permission to save these members. Check channel and Agent access.",
+ "environment.resolveRequired": "Resolve the issues shown under the selected Agents first.",
"environment.saveFailed": "Could not save channel members. Your choices are preserved; try again.",
"environment.saved": "Runtime environment updated",
"environment.scopeHint": "Applies only to this channel. Replies already running keep their environment, and the Agent’s own settings stay unchanged.",
diff --git a/locales/es-ES/channel.json b/locales/es-ES/channel.json
index 6bcc95301a8..50566267aa8 100644
--- a/locales/es-ES/channel.json
+++ b/locales/es-ES/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Este agente ya no está disponible. Elimínalo y elige otro.",
"environment.checkingDevice": "Comprobando estado",
"environment.chooseDevice": "Elegir un dispositivo",
- "environment.completeRequired": "Completa la configuración resaltada antes de continuar.",
"environment.configurationFailed": "No se pudieron cargar los ajustes de este agente. Inténtalo de nuevo.",
"environment.configurationLoading": "Cargando los ajustes de este agente…",
"environment.defaultsHint": "Cada agente utiliza su propio dispositivo y directorio de trabajo. Puedes cambiarlos para este canal más tarde desde la lista de miembros.",
diff --git a/locales/fa-IR/channel.json b/locales/fa-IR/channel.json
index 34bd4872a1d..0ca7e0b4f39 100644
--- a/locales/fa-IR/channel.json
+++ b/locales/fa-IR/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "این عامل دیگر در دسترس نیست. آن را حذف کرده و عامل دیگری انتخاب کنید.",
"environment.checkingDevice": "در حال بررسی وضعیت",
"environment.chooseDevice": "انتخاب دستگاه",
- "environment.completeRequired": "تنظیمات برجسته‌شده را قبل از ادامه تکمیل کنید.",
"environment.configurationFailed": "تنظیمات این عامل بارگذاری نشد. دوباره تلاش کنید.",
"environment.configurationLoading": "در حال بارگذاری تنظیمات این عامل…",
"environment.defaultsHint": "هر عامل از دستگاه و دایرکتوری کاری خود استفاده می‌کند. می‌توانید بعداً آن‌ها را از لیست اعضا برای این کانال تغییر دهید.",
diff --git a/locales/fr-FR/channel.json b/locales/fr-FR/channel.json
index c884889ec34..5fc157b4cc4 100644
--- a/locales/fr-FR/channel.json
+++ b/locales/fr-FR/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Cet Agent n'est plus disponible. Supprimez-le et choisissez-en un autre.",
"environment.checkingDevice": "Vérification du statut",
"environment.chooseDevice": "Choisir un appareil",
- "environment.completeRequired": "Complétez les paramètres surlignés avant de continuer.",
"environment.configurationFailed": "Impossible de charger les paramètres de cet Agent. Réessayez.",
"environment.configurationLoading": "Chargement des paramètres de cet Agent…",
"environment.defaultsHint": "Chaque Agent utilise son propre appareil et répertoire de travail. Vous pouvez les modifier pour ce canal plus tard depuis la liste des membres.",
diff --git a/locales/it-IT/channel.json b/locales/it-IT/channel.json
index 052040f600c..5416ddd9097 100644
--- a/locales/it-IT/channel.json
+++ b/locales/it-IT/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Questo agente non è più disponibile. Rimuovilo e scegline un altro.",
"environment.checkingDevice": "Verifica dello stato",
"environment.chooseDevice": "Scegli un dispositivo",
- "environment.completeRequired": "Completa le impostazioni evidenziate prima di continuare.",
"environment.configurationFailed": "Impossibile caricare le impostazioni di questo agente. Riprova.",
"environment.configurationLoading": "Caricamento delle impostazioni di questo agente…",
"environment.defaultsHint": "Ogni agente utilizza il proprio dispositivo e directory di lavoro. Puoi cambiarli per questo canale in seguito dalla lista dei membri.",
diff --git a/locales/ja-JP/channel.json b/locales/ja-JP/channel.json
index 54762bb0cd5..85d398f7f50 100644
--- a/locales/ja-JP/channel.json
+++ b/locales/ja-JP/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "このエージェントは利用できなくなりました。削除して別のエージェントを選択してください。",
"environment.checkingDevice": "ステータスを確認中",
"environment.chooseDevice": "デバイスを選択",
- "environment.completeRequired": "続行する前に、ハイライトされた設定を完了してください。",
"environment.configurationFailed": "このエージェントの設定を読み込めませんでした。もう一度お試しください。",
"environment.configurationLoading": "このエージェントの設定を読み込み中…",
"environment.defaultsHint": "各エージェントは独自のデバイスと作業ディレクトリを使用します。後でメンバーリストからこれらを変更できます。",
diff --git a/locales/ko-KR/channel.json b/locales/ko-KR/channel.json
index 1007dc19378..f44ae6b8b74 100644
--- a/locales/ko-KR/channel.json
+++ b/locales/ko-KR/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "이 에이전트는 더 이상 사용 가능하지 않습니다. 제거하고 다른 에이전트를 선택하세요.",
"environment.checkingDevice": "상태 확인 중",
"environment.chooseDevice": "기기 선택",
- "environment.completeRequired": "계속하기 전에 강조 표시된 설정을 완료하세요.",
"environment.configurationFailed": "이 에이전트의 설정을 로드할 수 없습니다. 다시 시도하세요.",
"environment.configurationLoading": "이 에이전트의 설정을 로드 중…",
"environment.defaultsHint": "각 에이전트는 자체 기기와 작업 디렉토리를 사용합니다. 나중에 멤버 목록에서 이를 변경할 수 있습니다.",
diff --git a/locales/nl-NL/channel.json b/locales/nl-NL/channel.json
index f0e7fff995d..5fe90528825 100644
--- a/locales/nl-NL/channel.json
+++ b/locales/nl-NL/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Deze Agent is niet langer beschikbaar. Verwijder deze en kies een andere.",
"environment.checkingDevice": "Status controleren",
"environment.chooseDevice": "Kies een apparaat",
- "environment.completeRequired": "Voltooi de gemarkeerde instellingen voordat je doorgaat.",
"environment.configurationFailed": "Kon de instellingen van deze Agent niet laden. Probeer het opnieuw.",
"environment.configurationLoading": "Instellingen van deze Agent laden…",
"environment.defaultsHint": "Elke Agent gebruikt zijn eigen apparaat en werkmap. Je kunt deze later wijzigen voor dit kanaal vanuit de ledenlijst.",
diff --git a/locales/pl-PL/channel.json b/locales/pl-PL/channel.json
index f08969694b5..aeeb92648fa 100644
--- a/locales/pl-PL/channel.json
+++ b/locales/pl-PL/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Ten Agent nie jest już dostępny. Usuń go i wybierz innego.",
"environment.checkingDevice": "Sprawdzanie statusu",
"environment.chooseDevice": "Wybierz urządzenie",
- "environment.completeRequired": "Uzupełnij podświetlone ustawienia przed kontynuowaniem.",
"environment.configurationFailed": "Nie udało się załadować ustawień tego Agenta. Spróbuj ponownie.",
"environment.configurationLoading": "Ładowanie ustawień tego Agenta…",
"environment.defaultsHint": "Każdy Agent używa własnego urządzenia i działającego katalogu. Możesz je zmienić dla tego kanału później z listy członków.",
diff --git a/locales/pt-BR/channel.json b/locales/pt-BR/channel.json
index b0b6d4106c0..3d1b058e7b1 100644
--- a/locales/pt-BR/channel.json
+++ b/locales/pt-BR/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Este Agente não está mais disponível. Remova-o e escolha outro.",
"environment.checkingDevice": "Verificando status",
"environment.chooseDevice": "Escolher um dispositivo",
- "environment.completeRequired": "Complete as configurações destacadas antes de continuar.",
"environment.configurationFailed": "Não foi possível carregar as configurações deste Agente. Tente novamente.",
"environment.configurationLoading": "Carregando as configurações deste Agente…",
"environment.defaultsHint": "Cada Agente usa seu próprio dispositivo e diretório de trabalho. Você pode alterá-los para este canal mais tarde na lista de membros.",
diff --git a/locales/ru-RU/channel.json b/locales/ru-RU/channel.json
index 1a6bbf10d79..13fa24df005 100644
--- a/locales/ru-RU/channel.json
+++ b/locales/ru-RU/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Этот агент больше недоступен. Удалите его и выберите другого.",
"environment.checkingDevice": "Проверка статуса",
"environment.chooseDevice": "Выберите устройство",
- "environment.completeRequired": "Завершите выделенные настройки перед продолжением.",
"environment.configurationFailed": "Не удалось загрузить настройки этого агента. Попробуйте еще раз.",
"environment.configurationLoading": "Загрузка настроек этого агента…",
"environment.defaultsHint": "Каждый агент использует свое устройство и рабочую директорию. Вы можете изменить их для этого канала позже из списка участников.",
diff --git a/locales/tr-TR/channel.json b/locales/tr-TR/channel.json
index 2bebf2c8252..3517130f231 100644
--- a/locales/tr-TR/channel.json
+++ b/locales/tr-TR/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Bu Ajan artık kullanılamıyor. Kaldırın ve başka birini seçin.",
"environment.checkingDevice": "Durum kontrol ediliyor",
"environment.chooseDevice": "Bir cihaz seçin",
- "environment.completeRequired": "Devam etmeden önce vurgulanan ayarları tamamlayın.",
"environment.configurationFailed": "Bu Ajanın ayarları yüklenemedi. Tekrar deneyin.",
"environment.configurationLoading": "Bu Ajanın ayarları yükleniyor…",
"environment.defaultsHint": "Her Ajan kendi cihazını ve çalışma dizinini kullanır. Bunları daha sonra üye listesinden bu kanal için değiştirebilirsiniz.",
diff --git a/locales/vi-VN/channel.json b/locales/vi-VN/channel.json
index 470e7109655..3e0320e5271 100644
--- a/locales/vi-VN/channel.json
+++ b/locales/vi-VN/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "Ajan này không còn khả dụng. Hãy xóa nó và chọn một Ajan khác.",
"environment.checkingDevice": "Đang kiểm tra trạng thái",
"environment.chooseDevice": "Chọn một thiết bị",
- "environment.completeRequired": "Hoàn thành các cài đặt được đánh dấu trước khi tiếp tục.",
"environment.configurationFailed": "Không thể tải cài đặt của Ajan này. Thử lại.",
"environment.configurationLoading": "Đang tải cài đặt của Ajan này…",
"environment.defaultsHint": "Mỗi Ajan sử dụng thiết bị và thư mục làm việc riêng. Bạn có thể thay đổi chúng cho kênh này sau từ danh sách thành viên.",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index ca1895381da..21b5f5317a6 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "此 Agent 已不可用,请移除后选择其他 Agent。",
"environment.checkingDevice": "正在确认状态",
"environment.chooseDevice": "选择设备",
- "environment.completeRequired": "请先补齐成员下方提示的配置。",
"environment.configurationFailed": "未能读取此 Agent 的配置,请重试。",
"environment.configurationLoading": "正在读取 Agent 配置…",
"environment.defaultsHint": "默认沿用各 Agent 自己的设备和工作目录,之后可在成员列表里为本频道单独修改。",
@@ -63,7 +62,11 @@
"environment.directoryUnavailable": "无法验证工作目录,请检查设备连接并重新选择目录。",
"environment.editNamed": "修改 {{name}} 的运行环境",
"environment.executionRequired": "请为每位编程 Agent 选择在线设备和工作目录。",
+ "environment.inherited.deviceOffline": "此 Agent 的设备已离线,请重新连接设备,或移除此 Agent。",
+ "environment.inherited.deviceRequired": "此编程 Agent 还没有默认设备,请先在它的设置里选择设备,或移除此 Agent。",
+ "environment.inherited.deviceUnavailable": "当前空间无法使用此 Agent 的设备,请在它的设置里更换设备,或移除此 Agent。",
"environment.permissionRequired": "你无权保存这些成员,请检查频道和 Agent 的访问权限。",
+ "environment.resolveRequired": "请先处理成员下方提示的问题。",
"environment.saveFailed": "未能保存频道成员,已保留你的选择,请重试。",
"environment.saved": "运行环境已更新",
"environment.scopeHint": "只对本频道生效。进行中的回复继续使用原环境,Agent 自身的设置不会改变。",
diff --git a/locales/zh-TW/channel.json b/locales/zh-TW/channel.json
index 9ad51a8e5fe..ff53edc1827 100644
--- a/locales/zh-TW/channel.json
+++ b/locales/zh-TW/channel.json
@@ -48,7 +48,6 @@
"environment.agentUnavailable": "此代理已不可用。移除它並選擇其他代理。",
"environment.checkingDevice": "正在檢查狀態",
"environment.chooseDevice": "選擇裝置",
- "environment.completeRequired": "完成高亮顯示的設置後才能繼續。",
"environment.configurationFailed": "無法加載此代理的設置。請再試一次。",
"environment.configurationLoading": "正在加載此代理的設置…",
"environment.defaultsHint": "每個代理使用其自己的裝置和工作目錄。您可以稍後從成員列表中更改它們。",
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 1a87de58baa..ef51ab4abfe 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -19,7 +19,6 @@ export default {
'This Agent is no longer available. Remove it and choose another.',
'environment.checkingDevice': 'Checking status',
'environment.chooseDevice': 'Choose a device',
- 'environment.completeRequired': 'Complete the highlighted settings before continuing.',
'environment.configurationFailed': 'Could not load this Agent’s settings. Try again.',
'environment.configurationLoading': 'Loading this Agent’s settings…',
'environment.defaultsHint':
@@ -34,12 +33,19 @@ export default {
'environment.devicesLoading': 'Checking device status…',
'environment.directoryLabel': 'Working directory for {{name}}',
'environment.directoryRequired': 'Choose a working directory on this device.',
+ 'environment.inherited.deviceOffline':
+ 'This Agent’s device is offline. Reconnect the device, or remove the Agent.',
+ 'environment.inherited.deviceRequired':
+ 'This coding Agent has no default device. Choose one in its settings, or remove the Agent.',
+ 'environment.inherited.deviceUnavailable':
+ 'This Agent’s device is unavailable in the current space. Change it in the Agent’s settings, or remove the Agent.',
'environment.directoryUnavailable':
'Could not verify the directory. Check the device connection and choose the directory again.',
'environment.executionRequired':
'Choose an online device and working directory for every coding Agent.',
'environment.permissionRequired':
'You do not have permission to save these members. Check channel and Agent access.',
+ 'environment.resolveRequired': 'Resolve the issues shown under the selected Agents first.',
'environment.saveFailed':
'Could not save channel members. Your choices are preserved; try again.',
'environment.signInRequired': 'Sign in again before saving channel members.',
diff --git a/src/features/Channels/CreateChannel/EnvironmentFields.tsx b/src/features/Channels/CreateChannel/EnvironmentFields.tsx
index c79acadb7f1..fed3969e2ea 100644
--- a/src/features/Channels/CreateChannel/EnvironmentFields.tsx
+++ b/src/features/Channels/CreateChannel/EnvironmentFields.tsx
@@ -8,36 +8,22 @@ import AsyncError from '@/components/AsyncError';
import { openPickWorkingDirModal } from '@/features/WorkingDirectory';
import type { DeviceListResult } from '@/store/device/useDeviceList';
-import type { ChannelAgentDraft, ChannelAgentIssue } from './agentEnvironment';
+import type { ChannelAgentIssue } from './agentEnvironment';
import type { useChannelAgentDraft } from './useChannelAgentDraft';
const styles = stylex.create({
directory: { maxWidth: '100%', overflow: 'hidden' },
});
-/** Issues the user resolves by choosing a device or directory, not by waiting. */
-const INPUT_ISSUES = new Set<ChannelAgentIssue>([
- 'deviceOffline',
- 'deviceRequired',
- 'deviceUnavailable',
- 'directoryRequired',
-]);
+/** Device issues of an inherited environment are fixed in the Agent's settings, not here. */
+const INHERITED_ISSUES = ['deviceOffline', 'deviceRequired', 'deviceUnavailable'] as const;
-export const needsEnvironmentInput = (issue?: ChannelAgentIssue) =>
- !!issue && INPUT_ISSUES.has(issue);
+const isInheritedIssue = (issue: ChannelAgentIssue): issue is (typeof INHERITED_ISSUES)[number] =>
+ (INHERITED_ISSUES as readonly ChannelAgentIssue[]).includes(issue);
export const deviceLabel = (device: DeviceListItem) =>
device.friendlyName || device.hostname || device.deviceId;
-/** Where an Agent runs, in one line: `device · directory`. */
-export const environmentSummary = (draft: ChannelAgentDraft, devices: DeviceListResult) => {
- if (!draft.deviceId) return;
- const device = devices.data?.find((item) => item.deviceId === draft.deviceId);
- return [device ? deviceLabel(device) : draft.deviceId, draft.workingDirectory]
- .filter(Boolean)
- .join(' · ');
-};
-
type DraftControls = ReturnType<typeof useChannelAgentDraft>;
/** Device and working directory for one Agent in one Channel. */
@@ -115,8 +101,11 @@ export const EnvironmentFields = ({
/** Why an Agent cannot be saved yet, or that its settings are still loading. */
export const EnvironmentIssue = ({
controls: { draft, retry, sync },
+ inherited,
}: {
controls: DraftControls;
+ /** The Agent's own device and directory apply; there is nothing to pick here. */
+ inherited?: boolean;
}) => {
const { t } = useTranslation('channel');
if (draft.issue === 'configurationFailed')
@@ -138,7 +127,9 @@ export const EnvironmentIssue = ({
role="status"
type={checking ? 'secondary' : 'danger'}
>
- {t(`environment.${draft.issue}`)}
+ {inherited && isInheritedIssue(draft.issue)
+ ? t(`environment.inherited.${draft.issue}`)
+ : t(`environment.${draft.issue}`)}
</Text>
);
};
diff --git a/src/features/Channels/CreateChannel/SelectedAgent.tsx b/src/features/Channels/CreateChannel/SelectedAgent.tsx
index 7f83c06837e..99f93f2221a 100644
--- a/src/features/Channels/CreateChannel/SelectedAgent.tsx
+++ b/src/features/Channels/CreateChannel/SelectedAgent.tsx
@@ -3,19 +3,13 @@ import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import { X } from 'lucide-react';
import type { Dispatch, SetStateAction } from 'react';
-import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import AgentAvatar from '@/components/AgentAvatar';
import type { DeviceListResult } from '@/store/device/useDeviceList';
import type { ChannelAgentDraft } from './agentEnvironment';
-import {
- EnvironmentFields,
- EnvironmentIssue,
- environmentSummary,
- needsEnvironmentInput,
-} from './EnvironmentFields';
+import { EnvironmentIssue } from './EnvironmentFields';
import { useChannelAgentDraft } from './useChannelAgentDraft';
import type { ChannelAgentOption } from './useChannelAgentOptions';
@@ -23,9 +17,13 @@ const styles = stylex.create({
extra: { paddingInlineStart: 44, paddingInlineEnd: 8, paddingBlockEnd: 8, minWidth: 0 },
});
+/** Channel options for a chosen Agent: inherit its own device and directory, never pick here. */
+const INHERITED = { directoryOptional: true };
+
/**
- * A chosen Agent keeps its own device and directory, shown as one line. Fields appear only
- * when the Agent cannot run without a choice; per-channel changes happen after creation.
+ * A chosen Agent keeps its own device and directory without showing them: nothing here can
+ * change them, so only what blocks creation appears. Per-channel changes happen after
+ * creation, from the member list.
*/
export const SelectedAgent = ({
agent,
@@ -39,13 +37,9 @@ export const SelectedAgent = ({
setDrafts: Dispatch<SetStateAction<ChannelAgentDraft[]>>;
}) => {
const { t } = useTranslation(['channel', 'chat']);
- const controls = useChannelAgentDraft(input, devices, setDrafts);
+ const controls = useChannelAgentDraft(input, devices, setDrafts, INHERITED);
const { draft } = controls;
- // Once the user starts fixing the environment, keep the fields until the row is removed.
- const [editing, setEditing] = useState(false);
const name = agentDisplayName(agent, t('unnamedAgent'));
- const showFields = draft.initialized && (editing || needsEnvironmentInput(draft.issue));
- const summary = !showFields && !draft.issue ? environmentSummary(draft, devices) : undefined;
return (
<Flexbox gap={4}>
@@ -71,31 +65,9 @@ export const SelectedAgent = ({
}
/>
</Flexbox>
- {(showFields || summary || draft.issue) && (
+ {draft.issue && (
<Flexbox gap={8} {...stylex.props(styles.extra)}>
- {summary && (
- <Text ellipsis fontSize={12} title={summary} type="secondary">
- {summary}
- </Text>
- )}
- {showFields && (
- <EnvironmentFields
- devices={devices}
- name={name}
- controls={{
- ...controls,
- change: (patch) => {
- setEditing(true);
- controls.change(patch);
- },
- changeDevice: (deviceId) => {
- setEditing(true);
- controls.changeDevice(deviceId);
- },
- }}
- />
- )}
- <EnvironmentIssue controls={controls} />
+ <EnvironmentIssue inherited controls={controls} />
</Flexbox>
)}
</Flexbox>
diff --git a/src/features/Channels/CreateChannel/agentEnvironment.test.ts b/src/features/Channels/CreateChannel/agentEnvironment.test.ts
index 02588958bdf..8fc128430b7 100644
--- a/src/features/Channels/CreateChannel/agentEnvironment.test.ts
+++ b/src/features/Channels/CreateChannel/agentEnvironment.test.ts
@@ -219,6 +219,32 @@ describe('Channel Agent submission guard', () => {
}
});
+ it('accepts an inherited device without a directory, but not a missing or offline device', () => {
+ const inherited = { directoryOptional: true };
+ const draft = reconcileChannelAgentDraft(
+ { agentId: 'native', initialized: false },
+ environment({ agencyConfig: { boundDeviceId: 'bound', executionTarget: 'device' } }),
+ undefined,
+ inherited,
+ );
+ expect(draft).toMatchObject({ deviceId: 'bound', initialized: true, issue: undefined });
+ expect(canSubmitChannelAgents([draft])).toBe(true);
+ expect(
+ getChannelAgentIssue(
+ { agentId: 'codex' },
+ environment({ agencyConfig: undefined, model: 'codex' }),
+ inherited,
+ ),
+ ).toBe('deviceRequired');
+ expect(
+ getChannelAgentIssue(
+ { agentId: 'pi', deviceId: 'bound' },
+ environment({ devices: [device('bound', { online: false })] }),
+ inherited,
+ ),
+ ).toBe('deviceOffline');
+ });
+
it.each([
[{ devicesConfirmed: false }, 'devicesLoading'],
[{ devicesError: new Error('refresh failed') }, 'devicesFailed'],
diff --git a/src/features/Channels/CreateChannel/agentEnvironment.ts b/src/features/Channels/CreateChannel/agentEnvironment.ts
index 43bd3e980ca..e5268f6121a 100644
--- a/src/features/Channels/CreateChannel/agentEnvironment.ts
+++ b/src/features/Channels/CreateChannel/agentEnvironment.ts
@@ -64,9 +64,15 @@ export const createChannelAgentSelection = (
return { agentId, deviceId, workingDirectory: getDeviceDirectory(deviceId, environment) };
};
+export interface ChannelAgentIssueOptions {
+ /** Inherited defaults may omit the directory; the server then uses the device's home folder. */
+ directoryOptional?: boolean;
+}
+
export const getChannelAgentIssue = (
selection: ChannelAgentSelection,
environment: ChannelAgentEnvironment,
+ { directoryOptional }: ChannelAgentIssueOptions = {},
): ChannelAgentIssue | undefined => {
const runtime = getRuntime(environment);
if (!isChannelRuntime(runtime)) return 'unsupportedRuntime';
@@ -78,7 +84,7 @@ export const getChannelAgentIssue = (
return 'deviceUnavailable';
if (device.onlineUnknown) return 'devicesLoading';
if (!device.online) return 'deviceOffline';
- if (!selection.workingDirectory?.trim()) return 'directoryRequired';
+ if (!directoryOptional && !selection.workingDirectory?.trim()) return 'directoryRequired';
};
export const changeChannelAgentDevice = (
@@ -96,6 +102,7 @@ export const reconcileChannelAgentDraft = (
draft: ChannelAgentDraft,
environment: ChannelAgentEnvironment,
sourceIssue?: ChannelAgentIssue,
+ options?: ChannelAgentIssueOptions,
): ChannelAgentDraft => {
let next = draft;
let issue = sourceIssue;
@@ -108,7 +115,7 @@ export const reconcileChannelAgentDraft = (
next = { ...draft, ...selection, initialized: true };
}
}
- issue ??= getChannelAgentIssue(next, environment);
+ issue ??= getChannelAgentIssue(next, environment, options);
}
return next === draft && draft.issue === issue ? draft : { ...next, issue };
};
diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsx
index f967e0252dc..baf03109018 100644
--- a/src/features/Channels/CreateChannel/index.tsx
+++ b/src/features/Channels/CreateChannel/index.tsx
@@ -148,7 +148,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
<Flexbox horizontal align="center" gap={8} justify="flex-end">
{agents.length > 0 && !canSubmit && (
<Text fontSize={12} type="secondary">
- {t('environment.completeRequired')}
+ {t('environment.resolveRequired')}
</Text>
)}
<Button disabled={busy} onClick={close}>
diff --git a/src/features/Channels/CreateChannel/useChannelAgentDraft.ts b/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
index 35c6ca268f8..fbc92445b83 100644
--- a/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
+++ b/src/features/Channels/CreateChannel/useChannelAgentDraft.ts
@@ -11,6 +11,7 @@ import type {
ChannelAgentDraft,
ChannelAgentEnvironment,
ChannelAgentIssue,
+ ChannelAgentIssueOptions,
} from './agentEnvironment';
import {
changeChannelAgentDevice,
@@ -22,6 +23,7 @@ export const useChannelAgentDraft = (
draft: ChannelAgentDraft,
devices: DeviceListResult,
setDrafts: Dispatch<SetStateAction<ChannelAgentDraft[]>>,
+ options?: ChannelAgentIssueOptions,
) => {
const { agentId } = draft;
const sync = useAgentStore((s) => s.useHydrateAgentConfig)(true, agentId);
@@ -51,7 +53,7 @@ export const useChannelAgentDraft = (
: !confirmed || !agent || isPreferenceLoading
? 'configurationLoading'
: undefined;
- const resolved = reconcileChannelAgentDraft(draft, environment, sourceIssue);
+ const resolved = reconcileChannelAgentDraft(draft, environment, sourceIssue, options);
// This is a form snapshot, not another fetch/cache. Removing and re-adding an
// Agent creates a new draft; an effect from its previous mount cannot overwrite it.
@@ -68,7 +70,7 @@ export const useChannelAgentDraft = (
'deviceId' in patch
? { ...item, ...changeChannelAgentDevice(item, patch.deviceId, environment) }
: { ...item, ...patch };
- return { ...next, issue: getChannelAgentIssue(next, environment) };
+ return { ...next, issue: getChannelAgentIssue(next, environment, options) };
}),
);
};