Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(sidebar): drag to reorder team and personal pinned agents (#23048)

Rdmclin261b7d687b6c7
diff --git a/apps/server/src/routers/lambda/__tests__/home.pinnedOrder.test.ts b/apps/server/src/routers/lambda/__tests__/home.pinnedOrder.test.ts
new file mode 100644
index 00000000000..acfbb6edd62
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/home.pinnedOrder.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HomeRepository } from '@/database/repositories/home';
+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';
+
+import { homeRouter } from '../home';
+
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/repositories/home', () => ({ HomeRepository: vi.fn() }));
+vi.mock('@/server/services/home', () => ({ HomeService: vi.fn() }));
+vi.mock('@/server/services/ftsSearch', () => ({ createFtsSearchRepo: vi.fn() }));
+vi.mock('@/server/services/workspacePermission', () => ({
+ getWorkspaceScopedPermissionMatches: vi.fn(),
+ hasWorkspaceScopedPermission: vi.fn(),
+}));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+
+const matches = vi.mocked(getWorkspaceScopedPermissionMatches);
+
+describe('homeRouter.updatePinnedOrder', () => {
+ let updatePinnedOrder: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ updatePinnedOrder = vi.fn();
+ vi.mocked(HomeRepository).mockImplementation(function () {
+ return { updatePinnedOrder } as never;
+ });
+ });
+
+ it('refuses a workspace member reordering the team pins', async () => {
+ matches.mockResolvedValue({ hasAllScope: false } as never);
+ const caller = homeRouter.createCaller({ userId: 'member-1', workspaceId: 'ws-1' } as never);
+
+ await expect(caller.updatePinnedOrder({ ids: ['a', 'b'] })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(updatePinnedOrder).not.toHaveBeenCalled();
+ });
+
+ it('lets a workspace owner/admin save the team order', async () => {
+ matches.mockResolvedValue({ hasAllScope: true } as never);
+ const caller = homeRouter.createCaller({ userId: 'admin-1', workspaceId: 'ws-1' } as never);
+
+ await caller.updatePinnedOrder({ ids: ['b', 'a'] });
+
+ expect(updatePinnedOrder).toHaveBeenCalledWith(['b', 'a']);
+ });
+
+ it('saves the personal order without a workspace permission check', async () => {
+ const caller = homeRouter.createCaller({ userId: 'user-1' } as never);
+
+ await caller.updatePinnedOrder({ ids: ['a'] });
+
+ expect(matches).not.toHaveBeenCalled();
+ expect(updatePinnedOrder).toHaveBeenCalledWith(['a']);
+ });
+
+ it('accepts a pin list longer than the personal pin cap', async () => {
+ // The `pinned` columns have no count limit, so a drag must be able to
+ // submit every rendered row.
+ const ids = Array.from({ length: 500 }, (_, index) => `agent-${index}`);
+ const caller = homeRouter.createCaller({ userId: 'user-1' } as never);
+
+ await caller.updatePinnedOrder({ ids });
+
+ expect(updatePinnedOrder).toHaveBeenCalledWith(ids);
+ });
+});
diff --git a/apps/server/src/routers/lambda/home.ts b/apps/server/src/routers/lambda/home.ts
index 4bfd46ad8d2..9897b88271b 100644
--- a/apps/server/src/routers/lambda/home.ts
+++ b/apps/server/src/routers/lambda/home.ts
@@ -4,12 +4,15 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPer
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
import { HomeRepository } from '@/database/repositories/home';
+import { MAX_PINNED_ORDER_ITEMS } from '@/database/repositories/home/pinnedOrder';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { type HomeBriefData, HomeService } from '@/server/services/home';
import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';
+import { assertCanWriteTeamPin } from './_helpers/sidebarPin';
+
const homeProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const workspaceId = ctx.workspaceId ?? undefined;
@@ -82,6 +85,18 @@ export const homeRouter = router({
return ctx.homeRepository.searchAgents(input.keyword);
}),
+ /**
+ * Save the drag-and-drop order of the sidebar's pinned rows. In a workspace
+ * these are the team pins every member sees, so only owners/admins may
+ * reorder them; in personal mode they are the user's own pins.
+ */
+ updatePinnedOrder: homeProcedure
+ .input(z.object({ ids: z.array(z.string().max(255)).max(MAX_PINNED_ORDER_ITEMS) }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanWriteTeamPin(ctx);
+ await ctx.homeRepository.updatePinnedOrder(input.ids);
+ }),
+
updateAgentSessionGroupId: homeProcedure
.use(withScopedPermission('agent:update'))
.input(
diff --git a/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts b/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts
new file mode 100644
index 00000000000..1e8c068e397
--- /dev/null
+++ b/packages/database/src/repositories/home/__tests__/sidebarPinnedOrder.test.ts
@@ -0,0 +1,95 @@
+// Drag-and-drop order of the sidebar's `pinned` bucket: the team order lives
+// on the workspace, the personal order on the user's preference.
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { AgentModel } from '../../../models/agent';
+import * as Schema from '../../../schemas';
+import { HomeRepository } from '../index';
+
+const clientDB = await getTestDB();
+
+const owner = 'u-pin-order-owner';
+const ws = 'ws-pin-order';
+
+const createPinned = async (model: AgentModel, title: string) => {
+ const agent = await model.create({ systemRole: '', title, visibility: 'public' } as any);
+ await model.update(agent.id, { pinned: true });
+ return agent.id;
+};
+
+beforeEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+ await clientDB
+ .insert(Schema.users)
+ .values([{ id: owner, preference: { sidebarHiddenAgentIds: ['kept'] } }]);
+ await clientDB.insert(Schema.workspaces).values({
+ id: ws,
+ name: 'WS',
+ primaryOwnerId: owner,
+ settings: { apiKey: { memberCreation: 'admins_only' }, sidebar: { other: true } },
+ slug: 'ws-pin-order',
+ });
+});
+
+afterEach(async () => {
+ await clientDB.delete(Schema.users);
+ await clientDB.delete(Schema.workspaces);
+});
+
+describe('HomeRepository pinned order', () => {
+ it('lays out workspace team pins in the saved order, new pins first', async () => {
+ const model = new AgentModel(clientDB, owner, ws);
+ const a = await createPinned(model, 'A');
+ const b = await createPinned(model, 'B');
+ const c = await createPinned(model, 'C');
+ const repo = new HomeRepository(clientDB, owner, ws);
+
+ await repo.updatePinnedOrder([a, c, b]);
+ expect((await repo.getSidebarAgentList()).pinned.map((item) => item.id)).toEqual([a, c, b]);
+
+ const d = await createPinned(model, 'D');
+ expect((await repo.getSidebarAgentList()).pinned.map((item) => item.id)).toEqual([d, a, c, b]);
+ });
+
+ it('stores the team order on the workspace without touching other settings', async () => {
+ const repo = new HomeRepository(clientDB, owner, ws);
+
+ await repo.updatePinnedOrder(['x', 'y', 'x']);
+
+ expect(await repo.getPinnedOrder()).toEqual(['x', 'y']);
+ const [row] = await clientDB
+ .select({ settings: Schema.workspaces.settings })
+ .from(Schema.workspaces)
+ .where(eq(Schema.workspaces.id, ws));
+ expect(row.settings).toEqual({
+ apiKey: { memberCreation: 'admins_only' },
+ sidebar: { other: true, teamPinnedOrder: ['x', 'y'] },
+ });
+ // The personal order is a separate list.
+ expect(await new HomeRepository(clientDB, owner).getPinnedOrder()).toEqual([]);
+ });
+
+ it('keeps the personal order on the user preference', async () => {
+ const model = new AgentModel(clientDB, owner);
+ const a = await createPinned(model, 'A');
+ const b = await createPinned(model, 'B');
+ const repo = new HomeRepository(clientDB, owner);
+
+ await repo.updatePinnedOrder([a, b]);
+ expect((await repo.getSidebarAgentList()).pinned.map((item) => item.id)).toEqual([a, b]);
+
+ await repo.updatePinnedOrder([b, a]);
+ expect((await repo.getSidebarAgentList()).pinned.map((item) => item.id)).toEqual([b, a]);
+
+ const [row] = await clientDB
+ .select({ preference: Schema.users.preference })
+ .from(Schema.users)
+ .where(eq(Schema.users.id, owner));
+ expect(row.preference).toEqual({ sidebarHiddenAgentIds: ['kept'], sidebarPinnedOrder: [b, a] });
+ // The workspace team order is untouched.
+ expect(await new HomeRepository(clientDB, owner, ws).getPinnedOrder()).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.ts
index c4e5272e6da..0ab294b8514 100644
--- a/packages/database/src/repositories/home/index.ts
+++ b/packages/database/src/repositories/home/index.ts
@@ -15,6 +15,8 @@ import {
chatGroups,
sessionGroups,
topics,
+ users,
+ workspaces,
} from '../../schemas';
import { type LobeChatDatabase } from '../../type';
import { sanitizeBm25Query } from '../../utils/bm25';
@@ -24,6 +26,7 @@ import { notShareVisitorTopic } from '../../utils/shareVisitor';
import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';
import { buildWorkspaceWhere } from '../../utils/workspace';
import type { FtsSearchCandidateSource } from '../ftsSearch';
+import { applyPinnedOrder, MAX_PINNED_ORDER_ITEMS, parsePinnedOrder } from './pinnedOrder';
// Mirrors the main chat sidebar's system-topic exclusions, plus the legacy
// task_manager trigger. These topics are surfaced in their own product surfaces,
@@ -194,7 +197,7 @@ export class HomeRepository {
.orderBy(sessionGroups.sort);
// 4. Process and categorize
- return this.processAgentList(
+ const result = this.processAgentList(
agentList,
chatGroupList,
groupList,
@@ -203,6 +206,67 @@ export class HomeRepository {
groupUnread,
agentLabelsMap,
);
+
+ // 5. Pinned rows follow the order chosen by drag and drop: the team order
+ // in a workspace, the user's own order in personal mode.
+ if (result.pinned.length > 1) {
+ result.pinned = applyPinnedOrder(result.pinned, await this.getPinnedOrder());
+ }
+
+ return result;
+ }
+
+ /**
+ * The saved order of the `pinned` bucket. In a workspace those rows are the
+ * team pins every member sees, so the order is shared and lives on the
+ * workspace (`settings.sidebar.teamPinnedOrder`). In personal mode they are
+ * the user's own pins (`preference.sidebarPinnedOrder`).
+ */
+ async getPinnedOrder(): Promise<string[]> {
+ if (this.workspaceId) {
+ const [row] = await this.db
+ .select({ order: sql<unknown>`${workspaces.settings} #> '{sidebar,teamPinnedOrder}'` })
+ .from(workspaces)
+ .where(eq(workspaces.id, this.workspaceId));
+ return parsePinnedOrder(row?.order);
+ }
+
+ const [row] = await this.db
+ .select({ order: sql<unknown>`${users.preference} -> 'sidebarPinnedOrder'` })
+ .from(users)
+ .where(eq(users.id, this.userId));
+ return parsePinnedOrder(row?.order);
+ }
+
+ /**
+ * Replace the saved order of the `pinned` bucket (see {@link getPinnedOrder}).
+ * One UPDATE that rewrites only this key, so a concurrent write to any other
+ * setting or preference is never lost. Callers authorize the workspace write:
+ * it changes the team section for every member.
+ */
+ async updatePinnedOrder(ids: string[]): Promise<void> {
+ const order = JSON.stringify([...new Set(ids)].slice(0, MAX_PINNED_ORDER_ITEMS));
+
+ if (this.workspaceId) {
+ await this.db
+ .update(workspaces)
+ .set({
+ settings: sql`coalesce(${workspaces.settings}, '{}'::jsonb) || jsonb_build_object(
+ 'sidebar',
+ coalesce(${workspaces.settings} -> 'sidebar', '{}'::jsonb)
+ || jsonb_build_object('teamPinnedOrder', ${order}::jsonb)
+ )`,
+ })
+ .where(eq(workspaces.id, this.workspaceId));
+ return;
+ }
+
+ await this.db
+ .update(users)
+ .set({
+ preference: sql`coalesce(${users.preference}, '{}'::jsonb) || jsonb_build_object('sidebarPinnedOrder', ${order}::jsonb)`,
+ })
+ .where(eq(users.id, this.userId));
}
/**
diff --git a/packages/database/src/repositories/home/pinnedOrder.test.ts b/packages/database/src/repositories/home/pinnedOrder.test.ts
new file mode 100644
index 00000000000..ab514774477
--- /dev/null
+++ b/packages/database/src/repositories/home/pinnedOrder.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { applyPinnedOrder, parsePinnedOrder } from './pinnedOrder';
+
+const rows = (...ids: string[]) => ids.map((id) => ({ id }));
+const ids = (items: { id: string }[]) => items.map((item) => item.id);
+
+describe('applyPinnedOrder', () => {
+ it('follows the saved order', () => {
+ expect(ids(applyPinnedOrder(rows('a', 'b', 'c'), ['c', 'a', 'b']))).toEqual(['c', 'a', 'b']);
+ });
+
+ it('puts rows missing from the order first, keeping their incoming order', () => {
+ expect(ids(applyPinnedOrder(rows('new2', 'b', 'new1', 'a'), ['a', 'b']))).toEqual([
+ 'new2',
+ 'new1',
+ 'a',
+ 'b',
+ ]);
+ });
+
+ it('ignores ids that match no row and keeps the first of duplicates', () => {
+ expect(ids(applyPinnedOrder(rows('a', 'b'), ['gone', 'b', 'a', 'b']))).toEqual(['b', 'a']);
+ });
+
+ it('returns the rows unchanged without an order', () => {
+ const items = rows('a', 'b');
+ expect(applyPinnedOrder(items, [])).toBe(items);
+ });
+});
+
+describe('parsePinnedOrder', () => {
+ it('keeps only string ids', () => {
+ expect(parsePinnedOrder(['a', 1, null, 'b'])).toEqual(['a', 'b']);
+ });
+
+ it('treats anything but an array as no order', () => {
+ expect(parsePinnedOrder(null)).toEqual([]);
+ expect(parsePinnedOrder({ a: 1 })).toEqual([]);
+ expect(parsePinnedOrder('a')).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/home/pinnedOrder.ts b/packages/database/src/repositories/home/pinnedOrder.ts
new file mode 100644
index 00000000000..30e8763f04a
--- /dev/null
+++ b/packages/database/src/repositories/home/pinnedOrder.ts
@@ -0,0 +1,36 @@
+/**
+ * Upper bound for a stored pinned-row order. The `pinned` columns behind it
+ * have no count limit and the sidebar renders every pinned row, so this only
+ * guards the payload size; it sits far above any real pin list so a drag
+ * always submits the whole list.
+ */
+export const MAX_PINNED_ORDER_ITEMS = 2000;
+
+/** Reads a stored order defensively: anything but a string array is no order. */
+export const parsePinnedOrder = (value: unknown): string[] =>
+ Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [];
+
+/**
+ * Lay out pinned rows by a user-chosen order. Rows missing from the order —
+ * pinned after it was last saved — keep their incoming (newest first) order
+ * and go on top, so a fresh pin still shows up first; the ordered rows follow
+ * in the saved sequence. Ids in the order that match no row are ignored.
+ */
+export const applyPinnedOrder = <T extends { id: string }>(
+ items: T[],
+ order: readonly string[],
+): T[] => {
+ if (items.length < 2 || order.length === 0) return items;
+
+ const rank = new Map<string, number>();
+ order.forEach((id, index) => {
+ if (!rank.has(id)) rank.set(id, index);
+ });
+
+ const unordered = items.filter((item) => !rank.has(item.id));
+ const ordered = items
+ .filter((item) => rank.has(item.id))
+ .sort((a, b) => rank.get(a.id)! - rank.get(b.id)!);
+
+ return [...unordered, ...ordered];
+};
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 1c6658ae538..d0d7adb3f64 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -363,6 +363,13 @@ export interface UserPreference {
* (Categories) hidden from the personal sidebar via Category Management.
*/
sidebarHiddenGroupIds?: string[];
+ /**
+ * Personal-mode order of the pinned Agents / chat groups at the top of the
+ * sidebar, set by drag and drop. Written only through
+ * `home.updatePinnedOrder`; deliberately absent from
+ * {@link UserPreferenceSchema} for the same reason as `islandDismissals`.
+ */
+ sidebarPinnedOrder?: string[];
/**
* @deprecated Use settings.general.telemetry instead
*/
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
index 71efc6beca0..3e6b28f1e2e 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentListContent.tsx
@@ -1,7 +1,8 @@
'use client';
-import { memo, useMemo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
@@ -13,6 +14,7 @@ import { resolveAgentListContentState } from './agentListContentState';
import Group from './Group';
import InboxItem from './InboxItem';
import SessionList from './List';
+import SortableList from './SortableList';
import { useAgentList } from './useAgentList';
interface AgentListContentProps {
@@ -39,6 +41,24 @@ const AgentListContent = memo<AgentListContentProps>(({ hideInbox, onMoreClick }
isLogin: !!isLogin,
});
const { customList, pinnedList, defaultList } = useAgentList();
+ // Personal pins are the user's own, so they can always be reordered. A
+ // workspace caller (compact switchers) gets the team pins here, whose order
+ // only owners/admins may change from the sidebar's own section.
+ const isWorkspace = !!useActiveWorkspaceId();
+ const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents);
+ const reorderPinnedAgents = useHomeStore((s) => s.reorderPinnedAgents);
+
+ // Pins hidden from the sidebar keep their place after the visible ones.
+ const handleReorderPinned = useCallback(
+ (ids: string[]) => {
+ const moved = new Set(ids);
+ return reorderPinnedAgents([
+ ...ids,
+ ...pinnedAgents.map((item) => item.id).filter((id) => !moved.has(id)),
+ ]);
+ },
+ [pinnedAgents, reorderPinnedAgents],
+ );
// Memoize computed visibility flags to prevent unnecessary recalculations
const { showPinned, showCustom } = useMemo(() => {
@@ -64,7 +84,12 @@ const AgentListContent = memo<AgentListContentProps>(({ hideInbox, onMoreClick }
return (
<>
{!hideInbox && <InboxItem style={{ minHeight: 36 }} />}
- {showPinned && <SessionList dataSource={pinnedList!} />}
+ {showPinned &&
+ (isWorkspace ? (
+ <SessionList dataSource={pinnedList!} />
+ ) : (
+ <SortableList dataSource={pinnedList!} onReorder={handleReorderPinned} />
+ ))}
{showCustom && <Group dataSource={customList!} />}
<SessionList
dataSource={defaultList ?? []}
diff --git a/src/features/HomeSidebar/Body/Agent/List/SortableList.tsx b/src/features/HomeSidebar/Body/Agent/List/SortableList.tsx
new file mode 100644
index 00000000000..2a494a6f4d9
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/SortableList.tsx
@@ -0,0 +1,175 @@
+'use client';
+
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { SidebarAgentItem } from '@lobechat/types';
+import { Flexbox, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, useMemo, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useGlobalStore } from '@/store/global';
+
+import {
+ RowKeyboardSensor,
+ RowMouseSensor,
+ RowTouchSensor,
+ sortableRowDropAnimation,
+ suppressNextClick,
+} from '../../sortableRow';
+import GroupItem from './AgentGroupItem';
+import AgentItem from './AgentItem';
+import { applyPendingOrder, resolveSortableDrop } from './dropOutsideWindow';
+
+const styles = stylex.create({
+ overlay: {
+ backgroundColor: cssVar.colorBgElevated,
+ borderRadius: cssVar.borderRadius,
+ boxShadow: cssVar.boxShadowSecondary,
+ cursor: 'grabbing',
+ pointerEvents: 'none',
+ },
+});
+
+const Row = memo<{ item: SidebarAgentItem }>(({ item }) =>
+ item.type === 'group' ? <GroupItem item={item} /> : <AgentItem item={item} />,
+);
+
+Row.displayName = 'SortableAgentRow';
+
+const SortableRow = memo<{ item: SidebarAgentItem }>(({ item }) => {
+ const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ id: item.id,
+ });
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={{
+ // The floating copy follows the pointer; the row itself marks where it will land.
+ opacity: isDragging ? 0.4 : undefined,
+ transform: CSS.Translate.toString(transform),
+ transition,
+ // Holding the press before the drag starts would otherwise select the title.
+ userSelect: 'none',
+ }}
+ {...attributes}
+ {...listeners}
+ // The row is natively draggable (drop it outside to open a new window).
+ // That native drag would take the pointer away from the sort, so it is
+ // cancelled here and the sort handles a drop outside the window instead.
+ onDragStart={(e) => e.preventDefault()}
+ >
+ <Row item={item} />
+ </div>
+ );
+});
+
+SortableRow.displayName = 'SortableAgentListRow';
+
+interface SortableListProps {
+ dataSource: SidebarAgentItem[];
+ /** Saves the new order of the rows in `dataSource`. */
+ onReorder: (ids: string[]) => Promise<void>;
+}
+
+/**
+ * A sidebar Agent list whose rows can be reordered by drag and drop, sharing
+ * the sensors and drop animation of the Favorites list. Dropping a row
+ * outside the window still opens it in a new window, as on a static list.
+ */
+const SortableList = memo<SortableListProps>(({ dataSource, onReorder }) => {
+ const { t } = useTranslation('common');
+ const openAgentInNewWindow = useGlobalStore((s) => s.openAgentInNewWindow);
+
+ const [activeId, setActiveId] = useState<string>();
+ // The dropped order, shown until the save settles: a save can wait behind an
+ // earlier one, and the row must not snap back meanwhile. On failure the list
+ // falls back to the store's (rolled back) order.
+ const [pendingIds, setPendingIds] = useState<string[]>();
+ const rows = useMemo(() => applyPendingOrder(dataSource, pendingIds), [dataSource, pendingIds]);
+ const ids = useMemo(() => rows.map((item) => item.id), [rows]);
+
+ const sensors = useSensors(
+ useSensor(RowMouseSensor, { activationConstraint: { distance: 5 } }),
+ // A press-and-hold picks a row up on touch, so a vertical swipe still scrolls the sidebar.
+ useSensor(RowTouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
+ useSensor(RowKeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ const activeItem = activeId ? rows.find((item) => item.id === activeId) : undefined;
+
+ const handleDragStart = ({ active }: DragStartEvent) => setActiveId(String(active.id));
+
+ const handleDragEnd = async (event: DragEndEvent) => {
+ setActiveId(undefined);
+ suppressNextClick();
+
+ const outcome = resolveSortableDrop(event, ids);
+ if (outcome.type === 'openWindow') {
+ openAgentInNewWindow(outcome.id);
+ return;
+ }
+ if (outcome.type !== 'reorder') return;
+
+ const nextIds = outcome.ids;
+ setPendingIds(nextIds);
+ try {
+ await onReorder(nextIds);
+ } catch (error) {
+ console.error('[sidebar] failed to save the pinned order', error);
+ toast.error(t('operationFailed'));
+ } finally {
+ // A later drop owns the pending order now; leave it in place.
+ setPendingIds((current) => (current === nextIds ? undefined : current));
+ }
+ };
+
+ return (
+ <DndContext
+ collisionDetection={closestCenter}
+ sensors={sensors}
+ onDragCancel={() => setActiveId(undefined)}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ <Flexbox gap={1}>
+ {rows.map((item) => (
+ <SortableRow item={item} key={item.id} />
+ ))}
+ </Flexbox>
+ </SortableContext>
+ {createPortal(
+ <DragOverlay dropAnimation={sortableRowDropAnimation}>
+ {activeItem ? (
+ <div {...stylex.props(styles.overlay)}>
+ <Row item={activeItem} />
+ </div>
+ ) : null}
+ </DragOverlay>,
+ document.body,
+ )}
+ </DndContext>
+ );
+});
+
+SortableList.displayName = 'SortableAgentList';
+
+export default SortableList;
diff --git a/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
index 2dd62373c85..8239c80af3b 100644
--- a/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/WorkspaceAgentListContent.tsx
@@ -3,12 +3,13 @@
import { cssVar, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { ChevronDown, ChevronUp, MoreHorizontal, PinIcon, UsersIcon } from 'lucide-react';
import { type ReactNode } from 'react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useHomeStore } from '@/store/home';
@@ -21,6 +22,7 @@ import { resolveAgentListContentState } from './agentListContentState';
import Group from './Group';
import InboxItem from './InboxItem';
import SessionList from './List';
+import SortableList from './SortableList';
import { useWorkspaceAgentSections } from './useWorkspaceAgentSections';
/** Team pins beyond this many fold behind a "show more" row. */
@@ -76,8 +78,32 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
const agentPageSize = useGlobalStore(systemStatusSelectors.agentPageSize);
const navigate = useWorkspaceAwareNavigate();
const [teamExpanded, setTeamExpanded] = useState(false);
+ // Team pins are shared by every member, so only owners/admins (the roles the
+ // server lets write team pins) can reorder them; everyone orders their own.
+ const { allowed: canManageTeamPins } = usePermission('manage_settings');
+ const [reorderPinnedAgents, reorderMyPinned] = useHomeStore((s) => [
+ s.reorderPinnedAgents,
+ s.reorderMyPinned,
+ ]);
const resolved = useWorkspaceAgentSections();
+ const { teamPinned } = resolved;
+ const teamOverflow = teamPinned.length > TEAM_PINNED_VISIBLE_LIMIT;
+ const visibleTeamPinned =
+ teamOverflow && !teamExpanded ? teamPinned.slice(0, TEAM_PINNED_VISIBLE_LIMIT) : teamPinned;
+
+ // While the team section is folded only its visible rows can move; the
+ // folded ones keep their order after them.
+ const handleReorderTeamPinned = useCallback(
+ (ids: string[]) => {
+ const moved = new Set(ids);
+ return reorderPinnedAgents([
+ ...ids,
+ ...teamPinned.map((item) => item.id).filter((id) => !moved.has(id)),
+ ]);
+ },
+ [reorderPinnedAgents, teamPinned],
+ );
const sections = useMemo(
() => ({
...resolved,
@@ -95,10 +121,7 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
</>
);
- const { folders, hasMore, myPinned, rest, teamPinned } = sections;
- const teamOverflow = teamPinned.length > TEAM_PINNED_VISIBLE_LIMIT;
- const visibleTeamPinned =
- teamOverflow && !teamExpanded ? teamPinned.slice(0, TEAM_PINNED_VISIBLE_LIMIT) : teamPinned;
+ const { folders, hasMore, myPinned, rest } = sections;
return (
<>
@@ -111,7 +134,11 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
title={t('navPanel.teamPinned')}
tooltip={t('navPanel.teamPinnedHint')}
/>
- <SessionList dataSource={visibleTeamPinned} />
+ {canManageTeamPins ? (
+ <SortableList dataSource={visibleTeamPinned} onReorder={handleReorderTeamPinned} />
+ ) : (
+ <SessionList dataSource={visibleTeamPinned} />
+ )}
{teamOverflow && (
// Subordinate to the team pins above, so it reads lighter and
// smaller than an agent row instead of competing with them.
@@ -141,7 +168,7 @@ const WorkspaceAgentListContent = memo<{ hideInbox?: boolean }>(({ hideInbox })
testId={'sidebar-my-pinned-header'}
title={t('navPanel.myPinned')}
/>
- <SessionList dataSource={myPinned} />
+ <SortableList dataSource={myPinned} onReorder={reorderMyPinned} />
</Flexbox>
)}
{folders.length > 0 && <Group dataSource={folders} />}
diff --git a/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.test.ts b/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.test.ts
new file mode 100644
index 00000000000..dbec004a9e2
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.test.ts
@@ -0,0 +1,79 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { describe, expect, it } from 'vitest';
+
+import { applyPendingOrder, isDropOutsideWindow, resolveSortableDrop } from './dropOutsideWindow';
+
+const viewport = { height: 600, width: 800 };
+const mouse = (clientX: number, clientY: number) =>
+ new MouseEvent('mousedown', { clientX, clientY });
+
+describe('isDropOutsideWindow', () => {
+ it('is false for a drop inside the window', () => {
+ expect(
+ isDropOutsideWindow({ activatorEvent: mouse(100, 100), delta: { x: 50, y: 200 } }, viewport),
+ ).toBe(false);
+ });
+
+ it('is true once the pointer travelled past an edge', () => {
+ expect(
+ isDropOutsideWindow({ activatorEvent: mouse(100, 100), delta: { x: 750, y: 0 } }, viewport),
+ ).toBe(true);
+ expect(
+ isDropOutsideWindow({ activatorEvent: mouse(100, 100), delta: { x: -150, y: 0 } }, viewport),
+ ).toBe(true);
+ });
+
+ it('never counts a keyboard drag', () => {
+ expect(
+ isDropOutsideWindow(
+ { activatorEvent: new KeyboardEvent('keydown'), delta: { x: 9999, y: 0 } },
+ viewport,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('resolveSortableDrop', () => {
+ const ids = ['a', 'b', 'c'];
+ const drop = (over: string | null, delta = { x: 0, y: 40 }) => ({
+ activatorEvent: mouse(100, 100),
+ active: { id: 'a' },
+ delta,
+ over: over ? { id: over } : null,
+ });
+
+ it('reorders when dropped on another row', () => {
+ expect(resolveSortableDrop(drop('c'), ids, viewport)).toEqual({
+ ids: ['b', 'c', 'a'],
+ type: 'reorder',
+ });
+ });
+
+ it('opens a new window outside the window even when a row is reported as over', () => {
+ expect(resolveSortableDrop(drop('b', { x: 900, y: 0 }), ids, viewport)).toEqual({
+ id: 'a',
+ type: 'openWindow',
+ });
+ });
+
+ it('does nothing when dropped back in place', () => {
+ expect(resolveSortableDrop(drop('a'), ids, viewport)).toEqual({ type: 'none' });
+ expect(resolveSortableDrop(drop(null), ids, viewport)).toEqual({ type: 'none' });
+ });
+});
+
+describe('applyPendingOrder', () => {
+ const rows = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
+
+ it('keeps the rows without a pending order', () => {
+ expect(applyPendingOrder(rows, undefined)).toBe(rows);
+ });
+
+ it('shows the dropped order, keeping new rows after it and skipping gone ids', () => {
+ expect(
+ applyPendingOrder([...rows, { id: 'new' }], ['c', 'gone', 'a', 'b']).map((row) => row.id),
+ ).toEqual(['c', 'a', 'b', 'new']);
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.ts b/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.ts
new file mode 100644
index 00000000000..450dccd2234
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Agent/List/dropOutsideWindow.ts
@@ -0,0 +1,84 @@
+interface DropEventLike {
+ activatorEvent: Event | null;
+ delta: { x: number; y: number };
+}
+
+const pointerStart = (event: Event | null): { x: number; y: number } | undefined => {
+ if (!event) return undefined;
+ if ('touches' in event) {
+ const touch = (event as TouchEvent).touches[0] ?? (event as TouchEvent).changedTouches[0];
+ return touch ? { x: touch.clientX, y: touch.clientY } : undefined;
+ }
+ if ('clientX' in event) {
+ const { clientX, clientY } = event as MouseEvent;
+ return { x: clientX, y: clientY };
+ }
+ return undefined;
+};
+
+/**
+ * Whether a sortable drag ended with the pointer outside the browser window:
+ * where it was picked up plus how far it travelled. A keyboard drag has no
+ * pointer, so it never counts.
+ */
+export const isDropOutsideWindow = (
+ { activatorEvent, delta }: DropEventLike,
+ viewport: { height: number; width: number } = {
+ height: window.innerHeight,
+ width: window.innerWidth,
+ },
+): boolean => {
+ const start = pointerStart(activatorEvent);
+ if (!start) return false;
+
+ const x = start.x + delta.x;
+ const y = start.y + delta.y;
+ return x < 0 || y < 0 || x > viewport.width || y > viewport.height;
+};
+
+export type SortableDropOutcome =
+ { type: 'none' } | { id: string; type: 'openWindow' } | { ids: string[]; type: 'reorder' };
+
+interface SortableDropEvent extends DropEventLike {
+ active: { id: string | number };
+ over: { id: string | number } | null;
+}
+
+/**
+ * What a finished drag on a sortable Agent list means. Outside the window is
+ * checked first: closest-center collision always resolves to some row, so a
+ * drop outside the window still reports one.
+ */
+export const resolveSortableDrop = (
+ event: SortableDropEvent,
+ ids: readonly string[],
+ viewport?: { height: number; width: number },
+): SortableDropOutcome => {
+ const activeId = String(event.active.id);
+ if (isDropOutsideWindow(event, viewport)) return { id: activeId, type: 'openWindow' };
+ if (!event.over || activeId === String(event.over.id)) return { type: 'none' };
+
+ const from = ids.indexOf(activeId);
+ const to = ids.indexOf(String(event.over.id));
+ if (from < 0 || to < 0) return { type: 'none' };
+
+ const next = [...ids];
+ next.splice(to, 0, ...next.splice(from, 1));
+ return { ids: next, type: 'reorder' };
+};
+
+/**
+ * Lay out rows by an order dropped but not yet saved. Rows the order does not
+ * name (added meanwhile) keep their place after the named ones; ids that no
+ * longer match a row are skipped.
+ */
+export const applyPendingOrder = <T extends { id: string }>(
+ rows: T[],
+ pendingIds: readonly string[] | undefined,
+): T[] => {
+ if (!pendingIds) return rows;
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ const named = pendingIds.flatMap((id) => byId.get(id) ?? []);
+ const namedIds = new Set(named.map((row) => row.id));
+ return [...named, ...rows.filter((row) => !namedIds.has(row.id))];
+};
diff --git a/src/services/home/index.ts b/src/services/home/index.ts
index a0a041d6662..ee81c38e496 100644
--- a/src/services/home/index.ts
+++ b/src/services/home/index.ts
@@ -33,6 +33,14 @@ export class HomeService {
return lambdaClient.home.searchAgents.query({ keyword });
};
+ /**
+ * Save the drag-and-drop order of the sidebar's pinned rows (the team pins
+ * in a workspace, the user's own pins in personal mode).
+ */
+ updatePinnedOrder = async (ids: string[]): Promise<void> => {
+ await lambdaClient.home.updatePinnedOrder.mutate({ ids });
+ };
+
/**
* Update an agent's session group
*/
diff --git a/src/store/home/slices/agentList/action.test.ts b/src/store/home/slices/agentList/action.test.ts
index bb7ac702b74..b9691c7556c 100644
--- a/src/store/home/slices/agentList/action.test.ts
+++ b/src/store/home/slices/agentList/action.test.ts
@@ -21,6 +21,7 @@ import { getAgentStoreState } from '@/store/agent';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
+import { reorderItems } from './action';
import { initialAgentListState } from './initialState';
import { agentListResource } from './projection';
@@ -130,4 +131,70 @@ describe('sidebar agent list replica', () => {
await expect(rename).rejects.toThrow('boom');
expect(useHomeStore.getState().agentGroups[0].items[0].title).toBe('Old');
});
+
+ it('reorders the pinned rows right away, saves in order, and rolls back on failure', async () => {
+ vi.spyOn(homeService, 'getSidebarAgentList').mockResolvedValue(
+ response({ pinned: [agent('a'), agent('b'), agent('c')] }),
+ );
+ sync();
+ await waitFor(() => expect(useHomeStore.getState().pinnedAgents).toHaveLength(3));
+ const pinnedIds = () => useHomeStore.getState().pinnedAgents.map((item) => item.id);
+
+ let reject!: (error: Error) => void;
+ const save = vi
+ .spyOn(homeService, 'updatePinnedOrder')
+ .mockImplementation(() => new Promise<void>((_, fail) => (reject = fail)));
+
+ const reorder = useHomeStore.getState().reorderPinnedAgents(['c', 'a', 'b']);
+ expect(pinnedIds()).toEqual(['c', 'a', 'b']);
+ await waitFor(() => expect(save).toHaveBeenCalledWith(['c', 'a', 'b']));
+
+ reject(new Error('boom'));
+ await expect(reorder).rejects.toThrow('boom');
+ expect(pinnedIds()).toEqual(['a', 'b', 'c']);
+ });
+});
+
+describe('reorderPinnedAgents across a scope change', () => {
+ it.each([
+ ['another workspace', (from: string) => from.replace(/:[^:]*$/, ':ws-2')],
+ // Same workspace slot, different account: comparing only the workspace
+ // would let user A's order go out on user B's session.
+ ['another account in the same workspace', (from: string) => `other-user:${from.split(':')[1]}`],
+ ])('drops a save still queued after switching to %s', async (_, next) => {
+ vi.spyOn(homeService, 'getSidebarAgentList').mockResolvedValue(
+ response({ pinned: [agent('a'), agent('b'), agent('c')] }),
+ );
+ sync();
+ await waitFor(() => expect(useHomeStore.getState().pinnedAgents).toHaveLength(3));
+
+ let finishFirst!: () => void;
+ const save = vi
+ .spyOn(homeService, 'updatePinnedOrder')
+ .mockImplementationOnce(() => new Promise<void>((resolve) => (finishFirst = resolve)))
+ .mockResolvedValue(undefined);
+
+ const first = useHomeStore.getState().reorderPinnedAgents(['c', 'a', 'b']);
+ const second = useHomeStore.getState().reorderPinnedAgents(['b', 'c', 'a']);
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+
+ scope = next(scope);
+ finishFirst();
+ // The skipped save is not an error for the caller.
+ await act(() => Promise.all([first, second]));
+
+ expect(save).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('reorderItems', () => {
+ it('puts the named rows first in order and keeps the rest after them', () => {
+ const items = [agent('a'), agent('b'), agent('c'), agent('d')];
+ expect(reorderItems(items, ['c', 'gone', 'a']).map((item) => item.id)).toEqual([
+ 'c',
+ 'a',
+ 'b',
+ 'd',
+ ]);
+ });
});
diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.ts
index 81db87c0c10..36a09a2c987 100644
--- a/src/store/home/slices/agentList/action.ts
+++ b/src/store/home/slices/agentList/action.ts
@@ -3,6 +3,7 @@ import isEqual from 'fast-deep-equal';
import { type SWRResponse } from 'swr';
import {
+ cacheScope,
createReplicaSlice,
linkReplicaEntity,
type ReplicaEntityAdapter,
@@ -89,10 +90,25 @@ type Setter = StoreSetter<HomeStore>;
export const createAgentListSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>
new AgentListActionImpl(set, get, _api);
+/**
+ * Put the rows named in `ids` first, in that order; rows it does not name keep
+ * their relative order after them.
+ */
+export const reorderItems = (items: SidebarAgentItem[], ids: readonly string[]) => {
+ const byId = new Map(items.map((item) => [item.id, item]));
+ const listed = ids.flatMap((id) => byId.get(id) ?? []);
+ const listedIds = new Set(listed.map((item) => item.id));
+ return [...listed, ...items.filter((item) => !listedIds.has(item.id))];
+};
+
+/** A pinned-order save dropped because the account or workspace changed meanwhile. */
+class ScopeChangedError extends Error {}
+
export class AgentListActionImpl {
readonly #set: Setter;
readonly #agentList;
readonly #agents;
+ #pinnedOrderQueue: Promise<unknown> = Promise.resolve();
constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
void _api;
@@ -138,6 +154,40 @@ export class AgentListActionImpl {
);
};
+ /**
+ * Reorder the `pinned` rows (team pins in a workspace, the user's own pins
+ * in personal mode) by drag and drop: the sidebar moves now and rolls back
+ * if the save fails. Saves run one after another, so quick successive drags
+ * reach the server in the order they were made. A save still queued when the
+ * cache scope changes (another account, or another workspace) is dropped: the
+ * request would carry the new session and overwrite its order with rows from
+ * the old one.
+ */
+ reorderPinnedAgents = async (ids: string[]): Promise<void> => {
+ const scope = cacheScope.get();
+ try {
+ await this.#agentList.optimistic(
+ AGENT_LIST_KEY,
+ (data) => (data ? { ...data, pinned: reorderItems(data.pinned, ids) } : data),
+ () => {
+ const operation = this.#pinnedOrderQueue
+ .catch(() => undefined)
+ .then(async () => {
+ // Failing the save rolls the unsaved order back out of the list.
+ if (cacheScope.get() !== scope) throw new ScopeChangedError();
+ await homeService.updatePinnedOrder(ids);
+ });
+ this.#pinnedOrderQueue = operation;
+ return operation;
+ },
+ );
+ } catch (error) {
+ // Nothing to report: the user left the account/workspace the drag was made in.
+ if (error instanceof ScopeChangedError) return;
+ throw error;
+ }
+ };
+
/** Fetch orchestration only; read the list through `homeAgentListSelectors`. */
useFetchAgentList = (isLogin: boolean | undefined): ReplicaSyncResult =>
this.#agentList.useSync(LIST_PARAMS, { enabled: isLogin === true });
diff --git a/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts b/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts
new file mode 100644
index 00000000000..7f258c16a4e
--- /dev/null
+++ b/src/store/home/slices/sidebarUI/action.reorderMyPinned.test.ts
@@ -0,0 +1,114 @@
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { useHomeStore } from '@/store/home';
+import { useUserStore } from '@/store/user';
+
+let scope = 'user-a:ws-1';
+
+const updatePreference = vi.fn();
+
+const setPinned = (ids: string[]) =>
+ useUserStore.setState({
+ updateWorkspaceUserPreference: updatePreference,
+ workspaceUserPreference: { sidebarPinnedItemIds: ids },
+ } as any);
+
+const reorder = (ids: string[]) => act(() => useHomeStore.getState().reorderMyPinned(ids));
+
+beforeEach(() => {
+ scope = 'user-a:ws-1';
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ updatePreference.mockReset().mockResolvedValue(undefined);
+});
+
+describe('reorderMyPinned', () => {
+ it('saves the new order of the shown pins', async () => {
+ setPinned(['a', 'b', 'c']);
+
+ await reorder(['c', 'a', 'b']);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['c', 'a', 'b'] });
+ });
+
+ it('keeps pins that are not shown after the reordered ones', async () => {
+ setPinned(['a', 'hidden', 'b', 'dangling']);
+
+ await reorder(['b', 'a']);
+
+ expect(updatePreference).toHaveBeenCalledWith({
+ sidebarPinnedItemIds: ['b', 'a', 'hidden', 'dangling'],
+ });
+ });
+
+ it('adopts a legacy private pin that lived only on its column', async () => {
+ setPinned(['a']);
+
+ await reorder(['legacy', 'a']);
+
+ expect(updatePreference).toHaveBeenCalledWith({ sidebarPinnedItemIds: ['legacy', 'a'] });
+ });
+
+ it('skips the write when nothing moved', async () => {
+ setPinned(['a', 'b']);
+
+ await reorder(['a', 'b']);
+
+ expect(updatePreference).not.toHaveBeenCalled();
+ });
+
+ it('sends quick successive reorders one after another, each on the previous result', async () => {
+ setPinned(['a', 'b', 'c']);
+ let finishFirst!: () => void;
+ updatePreference.mockImplementationOnce(async ({ sidebarPinnedItemIds }) => {
+ await new Promise<void>((resolve) => (finishFirst = resolve));
+ useUserStore.setState({ workspaceUserPreference: { sidebarPinnedItemIds } } as any);
+ });
+
+ const first = useHomeStore.getState().reorderMyPinned(['c', 'a', 'b']);
+ const second = useHomeStore.getState().reorderMyPinned(['b', 'c']);
+ await vi.waitFor(() => expect(updatePreference).toHaveBeenCalledTimes(1));
+ // The second write waits for the first to settle.
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(updatePreference).toHaveBeenCalledTimes(1);
+
+ finishFirst();
+ await act(() => Promise.all([first, second]));
+
+ expect(updatePreference).toHaveBeenNthCalledWith(1, { sidebarPinnedItemIds: ['c', 'a', 'b'] });
+ expect(updatePreference).toHaveBeenNthCalledWith(2, { sidebarPinnedItemIds: ['b', 'c', 'a'] });
+ });
+
+ it('still saves the next reorder after a failed one', async () => {
+ setPinned(['a', 'b']);
+ updatePreference.mockRejectedValueOnce(new Error('boom'));
+
+ await expect(useHomeStore.getState().reorderMyPinned(['b', 'a'])).rejects.toThrow('boom');
+ await reorder(['b', 'a']);
+
+ expect(updatePreference).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ ['another workspace', 'user-a:ws-2'],
+ // Same workspace, different account: A's order must not go out on B's session.
+ ['another account in the same workspace', 'user-b:ws-1'],
+ ])('drops a reorder still queued after switching to %s', async (_, nextScope) => {
+ setPinned(['a', 'b']);
+ let finishFirst!: () => void;
+ updatePreference.mockImplementationOnce(
+ () => new Promise<void>((resolve) => (finishFirst = resolve)),
+ );
+
+ const first = useHomeStore.getState().reorderMyPinned(['b', 'a']);
+ const second = useHomeStore.getState().reorderMyPinned(['a', 'b']);
+ await vi.waitFor(() => expect(updatePreference).toHaveBeenCalledTimes(1));
+
+ scope = nextScope;
+ finishFirst();
+ await act(() => Promise.all([first, second]));
+
+ expect(updatePreference).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.ts
index be78790660e..5df90b76a2a 100644
--- a/src/store/home/slices/sidebarUI/action.ts
+++ b/src/store/home/slices/sidebarUI/action.ts
@@ -1,6 +1,7 @@
import { toast } from '@lobehub/ui';
import { t } from 'i18next';
+import { cacheScope } from '@/libs/replica';
import { agentService } from '@/services/agent';
import { chatGroupService } from '@/services/chatGroup';
import { homeService } from '@/services/home';
@@ -33,6 +34,7 @@ export const createSidebarUISlice = (set: Setter, get: () => HomeStore, _api?: u
export class SidebarUIActionImpl {
readonly #get: () => HomeStore;
readonly #set: Setter;
+ #myPinnedQueue: Promise<unknown> = Promise.resolve();
constructor(set: Setter, get: () => HomeStore, _api?: unknown) {
void _api;
@@ -125,6 +127,39 @@ export class SidebarUIActionImpl {
if (isPrivate && !!item.pinned !== pinned) await writeColumn(pinned);
};
+ /**
+ * Reorder the member's own pins in the merged workspace Agents section.
+ * `ids` is the new order of the rows the sidebar shows; ids in the stored
+ * list that are not shown right now (hidden or dangling) keep their place
+ * after them, so a reorder never unpins anything.
+ */
+ reorderMyPinned = async (ids: string[]): Promise<void> => {
+ // The server merges each preference write into what it reads, so two quick
+ // drags sent at once could land out of order and the older one would win.
+ // Each reorder waits for the previous one and builds on its result. One
+ // still queued when the cache scope changes (another account or workspace)
+ // is dropped, since the write would land in the new session's preference.
+ const scope = cacheScope.get();
+ const operation = this.#myPinnedQueue
+ .catch(() => undefined)
+ .then(async () => {
+ if (cacheScope.get() !== scope) return;
+ const userStore = getUserStoreState();
+ const current = userStore.workspaceUserPreference.sidebarPinnedItemIds ?? [];
+ const shown = new Set(ids);
+ const nextIds = [...ids, ...current.filter((id) => !shown.has(id))].slice(
+ 0,
+ MAX_SIDEBAR_PINNED_ITEMS,
+ );
+ if (nextIds.length === current.length && nextIds.every((id, i) => id === current[i]))
+ return;
+
+ await userStore.updateWorkspaceUserPreference({ sidebarPinnedItemIds: nextIds });
+ });
+ this.#myPinnedQueue = operation;
+ await operation;
+ };
+
removeAgent = async (agentId: string): Promise<void> => {
await agentService.removeAgent(agentId);
await this.#get().refreshAgentList();