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(project): drag to reorder projects in the sidebar, with sort modes (#21490)

Lobehub Codere97e02753162
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index 98a0fe80fe6..27376101d06 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -385,6 +385,20 @@ export const projectRouter = router({
}
}),
+ /** Move one project in the scope's shared manual order, next to another project. */
+ move: projectWriteProcedure
+ .input(
+ idInput.and(z.union([z.object({ beforeId: z.string() }), z.object({ afterId: z.string() })])),
+ )
+ .mutation(async ({ ctx, input: { id, ...anchor } }) => {
+ try {
+ await ctx.projectModel.move(id, anchor);
+ return { message: 'Project moved', success: true };
+ } catch (error) {
+ mapProjectError(error, 'move');
+ }
+ }),
+
requestCompletion: projectWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
try {
return {
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 9865b8947f7..7227c8d0c9c 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -239,6 +239,11 @@
"sidebar.emptyAction": "Create your first project",
"sidebar.librariesEmpty": "No libraries are connected yet",
"sidebar.newConversation": "New topic",
+ "sidebar.reorderError": "Couldn't save the project order. Please try again.",
+ "sidebar.sort.createdAt": "Recently created",
+ "sidebar.sort.manual": "Custom order",
+ "sidebar.sort.title": "Sort projects",
+ "sidebar.sort.updatedAt": "Recently updated",
"sidebar.title": "Projects",
"sidebar.untitledConversation": "Untitled topic",
"topics.addLocation": "Add a working directory (optional)",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index ae4f5490916..e5db08a20ad 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -239,6 +239,11 @@
"sidebar.emptyAction": "创建第一个项目",
"sidebar.librariesEmpty": "还没有关联资料库",
"sidebar.newConversation": "新话题",
+ "sidebar.reorderError": "项目排序保存失败,请重试",
+ "sidebar.sort.createdAt": "最近创建",
+ "sidebar.sort.manual": "自定义排序",
+ "sidebar.sort.title": "项目排序",
+ "sidebar.sort.updatedAt": "最近更新",
"sidebar.title": "项目",
"sidebar.untitledConversation": "未命名话题",
"topics.addLocation": "添加工作目录(可选)",
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index 83d4c343af8..a216a4a92e4 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -53,6 +53,96 @@ describe('ProjectModel', () => {
await serverDB.delete(users);
});
+ describe('move', () => {
+ // The manual order as the sidebar reads it: sort_order, unplaced first, newest first.
+ const ids = async (m: ProjectModel) =>
+ (await m.list())
+ .toSorted(
+ (a, b) =>
+ (a.sortOrder ?? -1) - (b.sortOrder ?? -1) ||
+ b.updatedAt.getTime() - a.updatedAt.getTime(),
+ )
+ .map((p) => p.name);
+
+ it('leaves the list API in recently-updated order', async () => {
+ const a = await createProject(model, { name: 'A' });
+ const b = await createProject(model, { name: 'B' });
+ await model.move(a.id, { beforeId: b.id });
+
+ expect((await model.list()).map((p) => p.name)).toEqual(['B', 'A']);
+ });
+
+ it('places a project before or after another and keeps the order', async () => {
+ const a = await createProject(model, { name: 'A' });
+ const b = await createProject(model, { name: 'B' });
+ const c = await createProject(model, { name: 'C' });
+ expect(await ids(model)).toEqual(['C', 'B', 'A']);
+
+ await model.move(a.id, { beforeId: c.id });
+ expect(await ids(model)).toEqual(['A', 'C', 'B']);
+
+ await model.move(a.id, { afterId: b.id });
+ expect(await ids(model)).toEqual(['C', 'B', 'A']);
+ expect((await model.findById(c.id))?.sortOrder).toBe(0);
+ });
+
+ it('lists projects never placed above placed ones', async () => {
+ const a = await createProject(model, { name: 'A' });
+ const b = await createProject(model, { name: 'B' });
+ await model.move(a.id, { beforeId: b.id });
+ await createProject(model, { name: 'New' });
+
+ expect(await ids(model)).toEqual(['New', 'A', 'B']);
+ });
+
+ it('keeps updatedAt so the recently-updated order does not move', async () => {
+ const a = await createProject(model, { name: 'A' });
+ const b = await createProject(model, { name: 'B' });
+ const before = await model.findByIds([a.id, b.id]);
+
+ await model.move(a.id, { beforeId: b.id });
+
+ for (const row of await model.findByIds([a.id, b.id])) {
+ const original = before.find((p) => p.id === row.id)!;
+ expect(row.updatedAt.getTime()).toBe(original.updatedAt.getTime());
+ }
+ });
+
+ it('rejects projects outside the caller scope', async () => {
+ const mine = await createProject(model, { name: 'Mine' });
+ const theirs = await createProject(otherModel, { name: 'Theirs' });
+
+ await expect(model.move(theirs.id, { beforeId: mine.id })).rejects.toThrow(
+ 'Project not found',
+ );
+ expect((await otherModel.findById(theirs.id))?.sortOrder).toBeNull();
+ });
+
+ it("keeps each member's private projects in place when another member moves", async () => {
+ await serverDB.insert(workspaces).values({
+ id: 'project-order-workspace',
+ name: 'Project Order Workspace',
+ primaryOwnerId: userId,
+ slug: 'project-order-workspace',
+ });
+ const alice = new ProjectModel(serverDB, userId, 'project-order-workspace');
+ const bob = new ProjectModel(serverDB, otherUserId, 'project-order-workspace');
+ const publicA = await createProject(alice, { name: 'PublicA' });
+ const publicB = await createProject(alice, { name: 'PublicB' });
+ const privateA = await createProject(alice, { name: 'PrivateA', visibility: 'private' });
+ const privateB = await createProject(bob, { name: 'PrivateB', visibility: 'private' });
+
+ await alice.move(privateA.id, { beforeId: publicA.id });
+ await alice.move(publicB.id, { afterId: publicA.id });
+ expect(await ids(alice)).toEqual(['PrivateA', 'PublicA', 'PublicB']);
+
+ await bob.move(privateB.id, { afterId: publicB.id });
+
+ expect(await ids(alice)).toEqual(['PrivateA', 'PublicA', 'PublicB']);
+ expect(await ids(bob)).toEqual(['PublicA', 'PublicB', 'PrivateB']);
+ });
+ });
+
it('lets several projects share one main agent', async () => {
const shared = await new AgentModel(serverDB, userId).create({ title: 'Planner' });
const first = await createProject(model, { name: 'First' });
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 2f9676858af..fcfaad1ab96 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -369,6 +369,8 @@ export class ProjectModel {
.from(projects)
.leftJoin(agents, eq(agents.id, projects.coordinatorAgentId))
.where(and(this.readable(), statusWhere))
+ // Recently updated first for every caller; the sidebar applies the manual
+ // `sort_order` itself, so the order stays a sidebar view, not the API default.
.orderBy(desc(projects.updatedAt))
.limit(limit)
.offset(offset);
@@ -377,6 +379,72 @@ export class ProjectModel {
return rows.map(({ coordinatorAgent, project }) => ({ ...project, coordinatorAgent }));
}
+ /**
+ * Move one project in the scope's shared manual order, placing it directly
+ * before or after `anchorId` (both must be visible to the caller).
+ *
+ * The order spans every project in the scope — including other members'
+ * private ones the caller cannot see — so the move is applied to that full
+ * list and every row is renumbered. Positions never collide across members,
+ * no caller needs to send the whole list, and a per-scope lock makes sure
+ * concurrent moves in one scope apply one after another. `updated_at` is left alone:
+ * moving a project is not an edit, and the "recently updated" order must not
+ * jump.
+ */
+ async move(id: string, anchor: { afterId: string } | { beforeId: string }) {
+ const anchorId = 'beforeId' in anchor ? anchor.beforeId : anchor.afterId;
+ if (anchorId === id) return;
+
+ await this.db.transaction(async (tx) => {
+ // Serialize moves per scope before reading the order. Locking the rows in
+ // the ordered read itself is not enough: under READ COMMITTED a waiting
+ // transaction would return the order it sorted before the wait.
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${`project-order:${this.workspaceId ?? `user:${this.userId}`}`}))`,
+ );
+
+ const visible = await tx
+ .select({ id: projects.id })
+ .from(projects)
+ .where(and(inArray(projects.id, [id, anchorId]), this.manageable()));
+ if (visible.length !== 2) throw new Error('Project not found');
+
+ const scope = buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ isDeleted: projects.isDeleted,
+ userId: projects.userId,
+ workspaceId: projects.workspaceId,
+ },
+ );
+ const rows = await tx
+ .select({ id: projects.id })
+ .from(projects)
+ .where(scope)
+ .orderBy(sql`${projects.sortOrder} ASC NULLS FIRST`, desc(projects.updatedAt));
+
+ // Either project may have been deleted since the check above.
+ const ids = rows.map((row) => row.id);
+ if (!ids.includes(id) || !ids.includes(anchorId)) throw new Error('Project not found');
+
+ const order = ids.filter((rowId) => rowId !== id);
+ const anchorIndex = order.indexOf(anchorId);
+ order.splice('beforeId' in anchor ? anchorIndex : anchorIndex + 1, 0, id);
+
+ const position = sql.join(
+ order.map((rowId, index) => sql`WHEN ${rowId} THEN ${index}`),
+ sql` `,
+ );
+ await tx
+ .update(projects)
+ .set({
+ sortOrder: sql`(CASE ${projects.id} ${position} END)::integer`,
+ updatedAt: sql`${projects.updatedAt}`,
+ })
+ .where(and(inArray(projects.id, order), scope));
+ });
+ }
+
async update(id: string, input: UpdateProjectInput) {
const [project] = await this.db
.update(projects)
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 2fc5dcdd01c..0887003c08e 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -238,6 +238,11 @@ export default {
'sections.knowledgeBases': 'Libraries',
'sections.conversations': 'Topics',
'sections.tasks': 'Tasks',
+ 'sidebar.reorderError': "Couldn't save the project order. Please try again.",
+ 'sidebar.sort.createdAt': 'Recently created',
+ 'sidebar.sort.manual': 'Custom order',
+ 'sidebar.sort.title': 'Sort projects',
+ 'sidebar.sort.updatedAt': 'Recently updated',
'sidebar.emptyAction': 'Create your first project',
'sidebar.agentsEmpty': 'No agents are connected yet',
'sidebar.conversationsEmpty': 'No project topics yet',
diff --git a/src/features/HomeSidebar/Body/Project/ProjectItem.tsx b/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
index d59ee74f139..4c3161924b5 100644
--- a/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
+++ b/src/features/HomeSidebar/Body/Project/ProjectItem.tsx
@@ -13,6 +13,11 @@ import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import type { ProjectListItem } from '@/store/project';
import { useProjectStore } from '@/store/project';
+// `avatar` is an emoji or image URL, not a component: `Icon` would pass it to
+// createElement as a tag name and crash the whole page.
+export const projectIcon = (project: Pick<ProjectListItem, 'avatar'>) =>
+ project.avatar ? <Avatar avatar={project.avatar} shape={'square'} size={18} /> : FolderClosedIcon;
+
interface ProjectItemProps {
project: ProjectListItem;
}
@@ -67,6 +72,7 @@ const ProjectItem = memo<ProjectItemProps>(({ project }) => {
<NavItem
contextMenuItems={canManage ? menuItems : undefined}
disabled={deleting}
+ icon={projectIcon(project)}
title={project.name}
actions={
canManage ? (
@@ -75,15 +81,6 @@ const ProjectItem = memo<ProjectItemProps>(({ project }) => {
</DropdownMenu>
) : undefined
}
- // `avatar` is an emoji or image URL, not a component: `Icon` would pass it to
- // createElement as a tag name and crash the whole page.
- icon={
- project.avatar ? (
- <Avatar avatar={project.avatar} shape={'square'} size={18} />
- ) : (
- FolderClosedIcon
- )
- }
/>
</WorkspaceLink>
);
diff --git a/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx b/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx
new file mode 100644
index 00000000000..de2332b64e2
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Project/SortableProjectList.tsx
@@ -0,0 +1,207 @@
+'use client';
+
+import {
+ closestCenter,
+ defaultDropAnimationSideEffects,
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ arrayMove,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import { 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 NavItem from '@/features/NavPanel/components/NavItem';
+import { useCanManageProject } from '@/features/Projects/useCanManageProject';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import type { ProjectListItem } from '@/store/project';
+import { useProjectStore } from '@/store/project';
+
+import ProjectItem, { projectIcon } from './ProjectItem';
+import { sortProjects } from './sortProjects';
+
+const styles = stylex.create({
+ overlay: {
+ backgroundColor: cssVar.colorBgElevated,
+ borderRadius: cssVar.borderRadius,
+ boxShadow: cssVar.boxShadowSecondary,
+ cursor: 'grabbing',
+ },
+});
+
+const dropAnimation = {
+ sideEffects: defaultDropAnimationSideEffects({ styles: { active: { opacity: '0.4' } } }),
+};
+
+// The row is a link: a click fires on pointerup after a drag, so swallow the
+// one click that follows a drop instead of navigating to the dragged project.
+const suppressNextClick = () => {
+ const swallow = (event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ window.addEventListener('click', swallow, { capture: true, once: true });
+ // A drop that lands off the row produces no click; don't eat a later one.
+ setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
+};
+
+// Pressing on a row's own buttons (the ⋯ menu) must never pick the row up.
+const startsOnRowAction = (event: Event) =>
+ event.target instanceof Element && !!event.target.closest('.nav-item-actions');
+
+class RowMouseSensor extends MouseSensor {
+ static activators = [
+ {
+ eventName: 'onMouseDown' as const,
+ handler: ({ nativeEvent }: { nativeEvent: MouseEvent }) =>
+ nativeEvent.button === 0 && !startsOnRowAction(nativeEvent),
+ },
+ ];
+}
+
+// A keyboard drag starts only from the focused row itself. Enter / Space on
+// anything inside it — the project link, the ⋯ button — keeps its own meaning
+// (open the project, open the menu).
+const isRowItself = (event: Event) =>
+ event.target instanceof Element &&
+ event.target.getAttribute('aria-roledescription') === 'sortable';
+
+class RowKeyboardSensor extends KeyboardSensor {
+ static activators = KeyboardSensor.activators.map((activator) => ({
+ ...activator,
+ handler: (...args: Parameters<typeof activator.handler>) =>
+ isRowItself(args[0].nativeEvent) && activator.handler(...args),
+ }));
+}
+
+class RowTouchSensor extends TouchSensor {
+ static activators = [
+ {
+ eventName: 'onTouchStart' as const,
+ handler: ({ nativeEvent }: { nativeEvent: TouchEvent }) => !startsOnRowAction(nativeEvent),
+ },
+ ];
+}
+
+const SortableProjectItem = memo<{ project: ProjectListItem }>(({ project }) => {
+ const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ id: project.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}
+ // Stop the browser's native link drag from hijacking the pointer.
+ onDragStart={(e) => e.preventDefault()}
+ >
+ <ProjectItem project={project} />
+ </div>
+ );
+});
+
+SortableProjectItem.displayName = 'SortableProjectItem';
+
+const SortableProjectList = memo<{ projects: ProjectListItem[] }>(({ projects }) => {
+ const { t } = useTranslation('project');
+ const sortBy = useGlobalStore(systemStatusSelectors.projectListSortBy);
+ const moveProject = useProjectStore((s) => s.moveProject);
+ // The manual order is shared by the workspace, so only editors may change it.
+ const canManage = useCanManageProject();
+
+ const [activeId, setActiveId] = useState<string>();
+ const sorted = useMemo(() => sortProjects(projects, sortBy), [projects, sortBy]);
+ const ids = useMemo(() => sorted.map((p) => p.id), [sorted]);
+
+ 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 }),
+ );
+
+ if (sortBy !== 'manual' || !canManage)
+ return sorted.map((project) => <ProjectItem key={project.id} project={project} />);
+
+ const activeProject = activeId ? sorted.find((p) => p.id === activeId) : undefined;
+
+ const handleDragStart = ({ active }: DragStartEvent) => setActiveId(String(active.id));
+
+ const handleDragEnd = async ({ active, over }: DragEndEvent) => {
+ setActiveId(undefined);
+ suppressNextClick();
+ if (!over || active.id === over.id) return;
+
+ try {
+ await moveProject(
+ String(active.id),
+ arrayMove(ids, ids.indexOf(String(active.id)), ids.indexOf(String(over.id))),
+ );
+ } catch (error) {
+ console.error('Failed to save project order', error);
+ toast.error(t('sidebar.reorderError'));
+ }
+ };
+
+ return (
+ <DndContext
+ collisionDetection={closestCenter}
+ sensors={sensors}
+ onDragCancel={() => setActiveId(undefined)}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ {sorted.map((project) => (
+ <SortableProjectItem key={project.id} project={project} />
+ ))}
+ </SortableContext>
+ {createPortal(
+ <DragOverlay dropAnimation={dropAnimation}>
+ {activeProject ? (
+ <div {...stylex.props(styles.overlay)}>
+ <NavItem
+ icon={projectIcon(activeProject)}
+ // The card itself is the surface: no hover tint on top of the white.
+ style={{ backgroundColor: 'transparent' }}
+ title={activeProject.name}
+ />
+ </div>
+ ) : null}
+ </DragOverlay>,
+ document.body,
+ )}
+ </DndContext>
+ );
+});
+
+SortableProjectList.displayName = 'SortableProjectList';
+
+export default SortableProjectList;
diff --git a/src/features/HomeSidebar/Body/Project/index.tsx b/src/features/HomeSidebar/Body/Project/index.tsx
index 5f42a7f99b7..8e57f8c6aaa 100644
--- a/src/features/HomeSidebar/Body/Project/index.tsx
+++ b/src/features/HomeSidebar/Body/Project/index.tsx
@@ -8,11 +8,13 @@ import {
AccordionTrigger,
ActionIcon,
cx,
+ type DropdownItem,
+ DropdownMenu,
Flexbox,
Text,
} from '@lobehub/ui';
-import { ArrowRightIcon, PlusIcon } from 'lucide-react';
-import { memo } from 'react';
+import { ArrowDownUpIcon, ArrowRightIcon, PlusIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
@@ -21,11 +23,16 @@ import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { openCreateProjectModal } from '@/features/Projects/CreateProjectModal';
import { resolveProjectListState } from '@/features/Projects/projectListState';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useGlobalStore } from '@/store/global';
+import type { ProjectListSortBy } from '@/store/global/initialState';
+import { systemStatusSelectors } from '@/store/global/selectors';
import { useLoadedProjectList, useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
-import ProjectItem from './ProjectItem';
+import SortableProjectList from './SortableProjectList';
+
+const SORT_BYS: ProjectListSortBy[] = ['manual', 'createdAt', 'updatedAt'];
interface ProjectProps {
itemKey: string;
@@ -40,6 +47,20 @@ const Project = memo<ProjectProps>(({ itemKey }) => {
(s) => s.useFetchProjectList,
)(enabled);
const state = resolveProjectListState({ error, isHydrated, isValidating, projects });
+ const sortBy = useGlobalStore(systemStatusSelectors.projectListSortBy);
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+
+ const sortMenuItems = useMemo<DropdownItem[]>(
+ () =>
+ SORT_BYS.map((by) => ({
+ checked: sortBy === by,
+ key: by,
+ label: t(`sidebar.sort.${by}`),
+ onCheckedChange: () => updateSystemStatus({ projectListSortBy: by }),
+ type: 'checkbox' as const,
+ })),
+ [sortBy, t, updateSystemStatus],
+ );
if (!enabled) return null;
@@ -59,6 +80,9 @@ const Project = memo<ProjectProps>(({ itemKey }) => {
)}
>
<Flexbox horizontal align="center" gap={2}>
+ <DropdownMenu items={sortMenuItems} placement={'bottomRight'}>
+ <ActionIcon icon={ArrowDownUpIcon} size="small" title={t('sidebar.sort.title')} />
+ </DropdownMenu>
<ActionIcon
icon={ArrowRightIcon}
size="small"
@@ -86,7 +110,7 @@ const Project = memo<ProjectProps>(({ itemKey }) => {
onClick={() => openCreateProjectModal()}
/>
) : (
- projects?.map((project) => <ProjectItem key={project.id} project={project} />)
+ projects && <SortableProjectList projects={projects} />
)}
</AccordionPanel>
</AccordionItem>
diff --git a/src/features/HomeSidebar/Body/Project/sortProjects.test.ts b/src/features/HomeSidebar/Body/Project/sortProjects.test.ts
new file mode 100644
index 00000000000..b7171d8879b
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Project/sortProjects.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { sortProjects } from './sortProjects';
+
+const projects = [
+ { createdAt: '2026-01-02', id: 'a', updatedAt: '2026-03-01' },
+ { createdAt: '2026-01-03', id: 'b', updatedAt: '2026-02-01' },
+ { createdAt: '2026-01-01', id: 'c', updatedAt: '2026-04-01' },
+];
+const ids = (items: { id: string }[]) => items.map((i) => i.id);
+
+describe('sortProjects', () => {
+ it('follows sort_order in manual mode, unplaced projects first and newest first', () => {
+ const placed = [
+ { ...projects[0], sortOrder: 1 },
+ { ...projects[1], sortOrder: 0 },
+ { ...projects[2], sortOrder: null },
+ ];
+ expect(ids(sortProjects(placed, 'manual'))).toEqual(['c', 'b', 'a']);
+ expect(ids(sortProjects(projects, 'manual'))).toEqual(['c', 'a', 'b']);
+ });
+
+ it('puts the newest created project first', () => {
+ expect(ids(sortProjects(projects, 'createdAt'))).toEqual(['b', 'a', 'c']);
+ });
+
+ it('puts the most recently updated project first', () => {
+ expect(ids(sortProjects(projects, 'updatedAt'))).toEqual(['c', 'a', 'b']);
+ });
+});
diff --git a/src/features/HomeSidebar/Body/Project/sortProjects.ts b/src/features/HomeSidebar/Body/Project/sortProjects.ts
new file mode 100644
index 00000000000..b3753e8bac9
--- /dev/null
+++ b/src/features/HomeSidebar/Body/Project/sortProjects.ts
@@ -0,0 +1,27 @@
+import type { ProjectListSortBy } from '@/store/global/initialState';
+
+type SortableProject = {
+ createdAt: Date | string;
+ id: string;
+ sortOrder?: number | null;
+ updatedAt: Date | string;
+};
+
+const time = (value: Date | string) => new Date(value).getTime();
+
+/**
+ * Order the sidebar project list for the chosen view. `manual` follows the
+ * shared `sort_order`, with projects never placed (null) first; the others —
+ * and ties — put the newest first.
+ */
+export const sortProjects = <T extends SortableProject>(
+ projects: T[],
+ sortBy: ProjectListSortBy,
+): T[] => {
+ if (sortBy !== 'manual') return projects.toSorted((a, b) => time(b[sortBy]) - time(a[sortBy]));
+
+ const position = (p: T) => p.sortOrder ?? -1;
+ return projects.toSorted(
+ (a, b) => position(a) - position(b) || time(b.updatedAt) - time(a.updatedAt),
+ );
+};
diff --git a/src/services/project.ts b/src/services/project.ts
index f347bea0f03..178ef04bdd8 100644
--- a/src/services/project.ts
+++ b/src/services/project.ts
@@ -51,6 +51,9 @@ class ProjectService {
delete = async (id: string) => lambdaClient.project.delete.mutate({ id });
+ move = async (id: string, anchor: { afterId: string } | { beforeId: string }) =>
+ lambdaClient.project.move.mutate({ id, ...anchor });
+
create = async (
params: {
avatar?: string;
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 062e10544a2..a023438d4d5 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -162,6 +162,9 @@ export interface AgentDocumentSort {
order: 'asc' | 'desc';
}
+/** How the sidebar project list is ordered; `manual` follows the shared drag order. */
+export type ProjectListSortBy = 'manual' | 'createdAt' | 'updatedAt';
+
export interface SystemStatus {
/**
* Agent Builder panel width
@@ -321,6 +324,11 @@ export interface SystemStatus {
* number of private agents (ungrouped) to display in the Private sidebar bucket
*/
privateAgentPageSize?: number;
+ /**
+ * Order of the sidebar project list. Device-local view setting; the manual
+ * order itself is shared and lives on `projects.sort_order`.
+ */
+ projectListSortBy?: ProjectListSortBy;
/**
* Per byProject group (keyed by the group id, e.g. `project-id:<id>`): how its
* topics are sectioned. Absent means `none`.
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 34d3ba795cf..c524acd6da9 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -4,6 +4,7 @@ import type {
AgentDocumentSort,
GlobalState,
ModelDetailPanelExpandedKey,
+ ProjectListSortBy,
ProjectTopicSubGroupMode,
SystemStatus,
WorkspaceOverridableField,
@@ -446,6 +447,8 @@ const DEFAULT_AGENT_DOCUMENT_SORT: AgentDocumentSort = {
foldersFirst: true,
order: 'asc',
};
+const projectListSortBy = (s: GlobalState): ProjectListSortBy =>
+ s.status.projectListSortBy ?? 'manual';
const agentDocumentSort = (s: GlobalState): AgentDocumentSort =>
s.status.agentDocumentSort ?? DEFAULT_AGENT_DOCUMENT_SORT;
const agentListViewOptions = (s: GlobalState) => s.status.agentListViewOptions;
@@ -497,6 +500,7 @@ const homeSelectedAgentId = (s: GlobalState) => s.status.homeSelectedAgentId;
export const systemStatusSelectors = {
agentBuilderPanelWidth,
agentDocumentSort,
+ projectListSortBy,
agentListExpandedGroupKeys,
agentListSidebarSectionCollapsed,
agentListViewMode,
diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.ts
index 2e25caef760..d981e432d5d 100644
--- a/src/store/project/store.test.ts
+++ b/src/store/project/store.test.ts
@@ -49,6 +49,7 @@ vi.mock('@/services/project', () => ({
delete: vi.fn(),
detail: vi.fn(),
listAll: vi.fn(),
+ move: vi.fn(),
removeAgent: vi.fn(),
replaceCoordinator: vi.fn(),
update: vi.fn(),
@@ -168,6 +169,122 @@ describe('project store replicas', () => {
await waitFor(() => expect(useProjectStore.getState().projectListMap.all).toBeUndefined());
});
+ describe('moveProject', () => {
+ const deferred = () => {
+ let resolve!: (value: unknown) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+ };
+
+ const loadList = async (...ids: string[]) => {
+ vi.mocked(projectService.listAll).mockResolvedValue(ok(ids.map((id) => project(id))) as any);
+ renderHook(() => useProjectStore((s) => s.useFetchProjectList)(true), { wrapper });
+ await waitFor(() =>
+ expect(useProjectStore.getState().projectListMap[PROJECT_LIST_KEY]).toHaveLength(
+ ids.length,
+ ),
+ );
+ };
+ // Positions, not array order: the shared list keeps its own order.
+ const names = () =>
+ useProjectStore
+ .getState()
+ .projectListMap[PROJECT_LIST_KEY]?.toSorted(
+ (a, b) => (a.sortOrder ?? -1) - (b.sortOrder ?? -1),
+ )
+ .map((p) => p.id);
+
+ it('moves the row at once and sends queued moves only after the earlier one lands', async () => {
+ await loadList('a', 'b', 'c');
+ const first = deferred();
+ vi.mocked(projectService.move)
+ .mockReturnValueOnce(first.promise as any)
+ .mockResolvedValueOnce(ok(undefined) as any);
+ const { moveProject } = useProjectStore.getState();
+
+ const one = moveProject('c', ['c', 'a', 'b']);
+ const two = moveProject('b', ['b', 'c', 'a']);
+
+ expect(names()).toEqual(['b', 'c', 'a']);
+ await Promise.resolve();
+ expect(projectService.move).toHaveBeenCalledTimes(1);
+ expect(projectService.move).toHaveBeenLastCalledWith('c', { beforeId: 'a' });
+
+ first.resolve(ok(undefined));
+ await Promise.all([one, two]);
+ expect(projectService.move).toHaveBeenCalledTimes(2);
+ expect(projectService.move).toHaveBeenLastCalledWith('b', { beforeId: 'c' });
+ });
+
+ it('keeps the shared list order and reads back the server once the queue is idle', async () => {
+ await loadList('a', 'b', 'c');
+ vi.mocked(projectService.move).mockResolvedValue(ok(undefined) as any);
+ const fetchesBefore = vi.mocked(projectService.listAll).mock.calls.length;
+ const serverOrder = [
+ { ...project('a'), sortOrder: 1 },
+ { ...project('b'), sortOrder: 2 },
+ { ...project('c'), sortOrder: 0 },
+ ];
+ vi.mocked(projectService.listAll).mockResolvedValue(ok(serverOrder) as any);
+
+ await useProjectStore.getState().moveProject('c', ['c', 'a', 'b']);
+
+ const raw = () =>
+ useProjectStore.getState().projectListMap[PROJECT_LIST_KEY]?.map((p) => p.id);
+ expect(raw()).toEqual(['a', 'b', 'c']);
+ expect(names()).toEqual(['c', 'a', 'b']);
+ await waitFor(() =>
+ expect(vi.mocked(projectService.listAll).mock.calls.length).toBe(fetchesBefore + 1),
+ );
+ });
+
+ it('drops moves queued behind a failed one and refetches the server order', async () => {
+ await loadList('a', 'b', 'c');
+ const first = deferred();
+ vi.mocked(projectService.move).mockReturnValueOnce(first.promise as any);
+ const { moveProject } = useProjectStore.getState();
+
+ const one = moveProject('c', ['c', 'a', 'b']);
+ const two = moveProject('b', ['b', 'c', 'a']);
+ vi.mocked(projectService.listAll).mockResolvedValue(
+ ok(['a', 'b', 'c'].map((id) => project(id))) as any,
+ );
+
+ first.reject(new Error('boom'));
+ await expect(one).rejects.toThrow('boom');
+ await two;
+
+ expect(projectService.move).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(names()).toEqual(['a', 'b', 'c']));
+ });
+
+ it('ignores a drop made while a failed move is being reconciled', async () => {
+ await loadList('a', 'b', 'c');
+ vi.mocked(projectService.move).mockRejectedValueOnce(new Error('boom'));
+ const refetch = deferred();
+ const { moveProject } = useProjectStore.getState();
+
+ const failed = moveProject('c', ['c', 'a', 'b']);
+ vi.mocked(projectService.listAll).mockReturnValue(refetch.promise as any);
+ await vi.waitFor(() => expect(projectService.listAll).toHaveBeenCalledTimes(2));
+
+ // The list still shows the failed optimistic order while the refetch is in flight.
+ const late = moveProject('c', ['a', 'b', 'c']);
+ expect(names()).toEqual(['c', 'a', 'b']);
+
+ refetch.resolve(ok(['a', 'b', 'c'].map((id) => project(id))));
+ await expect(failed).rejects.toThrow('boom');
+ await late;
+
+ expect(projectService.move).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(names()).toEqual(['a', 'b', 'c']));
+ });
+ });
+
describe('mutations', () => {
const seed = () => {
const original = project('p1', 'Original');
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index 6f1d800af65..11c788255ef 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -52,6 +52,12 @@ interface ProjectStore extends ProjectStoreState {
slug?: string;
}) => Promise<ProjectListItem>;
deleteProject: (id: string) => Promise<void>;
+ /**
+ * Drop a project at a new place in the shared manual order. `ids` is the list
+ * as the user now sees it; the list moves at once and the write is queued
+ * behind earlier moves so they land in drop order.
+ */
+ moveProject: (id: string, ids: string[]) => Promise<void>;
refreshProjectList: () => Promise<void>;
removeProjectAgent: (projectId: string, agentId: string) => Promise<void>;
removeProjectKnowledgeBase: (projectId: string, knowledgeBaseId: string) => Promise<void>;
@@ -117,6 +123,10 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(
const projectEntity = linkReplicaEntity<ProjectListItem>([list, detail]);
const refreshList = () => list.revalidate(PROJECT_LIST_KEY);
+ let moveQueue: Promise<unknown> = Promise.resolve();
+ let moveGeneration = 0;
+ let reconciling: Promise<unknown> | undefined;
+ let pendingMoves = 0;
// A project page is keyed by its route param, so one project can sit under
// both its id and its slug.
@@ -174,6 +184,57 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(
refreshProjectList: async () => {
await refreshList();
},
+ moveProject: (id, ids) => {
+ // After a failed move the visible order is stale until the refetch
+ // lands; a drop made in that window would be computed against it, so
+ // ignore it — the list snaps back to the server order.
+ if (reconciling) return reconciling.then(() => undefined);
+
+ const index = ids.indexOf(id);
+ const anchor =
+ index < ids.length - 1 ? { beforeId: ids[index + 1] } : { afterId: ids[index - 1] };
+ // Only the positions change: the list itself is shared with pages that
+ // show it in their own order, and the sidebar sorts by `sortOrder`.
+ const position = new Map(ids.map((itemId, i) => [itemId, i]));
+ list.update(PROJECT_LIST_KEY, (items) =>
+ items?.map((item) =>
+ position.has(item.id) ? { ...item, sortOrder: position.get(item.id)! } : item,
+ ),
+ );
+ pendingMoves += 1;
+
+ // Moves are computed against the order the user sees, which assumes
+ // every earlier move landed. Once one fails, the queued ones are stale:
+ // drop them, and hold the queue until the refetch shows the real order.
+ const generation = moveGeneration;
+ const write = moveQueue.then(() =>
+ generation === moveGeneration ? projectService.move(id, anchor) : undefined,
+ );
+ moveQueue = write.then(
+ () => {
+ pendingMoves -= 1;
+ // Once the queue is idle, read back the server order: a list
+ // revalidation that raced this write, or another member's move, may
+ // have left the local positions behind.
+ if (pendingMoves === 0 && !reconciling) void refreshList();
+ },
+ () => {
+ pendingMoves -= 1;
+ moveGeneration += 1;
+ reconciling ??= refreshList().finally(() => {
+ reconciling = undefined;
+ });
+ return reconciling;
+ },
+ );
+ return write.then(
+ () => undefined,
+ async (error) => {
+ await moveQueue;
+ throw error;
+ },
+ );
+ },
removeProjectAgent: async (projectId, agentId) => {
patchDetail(projectId, (value) => ({
...value,