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(switchdash): make a room's members, count and picker one read (CHOO-1943)

Louis Amaudruz8cdf01309544
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
index 96968c0cd..fec310b7d 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/agents-store.ts
@@ -64,6 +64,23 @@ export class AgentsStore {
return null;
}
+ /**
+ * This install's agents that are registered on a given Switch server, i.e.
+ * the ones switchdash can actually act on there. The room views list and
+ * offer these and no others: an agent registered on some other switchdash
+ * cannot be shown under a room or driven from here, so offering it would
+ * promise something this app cannot deliver.
+ */
+ agentsOnServer(serverId: string): Agent[] {
+ const matching: Agent[] = [];
+ for (const agents of this.byLocation.values()) {
+ for (const agent of agents) {
+ if (agent.serverId === serverId && agent.switchAgentId) matching.push(agent);
+ }
+ }
+ return matching.sort((a, b) => a.name.localeCompare(b.name));
+ }
+
/** The Switch server a location's agents belong to, or null if unlinked. */
serverIdForLocation(locationId: string): string | null {
const agents = this.byLocation.get(locationId);
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index 2ce023695..2a3433ca3 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -85,7 +85,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
void toastPromise(
rpc.switchServers
.removeRoomAgent({ serverId, roomId, agentId: agent.switchAgentId })
- .then(() => switchRoomsStore.refreshAll()),
+ .then(() => switchRoomsStore.refreshRoomState()),
{
loading: `Removing ${label} from ${roomLabel}…`,
success: `${label} was removed from ${roomLabel}`,
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.tsx
index 77a07ea81..cce1e6210 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
@@ -18,7 +18,12 @@ import {
roomLabel,
} from './sidebar-room-grouping';
import { roomAgentGroupKey, roomViewGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
-import { type AgentEntry, agentSessions, scopedAgents } from './sidebar-tree-data';
+import {
+ type AgentEntry,
+ agentSessions,
+ agentsInActiveScope,
+ scopedAgents,
+} from './sidebar-tree-data';
/**
* The room-grouped sidebar: rooms at the top level, their member agents
@@ -34,18 +39,24 @@ import { type AgentEntry, agentSessions, scopedAgents } from './sidebar-tree-dat
/** Which of this app's agents belong to which room. Membership, not sessions:
* an agent is in a room whether or not it is running there — and, just as
* importantly, is *out* of it the moment membership is dropped, without waiting
- * for a session that is still pointed at the room to end. */
+ * for a session that is still pointed at the room to end.
+ *
+ * The membership itself is owned by the room store, which is also what the
+ * member count and the invite picker read; this only puts a local agent behind
+ * each id. Agent filters are deliberately not applied — they narrow the agent
+ * view, and a room's membership is a fact about the room, not about which
+ * agents you are currently looking at. */
function membersByRoom(): Map<string, AgentEntry[]> {
+ const byId = new Map<string, AgentEntry>();
+ for (const entry of agentsInActiveScope()) {
+ if (entry.agent.switchAgentId) byId.set(entry.agent.switchAgentId, entry);
+ }
const byRoom = new Map<string, AgentEntry[]>();
- for (const entry of scopedAgents()) {
- const { serverId, switchAgentId } = entry.agent;
- if (!serverId || !switchAgentId) continue;
- for (const membership of switchRoomsStore.roomsFor(serverId, switchAgentId) ?? []) {
- if (membership.archived) continue;
- const list = byRoom.get(membership.roomId);
- if (list) list.push(entry);
- else byRoom.set(membership.roomId, [entry]);
- }
+ for (const [roomId, memberIds] of switchRoomsStore.localMemberIdsByRoom) {
+ const entries = memberIds
+ .map((switchAgentId) => byId.get(switchAgentId))
+ .filter((entry): entry is AgentEntry => entry !== undefined);
+ if (entries.length > 0) byRoom.set(roomId, entries);
}
return byRoom;
}
@@ -121,7 +132,8 @@ export const RoomTree = observer(function RoomTree() {
header={
<RoomRow
label={roomLabel(roomKey)}
- count={roomSessions.length}
+ count={agentsInRoom.length}
+ undrawableCount={switchRoomsStore.undrawableMemberCount(roomKey)}
expanded={expanded}
depth={0}
bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}
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.tsx
index ee84f872e..aac6dbf49 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
@@ -39,8 +39,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
void loadRooms(false);
void switchServersStore.init().then(() => switchRoomsStore.loadRoomNames());
const onFocus = () => {
- void loadRooms(true);
- void switchRoomsStore.loadRoomNames();
+ void loadRooms(true).then(() => switchRoomsStore.loadRoomNames());
};
window.addEventListener('focus', onFocus);
return () => window.removeEventListener('focus', onFocus);
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.tsx
index 161728f9d..ecc96c817 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
@@ -104,9 +104,15 @@ export function RoomRow({
isActive = false,
depth = 0,
bridgeType = null,
+ undrawableCount = null,
}: {
label: string;
count: number;
+ /** 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
+ * not read as a member that is not there. Null when unknown. */
+ undrawableCount?: number | null;
expanded: boolean;
onToggle: () => void;
onOpenGateway: () => void;
@@ -219,6 +225,19 @@ export function RoomRow({
<TooltipContent>Open in gateway</TooltipContent>
</Tooltip>
<span className="shrink-0 text-xs text-foreground-tertiary-passive">{count}</span>
+ {undrawableCount !== null && undrawableCount > 0 && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="shrink-0 text-xs text-foreground-muted">+{undrawableCount}</span>
+ }
+ />
+ <TooltipContent>
+ {undrawableCount} more {undrawableCount === 1 ? 'member is' : 'members are'} in this
+ room but not on this switchdash, so they cannot be shown here
+ </TooltipContent>
+ </Tooltip>
+ )}
</SidebarMenuRow>
);
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
index 6de430322..92fc8a515 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -35,6 +35,24 @@ export function scopedAgents(): AgentEntry[] {
return sidebarStore.orderAgents(entries, (entry) => entry.agent.id);
}
+/**
+ * Every agent on the active server, ignoring the agent filters.
+ *
+ * Room membership is a fact about a room, so the agents a room lists — and the
+ * agents whose membership is fetched at all — must not depend on which filters
+ * the agent view happens to have set. {@link scopedAgents} is the filtered list
+ * and stays the right one for rendering the agent tree itself.
+ */
+export function agentsInActiveScope(): AgentEntry[] {
+ const entries: AgentEntry[] = [];
+ for (const location of sidebarStore.orderedLocations) {
+ for (const agent of agentsStore.byLocation.get(location.id) ?? []) {
+ entries.push({ agent, location });
+ }
+ }
+ return entries;
+}
+
/**
* An agent's visible sessions: the location's sessions it owns. Sessions are
* paired to their agent by `agent_id` — the authoritative link — not by matching
@@ -49,10 +67,12 @@ export function agentSessions(entry: AgentEntry): SessionStore[] {
);
}
-/** Every scoped agent that has a Switch identity, as membership-lookup keys. */
+/** Every agent on the active server that has a Switch identity, as
+ * membership-lookup keys. Unfiltered on purpose — see
+ * {@link agentsInActiveScope}. */
export function switchIdentities(): { serverId: string; switchAgentId: string }[] {
const identities: { serverId: string; switchAgentId: string }[] = [];
- for (const { agent } of scopedAgents()) {
+ for (const { agent } of agentsInActiveScope()) {
if (agent.serverId && agent.switchAgentId) {
identities.push({ serverId: agent.serverId, switchAgentId: agent.switchAgentId });
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index eae619d78..5b89dbaf7 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -1,7 +1,7 @@
-import { useQuery } from '@tanstack/react-query';
import { ChevronDown, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
@@ -24,10 +24,12 @@ import {
} from '@renderer/lib/ui/dialog';
import { Field, FieldLabel } from '@renderer/lib/ui/field';
import { cn } from '@renderer/utils/utils';
-import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
type Props = BaseModalProps<void> & { roomId: string };
+/** An agent that can be added: this install's agent, by its Switch identity. */
+type Candidate = { id: string; name: string };
+
export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
roomId,
onSuccess,
@@ -37,29 +39,25 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
const serverId = switchRoomsStore.roomServerId(roomId);
const roomName = switchRoomsStore.roomNameById(roomId);
- const [selected, setSelected] = useState<RemoteAgentSummary[]>([]);
+ const [selected, setSelected] = useState<Candidate[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
- const agentsQuery = useQuery({
- queryKey: ['remote-agents', serverId],
- queryFn: () => rpc.switchServers.listRemoteAgents(serverId!),
- enabled: !!serverId,
- });
- const membersQuery = useQuery({
- queryKey: ['roomAgentIds', serverId, roomId],
- queryFn: () => rpc.switchServers.listRoomAgentIds({ serverId: serverId!, roomId }),
- enabled: !!serverId,
- });
-
- // Agents already in the room are dropped rather than shown as no-ops: the
- // server ignores them, so offering them would suggest an effect there isn't.
- const members = new Set(membersQuery.data ?? []);
- const candidates = (agentsQuery.data ?? []).filter(
- (a) => !members.has(a.id) && !selected.some((s) => s.id === a.id)
- );
- const loading = agentsQuery.isLoading || membersQuery.isLoading;
- const nothingToAdd = !loading && candidates.length === 0 && selected.length === 0;
+ // Who can be added is answered from the same state the sidebar draws the room
+ // from, not from a query of its own: the room's members and the agents on
+ // offer have to be the same two sets the tree uses, or the picker and the
+ // sidebar can disagree about who is already in the room.
+ const members = new Set(switchRoomsStore.localMemberIds(roomId));
+ // Only this install's agents are offered. An agent registered on another
+ // switchdash could be added server-side but could never be shown or driven
+ // from here, so it is not ours to offer.
+ const candidates: Candidate[] = serverId
+ ? agentsStore
+ .agentsOnServer(serverId)
+ .map((agent) => ({ id: agent.switchAgentId as string, name: agent.name }))
+ .filter((a) => !members.has(a.id) && !selected.some((s) => s.id === a.id))
+ : [];
+ const nothingToAdd = candidates.length === 0 && selected.length === 0;
const handleSubmit = useCallback(async () => {
if (!serverId || selected.length === 0) return;
@@ -72,11 +70,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
roomId,
agentIds: selected.map((a) => a.id),
});
- // The sidebar lists agents under a room by membership, so the caches that
- // answer "which rooms is this agent in" have to be re-read, not just the
- // room list.
- await switchRoomsStore.refreshAll();
- await switchRoomsStore.loadRoomNames();
+ await switchRoomsStore.refreshRoomState();
onSuccess();
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
@@ -104,32 +98,32 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
<Combobox
items={candidates}
value={null}
- onValueChange={(next: RemoteAgentSummary | null) => {
+ onValueChange={(next: Candidate | null) => {
if (next) setSelected((current) => [...current, next]);
setError(null);
}}
- isItemEqualToValue={(a: RemoteAgentSummary, b: RemoteAgentSummary) => a.id === b.id}
- filter={(item: RemoteAgentSummary, query) =>
+ isItemEqualToValue={(a: Candidate, b: Candidate) => a.id === b.id}
+ filter={(item: Candidate, query) =>
item.name.toLowerCase().includes(query.toLowerCase())
}
autoHighlight
>
<ComboboxTrigger
- disabled={loading || nothingToAdd}
+ disabled={nothingToAdd}
className={cn(
'flex h-9 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-transparent px-2.5 py-1 text-sm outline-none',
- (loading || nothingToAdd) && 'cursor-not-allowed opacity-60'
+ nothingToAdd && 'cursor-not-allowed opacity-60'
)}
>
<span className="flex-1 truncate text-left text-foreground-muted">
- {loading ? 'Loading agents…' : 'Add an agent'}
+ Add an agent
</span>
<ChevronDown className="size-3.5 shrink-0 text-foreground-muted" />
</ComboboxTrigger>
<ComboboxContent className="min-w-(--anchor-width)">
<ComboboxInput showTrigger={false} placeholder="Search agents…" />
<ComboboxList>
- {(item: RemoteAgentSummary) => (
+ {(item: Candidate) => (
<ComboboxItem key={item.id} value={item}>
<span className="min-w-0 flex-1 truncate">{item.name}</span>
</ComboboxItem>
@@ -162,7 +156,8 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
)}
{nothingToAdd && (
<p className="mt-1 text-xs text-foreground-muted">
- Every agent on this server is already in the room.
+ Every agent on this switchdash is already in the room. Agents registered elsewhere
+ can only be added from the gateway.
</p>
)}
</Field>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index a0edb8863..7d589e413 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -113,10 +113,9 @@ export const CreateRoomModal = observer(function CreateRoomModal({
return;
}
- // Refresh the room caches so the sidebar shows the room straight away
+ // Re-read the room state so the sidebar shows the room straight away
// rather than at the next window focus.
- await switchRoomsStore.loadRoomNames();
- void switchRoomsStore.refreshAll();
+ await switchRoomsStore.refreshRoomState();
onSuccess({ roomId: result.room.id });
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index 52d897eeb..5ae6ee5d6 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -61,7 +61,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
// Refresh the bridge list everywhere it is consumed — this
// card and the room-creation picker share the query key.
void queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
- void switchRoomsStore.refreshAll();
+ void switchRoomsStore.refreshRoomState();
},
})
}
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.ts
index a6f41f8d2..227b1bdfc 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
@@ -157,6 +157,87 @@ describe('agent memberships', () => {
expect(listAgentRooms).toHaveBeenCalledTimes(2);
});
+ it('inverts memberships into the room-keyed view the sidebar draws', async () => {
+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => [
+ { roomId: 'shared', roomName: 'r', archived: false, status: 'live', roomRole: null },
+ {
+ roomId: `only-${agentId}`,
+ 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.localMemberIds('shared').sort()).toEqual(['agent-1', 'agent-2']);
+ expect(store.localMemberIds('only-agent-1')).toEqual(['agent-1']);
+ });
+
+ it('leaves an archived membership out of the room’s member list', async () => {
+ listAgentRooms.mockImplementation(async () => [
+ { roomId: 'gone', roomName: 'r', archived: true, status: 'live', roomRole: null },
+ ]);
+ const store = new SwitchRoomsStore();
+
+ await store.ensureMembershipsFor([{ serverId: 'srv-a', switchAgentId: 'agent-1' }]);
+
+ expect(store.localMemberIds('gone')).toEqual([]);
+ });
+
+ it('discloses members the server counts that this install cannot draw', async () => {
+ serversStore.servers = [{ id: 'srv-a', managed: true }];
+ serversStore.activeServerId = 'srv-a';
+ listRemoteRooms.mockImplementation(async () => [
+ room('shared', 'user-of-srv-a', { agentCount: 3 }),
+ ]);
+ listAgentRooms.mockImplementation(async () => [
+ { roomId: 'shared', roomName: 'r', archived: false, status: 'live', roomRole: null },
+ ]);
+ const store = new SwitchRoomsStore();
+
+ await store.loadRoomNames();
+ await store.ensureMembershipsFor([{ serverId: 'srv-a', switchAgentId: 'agent-1' }]);
+
+ // One member is drawable here; the other two exist but belong elsewhere.
+ expect(store.localMemberIds('shared')).toEqual(['agent-1']);
+ expect(store.undrawableMemberCount('shared')).toBe(1 + 1);
+ });
+
+ it('reports the undrawable count as unknown until the room list has loaded', () => {
+ const store = new SwitchRoomsStore();
+
+ expect(store.undrawableMemberCount('never-loaded')).toBeNull();
+ });
+
+ it('re-reads every tracked agent on refresh, not just the ones already cached', async () => {
+ // An agent created after the sidebar mounted has no cache entry, so a
+ // refresh keyed on the cache would never fetch it.
+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) => {
+ if (agentId === 'agent-late') throw new Error('not yet');
+ return [{ roomId: 'room-a', roomName: 'r', archived: false, status: 'live', roomRole: null }];
+ });
+ listRemoteRooms.mockImplementation(async () => []);
+ const store = new SwitchRoomsStore();
+ await store.ensureMembershipsFor([
+ { serverId: 'srv-a', switchAgentId: 'agent-1' },
+ { serverId: 'srv-a', switchAgentId: 'agent-late' },
+ ]);
+ expect(store.roomsFor('srv-a', 'agent-late')).toBeUndefined();
+
+ listAgentRooms.mockImplementation(async () => [
+ { roomId: 'room-b', roomName: 'r', archived: false, status: 'live', roomRole: null },
+ ]);
+ await store.refreshRoomState();
+
+ expect(store.roomsFor('srv-a', 'agent-late')?.[0].roomId).toBe('room-b');
+ });
+
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.ts
index 785c39181..345824d39 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>();
+ /** 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
+ * after the sidebar mounted is otherwise never fetched. */
+ private trackedIdentities: { serverId: string; switchAgentId: string }[] = [];
constructor() {
makeAutoObservable(this);
@@ -229,6 +234,68 @@ export class SwitchRoomsStore {
return this.roomsByAgent.get(key(serverId, switchAgentId));
}
+ /**
+ * Room id → the Switch agent ids of this install's agents that belong to it.
+ *
+ * The gateway answers membership per agent, so the room-keyed view has to be
+ * derived. Deriving it **here, once** rather than in each tree at render time
+ * is what makes a room's member list and its member count the same read: any
+ * view that wants either reads this, so the two cannot disagree.
+ *
+ * Scope is deliberate. This install can only act on its own agents, so those
+ * are the only members the sidebar draws (see {@link undrawableMemberCount}
+ * for how the rest are disclosed).
+ */
+ get localMemberIdsByRoom(): Map<string, string[]> {
+ const byRoom = new Map<string, string[]>();
+ for (const [cacheKey, memberships] of this.roomsByAgent) {
+ const switchAgentId = cacheKey.slice(cacheKey.indexOf(':') + 1);
+ for (const membership of memberships) {
+ if (membership.archived) continue;
+ const members = byRoom.get(membership.roomId);
+ if (members) members.push(switchAgentId);
+ else byRoom.set(membership.roomId, [switchAgentId]);
+ }
+ }
+ return byRoom;
+ }
+
+ /** The Switch agent ids of this install's agents in a room. */
+ localMemberIds(roomId: string): string[] {
+ return this.localMemberIdsByRoom.get(roomId) ?? [];
+ }
+
+ /**
+ * Members the server counts for a room that this install cannot draw — agents
+ * registered elsewhere, plus any whose membership failed to load. Null when
+ * the room's server list has not loaded, so the difference is unknown rather
+ * than zero.
+ *
+ * This is never rendered as the member count. The count is the length of what
+ * is drawn; this only discloses the gap, so a member that exists but cannot be
+ * shown is not mistaken for a member that is not there.
+ */
+ undrawableMemberCount(roomId: string): number | null {
+ const total = this.roomSummaryById(roomId)?.agentCount ?? null;
+ if (total === null) return null;
+ return Math.max(0, total - this.localMemberIds(roomId).length);
+ }
+
+ /**
+ * Re-read every fact the sidebar's room state is built from: the room lists
+ * and the membership of every tracked agent.
+ *
+ * The single door for "something changed, the view must catch up". Mutations
+ * call this instead of picking their own subset of refreshes, which is how a
+ * write ends up landing in one cache and missing another.
+ */
+ async refreshRoomState(): Promise<void> {
+ await Promise.all([
+ this.loadRoomNames(),
+ this.ensureMembershipsFor(this.trackedIdentities, { force: true }),
+ ]);
+ }
+
/**
* Load membership for several agents at once. The room-grouped sidebar lists
* an agent under every room it belongs to, not only the rooms it happens to
@@ -239,6 +306,9 @@ export class SwitchRoomsStore {
agents: { serverId: string; switchAgentId: string }[],
options: { force?: boolean } = {}
): Promise<void> {
+ runInAction(() => {
+ this.trackedIdentities = agents;
+ });
await Promise.all(
agents.map((a) => this.fetchAgentRooms(a.serverId, a.switchAgentId, options))
);
@@ -286,17 +356,6 @@ export class SwitchRoomsStore {
});
}
}
-
- /** Re-fetch every cached entry (e.g. on window focus). */
- async refreshAll(): Promise<void> {
- const keys = Array.from(this.roomsByAgent.keys());
- await Promise.all(
- keys.map((k) => {
- const [serverId, switchAgentId] = k.split(':');
- return this.fetchAgentRooms(serverId, switchAgentId, { force: true });
- })
- );
- }
}
export const switchRoomsStore = new SwitchRoomsStore();