🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): pick people when creating a Channel (#22161)
Lobehub Coderdf733c1d21e3
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex 0e82b54cbd3..a9d2872e6da 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -40,10 +40,13 @@ const channelProcedure = wsCompatProcedure.use(serverDatabase).use(async ({ ctx,export const channelRouter = router({...channelHistoryProcedures,+ /** Without a Channel, the people a new Channel in this workspace can start with. */userCandidates: channelProcedure- .input(z.object({ channelId, search: z.string().max(100).optional() }))+ .input(z.object({ channelId: channelId.optional(), search: z.string().max(100).optional() })).query(async ({ ctx, input }) => ({- data: await ctx.channelService.repository.userCandidates(input.channelId, input.search),+ data: input.channelId+ ? await ctx.channelService.repository.userCandidates(input.channelId, input.search)+ : await ctx.channelService.repository.newChannelUserCandidates(input.search),success: true,})),archive: channelProcedure.input(z.object({ channelId })).mutation(async ({ ctx, input }) => {@@ -93,9 +96,10 @@ export const channelRouter = router({create: channelProcedure.input(z.object({- agents: z.array(agentSelection).min(1).max(20),+ agents: z.array(agentSelection).max(20).default([]),projectId: z.string().min(1).optional(),title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength),+ userIds: z.array(z.string().min(1)).max(100).default([]),}),).mutation(async ({ ctx, input }) => ({diff --git a/apps/server/src/services/channel/ChannelService.environment.test.ts b/apps/server/src/services/channel/ChannelService.environment.test.tsindex 04e4f6e4c59..a50f10d13e9 100644--- a/apps/server/src/services/channel/ChannelService.environment.test.ts+++ b/apps/server/src/services/channel/ChannelService.environment.test.ts@@ -147,6 +147,7 @@ describe('changing an Agent member’s channel environment', () => {],projectId: undefined,title: 'c',+ userIds: [],});});diff --git a/apps/server/src/services/channel/ChannelService.members.test.ts b/apps/server/src/services/channel/ChannelService.members.test.tsnew file mode 100644index 00000000000..4cfa668bb65--- /dev/null+++ b/apps/server/src/services/channel/ChannelService.members.test.ts@@ -0,0 +1,53 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ChannelService } from './ChannelService';+import { notifyChannel } from './notify';++const { create, getAgent } = vi.hoisted(() => ({ create: vi.fn(), getAgent: vi.fn() }));+vi.mock('@/database/repositories/channel', async (original) => ({+ ...(await original<object>()),+ ChannelRepository: class {+ create = create;+ },+}));+vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));+vi.mock('@/server/services/agent', () => ({+ AgentService: class {+ getAgentConfigById = getAgent;+ },+}));+vi.mock('@/server/services/file', () => ({ FileService: class {} }));+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));++describe('creating a Channel with people', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ create.mockResolvedValue({ channel: { id: 'chn_1' } });+ getAgent.mockResolvedValue({ model: 'gpt-5' });+ });+ const service = () => new ChannelService({} as never, 'owner', 'workspace');++ it('starts a group with only people and tells them about it', async () => {+ await service().create({ agents: [], title: 'Team', userIds: ['mia'] });+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({ agents: [], title: 'Team', userIds: ['mia'] }),+ );+ expect(notifyChannel).toHaveBeenCalledWith(expect.anything(), 'chn_1');+ });++ it('keeps an Agent-only group quiet beyond its creator', async () => {+ await service().create({ agents: [{ agentId: 'agt_1' }], title: 'Team' });+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ userIds: [] }));+ expect(notifyChannel).not.toHaveBeenCalled();+ });++ it('starts a group with only its creator, without notifying the creator as an invitee', async () => {+ await service().create({ agents: [], title: 'Me', userIds: ['owner'] });+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ agents: [], userIds: [] }));+ expect(notifyChannel).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex bd42a03af7b..851cc5c8a0a 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -125,11 +125,15 @@ export class ChannelService {return { agentId: input.agentId, config, description: input.description, name: input.name };}+ /** A group starts with Agents, workspace people, both, or only its creator. */create = async (input: {agents: ChannelAgentSelection[];projectId?: string;title: string;+ userIds?: string[];}) => {+ // The creator joins as owner anyway; naming them is not an invitation to notify about.+ const userIds = (input.userIds ?? []).filter((id) => id !== this.userId);// The project must be readable in this scope, the same visibility as the project list.if (input.projectId && !(await this.projectModel.findById(input.projectId)))throw new ChannelError('NOT_FOUND', 'Project not found');@@ -137,7 +141,15 @@ export class ChannelService {const agents = await pMap(input.agents, (agent) => this.resolveAgent(agent), {concurrency: 5,});- return this.repository.create({ agents, projectId: input.projectId, title: input.title });+ const access = await this.repository.create({+ agents,+ projectId: input.projectId,+ title: input.title,+ userIds,+ });+ // Invited people see the new Channel without waiting for their next poll.+ if (userIds.length) await this.changed(access.channel.id);+ return access;};/**diff --git a/locales/ar/channel.json b/locales/ar/channel.jsonindex 22b00c86857..14338aba444 100644--- a/locales/ar/channel.json+++ b/locales/ar/channel.json@@ -97,7 +97,6 @@"moveToTrash": "نقل القناة إلى سلة المهملات","moveToTrashConfirm": "نقل “{{title}}” إلى سلة المهملات؟ ستتوقف الردود. يمكنك استعادة القناة وتاريخها من سلة المهملات. سيتم الاحتفاظ بالوكلاء والملفات.","moveToTrashSuccess": "تم نقل القناة إلى سلة المهملات",- "nameAutoPlaceholder": "اتركه فارغًا لتسميته بعد أعضائه","nameOptional": "اسم القناة (اختياري)","noDevice": "لا يوجد جهاز","noDevices": "لا يوجد جهاز متصل. قم بتوصيل جهاز، ثم اختره هنا.",diff --git a/locales/bg-BG/channel.json b/locales/bg-BG/channel.jsonindex e8f15c95712..d6371c3302c 100644--- a/locales/bg-BG/channel.json+++ b/locales/bg-BG/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Преместете канала в кошчето","moveToTrashConfirm": "Преместете „{{title}}“ в кошчето? Отговорите ще спрат. Можете да възстановите канала и неговата история от кошчето. Агенти и файлове ще бъдат запазени.","moveToTrashSuccess": "Каналът е преместен в кошчето",- "nameAutoPlaceholder": "Оставете празно, за да го именувате според неговите членове","nameOptional": "Име на канала (по избор)","noDevice": "Няма устройство","noDevices": "Няма свързано устройство. Свържете едно, след това го изберете тук.",diff --git a/locales/de-DE/channel.json b/locales/de-DE/channel.jsonindex 870a794a905..21c4879f9aa 100644--- a/locales/de-DE/channel.json+++ b/locales/de-DE/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Kanal in den Papierkorb verschieben","moveToTrashConfirm": "„{{title}}“ in den Papierkorb verschieben? Antworten werden gestoppt. Sie können den Kanal und seinen Verlauf aus dem Papierkorb wiederherstellen. Agenten und Dateien bleiben erhalten.","moveToTrashSuccess": "Kanal in den Papierkorb verschoben",- "nameAutoPlaceholder": "Leer lassen, um ihn nach seinen Mitgliedern zu benennen","nameOptional": "Kanalname (optional)","noDevice": "Kein Gerät","noDevices": "Kein Gerät ist verbunden. Verbinden Sie eines und wählen Sie es hier aus.",diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex db7a63a425b..00092639156 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -16,6 +16,7 @@"attachments.failed": "Upload failed. Try again.","attachments.limit": "Attach up to {{count}} files.","attachments.upload": "Attach files",+ "autoTitle.empty": "My Channel","autoTitle.more": "{{names}} and {{count}} more","autoTitle.separator": ", ","blocked.device_approval_pending": "Waiting for device approval",@@ -33,6 +34,7 @@"copyId": "Copy ID","copyIdSuccess": "Channel ID copied","create": "Create channel",+ "create.onlyYou": "Only you for now. Create it and invite members whenever you like.","delete": "Delete Channel","deleteConfirm": "Delete “{{title}}”? This channel will disappear for all its members and can no longer be opened. Running tasks will be requested to stop. Agents and local files will not be deleted.","deleteFailed": "Could not confirm the deletion. Try again.",@@ -106,7 +108,6 @@"moveToTrash": "Move channel to trash","moveToTrashConfirm": "Move “{{title}}” to trash? Replies will stop. You can restore the channel and its history from Trash. Agents and files will be kept.","moveToTrashSuccess": "Channel moved to trash",- "nameAutoPlaceholder": "Leave blank to name it after its members","nameOptional": "Channel name (optional)","noDevice": "No device","noDevices": "No device is connected. Connect one, then choose it here.",@@ -118,6 +119,7 @@"otherAgents": "Other Agents","people.empty": "All available workspace members have joined","people.noMatches": "No matching workspace members",+ "people.noOthers": "No one else is in this workspace yet","people.searchMore": "Showing the first 50 members. Search to find more.","person": "Person","projectAgents": "Project members",diff --git a/locales/es-ES/channel.json b/locales/es-ES/channel.jsonindex 50566267aa8..fdbdb5ef51a 100644--- a/locales/es-ES/channel.json+++ b/locales/es-ES/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Mover canal a la papelera","moveToTrashConfirm": "¿Mover “{{title}}” a la papelera? Las respuestas se detendrán. Puedes restaurar el canal y su historial desde la papelera. Los agentes y archivos se conservarán.","moveToTrashSuccess": "Canal movido a la papelera",- "nameAutoPlaceholder": "Déjalo en blanco para nombrarlo según sus miembros","nameOptional": "Nombre del canal (opcional)","noDevice": "Sin dispositivo","noDevices": "No hay dispositivos conectados. Conecta uno y luego elígelo aquí.",diff --git a/locales/fa-IR/channel.json b/locales/fa-IR/channel.jsonindex 0ca7e0b4f39..609ccf62c91 100644--- a/locales/fa-IR/channel.json+++ b/locales/fa-IR/channel.json@@ -97,7 +97,6 @@"moveToTrash": "انتقال کانال به زبالهدان","moveToTrashConfirm": "آیا میخواهید «{{title}}» را به زبالهدان منتقل کنید؟ پاسخها متوقف خواهند شد. میتوانید کانال و تاریخچه آن را از زبالهدان بازیابی کنید. عوامل و فایلها حفظ خواهند شد.","moveToTrashSuccess": "کانال به زبالهدان منتقل شد",- "nameAutoPlaceholder": "برای نامگذاری بر اساس اعضا خالی بگذارید","nameOptional": "نام کانال (اختیاری)","noDevice": "بدون دستگاه","noDevices": "هیچ دستگاهی متصل نیست. یکی را متصل کرده و سپس اینجا انتخاب کنید.",diff --git a/locales/fr-FR/channel.json b/locales/fr-FR/channel.jsonindex 5fc157b4cc4..d931c312e8b 100644--- a/locales/fr-FR/channel.json+++ b/locales/fr-FR/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Déplacer le canal à la corbeille","moveToTrashConfirm": "Déplacer « {{title}} » à la corbeille ? Les réponses s'arrêteront. Vous pouvez restaurer le canal et son historique depuis la corbeille. Les Agents et les fichiers seront conservés.","moveToTrashSuccess": "Canal déplacé à la corbeille",- "nameAutoPlaceholder": "Laissez vide pour le nommer d'après ses membres","nameOptional": "Nom du canal (optionnel)","noDevice": "Aucun appareil","noDevices": "Aucun appareil n'est connecté. Connectez-en un, puis choisissez-le ici.",diff --git a/locales/it-IT/channel.json b/locales/it-IT/channel.jsonindex 5416ddd9097..c919631bce6 100644--- a/locales/it-IT/channel.json+++ b/locales/it-IT/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Sposta il canale nel cestino","moveToTrashConfirm": "Spostare “{{title}}” nel cestino? Le risposte si fermeranno. Puoi ripristinare il canale e la sua cronologia dal cestino. Gli agenti e i file saranno mantenuti.","moveToTrashSuccess": "Canale spostato nel cestino",- "nameAutoPlaceholder": "Lascia vuoto per nominarlo in base ai suoi membri","nameOptional": "Nome del canale (opzionale)","noDevice": "Nessun dispositivo","noDevices": "Nessun dispositivo è connesso. Connettine uno, quindi sceglilo qui.",diff --git a/locales/ja-JP/channel.json b/locales/ja-JP/channel.jsonindex 85d398f7f50..0c58cfc3778 100644--- a/locales/ja-JP/channel.json+++ b/locales/ja-JP/channel.json@@ -97,7 +97,6 @@"moveToTrash": "チャンネルをゴミ箱に移動","moveToTrashConfirm": "「{{title}}」をゴミ箱に移動しますか?返信は停止します。チャンネルとその履歴はゴミ箱から復元できます。エージェントとファイルは保持されます。","moveToTrashSuccess": "チャンネルがゴミ箱に移動されました",- "nameAutoPlaceholder": "メンバーに基づいて名前を付ける場合は空白のままにしてください","nameOptional": "チャンネル名(任意)","noDevice": "デバイスなし","noDevices": "接続されているデバイスがありません。接続してからここで選択してください。",diff --git a/locales/ko-KR/channel.json b/locales/ko-KR/channel.jsonindex f44ae6b8b74..3f3a8e4fa2e 100644--- a/locales/ko-KR/channel.json+++ b/locales/ko-KR/channel.json@@ -97,7 +97,6 @@"moveToTrash": "채널을 휴지통으로 이동","moveToTrashConfirm": "“{{title}}”을(를) 휴지통으로 이동하시겠습니까? 응답이 중단됩니다. 채널과 기록은 휴지통에서 복원할 수 있습니다. 에이전트와 파일은 유지됩니다.","moveToTrashSuccess": "채널이 휴지통으로 이동되었습니다",- "nameAutoPlaceholder": "멤버를 기준으로 이름을 지정하려면 비워 두세요","nameOptional": "채널 이름 (선택 사항)","noDevice": "기기가 없습니다","noDevices": "연결된 기기가 없습니다. 하나를 연결한 후 여기에서 선택하세요.",diff --git a/locales/nl-NL/channel.json b/locales/nl-NL/channel.jsonindex 5fe90528825..e2007c7bdee 100644--- a/locales/nl-NL/channel.json+++ b/locales/nl-NL/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Kanaal naar prullenbak verplaatsen","moveToTrashConfirm": "“{{title}}” naar prullenbak verplaatsen? Reacties stoppen. Je kunt het kanaal en de geschiedenis herstellen vanuit de prullenbak. Agenten en bestanden blijven behouden.","moveToTrashSuccess": "Kanaal naar prullenbak verplaatst",- "nameAutoPlaceholder": "Laat leeg om het te benoemen naar zijn leden","nameOptional": "Kanaalnaam (optioneel)","noDevice": "Geen apparaat","noDevices": "Geen apparaat is verbonden. Verbind er een en kies het hier.",diff --git a/locales/pl-PL/channel.json b/locales/pl-PL/channel.jsonindex aeeb92648fa..cda41c9be0b 100644--- a/locales/pl-PL/channel.json+++ b/locales/pl-PL/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Przenieś kanał do kosza","moveToTrashConfirm": "Przenieść „{{title}}” do kosza? Odpowiedzi zostaną zatrzymane. Możesz przywrócić kanał i jego historię z Kosza. Agenci i pliki zostaną zachowane.","moveToTrashSuccess": "Kanał przeniesiony do kosza",- "nameAutoPlaceholder": "Pozostaw puste, aby nazwać go po jego członkach","nameOptional": "Nazwa kanału (opcjonalna)","noDevice": "Brak urządzenia","noDevices": "Żadne urządzenie nie jest połączone. Połącz jedno, a następnie wybierz je tutaj.",diff --git a/locales/pt-BR/channel.json b/locales/pt-BR/channel.jsonindex 3d1b058e7b1..409372eec88 100644--- a/locales/pt-BR/channel.json+++ b/locales/pt-BR/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Mover canal para a lixeira","moveToTrashConfirm": "Mover “{{title}}” para a lixeira? Respostas serão interrompidas. Você pode restaurar o canal e seu histórico da lixeira. Agentes e arquivos serão mantidos.","moveToTrashSuccess": "Canal movido para a lixeira",- "nameAutoPlaceholder": "Deixe em branco para nomeá-lo com base em seus membros","nameOptional": "Nome do canal (opcional)","noDevice": "Nenhum dispositivo","noDevices": "Nenhum dispositivo está conectado. Conecte um e escolha-o aqui.",diff --git a/locales/ru-RU/channel.json b/locales/ru-RU/channel.jsonindex 13fa24df005..151a8a884cb 100644--- a/locales/ru-RU/channel.json+++ b/locales/ru-RU/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Переместить канал в корзину","moveToTrashConfirm": "Переместить «{{title}}» в корзину? Ответы будут остановлены. Вы можете восстановить канал и его историю из корзины. Агенты и файлы будут сохранены.","moveToTrashSuccess": "Канал перемещен в корзину",- "nameAutoPlaceholder": "Оставьте пустым, чтобы назвать его по участникам","nameOptional": "Имя канала (необязательно)","noDevice": "Нет устройства","noDevices": "Нет подключенных устройств. Подключите одно, затем выберите его здесь.",diff --git a/locales/tr-TR/channel.json b/locales/tr-TR/channel.jsonindex 3517130f231..ec77d38fadf 100644--- a/locales/tr-TR/channel.json+++ b/locales/tr-TR/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Kanalı çöp kutusuna taşı","moveToTrashConfirm": "“{{title}}” çöp kutusuna taşınsın mı? Yanıtlar duracak. Kanalı ve geçmişini Çöp Kutusu'ndan geri yükleyebilirsiniz. Ajanlar ve dosyalar korunacak.","moveToTrashSuccess": "Kanal çöp kutusuna taşındı",- "nameAutoPlaceholder": "Üyelerine göre adlandırmak için boş bırakın","nameOptional": "Kanal adı (isteğe bağlı)","noDevice": "Cihaz yok","noDevices": "Hiçbir cihaz bağlı değil. Birini bağlayın, ardından burada seçin.",diff --git a/locales/vi-VN/channel.json b/locales/vi-VN/channel.jsonindex 3e0320e5271..692ce355028 100644--- a/locales/vi-VN/channel.json+++ b/locales/vi-VN/channel.json@@ -97,7 +97,6 @@"moveToTrash": "Chuyển kênh vào thùng rác","moveToTrashConfirm": "Chuyển “{{title}}” vào thùng rác? Các trả lời sẽ dừng lại. Bạn có thể khôi phục kênh và lịch sử của nó từ Thùng rác. Các Ajan và tệp sẽ được giữ lại.","moveToTrashSuccess": "Kênh đã được chuyển vào thùng rác",- "nameAutoPlaceholder": "Để trống để đặt tên theo các thành viên","nameOptional": "Tên kênh (tùy chọn)","noDevice": "Không có thiết bị","noDevices": "Không có thiết bị nào được kết nối. Kết nối một thiết bị, sau đó chọn nó ở đây.",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 3ae096250b9..17223c36f96 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -16,6 +16,7 @@"attachments.failed": "上传失败,请重试。","attachments.limit": "最多添加 {{count}} 个附件。","attachments.upload": "添加附件",+ "autoTitle.empty": "我的频道","autoTitle.more": "{{names}} 等 {{total}} 位成员","autoTitle.separator": "、","blocked.device_approval_pending": "等待设备授权",@@ -33,6 +34,7 @@"copyId": "复制 ID","copyIdSuccess": "已复制频道 ID","create": "创建频道",+ "create.onlyYou": "目前只有你。可以先创建,之后随时邀请成员。","delete": "删除频道","deleteConfirm": "删除「{{title}}」后,所有成员都将无法再访问此频道。运行中的任务将被请求停止,Agent 和本地文件不会被删除。","deleteFailed": "未能确认删除结果,请重试。",@@ -106,7 +108,6 @@"moveToTrash": "移至回收站","moveToTrashConfirm": "将「{{title}}」移至回收站?进行中的回复会停止,你可以在回收站恢复频道和历史消息。Agent 和文件将保留。","moveToTrashSuccess": "频道已移至回收站",- "nameAutoPlaceholder": "留空则按成员自动命名","nameOptional": "频道名称(可选)","noDevice": "不使用设备","noDevices": "还没有已连接的设备。连接设备后,再回来选择。",@@ -118,6 +119,7 @@"otherAgents": "其他 Agent","people.empty": "所有可添加的工作区成员均已加入","people.noMatches": "没有匹配的工作区成员",+ "people.noOthers": "工作区里还没有其他成员","people.searchMore": "当前显示前 50 位成员,可通过搜索查找更多。","person": "真人","projectAgents": "项目成员",diff --git a/locales/zh-TW/channel.json b/locales/zh-TW/channel.jsonindex ff53edc1827..fc71945be73 100644--- a/locales/zh-TW/channel.json+++ b/locales/zh-TW/channel.json@@ -97,7 +97,6 @@"moveToTrash": "將頻道移至垃圾桶","moveToTrashConfirm": "將「{{title}}」移至垃圾桶?回覆將停止。您可以從垃圾桶還原頻道及其歷史記錄。代理和檔案將被保留。","moveToTrashSuccess": "頻道已移至垃圾桶",- "nameAutoPlaceholder": "留空以根據成員命名","nameOptional": "頻道名稱(可選)","noDevice": "無裝置","noDevices": "無裝置已連接。連接一個,然後在此選擇。",diff --git a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts b/packages/database/src/repositories/channel/__tests__/userMembers.test.tsindex 7bc9418ab41..423c06bf2ff 100644--- a/packages/database/src/repositories/channel/__tests__/userMembers.test.ts+++ b/packages/database/src/repositories/channel/__tests__/userMembers.test.ts@@ -3,7 +3,7 @@ import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { channelMembers, workspaceMembers } from '../../../schemas';+import { channelMembers, channels, workspaceMembers } from '../../../schemas';import { ChannelRepository } from '..';import { createChannelFixture } from './testUtils';@@ -121,4 +121,79 @@ describe('Channel human membership', () => {});await expect(owner.userCandidates(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });});++ describe('starting a Channel with people', () => {+ it('lists everyone in the workspace except the creator, and adds the chosen people', async () => {+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ expect(await owner.newChannelUserCandidates()).toEqual([+ expect.objectContaining({ userId: fixture.memberId, username: 'mia' }),+ ]);+ expect(await owner.newChannelUserCandidates('nobody')).toEqual([]);++ const { channel } = await owner.create({+ title: 'People',+ userIds: [fixture.memberId, fixture.memberId, fixture.ownerId],+ });+ expect(channel.agentId).toBeNull();+ const members = await db+ .select()+ .from(channelMembers)+ .where(eq(channelMembers.channelId, channel.id));+ expect(members).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ role: 'owner', userId: fixture.ownerId }),+ expect.objectContaining({ role: 'member', status: 'active', userId: fixture.memberId }),+ ]),+ );+ expect(members).toHaveLength(2);+ const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ expect(await member.list()).toEqual([expect.objectContaining({ id: channel.id })]);+ });++ it('starts a group with only its creator, who can invite people later', async () => {+ const { owner, channel } = await create();+ expect(channel.agentId).toBeNull();+ expect(await owner.list()).toEqual([expect.objectContaining({ id: channel.id })]);+ expect((await owner.detail(channel.id)).members).toEqual([+ expect.objectContaining({ role: 'owner', userId: fixture.ownerId }),+ ]);+ await owner.addUser(channel.id, fixture.memberId);+ expect((await owner.detail(channel.id)).members).toHaveLength(2);+ });++ it('creates nothing when a chosen person is outside the workspace', async () => {+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ await expect(+ owner.create({ title: 'People', userIds: [fixture.memberId, 'outside-user'] }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(+ await db.select().from(channels).where(eq(channels.workspaceId, fixture.workspaceId)),+ ).toEqual([]);+ });++ it('keeps people out of personal Channels and direct conversations', async () => {+ const personal = new ChannelRepository(db, fixture.ownerId);+ await expect(personal.newChannelUserCandidates()).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ await expect(+ personal.create({ title: 'Personal', userIds: [fixture.memberId] }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ const { owner, channel } = await create();+ const agent = await fixture.addAgent(channel.id, 'Direct');+ await expect(+ owner.create({ agentId: agent.agentId!, title: 'Direct', userIds: [fixture.memberId] }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('does not list workspace people to someone who has left the workspace', async () => {+ await db+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(eq(workspaceMembers.userId, fixture.ownerId));+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ await expect(owner.newChannelUserCandidates()).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+ });});diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 8f94827739f..9b88f505aad 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -22,7 +22,7 @@ import {} from './agent';import { findThread } from './delivery';import { ChannelError } from './error';-import { addChannelUser, channelUserCandidates } from './people';+import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';import { retryRouting } from './routing';import type { ChannelSendInput } from './send';import { sendMessage } from './send';@@ -83,13 +83,18 @@ export class ChannelRepository {/** Callers check that the project is readable in this scope. */projectId?: string;title: string;+ /** Workspace people a group starts with, checked the same way as adding them later. */+ userIds?: string[];visibility?: ChannelVisibility;}) =>this.db.transaction(async (tx) => {const { agentId } = params;if (agentId !== undefined &&- (!agentId.trim() || params.visibility === 'public' || !!params.agents?.length)+ (!agentId.trim() ||+ params.visibility === 'public' ||+ !!params.agents?.length ||+ !!params.userIds?.length))throw new ChannelError('BAD_REQUEST',@@ -123,8 +128,10 @@ export class ChannelRepository {await addAgentMember(tx, channel, this.userId, { agentId, config: params.agentConfig });for (const agent of params.agents ?? [])await addAgentMember(tx, channel, this.userId, agent);+ const access = { channel, member } satisfies ChannelAccess;+ for (const userId of new Set(params.userIds)) await addChannelUser(tx, access, userId);- return { channel, member } satisfies ChannelAccess;+ return access;});/**@@ -240,6 +247,16 @@ export class ChannelRepository {addUser = async (channelId: string, userId: string) =>this.write(channelId, (tx, access) => addChannelUser(tx, access, userId), { minRole: 'admin' });+ /** People a new Channel in this workspace can start with. */+ newChannelUserCandidates = async (search?: string) => {+ const { workspaceId } = this;+ if (!workspaceId)+ throw new ChannelError('BAD_REQUEST', 'People can only be added to workspace group channels');+ return this.db.transaction((tx) =>+ newChannelUserCandidates(tx, workspaceId, this.userId, search),+ );+ };+userCandidates = async (channelId: string, search?: string) =>this.write(channelId, (tx, access) => channelUserCandidates(tx, access, search), {minRole: 'admin',diff --git a/packages/database/src/repositories/channel/people.ts b/packages/database/src/repositories/channel/people.tsindex a0b4a4b3d92..6bb48c4fef0 100644--- a/packages/database/src/repositories/channel/people.ts+++ b/packages/database/src/repositories/channel/people.ts@@ -1,4 +1,5 @@-import { and, asc, eq, isNull, notExists, or } from 'drizzle-orm';+import type { SQL } from 'drizzle-orm';+import { and, asc, eq, isNull, ne, notExists, or } from 'drizzle-orm';import { channelMembers, users, workspaceMembers } from '../../schemas';import type { Transaction } from '../../type';@@ -35,16 +36,12 @@ const requireGroupWorkspace = async (tx: Transaction, access: ChannelAccess) =>return requireWorkspace(tx, access);};-/**- * Only active people in this workspace; search the full directory, not a client-side page. A- * direct conversation lists them for the group that inviting from it starts.- */-export const channelUserCandidates = async (+const workspaceUserCandidates = (tx: Transaction,- access: ChannelAccess,- search = '',+ workspaceId: string,+ exclude: SQL,+ search: string,) => {- const workspaceId = await requireWorkspace(tx, access);const query = search.trim();return tx.select({@@ -59,18 +56,7 @@ export const channelUserCandidates = async (and(eq(workspaceMembers.workspaceId, workspaceId),isNull(workspaceMembers.deletedAt),- notExists(- tx- .select({ id: channelMembers.id })- .from(channelMembers)- .where(- and(- eq(channelMembers.channelId, access.channel.id),- eq(channelMembers.userId, users.id),- eq(channelMembers.status, 'active'),- ),- ),- ),+ exclude,query? or(ilikeContains(users.fullName, query), ilikeContains(users.username, query)): undefined,@@ -80,6 +66,46 @@ export const channelUserCandidates = async (.limit(50);};+/**+ * Only active people in this workspace; search the full directory, not a client-side page. A+ * direct conversation lists them for the group that inviting from it starts.+ */+export const channelUserCandidates = async (+ tx: Transaction,+ access: ChannelAccess,+ search = '',+) => {+ const workspaceId = await requireWorkspace(tx, access);+ return workspaceUserCandidates(+ tx,+ workspaceId,+ notExists(+ tx+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, access.channel.id),+ eq(channelMembers.userId, users.id),+ eq(channelMembers.status, 'active'),+ ),+ ),+ ),+ search,+ );+};++/** The people a new workspace Channel can start with: everyone active except its creator. */+export const newChannelUserCandidates = async (+ tx: Transaction,+ workspaceId: string,+ userId: string,+ search = '',+) => {+ await requireWorkspaceMember(tx, workspaceId, userId);+ return workspaceUserCandidates(tx, workspaceId, ne(users.id, userId), search);+};+export const addChannelUser = async (tx: Transaction, access: ChannelAccess, userId: string) => {const workspaceId = await requireGroupWorkspace(tx, access);await requireWorkspaceMember(tx, workspaceId, userId);diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 7a0e0f350d9..83185b36d02 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -3,6 +3,7 @@ export default {'people.empty': 'All available workspace members have joined','people.noMatches': 'No matching workspace members',+ 'people.noOthers': 'No one else is in this workspace yet','people.searchMore': 'Showing the first 50 members. Search to find more.','receipt.errorReason': 'Failure reason','receipt.errorUnavailable':@@ -10,6 +11,7 @@ export default {'title': 'Channels','create': 'Create channel','submit': 'Create',+ 'create.onlyYou': 'Only you for now. Create it and invite members whenever you like.','agents': 'Agents','otherAgents': 'Other Agents','projectAgents': 'Project members',@@ -134,6 +136,7 @@ export default {'activity.many': '{{count}} members are replying…','activity.one': '{{name}} · {{status}}','activity.two': '{{names}} are replying…',+ 'autoTitle.empty': 'My Channel','autoTitle.more': '{{names}} and {{count}} more','autoTitle.separator': ', ','environment.editNamed': 'Change where {{name}} runs',@@ -149,7 +152,6 @@ export default {'failure.locate': 'Show message','failure.messageLabel': 'Reply failed: {{names}}','failure.title': 'Failed replies · {{count}}',- 'nameAutoPlaceholder': 'Leave blank to name it after its members','nameOptional': 'Channel name (optional)','rename': 'Rename channel','renameFailed': 'Could not rename the channel. Try again.',diff --git a/src/features/Channels/CreateChannel/MemberSelection.tsx b/src/features/Channels/CreateChannel/MemberSelection.tsxindex f9306e441c7..454ab2f2d60 100644--- a/src/features/Channels/CreateChannel/MemberSelection.tsx+++ b/src/features/Channels/CreateChannel/MemberSelection.tsx@@ -68,12 +68,15 @@ const AgentOptionRow = ({* offer people, so inviting anyone happens in one place with one search.*/export const MemberSelection = ({+ emptyHint,exclude = [],options,people,value,onChange,}: {+ /** What an empty selection means, when submitting it is allowed. */+ emptyHint?: string;/** Agents already in the Channel. */exclude?: string[];onChange: Dispatch<SetStateAction<ChannelAgentDraft[]>>;@@ -112,24 +115,27 @@ export const MemberSelection = ({return (<Flexbox gap={12}>- <AsyncBoundary- data={agents}- error={options.error}- isLoading={!agents && !options.error}- onRetry={options.retry}- >- <div {...stylex.props(styles.picker)}>- <Flexbox gap={8} {...stylex.props(styles.pane)}>- <SearchBar- allowClear- autoFocus- placeholder={t(people ? 'invite.search' : 'searchAgents')}- value={search}- variant="filled"- onChange={(event) => setSearch(event.target.value)}- />- <Flexbox gap={people || priority.length ? 8 : 0} {...stylex.props(styles.pane)}>- {people && <PeopleOptions people={people} search={search} />}+ <div {...stylex.props(styles.picker)}>+ <Flexbox gap={8} {...stylex.props(styles.pane)}>+ <SearchBar+ allowClear+ autoFocus+ placeholder={t(people ? 'invite.search' : 'searchAgents')}+ value={search}+ variant="filled"+ onChange={(event) => setSearch(event.target.value)}+ />+ <Flexbox gap={people || priority.length ? 8 : 0} {...stylex.props(styles.pane)}>+ {people && <PeopleOptions people={people} search={search} />}+ {people && !agents && <SectionTitle>{t('agents')}</SectionTitle>}+ {/* People load on their own, so an Agent-list failure must not take them down. */}+ <AsyncBoundary+ data={agents}+ error={options.error}+ errorVariant={people ? 'inline' : 'block'}+ isLoading={!agents && !options.error}+ onRetry={options.retry}+ >{priority.length > 0 && (<Flexbox gap={2}><SectionTitle>{t('projectAgents')}</SectionTitle>@@ -142,7 +148,7 @@ export const MemberSelection = ({)}{others.length ? (others.map(renderAgent)- ) : priority.length ? null : people ? (+ ) : priority.length ? null : people?.channelId ? (<Text fontSize={12} type="secondary" {...stylex.props(styles.section)}>{t(search.trim() ? 'invite.noAgentMatches' : 'invite.noAgents')}</Text>@@ -150,52 +156,54 @@ export const MemberSelection = ({<AgentSelectionEmpty search={!!search.trim()} variant="noAvailable" />)}</Flexbox>- </Flexbox>+ </AsyncBoundary></Flexbox>- <Flexbox gap={8} {...stylex.props(styles.pane, styles.selected)}>- <Text fontSize={12} type="secondary">- {t('memberSelection.selectedAgents', { ns: 'chat', count: selectedCount })}- </Text>- {!selectedCount &&- (people ? (- <Text fontSize={12} type="secondary" {...stylex.props(styles.section)}>- {t('invite.noSelected')}- </Text>- ) : (- <AgentSelectionEmpty variant="noSelected" />- ))}- {people?.value.map((person) => (- <SelectedPerson- key={person.userId}- person={person}- onRemove={() =>- people.onChange((current) =>- current.filter((item) => item.userId !== person.userId),- )- }- />- ))}- {!!devices.error && (- <AsyncError- error={devices.error}- retrying={devices.isValidating}- title={t('environment.devicesFailed')}- variant="inline"- onRetry={() => void devices.mutate()}- />- )}- {value.map((draft) => (- <SelectedAgent- agent={agents?.find((agent) => agent.id === draft.agentId)}- devices={devices}- draft={draft}- key={draft.agentId}- setDrafts={onChange}- />+ </Flexbox>+ <Flexbox gap={8} {...stylex.props(styles.pane, styles.selected)}>+ <Text fontSize={12} type="secondary">+ {t('memberSelection.selectedAgents', { ns: 'chat', count: selectedCount })}+ </Text>+ {!selectedCount &&+ (emptyHint ? (+ <AgentSelectionEmpty description={emptyHint} />+ ) : people ? (+ <Text fontSize={12} type="secondary" {...stylex.props(styles.section)}>+ {t('invite.noSelected')}+ </Text>+ ) : (+ <AgentSelectionEmpty variant="noSelected" />))}- </Flexbox>- </div>- </AsyncBoundary>+ {people?.value.map((person) => (+ <SelectedPerson+ key={person.userId}+ person={person}+ onRemove={() =>+ people.onChange((current) =>+ current.filter((item) => item.userId !== person.userId),+ )+ }+ />+ ))}+ {!!devices.error && (+ <AsyncError+ error={devices.error}+ retrying={devices.isValidating}+ title={t('environment.devicesFailed')}+ variant="inline"+ onRetry={() => void devices.mutate()}+ />+ )}+ {value.map((draft) => (+ <SelectedAgent+ agent={agents?.find((agent) => agent.id === draft.agentId)}+ devices={devices}+ draft={draft}+ key={draft.agentId}+ setDrafts={onChange}+ />+ ))}+ </Flexbox>+ </div></Flexbox>);};diff --git a/src/features/Channels/CreateChannel/PeopleOptions.tsx b/src/features/Channels/CreateChannel/PeopleOptions.tsxindex 96b4445ded8..9f36018b07f 100644--- a/src/features/Channels/CreateChannel/PeopleOptions.tsx+++ b/src/features/Channels/CreateChannel/PeopleOptions.tsx@@ -17,7 +17,8 @@ import { pickerStyles } from './pickerStyles';const CANDIDATE_LIMIT = 50;export interface PeopleSelection {- channelId: string;+ /** Unset while creating a Channel: every workspace member except the creator. */+ channelId?: string;onChange: Dispatch<SetStateAction<ChannelPersonOption[]>>;value: ChannelPersonOption[];}@@ -59,7 +60,7 @@ export const PeopleOptions = ({ people, search }: { people: PeopleSelection; seaisLoading={isLoading}empty={<Text fontSize={12} type="secondary" {...stylex.props(pickerStyles.section)}>- {t(query ? 'people.noMatches' : 'people.empty')}+ {t(query ? 'people.noMatches' : people.channelId ? 'people.empty' : 'people.noOthers')}</Text>}onRetry={() => void mutate()}diff --git a/src/features/Channels/CreateChannel/agentEnvironment.test.ts b/src/features/Channels/CreateChannel/agentEnvironment.test.tsindex 8fc128430b7..16df54d4e50 100644--- a/src/features/Channels/CreateChannel/agentEnvironment.test.ts+++ b/src/features/Channels/CreateChannel/agentEnvironment.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';import type { ChannelAgentEnvironment } from './agentEnvironment';import {canSubmitChannelAgents,+ canSubmitChannelMembers,changeChannelAgentDevice,createChannelAgentSelection,getChannelAgentIssue,@@ -279,3 +280,21 @@ describe('Channel Agent submission guard', () => {);});});++describe('Channel member submission guard', () => {+ const ready = { agentId: 'native', initialized: true };+ const pending = { agentId: 'pi', initialized: true, issue: 'deviceRequired' as const };++ it('creates a Channel with only its creator, people only, or ready Agents', () => {+ expect(canSubmitChannelMembers([], { creating: true, people: 0 })).toBe(true);+ expect(canSubmitChannelMembers([], { creating: true, people: 2 })).toBe(true);+ expect(canSubmitChannelMembers([ready], { creating: true, people: 0 })).toBe(true);+ expect(canSubmitChannelMembers([ready, pending], { creating: true, people: 1 })).toBe(false);+ });++ it('requires an invitation to add someone', () => {+ expect(canSubmitChannelMembers([], { creating: false, people: 0 })).toBe(false);+ expect(canSubmitChannelMembers([], { creating: false, people: 1 })).toBe(true);+ expect(canSubmitChannelMembers([pending], { creating: false, people: 1 })).toBe(false);+ });+});diff --git a/src/features/Channels/CreateChannel/agentEnvironment.ts b/src/features/Channels/CreateChannel/agentEnvironment.tsindex 67d6eca74f5..65615a18556 100644--- a/src/features/Channels/CreateChannel/agentEnvironment.ts+++ b/src/features/Channels/CreateChannel/agentEnvironment.ts@@ -126,6 +126,15 @@ export const reconcileChannelAgentDraft = (export const canSubmitChannelAgents = (agents: ChannelAgentDraft[]) =>agents.length > 0 && agents.every((agent) => agent.initialized && !agent.issue);+/**+ * Every chosen Agent must be ready to run. A new Channel may start with only its creator, while+ * an invitation has to add someone.+ */+export const canSubmitChannelMembers = (+ agents: ChannelAgentDraft[],+ { creating, people }: { creating: boolean; people: number },+) => (!agents.length || canSubmitChannelAgents(agents)) && (creating || agents.length + people > 0);+/** Only send the channel-local choices, never form state or Agent configuration. */export const toChannelAgentSelection = (draft: ChannelAgentDraft): ChannelAgentSelection => {const { initialized: _initialized, issue: _issue, ...selection } = draft;diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsxindex 5800b63ad0d..25cab6c4650 100644--- a/src/features/Channels/CreateChannel/index.tsx+++ b/src/features/Channels/CreateChannel/index.tsx@@ -5,12 +5,13 @@ import { Hash } from 'lucide-react';import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import type { ChannelPersonOption } from '@/services/channel';import { channelActions } from '@/store/channel';import type { ChannelAgentDraft } from './agentEnvironment';-import { canSubmitChannelAgents, toChannelAgentSelection } from './agentEnvironment';+import { canSubmitChannelMembers, toChannelAgentSelection } from './agentEnvironment';import { defaultChannelTitle } from './channelTitle';import { MemberSelection } from './MemberSelection';import { usePersonName } from './PeopleOptions';@@ -56,7 +57,7 @@ export const openInviteMembers = (existing: ExistingChannel, onCreated?: (id: st/*** Like starting a group chat: choose members first. The name is optional and defaults to the* members' names; the sidebar renames it later. Inviting into an existing Channel uses the- * same picker without a name, and also lists workspace members in workspace Channels.+ * same picker without a name. Workspace Channels, new or existing, also list workspace members.*/function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {const { t } = useTranslation('channel');@@ -69,6 +70,9 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {const options = useChannelAgentOptions(existing ? undefined : projectId);const direct = existing?.directAgentName !== undefined;const nameOf = usePersonName();+ const activeWorkspaceId = useActiveWorkspaceId();+ // People join only workspace Channels: a new one is created in the active workspace.+ const canPickPeople = existing ? !!existing.workspaceId : !!activeWorkspaceId;const dirty = !!title.trim() || agents.length > 0 || people.length > 0;// A mask click must not drop what the user typed or picked; ✕ and Esc still close.@@ -82,17 +86,22 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {t('unnamedAgent'),),);- const autoTitle = defaultChannelTitle(- direct- ? [existing?.directAgentName || t('unnamedAgent'), ...agentNames, ...people.map(nameOf)]- : agentNames,- {- more: (names, count, total) => t('autoTitle.more', { count, names, total }),- separator: t('autoTitle.separator'),- },- CHANNEL_LIMITS.titleLength,- );- const canSubmit = canSubmitChannelAgents(agents) || (!agents.length && people.length > 0);+ // A Channel with no one else in it yet still needs a name the sidebar can show.+ const autoTitle =+ defaultChannelTitle(+ direct+ ? [existing?.directAgentName || t('unnamedAgent'), ...agentNames, ...people.map(nameOf)]+ : [...agentNames, ...people.map(nameOf)],+ {+ more: (names, count, total) => t('autoTitle.more', { count, names, total }),+ separator: t('autoTitle.separator'),+ },+ CHANNEL_LIMITS.titleLength,+ ) || t('autoTitle.empty');+ const canSubmit = canSubmitChannelMembers(agents, {+ creating: !existing,+ people: people.length,+ });const submit = async () => {if (busy || !canSubmit) return;@@ -120,6 +129,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {agents: selections,projectId,title: title.trim() || autoTitle,+ userIds: people.map((person) => person.userId),});close();onCreated?.(id);@@ -141,12 +151,13 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {)}<Flexbox gap={8} inert={busy}><MemberSelection+ emptyHint={existing ? undefined : t('create.onlyYou')}exclude={existing?.agentIds}options={options}value={agents}people={- existing?.workspaceId- ? { channelId: existing.id, onChange: setPeople, value: people }+ canPickPeople+ ? { channelId: existing?.id, onChange: setPeople, value: people }: undefined}onChange={setAgents}@@ -160,7 +171,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {<Inputid="channel-title"maxLength={CHANNEL_LIMITS.titleLength}- placeholder={autoTitle || t('nameAutoPlaceholder')}+ placeholder={autoTitle}prefix={<Icon icon={Hash} size={14} />}value={title}onChange={(event) => setTitle(event.target.value)}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 94672807785..edad258995e 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -49,7 +49,8 @@ export const channelKeys = {),userCandidates: def('channel:userCandidates',- (channelId: string, search: string) => ['channel:userCandidates', channelId, search] as const,+ (channelId: string | undefined, search: string) =>+ ['channel:userCandidates', channelId ?? null, search] as const,),};diff --git a/src/services/channel.ts b/src/services/channel.tsindex b7ebd4897d0..d9821236c0b 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -34,12 +34,17 @@ class ChannelService {lambdaClient.channel.rename.mutate({ channelId, title });addUser = (channelId: string, userId: string) =>lambdaClient.channel.addUser.mutate({ channelId, userId });- userCandidates = async (channelId: string, search: string) =>+ /** Without a Channel, the people a new Channel in the active workspace can start with. */+ userCandidates = async (channelId: string | undefined, search: string) =>(await lambdaClient.channel.userCandidates.query({ channelId, search })).data;addAgent = (channelId: string, agent: ChannelAgentSelection) =>lambdaClient.channel.addAgent.mutate({ agent, channelId });- create = (input: { agents: ChannelAgentSelection[]; projectId?: string; title: string }) =>- lambdaClient.channel.create.mutate(input);+ create = (input: {+ agents: ChannelAgentSelection[];+ projectId?: string;+ title: string;+ userIds?: string[];+ }) => lambdaClient.channel.create.mutate(input);createGroupFromDirect = (input: {agents: ChannelAgentSelection[];channelId: string;diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 546ea930680..7d29da72bcc 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -23,7 +23,7 @@ export const CHANNEL_IDLE_REFRESH_MS = 60_000;class ChannelActionImpl {readonly #private = new ChannelPrivateAction(useChannelStore.setState, useChannelStore.getState);- useFetchUserCandidates = (channelId: string, search: string) =>+ useFetchUserCandidates = (channelId: string | undefined, search: string) =>useClientDataSWR(channelKeys.userCandidates(channelId, search), () =>channelService.userCandidates(channelId, search),);