Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): complete live roster drag for bots and groups (#218)

Leoa2f29f7e731a
diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsx
index 21bea00a5..e4734da05 100644
--- a/apps/web/src/components/roster/BotRosterSidebar.tsx
+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx
@@ -1,20 +1,42 @@
-import { DragDropContext, Draggable, Droppable, type DropResult } from "@hello-pangea/dnd";
+import {
+ DndContext,
+ type DragEndEvent,
+ type DragOverEvent,
+ type DragStartEvent,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import { SortableContext, useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
import { useAtomValue } from "@effect/atom-react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { BotId, EnvironmentId, GroupId, ThreadId } from "@t3tools/contracts";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import {
+ ArrowDownIcon,
+ ArrowUpIcon,
BotIcon,
ChevronDownIcon,
ChevronRightIcon,
FolderInputIcon,
PinIcon,
+ PinOffIcon,
PlusIcon,
SearchIcon,
Trash2Icon,
UsersIcon,
} from "lucide-react";
-import { memo, useEffect, useMemo, useRef, useState } from "react";
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import { useShallow } from "zustand/react/shallow";
import { isElectron } from "../../env";
@@ -54,23 +76,46 @@ import { NewBotDialog } from "./NewBotDialog";
import { NewGroupDialog, type NewGroupInput } from "./NewGroupDialog";
import { GroupMemberStack } from "./GroupMemberStack";
import {
+ buildRosterListItems,
filterRosterBots,
filterRosterGroups,
formatRosterTimestamp,
isRecordableChatPath,
parseChatPath,
+ parseRosterEntryId,
+ parseRosterSectionHeaderId,
+ planRosterDrop,
+ planRosterSectionDrop,
resolveLatestRosterMessage,
+ resolveRosterDropTarget,
+ resolveRosterDropVerb,
resolveRosterIndicator,
- parseRosterBotDragId,
- parseRosterGroupDropId,
+ rosterItemKey,
+ rosterItemsEqual,
+ rosterItemsForZone,
+ rosterListItemId,
+ rosterMarkerId,
+ rosterSectionItems,
+ rosterZoneHasVisibleEntries,
+ rosterZonesEqual,
orderRosterBotsForShortcuts,
- rosterBotDragId,
- rosterGroupDropId,
resolveRosterShortcutBot,
+ type RosterDropVerb,
+ type RosterItemRef,
type RosterLastMessage,
+ type RosterListMarker,
type RosterPresence,
+ type RosterZone,
} from "./roster.logic";
-import { useRosterStore, type RosterItemRef, type RosterSection } from "./rosterStore";
+import {
+ animateRosterLayoutChanges,
+ createRosterCollisionDetection,
+ createRosterSortingStrategy,
+ restrictBelowRosterLabel,
+} from "./roster.drag";
+import { createRosterListMotion } from "./roster.motion";
+import { RosterDragLifecycle, RosterPointerSensor } from "./roster.pointer";
+import { useRosterStore, type RosterSection } from "./rosterStore";
import type { Bot, BotAvatar, Group } from "./types";
import { useBotThreadRef } from "./useBotThreadRef";
@@ -200,123 +245,194 @@ function useLatestBotMessage(
);
}
+type SortableRosterRowBag = Pick<
+ ReturnType<typeof useSortable>,
+ "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging"
+>;
+
+function SortableRosterRow(props: {
+ id: string;
+ disabled: boolean;
+ children: (bag: SortableRosterRowBag) => ReactNode;
+}) {
+ const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: props.id,
+ disabled: { draggable: props.disabled },
+ animateLayoutChanges: animateRosterLayoutChanges,
+ });
+ const bag = useMemo(
+ () => ({ listeners, setNodeRef, transform, transition, isDragging }),
+ [listeners, setNodeRef, transform, transition, isDragging],
+ );
+ return props.children(bag);
+}
+
+function sortableRootProps(sortable: SortableRosterRowBag) {
+ return {
+ ref: sortable.setNodeRef,
+ style: {
+ transform: CSS.Translate.toString(sortable.transform),
+ transition: sortable.transition,
+ visibility:
+ !sortable.isDragging && sortable.transform?.scaleY === 0 ? ("hidden" as const) : undefined,
+ },
+ ...sortable.listeners,
+ };
+}
+
+const dropVerbBadge: Record<RosterDropVerb, ReactNode> = {
+ pin: (
+ <>
+ <PinIcon aria-hidden className="size-3" />
+ Pin
+ </>
+ ),
+ unpin: (
+ <>
+ <PinOffIcon aria-hidden className="size-3" />
+ Unpin
+ </>
+ ),
+ move: (
+ <>
+ <FolderInputIcon aria-hidden className="size-3" />
+ Move
+ </>
+ ),
+};
+
+const ROSTER_DRAG_LABEL_HEIGHT = 24;
+
const BotRosterRow = memo(function BotRosterRow({
bot,
lastMessage,
isActive,
onSelect,
- index,
pinned,
sections,
onPin,
onMove,
- dragDisabled,
+ canMoveUp,
+ canMoveDown,
+ onNudge,
+ sortable,
+ dropVerb,
}: {
bot: Bot;
lastMessage: RosterLastMessage | null;
isActive: boolean;
onSelect: (bot: Bot) => void;
- index: number;
pinned: boolean;
sections: readonly RosterSection[];
onPin: (pinned: boolean) => void;
onMove: (sectionId: string | null) => void;
- dragDisabled: boolean;
+ canMoveUp: boolean;
+ canMoveDown: boolean;
+ onNudge: (delta: -1 | 1) => void;
+ sortable: SortableRosterRowBag;
+ dropVerb: RosterDropVerb | null;
}) {
const menuTriggerRef = useRef<HTMLButtonElement>(null);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const presence = useBotPresence(bot.id);
const latestMessage = useLatestBotMessage(bot.id, lastMessage);
return (
- <Draggable
- draggableId={rosterBotDragId(bot.id)}
- index={index}
- isDragDisabled={dragDisabled}
- disableInteractiveElementBlocking
+ <li
+ role="listitem"
+ data-roster-item
+ className={cn("list-none touch-pan-y", sortable.isDragging && "z-50")}
+ {...sortableRootProps(sortable)}
>
- {(provided, snapshot) => (
- <div
- ref={provided.innerRef}
- role="listitem"
- className={cn("list-none touch-pan-y", snapshot.isDragging && "z-50")}
- {...provided.draggableProps}
+ <div
+ data-testid="roster-bot-row"
+ data-bot-hover
+ onContextMenu={(event) => {
+ event.preventDefault();
+ menuTriggerRef.current?.click();
+ }}
+ className={cn(
+ "relative flex w-full items-center rounded-lg outline-none select-none",
+ sortable.isDragging
+ ? "bg-[linear-gradient(var(--sidebar-row-active),var(--sidebar-row-active)),linear-gradient(var(--sidebar),var(--sidebar))] text-sidebar-foreground shadow-lg"
+ : isActive
+ ? "bg-sidebar-row-active text-sidebar-foreground"
+ : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover",
+ )}
+ >
+ <button
+ type="button"
+ aria-current={isActive || undefined}
+ onClick={() => onSelect(bot)}
+ className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
>
- <div
- data-testid="roster-bot-row"
- data-bot-hover
- onContextMenu={(event) => {
- event.preventDefault();
- menuTriggerRef.current?.click();
- }}
- className={cn(
- "relative flex w-full items-center rounded-lg outline-none select-none",
- snapshot.isDragging
- ? "bg-sidebar-row-active text-sidebar-foreground shadow-xl"
- : isActive
- ? "bg-sidebar-row-active text-sidebar-foreground"
- : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover",
- )}
- >
- <button
- type="button"
- aria-current={isActive || undefined}
- onClick={() => onSelect(bot)}
- className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
- {...provided.dragHandleProps}
- >
- <RosterAvatar bot={bot} presence={presence} className="size-10" />
- <span className="flex min-w-0 flex-1 flex-col">
- <span className="flex items-baseline gap-2">
- <span className="min-w-0 flex-1 truncate text-sm font-semibold">{bot.name}</span>
- {latestMessage ? (
- <span className="shrink-0 text-xs tabular-nums text-sidebar-muted-foreground">
- {formatRosterTimestamp(latestMessage.at, timestampFormat)}
- </span>
- ) : null}
+ <RosterAvatar bot={bot} presence={presence} className="size-10" />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="flex items-baseline gap-2">
+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{bot.name}</span>
+ {latestMessage ? (
+ <span className="shrink-0 text-xs tabular-nums text-sidebar-muted-foreground">
+ {formatRosterTimestamp(latestMessage.at, timestampFormat)}
</span>
- {latestMessage ? (
- <span className="truncate text-[13px] text-sidebar-muted-foreground">
- {latestMessage.text}
- </span>
- ) : null}
+ ) : null}
+ </span>
+ {latestMessage ? (
+ <span className="truncate text-[13px] text-sidebar-muted-foreground">
+ {latestMessage.text}
</span>
- </button>
- <Menu>
- <MenuTrigger
- render={
- <button
- ref={menuTriggerRef}
- type="button"
- aria-label={`Actions for ${bot.name}`}
- className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
- />
- }
+ ) : null}
+ </span>
+ {sortable.isDragging && dropVerb !== null ? (
+ <span
+ role="status"
+ data-testid="roster-drop-verb"
+ className="pointer-events-none ml-auto inline-flex h-5 shrink-0 items-center gap-1 rounded-sm border border-primary/40 bg-primary/10 px-1.5 text-[11px] font-medium text-primary"
+ >
+ {dropVerbBadge[dropVerb]}
+ </span>
+ ) : null}
+ </button>
+ <Menu>
+ <MenuTrigger
+ render={
+ <button
+ ref={menuTriggerRef}
+ type="button"
+ aria-label={`Actions for ${bot.name}`}
+ className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
/>
- <MenuPopup align="end">
- <MenuItem onClick={() => onPin(!pinned)}>
- <PinIcon />
- {pinned ? "Unpin" : "Pin"}
- </MenuItem>
- <MenuSub>
- <MenuSubTrigger>
- <FolderInputIcon />
- Move to
- </MenuSubTrigger>
- <MenuSubPopup>
- {sections.map((section) => (
- <MenuItem key={section.id} onClick={() => onMove(section.id)}>
- {section.name}
- </MenuItem>
- ))}
- <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
- </MenuSubPopup>
- </MenuSub>
- </MenuPopup>
- </Menu>
- </div>
- </div>
- )}
- </Draggable>
+ }
+ />
+ <MenuPopup align="end">
+ <MenuItem onClick={() => onPin(!pinned)}>
+ <PinIcon />
+ {pinned ? "Unpin" : "Pin"}
+ </MenuItem>
+ <MenuItem disabled={!canMoveUp} onClick={() => onNudge(-1)}>
+ <ArrowUpIcon />
+ Move up
+ </MenuItem>
+ <MenuItem disabled={!canMoveDown} onClick={() => onNudge(1)}>
+ <ArrowDownIcon />
+ Move down
+ </MenuItem>
+ <MenuSub>
+ <MenuSubTrigger>
+ <FolderInputIcon />
+ Move to
+ </MenuSubTrigger>
+ <MenuSubPopup>
+ {sections.map((section) => (
+ <MenuItem key={section.id} onClick={() => onMove(section.id)}>
+ {section.name}
+ </MenuItem>
+ ))}
+ <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
+ </MenuSubPopup>
+ </MenuSub>
+ </MenuPopup>
+ </Menu>
+ </div>
+ </li>
);
});
@@ -366,10 +482,13 @@ function GroupRosterRow({
onSelect,
pinned,
onPin,
- index,
sections,
onMove,
- dragDisabled,
+ canMoveUp,
+ canMoveDown,
+ onNudge,
+ sortable,
+ dropVerb,
}: {
group: Group;
bots: readonly Bot[];
@@ -377,10 +496,13 @@ function GroupRosterRow({
onSelect: () => void;
pinned: boolean;
onPin: (pinned: boolean) => void;
- index: number;
sections: readonly RosterSection[];
onMove: (sectionId: string | null) => void;
- dragDisabled: boolean;
+ canMoveUp: boolean;
+ canMoveDown: boolean;
+ onNudge: (delta: -1 | 1) => void;
+ sortable: SortableRosterRowBag;
+ dropVerb: RosterDropVerb | null;
}) {
const menuTriggerRef = useRef<HTMLButtonElement>(null);
const members = group.members.filter(
@@ -388,142 +510,176 @@ function GroupRosterRow({
member.kind === "bot" && bots.some((bot) => bot.id === member.botId && !bot.archivedAt),
).length;
return (
- <Draggable
- draggableId={rosterGroupDropId(group.id)}
- index={index}
- isDragDisabled={dragDisabled}
- >
- {(dragProvided, dragSnapshot) => (
- <div
- ref={dragProvided.innerRef}
- {...dragProvided.draggableProps}
- role="listitem"
- data-testid="roster-group-card"
- onContextMenu={(event) => {
- event.preventDefault();
- menuTriggerRef.current?.click();
- }}
- className={cn(
- "relative flex touch-pan-y items-center rounded-lg",
- dragSnapshot.isDragging && "z-50 bg-sidebar shadow-xl",
- isActive && "bg-sidebar-row-active",
- )}
- >
- <button
- type="button"
- aria-current={isActive || undefined}
- onClick={onSelect}
- {...dragProvided.dragHandleProps}
- className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
- >
- <GroupMemberStack group={group} bots={bots} sizeClassName="size-10" />
- <span className="min-w-0 flex-1 truncate text-sm font-semibold">{group.name}</span>
- <span className="text-xs text-sidebar-muted-foreground">{members}</span>
- </button>
- <Menu>
- <MenuTrigger
- render={
- <button
- ref={menuTriggerRef}
- type="button"
- aria-label={`Actions for ${group.name}`}
- className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
- />
- }
- />
- <MenuPopup align="end">
- <MenuItem onClick={() => onPin(!pinned)}>
- <PinIcon />
- {pinned ? "Unpin" : "Pin"}
- </MenuItem>
- <MenuSub>
- <MenuSubTrigger>
- <FolderInputIcon />
- Move to
- </MenuSubTrigger>
- <MenuSubPopup>
- {sections.map((section) => (
- <MenuItem key={section.id} onClick={() => onMove(section.id)}>
- {section.name}
- </MenuItem>
- ))}
- <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
- </MenuSubPopup>
- </MenuSub>
- </MenuPopup>
- </Menu>
- </div>
- )}
- </Draggable>
- );
-}
-
-function PinnedRosterItem({
- item,
- bots,
- groups,
- onSelectBot,
- onSelectGroup,
-}: {
- item: RosterItemRef;
- bots: readonly Bot[];
- groups: readonly Group[];
- onSelectBot: (bot: Bot) => void;
- onSelectGroup: (group: Group) => void;
-}) {
- const menuTriggerRef = useRef<HTMLButtonElement>(null);
- const bot = item.kind === "bot" ? bots.find((candidate) => candidate.id === item.id) : null;
- const group = item.kind === "group" ? groups.find((candidate) => candidate.id === item.id) : null;
- if (!bot && !group) return null;
- const label = bot?.name ?? group!.name;
- return (
- <div
- className="relative w-20 shrink-0"
+ <li
+ role="listitem"
+ data-roster-item
+ data-testid="roster-group-card"
onContextMenu={(event) => {
event.preventDefault();
menuTriggerRef.current?.click();
}}
+ className={cn(
+ "relative flex touch-pan-y items-center rounded-lg",
+ sortable.isDragging && "z-50 bg-sidebar shadow-xl",
+ isActive && "bg-sidebar-row-active",
+ )}
+ {...sortableRootProps(sortable)}
>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- onClick={() => (bot ? onSelectBot(bot) : onSelectGroup(group!))}
- className="flex w-full flex-col items-center gap-1.5 rounded-xl px-1 py-2 text-sidebar-foreground outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring"
- >
- {bot ? (
- <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-12" />
- ) : (
- <span className="flex size-14 items-center justify-center">
- <GroupMemberStack group={group!} bots={bots} sizeClassName="size-14" />
- </span>
- )}
- <span className="w-full truncate text-[11px] font-medium">{label}</span>
- </button>
- }
- />
- <TooltipPopup>{label}</TooltipPopup>
- </Tooltip>
+ <button
+ type="button"
+ aria-current={isActive || undefined}
+ onClick={onSelect}
+ className="flex min-w-0 flex-1 cursor-grab items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
+ >
+ <GroupMemberStack group={group} bots={bots} sizeClassName="size-10" />
+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{group.name}</span>
+ <span className="text-xs text-sidebar-muted-foreground">{members}</span>
+ {sortable.isDragging && dropVerb !== null ? (
+ <span
+ role="status"
+ data-testid="roster-drop-verb"
+ className="pointer-events-none ml-auto inline-flex h-5 shrink-0 items-center gap-1 rounded-sm border border-primary/40 bg-primary/10 px-1.5 text-[11px] font-medium text-primary"
+ >
+ {dropVerbBadge[dropVerb]}
+ </span>
+ ) : null}
+ </button>
<Menu>
<MenuTrigger
render={
<button
ref={menuTriggerRef}
type="button"
- aria-label={`Actions for pinned ${label}`}
- className="absolute right-2 top-2 size-px overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label={`Actions for ${group.name}`}
+ className="absolute right-2 top-1/2 size-px -translate-y-1/2 overflow-hidden opacity-0 outline-none focus-visible:size-7 focus-visible:overflow-visible focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring"
/>
}
/>
- <MenuPopup align="center">
- <MenuItem onClick={() => useRosterStore.getState().setItemPinned(item, false)}>
+ <MenuPopup align="end">
+ <MenuItem onClick={() => onPin(!pinned)}>
<PinIcon />
- Unpin
+ {pinned ? "Unpin" : "Pin"}
+ </MenuItem>
+ <MenuItem disabled={!canMoveUp} onClick={() => onNudge(-1)}>
+ <ArrowUpIcon />
+ Move up
+ </MenuItem>
+ <MenuItem disabled={!canMoveDown} onClick={() => onNudge(1)}>
+ <ArrowDownIcon />
+ Move down
</MenuItem>
+ <MenuSub>
+ <MenuSubTrigger>
+ <FolderInputIcon />
+ Move to
+ </MenuSubTrigger>
+ <MenuSubPopup>
+ {sections.map((section) => (
+ <MenuItem key={section.id} onClick={() => onMove(section.id)}>
+ {section.name}
+ </MenuItem>
+ ))}
+ <MenuItem onClick={() => onMove(null)}>Unassigned</MenuItem>
+ </MenuSubPopup>
+ </MenuSub>
</MenuPopup>
</Menu>
- </div>
+ </li>
+ );
+}
+
+function SortableRosterMarker(props: {
+ marker: RosterListMarker;
+ className?: string;
+ children?: ReactNode;
+ draggable?: boolean;
+ "data-testid"?: string;
+}) {
+ const { setNodeRef, transform, transition, listeners } = useSortable({
+ id: rosterMarkerId(props.marker),
+ disabled: { draggable: props.draggable !== true },
+ animateLayoutChanges: animateRosterLayoutChanges,
+ });
+ return (
+ <li
+ ref={setNodeRef}
+ data-testid={props["data-testid"]}
+ className={cn("list-none", props.className)}
+ style={{
+ transform: CSS.Translate.toString(transform),
+ transition:
+ typeof props.marker !== "string" && props.marker.kind === "section-placeholder"
+ ? "none"
+ : props.marker === "unassigned-placeholder"
+ ? "none"
+ : transition,
+ visibility: transform?.scaleY === 0 ? "hidden" : undefined,
+ }}
+ {...(props.draggable ? listeners : {})}
+ >
+ {props.children}
+ </li>
+ );
+}
+
+function RosterDragBoundary(props: {
+ marker: "pinned-header" | "pinned-divider";
+ label: string;
+ visible: boolean;
+ isDropTarget: boolean;
+}) {
+ return (
+ <SortableRosterMarker
+ marker={props.marker}
+ data-testid={`roster-${props.marker}`}
+ className="pointer-events-none relative mx-0.5 -mb-px h-0"
+ >
+ {props.visible ? (
+ <div className="roster-drag-boundary-label absolute inset-x-2 top-1 flex h-4 items-center gap-2">
+ <span
+ className={cn(
+ "shrink-0 text-xs font-medium",
+ props.isDropTarget ? "text-primary" : "text-sidebar-foreground/80",
+ )}
+ >
+ {props.label}
+ </span>
+ <span
+ aria-hidden
+ className={cn(
+ "h-px flex-1",
+ props.isDropTarget ? "bg-primary/50" : "bg-sidebar-foreground/25",
+ )}
+ />
+ </div>
+ ) : null}
+ </SortableRosterMarker>
+ );
+}
+
+function RosterSectionPlaceholder(props: {
+ marker: RosterListMarker;
+ label: string;
+ showHint: boolean;
+ isDropTarget: boolean;
+}) {
+ return (
+ <SortableRosterMarker
+ marker={props.marker}
+ data-testid="roster-section-placeholder"
+ className="relative mx-0.5 -mb-px h-0"
+ >
+ {props.showHint ? (
+ <div
+ className={cn(
+ "absolute inset-x-0 top-0 flex h-9 items-center justify-center rounded-md border border-dashed border-sidebar-foreground/25 text-xs text-sidebar-foreground/80",
+ props.isDropTarget && "border-primary/40 bg-primary/5 text-primary",
+ )}
+ >
+ {props.label}
+ </div>
+ ) : null}
+ </SortableRosterMarker>
);
}
@@ -538,7 +694,15 @@ export default function BotRosterSidebar() {
reportFailure: false,
});
const pathname = useLocation({ select: (location) => location.pathname });
- const { bots, groups, lastMessageByBotId, selectedBotId, sections, pinnedItems } = useRosterStore(
+ const {
+ bots,
+ groups,
+ lastMessageByBotId,
+ selectedBotId,
+ sections,
+ pinnedItems,
+ unassignedItems,
+ } = useRosterStore(
useShallow((state) => ({
bots: state.bots,
groups: state.groups,
@@ -546,6 +710,7 @@ export default function BotRosterSidebar() {
selectedBotId: state.selectedBotId,
sections: state.sections,
pinnedItems: state.pinnedItems,
+ unassignedItems: state.unassignedItems,
})),
);
const [query, setQuery] = useState("");
@@ -573,93 +738,250 @@ export default function BotRosterSidebar() {
[bots, groups, query],
);
const groupRouteActive = pathname.startsWith("/groups/");
- const pinnedBotIds = useMemo(
- () => new Set(pinnedItems.filter((item) => item.kind === "bot").map((item) => item.id)),
+ const searching = query.trim().length > 0;
+ const pinnedKeys = useMemo(
+ () => new Set(pinnedItems.map((item) => rosterItemKey(item))),
[pinnedItems],
);
- const assignedBotIds = useMemo(
- () => new Set(sections.flatMap((section) => section.botIds)),
+ const liveItem = useCallback(
+ (item: RosterItemRef) => {
+ if (item.kind === "bot") return visibleBots.some((bot) => bot.id === item.id);
+ return visibleGroups.some((group) => group.id === item.id);
+ },
+ [visibleBots, visibleGroups],
+ );
+ const visiblePinnedItems = useMemo(() => pinnedItems.filter(liveItem), [liveItem, pinnedItems]);
+ const visibleSectionLayouts = useMemo(
+ () =>
+ sections.map((section) => ({
+ id: section.id,
+ name: section.name,
+ collapsed: !searching && section.collapsed,
+ items: rosterSectionItems(section).filter(
+ (item) => liveItem(item) && !pinnedKeys.has(rosterItemKey(item)),
+ ),
+ })),
+ [liveItem, pinnedKeys, searching, sections],
+ );
+ const assignedKeys = useMemo(
+ () => new Set(sections.flatMap((section) => rosterSectionItems(section).map(rosterItemKey))),
[sections],
);
- const botsBySection = useMemo(
+ const visibleUnassignedItems = useMemo(() => {
+ const remaining = (item: RosterItemRef) =>
+ liveItem(item) &&
+ !pinnedKeys.has(rosterItemKey(item)) &&
+ !assignedKeys.has(rosterItemKey(item));
+ if (unassignedItems.length > 0) {
+ const ordered = unassignedItems.filter(remaining);
+ const seen = new Set(ordered.map(rosterItemKey));
+ for (const group of visibleGroups) {
+ const item = { kind: "group" as const, id: group.id };
+ if (remaining(item) && !seen.has(rosterItemKey(item))) ordered.push(item);
+ }
+ for (const bot of visibleBots) {
+ const item = { kind: "bot" as const, id: bot.id };
+ if (remaining(item) && !seen.has(rosterItemKey(item))) ordered.push(item);
+ }
+ return ordered;
+ }
+ return [
+ ...visibleGroups.map((group) => ({ kind: "group" as const, id: group.id })),
+ ...visibleBots.map((bot) => ({ kind: "bot" as const, id: bot.id })),
+ ].filter(remaining);
+ }, [assignedKeys, liveItem, pinnedKeys, unassignedItems, visibleBots, visibleGroups]);
+ const rosterListItems = useMemo(
() =>
- new Map(
- sections.map((section) => [
- section.id,
- section.botIds
- .map((id) => visibleBots.find((bot) => bot.id === id))
- .filter((bot): bot is Bot => bot !== undefined && !pinnedBotIds.has(bot.id)),
- ]),
- ),
- [pinnedBotIds, sections, visibleBots],
+ buildRosterListItems({
+ pinnedItems: visiblePinnedItems,
+ sections: visibleSectionLayouts,
+ unassignedItems: visibleUnassignedItems,
+ }),
+ [visiblePinnedItems, visibleSectionLayouts, visibleUnassignedItems],
);
- const unassignedBots = useMemo(
- () => visibleBots.filter((bot) => !assignedBotIds.has(bot.id) && !pinnedBotIds.has(bot.id)),
- [assignedBotIds, pinnedBotIds, visibleBots],
+ const firstSectionId = sections[0]?.id ?? null;
+ const zoneByEntryId = useMemo(() => {
+ const map = new Map<string, RosterZone>();
+ for (const item of rosterListItems) {
+ if (item.kind === "entry") map.set(rosterListItemId(item), item.zone);
+ }
+ return map;
+ }, [rosterListItems]);
+ const [dragState, setDragState] = useState<{
+ readonly activeId: string;
+ readonly from: RosterZone | "section";
+ readonly targetZone: RosterZone | null;
+ readonly activationY: number | null;
+ } | null>(null);
+ const listMotionRef = useRef<ReturnType<typeof createRosterListMotion> | null>(null);
+ const rosterListRef = useRef<HTMLUListElement | null>(null);
+ const dragLabelOffsetRef = useRef(0);
+ const dragSensorRef = useRef<RosterPointerSensor | null>(null);
+ const attachListMotionRef = useCallback((node: HTMLUListElement | null) => {
+ rosterListRef.current = node;
+ listMotionRef.current?.dispose();
+ listMotionRef.current = node === null ? null : createRosterListMotion(node);
+ listMotionRef.current?.update(false);
+ }, []);
+ const finishRosterDrag = useCallback((started: boolean) => {
+ dragSensorRef.current = null;
+ if (started) {
+ listMotionRef.current?.release();
+ setDragState(null);
+ }
+ }, []);
+ const attachDragSensor = useCallback((sensor: RosterPointerSensor) => {
+ dragSensorRef.current = sensor;
+ }, []);
+ const cancelRosterDrag = useCallback(() => {
+ dragSensorRef.current?.cancel();
+ }, []);
+ const dndSensors = useSensors(
+ useSensor(RosterPointerSensor, {
+ distance: 6,
+ onAttach: attachDragSensor,
+ onFinish: finishRosterDrag,
+ }),
);
- const pinnedGroupIds = useMemo(
- () => new Set(pinnedItems.filter((item) => item.kind === "group").map((item) => item.id)),
- [pinnedItems],
+ const restrictBelowPins = useCallback(
+ (args: Parameters<typeof restrictBelowRosterLabel>[0]) =>
+ restrictBelowRosterLabel(args, dragLabelOffsetRef.current),
+ [],
);
- const assignedGroupIds = useMemo(
- () => new Set(sections.flatMap((section) => section.groupIds ?? [])),
- [sections],
+ const handleRosterDragStart = useCallback(
+ (event: DragStartEvent) => {
+ const activeId = String(event.active.id);
+ const sectionId = parseRosterSectionHeaderId(activeId);
+ const from = sectionId ? ("section" as const) : zoneByEntryId.get(activeId);
+ if (from === undefined) return;
+ listMotionRef.current?.suspend();
+ const list = rosterListRef.current;
+ const header = list?.querySelector<HTMLElement>('[data-testid="roster-pinned-header"]');
+ if (list && header) {
+ const listRect = list.getBoundingClientRect();
+ const scale = list.offsetWidth > 0 ? listRect.width / list.offsetWidth : 1;
+ dragLabelOffsetRef.current =
+ header.getBoundingClientRect().top - listRect.top + ROSTER_DRAG_LABEL_HEIGHT * scale;
+ } else {
+ dragLabelOffsetRef.current = 0;
+ }
+ setDragState({
+ activeId,
+ from,
+ targetZone: from === "section" ? null : from,
+ activationY:
+ event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null,
+ });
+ },
+ [zoneByEntryId],
+ );
+ const handleRosterDragOver = useCallback(
+ (event: DragOverEvent) => {
+ const activeId = String(event.active.id);
+ if (parseRosterSectionHeaderId(activeId)) return;
+ const target = event.over
+ ? resolveRosterDropTarget(rosterListItems, activeId, String(event.over.id), firstSectionId)
+ : null;
+ setDragState((current) =>
+ current === null || current.activeId !== activeId
+ ? current
+ : { ...current, targetZone: target?.zone ?? null },
+ );
+ },
+ [firstSectionId, rosterListItems],
+ );
+ const handleRosterDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ const activeId = String(event.active.id);
+ const overId = event.over ? String(event.over.id) : null;
+ if (overId === null) return;
+ const sectionId = parseRosterSectionHeaderId(activeId);
+ if (sectionId) {
+ useRosterStore.getState().applyRosterDrop(
+ planRosterSectionDrop({
+ sectionIds: sections.map((section) => section.id),
+ activeSectionId: sectionId,
+ overId,
+ }),
+ );
+ return;
+ }
+ const from = zoneByEntryId.get(activeId);
+ const target = resolveRosterDropTarget(rosterListItems, activeId, overId, firstSectionId);
+ if (from === undefined || target === null) return;
+ useRosterStore.getState().applyRosterDrop(
+ planRosterDrop({
+ activeId,
+ from,
+ target,
+ pinnedOrder: visiblePinnedItems,
+ }),
+ );
+ },
+ [firstSectionId, rosterListItems, sections, visiblePinnedItems, zoneByEntryId],
);
- const groupsBySection = useMemo(
+ useEffect(() => {
+ if (
+ dragState !== null &&
+ !rosterListItems.some((item) => rosterListItemId(item) === dragState.activeId)
+ ) {
+ cancelRosterDrag();
+ }
+ }, [cancelRosterDrag, dragState, rosterListItems]);
+ const listMotionPaused = dragState !== null;
+ const rosterListOrderKey = useMemo(
() =>
- new Map(
- sections.map((section) => [
- section.id,
- (section.groupIds ?? [])
- .map((id) => visibleGroups.find((group) => group.id === id))
- .filter(
- (group): group is Group => group !== undefined && !pinnedGroupIds.has(group.id),
- ),
- ]),
- ),
- [pinnedGroupIds, sections, visibleGroups],
+ rosterListItems
+ .map((item) =>
+ item.kind === "entry"
+ ? `${rosterItemKey(item.item)}:${rosterListItemId(item)}`
+ : rosterListItemId(item),
+ )
+ .join("\0"),
+ [rosterListItems],
);
- const unassignedGroups = useMemo(
+ useLayoutEffect(() => {
+ void rosterListOrderKey;
+ listMotionRef.current?.update(!listMotionPaused && rosterListItems.length > 0);
+ }, [listMotionPaused, rosterListItems.length, rosterListOrderKey]);
+ const sortableIds = useMemo(() => rosterListItems.map(rosterListItemId), [rosterListItems]);
+ const rosterSortingStrategy = useMemo(
() =>
- visibleGroups.filter(
- (group) => !assignedGroupIds.has(group.id) && !pinnedGroupIds.has(group.id),
- ),
- [assignedGroupIds, pinnedGroupIds, visibleGroups],
+ createRosterSortingStrategy({
+ items: rosterListItems,
+ firstSectionId,
+ boundaryLabelHeight: ROSTER_DRAG_LABEL_HEIGHT,
+ }),
+ [firstSectionId, rosterListItems],
);
- const handleDragEnd = ({ draggableId, source, destination, type }: DropResult) => {
- if (!destination) return;
- if (type === "roster-section") {
- useRosterStore.getState().reorderSections(source.index, destination.index);
- return;
- }
- if (type === "roster-group") {
- const groupId = parseRosterGroupDropId(draggableId);
- if (!groupId) return;
- if (destination.droppableId.startsWith("section-groups:")) {
- useRosterStore
- .getState()
- .moveGroupToSection(
- groupId,
- destination.droppableId.slice("section-groups:".length),
- destination.index,
+ const dndCollisionDetection = useMemo(
+ () =>
+ createRosterCollisionDetection(
+ (id) => {
+ if (dragState === null) return true;
+ if (dragState.from === "section") {
+ return (
+ parseRosterSectionHeaderId(id) !== null || id === rosterMarkerId("unassigned-header")
+ );
+ }
+ return (
+ resolveRosterDropTarget(rosterListItems, dragState.activeId, id, firstSectionId) !==
+ null
);
- } else if (destination.droppableId === "roster-unassigned-groups") {
- useRosterStore.getState().moveGroupToSection(groupId, null, destination.index);
- }
- return;
- }
- const botId = parseRosterBotDragId(draggableId);
- if (botId && destination.droppableId.startsWith("section:")) {
- useRosterStore
- .getState()
- .moveBotToSection(
- botId,
- destination.droppableId.slice("section:".length),
- destination.index,
- );
- } else if (botId && destination.droppableId === "roster-unassigned") {
- useRosterStore.getState().moveBotToSection(botId, null, destination.index);
- }
+ },
+ {
+ items: rosterListItems,
+ activationY: dragState?.activationY ?? null,
+ firstSectionId,
+ },
+ ),
+ [dragState, firstSectionId, rosterListItems],
+ );
+ const dragTargetZone = dragState?.targetZone ?? null;
+ const dropVerbFor = (id: string): RosterDropVerb | null => {
+ if (dragState === null || dragState.activeId !== id || dragState.from === "section")
+ return null;
+ return resolveRosterDropVerb(dragState.from, dragTargetZone);
};
// Remember the chat route the selected bot lands on, so re-selecting the
@@ -786,9 +1108,6 @@ export default function BotRosterSidebar() {
void navigate({ to: "/groups/$groupId", params: { groupId: group.id } });
};
- const isPinned = (item: RosterItemRef) =>
- pinnedItems.some((candidate) => candidate.kind === item.kind && candidate.id === item.id);
-
useEffect(() => {
if (pendingCreatedBotId === null) return;
const bot = bots.find((candidate) => candidate.id === pendingCreatedBotId);
@@ -879,50 +1198,217 @@ export default function BotRosterSidebar() {
))}
</ul>
</SidebarGroup>
- <DragDropContext onDragEnd={handleDragEnd}>
- {pinnedItems.length > 0 ? (
- <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-3 pt-3 group-data-[collapsible=icon]:hidden">
- <div
- className="flex justify-center gap-2 overflow-x-auto px-2 py-1"
+ <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-1 group-data-[collapsible=icon]:hidden">
+ <DndContext
+ sensors={dndSensors}
+ collisionDetection={dndCollisionDetection}
+ modifiers={[
+ restrictToVerticalAxis,
+ restrictBelowPins,
+ restrictToFirstScrollableAncestor,
+ ]}
+ onDragStart={handleRosterDragStart}
+ onDragOver={handleRosterDragOver}
+ onDragEnd={handleRosterDragEnd}
+ >
+ <RosterDragLifecycle onUnmount={cancelRosterDrag} />
+ <SortableContext items={sortableIds} strategy={rosterSortingStrategy}>
+ <ul
+ ref={attachListMotionRef}
role="list"
- aria-label="Pinned bots and groups"
+ aria-label="Bots and groups"
+ className="relative flex flex-col gap-px"
>
- {pinnedItems.map((item) => (
- <PinnedRosterItem
- key={`${item.kind}:${item.id}`}
- item={item}
- bots={bots}
- groups={groups}
- onSelectBot={handleSelect}
- onSelectGroup={handleSelectGroup}
- />
- ))}
- </div>
- </SidebarGroup>
- ) : null}
- <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-1 group-data-[collapsible=icon]:hidden">
- <Droppable droppableId="roster-sections" type="roster-section">
- {(sectionsProvided) => (
- <div ref={sectionsProvided.innerRef} {...sectionsProvided.droppableProps}>
- {sections.map((section, sectionIndex) => {
- const sectionBots = botsBySection.get(section.id) ?? [];
- const sectionGroups = groupsBySection.get(section.id) ?? [];
- const collapsed = query.length === 0 && section.collapsed;
+ {rosterListItems.map((item) => {
+ if (item.kind === "entry") {
+ const dropVerb = dropVerbFor(rosterListItemId(item));
+ const pinned = pinnedKeys.has(rosterItemKey(item.item));
+ const zoneOrder = rosterItemsForZone(item.zone, {
+ pinnedItems: visiblePinnedItems,
+ sections: visibleSectionLayouts,
+ unassignedItems: visibleUnassignedItems,
+ });
+ const zoneIndex = zoneOrder.findIndex((candidate) =>
+ rosterItemsEqual(candidate, item.item),
+ );
+ const canMoveUp = !searching && zoneIndex > 0;
+ const canMoveDown =
+ !searching && zoneIndex >= 0 && zoneIndex < zoneOrder.length - 1;
+ const onNudge = (delta: -1 | 1) =>
+ useRosterStore.getState().nudgeRosterItem(item.item, delta);
return (
- <Draggable
- key={section.id}
- draggableId={`section:${section.id}`}
- index={sectionIndex}
- isDragDisabled={query.length > 0}
+ <SortableRosterRow
+ key={rosterListItemId(item)}
+ id={rosterListItemId(item)}
+ disabled={searching}
>
- {(sectionProvided, sectionSnapshot) => (
- <section
- ref={sectionProvided.innerRef}
+ {(bag) =>
+ item.item.kind === "bot"
+ ? (() => {
+ const bot = bots.find(
+ (candidate) => candidate.id === item.item.id,
+ );
+ if (!bot) return null;
+ return (
+ <BotRosterRow
+ bot={bot}
+ lastMessage={lastMessageByBotId[bot.id] ?? null}
+ isActive={!groupRouteActive && selectedBotId === bot.id}
+ onSelect={handleSelect}
+ pinned={pinned}
+ sections={sections}
+ onPin={(nextPinned) =>
+ useRosterStore
+ .getState()
+ .setItemPinned({ kind: "bot", id: bot.id }, nextPinned)
+ }
+ onMove={(sectionId) =>
+ useRosterStore
+ .getState()
+ .moveBotToSection(bot.id, sectionId)
+ }
+ canMoveUp={canMoveUp}
+ canMoveDown={canMoveDown}
+ onNudge={onNudge}
+ sortable={bag}
+ dropVerb={dropVerb}
+ />
+ );
+ })()
+ : (() => {
+ const group = groups.find(
+ (candidate) => candidate.id === item.item.id,
+ );
+ if (!group) return null;
+ return (
+ <GroupRosterRow
+ group={group}
+ bots={bots}
+ isActive={pathname === `/groups/${group.id}`}
+ onSelect={() => handleSelectGroup(group)}
+ pinned={pinned}
+ sections={sections}
+ onPin={(nextPinned) =>
+ useRosterStore
+ .getState()
+ .setItemPinned(
+ { kind: "group", id: group.id },
+ nextPinned,
+ )
+ }
+ onMove={(sectionId) =>
+ useRosterStore
+ .getState()
+ .moveGroupToSection(group.id, sectionId)
+ }
+ canMoveUp={canMoveUp}
+ canMoveDown={canMoveDown}
+ onNudge={onNudge}
+ sortable={bag}
+ dropVerb={dropVerb}
+ />
+ );
+ })()
+ }
+ </SortableRosterRow>
+ );
+ }
+ const from = dragState?.from ?? null;
+ const dragging = from !== null;
+ switch (item.marker) {
+ case "pinned-header":
+ return (
+ <RosterDragBoundary
+ key="pinned-header"
+ marker="pinned-header"
+ label="Pinned"
+ visible={dragging}
+ isDropTarget={dragTargetZone === "pinned"}
+ />
+ );
+ case "pinned-divider":
+ return (
+ <RosterDragBoundary
+ key="pinned-divider"
+ marker="pinned-divider"
+ label={sections[0]?.name ?? "Unassigned"}
+ visible={dragging}
+ isDropTarget={dragTargetZone !== null && dragTargetZone !== "pinned"}
+ />
+ );
+ case "unassigned-header":
+ return (
+ <SortableRosterMarker
+ key="unassigned-header"
+ marker="unassigned-header"
+ data-testid="roster-unassigned-header"
+ className="relative"
+ >
+ <div
className={cn(
- "mb-1 rounded-lg",
- sectionSnapshot.isDragging && "bg-sidebar shadow-xl",
+ "flex h-8 items-center gap-1.5 px-2 text-xs font-medium text-sidebar-muted-foreground",
+ dragging && "text-sidebar-foreground/80",
+ dragTargetZone === "unassigned" && "text-primary",
)}
- {...sectionProvided.draggableProps}
+ >
+ <ChevronDownIcon className="size-3.5" />
+ <span>Unassigned</span>
+ <span className="tabular-nums">
+ {visibleUnassignedItems.length}
+ </span>
+ <span
+ aria-hidden
+ className={cn(
+ "h-px min-w-2 flex-1",
+ dragTargetZone === "unassigned"
+ ? "bg-primary/50"
+ : "bg-sidebar-border/60",
+ )}
+ />
+ </div>
+ </SortableRosterMarker>
+ );
+ case "unassigned-placeholder":
+ return (
+ <RosterSectionPlaceholder
+ key="unassigned-placeholder"
+ marker="unassigned-placeholder"
+ label="Unassigned"
+ showHint={
+ dragging &&
+ (visibleUnassignedItems.length === 0 ||
+ (dragState?.from === "unassigned" &&
+ visibleUnassignedItems.length === 1 &&
+ dragTargetZone !== null &&
+ dragTargetZone !== "unassigned"))
+ }
+ isDropTarget={dragTargetZone === "unassigned"}
+ />
+ );
+ default: {
+ if (typeof item.marker !== "object") return null;
+ const marker = item.marker;
+ if (marker.kind === "section-header") {
+ const section = sections.find(
+ (candidate) => candidate.id === marker.sectionId,
+ );
+ if (!section) return null;
+ const layout = visibleSectionLayouts.find(
+ (candidate) => candidate.id === section.id,
+ );
+ const collapsed = layout?.collapsed ?? section.collapsed;
+ const count = layout?.items.length ?? 0;
+ const zone = { sectionId: section.id };
+ const sectionIndex = sections.findIndex(
+ (candidate) => candidate.id === section.id,
+ );
+ return (
+ <SortableRosterMarker
+ key={rosterMarkerId(item.marker)}
+ marker={item.marker}
+ draggable={!searching}
+ data-testid="roster-section-header"
+ className="relative"
>
<div
className="relative flex h-8 items-center rounded-md hover:bg-sidebar-row-hover"
@@ -939,8 +1425,11 @@ export default function BotRosterSidebar() {
onClick={() =>
useRosterStore.getState().toggleSection(section.id)
}
- className="flex min-w-0 flex-1 cursor-grab items-center gap-1.5 px-2 text-left text-xs font-medium text-sidebar-muted-foreground active:cursor-grabbing"
- {...sectionProvided.dragHandleProps}
+ className={cn(
+ "flex min-w-0 flex-1 cursor-grab items-center gap-1.5 px-2 text-left text-xs font-medium text-sidebar-muted-foreground active:cursor-grabbing",
+ rosterZonesEqual(dragTargetZone ?? "pinned", zone) &&
+ "text-primary",
+ )}
>
{collapsed ? (
<ChevronRightIcon className="size-3.5" />
@@ -948,9 +1437,7 @@ export default function BotRosterSidebar() {
<ChevronDownIcon className="size-3.5" />
)}
<span className="truncate">{section.name}</span>
- <span className="tabular-nums">
- {sectionBots.length + sectionGroups.length}
- </span>
+ <span className="tabular-nums">{count}</span>
</button>
<Menu>
<MenuTrigger
@@ -964,6 +1451,28 @@ export default function BotRosterSidebar() {
}
/>
<MenuPopup align="end">
+ <MenuItem
+ disabled={searching || sectionIndex <= 0}
+ onClick={() =>
+ useRosterStore
+ .getState()
+ .reorderSections(sectionIndex, sectionIndex - 1)
+ }
+ >
+ <ArrowUpIcon />
+ Move up
+ </MenuItem>
+ <MenuItem
+ disabled={searching || sectionIndex >= sections.length - 1}
+ onClick={() =>
+ useRosterStore
+ .getState()
+ .reorderSections(sectionIndex, sectionIndex + 1)
+ }
+ >
+ <ArrowDownIcon />
+ Move down
+ </MenuItem>
<MenuItem
variant="destructive"
onClick={() =>
@@ -976,202 +1485,52 @@ export default function BotRosterSidebar() {
</MenuPopup>
</Menu>
</div>
- <Droppable
- droppableId={`section-groups:${section.id}`}
- type="roster-group"
- >
- {(provided, snapshot) => (
- <div
- ref={provided.innerRef}
- role="list"
- aria-label={`${section.name} groups`}
- data-drag-over={snapshot.isDraggingOver || undefined}
- className={cn(
- "rounded-lg data-[drag-over=true]:bg-sidebar-row-hover",
- collapsed
- ? "min-h-2"
- : sectionGroups.length > 0
- ? "min-h-10"
- : "min-h-1",
- )}
- {...provided.droppableProps}
- >
- {!collapsed
- ? sectionGroups.map((group, index) => (
- <GroupRosterRow
- key={group.id}
- group={group}
- bots={bots}
- index={index}
- sections={sections}
- dragDisabled={query.length > 0}
- isActive={pathname === `/groups/${group.id}`}
- onSelect={() => handleSelectGroup(group)}
- pinned={false}
- onPin={(pinned) =>
- useRosterStore.getState().setItemPinned(
- {
- kind: "group",
- id: group.id,
- },
- pinned,
- )
- }
- onMove={(sectionId) =>
- useRosterStore
- .getState()
- .moveGroupToSection(group.id, sectionId)
- }
- />
- ))
- : null}
- {provided.placeholder}
- </div>
- )}
- </Droppable>
- <Droppable droppableId={`section:${section.id}`} type="roster-bot">
- {(provided, snapshot) => (
- <div
- ref={provided.innerRef}
- role="list"
- aria-label={section.name}
- data-drag-over={snapshot.isDraggingOver || undefined}
- className={cn(
- "rounded-lg data-[drag-over=true]:bg-sidebar-row-hover",
- collapsed ? "min-h-2" : "min-h-10",
- )}
- {...provided.droppableProps}
- >
- {!collapsed
- ? sectionBots.map((bot, index) => (
- <BotRosterRow
- key={bot.id}
- bot={bot}
- index={index}
- lastMessage={lastMessageByBotId[bot.id] ?? null}
- isActive={
- !groupRouteActive && selectedBotId === bot.id
- }
- onSelect={handleSelect}
- pinned={isPinned({
- kind: "bot",
- id: bot.id,
- })}
- sections={sections}
- onPin={(pinned) =>
- useRosterStore
- .getState()
- .setItemPinned(
- { kind: "bot", id: bot.id },
- pinned,
- )
- }
- onMove={(sectionId) =>
- useRosterStore
- .getState()
- .moveBotToSection(bot.id, sectionId)
- }
- dragDisabled={query.length > 0}
- />
- ))
- : null}
- {provided.placeholder}
- </div>
- )}
- </Droppable>
- </section>
- )}
- </Draggable>
- );
- })}
- {sectionsProvided.placeholder}
- </div>
- )}
- </Droppable>
- <div className="flex h-8 items-center gap-1.5 px-2 text-xs font-medium text-sidebar-muted-foreground">
- <ChevronDownIcon className="size-3.5" />
- <span>Unassigned</span>
- <span className="tabular-nums">
- {unassignedBots.length + unassignedGroups.length}
- </span>
- </div>
- <Droppable droppableId="roster-unassigned-groups" type="roster-group">
- {(provided, snapshot) => (
- <div
- ref={provided.innerRef}
- role="list"
- aria-label="Unassigned groups"
- data-drag-over={snapshot.isDraggingOver || undefined}
- className="min-h-1 rounded-lg data-[drag-over=true]:bg-sidebar-row-hover"
- {...provided.droppableProps}
- >
- {unassignedGroups.map((group, index) => (
- <GroupRosterRow
- key={group.id}
- group={group}
- bots={bots}
- index={index}
- sections={sections}
- dragDisabled={query.length > 0}
- isActive={pathname === `/groups/${group.id}`}
- onSelect={() => handleSelectGroup(group)}
- pinned={false}
- onPin={(pinned) =>
- useRosterStore
- .getState()
- .setItemPinned({ kind: "group", id: group.id }, pinned)
- }
- onMove={(sectionId) =>
- useRosterStore.getState().moveGroupToSection(group.id, sectionId)
+ </SortableRosterMarker>
+ );
}
- />
- ))}
- {provided.placeholder}
- </div>
- )}
- </Droppable>
- <Droppable droppableId="roster-unassigned" type="roster-bot">
- {(provided, snapshot) => (
- <div
- ref={provided.innerRef}
- role="list"
- aria-label="Unassigned"
- data-drag-over={snapshot.isDraggingOver || undefined}
- className="min-h-10 rounded-lg data-[drag-over=true]:bg-sidebar-row-hover"
- {...provided.droppableProps}
- >
- {unassignedBots.map((bot, index) => (
- <BotRosterRow
- key={bot.id}
- bot={bot}
- index={index}
- lastMessage={lastMessageByBotId[bot.id] ?? null}
- isActive={!groupRouteActive && selectedBotId === bot.id}
- onSelect={handleSelect}
- pinned={isPinned({ kind: "bot", id: bot.id })}
- sections={sections}
- onPin={(pinned) =>
- useRosterStore
- .getState()
- .setItemPinned({ kind: "bot", id: bot.id }, pinned)
- }
- onMove={(sectionId) =>
- useRosterStore.getState().moveBotToSection(bot.id, sectionId)
- }
- dragDisabled={query.length > 0}
- />
- ))}
- {provided.placeholder}
- </div>
- )}
- </Droppable>
- {visibleBots.length === 0 && visibleGroups.length === 0 ? (
- <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">
- No bots match
- </div>
- ) : null}
- </SidebarGroup>
- </DragDropContext>
+ const zone = { sectionId: marker.sectionId };
+ const layout = visibleSectionLayouts.find(
+ (candidate) => candidate.id === marker.sectionId,
+ );
+ const activeEntry = dragState && parseRosterEntryId(dragState.activeId);
+ return (
+ <RosterSectionPlaceholder
+ key={rosterMarkerId(item.marker)}
+ marker={item.marker}
+ label={layout?.name ?? "Section"}
+ showHint={
+ dragging &&
+ (layout?.items.length === 0 ||
+ layout?.collapsed === true ||
+ (activeEntry !== null &&
+ dragState?.from !== "section" &&
+ dragState !== null &&
+ rosterZonesEqual(dragState.from, zone) &&
+ !rosterZoneHasVisibleEntries(
+ rosterListItems,
+ zone,
+ activeEntry ?? undefined,
+ ) &&
+ dragTargetZone !== null &&
+ !rosterZonesEqual(dragTargetZone, zone)))
+ }
+ isDropTarget={
+ dragTargetZone !== null && rosterZonesEqual(dragTargetZone, zone)
+ }
+ />
+ );
+ }
+ }
+ })}
+ </ul>
+ </SortableContext>
+ </DndContext>
+ {visibleBots.length === 0 && visibleGroups.length === 0 ? (
+ <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">
+ No bots match
+ </div>
+ ) : null}
+ </SidebarGroup>
</>
)}
</SidebarContent>
diff --git a/apps/web/src/components/roster/roster.drag.test.ts b/apps/web/src/components/roster/roster.drag.test.ts
new file mode 100644
index 000000000..c0ab1a3e8
--- /dev/null
+++ b/apps/web/src/components/roster/roster.drag.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from "vite-plus/test";
+import { closestCenter, type CollisionDetection } from "@dnd-kit/core";
+import { verticalListSortingStrategy, type SortingStrategy } from "@dnd-kit/sortable";
+
+import { createRosterCollisionDetection, createRosterSortingStrategy } from "./roster.drag";
+import {
+ buildRosterListItems,
+ rosterEntryId,
+ rosterListItemId,
+ rosterMarkerId,
+ type RosterItemRef,
+ type RosterListItem,
+} from "./roster.logic";
+
+const stationary = { x: 0, y: 0, scaleX: 1, scaleY: 1 };
+const akeru: RosterItemRef = { kind: "bot", id: "akeru" };
+const mori: RosterItemRef = { kind: "bot", id: "mori" };
+
+function layout(items: readonly RosterListItem[], active: string, over: string, cardHeight = 52) {
+ let top = 100;
+ const rects = items.map((item) => {
+ const height =
+ item.kind === "entry"
+ ? cardHeight
+ : item.marker === "pinned-header" || item.marker === "pinned-divider"
+ ? 0
+ : item.marker === "unassigned-placeholder" ||
+ (typeof item.marker === "object" && item.marker.kind === "section-placeholder")
+ ? 0
+ : 32;
+ const rect = { top, height, bottom: top + height, left: 0, right: 260, width: 260 };
+ top += height + 1;
+ return rect;
+ });
+ const activeIndex = items.findIndex((item) => rosterListItemId(item) === active);
+ return {
+ activeIndex,
+ overIndex: items.findIndex((item) => rosterListItemId(item) === over),
+ activeNodeRect: rects[activeIndex]!,
+ rects,
+ index: 0,
+ } satisfies Parameters<SortingStrategy>[0];
+}
+
+describe("roster collision detection", () => {
+ const items = buildRosterListItems({
+ pinnedItems: [],
+ sections: [],
+ unassignedItems: [akeru, mori],
+ });
+
+ function collisionArgs() {
+ const { rects, activeIndex, overIndex } = layout(
+ items,
+ rosterEntryId(akeru),
+ rosterEntryId(mori),
+ );
+ const collisionRect = rects[overIndex]!;
+ return {
+ active: {
+ id: rosterEntryId(akeru),
+ data: { current: {} },
+ rect: { current: { initial: rects[activeIndex]!, translated: collisionRect } },
+ },
+ collisionRect,
+ droppableRects: new Map(items.map((item, index) => [rosterListItemId(item), rects[index]!])),
+ droppableContainers: items.map((item, index) => ({
+ id: rosterListItemId(item),
+ key: rosterListItemId(item),
+ disabled: false,
+ data: { current: {} },
+ node: { current: null },
+ rect: { current: rects[index]! },
+ })),
+ pointerCoordinates: null,
+ } satisfies Parameters<CollisionDetection>[0];
+ }
+
+ it("rejects an unsupported neighbor instead of selecting another section", () => {
+ const args = collisionArgs();
+ const detector = createRosterCollisionDetection((id) => id !== rosterEntryId(mori));
+ expect(closestCenter(args)[0]?.id).toBe(rosterEntryId(mori));
+ expect(detector(args).map((collision) => collision.id)).toEqual([rosterEntryId(akeru)]);
+ });
+
+ it("selects the nearest supported target", () => {
+ const detector = createRosterCollisionDetection(() => true);
+ expect(detector(collisionArgs())[0]?.id).toBe(rosterEntryId(mori));
+ });
+});
+
+describe("roster drag projection", () => {
+ it("opens Pins label space while dragging an unassigned bot to the header", () => {
+ const items = buildRosterListItems({
+ pinnedItems: [],
+ sections: [],
+ unassignedItems: [akeru, mori],
+ });
+ const strategy = createRosterSortingStrategy({
+ items,
+ boundaryLabelHeight: 16,
+ });
+ const args = layout(items, rosterEntryId(akeru), rosterMarkerId("pinned-header"));
+ const header = strategy({ ...args, index: 0 });
+ expect(header).toEqual(stationary);
+ const akeruIndex = items.findIndex((item) => rosterListItemId(item) === rosterEntryId(akeru));
+ expect(strategy({ ...args, index: akeruIndex })).toEqual(stationary);
+ });
+
+ it("keeps same-section reorder on the default vertical strategy", () => {
+ const items = buildRosterListItems({
+ pinnedItems: [],
+ sections: [],
+ unassignedItems: [akeru, mori],
+ });
+ const strategy = createRosterSortingStrategy({ items });
+ const args = layout(items, rosterEntryId(akeru), rosterEntryId(mori));
+ for (let index = 0; index < items.length; index += 1) {
+ if (index === args.activeIndex) continue;
+ expect(strategy({ ...args, index })).toEqual(verticalListSortingStrategy({ ...args, index }));
+ }
+ });
+});
diff --git a/apps/web/src/components/roster/roster.drag.ts b/apps/web/src/components/roster/roster.drag.ts
new file mode 100644
index 000000000..9b865c90a
--- /dev/null
+++ b/apps/web/src/components/roster/roster.drag.ts
@@ -0,0 +1,362 @@
+import { closestCenter, type CollisionDetection, type Modifier } from "@dnd-kit/core";
+import {
+ defaultAnimateLayoutChanges,
+ verticalListSortingStrategy,
+ type AnimateLayoutChanges,
+ type SortingStrategy,
+} from "@dnd-kit/sortable";
+
+import {
+ parseRosterEntryId,
+ parseRosterSectionHeaderId,
+ resolveRosterDropTarget,
+ rosterListItemId,
+ rosterMarkerId,
+ type RosterListItem,
+ type RosterListMarker,
+ type RosterZone,
+} from "./roster.logic";
+
+const stationary = { x: 0, y: 0, scaleX: 1, scaleY: 1 };
+const hidden = { ...stationary, scaleY: 0 };
+type Layout = Parameters<SortingStrategy>[0];
+
+/** Sortable transforms own dragging; replaying the committed DOM order would
+ * animate the drop twice. */
+export const animateRosterLayoutChanges: AnimateLayoutChanges = (args) =>
+ args.isSorting ? defaultAnimateLayoutChanges(args) : false;
+
+/** Keep the lifted card below the Pins label, including when Pins is empty.
+ * The container rect follows scrolling; the offset is measured once at pickup. */
+export function restrictBelowRosterLabel(
+ { transform, containerNodeRect, draggingNodeRect }: Parameters<Modifier>[0],
+ offset: number,
+) {
+ if (!containerNodeRect || !draggingNodeRect) return transform;
+ const minimumY = containerNodeRect.top + offset - draggingNodeRect.top;
+ return transform.y < minimumY ? { ...transform, y: minimumY } : transform;
+}
+
+function markerIsPinnedBoundary(marker: RosterListMarker): boolean {
+ return marker === "pinned-header" || marker === "pinned-divider";
+}
+
+/** Reject the nearest unsupported target without selecting another section.
+ * Recreate this detector when drop eligibility changes. */
+export function createRosterCollisionDetection(
+ isValidTarget: (id: string) => boolean,
+ options: {
+ items?: readonly RosterListItem[];
+ activationY?: number | null;
+ firstSectionId?: string | null;
+ } = {},
+): CollisionDetection {
+ const validity = new Map<string, boolean>();
+ const zones = new Map<string, RosterZone | null>();
+ let previousPointerY = options.activationY;
+ let boundaryZone: "pinned" | "rest" | undefined;
+ return (args) => {
+ let collisions = closestCenter(args);
+ const pointer = args.pointerCoordinates;
+ const items = options.items;
+ const source = items?.find(
+ (item) => item.kind === "entry" && rosterListItemId(item) === String(args.active.id),
+ );
+ const boundary = args.droppableContainers
+ .find((container) => container.id === rosterMarkerId("pinned-divider"))
+ ?.node.current?.querySelector(".roster-drag-boundary-label")
+ ?.getBoundingClientRect();
+ if (items && boundary && source?.kind === "entry" && pointer) {
+ boundaryZone ??= source.zone === "pinned" ? "pinned" : "rest";
+ const previousY = previousPointerY ?? pointer.y;
+ previousPointerY = pointer.y;
+ if (pointer.x >= boundary.left && pointer.x <= boundary.right) {
+ if (pointer.y < previousY && pointer.y <= boundary.bottom) boundaryZone = "pinned";
+ else if (pointer.y > previousY && pointer.y >= boundary.top) boundaryZone = "rest";
+ const restTop = args.droppableContainers
+ .find((container) => {
+ const id = String(container.id);
+ return (
+ parseRosterSectionHeaderId(id) !== null || id === rosterMarkerId("unassigned-header")
+ );
+ })
+ ?.node.current?.getBoundingClientRect().top;
+ if (boundaryZone === "pinned" || (restTop != null && pointer.y < restTop)) {
+ const target = collisions.find((collision) => {
+ const id = String(collision.id);
+ if (!zones.has(id)) {
+ zones.set(
+ id,
+ resolveRosterDropTarget(
+ items,
+ String(args.active.id),
+ id,
+ options.firstSectionId ?? null,
+ )?.zone ?? null,
+ );
+ }
+ const zone = zones.get(id);
+ if (zone == null) return false;
+ return boundaryZone === "pinned" ? zone === "pinned" : zone !== "pinned";
+ });
+ if (target)
+ collisions = [target, ...collisions.filter((collision) => collision !== target)];
+ }
+ }
+ }
+ const nearest = collisions[0];
+ if (!nearest || nearest.id === args.active.id) {
+ return collisions;
+ }
+ const id = String(nearest.id);
+ const valid = validity.get(id) ?? isValidTarget(id);
+ validity.set(id, valid);
+ return valid ? collisions : collisions.filter((collision) => collision.id === args.active.id);
+ };
+}
+
+/** Preview the committed section layout without moving or mounting DOM nodes.
+ * A zero scaleY marks rows/markers to hide while retaining their measured nodes. */
+export function createRosterSortingStrategy(input: {
+ items: readonly RosterListItem[];
+ firstSectionId?: string | null;
+ cardHeight?: number;
+ slimHeight?: number;
+ headerHeight?: number;
+ /** Space each pinned boundary opens for its label while dragging. The
+ * markers stay zero height at rest, so nothing is reserved until pickup. */
+ boundaryLabelHeight?: number;
+}): SortingStrategy {
+ const { items } = input;
+ const indices = new Map(items.map((item, index) => [rosterListItemId(item), index]));
+ let previous: Pick<Layout, "rects" | "activeIndex" | "overIndex"> | undefined;
+ let transforms: ReturnType<SortingStrategy>[] | null = [];
+
+ function project({ rects, activeIndex, overIndex }: Layout) {
+ const active = items[activeIndex];
+ const over = items[overIndex] ?? active;
+ if (!active || !over || !rects[0]) return [];
+ if (active.kind === "marker") {
+ const sectionId =
+ typeof active.marker === "object" && active.marker.kind === "section-header"
+ ? active.marker.sectionId
+ : parseRosterSectionHeaderId(rosterListItemId(active));
+ if (!sectionId) return [];
+ return projectSectionReorder({
+ rects,
+ activeIndex,
+ overIndex,
+ sectionId,
+ activeNodeRect: null,
+ index: activeIndex,
+ });
+ }
+ const target = resolveRosterDropTarget(
+ items,
+ rosterListItemId(active),
+ rosterListItemId(over),
+ input.firstSectionId ?? null,
+ );
+ if (!target) return [];
+ const groups = new Map<string, Extract<RosterListItem, { kind: "entry" }>[]>();
+ const remember = (zone: RosterZone) => {
+ const id = zone === "pinned" || zone === "unassigned" ? zone : zone.sectionId;
+ if (!groups.has(id)) groups.set(id, []);
+ return groups.get(id)!;
+ };
+ let cardHeight = input.cardHeight;
+ let slimHeight = input.slimHeight;
+ let headerHeight = input.headerHeight;
+ for (const [index, item] of items.entries()) {
+ if (item.kind === "marker") {
+ if (
+ item.marker === "unassigned-header" ||
+ (typeof item.marker === "object" && item.marker.kind === "section-header")
+ ) {
+ const height = rects[index]?.height;
+ if (height) headerHeight ??= height;
+ }
+ continue;
+ }
+ cardHeight ??= rects[index]?.height;
+ if (item.item.kind !== active.item.kind || item.item.id !== active.item.id) {
+ remember(item.zone).push(item);
+ }
+ }
+ cardHeight ??= 52;
+ slimHeight ??= 36;
+ headerHeight ??= 32;
+ const labelHeight = input.boundaryLabelHeight ?? 0;
+ const moved: Extract<RosterListItem, { kind: "entry" }> = { ...active, zone: target.zone };
+ const destination = remember(target.zone);
+ const ranks = new Map(target.order.map((item, index) => [`${item.kind}:${item.id}`, index]));
+ const rank = ranks.get(`${active.item.kind}:${active.item.id}`) ?? Number.POSITIVE_INFINITY;
+ const insertAt = destination.findIndex(
+ (item) => (ranks.get(`${item.item.kind}:${item.item.id}`) ?? Number.POSITIVE_INFINITY) > rank,
+ );
+ destination.splice(insertAt < 0 ? destination.length : insertAt, 0, moved);
+
+ const projected: RosterListItem[] = [];
+ const marker = (name: RosterListMarker) => projected.push({ kind: "marker", marker: name });
+ marker("pinned-header");
+ projected.push(...(groups.get("pinned") ?? []));
+ marker("pinned-divider");
+ const sectionIds: string[] = [];
+ for (const item of items) {
+ if (
+ item.kind === "marker" &&
+ typeof item.marker === "object" &&
+ item.marker.kind === "section-header" &&
+ !sectionIds.includes(item.marker.sectionId)
+ ) {
+ sectionIds.push(item.marker.sectionId);
+ }
+ }
+ for (const sectionId of sectionIds) {
+ marker({ kind: "section-header", sectionId });
+ marker({ kind: "section-placeholder", sectionId });
+ projected.push(...(groups.get(sectionId) ?? []));
+ }
+ marker("unassigned-header");
+ marker("unassigned-placeholder");
+ projected.push(...(groups.get("unassigned") ?? []));
+
+ const result = items.map(() => hidden);
+ let top = rects[0].top;
+ for (const item of projected) {
+ const index = indices.get(rosterListItemId(item));
+ const rect = index === undefined ? undefined : rects[index];
+ if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top };
+ const movedEntry =
+ item.kind === "entry" && rosterListItemId(item) === rosterListItemId(active);
+ const height =
+ item.kind === "marker" && markerIsPinnedBoundary(item.marker)
+ ? labelHeight
+ : item.kind === "marker" &&
+ (item.marker === "unassigned-placeholder" ||
+ (typeof item.marker === "object" && item.marker.kind === "section-placeholder"))
+ ? (groups.get(typeof item.marker === "object" ? item.marker.sectionId : "unassigned")
+ ?.length ?? 0) === 0
+ ? slimHeight
+ : 0
+ : item.kind === "marker"
+ ? (rect?.height ?? headerHeight)
+ : movedEntry
+ ? cardHeight
+ : (rect?.height ?? cardHeight);
+ top += height + 1;
+ }
+ result[activeIndex] = stationary;
+ return result;
+ }
+
+ function projectSectionReorder({
+ rects,
+ activeIndex,
+ overIndex,
+ sectionId,
+ }: Layout & { sectionId: string }) {
+ const overId = rosterListItemId(items[overIndex] ?? items[activeIndex]!);
+ const overSectionId =
+ parseRosterSectionHeaderId(overId) ??
+ (overId === rosterMarkerId("unassigned-header") ? "__end__" : null);
+ if (overSectionId === null) return [];
+ const blocks: RosterListItem[][] = [];
+ let current: RosterListItem[] = [];
+ const flush = () => {
+ if (current.length > 0) blocks.push(current);
+ current = [];
+ };
+ for (const item of items) {
+ if (
+ item.kind === "marker" &&
+ (item.marker === "pinned-header" ||
+ item.marker === "pinned-divider" ||
+ (typeof item.marker === "object" && item.marker.kind === "section-header") ||
+ item.marker === "unassigned-header")
+ ) {
+ if (
+ typeof item.marker === "object" &&
+ item.marker.kind === "section-header" &&
+ current.length > 0
+ ) {
+ flush();
+ }
+ }
+ current.push(item);
+ }
+ flush();
+ const pinnedBlocks = blocks.filter((block) =>
+ block.some(
+ (item) =>
+ item.kind === "marker" &&
+ (item.marker === "pinned-header" || item.marker === "pinned-divider"),
+ ),
+ );
+ const sectionBlocks = blocks.filter((block) =>
+ block.some(
+ (item) =>
+ item.kind === "marker" &&
+ typeof item.marker === "object" &&
+ item.marker.kind === "section-header",
+ ),
+ );
+ const restBlocks = blocks.filter(
+ (block) => !pinnedBlocks.includes(block) && !sectionBlocks.includes(block),
+ );
+ const from = sectionBlocks.findIndex((block) =>
+ block.some(
+ (item) =>
+ item.kind === "marker" &&
+ typeof item.marker === "object" &&
+ item.marker.kind === "section-header" &&
+ item.marker.sectionId === sectionId,
+ ),
+ );
+ if (from === -1) return [];
+ const [moved] = sectionBlocks.splice(from, 1);
+ if (!moved) return [];
+ const to =
+ overSectionId === "__end__"
+ ? sectionBlocks.length
+ : sectionBlocks.findIndex((block) =>
+ block.some(
+ (item) =>
+ item.kind === "marker" &&
+ typeof item.marker === "object" &&
+ item.marker.kind === "section-header" &&
+ item.marker.sectionId === overSectionId,
+ ),
+ );
+ sectionBlocks.splice(to < 0 ? sectionBlocks.length : to, 0, moved);
+ const projected = [...pinnedBlocks.flat(), ...sectionBlocks.flat(), ...restBlocks.flat()];
+ const result = items.map(() => hidden);
+ let top = rects[0]?.top ?? 0;
+ for (const item of projected) {
+ const index = indices.get(rosterListItemId(item));
+ const rect = index === undefined ? undefined : rects[index];
+ if (index !== undefined && rect) result[index] = { ...stationary, y: top - rect.top };
+ top += (rect?.height ?? 0) + 1;
+ }
+ result[activeIndex] = stationary;
+ return result;
+ }
+
+ return (args) => {
+ if (
+ previous?.rects !== args.rects ||
+ previous.activeIndex !== args.activeIndex ||
+ previous.overIndex !== args.overIndex
+ ) {
+ previous = args;
+ transforms = project(args);
+ }
+ return transforms === null
+ ? verticalListSortingStrategy(args)
+ : (transforms[args.index] ?? stationary);
+ };
+}
+
+export function isRosterEntryDrag(id: string): boolean {
+ return parseRosterEntryId(id) !== null;
+}
diff --git a/apps/web/src/components/roster/roster.logic.test.ts b/apps/web/src/components/roster/roster.logic.test.ts
index ca8ecf358..ca007b74a 100644
--- a/apps/web/src/components/roster/roster.logic.test.ts
+++ b/apps/web/src/components/roster/roster.logic.test.ts
@@ -25,8 +25,18 @@ import {
resolveRosterShortcutBot,
parseRosterBotDragId,
parseRosterGroupDropId,
+ planRosterDrop,
+ planRosterSectionDrop,
+ moveRosterItemInOrder,
+ rosterItemsForZone,
+ buildRosterListItems,
+ resolveRosterDropTarget,
+ resolveRosterDropVerb,
rosterBotDragId,
+ rosterEntryId,
rosterGroupDropId,
+ rosterMarkerId,
+ rosterZoneHasVisibleEntries,
BLOB_COLORS,
BLOB_SHAPES,
} from "./roster.logic";
@@ -532,3 +542,143 @@ describe("parseChatPath", () => {
expect(isRecordableChatPath("/usage")).toBe(false);
});
});
+
+describe("roster drag drop planning", () => {
+ const akeru = { kind: "bot" as const, id: "akeru" };
+ const mori = { kind: "bot" as const, id: "mori" };
+ const crew = { kind: "group" as const, id: "crew" };
+
+ const items = buildRosterListItems({
+ pinnedItems: [akeru],
+ sections: [{ id: "news", name: "News", items: [crew], collapsed: false }],
+ unassignedItems: [mori],
+ });
+
+ it("builds pinned, named-section, and unassigned targets including empty placeholders", () => {
+ expect(items.map((item) => (item.kind === "marker" ? item.marker : item.item.id))).toEqual([
+ "pinned-header",
+ "akeru",
+ "pinned-divider",
+ { kind: "section-header", sectionId: "news" },
+ { kind: "section-placeholder", sectionId: "news" },
+ "crew",
+ "unassigned-header",
+ "unassigned-placeholder",
+ "mori",
+ ]);
+ });
+
+ it("pins an unassigned bot dropped on the Pins label", () => {
+ const target = resolveRosterDropTarget(
+ items,
+ rosterEntryId(mori),
+ rosterMarkerId("pinned-header"),
+ "news",
+ );
+ expect(target?.zone).toBe("pinned");
+ expect(target?.order).toEqual([mori, akeru]);
+ expect(
+ planRosterDrop({
+ activeId: rosterEntryId(mori),
+ from: "unassigned",
+ target: target!,
+ pinnedOrder: [akeru],
+ }),
+ ).toEqual({ kind: "pin", item: mori, order: [mori, akeru] });
+ expect(resolveRosterDropVerb("unassigned", "pinned")).toBe("pin");
+ });
+
+ it("unpins a bot dropped into Unassigned and keeps the named section as a move", () => {
+ const unpin = resolveRosterDropTarget(
+ items,
+ rosterEntryId(akeru),
+ rosterMarkerId("unassigned-placeholder"),
+ "news",
+ );
+ expect(unpin?.zone).toBe("unassigned");
+ expect(
+ planRosterDrop({
+ activeId: rosterEntryId(akeru),
+ from: "pinned",
+ target: unpin!,
+ pinnedOrder: [akeru],
+ }),
+ ).toEqual({
+ kind: "move",
+ item: akeru,
+ zone: "unassigned",
+ order: [akeru, mori],
+ unpin: true,
+ });
+ expect(resolveRosterDropVerb("pinned", "unassigned")).toBe("unpin");
+ expect(resolveRosterDropVerb({ sectionId: "news" }, "unassigned")).toBe("move");
+ });
+
+ it("keeps a collapsed or emptied section droppable after its last item leaves", () => {
+ const onlyCrew = buildRosterListItems({
+ pinnedItems: [],
+ sections: [{ id: "news", name: "News", items: [crew], collapsed: false }],
+ unassignedItems: [],
+ });
+ expect(rosterZoneHasVisibleEntries(onlyCrew, { sectionId: "news" }, crew)).toBe(false);
+ const target = resolveRosterDropTarget(
+ onlyCrew,
+ rosterEntryId(crew),
+ rosterMarkerId({ kind: "section-placeholder", sectionId: "news" }),
+ "news",
+ );
+ expect(target?.zone).toEqual({ sectionId: "news" });
+ expect(target?.order).toEqual([crew]);
+ });
+
+ it("reorders named sections onto Unassigned without touching group membership", () => {
+ expect(
+ planRosterSectionDrop({
+ sectionIds: ["news", "ops"],
+ activeSectionId: "news",
+ overId: rosterMarkerId("unassigned-header"),
+ }),
+ ).toEqual({ kind: "reorder-section", fromIndex: 0, toIndex: 1 });
+ });
+
+ it("does not plan a no-op pin reorder", () => {
+ const target = resolveRosterDropTarget(
+ items,
+ rosterEntryId(akeru),
+ rosterEntryId(akeru),
+ "news",
+ );
+ expect(
+ planRosterDrop({
+ activeId: rosterEntryId(akeru),
+ from: "pinned",
+ target: target!,
+ pinnedOrder: [akeru],
+ }).kind,
+ ).toBe("none");
+ expect(resolveRosterDropVerb("pinned", "pinned")).toBeNull();
+ });
+
+ it("nudges an item one slot without wrapping past the ends", () => {
+ const order = [akeru, mori, crew];
+ expect(moveRosterItemInOrder(order, mori, -1)?.map((item) => item.id)).toEqual([
+ "mori",
+ "akeru",
+ "crew",
+ ]);
+ expect(moveRosterItemInOrder(order, akeru, -1)).toBeNull();
+ expect(moveRosterItemInOrder(order, crew, 1)).toBeNull();
+ });
+
+ it("resolves the visible order for each roster zone", () => {
+ const layout = {
+ pinnedItems: [akeru],
+ sections: [{ id: "news", items: [mori] }],
+ unassignedItems: [crew],
+ };
+ expect(rosterItemsForZone("pinned", layout)).toEqual([akeru]);
+ expect(rosterItemsForZone("unassigned", layout)).toEqual([crew]);
+ expect(rosterItemsForZone({ sectionId: "news" }, layout)).toEqual([mori]);
+ expect(rosterItemsForZone({ sectionId: "missing" }, layout)).toEqual([]);
+ });
+});
diff --git a/apps/web/src/components/roster/roster.logic.ts b/apps/web/src/components/roster/roster.logic.ts
index e6556de35..0aeadebd7 100644
--- a/apps/web/src/components/roster/roster.logic.ts
+++ b/apps/web/src/components/roster/roster.logic.ts
@@ -352,6 +352,33 @@ export function filterRosterGroups(
const BOT_DRAG_PREFIX = "bot:";
const GROUP_DROP_PREFIX = "group:";
+const ROSTER_MARKER_PREFIX = "roster-marker-";
+
+export type RosterItemRef = { kind: "bot"; id: string } | { kind: "group"; id: string };
+
+export function rosterItemKey(item: RosterItemRef): string {
+ return `${item.kind}:${item.id}`;
+}
+
+export function rosterItemsEqual(left: RosterItemRef, right: RosterItemRef): boolean {
+ return left.kind === right.kind && left.id === right.id;
+}
+
+/** Shift an item by one slot in a visible zone. Null when it cannot move. */
+export function moveRosterItemInOrder(
+ order: readonly RosterItemRef[],
+ item: RosterItemRef,
+ delta: -1 | 1,
+): RosterItemRef[] | null {
+ const index = order.findIndex((candidate) => rosterItemsEqual(candidate, item));
+ const destination = index + delta;
+ if (index < 0 || destination < 0 || destination >= order.length) return null;
+ const next = [...order];
+ const [moved] = next.splice(index, 1);
+ if (!moved) return null;
+ next.splice(destination, 0, moved);
+ return next;
+}
export function rosterBotDragId(botId: string): string {
return `${BOT_DRAG_PREFIX}${botId}`;
@@ -369,6 +396,300 @@ export function parseRosterGroupDropId(id: string): string | null {
return id.startsWith(GROUP_DROP_PREFIX) ? id.slice(GROUP_DROP_PREFIX.length) || null : null;
}
+export function rosterEntryId(item: RosterItemRef): string {
+ return item.kind === "bot" ? rosterBotDragId(item.id) : rosterGroupDropId(item.id);
+}
+
+export function parseRosterEntryId(id: string): RosterItemRef | null {
+ const botId = parseRosterBotDragId(id);
+ if (botId) return { kind: "bot", id: botId };
+ const groupId = parseRosterGroupDropId(id);
+ if (groupId) return { kind: "group", id: groupId };
+ return null;
+}
+
+/** Reconstruct mixed section order from the persisted group-then-bot arrays. */
+export function rosterSectionItems(section: {
+ readonly botIds: readonly string[];
+ readonly groupIds?: readonly string[];
+ readonly items?: readonly RosterItemRef[] | undefined;
+}): RosterItemRef[] {
+ if (section.items && section.items.length > 0) return [...section.items];
+ return [
+ ...(section.groupIds ?? []).map((id) => ({ kind: "group" as const, id })),
+ ...section.botIds.map((id) => ({ kind: "bot" as const, id })),
+ ];
+}
+
+export function splitRosterSectionItems(items: readonly RosterItemRef[]): {
+ botIds: string[];
+ groupIds: string[];
+} {
+ return {
+ botIds: items.filter((item) => item.kind === "bot").map((item) => item.id),
+ groupIds: items.filter((item) => item.kind === "group").map((item) => item.id),
+ };
+}
+
+export type RosterZone = "pinned" | "unassigned" | { readonly sectionId: string };
+
+export function rosterItemsForZone(
+ zone: RosterZone,
+ layout: {
+ readonly pinnedItems: readonly RosterItemRef[];
+ readonly sections: readonly { readonly id: string; readonly items: readonly RosterItemRef[] }[];
+ readonly unassignedItems: readonly RosterItemRef[];
+ },
+): readonly RosterItemRef[] {
+ if (zone === "pinned") return layout.pinnedItems;
+ if (zone === "unassigned") return layout.unassignedItems;
+ return layout.sections.find((section) => section.id === zone.sectionId)?.items ?? [];
+}
+
+export function rosterZoneId(zone: RosterZone): string {
+ return zone === "pinned" || zone === "unassigned" ? zone : zone.sectionId;
+}
+
+export function rosterZonesEqual(left: RosterZone, right: RosterZone): boolean {
+ if (left === "pinned" || left === "unassigned") return left === right;
+ return typeof right === "object" && left.sectionId === right.sectionId;
+}
+
+export type RosterListMarker =
+ | "pinned-header"
+ | "pinned-divider"
+ | "unassigned-header"
+ | "unassigned-placeholder"
+ | { readonly kind: "section-header"; readonly sectionId: string }
+ | { readonly kind: "section-placeholder"; readonly sectionId: string };
+
+export function rosterMarkerId(marker: RosterListMarker): string {
+ if (typeof marker === "string") return `${ROSTER_MARKER_PREFIX}${marker}`;
+ return `${ROSTER_MARKER_PREFIX}${marker.kind}-${marker.sectionId}`;
+}
+
+export function parseRosterSectionHeaderId(id: string): string | null {
+ const prefix = `${ROSTER_MARKER_PREFIX}section-header-`;
+ return id.startsWith(prefix) ? id.slice(prefix.length) || null : null;
+}
+
+export type RosterListItem =
+ | { readonly kind: "entry"; readonly item: RosterItemRef; readonly zone: RosterZone }
+ | { readonly kind: "marker"; readonly marker: RosterListMarker };
+
+export function rosterListItemId(item: RosterListItem): string {
+ return item.kind === "entry" ? rosterEntryId(item.item) : rosterMarkerId(item.marker);
+}
+
+export type RosterLayoutSection = {
+ readonly id: string;
+ readonly name: string;
+ readonly items: readonly RosterItemRef[];
+ readonly collapsed: boolean;
+};
+
+export function buildRosterListItems(input: {
+ readonly pinnedItems: readonly RosterItemRef[];
+ readonly sections: readonly RosterLayoutSection[];
+ readonly unassignedItems: readonly RosterItemRef[];
+}): RosterListItem[] {
+ const items: RosterListItem[] = [{ kind: "marker", marker: "pinned-header" }];
+ for (const item of input.pinnedItems) {
+ items.push({ kind: "entry", item, zone: "pinned" });
+ }
+ items.push({ kind: "marker", marker: "pinned-divider" });
+ for (const section of input.sections) {
+ const zone = { sectionId: section.id };
+ items.push({ kind: "marker", marker: { kind: "section-header", sectionId: section.id } });
+ items.push({ kind: "marker", marker: { kind: "section-placeholder", sectionId: section.id } });
+ if (!section.collapsed) {
+ for (const item of section.items) {
+ items.push({ kind: "entry", item, zone });
+ }
+ }
+ }
+ items.push({ kind: "marker", marker: "unassigned-header" });
+ items.push({ kind: "marker", marker: "unassigned-placeholder" });
+ for (const item of input.unassignedItems) {
+ items.push({ kind: "entry", item, zone: "unassigned" });
+ }
+ return items;
+}
+
+function markerZone(marker: RosterListMarker, firstSectionId: string | null): RosterZone | null {
+ if (marker === "pinned-header") return "pinned";
+ if (marker === "pinned-divider")
+ return firstSectionId ? { sectionId: firstSectionId } : "unassigned";
+ if (marker === "unassigned-header" || marker === "unassigned-placeholder") return "unassigned";
+ return { sectionId: marker.sectionId };
+}
+
+function zoneAtRosterSlot(
+ items: readonly RosterListItem[],
+ index: number,
+ firstSectionId: string | null,
+): RosterZone {
+ let zone: RosterZone = "pinned";
+ for (let i = 0; i < index && i < items.length; i += 1) {
+ const item = items[i]!;
+ if (item.kind !== "marker") continue;
+ const next = markerZone(item.marker, firstSectionId);
+ if (next) zone = next;
+ if (typeof item.marker !== "string" && item.marker.kind === "section-header") {
+ zone = { sectionId: item.marker.sectionId };
+ }
+ if (item.marker === "unassigned-header") zone = "unassigned";
+ if (item.marker === "pinned-divider") {
+ zone = firstSectionId ? { sectionId: firstSectionId } : "unassigned";
+ }
+ }
+ return zone;
+}
+
+function zoneForOverItem(
+ over: RosterListItem,
+ moved: readonly RosterListItem[],
+ overIndex: number,
+ firstSectionId: string | null,
+): RosterZone {
+ if (over.kind === "entry") return over.zone;
+ if (over.marker === "pinned-header") return "pinned";
+ if (over.marker === "unassigned-header" || over.marker === "unassigned-placeholder") {
+ return "unassigned";
+ }
+ if (typeof over.marker !== "string") return { sectionId: over.marker.sectionId };
+ return zoneAtRosterSlot(moved, overIndex, firstSectionId);
+}
+
+export type RosterDropTarget = {
+ readonly zone: RosterZone;
+ readonly order: readonly RosterItemRef[];
+};
+
+function collectZoneOrder(items: readonly RosterListItem[], zone: RosterZone): RosterItemRef[] {
+ return items.flatMap((item) =>
+ item.kind === "entry" && rosterZonesEqual(item.zone, zone) ? [item.item] : [],
+ );
+}
+
+export function resolveRosterDropTarget(
+ items: readonly RosterListItem[],
+ activeId: string,
+ overId: string,
+ firstSectionId: string | null,
+): RosterDropTarget | null {
+ const activeIndex = items.findIndex((item) => rosterListItemId(item) === activeId);
+ const overIndex = items.findIndex((item) => rosterListItemId(item) === overId);
+ const active = activeIndex === -1 ? undefined : items[activeIndex];
+ const over = overIndex === -1 ? undefined : items[overIndex];
+ if (!active || !over || active.kind !== "entry") return null;
+ const moved = items.filter((_, index) => index !== activeIndex);
+ moved.splice(overIndex, 0, active);
+ const zone = zoneForOverItem(over, moved, overIndex, firstSectionId);
+ return {
+ zone,
+ order: collectZoneOrder(
+ moved.map((item) =>
+ item.kind === "entry" && rosterItemsEqual(item.item, active.item)
+ ? { ...item, zone }
+ : item,
+ ),
+ zone,
+ ),
+ };
+}
+
+export type RosterDropVerb = "pin" | "unpin" | "move";
+
+export function resolveRosterDropVerb(
+ from: RosterZone,
+ to: RosterZone | null,
+): RosterDropVerb | null {
+ if (to === null || rosterZonesEqual(from, to)) return null;
+ if (to === "pinned") return "pin";
+ if (from === "pinned") return "unpin";
+ return "move";
+}
+
+export type RosterDropPlan =
+ | { readonly kind: "none" }
+ | { readonly kind: "reorder-pinned"; readonly order: readonly RosterItemRef[] }
+ | { readonly kind: "pin"; readonly item: RosterItemRef; readonly order: readonly RosterItemRef[] }
+ | {
+ readonly kind: "move";
+ readonly item: RosterItemRef;
+ readonly zone: Exclude<RosterZone, "pinned">;
+ readonly order: readonly RosterItemRef[];
+ readonly unpin: boolean;
+ }
+ | { readonly kind: "reorder-section"; readonly fromIndex: number; readonly toIndex: number };
+
+function sameOrder(left: readonly RosterItemRef[], right: readonly RosterItemRef[]): boolean {
+ return (
+ left.length === right.length &&
+ left.every((item, index) => rosterItemsEqual(item, right[index]!))
+ );
+}
+
+export function planRosterDrop(input: {
+ readonly activeId: string;
+ readonly from: RosterZone;
+ readonly target: RosterDropTarget;
+ readonly pinnedOrder: readonly RosterItemRef[];
+}): RosterDropPlan {
+ const item = parseRosterEntryId(input.activeId);
+ if (!item) return { kind: "none" };
+ if (input.target.zone === "pinned") {
+ if (input.from === "pinned" && sameOrder(input.target.order, input.pinnedOrder)) {
+ return { kind: "none" };
+ }
+ if (input.from === "pinned") {
+ return { kind: "reorder-pinned", order: input.target.order };
+ }
+ return { kind: "pin", item, order: input.target.order };
+ }
+ return {
+ kind: "move",
+ item,
+ zone: input.target.zone,
+ order: input.target.order,
+ unpin: input.from === "pinned",
+ };
+}
+
+export function planRosterSectionDrop(input: {
+ readonly sectionIds: readonly string[];
+ readonly activeSectionId: string;
+ readonly overId: string;
+}): RosterDropPlan {
+ const fromIndex = input.sectionIds.indexOf(input.activeSectionId);
+ if (fromIndex === -1) return { kind: "none" };
+ const overSectionId = parseRosterSectionHeaderId(input.overId);
+ let toIndex: number;
+ if (overSectionId) {
+ toIndex = input.sectionIds.indexOf(overSectionId);
+ } else if (input.overId === rosterMarkerId("unassigned-header")) {
+ toIndex = input.sectionIds.length - 1;
+ } else {
+ return { kind: "none" };
+ }
+ if (toIndex === -1 || toIndex === fromIndex) return { kind: "none" };
+ return { kind: "reorder-section", fromIndex, toIndex };
+}
+
+export function rosterZoneHasVisibleEntries(
+ items: readonly RosterListItem[],
+ zone: RosterZone,
+ except?: RosterItemRef,
+): boolean {
+ return items.some(
+ (item) =>
+ item.kind === "entry" &&
+ rosterZonesEqual(item.zone, zone) &&
+ (except === undefined || !rosterItemsEqual(item.item, except)),
+ );
+}
+
/**
* Assigned groups first, then every bot without a group under Unassigned.
* A matching group keeps every member so stacked avatars stay visible.
diff --git a/apps/web/src/components/roster/roster.motion.test.ts b/apps/web/src/components/roster/roster.motion.test.ts
new file mode 100644
index 000000000..9cb1220d0
--- /dev/null
+++ b/apps/web/src/components/roster/roster.motion.test.ts
@@ -0,0 +1,156 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { createRosterListMotion } from "./roster.motion";
+
+class TestAnimation {
+ progress: number | null = 0;
+ playState: AnimationPlayState = "running";
+ effect = { getComputedTiming: () => ({ progress: this.progress }) };
+ cancel = vi.fn(() => {
+ this.playState = "idle";
+ });
+ private onFinish: (() => void) | undefined;
+ addEventListener(_type: string, listener: () => void) {
+ this.onFinish = listener;
+ }
+ finish() {
+ this.playState = "finished";
+ this.onFinish?.();
+ }
+}
+
+class TestRow {
+ offsetTop = 0;
+ offsetLeft = 4;
+ offsetWidth = 260;
+ namespaceURI = "http://www.w3.org/1999/xhtml";
+ dragTranslate = 0;
+ style: Record<string, string> = {};
+ inert = false;
+ attributes: { name: string; value: string }[] = [];
+ children: TestRow[] = [];
+ clones: TestRow[] = [];
+ remove = vi.fn();
+ animations: TestAnimation[] = [];
+ constructor(
+ readonly name: string,
+ public offsetHeight = 82,
+ ) {}
+ getBoundingClientRect() {
+ return { top: this.offsetTop + this.dragTranslate, height: this.offsetHeight };
+ }
+ setAttribute(name: string, value: string) {
+ this.removeAttribute(name);
+ this.attributes.push({ name, value });
+ }
+ removeAttribute(name: string) {
+ this.attributes = this.attributes.filter((attribute) => attribute.name !== name);
+ }
+ querySelectorAll(_selector: string): TestRow[] {
+ return this.children.flatMap((child) => [child, ...child.querySelectorAll("*")]);
+ }
+ cloneNode(_deep: boolean): TestRow {
+ const clone = new TestRow(`${this.name} clone`, this.offsetHeight);
+ clone.namespaceURI = this.namespaceURI;
+ clone.style = { ...this.style };
+ clone.attributes = this.attributes.map((attribute) => ({ ...attribute }));
+ clone.children = this.children.map((child) => child.cloneNode(true));
+ this.clones.push(clone);
+ return clone;
+ }
+ animate = vi.fn((_frames: Keyframe[], _options: KeyframeAnimationOptions) => {
+ const animation = new TestAnimation();
+ this.animations.push(animation);
+ return animation;
+ });
+}
+
+function fixture(rows: TestRow[]) {
+ const media = { matches: false };
+ const parent = {
+ children: rows,
+ ownerDocument: { defaultView: { matchMedia: () => media } },
+ getBoundingClientRect: () => ({ top: 0 }),
+ append(node: TestRow) {
+ parent.children.push(node);
+ node.remove.mockImplementation(() => {
+ parent.children = parent.children.filter((child) => child !== node);
+ });
+ },
+ };
+ function layout(next: TestRow[]) {
+ let top = 8;
+ for (const row of next) {
+ row.offsetTop = top;
+ top += row.offsetHeight + 1;
+ }
+ parent.children = [
+ ...next,
+ ...parent.children.filter((row) => row.style.position === "absolute"),
+ ];
+ }
+ layout(rows);
+ const motion = createRosterListMotion(parent as unknown as HTMLUListElement);
+ return { motion, layout, media, parent };
+}
+
+function expectMove(row: TestRow, offset: number) {
+ expect(row.animate).toHaveBeenLastCalledWith(
+ [{ transform: `translateY(${offset}px)` }, { transform: "translateY(0px)" }],
+ { duration: 150, easing: "ease-out" },
+ );
+}
+
+beforeEach(() => vi.stubGlobal("HTMLElement", TestRow));
+afterEach(() => vi.unstubAllGlobals());
+
+describe("roster list motion", () => {
+ it("glides every row from its released position into its committed slot", () => {
+ const [a, b, c] = [new TestRow("a"), new TestRow("b"), new TestRow("c")];
+ const { motion, layout } = fixture([a, b, c]);
+ motion.update(true);
+ motion.suspend();
+ a.dragTranslate = 130;
+ b.dragTranslate = -83;
+ c.dragTranslate = 16;
+ motion.update(false);
+ motion.release();
+ layout([b, a, c]);
+ a.dragTranslate = b.dragTranslate = c.dragTranslate = 0;
+ motion.update(true);
+ expectMove(a, 47);
+ expect(b.animations).toHaveLength(0);
+ expectMove(c, 16);
+ });
+
+ it("does not glide on release when motion is reduced", () => {
+ const [a, b] = [new TestRow("a"), new TestRow("b")];
+ const { motion, layout, media } = fixture([a, b]);
+ motion.update(true);
+ media.matches = true;
+ a.dragTranslate = 100;
+ motion.release();
+ layout([b, a]);
+ a.dragTranslate = 0;
+ motion.update(true);
+ expect(a.animations).toHaveLength(0);
+ expect(b.animations).toHaveLength(0);
+ });
+
+ it("does not replay sortable transforms after a cancelled drag", () => {
+ const a = new TestRow("a");
+ const b = new TestRow("b");
+ const { motion, layout } = fixture([a, b]);
+ motion.update(true);
+ motion.suspend();
+ a.dragTranslate = 200;
+ b.dragTranslate = -83;
+ motion.update(false);
+ motion.suspend();
+ a.dragTranslate = b.dragTranslate = 0;
+ layout([b, a]);
+ motion.update(true);
+ expect(a.animations).toHaveLength(0);
+ expect(b.animations).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/components/roster/roster.motion.ts b/apps/web/src/components/roster/roster.motion.ts
new file mode 100644
index 000000000..db1c2fbe6
--- /dev/null
+++ b/apps/web/src/components/roster/roster.motion.ts
@@ -0,0 +1,214 @@
+const motionTiming = { duration: 150, easing: "ease-out" };
+// A section collapse or pin change swaps several rows at once. Fades are the
+// expensive part: every removed row gets a deep clone and every clone and
+// entering row gets its own animation, and the layout reads in between force
+// synchronous reflows. Translating displaced rows is cheap, so only the fade
+// count decides whether an update animates.
+const MAX_FADED_ROWS_PER_UPDATE = 40;
+
+type RowPosition = { top: number; left: number; width: number; height: number };
+
+function progress(animation: Animation) {
+ return animation.playState === "finished"
+ ? 1
+ : (animation.effect?.getComputedTiming().progress ?? 0);
+}
+
+/** Animate rows between their layout positions. The list must be
+ * positioned so every direct child's offsetTop has the same origin. */
+export function createRosterListMotion(parent: HTMLUListElement) {
+ let positions: Map<HTMLElement, RowPosition> | null = null;
+ let disposed = false;
+ const reducedMotion = parent.ownerDocument.defaultView?.matchMedia(
+ "(prefers-reduced-motion: reduce)",
+ );
+ const running = new Map<HTMLElement, { animation: Animation; offset: number }>();
+ const entering = new Map<HTMLElement, Animation>();
+ const exiting = new Map<HTMLElement, Animation>();
+ // Visual tops at drag release, relative to the list, so the release
+ // commit can glide every row from where dnd-kit left it into its slot.
+ let released: Map<HTMLElement, number> | null = null;
+
+ const remainingOffset = (node: HTMLElement) => {
+ const current = running.get(node);
+ return current ? current.offset * (1 - progress(current.animation)) : 0;
+ };
+ const clearFades = () => {
+ for (const animation of [...entering.values(), ...exiting.values()]) animation.cancel();
+ for (const node of exiting.keys()) node.remove();
+ entering.clear();
+ exiting.clear();
+ };
+ const fadeOut = (node: HTMLElement, position: RowPosition) => {
+ if (position.height === 0) return;
+ // React owns the removed row; only a noninteractive copy stays for the fade.
+ const clone = node.cloneNode(true) as HTMLElement;
+ for (const element of [clone, ...clone.querySelectorAll("*")]) {
+ for (const attribute of Array.from(element.attributes)) {
+ if (
+ (attribute.name === "id" && element.namespaceURI !== "http://www.w3.org/2000/svg") ||
+ attribute.name === "data-roster-item" ||
+ attribute.name === "data-testid"
+ ) {
+ element.removeAttribute(attribute.name);
+ }
+ }
+ }
+ clone.setAttribute("aria-hidden", "true");
+ clone.inert = true;
+ Object.assign(clone.style, {
+ position: "absolute",
+ top: `${position.top + remainingOffset(node)}px`,
+ left: `${position.left}px`,
+ width: `${position.width}px`,
+ height: `${position.height}px`,
+ margin: "0",
+ boxSizing: "border-box",
+ contentVisibility: "visible",
+ transform: "none",
+ transition: "none",
+ pointerEvents: "none",
+ });
+ parent.append(clone);
+ const entry = entering.get(node);
+ const animation = clone.animate(
+ [{ opacity: entry ? progress(entry) : 1 }, { opacity: 0 }],
+ motionTiming,
+ );
+ exiting.set(clone, animation);
+ animation.addEventListener(
+ "finish",
+ () => {
+ clone.remove();
+ exiting.delete(clone);
+ },
+ { once: true },
+ );
+ };
+
+ const cancel = (node: HTMLElement) => {
+ running.get(node)?.animation.cancel();
+ running.delete(node);
+ };
+ const suspend = () => {
+ for (const node of running.keys()) cancel(node);
+ clearFades();
+ positions = null;
+ released = null;
+ };
+ const move = (node: HTMLElement, offset: number) => {
+ cancel(node);
+ if (offset === 0) return;
+ const animation = node.animate(
+ [{ transform: `translateY(${offset}px)` }, { transform: "translateY(0px)" }],
+ motionTiming,
+ );
+ running.set(node, { animation, offset });
+ animation.addEventListener(
+ "finish",
+ () => {
+ if (running.get(node)?.animation === animation) running.delete(node);
+ },
+ { once: true },
+ );
+ };
+
+ return {
+ update(animate: boolean) {
+ if (disposed) return;
+ const next = new Map(
+ Array.from(parent.children)
+ .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node))
+ .map((node) => [
+ node,
+ {
+ top: node.offsetTop,
+ left: node.offsetLeft,
+ width: node.offsetWidth,
+ height: node.offsetHeight,
+ },
+ ]),
+ );
+ let fadeCount = 0;
+ if (positions !== null) {
+ for (const [node, position] of positions) {
+ if (!next.has(node) && position.height > 0) fadeCount++;
+ }
+ for (const [node, position] of next) {
+ if (!positions.has(node) && position.height > 0) fadeCount++;
+ }
+ }
+ const shouldAnimate =
+ animate &&
+ positions !== null &&
+ !reducedMotion?.matches &&
+ fadeCount <= MAX_FADED_ROWS_PER_UPDATE;
+ if (!shouldAnimate) clearFades();
+ else {
+ for (const [node, position] of positions!) {
+ if (!next.has(node)) fadeOut(node, position);
+ }
+ }
+ for (const [node, animation] of entering) {
+ if (!next.has(node)) {
+ animation.cancel();
+ entering.delete(node);
+ }
+ }
+ for (const node of running.keys()) {
+ if (!shouldAnimate || !next.has(node)) cancel(node);
+ }
+ if (shouldAnimate) {
+ for (const [node, position] of next) {
+ const previousTop = positions?.get(node)?.top;
+ if (previousTop === undefined) {
+ if (position.height > 0) {
+ const animation = node.animate([{ opacity: 0 }, { opacity: 1 }], motionTiming);
+ entering.set(node, animation);
+ animation.addEventListener(
+ "finish",
+ () => {
+ if (entering.get(node) === animation) entering.delete(node);
+ },
+ { once: true },
+ );
+ }
+ continue;
+ }
+ if (previousTop === position.top) continue;
+ // Computed progress includes the effect's easing. Only our own
+ // translate is carried forward; dnd-kit's transforms are never read.
+ move(node, previousTop + remainingOffset(node) - position.top);
+ }
+ }
+ if (released !== null) {
+ if (!reducedMotion?.matches) {
+ for (const [node, position] of next) {
+ const top = released.get(node);
+ if (top !== undefined) move(node, top - position.top);
+ }
+ }
+ released = null;
+ }
+ positions = next;
+ },
+ /** Called on drag release, before the commit that clears dnd-kit's
+ * transforms. Takes every row's visual top, including the lifted row
+ * under the pointer and the peers holding the label gaps open, so the
+ * next update glides each of them into its committed slot. */
+ release() {
+ suspend();
+ const origin = parent.getBoundingClientRect().top;
+ released = new Map(
+ Array.from(parent.children)
+ .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node))
+ .map((node) => [node, node.getBoundingClientRect().top - origin]),
+ );
+ },
+ suspend,
+ dispose() {
+ suspend();
+ disposed = true;
+ },
+ };
+}
diff --git a/apps/web/src/components/roster/roster.pointer.test.ts b/apps/web/src/components/roster/roster.pointer.test.ts
new file mode 100644
index 000000000..1f877e46b
--- /dev/null
+++ b/apps/web/src/components/roster/roster.pointer.test.ts
@@ -0,0 +1,173 @@
+import type { SensorProps } from "@dnd-kit/core";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { RosterPointerSensor } from "./roster.pointer";
+
+class TestDocument extends EventTarget {
+ hidden = false;
+ getSelection = () => ({ removeAllRanges() {} });
+}
+
+let document: TestDocument;
+let window: EventTarget;
+const sensors: RosterPointerSensor[] = [];
+
+function pointer(type: string, values: Partial<PointerEvent> = {}) {
+ return Object.assign(new Event(type, { cancelable: true }), {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 10,
+ buttons: 1,
+ ...values,
+ });
+}
+
+function gesture() {
+ const callbacks = {
+ onStart: vi.fn(),
+ onMove: vi.fn(),
+ onEnd: vi.fn(),
+ onCancel: vi.fn(),
+ onAbort: vi.fn(),
+ onPending: vi.fn(),
+ };
+ const onFinish = vi.fn();
+ const props = {
+ active: "bot:akeru",
+ event: pointer("pointerdown"),
+ options: { distance: 6, onAttach: vi.fn(), onFinish },
+ ...callbacks,
+ } as unknown as SensorProps<ConstructorParameters<typeof RosterPointerSensor>[0]["options"]>;
+ const sensor = new RosterPointerSensor(props);
+ sensors.push(sensor);
+ return { sensor, onFinish, ...callbacks };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ document = new TestDocument();
+ window = Object.assign(new EventTarget(), { setTimeout });
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", window);
+});
+afterEach(() => {
+ for (const sensor of sensors.splice(0)) sensor.cancel();
+ vi.runAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("roster pointer lifecycle", () => {
+ it("keeps a click idle and starts only after the drag threshold", () => {
+ const click = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 16 }));
+ expect(click.onStart).not.toHaveBeenCalled();
+ document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
+ expect(click.onAbort).toHaveBeenCalledOnce();
+ expect(click.onFinish).toHaveBeenCalledOnce();
+
+ const drag = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 17 }));
+ expect(drag.onStart).toHaveBeenCalledExactlyOnceWith({ x: 10, y: 10 });
+ document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
+ expect(drag.onEnd).toHaveBeenCalledOnce();
+ expect(drag.onAbort).not.toHaveBeenCalled();
+ expect(drag.onFinish).toHaveBeenCalledOnce();
+ });
+
+ const interruptions = {
+ blur: () => window.dispatchEvent(new Event("blur")),
+ hidden: () => {
+ document.hidden = true;
+ document.dispatchEvent(new Event("visibilitychange"));
+ },
+ pagehide: () => window.dispatchEvent(new Event("pagehide")),
+ resize: () => window.dispatchEvent(new Event("resize")),
+ escape: () => document.dispatchEvent(Object.assign(new Event("keydown"), { code: "Escape" })),
+ pointercancel: () => document.dispatchEvent(pointer("pointercancel")),
+ "missed release": () =>
+ document.dispatchEvent(pointer("pointermove", { buttons: 0, clientY: 100 })),
+ };
+ for (const [name, interrupt] of Object.entries(interruptions)) {
+ it.each([false, true])(`cancels on ${name}, started=%s, and ignores late events`, (started) => {
+ const drag = gesture();
+ if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ interrupt();
+ document.dispatchEvent(pointer("pointermove", { clientY: 100 }));
+ document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
+ drag.sensor.cancel();
+ expect(drag.onCancel).toHaveBeenCalledOnce();
+ expect(drag.onEnd).not.toHaveBeenCalled();
+ expect(drag.onFinish).toHaveBeenCalledOnce();
+ expect(drag.onStart).toHaveBeenCalledTimes(started ? 1 : 0);
+ expect(drag.onAbort).toHaveBeenCalledTimes(started ? 0 : 1);
+
+ document.hidden = false;
+ const next = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
+ expect(next.onStart).toHaveBeenCalledOnce();
+ expect(next.onEnd).toHaveBeenCalledOnce();
+ });
+ }
+
+ it("suppresses a delayed release click after cancellation, then accepts the next click", () => {
+ const drag = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ drag.sensor.cancel();
+ vi.advanceTimersByTime(1000);
+ const releaseClick = new Event("click");
+ const releasePropagation = vi.spyOn(releaseClick, "stopPropagation");
+ document.dispatchEvent(releaseClick);
+ expect(releasePropagation).toHaveBeenCalledOnce();
+ document.dispatchEvent(pointer("pointerdown"));
+ const nextClick = new Event("click");
+ const nextPropagation = vi.spyOn(nextClick, "stopPropagation");
+ document.dispatchEvent(nextClick);
+ expect(nextPropagation).not.toHaveBeenCalled();
+ });
+
+ it("does not suppress a keyboard click after a cancelled drag", () => {
+ const drag = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ drag.sensor.cancel();
+ const keyboardClick = Object.assign(new Event("click"), { detail: 0 });
+ const keyboardPropagation = vi.spyOn(keyboardClick, "stopPropagation");
+ document.dispatchEvent(keyboardClick);
+ expect(keyboardPropagation).not.toHaveBeenCalled();
+ });
+
+ it("clears click suppression on the next keydown after a cancelled drag", () => {
+ const drag = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ drag.sensor.cancel();
+ document.dispatchEvent(Object.assign(new Event("keydown"), { code: "Enter" }));
+ const click = Object.assign(new Event("click"), { detail: 1 });
+ const propagation = vi.spyOn(click, "stopPropagation");
+ document.dispatchEvent(click);
+ expect(propagation).not.toHaveBeenCalled();
+ });
+
+ it("allows the next click when the cancelled release happened outside the document", () => {
+ const drag = gesture();
+ document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ drag.sensor.cancel();
+ document.dispatchEvent(pointer("pointerdown"));
+ const click = new Event("click");
+ const propagation = vi.spyOn(click, "stopPropagation");
+ document.dispatchEvent(click);
+ expect(propagation).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])("cancels when the list unmounts, started=%s", (started) => {
+ const drag = gesture();
+ if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));
+ drag.sensor.cancel();
+ document.dispatchEvent(pointer("pointermove", { clientY: 100 }));
+ document.dispatchEvent(pointer("pointerup", { buttons: 0 }));
+ expect(drag.onStart).toHaveBeenCalledTimes(started ? 1 : 0);
+ expect(drag.onCancel).toHaveBeenCalledOnce();
+ expect(drag.onEnd).not.toHaveBeenCalled();
+ expect(drag.onFinish).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/components/roster/roster.pointer.ts b/apps/web/src/components/roster/roster.pointer.ts
new file mode 100644
index 000000000..f7c015b1a
--- /dev/null
+++ b/apps/web/src/components/roster/roster.pointer.ts
@@ -0,0 +1,151 @@
+import { useLayoutEffect, type PointerEvent as ReactPointerEvent } from "react";
+import { type SensorProps } from "@dnd-kit/core";
+import { getOwnerDocument, getWindow } from "@dnd-kit/utilities";
+
+// Search unmounts the drag context while its owning sidebar remains mounted.
+export function RosterDragLifecycle({ onUnmount }: { onUnmount: () => void }) {
+ useLayoutEffect(() => onUnmount, [onUnmount]);
+ return null;
+}
+
+type Options = {
+ distance: number;
+ onAttach: (sensor: RosterPointerSensor) => void;
+ onFinish: (started: boolean) => void;
+};
+
+/** A roster gesture ends on release, cancellation, or loss of its window.
+ * Own the listeners so unmounting the list can cancel the sensor too. */
+export class RosterPointerSensor {
+ static activators = [
+ {
+ eventName: "onPointerDown" as const,
+ handler: ({ nativeEvent }: ReactPointerEvent) =>
+ nativeEvent.isPrimary && nativeEvent.button === 0,
+ },
+ ];
+ autoScrollEnabled = true;
+ private phase: "pending" | "dragging" | "finished" = "pending";
+ private readonly pointer: PointerEvent;
+ private readonly document: Document;
+ private readonly window: Window;
+
+ constructor(private readonly props: SensorProps<Options>) {
+ this.pointer = props.event as PointerEvent;
+ this.document = getOwnerDocument(this.pointer.target);
+ this.window = getWindow(this.pointer.target);
+ this.document.addEventListener("pointermove", this.move, { passive: false, capture: true });
+ this.document.addEventListener("pointerup", this.end, { capture: true });
+ this.document.addEventListener("pointercancel", this.pointerCancel, { capture: true });
+ this.document.addEventListener("keydown", this.keydown, { capture: true });
+ this.document.addEventListener("visibilitychange", this.visibilityChange);
+ this.window.addEventListener("blur", this.cancel);
+ this.window.addEventListener("pagehide", this.cancel);
+ this.window.addEventListener("resize", this.cancel);
+ this.document.addEventListener("dragstart", this.preventDefault);
+ this.document.addEventListener("contextmenu", this.preventDefault);
+ props.options.onAttach(this);
+ props.onPending(props.active, { distance: props.options.distance }, this.coordinates());
+ }
+
+ private coordinates = () => ({ x: this.pointer.clientX, y: this.pointer.clientY });
+ private preventDefault = (event: Event) => event.preventDefault();
+ private clearClickSuppression = () => {
+ this.document.removeEventListener("click", this.suppressClick, { capture: true });
+ this.document.removeEventListener("pointerdown", this.clearClickSuppression, { capture: true });
+ this.document.removeEventListener("keydown", this.clearClickSuppression, { capture: true });
+ };
+ private suppressClick = (event: Event) => {
+ // Keyboard-generated clicks report detail 0. Do not consume those; they
+ // are a later activation, not the pointer release from this gesture.
+ if ("detail" in event && (event as MouseEvent).detail === 0) {
+ this.clearClickSuppression();
+ return;
+ }
+ event.stopPropagation();
+ this.clearClickSuppression();
+ };
+ private clearSelection = () => this.document.getSelection()?.removeAllRanges();
+
+ private move = (event: PointerEvent) => {
+ if (this.phase === "finished" || event.pointerId !== this.pointer.pointerId) return;
+ // A release outside the window can be missed. Never activate or continue
+ // a drag when the initiating button is no longer held.
+ if ((event.buttons & 1) === 0) return this.cancel();
+ const coordinates = { x: event.clientX, y: event.clientY };
+ if (this.phase === "pending") {
+ const offset = {
+ x: event.clientX - this.pointer.clientX,
+ y: event.clientY - this.pointer.clientY,
+ };
+ if (Math.hypot(offset.x, offset.y) <= this.props.options.distance) {
+ this.props.onPending(
+ this.props.active,
+ { distance: this.props.options.distance },
+ this.coordinates(),
+ offset,
+ );
+ return;
+ }
+ this.phase = "dragging";
+ this.document.addEventListener("click", this.suppressClick, { capture: true });
+ this.document.addEventListener("selectionchange", this.clearSelection);
+ this.clearSelection();
+ this.props.onStart(this.coordinates());
+ return;
+ }
+ if (this.phase === "dragging") {
+ if (event.cancelable) event.preventDefault();
+ this.props.onMove(coordinates);
+ }
+ };
+
+ private end = (event: PointerEvent) => {
+ if (event.pointerId === this.pointer.pointerId) this.finish(false);
+ };
+ private pointerCancel = (event: PointerEvent) => {
+ if (event.pointerId === this.pointer.pointerId) this.cancel();
+ };
+ private keydown = (event: KeyboardEvent) => {
+ if (event.code === "Escape") this.cancel();
+ };
+ private visibilityChange = () => {
+ if (this.document.hidden) this.cancel();
+ };
+ cancel = () => this.finish(true);
+
+ private finish(cancelled: boolean) {
+ if (this.phase === "finished") return;
+ const aborted = this.phase === "pending";
+ this.phase = "finished";
+ this.document.removeEventListener("pointermove", this.move, { capture: true });
+ this.document.removeEventListener("pointerup", this.end, { capture: true });
+ this.document.removeEventListener("pointercancel", this.pointerCancel, { capture: true });
+ this.document.removeEventListener("keydown", this.keydown, { capture: true });
+ this.document.removeEventListener("visibilitychange", this.visibilityChange);
+ this.window.removeEventListener("blur", this.cancel);
+ this.window.removeEventListener("pagehide", this.cancel);
+ this.window.removeEventListener("resize", this.cancel);
+ this.document.removeEventListener("dragstart", this.preventDefault);
+ this.document.removeEventListener("contextmenu", this.preventDefault);
+ this.document.removeEventListener("selectionchange", this.clearSelection);
+ // Cancellation can precede release by an arbitrary amount of time. Consume
+ // that release click, or let a fresh pointerdown end suppression if release
+ // happened outside the document. Ordinary clicks never install this guard.
+ if (!aborted) {
+ this.document.addEventListener("pointerdown", this.clearClickSuppression, { capture: true });
+ // Blur/hide/resize can cancel without a release click. A following
+ // keyboard activation must not inherit that capture-phase suppressor.
+ this.document.addEventListener("keydown", this.clearClickSuppression, { capture: true });
+ }
+ try {
+ // Release the roster preview before dnd-kit clears its transforms.
+ // Its public end/cancel event can be omitted before its first layout.
+ this.props.options.onFinish(!aborted);
+ } finally {
+ if (aborted) this.props.onAbort(this.props.active);
+ if (cancelled) this.props.onCancel();
+ else this.props.onEnd();
+ }
+ }
+}
diff --git a/apps/web/src/components/roster/rosterStore.test.ts b/apps/web/src/components/roster/rosterStore.test.ts
index 6690622c0..c4306d3f0 100644
--- a/apps/web/src/components/roster/rosterStore.test.ts
+++ b/apps/web/src/components/roster/rosterStore.test.ts
@@ -47,6 +47,7 @@ beforeEach(() => {
chatPathByBotId: {},
sections: [],
pinnedItems: [],
+ unassignedItems: [],
environmentId: null,
});
});
@@ -60,6 +61,7 @@ afterEach(() => {
chatPathByBotId: initialState.chatPathByBotId,
sections: initialState.sections,
pinnedItems: initialState.pinnedItems,
+ unassignedItems: initialState.unassignedItems,
environmentId: initialState.environmentId,
});
if (typeof window !== "undefined") {
@@ -263,8 +265,138 @@ describe("roster sections and pins", () => {
name: "Work",
botIds: ["one"],
groupIds: [],
+ items: [{ kind: "bot", id: "one" }],
collapsed: true,
},
]);
});
+
+ it("applies pin, unpin, and mixed-section drops without changing group membership", () => {
+ const crew = group("crew");
+ useRosterStore.setState({
+ bots: [bot("akeru"), bot("mori")],
+ groups: [crew],
+ sections: [
+ {
+ id: "news",
+ name: "News",
+ botIds: ["akeru"],
+ groupIds: ["crew"],
+ items: [
+ { kind: "group", id: "crew" },
+ { kind: "bot", id: "akeru" },
+ ],
+ collapsed: false,
+ },
+ ],
+ });
+
+ useRosterStore.getState().applyRosterDrop({
+ kind: "pin",
+ item: { kind: "bot", id: "mori" },
+ order: [{ kind: "bot", id: "mori" }],
+ });
+ expect(useRosterStore.getState().pinnedItems).toEqual([{ kind: "bot", id: "mori" }]);
+ expect(useRosterStore.getState().groups).toEqual([crew]);
+
+ useRosterStore.getState().applyRosterDrop({
+ kind: "move",
+ item: { kind: "bot", id: "mori" },
+ zone: { sectionId: "news" },
+ order: [
+ { kind: "group", id: "crew" },
+ { kind: "bot", id: "akeru" },
+ { kind: "bot", id: "mori" },
+ ],
+ unpin: true,
+ });
+ expect(useRosterStore.getState().pinnedItems).toEqual([]);
+ expect(useRosterStore.getState().sections[0]?.items).toEqual([
+ { kind: "group", id: "crew" },
+ { kind: "bot", id: "akeru" },
+ { kind: "bot", id: "mori" },
+ ]);
+ expect(useRosterStore.getState().groups[0]?.members).toEqual([]);
+ });
+
+ it("nudges unassigned bots with Move up without changing group membership", () => {
+ useRosterStore.setState({
+ bots: [bot("akeru"), bot("mori"), bot("scout")],
+ groups: [group("crew")],
+ unassignedItems: [
+ { kind: "bot", id: "akeru" },
+ { kind: "bot", id: "mori" },
+ { kind: "bot", id: "scout" },
+ ],
+ });
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "bot", id: "mori" }, -1);
+
+ expect(useRosterStore.getState().unassignedItems.map((item) => item.id)).toEqual([
+ "mori",
+ "akeru",
+ "scout",
+ "crew",
+ ]);
+ expect(useRosterStore.getState().groups[0]?.members).toEqual([]);
+ });
+
+ it("nudges newly live unassigned items omitted from the saved order", () => {
+ useRosterStore.setState({
+ bots: [bot("akeru"), bot("mori")],
+ groups: [group("crew")],
+ unassignedItems: [{ kind: "bot", id: "akeru" }],
+ });
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "group", id: "crew" }, -1);
+ expect(useRosterStore.getState().unassignedItems).toEqual([
+ { kind: "group", id: "crew" },
+ { kind: "bot", id: "akeru" },
+ { kind: "bot", id: "mori" },
+ ]);
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "bot", id: "mori" }, -1);
+ expect(useRosterStore.getState().unassignedItems).toEqual([
+ { kind: "group", id: "crew" },
+ { kind: "bot", id: "mori" },
+ { kind: "bot", id: "akeru" },
+ ]);
+ });
+
+ it("nudges pinned and section items without crossing zones", () => {
+ useRosterStore.setState({
+ bots: [bot("akeru"), bot("mori"), bot("scout")],
+ groups: [group("crew")],
+ pinnedItems: [
+ { kind: "bot", id: "akeru" },
+ { kind: "group", id: "crew" },
+ ],
+ sections: [
+ {
+ id: "news",
+ name: "News",
+ botIds: ["mori", "scout"],
+ groupIds: [],
+ items: [
+ { kind: "bot", id: "mori" },
+ { kind: "bot", id: "scout" },
+ ],
+ collapsed: false,
+ },
+ ],
+ });
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "group", id: "crew" }, -1);
+ expect(useRosterStore.getState().pinnedItems.map((item) => item.id)).toEqual(["crew", "akeru"]);
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "bot", id: "scout" }, -1);
+ expect(useRosterStore.getState().sections[0]?.items?.map((item) => item.id)).toEqual([
+ "scout",
+ "mori",
+ ]);
+ expect(useRosterStore.getState().pinnedItems.map((item) => item.id)).toEqual(["crew", "akeru"]);
+
+ useRosterStore.getState().nudgeRosterItem({ kind: "group", id: "crew" }, -1);
+ expect(useRosterStore.getState().pinnedItems.map((item) => item.id)).toEqual(["crew", "akeru"]);
+ });
});
diff --git a/apps/web/src/components/roster/rosterStore.ts b/apps/web/src/components/roster/rosterStore.ts
index 24ef0666c..67380dd48 100644
--- a/apps/web/src/components/roster/rosterStore.ts
+++ b/apps/web/src/components/roster/rosterStore.ts
@@ -1,9 +1,20 @@
import { create } from "zustand";
import { randomUUID } from "../../lib/utils";
-import type { RosterLastMessage } from "./roster.logic";
+import {
+ moveRosterItemInOrder,
+ rosterItemKey,
+ rosterItemsEqual,
+ rosterSectionItems,
+ splitRosterSectionItems,
+ type RosterDropPlan,
+ type RosterItemRef,
+ type RosterLastMessage,
+} from "./roster.logic";
import type { Bot, BotAvatar, Group } from "./types";
+export type { RosterItemRef };
+
const PERSISTED_ROSTER_KEY = "akeru:roster:v1";
const persistedRosterMemory = new Map<string, PersistedRoster>();
@@ -17,6 +28,7 @@ interface PersistedRoster {
botLayout?: Array<{ id: string; pinned: boolean }>;
sections?: RosterSection[];
pinnedItems?: RosterItemRef[];
+ unassignedItems?: RosterItemRef[];
}
export interface RosterSection {
@@ -24,15 +36,69 @@ export interface RosterSection {
name: string;
botIds: string[];
groupIds?: string[];
+ items?: RosterItemRef[];
collapsed: boolean;
}
-export type RosterItemRef = { kind: "bot"; id: string } | { kind: "group"; id: string };
-
function firstAvailableBotId(bots: readonly Bot[]): string | null {
return bots.find((bot) => bot.archivedAt === null)?.id ?? null;
}
+function isRosterItemList(value: unknown): value is RosterItemRef[] {
+ return (
+ Array.isArray(value) &&
+ value.every(
+ (item) =>
+ typeof item === "object" &&
+ item !== null &&
+ ((item as { kind?: unknown }).kind === "bot" ||
+ (item as { kind?: unknown }).kind === "group") &&
+ typeof (item as { id?: unknown }).id === "string",
+ )
+ );
+}
+
+function withSectionItems(section: RosterSection, items: readonly RosterItemRef[]): RosterSection {
+ const split = splitRosterSectionItems(items);
+ return {
+ ...section,
+ items: [...items],
+ botIds: split.botIds,
+ groupIds: split.groupIds,
+ };
+}
+
+function removeItemFromSections(
+ sections: readonly RosterSection[],
+ item: RosterItemRef,
+): RosterSection[] {
+ return sections.map((section) =>
+ withSectionItems(
+ section,
+ rosterSectionItems(section).filter((candidate) => !rosterItemsEqual(candidate, item)),
+ ),
+ );
+}
+
+/** Insert `moved` into `previous` using the visible drop order, keeping
+ * hidden (pinned) members in place so pin state is not a membership change. */
+function mergeVisibleOrder(
+ previous: readonly RosterItemRef[],
+ visibleOrder: readonly RosterItemRef[],
+ moved: RosterItemRef,
+): RosterItemRef[] {
+ const withoutMoved = previous.filter((item) => !rosterItemsEqual(item, moved));
+ const movedIndex = visibleOrder.findIndex((item) => rosterItemsEqual(item, moved));
+ const after = movedIndex >= 0 ? visibleOrder[movedIndex + 1] : undefined;
+ const insertAt =
+ after === undefined
+ ? withoutMoved.length
+ : withoutMoved.findIndex((item) => rosterItemsEqual(item, after));
+ const next = [...withoutMoved];
+ next.splice(insertAt < 0 ? next.length : insertAt, 0, moved);
+ return next;
+}
+
function readPersistedRoster(environmentId: string | null = null): PersistedRoster | null {
const key = persistedRosterKey(environmentId);
const inMemory = persistedRosterMemory.get(key);
@@ -43,13 +109,15 @@ function readPersistedRoster(environmentId: string | null = null): PersistedRost
if (raw === null) return null;
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return null;
- const { selectedBotId, chatPathByBotId, botLayout, sections, pinnedItems } = parsed as {
- selectedBotId?: unknown;
- chatPathByBotId?: unknown;
- botLayout?: unknown;
- sections?: unknown;
- pinnedItems?: unknown;
- };
+ const { selectedBotId, chatPathByBotId, botLayout, sections, pinnedItems, unassignedItems } =
+ parsed as {
+ selectedBotId?: unknown;
+ chatPathByBotId?: unknown;
+ botLayout?: unknown;
+ sections?: unknown;
+ pinnedItems?: unknown;
+ unassignedItems?: unknown;
+ };
return {
...(typeof selectedBotId === "string" ? { selectedBotId } : {}),
...(typeof chatPathByBotId === "object" && chatPathByBotId !== null
@@ -79,28 +147,36 @@ function readPersistedRoster(environmentId: string | null = null): PersistedRost
(section as { groupIds: unknown[] }).groupIds.every(
(id) => typeof id === "string",
))) &&
+ ((section as { items?: unknown }).items === undefined ||
+ isRosterItemList((section as { items?: unknown }).items)) &&
typeof (section as { collapsed?: unknown }).collapsed === "boolean",
)
? {
sections: (
- sections as Array<Omit<RosterSection, "groupIds"> & { groupIds?: string[] }>
- ).map((section) => ({
- ...section,
- groupIds: section.groupIds ?? [],
- })),
+ sections as Array<
+ Omit<RosterSection, "groupIds" | "items"> & {
+ groupIds?: string[];
+ items?: RosterItemRef[];
+ }
+ >
+ ).map((section) => {
+ const items = rosterSectionItems({
+ botIds: section.botIds,
+ groupIds: section.groupIds ?? [],
+ items: section.items,
+ });
+ const split = splitRosterSectionItems(items);
+ return {
+ ...section,
+ botIds: split.botIds,
+ groupIds: split.groupIds,
+ items,
+ };
+ }),
}
: {}),
- ...(Array.isArray(pinnedItems) &&
- pinnedItems.every(
- (item) =>
- typeof item === "object" &&
- item !== null &&
- ((item as { kind?: unknown }).kind === "bot" ||
- (item as { kind?: unknown }).kind === "group") &&
- typeof (item as { id?: unknown }).id === "string",
- )
- ? { pinnedItems: pinnedItems as RosterItemRef[] }
- : {}),
+ ...(isRosterItemList(pinnedItems) ? { pinnedItems } : {}),
+ ...(isRosterItemList(unassignedItems) ? { unassignedItems } : {}),
};
} catch {
return null;
@@ -126,6 +202,7 @@ interface RosterStore {
chatPathByBotId: Record<string, string>;
sections: RosterSection[];
pinnedItems: RosterItemRef[];
+ unassignedItems: RosterItemRef[];
environmentId: string | null;
selectBot: (botId: string) => void;
setBotAvatar: (botId: string, avatar: BotAvatar) => boolean;
@@ -135,8 +212,11 @@ interface RosterStore {
deleteSection: (sectionId: string) => void;
moveGroupToSection: (groupId: string, sectionId: string | null, index?: number) => void;
moveBotToSection: (botId: string, sectionId: string | null, index?: number) => void;
+ moveItemToSection: (item: RosterItemRef, sectionId: string | null, index?: number) => void;
reorderSections: (sourceIndex: number, destinationIndex: number) => void;
+ nudgeRosterItem: (item: RosterItemRef, delta: -1 | 1) => void;
setItemPinned: (item: RosterItemRef, pinned: boolean) => void;
+ applyRosterDrop: (plan: RosterDropPlan) => void;
recordLastMessage: (botId: string, message: RosterLastMessage) => void;
recordChatPath: (botId: string, path: string) => void;
forgetChatPath: (botId: string) => void;
@@ -179,7 +259,13 @@ export function reorderVisibleRosterBots(
function saveState(
state: Pick<
RosterStore,
- "bots" | "selectedBotId" | "chatPathByBotId" | "sections" | "pinnedItems" | "environmentId"
+ | "bots"
+ | "selectedBotId"
+ | "chatPathByBotId"
+ | "sections"
+ | "pinnedItems"
+ | "unassignedItems"
+ | "environmentId"
>,
) {
persistRoster(
@@ -189,6 +275,7 @@ function saveState(
botLayout: state.bots.map((bot) => ({ id: bot.id, pinned: bot.pinned })),
sections: state.sections,
pinnedItems: state.pinnedItems,
+ unassignedItems: state.unassignedItems,
},
state.environmentId,
);
@@ -204,6 +291,7 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
chatPathByBotId: persisted?.chatPathByBotId ?? {},
sections: persisted?.sections ?? [],
pinnedItems: persisted?.pinnedItems ?? [],
+ unassignedItems: persisted?.unassignedItems ?? [],
environmentId: null,
selectBot: (botId) => {
@@ -258,6 +346,7 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
name: trimmed,
botIds: [],
groupIds: [],
+ items: [],
collapsed: false,
},
],
@@ -283,30 +372,64 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
},
moveBotToSection: (botId, sectionId, index) => {
- if (!get().bots.some((bot) => bot.id === botId && bot.archivedAt === null)) return;
+ get().moveItemToSection({ kind: "bot", id: botId }, sectionId, index);
+ },
+
+ moveGroupToSection: (groupId, sectionId, index) => {
+ get().moveItemToSection({ kind: "group", id: groupId }, sectionId, index);
+ },
+
+ moveItemToSection: (item, sectionId, index) => {
+ if (
+ item.kind === "bot" &&
+ !get().bots.some((bot) => bot.id === item.id && bot.archivedAt === null)
+ ) {
+ return;
+ }
+ if (item.kind === "group" && !get().groups.some((group) => group.id === item.id)) return;
if (sectionId !== null && !get().sections.some((section) => section.id === sectionId)) return;
set((state) => {
- const sections = state.sections.map((section) => {
- const botIds = section.botIds.filter((id) => id !== botId);
- if (section.id !== sectionId) return { ...section, botIds };
- botIds.splice(Math.min(Math.max(index ?? botIds.length, 0), botIds.length), 0, botId);
- return { ...section, botIds };
+ const sections = removeItemFromSections(state.sections, item).map((section) => {
+ if (section.id !== sectionId) return section;
+ const items = rosterSectionItems(section);
+ items.splice(Math.min(Math.max(index ?? items.length, 0), items.length), 0, item);
+ return withSectionItems(section, items);
});
- if (sectionId !== null) return { sections };
- const assigned = new Set(sections.flatMap((section) => section.botIds));
+ const assignedKeys = new Set(
+ sections.flatMap((section) => rosterSectionItems(section).map(rosterItemKey)),
+ );
+ const remainingUnassigned = state.unassignedItems.filter(
+ (candidate) =>
+ !rosterItemsEqual(candidate, item) && !assignedKeys.has(rosterItemKey(candidate)),
+ );
+ if (sectionId !== null) {
+ return { sections, unassignedItems: remainingUnassigned };
+ }
+ remainingUnassigned.splice(
+ Math.min(Math.max(index ?? remainingUnassigned.length, 0), remainingUnassigned.length),
+ 0,
+ item,
+ );
+ if (item.kind !== "bot") {
+ return { sections, unassignedItems: remainingUnassigned };
+ }
+ const assignedBotIds = new Set(sections.flatMap((section) => section.botIds));
const unassignedIds = state.bots
- .filter((bot) => bot.archivedAt === null && !assigned.has(bot.id) && bot.id !== botId)
+ .filter(
+ (bot) => bot.archivedAt === null && !assignedBotIds.has(bot.id) && bot.id !== item.id,
+ )
.map((bot) => bot.id);
unassignedIds.splice(
Math.min(Math.max(index ?? unassignedIds.length, 0), unassignedIds.length),
0,
- botId,
+ item.id,
);
const unassigned = new Set(unassignedIds);
const botsById = new Map(state.bots.map((bot) => [bot.id, bot] as const));
let botIndex = 0;
return {
sections,
+ unassignedItems: remainingUnassigned,
bots: state.bots.map((bot) =>
unassigned.has(bot.id) ? (botsById.get(unassignedIds[botIndex++]!) ?? bot) : bot,
),
@@ -315,21 +438,59 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
saveState(get());
},
- moveGroupToSection: (groupId, sectionId, index) => {
- if (!get().groups.some((group) => group.id === groupId)) return;
- if (sectionId !== null && !get().sections.some((section) => section.id === sectionId)) return;
- set((state) => ({
- sections: state.sections.map((section) => {
- const groupIds = (section.groupIds ?? []).filter((id) => id !== groupId);
- if (section.id !== sectionId) return { ...section, groupIds };
- groupIds.splice(
- Math.min(Math.max(index ?? groupIds.length, 0), groupIds.length),
- 0,
- groupId,
+ applyRosterDrop: (plan) => {
+ if (plan.kind === "none") return;
+ if (plan.kind === "reorder-section") {
+ get().reorderSections(plan.fromIndex, plan.toIndex);
+ return;
+ }
+ if (plan.kind === "reorder-pinned") {
+ set({ pinnedItems: [...plan.order] });
+ saveState(get());
+ return;
+ }
+ if (plan.kind === "pin") {
+ set({ pinnedItems: [...plan.order] });
+ saveState(get());
+ return;
+ }
+ set((state) => {
+ const pinnedItems = plan.unpin
+ ? state.pinnedItems.filter((candidate) => !rosterItemsEqual(candidate, plan.item))
+ : state.pinnedItems;
+ const sectionId = typeof plan.zone === "object" ? plan.zone.sectionId : null;
+ const sections = removeItemFromSections(state.sections, plan.item).map((section) => {
+ if (section.id !== sectionId) return section;
+ return withSectionItems(
+ section,
+ mergeVisibleOrder(rosterSectionItems(section), plan.order, plan.item),
);
- return { ...section, groupIds };
- }),
- }));
+ });
+ const unassignedItems =
+ sectionId === null
+ ? [...plan.order]
+ : state.unassignedItems.filter((candidate) => !rosterItemsEqual(candidate, plan.item));
+ if (plan.item.kind !== "bot" || sectionId !== null) {
+ return { pinnedItems, sections, unassignedItems };
+ }
+ const assignedBotIds = new Set(sections.flatMap((section) => section.botIds));
+ const unassignedIds = plan.order
+ .filter((entry) => entry.kind === "bot")
+ .map((entry) => entry.id);
+ const unassigned = new Set(unassignedIds);
+ const botsById = new Map(state.bots.map((bot) => [bot.id, bot] as const));
+ let botIndex = 0;
+ return {
+ pinnedItems,
+ sections,
+ unassignedItems,
+ bots: state.bots.map((bot) =>
+ unassigned.has(bot.id) && !assignedBotIds.has(bot.id)
+ ? (botsById.get(unassignedIds[botIndex++]!) ?? bot)
+ : bot,
+ ),
+ };
+ });
saveState(get());
},
@@ -351,6 +512,53 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
saveState(get());
},
+ nudgeRosterItem: (item, delta) => {
+ const state = get();
+ const pinned = moveRosterItemInOrder(state.pinnedItems, item, delta);
+ if (pinned) {
+ set({ pinnedItems: pinned });
+ saveState(get());
+ return;
+ }
+ for (const section of state.sections) {
+ const moved = moveRosterItemInOrder(rosterSectionItems(section), item, delta);
+ if (!moved) continue;
+ set({
+ sections: state.sections.map((candidate) =>
+ candidate.id === section.id ? withSectionItems(candidate, moved) : candidate,
+ ),
+ });
+ saveState(get());
+ return;
+ }
+ const assigned = new Set(
+ state.sections.flatMap((section) => rosterSectionItems(section).map(rosterItemKey)),
+ );
+ const pinnedKeys = new Set(state.pinnedItems.map(rosterItemKey));
+ const remaining = (candidate: RosterItemRef) =>
+ !assigned.has(rosterItemKey(candidate)) && !pinnedKeys.has(rosterItemKey(candidate));
+ const unassigned = state.unassignedItems.filter(remaining);
+ const seen = new Set(unassigned.map(rosterItemKey));
+ for (const group of state.groups) {
+ const candidate = { kind: "group" as const, id: group.id };
+ if (remaining(candidate) && !seen.has(rosterItemKey(candidate))) {
+ unassigned.push(candidate);
+ seen.add(rosterItemKey(candidate));
+ }
+ }
+ for (const bot of state.bots) {
+ const candidate = { kind: "bot" as const, id: bot.id };
+ if (bot.archivedAt === null && remaining(candidate) && !seen.has(rosterItemKey(candidate))) {
+ unassigned.push(candidate);
+ seen.add(rosterItemKey(candidate));
+ }
+ }
+ const movedUnassigned = moveRosterItemInOrder(unassigned, item, delta);
+ if (!movedUnassigned) return;
+ set({ unassignedItems: movedUnassigned });
+ saveState(get());
+ },
+
setItemPinned: (item, pinned) => {
set((state) => {
const withoutItem = state.pinnedItems.filter(
@@ -416,6 +624,16 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
const targetPinnedItems = switchingEnvironment
? (targetPersisted?.pinnedItems ?? [])
: get().pinnedItems;
+ const targetUnassignedItems = switchingEnvironment
+ ? (targetPersisted?.unassignedItems ?? [])
+ : get().unassignedItems;
+ const liveItem = (item: RosterItemRef) =>
+ item.kind === "bot"
+ ? bots.some((bot) => bot.id === item.id && bot.archivedAt === null)
+ : input.groups.some((group) => group.id === item.id);
+ const sections = targetSections.map((section) =>
+ withSectionItems(section, rosterSectionItems(section).filter(liveItem)),
+ );
set({
environmentId: input.environmentId,
bots,
@@ -423,18 +641,9 @@ export const useRosterStore = create<RosterStore>((set, get) => ({
chatPathByBotId: switchingEnvironment
? (targetPersisted?.chatPathByBotId ?? {})
: get().chatPathByBotId,
- sections: targetSections.map((section) => ({
- ...section,
- botIds: section.botIds.filter((id) => bots.some((bot) => bot.id === id)),
- groupIds: (section.groupIds ?? []).filter((id) =>
- input.groups.some((group) => group.id === id),
- ),
- })),
- pinnedItems: targetPinnedItems.filter((item) =>
- item.kind === "bot"
- ? bots.some((bot) => bot.id === item.id && bot.archivedAt === null)
- : input.groups.some((group) => group.id === item.id),
- ),
+ sections,
+ pinnedItems: targetPinnedItems.filter(liveItem),
+ unassignedItems: targetUnassignedItems.filter(liveItem),
selectedBotId,
...(input.lastMessageByBotId ? { lastMessageByBotId: input.lastMessageByBotId } : {}),
});
diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.ts
index 01ee2e0b0..d615b3218 100644
--- a/apps/web/src/components/sidebar/SidebarChrome.test.ts
+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts
@@ -226,14 +226,17 @@ describe("sidebar footer", () => {
expect(source).not.toContain("touch-none");
});
- it("keeps group membership out of roster drag and centers pinned items", () => {
+ it("keeps group membership out of roster drag and treats pins as a drop target", () => {
const source = NodeFS.readFileSync(
new URL("../roster/BotRosterSidebar.tsx", import.meta.url),
"utf8",
);
expect(source).not.toContain("botEnvironment.groups.assignMember");
- expect(source).toContain('className="flex justify-center gap-2 overflow-x-auto px-2 py-1"');
+ expect(source).toContain("roster-pinned-header");
+ expect(source).not.toContain("KeyboardSensor");
+ expect(source).toContain("Move up");
+ expect(source).toContain("Move down");
expect(source).toContain("onContextMenu={(event) => {");
});
diff --git a/docs/internals/glossary.md b/docs/internals/glossary.md
index 522c3a936..99516bc13 100644
--- a/docs/internals/glossary.md
+++ b/docs/internals/glossary.md
@@ -8,6 +8,7 @@ This is a living glossary for Akeru Bot. It explains what common terms mean in t
- [Project and workspace](#project-and-workspace)
- [Thread timeline](#thread-timeline)
+- [Roster organization](#roster-organization)
- [Orchestration](#orchestration)
- [Provider runtime](#provider-runtime)
- [Subscription provider](#subscription-provider)
@@ -40,6 +41,10 @@ The internal durable record for one user-facing chat and its workspace history.
A single user-to-assistant work cycle inside a thread. It starts with user input and ends when the session leaves `running` status, which [projector.ts][4] treats as the authoritative completion signal (`settledTurnStateForSessionStatus`). Checkpoint and diff work may settle afterward without changing when the turn ended. See [the contracts][1] and [ProviderRuntimeIngestion.ts][5].
+### Roster organization
+
+The live sidebar is `BotRosterSidebar`. Pins, named sections, and Unassigned are a client layout over bots and groups. They must not assign or remove group members, and they must not settle chats. Drag planning lives in `roster.logic.ts`; pointer cleanup, insertion-gap projection, and list motion live beside it in `roster.pointer.ts`, `roster.drag.ts`, and `roster.motion.ts`.
+
#### Activity
A user-visible log item attached to a thread. In [the contracts][1], activities cover important non-message events like approvals, tool actions, and failures. They are projected into thread state in [projector.ts][4].
diff --git a/docs/user/bots.md b/docs/user/bots.md
index 29f26ed86..a14167a55 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -54,6 +54,16 @@ start enabled for every bot. A workspace-disabled tool stays unavailable to ever
Changing the provider starts a fresh provider session with the same enabled tool set.
+## Organize the roster
+
+The sidebar lists pinned bots and groups, then any named sections you create, then everything else under **Unassigned**. Drag a bot or group to reorder it, pin it, or unpin it. Dragging into **Pinned** pins it at that spot. Dragging a pinned item into a section or Unassigned unpins it. Drag a section header to reorder sections.
+
+Pins, sections, and Unassigned are roster layout only. They do not change group membership, and they do not settle chats.
+
+While you drag, the destination label stays readable and takes the accent color. Empty and collapsed sections stay droppable. The lifted row shows **Pin**, **Unpin**, or **Move** when the drop would change its section. Reordering inside one section has no badge. These transitions follow your reduced-motion preference, and a drop does not replay a second animation.
+
+On this device the layout is stored in the browser for the connected environment. Refresh keeps it. Other devices keep their own layout until the environment can store roster order.
+
## Conversation panel
Use the panel button to collapse or reopen the bot editor. The default shortcut is `Mod+Alt+B`. You