🤯 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(task): group the assignee agent picker by sidebar groups (#21803)
Rdmclin2f260c6b6cdef
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 72442f054f7..0fd3519f70d 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -293,6 +293,7 @@"sidebar.title": "Topics","taskManager.agent": "Task Agent","taskManager.agentSelector.privateGroup": "Private",+ "taskManager.agentSelector.recentGroup": "Recently assigned","taskManager.agentSelector.workspaceGroup": "Workspace","taskManager.welcome": "Ask me about your tasks","temp": "Temporary",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex 106a50fab08..611e59cbed1 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -293,6 +293,7 @@"sidebar.title": "话题","taskManager.agent": "任务助手","taskManager.agentSelector.privateGroup": "私人",+ "taskManager.agentSelector.recentGroup": "最近指派","taskManager.agentSelector.workspaceGroup": "工作区","taskManager.welcome": "有什么任务问题想问我?","temp": "临时",diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 3c0f8128256..07e5b88aa10 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -325,6 +325,7 @@ export default {'sidebar.title': 'Topics','taskManager.agent': 'Task Agent','taskManager.agentSelector.privateGroup': 'Private',+ 'taskManager.agentSelector.recentGroup': 'Recently assigned','taskManager.agentSelector.workspaceGroup': 'Workspace','taskManager.welcome': 'Ask me about your tasks','temp': 'Temporary',diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex 759b7bc375e..54182521071 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -68,12 +68,15 @@ vi.mock('@/store/chat/selectors', () => ({chatPortalSelectors: { currentViewType: () => undefined, showPortal: () => mocks.showPortal },}));-vi.mock('@/store/global', () => ({- useGlobalStore: Object.assign(- (selector: (s: any) => unknown) => selector({ toggleLeftPanel: vi.fn() }),- { getState: () => ({ toggleLeftPanel: vi.fn() }) },- ),-}));+vi.mock('@/store/global', () => {+ // The assignee picker reads persisted UI status (folded groups, recents).+ const state = { status: {}, toggleLeftPanel: vi.fn(), updateSystemStatus: vi.fn() };+ return {+ useGlobalStore: Object.assign((selector: (s: any) => unknown) => selector(state), {+ getState: () => state,+ }),+ };+});vi.mock('@/store/global/selectors', () => ({systemStatusSelectors: { showLeftPanel: () => false },diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsxindex 16583cb1a71..f8dc39bab1e 100644--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx@@ -2,11 +2,12 @@ import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';import { createStaticStyles, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';import isEqual from 'fast-deep-equal';-import { UserRoundX } from 'lucide-react';+import { ChevronDown, ChevronRight, UserRoundX } from 'lucide-react';import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { type SidebarAgentItem } from '@/database/repositories/home';import NavItem from '@/features/NavPanel/components/NavItem';import SkeletonList from '@/features/NavPanel/components/SkeletonList';@@ -15,10 +16,20 @@ import { useFetchAgentList } from '@/hooks/useFetchAgentList';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';+import { useGlobalStore } from '@/store/global';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';import { useTaskStore } from '@/store/task';+import {+ type AssigneeAgentSection,+ buildAssigneeAgentSections,+ filterAssigneeSections,+ matchesAssigneeSearch,+ pickRecentAssignees,+ pushRecentAssignee,+} from './assigneeAgentSections';+interface AssigneeAgentSelectorProps {/** Offer the "unassigned" option; off where an owner is required. */allowUnassigned?: boolean;@@ -38,6 +49,26 @@ type AgentOption =| { key: 'unassigned'; kind: 'unassigned' }| { agent: SidebarAgentItem; key: string; kind: 'agent' };+type PickerRow =+ | { kind: 'option'; option: AgentOption }+ | { key: string; kind: 'scope'; title: string }+ | {+ collapsed: boolean;+ collapsible: boolean;+ count: number;+ id: string;+ kind: 'section';+ title: string;+ };++interface PickerScope {+ id: string;+ sections: AssigneeAgentSection[];+ title?: string;+}++const RECENT_SECTION_ID = 'recent';+const styles = createStaticStyles(({ css, cssVar }) => ({searchInput: css`width: 100%;@@ -65,12 +96,42 @@ const styles = createStaticStyles(({ css, cssVar }) => ({line-height: 1.4;color: ${cssVar.colorTextTertiary};`,-}));+ sectionToggle: css`+ cursor: pointer;-const matchesSearch = (agent: SidebarAgentItem, query: string) =>- [agentDisplayName(agent), agent.title].some((label) =>- (label ?? '').toLowerCase().includes(query),- );+ display: flex;+ gap: 4px;+ align-items: center;++ width: 100%;+ padding-block: 4px;+ padding-inline: 4px 8px;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ font-family: inherit;+ font-size: 12px;+ line-height: 1.4;+ color: ${cssVar.colorTextTertiary};+ text-align: start;++ background: transparent;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ sectionToggleTitle: css`+ overflow: hidden;+ flex: 1;++ min-width: 0;++ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));const triggerStyle: CSSProperties = {alignItems: 'center',@@ -104,6 +165,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const [search, setSearch] = useState('');const [activeIndex, setActiveIndex] = useState(0);const listRef = useRef<HTMLDivElement>(null);+ const keyboardMovedRef = useRef(false);const updateTask = useTaskStore((s) => s.updateTask);const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);@@ -125,81 +187,185 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(useFetchAgentList();- const workspaceAgents = useMemo<SidebarAgentItem[]>(() => {- const groupedItems = agentGroups.flatMap((group) => group.items);- const available = [...pinnedAgents, ...groupedItems, ...ungroupedAgents].filter(- (agent) => agent.type === 'agent',- );- const hasInbox = available.some((agent) => agent.id === inboxAgentId);-- if (inboxAgentId && !hasInbox) {- return [- {- avatar: inboxMeta?.avatar || DEFAULT_INBOX_AVATAR,- description: null,- id: inboxAgentId,- pinned: false,- title: agentDisplayName(inboxMeta, t('inbox.title', { ns: 'chat' })),- type: 'agent' as const,- updatedAt: new Date(),- },- ...available,- ];- }+ const workspaceId = useActiveWorkspaceId();+ const recentKey = workspaceId ?? 'personal';+ const recentIds = useGlobalStore((s) => s.status.recentAssigneeAgentIds?.[recentKey]);+ const collapsedGroups = useGlobalStore((s) => s.status.assigneeAgentSelectorCollapsedGroups);+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);- return available;- }, [pinnedAgents, agentGroups, ungroupedAgents, inboxAgentId, inboxMeta, t]);+ const scopes = useMemo<PickerScope[]>(() => {+ const labels = {+ pinned: t('navPanel.pinned', { ns: 'common' }),+ ungrouped: t('defaultList', { ns: 'chat' }),+ };+ const result: PickerScope[] = [];- const privateAgents = useMemo<SidebarAgentItem[]>(() => {- if (taskVisibility === 'public') return [];- const groupedItems = privateAgentGroups.flatMap((group) => group.items);- return [...privatePinnedAgents, ...groupedItems, ...privateUngroupedAgents].filter(- (agent) => agent.type === 'agent',+ if (taskVisibility !== 'public')+ result.push({+ id: 'private',+ sections: buildAssigneeAgentSections({+ groups: privateAgentGroups,+ labels,+ pinned: privatePinnedAgents,+ scope: 'private',+ ungrouped: privateUngroupedAgents,+ }),+ title: t('taskManager.agentSelector.privateGroup', { ns: 'topic' }),+ });++ const workspaceSections = buildAssigneeAgentSections({+ groups: agentGroups,+ labels,+ pinned: pinnedAgents,+ scope: 'workspace',+ ungrouped: ungroupedAgents,+ });+ result.push({+ id: 'workspace',+ sections: workspaceSections,+ title: hasPrivateAgents+ ? t('taskManager.agentSelector.workspaceGroup', { ns: 'topic' })+ : undefined,+ });++ return result;+ }, [+ agentGroups,+ hasPrivateAgents,+ pinnedAgents,+ privateAgentGroups,+ privatePinnedAgents,+ privateUngroupedAgents,+ t,+ taskVisibility,+ ungroupedAgents,+ ]);++ // The sidebar keeps the inbox above every group, so it leads the list here+ // too, ahead of Recent, where a header-less row would read as a recent pick.+ const inboxAgent = useMemo<SidebarAgentItem | undefined>(() => {+ if (!inboxAgentId) return;+ const listed = scopes.some((scope) =>+ scope.sections.some((section) => section.agents.some((agent) => agent.id === inboxAgentId)),);- }, [privateAgentGroups, privatePinnedAgents, privateUngroupedAgents, taskVisibility]);+ if (listed) return;+ return {+ avatar: inboxMeta?.avatar || DEFAULT_INBOX_AVATAR,+ description: null,+ id: inboxAgentId,+ pinned: false,+ title: agentDisplayName(inboxMeta, t('inbox.title', { ns: 'chat' })),+ type: 'agent' as const,+ updatedAt: new Date(),+ };+ }, [inboxAgentId, inboxMeta, scopes, t]);const query = search.trim().toLowerCase();- const filteredPrivate = useMemo(- () => (query ? privateAgents.filter((agent) => matchesSearch(agent, query)) : privateAgents),- [privateAgents, query],- );- const filteredWorkspace = useMemo(+ const recentAgents = useMemo(() =>- query ? workspaceAgents.filter((agent) => matchesSearch(agent, query)) : workspaceAgents,- [workspaceAgents, query],+ query+ ? []+ : // A standalone inbox already has its own row above Recent; offering+ // it here too would list it twice.+ pickRecentAssignees(+ recentIds,+ scopes.flatMap((scope) => scope.sections.flatMap((section) => section.agents)),+ ),+ [query, recentIds, scopes],);const unassignedLabel = t('taskList.unassigned', { ns: 'chat' });const showUnassigned =allowUnassigned && (!query || unassignedLabel.toLowerCase().includes(query));- const flatOptions = useMemo<AgentOption[]>(- () => [- ...(showUnassigned ? [{ key: 'unassigned', kind: 'unassigned' } as const] : []),- ...filteredPrivate.map(- (agent) => ({ agent, key: `agent:${agent.id}`, kind: 'agent' }) as const,- ),- ...filteredWorkspace.map(- (agent) => ({ agent, key: `agent:${agent.id}`, kind: 'agent' }) as const,- ),- ],- [filteredPrivate, filteredWorkspace, showUnassigned],++ // One ordered list of headers and options; the options alone drive the+ // keyboard. An agent can sit in both Recent and its group, so option keys+ // carry the section id.+ const rows = useMemo<PickerRow[]>(() => {+ const result: PickerRow[] = [];+ const pushAgents = (sectionId: string, agents: SidebarAgentItem[]) => {+ for (const agent of agents)+ result.push({+ kind: 'option',+ option: { agent, key: `${sectionId}:${agent.id}`, kind: 'agent' },+ });+ };++ if (showUnassigned)+ result.push({ kind: 'option', option: { key: 'unassigned', kind: 'unassigned' } });+ if (inboxAgent && (!query || matchesAssigneeSearch(inboxAgent, query)))+ pushAgents('inbox', [inboxAgent]);++ if (recentAgents.length > 0) {+ result.push({+ collapsed: false,+ collapsible: false,+ count: recentAgents.length,+ id: RECENT_SECTION_ID,+ kind: 'section',+ title: t('taskManager.agentSelector.recentGroup', { ns: 'topic' }),+ });+ pushAgents(RECENT_SECTION_ID, recentAgents);+ }++ for (const scope of scopes) {+ const sections = filterAssigneeSections(scope.sections, query);+ if (sections.length === 0) continue;+ if (scope.title) result.push({ key: scope.id, kind: 'scope', title: scope.title });++ for (const section of sections) {+ // A search reaches into folded groups, otherwise a match would hide.+ const collapsed = section.collapsible && !query && !!collapsedGroups?.[section.id];+ if (section.title)+ result.push({+ collapsed,+ // While searching every match shows, so there is nothing to fold.+ collapsible: section.collapsible && !query,+ count: section.agents.length,+ id: section.id,+ kind: 'section',+ title: section.title,+ });+ if (!collapsed) pushAgents(section.id, section.agents);+ }+ }++ return result;+ }, [collapsedGroups, inboxAgent, query, recentAgents, scopes, showUnassigned, t]);++ const flatOptions = useMemo(+ () => rows.flatMap((row) => (row.kind === 'option' ? [row.option] : ([] as AgentOption[]))),+ [rows],+ );++ const toggleSection = useCallback(+ (sectionId: string, collapsed: boolean) =>+ updateSystemStatus({ assigneeAgentSelectorCollapsedGroups: { [sectionId]: !collapsed } }),+ [updateSystemStatus],);- const selectedKey = currentAgentId ? `agent:${currentAgentId}` : 'unassigned';useEffect(() => {if (query) {setActiveIndex(0);return;}- const selectedIndex = flatOptions.findIndex((option) => option.key === selectedKey);+ const selectedIndex = flatOptions.findIndex((option) =>+ option.kind === 'agent' ? option.agent.id === currentAgentId : !currentAgentId,+ );setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0);- }, [flatOptions, query, selectedKey]);+ }, [currentAgentId, flatOptions, query]);const handleAgentChange = useCallback((agentId: string | null, agent?: SidebarAgentItem) => {if (!canEditTask || agentId === (currentAgentId ?? null)) return;setKey((value) => value + 1);setSearch('');+ if (agentId) {+ const current = useGlobalStore.getState().status.recentAssigneeAgentIds?.[recentKey];+ updateSystemStatus({+ recentAssigneeAgentIds: { [recentKey]: pushRecentAssignee(current, agentId) },+ });+ }if (onChange) {onChange(agentId);return;@@ -224,7 +390,15 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(},);},- [canEditTask, currentAgentId, onChange, taskIdentifier, updateTask],+ [+ canEditTask,+ currentAgentId,+ onChange,+ recentKey,+ taskIdentifier,+ updateSystemStatus,+ updateTask,+ ],);const handleSelect = useCallback(@@ -240,9 +414,11 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(if (flatOptions.length === 0) return;if (event.key === 'ArrowDown') {event.preventDefault();+ keyboardMovedRef.current = true;setActiveIndex((index) => (index + 1) % flatOptions.length);} else if (event.key === 'ArrowUp') {event.preventDefault();+ keyboardMovedRef.current = true;setActiveIndex((index) => (index - 1 + flatOptions.length) % flatOptions.length);} else if (event.key === 'Enter') {event.preventDefault();@@ -253,7 +429,11 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>([activeIndex, flatOptions, handleSelect],);+ // Follow the highlight only when the arrow keys moved it. Folding a group+ // shifts every index after it, and scrolling then jumped the list away.useEffect(() => {+ if (!keyboardMovedRef.current) return;+ keyboardMovedRef.current = false;const active = listRef.current?.querySelector<HTMLElement>(`[data-assignee-index="${activeIndex}"]`,);@@ -267,10 +447,16 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const renderOption = (option: AgentOption) => {const optionIndex = optionIndexByKey.get(option.key) ?? 0;const active = optionIndex === activeIndex;+ const agentTitle =+ option.kind === 'agent'+ ? agentDisplayName(option.agent, t('untitledAgent', { ns: 'chat' }))+ : undefined;return (<divdata-assignee-index={optionIndex}key={option.key}+ // Long names truncate; the native tooltip keeps similar ones apart.+ title={agentTitle}onMouseEnter={() => setActiveIndex(optionIndex)}>{option.kind === 'agent' ? (@@ -278,7 +464,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(active={active}agent={option.agent}agentId={option.agent.id}- agentTitle={agentDisplayName(option.agent, t('untitledAgent', { ns: 'chat' }))}+ agentTitle={agentTitle ?? ''}avatar={option.agent.avatar}onAgentChange={() => handleSelect(option)}onClose={() => setKey((value) => value + 1)}@@ -296,6 +482,37 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>();};+ const renderRow = (row: PickerRow) => {+ if (row.kind === 'option') return renderOption(row.option);+ if (row.kind === 'scope')+ return (+ <div className={styles.sectionHeader} key={`scope:${row.key}`}>+ {row.title}+ </div>+ );+ if (!row.collapsible)+ return (+ <div className={styles.sectionHeader} key={`section:${row.id}`}>+ {row.title}+ </div>+ );+ return (+ <button+ aria-expanded={!row.collapsed}+ className={styles.sectionToggle}+ key={`section:${row.id}`}+ type={'button'}+ onClick={() => toggleSection(row.id, row.collapsed)}+ // Keep focus in the search box so the arrow keys still move the list.+ onMouseDown={(event) => event.preventDefault()}+ >+ <Icon icon={row.collapsed ? ChevronRight : ChevronDown} size={14} />+ <span className={styles.sectionToggleTitle}>{row.title}</span>+ {row.collapsed && <span>{row.count}</span>}+ </button>+ );+ };+const blocked = disabled || !canEditTask;const baseTriggerStyle = block ? { ...triggerStyle, display: 'flex' } : triggerStyle;const trigger = blocked ? (@@ -322,7 +539,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(disabled={blocked}key={key}placement={'bottomLeft'}- styles={{ content: { padding: 0, width: 260 } }}+ styles={{ content: { padding: 0, width: 320 } }}trigger={'click'}content={<Suspense fallback={<SkeletonList rows={6} />}>@@ -336,7 +553,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(onChange={(event) => setSearch(event.target.value)}onKeyDown={handleSearchKeyDown}/>- {flatOptions.length === 0 ? (+ {rows.length === 0 ? (<Flexbox align={'center'} justify={'center'} padding={16}><Text fontSize={12} type={'secondary'}>{t('taskList.assigneeSearch.agentEmpty', { ns: 'chat' })}@@ -349,29 +566,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(ref={listRef}style={{ maxHeight: '50vh', overflowY: 'auto', width: '100%' }}>- {showUnassigned && renderOption({ key: 'unassigned', kind: 'unassigned' })}- {filteredPrivate.length > 0 && (- <>- <div className={styles.sectionHeader}>- {t('taskManager.agentSelector.privateGroup', { ns: 'topic' })}- </div>- {filteredPrivate.map((agent) =>- renderOption({ agent, key: `agent:${agent.id}`, kind: 'agent' }),- )}- </>- )}- {filteredWorkspace.length > 0 && (- <>- {hasPrivateAgents && (- <div className={styles.sectionHeader}>- {t('taskManager.agentSelector.workspaceGroup', { ns: 'topic' })}- </div>- )}- {filteredWorkspace.map((agent) =>- renderOption({ agent, key: `agent:${agent.id}`, kind: 'agent' }),- )}- </>- )}+ {rows.map(renderRow)}</Flexbox>)}</Flexbox>diff --git a/src/features/AgentTasks/features/assigneeAgentSections.test.ts b/src/features/AgentTasks/features/assigneeAgentSections.test.tsnew file mode 100644index 00000000000..283e1a452de--- /dev/null+++ b/src/features/AgentTasks/features/assigneeAgentSections.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest';++import { type SidebarAgentItem, type SidebarGroup } from '@/database/repositories/home';++import {+ buildAssigneeAgentSections,+ filterAssigneeSections,+ MAX_RECENT_ASSIGNEES,+ pickRecentAssignees,+ pushRecentAssignee,+} from './assigneeAgentSections';++const agent = (id: string, extra: Partial<SidebarAgentItem> = {}): SidebarAgentItem => ({+ avatar: null,+ description: null,+ id,+ pinned: false,+ title: id,+ type: 'agent',+ updatedAt: new Date(0),+ ...extra,+});++const group = (id: string, name: string, items: SidebarAgentItem[]): SidebarGroup => ({+ id,+ items,+ name,+ sort: 0,+});++const labels = { pinned: 'Pinned', ungrouped: 'Default List' };++describe('buildAssigneeAgentSections', () => {+ it('mirrors the sidebar: pinned, groups in order, then the rest', () => {+ const sections = buildAssigneeAgentSections({+ groups: [+ group('g-rollout', 'Rollouts', [agent('mh-rollout:run_1'), agent('mh-rollout:run_2')]),+ group('g-empty', 'Empty', []),+ group('g-work', 'Work', [agent('writer')]),+ ],+ labels,+ pinned: [agent('lobo')],+ scope: 'workspace',+ ungrouped: [agent('misc'), agent('chat-group', { type: 'group' })],+ });++ expect(sections.map((s) => [s.title, s.collapsible, s.agents.map((a) => a.id)])).toEqual([+ ['Pinned', false, ['lobo']],+ ['Rollouts', true, ['mh-rollout:run_1', 'mh-rollout:run_2']],+ ['Work', true, ['writer']],+ ['Default List', false, ['misc']],+ ]);+ });++ it('keeps a lone ungrouped list without a header', () => {+ const sections = buildAssigneeAgentSections({+ groups: [],+ labels,+ pinned: [],+ scope: 'private',+ ungrouped: [agent('a')],+ });++ expect(sections).toEqual([+ { agents: [agent('a')], collapsible: false, id: 'private:ungrouped', title: undefined },+ ]);+ });+});++describe('filterAssigneeSections', () => {+ it('matches the description and drops sections left empty', () => {+ const sections = buildAssigneeAgentSections({+ groups: [group('g', 'Rollouts', [agent('mh-rollout:run_1')])],+ labels,+ pinned: [],+ scope: 'workspace',+ ungrouped: [agent('reviewer', { description: 'Reviews pull requests' })],+ });++ const result = filterAssigneeSections(sections, 'pull request');++ expect(result.map((s) => s.agents.map((a) => a.id))).toEqual([['reviewer']]);+ });+});++describe('recent assignees', () => {+ it('resolves stored ids in order and skips agents no longer offered', () => {+ const result = pickRecentAssignees(['b', 'gone', 'a'], [agent('a'), agent('b')]);++ expect(result.map((a) => a.id)).toEqual(['b', 'a']);+ });++ it('moves a pick to the front without duplicates and caps the list', () => {+ const full = ['a', 'b', 'c', 'd', 'e'];++ expect(pushRecentAssignee(full, 'c')).toEqual(['c', 'a', 'b', 'd', 'e']);+ expect(pushRecentAssignee(full, 'f')).toEqual(['f', 'a', 'b', 'c', 'd']);+ expect(pushRecentAssignee(undefined, 'a')).toEqual(['a']);+ expect(pushRecentAssignee(full, 'f')).toHaveLength(MAX_RECENT_ASSIGNEES);+ });+});diff --git a/src/features/AgentTasks/features/assigneeAgentSections.ts b/src/features/AgentTasks/features/assigneeAgentSections.tsnew file mode 100644index 00000000000..f44cc329e50--- /dev/null+++ b/src/features/AgentTasks/features/assigneeAgentSections.ts@@ -0,0 +1,105 @@+import { agentDisplayName } from '@lobechat/types';++import { type SidebarAgentItem, type SidebarGroup } from '@/database/repositories/home';++/** How many recently assigned agents the picker offers above the full list. */+export const MAX_RECENT_ASSIGNEES = 5;++export interface AssigneeAgentSection {+ agents: SidebarAgentItem[];+ /** Only the user's own sidebar groups fold; pinned and the rest stay open. */+ collapsible: boolean;+ id: string;+ /** Omitted when the section is the only one, so a flat list keeps no header. */+ title?: string;+}++interface BuildSectionsParams {+ groups: SidebarGroup[];+ labels: { pinned: string; ungrouped: string };+ pinned: SidebarAgentItem[];+ /** Keeps private and workspace section ids apart. */+ scope: string;+ ungrouped: SidebarAgentItem[];+}++const onlyAgents = (items: SidebarAgentItem[]) => items.filter((item) => item.type === 'agent');++/**+ * Mirror the sidebar's layout (pinned, then the user's groups in sidebar order,+ * then everything else), so the grouping a user keeps in the sidebar also+ * organizes the assignee picker.+ */+export const buildAssigneeAgentSections = ({+ groups,+ labels,+ pinned,+ scope,+ ungrouped,+}: BuildSectionsParams): AssigneeAgentSection[] => {+ const sections: AssigneeAgentSection[] = [];++ const pinnedAgents = onlyAgents(pinned);+ if (pinnedAgents.length > 0)+ sections.push({+ agents: pinnedAgents,+ collapsible: false,+ id: `${scope}:pinned`,+ title: labels.pinned,+ });++ for (const group of groups) {+ const agents = onlyAgents(group.items);+ if (agents.length === 0) continue;+ sections.push({ agents, collapsible: true, id: group.id, title: group.name });+ }++ const ungroupedAgents = onlyAgents(ungrouped);+ if (ungroupedAgents.length > 0)+ sections.push({+ agents: ungroupedAgents,+ collapsible: false,+ id: `${scope}:ungrouped`,+ title: sections.length > 0 ? labels.ungrouped : undefined,+ });++ return sections;+};++export const matchesAssigneeSearch = (agent: SidebarAgentItem, query: string) =>+ [agentDisplayName(agent), agent.title, agent.description].some((label) =>+ (label ?? '').toLowerCase().includes(query),+ );++export const filterAssigneeSections = (+ sections: AssigneeAgentSection[],+ query: string,+): AssigneeAgentSection[] => {+ if (!query) return sections;+ return sections+ .map((section) => ({+ ...section,+ agents: section.agents.filter((agent) => matchesAssigneeSearch(agent, query)),+ }))+ .filter((section) => section.agents.length > 0);+};++/** Resolve stored ids against the agents the picker can offer, newest first. */+export const pickRecentAssignees = (+ recentIds: string[] | undefined,+ available: SidebarAgentItem[],+): SidebarAgentItem[] => {+ if (!recentIds?.length) return [];+ const byId = new Map(available.map((agent) => [agent.id, agent]));+ return recentIds+ .map((id) => byId.get(id))+ .filter((agent): agent is SidebarAgentItem => !!agent)+ .slice(0, MAX_RECENT_ASSIGNEES);+};++/**+ * Move `agentId` to the front. The list never gets shorter: `updateSystemStatus`+ * merges arrays by index, so a shorter write would keep the old tail.+ */+export const pushRecentAssignee = (current: string[] | undefined, agentId: string): string[] =>+ [agentId, ...(current ?? []).filter((id) => id !== agentId)].slice(0, MAX_RECENT_ASSIGNEES);diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 42ad50afdac..177d092afc1 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -224,6 +224,12 @@ export interface SystemStatus {* number of agents (defaultList) to display*/agentPageSize?: number;+ /**+ * Sidebar groups folded in the task assignee picker, keyed by group id.+ * Nested booleans so the lodash `merge` in `updateSystemStatus` replaces+ * scalars instead of index-merging arrays.+ */+ assigneeAgentSelectorCollapsedGroups?: Record<string, boolean>;chatInputHeight?: number;/*** Which topicGroups are collapsed, bucketed by group mode. We persist the@@ -367,6 +373,11 @@ export interface SystemStatus {*/projectTopicSubGroupModeByGroup?: Record<string, ProjectTopicSubGroupMode>;readNotificationSlugs?: string[];+ /**+ * Agents this device last picked as a task assignee, newest first, keyed by+ * workspace id (`personal` outside a workspace). See `pushRecentAssignee`.+ */+ recentAssigneeAgentIds?: Record<string, string[]>;/*** number of recent items to display*/