Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(switchdash): stop the sidebar rendering unknown room state as fact (CHOO-1943)
Louis Amaudruzd57efc66171a
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsxindex 15cad9fa9..63eafc611 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-tree.tsx@@ -7,6 +7,7 @@ import { SidebarSessionItem } from './session-item';import { AGENTS_CONTAINER, makeDndId, SortableBranch, SortableList } from './sidebar-dnd';import {groupByRoom,+ isRoomNameKnown,isRoomViewActive,openRoomInGateway,openRoomInMessagingApp,@@ -59,6 +60,7 @@ const AgentSessions = observer(function AgentSessions({<div key={roomKey}><RoomRowlabel={roomLabel(roomKey)}+ nameKnown={isRoomNameKnown(roomKey)}count={roomSessions.length}expanded={roomExpanded}depth={depth}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsxindex cce1e6210..c6d96be1c 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-tree.tsx@@ -10,6 +10,7 @@ import { SidebarSessionItem } from './session-item';import { makeDndId, ROOMS_CONTAINER, SortableBranch, SortableList } from './sidebar-dnd';import {groupByRoom,+ isRoomNameKnown,isRoomViewActive,openRoomInGateway,openRoomInMessagingApp,@@ -132,6 +133,7 @@ export const RoomTree = observer(function RoomTree() {header={<RoomRowlabel={roomLabel(roomKey)}+ nameKnown={isRoomNameKnown(roomKey)}count={agentsInRoom.length}undrawableCount={switchRoomsStore.undrawableMemberCount(roomKey)}expanded={expanded}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex aac6dbf49..c072e533e 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -1,3 +1,5 @@+import { AlertTriangle } from 'lucide-react';+import { reaction } from 'mobx';import { observer } from 'mobx-react-lite';import { useEffect, useRef } from 'react';import { agentsStore } from '@renderer/features/locations/stores/agents-store';@@ -11,6 +13,13 @@ import { RoomTree } from './room-tree';import { useScrollSelectionIntoView } from './sidebar-auto-scroll';import { switchIdentities } 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.+ */+const ROOM_STATE_RECONCILE_MS = 60_000;+/*** The sidebar body: loads what both trees read, then hands over to whichever* one the current grouping calls for.@@ -42,7 +51,34 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {void loadRooms(true).then(() => switchRoomsStore.loadRoomNames());};window.addEventListener('focus', onFocus);- return () => window.removeEventListener('focus', onFocus);++ // A server that was not connected when the rooms were loaded contributed+ // none, and signing in does not re-run the load by itself — so the rooms of+ // a server you just signed into would be missing until the next focus.+ const stopWatchingConnections = reaction(+ () =>+ switchServersStore.servers+ .filter((s) => switchServersStore.isConnected(s.id))+ .map((s) => s.id)+ .sort()+ .join(','),+ () => void loadRooms(true).then(() => switchRoomsStore.loadRoomNames())+ );++ // Nothing pushes room state to the app: a membership changed from Slack,+ // the gateway or another install is invisible until something asks again.+ // Focus is not enough on its own — a window left in the foreground never+ // refocuses — so reconcile on a slow timer as well.+ const reconcile = setInterval(() => {+ if (document.hidden) return;+ void switchRoomsStore.refreshRoomState();+ }, ROOM_STATE_RECONCILE_MS);++ return () => {+ window.removeEventListener('focus', onFocus);+ stopWatchingConnections();+ clearInterval(reconcile);+ };}, []);// Agent filters narrowing everything away is only an empty *agent* list. The@@ -55,6 +91,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {return (<div ref={scrollerRef} className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">+ <RoomStateDisclosure />{showFilterEmptyState ? (<p className="px-2 py-3 text-xs text-foreground-muted">No agents match filters</p>) : sidebarStore.grouping === 'room' ? (@@ -65,3 +102,41 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {</div>);});++/**+ * Says so when the room state on screen is known to be incomplete.+ *+ * The tree renders last-known rooms and memberships when a refresh fails, which+ * is the right thing to do — but rendering them silently would present a partial+ * view as the whole truth. A room missing its members and a room with no members+ * look identical otherwise.+ */+const RoomStateDisclosure = observer(function RoomStateDisclosure() {+ const unreadableServers = switchRoomsStore.unreadableServerNames;+ const unknownMemberships = switchRoomsStore.agentsWithUnknownMembership;+ if (unreadableServers.length === 0 && unknownMemberships === 0) return null;++ const reasons: string[] = [];+ if (unreadableServers.length > 0) reasons.push(`couldn’t reach ${unreadableServers.join(', ')}`);+ if (unknownMemberships > 0) {+ reasons.push(+ `${unknownMemberships} ${unknownMemberships === 1 ? 'agent’s' : 'agents’'} rooms didn’t load`+ );+ }++ return (+ <div className="mb-1 flex items-start gap-1.5 rounded-md bg-background-secondary px-2 py-1.5 text-xs text-foreground-muted">+ <AlertTriangle className="mt-px h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1">+ Rooms may be out of date — {reasons.join('; ')}.{' '}+ <button+ type="button"+ className="underline underline-offset-2 hover:text-foreground"+ onClick={() => void switchRoomsStore.refreshRoomState()}+ >+ Retry+ </button>+ </span>+ </div>+ );+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex ecc96c817..c17214273 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -21,6 +21,20 @@ export function roomLabel(roomKey: string): string {return switchRoomsStore.roomNameById(roomKey) ?? `Room ${roomKey.slice(0, 8)}`;}+/**+ * Whether a room's label is its real name or a stand-in.+ *+ * A room's id reaches the sidebar by live push while its name needs the+ * server's room list, so the two can be out of step — most often when the+ * server is not connected, or its list failed to load. The short-id fallback+ * that results looks exactly like a name, which is what makes it a lie; rows+ * use this to mark it as not-yet-known instead.+ */+export function isRoomNameKnown(roomKey: string): boolean {+ if (roomKey === UNASSIGNED_ROOM_KEY) return true;+ return switchRoomsStore.roomNameById(roomKey) !== null;+}+/** Open a room's detail page in the gateway web app (no-op for Unassigned). */export function openRoomInGateway(roomKey: string): void {if (roomKey === UNASSIGNED_ROOM_KEY) return;@@ -105,9 +119,13 @@ export function RoomRow({depth = 0,bridgeType = null,undrawableCount = null,+ nameKnown = true,}: {label: string;count: number;+ /** False when `label` is a stand-in because the room's name has not loaded.+ * Rendered as visibly provisional rather than as the room's name. */+ nameKnown?: boolean;/** Members the server counts that this install cannot draw — agents* registered on another switchdash, plus any whose membership failed to load.* Disclosed next to the count so a member that exists but cannot be shown is@@ -165,7 +183,23 @@ export function RoomRow({)}/></SidebarItemMiniButton>- <span className="min-w-0 flex-1 truncate text-sm">{label}</span>+ {nameKnown ? (+ <span className="min-w-0 flex-1 truncate text-sm">{label}</span>+ ) : (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="min-w-0 flex-1 truncate text-sm text-foreground-muted italic">+ {label}+ </span>+ }+ />+ <TooltipContent>+ This room's name hasn't loaded — its server is disconnected or did not+ respond. Shown by id until it does.+ </TooltipContent>+ </Tooltip>+ )}{channelLinkable && (<Tooltip><TooltipTriggerdiff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.tsnew file mode 100644index 000000000..da526dd41--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const getConnections = vi.hoisted(() => vi.fn());++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: vi.fn() },+ rpc: { switchRooms: { getConnections } },+}));++const { SwitchRoomsStore } = await import('./switch-rooms-store');++describe('session → room connections', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('seeds the connection set from the main process', async () => {+ getConnections.mockResolvedValue([{ sessionId: 'sess-1', roomId: 'room-a' }]);+ const store = new SwitchRoomsStore();++ store.ensureLoaded();++ await vi.waitFor(() => expect(store.roomForSession('sess-1')).toBe('room-a'));+ expect(store.seedError).toBeNull();+ });++ it('re-arms the seed after a failure instead of wedging on empty', async () => {+ // The loaded flag is set before the call, so without a failure branch every+ // session would read as connected to nothing for the whole app run — and+ // the room badges built on it would sit at zero, silently.+ getConnections.mockRejectedValueOnce(new Error('ipc down'));+ const store = new SwitchRoomsStore();++ store.ensureLoaded();+ await vi.waitFor(() => expect(store.seedError).toBe('ipc down'));++ getConnections.mockResolvedValue([{ sessionId: 'sess-2', roomId: 'room-b' }]);+ store.ensureLoaded();++ await vi.waitFor(() => expect(store.roomForSession('sess-2')).toBe('room-b'));+ expect(store.seedError).toBeNull();+ });+});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.tsindex 61524aff3..83f36fd05 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts@@ -8,10 +8,13 @@ import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomE* `sessionRoomChangedChannel` event. Connections are runtime-only — a session* disappears here when it switches rooms or its session exits.*/-class SwitchRoomsStore {+export class SwitchRoomsStore {/** sessionId → connected room id. */private roomBySession = new Map<string, string>();private loaded = false;+ /** Why the initial connection seed failed, when it did. Non-null means the+ * session→room mapping is incomplete and must not be read as authoritative. */+ seedError: string | null = null;constructor() {makeAutoObservable(this, {}, { autoBind: true });@@ -24,17 +27,33 @@ class SwitchRoomsStore {});}- /** Load the current connection set once (idempotent). */+ /**+ * Load the current connection set once (idempotent).+ *+ * A failure re-arms the load rather than leaving the flag set: the seed is+ * what every "which room is this session in" answer starts from, so wedging+ * it would report every session as connected to nothing, indefinitely and+ * without a word.+ */ensureLoaded(): void {if (this.loaded) return;this.loaded = true;- void rpc.switchRooms.getConnections().then((connections) => {- runInAction(() => {- for (const { sessionId, roomId } of connections) {- this.roomBySession.set(sessionId, roomId);- }+ void rpc.switchRooms+ .getConnections()+ .then((connections) => {+ runInAction(() => {+ this.seedError = null;+ for (const { sessionId, roomId } of connections) {+ this.roomBySession.set(sessionId, roomId);+ }+ });+ })+ .catch((cause: unknown) => {+ runInAction(() => {+ this.loaded = false;+ this.seedError = cause instanceof Error ? cause.message : String(cause);+ });});- });}/** The room a session is currently connected to, or null. */diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.tsindex 227b1bdfc..f2b70a62d 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts@@ -4,9 +4,9 @@ import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-serveconst listRemoteRooms = vi.hoisted(() => vi.fn());const listAgentRooms = vi.hoisted(() => vi.fn());const serversStore = vi.hoisted(() => ({- servers: [] as { id: string; managed?: boolean }[],+ servers: [] as { id: string; name?: string; managed?: boolean }[],activeServerId: null as string | null,- isConnected: () => true,+ isConnected: (_serverId: string): boolean => true,statusFor: (serverId: string) => ({ user: { id: `user-of-${serverId}` } }),}));@@ -117,6 +117,55 @@ describe('listed rooms', () => {expect(store.listedRoomsInActiveScope.map((r: { id: string }) => r.id)).toEqual(['srv-b-room']);});++ it('says the room list is incomplete when a server could not be read', async () => {+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ listRemoteRooms.mockImplementation(async (serverId: string) => {+ if (serverId === 'srv-a') throw new Error('unreachable');+ return [room('srv-b-room', 'user-of-srv-b')];+ });++ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.roomStateIncomplete).toBe(true);+ expect(store.unreadableServerNames).toEqual(['Alpha']);+ });++ it('counts a server it never asked as unknown, not as having no rooms', async () => {+ serversStore.servers = [+ { id: 'srv-a', name: 'Alpha' },+ { id: 'srv-b', name: 'Beta' },+ ];+ serversStore.isConnected = (serverId: string) => serverId !== 'srv-b';+ listRemoteRooms.mockImplementation(async () => []);++ const store = new SwitchRoomsStore();+ await store.loadRoomNames();++ expect(store.roomStateIncomplete).toBe(true);+ expect(store.unreadableServerNames).toEqual(['Beta']);+ serversStore.isConnected = () => true;+ });++ it('clears a server’s failure once it can be read again', async () => {+ serversStore.servers = [{ id: 'srv-a', name: 'Alpha' }];+ listRemoteRooms.mockImplementation(async () => {+ throw new Error('unreachable');+ });+ const store = new SwitchRoomsStore();+ await store.loadRoomNames();+ expect(store.roomStateIncomplete).toBe(true);++ listRemoteRooms.mockImplementation(async () => [room('back', 'user-of-srv-a')]);+ await store.loadRoomNames();++ expect(store.roomStateIncomplete).toBe(false);+ expect(store.unreadableServerNames).toEqual([]);+ });});describe('agent memberships', () => {@@ -238,6 +287,32 @@ describe('agent memberships', () => {expect(store.roomsFor('srv-a', 'agent-late')?.[0].roomId).toBe('room-b');});+ it('reports an agent whose membership failed as unknown, not as in no rooms', async () => {+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => {+ if (agentId === 'agent-1') throw new Error('nope');+ return [{ roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null }];+ });+ const store = new SwitchRoomsStore();++ await store.ensureMembershipsFor([+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },+ ]);++ expect(store.agentsWithUnknownMembership).toBe(1);+ });++ it('reports no unknown memberships once every tracked agent has loaded', async () => {+ const store = new SwitchRoomsStore();++ await store.ensureMembershipsFor([+ { serverId: 'srv-a', switchAgentId: 'agent-1' },+ { serverId: 'srv-a', switchAgentId: 'agent-2' },+ ]);++ expect(store.agentsWithUnknownMembership).toBe(0);+ });+it('lets one agent’s failed lookup stand without losing the others', async () => {listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => {if (agentId === 'agent-1') throw new Error('nope');diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.tsindex 345824d39..582445504 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts@@ -45,6 +45,11 @@ export class SwitchRoomsStore {readonly loading = new Set<string>();/** Last error per key, if the most recent fetch failed. */readonly errors = new Map<string, string>();+ /** Server id → why its room list could not be read, if the last try failed. */+ private readonly roomListErrors = new Map<string, string>();+ /** Servers that were not connected when the room list was last refreshed, so+ * their rooms were never asked for at all. */+ private unreachableServerIds: string[] = [];/** The agents whose membership this store is responsible for keeping current.* Recorded on {@link ensureMembershipsFor} so a refresh re-reads the current* set rather than only the keys that happen to be cached — an agent created@@ -190,14 +195,25 @@ export class SwitchRoomsStore {}/**- * Refresh the room id → name map from every connected server's room list.- * Best-effort: a server that fails to respond is skipped (its rooms keep- * their last-known names, or fall back to a short id in the UI).+ * Refresh the room catalogue from every connected server's room list.+ *+ * A server that cannot be read keeps its last-known rooms rather than losing+ * them, but the failure is recorded in {@link roomListErrors} instead of being+ * swallowed: last-known data rendered as if it were current is the one outcome+ * worse than showing nothing.*/async loadRoomNames(): Promise<void> {const connected = switchServersStore.servers.filter((s) =>switchServersStore.isConnected(s.id));+ runInAction(() => {+ // Not being connected is not a failure — there is simply nothing to ask+ // right now — but the rooms on that server are equally unknown, and the+ // sidebar has to be able to say so.+ this.unreachableServerIds = switchServersStore.servers+ .filter((s) => !switchServersStore.isConnected(s.id))+ .map((s) => s.id);+ });await Promise.all(connected.map(async (server) => {try {@@ -206,6 +222,7 @@ export class SwitchRoomsStore {// each gateway, so match against that server's signed-in identity.const signedInUserId = switchServersStore.statusFor(server.id)?.user?.id ?? null;runInAction(() => {+ this.roomListErrors.delete(server.id);for (const room of rooms) {this.roomNames.set(room.id, room.name);this.roomServerById.set(room.id, server.id);@@ -222,13 +239,51 @@ export class SwitchRoomsStore {signedInUserId ? active.filter((r) => r.ownerId === signedInUserId) : []);});- } catch {- // skip this server; names stay best-effort+ } catch (cause) {+ runInAction(() => {+ this.roomListErrors.set(+ server.id,+ cause instanceof Error ? cause.message : String(cause)+ );+ });}}));}+ /**+ * Whether the room catalogue on screen is known to be incomplete — a server+ * that could not be read, or one that is not connected so was never asked.+ *+ * The sidebar renders last-known rooms either way, which is the right call;+ * this is what stops it from passing them off as current.+ */+ get roomStateIncomplete(): boolean {+ return this.roomListErrors.size > 0 || this.unreachableServerIds.length > 0;+ }++ /** Names of the servers behind {@link roomStateIncomplete}, for disclosure. */+ get unreadableServerNames(): string[] {+ const ids = [...new Set([...this.roomListErrors.keys(), ...this.unreachableServerIds])];+ return ids+ .map((id) => switchServersStore.servers.find((s) => s.id === id)?.name ?? id)+ .sort((a, b) => a.localeCompare(b));+ }++ /**+ * Agents whose room membership is not known: the fetch failed, or has not run.+ *+ * Their rooms cannot list them, so a room can look emptier than it is. That is+ * indistinguishable from a genuinely empty room unless it is said out loud.+ */+ get agentsWithUnknownMembership(): number {+ return this.trackedIdentities.filter(+ ({ serverId, switchAgentId }) =>+ this.roomsByAgent.get(key(serverId, switchAgentId)) === undefined &&+ !this.isLoading(serverId, switchAgentId)+ ).length;+ }+/** Cached membership, or undefined if never fetched. */roomsFor(serverId: string, switchAgentId: string): RemoteAgentRoom[] | undefined {return this.roomsByAgent.get(key(serverId, switchAgentId));