Skip to content

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

[CHOO-3189] Agent icons: switch to DiceBear gaze; fix a Console reset race (#685)

Christian McDermott4f8a428ec79e
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
index f285bbe7b..31954c45c 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.test.ts
@@ -152,7 +152,7 @@ describe('backfillAgentIcons', () => {
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.
+ // has to be told, because the app draws its own avatars and looks correct.
given([agent({ id: 'a-1' }), agent({ id: 'a-2' })]);
updateAgentIcon.mockRejectedValue(new FakeGatewayError('http', 'not found', 404));
const backfill = await loadFresh();
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
index fa6d64e26..bad19502b 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/backfill-agent-icons.ts
@@ -5,14 +5,14 @@ import type { AgentIconBackfill, SwitchServer } from '@shared/core/switch-server
import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';
/**
- * Give the signed-in user's existing agents the bot avatar their name generates
+ * Give the signed-in user's existing agents the 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.
+ * Agents registered before icons existed have none. A current Switch server
+ * draws those with the same name-generated avatar this app does, but an older
+ * one draws a lettered badge on the chat platforms instead. This writes the
+ * avatar in, so an agent this app manages looks the same in the app as it does
+ * in Slack whichever server it is on.
*
* Only agents this install manages are touched, and only those with no icon at
* all — a chosen icon is never overwritten.
@@ -24,10 +24,10 @@ import { fetchAgents, GatewayError, updateAgentIcon } from './gateway-client';
* call, and a refusal is taken as "not yours" rather than argued with.
*
* **The outcome is reported rather than logged and forgotten.** The app draws a
- * name-derived 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.
+ * name-derived avatar for any agent the server has no icon for, so on an older
+ * server a failed write leaves the app looking correct while the chat platforms
+ * — which ask the server — still show the lettered badge. Nothing on screen
+ * would say why, so the caller is handed what happened and tells the user.
*/
export function backfillAgentIcons(
workspaceId: string,
@@ -116,7 +116,7 @@ async function writeMissingIcons(
}
if (failures.length > 0) {
- log.warn('agent icon backfill: some agents kept the lettered avatar', {
+ log.warn('agent icon backfill: some agents could not be given an icon', {
event: 'agent_icon_backfill',
workspaceId,
serverId: server.id,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
index c2ba81298..8af0fe473 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/command-palette/palette-agent-item.tsx
@@ -16,7 +16,7 @@ import { PALETTE_ITEM_CLASS } from './palette-item-styles';
* A row of its own rather than a branch of `PaletteKindIcon`, because the
* chosen icon comes from a query keyed by workspace and a hook cannot be called
* from inside a switch. An agent this app does not hold — a hit whose local row
- * has gone — still gets the bot drawn from its name, which is the same face the
+ * has gone — still gets the avatar drawn from its name, which is the same face the
* Switch bridges show.
*/
export const PaletteAgentItem = observer(function PaletteAgentItem({
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 a5e875889..71f2ec223 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
@@ -177,7 +177,7 @@ async function giveExistingAgentsAnIcon(): Promise<void> {
reportOnce(workspaceId, 'failed', {
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.',
+ 'Your agents show a generated icon here, but the Switch server has not stored it, so Slack and the other chat apps may still show their old picture.',
variant: 'destructive',
});
}
@@ -221,7 +221,7 @@ function reportBackfill(workspaceId: string, outcome: AgentIconBackfill): void {
reportOnce(workspaceId, `partial:${outcome.failed}`, {
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.',
+ 'Their icon could not be saved to the Switch server, so Slack and the other chat apps may still show their old picture.',
variant: 'destructive',
});
return;
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
index f70b1a7ab..125652118 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-avatar.tsx
@@ -11,7 +11,7 @@ import { agentAvatarUrlForName, agentInitials } from '@shared/core/agents/agent-
*
* Three states, in order:
* - the icon its owner chose;
- * - failing that, a bot drawn from its name, which is also what the Switch
+ * - failing that, an avatar drawn from its name, which is also what the Switch
* bridges show, so the app and Slack agree;
* - failing *that* — an image that will not load, most often because the
* machine is offline — its initials. Deliberately visible rather than a
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
index 7cdf6b094..804dfc1b6 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
@@ -17,12 +17,12 @@ const TABS: readonly { value: PickerTab; label: string }[] = [
];
/**
- * Choose an agent's picture (CHOO-2171): one of a set of generated bots, or a
+ * Choose an agent's picture (CHOO-2171): one of a set of generated avatars, or a
* link to an image of the reader's own.
*
* `iconUrl` is null when nothing has been chosen, and the agent then wears the
* avatar its name generates — the state the ✕ returns to. A new agent does not
- * start there: it opens on a concrete random bot, since an unnamed agent has no
+ * start there: it opens on a concrete random avatar, since an unnamed agent has no
* name to draw from.
*/
export function AgentIconPicker({
@@ -50,7 +50,7 @@ export function AgentIconPicker({
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.
+ // the same face drawn from the empty string.
const seedName = name.trim() || 'agent';
// The server generates the icons on offer, so every client offers the same
// ones and an agent created anywhere looks the same.
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
index 8a1859a96..d74dacd12 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
@@ -27,7 +27,7 @@ export function useWorkspaceAgents(workspaceId: string | null) {
* 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
+ * draws an avatar 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(
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
index 3b56e2904..e388ba1a9 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
@@ -54,7 +54,7 @@ async function initialIcon(): Promise<{ iconUrl: string | null; iconIsGenerated:
describe('a new agent', () => {
it('starts on a concrete generated icon', async () => {
const { iconUrl } = await initialIcon();
- expect(iconUrl).toContain('/bottts/png?');
+ expect(iconUrl).toContain('/gaze/png?');
});
it('counts that icon as generated rather than chosen', async () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
index 44be7df70..ebd8ceaf0 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/palette-agent-icon.test.tsx
@@ -140,9 +140,9 @@ describe('an agent in search', () => {
expect(src).toBe('https://icons.example/reviewer.png');
});
- it('falls back to the bot drawn from its name, not its provider logo', async () => {
+ it('falls back to the face drawn from its name, not its provider logo', async () => {
const src = await rowAvatarSrc({ known: true, iconUrl: null });
- expect(src).toContain('/bottts/png?');
+ expect(src).toContain('/gaze/png?');
expect(src).toContain(AGENT_NAME);
});
@@ -150,6 +150,6 @@ describe('an agent in search', () => {
// The lookup that used to supply the provider id can miss — a stale index
// entry, an agent removed since. A miss must not leave the row blank.
const src = await rowAvatarSrc({ known: false, iconUrl: null });
- expect(src).toContain('/bottts/png?');
+ expect(src).toContain('/gaze/png?');
});
});
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
index 341bf37a1..f0c8422a5 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
@@ -9,7 +9,7 @@ import {
} from './agent-avatar';
describe('randomAgentAvatarUrl', () => {
- it('draws a different bot each time', () => {
+ it('draws a different face each time', () => {
// A new agent opens on one of these, so two agents created in a row must
// not look alike.
const urls = new Set(Array.from({ length: 20 }, randomAgentAvatarUrl));
@@ -17,14 +17,14 @@ describe('randomAgentAvatarUrl', () => {
});
it('is an ordinary avatar URL once drawn', () => {
- expect(randomAgentAvatarUrl()).toContain('/bottts/png?');
+ expect(randomAgentAvatarUrl()).toContain('/gaze/png?');
});
});
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.
+ // nowhere, so the same seed has to redraw the same face forever.
expect(agentAvatarUrlForSeed('worker')).toBe(agentAvatarUrlForSeed('worker'));
});
@@ -36,14 +36,29 @@ describe('agentAvatarUrlForSeed', () => {
// 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')).toContain('/gaze/png?');
expect(agentAvatarUrlForSeed('worker')).not.toContain('/svg');
});
it('pins the drawing version', () => {
- // Unpinned, every stored icon silently becomes a different bot the day the
+ // Unpinned, every stored icon silently becomes a different face the day the
// service ships a new major.
- expect(agentAvatarUrlForSeed('worker')).toContain('/9.x/');
+ expect(agentAvatarUrlForSeed('worker')).toContain('/10.x/');
+ });
+
+ it('matches the URL the Switch server generates for the same seed', () => {
+ // The server's test (`core/tests/switch_core/test_agent_icon.py`) pins this
+ // same string. Drift between the two and an agent with no icon stored wears
+ // one face here and another on every chat platform.
+ expect(agentAvatarUrlForSeed('pm-agent')).toBe(
+ 'https://api.dicebear.com/10.x/gaze/png?seed=pm-agent&size=256&scale=1.1'
+ );
+ });
+
+ it('stays short enough for Slack with a UUID seed', () => {
+ // Slack refuses a whole post whose icon URL is over 255 characters, and
+ // the server adds a background parameter of about 25 more on the way.
+ expect(agentAvatarUrlForSeed(crypto.randomUUID()).length).toBeLessThan(200);
});
it('escapes a seed that would otherwise break the query string', () => {
@@ -97,8 +112,6 @@ describe('agentInitials', () => {
});
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');
});
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
index 393928dba..5b6b4bef4 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.ts
@@ -1,40 +1,49 @@
/**
- * How an agent's bot avatar is built (CHOO-2171).
+ * How an agent's 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.
+ * only decides which URL to offer — nothing here is persisted.
*
* 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
+ * - **Deterministic.** A seed always yields the same face, 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';
+ * face the day the service moved on. */
+const DICEBEAR_VERSION = '10.x';
+
+/** DiceBear's "gaze" style. The Switch server generates the same URL
+ * (`core/switch_core/agent_icon.py`); the two must stay identical, or an agent
+ * wears a different face here than on the chat platforms. */
+const DICEBEAR_STYLE = 'gaze';
/** 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. */
+/** Drawn a tenth larger than DiceBear's default, which leaves the body small
+ * at chat-avatar size. Every shape is allowed: listing all but the arch (the
+ * one a round crop trims at this scale) made the URL too long for Slack. */
+const AVATAR_SCALE = '1.1';
+
+/** How many avatars 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.
+ * always draws the same face.
*/
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()}`;
+ const params = new URLSearchParams({ seed, size: String(AVATAR_PIXELS), scale: AVATAR_SCALE });
+ return `https://api.dicebear.com/${DICEBEAR_VERSION}/${DICEBEAR_STYLE}/png?${params.toString()}`;
}
/**
@@ -60,7 +69,7 @@ export function randomAgentAvatarUrl(): string {
/**
* 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.
+ * different faces.
*
* 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
@@ -85,7 +94,7 @@ function sequentialSeeds(agentName: string, round: number, count: number): strin
* 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.
+ * `SW`.
*/
export function agentInitials(agentName: string): string {
const words = agentName.split(/[\s_-]+/).filter((word) => word.length > 0);
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 430e7d842..0ce361be3 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
@@ -231,9 +231,9 @@ export type RemoteAgentSummary = {
* (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.
+ * screen: it draws a name-derived avatar for any agent with no stored icon, so
+ * a server that rejected every write still looks right here while an older
+ * server's chat platforms show a lettered badge.
*/
export type AgentIconBackfill =
| { kind: 'written'; written: number }
diff --git a/console/packages/agent-providers/src/host/process-fence.test.ts b/console/packages/agent-providers/src/host/process-fence.test.ts
index e090f082e..5fcfee755 100644
--- a/console/packages/agent-providers/src/host/process-fence.test.ts
+++ b/console/packages/agent-providers/src/host/process-fence.test.ts
@@ -90,6 +90,27 @@ it('waits for confirmed exit after a transient permission error during group tea
}
});
+const throws = (code: string) => () => {
+ throw Object.assign(new Error(code), { code });
+};
+
+// macOS answers EPERM for a group left with only unreaped members, as it can
+// be the moment a host exits.
+it.each([
+ ['checking it', [throws('EPERM')]],
+ ['killing it', [(): true => true, throws('EPERM')]],
+])('waits out a group that answers EPERM when %s', async (_when, answers) => {
+ const kill = vi.spyOn(process, 'kill');
+ for (const answer of [throws('ESRCH'), ...answers, throws('ESRCH')])
+ kill.mockImplementationOnce(answer);
+ try {
+ await expect(fenceDeadOwner(12345, 12345)).resolves.toBeUndefined();
+ expect(kill).toHaveBeenLastCalledWith(-12345, 0);
+ } finally {
+ kill.mockRestore();
+ }
+});
+
it('does not assume a group is gone when permission stays denied', async () => {
const gone = Object.assign(new Error('Process exited'), { code: 'ESRCH' });
const denied = Object.assign(new Error('Permission denied'), { code: 'EPERM' });
diff --git a/console/packages/agent-providers/src/host/process-fence.ts b/console/packages/agent-providers/src/host/process-fence.ts
index 455ee0c59..8bc9fa4f8 100644
--- a/console/packages/agent-providers/src/host/process-fence.ts
+++ b/console/packages/agent-providers/src/host/process-fence.ts
@@ -26,12 +26,15 @@ export async function fenceDeadOwner(pid: number, group: number | null): Promise
if (exists(pid)) throw new Error('FENCING_REQUIRED: the shared host owner is still alive.');
if (group !== pid || process.platform === 'win32')
throw new Error('FENCING_REQUIRED: the previous host did not isolate its provider processes.');
- if (!exists(-group)) return;
try {
+ if (!exists(-group)) return;
process.kill(-group, 'SIGKILL');
} catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ESRCH') return;
- throw error;
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code === 'ESRCH') return;
+ // macOS answers EPERM for a group whose members have all exited but are
+ // not yet reaped. The wait below tells that apart from one that stays.
+ if (code !== 'EPERM') throw error;
}
for (let attempt = 0; attempt < 100; attempt++) {
try {
diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.ts
index 5152c62d4..ffe41747e 100644
--- a/console/packages/agent-providers/src/host/session-host.test.ts
+++ b/console/packages/agent-providers/src/host/session-host.test.ts
@@ -957,6 +957,24 @@ it.each(['session.exited', 'session.state.changed'] as const)(
}
);
+it('never reads stopped while a reset replaces the conversation', async () => {
+ const { host, adapter, emit } = await start('claude');
+ adapter.stopSession = vi.fn(async () => {
+ emit({ type: 'session.state.changed', status: 'stopped' });
+ emit({ type: 'session.exited', reason: 'Stopped' });
+ });
+ const reset = { ...message('reset'), body: { type: 'session.reset' as const } };
+ expect((await host.command(reset)).status).toBe('applied');
+ expect(adapter.stopSession).toHaveBeenCalled();
+ expect(
+ host
+ .replay(0)
+ .events.some(
+ (event) => event.body.type === 'session.upsert' && event.body.session.status === 'stopped'
+ )
+ ).toBe(false);
+});
+
async function openApproval(
emit: (event: Record<string, unknown>) => void,
host: HostedSession
diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.ts
index b3f59dadf..13b04381e 100644
--- a/console/packages/agent-providers/src/host/session-host.ts
+++ b/console/packages/agent-providers/src/host/session-host.ts
@@ -948,7 +948,14 @@ export class HostedSession {
}
private async providerEvent(event: ProviderRuntimeEvent): Promise<void> {
- if (this.resetting && event.type === 'session.exited') return;
+ // A reset stops the old conversation on the way to a fresh one. That stop
+ // is not the session's: shown, it reads as the session ending.
+ if (
+ this.resetting &&
+ (event.type === 'session.exited' ||
+ (event.type === 'session.state.changed' && event.status === 'stopped'))
+ )
+ return;
if (event.type === 'session.exited') {
for (const request of this.snapshot().requests)
if (request.state === 'open' || request.state === 'submitting')
diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.ts
index 953b927b1..ef483cb4e 100644
--- a/console/packages/agent-providers/src/host/shared-host.test.ts
+++ b/console/packages/agent-providers/src/host/shared-host.test.ts
@@ -102,6 +102,11 @@ async function start(
/** The provider reports work, such as subagents, still running outside any turn. */
backgroundWork?: { running: boolean };
resettable?: boolean;
+ /**
+ * Stopping a conversation reports it stopped and exited, as every provider
+ * adapter does, and returns only after the host has had time to look.
+ */
+ stopReports?: boolean;
/** What the launcher recorded when it created this session's root, if it did. */
owedStart?: string;
/** The file's text as written, for one that is not what a launcher writes. */
@@ -207,6 +212,10 @@ async function start(
interruptTurn: vi.fn(async () => {}),
stopSession: vi.fn(async () => {
live = false;
+ if (!opts.stopReports) return;
+ emit({ type: 'session.state.changed', status: 'stopped' });
+ emit({ type: 'session.exited', reason: 'Stopped' });
+ await new Promise((resolve) => setTimeout(resolve, 600));
}),
stopAll: vi.fn(async () => {}),
hasSession: () => live,
@@ -928,6 +937,35 @@ it('tells the session to rejoin its room once a reset asked for there has applie
}
}, 20000);
+it('keeps running through a reset whose provider reports the old conversation stopped', async () => {
+ const host = await start({ resettable: true, stopReports: true });
+ try {
+ const reset: Command = {
+ ...relayed('current', 'room-reset', { type: 'session.reset' }),
+ origin: {
+ actorId: '@person:test',
+ surface: 'switch-web',
+ roomId: 'room',
+ threadId: null,
+ messageId: 'message-9',
+ },
+ };
+ const answer = await host.parent.ask({
+ type: 'command',
+ command: reset,
+ requesterName: 'louisa',
+ });
+ expect(answer).toMatchObject({
+ ok: true,
+ value: { commandId: 'room-reset', status: 'applied' },
+ });
+ await vi.waitFor(() => expect(host.turns).toHaveLength(1), { timeout: 5000 });
+ expect(host.turns[0]!.text).toContain('Connect to Switch room "room"');
+ } finally {
+ expect(await host.stop()).toBeNull();
+ }
+}, 20000);
+
it('says a session is busy for each thing that keeps it from parking, and idle otherwise', () => {
const snapshot = (session: Partial<Session>, turns: string[], requests: string[]) =>
({
diff --git a/core/switch_core/agent_icon.py b/core/switch_core/agent_icon.py
index b7ad02918..aabb10a29 100644
--- a/core/switch_core/agent_icon.py
+++ b/core/switch_core/agent_icon.py
@@ -2,9 +2,12 @@
Switch stores a link to an agent's icon, never the image bytes. The picture may
come from an operator's own host or anywhere else the client chooses; an agent
-created without one gets a generated robot (`generated_icon_url`), the same set
+created without one gets a generated icon (`generated_icon_url`), the same set
every client offers, so it looks alike in the gateway, Console and every
-platform.
+platform. An agent with no icon stored at all is drawn with the one its name
+generates, so it looks the same as one that was given it. A sender that is not
+an agent at all keeps a lettered badge (`initials_icon_url`), so a person never
+wears an agent's face.
That makes the URL attacker-controlled input with two distinct consumers, and
the rules below exist for the second one:
@@ -23,8 +26,9 @@ rather than treating storage validation as sufficient.
"""
import ipaddress
+import re
from typing import NoReturn
-from urllib.parse import quote, urlsplit
+from urllib.parse import quote, unquote_plus, urlencode, 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.
@@ -109,40 +113,79 @@ def validate_icon_url(url: str) -> str:
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.
+# Generated icons. The URL is all Switch stores; the picture is DiceBear's
+# "gaze", raster because Slack, Discord and Mattermost render no SVG, and pinned
+# to a major version because the drawing changes between majors.
+_GENERATED_ICON_BASE = "https://api.dicebear.com/10.x/gaze/png"
+_GENERATED_ICON_PIXELS = 256
+# A tenth larger than DiceBear draws it, which leaves the body small in its
+# frame at chat-avatar size. At that scale a round crop (Discord, Mattermost,
+# Teams) trims a sliver off the arch silhouette's bottom corners. That was
+# chosen over listing the other shapes: the list made the URL too long for
+# Slack's 255-character `icon_url`, and the only shorter form, a comma list,
+# breaks wherever the query is re-encoded.
+_GENERATED_ICON_SCALE = "1.1"
+GENERATED_ICON_CHOICES = 10
- 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).
+def generated_icon_url(seed: str) -> str:
+ """The generated icon for `seed`: the same seed always draws the same face."""
+ query = [
+ ("seed", seed),
+ ("size", str(_GENERATED_ICON_PIXELS)),
+ ("scale", _GENERATED_ICON_SCALE),
+ ]
+ return f"{_GENERATED_ICON_BASE}?{urlencode(query, quote_via=quote)}"
+
+
+# The robot every client generated before gaze, in exactly the shape they built
+# it: a seed and this size, nothing else. A robot URL with anything more on it,
+# or in any other order, was put together by hand and is someone's choice, so it
+# is left alone. The migration that replaced stored robots (`2f6919dcdead`)
+# matches the same pattern, so a URL it left as a robot stays one when saved.
+_LEGACY_ICON = re.compile(
+ r"^https://api\.dicebear\.com/9\.x/bottts/png\?seed=([^&#]+)&size=256$"
+)
+
+
+def upgrade_legacy_icon_url(url: str) -> str:
+ """`url`, or the gaze icon for its seed when it is a generated robot.
+
+ Switch Console builds from before gaze still generate the robot for a new
+ agent and for one with no icon, and send it here to be stored. Converting it
+ on the way in means those clients cannot reintroduce robots after the
+ migration that replaced every stored one.
"""
- # 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
+ match = _LEGACY_ICON.match(url)
+ if match is None:
+ return url
+ return generated_icon_url(unquote_plus(match.group(1)))
-# Generated icons. The URL is all Switch stores; the picture is DiceBear's
-# "bottts" robot, raster because Slack, Discord and Mattermost render no SVG,
-# and pinned to a major version because the drawing changes between majors.
-_GENERATED_ICON_BASE = "https://api.dicebear.com/9.x/bottts/png"
-_GENERATED_ICON_PIXELS = 256
-GENERATED_ICON_CHOICES = 10
+def prepare_icon_url(url: str) -> str:
+ """The icon URL to store for `url`, or raise `InvalidIconUrl`.
+ An older client's generated robot is converted first and the result is
+ what gets validated: the gaze URL is longer than the robot it replaces, so
+ checking before converting would let a robot near the length limit be
+ stored over it.
+ """
+ return validate_icon_url(upgrade_legacy_icon_url(url.strip()))
-def generated_icon_url(seed: str) -> str:
- """The generated robot icon for `seed`: the same seed always draws the same robot."""
- return f"{_GENERATED_ICON_BASE}?seed={quote(seed, safe='')}&size={_GENERATED_ICON_PIXELS}"
+
+def initials_icon_url(name: str) -> str:
+ """The lettered badge for a sender that is not an agent.
+
+ A person relayed from another platform, or a platform's own bot, is drawn
+ with initials rather than a generated face: the generated faces are what
+ agents wear, and a human drawn as one would read as an agent.
+ """
+ # Escape first, substitute second. The `+` stands in for a space so the
+ # badge draws two initials for `switch_worker`; percent-encoding it after
+ # the fact turns it back into a literal plus and the name renders with one
+ # initial instead.
+ escaped = quote(name).replace("_", "+")
+ return f"https://ui-avatars.com/api/?name={escaped}&background=random&size=128"
def generated_icon_choices(agent_name: str, page: int) -> list[str]:
@@ -164,6 +207,8 @@ def normalise_icon_url(url: str | None) -> str | None:
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.
+ A generated robot from an older client is stored as its gaze equivalent
+ (`prepare_icon_url`).
"""
if url is None:
return None
@@ -171,4 +216,4 @@ def normalise_icon_url(url: str | None) -> str | None:
if not url.strip():
return None
- return validate_icon_url(url)
+ return prepare_icon_url(url)
diff --git a/core/switch_core/bridges/agent/operations/agent_management.py b/core/switch_core/bridges/agent/operations/agent_management.py
index af6f36ca9..5b10a1a68 100644
--- a/core/switch_core/bridges/agent/operations/agent_management.py
+++ b/core/switch_core/bridges/agent/operations/agent_management.py
@@ -214,7 +214,7 @@ async def create_agent(
must already exist there.
auto_approve: Let the agent run tools without asking for approval.
display_name: A human label shown next to `name`, or null for none.
- icon_url: An https link to the agent's icon, or null for the robot
+ icon_url: An https link to the agent's icon, or null for the icon
its name generates, the same one Switch Console offers first.
start: Start the agent now (true) or create it stopped (false).
diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.py
index ee5823e39..e0b304f10 100644
--- a/core/switch_core/bridges/agent/protocol/agent_core.py
+++ b/core/switch_core/bridges/agent/protocol/agent_core.py
@@ -18,7 +18,7 @@ from switch_core.addressing import (
parse_policy,
)
from switch_core.agent_display_name import normalise_display_name
-from switch_core.agent_icon import normalise_icon_url, validate_icon_url
+from switch_core.agent_icon import normalise_icon_url, prepare_icon_url
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.attachments import parse_attachment_group
from switch_core.authz import Action, Principal, require, require_manage
@@ -926,7 +926,7 @@ class AgentCore:
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
+ validated = prepare_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)
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index d01f2716a..df800b4d2 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -9,7 +9,7 @@ from datetime import datetime
from typing import Any, ClassVar, Literal, Protocol, final, runtime_checkable
from switch_core.agent_display_name import defuse_label_markup
-from switch_core.agent_icon import default_icon_url
+from switch_core.agent_icon import generated_icon_url, initials_icon_url
from switch_core.bridges.collaboration.ingress import CallbackEndpoint
from switch_core.bridges.collaboration.models import (
BridgeInstallLink,
@@ -525,6 +525,7 @@ class PlatformAdapter(ABC):
self._resolve_agent_presentation: (
Callable[[str], Awaitable[AgentPresentation | None]] | None
) = None
+ self._reported_missing_resolver = False
# 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
@@ -1573,22 +1574,13 @@ class PlatformAdapter(ABC):
message instead of at the next restart."""
self._resolve_agent_presentation = resolver
- def default_agent_icon(self, agent_name: str) -> str:
- """The avatar for an agent that has set no icon.
+ def adapt_icon_url(self, icon_url: str) -> str:
+ """Turn the icon URL chosen for a sender into the one this platform
+ should be handed.
- 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)
-
- def adapt_icon_url(self, raw: str | None, agent_name: str) -> str:
- """Turn the stored icon URL into the one this platform should be handed.
-
- `raw` is the agent's own icon, or None when it has none and the
- platform default stands in. Pure and synchronous so it composes with a
- single lookup: an override adjusts the URL, it does not go looking for
- one."""
- return raw or self.default_agent_icon(agent_name)
+ Pure and synchronous so it composes with a single lookup: an override
+ adjusts the URL, it does not go looking for one."""
+ return icon_url
def escape_label_for_body(self, label: str) -> str:
"""Neutralise a label's markup before it goes into message text.
@@ -1638,16 +1630,39 @@ class PlatformAdapter(ABC):
that need one of them alone — an unescaped label is not among them:
:attr:`AgentRendering.field_label` is reachable only alongside the
escaped one, so choosing it is a choice."""
- raw = AgentPresentation(display_name=None, icon_url=None)
- if self._resolve_agent_presentation is not None:
+ # An agent with no icon wears the face its name generates; a name the
+ # resolver says is no agent keeps a lettered badge, so a person relayed
+ # from elsewhere is never drawn as an agent. The name is the sending
+ # actor's own (an agent's is its identifier, never a room alias), so a
+ # miss is a sender that is not an agent rather than an agent the lookup
+ # failed to recognise.
+ #
+ # Without a resolver nothing can say who is who. The senders an adapter
+ # draws are overwhelmingly agents, so it draws them as agents rather
+ # than turning every agent into a person. The bridge core installs one
+ # before the adapter starts, so a running bridge without it is a wiring
+ # fault, and said so once.
+ if self._resolve_agent_presentation is None:
+ if not self._reported_missing_resolver:
+ self._reported_missing_resolver = True
+ logger.warning(
+ "%s has no agent presentation resolver: every sender is "
+ "drawn as an agent under its identifier, people included",
+ type(self).__name__,
+ )
+ label = agent_name
+ icon_url = generated_icon_url(agent_name)
+ else:
found = await self._resolve_agent_presentation(agent_name)
- if found is not None:
- raw = found
- label = raw.display_name or agent_name
+ label = (found.display_name if found else None) or agent_name
+ if found is None:
+ icon_url = initials_icon_url(agent_name)
+ else:
+ icon_url = found.icon_url or generated_icon_url(agent_name)
return AgentRendering(
field_label=label,
body_label=self.escape_label_for_body(label),
- icon_url=self.adapt_icon_url(raw.icon_url, agent_name),
+ icon_url=self.adapt_icon_url(icon_url),
)
async def agent_icon_url(self, agent_name: str) -> str:
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 980aed0a1..7a02df287 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -29,7 +29,6 @@ from mattermostdriver.exceptions import (
)
from pydantic import field_validator
-from switch_core.agent_icon import default_icon_url
from switch_core.bridges.collaboration.adapter import (
ActivityMark,
ActivitySnapshot,
@@ -2358,11 +2357,6 @@ class MattermostAdapter(PlatformAdapter):
# ── 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 _fetch_icon(self, url: str) -> bytes | None:
"""The icon's bytes, or None if it is larger than the ceiling."""
async with guarded_async_client(
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index a87b91873..ffc716ca5 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -63,7 +63,10 @@ from switch_core.bridges.collaboration.session.renderers.slack import (
from switch_core.bridges.collaboration.slack.agent_groups import (
SlackAgentGroupDirectory,
)
-from switch_core.bridges.collaboration.slack.avatar import on_slack_background
+from switch_core.bridges.collaboration.slack.avatar import (
+ on_slack_background,
+ slack_icon_argument,
+)
from switch_core.bridges.collaboration.slack.mrkdwn import escape_mrkdwn
from switch_core.room_wide_mention import (
CODE_AND_URLS,
@@ -601,7 +604,7 @@ class SlackAdapter(PlatformAdapter):
channel=channel_id,
text=content,
username=agent.field_label,
- icon_url=agent.icon_url,
+ icon_url=slack_icon_argument(agent.icon_url, sender_name),
thread_ts=thread_ts,
unfurl_links=False,
unfurl_media=False,
@@ -644,7 +647,7 @@ class SlackAdapter(PlatformAdapter):
text=text,
blocks=blocks,
username=agent.field_label,
- icon_url=agent.icon_url,
+ icon_url=slack_icon_argument(agent.icon_url, sender_name),
thread_ts=thread_ts,
unfurl_links=False,
unfurl_media=False,
@@ -1235,7 +1238,9 @@ class SlackAdapter(PlatformAdapter):
recipient_team_id=self._team_id,
task_display_mode="plan",
username=agent_name,
- icon_url=await self.agent_icon_url(agent_name),
+ icon_url=slack_icon_argument(
+ await self.agent_icon_url(agent_name), agent_name
+ ),
)
except SlackApiError as error:
logger.warning(
@@ -1615,11 +1620,11 @@ class SlackAdapter(PlatformAdapter):
text,
)
- def adapt_icon_url(self, raw: str | None, agent_name: str) -> str:
+ def adapt_icon_url(self, icon_url: str) -> str:
# Overridden for Slack alone: it flattens a transparent avatar onto
# white. Adjusting here rather than at each call site keeps every place
# that posts as an agent on the same background.
- return on_slack_background(super().adapt_icon_url(raw, agent_name))
+ return on_slack_background(super().adapt_icon_url(icon_url))
def slash_invite_hint(self) -> str:
# Slack passes a slash command's whole tail through as free text, so the
@@ -1915,7 +1920,7 @@ class SlackAdapter(PlatformAdapter):
channel=channel_id,
text="_thinking..._",
username=agent.field_label,
- icon_url=agent.icon_url,
+ icon_url=slack_icon_argument(agent.icon_url, sender_name),
thread_ts=thread_ts,
)
ts = result.get("ts")
diff --git a/core/switch_core/bridges/collaboration/slack/avatar.py b/core/switch_core/bridges/collaboration/slack/avatar.py
index 6299057aa..de5f063d8 100644
--- a/core/switch_core/bridges/collaboration/slack/avatar.py
+++ b/core/switch_core/bridges/collaboration/slack/avatar.py
@@ -12,15 +12,27 @@ background this can ask for. A link an operator supplied themselves is an opaque
image to us: there is no parameter to add, and rewriting someone else's URL on a
guess would be worse than leaving it alone. Such an icon keeps whatever
background it was authored with, transparent included.
+
+Slack also refuses a post outright when its `icon_url` is too long, so an
+avatar URL that runs over loses the message, not just the picture. One that does
+not fit is not sent, and Slack shows the app's own icon for that post.
"""
-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
+import logging
+from urllib.parse import parse_qsl, urlsplit, urlunsplit
+
+logger = logging.getLogger(__name__)
# Slack's resting dark surface, sampled from a real client. A hovered row
# lightens and the edge becomes faintly visible; matching the hover state
# instead would make it visible in the far commoner resting one.
SLACK_SURFACE = "1a1d21"
+#: The longest `icon_url` Slack accepts. One character more and
+#: `chat.postMessage` refuses the whole post with `invalid_arguments`; measured
+#: against the live API, as Slack does not document it.
+SLACK_ICON_URL_MAX = 255
+
_DICEBEAR_HOST = "api.dicebear.com"
_BACKGROUND_PARAM = "backgroundColor"
@@ -31,6 +43,10 @@ def on_slack_background(icon_url: str) -> str:
A DiceBear URL with no background of its own gains one. Anything else —
another host, or a DiceBear URL whose background was chosen deliberately —
is returned untouched.
+
+ The background is appended to the query as it stands rather than the
+ query being rebuilt: re-encoding it would turn a comma list's commas into
+ `%2C`, which DiceBear refuses.
"""
parts = urlsplit(icon_url)
if (parts.hostname or "").lower() != _DICEBEAR_HOST:
@@ -40,5 +56,32 @@ def on_slack_background(icon_url: str) -> str:
if any(key == _BACKGROUND_PARAM for key, _ in query):
return icon_url
- query.append((_BACKGROUND_PARAM, SLACK_SURFACE))
- return urlunsplit(parts._replace(query=urlencode(query)))
+ background = f"{_BACKGROUND_PARAM}={SLACK_SURFACE}"
+ joined = f"{parts.query}&{background}" if parts.query else background
+ return urlunsplit(parts._replace(query=joined))
+
+
+# Oversized icon URLs already reported, so an agent posting every turn does
+# not repeat one unchanged condition on every post.
+_reported_oversized: set[str] = set()
+
+
+def slack_icon_argument(icon_url: str, agent_name: str) -> str | None:
+ """The `icon_url` to hand Slack for a post, or None to send none.
+
+ None when Slack would refuse the URL: the post then goes out under the
+ app's own icon rather than not at all. Reported once per URL.
+ """
+ if len(icon_url) <= SLACK_ICON_URL_MAX:
+ return icon_url
+ if icon_url in _reported_oversized:
+ return None
+ _reported_oversized.add(icon_url)
+ logger.warning(
+ "The icon URL for %s is %d characters, over Slack's limit of %d; "
+ "posting under the Slack app's own icon instead.",
+ agent_name,
+ len(icon_url),
+ SLACK_ICON_URL_MAX,
+ )
+ return None
diff --git a/core/switch_core/management/schemas.py b/core/switch_core/management/schemas.py
index 3e66a7bb6..5e76a099c 100644
--- a/core/switch_core/management/schemas.py
+++ b/core/switch_core/management/schemas.py
@@ -392,7 +392,7 @@ class CreateManagedAgentRequest(_GatewayBody):
name: str
description: str
display_name: str | None = None
- # Null for the robot its name generates (`agent_icon.generated_icon_url`).
+ # Null for the icon its name generates (`agent_icon.generated_icon_url`).
icon_url: str | None = None
controller_id: str | None
desired_state: DesiredState
diff --git a/core/switch_core/migrations/versions/2f6919dcdead_agent_icons_to_dicebear_gaze.py b/core/switch_core/migrations/versions/2f6919dcdead_agent_icons_to_dicebear_gaze.py
new file mode 100644
index 000000000..78f65928b
--- /dev/null
+++ b/core/switch_core/migrations/versions/2f6919dcdead_agent_icons_to_dicebear_gaze.py
@@ -0,0 +1,80 @@
+"""move generated agent icons from DiceBear bottts to gaze
+
+Revision ID: 2f6919dcdead
+Revises: fabf9b9bff78
+
+Generated agent icons used to be DiceBear's 9.x "bottts" robot and are now its
+10.x "gaze" style. An agent's icon is stored as a URL, so the agents that were
+given a robot keep it until the stored URL changes; this rewrites each one to
+the gaze icon drawn from the same seed. The seed is carried over exactly as
+stored, already escaped, so it draws for the same input it did before.
+
+Only the robot URL Switch and Switch Console generated is touched, matched in
+exactly the shape they built it: a seed and `size=256`, nothing more. An icon on
+any other host, any other DiceBear style, or a robot URL carrying options of its
+own was chosen by someone and is left as it is. Downgrade is held to the same
+line, turning back only the gaze URL in exactly the shape this writes. Saving an
+icon applies the same pattern (`agent_icon.upgrade_legacy_icon_url`), so what
+this leaves as a robot stays one when saved.
+
+The gaze URL is longer than the robot it replaces. A robot whose gaze form would
+exceed the 2048 characters Switch accepts for an icon is left as it is rather
+than stored over the limit; saving one is refused for the same reason.
+
+The gaze URL is written out here rather than built by
+`switch_core.agent_icon.generated_icon_url`: a migration has to keep producing
+what it produced on the day it shipped, whatever that function becomes later.
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "2f6919dcdead"
+down_revision: str | Sequence[str] | None = "fabf9b9bff78"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_ROBOT = "https://api.dicebear.com/9.x/bottts/png?seed="
+_GAZE = "https://api.dicebear.com/10.x/gaze/png?seed="
+
+_GAZE_QUERY_AFTER_SEED = "&size=256&scale=1.1"
+
+# The whole stored URL has to be the generated robot, so the pattern is
+# anchored at both ends and the seed is the only part allowed to vary.
+_ROBOT_SEED = r"'^https://api\.dicebear\.com/9\.x/bottts/png\?seed=([^&#]+)&size=256$'"
+# A gaze URL's seed, checked afterwards against the full generated shape.
+_GAZE_SEED = r"'^https://api\.dicebear\.com/10\.x/gaze/png\?seed=([^&#]+)&'"
+
+
+# `agent_icon.MAX_ICON_URL_LENGTH` on the day this shipped.
+_MAX_ICON_URL_LENGTH = 2048
+
+
+def upgrade() -> None:
+ gaze = f"'{_GAZE}' || substring(icon_url from {_ROBOT_SEED}) || '{_GAZE_QUERY_AFTER_SEED}'"
+ # Runs as the schema owner, which row-level security does not restrict, so
+ # every tenant's agents are seen.
+ op.execute(
+ f"""
+ UPDATE agents
+ SET icon_url = {gaze}
+ WHERE icon_url ~ {_ROBOT_SEED}
+ AND length({gaze}) <= {_MAX_ICON_URL_LENGTH}
+ """
+ )
+
+
+def downgrade() -> None:
+ # Every generated gaze icon goes back to the robot for its seed, including
+ # ones given to agents after the upgrade: the code this returns to draws
+ # only robots, so a gaze icon would be the one face it never generates.
+ op.execute(
+ f"""
+ UPDATE agents
+ SET icon_url = '{_ROBOT}'
+ || substring(icon_url from {_GAZE_SEED}) || '&size=256'
+ WHERE icon_url = '{_GAZE}'
+ || substring(icon_url from {_GAZE_SEED}) || '{_GAZE_QUERY_AFTER_SEED}'
+ """
+ )
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
index e3e524407..2725c8a75 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py
@@ -16,7 +16,7 @@ from typing import Any
import discord
import pytest
-from switch_core.agent_icon import default_icon_url
+from switch_core.agent_icon import generated_icon_url, initials_icon_url
from switch_core.bridges.collaboration.adapter import (
AgentPresentation,
PlatformAdapter,
@@ -36,7 +36,10 @@ from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
)
-from switch_core.bridges.collaboration.slack.avatar import SLACK_SURFACE
+from switch_core.bridges.collaboration.slack.avatar import (
+ SLACK_ICON_URL_MAX,
+ SLACK_SURFACE,
+)
from switch_core.bridges.collaboration.teams.adapter import (
TeamsAdapter,
TeamsConnectionConfig,
@@ -58,7 +61,7 @@ TELEGRAM_CHAT = "-1001234567890"
# A DiceBear URL with no background of its own — the only shape Slack's avatar
# recolour can act on.
-_DICEBEAR = "https://api.dicebear.com/9.x/bottts/png?seed=worker&size=256"
+_DICEBEAR = generated_icon_url("worker")
def _run(coro: Any) -> Any:
@@ -235,18 +238,7 @@ class TestAdapterLabelSelection:
rendering = await adapter.agent_rendering("some-slack-bot")
assert rendering.field_label == "some-slack-bot"
- assert rendering.icon_url == default_icon_url("some-slack-bot")
-
- async def test_mattermost_still_pins_the_format_of_its_default_icon(self) -> None:
- """`default_agent_icon` is consulted through `self`, so the platform
- that uploads the bytes rather than passing a link on keeps the response
- format it can accept."""
- adapter = MattermostAdapter.__new__(MattermostAdapter)
- PlatformAdapter.__init__(adapter)
-
- assert await adapter.agent_icon_url("worker") == default_icon_url(
- "worker", image_format="png"
- )
+ assert rendering.icon_url == initials_icon_url("some-slack-bot")
def test_the_resolver_is_installed_before_the_adapter_starts() -> None:
@@ -440,6 +432,33 @@ def test_slack_still_draws_an_agent_icon_on_its_own_background() -> None:
assert f"backgroundColor={SLACK_SURFACE}" in client.calls[0]["icon_url"]
+def test_slack_is_handed_a_generated_icon_short_enough_to_accept() -> None:
+ """Slack refuses the whole post when its icon URL runs past 255 characters,
+ and the generated icon with its shapes spelled out one by one does."""
+ seed = "0faf365b-e9bc-4d38-8438-ab50087065eb"
+ bridge = _bridge(_agent("worker", None, generated_icon_url(seed)))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ icon = client.calls[0]["icon_url"]
+ assert icon is not None
+ assert len(icon) <= SLACK_ICON_URL_MAX
+
+
+def test_slack_still_posts_when_an_icon_url_is_too_long_to_send() -> None:
+ """An operator's own URL cannot be shortened. Sent anyway, Slack would
+ refuse the message along with it."""
+ signed = "https://cdn.example.com/avatar.png?signature=" + "a" * 300
+ bridge = _bridge(_agent("worker", None, signed))
+ adapter, client = _slack_adapter(bridge)
+
+ _run(adapter.send_message(SLACK_CHANNEL, "worker", "hello"))
+
+ assert len(client.calls) == 1
+ assert client.calls[0]["icon_url"] is None
+
+
def test_slack_resolves_an_agent_once_per_send() -> None:
"""One post needs the label and the icon; they come off one row, so it must
be one query. Two accessors awaited back to back made it two."""
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
index 7c423d297..27ea5af4a 100644
--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py
@@ -3,15 +3,18 @@
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.
+between that answer and the icon the agent's name generates.
"""
from __future__ import annotations
+import logging
from types import SimpleNamespace
from typing import Any
-from switch_core.agent_icon import default_icon_url
+import pytest
+
+from switch_core.agent_icon import generated_icon_url, initials_icon_url
from switch_core.bridges.collaboration.adapter import (
AgentPresentation,
PlatformAdapter,
@@ -94,9 +97,24 @@ class TestCollaborationCoreResolver:
class TestAdapterIconSelection:
- async def test_uses_the_default_when_no_resolver_is_installed(self) -> None:
+ async def test_draws_an_agent_face_when_no_resolver_is_installed(self) -> None:
+ # Nothing can say who is who, and the senders an adapter draws are
+ # overwhelmingly agents: drawing them all as people would be the worse
+ # mistake.
adapter = _Adapter()
- assert await adapter.agent_icon_url("worker") == default_icon_url("worker")
+ assert await adapter.agent_icon_url("worker") == generated_icon_url("worker")
+
+ async def test_says_once_that_no_resolver_is_installed(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ adapter = _Adapter()
+ with caplog.at_level(logging.WARNING):
+ await adapter.agent_icon_url("worker")
+ await adapter.agent_icon_url("manager")
+ reports = [
+ r for r in caplog.records if "no agent presentation resolver" in r.message
+ ]
+ assert len(reports) == 1
async def test_prefers_the_agents_own_icon(self) -> None:
adapter = _Adapter()
@@ -114,7 +132,7 @@ class TestAdapterIconSelection:
return AgentPresentation(display_name=None, icon_url=None)
adapter.set_agent_presentation_resolver(resolver)
- assert await adapter.agent_icon_url("worker") == default_icon_url("worker")
+ assert await adapter.agent_icon_url("worker") == generated_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
@@ -124,22 +142,5 @@ class TestAdapterIconSelection:
adapter.set_agent_presentation_resolver(bridge._agent_presentation)
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")
+ assert await adapter.agent_icon_url("plain") == generated_icon_url("plain")
+ assert await adapter.agent_icon_url("alice") == initials_icon_url("alice")
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
index b909e0fb1..28e32a67f 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_avatar.py
@@ -1,24 +1,37 @@
import asyncio
+import logging
from urllib.parse import parse_qs, urlsplit
-from switch_core.agent_icon import default_icon_url
+import pytest
+
+from switch_core.agent_icon import generated_icon_url, initials_icon_url
from switch_core.bridges.collaboration.adapter import AgentPresentation
from switch_core.bridges.collaboration.slack.adapter import (
SlackAdapter,
SlackConnectionConfig,
)
from switch_core.bridges.collaboration.slack.avatar import (
+ SLACK_ICON_URL_MAX,
SLACK_SURFACE,
on_slack_background,
+ slack_icon_argument,
)
-DICEBEAR = "https://api.dicebear.com/9.x/bottts/png?seed=worker&size=256"
+DICEBEAR = generated_icon_url("worker")
def _background(url: str) -> list[str]:
return parse_qs(urlsplit(url).query).get("backgroundColor", [])
+def _options(url: str) -> dict[str, list[str]]:
+ """Each option's values, however the URL spells a list of them."""
+ return {
+ key: [item for value in values for item in value.split(",")]
+ for key, values in parse_qs(urlsplit(url).query).items()
+ }
+
+
def test_gives_a_dicebear_avatar_slacks_background() -> None:
# Without this the PNG is transparent and Slack flattens it onto white,
# putting a bright square around every agent in a dark message list.
@@ -26,15 +39,33 @@ def test_gives_a_dicebear_avatar_slacks_background() -> None:
def test_keeps_the_rest_of_the_url_intact() -> None:
- # The seed decides which bot is drawn: lose it and the agent changes face.
- query = parse_qs(urlsplit(on_slack_background(DICEBEAR)).query)
+ # The seed decides which face is drawn: lose it and the agent changes face.
+ query = _options(on_slack_background(DICEBEAR))
assert query["seed"] == ["worker"]
- assert query["size"] == ["256"]
+ assert {
+ key: values for key, values in query.items() if key != "backgroundColor"
+ } == _options(DICEBEAR)
+
+
+def test_appends_the_background_without_re_encoding_the_query() -> None:
+ # A DiceBear URL someone wrote with a comma list keeps its commas: encoded
+ # as `%2C` the list is refused, and the avatar fails to load.
+ chosen = "https://api.dicebear.com/10.x/gaze/png?seed=x&shapeVariant=circle,square"
+ assert on_slack_background(chosen) == f"{chosen}&backgroundColor={SLACK_SURFACE}"
+
+
+def test_a_generated_icon_for_a_uuid_seed_fits_slacks_limit() -> None:
+ # Console seeds a new agent's icon with a UUID. Slack refuses the whole
+ # post when its icon URL is longer than 255 characters.
+ adapted = on_slack_background(
+ generated_icon_url("0faf365b-e9bc-4d38-8438-ab50087065eb")
+ )
+ assert len(adapted) <= SLACK_ICON_URL_MAX
def test_leaves_a_background_that_was_already_chosen() -> None:
chosen = f"{DICEBEAR}&backgroundColor=ff0000"
- assert on_slack_background(chosen) == chosen
+ assert _background(on_slack_background(chosen)) == ["ff0000"]
def test_leaves_an_operators_own_image_alone() -> None:
@@ -44,16 +75,16 @@ def test_leaves_an_operators_own_image_alone() -> None:
assert on_slack_background(custom) == custom
-def test_leaves_the_initials_default_alone() -> None:
+def test_leaves_the_initials_badge_alone() -> None:
# ui-avatars already draws an opaque background, so it has no white square
# to fix and its own colour must survive.
- default = default_icon_url("switch_worker")
- assert on_slack_background(default) == default
+ badge = initials_icon_url("switch_worker")
+ assert on_slack_background(badge) == badge
def test_does_not_match_a_lookalike_host() -> None:
# `api.dicebear.com.evil.test` is not DiceBear; only the exact host is.
- impostor = "https://api.dicebear.com.evil.test/9.x/bottts/png?seed=worker"
+ impostor = "https://api.dicebear.com.evil.test/10.x/gaze/png?seed=worker"
assert on_slack_background(impostor) == impostor
@@ -81,3 +112,24 @@ def test_the_slack_adapter_applies_it_to_a_resolved_icon() -> None:
resolved = asyncio.run(adapter.agent_icon_url("worker"))
assert _background(resolved) == [SLACK_SURFACE]
+
+
+def test_hands_slack_an_icon_url_up_to_its_limit() -> None:
+ at_limit = "https://example.com/" + "a" * (SLACK_ICON_URL_MAX - 20)
+ assert len(at_limit) == SLACK_ICON_URL_MAX
+ assert slack_icon_argument(at_limit, "worker") == at_limit
+
+
+def test_sends_no_icon_url_past_slacks_limit() -> None:
+ # Slack refuses the post itself over this, so the message would be lost.
+ over = "https://example.com/" + "a" * (SLACK_ICON_URL_MAX - 19)
+ assert slack_icon_argument(over, "worker") is None
+
+
+def test_an_oversized_icon_is_reported_once(caplog: pytest.LogCaptureFixture) -> None:
+ # An agent posts every turn; one unchanged condition is one warning.
+ oversized = "https://icons.example/" + "a" * 300 + "-once.png"
+ with caplog.at_level(logging.WARNING):
+ assert slack_icon_argument(oversized, "worker") is None
+ assert slack_icon_argument(oversized, "worker") is None
+ assert len([r for r in caplog.records if "over Slack's limit" in r.message]) == 1
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py b/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py
index e22306ca7..0cb54ed98 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py
@@ -31,7 +31,9 @@ def adapter():
conversations_history=AsyncMock(),
)
adapter.agent_rendering = AsyncMock(
- return_value=SimpleNamespace(field_label="worker", icon_url=None)
+ return_value=SimpleNamespace(
+ field_label="worker", icon_url="https://example.com/worker.png"
+ )
)
adapter._bot_user_id = "bot-demo"
return adapter
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 2871487d3..3cda7e06c 100644
--- a/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_teams_adapter.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import asyncio
from typing import Any
-from switch_core.agent_icon import default_icon_url
+from switch_core.agent_icon import generated_icon_url
from switch_core.bridges.collaboration.adapter import AgentPresentation, AgentRendering
from switch_core.bridges.collaboration.models import InboundCommand, InboundMessage
from switch_core.bridges.collaboration.teams.adapter import (
@@ -893,7 +893,7 @@ async def test_message_activity_falls_back_to_the_default_icon() -> None:
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")
+ assert image["url"] == generated_icon_url("worker")
def _card_text(activity: dict[str, Any]) -> str:
diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.py
index 4cc002405..d52d1f9d9 100644
--- a/core/tests/switch_core/gateway/test_agent_icon_route.py
+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py
@@ -12,6 +12,7 @@ import pytest
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.agent_icon import generated_icon_url
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
@@ -49,6 +50,32 @@ class TestUpdateAgentIcon:
assert stored is not None
assert stored.icon_url == _ICON
+ async def test_an_older_clients_generated_robot_is_stored_as_gaze(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Console builds from before gaze still send the robot their name
+ generates. Stored as sent, it would bring back a robot the migration
+ had already replaced."""
+ 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="https://api.dicebear.com/9.x/bottts/png?seed=a1&size=256"
+ ),
+ session,
+ _AGENT_STORE,
+ owner,
+ await is_admin(session, owner),
+ )
+
+ assert summary.icon_url == generated_icon_url("a1")
+ stored = await _AGENT_STORE.get(session, agent.id)
+ assert stored is not None
+ assert stored.icon_url == generated_icon_url("a1")
+
async def test_owner_can_change_an_existing_icon(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None:
diff --git a/core/tests/switch_core/test_agent_icon.py b/core/tests/switch_core/test_agent_icon.py
index c623fb8fb..14c2d8154 100644
--- a/core/tests/switch_core/test_agent_icon.py
+++ b/core/tests/switch_core/test_agent_icon.py
@@ -13,7 +13,9 @@ from switch_core.agent_icon import (
InvalidIconUrl,
generated_icon_choices,
generated_icon_url,
+ initials_icon_url,
normalise_icon_url,
+ upgrade_legacy_icon_url,
validate_icon_url,
)
@@ -147,13 +149,95 @@ def test_normalise_validates_a_present_url() -> None:
normalise_icon_url("http://10.0.0.1/i.png")
-def test_generated_icon_is_a_stable_raster_robot_per_seed() -> None:
+def test_generated_icon_is_a_stable_raster_gaze_per_seed() -> None:
+ # Switch Console builds the same URL (`agent-avatar.ts`) and its test pins
+ # this same string: change one and the other has to follow, or an agent
+ # wears a different face in the app than on the chat platforms.
url = generated_icon_url("pm-agent")
- assert url == "https://api.dicebear.com/9.x/bottts/png?seed=pm-agent&size=256"
+ assert (
+ url == "https://api.dicebear.com/10.x/gaze/png?seed=pm-agent&size=256&scale=1.1"
+ )
assert generated_icon_url("pm-agent") == url
assert validate_icon_url(url) == url
+ ("stored", "seed"),
+ [
+ # Switch's own robot, and Switch Console's (same shape).
+ ("https://api.dicebear.com/9.x/bottts/png?seed=pm-agent&size=256", "pm-agent"),
+ (
+ "https://api.dicebear.com/9.x/bottts/png?seed=0b6c4f0e-8e1a-4f7e-9d65-0c2b5a3e9f11&size=256",
+ "0b6c4f0e-8e1a-4f7e-9d65-0c2b5a3e9f11",
+ ),
+ (
+ "https://api.dicebear.com/9.x/bottts/png?seed=pm-agent-1-4&size=256",
+ "pm-agent-1-4",
+ ),
+ ],
+)
+def test_a_generated_robot_is_upgraded_to_gaze_for_its_seed(
+ stored: str, seed: str
+) -> None:
+ assert upgrade_legacy_icon_url(stored) == generated_icon_url(seed)
+ assert normalise_icon_url(stored) == generated_icon_url(seed)
+
+
+ "url",
+ [
+ # Options of its own: someone built this by hand.
+ "https://api.dicebear.com/9.x/bottts/png?seed=x&size=256&backgroundColor=ff0000",
+ "https://api.dicebear.com/9.x/bottts/png?seed=x&size=128",
+ "https://api.dicebear.com/9.x/bottts/png?seed=&size=256",
+ "https://api.dicebear.com/9.x/bottts/png?size=256",
+ "https://api.dicebear.com/9.x/bottts/svg?seed=x&size=256",
+ "https://api.dicebear.com/9.x/bottts/png?seed=x&size=256#frag",
+ # Same fields, another order: no client built it this way.
+ "https://api.dicebear.com/9.x/bottts/png?size=256&seed=x",
+ "https://API.dicebear.com/9.x/bottts/png?seed=x&size=256",
+ # Another style, another host, or a lookalike host.
+ "https://api.dicebear.com/9.x/identicon/png?seed=x&size=256",
+ "https://cdn.example.com/9.x/bottts/png?seed=x&size=256",
+ "https://api.dicebear.com.example/9.x/bottts/png?seed=x&size=256",
+ ],
+)
+def test_anything_but_the_generated_robot_is_left_alone(url: str) -> None:
+ assert upgrade_legacy_icon_url(url) == url
+
+
+def test_a_robot_is_converted_before_it_is_validated() -> None:
+ # Surrounding whitespace is stripped first, so it does not hide a robot.
+ stored = " https://api.dicebear.com/9.x/bottts/png?seed=pm-agent&size=256 "
+ assert normalise_icon_url(stored) == generated_icon_url("pm-agent")
+
+
+def test_a_robot_whose_gaze_form_is_over_the_limit_is_refused() -> None:
+ # The robot fits, but the gaze URL it becomes is longer. Checking before
+ # converting would store it over the limit.
+ seed = "a" * 1990
+ robot = f"https://api.dicebear.com/9.x/bottts/png?seed={seed}&size=256"
+ assert len(robot) <= MAX_ICON_URL_LENGTH < len(generated_icon_url(seed))
+ with pytest.raises(InvalidIconUrl, match="at most"):
+ normalise_icon_url(robot)
+
+
+def test_the_gaze_icon_is_left_alone() -> None:
+ url = generated_icon_url("pm-agent")
+ assert upgrade_legacy_icon_url(url) == url
+
+
+def test_initials_badge_reads_underscores_as_word_breaks() -> None:
+ # Two words, so the badge draws two letters for `switch_worker`.
+ assert "name=switch+worker&" in initials_icon_url("switch_worker")
+ assert initials_icon_url("worker") != initials_icon_url("manager")
+
+
+def test_generated_icon_escapes_the_seed() -> None:
+ url = generated_icon_url("a&b=c d")
+ assert "seed=a%26b%3Dc%20d&" in url
+
+
def test_generated_choices_lead_with_the_name_and_stay_put() -> None:
first = generated_icon_choices("pm-agent", 0)
assert len(first) == GENERATED_ICON_CHOICES
diff --git a/core/tests/switch_core/test_migration_agent_icons_to_gaze.py b/core/tests/switch_core/test_migration_agent_icons_to_gaze.py
new file mode 100644
index 000000000..e8d336bbd
--- /dev/null
+++ b/core/tests/switch_core/test_migration_agent_icons_to_gaze.py
@@ -0,0 +1,135 @@
+"""`2f6919dcdead` moves generated agent icons from DiceBear bottts to gaze.
+
+An agent's icon is a stored URL, so agents given the old robot keep it until the
+row changes. This seeds every kind of stored icon, runs the migration up and
+back down, and checks only the generated robots moved, each keeping its seed,
+while robots someone customised by hand stayed as they were.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
+
+from switch_core.agent_icon import generated_icon_url
+from tests.switch_core.test_migration_definitions_advanced_config import _migrate_to
+
+_DB = "migration_agent_icons_to_gaze"
+_PRE_MIGRATION_REVISION = "fabf9b9bff78"
+_MIGRATION_UNDER_TEST = "2f6919dcdead"
+
+_ROBOT = "https://api.dicebear.com/9.x/bottts/png"
+_UUID = "0b6c4f0e-8e1a-4f7e-9d65-0c2b5a3e9f11"
+_HAND_GAZE = "https://api.dicebear.com/10.x/gaze/png?seed=x&backgroundColor=ffe3ea"
+
+# Everything the migration must not touch, up or down: only the robot URL in
+# exactly the shape Switch and Switch Console generated it is theirs to move.
+_UNTOUCHED: dict[str, str | None] = {
+ "custom": "https://icons.example/reviewer.png",
+ "other-style": "https://api.dicebear.com/9.x/identicon/png?seed=chosen",
+ "lookalike": "https://api.dicebear.com.example/9.x/bottts/png?seed=x&size=256",
+ "robot-with-options": f"{_ROBOT}?seed=x&size=256&backgroundColor=ff0000",
+ "robot-other-size": f"{_ROBOT}?seed=x&size=128",
+ "robot-size-first": f"{_ROBOT}?size=256&seed=x",
+ "robot-unseeded": f"{_ROBOT}?size=256",
+ # Fits as a robot, but its gaze form would be over the 2048-character limit.
+ "robot-near-limit": f"{_ROBOT}?seed={'a' * 1990}&size=256",
+ "none": None,
+}
+
+
+async def migration_url(postgres_url: str) -> Any:
+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")
+ async with admin.connect() as connection:
+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))
+ await connection.execute(text(f'CREATE DATABASE "{_DB}"'))
+ await admin.dispose()
+
+ base, _, _ = postgres_url.rpartition("/")
+ try:
+ yield f"{base}/{_DB}"
+ finally:
+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")
+ async with admin.connect() as connection:
+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_DB}"'))
+ await admin.dispose()
+
+
+async def _insert(engine: AsyncEngine, icons: dict[str, str | None]) -> None:
+ async with engine.begin() as connection:
+ # The agents' tenants, clients and keys are beside the point here.
+ await connection.execute(text("SET LOCAL session_replication_role = replica"))
+ for name, icon_url in icons.items():
+ await connection.execute(
+ text(
+ "INSERT INTO agents (tenant_id, id, name, description, icon_url, "
+ "agent_type, connector_type, integration_profile, client_id, "
+ "api_key_id) VALUES ('t', :name, :name, '', :icon_url, "
+ "'auto_session', 'mcp', '{}', :name, :name)"
+ ),
+ {"name": name, "icon_url": icon_url},
+ )
+
+
+async def _icons(engine: AsyncEngine) -> dict[str, str | None]:
+ async with engine.connect() as connection:
+ result = await connection.execute(text("SELECT name, icon_url FROM agents"))
+ return {row.name: row.icon_url for row in result}
+
+
+async def test_generated_robots_become_gaze_and_back(migration_url: str) -> None:
+ engine = create_async_engine(migration_url)
+ try:
+ async with engine.begin() as connection:
+ await connection.run_sync(
+ _migrate_to(_PRE_MIGRATION_REVISION, downgrade=False)
+ )
+ await _insert(
+ engine,
+ {
+ "named": f"{_ROBOT}?seed=named&size=256",
+ "picked": f"{_ROBOT}?seed=named-2-7&size=256",
+ "random": f"{_ROBOT}?seed={_UUID}&size=256",
+ "escaped": f"{_ROBOT}?seed=a%26b&size=256",
+ **_UNTOUCHED,
+ },
+ )
+
+ async with engine.begin() as connection:
+ await connection.run_sync(
+ _migrate_to(_MIGRATION_UNDER_TEST, downgrade=False)
+ )
+ upgraded = await _icons(engine)
+ # Given after the upgrade: a hand-built gaze URL with options of its
+ # own, which downgrade must leave alone like the upgrade's own rule.
+ await _insert(engine, {"hand-gaze": _HAND_GAZE})
+
+ async with engine.begin() as connection:
+ await connection.run_sync(
+ _migrate_to(_PRE_MIGRATION_REVISION, downgrade=True)
+ )
+ downgraded = await _icons(engine)
+ finally:
+ await engine.dispose()
+
+ # The migration's frozen URL is the one the server generates today, so an
+ # agent moved by it looks the same as one created after it.
+ assert upgraded == {
+ "named": generated_icon_url("named"),
+ "picked": generated_icon_url("named-2-7"),
+ "random": generated_icon_url(_UUID),
+ "escaped": generated_icon_url("a&b"),
+ **_UNTOUCHED,
+ }
+ assert downgraded == {
+ "named": f"{_ROBOT}?seed=named&size=256",
+ "picked": f"{_ROBOT}?seed=named-2-7&size=256",
+ "random": f"{_ROBOT}?seed={_UUID}&size=256",
+ "escaped": f"{_ROBOT}?seed=a%26b&size=256",
+ "hand-gaze": _HAND_GAZE,
+ **_UNTOUCHED,
+ }