🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-documents): sort the document tree by name, created or modified time (#20926)
Arvin Xu01278af203af
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 0299601cbce..6b4cd761fcc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3262,6 +3262,15 @@"workingPanel.resources.tree.newSubDocument": "New sub-document","workingPanel.resources.tree.parentMissing": "Parent folder is unavailable","workingPanel.resources.tree.rename": "Rename",+ "workingPanel.resources.tree.sort.asc": "Ascending",+ "workingPanel.resources.tree.sort.by": "Sort by",+ "workingPanel.resources.tree.sort.createdAt": "Date created",+ "workingPanel.resources.tree.sort.desc": "Descending",+ "workingPanel.resources.tree.sort.foldersFirst": "Folders first",+ "workingPanel.resources.tree.sort.name": "Name",+ "workingPanel.resources.tree.sort.order": "Order",+ "workingPanel.resources.tree.sort.title": "Sort",+ "workingPanel.resources.tree.sort.updatedAt": "Date modified","workingPanel.resources.tree.untitledDocument": "Untitled document","workingPanel.resources.tree.untitledFolder": "Untitled folder","workingPanel.resources.tree.uploadError": "Failed to upload",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 1beeeaa254c..3cf1f9444ea 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3262,6 +3262,15 @@"workingPanel.resources.tree.newSubDocument": "新建子文档","workingPanel.resources.tree.parentMissing": "上级目录不可用","workingPanel.resources.tree.rename": "重命名",+ "workingPanel.resources.tree.sort.asc": "升序",+ "workingPanel.resources.tree.sort.by": "排序方式",+ "workingPanel.resources.tree.sort.createdAt": "创建时间",+ "workingPanel.resources.tree.sort.desc": "降序",+ "workingPanel.resources.tree.sort.foldersFirst": "文件夹置顶",+ "workingPanel.resources.tree.sort.name": "名称",+ "workingPanel.resources.tree.sort.order": "顺序",+ "workingPanel.resources.tree.sort.title": "排序",+ "workingPanel.resources.tree.sort.updatedAt": "更新时间","workingPanel.resources.tree.untitledDocument": "未命名文档","workingPanel.resources.tree.untitledFolder": "未命名文件夹","workingPanel.resources.tree.uploadError": "上传失败",diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.list.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.list.test.tsnew file mode 100644index 00000000000..27f4a2de0c5--- /dev/null+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.list.test.ts@@ -0,0 +1,45 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, documents, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { AgentDocumentModel } from '../agentDocument';++const userId = 'agent-document-list-test-user';+const agentId = 'agent-document-list-test-agent';++let agentDocumentModel: AgentDocumentModel;+const serverDB: LobeChatDatabase = await getTestDB();++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }]);+ await serverDB.insert(agents).values([{ id: agentId, userId }]);+ agentDocumentModel = new AgentDocumentModel(serverDB, userId);+});++describe('AgentDocumentModel list timestamps', () => {+ // The document tree sorts by these; a content edit only touches `documents`.+ it('returns the backing document creation and last-change times', async () => {+ const created = await agentDocumentModel.create(agentId, 'notes.md', 'content', {+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ });+ const createdAt = new Date('2025-12-01T00:00:00.000Z');+ const documentUpdatedAt = new Date('2026-02-01T00:00:00.000Z');+ await serverDB+ .update(documents)+ .set({ createdAt, updatedAt: documentUpdatedAt })+ .where(eq(documents.id, created.documentId));++ const [byAgent] = await agentDocumentModel.listByAgent(agentId);+ const [byIds] = await agentDocumentModel.listByDocumentIds(agentId, [created.documentId]);++ for (const item of [byAgent, byIds]) {+ expect(item.createdAt).toEqual(createdAt);+ expect(item.documentUpdatedAt).toEqual(documentUpdatedAt);+ expect(item.updatedAt).toEqual(new Date('2026-01-01T00:00:00.000Z'));+ }+ });+});diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex f8c95d2e1e2..4cbdfcc7165 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -91,9 +91,29 @@ interface ConvertAgentDocumentToSkillIndexParams {title: string;}+/** Columns of one document-tree row (agent binding joined to its document). */+const listItemColumns = {+ createdAt: documents.createdAt,+ description: documents.description,+ documentId: agentDocuments.documentId,+ documentUpdatedAt: documents.updatedAt,+ fileId: documents.fileId,+ fileType: documents.fileType,+ filename: documents.filename,+ id: agentDocuments.id,+ parentId: documents.parentId,+ policy: agentDocuments.policy,+ sourceType: documents.sourceType,+ templateId: agentDocuments.templateId,+ title: documents.title,+ updatedAt: agentDocuments.updatedAt,+};+interface AgentDocumentListQueryRow {+ createdAt: Date;description: string | null;documentId: string;+ documentUpdatedAt: Date;fileId: string | null;filename: string | null;fileType: string;@@ -273,8 +293,10 @@ export class AgentDocumentModel {const filename = row.filename ?? '';const policy = (row.policy as AgentDocumentPolicy | null) ?? null;const item = {+ createdAt: row.createdAt,description: row.description ?? null,documentId: row.documentId,+ documentUpdatedAt: row.documentUpdatedAt,fileId: row.fileId,fileType: row.fileType,filename,@@ -1161,20 +1183,7 @@ export class AgentDocumentModel {const parentId = options?.parentId;const excludeWeb = options?.excludeWeb;const results = await this.db- .select({- description: documents.description,- documentId: agentDocuments.documentId,- fileId: documents.fileId,- fileType: documents.fileType,- filename: documents.filename,- id: agentDocuments.id,- parentId: documents.parentId,- policy: agentDocuments.policy,- sourceType: documents.sourceType,- templateId: agentDocuments.templateId,- title: documents.title,- updatedAt: agentDocuments.updatedAt,- })+ .select(listItemColumns).from(agentDocuments).innerJoin(documents, eq(agentDocuments.documentId, documents.id)).where(@@ -1346,20 +1355,7 @@ export class AgentDocumentModel {const sourceType = options?.sourceType;const results = await this.db- .select({- description: documents.description,- documentId: agentDocuments.documentId,- fileId: documents.fileId,- fileType: documents.fileType,- filename: documents.filename,- id: agentDocuments.id,- parentId: documents.parentId,- policy: agentDocuments.policy,- sourceType: documents.sourceType,- templateId: agentDocuments.templateId,- title: documents.title,- updatedAt: agentDocuments.updatedAt,- })+ .select(listItemColumns).from(agentDocuments).innerJoin(documents, eq(agentDocuments.documentId, documents.id)).where(diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.tsindex 347bc62af3e..8dca1f04167 100644--- a/packages/database/src/models/agentDocuments/types.ts+++ b/packages/database/src/models/agentDocuments/types.ts@@ -85,8 +85,15 @@ export interface AgentDocumentWithRules extends AgentDocument, AgentDocumentDeri/** A document-tree entry with its optional original uploaded file. */export interface AgentDocumentListItem extends AgentDocumentDerivedFields {+ /** When the backing document was created. */+ createdAt: Date;description: string | null;documentId: string;+ /**+ * When the backing document last changed (content, title, …). `updatedAt` is+ * the agent binding's, which content edits do not touch.+ */+ documentUpdatedAt: Date;/** Original file to preview; absent for editable agent documents. */fileId?: string | null;filename: string;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 34ee1d2db61..d23e2ad8727 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3357,6 +3357,15 @@ export default {'workingPanel.resources.tree.newSubDocument': 'New sub-document','workingPanel.resources.tree.newFolder': 'New folder','workingPanel.resources.tree.rename': 'Rename',+ 'workingPanel.resources.tree.sort.asc': 'Ascending',+ 'workingPanel.resources.tree.sort.by': 'Sort by',+ 'workingPanel.resources.tree.sort.createdAt': 'Date created',+ 'workingPanel.resources.tree.sort.desc': 'Descending',+ 'workingPanel.resources.tree.sort.foldersFirst': 'Folders first',+ 'workingPanel.resources.tree.sort.name': 'Name',+ 'workingPanel.resources.tree.sort.order': 'Order',+ 'workingPanel.resources.tree.sort.title': 'Sort',+ 'workingPanel.resources.tree.sort.updatedAt': 'Date modified','workingPanel.resources.tree.untitledDocument': 'Untitled document','workingPanel.resources.tree.untitledFolder': 'Untitled folder','workingPanel.resources.tree.uploadError': 'Failed to upload',diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsxindex 76e2d8b25bc..40c58861a4b 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx@@ -1,10 +1,12 @@import { Flexbox, Icon } from '@lobehub/ui';import { ActionIcon, type DropdownItem, DropdownMenu, Text } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';-import { FilePlusIcon, FileUp, FolderPlusIcon, PlusIcon } from 'lucide-react';+import { ArrowDownUpIcon, FilePlusIcon, FileUp, FolderPlusIcon, PlusIcon } from 'lucide-react';import { memo, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import type { AgentDocumentSort } from '@/store/global/initialState';+const styles = createStaticStyles(({ css, cssVar }) => ({toolbar: css`/* Title on the column of the panel tabs' icons; the + stays on the row edge. */@@ -17,14 +19,19 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));+const SORT_FIELDS = ['name', 'createdAt', 'updatedAt'] as const;+const SORT_ORDERS = ['asc', 'desc'] as const;+interface Props {onCreateDocument: () => void;onCreateFolder: () => void;+ onSortChange: (sort: AgentDocumentSort) => void;onUploadFiles: (files: File[]) => void;+ sort: AgentDocumentSort;}const DocumentExplorerToolbar = memo<Props>(- ({ onCreateDocument, onCreateFolder, onUploadFiles }) => {+ ({ onCreateDocument, onCreateFolder, onSortChange, onUploadFiles, sort }) => {const { t } = useTranslation('chat');const fileInputRef = useRef<HTMLInputElement>(null);const createMenuItems = useMemo<DropdownItem[]>(@@ -52,6 +59,45 @@ const DocumentExplorerToolbar = memo<Props>([onCreateDocument, onCreateFolder, t],);+ const sortMenuItems = useMemo<DropdownItem[]>(+ () => [+ {+ children: SORT_FIELDS.map((by) => ({+ checked: sort.by === by,+ key: `sort-by-${by}`,+ label: t(`workingPanel.resources.tree.sort.${by}`),+ onCheckedChange: () => onSortChange({ ...sort, by }),+ type: 'checkbox' as const,+ })),+ key: 'sort-by',+ label: t('workingPanel.resources.tree.sort.by'),+ type: 'group' as const,+ },+ { type: 'divider' as const },+ {+ children: SORT_ORDERS.map((order) => ({+ checked: sort.order === order,+ key: `sort-order-${order}`,+ label: t(`workingPanel.resources.tree.sort.${order}`),+ onCheckedChange: () => onSortChange({ ...sort, order }),+ type: 'checkbox' as const,+ })),+ key: 'sort-order',+ label: t('workingPanel.resources.tree.sort.order'),+ type: 'group' as const,+ },+ { type: 'divider' as const },+ {+ checked: sort.foldersFirst,+ key: 'sort-folders-first',+ label: t('workingPanel.resources.tree.sort.foldersFirst'),+ onCheckedChange: (foldersFirst: boolean) => onSortChange({ ...sort, foldersFirst }),+ type: 'checkbox' as const,+ },+ ],+ [onSortChange, sort, t],+ );+return (<Flexboxhorizontal@@ -62,13 +108,22 @@ const DocumentExplorerToolbar = memo<Props>(<Text className={styles.title} type={'secondary'}>{t('workingPanel.resources.filter.documents')}</Text>- <DropdownMenu items={createMenuItems} placement={'bottomRight'}>- <ActionIcon- icon={PlusIcon}- size={'small'}- title={t('workingPanel.resources.tree.create')}- />- </DropdownMenu>+ <Flexbox horizontal align={'center'}>+ <DropdownMenu items={sortMenuItems} placement={'bottomRight'}>+ <ActionIcon+ icon={ArrowDownUpIcon}+ size={'small'}+ title={t('workingPanel.resources.tree.sort.title')}+ />+ </DropdownMenu>+ <DropdownMenu items={createMenuItems} placement={'bottomRight'}>+ <ActionIcon+ icon={PlusIcon}+ size={'small'}+ title={t('workingPanel.resources.tree.create')}+ />+ </DropdownMenu>+ </Flexbox><inputhiddenmultiplediff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex 985677440b5..0f84b9aac4e 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -36,6 +36,9 @@ import {import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';import { agentDocumentService } from '@/services/agentDocument';+import { useGlobalStore } from '@/store/global';+import type { AgentDocumentSort } from '@/store/global/initialState';+import { systemStatusSelectors } from '@/store/global/selectors';import { openConvertToSkillModal, slugifySkillName } from './ConvertToSkillModal';import DocumentExplorerToolbar from './DocumentExplorerToolbar';@@ -43,6 +46,7 @@ import { useDocumentTreeOps } from './hooks/useDocumentTreeOps';import type { AgentDocumentItem } from './types';import { isOrphanSkillBundleItem } from './types';import { canDropDocument } from './utils/canDrop';+import { createDocumentComparator } from './utils/sortDocuments';const SKILL_INDEX_FILENAME = 'SKILL.md';const FILE_TREE_HOST_TAG = 'file-tree-container';@@ -197,6 +201,14 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen[documents, parentDocumentIds, resolveNodeName, resolveParentRowId],);+ const sort = useGlobalStore(systemStatusSelectors.agentDocumentSort);+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ const handleSortChange = useCallback(+ (agentDocumentSort: AgentDocumentSort) => updateSystemStatus({ agentDocumentSort }),+ [updateSystemStatus],+ );+ const compareNodes = useMemo(() => createDocumentComparator(sort), [sort]);+const treeStyleVars = useMemo(() =>getExplorerTreeStyleVars({@@ -503,8 +515,10 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumenconst toolbar = (<DocumentExplorerToolbar+ sort={sort}onCreateDocument={() => handleCreateDocument(null)}onCreateFolder={() => handleCreateFolder(null)}+ onSortChange={handleSortChange}onUploadFiles={(files) => void ops.uploadFiles(null, files)}/>);@@ -540,6 +554,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumenitemHeight={DOCUMENT_TREE_LAYOUT.itemHeight}nodes={nodes}ref={treeRef}+ sort={compareNodes}style={{ height: '100%' }}unsafeCSS={DOCUMENT_TREE_UNSAFE_CSS}onCommitRename={handleCommitRename}diff --git a/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts b/src/features/AgentDocumentsExplorer/utils/pendingDocument.tsindex 9a14d8d22ff..ecc6f5fa1da 100644--- a/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts+++ b/src/features/AgentDocumentsExplorer/utils/pendingDocument.ts@@ -25,8 +25,10 @@ export const makePendingDocument = ({const now = new Date();return {category: AGENT_DOCUMENT_CATEGORY,+ createdAt: now,description: null,documentId: id,+ documentUpdatedAt: now,filename: title,fileType: isFolder ? CUSTOM_FOLDER_FILE_TYPE : CUSTOM_DOCUMENT_FILE_TYPE,id,diff --git a/src/features/AgentDocumentsExplorer/utils/sortDocuments.test.ts b/src/features/AgentDocumentsExplorer/utils/sortDocuments.test.tsnew file mode 100644index 00000000000..2d03413f421--- /dev/null+++ b/src/features/AgentDocumentsExplorer/utils/sortDocuments.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest';++import type { ExplorerTreeNode } from '@/features/ExplorerTree';+import type { AgentDocumentSort } from '@/store/global/initialState';++import type { AgentDocumentItem } from '../types';+import { createDocumentComparator } from './sortDocuments';++const node = (+ name: string,+ options: {+ appearance?: 'file';+ createdAt?: string;+ documentUpdatedAt?: string;+ isFolder?: boolean;+ updatedAt?: string;+ } = {},+): ExplorerTreeNode<AgentDocumentItem> => ({+ appearance: options.appearance,+ data: {+ createdAt: new Date(options.createdAt ?? '2026-01-01'),+ documentUpdatedAt: new Date(options.documentUpdatedAt ?? '2026-01-01'),+ updatedAt: new Date(options.updatedAt ?? '2026-01-01'),+ } as AgentDocumentItem,+ id: name,+ isFolder: options.isFolder,+ name,+});++const order = (sort: AgentDocumentSort, nodes: ExplorerTreeNode<AgentDocumentItem>[]) =>+ nodes+ .slice()+ .sort(createDocumentComparator(sort))+ .map((n) => n.name);++describe('createDocumentComparator', () => {+ it('compares names numerically and case-insensitively, folders first', () => {+ const nodes = [node('Week 10'), node('week 2'), node('Archive', { isFolder: true })];+ expect(order({ by: 'name', foldersFirst: true, order: 'asc' }, nodes)).toEqual([+ 'Archive',+ 'week 2',+ 'Week 10',+ ]);+ expect(order({ by: 'name', foldersFirst: false, order: 'desc' }, nodes)).toEqual([+ 'Week 10',+ 'week 2',+ 'Archive',+ ]);+ });++ // The default sort must draw what the tree drew before the sort menu existed.+ it('keeps the tree default name order across scripts: Latin, then CJK, then emoji', () => {+ const nodes = [+ node('📔 每日日记.md'),+ node('周报.md'),+ node('alpha 方案.md'),+ node('Week 2.md'),+ ];+ expect(order({ by: 'name', foldersFirst: true, order: 'asc' }, nodes)).toEqual([+ 'alpha 方案.md',+ 'Week 2.md',+ '周报.md',+ '📔 每日日记.md',+ ]);+ });++ it('sorts by time with the name breaking ties', () => {+ const nodes = [+ node('old', { updatedAt: '2026-01-01' }),+ node('b-new', { updatedAt: '2026-03-01' }),+ node('a-new', { updatedAt: '2026-03-01' }),+ ];+ expect(order({ by: 'updatedAt', foldersFirst: true, order: 'desc' }, nodes)).toEqual([+ 'a-new',+ 'b-new',+ 'old',+ ]);+ });++ it('counts a content edit, which only touches the backing document, as an update', () => {+ const nodes = [+ node('renamed', { updatedAt: '2026-02-01' }),+ node('edited', { documentUpdatedAt: '2026-03-01' }),+ ];+ expect(order({ by: 'updatedAt', foldersFirst: true, order: 'desc' }, nodes)).toEqual([+ 'edited',+ 'renamed',+ ]);+ });++ it('keeps a document holding sub-documents among the files', () => {+ const nodes = [+ node('b', { createdAt: '2026-02-01' }),+ node('a-parent', { appearance: 'file', createdAt: '2026-03-01', isFolder: true }),+ node('z-folder', { createdAt: '2026-01-01', isFolder: true }),+ ];+ expect(order({ by: 'createdAt', foldersFirst: true, order: 'asc' }, nodes)).toEqual([+ 'z-folder',+ 'b',+ 'a-parent',+ ]);+ });+});diff --git a/src/features/AgentDocumentsExplorer/utils/sortDocuments.ts b/src/features/AgentDocumentsExplorer/utils/sortDocuments.tsnew file mode 100644index 00000000000..fe716d15b9b--- /dev/null+++ b/src/features/AgentDocumentsExplorer/utils/sortDocuments.ts@@ -0,0 +1,72 @@+import type { ExplorerTreeNode, ExplorerTreeNodeComparator } from '@/features/ExplorerTree';+import type { AgentDocumentSort } from '@/store/global/initialState';++import type { AgentDocumentItem } from '../types';++type DocumentNode = ExplorerTreeNode<AgentDocumentItem>;++// Dates arrive as Date over superjson; tolerate a serialized string too.+const toTime = (value: Date | string | null | undefined): number =>+ value ? new Date(value).getTime() || 0 : 0;++const timeOf = (node: DocumentNode, by: 'createdAt' | 'updatedAt'): number => {+ const doc = node.data;+ if (!doc) return 0;+ if (by === 'createdAt') return toTime(doc.createdAt);+ // A rename or move touches the binding; a content edit only the document.+ return Math.max(toTime(doc.documentUpdatedAt), toTime(doc.updatedAt));+};++// A document holding sub-documents is a tree container drawn as a file; it+// sorts with the files, not the folders.+const isFolderRow = (node: DocumentNode) => !!node.isFolder && node.appearance !== 'file';++// Lower-cased text runs and numeric runs, so `week 2` sorts before `Week 10`.+const toNaturalTokens = (value: string): (number | string)[] =>+ value+ .toLowerCase()+ .split(/(\d+)/)+ .filter(Boolean)+ .map((token) => (/^\d+$/.test(token) ? Number(token) : token));++/**+ * The tree's own default name order (@pierre/trees): case-insensitive, numbers+ * by value, everything else by code unit. Keeping it means the default sort+ * draws exactly what the tree drew before a sort menu existed.+ */+export const compareNames = (a: string, b: string): number => {+ const left = toNaturalTokens(a);+ const right = toNaturalTokens(b);+ for (let index = 0; index < Math.min(left.length, right.length); index += 1) {+ const l = left[index];+ const r = right[index];+ if (l === r) continue;+ if (typeof l === 'number' && typeof r === 'number') return l - r;+ return String(l) < String(r) ? -1 : 1;+ }+ if (left.length !== right.length) return left.length - right.length;+ if (a === b) return 0;+ return a < b ? -1 : 1;+};++/**+ * Orders document tree siblings. Names use the tree's default order; time sorts+ * fall back to the name on ties.+ */+export const createDocumentComparator = (+ sort: AgentDocumentSort,+): ExplorerTreeNodeComparator<AgentDocumentItem> => {+ const direction = sort.order === 'asc' ? 1 : -1;++ return (a, b) => {+ if (sort.foldersFirst) {+ const aFolder = isFolderRow(a);+ if (aFolder !== isFolderRow(b)) return aFolder ? -1 : 1;+ }+ const byName = compareNames(a.name, b.name);+ const field = sort.by;+ if (field === 'name') return byName * direction;+ const byTime = timeOf(a, field) - timeOf(b, field);+ return byTime * direction || byName;+ };+};diff --git a/src/features/ExplorerTree/adapter/sort.test.ts b/src/features/ExplorerTree/adapter/sort.test.tsnew file mode 100644index 00000000000..5cf65d95001--- /dev/null+++ b/src/features/ExplorerTree/adapter/sort.test.ts@@ -0,0 +1,50 @@+import type { FileTreeSortEntry } from '@pierre/trees';+import { describe, expect, it } from 'vitest';++import type { ExplorerTreeNode, ExplorerTreeNodeComparator } from '../types';+import { normalizeTree } from './normalize';+import { buildSortSignature, createPathComparator } from './sort';++const nodes: ExplorerTreeNode<number>[] = [+ { data: 2, id: 'docs', isFolder: true, name: 'docs', parentId: null },+ { data: 1, id: 'b', name: 'b.md', parentId: null },+ { data: 1, id: 'x', name: 'x.md', parentId: 'docs' },+];+const tree = normalizeTree(nodes);+const byData: ExplorerTreeNodeComparator<number> = (a, b) => a.data! - b.data!;++const entry = (path: string): FileTreeSortEntry => {+ const isDirectory = path.endsWith('/');+ const segments = (isDirectory ? path.slice(0, -1) : path).split('/');+ return { basename: segments.at(-1)!, depth: segments.length, isDirectory, path, segments };+};++describe('createPathComparator', () => {+ const compare = createPathComparator(+ () => tree,+ () => byData,+ );++ it('orders full paths by the ancestors where they diverge', () => {+ expect(compare(entry('docs/x.md'), entry('b.md'))).toBeGreaterThan(0);+ expect(compare(entry('b.md'), entry('docs/'))).toBeLessThan(0);+ });++ it('puts a parent before its descendants', () => {+ expect(compare(entry('docs/'), entry('docs/x.md'))).toBeLessThan(0);+ expect(compare(entry('docs/x.md'), entry('docs/'))).toBeGreaterThan(0);+ });++ it('falls back to folders first for rows the nodes do not know', () => {+ expect(compare(entry('zzz.md'), entry('docs/'))).toBeGreaterThan(0);+ });+});++describe('buildSortSignature', () => {+ it('changes only when the sibling order changes', () => {+ const signature = buildSortSignature(tree, byData);+ expect(buildSortSignature(normalizeTree([...nodes].reverse()), byData)).toBe(signature);+ expect(buildSortSignature(tree, (a, b) => byData(b, a))).not.toBe(signature);+ expect(buildSortSignature(tree, undefined)).toBe('');+ });+});diff --git a/src/features/ExplorerTree/adapter/sort.ts b/src/features/ExplorerTree/adapter/sort.tsnew file mode 100644index 00000000000..21f1d27df6a--- /dev/null+++ b/src/features/ExplorerTree/adapter/sort.ts@@ -0,0 +1,75 @@+import type { FileTreeSortComparator, FileTreeSortEntry } from '@pierre/trees';++import type { ExplorerTreeNode, ExplorerTreeNodeComparator } from '../types';+import type { NormalizedTree } from './normalize';++const compareFallback = (left: FileTreeSortEntry, right: FileTreeSortEntry): number => {+ if (left.isDirectory !== right.isDirectory) return left.isDirectory ? -1 : 1;+ return left.basename.localeCompare(right.basename);+};++// The tree path of the ancestor (or the entry itself) at `depthIndex`.+const pathAt = (entry: FileTreeSortEntry, depthIndex: number): string => {+ const isLast = depthIndex === entry.segments.length - 1;+ const joined = entry.segments.slice(0, depthIndex + 1).join('/');+ return !isLast || entry.isDirectory ? `${joined}/` : joined;+};++/**+ * Adapts a node comparator to @pierre/trees. The tree calls it on sibling rows+ * when it inserts one, but on arbitrary full paths when it builds the store+ * from a path list, so two paths are ordered by the first ancestors where they+ * diverge (a parent always comes before its own descendants).+ */+export const createPathComparator =+ <TData>(+ getTree: () => NormalizedTree<TData>,+ getCompare: () => ExplorerTreeNodeComparator<TData> | undefined,+ ): FileTreeSortComparator =>+ (left, right) => {+ const shared = Math.min(left.segments.length, right.segments.length);+ let index = 0;+ while (index < shared && left.segments[index] === right.segments[index]) index += 1;+ if (index === left.segments.length && index === right.segments.length) return 0;+ if (index === left.segments.length) return -1;+ if (index === right.segments.length) return 1;++ const compare = getCompare();+ if (!compare) return compareFallback(left, right);++ const tree = getTree();+ const leftNode = tree.nodeById.get(tree.idByPath.get(pathAt(left, index)) ?? '');+ const rightNode = tree.nodeById.get(tree.idByPath.get(pathAt(right, index)) ?? '');+ // A row the tree holds but the nodes don't (an optimistic create).+ if (!leftNode || !rightNode) return compareFallback(left, right);++ return (+ compare(leftNode, rightNode) ||+ left.segments[index].localeCompare(right.segments[index]) ||+ (left.segments[index] < right.segments[index] ? -1 : 1)+ );+ };++/**+ * The sibling order `compare` produces, as one string. Equal signatures mean+ * the tree is already drawn in this order and needs no re-sort.+ */+export const buildSortSignature = <TData>(+ tree: NormalizedTree<TData>,+ compare: ExplorerTreeNodeComparator<TData> | undefined,+): string => {+ if (!compare) return '';+ const byParent = new Map<string | null, ExplorerTreeNode<TData>[]>();+ for (const [id, node] of tree.nodeById) {+ const parentId = tree.parentIdById.get(id) ?? null;+ const siblings = byParent.get(parentId);+ if (siblings) siblings.push(node);+ else byParent.set(parentId, [node]);+ }+ const groups: string[] = [];+ for (const [parentId, siblings] of byParent) {+ const ordered = siblings.slice().sort(compare);+ groups.push(`${parentId ?? ''}:${ordered.map((node) => node.id).join(',')}`);+ }+ return groups.sort().join('\n');+};diff --git a/src/features/ExplorerTree/index.tsx b/src/features/ExplorerTree/index.tsxindex 8b420caa0c0..9fb519dd039 100644--- a/src/features/ExplorerTree/index.tsx+++ b/src/features/ExplorerTree/index.tsx@@ -19,6 +19,7 @@ export type {ExplorerTreeMoveEvent,ExplorerTreeNameCheck,ExplorerTreeNode,+ ExplorerTreeNodeComparator,ExplorerTreeProps,ExplorerTreeRowDecorationCtx,} from './types';diff --git a/src/features/ExplorerTree/types.ts b/src/features/ExplorerTree/types.tsindex 2f15ecfe632..ea4826fda8c 100644--- a/src/features/ExplorerTree/types.ts+++ b/src/features/ExplorerTree/types.ts@@ -19,6 +19,12 @@ export interface ExplorerTreeNode<TData = unknown> {parentId?: string | null;}+/** Orders sibling rows; return < 0 to put `a` first. */+export type ExplorerTreeNodeComparator<TData = unknown> = (+ a: ExplorerTreeNode<TData>,+ b: ExplorerTreeNode<TData>,+) => number;+export interface ExplorerTreeMoveEvent<TData = unknown> {/** @deprecated Transitional compatibility for the current @pierre/trees bridge. */index?: number;@@ -155,6 +161,12 @@ export interface ExplorerTreeProps<TData = unknown> {) => boolean | void;overscan?: number;selectedIds?: string[];+ /**+ * Sibling order. Without it the tree lists folders first, then names by code+ * point. Whether a comparator is used is fixed on mount; passing a new one+ * (or nodes that it orders differently) re-sorts the rows in place.+ */+ sort?: ExplorerTreeNodeComparator<TData>;style?: CSSProperties;/** Raw CSS injected into the pierre/trees shadow DOM via FILE_TREE_UNSAFE_CSS_ATTRIBUTE. */unsafeCSS?: string;diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsxindex dae45388bc0..360fd5a2eb2 100644--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx@@ -10,7 +10,7 @@ import type { AgentDocumentItem } from '@/features/AgentDocumentsExplorer/types'import { canGoNative } from '@/libs/contextMenu/canGoNative';import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';-import type { ExplorerTreeHandle, ExplorerTreeNode } from '../types';+import type { ExplorerTreeHandle, ExplorerTreeNode, ExplorerTreeNodeComparator } from '../types';import { isItemToggleEventPath } from './eventPath';import ExplorerTree, { buildFileAppearanceCSS, getItemPathFromEventPath } from './ExplorerTree';@@ -479,3 +479,82 @@ describe('ExplorerTree flattenEmptyDirectories', () => {expect(root()?.querySelector('[data-item-flattened-subitems]')).toBeNull();});});++// ─── sort ────────────────────────────────────────────────────────────────────++interface RankData {+ rank: number;+}++const getSortedRowPaths = (container: HTMLElement): string[] => {+ const root = container.querySelector('file-tree-container')?.shadowRoot;+ return [...(root?.querySelectorAll<HTMLElement>('[data-item-path]') ?? [])].map(+ (row) => row.dataset.itemPath!,+ );+};++const rankedNodes: ExplorerTreeNode<RankData>[] = [+ { data: { rank: 2 }, id: 'docs', isFolder: true, name: 'docs', parentId: null },+ { data: { rank: 1 }, id: 'b', name: 'b.md', parentId: null },+ { data: { rank: 3 }, id: 'a', name: 'a.md', parentId: null },+ { data: { rank: 2 }, id: 'docs-x', name: 'x.md', parentId: 'docs' },+ { data: { rank: 1 }, id: 'docs-y', name: 'y.md', parentId: 'docs' },+];++const byRank: ExplorerTreeNodeComparator<RankData> = (a, b) => a.data!.rank - b.data!.rank;+const byRankDesc: ExplorerTreeNodeComparator<RankData> = (a, b) => b.data!.rank - a.data!.rank;++describe('ExplorerTree sort', () => {+ it('orders siblings at every depth with the comparator, files mixed with folders', async () => {+ const view = render(+ <ExplorerTree defaultExpandedIds={['docs']} nodes={rankedNodes} sort={byRank} />,+ );++ await waitFor(() =>+ expect(getSortedRowPaths(view.container)).toEqual([+ 'b.md',+ 'docs/',+ 'docs/y.md',+ 'docs/x.md',+ 'a.md',+ ]),+ );+ });++ it('re-sorts in place when the comparator changes, keeping folders open', async () => {+ const view = render(+ <ExplorerTree defaultExpandedIds={['docs']} nodes={rankedNodes} sort={byRank} />,+ );+ await waitFor(() => expect(getSortedRowPaths(view.container)[0]).toBe('b.md'));++ view.rerender(+ <ExplorerTree defaultExpandedIds={['docs']} nodes={rankedNodes} sort={byRankDesc} />,+ );++ await waitFor(() =>+ expect(getSortedRowPaths(view.container)).toEqual([+ 'a.md',+ 'docs/',+ 'docs/x.md',+ 'docs/y.md',+ 'b.md',+ ]),+ );+ });++ it('re-sorts when the data reorders rows whose paths did not change', async () => {+ const view = render(<ExplorerTree nodes={rankedNodes} sort={byRank} />);+ await waitFor(() =>+ expect(getSortedRowPaths(view.container)).toEqual(['b.md', 'docs/', 'a.md']),+ );++ const bumped = rankedNodes.map((node) =>+ node.id === 'a' ? { ...node, data: { rank: 0 } } : node,+ );+ view.rerender(<ExplorerTree nodes={bumped} sort={byRank} />);++ await waitFor(() =>+ expect(getSortedRowPaths(view.container)).toEqual(['a.md', 'b.md', 'docs/']),+ );+ });+});diff --git a/src/features/ExplorerTree/view/ExplorerTree.tsx b/src/features/ExplorerTree/view/ExplorerTree.tsxindex 906f9321021..5377803eff2 100644--- a/src/features/ExplorerTree/view/ExplorerTree.tsx+++ b/src/features/ExplorerTree/view/ExplorerTree.tsx@@ -23,6 +23,7 @@ import { useSingleton } from '@/hooks/useSingleton';import { arrayEqual, normalizeTree, remapIdsToPaths, remapPathsToIds } from '../adapter';import { extractName, toCanonicalTreePath } from '../adapter/path';+import { buildSortSignature, createPathComparator } from '../adapter/sort';import { cssString } from '../folderIconStyle';import type {ExplorerTreeHandle,@@ -120,6 +121,10 @@ function ExplorerTreeInner<TData>(const suppressModelEventsRef = useRef(false);const renamingRef = useRef(false);const pendingCreateRef = useRef<PendingCreate | null>(null);+ // The sibling order the model currently draws (see buildSortSignature).+ const drawnSortSignatureRef = useSingleton(() => ({+ current: buildSortSignature(adapterRef.current, props.sort),+ }));const initialOptions = useMemo((): FileTreeOptions => {const initial = adapterRef.current;@@ -224,6 +229,12 @@ function ExplorerTreeInner<TData>(},overscan: props.overscan,paths: initial.paths,+ ...(props.sort && {+ sort: createPathComparator(+ () => adapterRef.current,+ () => propsRef.current.sort,+ ),+ }),renaming: {canRename: (item) => {const path = toCanonicalTreePath(item.path, item.isFolder);@@ -493,6 +504,7 @@ function ExplorerTreeInner<TData>(model.resetPaths(next.paths, {initialExpandedPaths,});+ drawnSortSignatureRef.current = buildSortSignature(next, propsRef.current.sort);for (const path of nextSelectedPaths) {getItemSafely(model, path)?.select();}@@ -510,7 +522,19 @@ function ExplorerTreeInner<TData>(} finally {suppressModelEventsRef.current = false;}- }, [adapterRef, props.nodes, model, requestTreeRebuild]);+ }, [adapterRef, drawnSortSignatureRef, props.nodes, model, requestTreeRebuild]);++ // Runs after the nodes effect above. The tree only sorts when it rebuilds its+ // paths, so a new comparator, or data that reorders rows under unchanged+ // paths (a document edited while sorting by update time), needs a re-apply.+ useLayoutEffect(() => {+ const signature = buildSortSignature(adapterRef.current, props.sort);+ if (signature === drawnSortSignatureRef.current) return;+ // Re-applying would drop an open name input; retry on the next change.+ if (renamingRef.current || pendingCreateRef.current) return;+ resyncRef.current();+ drawnSortSignatureRef.current = signature;+ }, [adapterRef, drawnSortSignatureRef, props.nodes, props.sort]);// Runs after the nodes effect above, so it reads the paths just applied. On// first mount the shadow root can attach a frame after this effect, so thediff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex d3b50604e37..f0801c4bd45 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -147,11 +147,22 @@ export type ProjectTopicSubGroupMode = 'none' | 'byDevice' | 'byTime' | 'byStatuexport const DEFAULT_HOME_SIDEBAR_EXPANDED_KEYS = ['recents', 'agent', 'private'];+/** How the agent document tree orders sibling rows. */+export interface AgentDocumentSort {+ by: 'createdAt' | 'name' | 'updatedAt';+ foldersFirst: boolean;+ order: 'asc' | 'desc';+}+export interface SystemStatus {/*** Agent Builder panel width*/agentBuilderPanelWidth?: number;+ /**+ * Sort order of the agent document tree (working panel 「文档」).+ */+ agentDocumentSort?: AgentDocumentSort;/*** Expanded group keys of the agent view-all page. Expanded (not collapsed)* keys are persisted because groups default to COLLAPSED (mirrors Linear) —diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex d6040619500..5bf26408b4b 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -1,6 +1,7 @@import { type TopicGroupMode } from '@/types/topic';import type {+ AgentDocumentSort,GlobalState,ModelDetailPanelExpandedKey,ProjectTopicSubGroupMode,@@ -439,6 +440,13 @@ const filePanelWidth = (s: GlobalState) => s.status.filePanelWidth;const groupAgentBuilderPanelWidth = (s: GlobalState) => s.status.groupAgentBuilderPanelWidth || 360;const imagePanelWidth = (s: GlobalState) => s.status.imagePanelWidth;const agentListViewMode = (s: GlobalState) => s.status.agentListViewMode || 'list';+const DEFAULT_AGENT_DOCUMENT_SORT: AgentDocumentSort = {+ by: 'name',+ foldersFirst: true,+ order: 'asc',+};+const agentDocumentSort = (s: GlobalState): AgentDocumentSort =>+ s.status.agentDocumentSort ?? DEFAULT_AGENT_DOCUMENT_SORT;const agentListViewOptions = (s: GlobalState) => s.status.agentListViewOptions;const agentListExpandedGroupKeys = (s: GlobalState) => s.status.agentListExpandedGroupKeys ?? [];const agentListSidebarSectionCollapsed = (s: GlobalState) =>@@ -487,6 +495,7 @@ const homeSelectedAgentId = (s: GlobalState) => s.status.homeSelectedAgentId;export const systemStatusSelectors = {agentBuilderPanelWidth,+ agentDocumentSort,agentListExpandedGroupKeys,agentListSidebarSectionCollapsed,agentListViewMode,