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): scroll the selected sidebar row into view (CHOO-2010)

Christian McDermottc7571c5beebf
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
index 878a00fcf..31e476d0a 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
@@ -17,7 +17,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { REMOTE_HOSTS_QUERY_KEY } from '@renderer/features/remote-hosts/views/remote-hosts-view';
import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
-import { agentExpandKey } from '@renderer/features/sidebar/agent-item';
+import { agentExpandKey } from '@renderer/features/sidebar/sidebar-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { commandRegistry } from '@renderer/lib/commands/registry';
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx
index 036307323..8bd1b64f3 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -37,12 +37,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/toolti
import { cn } from '@renderer/utils/utils';
import type { Agent } from '@shared/core/agents/agents';
import { SidebarItemMiniButton, SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';
-import { depthIndent } from './sidebar-store';
-
-/** Expand-state key for an agent row (default open; its sessions live below it). */
-export function agentExpandKey(agentId: string): string {
- return `ag:${agentId}`;
-}
+import { agentExpandKey, depthIndent } from './sidebar-store';
/**
* A single agent in the flat sidebar list. switchdash has no main/subagent
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.tsx
index 6a7bc1487..15cad9fa9 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
@@ -2,7 +2,7 @@ import { observer } from 'mobx-react-lite';
import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { sidebarStore } from '@renderer/lib/stores/app-state';
-import { agentExpandKey, SidebarAgentItem } from './agent-item';
+import { SidebarAgentItem } from './agent-item';
import { SidebarSessionItem } from './session-item';
import { AGENTS_CONTAINER, makeDndId, SortableBranch, SortableList } from './sidebar-dnd';
import {
@@ -14,7 +14,7 @@ import {
RoomRow,
roomLabel,
} from './sidebar-room-grouping';
-import { agentRoomGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
+import { agentExpandKey, agentRoomGroupKey, UNASSIGNED_ROOM_KEY } from './sidebar-store';
import { agentSessions, scopedAgents } from './sidebar-tree-data';
/**
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx
index a54f77b88..983dc5bee 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/session-item.tsx
@@ -1,6 +1,5 @@
import { MessageSquare } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useEffect, useRef } from 'react';
import { SessionContextMenu } from '@renderer/features/sessions/components/session-context-menu';
import {
getSessionManagerStore,
@@ -10,7 +9,6 @@ import { SessionSidebarTrailingSlot } from '@renderer/features/sidebar/session-s
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { sidebarStore } from '@renderer/lib/stores/app-state';
import { cn } from '@renderer/utils/utils';
import { useAppSettingsKey } from '../settings/use-app-settings-key';
import { SidebarMenuAction, SidebarMenuRow } from './sidebar-primitives';
@@ -42,17 +40,6 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({
const isActive =
currentView === 'session' && params.sessionId === sessionId && params.locationId === locationId;
- // A deeplink reveal expands the tree and asks this session's row to center
- // itself; reading the flag in render (not just the effect) lets the row react
- // whether it was already mounted or only just appeared after the expand.
- const rowRef = useRef<HTMLDivElement>(null);
- const shouldScrollIntoView = sidebarStore.pendingScrollSessionId === sessionId;
- useEffect(() => {
- if (!shouldScrollIntoView) return;
- rowRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' });
- sidebarStore.clearPendingScroll();
- }, [shouldScrollIntoView]);
-
const session = getSessionStore(locationId, sessionId)!;
const sessionManager = getSessionManagerStore(locationId);
@@ -103,7 +90,6 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({
onDelete={handleDelete}
>
<SidebarMenuRow
- ref={rowRef}
className={cn(
'group/row flex items-center justify-between px-1 h-8 gap-1',
rowVariant === 'pinned' && 'pl-2'
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts
new file mode 100644
index 000000000..4de54c3b0
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest';
+import { scrollDeltaFor } from './sidebar-auto-scroll';
+
+// The hook this module also exports reaches the app's singletons; the scroll
+// rule under test does not.
+vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));
+vi.mock('@renderer/lib/stores/app-state', () => ({ appState: {}, sidebarStore: {} }));
+
+const viewport = { top: 100, bottom: 400 };
+const MARGIN = 8;
+
+describe('scrollDeltaFor', () => {
+ it('leaves a row that is already fully visible alone', () => {
+ expect(scrollDeltaFor(viewport, { top: 200, bottom: 232 }, MARGIN)).toBe(0);
+ });
+
+ it('leaves a row flush against an edge alone rather than nudging it by the margin', () => {
+ expect(scrollDeltaFor(viewport, { top: 100, bottom: 132 }, MARGIN)).toBe(0);
+ expect(scrollDeltaFor(viewport, { top: 368, bottom: 400 }, MARGIN)).toBe(0);
+ });
+
+ it('scrolls up for a row above the viewport, clearing the margin', () => {
+ expect(scrollDeltaFor(viewport, { top: 40, bottom: 72 }, MARGIN)).toBe(-68);
+ });
+
+ it('scrolls down for a row below the viewport, clearing the margin', () => {
+ expect(scrollDeltaFor(viewport, { top: 500, bottom: 532 }, MARGIN)).toBe(140);
+ });
+
+ it('brings a partly-cut row fully into view', () => {
+ expect(scrollDeltaFor(viewport, { top: 90, bottom: 122 }, MARGIN)).toBe(-18);
+ expect(scrollDeltaFor(viewport, { top: 380, bottom: 412 }, MARGIN)).toBe(20);
+ });
+
+ it('aligns a row taller than the viewport to the top instead of chasing it', () => {
+ expect(scrollDeltaFor(viewport, { top: 50, bottom: 600 }, MARGIN)).toBe(-58);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts
new file mode 100644
index 000000000..d0b2e041e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-auto-scroll.ts
@@ -0,0 +1,91 @@
+import { useLayoutEffect, useRef, type RefObject } from 'react';
+import { sidebarStore } from '@renderer/lib/stores/app-state';
+import { isSidebarRowDragging } from './sidebar-drag-state';
+import { currentSelectionKey, currentSidebarSelection } from './sidebar-selection';
+
+/**
+ * Keep the selected sidebar row in view.
+ *
+ * The tree has one scroll container and every row type marks itself
+ * `data-active`, so this is one effect on that container rather than a scroll
+ * call per row type — which would have to be repeated for sessions, agents,
+ * agents-under-rooms and rooms, and then again for each of the dozen places
+ * that can change the selection.
+ */
+
+/** Gap left between the row and the edge of the viewport when scrolling it in. */
+const SCROLL_MARGIN = 8;
+
+interface Edges {
+ top: number;
+ bottom: number;
+}
+
+/**
+ * How far the scroller must move for `row` to sit inside it, in pixels
+ * (negative scrolls up). Zero when the row is already fully visible — a row on
+ * screen is never nudged, whatever its position.
+ *
+ * Split out from the effect so the rule is testable without a DOM or a layout.
+ */
+export function scrollDeltaFor(scroller: Edges, row: Edges, margin = SCROLL_MARGIN): number {
+ const above = row.top - scroller.top;
+ const below = row.bottom - scroller.bottom;
+ if (above >= 0 && below <= 0) return 0;
+ // A row taller than the viewport is aligned to the top rather than chased.
+ return above < 0 ? above - margin : below + margin;
+}
+
+/**
+ * The active row to bring into view, or null when none is rendered.
+ *
+ * A room lists under every agent that has sessions in it, so several rows can
+ * be active at once. One already on screen wins: there is no reason to move the
+ * viewport to a different copy of what the user can already see.
+ */
+function activeRowIn(scroller: HTMLElement): HTMLElement | null {
+ const rows = Array.from(scroller.querySelectorAll<HTMLElement>('[data-active]'));
+ const scrollerEdges = scroller.getBoundingClientRect();
+ for (const row of rows) {
+ if (scrollDeltaFor(scrollerEdges, row.getBoundingClientRect()) === 0) return row;
+ }
+ return rows[0] ?? null;
+}
+
+export function useScrollSelectionIntoView(scrollerRef: RefObject<HTMLElement | null>): void {
+ // Read in render so the sidebar re-renders — and this effect re-runs — the
+ // moment the selection changes, wherever it was changed from.
+ const selectionKey = currentSelectionKey();
+ const settledKey = useRef<string | null>(null);
+
+ useLayoutEffect(() => {
+ const scroller = scrollerRef.current;
+ if (!scroller || settledKey.current === selectionKey) return;
+
+ const selection = currentSidebarSelection();
+ if (selection) sidebarStore.revealSelection(selection);
+
+ const bringIntoView = (): boolean => {
+ if (isSidebarRowDragging()) return false;
+ const row = activeRowIn(scroller);
+ if (!row) return false;
+ settledKey.current = selectionKey;
+ const delta = scrollDeltaFor(scroller.getBoundingClientRect(), row.getBoundingClientRect());
+ // Instant, never smooth: a glide under a held pointer travels far enough
+ // to cross the drag activation distance and turn a click into a drag.
+ if (delta !== 0) scroller.scrollTop += delta;
+ return true;
+ };
+
+ if (bringIntoView()) return;
+
+ // The row can arrive after the selection does — expanding its group renders
+ // it a beat later, and at startup the restored view is set before the tree
+ // has loaded. Watch until it shows up, then stop.
+ const pending = new MutationObserver(() => {
+ if (bringIntoView()) pending.disconnect();
+ });
+ pending.observe(scroller, { childList: true, subtree: true });
+ return () => pending.disconnect();
+ }, [selectionKey, scrollerRef]);
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx
index 06de23999..815bde46b 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx
@@ -15,6 +15,7 @@ import {
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { CSSProperties, ReactNode } from 'react';
+import { setSidebarRowDragging } from './sidebar-drag-state';
/**
* Drag-to-reorder plumbing for the sidebar's two top-level lists: the agents in
@@ -133,14 +134,24 @@ export function SortableList({
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
function onDragEnd(event: DragEndEvent) {
+ setSidebarRowDragging(false);
const { active, over } = event;
if (!over) return;
const reordered = reorderOnDrop(itemIds, String(active.id), String(over.id));
if (reordered) onReorder(reordered);
}
+ // The drag is announced to the rest of the sidebar because dnd-kit measures
+ // every droppable when it starts: anything that scrolls the list before the
+ // drop desyncs those rects and the row lands in the wrong slot.
return (
- <DndContext sensors={sensors} collisionDetection={sameContainerCollision} onDragEnd={onDragEnd}>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={sameContainerCollision}
+ onDragStart={() => setSidebarRowDragging(true)}
+ onDragCancel={() => setSidebarRowDragging(false)}
+ onDragEnd={onDragEnd}
+ >
<SortableContext
items={itemIds.map((itemId) => makeDndId(containerId, itemId))}
strategy={verticalListSortingStrategy}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-drag-state.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-drag-state.ts
new file mode 100644
index 000000000..cfbd239ce
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-drag-state.ts
@@ -0,0 +1,21 @@
+/**
+ * Whether a sidebar row is being dragged to reorder.
+ *
+ * A plain flag rather than store state: nothing renders from it, it is read
+ * once inside a callback, and keeping it free of imports keeps the drag
+ * plumbing free of the app's singletons.
+ *
+ * It exists because dnd-kit measures every droppable when a drag starts.
+ * Anything that scrolls the list before the drop desyncs those rects, and the
+ * row lands in a slot the user did not aim at.
+ */
+
+let dragging = false;
+
+export function setSidebarRowDragging(value: boolean): void {
+ dragging = value;
+}
+
+export function isSidebarRowDragging(): boolean {
+ return dragging;
+}
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 bf7b30166..ee84f872e 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,5 +1,5 @@
import { observer } from 'mobx-react-lite';
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
@@ -8,6 +8,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-ser
import { sidebarStore } from '@renderer/lib/stores/app-state';
import { AgentTree } from './agent-tree';
import { RoomTree } from './room-tree';
+import { useScrollSelectionIntoView } from './sidebar-auto-scroll';
import { switchIdentities } from './sidebar-tree-data';
/**
@@ -19,6 +20,11 @@ import { switchIdentities } from './sidebar-tree-data';
* components rather than one tree with the levels swapped.
*/
export const SidebarGroupedList = observer(function SidebarGroupedList() {
+ // The tree's only scroller, and so the only place that has to keep the
+ // selected row — session, agent, agent-under-room or room — in view.
+ const scrollerRef = useRef<HTMLDivElement>(null);
+ useScrollSelectionIntoView(scrollerRef);
+
// Live session→room connections, room names and room membership all live on
// the server; pull them once on mount and refresh on focus.
useEffect(() => {
@@ -49,7 +55,7 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
sidebarStore.filteredLocations.length === 0;
return (
- <div className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">
+ <div ref={scrollerRef} className="min-h-0 flex-1 overflow-y-auto px-3 pt-1 pb-3">
{showFilterEmptyState ? (
<p className="px-2 py-3 text-xs text-foreground-muted">No agents match filters</p>
) : sidebarStore.grouping === 'room' ? (
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-selection.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-selection.ts
new file mode 100644
index 000000000..b5d4bc690
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-selection.ts
@@ -0,0 +1,93 @@
+import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';
+import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
+import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
+import type { SidebarSelection } from './sidebar-store';
+import { agentSessions, scopedAgents } from './sidebar-tree-data';
+
+/**
+ * Which sidebar row the open view selects.
+ *
+ * Selection is read from navigation rather than reported by the rows, because
+ * the rows are the thing that may not be rendered yet — a collapsed group, or a
+ * tree that has not finished loading. It also means the dozen places that can
+ * change the selection (the palette, keyboard navigation, notifications, the app
+ * menu, modals, deeplinks, the restored view at startup) need no part in this.
+ */
+
+/**
+ * A stable key for *what* is selected, from navigation alone.
+ *
+ * Deliberately cheap and deliberately not derived from the rendered list: it is
+ * what auto-scrolling keys on, and a key that moved with the list would scroll
+ * the tree every time a drag reordered it.
+ */
+export function currentSelectionKey(): string {
+ const { navigation } = appState;
+ const grouping = sidebarStore.grouping;
+ switch (navigation.currentViewId) {
+ case 'session': {
+ const params = navigation.viewParamsStore.session;
+ return `${grouping}|session|${params?.locationId ?? ''}|${params?.sessionId ?? ''}`;
+ }
+ case 'location': {
+ const params = navigation.viewParamsStore.location;
+ return `${grouping}|location|${params?.locationId ?? ''}|${params?.agentName ?? ''}|${params?.roomId ?? ''}`;
+ }
+ case 'room': {
+ const params = navigation.viewParamsStore.room;
+ return `${grouping}|room|${params?.roomId ?? ''}`;
+ }
+ default:
+ return `${grouping}|none`;
+ }
+}
+
+/** The agents with a session in `roomKey` — the agents the agent-focused tree
+ * lists that room's heading under. */
+function agentsWithSessionsInRoom(roomKey: string): string[] {
+ const agentIds: string[] = [];
+ for (const entry of scopedAgents()) {
+ const present = agentSessions(entry).some(
+ (session) => roomConnectionsStore.roomForSession(session.data.id) === roomKey
+ );
+ if (present) agentIds.push(entry.agent.id);
+ }
+ return agentIds;
+}
+
+/**
+ * The selected row resolved to the ids the tree nests it under, or null when
+ * the open view selects nothing in the sidebar (home, settings, …).
+ */
+export function currentSidebarSelection(): SidebarSelection | null {
+ const { navigation } = appState;
+ switch (navigation.currentViewId) {
+ case 'session': {
+ const params = navigation.viewParamsStore.session;
+ if (!params) return null;
+ const session = getSessionStore(params.locationId, params.sessionId);
+ if (!session || !('agentId' in session.data) || !session.data.agentId) return null;
+ return {
+ kind: 'session',
+ agentId: session.data.agentId,
+ roomKey: roomConnectionsStore.roomForSession(params.sessionId),
+ };
+ }
+ case 'location': {
+ const params = navigation.viewParamsStore.location;
+ if (!params) return null;
+ return { kind: 'agent', roomKey: params.roomId ?? null };
+ }
+ case 'room': {
+ const params = navigation.viewParamsStore.room;
+ if (!params) return null;
+ return {
+ kind: 'room',
+ roomKey: params.roomId,
+ agentIds: agentsWithSessionsInRoom(params.roomId),
+ };
+ }
+ default:
+ return null;
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
index e76251355..5a8eeeb97 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.test.ts
@@ -4,6 +4,7 @@ import { switchServersStore } from '@renderer/features/switch-servers/switch-ser
import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';
import type { Agent } from '@shared/core/agents/agents';
import {
+ agentExpandKey,
agentRoomGroupKey,
applyManualOrder,
roomAgentGroupKey,
@@ -145,18 +146,58 @@ describe('SidebarStore grouping', () => {
expect(restored.expandedRoomKeys.has('room-2')).toBe(true);
});
- it('reveals a session in its room across both layouts', () => {
+ it('opens the agent and room group a selected session sits in', () => {
+ const store = new SidebarStore(locationManager([]));
+ // Simulate the user having collapsed both groups above the session.
+ store.toggleGroupExpanded(agentExpandKey('agent-1'));
+ store.toggleGroupExpanded(agentRoomGroupKey('agent-1', 'room-1'));
+
+ store.revealSelection({ kind: 'session', agentId: 'agent-1', roomKey: 'room-1' });
+
+ expect(store.isGroupExpanded(agentExpandKey('agent-1'))).toBe(true);
+ expect(store.isGroupExpanded(agentRoomGroupKey('agent-1', 'room-1'))).toBe(true);
+ });
+
+ it('leaves the grouping the user cannot see untouched', () => {
const store = new SidebarStore(locationManager([]));
- // Simulate the user having collapsed the room group in each layout.
- store.toggleGroupExpanded(agentRoomGroupKey('location-1', 'room-1'));
store.toggleGroupExpanded(roomViewGroupKey('room-1'));
- expect(store.isGroupExpanded(agentRoomGroupKey('location-1', 'room-1'))).toBe(false);
+ store.toggleGroupExpanded(roomAgentGroupKey('room-1', 'agent-1'));
+
+ // Agent-focused is on screen, so the room-focused groups stay as they were.
+ store.revealSelection({ kind: 'session', agentId: 'agent-1', roomKey: 'room-1' });
+
expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(false);
+ expect(store.isGroupExpanded(roomAgentGroupKey('room-1', 'agent-1'))).toBe(false);
- store.revealSessionInRoom('location-1', 'room-1');
+ store.setGrouping('room');
+ store.revealSelection({ kind: 'session', agentId: 'agent-1', roomKey: 'room-1' });
+
+ expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(true);
+ expect(store.isGroupExpanded(roomAgentGroupKey('room-1', 'agent-1'))).toBe(true);
+ });
+
+ it('opens every agent a selected room is listed under', () => {
+ const store = new SidebarStore(locationManager([]));
+ store.toggleGroupExpanded(agentExpandKey('agent-1'));
+ store.toggleGroupExpanded(agentExpandKey('agent-2'));
+
+ store.revealSelection({
+ kind: 'room',
+ roomKey: 'room-1',
+ agentIds: ['agent-1', 'agent-2'],
+ });
+
+ expect(store.isGroupExpanded(agentExpandKey('agent-1'))).toBe(true);
+ expect(store.isGroupExpanded(agentExpandKey('agent-2'))).toBe(true);
+ });
+
+ it('opens the room an agent was selected from, in the room-focused tree', () => {
+ const store = new SidebarStore(locationManager([]));
+ store.setGrouping('room');
+ store.toggleGroupExpanded(roomViewGroupKey('room-1'));
+
+ store.revealSelection({ kind: 'agent', roomKey: 'room-1' });
- expect(store.expandedLocationIds.has('location-1')).toBe(true);
- expect(store.isGroupExpanded(agentRoomGroupKey('location-1', 'room-1'))).toBe(true);
expect(store.isGroupExpanded(roomViewGroupKey('room-1'))).toBe(true);
});
@@ -170,17 +211,6 @@ describe('SidebarStore grouping', () => {
expect(store.isGroupExpanded(roomAgentGroupKey('room-2', 'agent-1'))).toBe(true);
});
- it('tracks and clears a pending scroll-to-session request', () => {
- const store = new SidebarStore(locationManager([]));
- expect(store.pendingScrollSessionId).toBeNull();
-
- store.requestScrollToSession('session-1');
- expect(store.pendingScrollSessionId).toBe('session-1');
-
- store.clearPendingScroll();
- expect(store.pendingScrollSessionId).toBeNull();
- });
-
it("returns a location's visible sessions for grouped views", () => {
const store = new SidebarStore(
locationManagerWithSessions([
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
index 63e32b30c..918ff3e2b 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-store.ts
@@ -45,9 +45,15 @@ export function depthIndent(depth: number): { paddingLeft: number } {
return { paddingLeft: depth * SIDEBAR_DEPTH_STEP };
}
+/** `collapsedGroupKeys` key for an agent row (agent-focused view); its sessions
+ * live below it. Default open. */
+export function agentExpandKey(agentId: string): string {
+ return `ag:${agentId}`;
+}
+
/** `collapsedGroupKeys` key for a room nested under an agent (agent-focused view). */
-export function agentRoomGroupKey(locationId: string, roomKey: string): string {
- return `ar:${locationId}|${roomKey}`;
+export function agentRoomGroupKey(agentId: string, roomKey: string): string {
+ return `ar:${agentId}|${roomKey}`;
}
/** `collapsedGroupKeys` key for a room header in the room-focused view. */
@@ -103,6 +109,20 @@ export type SidebarRow =
| { kind: 'location'; locationId: string }
| { kind: 'session'; locationId: string; sessionId: string };
+/**
+ * The sidebar row the open view selects, resolved to the ids the tree nests it
+ * under. Resolving it needs agent and room data the store does not hold, so it
+ * is built in `sidebar-selection.ts` and handed here to be acted on.
+ */
+export type SidebarSelection =
+ /** A session, under its agent and — when connected — its room. */
+ | { kind: 'session'; agentId: string; roomKey: string | null }
+ /** An agent's page. `roomKey` is set when it was opened from a room's member list. */
+ | { kind: 'agent'; roomKey: string | null }
+ /** A room's conversation. `agentIds` are the agents with sessions in it, which
+ * is where the agent-focused tree lists that room. */
+ | { kind: 'room'; roomKey: string; agentIds: string[] };
+
/**
* Reorder `items` to honour a saved manual order. Items present in `stored`
* appear in that order; items missing from it (newly arrived) keep their
@@ -166,12 +186,6 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
roomSortBy: SidebarRoomSortBy = 'name';
filterBridgeTypes = observable.set<string>();
filterRoomHasLiveSession = false;
- /**
- * Session whose row should scroll itself into view once it mounts. Set by the
- * deeplink handler (after revealing/expanding the tree) so the landed session
- * is centered in the sidebar; the row clears it after scrolling.
- */
- pendingScrollSessionId: string | null = null;
constructor(private readonly locationManager: LocationManagerStore) {
makeAutoObservable(this, {
@@ -586,25 +600,49 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {
}
/**
- * Reveal a session's row in the sidebar without changing the current grouping:
- * expand its agent and un-collapse the room group it sits in, covering both the
- * agent-focused and room-focused layouts. Used by the deeplink handler so the
- * targeted session is visible (and thus highlighted) wherever it lives.
+ * Open whatever is hiding the selected row, so there is a row to scroll to.
+ *
+ * Only the layout on screen is touched: expanding groups in the grouping the
+ * user cannot see would be a change they never asked for and would not
+ * discover until they switched. Idempotent, and driven by the selection
+ * changing rather than by the tree, so collapsing a group the selection sits
+ * in still works.
*/
- revealSessionInRoom(locationId: string, roomId: string): void {
- this.ensureLocationExpanded(locationId);
- this.ensureGroupExpanded(agentRoomGroupKey(locationId, roomId));
- this.ensureGroupExpanded(roomViewGroupKey(roomId));
- }
-
- /** Ask the given session's sidebar row to scroll itself into view when it renders. */
- requestScrollToSession(sessionId: string): void {
- this.pendingScrollSessionId = sessionId;
- }
-
- /** Clear the pending scroll request (called by the row once it has scrolled). */
- clearPendingScroll(): void {
- this.pendingScrollSessionId = null;
+ revealSelection(selection: SidebarSelection): void {
+ switch (selection.kind) {
+ case 'session': {
+ if (this.grouping === 'room') {
+ // A session with no room is not in the room-focused tree at all.
+ if (!selection.roomKey) return;
+ this.ensureGroupExpanded(roomViewGroupKey(selection.roomKey));
+ this.ensureGroupExpanded(roomAgentGroupKey(selection.roomKey, selection.agentId));
+ return;
+ }
+ this.ensureGroupExpanded(agentExpandKey(selection.agentId));
+ if (selection.roomKey) {
+ this.ensureGroupExpanded(agentRoomGroupKey(selection.agentId, selection.roomKey));
+ }
+ return;
+ }
+ case 'agent': {
+ // Agents are top level in their own tree; under a room in the other one,
+ // where the row only lights up for the room it was opened from.
+ if (this.grouping === 'room' && selection.roomKey) {
+ this.ensureGroupExpanded(roomViewGroupKey(selection.roomKey));
+ }
+ return;
+ }
+ case 'room': {
+ // Rooms are top level in their own tree; a heading under each agent with
+ // sessions there in the other one.
+ if (this.grouping === 'agent') {
+ for (const agentId of selection.agentIds) {
+ this.ensureGroupExpanded(agentExpandKey(agentId));
+ }
+ }
+ return;
+ }
+ }
}
/** Set the sort key and clear all manual session orders so the list fully re-sorts. */
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
index f0488babd..e3ca3828d 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
@@ -5,7 +5,7 @@ import { getLocationManagerStore } from '@renderer/features/locations/stores/loc
import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
import { events } from '@renderer/lib/ipc';
import { scopeToLocationServer } from '@renderer/lib/layout/scope-to-server';
-import { appState, sidebarStore } from '@renderer/lib/stores/app-state';
+import { appState } from '@renderer/lib/stores/app-state';
import { sessionDeeplinkChannel } from '@shared/core/switch-rooms/switchRoomEvents';
import { pickDeeplinkTarget } from './session-deeplink-resolve';
import { switchRoomsStore as roomConnectionsStore } from './switch-rooms-store';
@@ -49,8 +49,7 @@ function findSessionById(sessionId: string): { locationId: string; sessionId: st
* Listens for `switchdash://session?…` deeplinks (delivered by the main process
* after a messaging-app click) and focuses the app on the matching agent
* session: it selects the session's Switch server (so the server-scoped sidebar
- * shows it), reveals/expands the session in the sidebar, and navigates to the
- * session view. A render-less component so it can subscribe via the typed event
+ * shows it) and navigates to the session view. A render-less component so it can subscribe via the typed event
* bus and use the navigation store. No live session for the room → logged and
* ignored.
*/
@@ -86,11 +85,10 @@ export function SessionDeeplinkListener(): null {
roomId,
});
// Scope the sidebar to the session's server first; otherwise its location
- // is filtered out of the server-scoped tree and the reveal has nothing
- // to expand.
+ // is filtered out of the server-scoped tree and there is no row to
+ // reveal. Navigating is all the sidebar needs — it expands and scrolls
+ // to whatever the open view selects, from any origin.
await scopeToLocationServer(match.locationId);
- sidebarStore.revealSessionInRoom(match.locationId, roomId);
- sidebarStore.requestScrollToSession(match.sessionId);
appState.navigation.navigate('session', match);
})();
});