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): restore sidebar drag-to-reorder for agents and rooms (CHOO-2007)
Louis Amaudruzd0e5b3301a09
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 97f60c3d6..6a7bc1487 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@@ -4,6 +4,7 @@ import { switchRoomsStore } from '@renderer/features/switch-servers/switch-roomsimport { sidebarStore } from '@renderer/lib/stores/app-state';import { agentExpandKey, SidebarAgentItem } from './agent-item';import { SidebarSessionItem } from './session-item';+import { AGENTS_CONTAINER, makeDndId, SortableBranch, SortableList } from './sidebar-dnd';import {groupByRoom,isRoomViewActive,@@ -89,13 +90,21 @@ const AgentSessions = observer(function AgentSessions({});export const AgentTree = observer(function AgentTree() {+ const entries = scopedAgents();return (- <>- {scopedAgents().map((entry) => {+ <SortableList+ containerId={AGENTS_CONTAINER}+ itemIds={entries.map((entry) => entry.agent.id)}+ onReorder={(orderedIds) => sidebarStore.setAgentOrder(orderedIds)}+ >+ {entries.map((entry) => {const expanded = sidebarStore.isGroupExpanded(agentExpandKey(entry.agent.id));return (- <div key={entry.agent.id}>- <SidebarAgentItem agent={entry.agent} depth={0} />+ <SortableBranch+ key={entry.agent.id}+ id={makeDndId(AGENTS_CONTAINER, entry.agent.id)}+ header={<SidebarAgentItem agent={entry.agent} depth={0} />}+ >{expanded && (<AgentSessionsagentId={entry.agent.id}@@ -104,9 +113,9 @@ export const AgentTree = observer(function AgentTree() {depth={1}/>)}- </div>+ </SortableBranch>);})}- </>+ </SortableList>);});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 0325b2076..77a07ea81 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@@ -7,6 +7,7 @@ import { sidebarStore } from '@renderer/lib/stores/app-state';import { RoomAgentRow } from './room-agent-row';import { filterRoomGroups, sortRoomGroups } from './room-tree-data';import { SidebarSessionItem } from './session-item';+import { makeDndId, ROOMS_CONTAINER, SortableBranch, SortableList } from './sidebar-dnd';import {groupByRoom,isRoomViewActive,@@ -74,7 +75,7 @@ export const RoomTree = observer(function RoomTree() {]),];- const groups = sortRoomGroups(+ const sorted = sortRoomGroups(filterRoomGroups(groupByRoom(allSessions, alwaysShow)// This view lists rooms. A session connected to none of them is not in@@ -95,36 +96,48 @@ export const RoomTree = observer(function RoomTree() {),sidebarStore.roomSortBy);+ // The user's dragged order sits on top of the default one, so a room they+ // placed stays put while rooms they have not touched keep sorting normally.+ const groups = sidebarStore.orderRooms(sorted, (group) => group.roomKey);if (groups.length === 0 && sidebarStore.hasActiveRoomFilters) {return <p className="px-2 py-3 text-xs text-foreground-muted">No rooms match filters</p>;}return (- <>+ <SortableList+ containerId={ROOMS_CONTAINER}+ itemIds={groups.map((group) => group.roomKey)}+ onReorder={(orderedIds) => sidebarStore.setRoomOrder(orderedIds)}+ >{groups.map(({ roomKey, sessions: roomSessions }) => {const roomViewKey = roomViewGroupKey(roomKey);const expanded = sidebarStore.isGroupExpanded(roomViewKey);const agentsInRoom = members.get(roomKey) ?? [];return (- <div key={roomKey}>- <RoomRow- label={roomLabel(roomKey)}- count={roomSessions.length}- expanded={expanded}- depth={0}- bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}- onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}- onSelect={() => openRoomView(roomKey)}- isActive={isRoomViewActive(roomKey)}- onOpenGateway={() => openRoomInGateway(roomKey)}- onOpenChannel={- switchRoomsStore.roomChannelUrl(roomKey)- ? () => openRoomInMessagingApp(roomKey)- : null- }- onAddAgent={() => showAddAgentsToRoomModal({ roomId: roomKey })}- />+ <SortableBranch+ key={roomKey}+ id={makeDndId(ROOMS_CONTAINER, roomKey)}+ header={+ <RoomRow+ label={roomLabel(roomKey)}+ count={roomSessions.length}+ expanded={expanded}+ depth={0}+ bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}+ onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}+ onSelect={() => openRoomView(roomKey)}+ isActive={isRoomViewActive(roomKey)}+ onOpenGateway={() => openRoomInGateway(roomKey)}+ onOpenChannel={+ switchRoomsStore.roomChannelUrl(roomKey)+ ? () => openRoomInMessagingApp(roomKey)+ : null+ }+ onAddAgent={() => showAddAgentsToRoomModal({ roomId: roomKey })}+ />+ }+ >{expanded &&agentsInRoom.map((entry) => {const sessionsHere = roomSessions.filter(@@ -148,9 +161,9 @@ export const RoomTree = observer(function RoomTree() {</Fragment>);})}- </div>+ </SortableBranch>);})}- </>+ </SortableList>);});diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.test.tsnew file mode 100644index 000000000..6f2280d36--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import {+ AGENTS_CONTAINER,+ makeDndId,+ parseDndId,+ reorderOnDrop,+ ROOMS_CONTAINER,+} from './sidebar-dnd';++describe('sidebar drag ids', () => {+ it('round-trips a container and item id', () => {+ expect(parseDndId(makeDndId(AGENTS_CONTAINER, 'agent-1'))).toEqual({+ containerId: AGENTS_CONTAINER,+ itemId: 'agent-1',+ });+ });++ it('keeps an item id containing the separator intact', () => {+ // Room keys are opaque, so the split must be on the FIRST separator only.+ const id = makeDndId(ROOMS_CONTAINER, 'room~~odd');+ expect(parseDndId(id)).toEqual({ containerId: ROOMS_CONTAINER, itemId: 'room~~odd' });+ });++ it('rejects an id with no separator', () => {+ expect(parseDndId('agents')).toBeNull();+ });+});++describe('reorderOnDrop', () => {+ const ids = ['a', 'b', 'c'];+ const dnd = (itemId: string) => makeDndId(AGENTS_CONTAINER, itemId);++ it('moves the dragged item to the drop position', () => {+ expect(reorderOnDrop(ids, dnd('a'), dnd('c'))).toEqual(['b', 'c', 'a']);+ expect(reorderOnDrop(ids, dnd('c'), dnd('a'))).toEqual(['c', 'a', 'b']);+ });++ it('is a no-op when dropped on itself', () => {+ expect(reorderOnDrop(ids, dnd('b'), dnd('b'))).toBeNull();+ });++ it('refuses a drop into a different container', () => {+ // Agents and rooms are separate lists; a drag may reorder, never re-parent.+ expect(reorderOnDrop(ids, dnd('a'), makeDndId(ROOMS_CONTAINER, 'b'))).toBeNull();+ });++ it('refuses a drop involving an id that is no longer listed', () => {+ expect(reorderOnDrop(ids, dnd('gone'), dnd('b'))).toBeNull();+ expect(reorderOnDrop(ids, dnd('a'), dnd('gone'))).toBeNull();+ });++ it('does not mutate the list it was given', () => {+ const original = [...ids];+ reorderOnDrop(ids, dnd('a'), dnd('c'));+ expect(ids).toEqual(original);+ });+});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.tsxnew file mode 100644index 000000000..06de23999--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/sidebar-dnd.tsx@@ -0,0 +1,152 @@+import {+ closestCenter,+ DndContext,+ PointerSensor,+ useSensor,+ useSensors,+ type CollisionDetection,+ type DragEndEvent,+} from '@dnd-kit/core';+import {+ arrayMove,+ SortableContext,+ useSortable,+ verticalListSortingStrategy,+} from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import type { CSSProperties, ReactNode } from 'react';++/**+ * Drag-to-reorder plumbing for the sidebar's two top-level lists: the agents in+ * the agent view and the rooms in the room view.+ *+ * Every draggable carries a composite id `${containerId}~~${itemId}`. The+ * container id identifies the sibling set an item belongs to; reordering is+ * restricted to within a container so a drag can only change order, never move+ * an item into a different list.+ */+const SEP = '~~';++/** The reorderable sibling sets. Only the top level of each view is draggable. */+export const AGENTS_CONTAINER = 'agents';+export const ROOMS_CONTAINER = 'rooms';++export function makeDndId(containerId: string, itemId: string): string {+ return `${containerId}${SEP}${itemId}`;+}++export function parseDndId(dndId: string): { containerId: string; itemId: string } | null {+ const idx = dndId.indexOf(SEP);+ if (idx === -1) return null;+ return { containerId: dndId.slice(0, idx), itemId: dndId.slice(idx + SEP.length) };+}++/**+ * Collision detection that only considers droppables in the same container as+ * the active item, so a drag can only land among its own siblings.+ */+const sameContainerCollision: CollisionDetection = (args) => {+ const active = parseDndId(String(args.active.id));+ if (!active) return [];+ const droppableContainers = args.droppableContainers.filter((container) => {+ const parsed = parseDndId(String(container.id));+ return parsed?.containerId === active.containerId;+ });+ return closestCenter({ ...args, droppableContainers });+};++/**+ * The order `ids` takes when the item dragged from `activeId` is dropped on+ * `overId`, or null when the drop is a no-op (same slot, foreign container, or+ * an id that is no longer in the list).+ *+ * Split out from the drag handler so the reorder rule is testable without a DOM+ * or a pointer.+ */+export function reorderOnDrop(+ ids: readonly string[],+ activeId: string,+ overId: string+): string[] | null {+ const from = parseDndId(activeId);+ const to = parseDndId(overId);+ if (!from || !to || from.containerId !== to.containerId) return null;+ const oldIndex = ids.indexOf(from.itemId);+ const newIndex = ids.indexOf(to.itemId);+ if (oldIndex === -1 || newIndex === -1 || oldIndex === newIndex) return null;+ return arrayMove([...ids], oldIndex, newIndex);+}++function useSortableRow(id: string) {+ const { setNodeRef, transform, transition, isDragging, listeners } = useSortable({ id });+ const style: CSSProperties = {+ transform: CSS.Transform.toString(transform),+ transition,+ opacity: isDragging ? 0.4 : undefined,+ position: 'relative',+ zIndex: isDragging ? 1 : undefined,+ };+ return { setNodeRef, style, listeners };+}++/**+ * One draggable top-level row. Only `header` is the drag handle: `children`+ * (the row's expanded subtree) moves with it but does not start a drag, so+ * dragging inside an expanded agent or room does nothing rather than picking up+ * the whole branch by surprise.+ */+export function SortableBranch({+ id,+ header,+ children,+}: {+ id: string;+ header: ReactNode;+ children?: ReactNode;+}) {+ const { setNodeRef, style, listeners } = useSortableRow(id);+ return (+ <div ref={setNodeRef} style={style}>+ <div {...listeners}>{header}</div>+ {children}+ </div>+ );+}++/**+ * Wraps one top-level list in the drag context that reorders it. `itemIds` is+ * the list as currently rendered; `onReorder` receives the new order on drop.+ */+export function SortableList({+ containerId,+ itemIds,+ onReorder,+ children,+}: {+ containerId: string;+ itemIds: string[];+ onReorder: (orderedItemIds: string[]) => void;+ children: ReactNode;+}) {+ // A short activation distance keeps a click a click: rows open pages, toggle+ // expansion and open context menus, and none of that may become a drag.+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));++ function onDragEnd(event: DragEndEvent) {+ const { active, over } = event;+ if (!over) return;+ const reordered = reorderOnDrop(itemIds, String(active.id), String(over.id));+ if (reordered) onReorder(reordered);+ }++ return (+ <DndContext sensors={sensors} collisionDetection={sameContainerCollision} onDragEnd={onDragEnd}>+ <SortableContext+ items={itemIds.map((itemId) => makeDndId(containerId, itemId))}+ strategy={verticalListSortingStrategy}+ >+ {children}+ </SortableContext>+ </DndContext>+ );+}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.tsindex 37dc36a38..e76251355 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@@ -81,37 +81,35 @@ describe('SidebarStore location ordering', () => {expect(store.orderedLocations.map((location) => location.id)).toEqual(['new', 'old']);});- it('places locations missing from a saved manual order first', () => {+ it('orders locations by recency alone — manual order lives on agents, not locations', () => {const store = new SidebarStore(locationManager([{ id: 'old', createdAt: '2026-01-01T00:00:00.000Z' },- { id: 'manual', createdAt: '2026-01-02T00:00:00.000Z' },+ { id: 'middle', createdAt: '2026-01-02T00:00:00.000Z' },{ id: 'new', createdAt: '2026-01-03T00:00:00.000Z' },]));- store.setLocationOrder(['manual', 'old']);-- expect(store.orderedLocations.map((location) => location.id)).toEqual(['new', 'manual', 'old']);+ expect(store.orderedLocations.map((location) => location.id)).toEqual(['new', 'middle', 'old']);});it('returns visible session entries in rendered location-tree order', () => {const store = new SidebarStore(locationManagerWithSessions([{+ // Newest, so it renders first and its sessions lead the list.id: 'location-1',- createdAt: '2026-01-01T00:00:00.000Z',+ createdAt: '2026-01-02T00:00:00.000Z',sessionIds: ['session-1a', 'session-1b'],},{id: 'location-2',- createdAt: '2026-01-02T00:00:00.000Z',+ createdAt: '2026-01-01T00:00:00.000Z',sessionIds: ['session-2a'],},]));- store.setLocationOrder(['location-1', 'location-2']);store.ensureLocationExpanded('location-1');store.ensureLocationExpanded('location-2');store.setSessionOrder('location-1', ['session-1a', 'session-1b']);@@ -479,41 +477,54 @@ describe('applyManualOrder', () => {});});-describe('SidebarStore grouped-view ordering', () => {- it('orders top-level room keys by the saved manual room order', () => {+describe('SidebarStore drag-to-reorder ordering', () => {+ it('orders top-level rooms by the saved manual room order', () => {const store = new SidebarStore(locationManager([]));store.setRoomOrder(['room-c', 'room-a']);+ const rooms = [{ roomKey: 'room-a' }, { roomKey: 'room-b' }, { roomKey: 'room-c' }];// Saved rooms come first in saved order; unknown rooms append.- expect(store.orderRoomKeys(['room-a', 'room-b', 'room-c'])).toEqual([- 'room-c',- 'room-a',- 'room-b',+ expect(store.orderRooms(rooms, (room) => room.roomKey)).toEqual([+ { roomKey: 'room-c' },+ { roomKey: 'room-a' },+ { roomKey: 'room-b' },+ ]);+ });++ it('orders top-level agents by the saved manual agent order', () => {+ const store = new SidebarStore(locationManager([]));+ store.setAgentOrder(['agent-c', 'agent-a']);+ const agents = [{ id: 'agent-a' }, { id: 'agent-b' }, { id: 'agent-c' }];+ expect(store.orderAgents(agents, (agent) => agent.id)).toEqual([+ { id: 'agent-c' },+ { id: 'agent-a' },+ { id: 'agent-b' },]);});- it('orders a sub-group by its saved order, surfacing new sessions first', () => {+ it('keeps a dragged agent in place when a new agent arrives', () => {const store = new SidebarStore(locationManager([]));- const sessions = [{ id: 's1' }, { id: 's2' }, { id: 's3' }];- store.setGroupOrder('as:p1|room-1', ['s2', 's1']);- expect(store.orderGroupItems('as:p1|room-1', sessions, (s) => s.id, true)).toEqual([- { id: 's3' },- { id: 's2' },- { id: 's1' },+ store.setAgentOrder(['agent-b', 'agent-a']);+ // A newly-added agent must not displace an order the user set deliberately.+ const agents = [{ id: 'agent-a' }, { id: 'agent-b' }, { id: 'fresh' }];+ expect(store.orderAgents(agents, (agent) => agent.id).map((agent) => agent.id)).toEqual([+ 'agent-b',+ 'agent-a',+ 'fresh',]);});- it('round-trips room and group order through the snapshot', () => {+ it('round-trips agent and room order through the snapshot', () => {const store = new SidebarStore(locationManager([]));store.setRoomOrder(['room-2', 'room-1']);- store.setGroupOrder('as:p1|room-1', ['s2', 's1']);+ store.setAgentOrder(['agent-2', 'agent-1']);const snapshot = store.snapshot;expect(snapshot.roomOrder).toEqual(['room-2', 'room-1']);- expect(snapshot.groupOrder).toEqual({ 'as:p1|room-1': ['s2', 's1'] });+ expect(snapshot.agentOrder).toEqual(['agent-2', 'agent-1']);const restored = new SidebarStore(locationManager([]));restored.restoreSnapshot(snapshot);expect(restored.roomOrder).toEqual(['room-2', 'room-1']);- expect(restored.groupOrder).toEqual({ 'as:p1|room-1': ['s2', 's1'] });+ expect(restored.agentOrder).toEqual(['agent-2', 'agent-1']);});});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.tsindex 23619f9f2..63e32b30c 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@@ -131,12 +131,16 @@ export function applyManualOrder<T>(}export class SidebarStore implements Snapshottable<SidebarSnapshot> {- locationOrder: string[] = [];+ /**+ * Manual order of the top-level agents (agent-focused grouping), by agent id.+ * The agent is the unit the sidebar lists and the user drags; a location can+ * hold several agents, so ordering by location cannot express a drag that+ * moves one of them past its neighbour.+ */+ agentOrder: string[] = [];sessionOrderByLocation: Record<string, string[]> = {};/** Manual order of top-level rooms (room-focused grouping). */roomOrder: string[] = [];- /** Manual order of items within a grouped-view sub-group, keyed by container id. */- groupOrder: Record<string, string[]> = {};expandedLocationIds = observable.set<string>();sessionSortBy: SidebarSessionSortBy = 'created-at';grouping: SidebarGrouping = 'agent';@@ -223,19 +227,17 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {return agentsStore.serverIdForLocation(locationId) === activeServerId;}+ /**+ * Server-scoped locations, newest first. Locations are no longer a level of+ * the sidebar tree — the manual order the user drags lives on agents and+ * rooms — so this is the plain default order the agent list is built from.+ */get orderedLocations(): LocationStore[] {const all = Array.from(this.locationManager.locations.values()).filter((location) =>this.isLocationInActiveScope(location.id));- return [...all].sort((a, b) => {- const ai = this.locationOrder.indexOf(a.id);- const bi = this.locationOrder.indexOf(b.id);- if (ai === -1 && bi === -1) return this.compareSidebarLocations(a, b);- if (ai === -1) return -1;- if (bi === -1) return 1;- return ai - bi;- });+ return [...all].sort((a, b) => this.compareSidebarLocations(a, b));}/** The representative agent of a location (the agent shown on its sidebar row):@@ -427,14 +429,13 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {get snapshot(): SidebarSnapshot {return {expandedLocationIds: [...this.expandedLocationIds],- locationOrder: [...this.locationOrder],+ agentOrder: [...this.agentOrder],sessionOrderByLocation: { ...this.sessionOrderByLocation },sessionSortBy: this.sessionSortBy,grouping: this.grouping,expandedRoomKeys: [...this.expandedRoomKeys],collapsedGroupKeys: [...this.collapsedGroupKeys],roomOrder: [...this.roomOrder],- groupOrder: { ...this.groupOrder },filterConnections: [...this.filterConnections],filterProviderIds: [...this.filterProviderIds],filterHasLiveSession: this.filterHasLiveSession,@@ -448,8 +449,8 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {if (snapshot.expandedLocationIds !== undefined) {this.expandedLocationIds.replace(snapshot.expandedLocationIds);}- if (snapshot.locationOrder !== undefined) {- this.locationOrder = [...snapshot.locationOrder];+ if (snapshot.agentOrder !== undefined) {+ this.agentOrder = [...snapshot.agentOrder];}if (snapshot.sessionOrderByLocation !== undefined) {this.sessionOrderByLocation = { ...snapshot.sessionOrderByLocation };@@ -469,9 +470,6 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {if (snapshot.roomOrder !== undefined) {this.roomOrder = [...snapshot.roomOrder];}- if (snapshot.groupOrder !== undefined) {- this.groupOrder = { ...snapshot.groupOrder };- }if (snapshot.filterConnections !== undefined) {this.filterConnections.replace(snapshot.filterConnections.filter(isAgentConnectionKind));}@@ -615,34 +613,26 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {this.sessionOrderByLocation = {};}- setLocationOrder(ids: string[]): void {- this.locationOrder = ids;+ setAgentOrder(ids: string[]): void {+ this.agentOrder = ids;}setRoomOrder(ids: string[]): void {this.roomOrder = ids;}- setGroupOrder(containerId: string, ids: string[]): void {- this.groupOrder = { ...this.groupOrder, [containerId]: ids };- }-- /** Top-level room keys reordered by the saved manual room order. */- orderRoomKeys(roomKeys: string[]): string[] {- return applyManualOrder(roomKeys, (key) => key, this.roomOrder, false);- }-/**- * Items within a grouped-view sub-group reordered by its saved manual order.- * `newFirst` surfaces freshly-arrived items at the top (used for sessions).+ * Top-level agents reordered by the saved manual order. An agent the user has+ * never dragged sorts after the ones they have, keeping a newly-added agent+ * from displacing an arrangement they set deliberately.*/- orderGroupItems<T>(- containerId: string,- items: T[],- getId: (item: T) => string,- newFirst: boolean- ): T[] {- return applyManualOrder(items, getId, this.groupOrder[containerId], newFirst);+ orderAgents<T>(agents: T[], getId: (agent: T) => string): T[] {+ return applyManualOrder(agents, getId, this.agentOrder, false);+ }++ /** Top-level rooms reordered by the saved manual room order, same rule. */+ orderRooms<T>(rooms: T[], getId: (room: T) => string): T[] {+ return applyManualOrder(rooms, getId, this.roomOrder, false);}mergeSessionOrder(locationId: string, sessions: SessionStore[]): SessionStore[] {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.tsindex 38017ab7b..6de430322 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@@ -14,8 +14,12 @@ import type { Agent } from '@shared/core/agents/agents';export type AgentEntry = { agent: Agent; location: LocationStore };/**- * The flat list of agents in the active-server scope, newest first. switchdash- * shows agents as a flat list — not grouped by directory (CHOO-1440).+ * The flat list of agents in the active-server scope. switchdash shows agents+ * as a flat list — not grouped by directory (CHOO-1440).+ *+ * Newest first, then overlaid with the user's manual drag order: an agent they+ * have positioned stays where they put it, and one they have not sorts after+ * those by recency.*/export function scopedAgents(): AgentEntry[] {const entries: AgentEntry[] = [];@@ -24,10 +28,11 @@ export function scopedAgents(): AgentEntry[] {entries.push({ agent, location });}}- return entries.sort(+ entries.sort((a, b) =>b.agent.createdAt.localeCompare(a.agent.createdAt) || a.agent.name.localeCompare(b.agent.name));+ return sidebarStore.orderAgents(entries, (entry) => entry.agent.id);}/**diff --git a/dash/apps/switchdash-desktop/src/shared/view-state.ts b/dash/apps/switchdash-desktop/src/shared/view-state.tsindex c86f839e3..7ffd90e24 100644--- a/dash/apps/switchdash-desktop/src/shared/view-state.ts+++ b/dash/apps/switchdash-desktop/src/shared/view-state.ts@@ -25,7 +25,12 @@ export type SidebarGrouping = 'agent' | 'room';/** Persisted sidebar UI state; fields may be absent in older DB blobs. */export type SidebarSnapshot = {expandedLocationIds?: string[];- locationOrder?: string[];+ /**+ * Manual order of the top-level agents in the agent-focused grouping, by+ * agent id. Superseded `locationOrder`, which keyed the same intent by+ * location and so could not order two agents sharing one.+ */+ agentOrder?: string[];sessionOrderByLocation?: Record<string, string[]>;sessionSortBy?: SidebarSessionSortBy;grouping?: SidebarGrouping;@@ -39,12 +44,6 @@ export type SidebarSnapshot = {collapsedGroupKeys?: string[];/** Manual order of the top-level rooms in the room-focused grouping. */roomOrder?: string[];- /**- * Manual order of items within a grouped-view sub-group, keyed by a container- * id (e.g. an agent's room group, or a room's per-agent session group). Used by- * the grouped views' drag-to-reorder; absent groups fall back to the default sort.- */- groupOrder?: Record<string, string[]>;/*** Optional left-sidebar filters. Each dimension is additive and composes with* the others (AND across dimensions, OR within one). An empty array / false