Skip to content

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

fix(console): Switch Console bug round-up #2 (CHOO-2203) (#260)

Louis Amaudruzd9489b28100c
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 5af84bb89..e54d55f1f 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
@@ -236,8 +236,7 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
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. */}
+ recognised by. */}
<div className="flex flex-col items-center gap-1.5 pb-1">
<AgentIconPicker
name={form.agentName}
@@ -246,7 +245,7 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })
size={84}
/>
<span className="text-xs text-foreground-muted">
- {form.iconUrl === null ? 'Automatically generated' : 'Click to change'}
+ {form.iconIsGenerated ? 'Automatically generated' : 'Custom icon'}
</span>
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
index d822825d0..991eefba1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
@@ -1,4 +1,5 @@
import { useCallback, useState } from 'react';
+import { randomAgentAvatarUrl } from '@shared/core/agents/agent-avatar';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';
import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';
@@ -52,11 +53,13 @@ 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);
+ // The agent's icon (CHOO-2171). A new agent opens on a random bot rather than
+ // one drawn from its name: the name is empty at that point, so a name-derived
+ // seed is the same constant for everybody, and two agents that end up sharing
+ // a name have no reason to share a face. Null still means "whatever the name
+ // generates" — that is what the ✕ in the picker returns to.
+ const [initialIconUrl] = useState(randomAgentAvatarUrl);
+ const [iconUrl, setIconUrl] = useState<string | null>(initialIconUrl);
const setAutoApprove = useCallback((value: boolean) => {
setAutoApproveRaw(value);
@@ -95,6 +98,10 @@ export function useConfigureAgentForm() {
setAddressingPolicy,
iconUrl,
setIconUrl,
+ /** Whether the icon on screen is still one this app drew, as opposed to one
+ * the user went and chose. Only the caption cares; the value sent to the
+ * server is `iconUrl` either way. */
+ iconIsGenerated: iconUrl === null || iconUrl === initialIconUrl,
isValid,
};
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
index 47db85faf..4a0801d62 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.test.ts
@@ -13,6 +13,11 @@ const mocks = vi.hoisted(() => ({
inspectLocationPath: vi.fn(),
openLocation: vi.fn(),
eventOn: vi.fn(),
+ refreshAfterOnboarding: vi.fn(async () => {}),
+}));
+
+vi.mock('@renderer/features/sidebar/sidebar-tree-data', () => ({
+ refreshSidebarRoomStateAfterOnboarding: mocks.refreshAfterOnboarding,
}));
vi.mock('@renderer/lib/ipc', () => ({
@@ -179,6 +184,30 @@ describe('LocationManagerStore agent onboarding', () => {
expect(loc.phase).toBe('error');
expect(loc.error).toBe('Sign in to Pilot before adding this agent.');
}
+
+ expect(mocks.refreshAfterOnboarding).not.toHaveBeenCalled();
+ });
+
+ it('refreshes sidebar room state once the agent is onboarded', async () => {
+ const store = new LocationManagerStore();
+
+ const result = await store.startAgentOnboarding(
+ {
+ mode: 'pick',
+ name: 'Location',
+ path: '/location',
+ serverId: 'server-1',
+ providerId: 'claude',
+ },
+ { id: 'optimistic-location' }
+ );
+
+ expect(result.kind).toBe('creating');
+ if (result.kind === 'creating') await result.completion;
+
+ // The agent's rooms are written server-side after onboarding returns, so
+ // nothing would show them until the background reconcile without this.
+ expect(mocks.refreshAfterOnboarding).toHaveBeenCalledTimes(1);
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
index 37be9b07f..d8693138a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
@@ -1,5 +1,6 @@
import { err, ok } from '@switch-console/shared';
import { makeObservable, observable, runInAction } from 'mobx';
+import { refreshSidebarRoomStateAfterOnboarding } from '@renderer/features/sidebar/sidebar-tree-data';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
@@ -184,6 +185,7 @@ export class LocationManagerStore {
// Drop the optimistic placeholder; key the store by the real location id.
runInAction(() => this.locations.delete(placeholderId));
this._setAndOpenLocation(location.id, location);
+ void refreshSidebarRoomStateAfterOnboarding();
result = ok();
}
} catch (error) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
index 7aa54ec13..94aac1b64 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
@@ -15,10 +15,12 @@ import { refreshSidebarRoomState } from './sidebar-tree-data';
/**
* How often the room state is reconciled against the servers while the window
- * is visible. Slow on purpose: it is a safety net for changes made outside this
- * app, not the primary path — mutations made here refresh immediately.
+ * is visible. A safety net for changes made outside this app, not the primary
+ * path — mutations made here refresh immediately. Kept short enough that a
+ * change nothing here initiated (a bridge adopting a channel, an agent joining
+ * a room server-side) does not sit invisible for a noticeable stretch.
*/
-const ROOM_STATE_RECONCILE_MS = 60_000;
+const ROOM_STATE_RECONCILE_MS = 20_000;
/** @see refreshSidebarRoomState — shared so every trigger, including the
* mutations in other components, refreshes the same set. */
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 bb2fbb623..0728867b0 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
@@ -124,6 +124,31 @@ export async function refreshSidebarRoomState(force: boolean): Promise<void> {
void giveExistingAgentsAnIcon();
}
+/**
+ * Gaps between the passes {@link refreshSidebarRoomStateAfterOnboarding} makes.
+ * Spread over a few seconds rather than fired once, because the state being
+ * waited for does not exist yet when onboarding returns.
+ */
+const POST_ONBOARD_REFRESH_GAPS_MS = [0, 2_000, 4_000];
+
+/**
+ * Catch up after onboarding an agent, whose rooms land asynchronously.
+ *
+ * Onboarding returns once the agent is registered, but its room membership is
+ * still being written: the collaboration bridge creates the agent's bot on the
+ * chat platform and adds it to the team, the platform auto-joins it to that
+ * team's default channels, and only then does the bridge see those joins and
+ * record the rooms. A single refresh on completion reliably loses that race and
+ * leaves the new agent looking roomless until the background reconcile, so
+ * re-read a few times across the window in which the server settles.
+ */
+export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {
+ for (const gap of POST_ONBOARD_REFRESH_GAPS_MS) {
+ if (gap > 0) await new Promise((resolve) => setTimeout(resolve, gap));
+ await refreshSidebarRoomState(true);
+ }
+}
+
/**
* 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
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/theme-tokens.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/theme-tokens.ts
index 833bcd70f..8bf0f4feb 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/theme-tokens.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/theme-tokens.ts
@@ -14,7 +14,9 @@ const TOKEN_VARIABLES: Record<keyof ThemeTokens, string> = {
foregroundMuted: '--foreground-muted',
border: '--border',
accent: '--primary-button-border',
- accentStrong: '--selection',
+ // Link and mention text, so it needs a foreground colour: `--selection` is a
+ // highlight background and is unreadable as text on the light palette.
+ accentStrong: '--foreground-info',
buttonBg: '--primary-button-background',
buttonColor: '--primary-button-foreground',
destructive: '--foreground-destructive',
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 c3175a159..fe81eb489 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-icon-picker.tsx
@@ -1,4 +1,4 @@
-import { RotateCw, X } from 'lucide-react';
+import { Pencil, RotateCw, X } from 'lucide-react';
import { useState } from 'react';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { Input } from '@renderer/lib/ui/input';
@@ -19,10 +19,9 @@ const TABS: readonly { value: PickerTab; label: string }[] = [
* 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.
+ * 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
+ * name to draw from.
*/
export function AgentIconPicker({
name,
@@ -71,11 +70,22 @@ export function AgentIconPicker({
aria-label="Change the agent's icon"
disabled={disabled}
className={cn(
- 'rounded-full transition-opacity',
+ 'relative rounded-full transition-opacity',
!disabled && 'cursor-pointer hover:opacity-80'
)}
>
<AgentAvatar name={seedName} iconUrl={iconUrl} size={size} />
+ {/* Shown at rest rather than on hover: that the picture is editable at
+ all is not guessable, and a hover-only affordance answers the
+ question only for someone who already suspected the answer. */}
+ {!disabled ? (
+ <span
+ aria-hidden
+ className="absolute right-0 bottom-0 flex size-6 items-center justify-center rounded-full border border-border bg-background text-foreground-muted shadow-sm"
+ >
+ <Pencil className="size-3" />
+ </span>
+ ) : null}
</PopoverTrigger>
<PopoverContent align="center" sideOffset={8} className="w-80 gap-3">
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
new file mode 100644
index 000000000..3b56e2904
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-icon.test.tsx
@@ -0,0 +1,73 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+/**
+ * The picture a brand-new agent opens on (CHOO-2203).
+ *
+ * The form used to start with no icon at all, which left the avatar seeded by
+ * the empty name — a single hard-coded bot that every agent, for every user,
+ * was first shown as. Pinned here because it is invisible to every other test:
+ * a constant icon is a working icon, just the same one every time.
+ */
+import { useConfigureAgentForm } from '@renderer/features/locations/components/add-agent-modal/modes';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ if (root) await act(async () => root!.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+/** The icon state the creation form starts on, read off the real hook. */
+async function initialIcon(): Promise<{ iconUrl: string | null; iconIsGenerated: boolean }> {
+ let seen: { iconUrl: string | null; iconIsGenerated: boolean } = {
+ iconUrl: null,
+ iconIsGenerated: false,
+ };
+ function Probe() {
+ const form = useConfigureAgentForm();
+ seen = { iconUrl: form.iconUrl, iconIsGenerated: form.iconIsGenerated };
+ return null;
+ }
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ )
+ );
+ await act(async () => root!.unmount());
+ root = null;
+ container.remove();
+ container = null;
+ return seen;
+}
+
+describe('a new agent', () => {
+ it('starts on a concrete generated icon', async () => {
+ const { iconUrl } = await initialIcon();
+ expect(iconUrl).toContain('/bottts/png?');
+ });
+
+ it('counts that icon as generated rather than chosen', async () => {
+ // Drives the caption under the avatar: the user has not picked anything
+ // yet, so it must not claim they have.
+ expect((await initialIcon()).iconIsGenerated).toBe(true);
+ });
+
+ it('gives two agents created in a row different icons', async () => {
+ // The bug: with a name-derived seed and no name yet, every agent opened on
+ // the same bot.
+ const first = await initialIcon();
+ const second = await initialIcon();
+ expect(first.iconUrl).not.toBe(second.iconUrl);
+ });
+});
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 823a2c098..341bf37a1 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-avatar.test.ts
@@ -5,8 +5,22 @@ import {
agentAvatarUrlForName,
agentAvatarUrlForSeed,
agentInitials,
+ randomAgentAvatarUrl,
} from './agent-avatar';
+describe('randomAgentAvatarUrl', () => {
+ it('draws a different bot 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));
+ expect(urls.size).toBe(20);
+ });
+
+ it('is an ordinary avatar URL once drawn', () => {
+ expect(randomAgentAvatarUrl()).toContain('/bottts/png?');
+ });
+});
+
describe('agentAvatarUrlForSeed', () => {
it('is stable for a seed', () => {
// The whole scheme rests on this: an agent's generated avatar is stored
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 8c82f95fe..393928dba 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
@@ -45,6 +45,18 @@ export function agentAvatarUrlForName(agentName: string): string {
return agentAvatarUrlForSeed(agentName);
}
+/**
+ * An avatar drawn from a fresh random seed.
+ *
+ * For a *new* agent, whose name is not typed yet and whose eventual name is no
+ * reason for two people's agents to look alike. Determinism is the point
+ * everywhere else in this module, so the randomness is confined to picking the
+ * seed: once drawn, the URL is an ordinary stable one.
+ */
+export function randomAgentAvatarUrl(): string {
+ return agentAvatarUrlForSeed(crypto.randomUUID());
+}
+
/**
* 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
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 8df4d7c5f..ae38e5ee1 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -44,6 +44,13 @@ logger = logging.getLogger(__name__)
# stream unbounded data into memory.
_MAX_BOT_ICON_BYTES = 5 * 1024 * 1024
+# Mattermost channel types a bot can be *added* to: open and private channels.
+# Membership of a DM ("D") or group DM ("G") is a property of the conversation
+# existing rather than of anyone joining, so Mattermost raises no `user_added`
+# for them and they must not be adopted from a membership sweep either — a DM
+# becomes a room when someone actually writes in it.
+_JOINABLE_MM_CHANNEL_TYPES = frozenset({"O", "P"})
+
class MattermostConnectionConfig(BridgeConnectionConfig):
url: str
@@ -903,8 +910,66 @@ class MattermostAdapter(CollaborationAdapter):
)
ws_thread.start()
+ await self._bridge_channels_already_joined(agent_name, bot_id)
+
logger.info("Created Mattermost bot identity: %s", agent_name)
+ async def _bridge_channels_already_joined(
+ self, agent_name: str, bot_id: str
+ ) -> None:
+ """Bridge the channels this bot is a member of but was never seen joining.
+
+ A bot cannot witness its own joins: its websocket opens only after it has
+ been added to the team, by which point Mattermost has already put it in
+ the team's default channels. Those joins are therefore noticed only if
+ some *other* agent's socket happens to be listening, which means the
+ first agent on an instance bridges nothing at all and a later one drags
+ the backlog in with it. Ask Mattermost outright instead of waiting to
+ overhear it.
+
+ Also runs for every known agent on startup, so a channel joined while the
+ bridge was down is picked up rather than waiting for the next message in
+ it.
+ """
+ loop = self._main_loop
+ if self._on_agent_joined is None or self._admin_driver is None or loop is None:
+ return
+ try:
+ channels = await loop.run_in_executor(
+ None,
+ self._admin_driver.channels.get_channels_for_user,
+ bot_id,
+ self._team_id,
+ )
+ except Exception:
+ logger.exception(
+ "Could not list Mattermost channels for agent %s", agent_name
+ )
+ return
+
+ for channel in channels or []:
+ channel_id = str(channel.get("id", ""))
+ mm_type = str(channel.get("type", ""))
+ if not channel_id or mm_type not in _JOINABLE_MM_CHANNEL_TYPES:
+ continue
+ try:
+ await self._on_agent_joined(
+ InboundAgentJoin(
+ channel_id=channel_id,
+ channel_type=self._to_channel_type(mm_type),
+ agent_name=agent_name,
+ channel_name=str(channel.get("display_name", "")) or None,
+ )
+ )
+ except Exception:
+ # One channel that cannot be bridged is not a reason to abandon
+ # the rest, nor to fail the agent's registration.
+ logger.exception(
+ "Could not bridge Mattermost channel %s for agent %s",
+ channel_id,
+ agent_name,
+ )
+
async def _ensure_admin_bot(self) -> None:
"""Provision the dedicated Switch Admin bot used to post admin/system
messages in regular channels. Idempotent — reuses an existing bot."""
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_existing_channel_adoption.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_existing_channel_adoption.py
new file mode 100644
index 000000000..0fab07f41
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_existing_channel_adoption.py
@@ -0,0 +1,194 @@
+"""An agent's existing Mattermost channels are bridged without being overheard.
+
+A Mattermost bot never witnesses its own joins: its websocket opens only after
+it has been added to the team, and Mattermost has by then already dropped it
+into the team's default channels. Adoption used to depend entirely on those
+`user_added` broadcasts, so a join was noticed only when some *other* agent's
+socket happened to be listening — the first agent on an instance bridged
+nothing at all, and the second one dragged Town Square and Off-Topic in behind
+it.
+
+So the adapter asks Mattermost which channels the bot is in rather than waiting
+to overhear it (CHOO-2203).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from switch_core.bridges.collaboration.mattermost.adapter import (
+ MattermostAdapter,
+ MattermostConnectionConfig,
+)
+from switch_core.bridges.collaboration.models import InboundAgentJoin
+
+
+def _adapter() -> MattermostAdapter:
+ return MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+
+
+class _Channels:
+ def __init__(self, channels: list[dict[str, str]] | Exception) -> None:
+ self._channels = channels
+ self.calls: list[tuple[str, str]] = []
+
+ def get_channels_for_user(self, user_id: str, team_id: str) -> Any:
+ self.calls.append((user_id, team_id))
+ if isinstance(self._channels, Exception):
+ raise self._channels
+ return self._channels
+
+
+class _Driver:
+ def __init__(self, channels: _Channels) -> None:
+ self.channels = channels
+
+
+def _wire(
+ adapter: MattermostAdapter, channels: list[dict[str, str]] | Exception
+) -> tuple[_Channels, list[InboundAgentJoin]]:
+ endpoint = _Channels(channels)
+ adapter._admin_driver = _Driver(endpoint) # type: ignore[assignment]
+ adapter._team_id = "team-1"
+ seen: list[InboundAgentJoin] = []
+
+ async def on_agent_joined(join: InboundAgentJoin) -> None:
+ seen.append(join)
+
+ adapter._on_agent_joined = on_agent_joined
+ return endpoint, seen
+
+
+def _run(adapter: MattermostAdapter, agent: str = "worker") -> None:
+ async def go() -> None:
+ adapter._main_loop = asyncio.get_running_loop()
+ await adapter._bridge_channels_already_joined(agent, "bot-1")
+
+ asyncio.run(go())
+
+
+def test_bridges_every_channel_the_bot_is_already_in() -> None:
+ # The exact shape of a first agent's membership: Mattermost put it in both
+ # defaults at team-join, and nobody was listening when it happened.
+ adapter = _adapter()
+ endpoint, seen = _wire(
+ adapter,
+ [
+ {"id": "c-town", "type": "O", "display_name": "Town Square"},
+ {"id": "c-off", "type": "O", "display_name": "Off-Topic"},
+ ],
+ )
+
+ _run(adapter)
+
+ assert endpoint.calls == [("bot-1", "team-1")]
+ assert [join.channel_id for join in seen] == ["c-town", "c-off"]
+ assert [join.channel_name for join in seen] == ["Town Square", "Off-Topic"]
+ assert {join.agent_name for join in seen} == {"worker"}
+
+
+def test_carries_the_channel_type_across() -> None:
+ # The room is provisioned from this, so a private channel must not be
+ # bridged as a public one.
+ adapter = _adapter()
+ _, seen = _wire(
+ adapter,
+ [
+ {"id": "c-pub", "type": "O", "display_name": "Public"},
+ {"id": "c-priv", "type": "P", "display_name": "Private"},
+ ],
+ )
+
+ _run(adapter)
+
+ assert [join.channel_type for join in seen] == [
+ "channel_public",
+ "channel_private",
+ ]
+
+
+def test_leaves_direct_and_group_messages_alone() -> None:
+ # A bot has a DM channel with the admin the moment anyone opens one, and it
+ # is listed among its channels whether or not a word was ever said in it.
+ # Nobody "joins" a DM, so the join path could never have reported one, and
+ # sweeping memberships must not invent rooms the events never would have —
+ # a DM becomes a room when someone writes in it.
+ adapter = _adapter()
+ _, seen = _wire(
+ adapter,
+ [
+ {"id": "c-dm", "type": "D", "display_name": ""},
+ {"id": "c-group", "type": "G", "display_name": ""},
+ {"id": "c-real", "type": "O", "display_name": "Town Square"},
+ ],
+ )
+
+ _run(adapter)
+
+ assert [join.channel_id for join in seen] == ["c-real"]
+
+
+def test_skips_a_channel_type_it_does_not_recognise() -> None:
+ # Unknown types map to "channel_public" by default, so an allowlist is what
+ # keeps a future Mattermost channel kind from being bridged as an open one.
+ adapter = _adapter()
+ _, seen = _wire(adapter, [{"id": "c-new", "type": "Z", "display_name": "New"}])
+
+ _run(adapter)
+
+ assert seen == []
+
+
+def test_one_unbridgeable_channel_does_not_strand_the_others() -> None:
+ # This runs inside agent registration, so a single bad channel must not take
+ # the agent's other rooms — or the registration itself — down with it.
+ adapter = _adapter()
+ _, seen = _wire(
+ adapter,
+ [
+ {"id": "c-bad", "type": "O", "display_name": "Bad"},
+ {"id": "c-good", "type": "O", "display_name": "Good"},
+ ],
+ )
+ failed: list[str] = []
+
+ async def on_agent_joined(join: InboundAgentJoin) -> None:
+ if join.channel_id == "c-bad":
+ failed.append(join.channel_id)
+ raise RuntimeError("room provisioning blew up")
+ seen.append(join)
+
+ adapter._on_agent_joined = on_agent_joined
+
+ _run(adapter)
+
+ assert failed == ["c-bad"]
+ assert [join.channel_id for join in seen] == ["c-good"]
+
+
+def test_a_failed_listing_is_survivable() -> None:
+ # Mattermost being unreachable at this moment must not fail the agent.
+ adapter = _adapter()
+ _, seen = _wire(adapter, RuntimeError("mattermost down"))
+
+ _run(adapter)
+
+ assert seen == []
+
+
+def test_does_nothing_before_the_bridge_is_wired() -> None:
+ adapter = _adapter()
+ endpoint, _ = _wire(adapter, [{"id": "c", "type": "O", "display_name": "C"}])
+ adapter._on_agent_joined = None # type: ignore[assignment]
+
+ _run(adapter)
+
+ assert endpoint.calls == []