Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Decision routing settings and the room auto-route toggle in Console and the gateway

agent-runner353f2ed85236d2d
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 25ef87eb4..5a3582617 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -38,8 +38,10 @@ import {
normaliseServerUrl,
type AddServerParams,
type BundledChatSignIn,
+ type ClearDecisionSettingsResult,
type ClearTrustSettingsResult,
type CreatedRegistrationKey,
+ type FetchDecisionSettingsResult,
type FetchTrustSettingsResult,
type PasswordLoginParams,
type RenameServerParams,
@@ -52,6 +54,10 @@ import {
type SwitchUser,
type UpdateServerParams,
type UpdateServerResult,
+ type TestDecisionSettingsParams,
+ type TestDecisionSettingsResult,
+ type UpdateDecisionSettingsParams,
+ type UpdateDecisionSettingsResult,
type UpdateTrustSettingsParams,
type UpdateTrustSettingsResult,
} from '@shared/core/switch-servers/switch-servers';
@@ -67,6 +73,12 @@ import {
signup,
} from './auth';
import { bundledChatSignInFor } from './bundled-chat-sign-in';
+import {
+ clearDecisionSettingsOnServer,
+ fetchDecisionSettingsFromServer,
+ testDecisionSettingsOnServer,
+ updateDecisionSettingsOnServer,
+} from './decision-settings';
import {
getConnectionCatalog,
getGitHubConnection,
@@ -577,6 +589,36 @@ export const switchServersController = createRPCController({
clearTrustSettings: async (serverId: string): Promise<ClearTrustSettingsResult> =>
clearTrustSettingsOnServer(await requireReachableServer(serverId)),
+ /**
+ * A workspace's decision routing settings, its admins only. Scoped to the
+ * workspace named, not the server: each workspace chooses its own decision
+ * backend, so the call runs with that workspace's tenant selected.
+ */
+ getDecisionSettings: (workspaceId: string): Promise<FetchDecisionSettingsResult> =>
+ withReachableWorkspaceSession(workspaceId, fetchDecisionSettingsFromServer),
+
+ updateDecisionSettings: ({
+ workspaceId,
+ ...input
+ }: UpdateDecisionSettingsParams): Promise<UpdateDecisionSettingsResult> =>
+ withReachableWorkspaceSession(workspaceId, (server) =>
+ updateDecisionSettingsOnServer(server, input)
+ ),
+
+ /** Return the workspace to the server's default decision backend. */
+ clearDecisionSettings: (workspaceId: string): Promise<ClearDecisionSettingsResult> =>
+ withReachableWorkspaceSession(workspaceId, clearDecisionSettingsOnServer),
+
+ /** Run one sample decision against the unsaved values, or the server
+ * default, nothing stored. */
+ testDecisionSettings: ({
+ workspaceId,
+ ...input
+ }: TestDecisionSettingsParams): Promise<TestDecisionSettingsResult> =>
+ withReachableWorkspaceSession(workspaceId, (server) =>
+ testDecisionSettingsOnServer(server, input)
+ ),
+
/**
* The apps connectors sign in through, for the server's operator: not
* scoped to a workspace, since one app serves them all. Null when the
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.test.ts
new file mode 100644
index 000000000..9ca03551d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.test.ts
@@ -0,0 +1,503 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+
+const managedServerHostBlocked = vi.hoisted(() => vi.fn(() => null));
+const managedServerStoppedPhase = vi.hoisted(() => vi.fn(() => null));
+const noteManagedServerUnanswered = vi.hoisted(() => vi.fn());
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked,
+ managedServerStoppedPhase,
+ noteManagedServerUnanswered,
+}));
+
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
+
+const {
+ fetchDecisionSettingsFromServer,
+ updateDecisionSettingsOnServer,
+ clearDecisionSettingsOnServer,
+ testDecisionSettingsOnServer,
+} = await import('./decision-settings');
+const { fetchRoomDetail, setRoomAutoRoute } = await import('./gateway-client');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ url: 'https://switch.example.com',
+ dashboardUrl: null,
+ managed: false,
+} as never;
+
+/** A far-from-expiry JWT, so no renewal path is exercised here. */
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ const text = body === null ? '' : typeof body === 'string' ? body : JSON.stringify(body);
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => (typeof body === 'string' || body === null ? {} : body),
+ headers: { get: () => null, getSetCookie: () => [] },
+ text: async () => text,
+ } as unknown as Response;
+}
+
+const SETTINGS_JSON = {
+ source: 'workspace',
+ effective: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ available: true,
+ reason: null,
+ },
+ workspace: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ has_api_key: true,
+ api_key_last4: 'AwcA',
+ api_key_unreadable: false,
+ updated_at: '2026-10-27T10:00:00Z',
+ },
+ server_default: { configured: true, endpoint: 'http://decision:8230', has_api_key: false },
+ options: { haiku_anthropic: true, haiku_bedrock: false },
+};
+
+const SETTINGS = {
+ source: 'workspace',
+ effective: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ available: true,
+ reason: null,
+ },
+ workspace: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ hasApiKey: true,
+ apiKeyLast4: 'AwcA',
+ apiKeyUnreadable: false,
+ updatedAt: '2026-10-27T10:00:00Z',
+ },
+ serverDefault: { configured: true, endpoint: 'http://decision:8230', hasApiKey: false },
+ options: { haikuAnthropic: true, haikuBedrock: false },
+};
+
+const DEFAULT_JSON = {
+ source: 'server_default',
+ effective: {
+ backend: 'endpoint',
+ endpoint: 'http://decision:8230',
+ threshold: null,
+ available: true,
+ reason: null,
+ },
+ workspace: null,
+ server_default: { configured: true, endpoint: 'http://decision:8230', has_api_key: false },
+ options: { haiku_anthropic: true, haiku_bedrock: false },
+};
+
+const ENDPOINT_INPUT = {
+ backend: 'endpoint' as const,
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+};
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('fetchDecisionSettingsFromServer', () => {
+ it('returns the loaded settings on success, never a key', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).resolves.toEqual({
+ kind: 'loaded',
+ settings: SETTINGS,
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/decision-settings');
+ expect(init.method ?? 'GET').toBe('GET');
+ });
+
+ it('reads a workspace on the server default as having no setting of its own', async () => {
+ fetchMock.mockResolvedValue(response(200, DEFAULT_JSON));
+
+ const result = await fetchDecisionSettingsFromServer(SERVER);
+ expect(result).toMatchObject({
+ kind: 'loaded',
+ settings: { source: 'server_default', workspace: null },
+ });
+ });
+
+ it('maps a rejected session onto unauthenticated so the caller prompts a sign-in', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a member who is not a workspace admin as forbidden, not a thrown error', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it('reports a server without the route as unsupported', async () => {
+ fetchMock.mockResolvedValue(response(404, { detail: 'Not Found' }));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).resolves.toEqual({
+ kind: 'unsupported',
+ });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).resolves.toMatchObject({
+ kind: 'error',
+ });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(fetchDecisionSettingsFromServer(SERVER)).rejects.toMatchObject({ status: 500 });
+ });
+});
+
+describe('updateDecisionSettingsOnServer', () => {
+ it('returns the saved settings on success', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await expect(updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toEqual({
+ kind: 'saved',
+ settings: SETTINGS,
+ });
+ });
+
+ it('PUTs the settings, omitting api_key when none is given so the stored one is kept', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT);
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/decision-settings');
+ expect(init.method).toBe('PUT');
+ expect(JSON.parse(init.body)).toEqual({
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+ });
+ });
+
+ it('sends a new key, or the request to clear the stored one', async () => {
+ fetchMock.mockResolvedValue(response(200, SETTINGS_JSON));
+
+ await updateDecisionSettingsOnServer(SERVER, {
+ backend: 'haiku_anthropic',
+ apiKey: 'sk-ant-placeholder',
+ });
+ await updateDecisionSettingsOnServer(SERVER, { ...ENDPOINT_INPUT, clearApiKey: true });
+
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ backend: 'haiku_anthropic',
+ api_key: 'sk-ant-placeholder',
+ });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toMatchObject({ clear_api_key: true });
+ });
+
+ it('reports a refused value as invalid, with the gateway’s own sentence', async () => {
+ fetchMock.mockResolvedValue(
+ response(422, { detail: 'haiku_bedrock is not enabled on this server' })
+ );
+
+ await expect(
+ updateDecisionSettingsOnServer(SERVER, { backend: 'haiku_bedrock' })
+ ).resolves.toEqual({
+ kind: 'invalid',
+ message: 'haiku_bedrock is not enabled on this server',
+ });
+ });
+
+ it('words a FastAPI validation list as its messages rather than raw JSON', async () => {
+ fetchMock.mockResolvedValue(
+ response(422, {
+ detail: [
+ {
+ type: 'less_than_equal',
+ loc: ['body', 'threshold'],
+ msg: 'Input should be less than or equal to 1',
+ },
+ ],
+ })
+ );
+
+ await expect(
+ updateDecisionSettingsOnServer(SERVER, { ...ENDPOINT_INPUT, threshold: 1.5 })
+ ).resolves.toEqual({
+ kind: 'invalid',
+ message: 'threshold: Input should be less than or equal to 1',
+ });
+ });
+
+ it('maps a rejected session onto unauthenticated', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a member who is not a workspace admin as forbidden', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));
+
+ await expect(updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toEqual({
+ kind: 'forbidden',
+ });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toMatchObject({
+ kind: 'error',
+ });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(updateDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).rejects.toMatchObject({
+ status: 500,
+ });
+ });
+});
+
+describe('clearDecisionSettingsOnServer', () => {
+ it('DELETEs the workspace’s setting, then reads back the server default it now uses', async () => {
+ fetchMock
+ .mockResolvedValueOnce(response(204, null))
+ .mockResolvedValueOnce(response(200, DEFAULT_JSON));
+
+ const result = await clearDecisionSettingsOnServer(SERVER);
+
+ expect(result).toMatchObject({
+ kind: 'cleared',
+ settings: { source: 'server_default', workspace: null },
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/decision-settings');
+ expect(init.method).toBe('DELETE');
+ expect(fetchMock.mock.calls[1][0]).toBe('https://switch.example.com/gateway/decision-settings');
+ });
+
+ it('maps a rejected session onto unauthenticated', async () => {
+ fetchMock.mockResolvedValue(response(401, 'Token expired'));
+
+ await expect(clearDecisionSettingsOnServer(SERVER)).resolves.toEqual({
+ kind: 'unauthenticated',
+ });
+ });
+
+ it('reports a member who is not a workspace admin as forbidden', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));
+
+ await expect(clearDecisionSettingsOnServer(SERVER)).resolves.toEqual({ kind: 'forbidden' });
+ });
+
+ it('reports an unreachable gateway rather than failing silently', async () => {
+ fetchMock.mockRejectedValue(new Error('ECONNREFUSED'));
+
+ await expect(clearDecisionSettingsOnServer(SERVER)).resolves.toMatchObject({ kind: 'error' });
+ });
+
+ it('rethrows a server fault rather than flattening it into a form error', async () => {
+ fetchMock.mockResolvedValue(response(500, 'Internal Server Error'));
+
+ await expect(clearDecisionSettingsOnServer(SERVER)).rejects.toMatchObject({ status: 500 });
+ });
+});
+
+describe('testDecisionSettingsOnServer', () => {
+ it('POSTs the unsaved values and returns the pick, confidence and latency', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, {
+ ok: true,
+ agent: 'deploy-bot',
+ model_choice: 'deploy-bot',
+ confidence: 0.91,
+ latency_ms: 420,
+ backend: 'endpoint',
+ error: null,
+ })
+ );
+
+ await expect(testDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toEqual({
+ kind: 'tested',
+ outcome: {
+ ok: true,
+ agent: 'deploy-bot',
+ modelChoice: 'deploy-bot',
+ confidence: 0.91,
+ latencyMs: 420,
+ backend: 'endpoint',
+ error: null,
+ },
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/decision-settings/test');
+ expect(init.method).toBe('POST');
+ expect(JSON.parse(init.body)).toEqual({
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+ });
+ });
+
+ it('tests the server default as `default`, sending nothing of the workspace’s', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, {
+ ok: true,
+ agent: null,
+ model_choice: 'none',
+ confidence: 0.2,
+ latency_ms: 300,
+ backend: 'default',
+ error: null,
+ })
+ );
+
+ await testDecisionSettingsOnServer(SERVER, { backend: 'default' });
+
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ backend: 'default' });
+ });
+
+ it('returns a failed decision as an answer, with its reason', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, {
+ ok: false,
+ agent: null,
+ model_choice: null,
+ confidence: null,
+ latency_ms: null,
+ backend: 'haiku_anthropic',
+ error: { code: 'key_refused', message: 'The Anthropic API refused the key.' },
+ })
+ );
+
+ await expect(
+ testDecisionSettingsOnServer(SERVER, { backend: 'haiku_anthropic', apiKey: 'bad' })
+ ).resolves.toMatchObject({
+ kind: 'tested',
+ outcome: {
+ ok: false,
+ error: { code: 'key_refused', message: 'The Anthropic API refused the key.' },
+ },
+ });
+ });
+
+ it('reports refused values as invalid', async () => {
+ fetchMock.mockResolvedValue(response(422, { detail: 'endpoint must be an http(s) URL' }));
+
+ await expect(
+ testDecisionSettingsOnServer(SERVER, { backend: 'endpoint', endpoint: 'nope' })
+ ).resolves.toEqual({ kind: 'invalid', message: 'endpoint must be an http(s) URL' });
+ });
+
+ it('reports a member who is not a workspace admin as forbidden', async () => {
+ fetchMock.mockResolvedValue(response(403, { detail: 'Workspace admin access required' }));
+
+ await expect(testDecisionSettingsOnServer(SERVER, ENDPOINT_INPUT)).resolves.toEqual({
+ kind: 'forbidden',
+ });
+ });
+});
+
+describe('a room’s auto-route setting', () => {
+ const ROOM_JSON = {
+ id: 'room-1',
+ name: 'ops',
+ description: '',
+ channel_type: null,
+ agent_count: 2,
+ bridge_display_name: null,
+ archived: false,
+ created_at: '2026-10-27T10:00:00Z',
+ };
+
+ it('reads auto_route from the room detail', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, {
+ ...ROOM_JSON,
+ auto_route: {
+ on: true,
+ available: true,
+ reason: null,
+ fallback_agent: 'agent-7',
+ fallback_agent_name: 'triage-bot',
+ },
+ })
+ );
+
+ const room = await fetchRoomDetail(SERVER, 'room-1');
+ expect(room.autoRoute).toEqual({
+ on: true,
+ available: true,
+ reason: null,
+ fallbackAgent: 'agent-7',
+ fallbackAgentName: 'triage-bot',
+ });
+ });
+
+ it('leaves it absent for a server that predates it', async () => {
+ fetchMock.mockResolvedValue(response(200, ROOM_JSON));
+
+ const room = await fetchRoomDetail(SERVER, 'room-1');
+ expect(room.autoRoute).toBeUndefined();
+ });
+
+ it('PUTs only the fields changed and returns the setting as it now stands', async () => {
+ fetchMock.mockResolvedValue(
+ response(200, { on: false, available: true, reason: null, fallback_agent: null })
+ );
+
+ await expect(setRoomAutoRoute(SERVER, 'room-1', { on: false })).resolves.toEqual({
+ on: false,
+ available: true,
+ reason: null,
+ fallbackAgent: null,
+ fallbackAgentName: null,
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/rooms/room-1/auto-route');
+ expect(init.method).toBe('PUT');
+ expect(JSON.parse(init.body)).toEqual({ on: false });
+
+ await setRoomAutoRoute(SERVER, 'room-1', { fallbackAgent: null });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ fallback_agent: null });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.ts
new file mode 100644
index 000000000..da43685ec
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/decision-settings.ts
@@ -0,0 +1,142 @@
+import {
+ clearDecisionSettings,
+ fetchDecisionSettings,
+ GatewayError,
+ testDecisionSettings,
+ updateDecisionSettings,
+} from '@main/core/switch-servers/gateway-client';
+import type {
+ ClearDecisionSettingsResult,
+ DecisionSettingsInput,
+ DecisionTestInput,
+ FetchDecisionSettingsResult,
+ SwitchServer,
+ TestDecisionSettingsResult,
+ UpdateDecisionSettingsResult,
+} from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * Load the decision routing settings of the workspace the session selects,
+ * mapping recoverable gateway failures the way Switch Trust's settings do: a
+ * member who isn't the workspace's admin gets `forbidden` rather than a
+ * thrown error, so the section can say why.
+ *
+ * The caller selects the workspace (`withReachableWorkspaceSession`); these
+ * routes answer for whichever workspace the session names.
+ */
+export async function fetchDecisionSettingsFromServer(
+ server: SwitchServer
+): Promise<FetchDecisionSettingsResult> {
+ try {
+ return { kind: 'loaded', settings: await fetchDecisionSettings(server) };
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.kind === 'http' && cause.status === 404) {
+ return { kind: 'unsupported' };
+ }
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/**
+ * Save the selected workspace's decision settings. A refusal of the values
+ * (a threshold out of range, a URL that isn't http(s), Bedrock the server
+ * doesn't allow) is `invalid` with the gateway's own sentence; an unexpected
+ * 500 still throws, since it is a bug rather than a form error.
+ */
+export async function updateDecisionSettingsOnServer(
+ server: SwitchServer,
+ input: DecisionSettingsInput
+): Promise<UpdateDecisionSettingsResult> {
+ try {
+ return { kind: 'saved', settings: await updateDecisionSettings(server, input) };
+ } catch (cause) {
+ const invalid = invalidResult(cause);
+ if (invalid) return invalid;
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/** Return the selected workspace to the server default, answering with the
+ * settings as they now stand. */
+export async function clearDecisionSettingsOnServer(
+ server: SwitchServer
+): Promise<ClearDecisionSettingsResult> {
+ try {
+ return { kind: 'cleared', settings: await clearDecisionSettings(server) };
+ } catch (cause) {
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/** Run one sample decision against unsaved values, or the server default. A
+ * decision that failed is `tested` with the reason in its outcome; only a
+ * refused request is not. */
+export async function testDecisionSettingsOnServer(
+ server: SwitchServer,
+ input: DecisionTestInput
+): Promise<TestDecisionSettingsResult> {
+ try {
+ return { kind: 'tested', outcome: await testDecisionSettings(server, input) };
+ } catch (cause) {
+ const invalid = invalidResult(cause);
+ if (invalid) return invalid;
+ const result = recoverableResult(cause);
+ if (result) return result;
+ throw cause;
+ }
+}
+
+/**
+ * A 400 or 422, with the gateway's explanation. FastAPI's own validation
+ * answers with a list of `{loc, msg}` rather than a sentence, so those are
+ * joined: "Input should be less than or equal to 1" reads better in a form
+ * than the status line and raw JSON.
+ */
+function invalidResult(cause: unknown): { kind: 'invalid'; message: string } | null {
+ if (!(cause instanceof GatewayError) || cause.kind !== 'http') return null;
+ if (cause.status !== 400 && cause.status !== 422) return null;
+ return {
+ kind: 'invalid',
+ message: cause.detail ?? validationMessages(cause.body) ?? cause.message,
+ };
+}
+
+function validationMessages(body: string | undefined): string | null {
+ if (!body) return null;
+ try {
+ const parsed = JSON.parse(body) as { detail?: unknown };
+ if (!Array.isArray(parsed.detail)) return null;
+ const messages = parsed.detail
+ .map((item: unknown) => fieldMessage(item))
+ .filter((message): message is string => message !== null);
+ return messages.length > 0 ? messages.join('; ') : null;
+ } catch {
+ return null;
+ }
+}
+
+function fieldMessage(item: unknown): string | null {
+ if (typeof item !== 'object' || item === null) return null;
+ const { loc, msg } = item as { loc?: unknown; msg?: unknown };
+ if (typeof msg !== 'string') return null;
+ const field = Array.isArray(loc) ? loc.filter((part) => part !== 'body').at(-1) : undefined;
+ return typeof field === 'string' ? `${field}: ${msg}` : msg;
+}
+
+/** The failure cases every decision settings call can produce, all behind the
+ * same workspace-admin gate. */
+function recoverableResult(
+ cause: unknown
+): { kind: 'unauthenticated' } | { kind: 'forbidden' } | { kind: 'error'; message: string } | null {
+ if (!(cause instanceof GatewayError)) return null;
+ if (cause.kind === 'unauthorized') return { kind: 'unauthenticated' };
+ if (cause.kind === 'network') return { kind: 'error', message: cause.message };
+ if (cause.kind === 'http' && cause.status === 403) return { kind: 'forbidden' };
+ return null;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 5eef71ebe..4a813b89d 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -80,6 +80,11 @@ import {
type ChannelRetirement,
type ChatClaim,
type ConnectedChat,
+ type DecisionBackend,
+ type DecisionSettings,
+ type DecisionSettingsInput,
+ type DecisionTestInput,
+ type DecisionTestOutcome,
type DeleteBridgeResult,
type LinkCode,
type LinkedIdentity,
@@ -101,6 +106,7 @@ import {
type RetireOutcome,
type SwitchApiKey,
type CreatedRegistrationKey,
+ type RoomAutoRoute,
type SwitchAuthConfig,
type SwitchServer,
type SwitchServerDeclaration,
@@ -549,6 +555,137 @@ export async function clearTrustSettings(server: SwitchServer): Promise<TrustSet
return mapTrustSettings((await res.json()) as TrustSettingsJson);
}
+type DecisionSettingsJson = {
+ source: 'workspace' | 'server_default';
+ effective: {
+ backend: DecisionBackend;
+ endpoint: string | null;
+ threshold: number | null;
+ available: boolean;
+ reason: string | null;
+ };
+ workspace: {
+ backend: DecisionBackend;
+ endpoint: string | null;
+ threshold: number | null;
+ has_api_key: boolean;
+ api_key_last4: string | null;
+ api_key_unreadable: boolean;
+ updated_at: string;
+ } | null;
+ server_default: { configured: boolean; endpoint: string | null; has_api_key: boolean };
+ options: { haiku_anthropic: boolean; haiku_bedrock: boolean };
+};
+
+function mapDecisionSettings(json: DecisionSettingsJson): DecisionSettings {
+ const { workspace } = json;
+ return {
+ source: json.source,
+ effective: {
+ backend: json.effective.backend,
+ endpoint: json.effective.endpoint,
+ threshold: json.effective.threshold,
+ available: json.effective.available,
+ reason: json.effective.reason,
+ },
+ workspace:
+ workspace === null
+ ? null
+ : {
+ backend: workspace.backend,
+ endpoint: workspace.endpoint,
+ threshold: workspace.threshold,
+ hasApiKey: workspace.has_api_key,
+ apiKeyLast4: workspace.api_key_last4,
+ apiKeyUnreadable: workspace.api_key_unreadable,
+ updatedAt: workspace.updated_at,
+ },
+ serverDefault: {
+ configured: json.server_default.configured,
+ endpoint: json.server_default.endpoint,
+ hasApiKey: json.server_default.has_api_key,
+ },
+ options: {
+ haikuAnthropic: json.options.haiku_anthropic,
+ haikuBedrock: json.options.haiku_bedrock,
+ },
+ };
+}
+
+/** The wire body `PUT /decision-settings` and its test take; a field left
+ * unset is left out, so the stored key survives a save that doesn't name one. */
+function decisionSettingsBody(input: DecisionTestInput): Record<string, unknown> {
+ if (input.backend === 'default') return { backend: 'default' };
+ return {
+ backend: input.backend,
+ ...(input.endpoint !== undefined ? { endpoint: input.endpoint } : {}),
+ ...(input.apiKey !== undefined ? { api_key: input.apiKey } : {}),
+ ...(input.clearApiKey !== undefined ? { clear_api_key: input.clearApiKey } : {}),
+ ...(input.threshold !== undefined ? { threshold: input.threshold } : {}),
+ };
+}
+
+/** The decision routing settings of the workspace the session selects, its
+ * admins only (`GET /decision-settings`). */
+export async function fetchDecisionSettings(server: SwitchServer): Promise<DecisionSettings> {
+ const res = await gatewayFetch(server, '/decision-settings', { authenticated: true });
+ return mapDecisionSettings((await res.json()) as DecisionSettingsJson);
+}
+
+/** Save the selected workspace's decision routing settings (`PUT /decision-settings`). */
+export async function updateDecisionSettings(
+ server: SwitchServer,
+ input: DecisionSettingsInput
+): Promise<DecisionSettings> {
+ const res = await gatewayFetch(server, '/decision-settings', {
+ authenticated: true,
+ method: 'PUT',
+ body: decisionSettingsBody(input),
+ });
+ return mapDecisionSettings((await res.json()) as DecisionSettingsJson);
+}
+
+/** Return the selected workspace to the server default (`DELETE /decision-settings`,
+ * which answers 204), then read the settings back as they now stand. */
+export async function clearDecisionSettings(server: SwitchServer): Promise<DecisionSettings> {
+ await gatewayFetch(server, '/decision-settings', { authenticated: true, method: 'DELETE' });
+ return fetchDecisionSettings(server);
+}
+
+type DecisionTestJson = {
+ ok: boolean;
+ agent: string | null;
+ model_choice: string | null;
+ confidence: number | null;
+ latency_ms: number | null;
+ backend: string | null;
+ error: { code: string; message: string } | null;
+};
+
+/** Run one sample decision against unsaved values, or the server default
+ * (`POST /decision-settings/test`). A failed decision is an answer, not an
+ * error: it comes back with `ok` false. */
+export async function testDecisionSettings(
+ server: SwitchServer,
+ input: DecisionTestInput
+): Promise<DecisionTestOutcome> {
+ const res = await gatewayFetch(server, '/decision-settings/test', {
+ authenticated: true,
+ method: 'POST',
+ body: decisionSettingsBody(input),
+ });
+ const json = (await res.json()) as DecisionTestJson;
+ return {
+ ok: json.ok,
+ agent: json.agent,
+ modelChoice: json.model_choice,
+ confidence: json.confidence,
+ latencyMs: json.latency_ms,
+ backend: json.backend,
+ error: json.error === null ? null : { code: json.error.code, message: json.error.message },
+ };
+}
+
type ServerDeclarationJson = {
version: string | null;
contracts: Record<string, { speaks: number; accepts: number }>;
@@ -3385,6 +3522,8 @@ type RoomDetailJson = RoomSummaryJson & {
external_channel_id?: string | null;
transport_room_id?: string | null;
archived_at?: string | null;
+ /** Absent from a server that predates decision routing. */
+ auto_route?: RoomAutoRouteJson;
};
/** The server's visibility words; anything else reads as private, the narrower of the two. */
@@ -3394,6 +3533,25 @@ function visibilityOf(value: string | undefined): RoomVisibility {
return value === 'public' ? 'public' : 'private';
}
+type RoomAutoRouteJson = {
+ on: boolean;
+ available: boolean;
+ reason: string | null;
+ fallback_agent: string | null;
+ /** Absent from a server that predates it. */
+ fallback_agent_name?: string | null;
+};
+
+function mapRoomAutoRoute(json: RoomAutoRouteJson): RoomAutoRoute {
+ return {
+ on: json.on,
+ available: json.available,
+ reason: json.reason,
+ fallbackAgent: json.fallback_agent,
+ fallbackAgentName: json.fallback_agent_name ?? null,
+ };
+}
+
function mapRoomDetail(r: RoomDetailJson): RemoteRoomDetail {
return {
...mapRoomSummary(r),
@@ -3414,6 +3572,7 @@ function mapRoomDetail(r: RoomDetailJson): RemoteRoomDetail {
externalChannelId: r.external_channel_id ?? null,
transportRoomId: r.transport_room_id ?? null,
archivedAt: r.archived_at ?? null,
+ ...(r.auto_route ? { autoRoute: mapRoomAutoRoute(r.auto_route) } : {}),
};
}
@@ -3584,6 +3743,27 @@ export async function fetchBridgeUserNames(
);
}
+/**
+ * Change a room's auto-route setting (`PUT /rooms/{id}/auto-route`), the same
+ * store `!auto-route` writes; a field left out is left alone. Answers with the
+ * setting as it now stands.
+ */
+export async function setRoomAutoRoute(
+ server: SwitchServer,
+ roomId: string,
+ changes: { on?: boolean; fallbackAgent?: string | null }
+): Promise<RoomAutoRoute> {
+ const res = await gatewayFetch(server, `/rooms/${encodeURIComponent(roomId)}/auto-route`, {
+ authenticated: true,
+ method: 'PUT',
+ body: {
+ ...(changes.on !== undefined ? { on: changes.on } : {}),
+ ...(changes.fallbackAgent !== undefined ? { fallback_agent: changes.fallbackAgent } : {}),
+ },
+ });
+ return mapRoomAutoRoute((await res.json()) as RoomAutoRouteJson);
+}
+
/**
* Add agents to an existing room (`POST /rooms/{id}/agents`). Requires write
* access to the room. Agents already in the room are ignored server-side, so
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
index de61211c9..98e3da2ab 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
@@ -78,6 +78,7 @@ import {
connectServiceWithKey,
disconnectGitHub,
disconnectService,
+ setRoomAutoRoute,
setServiceGrant,
setWorkspaceService,
removeServiceGrant,
@@ -199,6 +200,8 @@ import type {
RemoteBridgeType,
RemoteExternalUser,
RemoteRoomDetail,
+ RoomAutoRoute,
+ SetRoomAutoRouteParams,
RemoteRoomGroup,
RemoteRoomRole,
RemoteRoomSummary,
@@ -1260,6 +1263,20 @@ export const workspacesController = createRPCController({
fetchBridgeUserNames(server, params.bridgeId)
),
+ /**
+ * Turn auto-route on or off in a room, or name its triage agent, through the
+ * same store `!auto-route` writes. Answers with the setting as it now stands;
+ * a refusal propagates, so the toggle never shows a state the server didn't take.
+ */
+ setRoomAutoRoute: ({
+ workspaceId,
+ roomId,
+ ...changes
+ }: SetRoomAutoRouteParams): Promise<RoomAutoRoute> =>
+ withReachableWorkspaceSession(workspaceId, (server) =>
+ setRoomAutoRoute(server, roomId, changes)
+ ),
+
/**
* Add agents to a room. Failures propagate as-is: the caller shows the
* gateway's own words (e.g. an agent whose server-side client is not running,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts
index 0dabbfbe8..dfa5e4ce8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-sections.ts
@@ -1,4 +1,4 @@
-export type AdminSection = 'messaging-apps' | 'connectors' | 'switch-trust' | 'apps';
+export type AdminSection = 'messaging-apps' | 'connectors' | 'decision' | 'switch-trust' | 'apps';
export type AdminScope = 'workspace' | 'server';
@@ -6,6 +6,7 @@ export const ADMIN_MENU_LABELS = {
'messaging-apps': 'Messaging apps',
connectors: 'Connectors',
'switch-trust': 'Switch Trust',
+ decision: 'Decision routing',
apps: 'Connector apps',
} as const satisfies Record<AdminSection, string>;
@@ -23,6 +24,9 @@ export type AdminGroup = { scope: AdminScope; items: AdminSection[] };
* Your own accounts are linked in Settings.
* - Connectors: the workspace's connector switches, for its admins, where
* the server has service connections on.
+ * - Decision routing: which decision service the workspace's auto-route
+ * rooms ask, for its admins. It is not about connectors, so it is there
+ * whether or not the server has service connections on.
* - Switch Trust: the deployment's guardrails, for the server's operator.
* - Connector apps: the apps connectors sign in through, for the operator of
* a Switch that serves no gateway (one this Console runs without Docker),
@@ -42,7 +46,11 @@ export function adminGroups(person: {
{
scope: 'workspace',
items: person.administers
- ? ['messaging-apps', ...(serviceConnections ? (['connectors'] as const) : [])]
+ ? [
+ 'messaging-apps',
+ ...(serviceConnections ? (['connectors'] as const) : []),
+ 'decision',
+ ]
: [],
},
{
diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx
index 7ecd51808..e90b28c48 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/admin-view.tsx
@@ -28,6 +28,7 @@ import {
import { ConnectorAppProfile } from './connector-app-profile';
import { useConnectorApps } from './connector-apps-queries';
import { ConnectorAppsTab } from './connector-apps-tab';
+import { DecisionRoutingSection } from './decision-routing-section';
import { WorkspaceSwitchesTab } from './workspace-switches-tab';
type AdminParams = {
@@ -94,6 +95,22 @@ const AdminPanel = observer(function AdminPanel() {
</PageContent>
</AdminFrame>
);
+ if (section === 'decision')
+ return (
+ <AdminFrame serverId={serverId} groups={groups} active="decision">
+ <PageContent className="px-0">
+ <div className="space-y-6 pb-10">
+ <PageHeader
+ sticky
+ title={ADMIN_MENU_LABELS.decision}
+ description={`In an auto-route room, Switch asks a decision service which agent should answer a message that tags nobody. Choose the one ${workspace.name}’s rooms use.`}
+ />
+ {/* Keyed so a workspace switch reads that workspace's own setting. */}
+ <DecisionRoutingSection key={workspace.id} workspaceId={workspace.id} />
+ </div>
+ </PageContent>
+ </AdminFrame>
+ );
// Keyed so a workspace switch starts the search afresh.
return (
<Admin
diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing-section.tsx
new file mode 100644
index 000000000..3994e07c5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing-section.tsx
@@ -0,0 +1,342 @@
+import { useEffect, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import { Checkbox } from '@renderer/lib/ui/checkbox';
+import { Field, FieldDescription, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { RadioGroup, RadioGroupItem } from '@renderer/lib/ui/radio-group';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import type {
+ ClearDecisionSettingsResult,
+ DecisionSettings,
+ DecisionTestOutcome,
+ UpdateDecisionSettingsResult,
+} from '@shared/core/switch-servers/switch-servers';
+import {
+ CHOICE_LABELS,
+ choiceFields,
+ type DecisionChoice,
+ type DecisionForm,
+ appliesText,
+ formFor,
+ formProblem,
+ haikuNote,
+ inputFor,
+ offeredChoices,
+ serverDefaultText,
+ storedKeyText,
+ testInputFor,
+ testOutcomeText,
+} from './decision-routing';
+
+/** The recoverable failure kinds every decision settings call can produce,
+ * worded for someone filling in the form. */
+function resultText(result: { kind: string; message?: string }): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Your session has expired. Sign in again.';
+ case 'forbidden':
+ return 'Only an admin of this workspace can view or change its decision routing.';
+ case 'unsupported':
+ return 'This Switch server doesn’t offer decision routing settings. Update it to set them up here.';
+ default:
+ return result.message ?? 'Could not reach the decision routing settings.';
+ }
+}
+
+const CHOICE_HINTS: Record<DecisionChoice, string> = {
+ server_default: '',
+ none: 'Auto-route is off in this workspace’s rooms, whatever the server default.',
+ endpoint: 'A decision service you run. Room messages are sent to it.',
+ haiku_anthropic:
+ 'The most accurate picks, at about 1.5 s each. Room messages are sent to Anthropic.',
+ haiku_bedrock: 'Haiku through Amazon Bedrock, on this server’s AWS account. No key needed.',
+};
+
+type TestState =
+ | { phase: 'idle' }
+ | { phase: 'testing' }
+ | { phase: 'done'; outcome: DecisionTestOutcome }
+ | { phase: 'failed'; message: string };
+
+/**
+ * A workspace's decision routing: who decides which agent answers an untagged
+ * message in its auto-route rooms. The server's default applies until a
+ * workspace admin chooses otherwise — none, a self-hosted endpoint, or Haiku
+ * where the server can run it — and a test runs one sample decision against
+ * the values as entered, before anything is saved.
+ *
+ * The form shows what the server says: it is reset from each answer, and a
+ * refusal leaves the stored setting as it was, with the reason under it.
+ */
+export function DecisionRoutingSection({ workspaceId }: { workspaceId: string }) {
+ const [settings, setSettings] = useState<DecisionSettings | null>(null);
+ const [form, setForm] = useState<DecisionForm | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [actionError, setActionError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<'saving' | 'resetting' | null>(null);
+ const [saved, setSaved] = useState(false);
+ const [test, setTest] = useState<TestState>({ phase: 'idle' });
+
+ useEffect(() => {
+ let cancelled = false;
+ setSettings(null);
+ setForm(null);
+ setLoadError(null);
+ rpc.switchServers.getDecisionSettings(workspaceId).then(
+ (result) => {
+ if (cancelled) return;
+ if (result.kind === 'loaded') {
+ setSettings(result.settings);
+ setForm(formFor(result.settings));
+ } else {
+ setLoadError(resultText(result));
+ }
+ },
+ (error: unknown) => {
+ if (!cancelled) setLoadError(failureText(error, 'Could not load decision routing.'));
+ }
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [workspaceId]);
+
+ if (loadError !== null) {
+ return (
+ <Alert variant="destructive">
+ <AlertDescription>{loadError}</AlertDescription>
+ </Alert>
+ );
+ }
+ if (settings === null || form === null) return <Spinner />;
+
+ const edit = (changes: Partial<DecisionForm>) => {
+ setForm({ ...form, ...changes });
+ setSaved(false);
+ setTest({ phase: 'idle' });
+ };
+
+ const apply = (result: UpdateDecisionSettingsResult | ClearDecisionSettingsResult) => {
+ if (result.kind === 'saved' || result.kind === 'cleared') {
+ setSettings(result.settings);
+ setForm(formFor(result.settings));
+ setActionError(null);
+ setSaved(true);
+ } else {
+ setActionError(resultText(result));
+ }
+ };
+
+ const reset = async () => {
+ setBusy('resetting');
+ setActionError(null);
+ try {
+ apply(await rpc.switchServers.clearDecisionSettings(workspaceId));
+ } catch (cause) {
+ setActionError(failureText(cause, 'Could not return to the server default.'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const save = async () => {
+ const input = inputFor(form);
+ if (input === null) return reset();
+ setBusy('saving');
+ setActionError(null);
+ try {
+ apply(await rpc.switchServers.updateDecisionSettings({ workspaceId, ...input }));
+ } catch (cause) {
+ setActionError(failureText(cause, 'Could not save decision routing.'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const testable = testInputFor(form, settings);
+ const runTest = async () => {
+ if (!('input' in testable)) return;
+ setTest({ phase: 'testing' });
+ try {
+ const result = await rpc.switchServers.testDecisionSettings({
+ workspaceId,
+ ...testable.input,
+ });
+ setTest(
+ result.kind === 'tested'
+ ? { phase: 'done', outcome: result.outcome }
+ : { phase: 'failed', message: resultText(result) }
+ );
+ } catch (cause) {
+ setTest({ phase: 'failed', message: failureText(cause, 'Could not run the test.') });
+ }
+ };
+
+ const fields = choiceFields(form.choice);
+ const problem = form.choice === 'server_default' ? null : formProblem(form, settings);
+ const keyText = storedKeyText(settings);
+ const note = haikuNote(settings);
+ const unchanged = form.choice === 'server_default' && settings.source === 'server_default';
+
+ return (
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-2" aria-label="Setting that applies">
+ <p className="text-sm text-foreground">{appliesText(settings)}</p>
+ {!settings.effective.available && settings.effective.reason && (
+ <Alert variant="warning">
+ <AlertDescription>{settings.effective.reason}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+
+ <fieldset className="flex flex-col gap-2">
+ <legend className="mb-2 text-sm font-medium text-foreground">Backend</legend>
+ <RadioGroup
+ value={form.choice}
+ onValueChange={(value) => edit({ choice: value as DecisionChoice })}
+ className="gap-2.5"
+ aria-label="Decision backend"
+ >
+ {offeredChoices(settings).map((choice) => (
+ <label key={choice} className="flex items-start gap-2.5 text-sm">
+ <RadioGroupItem value={choice} className="mt-0.5" />
+ <span className="flex flex-col">
+ <span className="text-foreground">{CHOICE_LABELS[choice]}</span>
+ <span className="text-xs text-foreground-muted">
+ {choice === 'server_default'
+ ? `Currently ${serverDefaultText(settings)}.`
+ : CHOICE_HINTS[choice]}
+ </span>
+ </span>
+ </label>
+ ))}
+ </RadioGroup>
+ {note !== null && <p className="text-xs text-foreground-muted">{note}</p>}
+ </fieldset>
+
+ {(fields.endpoint || fields.key || fields.threshold) && (
+ <FieldGroup>
+ {fields.endpoint && (
+ <Field>
+ <FieldLabel htmlFor="decision-endpoint">Endpoint URL</FieldLabel>
+ <Input
+ id="decision-endpoint"
+ value={form.endpoint}
+ placeholder="https://decision.example.com"
+ spellCheck={false}
+ autoComplete="off"
+ onChange={(e) => edit({ endpoint: e.target.value })}
+ />
+ </Field>
+ )}
+ {fields.key && (
+ <Field>
+ <FieldLabel htmlFor="decision-key">
+ {form.choice === 'haiku_anthropic' ? 'Anthropic API key' : 'API key (optional)'}
+ {keyText !== null && (
+ <span
+ className={
+ settings.workspace?.apiKeyUnreadable
+ ? 'ml-1 font-normal text-destructive'
+ : 'ml-1 font-normal text-foreground-muted'
+ }
+ >
+ ({keyText})
+ </span>
+ )}
+ </FieldLabel>
+ <Input
+ id="decision-key"
+ type="password"
+ autoComplete="new-password"
+ spellCheck={false}
+ placeholder={keyText !== null ? 'Leave blank to keep the current key' : ''}
+ value={form.apiKey}
+ onChange={(e) => edit({ apiKey: e.target.value })}
+ />
+ {form.choice === 'endpoint' && settings.workspace?.hasApiKey && (
+ <label className="flex items-center gap-2 text-xs text-foreground-muted">
+ <Checkbox
+ checked={form.clearApiKey}
+ disabled={form.apiKey.trim() !== ''}
+ onCheckedChange={(checked) => edit({ clearApiKey: checked === true })}
+ />
+ Remove the stored key
+ </label>
+ )}
+ </Field>
+ )}
+ {fields.threshold && (
+ <Field>
+ <FieldLabel htmlFor="decision-threshold">Confidence threshold</FieldLabel>
+ <Input
+ id="decision-threshold"
+ inputMode="decimal"
+ className="w-32"
+ placeholder="Default"
+ value={form.threshold}
+ onChange={(e) => edit({ threshold: e.target.value })}
+ />
+ <FieldDescription className="text-xs">
+ Between 0 and 1. A pick less confident than this goes to nobody. Leave blank for the
+ decision service’s own.
+ </FieldDescription>
+ </Field>
+ )}
+ </FieldGroup>
+ )}
+
+ {problem !== null && <p className="text-xs text-foreground-muted">{problem}</p>}
+ {actionError !== null && (
+ <p className="text-xs text-destructive">Not saved — {actionError}</p>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ size="sm"
+ disabled={problem !== null || unchanged || busy !== null}
+ onClick={() => void save()}
+ >
+ {busy === 'saving' ? 'Saving…' : 'Save'}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!('input' in testable) || test.phase === 'testing' || busy !== null}
+ title={'blocked' in testable ? testable.blocked : undefined}
+ onClick={() => void runTest()}
+ >
+ {test.phase === 'testing' ? 'Testing…' : 'Test'}
+ </Button>
+ {settings.source === 'workspace' && (
+ <Button variant="ghost" size="sm" disabled={busy !== null} onClick={() => void reset()}>
+ {busy === 'resetting' ? 'Returning…' : 'Use server default'}
+ </Button>
+ )}
+ {saved && actionError === null && (
+ <span className="text-xs text-foreground-muted">Saved.</span>
+ )}
+ </div>
+
+ <TestResult state={test} />
+ </div>
+ );
+}
+
+function TestResult({ state }: { state: TestState }) {
+ if (state.phase === 'idle' || state.phase === 'testing') return null;
+ const failed = state.phase === 'failed' || !state.outcome.ok;
+ const text = state.phase === 'failed' ? state.message : testOutcomeText(state.outcome);
+ return (
+ <p
+ role="status"
+ aria-label="Test result"
+ className={failed ? 'text-sm text-destructive' : 'text-sm text-foreground'}
+ >
+ {failed ? `Test failed — ${text}` : text}
+ </p>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing.ts b/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing.ts
new file mode 100644
index 000000000..b033ccfc6
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/admin/decision-routing.ts
@@ -0,0 +1,198 @@
+import type {
+ DecisionBackend,
+ DecisionSettings,
+ DecisionSettingsInput,
+ DecisionTestInput,
+ DecisionTestOutcome,
+} from '@shared/core/switch-servers/switch-servers';
+
+/** What the form offers: the server's default, or one of the backends a
+ * workspace can save as its own. */
+export type DecisionChoice = 'server_default' | DecisionBackend;
+
+export type DecisionForm = {
+ choice: DecisionChoice;
+ endpoint: string;
+ /** A new key; blank keeps whatever key is stored. */
+ apiKey: string;
+ /** Remove the stored key on save. */
+ clearApiKey: boolean;
+ /** As typed; blank leaves it to the decision service. */
+ threshold: string;
+};
+
+export const CHOICE_LABELS = {
+ server_default: 'Use server default',
+ none: 'None',
+ endpoint: 'Self-hosted endpoint',
+ haiku_anthropic: 'Haiku (Anthropic API)',
+ haiku_bedrock: 'Haiku on Bedrock',
+} as const satisfies Record<DecisionChoice, string>;
+
+export function formFor(settings: DecisionSettings): DecisionForm {
+ const own = settings.workspace;
+ return {
+ choice: own?.backend ?? 'server_default',
+ endpoint: own?.endpoint ?? '',
+ apiKey: '',
+ clearApiKey: false,
+ threshold: own?.threshold === null || own?.threshold === undefined ? '' : String(own.threshold),
+ };
+}
+
+/**
+ * The choices the form offers, in order. Haiku runs inside the server's
+ * decision service, so neither Haiku choice is offered without one; Bedrock
+ * spends the server's AWS credentials, so it is offered only where the
+ * operator allows it. A workspace already saved on a choice the server no
+ * longer offers still sees it, so the form shows what is stored.
+ */
+export function offeredChoices(settings: DecisionSettings): DecisionChoice[] {
+ const saved = settings.workspace?.backend;
+ return [
+ 'server_default',
+ 'none',
+ 'endpoint',
+ ...(settings.options.haikuAnthropic || saved === 'haiku_anthropic'
+ ? (['haiku_anthropic'] as const)
+ : []),
+ ...(settings.options.haikuBedrock || saved === 'haiku_bedrock'
+ ? (['haiku_bedrock'] as const)
+ : []),
+ ];
+}
+
+/** Why a Haiku choice is missing, or null when both are offered. */
+export function haikuNote(settings: DecisionSettings): string | null {
+ if (!settings.options.haikuAnthropic) {
+ return 'Haiku isn’t offered: it runs inside this server’s decision service, and this server has none configured. Its operator can add one.';
+ }
+ if (!settings.options.haikuBedrock) {
+ return 'Haiku on Bedrock isn’t offered: it uses this server’s own AWS credentials, so its operator has to turn it on.';
+ }
+ return null;
+}
+
+/** The server's default in words. */
+export function serverDefaultText(settings: DecisionSettings): string {
+ const { serverDefault } = settings;
+ if (!serverDefault.configured) return 'none — this server has no decision service configured';
+ return serverDefault.endpoint
+ ? `self-hosted decision service (${serverDefault.endpoint})`
+ : 'self-hosted decision service';
+}
+
+/** Which setting applies to the workspace's rooms, and what it comes to. */
+export function appliesText(settings: DecisionSettings): string {
+ if (settings.source === 'server_default') {
+ return `This workspace uses the server default: ${serverDefaultText(settings)}.`;
+ }
+ const own = settings.workspace;
+ const backend = own?.backend ?? settings.effective.backend;
+ const where = backend === 'endpoint' && own?.endpoint ? ` (${own.endpoint})` : '';
+ return `This workspace’s own setting applies: ${CHOICE_LABELS[backend]}${where}. The server default is ${serverDefaultText(settings)}.`;
+}
+
+/** The stored key, in words: never the key itself. */
+export function storedKeyText(settings: DecisionSettings): string | null {
+ const own = settings.workspace;
+ if (!own?.hasApiKey) return null;
+ if (own.apiKeyUnreadable || !own.apiKeyLast4) {
+ return 'set but unreadable — enter a new key to replace it';
+ }
+ return `set, ending in ${own.apiKeyLast4}`;
+}
+
+/** Whether a choice takes a key, an endpoint and a threshold. */
+export function choiceFields(choice: DecisionChoice): {
+ endpoint: boolean;
+ key: boolean;
+ threshold: boolean;
+} {
+ return {
+ endpoint: choice === 'endpoint',
+ key: choice === 'endpoint' || choice === 'haiku_anthropic',
+ threshold: choice === 'endpoint' || choice === 'haiku_anthropic' || choice === 'haiku_bedrock',
+ };
+}
+
+/** The threshold as typed: null when blank, NaN when it isn't a number. */
+function parsedThreshold(text: string): number | null {
+ const trimmed = text.trim();
+ if (trimmed === '') return null;
+ return Number(trimmed);
+}
+
+/** What stops the form being saved or tested, in a sentence; null when nothing does. */
+export function formProblem(form: DecisionForm, settings: DecisionSettings): string | null {
+ const fields = choiceFields(form.choice);
+ if (fields.endpoint && form.endpoint.trim() === '') return 'Enter the endpoint’s URL.';
+ if (form.choice === 'haiku_anthropic' && form.apiKey.trim() === '') {
+ const own = settings.workspace;
+ const usableKey = own?.hasApiKey && !own.apiKeyUnreadable && !form.clearApiKey;
+ if (!usableKey) return 'Enter an Anthropic API key.';
+ }
+ if (fields.threshold) {
+ const threshold = parsedThreshold(form.threshold);
+ if (threshold !== null && !(threshold >= 0 && threshold <= 1)) {
+ return 'The threshold must be between 0 and 1.';
+ }
+ }
+ return null;
+}
+
+/**
+ * The body a save or a test sends for the form; null for the server default,
+ * which is not saved but returned to (`DELETE`). A blank key is left out, so
+ * the stored one is kept.
+ */
+export function inputFor(form: DecisionForm): DecisionSettingsInput | null {
+ if (form.choice === 'server_default') return null;
+ const fields = choiceFields(form.choice);
+ const apiKey = form.apiKey.trim();
+ return {
+ backend: form.choice,
+ ...(fields.endpoint ? { endpoint: form.endpoint.trim() } : {}),
+ ...(fields.key && apiKey !== '' ? { apiKey } : {}),
+ ...(fields.key && apiKey === '' && form.clearApiKey ? { clearApiKey: true } : {}),
+ ...(fields.threshold ? { threshold: parsedThreshold(form.threshold) } : {}),
+ };
+}
+
+/**
+ * What Test sends for the form, or why it can't run. The server default is
+ * tested as `default`, which the server runs with its own endpoint and key,
+ * so it can be tested whatever the workspace has saved.
+ */
+export function testInputFor(
+ form: DecisionForm,
+ settings: DecisionSettings
+): { input: DecisionTestInput } | { blocked: string } {
+ if (form.choice === 'none') return { blocked: 'Nothing to test: auto-route is off.' };
+ if (form.choice === 'server_default') {
+ if (!settings.serverDefault.configured) {
+ return { blocked: 'Nothing to test: this server has no decision service configured.' };
+ }
+ return { input: { backend: 'default' } };
+ }
+ const problem = formProblem(form, settings);
+ if (problem !== null) return { blocked: problem };
+ return { input: inputFor(form) as DecisionSettingsInput };
+}
+
+/** "0.42 s" */
+export function latencyText(ms: number): string {
+ return `${(ms / 1000).toFixed(2)} s`;
+}
+
+/** A test's result in a sentence: the pick, confidence and latency, or why it failed. */
+export function testOutcomeText(outcome: DecisionTestOutcome): string {
+ if (!outcome.ok) {
+ return outcome.error?.message ?? 'The test failed without saying why.';
+ }
+ const pick = outcome.agent === null ? 'Picked nobody (none)' : `Picked ${outcome.agent}`;
+ const parts = [pick];
+ if (outcome.confidence !== null) parts.push(`confidence ${outcome.confidence.toFixed(2)}`);
+ if (outcome.latencyMs !== null) parts.push(latencyText(outcome.latencyMs));
+ return parts.join(' · ');
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-auto-route-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-auto-route-section.tsx
new file mode 100644
index 000000000..d9b09ea1c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-auto-route-section.tsx
@@ -0,0 +1,157 @@
+import { useQueryClient } from '@tanstack/react-query';
+import { useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/lib/ui/select';
+import { Switch } from '@renderer/lib/ui/switch';
+import type { RemoteRoomDetail, RoomAutoRoute } from '@shared/core/switch-servers/switch-servers';
+
+/** The value the triage picker uses for "nobody": Select values are strings. */
+const NO_TRIAGE = '';
+
+/**
+ * A room's auto-route switch, beside `!auto-route` and writing the same
+ * setting: on, untagged messages are routed by the workspace's decision
+ * service. Where the workspace has no decision backend, or the server has the
+ * feature off, it is shown unavailable with the server's own reason, and can
+ * only be turned off. Below it, the room's optional triage agent, which gets
+ * undecided messages while the decision service is failing.
+ *
+ * Shows what the server says: the switch and picker move only once the
+ * server has answered, and a refusal leaves them as they were with the
+ * reason beside them. Only the room's owner and the workspace's admins may
+ * change it, so for anyone else both are shown but held.
+ */
+export function RoomAutoRouteSection({
+ workspaceId,
+ room,
+ autoRoute,
+ agents,
+ canManage,
+ detailKey,
+}: {
+ workspaceId: string;
+ room: Pick<RemoteRoomDetail, 'id'>;
+ autoRoute: RoomAutoRoute;
+ /** The room's agents, for the triage picker. */
+ agents: { id: string; name: string }[];
+ /** Whether the signed-in account may change it: the room's owner or a workspace admin. */
+ canManage: boolean;
+ /** The query the room's detail is read under, written back from each answer. */
+ detailKey: readonly unknown[];
+}) {
+ const queryClient = useQueryClient();
+ const [pending, setPending] = useState<'on' | 'fallback' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function change(
+ which: 'on' | 'fallback',
+ changes: { on?: boolean; fallbackAgent?: string | null }
+ ) {
+ setPending(which);
+ setError(null);
+ try {
+ const updated = await rpc.workspaces.setRoomAutoRoute({
+ workspaceId,
+ roomId: room.id,
+ ...changes,
+ });
+ queryClient.setQueryData<RemoteRoomDetail>(detailKey, (current) =>
+ current ? { ...current, autoRoute: updated } : current
+ );
+ } catch (cause) {
+ setError(failureText(cause, 'Could not change auto-route for this room.'));
+ } finally {
+ setPending(null);
+ }
+ }
+
+ // Unavailable, it can still be turned off, so a room isn't stuck "on".
+ const canFlip = canManage && pending === null && (autoRoute.available || autoRoute.on);
+ const triage = autoRoute.fallbackAgent;
+ // A triage agent that has left the room is still listed, so the setting stays visible.
+ const triageChoices =
+ triage !== null && !agents.some((agent) => agent.id === triage)
+ ? [...agents, { id: triage, name: autoRoute.fallbackAgentName ?? triage }]
+ : agents;
+ const triageName =
+ triage === null
+ ? 'None'
+ : (autoRoute.fallbackAgentName ??
+ triageChoices.find((agent) => agent.id === triage)?.name ??
+ triage);
+
+ return (
+ <section className="flex flex-col gap-3" aria-label="Auto-route">
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col gap-0.5">
+ <h2 className="text-sm font-semibold text-foreground">Auto-route</h2>
+ <p className="text-xs text-foreground-muted">
+ A message that tags nobody goes to the agent the workspace’s decision service picks. The
+ same as <code>!auto-route on</code> in the room.
+ </p>
+ </div>
+ <Switch
+ aria-label="Auto-route in this room"
+ checked={autoRoute.on}
+ disabled={!canFlip}
+ onCheckedChange={(on) => void change('on', { on })}
+ />
+ </div>
+
+ {!autoRoute.available && (
+ <p className="text-xs text-foreground-warning" role="note">
+ {autoRoute.on ? 'On, but unavailable: ' : 'Unavailable: '}
+ {autoRoute.reason ?? 'the server did not say why.'}
+ </p>
+ )}
+
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-sm text-foreground-muted">
+ Triage agent while auto-route is unavailable
+ </span>
+ <span className="text-xs text-foreground-muted">
+ Gets the messages auto-route can’t decide while the decision service is failing.
+ Otherwise they go to nobody.
+ </span>
+ </div>
+ <Select
+ value={autoRoute.fallbackAgent ?? NO_TRIAGE}
+ disabled={!canManage || pending !== null}
+ onValueChange={(next) =>
+ void change('fallback', {
+ fallbackAgent: next === NO_TRIAGE || next === null ? null : next,
+ })
+ }
+ >
+ <SelectTrigger aria-label="Triage agent" className="w-48 shrink-0">
+ <SelectValue>{triageName}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NO_TRIAGE}>None</SelectItem>
+ {triageChoices.map((agent) => (
+ <SelectItem key={agent.id} value={agent.id}>
+ {agent.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {!canManage && (
+ <p className="text-xs text-foreground-muted">
+ Only the room’s owner or a workspace admin can change these.
+ </p>
+ )}
+ {pending !== null && <span className="text-xs text-foreground-muted">Saving…</span>}
+ {error !== null && <p className="text-xs text-destructive">Not changed — {error}</p>}
+ </section>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index f55584b8e..680815163 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -15,15 +15,17 @@ import { describeFailure, failureText } from '@renderer/lib/errors/describe-fail
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import { Textarea } from '@renderer/lib/ui/textarea';
import { cn } from '@renderer/utils/utils';
import { type ChatSummary } from '@shared/core/chats/chats';
import type { RemoteRoomDetail } from '@shared/core/switch-servers/switch-servers';
+import { RoomAutoRouteSection } from './room-auto-route-section';
import { channelOnDeleteSummary } from './room-delete-wording';
import { roomTitle } from './room-labels';
-import { roomDetailKey, useRoomDetail } from './room-participants';
+import { agentNameFor, roomDetailKey, useRoomDetail } from './room-participants';
import {
AccessAndGroupFields,
ArchiveRoomSection,
@@ -194,6 +196,15 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
permissions={permissions}
administersWorkspace={administersWorkspaceById(workspaceId)}
/>
+ {/* Absent from a server that predates decision routing. */}
+ {room.autoRoute && (
+ <AutoRouteSection
+ workspaceId={workspaceId}
+ room={room}
+ autoRoute={room.autoRoute}
+ canManage={permissions.canManage}
+ />
+ )}
<RolesSection workspaceId={workspaceId} room={room} permissions={permissions} />
<RoomInfoSection room={room} />
<section
@@ -511,6 +522,36 @@ function Field({
);
}
+/** The room's auto-route switch and triage agent, offering the room's own agents. */
+const AutoRouteSection = observer(function AutoRouteSection({
+ workspaceId,
+ room,
+ autoRoute,
+ canManage,
+}: {
+ workspaceId: string;
+ room: RemoteRoomDetail;
+ autoRoute: NonNullable<RemoteRoomDetail['autoRoute']>;
+ canManage: boolean;
+}) {
+ const remoteAgents = useWorkspaceAgents(workspaceId);
+ const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));
+ const agents = room.agentIds.map((id) => ({
+ id,
+ name: agentNameFor(id, workspaceId, remoteById),
+ }));
+ return (
+ <RoomAutoRouteSection
+ workspaceId={workspaceId}
+ room={room}
+ autoRoute={autoRoute}
+ agents={agents}
+ canManage={canManage}
+ detailKey={roomDetailKey(workspaceId, room.id)}
+ />
+ );
+});
+
function PanelNotice({
icon,
title,
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts
index 56857b618..7031601b2 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/tests/admin.test.ts
@@ -49,17 +49,22 @@ describe('the Admin page’s sections', () => {
serviceConnections: true,
};
- it('gives workspace admins its messaging apps and connector switches', () => {
+ it('gives workspace admins its messaging apps, connector switches and decision routing', () => {
expect(adminGroups({ ...person, administers: true })).toEqual([
- { scope: 'workspace', items: ['messaging-apps', 'connectors'] },
+ { scope: 'workspace', items: ['messaging-apps', 'connectors', 'decision'] },
]);
expect(adminGroups(person)).toEqual([]);
});
+ it('hides decision routing from a member who is not the workspace’s admin', () => {
+ const member = adminGroups({ ...person, serviceConnections: false });
+ expect(member.flatMap((group) => group.items)).not.toContain('decision');
+ });
+
it('gives the server’s operator Switch Trust, and connector apps only on a Switch with no gateway', () => {
const operator = { ...person, administers: true, operator: true };
expect(adminGroups(operator)).toEqual([
- { scope: 'workspace', items: ['messaging-apps', 'connectors'] },
+ { scope: 'workspace', items: ['messaging-apps', 'connectors', 'decision'] },
{ scope: 'server', items: ['switch-trust'] },
]);
expect(adminGroups({ ...operator, operatesGatewaylessServer: true })[1]).toEqual({
@@ -68,7 +73,7 @@ describe('the Admin page’s sections', () => {
});
});
- it('keeps only the connector sections behind service connections', () => {
+ it('keeps only the connector sections behind service connections, not decision routing', () => {
expect(
adminGroups({
administers: true,
@@ -77,7 +82,7 @@ describe('the Admin page’s sections', () => {
serviceConnections: false,
})
).toEqual([
- { scope: 'workspace', items: ['messaging-apps'] },
+ { scope: 'workspace', items: ['messaging-apps', 'decision'] },
{ scope: 'server', items: ['switch-trust'] },
]);
});
@@ -93,7 +98,10 @@ describe('the Admin page’s sections', () => {
expect(shownAdminSection(operator, 'apps')).toBe('apps');
expect(shownAdminSection(admin, 'apps')).toBe('messaging-apps');
expect(shownAdminSection(admin, 'connectors')).toBe('connectors');
+ expect(shownAdminSection(admin, 'decision')).toBe('decision');
expect(shownAdminSection([], 'connectors')).toBeNull();
+ const off = adminGroups({ ...person, administers: true, serviceConnections: false });
+ expect(shownAdminSection(off, 'connectors')).toBe('messaging-apps');
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx
index 9368d8861..8e9c5a4c8 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/admin-page.test.tsx
@@ -31,6 +31,7 @@ const featureFlags = vi.hoisted(() => ({
})),
}));
const switchServers = vi.hoisted(() => ({
+ getDecisionSettings: vi.fn(),
getConnectorApps: vi.fn(),
checkConnectorApp: vi.fn(),
saveConnectorApp: vi.fn(),
@@ -194,7 +195,7 @@ it('lists its sections under what they reach, and each service as a tile with wh
expect(workspaces.getWorkspaceServices).toHaveBeenCalledWith('workspace');
expect(page.textContent).toContain('Choose which services people in Acme can connect');
const workspace = page.querySelector('nav [role="group"][aria-label="Workspace"]')!;
- expect(workspace.textContent).toBe('Workspace · AcmeMessaging appsConnectors');
+ expect(workspace.textContent).toBe('Workspace · AcmeMessaging appsConnectorsDecision routing');
expect(workspace.querySelector('[aria-current="page"]')!.textContent).toBe('Connectors');
expect(page.querySelector('nav [role="group"][aria-label="Server"]')).toBeNull();
expect(tiles(page)!.textContent).toContain('3 members connected · 2 agents use it');
@@ -287,6 +288,65 @@ it('tells someone who administers nothing whom to ask, asking the server nothing
expect(page.textContent).toContain('Ask a workspace admin to change these.')
);
expect(workspaces.getWorkspaceServices).not.toHaveBeenCalled();
+ expect(page.textContent).not.toContain('Decision routing');
+ expect(switchServers.getDecisionSettings).not.toHaveBeenCalled();
+});
+
+it('gives the workspace’s admins Decision routing under Workspace, with service connections off too', async () => {
+ featureFlags.get.mockResolvedValueOnce({
+ success: true,
+ data: {
+ serverId: 'server',
+ flags: { service_connections: false },
+ fetchedAt: 1,
+ error: null,
+ },
+ });
+ switchServers.getDecisionSettings.mockResolvedValue({
+ kind: 'loaded',
+ settings: {
+ source: 'server_default',
+ effective: {
+ backend: 'endpoint',
+ endpoint: 'http://decision:8230',
+ threshold: null,
+ available: true,
+ reason: null,
+ },
+ workspace: null,
+ serverDefault: { configured: true, endpoint: 'http://decision:8230', hasApiKey: false },
+ options: { haikuAnthropic: true, haikuBedrock: false },
+ },
+ });
+ navigation.navigate('admin', { section: 'decision' });
+ const page = await render();
+
+ await vi.waitFor(() =>
+ expect(page.textContent).toContain('This workspace uses the server default')
+ );
+ expect(switchServers.getDecisionSettings).toHaveBeenCalledWith('workspace');
+ const workspace = page.querySelector('nav [role="group"][aria-label="Workspace"]')!;
+ expect(workspace.textContent).toBe('Workspace · AcmeMessaging appsDecision routing');
+ expect(workspace.querySelector('[aria-current="page"]')!.textContent).toBe('Decision routing');
+ expect(workspaces.getWorkspaceServices).not.toHaveBeenCalled();
+});
+
+it('opens Decision routing from its menu entry beside Connectors', async () => {
+ workspaces.getWorkspaceServices.mockResolvedValue(SERVICES);
+ switchServers.getDecisionSettings.mockResolvedValue({ kind: 'forbidden' });
+ const page = await render();
+ await vi.waitFor(() => expect(tiles(page)).not.toBeNull());
+
+ const entry = [...page.querySelectorAll<HTMLElement>('nav button')].find(
+ (button) => button.textContent === 'Decision routing'
+ )!;
+ await act(async () => entry.click());
+
+ await vi.waitFor(() =>
+ expect(page.textContent).toContain(
+ 'Only an admin of this workspace can view or change its decision routing.'
+ )
+ );
});
function connectorApp(overrides: Partial<ConnectorApp>): ConnectorApp {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/decision-routing-section.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/decision-routing-section.test.tsx
new file mode 100644
index 000000000..89324bfea
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/decision-routing-section.test.tsx
@@ -0,0 +1,408 @@
+/**
+ * A workspace's decision routing on the Admin page: which setting applies
+ * (its own or the server's default), the backends the server can run, a key
+ * shown only by its last four characters, a save that shows what the server
+ * stored, a return to the server default, and a test of the values as
+ * entered, showing the pick, confidence and latency or why it failed.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { DecisionSettings } from '@shared/core/switch-servers/switch-servers';
+
+const switchServers = vi.hoisted(() => ({
+ getDecisionSettings: vi.fn(),
+ updateDecisionSettings: vi.fn(),
+ clearDecisionSettings: vi.fn(),
+ testDecisionSettings: vi.fn(),
+}));
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: { switchServers },
+}));
+
+import { DecisionRoutingSection } from '@renderer/features/admin/decision-routing-section';
+
+const SERVER_DEFAULT: DecisionSettings = {
+ source: 'server_default',
+ effective: {
+ backend: 'endpoint',
+ endpoint: 'http://decision:8230',
+ threshold: null,
+ available: true,
+ reason: null,
+ },
+ workspace: null,
+ serverDefault: { configured: true, endpoint: 'http://decision:8230', hasApiKey: false },
+ options: { haikuAnthropic: true, haikuBedrock: false },
+};
+
+const OWN_HAIKU: DecisionSettings = {
+ ...SERVER_DEFAULT,
+ source: 'workspace',
+ effective: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ available: true,
+ reason: null,
+ },
+ workspace: {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ hasApiKey: true,
+ apiKeyLast4: 'AwcA',
+ apiKeyUnreadable: false,
+ updatedAt: '2026-10-27T10:00:00Z',
+ },
+};
+
+const NO_SERVICE: DecisionSettings = {
+ ...SERVER_DEFAULT,
+ effective: {
+ backend: 'none',
+ endpoint: null,
+ threshold: null,
+ available: false,
+ reason:
+ 'Auto-route needs a decision service. A workspace admin can set one up in Switch Console → Admin → Decision routing.',
+ },
+ serverDefault: { configured: false, endpoint: null, hasApiKey: false },
+ options: { haikuAnthropic: false, haikuBedrock: false },
+};
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ for (const mock of Object.values(switchServers)) mock.mockReset();
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(settings: DecisionSettings | { kind: string }): Promise<HTMLElement> {
+ switchServers.getDecisionSettings.mockResolvedValue(
+ 'kind' in settings ? settings : { kind: 'loaded', settings }
+ );
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => root!.render(<DecisionRoutingSection workspaceId="ws-1" />));
+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());
+ return container;
+}
+
+/** A backend choice's own name, beside its radio and above its hint. */
+function choiceName(label: HTMLLabelElement): string {
+ return label.querySelector(':scope > span:last-child > span:first-child')?.textContent ?? '';
+}
+
+function choices(el: HTMLElement): string[] {
+ return [...el.querySelectorAll('label')]
+ .filter((label) => label.querySelector('[role="radio"]'))
+ .map(choiceName);
+}
+
+async function choose(el: HTMLElement, choice: string) {
+ const label = [...el.querySelectorAll('label')].find(
+ (candidate) => candidate.querySelector('[role="radio"]') && choiceName(candidate) === choice
+ );
+ if (!label) throw new Error(`no choice ${choice}`);
+ await act(async () => label.querySelector<HTMLElement>('[role="radio"]')!.click());
+}
+
+function button(el: HTMLElement, text: string | RegExp): HTMLButtonElement {
+ const found = [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>
+ typeof text === 'string' ? b.textContent?.trim() === text : text.test(b.textContent ?? '')
+ );
+ if (!found) throw new Error(`no button ${text}`);
+ return found;
+}
+
+async function type(field: HTMLInputElement, value: string) {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(field, value);
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+function field(el: HTMLElement, id: string): HTMLInputElement {
+ const input = el.querySelector<HTMLInputElement>(`#${id}`);
+ if (!input) throw new Error(`no field ${id}`);
+ return input;
+}
+
+it('says the server default applies, what it is, and offers Haiku but not Bedrock', async () => {
+ const el = await render(SERVER_DEFAULT);
+
+ expect(switchServers.getDecisionSettings).toHaveBeenCalledWith('ws-1');
+ expect(el.textContent).toContain(
+ 'This workspace uses the server default: self-hosted decision service (http://decision:8230).'
+ );
+ expect(choices(el)).toEqual([
+ 'Use server default',
+ 'None',
+ 'Self-hosted endpoint',
+ 'Haiku (Anthropic API)',
+ ]);
+ expect(el.textContent).toContain('Haiku on Bedrock isn’t offered');
+ // Nothing to save while the server default is chosen and applies.
+ expect(button(el, 'Save').disabled).toBe(true);
+ expect(
+ [...el.querySelectorAll('button')].some((b) => b.textContent === 'Use server default')
+ ).toBe(false);
+});
+
+it('explains why Haiku is missing, and why auto-route is unavailable, on a server without a decision service', async () => {
+ const el = await render(NO_SERVICE);
+
+ expect(choices(el)).toEqual(['Use server default', 'None', 'Self-hosted endpoint']);
+ expect(el.textContent).toContain('this server has none configured');
+ expect(el.textContent).toContain('none — this server has no decision service configured');
+ expect(el.querySelector('[role="alert"]')?.textContent).toContain(
+ 'Auto-route needs a decision service.'
+ );
+ expect(button(el, 'Test').disabled).toBe(true);
+});
+
+it('shows the workspace’s own setting and a stored key only by its last four characters', async () => {
+ const el = await render(OWN_HAIKU);
+
+ expect(el.textContent).toContain('This workspace’s own setting applies: Haiku (Anthropic API).');
+ expect(el.textContent).toContain('(set, ending in AwcA)');
+ expect(field(el, 'decision-key').value).toBe('');
+ expect(field(el, 'decision-threshold').value).toBe('0.4');
+ expect(button(el, 'Use server default')).toBeTruthy();
+});
+
+it('says a key it can no longer read is unreadable, and still lets a new one be saved', async () => {
+ const el = await render({
+ ...OWN_HAIKU,
+ workspace: { ...OWN_HAIKU.workspace!, apiKeyLast4: null, apiKeyUnreadable: true },
+ });
+
+ expect(el.textContent).toContain('set but unreadable — enter a new key to replace it');
+ expect(button(el, 'Save').disabled).toBe(true);
+ await type(field(el, 'decision-key'), 'fake-key');
+ expect(button(el, 'Save').disabled).toBe(false);
+});
+
+it('saves a self-hosted endpoint, then shows what the server stored', async () => {
+ const stored: DecisionSettings = {
+ ...SERVER_DEFAULT,
+ source: 'workspace',
+ effective: {
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+ available: true,
+ reason: null,
+ },
+ workspace: {
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+ hasApiKey: false,
+ apiKeyLast4: null,
+ apiKeyUnreadable: false,
+ updatedAt: '2026-10-27T10:00:00Z',
+ },
+ };
+ switchServers.updateDecisionSettings.mockResolvedValue({ kind: 'saved', settings: stored });
+ const el = await render(SERVER_DEFAULT);
+
+ await choose(el, 'Self-hosted endpoint');
+ expect(button(el, 'Save').disabled).toBe(true);
+ await type(field(el, 'decision-endpoint'), 'https://decide.example');
+ await type(field(el, 'decision-threshold'), '0.5');
+ await act(async () => button(el, 'Save').click());
+
+ expect(switchServers.updateDecisionSettings).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: 0.5,
+ });
+ await vi.waitFor(() =>
+ expect(el.textContent).toContain(
+ 'This workspace’s own setting applies: Self-hosted endpoint (https://decide.example).'
+ )
+ );
+ expect(el.textContent).toContain('Saved.');
+});
+
+it('holds a threshold outside 0 to 1, and shows a refusal from the server in its words', async () => {
+ switchServers.updateDecisionSettings.mockResolvedValue({
+ kind: 'invalid',
+ message: 'threshold: Input should be less than or equal to 1',
+ });
+ const el = await render(SERVER_DEFAULT);
+ await choose(el, 'Self-hosted endpoint');
+ await type(field(el, 'decision-endpoint'), 'https://decide.example');
+
+ await type(field(el, 'decision-threshold'), '1.5');
+ expect(el.textContent).toContain('The threshold must be between 0 and 1.');
+ expect(button(el, 'Save').disabled).toBe(true);
+
+ await type(field(el, 'decision-threshold'), '1');
+ await act(async () => button(el, 'Save').click());
+ await vi.waitFor(() =>
+ expect(el.textContent).toContain(
+ 'Not saved — threshold: Input should be less than or equal to 1'
+ )
+ );
+ expect(el.textContent).toContain('This workspace uses the server default');
+});
+
+it('returns the workspace to the server default', async () => {
+ switchServers.clearDecisionSettings.mockResolvedValue({
+ kind: 'cleared',
+ settings: SERVER_DEFAULT,
+ });
+ const el = await render(OWN_HAIKU);
+
+ await act(async () => button(el, 'Use server default').click());
+
+ expect(switchServers.clearDecisionSettings).toHaveBeenCalledWith('ws-1');
+ await vi.waitFor(() =>
+ expect(el.textContent).toContain('This workspace uses the server default')
+ );
+});
+
+it('tests the unsaved values and shows the pick, confidence and latency', async () => {
+ switchServers.testDecisionSettings.mockResolvedValue({
+ kind: 'tested',
+ outcome: {
+ ok: true,
+ agent: 'deploy-bot',
+ modelChoice: 'deploy-bot',
+ confidence: 0.91,
+ latencyMs: 420,
+ backend: 'endpoint',
+ error: null,
+ },
+ });
+ const el = await render(SERVER_DEFAULT);
+ await choose(el, 'Self-hosted endpoint');
+ await type(field(el, 'decision-endpoint'), 'https://decide.example');
+
+ await act(async () => button(el, 'Test').click());
+
+ expect(switchServers.testDecisionSettings).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ backend: 'endpoint',
+ endpoint: 'https://decide.example',
+ threshold: null,
+ });
+ expect(switchServers.updateDecisionSettings).not.toHaveBeenCalled();
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Test result"]')?.textContent).toBe(
+ 'Picked deploy-bot · confidence 0.91 · 0.42 s'
+ )
+ );
+});
+
+it('tests the server default it uses', async () => {
+ switchServers.testDecisionSettings.mockResolvedValue({
+ kind: 'tested',
+ outcome: {
+ ok: true,
+ agent: null,
+ modelChoice: 'none',
+ confidence: 0.2,
+ latencyMs: 380,
+ backend: 'endpoint',
+ error: null,
+ },
+ });
+ const el = await render(SERVER_DEFAULT);
+
+ await act(async () => button(el, 'Test').click());
+
+ expect(switchServers.testDecisionSettings).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ backend: 'default',
+ });
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Test result"]')?.textContent).toBe(
+ 'Picked nobody (none) · confidence 0.20 · 0.38 s'
+ )
+ );
+});
+
+it('tests the server default before returning to it, whatever the workspace saved', async () => {
+ switchServers.testDecisionSettings.mockResolvedValue({
+ kind: 'tested',
+ outcome: {
+ ok: true,
+ agent: 'deploy-bot',
+ modelChoice: 'deploy-bot',
+ confidence: 0.8,
+ latencyMs: 300,
+ backend: 'default',
+ error: null,
+ },
+ });
+ const el = await render(OWN_HAIKU);
+ await choose(el, 'Use server default');
+
+ await act(async () => button(el, 'Test').click());
+
+ expect(switchServers.testDecisionSettings).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ backend: 'default',
+ });
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Test result"]')?.textContent).toBe(
+ 'Picked deploy-bot · confidence 0.80 · 0.30 s'
+ )
+ );
+ expect(switchServers.clearDecisionSettings).not.toHaveBeenCalled();
+});
+
+it('shows why a test failed, saving nothing', async () => {
+ switchServers.testDecisionSettings.mockResolvedValue({
+ kind: 'tested',
+ outcome: {
+ ok: false,
+ agent: null,
+ modelChoice: null,
+ confidence: null,
+ latencyMs: null,
+ backend: 'haiku_anthropic',
+ error: { code: 'key_refused', message: 'The Anthropic API refused the key.' },
+ },
+ });
+ const el = await render(SERVER_DEFAULT);
+ await choose(el, 'Haiku (Anthropic API)');
+ await type(field(el, 'decision-key'), 'sk-wrong');
+
+ await act(async () => button(el, 'Test').click());
+
+ expect(switchServers.testDecisionSettings).toHaveBeenCalledWith(
+ expect.objectContaining({ backend: 'haiku_anthropic', apiKey: 'sk-wrong' })
+ );
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Test result"]')?.textContent).toBe(
+ 'Test failed — The Anthropic API refused the key.'
+ )
+ );
+ expect(switchServers.updateDecisionSettings).not.toHaveBeenCalled();
+});
+
+it('tells a member who is not the workspace’s admin that it is theirs to change', async () => {
+ const el = await render({ kind: 'forbidden' });
+
+ expect(el.textContent).toContain(
+ 'Only an admin of this workspace can view or change its decision routing.'
+ );
+ expect(el.querySelector('[role="radio"]')).toBeNull();
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-auto-route.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-auto-route.test.tsx
new file mode 100644
index 000000000..97999f07b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-auto-route.test.tsx
@@ -0,0 +1,296 @@
+/**
+ * A room's auto-route switch on its settings page, beside `!auto-route` and
+ * writing the same setting. It shows what the server says: on or off, and,
+ * where the workspace has no decision backend, unavailable with the server's
+ * own reason. Below it, the room's triage agent for while auto-route is
+ * unavailable, picked from the room's own agents.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { RoomAutoRoute } from '@shared/core/switch-servers/switch-servers';
+
+const getRoomDetail = vi.hoisted(() => vi.fn());
+const setRoomAutoRoute = vi.hoisted(() => vi.fn());
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: {
+ workspaces: {
+ getRoomDetail,
+ setRoomAutoRoute,
+ updateRoom: vi.fn(),
+ listAgents: vi.fn(() =>
+ Promise.resolve([
+ { id: 'agent-deploy', name: 'deploy-bot', iconUrl: null, knownAgentType: null },
+ { id: 'agent-triage', name: 'triage-bot', iconUrl: null, knownAgentType: null },
+ ])
+ ),
+ },
+ agents: { getAgents: vi.fn(() => Promise.resolve([])) },
+ },
+}));
+
+const access = vi.hoisted(() => ({ administers: true }));
+
+vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({
+ administersWorkspaceInScope: () => access.administers,
+ operatesServer: () => false,
+}));
+
+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
+ switchRoomsStore: {
+ roomWorkspaceId: () => 'ws-1',
+ roomServerId: () => 'server-1',
+ canDeleteRoom: () => false,
+ },
+}));
+
+import { RoomConfigurationPanel } from '@renderer/features/switch-rooms/room-configuration-panel';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+
+const NO_BACKEND =
+ 'Auto-route needs a decision service. A workspace admin can set one up in Switch Console → Admin → Decision routing.';
+
+const OFF: RoomAutoRoute = {
+ on: false,
+ available: true,
+ reason: null,
+ fallbackAgent: null,
+ fallbackAgentName: null,
+};
+
+function room(autoRoute: RoomAutoRoute | undefined, ownerId: string | null = null) {
+ return {
+ id: 'room-1',
+ ownerId,
+ name: 'ops',
+ description: '',
+ instructions: null,
+ bridgeType: null,
+ bridgeDisplayName: null,
+ externalChannelUrl: null,
+ agentIds: ['agent-deploy', 'agent-triage'],
+ connectedUserNames: [],
+ ...(autoRoute ? { autoRoute } : {}),
+ };
+}
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ access.administers = true;
+ vi.spyOn(workspacesStore, 'serverIdFor').mockReturnValue('server-1');
+ getRoomDetail.mockReset();
+ setRoomAutoRoute.mockReset();
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render(
+ autoRoute: RoomAutoRoute | undefined,
+ ownerId: string | null = null
+): Promise<HTMLElement> {
+ getRoomDetail.mockResolvedValue(room(autoRoute, ownerId));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <RoomConfigurationPanel roomId="room-1" />
+ </QueryClientProvider>
+ )
+ );
+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());
+ return container;
+}
+
+function toggle(el: HTMLElement): HTMLElement {
+ const found = el.querySelector<HTMLElement>(
+ '[role="switch"][aria-label="Auto-route in this room"]'
+ );
+ if (!found) throw new Error('no auto-route switch');
+ return found;
+}
+
+function checked(el: HTMLElement): boolean {
+ return toggle(el).getAttribute('aria-checked') === 'true';
+}
+
+function disabled(el: HTMLElement): boolean {
+ const t = toggle(el);
+ return t.hasAttribute('data-disabled') || t.getAttribute('aria-disabled') === 'true';
+}
+
+async function pickTriage(el: HTMLElement, choice: string) {
+ await act(async () => el.querySelector<HTMLElement>('[aria-label="Triage agent"]')!.click());
+ await vi.waitFor(() =>
+ expect(document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0)
+ );
+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (candidate) => candidate.textContent?.trim() === choice
+ );
+ if (!option) throw new Error(`no option ${choice}`);
+ await act(async () => option.click());
+}
+
+it('shows nothing for a server that predates auto-route', async () => {
+ const el = await render(undefined);
+
+ expect(el.textContent).toContain('General');
+ expect(el.querySelector('[aria-label="Auto-route in this room"]')).toBeNull();
+});
+
+it('turns auto-route on, and shows it on once the server says so', async () => {
+ setRoomAutoRoute.mockResolvedValue({ ...OFF, on: true });
+ const el = await render(OFF);
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+ expect(checked(el)).toBe(false);
+
+ await act(async () => toggle(el).click());
+
+ expect(setRoomAutoRoute).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ roomId: 'room-1',
+ on: true,
+ });
+ await vi.waitFor(() => expect(checked(el)).toBe(true));
+});
+
+it('turns auto-route off', async () => {
+ setRoomAutoRoute.mockResolvedValue(OFF);
+ const el = await render({ ...OFF, on: true });
+ await vi.waitFor(() => expect(checked(el)).toBe(true));
+
+ await act(async () => toggle(el).click());
+
+ expect(setRoomAutoRoute).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ roomId: 'room-1',
+ on: false,
+ });
+ await vi.waitFor(() => expect(checked(el)).toBe(false));
+});
+
+it('leaves the switch as it was when the server refuses, with the reason', async () => {
+ setRoomAutoRoute.mockRejectedValue(new Error('Only a room admin can change auto-route.'));
+ const el = await render(OFF);
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+
+ await act(async () => toggle(el).click());
+
+ await vi.waitFor(() => expect(el.textContent).toContain('Not changed —'));
+ expect(el.textContent).toContain('Only a room admin can change auto-route.');
+ expect(checked(el)).toBe(false);
+});
+
+it('shows auto-route unavailable with the server’s reason, and holds the switch', async () => {
+ const el = await render({
+ on: false,
+ available: false,
+ reason: NO_BACKEND,
+ fallbackAgent: null,
+ fallbackAgentName: null,
+ });
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+
+ expect(el.textContent).toContain(`Unavailable: ${NO_BACKEND}`);
+ expect(disabled(el)).toBe(true);
+});
+
+it('still lets auto-route be turned off where it is on but unavailable', async () => {
+ const el = await render({
+ on: true,
+ available: false,
+ reason: NO_BACKEND,
+ fallbackAgent: null,
+ fallbackAgentName: null,
+ });
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+
+ expect(el.textContent).toContain(`On, but unavailable: ${NO_BACKEND}`);
+ expect(disabled(el)).toBe(false);
+});
+
+it('names the room’s triage agent from its own agents, and clears it', async () => {
+ setRoomAutoRoute.mockResolvedValueOnce({
+ ...OFF,
+ fallbackAgent: 'agent-triage',
+ fallbackAgentName: 'triage-bot',
+ });
+ const el = await render(OFF);
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Triage agent"]')?.textContent).toContain('None')
+ );
+
+ await pickTriage(el, 'triage-bot');
+
+ expect(setRoomAutoRoute).toHaveBeenCalledWith({
+ workspaceId: 'ws-1',
+ roomId: 'room-1',
+ fallbackAgent: 'agent-triage',
+ });
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Triage agent"]')?.textContent).toContain('triage-bot')
+ );
+
+ setRoomAutoRoute.mockResolvedValueOnce(OFF);
+ await pickTriage(el, 'None');
+ expect(setRoomAutoRoute).toHaveBeenLastCalledWith({
+ workspaceId: 'ws-1',
+ roomId: 'room-1',
+ fallbackAgent: null,
+ });
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Triage agent"]')?.textContent).toContain('None')
+ );
+});
+
+it('names a triage agent by the name the server gives, even one that has left the room', async () => {
+ const el = await render({ ...OFF, fallbackAgent: 'agent-gone', fallbackAgentName: 'old-triage' });
+
+ await vi.waitFor(() =>
+ expect(el.querySelector('[aria-label="Triage agent"]')?.textContent).toContain('old-triage')
+ );
+});
+
+it('holds the switch and picker for someone who neither owns the room nor administers the workspace', async () => {
+ access.administers = false;
+ const el = await render({ ...OFF, on: true });
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+
+ expect(checked(el)).toBe(true);
+ expect(disabled(el)).toBe(true);
+ const picker = el.querySelector<HTMLElement>('[aria-label="Triage agent"]')!;
+ expect(picker.hasAttribute('data-disabled') || picker.hasAttribute('disabled')).toBe(true);
+ expect(el.textContent).toContain('Only the room’s owner or a workspace admin can change these.');
+});
+
+it('lets the room’s owner change it without administering the workspace', async () => {
+ access.administers = false;
+ vi.spyOn(switchServersStore, 'statusFor').mockReturnValue({
+ user: { id: 'user-owner' },
+ } as never);
+ const el = await render(OFF, 'user-owner');
+ await vi.waitFor(() => expect(toggle(el)).toBeTruthy());
+
+ expect(disabled(el)).toBe(false);
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/decision-routing.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/decision-routing.test.ts
new file mode 100644
index 000000000..60e1fdd65
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/decision-routing.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest';
+import {
+ appliesText,
+ formFor,
+ formProblem,
+ haikuNote,
+ inputFor,
+ latencyText,
+ offeredChoices,
+ storedKeyText,
+ testInputFor,
+ testOutcomeText,
+} from '@renderer/features/admin/decision-routing';
+import type { DecisionSettings } from '@shared/core/switch-servers/switch-servers';
+
+function settings(overrides: Partial<DecisionSettings> = {}): DecisionSettings {
+ return {
+ source: 'server_default',
+ effective: {
+ backend: 'endpoint',
+ endpoint: 'http://decision:8230',
+ threshold: null,
+ available: true,
+ reason: null,
+ },
+ workspace: null,
+ serverDefault: { configured: true, endpoint: 'http://decision:8230', hasApiKey: false },
+ options: { haikuAnthropic: true, haikuBedrock: false },
+ ...overrides,
+ };
+}
+
+const OWN_HAIKU: DecisionSettings['workspace'] = {
+ backend: 'haiku_anthropic',
+ endpoint: null,
+ threshold: 0.4,
+ hasApiKey: true,
+ apiKeyLast4: 'AwcA',
+ apiKeyUnreadable: false,
+ updatedAt: '2026-10-27T10:00:00Z',
+};
+
+describe('decision routing settings in words', () => {
+ it('says the server default applies, and what it is', () => {
+ expect(appliesText(settings())).toBe(
+ 'This workspace uses the server default: self-hosted decision service (http://decision:8230).'
+ );
+ expect(
+ appliesText(
+ settings({ serverDefault: { configured: false, endpoint: null, hasApiKey: false } })
+ )
+ ).toBe(
+ 'This workspace uses the server default: none — this server has no decision service configured.'
+ );
+ });
+
+ it('says the workspace’s own setting applies, beside the server default', () => {
+ expect(appliesText(settings({ source: 'workspace', workspace: OWN_HAIKU }))).toBe(
+ 'This workspace’s own setting applies: Haiku (Anthropic API). The server default is self-hosted decision service (http://decision:8230).'
+ );
+ });
+
+ it('shows a stored key only by its last four characters, or as unreadable', () => {
+ expect(storedKeyText(settings())).toBeNull();
+ expect(storedKeyText(settings({ workspace: OWN_HAIKU }))).toBe('set, ending in AwcA');
+ expect(
+ storedKeyText(
+ settings({ workspace: { ...OWN_HAIKU!, apiKeyLast4: null, apiKeyUnreadable: true } })
+ )
+ ).toBe('set but unreadable — enter a new key to replace it');
+ });
+
+ it('formats a latency in seconds and a test’s outcome', () => {
+ expect(latencyText(420)).toBe('0.42 s');
+ expect(
+ testOutcomeText({
+ ok: true,
+ agent: 'deploy-bot',
+ modelChoice: 'deploy-bot',
+ confidence: 0.912,
+ latencyMs: 420,
+ backend: 'endpoint',
+ error: null,
+ })
+ ).toBe('Picked deploy-bot · confidence 0.91 · 0.42 s');
+ expect(
+ testOutcomeText({
+ ok: true,
+ agent: null,
+ modelChoice: 'none',
+ confidence: 0.3,
+ latencyMs: 1500,
+ backend: 'endpoint',
+ error: null,
+ })
+ ).toBe('Picked nobody (none) · confidence 0.30 · 1.50 s');
+ expect(
+ testOutcomeText({
+ ok: false,
+ agent: null,
+ modelChoice: null,
+ confidence: null,
+ latencyMs: null,
+ backend: 'endpoint',
+ error: { code: 'unreachable', message: 'The endpoint could not be reached within 5 s.' },
+ })
+ ).toBe('The endpoint could not be reached within 5 s.');
+ });
+});
+
+describe('the backends offered', () => {
+ it('offers Haiku only where the server runs a decision service, and Bedrock only where allowed', () => {
+ expect(offeredChoices(settings())).toEqual([
+ 'server_default',
+ 'none',
+ 'endpoint',
+ 'haiku_anthropic',
+ ]);
+ expect(
+ offeredChoices(settings({ options: { haikuAnthropic: true, haikuBedrock: true } }))
+ ).toContain('haiku_bedrock');
+ const noService = settings({ options: { haikuAnthropic: false, haikuBedrock: false } });
+ expect(offeredChoices(noService)).toEqual(['server_default', 'none', 'endpoint']);
+ expect(haikuNote(noService)).toContain('this server has none configured');
+ expect(haikuNote(settings())).toContain('Bedrock');
+ });
+
+ it('keeps a saved choice the server no longer offers, so the form shows what is stored', () => {
+ expect(
+ offeredChoices(
+ settings({
+ workspace: OWN_HAIKU,
+ options: { haikuAnthropic: false, haikuBedrock: false },
+ })
+ )
+ ).toContain('haiku_anthropic');
+ });
+});
+
+describe('the form', () => {
+ it('starts from the stored setting, never the key', () => {
+ expect(formFor(settings())).toEqual({
+ choice: 'server_default',
+ endpoint: '',
+ apiKey: '',
+ clearApiKey: false,
+ threshold: '',
+ });
+ expect(formFor(settings({ source: 'workspace', workspace: OWN_HAIKU }))).toMatchObject({
+ choice: 'haiku_anthropic',
+ apiKey: '',
+ threshold: '0.4',
+ });
+ });
+
+ it('refuses a threshold outside 0 to 1, a missing endpoint, and Haiku with no key', () => {
+ const base = formFor(settings());
+ expect(formProblem({ ...base, choice: 'endpoint', endpoint: '' }, settings())).toBe(
+ 'Enter the endpoint’s URL.'
+ );
+ expect(
+ formProblem(
+ { ...base, choice: 'endpoint', endpoint: 'https://d.example', threshold: '1.5' },
+ settings()
+ )
+ ).toBe('The threshold must be between 0 and 1.');
+ expect(
+ formProblem(
+ { ...base, choice: 'endpoint', endpoint: 'https://d.example', threshold: 'abc' },
+ settings()
+ )
+ ).toBe('The threshold must be between 0 and 1.');
+ expect(formProblem({ ...base, choice: 'haiku_anthropic' }, settings())).toBe(
+ 'Enter an Anthropic API key.'
+ );
+ expect(
+ formProblem({ ...base, choice: 'haiku_anthropic' }, settings({ workspace: OWN_HAIKU }))
+ ).toBeNull();
+ expect(formProblem({ ...base, choice: 'none' }, settings())).toBeNull();
+ });
+
+ it('sends only the fields a backend takes, keeping the stored key when none is typed', () => {
+ const base = formFor(settings());
+ expect(inputFor(base)).toBeNull();
+ expect(inputFor({ ...base, choice: 'none', endpoint: 'x', threshold: '0.3' })).toEqual({
+ backend: 'none',
+ });
+ expect(
+ inputFor({ ...base, choice: 'endpoint', endpoint: ' https://d.example ', threshold: '0.5' })
+ ).toEqual({ backend: 'endpoint', endpoint: 'https://d.example', threshold: 0.5 });
+ expect(inputFor({ ...base, choice: 'haiku_anthropic', apiKey: ' fake-key ' })).toEqual({
+ backend: 'haiku_anthropic',
+ apiKey: 'fake-key',
+ threshold: null,
+ });
+ expect(
+ inputFor({ ...base, choice: 'endpoint', endpoint: 'https://d.example', clearApiKey: true })
+ ).toMatchObject({ clearApiKey: true });
+ expect(inputFor({ ...base, choice: 'haiku_bedrock', apiKey: 'ignored' })).toEqual({
+ backend: 'haiku_bedrock',
+ threshold: null,
+ });
+ });
+
+ it('tests the server default as `default`, whatever the workspace has saved', () => {
+ const base = formFor(settings());
+ expect(testInputFor(base, settings())).toEqual({ input: { backend: 'default' } });
+ expect(testInputFor(base, settings({ source: 'workspace', workspace: OWN_HAIKU }))).toEqual({
+ input: { backend: 'default' },
+ });
+ expect(
+ testInputFor(
+ base,
+ settings({ serverDefault: { configured: false, endpoint: null, hasApiKey: false } })
+ )
+ ).toMatchObject({ blocked: expect.stringContaining('no decision service') });
+ expect(testInputFor({ ...base, choice: 'none' }, settings())).toMatchObject({
+ blocked: expect.any(String),
+ });
+ expect(
+ testInputFor({ ...base, choice: 'endpoint', endpoint: 'https://d.example' }, settings())
+ ).toEqual({ input: { backend: 'endpoint', endpoint: 'https://d.example', threshold: null } });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index 73d04da2d..fa3f4fa9a 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -432,6 +432,36 @@ export type RemoteRoomDetail = RemoteRoomSummary & {
transportRoomId: string | null;
/** When the room was archived, or null while it is in use. */
archivedAt: string | null;
+ /** Whether untagged messages here are routed by the workspace's decision
+ * service. Undefined from a server that predates decision routing. */
+ autoRoute?: RoomAutoRoute;
+};
+
+/**
+ * A room's auto-route setting (`!auto-route`) and whether it can take effect:
+ * `available` is false when the server has the feature off or the room's
+ * workspace has no decision backend, and `reason` then says what is missing
+ * and who can fix it.
+ */
+export type RoomAutoRoute = {
+ on: boolean;
+ available: boolean;
+ reason: string | null;
+ /** The id of the agent that gets undecided messages while the decision
+ * service is failing; null when nobody does. */
+ fallbackAgent: string | null;
+ /** That agent's name, for display; null when there is none, or from a
+ * server that predates it. */
+ fallbackAgentName: string | null;
+};
+
+/** A change to a room's auto-route setting (`PUT /rooms/{id}/auto-route`);
+ * a field left out is left alone. */
+export type SetRoomAutoRouteParams = {
+ workspaceId: string;
+ roomId: string;
+ on?: boolean;
+ fallbackAgent?: string | null;
};
/** `public` lets every member of the workspace in; `private` only the owner and admins. */
@@ -868,6 +898,129 @@ export type ClearTrustSettingsResult =
| { kind: 'forbidden' }
| { kind: 'error'; message: string };
+/**
+ * Who decides an untagged message in a workspace's auto-route rooms: nobody
+ * (`none`), a self-hosted decision endpoint, or Haiku run inside the server's
+ * decision service, through the Anthropic API or Amazon Bedrock.
+ */
+export type DecisionBackend = 'none' | 'endpoint' | 'haiku_anthropic' | 'haiku_bedrock';
+
+/**
+ * A workspace's decision routing settings (`GET /decision-settings`), read for
+ * the workspace the session selects. A workspace with no saved choice uses the
+ * server's default, from its environment; `source` says which applies and
+ * `effective` what that comes to.
+ *
+ * The key is never returned: `hasApiKey`/`apiKeyLast4` only confirm one is
+ * stored, and `apiKeyUnreadable` says the server can no longer decrypt it.
+ */
+export type DecisionSettings = {
+ source: 'workspace' | 'server_default';
+ effective: {
+ backend: DecisionBackend;
+ endpoint: string | null;
+ threshold: number | null;
+ available: boolean;
+ /** Why auto-route is unavailable, in the server's words; null when it is available. */
+ reason: string | null;
+ };
+ /** Null while the workspace uses the server default. */
+ workspace: {
+ backend: DecisionBackend;
+ endpoint: string | null;
+ threshold: number | null;
+ hasApiKey: boolean;
+ apiKeyLast4: string | null;
+ apiKeyUnreadable: boolean;
+ updatedAt: string;
+ } | null;
+ serverDefault: { configured: boolean; endpoint: string | null; hasApiKey: boolean };
+ /** Which Haiku backends the server can run: both need its decision service,
+ * and Bedrock also its operator's say-so. */
+ options: { haikuAnthropic: boolean; haikuBedrock: boolean };
+};
+
+/**
+ * The values a workspace admin saves or tests (`PUT /decision-settings`,
+ * `POST /decision-settings/test`). `apiKey` left unset keeps whatever key is
+ * stored, so re-saving the endpoint or threshold doesn't force re-entering
+ * the secret; `clearApiKey` removes it.
+ */
+export type DecisionSettingsInput = {
+ backend: DecisionBackend;
+ endpoint?: string | null;
+ apiKey?: string;
+ clearApiKey?: boolean;
+ threshold?: number | null;
+};
+
+/** Outcome of loading a workspace's decision settings. Its admins only, so a
+ * member who isn't one gets `forbidden` rather than an empty form. */
+export type FetchDecisionSettingsResult =
+ | { kind: 'loaded'; settings: DecisionSettings }
+ /** The server predates per-workspace decision settings. */
+ | { kind: 'unsupported' }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'error'; message: string };
+
+export type UpdateDecisionSettingsParams = { workspaceId: string } & DecisionSettingsInput;
+
+/** What a test runs against: unsaved values, or `default` for the server's
+ * own default, tested with its own endpoint and key and never the
+ * workspace's stored key. */
+export type DecisionTestInput = DecisionSettingsInput | { backend: 'default' };
+
+export type TestDecisionSettingsParams = { workspaceId: string } & DecisionTestInput;
+
+/** Outcome of saving a workspace's decision settings; `invalid` carries the
+ * server's own sentence (a threshold out of range, a bad URL, Bedrock not allowed). */
+export type UpdateDecisionSettingsResult =
+ | { kind: 'saved'; settings: DecisionSettings }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'invalid'; message: string }
+ | { kind: 'error'; message: string };
+
+/** Outcome of returning a workspace to the server default (`DELETE /decision-settings`),
+ * with the settings as they now stand. */
+export type ClearDecisionSettingsResult =
+ | { kind: 'cleared'; settings: DecisionSettings }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'error'; message: string };
+
+export type DecisionTestErrorCode =
+ | 'unreachable'
+ | 'timeout'
+ | 'unauthorized'
+ | 'key_refused'
+ | 'bad_answer'
+ | 'backend_unavailable'
+ | 'not_configured';
+
+/** One sample decision run against unsaved values: the pick (null for none),
+ * its confidence and latency, or why it failed. */
+export type DecisionTestOutcome = {
+ ok: boolean;
+ agent: string | null;
+ modelChoice: string | null;
+ confidence: number | null;
+ latencyMs: number | null;
+ backend: string | null;
+ error: { code: DecisionTestErrorCode | string; message: string } | null;
+};
+
+/** Outcome of asking the server to test decision settings. A failed test is
+ * still `tested`, with the failure in the outcome; the other kinds are about
+ * the request itself. */
+export type TestDecisionSettingsResult =
+ | { kind: 'tested'; outcome: DecisionTestOutcome }
+ | { kind: 'unauthenticated' }
+ | { kind: 'forbidden' }
+ | { kind: 'invalid'; message: string }
+ | { kind: 'error'; message: string };
+
/** A bridged (external) human identity on a server. The `users` dimension of an
* addressing policy keys off these ids. */
export type RemoteExternalUser = {
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 0cf8b4bc3..61f3e404a 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -214,6 +214,29 @@ export interface RoomDetail extends RoomSummary {
// Agent ids configured to receive room_join events in this room.
join_event_listeners: string[];
archived_at: string | null;
+ /** Absent on servers that predate decision routing. */
+ auto_route?: RoomAutoRoute;
+}
+
+/**
+ * Whether untagged messages in the room are routed by the workspace's decision
+ * service (`!auto-route`), and whether they can be: `available` is false when
+ * the server has the feature off or the workspace has no decision backend, and
+ * `reason` then says what is missing and who can fix it.
+ */
+export interface RoomAutoRoute {
+ on: boolean;
+ available: boolean;
+ reason: string | null;
+ /** The id of the agent that gets undecided messages while the decision service is failing. */
+ fallback_agent: string | null;
+ /** That agent's name, for display. Absent on servers that predate it. */
+ fallback_agent_name?: string | null;
+}
+
+export interface SetRoomAutoRouteInput {
+ on?: boolean;
+ fallback_agent?: string | null;
}
export interface CreateRoomInput {
@@ -502,6 +525,13 @@ export async function setRoomAgentJoinEvents(
});
}
+export async function setRoomAutoRoute(
+ roomId: string,
+ input: SetRoomAutoRouteInput,
+): Promise<RoomAutoRoute> {
+ return jsonRequest<RoomAutoRoute>(`/rooms/${roomId}/auto-route`, "PUT", input);
+}
+
export async function addRoomUsers(
roomId: string,
userNames: string[],
diff --git a/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx b/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx
new file mode 100644
index 000000000..7d7d9aad3
--- /dev/null
+++ b/gateway/src/pages/rooms/RoomAutoRouteSection.test.tsx
@@ -0,0 +1,212 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { AgentSummary, RoomAutoRoute, RoomDetail } from "../../data/api";
+import RoomAutoRouteSection from "./RoomAutoRouteSection";
+
+const NO_BACKEND =
+ "Auto-route needs a decision service. A workspace admin can set one up in Switch Console → Admin → Decision routing.";
+
+function agent(id: string, name: string): AgentSummary {
+ return {
+ id,
+ name,
+ display_name: null,
+ description: "",
+ connector_type: "claude_code",
+ connection_model: "auto_session",
+ tool_count: 0,
+ model_count: 0,
+ owner_id: "u1",
+ owner_name: "ada",
+ oauth_client_id: null,
+ created_at: "2026-10-01T00:00:00Z",
+ parent_agent_id: null,
+ known_agent_type: "claude-code",
+ known_agent_options: null,
+ };
+}
+
+const room = {
+ id: "r1",
+ name: "support",
+ agent_ids: ["a1", "a2"],
+} as RoomDetail;
+
+const AGENTS = [agent("a1", "deploy-bot"), agent("a2", "triage-bot"), agent("a3", "elsewhere")];
+
+type Call = { path: string; method: string; body: unknown };
+
+function mockServer(answer: (body: Record<string, unknown>) => Response) {
+ const calls: Call[] = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const path = String(input);
+ const method = init?.method ?? "GET";
+ const body = init?.body ? JSON.parse(String(init.body)) : null;
+ calls.push({ path, method, body });
+ if (path === "/gateway/agents") return new Response(JSON.stringify(AGENTS));
+ if (path === "/gateway/rooms/r1/auto-route" && method === "PUT") return answer(body);
+ return new Response(JSON.stringify({ detail: "Not Found" }), { status: 404 });
+ }),
+ );
+ return calls;
+}
+
+function toggle(): HTMLInputElement {
+ return screen.getByRole("switch") as HTMLInputElement;
+}
+
+function routed(state: RoomAutoRoute): Response {
+ return new Response(JSON.stringify(state));
+}
+
+const OFF: RoomAutoRoute = { on: false, available: true, reason: null, fallback_agent: null };
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("RoomAutoRouteSection", () => {
+ it("turns auto-route on, and shows on only once the server says so", async () => {
+ const calls = mockServer((body) => routed({ ...OFF, on: body.on as boolean }));
+ render(<RoomAutoRouteSection room={room} autoRoute={OFF} canManage />);
+
+ expect(toggle().checked).toBe(false);
+ screen.getByText("Off");
+ fireEvent.click(toggle());
+
+ await waitFor(() => expect(toggle().checked).toBe(true));
+ screen.getByText("On");
+ expect(calls.filter((c) => c.method === "PUT")).toEqual([
+ { path: "/gateway/rooms/r1/auto-route", method: "PUT", body: { on: true } },
+ ]);
+ });
+
+ it("turns auto-route off", async () => {
+ const calls = mockServer((body) => routed({ ...OFF, on: body.on as boolean }));
+ render(<RoomAutoRouteSection room={room} autoRoute={{ ...OFF, on: true }} canManage />);
+
+ fireEvent.click(toggle());
+
+ await waitFor(() => expect(toggle().checked).toBe(false));
+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({ on: false });
+ });
+
+ it("leaves the toggle as it was and says why when the server refuses", async () => {
+ mockServer(
+ () => new Response(JSON.stringify({ detail: "Only a room admin can change this." }), { status: 403 }),
+ );
+ render(<RoomAutoRouteSection room={room} autoRoute={OFF} canManage />);
+
+ fireEvent.click(toggle());
+
+ await screen.findByText("Only a room admin can change this.");
+ expect(toggle().checked).toBe(false);
+ });
+
+ it("shows unavailable with the server's reason and cannot be turned on", () => {
+ mockServer(() => routed(OFF));
+ render(
+ <RoomAutoRouteSection
+ room={room}
+ autoRoute={{ ...OFF, available: false, reason: NO_BACKEND }}
+ canManage
+ />,
+ );
+
+ screen.getByText(NO_BACKEND);
+ expect(toggle().disabled).toBe(true);
+ });
+
+ it("can still be turned off where it is unavailable", () => {
+ mockServer(() => routed(OFF));
+ render(
+ <RoomAutoRouteSection
+ room={room}
+ autoRoute={{ on: true, available: false, reason: NO_BACKEND, fallback_agent: null }}
+ canManage
+ />,
+ );
+
+ expect(toggle().disabled).toBe(false);
+ });
+
+ it("is read-only for someone who neither owns the room nor administers the workspace", () => {
+ mockServer(() => routed(OFF));
+ render(<RoomAutoRouteSection room={room} autoRoute={OFF} canManage={false} />);
+
+ expect(toggle().disabled).toBe(true);
+ expect(screen.getByText("Only the room's owner or a workspace admin can change auto-route.")).toBeTruthy();
+ });
+
+ it("offers the room's own agents as triage agent and saves the pick", async () => {
+ const calls = mockServer((body) =>
+ routed({ ...OFF, fallback_agent: body.fallback_agent as string | null }),
+ );
+ render(<RoomAutoRouteSection room={room} autoRoute={OFF} canManage />);
+
+ const select = screen.getByRole("combobox", {
+ name: "Triage agent while auto-route is unavailable",
+ });
+ fireEvent.mouseDown(select);
+ const listbox = await screen.findByRole("listbox");
+ await within(listbox).findByRole("option", { name: "triage-bot" });
+ expect(within(listbox).getAllByRole("option").map((o) => o.textContent)).toEqual([
+ "None",
+ "deploy-bot",
+ "triage-bot",
+ ]);
+ fireEvent.click(within(listbox).getByRole("option", { name: "triage-bot" }));
+
+ await waitFor(() => expect(select.textContent).toContain("triage-bot"));
+ // Saved by id, the way the room's setting names its triage agent.
+ expect(calls.find((c) => c.method === "PUT")?.body).toEqual({ fallback_agent: "a2" });
+ });
+
+ it("clears the triage agent with None", async () => {
+ const calls = mockServer(() => routed(OFF));
+ render(
+ <RoomAutoRouteSection room={room} autoRoute={{ ...OFF, fallback_agent: "a2" }} canManage />,
+ );
+
+ const select = screen.getByRole("combobox", {
+ name: "Triage agent while auto-route is unavailable",
+ });
+ await waitFor(() => expect(select.textContent).toContain("triage-bot"));
+ fireEvent.mouseDown(select);
+ fireEvent.click(within(await screen.findByRole("listbox")).getByRole("option", { name: "None" }));
+
+ await waitFor(() => expect(calls.find((c) => c.method === "PUT")?.body).toEqual({ fallback_agent: null }));
+ await waitFor(() => expect(select.textContent).not.toContain("triage-bot"));
+ });
+
+ it("still names a triage agent that has left the room", async () => {
+ mockServer(() => routed(OFF));
+ render(
+ <RoomAutoRouteSection room={room} autoRoute={{ ...OFF, fallback_agent: "a3" }} canManage />,
+ );
+
+ const select = screen.getByRole("combobox", {
+ name: "Triage agent while auto-route is unavailable",
+ });
+ await waitFor(() => expect(select.textContent).toContain("elsewhere"));
+ });
+
+ it("names a departed triage agent by the name the server gives", async () => {
+ mockServer(() => routed(OFF));
+ render(
+ <RoomAutoRouteSection
+ room={room}
+ autoRoute={{ ...OFF, fallback_agent: "gone-id", fallback_agent_name: "old-triage" }}
+ canManage
+ />,
+ );
+
+ const select = screen.getByRole("combobox", {
+ name: "Triage agent while auto-route is unavailable",
+ });
+ await waitFor(() => expect(select.textContent).toContain("old-triage"));
+ });
+});
diff --git a/gateway/src/pages/rooms/RoomAutoRouteSection.tsx b/gateway/src/pages/rooms/RoomAutoRouteSection.tsx
new file mode 100644
index 000000000..712d71d58
--- /dev/null
+++ b/gateway/src/pages/rooms/RoomAutoRouteSection.tsx
@@ -0,0 +1,113 @@
+import {
+ Alert,
+ FormControlLabel,
+ MenuItem,
+ Stack,
+ Switch,
+ TextField,
+ Typography,
+} from "@mui/material";
+import { useEffect, useMemo, useState } from "react";
+import {
+ type RoomAutoRoute,
+ type RoomDetail,
+ type SetRoomAutoRouteInput,
+ setRoomAutoRoute,
+} from "../../data/api";
+import { useAgents } from "../../data/hooks";
+
+/**
+ * The room's `!auto-route` setting as a toggle, and the triage agent that
+ * gets undecided messages while the decision service is failing. Shows what
+ * the server says: the toggle never flips before the server has answered,
+ * and where auto-route cannot work here it says why, in the server's words.
+ */
+export default function RoomAutoRouteSection({
+ room,
+ autoRoute,
+ canManage,
+}: {
+ room: RoomDetail;
+ autoRoute: RoomAutoRoute;
+ canManage: boolean;
+}) {
+ const { data: allAgents } = useAgents();
+ const [state, setState] = useState(autoRoute);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => setState(autoRoute), [autoRoute]);
+
+ const triageChoices = useMemo(() => {
+ const choices = (allAgents ?? [])
+ .filter((a) => room.agent_ids.includes(a.id))
+ .map((a) => ({ id: a.id, name: a.name }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ // A triage agent that has since left the room is still the setting.
+ const triage = state.fallback_agent;
+ if (triage && !choices.some((c) => c.id === triage)) {
+ const known = (allAgents ?? []).find((a) => a.id === triage);
+ choices.push({ id: triage, name: state.fallback_agent_name ?? known?.name ?? triage });
+ }
+ return choices;
+ }, [allAgents, room.agent_ids, state.fallback_agent, state.fallback_agent_name]);
+
+ const save = async (input: SetRoomAutoRouteInput) => {
+ setSaving(true);
+ setError(null);
+ try {
+ setState(await setRoomAutoRoute(room.id, input));
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Failed to update auto-route");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Stack spacing={1.5}>
+ <Typography variant="overline" sx={{ color: "text.secondary", display: "block" }}>
+ Auto-route
+ </Typography>
+ <Typography variant="caption" color="text.secondary">
+ When on, a message that tags nobody goes to the one agent the
+ workspace's decision service picks, or to nobody. Same setting as{" "}
+ <code>!auto-route</code> in the room.
+ </Typography>
+ {error && <Alert severity="error">{error}</Alert>}
+ {!state.available && state.reason && <Alert severity="info">{state.reason}</Alert>}
+ <FormControlLabel
+ control={
+ <Switch
+ checked={state.on}
+ onChange={(e) => save({ on: e.target.checked })}
+ // Turning it off stays possible where it cannot work.
+ disabled={!canManage || saving || (!state.available && !state.on)}
+ />
+ }
+ label={state.on ? "On" : "Off"}
+ />
+ <TextField
+ select
+ size="small"
+ label="Triage agent while auto-route is unavailable"
+ value={state.fallback_agent ?? ""}
+ onChange={(e) => save({ fallback_agent: e.target.value || null })}
+ disabled={!canManage || saving}
+ sx={{ width: 360 }}
+ helperText={
+ canManage
+ ? "Gets the messages auto-route could not decide while the decision service is failing. Off by default."
+ : "Only the room's owner or a workspace admin can change auto-route."
+ }
+ >
+ <MenuItem value="">None</MenuItem>
+ {triageChoices.map((choice) => (
+ <MenuItem key={choice.id} value={choice.id}>
+ {choice.name}
+ </MenuItem>
+ ))}
+ </TextField>
+ </Stack>
+ );
+}
diff --git a/gateway/src/pages/rooms/RoomDetailPage.tsx b/gateway/src/pages/rooms/RoomDetailPage.tsx
index 378e41824..e6383d9b4 100644
--- a/gateway/src/pages/rooms/RoomDetailPage.tsx
+++ b/gateway/src/pages/rooms/RoomDetailPage.tsx
@@ -57,6 +57,7 @@ import {
formatDateTime,
titleCase,
} from "../../theme/hootFormat";
+import RoomAutoRouteSection from "./RoomAutoRouteSection";
import RoomGroupSection from "./RoomGroupSection";
import RoomGraphView from "./RoomGraphView";
import RoomLinkedRoomsSection from "./RoomLinkedRoomsSection";
@@ -130,6 +131,13 @@ export default function RoomDetailPage() {
<Divider />
<RolesSection room={room} canWrite={canWrite} onChanged={refetch} />
<Divider />
+ {room.auto_route && (
+ <>
+ {/* Auto-route is the room owner's and the workspace admins' to change. */}
+ <RoomAutoRouteSection room={room} autoRoute={room.auto_route} canManage={canManage} />
+ <Divider />
+ </>
+ )}
<EditableFieldsSection
room={room}
canWrite={canWrite}