Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
New room: check an existing channel's id, explain a refused one, start again on another app
Simon Flack310934c1c2c3
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.tsindex e3c6e168a..39f00a3d0 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.test.ts@@ -150,6 +150,26 @@ describe('createRoomOnServer', () => {await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toMatchObject({ kind: 'error' });});+ it('says the messaging app refused when the server reports a bridge operation failure', async () => {+ fetchMock.mockResolvedValue(response(502, { detail: 'channel_not_found' }));++ await expect(createRoomOnServer(SERVER, PARAMS)).resolves.toEqual({+ kind: 'error',+ message: 'The messaging app could not make the room: channel_not_found',+ });+ });++ it('explains a fault on an existing channel in terms of the id that was typed', async () => {+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));++ const result = await createRoomOnServer(SERVER, {+ ...PARAMS,+ channel: { kind: 'existing', externalChannelId: 'C0123ABCD' },+ });+ expect(result).toMatchObject({ kind: 'invalid' });+ expect(result.kind === 'invalid' && result.message).toMatch(/Check the id/);+ });+it('rethrows a server fault rather than flattening it into a form error', async () => {fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.tsindex 4683c08a5..1fc29a59d 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-room.ts@@ -22,12 +22,15 @@ function isBridgeFailure(detail: string): boolean {return /bridge/i.test(detail) && /not running|unavailable|not found/i.test(detail);}+const EXISTING_CHANNEL_REFUSED =+ 'Switch couldn’t use that channel. Check the id, that the Switch app is in the channel, and that no other room already uses it.';+/*** Create a room on `server` and map recoverable gateway failures onto a typed* {@link CreateRoomResult}, so the modal can name what went wrong instead of* surfacing a raw status line — or worse, appearing to do nothing.*- * Unmapped failures still throw: an unexpected 500 is a bug, not a form error,+ * Unmapped failures still throw: any other unexpected 500 is a bug, not a form error,* and should reach the logs rather than be flattened into the same inline* message as a typo in the room name.*/@@ -56,6 +59,17 @@ export async function createRoomOnServer(? { kind: 'bridge-unavailable', message }: { kind: 'invalid', message };}+ // The messaging app turned the request down (`BridgeOperationError`).+ if (cause.kind === 'http' && cause.status === 502)+ return {+ kind: 'error',+ message: `The messaging app could not make the room: ${cause.detail ?? cause.message}`,+ };+ // A named channel the server cannot use fails as a fault rather than a+ // 400: an id the app does not know, a channel its bot is not in, or one+ // another room already uses. Said so, since Console is where the id was typed.+ if (cause.kind === 'http' && cause.status === 500 && params.channel?.kind === 'existing')+ return { kind: 'invalid', message: EXISTING_CHANNEL_REFUSED };if (cause.kind === 'network') return { kind: 'error', message: cause.message };}throw cause;diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsxindex bf9c18702..c54941406 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx@@ -193,7 +193,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({startingAgentState !== 'pending' &&!nowhere &&canCreate({ name }) &&- (selectedBridge === null || roomOptionsReady(roomOptions)) &&+ (selectedBridge === null || roomOptionsReady(roomOptions, selectedBridge.type)) &&!isSubmitting;async function handleSubmit() {@@ -419,6 +419,10 @@ export const CreateRoomModal = observer(function CreateRoomModal({onChange={(next) => {setWhere(next);setError(null);+ // A channel, and above all a typed id, belongs to the app it was+ // chosen for: another app starts again from a new public channel.+ if (next !== where)+ setOptions((now) => ({ ...now, channel: DEFAULT_ROOM_OPTIONS.channel }));// A bridged room starts with agents only.if (next !== SWITCH_CONSOLE)changePicks(shownPicked.filter((each) => each.kind === 'agent'));diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-options.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-options.tsxindex abb2f324e..81cad988f 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-options.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/create-room-options.tsx@@ -15,7 +15,7 @@ import {} from '@renderer/lib/ui/select';import { cn } from '@renderer/utils/utils';import type { RemoteBridge, RoomAccess } from '@shared/core/switch-servers/switch-servers';-import { type ChannelChoice, channelChoiceCards } from './room-channel-choices';+import { type ChannelChoice, channelChoiceCards, channelIdProblem } from './room-channel-choices';import type { RoomCreateOptions } from './room-create-request';const NO_GROUP = '__none__';@@ -80,17 +80,7 @@ export function RoomChannelField({))}</div>{value.channel.kind === 'existing' && (- <Input- aria-label="Channel id"- placeholder="The channel’s id"- value={value.channel.externalChannelId}- onChange={(event) =>- onChange({- ...value,- channel: { kind: 'existing', externalChannelId: event.target.value },- })- }- />+ <ExistingChannelId bridge={bridge} value={value} onChange={onChange} />)}<span className="text-xs text-foreground-muted">Console can’t move a room to another channel later.@@ -99,6 +89,36 @@ export function RoomChannelField({);}+function ExistingChannelId({+ bridge,+ value,+ onChange,+}: {+ bridge: RemoteBridge;+ value: RoomCreateOptions;+ onChange: (next: RoomCreateOptions) => void;+}) {+ if (value.channel.kind !== 'existing') return null;+ const problem = channelIdProblem(bridge.type, value.channel.externalChannelId);+ return (+ <>+ <Input+ aria-label="Channel id"+ placeholder="The channel’s id"+ value={value.channel.externalChannelId}+ onChange={(event) =>+ onChange({+ ...value,+ channel: { kind: 'existing', externalChannelId: event.target.value },+ })+ }+ aria-invalid={problem !== null}+ />+ {problem && <span className="text-xs text-destructive">{problem}</span>}+ </>+ );+}+/*** What a room can be made with that is easy to change afterwards, in its* Configuration tab: its group and who may see and change it. Shut untildiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.test.tsindex e4ed3473d..39b93baf5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.test.ts@@ -1,7 +1,10 @@import { describe, expect, it } from 'vitest';-import { channelChoiceCards, optionsForBridge } from './room-channel-choices';+import { channelChoiceCards, optionsForBridge, channelIdProblem } from './room-channel-choices';import { DEFAULT_ROOM_OPTIONS } from './room-create-request';+// Mattermost's shape (26 lowercase letters and digits), kept low-entropy so it reads as made up.+const MATTERMOST_ID = 'mm' + '0'.repeat(24);+const bridge = (type: string, channelIdsRefused: string | null = null) => ({type,displayName: `Acme ${type}`,@@ -60,3 +63,25 @@ describe('keeping the channel choice to what the app offers', () => {});});});++describe('channelIdProblem', () => {+ it('accepts an id of each platform’s shape', () => {+ expect(channelIdProblem('slack', 'C0123ABCD')).toBeNull();+ expect(channelIdProblem('slack', 'G01ABCDEF')).toBeNull();+ expect(channelIdProblem('mattermost', MATTERMOST_ID)).toBeNull();+ expect(channelIdProblem('discord', '1234567890123456789')).toBeNull();+ expect(channelIdProblem('teams', '19:[email protected]')).toBeNull();+ });++ it('says where to find the id when it is not of the shape', () => {+ expect(channelIdProblem('slack', '#general')).toMatch(/starts with C or G/);+ expect(channelIdProblem('mattermost', 'town-square')).toMatch(/View Info/);+ expect(channelIdProblem('discord', 'general')).toMatch(/Copy Channel ID/);+ expect(channelIdProblem('teams', '19%3aabc%40thread.tacv2')).toMatch(/%3a/);+ });++ it('says nothing for a blank id or a platform it does not know', () => {+ expect(channelIdProblem('slack', ' ')).toBeNull();+ expect(channelIdProblem('zulip', 'anything')).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.tsindex 8ebab9bdc..d11ece197 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-channel-choices.ts@@ -82,3 +82,40 @@ export function optionsForBridge(: 'public';return offered.has(choice) ? options : { ...options, channel: { kind: 'new', private: false } };}++/**+ * What is wrong with `id` as a channel id on `bridgeType`, saying where to+ * find the right one, or null when it has the platform's shape (or the+ * platform is one Console does not know). Checked here because the server+ * reports a malformed id only as a fault: a Discord id that is not a number,+ * say, fails as it is read.+ */+export function channelIdProblem(bridgeType: string, id: string): string | null {+ const value = id.trim();+ if (value === '') return null;+ const shape = CHANNEL_ID_SHAPE[bridgeType];+ return shape && !shape.pattern.test(value) ? shape.problem : null;+}++const CHANNEL_ID_SHAPE: Record<string, { pattern: RegExp; problem: string }> = {+ slack: {+ pattern: /^[CG][A-Z0-9]{6,}$/,+ problem:+ 'A Slack channel id starts with C or G, like C0123ABCD. It is at the bottom of the channel’s details.',+ },+ mattermost: {+ pattern: /^[a-z0-9]{26}$/,+ problem:+ 'A Mattermost channel id is 26 lowercase letters and digits. It is under the channel’s View Info.',+ },+ discord: {+ pattern: /^\d{15,22}$/,+ problem:+ 'A Discord channel id is a long number. With Developer Mode on, right-click the channel and choose Copy Channel ID.',+ },+ teams: {+ pattern: /^19:[^\s/?#%@]+@thread\.(?:tacv2|skype)$/,+ problem:+ 'A Teams channel id looks like 19:…@thread.tacv2. It is in the channel’s link, where : is written %3a and @ is %40.',+ },+};diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.tsindex f469c3b6d..0be3c8076 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.test.ts@@ -96,13 +96,15 @@ describe('roomCreateRequest', () => {describe('roomOptionsReady', () => {it('needs a channel id only when binding an existing channel', () => {- expect(roomOptionsReady(DEFAULT_ROOM_OPTIONS)).toBe(true);+ expect(roomOptionsReady(DEFAULT_ROOM_OPTIONS, 'slack')).toBe(true);const existing = (id: string) => ({...DEFAULT_ROOM_OPTIONS,channel: { kind: 'existing' as const, externalChannelId: id },});- expect(roomOptionsReady(existing(' '))).toBe(false);- expect(roomOptionsReady(existing('C1'))).toBe(true);+ expect(roomOptionsReady(existing(' '), 'slack')).toBe(false);+ expect(roomOptionsReady(existing('C0123ABCD'), 'slack')).toBe(true);+ // An id not of the app's shape is held back, with the reason shown beside it.+ expect(roomOptionsReady(existing('general'), 'slack')).toBe(false);});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.tsindex a2e8d0337..5396a93b0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-create-request.ts@@ -1,4 +1,5 @@import type { NewRoomChannel, RoomAccess } from '@shared/core/switch-servers/switch-servers';+import { channelIdProblem } from './room-channel-choices';/** What the New room dialog asks the server for: a Switch Console chat when no messaging app is chosen, else a room bridged to the chosen one. */export type RoomCreateRequest =@@ -101,9 +102,11 @@ function roomOptionsParams(options: RoomCreateOptions) {};}-/** Whether More options are complete: an existing channel has to be named. */-export function roomOptionsReady(options: RoomCreateOptions): boolean {- return options.channel.kind !== 'existing' || options.channel.externalChannelId.trim() !== '';+/** Whether the options can be sent: an existing channel has to be named, by an id of its app's shape. */+export function roomOptionsReady(options: RoomCreateOptions, bridgeType: string): boolean {+ if (options.channel.kind !== 'existing') return true;+ const id = options.channel.externalChannelId;+ return id.trim() !== '' && channelIdProblem(bridgeType, id) === null;}/** A room needs only a name; a bridged room's description is optional, as its channel topic is. */diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/create-room-modal-wiring.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-room-modal-wiring.test.tsxnew file mode 100644index 000000000..8a0f4faba--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/create-room-modal-wiring.test.tsx@@ -0,0 +1,226 @@+/**+ * The New room dialog end to end, short of the server: what it sends for a+ * room on a messaging app, that an existing channel needs an id of its app's+ * shape before Create, that switching app starts the channel choice again,+ * and that a Switch Console room is made as a chat, without the options.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++const rpcMock = vi.hoisted(() => ({+ workspaces: {+ listBridges: vi.fn(),+ listAgents: vi.fn(async () => []),+ listRoomGroups: vi.fn(async () => []),+ createRoom: vi.fn(),+ },+ chats: {+ workspaceMembers: vi.fn(async () => []),+ agentCandidates: vi.fn(async () => []),+ create: vi.fn(),+ },+}));++vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: rpcMock }));+vi.mock('@renderer/lib/hooks/useFeatureFlags', () => ({+ useFeatureFlags: () => ({ group_chats: true }),+}));+vi.mock('@renderer/features/managed-agents/use-managed-agents', () => ({+ useManagedAgents: () => ({ data: [] }),+}));+vi.mock('@renderer/features/locations/stores/agents-store', () => ({+ agentsStore: { agentsInWorkspace: () => [] },+}));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ activeServerId: 's1',+ servers: [{ id: 's1', name: 'Acme' }],+ statusFor: () => ({ connected: true, user: { id: 'u1' } }),+ },+}));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: {+ workspaces: [{ id: 'ws', tenantId: null }],+ idOnServerInScope: (serverId: string | null) => (serverId ? 'ws' : null),+ },+}));+vi.mock('@renderer/features/chats/stores/chats', () => ({ chatsStore: { add: vi.fn() } }));+vi.mock('@renderer/features/sidebar/sidebar-room-grouping', () => ({ openRoomView: vi.fn() }));+vi.mock('@renderer/features/sidebar/sidebar-tree-data', () => ({+ refreshSidebarRoomState: vi.fn(async () => {}),+}));+vi.mock('@renderer/lib/stores/app-state', () => ({+ sidebarStore: { setGrouping: vi.fn(), ensureRoomExpanded: vi.fn() },+}));+vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useModalContext: () => ({ setCloseGuard: () => {} }),+}));+// The dialog's frame needs an open dialog around it; its contents are the subject here.+vi.mock('@renderer/lib/ui/dialog', () => {+ const pass = ({ children }: { children?: React.ReactNode }) => <>{children}</>;+ return { DialogContentArea: pass, DialogFooter: pass, DialogHeader: pass, DialogTitle: pass };+});+// The app pill is a menu; a plain select stands in for it, as the choice is what matters here.+vi.mock('@renderer/features/switch-servers/messaging-app-selector', () => ({+ SWITCH_CONSOLE: '',+ MessagingAppSelector: ({+ bridges,+ value,+ onChange,+ }: {+ bridges: { id: string; displayName: string }[];+ value: string;+ onChange: (value: string) => void;+ }) => (+ <select aria-label="Messaging app" value={value} onChange={(e) => onChange(e.target.value)}>+ <option value="">Switch Console</option>+ {bridges.map((bridge) => (+ <option key={bridge.id} value={bridge.id}>+ {bridge.displayName}+ </option>+ ))}+ </select>+ ),+}));++import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomModal';++const bridge = (id: string, type: string, displayName: string) => ({+ id,+ type,+ displayName,+ status: 'active',+ canCreateChannels: true,+ channelIdsRefused: null,+});++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ rpcMock.workspaces.listBridges.mockResolvedValue([+ bridge('b1', 'slack', 'Acme Slack'),+ bridge('b2', 'mattermost', 'switch-dev'),+ ]);+ rpcMock.workspaces.createRoom.mockResolvedValue({ kind: 'created', room: { id: 'r1' } });+ rpcMock.chats.create.mockResolvedValue({ roomId: 'r2' });+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+ vi.clearAllMocks();+});++async function render(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <CreateRoomModal onSuccess={() => {}} onClose={() => {}} />+ </QueryClientProvider>+ )+ );+ await act(async () => {});+ return container;+}++async function typeInto(input: HTMLInputElement, text: string) {+ await act(async () => {+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!.call(+ input,+ text+ );+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++async function chooseApp(host: HTMLElement, value: string) {+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Messaging app"]')!;+ await act(async () => {+ select.value = value;+ select.dispatchEvent(new Event('change', { bubbles: true }));+ });+}++const card = (host: HTMLElement, title: string) =>+ [...host.querySelectorAll<HTMLButtonElement>('[role="radio"]')].find((each) =>+ each.textContent?.startsWith(title)+ )!;+const createButton = (host: HTMLElement) =>+ [...host.querySelectorAll('button')].find((each) => each.textContent?.includes('Create room'))!;+const channelIdInput = (host: HTMLElement) =>+ host.querySelector<HTMLInputElement>('input[aria-label="Channel id"]');++describe('New room dialog', () => {+ it('holds Create until an existing channel has an id of its app’s shape, then sends it', async () => {+ const host = await render();+ await typeInto(host.querySelector<HTMLInputElement>('#new-room-name')!, 'design-review');+ await chooseApp(host, 'b1');+ await act(async () => card(host, 'Existing channel').click());++ expect(createButton(host).disabled).toBe(true);+ await typeInto(channelIdInput(host)!, 'general');+ expect(createButton(host).disabled).toBe(true);+ expect(host.textContent).toContain('starts with C or G');++ await typeInto(channelIdInput(host)!, 'C0123ABCD');+ expect(createButton(host).disabled).toBe(false);+ await act(async () => createButton(host).click());++ expect(rpcMock.workspaces.createRoom).toHaveBeenCalledWith(+ expect.objectContaining({+ bridgeId: 'b1',+ name: 'design-review',+ channel: { kind: 'existing', externalChannelId: 'C0123ABCD' },+ groupId: null,+ })+ );+ });++ it('starts the channel choice again on another app, dropping a typed id', async () => {+ const host = await render();+ await typeInto(host.querySelector<HTMLInputElement>('#new-room-name')!, 'design-review');+ await chooseApp(host, 'b1');+ await act(async () => card(host, 'Existing channel').click());+ await typeInto(channelIdInput(host)!, 'C0123ABCD');++ await chooseApp(host, 'b2');+ expect(channelIdInput(host)).toBeNull();+ expect(card(host, 'New public channel').getAttribute('aria-checked')).toBe('true');++ await act(async () => createButton(host).click());+ expect(rpcMock.workspaces.createRoom).toHaveBeenCalledWith(+ expect.objectContaining({ bridgeId: 'b2', channel: { kind: 'new', private: false } })+ );+ });++ it('makes a Switch Console room as a chat, leaving the app’s options behind', async () => {+ const host = await render();+ await typeInto(host.querySelector<HTMLInputElement>('#new-room-name')!, 'design-review');+ await chooseApp(host, 'b1');+ await act(async () => card(host, 'New private channel').click());+ await chooseApp(host, '');++ await act(async () => createButton(host).click());+ expect(rpcMock.workspaces.createRoom).not.toHaveBeenCalled();+ expect(rpcMock.chats.create).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'design-review', kind: 'group' })+ );+ });+});