Skip to content

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

feat: custom agent icons across switch-core, the bridges and the console (CHOO-2171) (#237)

Louis Amaudruz1f5b41939eba
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 29a9c48c5..72a3da4e7 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
@@ -85,6 +85,7 @@ function params(overrides: Record<string, unknown> = {}) {
providerId: 'codex' as const,
serverId: 'srv-1',
description: 'Codex running in repo',
+ iconUrl: null,
autoSession: false,
autoApprove: false,
definitionAttributes: {},
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 d2099ba42..76d1cb775 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 { ensureLocation, getLocationByHostDir } from '@main/core/locations/store
import { getPlugin } from '@main/core/providers/plugin-registry';
import { getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
+import { agentAvatarUrlForName } 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';
@@ -34,6 +35,9 @@ export type AddAgentParams = {
/** The registered Switch server to mint the identity on. */
serverId: string;
description: string;
+ /** The icon picked in the create form. Null means the form offered no
+ * choice, and the agent is registered with the avatar its name generates. */
+ iconUrl: string | null;
autoSession: boolean;
autoApprove: boolean;
/** Provider-specific definition attributes (model, effort, tools, prompt, …),
@@ -88,6 +92,7 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>
repoDir: params.dir,
autoSession: params.autoSession,
agentType: knownAgentTypeForProvider(params.providerId),
+ iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),
});
if (registered.kind !== 'created') return registered;
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
index bfa4fc5f8..37ce11818 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts
@@ -9,6 +9,7 @@ import { getPlugin } from '@main/core/providers/plugin-registry';
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
import { findServerByEndpoint, getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
+import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { Agent } from '@shared/core/agents/agents';
import type { OnboardAgentError } from '@shared/core/agents/onboarding';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
@@ -131,6 +132,9 @@ async function resolveIdentity(
// This path onboards `.claude/agents/*.md` definitions, so the identity is a
// Claude Code one by construction.
agentType: knownAgentTypeForProvider('claude'),
+ // Nobody is at a form to choose one, so it starts with the avatar its name
+ // generates — the same picture it would be shown with anyway.
+ iconUrl: agentAvatarUrlForName(name),
});
if (registered.kind !== 'created') {
const message = 'message' in registered ? registered.message : '';
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
index aaa1a552c..cd9c403c1 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
@@ -12,6 +12,9 @@ export type RegisterAgentInput = {
* `knownAgentTypeForProvider`. Required — an omitted type would silently
* register the agent as Claude Code whatever it actually runs (CHOO-1436). */
agentType: KnownAgentType;
+ /** The icon chosen in the create form, or null for none. Required so a new
+ * create flow has to say which it means. */
+ iconUrl: string | null;
};
/**
@@ -40,6 +43,7 @@ export async function registerAgentIdentity(
name: input.name,
description: input.description,
agentType: input.agentType,
+ iconUrl: input.iconUrl,
options: {
channels_enabled: true,
repo_dir: input.repoDir,
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
new file mode 100644
index 000000000..04f7f994b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -0,0 +1,223 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
+import type { RemoteAgentSummary, SwitchServer } from '@shared/core/switch-servers/switch-servers';
+
+const fetchAgents = vi.fn();
+const updateAgentIcon = vi.fn();
+const getAgents = vi.fn();
+
+/** Stands in for the real `GatewayError`, which the module narrows on by
+ * `instanceof` and by `status`. */
+class FakeGatewayError extends Error {
+ constructor(
+ readonly kind: string,
+ message: string,
+ readonly status?: number
+ ) {
+ super(message);
+ }
+}
+
+vi.mock('./gateway-client', () => ({
+ fetchAgents: (...args: unknown[]) => fetchAgents(...args),
+ updateAgentIcon: (...args: unknown[]) => updateAgentIcon(...args),
+ GatewayError: FakeGatewayError,
+}));
+
+vi.mock('@main/core/agents/getAgents', () => ({
+ getAgents: (...args: unknown[]) => getAgents(...args),
+}));
+
+vi.mock('@main/lib/logger', () => ({
+ log: { info: vi.fn(), warn: vi.fn(), debug: vi.fn(), error: vi.fn() },
+}));
+
+function agent(overrides: Partial<RemoteAgentSummary>): RemoteAgentSummary {
+ return {
+ id: 'a-1',
+ name: 'worker',
+ description: '',
+ connectorType: 'claude-code',
+ ownerId: 'user-me',
+ ownerName: 'me',
+ knownAgentType: 'claude-code',
+ addressingPolicy: null,
+ iconUrl: null,
+ createdAt: '2026-01-01T00:00:00Z',
+ ...overrides,
+ };
+}
+
+function server(id: string): SwitchServer {
+ return { id } as SwitchServer;
+}
+
+/**
+ * Set up a server's agent list and which of them this install manages locally.
+ * `managed` defaults to all of them — the ordinary case of a machine looking at
+ * its own agents.
+ */
+function given(remote: RemoteAgentSummary[], managed?: string[]) {
+ const ids = managed ?? remote.map((a) => a.id);
+ fetchAgents.mockResolvedValue(remote);
+ getAgents.mockResolvedValue(
+ ids.map((switchAgentId) => ({ id: `local-${switchAgentId}`, switchAgentId, serverId: 's-1' }))
+ );
+}
+
+/** Re-imported per test: the module remembers which servers it has done, which
+ * is the behaviour under test in one case and interference in every other. */
+async function loadFresh() {
+ vi.resetModules();
+ return (await import('./backfill-agent-icons')).backfillAgentIcons;
+}
+
+beforeEach(() => {
+ fetchAgents.mockReset().mockResolvedValue([]);
+ getAgents.mockReset().mockResolvedValue([]);
+ updateAgentIcon.mockReset().mockResolvedValue(agent({}));
+});
+
+describe('backfillAgentIcons', () => {
+ it('gives an icon-less agent the avatar its name generates', async () => {
+ given([agent({ id: 'a-1', name: 'switch_worker' })]);
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(updateAgentIcon).toHaveBeenCalledWith(
+ expect.anything(),
+ 'a-1',
+ agentAvatarUrlForName('switch_worker')
+ );
+ });
+
+ it('gives an agent with no recorded owner its icon', async () => {
+ // The regression that made this whole pass a no-op: agents registered
+ // before Switch tracked ownership have `ownerId: null`, and filtering on
+ // "owned by me" skipped precisely the oldest agents — the ones a backfill
+ // exists for. Whether the write is allowed is the gateway's call.
+ given([agent({ id: 'a-1', name: 'ancient', ownerId: null })]);
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(updateAgentIcon).toHaveBeenCalledOnce();
+ });
+
+ it('leaves an agent that already has an icon alone', async () => {
+ // A chosen icon is the owner's; overwriting it with a generated one would
+ // undo their choice on every startup.
+ given([agent({ iconUrl: 'https://example.com/mine.png' })]);
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ expect(updateAgentIcon).not.toHaveBeenCalled();
+ });
+
+ it('ignores an agent this install does not manage', async () => {
+ // `GET /agents` lists the whole server. Someone else's agent is not ours to
+ // give a picture to, even if this user happens to be an admin.
+ given([agent({ id: 'a-1' }), agent({ id: 'someone-elses' })], ['a-1']);
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ expect(updateAgentIcon).toHaveBeenCalledWith(expect.anything(), 'a-1', expect.any(String));
+ });
+
+ it('ignores a local agent belonging to a different server', async () => {
+ fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);
+ getAgents.mockResolvedValue([
+ { id: 'local-1', switchAgentId: 'a-1', serverId: 'another-server' },
+ ]);
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ expect(updateAgentIcon).not.toHaveBeenCalled();
+ });
+
+ it('treats a refusal as not-ours rather than a failure', async () => {
+ given([agent({ id: 'a-1' })]);
+ updateAgentIcon.mockRejectedValueOnce(new FakeGatewayError('http', 'forbidden', 403));
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 0 });
+ });
+
+ 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
+ // has to be told, because the app draws its own bots and looks correct.
+ given([agent({ id: 'a-1' }), agent({ id: 'a-2' })]);
+ updateAgentIcon.mockRejectedValue(new FakeGatewayError('http', 'not found', 404));
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'unsupported' });
+ });
+
+ it('reports the agents that kept the old icon', async () => {
+ given([agent({ id: 'a-1' }), agent({ id: 'a-2' }), agent({ id: 'a-3' })]);
+ updateAgentIcon.mockRejectedValueOnce(new Error('boom'));
+ const backfill = await loadFresh();
+
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'partial', written: 2, failed: 1 });
+ expect(updateAgentIcon).toHaveBeenCalledTimes(3);
+ });
+
+ it('asks the gateway once per server however often it is called', async () => {
+ given([agent({})]);
+ const backfill = await loadFresh();
+
+ await backfill(server('s-1'));
+ await backfill(server('s-1'));
+ await backfill(server('s-1'));
+
+ expect(updateAgentIcon).toHaveBeenCalledTimes(1);
+ expect(fetchAgents).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not start a second pass while the first is still running', async () => {
+ // Two sidebar refreshes can land together on startup; without this each
+ // would see no icons yet and write every agent twice.
+ let release = (_: RemoteAgentSummary[]) => {};
+ getAgents.mockResolvedValue([{ id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' }]);
+ fetchAgents.mockReturnValue(
+ new Promise<RemoteAgentSummary[]>((resolve) => {
+ release = resolve;
+ })
+ );
+ const backfill = await loadFresh();
+
+ const first = backfill(server('s-1'));
+ const second = backfill(server('s-1'));
+ release([agent({ id: 'a-1' })]);
+ await Promise.all([first, second]);
+
+ expect(fetchAgents).toHaveBeenCalledTimes(1);
+ expect(updateAgentIcon).toHaveBeenCalledTimes(1);
+ });
+
+ it('tries again after a failed pass', async () => {
+ // A server unreachable at startup must not be written off for the rest of
+ // the run — otherwise its agents keep the lettered avatar until a restart.
+ fetchAgents.mockRejectedValueOnce(new Error('offline'));
+ const backfill = await loadFresh();
+
+ await expect(backfill(server('s-1'))).rejects.toThrow('offline');
+
+ given([agent({})]);
+ expect(await backfill(server('s-1'))).toEqual({ kind: 'written', written: 1 });
+ });
+
+ it('handles each server separately', async () => {
+ fetchAgents.mockResolvedValue([agent({ id: 'a-1' })]);
+ getAgents.mockResolvedValue([
+ { id: 'local-1', switchAgentId: 'a-1', serverId: 's-1' },
+ { id: 'local-2', switchAgentId: 'a-1', serverId: 's-2' },
+ ]);
+ const backfill = await loadFresh();
+
+ await backfill(server('s-1'));
+ await backfill(server('s-2'));
+
+ expect(updateAgentIcon).toHaveBeenCalledTimes(2);
+ });
+});
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
new file mode 100644
index 000000000..3f6427268
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
@@ -0,0 +1,120 @@
+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';
+
+/**
+ * Give the signed-in user's existing agents the bot avatar their name generates
+ * (CHOO-2171).
+ *
+ * Agents registered before icons existed have none, and the Switch server's own
+ * fallback for those is the lettered avatar the bridges have always drawn. This
+ * writes the bot in, so an agent this app manages looks the same in the app as
+ * it does in Slack — and an agent belonging to an install that has not updated
+ * keeps the letters, which is the intended way to tell the two apart.
+ *
+ * Only agents this install manages are touched, and only those with no icon at
+ * all — a chosen icon is never overwritten.
+ *
+ * Managed-by-this-app is the line rather than owned-by-this-user, and the
+ * difference matters: an agent registered before Switch tracked ownership has
+ * no owner, so an owner check silently skips exactly the oldest agents — the
+ * ones this exists for. Whether the write is permitted is then the gateway's
+ * 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 bot for any agent the server has no icon for, so a failed write
+ * leaves the app looking correct while the chat platforms — which ask the
+ * server — still show the lettered avatar. Nothing on screen would say why, so
+ * the caller is handed what happened and tells the user.
+ */
+export function backfillAgentIcons(server: SwitchServer): Promise<AgentIconBackfill> {
+ const settled = completed.get(server.id);
+ if (settled !== undefined) return Promise.resolve(settled);
+
+ const running = inFlight.get(server.id);
+ if (running) return running;
+
+ const run = writeMissingIcons(server)
+ .then((outcome) => {
+ completed.set(server.id, outcome);
+ return outcome;
+ })
+ .finally(() => inFlight.delete(server.id));
+
+ inFlight.set(server.id, run);
+ return run;
+}
+
+/** Servers already done this run, and what happened to each. Kept so opening
+ * the agents page repeatedly does not re-ask the gateway; a server that threw
+ * is deliberately absent, so the next refresh tries again. */
+const completed = new Map<string, AgentIconBackfill>();
+const inFlight = new Map<string, Promise<AgentIconBackfill>>();
+
+async function writeMissingIcons(server: SwitchServer): Promise<AgentIconBackfill> {
+ const [agents, local] = await Promise.all([fetchAgents(server), getAgents()]);
+ // `GET /agents` lists the whole server, most of which is nothing to do with
+ // this computer.
+ const managed = new Set(
+ local
+ .filter((agent) => agent.serverId === server.id && agent.switchAgentId !== null)
+ .map((agent) => agent.switchAgentId as string)
+ );
+ const missing = agents.filter((agent) => agent.iconUrl === null && managed.has(agent.id));
+ if (missing.length === 0) return { kind: 'written', written: 0 };
+
+ let written = 0;
+ const failures: string[] = [];
+ let notFound = 0;
+ for (const agent of missing) {
+ try {
+ await updateAgentIcon(server, agent.id, agentAvatarUrlForName(agent.name));
+ written += 1;
+ } catch (cause) {
+ // A refusal means the agent is not this user's to change — expected on a
+ // shared machine, and not a failure to report.
+ if (cause instanceof GatewayError && cause.status === 403) {
+ log.debug('agent icon backfill: not ours to change', { agent: agent.name });
+ continue;
+ }
+ // Anything else must not cost the remaining agents their icons, so it is
+ // collected rather than thrown.
+ failures.push(agent.name);
+ if (cause instanceof GatewayError && cause.status === 404) notFound += 1;
+ log.debug('agent icon backfill: one agent failed', { agent: agent.name, cause });
+ }
+ }
+
+ // Every single write 404ing is a server without the icon endpoint at all,
+ // not a set of missing agents — the agents came from that same server one
+ // request earlier. Worth separating: one is "upgrade the server", the other
+ // is "these particular agents went away".
+ if (written === 0 && notFound > 0 && notFound === missing.length) {
+ log.warn('agent icon backfill: this server has no agent-icon endpoint', {
+ event: 'agent_icon_backfill',
+ serverId: server.id,
+ agents: missing.length,
+ });
+ return { kind: 'unsupported' };
+ }
+
+ if (failures.length > 0) {
+ log.warn('agent icon backfill: some agents kept the lettered avatar', {
+ event: 'agent_icon_backfill',
+ serverId: server.id,
+ written,
+ failed: failures.length,
+ failedAgents: failures,
+ });
+ return { kind: 'partial', written, failed: failures.length };
+ }
+
+ log.info('agent icon backfill: done', {
+ event: 'agent_icon_backfill',
+ serverId: server.id,
+ written,
+ });
+ return { kind: 'written', written };
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
index 7b31cad0e..f00fc8b96 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.test.ts
@@ -24,6 +24,8 @@ vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
managedServerHostBlocked,
}));
vi.mock('./auth', () => ({ oidcLogin: vi.fn(), passwordLogin: vi.fn() }));
+// Reads this install's own agent rows, and through them the database client.
+vi.mock('./backfill-agent-icons', () => ({ backfillAgentIcons: vi.fn() }));
// Reaches the encrypted secrets store, and through it the database client.
vi.mock('./bundled-chat-sign-in', () => ({ bundledChatSignInFor: vi.fn() }));
vi.mock('./gateway-web', () => ({ openAuthenticatedGatewayPage: vi.fn() }));
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 626811743..f7e3a0a13 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
@@ -18,6 +18,7 @@ import {
managedServerHostBlocked,
} from '@main/core/managed-switch-server/managed-server-status';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
+import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';
import type {
@@ -26,6 +27,7 @@ import type {
AgentDefaults,
AgentVerifyResult,
BridgeDirectorySearchResult,
+ AgentIconBackfill,
BundledChatSignIn,
ClaimIdentityParams,
ClaimIdentityResult,
@@ -61,6 +63,7 @@ import type {
} from '@shared/core/switch-servers/switch-servers';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { type LoginError, oidcLogin, passwordLogin } from './auth';
+import { backfillAgentIcons } from './backfill-agent-icons';
import { withResolvedHomeUrls } from './bridge-home-url';
import { bundledChatSignInFor } from './bundled-chat-sign-in';
import { createBridgeOnServer } from './create-bridge';
@@ -90,6 +93,7 @@ import {
releaseBridgeIdentity,
removeRoomAgent,
updateAddressingPolicy,
+ updateAgentIcon,
updateRoom,
} from './gateway-client';
import { openAuthenticatedGatewayPage } from './gateway-web';
@@ -423,6 +427,22 @@ export const switchServersController = createRPCController({
}): Promise<void> =>
updateAddressingPolicy(await requireServer(params.serverId), params.agentId, params.policy),
+ /** Give this user's icon-less agents the avatar their name generates. Runs
+ * once per server per app run; reports what happened so the caller can say
+ * when the icons did not reach the server. */
+ backfillAgentIcons: async (serverId: string): Promise<AgentIconBackfill> =>
+ backfillAgentIcons(await requireServer(serverId)),
+
+ /** Set or clear an agent's icon. Returns the agent as the server now holds
+ * it, so the caller refreshes from the stored value rather than the one it
+ * hoped for. */
+ updateAgentIcon: async (params: {
+ serverId: string;
+ agentId: string;
+ iconUrl: string | null;
+ }): Promise<RemoteAgentSummary> =>
+ updateAgentIcon(await requireServer(params.serverId), params.agentId, params.iconUrl),
+
verifyAgent: async (params: {
serverId: string;
agentId: string;
@@ -458,6 +478,7 @@ export const switchServersController = createRPCController({
description: params.description,
repoDir: params.dir,
autoSession: params.autoSession,
+ iconUrl: agentAvatarUrlForName(params.name),
// Provisioning writes `.claude/settings.local.json` — this is the Claude
// Code path by construction, not a fallback.
agentType: knownAgentTypeForProvider('claude'),
@@ -505,6 +526,7 @@ export const switchServersController = createRPCController({
description: params.description,
repoDir: params.remoteRepoDir,
autoSession: params.autoSession,
+ iconUrl: agentAvatarUrlForName(params.name),
// Remote provisioning likewise writes `.claude/settings.local.json`.
agentType: knownAgentTypeForProvider('claude'),
});
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 14a9bc9b3..e809a8fec 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
@@ -504,6 +504,7 @@ describe('registerKnownAgent', () => {
description: 'Codex running in repo',
agentType: 'codex',
options: { channels_enabled: true, repo_dir: '/repo' },
+ iconUrl: null,
});
expect(registered).toEqual({ id: 'sw-1', apiKey: 'tok-123' });
@@ -513,6 +514,7 @@ describe('registerKnownAgent', () => {
name: 'codex-hoot',
description: 'Codex running in repo',
options: { channels_enabled: true, repo_dir: '/repo' },
+ icon_url: null,
overwrite: false,
});
});
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 c5c0d61f2..fa16f5c1a 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
@@ -313,6 +313,10 @@ export async function registerKnownAgent(
* `knownAgentTypeForProvider` rather than letting a call site fall back to
* Claude Code's shape by omission (CHOO-1436). */
agentType: KnownAgentType;
+ /** The agent's icon, or null to leave it unset and let the fallback draw
+ * one. Required rather than optional so a create flow states which it
+ * means instead of dropping the user's choice by forgetting the field. */
+ iconUrl: string | null;
}
): Promise<RegisteredAgent> {
const res = await gatewayFetch(server, '/agents/register', {
@@ -323,6 +327,7 @@ export async function registerKnownAgent(
name: params.name,
description: params.description,
options: params.options,
+ icon_url: params.iconUrl,
overwrite: false,
},
});
@@ -330,30 +335,44 @@ export async function registerKnownAgent(
return { id: json.id, apiKey: json.api_key };
}
+/** The gateway's wire shape for an agent, as `AgentSummary` and the `AgentDetail`
+ * superset both send it. Fields the gateway added later are optional here so an
+ * older server still parses. */
+type AgentSummaryJson = {
+ id: string;
+ name: string;
+ description: string;
+ connector_type: string;
+ owner_id?: string | null;
+ owner_name: string | null;
+ known_agent_type: string | null;
+ addressing_policy?: AddressingPolicy | null;
+ icon_url?: string | null;
+ created_at: string;
+};
+
+/** Single place the agent wire shape becomes a `RemoteAgentSummary`. Every
+ * endpoint returning an agent goes through here, so a new field cannot reach
+ * one caller and silently miss another. */
+function toRemoteAgentSummary(json: AgentSummaryJson): RemoteAgentSummary {
+ return {
+ id: json.id,
+ name: json.name,
+ description: json.description,
+ connectorType: json.connector_type,
+ ownerId: json.owner_id ?? null,
+ ownerName: json.owner_name,
+ knownAgentType: json.known_agent_type,
+ addressingPolicy: json.addressing_policy ?? null,
+ iconUrl: json.icon_url ?? null,
+ createdAt: json.created_at,
+ };
+}
+
export async function fetchAgents(server: SwitchServer): Promise<RemoteAgentSummary[]> {
const res = await gatewayFetch(server, '/agents', { authenticated: true });
- const json = (await res.json()) as Array<{
- id: string;
- name: string;
- description: string;
- connector_type: string;
- owner_id?: string | null;
- owner_name: string | null;
- known_agent_type: string | null;
- addressing_policy?: AddressingPolicy | null;
- created_at: string;
- }>;
- return json.map((a) => ({
- id: a.id,
- name: a.name,
- description: a.description,
- connectorType: a.connector_type,
- ownerId: a.owner_id ?? null,
- ownerName: a.owner_name,
- knownAgentType: a.known_agent_type,
- addressingPolicy: a.addressing_policy ?? null,
- createdAt: a.created_at,
- }));
+ const json = (await res.json()) as AgentSummaryJson[];
+ return json.map(toRemoteAgentSummary);
}
/**
@@ -369,28 +388,7 @@ export async function fetchAgentDetail(
const res = await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}`, {
authenticated: true,
});
- const json = (await res.json()) as {
- id: string;
- name: string;
- description: string;
- connector_type: string;
- owner_id?: string | null;
- owner_name: string | null;
- known_agent_type: string | null;
- addressing_policy?: AddressingPolicy | null;
- created_at: string;
- };
- return {
- id: json.id,
- name: json.name,
- description: json.description,
- connectorType: json.connector_type,
- ownerId: json.owner_id ?? null,
- ownerName: json.owner_name,
- knownAgentType: json.known_agent_type,
- addressingPolicy: json.addressing_policy ?? null,
- createdAt: json.created_at,
- };
+ return toRemoteAgentSummary((await res.json()) as AgentSummaryJson);
}
/**
@@ -551,6 +549,28 @@ export async function updateAddressingPolicy(
});
}
+/**
+ * Set (or clear, with `iconUrl = null`) an agent's icon (`PUT /agents/{id}/icon`).
+ * Only the agent's owner (or an admin) may change it; a non-owner request
+ * surfaces as a `GatewayError`, as does a URL the gateway rejects — it accepts
+ * public `https` only, so a link to a private address comes back as a 400.
+ *
+ * Returns the agent as the gateway now holds it, so a caller can refresh from
+ * the server's answer rather than assuming the value it sent was stored.
+ */
+export async function updateAgentIcon(
+ server: SwitchServer,
+ agentId: string,
+ iconUrl: string | null
+): Promise<RemoteAgentSummary> {
+ const res = await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}/icon`, {
+ authenticated: true,
+ method: 'PUT',
+ body: { icon_url: iconUrl },
+ });
+ return toRemoteAgentSummary((await res.json()) as AgentSummaryJson);
+}
+
/** List a server's room groups (`GET /room-groups`), for the addressing-rule
* room-group selector. */
export async function fetchRoomGroups(server: SwitchServer): Promise<RemoteRoomGroup[]> {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index 840151020..f1d1e92d0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -269,6 +269,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
providerId: pickState.providerId,
serverId: pickState.serverId,
description: form.description.trim(),
+ iconUrl: form.iconUrl,
autoSession: form.autoSession,
autoApprove: form.autoApprove,
definitionAttributes: advancedAttributesRef.current,
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 6c3d5120a..82615d0c6 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
@@ -7,6 +7,7 @@ import { AddressingPolicyControl } from '@renderer/features/switch-servers/addre
import type { OptionItem } from '@renderer/features/switch-servers/addressing-policy-editor';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';
@@ -213,6 +214,21 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
const descriptionId = useId();
return (
<FieldGroup>
+ {/* Above the name, because it is the first thing the finished agent is
+ recognised by — and it follows the name as it is typed, which only
+ reads as cause and effect if it is on screen while you type. */}
+ <div className="flex flex-col items-center gap-1.5 pb-1">
+ <AgentIconPicker
+ name={form.agentName}
+ iconUrl={form.iconUrl}
+ onChange={form.setIconUrl}
+ size={84}
+ />
+ <span className="text-xs text-foreground-muted">
+ {form.iconUrl === null ? 'Automatically generated' : 'Click to change'}
+ </span>
+ </div>
+
<Field>
<FieldLabel htmlFor={nameId}>Name</FieldLabel>
<Input
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 a799f992d..d822825d0 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
@@ -52,6 +52,11 @@ export function useConfigureAgentForm() {
const [addressingPolicy, setAddressingPolicy] = useState<AddressingPolicy | null>(() =>
ownerOnlyPolicy()
);
+ // The agent's icon (CHOO-2171). Null means "whatever the name generates",
+ // which is also what the ✕ in the picker returns to — held as null rather
+ // than as the resolved URL so the avatar keeps following the name while the
+ // user is still typing it.
+ const [iconUrl, setIconUrl] = useState<string | null>(null);
const setAutoApprove = useCallback((value: boolean) => {
setAutoApproveRaw(value);
@@ -88,6 +93,8 @@ export function useConfigureAgentForm() {
suggestAutoApprove,
addressingPolicy,
setAddressingPolicy,
+ iconUrl,
+ setIconUrl,
isValid,
};
}
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 a10332cb7..6c5f23fd3 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
@@ -1,15 +1,17 @@
-import { useQuery } from '@tanstack/react-query';
-import { Bot } from 'lucide-react';
+import { useQueryClient } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import {
getLocationStore,
locationDisplayName,
} from '@renderer/features/locations/stores/location-selectors';
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
+import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Badge } from '@renderer/lib/ui/badge';
import { Button } from '@renderer/lib/ui/button';
import { BoundShortcut } from '@renderer/lib/ui/shortcut';
@@ -35,23 +37,49 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
const provider = agent?.providerId ? providerDisplayName(agent.providerId) : null;
const serverId = agent?.serverId ?? null;
- const { data: remoteAgents } = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),
- enabled: serverId !== null,
- });
- const description =
- (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId)?.description ?? null;
+ const { data: remoteAgents } = useRemoteAgents(serverId);
+ const remote = (remoteAgents ?? []).find((a) => a.id === agent?.switchAgentId) ?? null;
+ const description = remote?.description ?? null;
const roomable = serverId !== null && agent?.switchAgentId != null;
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+ const switchAgentId = agent?.switchAgentId ?? null;
+
+ /** The icon is stored on the Switch server, not locally, so a change is a
+ * request that can fail. It is reported rather than swallowed: a picture
+ * that silently reverts on the next refresh is worse than an error. */
+ const changeIcon = async (iconUrl: string | null) => {
+ if (serverId === null || switchAgentId === null) return;
+ try {
+ await rpc.switchServers.updateAgentIcon({ serverId, agentId: switchAgentId, iconUrl });
+ await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ } catch (cause) {
+ toast({
+ title: "Could not change the agent's icon",
+ description: cause instanceof Error ? cause.message : String(cause),
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const editableIcon = serverId !== null && switchAgentId !== null;
+
return (
<header className="flex shrink-0 items-start gap-5 pt-10">
- <span className="flex size-20 shrink-0 items-center justify-center rounded-[18px] bg-[var(--surface-2)]">
- {agent?.providerId ? (
- <AgentIcon id={agent.providerId} size={40} />
+ <span className="flex size-[88px] shrink-0 items-center justify-center">
+ {editableIcon ? (
+ <AgentIconPicker
+ name={title}
+ iconUrl={remote?.iconUrl ?? null}
+ onChange={changeIcon}
+ size={88}
+ />
) : (
- <Bot className="size-9 text-foreground-muted" />
+ // 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} />
)}
</span>
<div className="flex min-w-0 flex-1 flex-col gap-2">
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 6ba7c23c0..1ee67530f 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
@@ -12,6 +12,7 @@ import {
hasDiscardableSessionError,
hasSessionError,
} from '@renderer/features/sessions/stores/session-selectors';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -19,6 +20,7 @@ import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
import {
ContextMenu,
ContextMenuContent,
@@ -60,6 +62,7 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
const agentName = agent.name;
const location = getLocationStore(agent.locationId);
+ const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);
// The agent's name IS its Switch identity: Switch Console chose it, registered it
// under that name, and keys its credentials and definition by it. Reading the
@@ -104,16 +107,29 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
selection highlight still spans the sidebar's full width at every
depth. */}
<div className="flex min-w-0 flex-1 items-center gap-[9px]" style={depthIndent(depth)}>
- <span className="flex size-4 shrink-0 items-center justify-center">
- {agent.providerId ? (
- <AgentIcon id={agent.providerId} size={16} className="h-4 w-4" />
- ) : (
- <Bot className="h-4 w-4" />
- )}
+ {/* 21px inside an 18px slot, so the larger circle reads at the same
+ weight as the provider glyphs it replaced without growing the
+ row or shifting the label. */}
+ <span className="flex size-[18px] shrink-0 items-center justify-center">
+ <AgentAvatar
+ name={label}
+ iconUrl={iconUrl}
+ size={21}
+ className="-mx-[1.5px] bg-transparent"
+ />
</span>
<SidebarMenuAction aria-label={`Open agent ${label}`} className="truncate select-none">
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate">{label}</span>
+ {/* What the agent runs on. The avatar took the leading slot, so
+ without this the row no longer says. Hideable from the
+ Sessions menu for a reader who only cares about identity. */}
+ {!sidebarStore.hideProviderMark &&
+ (agent.providerId ? (
+ <AgentIcon id={agent.providerId} size={12} className="h-3 w-3 shrink-0" />
+ ) : (
+ <Bot className="h-3 w-3 shrink-0 text-foreground-muted" />
+ ))}
{location.data?.sshHost != null && (
<Tooltip>
<TooltipTrigger>
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 ef28d774f..416f6bd00 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
@@ -3,12 +3,14 @@ import { observer } from 'mobx-react-lite';
import { getLocationStore } from '@renderer/features/locations/stores/location-selectors';
import { HostTroubleIndicator } from '@renderer/features/remote-hosts/host-trouble-indicator';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
import {
ContextMenu,
ContextMenuContent,
@@ -56,6 +58,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
// This is a Switch room's member list, so the Switch identity is what matters
// — and that is the stored name: it is what was registered on the server.
const label = agent.name || 'Unnamed agent';
+ const iconUrl = useAgentIconUrl(agent.serverId, agent.switchAgentId);
const expandKey = roomAgentGroupKey(roomId, agent.id);
const expanded = sidebarStore.isGroupExpanded(expandKey);
@@ -106,16 +109,26 @@ export const RoomAgentRow = observer(function RoomAgentRow({
{/* Indent on the content, not the row, so the highlight still spans
the sidebar's full width at every depth. */}
<div className="flex min-w-0 flex-1 items-center gap-[9px]" style={depthIndent(depth)}>
- <span className="flex size-4 shrink-0 items-center justify-center">
- {agent.providerId ? (
- <AgentIcon id={agent.providerId} size={16} className="h-4 w-4" />
- ) : (
- <Bot className="h-4 w-4" />
- )}
+ <span className="flex size-[18px] shrink-0 items-center justify-center">
+ <AgentAvatar
+ name={label}
+ iconUrl={iconUrl}
+ size={21}
+ className="-mx-[1.5px] bg-transparent"
+ />
</span>
<SidebarMenuAction aria-label={`Open agent ${label}`} className="truncate select-none">
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate">{label}</span>
+ {/* Mirrors the agent-grouped row: the same agent must not carry
+ a different amount of information depending on how the
+ sidebar happens to be grouped. */}
+ {!sidebarStore.hideProviderMark &&
+ (agent.providerId ? (
+ <AgentIcon id={agent.providerId} size={12} className="h-3 w-3 shrink-0" />
+ ) : (
+ <Bot className="h-3 w-3 shrink-0 text-foreground-muted" />
+ ))}
{/* Same agent, same host problem — this row used to show
nothing, so whether you saw it depended on which grouping
the sidebar happened to be in. */}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
index c55bd9d2e..61ed8a621 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sessions-section-header.tsx
@@ -291,6 +291,16 @@ export const SessionsSectionHeader = observer(function SessionsSectionHeader() {
Clear filters
</DropdownMenuItem>
<DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Show</DropdownMenuLabel>
+ <DropdownMenuCheckboxItem
+ checked={!sidebarStore.hideProviderMark}
+ onCheckedChange={(checked) => sidebarStore.setHideProviderMark(!checked)}
+ >
+ Agent type mark
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
<DropdownMenuItem onClick={() => sidebarStore.collapseAll()}>
<ChevronsDownUp className="mr-1.5 h-4 w-4" />
Collapse all
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
index 85f19932d..c2c77f849 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts
@@ -190,6 +190,11 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
/** Whether the first-run setup checklist is collapsed to its header row. */
onboardingChecklistCollapsed = false;
+ /** Whether to hide the provider mark beside a sidebar agent's name. Stated
+ * as "hide" so the default — showing it — is the falsy one, and a reader who
+ * never opens the menu keeps seeing what an agent runs on. */
+ hideProviderMark = false;
+
constructor(private readonly locationManager: LocationManagerStore) {
makeAutoObservable(this, {
expandedLocationIds: false,
@@ -471,6 +476,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
filterBridgeTypes: [...this.filterBridgeTypes],
filterRoomHasLiveSession: this.filterRoomHasLiveSession,
onboardingChecklistCollapsed: this.onboardingChecklistCollapsed,
+ hideProviderMark: this.hideProviderMark,
};
}
@@ -519,12 +525,19 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
if (snapshot.onboardingChecklistCollapsed !== undefined) {
this.onboardingChecklistCollapsed = snapshot.onboardingChecklistCollapsed;
}
+ if (snapshot.hideProviderMark !== undefined) {
+ this.hideProviderMark = snapshot.hideProviderMark;
+ }
}
toggleOnboardingChecklistCollapsed(): void {
this.onboardingChecklistCollapsed = !this.onboardingChecklistCollapsed;
}
+ setHideProviderMark(hidden: boolean): void {
+ this.hideProviderMark = hidden;
+ }
+
/** Called on first load when no snapshot exists — expand all known locations. */
expandAllLocations(): void {
for (const location of this.orderedLocations) {
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 5282a1d3f..bb2fbb623 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
@@ -3,8 +3,12 @@ import type { LocationStore } from '@renderer/features/locations/stores/location
import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
import { sidebarStore } from '@renderer/lib/stores/app-state';
+import { log } from '@renderer/utils/logger';
import type { Agent } from '@shared/core/agents/agents';
+import type { AgentIconBackfill } from '@shared/core/switch-servers/switch-servers';
/**
* What the two sidebar trees agree on: which agents are in scope and which
@@ -117,4 +121,56 @@ export async function refreshSidebarRoomState(force: boolean): Promise<void> {
switchRoomsStore.ensureMembershipsFor(switchIdentities(), { force }),
switchRoomsStore.loadRoomNames(),
]);
+ void giveExistingAgentsAnIcon();
+}
+
+/**
+ * Fill in the avatar of any of this user's agents registered before icons
+ * existed (CHOO-2171). The main process does it once per server per run, so
+ * calling it on every refresh costs nothing after the first.
+ *
+ * Not awaited by the caller and never allowed to throw: the sidebar must paint
+ * whether or not the gateway is reachable, and an agent without an icon still
+ * shows the avatar its name generates in the meantime.
+ *
+ * **A failure here has to be said out loud.** That name-derived avatar makes
+ * the app look finished whether or not the server accepted anything, and the
+ * only place the difference shows is Slack — where the agent keeps its old
+ * lettered picture with nothing explaining why.
+ */
+async function giveExistingAgentsAnIcon(): Promise<void> {
+ const serverIds = new Set(switchIdentities().map((identity) => identity.serverId));
+ for (const serverId of serverIds) {
+ try {
+ reportBackfill(await rpc.switchServers.backfillAgentIcons(serverId));
+ } catch (cause) {
+ log.warn('could not give existing agents their icons', { serverId, cause });
+ toast({
+ title: 'Agent icons could not be saved',
+ description:
+ 'Your agents show a generated icon here, but the Switch server has not stored it — so they keep their old picture in Slack and the other chat apps.',
+ variant: 'destructive',
+ });
+ }
+ }
+}
+
+function reportBackfill(outcome: AgentIconBackfill): void {
+ if (outcome.kind === 'unsupported') {
+ toast({
+ title: 'This Switch server does not support agent icons yet',
+ description:
+ 'Your agents show a generated icon here, but it cannot be saved, so they keep their old picture in Slack and the other chat apps. Updating the server fixes it.',
+ variant: 'destructive',
+ });
+ return;
+ }
+ if (outcome.kind === 'partial') {
+ toast({
+ title: `${outcome.failed} agent${outcome.failed === 1 ? '' : 's'} kept the old icon`,
+ description:
+ 'Their icon could not be saved to the Switch server, so it will not show in Slack or the other chat apps.',
+ variant: 'destructive',
+ });
+ }
}
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 b904b4e70..0a16d7e48 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
@@ -3,9 +3,11 @@ import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { AgentMark, agentProviderLabel } from '@renderer/lib/components/agent-mark';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
import {
Combobox,
@@ -27,7 +29,12 @@ import { Field, FieldLabel } from '@renderer/lib/ui/field';
type Props = BaseModalProps<void> & { roomId: string };
/** An agent that can be added: this install's agent, by its Switch identity. */
-type Candidate = { id: string; name: string; providerId: string | null };
+type Candidate = {
+ id: string;
+ name: string;
+ providerId: string | null;
+ iconUrl: string | null;
+};
export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
roomId,
@@ -47,6 +54,10 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
// offer have to be the same two sets the tree uses, or the picker and the
// sidebar can disagree about who is already in the room.
const members = new Set(switchRoomsStore.localMemberIds(roomId));
+ // The agents' own icons live on the server, not in the local row, so the
+ // list is joined against the server's summary to draw them.
+ const { data: remoteAgents } = useRemoteAgents(serverId);
+ const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
// Only this install's agents are offered. An agent registered on another
// Switch Console could be added server-side but could never be shown or driven
// from here, so it is not ours to offer.
@@ -57,6 +68,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
id: agent.switchAgentId as string,
name: agent.name,
providerId: agent.providerId ?? null,
+ iconUrl: remoteById.get(agent.switchAgentId as string)?.iconUrl ?? null,
}))
.filter((a) => !members.has(a.id) && !selected.some((s) => s.id === a.id))
: [];
@@ -144,7 +156,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
<ComboboxList>
{(item: Candidate) => (
<ComboboxItem key={item.id} value={item} showCheck={false}>
- <AgentMark providerId={item.providerId} size={16} />
+ <AgentAvatar name={item.name} iconUrl={item.iconUrl} size={22} />
<span className="min-w-0 flex-1 truncate">{item.name}</span>
<span className="shrink-0 text-xs text-foreground-muted">
{agentProviderLabel(item.providerId)}
@@ -188,7 +200,7 @@ function ChosenAgentTile({ agent, onRemove }: { agent: Candidate; onRemove: () =
// dialog's own background, so a tile drawn in it was a tile nobody could
// see.
<div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
- <AgentMark providerId={agent.providerId} size={22} />
+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm text-foreground">{agent.name}</span>
<span className="truncate text-xs text-foreground-muted">
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 bf0e0657a..b7e5c43d9 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
@@ -1,14 +1,15 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { Bot, ExternalLink, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
+import { ExternalLink, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
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 { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import {
@@ -302,10 +303,7 @@ const ParticipantsSection = observer(function ParticipantsSection({
// Names for agents belonging to other installs, which this computer has no
// local record of. Shares its key with the rest of the app, so it is usually
// already in hand.
- const remoteAgents = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId),
- });
+ const remoteAgents = useRemoteAgents(serverId);
const remoteById = new Map((remoteAgents.data ?? []).map((a) => [a.id, a]));
async function refresh() {
@@ -340,7 +338,7 @@ const ParticipantsSection = observer(function ParticipantsSection({
{room.agentIds.map((agentId) => (
<ParticipantCard
key={agentId}
- mark={<AgentMark agentId={agentId} serverId={serverId} />}
+ mark={<AgentMark agentId={agentId} serverId={serverId} remoteById={remoteById} />}
name={agentNameFor(agentId, serverId, remoteById)}
detail={agentKindFor(agentId, serverId, remoteById)}
/>
@@ -406,6 +404,8 @@ const AddAgentPanel = observer(function AddAgentPanel({
const [error, setError] = useState<string | null>(null);
const members = new Set(room.agentIds);
+ const { data: remoteAgents } = useRemoteAgents(serverId);
+ const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
const query = filter.trim().toLowerCase();
const candidates = agentsStore
.agentsOnServer(serverId)
@@ -479,11 +479,11 @@ const AddAgentPanel = observer(function AddAgentPanel({
busyId !== null && 'cursor-wait'
)}
>
- {agent.providerId ? (
- <AgentIcon id={agent.providerId} size={18} />
- ) : (
- <Bot className="size-4 shrink-0 text-foreground-muted" />
- )}
+ <AgentAvatar
+ name={agent.name}
+ iconUrl={remoteById.get(switchAgentId)?.iconUrl ?? null}
+ size={22}
+ />
<span className="min-w-0 flex-1 truncate text-sm text-foreground">
{agent.name}
</span>
@@ -523,19 +523,24 @@ function PanelNotice({
);
}
-/** The mark of what an agent runs, resolved through this install's copy of it. */
-function AgentMark({ agentId, serverId }: { agentId: string; serverId: string }) {
- const providerId = localAgentFor(agentId, serverId)?.providerId ?? null;
- if (!providerId) {
- return (
- <span className="flex size-7 shrink-0 items-center justify-center">
- <Bot className="size-4 text-foreground-muted" />
- </span>
- );
- }
+/** An agent's own picture, beside the human participants' initials discs. */
+function AgentMark({
+ agentId,
+ serverId,
+ remoteById,
+}: {
+ agentId: string;
+ serverId: string;
+ remoteById: Map<string, RemoteAgentSummary>;
+}) {
+ const remote = remoteById.get(agentId) ?? null;
return (
<span className="flex size-7 shrink-0 items-center justify-center">
- <AgentIcon id={providerId} size={20} />
+ <AgentAvatar
+ name={agentNameFor(agentId, serverId, remoteById)}
+ iconUrl={remote?.iconUrl ?? null}
+ 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 c737dfa36..7d59d4358 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
@@ -5,10 +5,8 @@ import { useCallback, useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
-import {
- AgentMark as SharedAgentMark,
- agentProviderLabel,
-} from '@renderer/lib/components/agent-mark';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { rpc } from '@renderer/lib/ipc';
@@ -332,7 +330,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
<ComboboxList>
{(item: RemoteAgentSummary) => (
<ComboboxItem key={item.id} value={item} showCheck={false}>
- <AgentMark agentId={item.id} serverId={serverId} size={16} />
+ <AgentAvatar name={item.name} iconUrl={item.iconUrl} size={22} />
<span className="min-w-0 flex-1 truncate">{item.name}</span>
<span className="shrink-0 text-xs text-foreground-muted">
{providerLabelFor(item.id, serverId)}
@@ -478,7 +476,7 @@ function ChosenAgentTile({
// dialog's own background, so a tile drawn in it was a tile nobody could
// see.
<div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
- <AgentMark agentId={agent.id} serverId={serverId} size={22} />
+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm text-foreground">{agent.name}</span>
<span className="truncate text-xs text-foreground-muted">
@@ -497,24 +495,6 @@ function ChosenAgentTile({
);
}
-/** The mark of what an agent runs, resolved through this install's copy of it. */
-function AgentMark({
- agentId,
- serverId,
- size,
-}: {
- agentId: string;
- serverId: string;
- size: number;
-}) {
- return (
- <SharedAgentMark
- providerId={localAgentFor(agentId, serverId)?.providerId ?? null}
- size={size}
- />
- );
-}
-
/** This install's record of a Switch agent, which is where its provider is
* known — the server's summary says what type it is, not what runs it here. */
function localAgentFor(switchAgentId: string, serverId: string) {
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 b5c742bf8..5c78f6ae8 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
@@ -6,11 +6,12 @@ import { useConfirmDeleteAgent } from '@renderer/features/locations/hooks/use-co
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { getLocationStore } from '@renderer/features/locations/stores/location-selectors';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useAgentIconUrl } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
import {
DropdownMenu,
@@ -93,6 +94,7 @@ const AgentCard = observer(function AgentCard({
const sshHost = location?.data?.sshHost ?? null;
const label = agent.name || 'Unnamed agent';
const provider = providerDisplayName(agent.providerId);
+ const iconUrl = useAgentIconUrl(serverId, agent.switchAgentId);
const gatewayUrl =
agent.switchAgentId && switchRoomsStore.gatewayAgentUrl(serverId, agent.switchAgentId);
@@ -112,13 +114,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">
- <span className="flex size-16 items-center justify-center rounded-full bg-background">
- {agent.providerId ? (
- <AgentIcon id={agent.providerId} size={30} />
- ) : (
- <Bot className="size-7 text-foreground-muted" />
- )}
- </span>
+ <AgentAvatar name={label} iconUrl={iconUrl} 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 81ac90753..dbb620e6b 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
@@ -1,4 +1,4 @@
-import { Bot, ChevronDown, DoorOpen, MessageSquare, Plus } from 'lucide-react';
+import { ChevronDown, DoorOpen, MessageSquare, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
@@ -6,11 +6,12 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
import { openRoom } from '@renderer/features/switch-rooms/open-room';
import { roomTitle } from '@renderer/features/switch-rooms/room-labels';
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
import { SearchInput } from '@renderer/lib/ui/search-input';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
@@ -244,6 +245,8 @@ const RoomRow = observer(function RoomRow({
serverId: string;
}) {
const members = switchRoomsStore.localMemberIds(room.id);
+ const { data: remoteAgents } = useRemoteAgents(serverId);
+ const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
const localAgents = agentsStore
.agentsOnServer(serverId)
.filter((agent) => agent.switchAgentId != null && members.includes(agent.switchAgentId));
@@ -282,21 +285,21 @@ const RoomRow = observer(function RoomRow({
// the room — and a stack reads as that, where an evenly spaced
// row reads as a set of separate controls to click.
//
- // Each mark sits in a filled disc, so what a mark in front hides
- // is a clean circle rather than the silhouette of its own logo —
- // the marks are different shapes, and letting them interlock made
- // two agents read as one broken glyph.
+ // Each avatar keeps its ring, so what the one in front hides is a
+ // clean circle rather than a bitten-into picture — the avatars
+ // are all different, and letting them interlock made two agents
+ // read as one broken image.
<span className="flex shrink-0 items-center -space-x-1.5">
{localAgents.map((agent) => (
<span
key={agent.id}
className="flex size-6 items-center justify-center rounded-full bg-background ring-1 ring-[var(--hair-soft)] transition-colors group-hover/room:bg-[var(--fill)]"
>
- {agent.providerId ? (
- <AgentIcon id={agent.providerId} size={14} />
- ) : (
- <Bot className="size-3.5 text-foreground-muted" />
- )}
+ <AgentAvatar
+ name={agent.name}
+ iconUrl={remoteById.get(agent.switchAgentId ?? '')?.iconUrl ?? null}
+ size={22}
+ />
</span>
))}
</span>
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
new file mode 100644
index 000000000..f70b1a7ab
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
@@ -0,0 +1,63 @@
+import { useState } from 'react';
+import { cn } from '@renderer/utils/utils';
+import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-avatar';
+
+/**
+ * An agent's own picture, at whatever size the surface asks for (CHOO-2171).
+ *
+ * This is the agent's identity — distinct from `AgentIcon`, which shows the
+ * *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:
+ * - the icon its owner chose;
+ * - failing that, a bot 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.
+ */
+export function AgentAvatar({
+ name,
+ iconUrl,
+ size = 16,
+ className,
+}: {
+ name: string;
+ /** The agent's chosen icon, or null to draw one from its name. */
+ iconUrl: string | null;
+ /** Rendered size in pixels. Default: 16. */
+ size?: number;
+ className?: string;
+}) {
+ const src = iconUrl ?? agentAvatarUrlForName(name);
+ const [failedSrc, setFailedSrc] = useState<string | null>(null);
+
+ const shape = cn('inline-flex shrink-0 items-center justify-center rounded-full', className);
+
+ if (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}
+ >
+ {agentInitials(name)}
+ </span>
+ );
+ }
+
+ return (
+ <span className={shape} style={{ width: size, height: size }}>
+ <img
+ src={src}
+ alt=""
+ width={size}
+ height={size}
+ className="size-full rounded-full object-cover"
+ onError={() => setFailedSrc(src)}
+ />
+ </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
new file mode 100644
index 000000000..c3175a159
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
@@ -0,0 +1,180 @@
+import { RotateCw, X } from 'lucide-react';
+import { useState } from 'react';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+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 { agentAvatarChoices } from '@shared/core/agents/agent-avatar';
+
+type PickerTab = 'generated' | 'url';
+
+const TABS: readonly { value: PickerTab; label: string }[] = [
+ { value: 'generated', label: 'Generated' },
+ { value: 'url', label: 'Image URL' },
+];
+
+/**
+ * Choose an agent's picture (CHOO-2171): one of a set of generated bots, or a
+ * link to an image of the reader's own.
+ *
+ * `iconUrl` is null when nothing has been chosen, and the agent then wears the
+ * avatar its name generates. That null is deliberately preserved rather than
+ * resolved to a URL on open: while a new agent is still being named, its
+ * avatar should follow what is being typed, and it can only do that if no
+ * concrete choice has been recorded.
+ */
+export function AgentIconPicker({
+ name,
+ iconUrl,
+ onChange,
+ size = 84,
+ disabled = false,
+}: {
+ /** The agent's name, which seeds the generated avatars. */
+ name: string;
+ /** The current choice, or null for "whatever the name generates". */
+ iconUrl: string | null;
+ onChange: (iconUrl: string | null) => void;
+ /** Diameter of the avatar that opens the picker. */
+ size?: number;
+ disabled?: boolean;
+}) {
+ const [tab, setTab] = useState<PickerTab>('generated');
+ const [round, setRound] = useState(0);
+ const [urlDraft, setUrlDraft] = useState('');
+ const [urlError, setUrlError] = useState<string | null>(null);
+
+ // An unnamed agent still needs something to seed the grid, or every tile is
+ // the same bot drawn from the empty string.
+ const seedName = name.trim() || 'agent';
+ const choices = agentAvatarChoices(seedName, round);
+
+ const commitUrl = () => {
+ const trimmed = urlDraft.trim();
+ if (trimmed === '') {
+ setUrlError(null);
+ onChange(null);
+ return;
+ }
+ if (!/^https:\/\/\S+$/i.test(trimmed)) {
+ setUrlError('Must be a link starting with https://');
+ return;
+ }
+ setUrlError(null);
+ onChange(trimmed);
+ };
+
+ return (
+ <Popover>
+ <PopoverTrigger
+ aria-label="Change the agent's icon"
+ disabled={disabled}
+ className={cn(
+ 'rounded-full transition-opacity',
+ !disabled && 'cursor-pointer hover:opacity-80'
+ )}
+ >
+ <AgentAvatar name={seedName} iconUrl={iconUrl} size={size} />
+ </PopoverTrigger>
+
+ <PopoverContent align="center" sideOffset={8} className="w-80 gap-3">
+ <SegmentedControl
+ value={tab}
+ onChange={setTab}
+ options={TABS}
+ ariaLabel="How to choose the icon"
+ />
+
+ {tab === 'generated' ? (
+ <div className="flex flex-col gap-2">
+ <div className="grid grid-cols-5 gap-2">
+ {choices.map((choice) => {
+ const selected = iconUrl === choice;
+ return (
+ <button
+ key={choice}
+ type="button"
+ aria-label="Use this icon"
+ aria-pressed={selected}
+ onClick={() => onChange(choice)}
+ className={cn(
+ 'flex cursor-pointer items-center justify-center rounded-full p-0.5 ring-2 transition-colors',
+ selected ? 'ring-border-focus' : 'ring-transparent hover:ring-border'
+ )}
+ >
+ <AgentAvatar name={seedName} iconUrl={choice} size={44} />
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-xs text-foreground-muted">
+ {round === 0
+ ? "First is generated from the agent's name."
+ : 'Shuffled — keep going for more.'}
+ </p>
+ <button
+ type="button"
+ onClick={() => 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
+ </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} />
+ <Input
+ value={urlDraft}
+ placeholder="https://example.com/avatar.png"
+ onChange={(event) => setUrlDraft(event.target.value)}
+ onBlur={commitUrl}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ commitUrl();
+ }
+ }}
+ />
+ </div>
+ {/* Named formats rather than "an image": the same link is handed to
+ Slack and Discord for the agent's avatar there, and neither
+ renders SVG, so a vector link works here and nowhere else. */}
+ <p
+ className={cn(
+ 'text-xs',
+ urlError ? 'text-foreground-danger' : 'text-foreground-muted'
+ )}
+ >
+ {urlError ?? 'A direct link to a PNG or JPEG. It is cropped to a circle.'}
+ </p>
+ </div>
+ )}
+
+ {iconUrl !== null && (
+ <button
+ type="button"
+ onClick={() => {
+ setUrlDraft('');
+ setUrlError(null);
+ onChange(null);
+ }}
+ 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
+ </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()}"`}.
+ </p>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts
new file mode 100644
index 000000000..2b2b4798c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-remote-agents.ts
@@ -0,0 +1,40 @@
+import { useQuery } from '@tanstack/react-query';
+import { rpc } from '@renderer/lib/ipc';
+import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
+
+/** The agent list a server holds, keyed so every surface shares one fetch.
+ * Several unrelated views ask for this at once — the sidebar rows, the room
+ * panels, the agent page — and they must agree, so the key is defined once
+ * here rather than retyped at each call site. */
+export function remoteAgentsQueryKey(serverId: string | null) {
+ return ['remote-agents', serverId] as const;
+}
+
+/**
+ * Every agent registered on `serverId`, or an idle query when there is no
+ * server to ask.
+ */
+export function useRemoteAgents(serverId: string | null) {
+ return useQuery<RemoteAgentSummary[]>({
+ queryKey: remoteAgentsQueryKey(serverId),
+ queryFn: () => rpc.switchServers.listRemoteAgents(serverId as string),
+ enabled: serverId !== null,
+ });
+}
+
+/**
+ * An agent's chosen icon, or null when it has none, is not on this server, or
+ * the list has not arrived yet.
+ *
+ * Null is not an error and callers must not treat it as one: `AgentAvatar`
+ * draws a bot from the agent's name instead, so a row renders the right
+ * picture on first paint and simply sharpens to a custom icon if there is one.
+ */
+export function useAgentIconUrl(
+ serverId: string | null,
+ switchAgentId: string | null
+): string | null {
+ const agents = useRemoteAgents(serverId);
+ if (switchAgentId === null) return null;
+ return agents.data?.find((agent) => agent.id === switchAgentId)?.iconUrl ?? null;
+}
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
new file mode 100644
index 000000000..823a2c098
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import {
+ AVATAR_CHOICE_COUNT,
+ agentAvatarChoices,
+ agentAvatarUrlForName,
+ agentAvatarUrlForSeed,
+ agentInitials,
+} from './agent-avatar';
+
+describe('agentAvatarUrlForSeed', () => {
+ it('is stable for a seed', () => {
+ // The whole scheme rests on this: an agent's generated avatar is stored
+ // nowhere, so the same seed has to redraw the same bot forever.
+ expect(agentAvatarUrlForSeed('worker')).toBe(agentAvatarUrlForSeed('worker'));
+ });
+
+ it('differs between seeds', () => {
+ expect(agentAvatarUrlForSeed('worker')).not.toBe(agentAvatarUrlForSeed('manager'));
+ });
+
+ it('asks for a raster image, not a vector one', () => {
+ // Slack, Discord and Mattermost are handed this exact URL as the agent's
+ // avatar and none of them render SVG. An `svg` here would look right in
+ // the app and show nothing on any chat platform.
+ expect(agentAvatarUrlForSeed('worker')).toContain('/bottts/png?');
+ expect(agentAvatarUrlForSeed('worker')).not.toContain('/svg');
+ });
+
+ it('pins the drawing version', () => {
+ // Unpinned, every stored icon silently becomes a different bot the day the
+ // service ships a new major.
+ expect(agentAvatarUrlForSeed('worker')).toContain('/9.x/');
+ });
+
+ it('escapes a seed that would otherwise break the query string', () => {
+ const url = agentAvatarUrlForSeed('a&b=c d');
+ expect(url).toContain('seed=a%26b%3Dc+d');
+ // One `?`, and the seed cannot introduce parameters of its own.
+ expect(url.split('?')).toHaveLength(2);
+ });
+});
+
+describe('agentAvatarChoices', () => {
+ it('leads with the avatar the agent already has', () => {
+ // The first tile is the one the agent is currently wearing, so the grid
+ // opens showing the status quo rather than ten alternatives to it.
+ expect(agentAvatarChoices('worker', 0)[0]).toBe(agentAvatarUrlForName('worker'));
+ });
+
+ it('offers a full page of distinct choices', () => {
+ const choices = agentAvatarChoices('worker', 0);
+ expect(choices).toHaveLength(AVATAR_CHOICE_COUNT);
+ expect(new Set(choices).size).toBe(AVATAR_CHOICE_COUNT);
+ });
+
+ it('gives a different set on the next round', () => {
+ const first = agentAvatarChoices('worker', 0);
+ const second = agentAvatarChoices('worker', 1);
+ expect(second.some((choice) => first.includes(choice))).toBe(false);
+ });
+
+ it('drops the name avatar from later rounds', () => {
+ // Round 0 leads with it; after that the reader has already declined it.
+ expect(agentAvatarChoices('worker', 1)).not.toContain(agentAvatarUrlForName('worker'));
+ });
+
+ it('gives the same page each time it is asked', () => {
+ // A grid that reshuffles on every render is impossible to choose from —
+ // the tile you reached for is gone by the time you click.
+ expect(agentAvatarChoices('worker', 2)).toEqual(agentAvatarChoices('worker', 2));
+ });
+
+ it('gives different agents different choices', () => {
+ const worker = agentAvatarChoices('worker', 0);
+ const manager = agentAvatarChoices('manager', 0);
+ expect(worker.some((choice) => manager.includes(choice))).toBe(false);
+ });
+});
+
+describe('agentInitials', () => {
+ it('takes the first letter of a single-word name', () => {
+ expect(agentInitials('worker')).toBe('W');
+ });
+
+ it('treats underscores as word breaks', () => {
+ // Matches what the Switch bridges put on Slack for the same agent, so the
+ // offline fallback here and the platform fallback there agree.
+ expect(agentInitials('switch_worker')).toBe('SW');
+ });
+
+ it('treats hyphens and spaces as word breaks too', () => {
+ expect(agentInitials('obsidian-backup')).toBe('OB');
+ expect(agentInitials('code review bot')).toBe('CR');
+ });
+
+ it('stops at two letters', () => {
+ expect(agentInitials('one_two_three_four')).toBe('OT');
+ });
+
+ it('answers for a name that is empty or only separators', () => {
+ // Reached while a new agent is being named, so it must not render blank.
+ expect(agentInitials('')).toBe('?');
+ expect(agentInitials('___')).toBe('?');
+ });
+});
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
new file mode 100644
index 000000000..8c82f95fe
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
@@ -0,0 +1,83 @@
+/**
+ * How an agent's bot avatar is built (CHOO-2171).
+ *
+ * An agent's icon is stored on the Switch server as a plain URL, so this module
+ * only decides which URL to offer — nothing here is persisted, and the server
+ * neither knows nor cares that DiceBear produced the picture.
+ *
+ * Two constraints shape what is generated:
+ *
+ * - **Raster, not vector.** The same URL is handed to Slack, Discord and
+ * Mattermost for a bot avatar, and none of them render SVG. An SVG link
+ * would look right in this app and show nothing on the chat platforms.
+ * - **Deterministic.** A seed always yields the same bot, so an agent's
+ * generated avatar is stable across machines and across restarts, and the
+ * "use the one from the name" reset is a value rather than a coin flip.
+ */
+
+/** DiceBear's major version. Pinned in the URL because the drawing changes
+ * between majors: unpinned, every stored icon would quietly become a different
+ * bot the day the service moved on. */
+const DICEBEAR_VERSION = '9.x';
+
+/** Rendered size in pixels. The largest place an avatar appears is the agent
+ * page at 88px, so 256 keeps it sharp on a 2x display without making the
+ * sidebar's 21px copies expensive. */
+const AVATAR_PIXELS = 256;
+
+/** How many bots the picker shows at once. */
+export const AVATAR_CHOICE_COUNT = 10;
+
+/**
+ * The avatar URL for an arbitrary seed. Any string works; the same string
+ * always draws the same bot.
+ */
+export function agentAvatarUrlForSeed(seed: string): string {
+ const params = new URLSearchParams({ seed, size: String(AVATAR_PIXELS) });
+ return `https://api.dicebear.com/${DICEBEAR_VERSION}/bottts/png?${params.toString()}`;
+}
+
+/**
+ * The avatar an agent gets from its own name — the one the picker offers first
+ * and the one the ✕ reset returns to.
+ */
+export function agentAvatarUrlForName(agentName: string): string {
+ return agentAvatarUrlForSeed(agentName);
+}
+
+/**
+ * One page of choices for the picker. `round` 0 leads with the agent's own
+ * name, so the first tile is the avatar it already has; later rounds are
+ * different bots.
+ *
+ * Rounds are derived from the name rather than drawn at random so that the
+ * same agent offers the same choices every time the picker is opened — a grid
+ * that reshuffles itself on every render is impossible to choose from, and
+ * impossible to test.
+ */
+export function agentAvatarChoices(agentName: string, round: number): string[] {
+ const seeds =
+ round === 0
+ ? [agentName, ...sequentialSeeds(agentName, 0, AVATAR_CHOICE_COUNT - 1)]
+ : sequentialSeeds(agentName, round, AVATAR_CHOICE_COUNT);
+ return seeds.map(agentAvatarUrlForSeed);
+}
+
+function sequentialSeeds(agentName: string, round: number, count: number): string[] {
+ return Array.from({ length: count }, (_, index) => `${agentName}-${round}-${index}`);
+}
+
+/**
+ * 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
+ * avatar is wanted.
+ *
+ * Underscores and hyphens count as word breaks so `switch_worker` reads as
+ * `SW`, matching what the Switch bridges put on Slack for the same agent.
+ */
+export function agentInitials(agentName: string): string {
+ const words = agentName.split(/[\s_-]+/).filter((word) => word.length > 0);
+ if (words.length === 0) return '?';
+ const letters = words.slice(0, 2).map((word) => word[0]);
+ return letters.join('').toUpperCase();
+}
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 9ad6fe52e..c7829d73f 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
@@ -189,9 +189,29 @@ export type RemoteAgentSummary = {
* owner" is one list read rather than a read per agent. Null also for a
* server older than the field, which reads the same as open. */
addressingPolicy: AddressingPolicy | null;
+ /** Absolute URL of the agent's own icon, or null when it has none. Null is
+ * the ordinary state rather than an error: the display layer draws a
+ * name-derived avatar instead, so the fallback can change without every
+ * agent needing rewriting. */
+ iconUrl: string | null;
createdAt: string;
};
+/**
+ * What came of giving this user's icon-less agents their generated avatar
+ * (CHOO-2171).
+ *
+ * Reported rather than logged because the app cannot tell the difference on
+ * screen: it draws a name-derived bot for any agent with no stored icon, so a
+ * server that rejected every write still looks right here while the chat
+ * platforms show the lettered avatar.
+ */
+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 };
+
/** Read-only summary of a remote room (mirrors the gateway `RoomSummary`). */
export type RemoteRoomSummary = {
id: string;
diff --git a/console/apps/switch-console-desktop/src/shared/view-state.ts b/console/apps/switch-console-desktop/src/shared/view-state.ts
index e4f40344e..d2022f98c 100644
--- a/console/apps/switch-console-desktop/src/shared/view-state.ts
+++ b/console/apps/switch-console-desktop/src/shared/view-state.ts
@@ -68,6 +68,14 @@ export type SidebarSnapshot = {
* somewhere the checklist itself no longer occupies.
*/
onboardingChecklistCollapsed?: boolean;
+ /**
+ * Whether a sidebar agent row shows the small mark of the provider it runs
+ * on, beside its name. The agent's own icon took over the row's leading slot
+ * (CHOO-2171), and this mark is what still answers "what does this actually
+ * run?" — so it is on unless the reader turns it off, and absent from an
+ * older blob reads as on.
+ */
+ hideProviderMark?: boolean;
};
/** `filterBridgeTypes` entry standing for "no messaging app", which has no
diff --git a/core/switch_core/agent_icon.py b/core/switch_core/agent_icon.py
new file mode 100644
index 000000000..96bba44f2
--- /dev/null
+++ b/core/switch_core/agent_icon.py
@@ -0,0 +1,147 @@
+"""Validation for an agent's icon URL (CHOO-2171).
+
+Switch stores a link to an agent's icon, never the image bytes. The picture may
+come from a generated-avatar service, an operator's own host, or anywhere else
+the client chooses — core does not care, and deliberately knows nothing about
+any provider.
+
+That makes the URL attacker-controlled input with two distinct consumers, and
+the rules below exist for the second one:
+
+ - **Rendered** in the gateway and relayed to collaboration bridges, which
+ hand the link to Slack / Discord / Teams for *them* to fetch. Harmless.
+ - **Fetched by Switch itself.** The Mattermost adapter downloads an agent's
+ avatar and re-uploads it as the bot's icon. A URL naming an internal
+ address would make that a probe into the network Switch runs in, so the
+ scheme and host are constrained here, at the point of storage.
+
+Host checks here cover literal IP addresses only. A DNS name resolving to a
+private address (or re-resolving after this check) can only be caught when the
+fetch happens, so a caller that actually retrieves the URL must guard there too
+rather than treating storage validation as sufficient.
+"""
+
+import ipaddress
+from typing import NoReturn
+from urllib.parse import quote, urlsplit
+
+# Long enough for a generated-avatar link carrying a full set of style options,
+# short enough that the column cannot be used to smuggle a payload.
+MAX_ICON_URL_LENGTH = 2048
+
+_BLOCKED_HOSTNAMES = frozenset(
+ {
+ "localhost",
+ "localhost.localdomain",
+ "ip6-localhost",
+ "ip6-loopback",
+ }
+)
+
+
+class InvalidIconUrl(ValueError):
+ """Raised when an icon URL is missing, malformed, or points somewhere unsafe."""
+
+
+def _reject(reason: str) -> NoReturn:
+ raise InvalidIconUrl(f"Invalid agent icon URL: {reason}")
+
+
+def _check_host(hostname: str) -> None:
+ if hostname.lower() in _BLOCKED_HOSTNAMES:
+ _reject("must not point at the local machine")
+
+ try:
+ address = ipaddress.ip_address(hostname)
+ except ValueError:
+ return
+
+ if (
+ address.is_private
+ or address.is_loopback
+ or address.is_link_local
+ or address.is_reserved
+ or address.is_multicast
+ or address.is_unspecified
+ ):
+ _reject("must not point at a private, loopback, or link-local address")
+
+
+def validate_icon_url(url: str) -> str:
+ """Return `url` stripped, or raise `InvalidIconUrl`.
+
+ Accepts only an absolute `https://` URL with a plain hostname. Rejects
+ other schemes (`data:`, `javascript:`, `file:`, plaintext `http:`),
+ embedded credentials, and hosts that name the local machine or a private
+ network.
+ """
+ if not isinstance(url, str):
+ _reject("must be a string")
+
+ candidate = url.strip()
+ if not candidate:
+ _reject("must not be empty")
+
+ if len(candidate) > MAX_ICON_URL_LENGTH:
+ _reject(f"must be at most {MAX_ICON_URL_LENGTH} characters")
+
+ if any(character.isspace() or ord(character) < 0x20 for character in candidate):
+ _reject("must not contain whitespace or control characters")
+
+ try:
+ parts = urlsplit(candidate)
+ except ValueError as exc:
+ _reject(f"could not be parsed ({exc})")
+
+ if parts.scheme != "https":
+ _reject(f"must use https, got {parts.scheme or 'no scheme'!r}")
+
+ if parts.username or parts.password:
+ _reject("must not embed credentials")
+
+ hostname = parts.hostname
+ if not hostname:
+ _reject("must include a hostname")
+
+ _check_host(hostname)
+
+ return candidate
+
+
+def default_icon_url(agent_name: str, *, image_format: str | None = None) -> str:
+ """The initials avatar shown for an agent that has set no icon of its own.
+
+ Unchanged from what the collaboration bridges have always generated — this
+ is the picture agents already have on Slack, Mattermost, Discord and Teams,
+ and it stays the default so nothing regresses for an agent nobody has given
+ an icon to. It is gathered here only so the four bridges stop each keeping
+ their own copy of the URL.
+
+ `image_format` forces a response format for a caller that needs real bytes
+ rather than a link to hand onward (Mattermost uploads the image itself).
+ """
+ # Escape first, substitute second. The `+` stands in for a space so the
+ # avatar draws two initials for `switch_worker`; percent-encoding it after
+ # the fact turns it back into a literal plus and the agent renders with one
+ # initial instead. Agent names are already restricted to characters that
+ # need no escaping, so `quote` is only a guard against a name that somehow
+ # got past that.
+ name = quote(agent_name).replace("_", "+")
+ url = f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
+ return f"{url}&format={image_format}" if image_format else url
+
+
+def normalise_icon_url(url: str | None) -> str | None:
+ """Validate an optional icon URL, treating blank as "no icon".
+
+ Callers accept `None` to mean "leave unset" and an empty string to mean
+ "clear it"; both collapse to `None` so a cleared icon is stored as NULL
+ rather than as an empty string the display layer would have to special-case.
+ """
+ if url is None:
+ return None
+
+ if not url.strip():
+ return None
+
+ return validate_icon_url(url)
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index bd66f2b2d..e70627ea8 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -158,6 +158,7 @@ async def register_agent_endpoint(
result = await protocol.register_agent(
name=req.name,
description=req.description,
+ icon_url=req.icon_url,
connector_type=req.connector_type,
integration_profile=req.integration_profile,
tools=req.tools,
@@ -181,6 +182,7 @@ async def _register_known(
agent_type: str,
name: str,
description: str,
+ icon_url: str | None,
options_raw: dict,
parent_agent_id: str | None,
overwrite: bool,
@@ -214,6 +216,7 @@ async def _register_known(
result = await protocol.register_agent(
name=name,
description=description,
+ icon_url=icon_url,
connector_type=spec.connector_type,
integration_profile=integration_profile,
tools=spec.tools,
@@ -243,6 +246,7 @@ async def register_known_agent_endpoint(
agent_type=req.agent_type,
name=req.name,
description=req.description,
+ icon_url=req.icon_url,
options_raw=req.options,
parent_agent_id=req.parent_agent_id,
overwrite=req.overwrite,
@@ -328,6 +332,11 @@ async def register_known_agents_bulk_endpoint(
agent_type=req.agent_type,
name=name,
description=description,
+ # Subagents deliberately do not inherit the parent's icon: sharing
+ # one would make every child render identically in a list, whereas
+ # no icon lets each fall back to something derived from its own
+ # name. An individual subagent can still be given one afterwards.
+ icon_url=None,
options_raw=options,
parent_agent_id=req.parent_agent_id,
overwrite=req.overwrite,
diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.py
index 1f6669602..5faa1e8dc 100644
--- a/core/switch_core/bridges/agent/api/schemas.py
+++ b/core/switch_core/bridges/agent/api/schemas.py
@@ -20,6 +20,7 @@ from switch_core.bridges.agent.protocol.types import (
class RegisterAgentRequest(BaseModel):
name: str
description: str
+ icon_url: str | None = None
connector_type: str
integration_profile: IntegrationProfile
tools: list[ToolSpec] = []
@@ -37,6 +38,7 @@ class RegisterKnownAgentRequest(BaseModel):
agent_type: str
name: str
description: str
+ icon_url: str | None = None
options: dict[str, Any] = {}
# When set, register this agent as a child of `parent_agent_id` (e.g. a
# Claude Code subagent under the user's main agent). None = top-level.
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index dec1e594b..7930bc4d4 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -1551,9 +1551,10 @@ async def list_agents(
Returns:
A list of agent summaries (sorted by name), each
- {id, name, description, connector_type, connection_model,
+ {id, name, description, icon_url, connector_type, connection_model,
tool_count, model_count, owner_id, owner_name, oauth_client_id,
created_at, parent_agent_id, known_agent_type, known_agent_options}.
+ `icon_url` is null when the agent has no icon set.
Use `get_agent_detail` for the full detail of one agent.
"""
agent_id = get_agent_id()
@@ -1575,11 +1576,12 @@ async def get_agent_detail(agent_id: str) -> dict[str, Any]:
`list_all_rooms`/`get_room_detail`).
Returns:
- {id, name, description, connector_type, connection_model,
+ {id, name, description, icon_url, connector_type, connection_model,
tool_count, model_count, owner_id, owner_name, oauth_client_id,
created_at, parent_agent_id, known_agent_type, known_agent_options,
agent_type, integration_profile, tools, models, rooms, sessions,
children}.
+ `icon_url` is null when the agent has no icon set.
"""
caller_id = get_agent_id()
protocol = get_protocol()
diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.py
index 15722e471..c313850b2 100644
--- a/core/switch_core/bridges/agent/protocol/agent_detail.py
+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py
@@ -61,6 +61,7 @@ async def build_agent_summary(
id=agent.id,
name=agent.name,
description=agent.description,
+ icon_url=agent.icon_url,
connector_type=agent.connector_type,
connection_model=profile.get("connection_model"),
tool_count=len(tools),
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 5c251eb82..071cf89f0 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -26,6 +26,7 @@ from switch_core.addressing import (
owner_only_policy,
parse_policy,
)
+from switch_core.agent_icon import normalise_icon_url, validate_icon_url
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.authz import Action, Principal, require, require_manage
from switch_core.bridges.agent.protocol.agent_detail import (
@@ -187,6 +188,7 @@ class ProtocolService:
*,
name: str,
description: str,
+ icon_url: str | None = None,
connector_type: str,
integration_profile: IntegrationProfile,
tools: list[ToolSpec] | None = None,
@@ -220,9 +222,15 @@ class ProtocolService:
rotates the API key and replaces the integration profile, so callers
must explicitly opt in.
+ ``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.
+
Raises:
ValueError: name is invalid (lowercase alphanumeric, dots, hyphens,
or underscores — no spaces).
+ InvalidIconUrl: ``icon_url`` is malformed or points somewhere unsafe.
AgentExistsError: agent with this name exists and ``overwrite`` is
False.
"""
@@ -232,6 +240,8 @@ class ProtocolService:
"Use only lowercase letters, digits, dots, hyphens, and underscores."
)
+ validated_icon_url = normalise_icon_url(icon_url)
+
tool_specs = tools or []
model_specs = models or []
profile_data = integration_profile.model_dump()
@@ -256,6 +266,7 @@ class ProtocolService:
api_key_hash=api_key_hash,
encrypted_key=encrypted_key,
description=description,
+ icon_url=validated_icon_url,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=profile_data,
@@ -272,6 +283,7 @@ class ProtocolService:
session=session,
name=name,
description=description,
+ icon_url=validated_icon_url,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=profile_data,
@@ -345,6 +357,7 @@ class ProtocolService:
session: AsyncSession,
name: str,
description: str,
+ icon_url: str | None,
agent_type: str,
connector_type: str,
integration_profile: dict[str, Any],
@@ -375,6 +388,7 @@ class ProtocolService:
agent = Agent(
name=name,
description=description,
+ icon_url=icon_url,
agent_type=agent_type,
connector_type=connector_type,
integration_profile=integration_profile,
@@ -424,6 +438,7 @@ class ProtocolService:
api_key_hash: str,
encrypted_key: str,
description: str,
+ icon_url: str | None,
agent_type: str,
connector_type: str,
integration_profile: dict[str, Any],
@@ -444,6 +459,10 @@ class ProtocolService:
await self.api_key_store.create(session, new_api_key_record)
old_api_key_id = existing.api_key_id
+ # An omitted icon keeps whatever the agent already has: re-registration
+ # rotates credentials and rebuilds the profile, and callers that know
+ # nothing about icons must not wipe one the owner chose.
+ icon_fields = {} if icon_url is None else {"icon_url": icon_url}
await self.agent_store.update(
session,
existing.id,
@@ -455,6 +474,7 @@ class ProtocolService:
metadata_=metadata,
oauth_client_id=oauth_client_id,
parent_agent_id=parent_agent_id,
+ **icon_fields,
)
await self.api_key_store.delete(session, old_api_key_id)
@@ -569,6 +589,28 @@ class ProtocolService:
await self.agent_store.update(session, agent_id, **updates)
await session.commit()
+ async def set_agent_icon(self, agent_id: str, icon_url: str | None) -> None:
+ """Set, change, or clear an agent's icon.
+
+ A URL replaces whatever the agent has; ``None`` clears it, leaving the
+ agent with no icon so callers fall back to their own default. This is
+ deliberately a separate operation from ``update_agent`` rather than
+ another optional field on it: there, ``None`` means "leave alone", and
+ an icon needs "remove it" to be sayable.
+
+ Raises:
+ InvalidIconUrl: the URL is malformed or points somewhere unsafe.
+ ValueError: no agent with this id exists.
+ """
+ validated = validate_icon_url(icon_url) if icon_url is not None else None
+
+ async with self.session_factory() as session:
+ agent = await self.agent_store.get(session, agent_id)
+ if agent is None:
+ raise ValueError(f"No such agent: {agent_id}")
+ await self.agent_store.update(session, agent_id, icon_url=validated)
+ await session.commit()
+
async def _remove_bridge_identities(self, agent_name: str) -> None:
for bridge_core in self.collab_lifecycle.all_bridges():
try:
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 16d659f5b..8f680b1c6 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -7,6 +7,7 @@ from collections.abc import Awaitable, Callable
from dataclasses import dataclass, replace
from typing import ClassVar
+from switch_core.agent_icon import default_icon_url
from switch_core.bridges.collaboration.models import (
BridgeInstallLink,
ChannelCreationUnsupported,
@@ -88,6 +89,11 @@ class CollaborationAdapter(ABC):
# Set by set_channel_migration_handler. Called with (old_id, new_id)
# when the platform reissues a channel's id.
self._on_channel_migrated: Callable[[str, str], Awaitable[None]] | None = None
+ # Set by set_agent_icon_resolver. Returns an agent's own icon URL, or
+ # None when it has not been given one. Left unset an adapter still
+ # works — every agent just gets the default — so adapters stay usable
+ # without a bridge core wired up behind them.
+ self._resolve_agent_icon: Callable[[str], Awaitable[str | None]] | None = None
# Inbound attachment size ceiling, set by the lifecycle service from
# config.agent_media_max_bytes. Adapters check a platform-reported file
# size against this before downloading so an oversize file is rejected
@@ -625,3 +631,33 @@ class CollaborationAdapter(ABC):
The symptom without it is one-way traffic — sends still arrive, because
the platform forwards them, while nothing inbound matches a room again."""
self._on_channel_migrated = handler
+
+ def set_agent_icon_resolver(
+ self, resolver: Callable[[str], Awaitable[str | None]]
+ ) -> None:
+ """Install the lookup for an agent's own icon URL (None if it has none).
+
+ The bridge core supplies this because the adapter has no database of
+ its own. Resolution happens per send rather than being cached, so
+ changing an agent's icon shows up on its next message instead of at the
+ next restart."""
+ self._resolve_agent_icon = resolver
+
+ def default_agent_icon(self, agent_name: str) -> str:
+ """The avatar for an agent that has set no icon.
+
+ Overridable for a platform that needs the default in a particular shape
+ — Mattermost uploads the bytes rather than passing a link on, so it
+ pins the response format."""
+ return default_icon_url(agent_name)
+
+ async def agent_icon_url(self, agent_name: str) -> str:
+ """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."""
+ if self._resolve_agent_icon is not None:
+ chosen = await self._resolve_agent_icon(agent_name)
+ if chosen:
+ return chosen
+ return self.default_agent_icon(agent_name)
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 7c62dfe76..6ee788d7e 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -171,6 +171,7 @@ class BridgeCore:
await self._load_channel_map()
await self._load_existing_puppets()
self._adapter.set_channel_migration_handler(self._handle_channel_migrated)
+ self._adapter.set_agent_icon_resolver(self._agent_icon_url)
await self._adapter.start(
on_message=self._handle_inbound_message,
on_command=self._handle_inbound_command,
@@ -255,6 +256,18 @@ class BridgeCore:
# ── Inbound (platform → room) ───────────────────────────────────────────
+ async def _agent_icon_url(self, agent_name: str) -> str | None:
+ """An agent's own icon URL, or None if it has not been given one.
+
+ Installed on the adapter as its icon resolver; None sends the adapter
+ to its existing default. A name matching no agent — an alias, or a bot
+ the platform reports that Switch does not own — also yields None rather
+ than an error, since the caller only wants to know whether to override.
+ """
+ async with self._session_factory() as session:
+ agent = await self._agent_store.get_by_name(session, agent_name)
+ return agent.icon_url if agent else None
+
async def _is_registered_agent(self, name: str) -> bool:
"""Whether `name` is a registered Switch agent. Switch creates each
bridge bot with username == agent name, so a bridged agent's bot
diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.py
index 452731c41..84a5967e4 100644
--- a/core/switch_core/bridges/collaboration/discord/adapter.py
+++ b/core/switch_core/bridges/collaboration/discord/adapter.py
@@ -232,13 +232,6 @@ class DiscordAdapter(CollaborationAdapter):
raise RuntimeError("Discord client not connected")
return self._client
- # ── Agent icon ───────────────────────────────────────────────────────────
-
- @staticmethod
- def _get_agent_icon(agent_name: str) -> str:
- name = agent_name.replace("_", "+")
- return f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
-
# ── Messaging ────────────────────────────────────────────────────────────
async def send_message(
@@ -284,12 +277,16 @@ class DiscordAdapter(CollaborationAdapter):
kwargs: dict[str, Any] = {}
if thread is not None:
kwargs["thread"] = thread
+ # Resolved once here rather than inside the send callback: that callback
+ # is synchronous, and a chunked message would otherwise re-resolve per
+ # chunk and could split one message across two different avatars.
+ avatar_url = await self.agent_icon_url(sender_name)
return await self._send_chunked(
content,
lambda part: webhook.send(
content=part,
username=sender_name,
- avatar_url=self._get_agent_icon(sender_name),
+ avatar_url=avatar_url,
suppress_embeds=True,
wait=True,
**kwargs,
@@ -423,7 +420,7 @@ class DiscordAdapter(CollaborationAdapter):
sent: Any = await webhook.send(
content=body,
username=sender_name,
- avatar_url=self._get_agent_icon(sender_name),
+ avatar_url=await self.agent_icon_url(sender_name),
file=discord.File(io.BytesIO(data), filename=filename),
wait=True,
**kwargs,
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index dc79714cc..aff48ed49 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -18,6 +18,7 @@ import requests as sync_requests
from mattermostdriver import Driver
from mattermostdriver.exceptions import NoAccessTokenProvided
+from switch_core.agent_icon import default_icon_url
from switch_core.bridges.collaboration.adapter import (
CollaborationAdapter,
LiveRuntimeIndicator,
@@ -38,6 +39,11 @@ from switch_core.bridges.collaboration.models import (
logger = logging.getLogger(__name__)
+# Ceiling on a bot icon Switch downloads before re-uploading it to Mattermost.
+# Generously above any real avatar; it exists so a hostile or broken URL cannot
+# stream unbounded data into memory.
+_MAX_BOT_ICON_BYTES = 5 * 1024 * 1024
+
class MattermostConnectionConfig(BridgeConnectionConfig):
url: str
@@ -964,18 +970,37 @@ class MattermostAdapter(CollaborationAdapter):
# ── Bot icons ────────────────────────────────────────────────────────────
+ def default_agent_icon(self, agent_name: str) -> str:
+ # Mattermost uploads the image itself rather than passing a link on, so
+ # the response has to be a PNG it can accept.
+ return default_icon_url(agent_name, image_format="png")
+
async def _set_bot_icon(self, bot_id: str, agent_name: str) -> None:
if not self._admin_driver or not self._main_loop:
logger.error("[BOT-ICON] skipping %s: no driver or loop", agent_name)
return
driver = self._admin_driver
try:
- url = f"https://ui-avatars.com/api/?name={agent_name}&background=random&size=128&format=png"
+ url = await self.agent_icon_url(agent_name)
logger.debug("[BOT-ICON] fetching avatar for %s", agent_name)
- async with httpx.AsyncClient() as client:
- resp = await client.get(url)
+ # This is the one place Switch dereferences an agent's icon URL
+ # rather than handing it to a platform, so the fetch is bounded:
+ # redirects off (a permitted host could otherwise bounce us to an
+ # internal one, which validation at write time cannot foresee) and
+ # a size ceiling so a hostile response cannot be read unbounded.
+ async with httpx.AsyncClient(follow_redirects=False) as client:
+ resp = await client.get(url, timeout=10.0)
resp.raise_for_status()
image_bytes = resp.content
+ if len(image_bytes) > _MAX_BOT_ICON_BYTES:
+ logger.error(
+ "[BOT-ICON] icon for %s is %d bytes, over the %d limit — "
+ "leaving the current icon in place",
+ agent_name,
+ len(image_bytes),
+ _MAX_BOT_ICON_BYTES,
+ )
+ return
logger.debug(
"[BOT-ICON] fetched %d bytes for %s", len(image_bytes), agent_name
)
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 98418fbcb..d245bbf29 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -127,13 +127,6 @@ class SlackAdapter(CollaborationAdapter):
self._web_client = None
logger.info("Slack adapter stopped")
- # ── Agent icon ───────────────────────────────────────────────────────────
-
- @staticmethod
- def _get_agent_icon(agent_name: str) -> str:
- name = agent_name.replace("_", "+")
- return f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
-
# ── Messaging ────────────────────────────────────────────────────────────
async def send_message(
@@ -164,7 +157,7 @@ class SlackAdapter(CollaborationAdapter):
channel=channel_id,
text=self.translate_outbound(content),
username=sender_name,
- icon_url=self._get_agent_icon(sender_name),
+ icon_url=await self.agent_icon_url(sender_name),
thread_ts=thread_ts,
unfurl_links=False,
unfurl_media=False,
@@ -433,7 +426,7 @@ class SlackAdapter(CollaborationAdapter):
channel=channel_id,
text="_thinking..._",
username=sender_name,
- icon_url=self._get_agent_icon(sender_name),
+ icon_url=await self.agent_icon_url(sender_name),
thread_ts=thread_ts,
)
ts = result.get("ts")
diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.py
index 6a8501c11..6a7bea1fb 100644
--- a/core/switch_core/bridges/collaboration/teams/adapter.py
+++ b/core/switch_core/bridges/collaboration/teams/adapter.py
@@ -393,13 +393,16 @@ class TeamsAdapter(CollaborationAdapter):
def _thread_conversation(channel_id: str, root_id: str) -> str:
return f"{channel_id};messageid={root_id}"
- def _message_activity(self, sender_name: str, body: str) -> dict[str, Any]:
+ async def _message_activity(self, sender_name: str, body: str) -> dict[str, Any]:
+ icon_url = await self.agent_icon_url(sender_name)
return {
"type": "message",
# Notification/preview text; without it Teams renders a
# "cards.unsupported" placeholder in toasts, mobile, and link previews.
"summary": f"{sender_name}: {body}",
- "attachments": [card_attachment(agent_message_card(sender_name, body))],
+ "attachments": [
+ card_attachment(agent_message_card(sender_name, body, icon_url))
+ ],
}
# ── Messaging ────────────────────────────────────────────────────────────
@@ -415,7 +418,9 @@ class TeamsAdapter(CollaborationAdapter):
raise RuntimeError("Cannot send message: Teams adapter not started")
service_url = self._service_url_for(channel_id)
- activity = self._message_activity(sender_name, self.translate_outbound(content))
+ activity = await self._message_activity(
+ sender_name, self.translate_outbound(content)
+ )
if self._is_channel(channel_id) and thread_root_id is None:
conversation_id, msg_id = await self._connector.create_channel_thread(
@@ -592,7 +597,7 @@ class TeamsAdapter(CollaborationAdapter):
service_url=service_url,
conversation_id=conversation_id,
activity_id=message_ref,
- activity=self._message_activity(agent_name, body),
+ activity=await self._message_activity(agent_name, body),
)
async def _clear_working(self, channel_id: str, agent_name: str) -> None:
diff --git a/core/switch_core/bridges/collaboration/teams/cards.py b/core/switch_core/bridges/collaboration/teams/cards.py
index 95e70a1e5..de8f5e0d4 100644
--- a/core/switch_core/bridges/collaboration/teams/cards.py
+++ b/core/switch_core/bridges/collaboration/teams/cards.py
@@ -1,26 +1,21 @@
from __future__ import annotations
from typing import Any
-from urllib.parse import quote
ADAPTIVE_CARD_CONTENT_TYPE = "application/vnd.microsoft.card.adaptive"
-def agent_icon_url(agent_name: str) -> str:
- """A stable generated avatar for an agent, matching the Slack adapter's
- scheme so the same agent looks the same across bridged platforms."""
- name = quote(agent_name.replace("_", "+"))
- return f"https://ui-avatars.com/api/?name={name}&background=random&size=128"
-
-
-def agent_message_card(agent_name: str, body: str) -> dict[str, Any]:
+def agent_message_card(agent_name: str, body: str, icon_url: str) -> dict[str, Any]:
"""An Adaptive Card that labels a message with the sending agent's identity.
Teams has a single bot identity and no per-message username override (unlike
Slack), so each Switch agent is presented as a card whose header carries the
agent's avatar + name, with the message body beneath. ``body`` should already
be run through ``translate_outbound`` (Adaptive Card TextBlocks render a
- markdown subset: bold, italic, links, lists)."""
+ markdown subset: bold, italic, links, lists).
+
+ ``icon_url`` is resolved by the caller — the agent's own icon or the shared
+ default — because looking it up is async and this builder is not."""
return {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
@@ -39,7 +34,7 @@ def agent_message_card(agent_name: str, body: str) -> dict[str, Any]:
"items": [
{
"type": "Image",
- "url": agent_icon_url(agent_name),
+ "url": icon_url,
"size": "Small",
"style": "Person",
"altText": agent_name,
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 304653762..0599a658d 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -99,6 +99,12 @@ class Agent(Base):
id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
name: Mapped[str] = mapped_column(Text, unique=True, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
+ # Absolute https URL of the agent's icon (CHOO-2171). Switch stores the
+ # link, never image bytes: whatever produces the picture — a generated-
+ # avatar service, the operator's own host — is the client's concern. NULL
+ # means no icon was chosen, and the display layer supplies the fallback, so
+ # that fallback can change without touching stored rows.
+ icon_url: Mapped[str | None] = mapped_column(Text, nullable=True)
agent_type: Mapped[str] = mapped_column(Text, nullable=False)
connector_type: Mapped[str] = mapped_column(Text, nullable=False)
integration_profile: Mapped[dict] = mapped_column(JSONB, nullable=False)
diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.py
index 36c8784bc..7ed680c0b 100644
--- a/core/switch_core/gateway/agents.py
+++ b/core/switch_core/gateway/agents.py
@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.agent_icon import InvalidIconUrl, normalise_icon_url
from switch_core.authz import Principal, require_manage
from switch_core.bridges.agent.protocol.agent_detail import (
AgentOptionsNotEditable,
@@ -44,6 +45,7 @@ from switch_core.gateway.schemas import (
RegisterKnownSubagentsResponse,
RegisterOtherAgentRequest,
UpdateAddressingPolicyRequest,
+ UpdateAgentIconRequest,
UpdateAgentOptionsRequest,
)
from switch_core.gateway.subagent_registration import derive_subagent_registrations
@@ -158,6 +160,7 @@ async def register_known_agent(
result = await protocol.register_agent(
name=req.name,
description=req.description,
+ icon_url=req.icon_url,
connector_type=spec.connector_type,
integration_profile=integration_profile,
tools=spec.tools,
@@ -169,6 +172,7 @@ async def register_known_agent(
except AgentExistsError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except ValueError as exc:
+ # Covers InvalidIconUrl, which subclasses ValueError.
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RegisterAgentResponse(
@@ -337,6 +341,59 @@ async def update_agent_options(
return await build_agent_summary(session, agent_store, agent, owner_name)
[email protected]("/{agent_id}/icon")
+async def update_agent_icon(
+ agent_id: str,
+ req: UpdateAgentIconRequest,
+ session: Annotated[AsyncSession, Depends(get_session)],
+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],
+ user: Annotated[User, Depends(get_current_user)],
+) -> AgentSummary:
+ """Set, change, or clear an agent's icon (CHOO-2171).
+
+ ``icon_url: null`` clears it, leaving the agent with no icon so the caller
+ renders its own fallback. Only the agent's owner (or an admin) may change
+ it. Unlike options, this applies to every agent regardless of how it was
+ registered.
+
+ The URL must be an absolute https address that is not the local machine or
+ 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.
+ """
+ agent = await agent_store.get(session, agent_id)
+ if agent is None:
+ raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")
+
+ try:
+ require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)
+ except PermissionError:
+ raise HTTPException(
+ status_code=403,
+ detail="Only the agent's owner or an admin can change its icon.",
+ )
+
+ try:
+ icon_url = normalise_icon_url(req.icon_url)
+ except InvalidIconUrl as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ await agent_store.update(session, agent_id, icon_url=icon_url)
+ await session.commit()
+ await session.refresh(agent)
+
+ logger.info(
+ "%s agent %s icon by user %s",
+ "Cleared" if icon_url is None else "Set",
+ agent.name,
+ user.name,
+ )
+
+ owner_name = user.name if agent.owner_id == user.id else None
+ return await build_agent_summary(session, agent_store, agent, owner_name)
+
+
@router.post("/register-other")
async def register_other_agent(
req: RegisterOtherAgentRequest,
@@ -358,6 +415,7 @@ async def register_other_agent(
result = await protocol.register_agent(
name=req.name,
description=req.description,
+ icon_url=req.icon_url,
connector_type="external",
integration_profile=default_profile,
owner_id=user.id,
@@ -366,6 +424,7 @@ async def register_other_agent(
except AgentExistsError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except ValueError as exc:
+ # Covers InvalidIconUrl, which subclasses ValueError.
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RegisterAgentResponse(
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index fcae15397..896002106 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -214,6 +214,10 @@ class AgentSummary(BaseModel):
id: str
name: str
description: str
+ # Absolute https URL of the agent's icon, or null when none is set. Null is
+ # not an error: the caller renders its own fallback rather than Switch
+ # inventing a default, so the fallback can change without a data migration.
+ icon_url: str | None = None
connector_type: str
connection_model: str | None
tool_count: int
@@ -303,6 +307,17 @@ class UpdateAddressingPolicyRequest(BaseModel):
policy: AddressingPolicy | None = None
+class UpdateAgentIconRequest(BaseModel):
+ """Set (or clear) an agent's icon.
+
+ ``icon_url: null`` clears it — the agent falls back to whatever default the
+ caller renders. The field is required rather than defaulted so that
+ clearing an icon is always something the client said, never something it
+ forgot to send."""
+
+ icon_url: str | None
+
+
class KnownAgentType(BaseModel):
key: str
connector_type: str
@@ -314,6 +329,10 @@ class RegisterKnownAgentRequest(BaseModel):
agent_type: str
name: str
description: str
+ # Optional at registration: an agent may be given its icon later, and a
+ # re-registration that omits it keeps whatever icon the agent already has
+ # rather than clearing it.
+ icon_url: str | None = None
options: dict[str, Any] = {}
overwrite: bool = False
@@ -373,6 +392,7 @@ class UpdateAgentOptionsRequest(BaseModel):
class RegisterOtherAgentRequest(BaseModel):
name: str
description: str
+ icon_url: str | None = None
overwrite: bool = False
diff --git a/core/switch_core/migrations/versions/a2171c0de1f4_add_icon_url_to_agents.py b/core/switch_core/migrations/versions/a2171c0de1f4_add_icon_url_to_agents.py
new file mode 100644
index 000000000..e3fba7eeb
--- /dev/null
+++ b/core/switch_core/migrations/versions/a2171c0de1f4_add_icon_url_to_agents.py
@@ -0,0 +1,26 @@
+"""add icon_url to agents (CHOO-2171)
+
+Revision ID: a2171c0de1f4
+Revises: c2137e4a9b7d
+Create Date: 2026-08-16 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "a2171c0de1f4"
+down_revision: str | None = "c2137e4a9b7d"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("agents", sa.Column("icon_url", sa.Text(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("agents", "icon_url")
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
new file mode 100644
index 000000000..948089706
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
@@ -0,0 +1,137 @@
+"""An agent's own icon reaches the collaboration bridges (CHOO-2171).
+
+The bridges are where an icon is actually seen by people, and the adapters hold
+no database, so the bridge core supplies the lookup. These pin the two halves:
+the core answering with the agent's icon (or nothing), and the adapter choosing
+between that answer and the default it has always generated.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from switch_core.agent_icon import default_icon_url
+from switch_core.bridges.collaboration.adapter import CollaborationAdapter
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+
+_CUSTOM = "https://cdn.example.com/9.x/bottts/png?seed=chosen"
+
+
+class _Session:
+ async def __aenter__(self) -> _Session:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+
+class _AgentStore:
+ def __init__(self, agents: dict[str, SimpleNamespace]) -> None:
+ self._agents = agents
+
+ async def get_by_name(self, session: Any, name: str) -> SimpleNamespace | None:
+ return self._agents.get(name)
+
+
+def _bridge(agents: dict[str, SimpleNamespace]) -> BridgeCore:
+ bridge = BridgeCore.__new__(BridgeCore)
+ bridge._agent_store = _AgentStore(agents) # type: ignore[assignment]
+ bridge._session_factory = _Session # type: ignore[assignment]
+ return bridge
+
+
+def _agent(icon_url: str | None) -> SimpleNamespace:
+ return SimpleNamespace(name="worker", icon_url=icon_url)
+
+
+class _Adapter(CollaborationAdapter):
+ """Concrete only so it can be instantiated — the icon plumbing under test
+ lives entirely on the base class, and none of the platform methods are
+ called here."""
+
+ async def start(self, *a: Any, **k: Any) -> Any: ...
+ async def stop(self, *a: Any, **k: Any) -> Any: ...
+ async def send_message(self, *a: Any, **k: Any) -> Any: ...
+ async def send_typing(self, *a: Any, **k: Any) -> Any: ...
+ async def update_message(self, *a: Any, **k: Any) -> Any: ...
+ async def delete_message(self, *a: Any, **k: Any) -> Any: ...
+ async def create_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_type(self, *a: Any, **k: Any) -> Any: ...
+ async def get_channel_agent_names(self, *a: Any, **k: Any) -> Any: ...
+ async def add_agents_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def add_users_to_channel(self, *a: Any, **k: Any) -> Any: ...
+ async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...
+ def translate_inbound(self, *a: Any, **k: Any) -> Any: ...
+ def translate_outbound(self, *a: Any, **k: Any) -> Any: ...
+
+
+class TestBridgeCoreResolver:
+ async def test_returns_the_agents_own_icon(self) -> None:
+ bridge = _bridge({"worker": _agent(_CUSTOM)})
+ assert await bridge._agent_icon_url("worker") == _CUSTOM
+
+ async def test_returns_none_when_the_agent_has_no_icon(self) -> None:
+ """None, not a default — choosing the default is the adapter's job, so
+ each platform keeps the one it has always produced."""
+ bridge = _bridge({"worker": _agent(None)})
+ assert await bridge._agent_icon_url("worker") is None
+
+ async def test_returns_none_for_a_name_that_is_not_an_agent(self) -> None:
+ """Bridges also render aliases and third-party bots. An unknown name is
+ not an error here — the caller only wants to know whether to override."""
+ bridge = _bridge({})
+ assert await bridge._agent_icon_url("some-slack-bot") is None
+
+
+class TestAdapterIconSelection:
+ async def test_uses_the_default_when_no_resolver_is_installed(self) -> None:
+ adapter = _Adapter()
+ assert await adapter.agent_icon_url("worker") == default_icon_url("worker")
+
+ async def test_prefers_the_agents_own_icon(self) -> None:
+ adapter = _Adapter()
+
+ async def resolver(name: str) -> str | None:
+ return _CUSTOM
+
+ adapter.set_agent_icon_resolver(resolver)
+ 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()
+
+ async def resolver(name: str) -> str | None:
+ return None
+
+ adapter.set_agent_icon_resolver(resolver)
+ assert await adapter.agent_icon_url("worker") == default_icon_url("worker")
+
+ async def test_an_end_to_end_override_through_the_bridge_resolver(self) -> None:
+ """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.set_agent_icon_resolver(bridge._agent_icon_url)
+
+ assert await adapter.agent_icon_url("worker") == _CUSTOM
+ assert await adapter.agent_icon_url("plain") == default_icon_url("plain")
+
+
+class TestDefaultIcon:
+ async def test_is_stable_for_a_given_name(self) -> None:
+ assert default_icon_url("worker") == default_icon_url("worker")
+
+ async def test_differs_between_agents(self) -> None:
+ assert default_icon_url("worker") != default_icon_url("manager")
+
+ async def test_underscores_become_word_separators(self) -> None:
+ """The avatar draws initials, so `a_b` has to read as two words rather
+ than one — this is the behaviour the bridges already relied on."""
+ assert "a+b" in default_icon_url("a_b")
+
+ async def test_format_override_is_appended_for_callers_that_need_bytes(
+ self,
+ ) -> None:
+ assert default_icon_url("worker", image_format="png").endswith("&format=png")
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
index 1e678062f..710ca695c 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py
@@ -84,6 +84,11 @@ def test_the_handler_is_installed_before_the_adapter_starts() -> None:
def set_channel_migration_handler(self, handler: Any) -> None:
installed.append(handler)
+ def set_agent_icon_resolver(self, resolver: Any) -> None:
+ # Not what this test is about; present so the stub satisfies what
+ # `start` installs on its adapter.
+ return None
+
async def start(self, **kwargs: Any) -> None:
started.append("started")
assert installed, "the handler must be installed before start()"
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 82b81c20c..779a936aa 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
from typing import Any
+from switch_core.agent_icon import default_icon_url
from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
@@ -820,25 +821,57 @@ def test_typing_false_is_noop() -> None:
def test_agent_card_carries_name_and_body() -> None:
- card = agent_message_card("worker", "the message body")
+ card = agent_message_card("worker", "the message body", "https://example.com/i.png")
# Name appears in the header column; body appears as its own TextBlock.
header = card["body"][0]["columns"][1]["items"][0]
assert header["text"] == "worker"
assert card["body"][1]["text"] == "the message body"
-def test_message_activity_carries_notification_summary_and_fallback() -> None:
+def test_agent_card_renders_the_supplied_icon() -> None:
+ card = agent_message_card("worker", "body", "https://example.com/custom.png")
+ image = card["body"][0]["columns"][0]["items"][0]
+ assert image["url"] == "https://example.com/custom.png"
+
+
+async def test_message_activity_carries_notification_summary_and_fallback() -> None:
# Without a plain-text summary on the activity and a fallbackText on the card,
# Teams renders a "cards.unsupported" placeholder in notifications, mobile, and
# link/search previews.
adapter = _adapter()
- activity = adapter._message_activity("worker", "hello world")
+ activity = await adapter._message_activity("worker", "hello world")
assert activity["summary"] == "worker: hello world"
assert (
activity["attachments"][0]["content"]["fallbackText"] == "worker: hello world"
)
+async def test_message_activity_uses_the_agents_own_icon_when_it_has_one() -> None:
+ adapter = _adapter()
+
+ async def _resolver(agent_name: str) -> str | None:
+ return "https://example.com/worker.png" if agent_name == "worker" else None
+
+ adapter.set_agent_icon_resolver(_resolver)
+ activity = await adapter._message_activity("worker", "hello")
+
+ image = activity["attachments"][0]["content"]["body"][0]["columns"][0]["items"][0]
+ assert image["url"] == "https://example.com/worker.png"
+
+
+async def test_message_activity_falls_back_to_the_default_icon() -> None:
+ adapter = _adapter()
+
+ async def _resolver(agent_name: str) -> str | None:
+ return None
+
+ adapter.set_agent_icon_resolver(_resolver)
+ activity = await adapter._message_activity("worker", "hello")
+
+ image = activity["attachments"][0]["content"]["body"][0]["columns"][0]["items"][0]
+ assert image["url"] == default_icon_url("worker")
+
+
# ── Runtime state ────────────────────────────────────────────────────────────
diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.py
new file mode 100644
index 000000000..e564043f5
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py
@@ -0,0 +1,271 @@
+"""The gateway route that sets, changes, and clears an agent's icon (CHOO-2171).
+
+Exercised against real Postgres with real stores, like the other gateway route
+tests. What matters here is that ownership is enforced, that an unsafe URL is
+refused at write time rather than stored to fail later, and that clearing is
+expressible and lands as NULL.
+"""
+
+from __future__ import annotations
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Agent, ApiKey, Client, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.gateway.agents import update_agent_icon
+from switch_core.gateway.schemas import UpdateAgentIconRequest
+
+_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"
+
+
+async def _add_user(session: AsyncSession, *, name: str, role: str = "user") -> User:
+ user = User(name=name, email=f"{name}@example.com", role=role)
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def _add_agent(
+ session: AsyncSession,
+ *,
+ name: str,
+ owner_id: str | None,
+ icon_url: str | None = None,
+) -> Agent:
+ client = Client(
+ type="agent",
+ matrix_user_id=f"@{name}:test",
+ display_name=name,
+ password=f"pw-{name}",
+ )
+ session.add(client)
+ await session.flush()
+
+ api_key = ApiKey(
+ type="agent",
+ key_hash=f"hash-{name}",
+ encrypted_key=f"enc-{name}",
+ label=name,
+ user_id=owner_id,
+ )
+ session.add(api_key)
+ await session.flush()
+
+ agent = Agent(
+ name=name,
+ description=f"{name} desc",
+ icon_url=icon_url,
+ agent_type="session_passive",
+ connector_type="external",
+ integration_profile={"connection_model": "session_passive"},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ owner_id=owner_id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
+
+
+class TestUpdateAgentIcon:
+ async def test_owner_can_set_an_icon(
+ 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,
+ )
+
+ assert summary.icon_url == _ICON
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url == _ICON
+
+ async def test_owner_can_change_an_existing_icon(
+ 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, icon_url=_ICON
+ )
+
+ summary = await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=_OTHER_ICON),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.icon_url == _OTHER_ICON
+
+ async def test_null_clears_the_icon(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Clearing has to be expressible — the whole reason this is a separate
+ route rather than another optional field on the agent update."""
+ async with session_factory() as session:
+ owner = await _add_user(session, name="owner")
+ agent = await _add_agent(
+ session, name="a1", owner_id=owner.id, icon_url=_ICON
+ )
+
+ summary = await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=None),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.icon_url is None
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url is None
+
+ async def test_blank_string_clears_rather_than_storing_empty(
+ 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, icon_url=_ICON
+ )
+
+ summary = await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=" "),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert summary.icon_url is None
+
+ async def test_non_owner_is_refused(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await _add_user(session, name="owner")
+ other = await _add_user(session, name="other")
+ agent = await _add_agent(session, name="a1", owner_id=owner.id)
+
+ with pytest.raises(HTTPException) as exc:
+ await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=_ICON),
+ session,
+ _AGENT_STORE,
+ other,
+ )
+
+ assert exc.value.status_code == 403
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url is None
+
+ async def test_admin_can_set_an_icon_on_an_agent_they_do_not_own(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await _add_user(session, name="owner")
+ admin = await _add_user(session, name="admin", role="admin")
+ 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,
+ admin,
+ )
+
+ assert summary.icon_url == _ICON
+
+ async def test_unknown_agent_is_404(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ owner = await _add_user(session, name="owner")
+
+ with pytest.raises(HTTPException) as exc:
+ await update_agent_icon(
+ "no-such-agent",
+ UpdateAgentIconRequest(icon_url=_ICON),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert exc.value.status_code == 404
+
+ @pytest.mark.parametrize(
+ "bad_url",
+ [
+ "http://cdn.example.com/i.png",
+ "javascript:alert(1)",
+ "https://127.0.0.1/i.png",
+ "https://169.254.169.254/latest/meta-data/",
+ "https://localhost/i.png",
+ ],
+ )
+ async def test_unsafe_url_is_rejected_and_nothing_is_stored(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ bad_url: str,
+ ) -> None:
+ """Refused at write time, not stored to break later at render time —
+ and never stored at all, since Switch itself dereferences the URL when
+ a bridge needs the image as bytes."""
+ 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 exc:
+ await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url=bad_url),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ assert exc.value.status_code == 400
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url is None
+
+ async def test_a_rejected_change_leaves_the_previous_icon_intact(
+ 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, icon_url=_ICON
+ )
+
+ with pytest.raises(HTTPException):
+ await update_agent_icon(
+ agent.id,
+ UpdateAgentIconRequest(icon_url="https://192.168.0.9/i.png"),
+ session,
+ _AGENT_STORE,
+ owner,
+ )
+
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url == _ICON
diff --git a/core/tests/switch_core/test_agent_icon.py b/core/tests/switch_core/test_agent_icon.py
new file mode 100644
index 000000000..836e9102c
--- /dev/null
+++ b/core/tests/switch_core/test_agent_icon.py
@@ -0,0 +1,144 @@
+"""Icon URL validation (CHOO-2171).
+
+The rejection cases matter more than the acceptance ones: the Mattermost
+adapter fetches an agent's icon server-side, so a stored URL is a request
+Switch will make on behalf of whoever typed it.
+"""
+
+import pytest
+
+from switch_core.agent_icon import (
+ MAX_ICON_URL_LENGTH,
+ InvalidIconUrl,
+ normalise_icon_url,
+ validate_icon_url,
+)
+
+
+ "url",
+ [
+ "https://example.com/icon.png",
+ "https://cdn.example.com/9.x/bottts/png?seed=switch-worker&size=200",
+ "https://example.com:8443/a/b/c.svg",
+ # Literal IPs are allowed when genuinely routable. Note the documentation
+ # ranges (198.51.100.0/24, 2001:db8::/32) are NOT usable as stand-ins
+ # here — Python classifies them private, so they are refused.
+ "https://8.8.8.8/icon.png",
+ "https://[2606:4700:4700::1111]/icon.png",
+ ],
+)
+def test_accepts_public_https_urls(url: str) -> None:
+ assert validate_icon_url(url) == url
+
+
+ "url",
+ [
+ " https://example.com/i.png ",
+ "https://example.com/i.png\n",
+ "\thttps://example.com/i.png",
+ ],
+)
+def test_strips_surrounding_whitespace(url: str) -> None:
+ """Surrounding whitespace is trimmed, including a trailing newline from a
+ copy-paste. Whitespace *inside* the URL is a different matter — see below."""
+ assert validate_icon_url(url) == "https://example.com/i.png"
+
+
+ "url",
+ [
+ "http://example.com/icon.png",
+ "javascript:alert(1)",
+ "data:image/svg+xml,<svg onload=alert(1)/>",
+ "file:///etc/passwd",
+ "ftp://example.com/icon.png",
+ "//example.com/icon.png",
+ "example.com/icon.png",
+ ],
+)
+def test_rejects_non_https_schemes(url: str) -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(url)
+
+
+ "url",
+ [
+ "https://localhost/icon.png",
+ "https://LOCALHOST/icon.png",
+ "https://127.0.0.1/icon.png",
+ "https://127.13.13.13/icon.png",
+ "https://10.0.0.5/icon.png",
+ "https://192.168.1.1/icon.png",
+ "https://172.16.4.2/icon.png",
+ "https://169.254.169.254/latest/meta-data/",
+ "https://[::1]/icon.png",
+ "https://[fe80::1]/icon.png",
+ "https://0.0.0.0/icon.png",
+ ],
+)
+def test_rejects_internal_addresses(url: str) -> None:
+ """A URL naming the host or its private network would turn the
+ Mattermost avatar fetch into an internal probe."""
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(url)
+
+
+def test_rejects_embedded_credentials() -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url("https://user:[email protected]/icon.png")
+
+
+def test_rejects_missing_hostname() -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url("https:///icon.png")
+
+
+def test_rejects_overlong_url() -> None:
+ too_long = "https://example.com/" + ("a" * MAX_ICON_URL_LENGTH)
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(too_long)
+
+
+def test_accepts_url_at_the_length_limit() -> None:
+ prefix = "https://example.com/"
+ exact = prefix + "a" * (MAX_ICON_URL_LENGTH - len(prefix))
+ assert len(exact) == MAX_ICON_URL_LENGTH
+ assert validate_icon_url(exact) == exact
+
+
+ "url",
+ [
+ "https://example.com/ic on.png",
+ "https://exa\tmple.com/icon.png",
+ "https://example.com/icon.png\r\nHost: evil",
+ "https://example.com/ic\x00on.png",
+ ],
+)
+def test_rejects_internal_whitespace_and_control_characters(url: str) -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(url)
+
+
[email protected]("blank", ["", " ", "\t"])
+def test_rejects_blank(blank: str) -> None:
+ with pytest.raises(InvalidIconUrl):
+ validate_icon_url(blank)
+
+
[email protected]("blank", [None, "", " "])
+def test_normalise_collapses_absent_and_blank_to_none(blank: str | None) -> None:
+ """One stored representation for "no icon" — NULL — so the display layer
+ never has to distinguish a missing icon from an empty string."""
+ assert normalise_icon_url(blank) is None
+
+
+def test_normalise_validates_a_present_url() -> None:
+ assert normalise_icon_url(" https://example.com/i.png ") == (
+ "https://example.com/i.png"
+ )
+ with pytest.raises(InvalidIconUrl):
+ normalise_icon_url("http://10.0.0.1/i.png")