Skip to content

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

Add THIRD_PARTY_AVATARS_ENABLED to turn off external avatar services (CHOO-3403) (#734)

Paul Abbaziabcc5c5f20054
diff --git a/.env.example b/.env.example
index 0f689c20f..556e78af0 100644
--- a/.env.example
+++ b/.env.example
@@ -133,6 +133,14 @@ DB_NAME=switch
# usage out of the production numbers if telemetry is ever switched on.
TELEMETRY_ENVIRONMENT=local
+# ── Avatars ──────────────────────────────────────────────────────────────────
+# An agent with no icon of its own is drawn by api.dicebear.com with its name as
+# the seed, and a person relayed from another platform by ui-avatars.com with
+# their name in the URL. Chat clients load those images, so the services see
+# the name and each reader's address. Set false to send no such URL: each
+# platform shows its own default icon instead.
+# THIRD_PARTY_AVATARS_ENABLED=true
+
# ── Client identity ──────────────────────────────────────────────────────────
# The server half of every member's `@localpart:server` id. Nothing is
# contacted at it; the ids are stable public handles. (MATRIX_SERVER_NAME, the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5dcd426d5..696e2d82d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -53,6 +53,27 @@ version of their own to them without also giving them a release of their own.
organization's Rovo credits on every call, are still not asked for; four
Confluence write tools (infographics and apps on a page) spend 15-30 credits
a request, and the skill tells agents to use them only when asked.
+- **Operators can keep names away from outside avatar services.** An agent with
+ no icon of its own is drawn by api.dicebear.com with its name as the seed, and
+ a person relayed from another platform by ui-avatars.com with their name in the
+ URL. Chat clients load those images, so the services see the name and each
+ reader's address. With `THIRD_PARTY_AVATARS_ENABLED=false` (Helm:
+ `switchCore.thirdPartyAvatars.enabled`), no bridge sends such a URL, icons
+ already stored on those services included, and each platform shows its own
+ default: Slack the app's icon, Discord its default avatar, Teams no image,
+ while a Mattermost bot keeps the image it already has. People and agents
+ without an icon of their own then share that default. New managed agents get
+ no generated icon, and an agent created or registered with an icon on those
+ services gets none. Setting one later is refused with the reason, rather than
+ stored to never show. `GET /agents/icon-choices` offers none and says why, and
+ `GET /agents/avatar-settings` tells Switch Console the setting. The default is
+ unchanged. A server Switch Console runs for you always uses the default.
+
+#### Security
+- **An agent icon URL must spell its host plainly.** A link with a backslash,
+ or a host with percent-encoding or non-ASCII characters, is refused: browsers
+ and chat clients read such a host differently from Switch, so its checks
+ could not tell where the image would be loaded from.
### [0.30.0] - 2026-10-12
@@ -1624,6 +1645,20 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+- **Console follows a server that keeps names away from avatar services.** On a
+ server with `THIRD_PARTY_AVATARS_ENABLED=false`, Console no longer loads
+ DiceBear or ui-avatars.com images for that server's agents and shows their
+ initials instead. Its icon picker offers only an image link and refuses one
+ to either service, new agents are created without a generated icon, and it
+ no longer writes generated icons onto existing agents. Until it has heard
+ from a server, Console shows initials rather than send a name, and it reads
+ the setting again every few minutes, so a server restarted with it changed
+ needs no Console restart. A setting it cannot read counts as off: the icon
+ picker says so and offers to ask again, and a new agent is still created,
+ without a generated icon. Agents on servers that leave the setting on look as
+ before. Older versions of Console load those images whatever the server says.
+
#### Fixed
- **Signing in to a service through Core works on a server whose gateway and
API are on different hosts.** Core sends the browser through its own
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
index d7101562f..e373c7b78 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts
@@ -1,5 +1,6 @@
import type { PluginFs } from '@switch-console/core/agents/plugins';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import { agentSettingsRelativePath } from './switch-settings-paths';
const inspectRemoteDir = vi.hoisted(() => vi.fn());
@@ -59,6 +60,7 @@ const h = vi.hoisted(() => {
apiKey: 'tok-123',
})),
createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input })),
+ fetchAvatarSettings: vi.fn(async () => ({ thirdPartyAvatarsEnabled: true })),
};
});
@@ -79,6 +81,9 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({
vi.mock('@main/core/workspaces/workspace-session', () => ({
withWorkspaceSession: (_workspaceId: string, fn: (server: unknown) => unknown) => fn(mockServer),
}));
+vi.mock('@main/core/switch-servers/gateway-client', () => ({
+ fetchAvatarSettings: h.fetchAvatarSettings,
+}));
vi.mock('@main/core/locations/store', () => ({
ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),
getLocationByHostDir: vi.fn(async () => ({ id: 'loc-1' })),
@@ -148,6 +153,7 @@ describe('addAgent', () => {
h.state.repoAgents = h.repoAgents;
h.state.workdir = fakeFs();
h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });
+ h.fetchAvatarSettings.mockResolvedValue({ thirdPartyAvatarsEnabled: true });
// `clearAllMocks` resets call records but not implementations: without a
// default, whichever test last set one decides the answer for the rest.
inspectRemoteDir.mockResolvedValue({ dir: '/repo', status: 'directory' });
@@ -262,6 +268,69 @@ describe('addAgent', () => {
);
});
+ describe('the icon a server that disables third-party avatars is sent', () => {
+ beforeEach(() => {
+ h.fetchAvatarSettings.mockResolvedValue({ thirdPartyAvatarsEnabled: false });
+ });
+
+ it('registers with no icon when nothing was chosen, rather than the name-generated one', async () => {
+ await addAgent(params({ iconUrl: null }));
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: null })
+ );
+ });
+
+ it('strips a third-party icon URL that was already chosen', async () => {
+ // The new-agent form opens on a random DiceBear avatar before the server
+ // is known; this is the backstop for whatever it sends regardless.
+ await addAgent(params({ iconUrl: agentAvatarUrlForName('codex-hoot') }));
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: null })
+ );
+ });
+
+ it('keeps a custom, non-third-party icon URL', async () => {
+ await addAgent(params({ iconUrl: 'https://example.com/avatar.png' }));
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: 'https://example.com/avatar.png' })
+ );
+ });
+ });
+
+ describe('a server whose avatar setting cannot be read', () => {
+ beforeEach(() => {
+ h.fetchAvatarSettings.mockRejectedValue(new Error('avatar settings unavailable'));
+ });
+
+ it('still creates the agent, with no generated icon', async () => {
+ const result = await addAgent(params({ iconUrl: null }));
+ expect(result.kind).toBe('created');
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: null })
+ );
+ });
+
+ it('keeps a custom, non-third-party icon', async () => {
+ await addAgent(params({ iconUrl: 'https://example.com/avatar.png' }));
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: 'https://example.com/avatar.png' })
+ );
+ });
+ });
+
+ it('falls back to the name-generated avatar when nothing was chosen and the server allows it', async () => {
+ await addAgent(params({ iconUrl: null }));
+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ iconUrl: agentAvatarUrlForName('codex-hoot') })
+ );
+ });
+
it('writes nothing to the workdir when registration fails', async () => {
h.registerAgentIdentity.mockResolvedValue({ kind: 'name-conflict' } as never);
const fs = h.state.workdir as PluginFs;
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index 9702c156a..7560ee2a8 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -6,6 +6,7 @@ import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation, getLocationByHostDir } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
+import { type AvatarSettings, fetchAvatarSettings } from '@main/core/switch-servers/gateway-client';
import { getServer } from '@main/core/switch-servers/servers-store';
import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';
@@ -15,7 +16,8 @@ import { withWorkspaceSession } from '@main/core/workspaces/workspace-session';
import { requireWorkspaceForServer } from '@main/core/workspaces/workspaces-store';
import { db } from '@main/db/client';
import { agents as agentsTable } from '@main/db/schema';
-import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
+import { log } from '@main/lib/logger';
+import { agentAvatarUrlForName, isThirdPartyAvatarUrl } from '@shared/core/agents/agent-avatar';
import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
@@ -305,21 +307,61 @@ export async function writeNewAgentConfigFile(
);
}
+/**
+ * The icon to register a new agent with: the one the form chose, or the
+ * name-generated avatar when nothing was chosen — but only when the owning
+ * server allows a name to be sent to DiceBear for that. A server that
+ * disables third-party avatars gets `null` instead, even when
+ * `requestedIconUrl` already carries a third-party URL: the new-agent form
+ * opens on a random DiceBear avatar before anything is known about where the
+ * agent will land, and may be submitted before the server has answered. The
+ * server drops such an icon on registration as well; this keeps the request
+ * itself from carrying one.
+ */
+function resolveNewAgentIconUrl(
+ requestedIconUrl: string | null,
+ name: string,
+ avatarSettings: AvatarSettings
+): string | null {
+ if (avatarSettings.thirdPartyAvatarsEnabled) {
+ return requestedIconUrl ?? agentAvatarUrlForName(name);
+ }
+ return requestedIconUrl !== null && !isThirdPartyAvatarUrl(requestedIconUrl)
+ ? requestedIconUrl
+ : null;
+}
+
+/** The server's avatar setting for a new agent's icon. One that cannot be read
+ * counts as off: the agent is still created, with no generated icon, rather
+ * than an avatar endpoint deciding whether an agent can be created at all. */
+async function avatarSettingsForNewAgent(server: SwitchServer): Promise<AvatarSettings> {
+ try {
+ return await fetchAvatarSettings(server);
+ } catch (error) {
+ log.warn(
+ 'addAgent: could not read the server avatar setting; registering without a generated icon',
+ { serverId: server.id, error: String(error) }
+ );
+ return { thirdPartyAvatarsEnabled: false };
+ }
+}
+
async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
const checked = await checkNewAgent(params);
if (checked.kind !== 'ok') return reportFailedCreate(params, checked);
const { server, workspace: targetWorkspace, slotAgentId } = checked;
- const registered = await withWorkspaceSession(targetWorkspace.id, (target) =>
- registerAgentIdentity(target, {
+ const registered = await withWorkspaceSession(targetWorkspace.id, async (target) => {
+ const avatarSettings = await avatarSettingsForNewAgent(target);
+ return registerAgentIdentity(target, {
name: params.name,
description: params.description,
displayName: params.displayName,
repoDir: params.dir,
agentType: knownAgentTypeForProvider(params.providerId),
- iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),
- })
- );
+ iconUrl: resolveNewAgentIconUrl(params.iconUrl, params.name, avatarSettings),
+ });
+ });
if (registered.kind !== 'created') return reportFailedCreate(params, registered);
const workdir = await resolveWorkdirFsFor(params.sshHost, params.dir);
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
index 186281228..0fb221bf9 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -305,6 +305,12 @@ services:
# writes its own answer here for a server it runs.
TELEMETRY_INTERNAL:
TELEMETRY_SNAPSHOT_INTERVAL_HOURS:
+ # Whether agents and people are drawn by outside avatar services, which
+ # see their names (api.dicebear.com, ui-avatars.com). Unset is true;
+ # false leaves each platform's default icon. A server Switch Console runs
+ # for you always uses the default: Console writes its `.env` afresh on
+ # every start and does not set this.
+ THIRD_PARTY_AVATARS_ENABLED:
depends_on:
postgres:
condition: service_healthy
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
index 31954c45c..bf50aae9a 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -5,6 +5,7 @@ import type { RemoteAgentSummary, SwitchServer } from '@shared/core/switch-serve
const fetchAgents = vi.fn();
const updateAgentIcon = vi.fn();
const getAgents = vi.fn();
+const fetchAvatarSettings = vi.fn();
/** Stands in for the real `GatewayError`, which the module narrows on by
* `instanceof` and by `status`. */
@@ -21,6 +22,7 @@ class FakeGatewayError extends Error {
vi.mock('./gateway-client', () => ({
fetchAgents: (...args: unknown[]) => fetchAgents(...args),
updateAgentIcon: (...args: unknown[]) => updateAgentIcon(...args),
+ fetchAvatarSettings: (...args: unknown[]) => fetchAvatarSettings(...args),
GatewayError: FakeGatewayError,
}));
@@ -83,6 +85,7 @@ beforeEach(() => {
fetchAgents.mockReset().mockResolvedValue([]);
getAgents.mockReset().mockResolvedValue([]);
updateAgentIcon.mockReset().mockResolvedValue(agent({}));
+ fetchAvatarSettings.mockReset().mockResolvedValue({ thirdPartyAvatarsEnabled: true });
});
describe('backfillAgentIcons', () => {
@@ -149,6 +152,16 @@ describe('backfillAgentIcons', () => {
expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'written', written: 0 });
});
+ it('writes nothing, and says so, when the server disables third-party avatars', async () => {
+ given([agent({ id: 'a-1', name: 'switch_worker' })]);
+ fetchAvatarSettings.mockResolvedValue({ thirdPartyAvatarsEnabled: false });
+ const backfill = await loadFresh();
+
+ expect(await backfill('ws-1', server('s-1'))).toEqual({ kind: 'disabled' });
+ expect(fetchAgents).not.toHaveBeenCalled();
+ expect(updateAgentIcon).not.toHaveBeenCalled();
+ });
+
it('reports a server with no icon endpoint', async () => {
// Every write 404ing means the route does not exist, not that the agents
// vanished — they came from that same server one request earlier. The user
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
index bad19502b..41a3b81b6 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
@@ -2,17 +2,19 @@ import { getAgents } from '@main/core/agents/getAgents';
import { log } from '@main/lib/logger';
import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { AgentIconBackfill, SwitchServer } from '@shared/core/switch-servers/switch-servers';
-import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';
+import { fetchAgents, fetchAvatarSettings, GatewayError, updateAgentIcon } from './gateway-client';
/**
* Give the signed-in user's existing agents the avatar their name generates
- * (CHOO-2171).
+ * (CHOO-2171) — unless the server disables sending names to a third party for
+ * that (`THIRD_PARTY_AVATARS_ENABLED`), in which case this writes nothing at
+ * all.
*
* Agents registered before icons existed have none. A current Switch server
- * draws those with the same name-generated avatar this app does, but an older
- * one draws a lettered badge on the chat platforms instead. This writes the
- * avatar in, so an agent this app manages looks the same in the app as it does
- * in Slack whichever server it is on.
+ * that allows it draws those with the same name-generated avatar this app
+ * does, but an older one draws a lettered badge on the chat platforms instead.
+ * This writes the avatar in, so an agent this app manages looks the same in
+ * the app as it does in Slack whichever server it is on.
*
* Only agents this install manages are touched, and only those with no icon at
* all — a chosen icon is never overwritten.
@@ -24,10 +26,11 @@ import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';
* call, and a refusal is taken as "not yours" rather than argued with.
*
* **The outcome is reported rather than logged and forgotten.** The app draws a
- * name-derived avatar for any agent the server has no icon for, so on an older
- * server a failed write leaves the app looking correct while the chat platforms
- * — which ask the server — still show the lettered badge. Nothing on screen
- * would say why, so the caller is handed what happened and tells the user.
+ * name-derived avatar for any agent the server has no icon for and allows it,
+ * so on an older server a failed write leaves the app looking correct while the
+ * chat platforms — which ask the server — still show the lettered badge.
+ * Nothing on screen would say why, so the caller is handed what happened and
+ * tells the user.
*/
export function backfillAgentIcons(
workspaceId: string,
@@ -68,6 +71,11 @@ async function writeMissingIcons(
workspaceId: string,
server: SwitchServer
): Promise<AgentIconBackfill> {
+ const avatarSettings = await fetchAvatarSettings(server);
+ if (!avatarSettings.thirdPartyAvatarsEnabled) {
+ return { kind: 'disabled' };
+ }
+
const [agents, local] = await Promise.all([fetchAgents(server), getAgents()]);
// `GET /agents` lists the whole workspace, most of which is nothing to do
// with this computer.
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 33808db1c..bd501255d 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
@@ -45,6 +45,7 @@ import {
getConnectionCatalog,
getGitHubConnection,
fetchAgentIconChoices,
+ fetchAvatarSettings,
cloudMachineLifecycle,
ensureCloudMachine,
listCloudMachines,
@@ -212,6 +213,10 @@ export const switchServersController = createRPCController({
/** Whether the signed-in account may create a workspace on the server. */
canCreateWorkspace: (serverId: string) =>
withServerWorkspaceSession(serverId, (server) => fetchCanCreateWorkspace(server)),
+ /** Whether this server allows a third-party avatar URL (DiceBear, ui-avatars.com)
+ * to be generated or sent anywhere. */
+ avatarSettings: (serverId: string) =>
+ withReachableServerWorkspaceSession(serverId, (server) => fetchAvatarSettings(server)),
/** The caller's cloud machines, or null when the server offers none. */
cloudMachines: (serverId: string) =>
withServerWorkspaceSession(serverId, async (server) =>
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index 019f70b56..c9ec38907 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -110,6 +110,8 @@ const {
fetchAgentManagementAccess,
updateCanManageAgents,
updateManagedAgent,
+ fetchAvatarSettings,
+ fetchAgentIconChoices,
} = await import('./gateway-client');
const SERVER = {
@@ -126,6 +128,14 @@ const MANAGED = {
managed: true,
} as never;
+/** `SERVER` under a different id — `SERVER` is typed `as never` so TypeScript
+ * can hand it to every call expecting a full `SwitchServer`, but that also
+ * means it cannot be spread. Used where a test needs several distinct servers
+ * (e.g. the per-server avatar-settings cache) without redeclaring every field. */
+function serverWithId(id: string): typeof SERVER {
+ return { id, name: 'S', gatewayUrl: 'https://switch.example.com', managed: false } as never;
+}
+
/** A structurally-valid JWT whose payload `exp` is `secondsFromNow` in the
* future (or past when negative). Signature is a placeholder — the client only
* base64-decodes the payload to read `exp`. */
@@ -2883,3 +2893,111 @@ describe('agent management calls', () => {
);
});
});
+
+describe('fetchAvatarSettings', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(2 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('reports the server’s own answer', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse({ third_party_avatars_enabled: false }));
+ const server = serverWithId('avatar-enabled-false');
+ await expect(fetchAvatarSettings(server)).resolves.toEqual({
+ thirdPartyAvatarsEnabled: false,
+ });
+ });
+
+ it('reads a 404 as a server predating the setting, which always sent these URLs', async () => {
+ fetchMock.mockImplementation(async () => errorResponse(404, '{"detail":"Not Found"}'));
+ const server = serverWithId('avatar-404');
+ await expect(fetchAvatarSettings(server)).resolves.toEqual({
+ thirdPartyAvatarsEnabled: true,
+ });
+ });
+
+ it('propagates any other failure rather than guessing an answer', async () => {
+ fetchMock.mockImplementation(async () => errorResponse(500, '{"detail":"boom"}'));
+ const server = serverWithId('avatar-500');
+ await expect(fetchAvatarSettings(server)).rejects.toThrow();
+ });
+
+ it('answers a burst of callers with one request', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse({ third_party_avatars_enabled: true }));
+ const server = serverWithId('avatar-cached');
+ await fetchAvatarSettings(server);
+ await fetchAvatarSettings(server);
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ it('asks again after a minute, so a server restarted with it off is heard', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ const server = serverWithId('avatar-expiry');
+ fetchMock.mockImplementation(async () => jsonResponse({ third_party_avatars_enabled: true }));
+ await expect(fetchAvatarSettings(server)).resolves.toEqual({
+ thirdPartyAvatarsEnabled: true,
+ });
+
+ fetchMock.mockImplementation(async () =>
+ jsonResponse({ third_party_avatars_enabled: false })
+ );
+ vi.setSystemTime(Date.now() + 61_000);
+ await expect(fetchAvatarSettings(server)).resolves.toEqual({
+ thirdPartyAvatarsEnabled: false,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('asks again after a failure, rather than caching it', async () => {
+ const server = serverWithId('avatar-retry');
+ fetchMock.mockImplementationOnce(async () => errorResponse(500, '{"detail":"boom"}'));
+ await expect(fetchAvatarSettings(server)).rejects.toThrow();
+
+ fetchMock.mockImplementation(async () => jsonResponse({ third_party_avatars_enabled: true }));
+ await expect(fetchAvatarSettings(server)).resolves.toEqual({
+ thirdPartyAvatarsEnabled: true,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('fetchAgentIconChoices', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(2 * 60 * 60));
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('carries the server’s flag with the choices', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse({ choices: [], third_party_avatars_enabled: false })
+ );
+ await expect(fetchAgentIconChoices(serverWithId('choices-off'), 'worker', 0)).resolves.toEqual({
+ choices: [],
+ thirdPartyAvatarsEnabled: false,
+ });
+ });
+
+ it('reads a missing flag as a server predating the setting, which always generated them', async () => {
+ fetchMock.mockImplementation(async () =>
+ jsonResponse({ choices: ['https://example.com/a.png'] })
+ );
+ await expect(fetchAgentIconChoices(serverWithId('choices-old'), 'worker', 0)).resolves.toEqual({
+ choices: ['https://example.com/a.png'],
+ thirdPartyAvatarsEnabled: true,
+ });
+ });
+});
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 9fbde8c17..13c4c8c4a 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
@@ -1182,21 +1182,82 @@ export async function updateCanManageAgents(
});
}
+/** Whether a server generates and forwards third-party avatar URLs — DiceBear
+ * for an agent with no icon, `ui-avatars.com` for a relayed platform user — or
+ * has turned that off (`THIRD_PARTY_AVATARS_ENABLED` on the server). */
+export type AvatarSettings = { thirdPartyAvatarsEnabled: boolean };
+
+/** How long a server's answer to `GET /agents/avatar-settings` is reused. The
+ * avatars, the picker, the new-agent default and the icon backfill all ask
+ * within a few seconds of a workspace loading, and this answers them with one
+ * request. It is not kept for the session: the setting changes when the
+ * server restarts, which a running Console outlives, and an operator who
+ * turns it off should not wait for every Console to restart. */
+const AVATAR_SETTINGS_TTL_MS = 60_000;
+
+/** Evicted on failure, so a transient network error is asked again rather
+ * than answered from the cache. */
+const avatarSettingsCache = new Map<string, { at: number; request: Promise<AvatarSettings> }>();
+
+/**
+ * Whether `server` allows a third-party avatar URL to be generated or sent
+ * anywhere (`GET /agents/avatar-settings`).
+ *
+ * A 404 is a server predating the setting: every such server always generated
+ * and forwarded these URLs, so absence reads as enabled — the same behavior as
+ * before the setting existed, and the same pattern as every other
+ * predates-the-capability field in this file. Any other failure propagates.
+ */
+export function fetchAvatarSettings(server: SwitchServer): Promise<AvatarSettings> {
+ const cached = avatarSettingsCache.get(server.id);
+ if (cached && Date.now() - cached.at < AVATAR_SETTINGS_TTL_MS) return cached.request;
+ const request: Promise<AvatarSettings> = requestAvatarSettings(server).catch((cause) => {
+ if (avatarSettingsCache.get(server.id)?.request === request) {
+ avatarSettingsCache.delete(server.id);
+ }
+ throw cause;
+ });
+ avatarSettingsCache.set(server.id, { at: Date.now(), request });
+ return request;
+}
+
+async function requestAvatarSettings(server: SwitchServer): Promise<AvatarSettings> {
+ let res: Response;
+ try {
+ res = await gatewayFetch(server, '/agents/avatar-settings', { authenticated: true });
+ } catch (cause) {
+ if (cause instanceof GatewayError && cause.status === 404) {
+ return { thirdPartyAvatarsEnabled: true };
+ }
+ throw cause;
+ }
+ const json = (await res.json()) as { third_party_avatars_enabled: boolean };
+ return { thirdPartyAvatarsEnabled: json.third_party_avatars_enabled };
+}
+
/**
* One page of the icons the server generates for an agent called `name`
* (`GET /agents/icon-choices`): page 0 leads with the one an agent of that
- * name gets when nobody picks an icon.
+ * name gets when nobody picks an icon. `choices` is empty on a server that
+ * disables third-party avatars — callers that already know that from
+ * {@link fetchAvatarSettings} should not call this at all, but the server
+ * answers consistently either way.
*/
export async function fetchAgentIconChoices(
server: SwitchServer,
name: string,
page: number
-): Promise<string[]> {
+): Promise<{ choices: string[]; thirdPartyAvatarsEnabled: boolean }> {
const query = new URLSearchParams({ name, page: String(page) });
const res = await gatewayFetch(server, `/agents/icon-choices?${query.toString()}`, {
authenticated: true,
});
- return ((await res.json()) as { choices: string[] }).choices;
+ const json = (await res.json()) as { choices: string[]; third_party_avatars_enabled?: boolean };
+ // Absent on a server predating the setting, which always generated them.
+ return {
+ choices: json.choices,
+ thirdPartyAvatarsEnabled: json.third_party_avatars_enabled ?? true,
+ };
}
/**
diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
index 8af0fe473..38578284f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
@@ -39,6 +39,7 @@ export const PaletteAgentItem = observer(function PaletteAgentItem({
<AgentAvatar
name={item.title}
iconUrl={iconUrl}
+ serverId={agent?.serverId ?? null}
size={16}
className="-mx-px bg-transparent"
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
index d031deb78..9f6bc12e3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
@@ -241,7 +241,11 @@ export function AgentIdentityFields({
size={84}
/>
<span className="text-xs text-foreground-muted">
- {form.iconIsGenerated ? 'Automatically generated' : 'Custom icon'}
+ {form.iconUrl === null && form.thirdPartyAvatarsEnabled === false
+ ? 'No icon'
+ : form.iconIsGenerated
+ ? 'Automatically generated'
+ : 'Custom icon'}
</span>
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
index 88b3f3f54..68ff334e9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
@@ -1,5 +1,6 @@
-import { useCallback, useState } from 'react';
-import { randomAgentAvatarUrl } from '@shared/core/agents/agent-avatar';
+import { useCallback, useEffect, useState } from 'react';
+import { useThirdPartyAvatarsEnabled } from '@renderer/lib/stores/use-avatar-settings';
+import { isThirdPartyAvatarUrl, randomAgentAvatarUrl } from '@shared/core/agents/agent-avatar';
import { AGENT_NAME_PATTERN, slugifyAgentNamePart } from '@shared/core/agents/agent-slug';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';
@@ -39,7 +40,7 @@ export type PickModeState = ReturnType<typeof usePickMode>;
* local agent, one for a remote one — and switching between them swapped which
* was on screen, so the name and description the user had typed vanished.
*/
-export function useConfigureAgentForm() {
+export function useConfigureAgentForm(serverId: string | null) {
const [agentName, setAgentNameFolded] = useState('');
// What was typed, before the identifier folded it to lowercase. The slug
// offer hands this back as the display name, so the capitals in a typed
@@ -68,6 +69,19 @@ export function useConfigureAgentForm() {
// generates" — that is what the ✕ in the picker returns to.
const [initialIconUrl] = useState(randomAgentAvatarUrl);
const [iconUrl, setIconUrl] = useState<string | null>(initialIconUrl);
+ const thirdPartyAvatarsEnabled = useThirdPartyAvatarsEnabled(serverId);
+
+ // The random bot above is drawn before anything is known about where the
+ // agent will land, so a server that turns out to disable third-party
+ // avatars has to lose it retroactively — sent as-is, it would be the one
+ // DiceBear URL this form ever created without the server's permission.
+ // Nothing else changes here while the server is still unknown or allows
+ // them: this only fires once the answer is a confirmed no.
+ useEffect(() => {
+ if (thirdPartyAvatarsEnabled === false && iconUrl !== null && isThirdPartyAvatarUrl(iconUrl)) {
+ setIconUrl(null);
+ }
+ }, [thirdPartyAvatarsEnabled, iconUrl]);
const setAutoApprove = useCallback((value: boolean) => {
setAutoApproveRaw(value);
@@ -151,6 +165,7 @@ export function useConfigureAgentForm() {
* the user went and chose. Only the caption cares; the value sent to the
* server is `iconUrl` either way. */
iconIsGenerated: iconUrl === null || iconUrl === initialIconUrl,
+ thirdPartyAvatarsEnabled,
isValid,
};
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
index bedaed9df..f9a1ce239 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx
@@ -115,7 +115,6 @@ export const NewAgentForm = observer(function NewAgentForm({
const showAddServerModal = useShowModal('addServerModal');
const pickState = usePickMode();
- const form = useConfigureAgentForm();
// Run location: 'local' (default) or an onboarded remote host's SSH alias. A
// remote agent runs its sessions on the host and needs a remote working dir.
@@ -137,6 +136,10 @@ export const NewAgentForm = observer(function NewAgentForm({
const selectedServer = switchServersStore.servers.find(
(server) => server.id === selectedServerId
);
+ // Ahead of `pickState.serverId`, which only catches up a tick later (see the
+ // effect below) — the icon form needs the server as early as possible so its
+ // own privacy check has the least time to run against a stale answer.
+ const form = useConfigureAgentForm(selectedServerId);
// Running in the cloud is offered where the server's flag offers it, and can
// be chosen only where the server says this workspace can claim a machine:
// its cloud machine list is null where it cannot, and undefined until read.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
index 1745fd09f..ba27e1563 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
@@ -48,7 +48,13 @@ const AgentCrumb = observer(function AgentCrumb({ agent }: { agent: Agent | null
// provider logo that used to sit here says what it runs on, which is
// not what a crumb naming one agent is for.
icon: agent ? (
- <AgentAvatar name={label} iconUrl={iconUrl} size={16} className="bg-transparent" />
+ <AgentAvatar
+ name={label}
+ iconUrl={iconUrl}
+ serverId={agent.serverId}
+ size={16}
+ className="bg-transparent"
+ />
) : (
<Bot className="size-3.5 shrink-0" />
),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
index bec40e643..641ad851d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
@@ -88,7 +88,7 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
) : (
// Not registered on a server yet, so there is nothing to change the
// icon on — shown, but not offered as editable.
- <AgentAvatar name={title} iconUrl={null} size={88} />
+ <AgentAvatar name={title} iconUrl={null} serverId={agent?.serverId ?? null} size={88} />
)
}
title={title}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
index cb7b2871b..cefb482c9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
@@ -71,6 +71,7 @@ const ManagedAgentRow = observer(function ManagedAgentRow({ agent }: { agent: Ma
<SidebarAgentRow
label={label}
iconUrl={agent.iconUrl}
+ serverId={agent.serverId}
providerId={isValidProviderId(provider) ? provider : null}
isActive={currentView === 'managedAgent' && params.agentId === agent.agentId}
depth={0}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx
index 76cfaf67c..2bb291c48 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-view.tsx
@@ -46,6 +46,7 @@ const ManagedAgentTitlebar = observer(function ManagedAgentTitlebar() {
<AgentAvatar
name={label}
iconUrl={agent?.iconUrl ?? null}
+ serverId={params.serverId}
size={16}
className="bg-transparent"
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
index 05d7ed228..48d66f7cf 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { User as UserIcon } from 'lucide-react';
import { useMemo, useState } from 'react';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import {
type AgentPick,
AgentPickerRow,
@@ -49,11 +50,14 @@ export function TileGrid({ children }: { children: React.ReactNode }) {
// ── Agents ──────────────────────────────────────────────────────────────────
function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {
+ const serverId =
+ lists.workspaceId === null ? null : workspacesStore.serverIdFor(lists.workspaceId);
const found = lists.agents.find((a) => a.name === name);
return found ? (
<ChosenAgentTile
key={name}
agent={found}
+ serverId={serverId}
subtitle={agentProviderLabelFor(found.id, lists.workspaceId)}
onRemove={onRemove}
/>
@@ -61,6 +65,7 @@ function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {
<ChosenAgentTile
key={name}
agent={{ id: name, name, iconUrl: null }}
+ serverId={serverId}
subtitle={NOT_ON_SERVER}
subtitleTone="warning"
onRemove={onRemove}
@@ -77,6 +82,8 @@ function AgentCombobox({
exclude: string[];
onPick: (name: string) => void;
}) {
+ const serverId =
+ lists.workspaceId === null ? null : workspacesStore.serverIdFor(lists.workspaceId);
const items = lists.agents.filter((a) => !exclude.includes(a.name));
return (
<PickerCombobox
@@ -86,6 +93,7 @@ function AgentCombobox({
renderItem={(agent) => (
<AgentPickerRow
agent={agent}
+ serverId={serverId}
subtitle={agentProviderLabelFor(agent.id, lists.workspaceId)}
/>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index b46e0a3aa..1bccd534c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -121,6 +121,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
<SidebarAgentRow
label={label}
iconUrl={iconUrl}
+ serverId={agent.serverId}
providerId={agent.providerId ?? null}
isActive={isActive}
depth={depth}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
index 3043b5b0d..0fe248eb2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-row.tsx
@@ -20,6 +20,7 @@ import { depthIndent } from './sidebar-store';
export const SidebarAgentRow = observer(function SidebarAgentRow({
label,
iconUrl,
+ serverId,
providerId,
isActive,
depth,
@@ -34,6 +35,8 @@ export const SidebarAgentRow = observer(function SidebarAgentRow({
}: {
label: string;
iconUrl: string | null;
+ /** The Switch server this agent belongs to, or null when it has none. */
+ serverId: string | null;
providerId: AgentProviderId | null;
isActive: boolean;
depth: number;
@@ -74,6 +77,7 @@ export const SidebarAgentRow = observer(function SidebarAgentRow({
<AgentAvatar
name={label}
iconUrl={iconUrl}
+ serverId={serverId}
size={21}
className={cn('bg-transparent', dimmed && 'opacity-60')}
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index a9c3b4361..e6b86d166 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -119,6 +119,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
<AgentAvatar
name={label}
iconUrl={iconUrl}
+ serverId={agent.serverId}
size={21}
className="-mx-[1.5px] bg-transparent"
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
index 38bf9ed01..adb275583 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -238,5 +238,8 @@ function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {
});
return;
}
+ // 'written' and 'disabled' both fall through here silently: a server that
+ // disables third-party avatars wrote nothing on purpose, which is the
+ // outcome working as intended, not a problem to surface.
reportedBackfill.delete(workspaceId);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index 34cc9679f..b3c2c0a6d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -211,6 +211,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
<ChosenAgentTile
key={agent.id}
agent={agent}
+ serverId={serverId}
subtitle={agentProviderLabel(agent.providerId)}
onRemove={() =>
setSelected((current) => current.filter((a) => a.id !== agent.id))
@@ -228,7 +229,11 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
}}
searchText={(item) => item.name}
renderItem={(item) => (
- <AgentPickerRow agent={item} subtitle={agentProviderLabel(item.providerId)} />
+ <AgentPickerRow
+ agent={item}
+ serverId={serverId}
+ subtitle={agentProviderLabel(item.providerId)}
+ />
)}
disabled={nothingToAdd}
placeholder="Search agents to add..."
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 bc69ee366..ff3963ada 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
@@ -4,6 +4,7 @@ import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';
@@ -529,6 +530,7 @@ const AddAgentPanel = observer(function AddAgentPanel({
<AgentAvatar
name={agent.name}
iconUrl={remoteById.get(switchAgentId)?.iconUrl ?? null}
+ serverId={agent.serverId}
size={22}
/>
<span className="min-w-0 flex-1 truncate text-sm text-foreground">
@@ -586,6 +588,7 @@ function AgentMark({
<AgentAvatar
name={agentNameFor(agentId, workspaceId, remoteById)}
iconUrl={remote?.iconUrl ?? null}
+ serverId={workspacesStore.serverIdFor(workspaceId)}
size={26}
/>
</span>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index 023b5319c..9a33865b3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -307,6 +307,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
<ChosenAgentTile
key={agent.id}
agent={agent}
+ serverId={serverId || null}
subtitle={providerLabel(agent.id)}
onRemove={() =>
setAgents((current) => current.filter((a) => a.id !== agent.id))
@@ -321,7 +322,11 @@ export const CreateRoomModal = observer(function CreateRoomModal({
onPick={(next) => setAgents((current) => [...current, next])}
searchText={(item) => item.name}
renderItem={(item) => (
- <AgentPickerRow agent={item} subtitle={providerLabel(item.id)} />
+ <AgentPickerRow
+ agent={item}
+ serverId={serverId || null}
+ subtitle={providerLabel(item.id)}
+ />
)}
disabled={agentsQuery.isLoading}
placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
index f0ae1d2ab..c0f31e88f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
@@ -148,7 +148,7 @@ function ManagedAgentCard({ agent }: { agent: ManagedAgentView }) {
/>
<div className="pointer-events-none flex flex-1 flex-col p-[14px]">
<div className="flex flex-1 items-center justify-center py-3">
- <AgentAvatar name={label} iconUrl={agent.iconUrl} size={66} />
+ <AgentAvatar name={label} iconUrl={agent.iconUrl} serverId={agent.serverId} size={66} />
</div>
<div className="min-w-0">
<div className="truncate text-sm font-medium text-foreground">{label}</div>
@@ -202,7 +202,7 @@ const AgentCard = observer(function AgentCard({
<div className="pointer-events-none flex flex-1 flex-col p-[14px]">
<div className="flex flex-1 items-center justify-center py-3">
- <AgentAvatar name={label} iconUrl={iconUrl} size={66} />
+ <AgentAvatar name={label} iconUrl={iconUrl} serverId={serverId} size={66} />
</div>
<div className="min-w-0">
<div className="truncate text-sm font-medium text-foreground">{label}</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
index c6ed2bade..066bd5ff7 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx
@@ -314,6 +314,7 @@ const RoomRow = observer(function RoomRow({
<AgentAvatar
name={agent.name}
iconUrl={remoteById.get(agent.switchAgentId ?? '')?.iconUrl ?? null}
+ serverId={serverId}
size={22}
/>
</span>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx
index 4376a102c..e738868bd 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx
@@ -4,6 +4,7 @@ import type { ParsedAgentEntry } from '@main/core/agent-templates/template-docum
import type { TemplateRoom } from '@main/core/room-templates/controller';
import { LocalDirectorySelector } from '@renderer/features/locations/components/add-agent-modal/local-directory-selector';
import { AgentField, type EntityLists } from '@renderer/features/room-templates/entity-fields';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { Input } from '@renderer/lib/ui/input';
import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
@@ -226,10 +227,12 @@ export function AgentSlotCard({
slot.mode === 'existing'
? slot.existingName || 'Pick an agent'
: (slot.createdName ?? wantedName);
+ const serverId =
+ lists.workspaceId === null ? null : workspacesStore.serverIdFor(lists.workspaceId);
return (
<Card className={cn(slot.status === 'failed' && 'border-destructive/50')}>
<div className="flex items-center gap-3">
- <AgentAvatar name={shownName || 'agent'} iconUrl={null} size={28} />
+ <AgentAvatar name={shownName || 'agent'} iconUrl={null} serverId={serverId} size={28} />
<div className="min-w-0 flex-1">
<div
className={cn(
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
index 7e88438a5..769c3d60d 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
+import { useAvatarSettings } from '@renderer/lib/stores/use-avatar-settings';
import { cn } from '@renderer/utils/utils';
-import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-avatar';
+import { agentInitials, resolveAgentAvatarSrc } from '@shared/core/agents/agent-avatar';
/**
* An agent's own picture, at whatever size the surface asks for (CHOO-2171).
@@ -9,14 +10,19 @@ import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-
* *provider* it runs on. Every surface listing agents uses this one component
* so the same agent wears the same face everywhere.
*
- * Three states, in order:
+ * Generated avatars are drawn by DiceBear from the agent's name, so whether
+ * one may be loaded is up to the agent's server (`THIRD_PARTY_AVATARS_ENABLED`).
+ * In order:
* - the icon its owner chose;
- * - failing that, an avatar drawn from its name, which is also what the Switch
- * bridges show, so the app and Slack agree;
- * - failing *that* — an image that will not load, most often because the
- * machine is offline — its initials. Deliberately visible rather than a
- * blank square or a broken-image glyph: a missing avatar should read as a
- * missing avatar.
+ * - failing that, on a server that allows it, an avatar drawn from its name,
+ * which is also what the Switch bridges show, so the app and Slack agree;
+ * - otherwise its initials. That covers a server that turns third-party
+ * avatars off, which also withholds a chosen icon on DiceBear or
+ * ui-avatars.com; a server whose answer is not in yet, or no server at all,
+ * so no name leaves the machine before Console knows it may; and an image
+ * that will not load, most often because the machine is offline.
+ * Deliberately visible rather than a blank square or a broken-image glyph:
+ * a missing avatar should read as a missing avatar.
*
* A failed load is tried again a few times, further apart each time, before
* the initials stay: the avatar service refuses a burst of requests (a sidebar
@@ -25,24 +31,32 @@ import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-
export function AgentAvatar({
name,
iconUrl,
+ serverId,
size = 16,
className,
}: {
name: string;
- /** The agent's chosen icon, or null to draw one from its name. */
+ /** The agent's chosen icon, or null to draw one from its name — subject to
+ * what `serverId` allows. */
iconUrl: string | null;
+ /** The Switch server this agent belongs to, or null when it has none.
+ * Required rather than optional: whether a name-seeded avatar may be built
+ * at all depends on this server's setting, so a call site cannot skip it
+ * without deciding to always fail closed. */
+ serverId: string | null;
/** Rendered size in pixels. Default: 16. */
size?: number;
className?: string;
}) {
- const src = iconUrl ?? agentAvatarUrlForName(name);
+ const avatarSettings = useAvatarSettings(serverId);
const [failedSrc, setFailedSrc] = useState<string | null>(null);
+ const src = resolveAgentAvatarSrc(iconUrl, name, avatarSettings.thirdPartyAvatarsEnabled);
const [attempt, setAttempt] = useState({ src, count: 0 });
const tries = attempt.src === src ? attempt.count : 0;
// After a failed load, try again later; the initials show in the meantime.
useEffect(() => {
- if (failedSrc !== src || tries >= RETRY_DELAYS_MS.length) return;
+ if (src === null || failedSrc !== src || tries >= RETRY_DELAYS_MS.length) return;
const delay = RETRY_DELAYS_MS[tries] * (0.75 + Math.random() * 0.5);
const timer = setTimeout(() => {
setAttempt({ src, count: tries + 1 });
@@ -53,12 +67,16 @@ export function AgentAvatar({
const shape = cn('inline-flex shrink-0 items-center justify-center rounded-full', className);
- if (failedSrc === src) {
+ if (src === null || failedSrc === src) {
return (
<span
className={cn(shape, 'bg-background-tertiary font-medium text-foreground-muted')}
style={{ width: size, height: size, fontSize: Math.max(8, Math.round(size * 0.4)) }}
- title={name}
+ title={
+ src === null && avatarSettings.error !== null
+ ? `${name} — couldn't read this server's avatar setting`
+ : name
+ }
>
{agentInitials(name)}
</span>
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
index 804dfc1b6..40a9367b9 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
@@ -1,21 +1,27 @@
import { useQuery } from '@tanstack/react-query';
import { Pencil, RotateCw, X } from 'lucide-react';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
+import { useAvatarSettings } from '@renderer/lib/stores/use-avatar-settings';
import { Input } from '@renderer/lib/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@renderer/lib/ui/popover';
import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
import { cn } from '@renderer/utils/utils';
+import { isThirdPartyAvatarUrl } from '@shared/core/agents/agent-avatar';
type PickerTab = 'generated' | 'url';
-const TABS: readonly { value: PickerTab; label: string }[] = [
+const BOTH_TABS: readonly { value: PickerTab; label: string }[] = [
{ value: 'generated', label: 'Generated' },
{ value: 'url', label: 'Image URL' },
];
+const URL_ONLY_TAB: readonly { value: PickerTab; label: string }[] = [
+ { value: 'url', label: 'Image URL' },
+];
+
/**
* Choose an agent's picture (CHOO-2171): one of a set of generated avatars, or a
* link to an image of the reader's own.
@@ -24,6 +30,16 @@ const TABS: readonly { value: PickerTab; label: string }[] = [
* avatar its name generates — the state the ✕ returns to. A new agent does not
* start there: it opens on a concrete random avatar, since an unnamed agent has no
* name to draw from.
+ *
+ * A server that disables third-party avatars (`THIRD_PARTY_AVATARS_ENABLED`)
+ * offers neither of those — generating one sends the name to DiceBear, and
+ * drawing from the name here but not on the server would disagree with what
+ * Slack shows anyway — so the picker then offers only a link to an image of
+ * the reader's own, with a line saying why the other option is missing rather
+ * than just not there. While the server's setting is still unknown, the
+ * Generated tab stays to avoid the layout jumping, but nothing is fetched for
+ * it yet; if the setting cannot be read, the tab says so and offers to ask
+ * again.
*/
export function AgentIconPicker({
serverId,
@@ -49,16 +65,38 @@ export function AgentIconPicker({
const [urlDraft, setUrlDraft] = useState('');
const [urlError, setUrlError] = useState<string | null>(null);
+ const {
+ thirdPartyAvatarsEnabled,
+ error: settingsError,
+ retry: retrySettings,
+ } = useAvatarSettings(serverId);
+ // Hidden only once the server has actually said no — while it is still
+ // unknown this stays up so the popover does not reflow a moment later, it
+ // just offers nothing in it yet (see the query below).
+ const generatedOffered = thirdPartyAvatarsEnabled !== false;
+ const tabs = generatedOffered ? BOTH_TABS : URL_ONLY_TAB;
+
+ // A reader left on the Generated tab when its server turns out to disable
+ // it would be looking at a tab that no longer exists.
+ useEffect(() => {
+ if (!generatedOffered) setTab('url');
+ }, [generatedOffered]);
+
// An unnamed agent still needs something to seed the grid, or every tile is
// the same face drawn from the empty string.
const seedName = name.trim() || 'agent';
// The server generates the icons on offer, so every client offers the same
- // ones and an agent created anywhere looks the same.
+ // ones and an agent created anywhere looks the same. Not asked at all until
+ // the server has said it allows them: a server that disables them answers
+ // this with an empty list anyway, but there is no reason to send the name
+ // over the wire to be told that.
const { data: choices = [], error: choicesError } = useQuery({
queryKey: ['agent-icon-choices', serverId, seedName, round],
queryFn: () =>
- rpc.switchServers.agentIconChoices({ serverId: serverId!, name: seedName, page: round }),
- enabled: serverId !== null,
+ rpc.switchServers
+ .agentIconChoices({ serverId: serverId!, name: seedName, page: round })
+ .then((result) => result.choices),
+ enabled: serverId !== null && thirdPartyAvatarsEnabled === true,
staleTime: Infinity,
});
@@ -73,6 +111,13 @@ export function AgentIconPicker({
setUrlError('Must be a link starting with https://');
return;
}
+ // The server refuses it too; saying so here keeps the draft to fix.
+ if (thirdPartyAvatarsEnabled === false && isThirdPartyAvatarUrl(trimmed)) {
+ setUrlError(
+ "This server doesn't show icons from DiceBear or ui-avatars.com. Link an image on another host."
+ );
+ return;
+ }
setUrlError(null);
onChange(trimmed);
};
@@ -87,7 +132,7 @@ export function AgentIconPicker({
!disabled && 'cursor-pointer hover:opacity-80'
)}
>
- <AgentAvatar name={seedName} iconUrl={iconUrl} size={size} />
+ <AgentAvatar name={seedName} iconUrl={iconUrl} serverId={serverId} size={size} />
{/* Shown at rest rather than on hover: that the picture is editable at
all is not guessable, and a hover-only affordance answers the
question only for someone who already suspected the answer. */}
@@ -102,14 +147,16 @@ export function AgentIconPicker({
</PopoverTrigger>
<PopoverContent align="center" sideOffset={8} className="w-80 gap-3">
- <SegmentedControl
- value={tab}
- onChange={setTab}
- options={TABS}
- ariaLabel="How to choose the icon"
- />
+ {generatedOffered && (
+ <SegmentedControl
+ value={tab}
+ onChange={setTab}
+ options={tabs}
+ ariaLabel="How to choose the icon"
+ />
+ )}
- {tab === 'generated' ? (
+ {tab === 'generated' && generatedOffered ? (
<div className="flex flex-col gap-2">
<div className="grid grid-cols-5 gap-2">
{choices.map((choice) => {
@@ -126,7 +173,7 @@ export function AgentIconPicker({
selected ? 'ring-border-focus' : 'ring-transparent hover:ring-border'
)}
>
- <AgentAvatar name={seedName} iconUrl={choice} size={44} />
+ <AgentAvatar name={seedName} iconUrl={choice} serverId={serverId} size={44} />
</button>
);
})}
@@ -134,25 +181,29 @@ export function AgentIconPicker({
<p className="text-xs text-foreground-muted">
{serverId === null
? 'Choose a Switch server to see the icons it offers.'
- : choicesError
- ? `The server's icons could not be loaded: ${failureText(choicesError, 'try again')}`
- : round === 0
- ? "First is generated from the agent's name."
- : 'Shuffled — keep going for more.'}
+ : settingsError
+ ? `Couldn't read whether this server allows generated icons: ${failureText(settingsError, 'try again')}`
+ : thirdPartyAvatarsEnabled === null
+ ? 'Checking what this server allows…'
+ : choicesError
+ ? `The server's icons could not be loaded: ${failureText(choicesError, 'try again')}`
+ : round === 0
+ ? "First is generated from the agent's name."
+ : 'Shuffled — keep going for more.'}
</p>
<button
type="button"
- onClick={() => setRound((current) => current + 1)}
+ onClick={settingsError ? retrySettings : () => setRound((current) => current + 1)}
className="flex cursor-pointer items-center justify-center gap-1.5 rounded-md border border-border py-1.5 text-xs hover:bg-background-tertiary"
>
<RotateCw className="size-3.5" />
- Show 9 more
+ {settingsError ? 'Try again' : 'Show 9 more'}
</button>
</div>
) : (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2.5 rounded-md bg-background-tertiary p-2.5">
- <AgentAvatar name={seedName} iconUrl={iconUrl} size={44} />
+ <AgentAvatar name={seedName} iconUrl={iconUrl} serverId={serverId} size={44} />
<Input
value={urlDraft}
placeholder="https://example.com/avatar.png"
@@ -175,7 +226,10 @@ export function AgentIconPicker({
urlError ? 'text-foreground-danger' : 'text-foreground-muted'
)}
>
- {urlError ?? 'A direct link to a PNG or JPEG. It is cropped to a circle.'}
+ {urlError ??
+ (generatedOffered
+ ? 'A direct link to a PNG or JPEG. It is cropped to a circle.'
+ : "This server doesn't generate icons from a name — paste a direct link to a PNG or JPEG instead. It is cropped to a circle.")}
</p>
</div>
)}
@@ -191,14 +245,16 @@ export function AgentIconPicker({
className="flex cursor-pointer items-center gap-1.5 text-xs text-foreground-muted hover:text-foreground"
>
<X className="size-3.5" />
- Use the one from the name
+ {generatedOffered ? 'Use the one from the name' : 'Remove'}
</button>
)}
{/* Why the picture is what it is. Without this the avatar appears to
change arbitrarily as the name is typed. */}
{iconUrl === null && (
<p className="text-xs text-foreground-passive">
- Using the one from the name{name.trim() === '' ? '' : ` "${name.trim()}"`}.
+ {generatedOffered
+ ? `Using the one from the name${name.trim() === '' ? '' : ` "${name.trim()}"`}.`
+ : 'No icon set — shown by its initials.'}
</p>
)}
</PopoverContent>
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
index e1570e126..8d010dac7 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
@@ -26,10 +26,19 @@ export function agentProviderLabelFor(switchAgentId: string, workspaceId: string
}
/** One agent in a picker list: avatar, name, and what runs it. */
-export function AgentPickerRow({ agent, subtitle }: { agent: AgentPick; subtitle: string }) {
+export function AgentPickerRow({
+ agent,
+ serverId,
+ subtitle,
+}: {
+ agent: AgentPick;
+ /** The Switch server `agent` belongs to, or null when it is not known. */
+ serverId: string | null;
+ subtitle: string;
+}) {
return (
<>
- <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={22} />
+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={22} />
<span className="min-w-0 flex-1 truncate">{agent.name}</span>
<span className="shrink-0 text-xs text-foreground-muted">{subtitle}</span>
</>
@@ -39,18 +48,21 @@ export function AgentPickerRow({ agent, subtitle }: { agent: AgentPick; subtitle
/** An agent already chosen, with the way to take it back out. */
export function ChosenAgentTile({
agent,
+ serverId,
subtitle,
subtitleTone,
onRemove,
}: {
agent: AgentPick;
+ /** The Switch server `agent` belongs to, or null when it is not known. */
+ serverId: string | null;
subtitle: string;
subtitleTone?: 'muted' | 'warning';
onRemove: () => void;
}) {
return (
<ChosenTile
- mark={<AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />}
+ mark={<AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={26} />}
title={agent.name}
subtitle={subtitle}
subtitleTone={subtitleTone}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-avatar-settings.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-avatar-settings.ts
new file mode 100644
index 000000000..458b76811
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-avatar-settings.ts
@@ -0,0 +1,58 @@
+import { useQuery } from '@tanstack/react-query';
+import { rpc } from '@renderer/lib/ipc';
+
+/** How often a server's setting is read again while something shows it. */
+const AVATAR_SETTINGS_REFRESH_MS = 5 * 60_000;
+
+/** Query key for a server's third-party-avatar setting, shared so every
+ * surface that asks (the agent avatar, the icon picker, the new-agent form)
+ * agrees on one cached answer per server. */
+export function avatarSettingsQueryKey(serverId: string | null) {
+ return ['avatar-settings', serverId] as const;
+}
+
+/** A server's avatar setting, as the surfaces that draw agents need it. */
+export type AvatarSettingsState = {
+ /** The server's answer, or `null` while there is none: no server to ask, an
+ * answer not in yet, or one that could not be read. */
+ thirdPartyAvatarsEnabled: boolean | null;
+ /** Why there is no answer, when reading it failed. */
+ error: Error | null;
+ /** Ask the server again. */
+ retry: () => void;
+};
+
+/**
+ * Whether `serverId` allows a third-party avatar URL (DiceBear, ui-avatars.com)
+ * to be generated or sent anywhere — the operator's `THIRD_PARTY_AVATARS_ENABLED`
+ * setting.
+ *
+ * Callers must treat a `null` answer the same as "disabled" for anything that
+ * would send a name off the machine — see `AgentAvatar`, which is the one place
+ * that matters most. A read that failed is still `null`, and says so in
+ * `error`, so a surface can tell "could not ask" from "still asking".
+ *
+ * Asked again every few minutes: the setting changes when the server
+ * restarts, which a running Console outlives, so an operator who turns it off
+ * reaches this app without anyone restarting it.
+ */
+export function useAvatarSettings(serverId: string | null): AvatarSettingsState {
+ const { data, error, refetch } = useQuery({
+ queryKey: avatarSettingsQueryKey(serverId),
+ queryFn: () => rpc.switchServers.avatarSettings(serverId as string),
+ enabled: serverId !== null,
+ staleTime: AVATAR_SETTINGS_REFRESH_MS,
+ refetchInterval: AVATAR_SETTINGS_REFRESH_MS,
+ });
+ return {
+ thirdPartyAvatarsEnabled: data?.thirdPartyAvatarsEnabled ?? null,
+ // A failed refetch keeps the last answer, which still stands.
+ error: data === undefined ? error : null,
+ retry: () => void refetch(),
+ };
+}
+
+/** {@link useAvatarSettings}, for a caller that needs only the answer. */
+export function useThirdPartyAvatarsEnabled(serverId: string | null): boolean | null {
+ return useAvatarSettings(serverId).thirdPartyAvatarsEnabled;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
index d0e4bfe19..072b043c2 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/add-agent-settings-disclosure.test.tsx
@@ -68,7 +68,7 @@ afterEach(async () => {
});
function Panel() {
- const form = useConfigureAgentForm();
+ const form = useConfigureAgentForm(null);
return (
<AgentSettingsSection
form={form}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx
index 5d5218b8a..e442f0a4a 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-avatar-retry.test.tsx
@@ -2,6 +2,7 @@
* An agent's avatar that fails to load is tried again before the initials
* stay: the avatar service refuses bursts, and those refusals pass.
*/
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
@@ -28,7 +29,15 @@ it('tries a failed avatar again, then keeps the initials after the last try', as
document.body.appendChild(container);
root = createRoot(container);
await act(async () =>
- root!.render(<AgentAvatar name="Ada Lovelace" iconUrl="https://avatars.invalid/ada.svg" />)
+ root!.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <AgentAvatar
+ name="Ada Lovelace"
+ iconUrl="https://avatars.invalid/ada.svg"
+ serverId={null}
+ />
+ </QueryClientProvider>
+ )
);
for (let tryNumber = 0; tryNumber < 3; tryNumber++) {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-privacy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-privacy.test.tsx
new file mode 100644
index 000000000..b215adc6a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-privacy.test.tsx
@@ -0,0 +1,135 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+/**
+ * What the icon picker offers once it knows whether its server allows
+ * third-party avatars (THIRD_PARTY_AVATARS_ENABLED).
+ *
+ * A server that disables them has nothing to generate — offering a Generated
+ * tab that always comes back empty would read as broken, not as a choice the
+ * operator made, so the tab itself has to go, with a line saying why.
+ */
+import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
+import { avatarSettingsQueryKey } from '@renderer/lib/stores/use-avatar-settings';
+
+// An answer the server never gives, so an unseeded setting stays "not known
+// yet" rather than failing; a seeded one is fresh and never asked for.
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: {
+ switchServers: {
+ avatarSettings: vi.fn(() => new Promise<never>(() => {})),
+ agentIconChoices: vi.fn(() =>
+ Promise.resolve({ choices: [], thirdPartyAvatarsEnabled: true })
+ ),
+ },
+ },
+}));
+
+const SERVER_ID = 'srv-1';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+/** Renders the picker and opens it, seeding the server's avatar setting —
+ * `null` leaves it unseeded, exercising "not known yet". */
+async function openPicker(
+ thirdPartyAvatarsEnabled: boolean | null,
+ onChange: (iconUrl: string | null) => void = () => {}
+): Promise<void> {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: Infinity } },
+ });
+ if (thirdPartyAvatarsEnabled !== null) {
+ client.setQueryData(avatarSettingsQueryKey(SERVER_ID), { thirdPartyAvatarsEnabled });
+ }
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <AgentIconPicker serverId={SERVER_ID} name="worker" iconUrl={null} onChange={onChange} />
+ </QueryClientProvider>
+ )
+ );
+
+ const trigger = container.querySelector<HTMLElement>('[aria-label="Change the agent\'s icon"]');
+ expect(trigger, 'the picker drew no trigger to open').not.toBeNull();
+ await act(async () => trigger!.click());
+}
+
+describe('the icon picker on a server that disables third-party avatars', () => {
+ it('offers no Generated tab', async () => {
+ await openPicker(false);
+ expect(document.querySelector('[aria-label="Generated"]')).toBeNull();
+ });
+
+ it('does not show a tab control for a single remaining option', async () => {
+ // One option is no choice at all — a segmented control with one button in
+ // it reads as broken, not as "here is the one thing you can do".
+ await openPicker(false);
+ expect(document.querySelector('[aria-label="How to choose the icon"]')).toBeNull();
+ });
+
+ it('explains why, rather than leaving the missing tab a mystery', async () => {
+ await openPicker(false);
+ expect(document.body.textContent).toContain("doesn't generate icons from a name");
+ });
+
+ it('refuses a link to an avatar service, saying why, rather than saving it', async () => {
+ const chosen: (string | null)[] = [];
+ await openPicker(false, (iconUrl) => chosen.push(iconUrl));
+ const input = document.querySelector<HTMLInputElement>(
+ 'input[placeholder="https://example.com/avatar.png"]'
+ )!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(
+ input,
+ 'https://api.dicebear.com/10.x/gaze/png?seed=worker'
+ );
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () =>
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
+ );
+ expect(chosen).toEqual([]);
+ expect(document.body.textContent).toContain("doesn't show icons from DiceBear");
+ });
+
+ it('still offers the Image URL field directly', async () => {
+ await openPicker(false);
+ expect(
+ document.querySelector('input[placeholder="https://example.com/avatar.png"]')
+ ).not.toBeNull();
+ });
+});
+
+describe('the icon picker on a server that allows third-party avatars', () => {
+ it('offers both tabs', async () => {
+ await openPicker(true);
+ expect(document.querySelector('[aria-label="Generated"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Image URL"]')).not.toBeNull();
+ });
+});
+
+describe('the icon picker before its server has answered', () => {
+ it('keeps the Generated tab up rather than reflowing twice', async () => {
+ await openPicker(null);
+ expect(document.querySelector('[aria-label="Generated"]')).not.toBeNull();
+ });
+
+ it('says it is checking, rather than claiming a page of icons', async () => {
+ await openPicker(null);
+ expect(document.body.textContent).toContain('Checking what this server allows');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-settings-error.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-settings-error.test.tsx
new file mode 100644
index 000000000..c4bdf939e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-picker-settings-error.test.tsx
@@ -0,0 +1,84 @@
+/**
+ * The icon picker when its server's avatar setting (THIRD_PARTY_AVATARS_ENABLED)
+ * cannot be read.
+ *
+ * An unread setting still counts as "not allowed", so nothing is asked for in
+ * the agent's name. What it must not do is look like it is still asking: the
+ * reader is told the setting could not be read, and can ask again.
+ */
+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 { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
+
+const avatarSettings = vi.hoisted(() => vi.fn());
+const agentIconChoices = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: vi.fn() },
+ rpc: { switchServers: { avatarSettings, agentIconChoices } },
+}));
+
+const SERVER_ID = 'srv-1';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ avatarSettings.mockReset().mockRejectedValue(new Error('server unreachable'));
+ agentIconChoices.mockReset().mockResolvedValue({ choices: [], thirdPartyAvatarsEnabled: true });
+});
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function openPicker(): Promise<void> {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <AgentIconPicker serverId={SERVER_ID} name="worker" iconUrl={null} onChange={() => {}} />
+ </QueryClientProvider>
+ )
+ );
+ await vi.waitFor(() => expect(avatarSettings).toHaveBeenCalled());
+ const trigger = container.querySelector<HTMLElement>('[aria-label="Change the agent\'s icon"]');
+ expect(trigger, 'the picker drew no trigger to open').not.toBeNull();
+ await act(async () => trigger!.click());
+}
+
+function buttonNamed(label: string): HTMLButtonElement | undefined {
+ return [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);
+}
+
+it('says the setting could not be read, rather than that it is still checking', async () => {
+ await openPicker();
+ await vi.waitFor(() =>
+ expect(document.body.textContent).toContain(
+ "Couldn't read whether this server allows generated icons"
+ )
+ );
+ expect(document.body.textContent).not.toContain('Checking what this server allows');
+});
+
+it('asks for no icons in the agent’s name while the setting is unread', async () => {
+ await openPicker();
+ await vi.waitFor(() => expect(buttonNamed('Try again')).toBeDefined());
+ expect(agentIconChoices).not.toHaveBeenCalled();
+});
+
+it('asks the server again from Try again', async () => {
+ await openPicker();
+ await vi.waitFor(() => expect(buttonNamed('Try again')).toBeDefined());
+ const before = avatarSettings.mock.calls.length;
+ await act(async () => buttonNamed('Try again')!.click());
+ await vi.waitFor(() => expect(avatarSettings.mock.calls.length).toBeGreaterThan(before));
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx
index 72b279cb7..80dde0d9c 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-default-policy.test.tsx
@@ -28,7 +28,7 @@ afterEach(async () => {
async function initialMode(): Promise<string> {
let seen = '';
function Probe() {
- const form = useConfigureAgentForm();
+ const form = useConfigureAgentForm(null);
seen = addressingModeOf(form.addressingPolicy);
return null;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx
index 050cb0f6a..1fd6df7bb 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-display-name.test.tsx
@@ -44,7 +44,7 @@ afterEach(async () => {
async function mountForm(): Promise<() => ConfigureAgentFormState> {
let latest: ConfigureAgentFormState | null = null;
function Probe() {
- latest = useConfigureAgentForm();
+ latest = useConfigureAgentForm(null);
return null;
}
container = document.createElement('div');
@@ -135,7 +135,7 @@ afterEach(async () => {
});
function Fields() {
- domForm = useConfigureAgentForm();
+ domForm = useConfigureAgentForm(null);
return <AgentIdentityFields form={domForm} serverId={null} nameTaken={false} />;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
index e388ba1a9..9a6f0a4ff 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
@@ -1,9 +1,11 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
/**
- * The picture a brand-new agent opens on (CHOO-2203).
+ * The picture a brand-new agent opens on (CHOO-2203), and what happens to it
+ * when the chosen server turns out to disable third-party avatars
+ * (THIRD_PARTY_AVATARS_ENABLED).
*
* The form used to start with no icon at all, which left the avatar seeded by
* the empty name — a single hard-coded bot that every agent, for every user,
@@ -12,6 +14,13 @@ import { afterEach, describe, expect, it } from 'vitest';
*/
import { useConfigureAgentForm } from '@renderer/features/locations/components/add-agent-modal/modes';
+const avatarSettings = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: { switchServers: { avatarSettings } },
+}));
+
let container: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -20,16 +29,19 @@ afterEach(async () => {
container?.remove();
container = null;
root = null;
+ avatarSettings.mockReset();
});
/** The icon state the creation form starts on, read off the real hook. */
-async function initialIcon(): Promise<{ iconUrl: string | null; iconIsGenerated: boolean }> {
+async function initialIcon(
+ serverId: string | null = null
+): Promise<{ iconUrl: string | null; iconIsGenerated: boolean }> {
let seen: { iconUrl: string | null; iconIsGenerated: boolean } = {
iconUrl: null,
iconIsGenerated: false,
};
function Probe() {
- const form = useConfigureAgentForm();
+ const form = useConfigureAgentForm(serverId);
seen = { iconUrl: form.iconUrl, iconIsGenerated: form.iconIsGenerated };
return null;
}
@@ -71,3 +83,67 @@ describe('a new agent', () => {
expect(first.iconUrl).not.toBe(second.iconUrl);
});
});
+
+describe('a new agent on a server that disables third-party avatars', () => {
+ /**
+ * The icon state once the server's answer has arrived, read off the real
+ * hook with its own `QueryClientProvider` so the effect that clears the
+ * random DiceBear default actually runs.
+ */
+ async function settledIcon(thirdPartyAvatarsEnabled: boolean): Promise<{
+ iconUrl: string | null;
+ iconIsGenerated: boolean;
+ thirdPartyAvatarsEnabled: boolean | null;
+ }> {
+ avatarSettings.mockResolvedValue({ thirdPartyAvatarsEnabled });
+ let seen: {
+ iconUrl: string | null;
+ iconIsGenerated: boolean;
+ thirdPartyAvatarsEnabled: boolean | null;
+ } = {
+ iconUrl: null,
+ iconIsGenerated: false,
+ thirdPartyAvatarsEnabled: null,
+ };
+ function Probe() {
+ const form = useConfigureAgentForm('srv-1');
+ seen = {
+ iconUrl: form.iconUrl,
+ iconIsGenerated: form.iconIsGenerated,
+ thirdPartyAvatarsEnabled: form.thirdPartyAvatarsEnabled,
+ };
+ return null;
+ }
+ 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}>
+ <Probe />
+ </QueryClientProvider>
+ )
+ );
+ await vi.waitFor(() => expect(avatarSettings).toHaveBeenCalled());
+ // Let the server's answer reach the effect that acts on it.
+ await act(async () => {});
+ return seen;
+ }
+
+ it('loses the random DiceBear default once the server says no', async () => {
+ expect((await settledIcon(false)).iconUrl).toBeNull();
+ });
+
+ it('still counts a cleared icon as generated, not as a custom choice', async () => {
+ expect((await settledIcon(false)).iconIsGenerated).toBe(true);
+ });
+
+ it('carries the server’s answer, so the caption can say there is no icon', async () => {
+ expect((await settledIcon(false)).thirdPartyAvatarsEnabled).toBe(false);
+ });
+
+ it('keeps the random DiceBear default when the server allows it', async () => {
+ expect((await settledIcon(true)).iconUrl).toContain('/gaze/png?');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
index 7d1b764b0..2875f4c16 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-name-suggestion.test.tsx
@@ -42,7 +42,7 @@ afterEach(async () => {
});
function Fields({ nameTaken }: { nameTaken: boolean }) {
- form = useConfigureAgentForm();
+ form = useConfigureAgentForm(null);
return <AgentIdentityFields form={form} serverId={null} nameTaken={nameTaken} />;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
index ebd8ceaf0..b3c017c1f 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
@@ -16,6 +16,7 @@ import { PaletteAgentItem } from '@renderer/features/command-palette/palette-age
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { ThemeContext } from '@renderer/lib/providers/theme-provider';
import { AGENTS_METADATA_QUERY_KEY } from '@renderer/lib/stores/use-agents';
+import { avatarSettingsQueryKey } from '@renderer/lib/stores/use-avatar-settings';
import { workspaceAgentsQueryKey } from '@renderer/lib/stores/use-workspace-agents';
import type { Agent } from '@shared/core/agents/agents';
import type { SearchItem } from '@shared/core/search';
@@ -89,13 +90,23 @@ afterEach(async () => {
runInAction(() => agentsStore.byLocation.clear());
});
-/** The `src` of the picture the search row draws for the agent. */
-async function rowAvatarSrc(options: {
- /** Seed the local agent row, as a hit on a known agent would find it. */
+/**
+ * What the search row drew for the agent: the `src` of its picture, or null
+ * when it drew initials instead (no third-party avatar allowed, or none
+ * chosen).
+ */
+async function rowAvatar(options: {
+ /** Seed the local agent row, as a hit on a known agent would find it. A
+ * miss (false) means the row has no server to ask either, so it is also
+ * how "no server known" is exercised here. */
known: boolean;
/** The icon the server holds for it, or null for none. */
iconUrl: string | null;
-}): Promise<string> {
+ /** The owning server's `THIRD_PARTY_AVATARS_ENABLED` answer. Left unset to
+ * exercise "not known yet" — `known: false` makes this moot, since there is
+ * then no server id to ask about. */
+ thirdPartyAvatarsEnabled?: boolean;
+}): Promise<string | null> {
if (options.known) {
runInAction(() => agentsStore.byLocation.set(LOCATION_ID, [AGENT]));
}
@@ -110,6 +121,11 @@ async function rowAvatarSrc(options: {
// so it resolves to nothing rather than reaching for a main process the test
// does not have; the mark itself is the sidebar's, already covered there.
client.setQueryData(AGENTS_METADATA_QUERY_KEY, []);
+ if (options.thirdPartyAvatarsEnabled !== undefined) {
+ client.setQueryData(avatarSettingsQueryKey(SERVER_ID), {
+ thirdPartyAvatarsEnabled: options.thirdPartyAvatarsEnabled,
+ });
+ }
container = document.createElement('div');
document.body.appendChild(container);
@@ -130,26 +146,42 @@ async function rowAvatarSrc(options: {
// `alt=""` is the avatar's; the provider mark carries its provider's name.
const img = container.querySelector('img[alt=""]');
- if (!img) throw new Error('the search row drew no picture at all');
- return img.getAttribute('src') ?? '';
+ return img ? img.getAttribute('src') : null;
}
describe('an agent in search', () => {
it('wears its own chosen icon', async () => {
- const src = await rowAvatarSrc({ known: true, iconUrl: 'https://icons.example/reviewer.png' });
+ const src = await rowAvatar({ known: true, iconUrl: 'https://icons.example/reviewer.png' });
expect(src).toBe('https://icons.example/reviewer.png');
});
- it('falls back to the face drawn from its name, not its provider logo', async () => {
- const src = await rowAvatarSrc({ known: true, iconUrl: null });
+ it('falls back to the face drawn from its name on a server that allows it, not its provider logo', async () => {
+ const src = await rowAvatar({ known: true, iconUrl: null, thirdPartyAvatarsEnabled: true });
expect(src).toContain('/gaze/png?');
expect(src).toContain(AGENT_NAME);
});
- it('still draws a face when the app holds no local row for the hit', async () => {
+ it('withholds the generated face when its server disables third-party avatars', async () => {
+ const src = await rowAvatar({ known: true, iconUrl: null, thirdPartyAvatarsEnabled: false });
+ expect(src).toBeNull();
+ });
+
+ it('still shows a custom icon even when its server disables third-party avatars', async () => {
+ const src = await rowAvatar({
+ known: true,
+ iconUrl: 'https://icons.example/reviewer.png',
+ thirdPartyAvatarsEnabled: false,
+ });
+ expect(src).toBe('https://icons.example/reviewer.png');
+ });
+
+ it('shows initials rather than a face when the app holds no local row for the hit', async () => {
// The lookup that used to supply the provider id can miss — a stale index
- // entry, an agent removed since. A miss must not leave the row blank.
- const src = await rowAvatarSrc({ known: false, iconUrl: null });
- expect(src).toContain('/gaze/png?');
+ // entry, an agent removed since. A miss leaves no server to ask about
+ // third-party avatars either, so this is the same "unknown" case the
+ // privacy setting fails closed on: no name-seeded avatar until Console
+ // knows the server allows it.
+ const src = await rowAvatar({ known: false, iconUrl: null });
+ expect(src).toBeNull();
});
});
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
index f0c8422a5..ba3260b30 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
@@ -5,7 +5,9 @@ import {
agentAvatarUrlForName,
agentAvatarUrlForSeed,
agentInitials,
+ isThirdPartyAvatarUrl,
randomAgentAvatarUrl,
+ resolveAgentAvatarSrc,
} from './agent-avatar';
describe('randomAgentAvatarUrl', () => {
@@ -106,6 +108,88 @@ describe('agentAvatarChoices', () => {
});
});
+describe('isThirdPartyAvatarUrl', () => {
+ it('matches a DiceBear URL', () => {
+ expect(isThirdPartyAvatarUrl(agentAvatarUrlForName('worker'))).toBe(true);
+ });
+
+ it('matches a ui-avatars.com URL', () => {
+ expect(isThirdPartyAvatarUrl('https://ui-avatars.com/api/?name=Ada+Lovelace')).toBe(true);
+ });
+
+ it('matches a subdomain of either host', () => {
+ expect(isThirdPartyAvatarUrl('https://api.dicebear.com/10.x/gaze/png?seed=x')).toBe(true);
+ expect(isThirdPartyAvatarUrl('https://cdn.ui-avatars.com/api/?name=x')).toBe(true);
+ });
+
+ it('matches regardless of case', () => {
+ expect(isThirdPartyAvatarUrl('https://API.DICEBEAR.COM/10.x/gaze/png?seed=x')).toBe(true);
+ });
+
+ it('ignores a trailing dot on the hostname, as the server does', () => {
+ // `dicebear.com.` names the same host as `dicebear.com`.
+ expect(isThirdPartyAvatarUrl('https://dicebear.com./10.x/gaze/png?seed=x')).toBe(true);
+ expect(isThirdPartyAvatarUrl('https://api.dicebear.com./10.x/gaze/png?seed=x')).toBe(true);
+ expect(isThirdPartyAvatarUrl('https://ui-avatars.com./api/?name=x')).toBe(true);
+ });
+
+ it('rejects a lookalike host that merely starts or ends with the name', () => {
+ // `api.dicebear.com` is a label under `.example`, not a DiceBear subdomain.
+ expect(isThirdPartyAvatarUrl('https://api.dicebear.com.example/x')).toBe(false);
+ expect(isThirdPartyAvatarUrl('https://notdicebear.com/x.png')).toBe(false);
+ expect(isThirdPartyAvatarUrl('https://ui-avatars.com.evil.test/api/?name=x')).toBe(false);
+ });
+
+ it('rejects an unrelated host', () => {
+ expect(isThirdPartyAvatarUrl('https://example.com/avatar.png')).toBe(false);
+ });
+
+ it('answers false for a URL that cannot be parsed', () => {
+ expect(isThirdPartyAvatarUrl('not a url')).toBe(false);
+ });
+});
+
+describe('resolveAgentAvatarSrc', () => {
+ // These are AgentAvatar's own states — pulled out so the privacy-sensitive
+ // decision ("may a name-seeded or stored third-party URL be shown at all")
+ // is tested without rendering the component.
+
+ it('falls back to the name-generated avatar when the server allows it and nothing was chosen', () => {
+ expect(resolveAgentAvatarSrc(null, 'worker', true)).toBe(agentAvatarUrlForName('worker'));
+ });
+
+ it('shows a chosen icon as-is when the server allows third-party avatars', () => {
+ expect(resolveAgentAvatarSrc('https://example.com/a.png', 'worker', true)).toBe(
+ 'https://example.com/a.png'
+ );
+ });
+
+ it('shows nothing — not the name-generated avatar — when the server disables them', () => {
+ expect(resolveAgentAvatarSrc(null, 'worker', false)).toBeNull();
+ });
+
+ it('withholds a stored third-party icon when the server disables them', () => {
+ expect(resolveAgentAvatarSrc(agentAvatarUrlForName('worker'), 'worker', false)).toBeNull();
+ });
+
+ it('still shows a custom, non-third-party icon when the server disables third-party avatars', () => {
+ expect(resolveAgentAvatarSrc('https://example.com/a.png', 'worker', false)).toBe(
+ 'https://example.com/a.png'
+ );
+ });
+
+ it('treats "not known yet" exactly like disabled, not like enabled', () => {
+ expect(resolveAgentAvatarSrc(null, 'worker', null)).toBeNull();
+ expect(resolveAgentAvatarSrc(agentAvatarUrlForName('worker'), 'worker', null)).toBeNull();
+ });
+
+ it('still shows a custom, non-third-party icon while the server is not known yet', () => {
+ expect(resolveAgentAvatarSrc('https://example.com/a.png', 'worker', null)).toBe(
+ 'https://example.com/a.png'
+ );
+ });
+});
+
describe('agentInitials', () => {
it('takes the first letter of a single-word name', () => {
expect(agentInitials('worker')).toBe('W');
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
index 5b6b4bef4..b339d3f67 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
@@ -88,6 +88,53 @@ function sequentialSeeds(agentName: string, round: number, count: number): strin
return Array.from({ length: count }, (_, index) => `${agentName}-${round}-${index}`);
}
+/** The services `isThirdPartyAvatarUrl` matches, any host under them included. */
+const THIRD_PARTY_AVATAR_SERVICES = ['dicebear.com', 'ui-avatars.com'];
+
+/**
+ * Whether `url` is drawn by an outside avatar service: DiceBear, which draws
+ * the generated faces, or ui-avatars.com, which Switch uses for a person
+ * relayed from another platform. Those services see whatever is in the URL and
+ * the address of whoever loads it.
+ *
+ * The server draws the same line (`is_third_party_avatar` in
+ * `core/switch_core/agent_icon.py`) for `THIRD_PARTY_AVATARS_ENABLED`, so the
+ * two must agree, or this app would load an icon the server withholds from
+ * Slack. An unparseable URL names neither service.
+ */
+export function isThirdPartyAvatarUrl(url: string): boolean {
+ let hostname: string;
+ try {
+ hostname = new URL(url).hostname.toLowerCase();
+ } catch {
+ return false;
+ }
+ // A trailing dot names the same host.
+ const host = hostname.replace(/\.+$/, '');
+ return THIRD_PARTY_AVATAR_SERVICES.some(
+ (service) => host === service || host.endsWith(`.${service}`)
+ );
+}
+
+/**
+ * The URL `AgentAvatar` should load, or null to show initials.
+ *
+ * `thirdPartyAvatarsEnabled` is the agent's server's setting, or null while it
+ * is not known. Unknown behaves as disabled, so no name leaves the machine
+ * before the server has said it may.
+ */
+export function resolveAgentAvatarSrc(
+ iconUrl: string | null,
+ name: string,
+ thirdPartyAvatarsEnabled: boolean | null
+): string | null {
+ if (thirdPartyAvatarsEnabled === true) {
+ return iconUrl ?? agentAvatarUrlForName(name);
+ }
+ // An icon on any other host still shows.
+ return iconUrl !== null && !isThirdPartyAvatarUrl(iconUrl) ? iconUrl : null;
+}
+
/**
* The letters shown when an agent has no picture to draw — either because the
* image failed to load or because nothing has been chosen and no name-derived
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 bdc27009d..13aa56825 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
@@ -239,7 +239,10 @@ export type AgentIconBackfill =
| { kind: 'written'; written: number }
/** The server has no agent-icon endpoint — it predates the feature. */
| { kind: 'unsupported' }
- | { kind: 'partial'; written: number; failed: number };
+ | { kind: 'partial'; written: number; failed: number }
+ /** The server disables third-party avatars, so nothing was generated or
+ * written — by the operator's own choice, not a failure. */
+ | { kind: 'disabled' };
/** Read-only summary of a remote room (mirrors the gateway `RoomSummary`). */
export type RemoteRoomSummary = {
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index 7621c71db..f3ebc7d3f 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -745,7 +745,9 @@ shared by several machines is refused with the candidates; pass the id.
`actual.process`; while `actual` is still null, `pending` or `starting`,
check again every 2 seconds, for at most a minute, before telling anyone the
agent is ready. An agent created without an `icon_url` gets the icon its name
-generates.
+generates, unless the server has third-party avatars turned off: it then gets
+no icon, each platform shows its default, and an `icon_url` on dicebear.com or
+ui-avatars.com is not accepted.
## Room roles (assumable)
diff --git a/core/switch_core/agent_icon.py b/core/switch_core/agent_icon.py
index aabb10a29..b36588b7f 100644
--- a/core/switch_core/agent_icon.py
+++ b/core/switch_core/agent_icon.py
@@ -9,6 +9,10 @@ generates, so it looks the same as one that was given it. A sender that is not
an agent at all keeps a lettered badge (`initials_icon_url`), so a person never
wears an agent's face.
+Both are drawn by outside services that see the name in the URL. An operator
+who sets `THIRD_PARTY_AVATARS_ENABLED=false` gets neither: the bridges send no
+icon where one would be (`is_third_party_avatar`), and nothing new is generated.
+
That makes the URL attacker-controlled input with two distinct consumers, and
the rules below exist for the second one:
@@ -44,6 +48,10 @@ _BLOCKED_HOSTNAMES = frozenset(
)
+# A host part that clients and `urlsplit` read differently.
+_AMBIGUOUS_HOST = re.compile(r"[\\%]|[^\x00-\x7f]")
+
+
class InvalidIconUrl(ValueError):
"""Raised when an icon URL is missing, malformed, or points somewhere unsafe."""
@@ -93,11 +101,25 @@ def validate_icon_url(url: str) -> str:
if any(character.isspace() or ord(character) < 0x20 for character in candidate):
_reject("must not contain whitespace or control characters")
+ # Browsers and chat clients read `\` as `/`, so for them the host ends
+ # where `urlsplit` sees it continue, and every host check here would be
+ # made against a host nobody loads.
+ if "\\" in candidate:
+ _reject("must not contain a backslash")
+
try:
parts = urlsplit(candidate)
except ValueError as exc:
_reject(f"could not be parsed ({exc})")
+ # Clients decode a percent-encoded host and map non-ASCII look-alikes
+ # (`。` for `.`) before connecting; `urlsplit` does neither.
+ if _AMBIGUOUS_HOST.search(parts.netloc):
+ _reject(
+ "must spell its host plainly, without percent-encoding or non-ASCII "
+ "characters (an international name goes in its xn-- form)"
+ )
+
if parts.scheme != "https":
_reject(f"must use https, got {parts.scheme or 'no scheme'!r}")
@@ -116,7 +138,9 @@ def validate_icon_url(url: str) -> str:
# Generated icons. The URL is all Switch stores; the picture is DiceBear's
# "gaze", raster because Slack, Discord and Mattermost render no SVG, and pinned
# to a major version because the drawing changes between majors.
-_GENERATED_ICON_BASE = "https://api.dicebear.com/10.x/gaze/png"
+_GENERATED_ICON_SERVICE = "dicebear.com"
+GENERATED_ICON_HOST = f"api.{_GENERATED_ICON_SERVICE}"
+_GENERATED_ICON_BASE = f"https://{GENERATED_ICON_HOST}/10.x/gaze/png"
_GENERATED_ICON_PIXELS = 256
# A tenth larger than DiceBear draws it, which leaves the body small in its
# frame at chat-avatar size. At that scale a round crop (Discord, Mattermost,
@@ -173,6 +197,9 @@ def prepare_icon_url(url: str) -> str:
return validate_icon_url(upgrade_legacy_icon_url(url.strip()))
+_INITIALS_ICON_SERVICE = "ui-avatars.com"
+
+
def initials_icon_url(name: str) -> str:
"""The lettered badge for a sender that is not an agent.
@@ -185,7 +212,74 @@ def initials_icon_url(name: str) -> str:
# the fact turns it back into a literal plus and the name renders with one
# initial instead.
escaped = quote(name).replace("_", "+")
- return f"https://ui-avatars.com/api/?name={escaped}&background=random&size=128"
+ return f"https://{_INITIALS_ICON_SERVICE}/api/?name={escaped}&background=random&size=128"
+
+
+# Every service the two builders above send a name to. Any host under them
+# counts, not just the one a builder uses, because a stored icon can name any.
+_THIRD_PARTY_AVATAR_SERVICES = (_GENERATED_ICON_SERVICE, _INITIALS_ICON_SERVICE)
+
+
+def is_third_party_avatar(url: str) -> bool:
+ """Whether `url` is drawn by one of the avatar services above.
+
+ Those services receive whatever is in the URL, which for the icons Switch
+ builds is an agent's or a person's name, along with the address of every
+ client that loads it. `THIRD_PARTY_AVATARS_ENABLED=false` keeps every such
+ URL from leaving the server, whoever chose it.
+ """
+ try:
+ parts = urlsplit(url)
+ host = parts.hostname
+ except ValueError:
+ return False
+ if not host:
+ return False
+ # Which service such a host names depends on the client reading it, so it
+ # counts as one. `validate_icon_url` refuses to store such a host; only an
+ # older row can carry one.
+ if _AMBIGUOUS_HOST.search(parts.netloc):
+ return True
+ # A trailing dot names the same host, and `hostname` is already lowercase.
+ host = host.rstrip(".")
+ return any(
+ host == service or host.endswith(f".{service}")
+ for service in _THIRD_PARTY_AVATAR_SERVICES
+ )
+
+
+def refuse_third_party_avatar(
+ url: str | None, *, third_party_avatars: bool
+) -> str | None:
+ """`url`, or `InvalidIconUrl` when this server would withhold it.
+
+ For a request that sets an icon. With third-party avatars off every bridge
+ withholds an icon on one of the avatar services, so storing one would
+ leave the agent drawn with each platform's default and nothing to say why.
+ """
+ if url is not None and not third_party_avatars and is_third_party_avatar(url):
+ _reject(
+ "this server has third-party avatars turned off, so an icon from "
+ "dicebear.com or ui-avatars.com would never be shown; link an image "
+ "on another host"
+ )
+ return url
+
+
+def drop_third_party_avatar(
+ url: str | None, *, third_party_avatars: bool
+) -> str | None:
+ """`url`, or None when this server would withhold it.
+
+ For creating or registering an agent, where a client sends an icon of its
+ own when nobody chose one: Switch Console releases from before the setting
+ send a DiceBear face every time. Refusing those would stop them creating
+ agents at all, so the agent is created with no icon instead, as the
+ response shows.
+ """
+ if url is not None and not third_party_avatars and is_third_party_avatar(url):
+ return None
+ return url
def generated_icon_choices(agent_name: str, page: int) -> list[str]:
diff --git a/core/switch_core/bridges/agent/operations/agent_management.py b/core/switch_core/bridges/agent/operations/agent_management.py
index 70ae6945e..8534d94b2 100644
--- a/core/switch_core/bridges/agent/operations/agent_management.py
+++ b/core/switch_core/bridges/agent/operations/agent_management.py
@@ -218,7 +218,9 @@ async def create_agent(
auto_approve: Let the agent run tools without asking for approval.
display_name: A human label shown next to `name`, or null for none.
icon_url: An https link to the agent's icon, or null for the icon
- its name generates, the same one Switch Console offers first.
+ its name generates, the same one Switch Console offers first. A
+ server with third-party avatars off generates none, and the agent
+ then shows each platform's default icon.
start: Start the agent now (true) or create it stopped (false).
Returns:
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 39a3b4d22..055c4c3fa 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -2160,7 +2160,9 @@ async def update_agent_detail(
Any agent:
description: What the agent is for.
display_name: Human label shown next to its name; "" clears it.
- icon_url: An https link to its icon; "" clears it.
+ icon_url: An https link to its icon; "" clears it. A server with
+ third-party avatars off refuses one on dicebear.com or
+ ui-avatars.com.
addressing: Who can address it: "owner_only" (your owner alone, not
even their other agents, you included), "owner_and_owner_agents"
(your owner and any agent they own) or "anyone".
@@ -2203,6 +2205,7 @@ async def update_agent_detail(
display_name=display_name,
icon_url=icon_url,
addressing=addressing,
+ third_party_avatars=protocol.config.third_party_avatars_enabled,
)
changes = ManagedAgentChanges(
provider=provider,
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index 4127d7536..bca651c05 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -18,7 +18,12 @@ from switch_core.addressing import (
parse_policy,
)
from switch_core.agent_display_name import normalise_display_name
-from switch_core.agent_icon import normalise_icon_url, prepare_icon_url
+from switch_core.agent_icon import (
+ drop_third_party_avatar,
+ normalise_icon_url,
+ prepare_icon_url,
+ refuse_third_party_avatar,
+)
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.attachments import parse_attachment_group
from switch_core.authz import Action, Principal, require, require_manage
@@ -389,7 +394,8 @@ class AgentCore:
``icon_url`` is the agent's icon as an absolute https URL, or None for
no icon. On re-registration None leaves any existing icon alone rather
than clearing it, so re-registering an agent does not silently discard
- a picture the owner chose.
+ a picture the owner chose. With third-party avatars off, an icon on
+ one of those services counts as None (`drop_third_party_avatar`).
``display_name`` is the human-readable label shown beside the machine
identifier ``name``, or None for none. It behaves like ``icon_url`` on
@@ -422,7 +428,10 @@ class AgentCore:
"its bridge identities both belong to one"
)
- validated_icon_url = normalise_icon_url(icon_url)
+ validated_icon_url = drop_third_party_avatar(
+ normalise_icon_url(icon_url),
+ third_party_avatars=self.config.third_party_avatars_enabled,
+ )
validated_display_name = normalise_display_name(display_name)
tool_specs = tools or []
@@ -903,10 +912,14 @@ class AgentCore:
an icon needs "remove it" to be sayable.
Raises:
- InvalidIconUrl: the URL is malformed or points somewhere unsafe.
+ InvalidIconUrl: the URL is malformed, points somewhere unsafe, or
+ is on an avatar service this server has turned off.
ValueError: no agent with this id exists.
"""
- validated = prepare_icon_url(icon_url) if icon_url is not None else None
+ validated = refuse_third_party_avatar(
+ prepare_icon_url(icon_url) if icon_url is not None else None,
+ third_party_avatars=self.config.third_party_avatars_enabled,
+ )
async with self.session_factory() as session:
agent = await self.agent_store.get(session, agent_id)
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index 86ff8cfa1..7f8595d33 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -23,7 +23,7 @@ from switch_core.addressing import (
owner_only_policy,
)
from switch_core.agent_display_name import normalise_display_name
-from switch_core.agent_icon import normalise_icon_url
+from switch_core.agent_icon import normalise_icon_url, refuse_third_party_avatar
from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
from switch_core.bridges.agent.protocol.statuses import agent_statuses_by_room
from switch_core.db.models import Agent, AgentSession
@@ -394,10 +394,12 @@ class AgentProfileUpdate:
display_name: str | None,
icon_url: str | None,
addressing: str | None,
+ third_party_avatars: bool,
) -> AgentProfileUpdate:
"""None leaves a field as it is; an empty `display_name` or `icon_url`
clears it. Raises ValueError (InvalidIconUrl, InvalidDisplayName) for
- a value that cannot be stored."""
+ a value that cannot be stored, which includes an icon on an avatar
+ service when `third_party_avatars` (the server's setting) is off."""
columns: dict[str, Any] = {}
if description is not None:
if not description.strip():
@@ -406,7 +408,9 @@ class AgentProfileUpdate:
if display_name is not None:
columns["display_name"] = normalise_display_name(display_name)
if icon_url is not None:
- columns["icon_url"] = normalise_icon_url(icon_url)
+ columns["icon_url"] = refuse_third_party_avatar(
+ normalise_icon_url(icon_url), third_party_avatars=third_party_avatars
+ )
if addressing is not None:
columns["addressing_policy"] = addressing_policy_for(addressing)
return cls(columns=columns)
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index bd685a606..381d1e673 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -11,7 +11,11 @@ from pathlib import Path
from typing import Any, ClassVar, Literal, Protocol, final, runtime_checkable
from switch_core.agent_display_name import defuse_label_markup
-from switch_core.agent_icon import generated_icon_url, initials_icon_url
+from switch_core.agent_icon import (
+ generated_icon_url,
+ initials_icon_url,
+ is_third_party_avatar,
+)
from switch_core.bridges.collaboration.ingress import CallbackEndpoint
from switch_core.bridges.collaboration.install import InboundWebhook, WebhookRequest
from switch_core.bridges.collaboration.models import (
@@ -82,7 +86,8 @@ class AgentRendering:
field_label: str
body_label: str
- icon_url: str
+ # None when the platform should draw its own default icon for the sender.
+ icon_url: str | None
@dataclass(frozen=True)
@@ -573,10 +578,20 @@ class PlatformAdapter(ABC):
self._max_attachment_bytes = 20 * 1024 * 1024
# Set by `set_webhook_url` for an adapter that receives webhooks.
self.webhook_url: str | None = None
+ # Set by the lifecycle service from config.third_party_avatars_enabled.
+ # Off until then, so an adapter whose wiring was missed shows platform
+ # default icons, which someone notices, rather than quietly sending
+ # names to avatar services an operator has turned off.
+ self._third_party_avatars = False
def set_max_attachment_bytes(self, max_bytes: int) -> None:
self._max_attachment_bytes = max_bytes
+ def set_third_party_avatars(self, enabled: bool) -> None:
+ """Whether this adapter may hand platforms an icon drawn by an outside
+ avatar service (`agent_icon.is_third_party_avatar`)."""
+ self._third_party_avatars = enabled
+
@classmethod
def describe(cls, key: str) -> MessagingPlatform:
"""What this adapter declares about its platform, registered as `key`."""
@@ -1863,6 +1878,11 @@ class PlatformAdapter(ABC):
# than turning every agent into a person. The bridge core installs one
# before the adapter starts, so a running bridge without it is a wiring
# fault, and said so once.
+ #
+ # The face and the badge are both drawn by outside services that see
+ # the name. With third-party avatars off neither is built, and a stored
+ # icon on one of those services is withheld too, so the sender goes out
+ # with no icon and the platform draws its own default.
if self._resolve_agent_presentation is None:
if not self._reported_missing_resolver:
self._reported_missing_resolver = True
@@ -1872,25 +1892,40 @@ class PlatformAdapter(ABC):
type(self).__name__,
)
label = agent_name
- icon_url = generated_icon_url(agent_name)
+ icon_url = self._generated_icon(agent_name)
else:
found = await self._resolve_agent_presentation(agent_name)
label = (found.display_name if found else None) or agent_name
if found is None:
- icon_url = initials_icon_url(agent_name)
+ icon_url = (
+ initials_icon_url(agent_name) if self._third_party_avatars else None
+ )
+ elif found.icon_url is None:
+ icon_url = self._generated_icon(agent_name)
+ elif not self._third_party_avatars and is_third_party_avatar(
+ found.icon_url
+ ):
+ icon_url = None
else:
- icon_url = found.icon_url or generated_icon_url(agent_name)
+ icon_url = found.icon_url
return AgentRendering(
field_label=label,
body_label=self.escape_label_for_body(label),
- icon_url=self.adapt_icon_url(icon_url),
+ icon_url=None if icon_url is None else self.adapt_icon_url(icon_url),
)
- async def agent_icon_url(self, agent_name: str) -> str:
+ def _generated_icon(self, agent_name: str) -> str | None:
+ return generated_icon_url(agent_name) if self._third_party_avatars else None
+
+ async def agent_icon_url(self, agent_name: str) -> str | None:
"""The icon URL to render for an agent on this platform.
Adapters call this wherever they need a per-message avatar: the agent's
- own icon when it has one, otherwise this platform's existing default."""
+ own icon when it has one, otherwise this platform's existing default.
+ None when third-party avatars are off and the icon would have come from
+ an outside avatar service: the generated face or lettered badge, or a
+ stored icon on one of those services, whoever chose it. The platform
+ then draws its own default."""
return (await self.agent_rendering(agent_name)).icon_url
async def agent_label_for_body(self, agent_name: str) -> str:
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index 7a1be5969..b3b3ff5b3 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -1018,6 +1018,7 @@ class CollaborationBridgeLifecycleService:
)
)
adapter.set_max_attachment_bytes(self._config.agent_media_max_bytes)
+ adapter.set_third_party_avatars(self._config.third_party_avatars_enabled)
callback_endpoint = self._callback_ingress.endpoint_for(
bridge.type, bridge_id
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 816836cde..aa46cb4e7 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -2410,6 +2410,14 @@ class MattermostAdapter(PlatformAdapter):
driver = self._admin_driver
try:
url = await self.agent_icon_url(agent_name)
+ if url is None:
+ # Nothing is uploaded, so the bot keeps the image it has: the
+ # default for a new bot, or whatever an earlier start set.
+ logger.debug(
+ "[BOT-ICON] no icon to send for %s; leaving the bot's current image",
+ agent_name,
+ )
+ return
logger.debug("[BOT-ICON] fetching avatar for %s", agent_name)
# This is the one place Switch dereferences an agent's icon URL
# rather than handing it to a platform, so the fetch is bounded:
diff --git a/core/switch_core/bridges/collaboration/slack/avatar.py b/core/switch_core/bridges/collaboration/slack/avatar.py
index de5f063d8..564c00fcc 100644
--- a/core/switch_core/bridges/collaboration/slack/avatar.py
+++ b/core/switch_core/bridges/collaboration/slack/avatar.py
@@ -21,6 +21,8 @@ not fit is not sent, and Slack shows the app's own icon for that post.
import logging
from urllib.parse import parse_qsl, urlsplit, urlunsplit
+from switch_core.agent_icon import GENERATED_ICON_HOST
+
logger = logging.getLogger(__name__)
# Slack's resting dark surface, sampled from a real client. A hovered row
@@ -33,7 +35,6 @@ SLACK_SURFACE = "1a1d21"
#: against the live API, as Slack does not document it.
SLACK_ICON_URL_MAX = 255
-_DICEBEAR_HOST = "api.dicebear.com"
_BACKGROUND_PARAM = "backgroundColor"
@@ -49,7 +50,7 @@ def on_slack_background(icon_url: str) -> str:
`%2C`, which DiceBear refuses.
"""
parts = urlsplit(icon_url)
- if (parts.hostname or "").lower() != _DICEBEAR_HOST:
+ if parts.hostname != GENERATED_ICON_HOST:
return icon_url
query = parse_qsl(parts.query, keep_blank_values=True)
@@ -66,13 +67,14 @@ def on_slack_background(icon_url: str) -> str:
_reported_oversized: set[str] = set()
-def slack_icon_argument(icon_url: str, agent_name: str) -> str | None:
+def slack_icon_argument(icon_url: str | None, agent_name: str) -> str | None:
"""The `icon_url` to hand Slack for a post, or None to send none.
- None when Slack would refuse the URL: the post then goes out under the
- app's own icon rather than not at all. Reported once per URL.
+ None when there is no icon, or when Slack would refuse the URL: the post
+ then goes out under the app's own icon rather than not at all. An
+ oversized URL is reported once.
"""
- if len(icon_url) <= SLACK_ICON_URL_MAX:
+ if icon_url is None or len(icon_url) <= SLACK_ICON_URL_MAX:
return icon_url
if icon_url in _reported_oversized:
return None
diff --git a/core/switch_core/bridges/collaboration/teams/cards.py b/core/switch_core/bridges/collaboration/teams/cards.py
index 26ac5c097..eaada408f 100644
--- a/core/switch_core/bridges/collaboration/teams/cards.py
+++ b/core/switch_core/bridges/collaboration/teams/cards.py
@@ -367,6 +367,26 @@ def _schema_version(below: list[dict[str, Any]]) -> str:
return _BASE_VERSION
+def _avatar_column(agent: AgentRendering) -> list[dict[str, Any]]:
+ if agent.icon_url is None:
+ return []
+ return [
+ {
+ "type": "Column",
+ "width": "auto",
+ "items": [
+ {
+ "type": "Image",
+ "url": agent.icon_url,
+ "size": "Small",
+ "style": "Person",
+ "altText": agent.field_label,
+ }
+ ],
+ }
+ ]
+
+
def agent_message_card(
agent: AgentRendering,
body: str,
@@ -412,19 +432,7 @@ def agent_message_card(
{
"type": "ColumnSet",
"columns": [
- {
- "type": "Column",
- "width": "auto",
- "items": [
- {
- "type": "Image",
- "url": agent.icon_url,
- "size": "Small",
- "style": "Person",
- "altText": agent.field_label,
- }
- ],
- },
+ *_avatar_column(agent),
{
"type": "Column",
"width": "stretch",
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index b44f2c457..4ab4f8c9a 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -436,6 +436,18 @@ class SwitchConfig(BaseSettings):
# separately by email domain whether or not this is set.
telemetry_internal: bool = False
+ # Whether agents and people may be drawn by outside avatar services. An
+ # agent with no icon of its own wears a face from api.dicebear.com seeded
+ # with its name, and a person relayed from another platform a lettered
+ # badge from ui-avatars.com with their name in the URL. Slack, Discord and
+ # Teams clients load those URLs, so the services see the name and each
+ # reader's address; the Mattermost adapter loads them from this server.
+ # False sends no such URL anywhere, stored ones included: each platform
+ # shows its own default icon, new agents get no generated icon, setting an
+ # icon on one of those services is refused, and Switch Console stops
+ # drawing them for this server's agents.
+ third_party_avatars_enabled: bool = True
+
server_host: str = "0.0.0.0"
server_port: int = 8000
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 3e2c9e1fc..9446dea6a 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -12,6 +12,7 @@ from switch_core.agent_icon import (
InvalidIconUrl,
generated_icon_choices,
normalise_icon_url,
+ refuse_third_party_avatar,
)
from switch_core.authz import Principal, require_manage
from switch_core.bridges.agent.protocol.agent_core import AgentCore, AgentExistsError
@@ -26,6 +27,7 @@ from switch_core.bridges.agent.protocol.types import (
IntegrationProfile,
TaskProtocolConfig,
)
+from switch_core.config import SwitchConfig
from switch_core.db.models import User
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.room_store import RoomStore
@@ -33,6 +35,7 @@ from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.auth import get_current_user, get_tenant_is_admin
from switch_core.gateway.dependencies import (
get_agent_store,
+ get_config,
get_protocol,
get_room_store,
get_session,
@@ -42,7 +45,9 @@ from switch_core.gateway.known_agents import known_agent, known_agents
from switch_core.gateway.schemas import (
AgentDetail,
AgentSummary,
+ AvatarSettingsResponse,
BulkRegisterResult,
+ IconChoicesResponse,
KnownAgentType,
RegisterAgentResponse,
RegisterKnownAgentRequest,
@@ -152,15 +157,34 @@ async def list_known_agent_types() -> list[KnownAgentType]:
]
[email protected]("/avatar-settings")
+async def get_avatar_settings(
+ _user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> AvatarSettingsResponse:
+ """Whether a client may draw agents with icons from outside avatar
+ services. Switch Console builds the same generated icons the bridges do,
+ so it asks here rather than sending names the operator has kept in."""
+ return AvatarSettingsResponse(
+ third_party_avatars_enabled=config.third_party_avatars_enabled
+ )
+
+
@router.get("/icon-choices")
async def list_icon_choices(
_user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
name: Annotated[str, Query(min_length=1, max_length=128)],
page: Annotated[int, Query(ge=0, le=1000)] = 0,
-) -> dict[str, list[str]]:
+) -> IconChoicesResponse:
"""One page of generated icons for an agent called `name`: page 0 leads
- with the one an agent of that name gets when nobody picks an icon."""
- return {"choices": generated_icon_choices(name, page)}
+ with the one an agent of that name gets when nobody picks an icon. An
+ empty page, flagged as such, when third-party avatars are off."""
+ if not config.third_party_avatars_enabled:
+ return IconChoicesResponse(choices=[], third_party_avatars_enabled=False)
+ return IconChoicesResponse(
+ choices=generated_icon_choices(name, page), third_party_avatars_enabled=True
+ )
@router.post("/register")
@@ -392,6 +416,7 @@ async def update_agent_icon(
agent_store: Annotated[AgentStore, Depends(get_agent_store)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
) -> AgentSummary:
"""Set, change, or clear an agent's icon (CHOO-2171).
@@ -404,7 +429,9 @@ async def update_agent_icon(
a private network — Switch dereferences it when a bridge needs the image
as bytes, so an unconstrained URL would be a request made on the caller's
behalf from inside our network. A rejected URL returns 400 rather than
- being stored and failing later at render time.
+ being stored and failing later at render time. So is an icon on an avatar
+ service while the server has third-party avatars off, which no bridge
+ would show.
"""
agent = await agent_store.get(session, agent_id)
if agent is None:
@@ -422,7 +449,10 @@ async def update_agent_icon(
)
try:
- icon_url = normalise_icon_url(req.icon_url)
+ icon_url = refuse_third_party_avatar(
+ normalise_icon_url(req.icon_url),
+ third_party_avatars=config.third_party_avatars_enabled,
+ )
except InvalidIconUrl as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 77d6baa74..4d574f752 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -359,6 +359,23 @@ class UpdateAgentIconRequest(BaseModel):
icon_url: str | None
+class AvatarSettingsResponse(BaseModel):
+ """Whether this server lets icons drawn by outside avatar services through
+ (`THIRD_PARTY_AVATARS_ENABLED`). A client that draws agents itself follows
+ it, so turning it off covers the client as well as the bridges."""
+
+ third_party_avatars_enabled: bool
+
+
+class IconChoicesResponse(BaseModel):
+ """One page of generated icons to choose from. `choices` is empty when
+ `third_party_avatars_enabled` is false: the server generates none, rather
+ than having none to offer."""
+
+ choices: list[str]
+ third_party_avatars_enabled: bool
+
+
class UpdateAgentDescriptionRequest(BaseModel):
"""Change what an agent is for. A description is required, so a blank one
is refused rather than stored."""
diff --git a/core/switch_core/management/schemas.py b/core/switch_core/management/schemas.py
index f05a80ae5..d089a8adb 100644
--- a/core/switch_core/management/schemas.py
+++ b/core/switch_core/management/schemas.py
@@ -396,7 +396,8 @@ class CreateManagedAgentRequest(_GatewayBody):
name: str
description: str
display_name: str | None = None
- # Null for the icon its name generates (`agent_icon.generated_icon_url`).
+ # Null for the icon its name generates (`agent_icon.generated_icon_url`),
+ # or for no icon when the server has third-party avatars off.
icon_url: str | None = None
controller_id: str | None
desired_state: DesiredState
diff --git a/core/switch_core/management/service.py b/core/switch_core/management/service.py
index 000ba9df8..2a8a2afcd 100644
--- a/core/switch_core/management/service.py
+++ b/core/switch_core/management/service.py
@@ -31,6 +31,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.agent_icon import (
InvalidIconUrl,
+ drop_third_party_avatar,
generated_icon_url,
normalise_icon_url,
)
@@ -115,6 +116,9 @@ class ManagementSettings:
# against (`GATEWAY_PUBLIC_URL`). None when the deployment has not said,
# and then nothing can tell an owner what `--server` to enroll with.
server_url: str | None
+ # `THIRD_PARTY_AVATARS_ENABLED`. Off, a new agent with no chosen icon
+ # stores none rather than the generated one, which carries its name.
+ third_party_avatars: bool
@dataclass(frozen=True)
@@ -1097,9 +1101,12 @@ class ManagementService:
)
definition = with_directory(request.definition, controller, request.name)
try:
- icon_url = normalise_icon_url(request.icon_url) or generated_icon_url(
- request.name
+ icon_url = drop_third_party_avatar(
+ normalise_icon_url(request.icon_url),
+ third_party_avatars=self.settings.third_party_avatars,
)
+ if icon_url is None and self.settings.third_party_avatars:
+ icon_url = generated_icon_url(request.name)
except InvalidIconUrl as exc:
raise ManagementError(422, reason_codes.VALIDATION_ERROR, str(exc)) from exc
spec, options, metadata = _known_agent_registration(definition, None)
diff --git a/core/switch_core/management/wiring.py b/core/switch_core/management/wiring.py
index 47243e733..6d3f06fbd 100644
--- a/core/switch_core/management/wiring.py
+++ b/core/switch_core/management/wiring.py
@@ -128,6 +128,7 @@ def build_management(
token_secret: str,
status_interval_seconds: int,
server_url: str | None,
+ third_party_avatars: bool,
session_factory: async_sessionmaker[AsyncSession],
presence: ControllerPresence,
auth_cache: ControllerAuthCache,
@@ -149,6 +150,7 @@ def build_management(
token_secret=token_secret,
status_interval_seconds=status_interval_seconds,
server_url=server_url,
+ third_party_avatars=third_party_avatars,
),
notifier=ControllerNotifier(),
controllers=controllers,
@@ -201,6 +203,7 @@ def create_management(
token_secret=config.controller_token_secret,
status_interval_seconds=config.controller_status_interval_seconds,
server_url=config.gateway_public_url,
+ third_party_avatars=config.third_party_avatars_enabled,
session_factory=session_factory,
presence=presence,
# The agent API-key cache's bound: the longest a controller revoked
diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
index cda470435..8d3bbfb76 100644
--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -76,7 +76,8 @@ def make_service(
svc.client_lifecycle = FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = NoBridges() # type: ignore[attr-defined]
svc.config = SimpleNamespace(
- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),
+ third_party_avatars_enabled=True,
) # type: ignore[attr-defined]
return svc
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
index e90429ff3..d05c11f32 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py
@@ -4,7 +4,7 @@ import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.addressing import owner_and_owner_agents_policy, owner_only_policy
-from switch_core.agent_icon import InvalidIconUrl
+from switch_core.agent_icon import InvalidIconUrl, generated_icon_url
from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.agent.protocol.agent_detail import AgentProfileUpdate
@@ -181,12 +181,14 @@ def _profile(
display_name: str | None = None,
icon_url: str | None = None,
addressing: str | None = None,
+ third_party_avatars: bool = True,
) -> AgentProfileUpdate:
return AgentProfileUpdate.parse(
description=description,
display_name=display_name,
icon_url=icon_url,
addressing=addressing,
+ third_party_avatars=third_party_avatars,
)
@@ -276,6 +278,18 @@ class TestUpdateAgentDetail:
with pytest.raises(ValueError, match="description must not be blank"):
_profile(description=" ")
+ def test_an_avatar_service_icon_is_refused_only_when_the_server_turns_them_off(
+ self,
+ ) -> None:
+ dicebear = generated_icon_url("target")
+ with pytest.raises(InvalidIconUrl, match="third-party avatars turned off"):
+ _profile(icon_url=dicebear, third_party_avatars=False)
+ assert _profile(icon_url=dicebear).columns == {"icon_url": dicebear}
+ other = "https://example.com/r.png"
+ assert _profile(icon_url=other, third_party_avatars=False).columns == {
+ "icon_url": other
+ }
+
async def test_non_owner_is_rejected(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
index 5a1b010b3..f36e8b556 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py
@@ -93,7 +93,8 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:
svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
svc.config = SimpleNamespace(
- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),
+ third_party_avatars_enabled=True,
) # type: ignore[attr-defined]
return svc
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
index dcdb027cd..6be41a782 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_register_overwrite_owner_guard.py
@@ -71,7 +71,8 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:
svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
svc.config = SimpleNamespace(
- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),
+ third_party_avatars_enabled=True,
) # type: ignore[attr-defined]
# Duck-typed: the attribute exists on AgentCore after the api-key
# cache landed on main; a no-op stand-in keeps this test valid on both
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
index 36e357153..dc85fa1a6 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py
@@ -71,7 +71,8 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:
svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
svc.config = SimpleNamespace(
- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),
+ third_party_avatars_enabled=True,
) # type: ignore[attr-defined]
return svc
diff --git a/core/tests/switch_core/bridges/agent/test_api_key_cache.py b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
index eef489c71..8b950dc86 100644
--- a/core/tests/switch_core/bridges/agent/test_api_key_cache.py
+++ b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
@@ -427,7 +427,8 @@ def _agent_core(
svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
svc.event_buffer = SimpleNamespace(remove=lambda _agent_id: None) # type: ignore[attr-defined]
svc.config = SimpleNamespace(
- keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None)
+ keyring=Keyring.parse("test:" + "x" * 40, legacy_secret=None),
+ third_party_avatars_enabled=True,
) # type: ignore[attr-defined]
return svc
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
index a73758ced..15747e84b 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
@@ -111,7 +111,12 @@ def _bridge(*agents: SimpleNamespace) -> CollaborationCore:
class _BareAdapter(PlatformAdapter):
"""Concrete only so it can be instantiated: the label plumbing under test
- lives on the base class and no platform method is called."""
+ lives on the base class and no platform method is called. Third-party
+ avatars are on, as the lifecycle sets them under the default config."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.set_third_party_avatars(True)
display_name: ClassVar[str] = "Stub"
@@ -324,6 +329,7 @@ def _slack_adapter(
bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"
)
)
+ adapter.set_third_party_avatars(True)
client = _FakeSlackClient()
adapter._web_client = client # type: ignore[assignment]
adapter._bot_user_id = "U1"
@@ -1072,6 +1078,7 @@ def _teams_adapter(
client_state="s3cr3t",
)
)
+ adapter.set_third_party_avatars(True)
connector = _FakeTeamsConnector()
adapter._connector = connector # type: ignore[assignment]
adapter._default_service_url = "https://smba.example/amer/"
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
index a0affbe15..1f7971667 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
@@ -8,6 +8,7 @@ between that answer and the icon the agent's name generates.
from __future__ import annotations
+import asyncio
import logging
from types import SimpleNamespace
from typing import Any, ClassVar
@@ -20,6 +21,10 @@ from switch_core.bridges.collaboration.adapter import (
PlatformAdapter,
)
from switch_core.bridges.collaboration.collaboration_core import CollaborationCore
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
_CUSTOM = "https://cdn.example.com/9.x/bottts/png?seed=chosen"
@@ -98,18 +103,25 @@ class TestCollaborationCoreResolver:
assert await bridge._agent_presentation("some-slack-bot") is None
+def _with_third_party_avatars() -> _Adapter:
+ """An adapter as the lifecycle starts it under the default config."""
+ adapter = _Adapter()
+ adapter.set_third_party_avatars(True)
+ return adapter
+
+
class TestAdapterIconSelection:
async def test_draws_an_agent_face_when_no_resolver_is_installed(self) -> None:
# Nothing can say who is who, and the senders an adapter draws are
# overwhelmingly agents: drawing them all as people would be the worse
# mistake.
- adapter = _Adapter()
+ adapter = _with_third_party_avatars()
assert await adapter.agent_icon_url("worker") == generated_icon_url("worker")
async def test_says_once_that_no_resolver_is_installed(
self, caplog: pytest.LogCaptureFixture
) -> None:
- adapter = _Adapter()
+ adapter = _with_third_party_avatars()
with caplog.at_level(logging.WARNING):
await adapter.agent_icon_url("worker")
await adapter.agent_icon_url("manager")
@@ -119,7 +131,7 @@ class TestAdapterIconSelection:
assert len(reports) == 1
async def test_prefers_the_agents_own_icon(self) -> None:
- adapter = _Adapter()
+ adapter = _with_third_party_avatars()
async def resolver(name: str) -> AgentPresentation | None:
return AgentPresentation(display_name=None, icon_url=_CUSTOM)
@@ -128,7 +140,7 @@ class TestAdapterIconSelection:
assert await adapter.agent_icon_url("worker") == _CUSTOM
async def test_falls_back_to_the_default_when_the_agent_has_none(self) -> None:
- adapter = _Adapter()
+ adapter = _with_third_party_avatars()
async def resolver(name: str) -> AgentPresentation | None:
return AgentPresentation(display_name=None, icon_url=None)
@@ -140,9 +152,106 @@ class TestAdapterIconSelection:
"""The two halves wired together, which is the thing that actually has
to work and which neither test above proves on its own."""
bridge = _bridge({"worker": _agent(_CUSTOM), "plain": _agent(None)})
- adapter = _Adapter()
+ adapter = _with_third_party_avatars()
adapter.set_agent_presentation_resolver(bridge._agent_presentation)
assert await adapter.agent_icon_url("worker") == _CUSTOM
assert await adapter.agent_icon_url("plain") == generated_icon_url("plain")
assert await adapter.agent_icon_url("alice") == initials_icon_url("alice")
+
+
+class TestThirdPartyAvatarsOff:
+ """With `THIRD_PARTY_AVATARS_ENABLED=false` no sender's name goes into a
+ URL that a platform, or Switch itself, fetches from an avatar service."""
+
+ @pytest.mark.parametrize(
+ "presentation",
+ [
+ AgentPresentation(display_name=None, icon_url=None),
+ AgentPresentation(display_name=None, icon_url=generated_icon_url("worker")),
+ AgentPresentation(display_name=None, icon_url=initials_icon_url("worker")),
+ AgentPresentation(
+ display_name=None,
+ icon_url="https://api.dicebear.com./10.x/gaze/png?seed=worker",
+ ),
+ AgentPresentation(
+ display_name=None,
+ icon_url="https://avatars.dicebear.com/api/bottts/worker.png",
+ ),
+ None,
+ ],
+ ids=[
+ "agent-without-icon",
+ "stored-generated",
+ "stored-initials",
+ "stored-trailing-dot-host",
+ "stored-other-subdomain",
+ "person",
+ ],
+ )
+ async def test_sends_no_icon_rather_than_a_generated_one(
+ self, presentation: AgentPresentation | None
+ ) -> None:
+ adapter = _Adapter()
+ adapter.set_third_party_avatars(False)
+
+ async def resolver(name: str) -> AgentPresentation | None:
+ return presentation
+
+ adapter.set_agent_presentation_resolver(resolver)
+ assert await adapter.agent_icon_url("worker") is None
+
+ async def test_an_adapter_nobody_configured_sends_none(self) -> None:
+ """The lifecycle turns them on from config. An adapter it never told
+ withholds them, so missed wiring shows platform defaults rather than
+ sending names an operator kept in."""
+ adapter = _Adapter()
+
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=None)
+
+ adapter.set_agent_presentation_resolver(resolver)
+ assert await adapter.agent_icon_url("worker") is None
+
+ async def test_sends_no_icon_without_a_resolver(self) -> None:
+ adapter = _Adapter()
+ adapter.set_third_party_avatars(False)
+ assert await adapter.agent_icon_url("worker") is None
+
+ async def test_an_agents_own_icon_still_goes_out(self) -> None:
+ adapter = _Adapter()
+ adapter.set_third_party_avatars(False)
+
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=_CUSTOM)
+
+ adapter.set_agent_presentation_resolver(resolver)
+ assert await adapter.agent_icon_url("worker") == _CUSTOM
+
+ async def test_mattermost_fetches_nothing_for_an_agent_without_an_icon(
+ self,
+ ) -> None:
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mattermost.invalid",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ adapter.set_third_party_avatars(False)
+ adapter._admin_driver = object() # type: ignore[assignment]
+ adapter._main_loop = asyncio.get_running_loop()
+ fetched: list[str] = []
+
+ async def fetch_icon(url: str) -> bytes | None:
+ fetched.append(url)
+ return None
+
+ async def resolver(name: str) -> AgentPresentation | None:
+ return AgentPresentation(display_name=None, icon_url=None)
+
+ adapter._fetch_icon = fetch_icon # type: ignore[method-assign]
+ adapter.set_agent_presentation_resolver(resolver)
+ await adapter._set_bot_icon("bot-1", "worker")
+ assert fetched == []
diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
index 0a2a8b70f..f5a3eda84 100644
--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
import discord
import pytest
+from discord.http import handle_message_parameters
from switch_core.bridges.agent.commands import COMMANDS
from switch_core.bridges.collaboration.discord import adapter as adapter_module
@@ -28,6 +29,7 @@ def _adapter() -> DiscordAdapter:
config=DiscordConnectionConfig(bot_token="token", guild_id=str(GUILD_ID))
)
adapter._connection._bot_user_id = BOT_USER_ID
+ adapter.set_third_party_avatars(True)
return adapter
@@ -623,6 +625,23 @@ def test_send_message_posts_via_webhook_with_agent_identity() -> None:
assert ref == f"{CHANNEL_ID}:901"
+def test_with_third_party_avatars_off_discord_draws_its_default_avatar() -> None:
+ """No avatar goes to the webhook, and discord.py leaves a None one out of
+ the request, so Discord shows its own default rather than a broken image."""
+ adapter = _adapter()
+ adapter.set_third_party_avatars(False)
+ channel = _FakeChannel()
+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})
+ webhook = _FakeWebhook()
+ adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook
+
+ _run(adapter.send_message(str(CHANNEL_ID), "my-agent", "hello"))
+
+ assert webhook.sent[0]["avatar_url"] is None
+ request = handle_message_parameters(content="hello", avatar_url=None)
+ assert "avatar_url" not in request.payload
+
+
def test_an_agent_message_cannot_page_the_channel() -> None:
# Discord decides who a message pings from the request, not the markup, so
# the webhook path pins the same guard every other send path does.
diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_third_party_avatars.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_third_party_avatars.py
new file mode 100644
index 000000000..6e678e1c1
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_third_party_avatars.py
@@ -0,0 +1,67 @@
+"""Handing a started bridge the operator's `THIRD_PARTY_AVATARS_ENABLED`.
+
+The adapter withholds third-party avatars until it is told otherwise, and the
+lifecycle service is the one thing that tells it. Dropping that call would make
+every deployment lose its generated icons; passing the wrong value would send
+names an operator turned off. Either way, it has to be the config's value that
+arrives.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.agent_icon import generated_icon_url
+from switch_core.bridges.collaboration.adapter import PlatformAdapter
+
+from .test_lifecycle_tenant_binding import (
+ _make_bridge,
+ _make_tenant,
+ _service,
+ _StubAdapter,
+ _StubConfig,
+)
+
+
+ ("enabled", "expected"),
+ [(True, generated_icon_url("worker")), (False, None)],
+ ids=["on", "off"],
+)
+async def test_a_started_bridge_follows_the_setting(
+ session_factory: async_sessionmaker[AsyncSession],
+ enabled: bool,
+ expected: str | None,
+) -> None:
+ tenant = f"tenant-{uuid.uuid4().hex[:8]}"
+ async with session_factory() as session:
+ await _make_tenant(session, tenant)
+ bridge_id, _ = await _make_bridge(session, tenant_id=tenant)
+ await session.commit()
+
+ service = _service(session_factory)
+ service._config.third_party_avatars_enabled = enabled
+ built: list[_StubAdapter] = []
+
+ class _Recording(_StubAdapter):
+ def __init__(self, *, config: Any) -> None:
+ PlatformAdapter.__init__(self)
+ super().__init__(config=config)
+ built.append(self)
+
+ service.register_adapter("mattermost", _Recording, _StubConfig)
+
+ async def _run(bridge_id: str, tenant_id: str, *_: object) -> None:
+ return None
+
+ service._run_bridge = _run # type: ignore[method-assign]
+
+ try:
+ await service.start(bridge_id)
+ assert await built[0].agent_icon_url("worker") == expected
+ finally:
+ await service.stop_all()
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
index 28e32a67f..f6b52d2e8 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
@@ -104,6 +104,7 @@ def test_the_slack_adapter_applies_it_to_a_resolved_icon() -> None:
workspace_id="T123",
)
)
+ adapter.set_third_party_avatars(True)
async def resolver(name: str) -> AgentPresentation | None:
return AgentPresentation(display_name=None, icon_url=DICEBEAR)
@@ -120,6 +121,10 @@ def test_hands_slack_an_icon_url_up_to_its_limit() -> None:
assert slack_icon_argument(at_limit, "worker") == at_limit
+def test_sends_no_icon_url_when_there_is_no_icon() -> None:
+ assert slack_icon_argument(None, "worker") is None
+
+
def test_sends_no_icon_url_past_slacks_limit() -> None:
# Slack refuses the post itself over this, so the message would be lost.
over = "https://example.com/" + "a" * (SLACK_ICON_URL_MAX - 19)
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
index 66f79b1c7..461be7f06 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -32,7 +32,9 @@ def _config() -> TeamsConnectionConfig:
def _adapter() -> TeamsAdapter:
- return TeamsAdapter(config=_config())
+ adapter = TeamsAdapter(config=_config())
+ adapter.set_third_party_avatars(True)
+ return adapter
def _run(coro: Any) -> Any:
diff --git a/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
index c17a05ba1..4c0ba88d5 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_outbound_rendering.py
@@ -156,6 +156,16 @@ def test_a_card_with_no_mentions_carries_no_msteams_block() -> None:
assert "msteams" not in agent_message_card(_RENDERING, "hello", [], [])
+def test_a_sender_with_no_icon_gets_no_image_element() -> None:
+ """An Image with no url is an invalid card, and Teams drops the whole post."""
+ rendering = AgentRendering(field_label="james", body_label="james", icon_url=None)
+ card = agent_message_card(rendering, "hello", [], [])
+ header = card["body"][0]
+ assert [item["type"] for col in header["columns"] for item in col["items"]] == [
+ "TextBlock"
+ ]
+
+
# ── the app's own handle ─────────────────────────────────────────────────────
diff --git a/core/tests/switch_core/gateway/test_agent_icon_choices.py b/core/tests/switch_core/gateway/test_agent_icon_choices.py
index e691db970..54f6d3883 100644
--- a/core/tests/switch_core/gateway/test_agent_icon_choices.py
+++ b/core/tests/switch_core/gateway/test_agent_icon_choices.py
@@ -1,13 +1,44 @@
from types import SimpleNamespace
from typing import Any, cast
+import pytest
+
from switch_core.agent_icon import generated_icon_choices
-from switch_core.gateway.agents import list_icon_choices
+from switch_core.gateway.agents import get_avatar_settings, list_icon_choices
+from switch_core.gateway.schemas import AvatarSettingsResponse, IconChoicesResponse
+
+_USER = cast(Any, SimpleNamespace(id="user-1"))
+
+
+def _config(third_party_avatars_enabled: bool) -> Any:
+ return SimpleNamespace(third_party_avatars_enabled=third_party_avatars_enabled)
async def test_offers_the_server_generated_icons_page_by_page() -> None:
- user = cast(Any, SimpleNamespace(id="user-1"))
- first = await list_icon_choices(_user=user, name="pm-agent", page=0)
- later = await list_icon_choices(_user=user, name="pm-agent", page=2)
- assert first == {"choices": generated_icon_choices("pm-agent", 0)}
- assert later == {"choices": generated_icon_choices("pm-agent", 2)}
+ first = await list_icon_choices(
+ _user=_USER, config=_config(True), name="pm-agent", page=0
+ )
+ later = await list_icon_choices(
+ _user=_USER, config=_config(True), name="pm-agent", page=2
+ )
+ assert first == IconChoicesResponse(
+ choices=generated_icon_choices("pm-agent", 0), third_party_avatars_enabled=True
+ )
+ assert later == IconChoicesResponse(
+ choices=generated_icon_choices("pm-agent", 2), third_party_avatars_enabled=True
+ )
+
+
+async def test_offers_none_when_third_party_avatars_are_off_and_says_why() -> None:
+ """An empty page alone reads as "nothing to offer". The flag says the
+ server generates none, so a picker can explain itself."""
+ off = await list_icon_choices(
+ _user=_USER, config=_config(False), name="pm-agent", page=0
+ )
+ assert off == IconChoicesResponse(choices=[], third_party_avatars_enabled=False)
+
+
[email protected]("enabled", [True, False])
+async def test_avatar_settings_report_the_servers_setting(enabled: bool) -> None:
+ settings = await get_avatar_settings(_user=_USER, config=_config(enabled))
+ assert settings == AvatarSettingsResponse(third_party_avatars_enabled=enabled)
diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.py
index d52d1f9d9..9671a1654 100644
--- a/core/tests/switch_core/gateway/test_agent_icon_route.py
+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py
@@ -8,6 +8,9 @@ expressible and lands as NULL.
from __future__ import annotations
+from types import SimpleNamespace
+from typing import Any
+
import pytest
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@@ -27,6 +30,9 @@ _AGENT_STORE = AgentStore()
_ICON = "https://cdn.example.com/9.x/bottts/png?seed=switch-worker"
_OTHER_ICON = "https://cdn.example.com/9.x/shapes/png?seed=switch-worker"
+_AVATARS_ON: Any = SimpleNamespace(third_party_avatars_enabled=True)
+_AVATARS_OFF: Any = SimpleNamespace(third_party_avatars_enabled=False)
+
class TestUpdateAgentIcon:
async def test_owner_can_set_an_icon(
@@ -43,6 +49,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert summary.icon_url == _ICON
@@ -69,6 +76,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert summary.icon_url == generated_icon_url("a1")
@@ -92,6 +100,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert summary.icon_url == _OTHER_ICON
@@ -114,6 +123,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert summary.icon_url is None
@@ -137,6 +147,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert summary.icon_url is None
@@ -157,6 +168,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
other,
await is_admin(session, other),
+ _AVATARS_ON,
)
assert exc.value.status_code == 403
@@ -179,6 +191,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
admin,
await is_admin(session, admin),
+ _AVATARS_ON,
)
assert summary.icon_url == _ICON
@@ -197,6 +210,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert exc.value.status_code == 404
@@ -231,6 +245,7 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
assert exc.value.status_code == 400
@@ -255,8 +270,57 @@ class TestUpdateAgentIcon:
_AGENT_STORE,
owner,
await is_admin(session, owner),
+ _AVATARS_ON,
)
stored = await _AGENT_STORE.get(session, agent.id)
assert stored is not None
assert stored.icon_url == _ICON
+
+
+class TestWithThirdPartyAvatarsOff:
+ """No bridge shows an icon on an avatar service on such a server, so
+ setting one is refused where the owner can see why, not stored to vanish."""
+
+ async def test_an_avatar_service_icon_is_refused_and_nothing_is_stored(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
+
+ with pytest.raises(HTTPException) as refused:
+ await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=generated_icon_url("a1")),
+ session,
+ _AGENT_STORE,
+ owner,
+ await is_admin(session, owner),
+ _AVATARS_OFF,
+ )
+
+ assert refused.value.status_code == 400
+ assert "third-party avatars turned off" in str(refused.value.detail)
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url is None
+
+ async def test_an_icon_on_any_other_host_is_still_set(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await add_user(session, name="owner")
+ agent = await add_agent(session, name="a1", owner_id=owner.id)
+
+ summary = await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=_ICON),
+ session,
+ _AGENT_STORE,
+ owner,
+ await is_admin(session, owner),
+ _AVATARS_OFF,
+ )
+
+ assert summary.icon_url == _ICON
diff --git a/core/tests/switch_core/gateway/test_cloud_controller_machines.py b/core/tests/switch_core/gateway/test_cloud_controller_machines.py
index dd2d584e1..8648826d2 100644
--- a/core/tests/switch_core/gateway/test_cloud_controller_machines.py
+++ b/core/tests/switch_core/gateway/test_cloud_controller_machines.py
@@ -104,6 +104,7 @@ def _hosted_app(
hosted_disk_retention_days=7,
hosted_launch_capacity=1,
hosted_agents_enabled=True,
+ third_party_avatars_enabled=True,
)
async def session():
diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.py
index 1413f3816..a97c06df0 100644
--- a/core/tests/switch_core/management/harness.py
+++ b/core/tests/switch_core/management/harness.py
@@ -140,7 +140,9 @@ def protocol_service(
svc.api_key_cache = cache
svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[assignment]
svc.collab_lifecycle = _NoBridges() # type: ignore[assignment]
- svc.config = SimpleNamespace(keyring=TEST_KEYRING) # type: ignore[assignment]
+ svc.config = SimpleNamespace( # type: ignore[assignment]
+ keyring=TEST_KEYRING, third_party_avatars_enabled=True
+ )
svc.telemetry = None
svc.event_buffer = EventBuffer(sequence_base=0)
svc.connections = AgentConnectionRegistry()
@@ -190,6 +192,7 @@ def build_harness(
*,
controller_auth_ttl_seconds: float = 5,
server_url: str | None = SERVER_URL,
+ third_party_avatars: bool = True,
) -> Harness:
"""The controller-token cache is on, as it is by default in production,
so every management test runs through it."""
@@ -203,6 +206,7 @@ def build_harness(
token_secret=TOKEN_SECRET,
status_interval_seconds=STATUS_INTERVAL,
server_url=server_url,
+ third_party_avatars=third_party_avatars,
session_factory=session_factory,
presence=protocol.connections.controllers,
auth_cache=controller_auth_cache,
@@ -241,7 +245,9 @@ def build_harness(
gateway_app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()
gateway_app.dependency_overrides[gw_deps.get_protocol] = lambda: protocol
gateway_app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(
- keyring=TEST_KEYRING, gateway_tenant_choice_enabled=False
+ keyring=TEST_KEYRING,
+ gateway_tenant_choice_enabled=False,
+ third_party_avatars_enabled=third_party_avatars,
)
agent_app.mount("/gateway", gateway_app)
agent_app.add_middleware(
diff --git a/core/tests/switch_core/management/test_gateway_routes.py b/core/tests/switch_core/management/test_gateway_routes.py
index 869540990..6daa787ab 100644
--- a/core/tests/switch_core/management/test_gateway_routes.py
+++ b/core/tests/switch_core/management/test_gateway_routes.py
@@ -348,6 +348,45 @@ class TestManagedAgents:
assert painter.icon_url == "https://example.com/painter.png"
assert prober is None
+ async def test_create_stores_no_generated_icon_when_third_party_avatars_are_off(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ harness = build_harness(session_factory, third_party_avatars=False)
+ owner = await add_member(harness.session_factory, "ada")
+ async with harness.client() as client:
+ created = await create_managed_agent(
+ client, owner, name="scout", controller_id=None
+ )
+ assert created.status_code == 201, created.text
+ async with harness.session_factory() as session:
+ scout = await AgentStore().get(session, created.json()["agent_id"])
+ assert scout is not None and scout.icon_url is None
+
+ async def test_create_drops_a_sent_avatar_service_icon_when_third_party_avatars_are_off(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Older Console builds send a DiceBear face when nobody picked one.
+ Refused, they could create no agent at all; the agent gets none."""
+ harness = build_harness(session_factory, third_party_avatars=False)
+ owner = await add_member(harness.session_factory, "ada")
+ async with harness.client() as client:
+ created = await client.post(
+ "/gateway/management/agents",
+ json={
+ "name": "painter",
+ "description": "Paints",
+ "icon_url": generated_icon_url("painter"),
+ "controller_id": None,
+ "desired_state": "stopped",
+ "definition": definition(),
+ },
+ cookies=cookies_for(owner),
+ )
+ assert created.status_code == 201, created.text
+ async with harness.session_factory() as session:
+ painter = await AgentStore().get(session, created.json()["agent_id"])
+ assert painter is not None and painter.icon_url is None
+
async def test_a_name_clash_is_refused(self, harness: Harness) -> None:
owner = await add_member(harness.session_factory, "ada")
async with harness.client() as client:
diff --git a/core/tests/switch_core/test_agent_icon.py b/core/tests/switch_core/test_agent_icon.py
index 14c2d8154..e7938d63c 100644
--- a/core/tests/switch_core/test_agent_icon.py
+++ b/core/tests/switch_core/test_agent_icon.py
@@ -11,10 +11,13 @@ from switch_core.agent_icon import (
GENERATED_ICON_CHOICES,
MAX_ICON_URL_LENGTH,
InvalidIconUrl,
+ drop_third_party_avatar,
generated_icon_choices,
generated_icon_url,
initials_icon_url,
+ is_third_party_avatar,
normalise_icon_url,
+ refuse_third_party_avatar,
upgrade_legacy_icon_url,
validate_icon_url,
)
@@ -246,3 +249,93 @@ def test_generated_choices_lead_with_the_name_and_stay_put() -> None:
second = generated_icon_choices("pm-agent", 1)
assert len(second) == GENERATED_ICON_CHOICES
assert not set(first) & set(second)
+
+
+def test_both_builders_are_recognised_as_third_party() -> None:
+ # The check and the builders share their hosts, so moving a builder to
+ # another host cannot leave the check behind.
+ assert is_third_party_avatar(generated_icon_url("pm-agent"))
+ assert is_third_party_avatar(initials_icon_url("Jane Q. Doe"))
+
+
+ "url",
+ [
+ "https://api.dicebear.com/9.x/bottts/png?seed=x&size=256",
+ "https://API.DiceBear.com/10.x/gaze/png?seed=x",
+ # A trailing dot names the same host.
+ "https://api.dicebear.com./10.x/gaze/png?seed=x",
+ "https://ui-avatars.com./api/?name=x",
+ # Any host under either service, not only the one a builder uses.
+ "https://avatars.dicebear.com/api/bottts/x.png",
+ "https://dicebear.com/x.png",
+ "https://www.ui-avatars.com/api/?name=x",
+ "https://api.dicebear.com:443/10.x/gaze/png?seed=x",
+ ],
+)
+def test_recognises_every_spelling_of_the_avatar_services(url: str) -> None:
+ assert is_third_party_avatar(url)
+
+
+ "url",
+ [
+ "https://cdn.example.com/9.x/bottts/png?seed=x&size=256",
+ # Lookalikes are someone else's host.
+ "https://api.dicebear.com.example/10.x/gaze/png?seed=x",
+ "https://notdicebear.com/x.png",
+ "https://ui-avatars.com.evil.test/api/?name=x",
+ "https://example.com/?u=https://api.dicebear.com/x",
+ "not a url",
+ "https://[::1/x.png",
+ ],
+)
+def test_leaves_every_other_host_alone(url: str) -> None:
+ assert not is_third_party_avatar(url)
+
+
+# Hosts that browsers and chat clients read differently from `urlsplit`: a
+# backslash ends the host for them, `%2e` decodes to a dot, and `。` maps to one.
+_AMBIGUOUS_HOSTS = [
+ "https://api.dicebear.com\\x.png",
+ "https://api.dicebear.com%2e/x.png",
+ "https://api。dicebear。com/x.png",
+]
+
+
[email protected]("url", _AMBIGUOUS_HOSTS)
+def test_a_host_clients_read_differently_is_refused(url: str) -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(url)
+
+
+def test_percent_encoding_outside_the_host_is_still_accepted() -> None:
+ url = "https://cdn.example.com/icons/a%20b.png?label=x%2Cy"
+ assert validate_icon_url(url) == url
+
+
[email protected]("url", _AMBIGUOUS_HOSTS)
+def test_a_stored_host_clients_read_differently_counts_as_an_avatar_service(
+ url: str,
+) -> None:
+ # Stored before `validate_icon_url` refused them; which service the
+ # client loads cannot be told from here, so it is withheld.
+ assert is_third_party_avatar(url)
+
+
+def test_setting_an_avatar_service_icon_is_refused_only_with_them_off() -> None:
+ dicebear = generated_icon_url("pm-agent")
+ with pytest.raises(InvalidIconUrl, match="third-party avatars turned off"):
+ refuse_third_party_avatar(dicebear, third_party_avatars=False)
+ assert refuse_third_party_avatar(dicebear, third_party_avatars=True) == dicebear
+ other = "https://cdn.example.com/a.png"
+ assert refuse_third_party_avatar(other, third_party_avatars=False) == other
+ assert refuse_third_party_avatar(None, third_party_avatars=False) is None
+
+
+def test_creating_with_an_avatar_service_icon_drops_it_only_with_them_off() -> None:
+ dicebear = generated_icon_url("pm-agent")
+ assert drop_third_party_avatar(dicebear, third_party_avatars=False) is None
+ assert drop_third_party_avatar(dicebear, third_party_avatars=True) == dicebear
+ other = "https://cdn.example.com/a.png"
+ assert drop_third_party_avatar(other, third_party_avatars=False) == other
diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.yml
index aa6dd41de..3ce62c9ae 100644
--- a/deploy/local/standalone-docker-compose.yml
+++ b/deploy/local/standalone-docker-compose.yml
@@ -298,6 +298,12 @@ services:
# writes its own answer here for a server it runs.
TELEMETRY_INTERNAL:
TELEMETRY_SNAPSHOT_INTERVAL_HOURS:
+ # Whether agents and people are drawn by outside avatar services, which
+ # see their names (api.dicebear.com, ui-avatars.com). Unset is true;
+ # false leaves each platform's default icon. A server Switch Console runs
+ # for you always uses the default: Console writes its `.env` afresh on
+ # every start and does not set this.
+ THIRD_PARTY_AVATARS_ENABLED:
depends_on:
postgres:
condition: service_healthy
diff --git a/deploy/remote/helm/switch/README.md b/deploy/remote/helm/switch/README.md
index be0dae3d0..b8288b67d 100644
--- a/deploy/remote/helm/switch/README.md
+++ b/deploy/remote/helm/switch/README.md
@@ -185,6 +185,27 @@ required keys are listed above the `secrets:` block in `values.yaml`.
Bridge credentials are **not** among them. Those are entered in the gateway and
stored in the database.
+## Avatars from outside services
+
+An agent with no icon of its own is drawn by api.dicebear.com with its name as
+the seed, and a person relayed from another platform by ui-avatars.com with their
+name in the URL. Slack, Discord and Teams clients load those images, so the
+services see the name and each reader's address; the Mattermost bridge loads them
+from switch-core. To send no such URL:
+
+```yaml
+switchCore:
+ thirdPartyAvatars:
+ enabled: false
+```
+
+Each platform then shows its own default icon (Slack the app's icon, Discord its
+default avatar, Teams no image), icons already stored on those services are
+withheld too, and new agents get no generated icon. Setting an icon on one of
+those services is refused with the reason. Switch Console asks the server and
+stops drawing them for its agents. An icon an owner set on any other host is
+unaffected.
+
## Agent management
Managed agents, and the agent controllers that run them on users' machines, are
diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tpl
index 29a3c90a0..162a2ac1e 100644
--- a/deploy/remote/helm/switch/templates/_helpers.tpl
+++ b/deploy/remote/helm/switch/templates/_helpers.tpl
@@ -862,6 +862,8 @@ this one. Drop it once the oldest supported image reads ID_SERVER_NAME. */}}
- name: TELEMETRY_INTERNAL
value: {{ .Values.switchCore.telemetry.internal | quote }}
{{- end }}
+- name: THIRD_PARTY_AVATARS_ENABLED
+ value: {{ .Values.switchCore.thirdPartyAvatars.enabled | quote }}
# switch-core sits behind the cluster/ALB and enforces its own
# BearerAuthMiddleware, so fastmcp's browser-oriented DNS-rebinding
# Host/Origin guard (default-on since mcp 1.28) only rejects the
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 7d211eec5..34fc7d160 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -282,6 +282,16 @@ switchCore:
# told from adoption. Leave it false on any other deployment.
internal: false
+ # Agents and people drawn by outside avatar services. An agent with no icon
+ # of its own wears a face from api.dicebear.com seeded with its name, and a
+ # person relayed from another platform a lettered badge from ui-avatars.com
+ # with their name in the URL. Chat clients load those images, so the services
+ # see the name and each reader's address. false sends no such URL, stored
+ # icons included: each platform shows its own default icon, new agents get no
+ # generated icon, and Switch Console stops drawing them for this server.
+ thirdPartyAvatars:
+ enabled: true
+
# Public base URL the gateway is served on (used for links / OIDC redirects).
frontendBaseUrl: ""
# Public origin (scheme + host, no path) of the gateway HTTP API itself, used