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.

🐛 fix(task): group bulk Assign to agent and confirm before assigning a private agent (#22300)

Rdmclin2816c79c71112
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 6d891ff0cbc..b46f3edd50f 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2669,6 +2669,13 @@
"taskList.bulk.actions": "Actions",
"taskList.bulk.archive": "Archive",
"taskList.bulk.assignAgent": "Assign to agent…",
+ "taskList.bulk.assignPrivate.hint_one": "This agent is private, so {{count}} public task and its subtasks become private before it is assigned. Members assigned to them are unassigned.",
+ "taskList.bulk.assignPrivate.hint_other": "This agent is private, so {{count}} public tasks and their subtasks become private before it is assigned. Members assigned to them are unassigned.",
+ "taskList.bulk.assignPrivate.ok": "Make private and assign",
+ "taskList.bulk.assignPrivate.takeOverWarning_one": "{{count}} of them was created by another member. It becomes your private task: its creator loses access, and its schedule or heartbeat is turned off.",
+ "taskList.bulk.assignPrivate.takeOverWarning_other": "{{count}} of them were created by other members. They become your private tasks: their creators lose access, and their schedule or heartbeat is turned off.",
+ "taskList.bulk.assignPrivate.title_one": "Assign {{count}} task to a private agent?",
+ "taskList.bulk.assignPrivate.title_other": "Assign {{count}} tasks to a private agent?",
"taskList.bulk.assignToMe": "Assign to me",
"taskList.bulk.changeStatus": "Change status…",
"taskList.bulk.clear": "Clear selection",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 421a9923ca4..b9e02891a0f 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2669,6 +2669,13 @@
"taskList.bulk.actions": "操作",
"taskList.bulk.archive": "归档",
"taskList.bulk.assignAgent": "指派给助理…",
+ "taskList.bulk.assignPrivate.hint_one": "该助理为私人助理,指派前 {{count}} 个公开任务及其子任务会先设为私人,已指派的成员会被移除。",
+ "taskList.bulk.assignPrivate.hint_other": "该助理为私人助理,指派前 {{count}} 个公开任务及其子任务会先设为私人,已指派的成员会被移除。",
+ "taskList.bulk.assignPrivate.ok": "设为私人并指派",
+ "taskList.bulk.assignPrivate.takeOverWarning_one": "其中 {{count}} 个任务由其他成员创建,会收归为你的私人任务:创建者将无法再看到它,定时与心跳会被关闭。",
+ "taskList.bulk.assignPrivate.takeOverWarning_other": "其中 {{count}} 个任务由其他成员创建,会收归为你的私人任务:创建者将无法再看到它们,定时与心跳会被关闭。",
+ "taskList.bulk.assignPrivate.title_one": "将 {{count}} 个任务指派给私人助理?",
+ "taskList.bulk.assignPrivate.title_other": "将 {{count}} 个任务指派给私人助理?",
"taskList.bulk.assignToMe": "指派给我",
"taskList.bulk.changeStatus": "修改状态…",
"taskList.bulk.clear": "取消选择",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ee89029557e..b7c64b27f4e 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3141,6 +3141,17 @@ export default {
'taskList.bulk.actions': 'Actions',
'taskList.bulk.archive': 'Archive',
'taskList.bulk.assignAgent': 'Assign to agent…',
+ 'taskList.bulk.assignPrivate.hint_one':
+ 'This agent is private, so {{count}} public task and its subtasks become private before it is assigned. Members assigned to them are unassigned.',
+ 'taskList.bulk.assignPrivate.hint_other':
+ 'This agent is private, so {{count}} public tasks and their subtasks become private before it is assigned. Members assigned to them are unassigned.',
+ 'taskList.bulk.assignPrivate.ok': 'Make private and assign',
+ 'taskList.bulk.assignPrivate.takeOverWarning_one':
+ '{{count}} of them was created by another member. It becomes your private task: its creator loses access, and its schedule or heartbeat is turned off.',
+ 'taskList.bulk.assignPrivate.takeOverWarning_other':
+ '{{count}} of them were created by other members. They become your private tasks: their creators lose access, and their schedule or heartbeat is turned off.',
+ 'taskList.bulk.assignPrivate.title_one': 'Assign {{count}} task to a private agent?',
+ 'taskList.bulk.assignPrivate.title_other': 'Assign {{count}} tasks to a private agent?',
'taskList.bulk.assignToMe': 'Assign to me',
'taskList.bulk.changeStatus': 'Change status…',
'taskList.bulk.clear': 'Clear selection',
diff --git a/src/features/AgentTasks/AgentTaskList/selection/BulkAssignPrivateConfirmContent.tsx b/src/features/AgentTasks/AgentTaskList/selection/BulkAssignPrivateConfirmContent.tsx
new file mode 100644
index 00000000000..baa54780f2e
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/BulkAssignPrivateConfirmContent.tsx
@@ -0,0 +1,44 @@
+import { Alert } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
+
+interface BulkAssignPrivateConfirmContentProps {
+ /** Public tasks in the selection that go private first. */
+ count: number;
+ /** How many of them another workspace member created (taken over). */
+ takeOverCount: number;
+}
+
+/**
+ * Body of the confirmation shown before a batch is assigned to a private
+ * agent: like the single-task picker, its public tasks go private first, and
+ * a teammate's task is taken over as the caller's own, so that count is
+ * called out on its own.
+ */
+const BulkAssignPrivateConfirmContent = memo<BulkAssignPrivateConfirmContentProps>(
+ ({ count, takeOverCount }) => {
+ const { t } = useTranslation('chat');
+ return (
+ <>
+ <VisibilityConfirmContent variant="makePrivate" />
+ <div style={{ marginTop: 8, opacity: 0.7 }}>
+ {t('taskList.bulk.assignPrivate.hint', { count })}
+ </div>
+ {takeOverCount > 0 && (
+ <Alert
+ data-testid={'task-bulk-assign-private-takeover-warning'}
+ style={{ marginTop: 12 }}
+ title={t('taskList.bulk.assignPrivate.takeOverWarning', { count: takeOverCount })}
+ type={'warning'}
+ />
+ )}
+ </>
+ );
+ },
+);
+
+BulkAssignPrivateConfirmContent.displayName = 'BulkAssignPrivateConfirmContent';
+
+export default BulkAssignPrivateConfirmContent;
diff --git a/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.test.tsx b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.test.tsx
new file mode 100644
index 00000000000..87ec6ae2bc8
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.test.tsx
@@ -0,0 +1,159 @@
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskSelectionStore } from './store';
+import TaskBulkActionsPanel from './TaskBulkActionsPanel';
+
+const run = vi.fn();
+const confirmModal = vi.fn();
+const rememberAssignee = vi.fn();
+
+const agent = (id: string, title: string) => ({
+ avatar: null,
+ description: null,
+ id,
+ pinned: false,
+ title,
+ type: 'agent' as const,
+ updatedAt: new Date(),
+});
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirmModal: (...args: unknown[]) => confirmModal(...args),
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { count?: number }) =>
+ options?.count === undefined ? key : `${key}:${options.count}`,
+ }),
+}));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => 'ws_1',
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/components/AgentAvatar', () => ({ default: () => null }));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({ userProfileSelectors: { userId: () => 'me' } }));
+vi.mock('../../features/useAssigneeAgentScopes', () => ({
+ useAssigneeAgentScopes: () => ({
+ inboxAgent: undefined,
+ privateAgentIds: new Set(['agt_private']),
+ recentIds: [],
+ rememberAssignee,
+ scopes: [
+ {
+ id: 'private',
+ sections: [{ agents: [agent('agt_private', 'Secret')], collapsible: false, id: 'p' }],
+ title: 'Private',
+ },
+ {
+ id: 'workspace',
+ sections: [
+ {
+ agents: [agent('agt_pinned', 'Nasa')],
+ collapsible: false,
+ id: 'workspace:pinned',
+ title: 'Pinned',
+ },
+ {
+ agents: [agent('agt_shared', 'Cook')],
+ collapsible: true,
+ id: 'grp_1',
+ title: 'Kitchen',
+ },
+ ],
+ title: 'Workspace',
+ },
+ ],
+ }),
+}));
+vi.mock('./useTaskBatchActions', () => ({
+ useTaskBatchActions: () => ({ run, running: false }),
+}));
+
+const tasks = [
+ { createdByUserId: 'me', id: 'own', identifier: 'T-1', status: 'backlog', visibility: 'public' },
+ {
+ createdByUserId: 'other',
+ id: 'theirs',
+ identifier: 'T-2',
+ status: 'backlog',
+ visibility: 'public',
+ },
+ {
+ createdByUserId: 'me',
+ id: 'mine',
+ identifier: 'T-3',
+ status: 'backlog',
+ visibility: 'private',
+ },
+] as never[];
+
+const openAgentPage = () => {
+ render(<TaskBulkActionsPanel tasks={tasks} onClose={vi.fn()} />);
+ fireEvent.click(screen.getByText('taskList.bulk.assignAgent'));
+};
+
+beforeEach(() => {
+ useTaskSelectionStore.getState().prune(new Set(['own', 'theirs', 'mine']));
+ useTaskSelectionStore.getState().selectAll(['own', 'theirs', 'mine']);
+});
+
+afterEach(() => {
+ useTaskSelectionStore.getState().clear();
+ run.mockReset();
+ confirmModal.mockReset();
+ rememberAssignee.mockReset();
+});
+
+describe('TaskBulkActionsPanel · assign agent', () => {
+ it('groups agents like the single-task picker', () => {
+ openAgentPage();
+
+ const headings = [...document.querySelectorAll('[cmdk-group-heading]')].map(
+ (node) => node.textContent,
+ );
+ expect(headings).toEqual(['Private', 'Workspace · Pinned', 'Workspace · Kitchen']);
+ const kitchen = screen.getByText('Workspace · Kitchen').closest('[cmdk-group]') as HTMLElement;
+ expect(within(kitchen).getByText('Cook')).toBeTruthy();
+ });
+
+ it('assigns a workspace agent straight away', () => {
+ openAgentPage();
+ fireEvent.click(screen.getByText('Cook'));
+
+ expect(confirmModal).not.toHaveBeenCalled();
+ expect(run).toHaveBeenCalledWith({ kind: 'update', patch: { assigneeAgentId: 'agt_shared' } });
+ expect(rememberAssignee).toHaveBeenCalledWith('agt_shared');
+ });
+
+ it('asks before making public tasks private for a private agent, then assigns them all', async () => {
+ openAgentPage();
+ fireEvent.click(screen.getByText('Secret'));
+
+ expect(run).not.toHaveBeenCalled();
+ expect(rememberAssignee).not.toHaveBeenCalled();
+ expect(confirmModal).toHaveBeenCalledTimes(1);
+ const [modal] = confirmModal.mock.calls[0] as [
+ {
+ content: React.ReactElement<{ count: number; takeOverCount: number }>;
+ onOk: () => void;
+ title: string;
+ },
+ ];
+ expect(modal.title).toBe('taskList.bulk.assignPrivate.title:3');
+ expect(modal.content.props).toEqual({ count: 2, takeOverCount: 1 });
+
+ modal.onOk();
+
+ expect(rememberAssignee).toHaveBeenCalledWith('agt_private');
+
+ expect(run).toHaveBeenCalledWith(
+ { kind: 'update', patch: { assigneeAgentId: 'agt_private' } },
+ expect.objectContaining({ prepare: expect.any(Function) }),
+ );
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx
index db3df2024d9..ce4146f991f 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx
+++ b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx
@@ -30,21 +30,23 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import AgentAvatar from '@/components/AgentAvatar';
+import { type SidebarAgentItem } from '@/database/repositories/home';
import { styles } from '@/features/CommandMenu/styles';
-import { useFetchAgentList } from '@/hooks/useFetchAgentList';
import { usePermission } from '@/hooks/usePermission';
-import { useHomeStore } from '@/store/home';
-import { homeAgentListSelectors } from '@/store/home/selectors';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { pickRecentAssignees } from '../../features/assigneeAgentSections';
import { PRIORITY_META } from '../../features/TaskPriorityTag';
import { STATUS_META } from '../../features/taskStatusMeta';
+import { useAssigneeAgentScopes } from '../../features/useAssigneeAgentScopes';
import { hasWorkspaceMemberDirectory } from '../../shared/memberAssigneeMode';
+import BulkAssignPrivateConfirmContent from './BulkAssignPrivateConfirmContent';
import BulkDeleteConfirmContent from './BulkDeleteConfirmContent';
+import { privatizeTasks } from './privatizeTasks';
import { useTaskSelectionStore } from './store';
-import { countTasksCreatedByOthers } from './taskSelectionModel';
+import { countTasksCreatedByOthers, pickTasksToPrivatize } from './taskSelectionModel';
import { type TaskBatchStatus, useTaskBatchActions } from './useTaskBatchActions';
const BATCH_STATUSES: TaskBatchStatus[] = ['backlog', 'paused', 'completed', 'canceled'];
@@ -87,7 +89,7 @@ const Item = ({
* one batch request for the whole selection (see `useTaskBatchActions`).
*/
const TaskBulkActionsPanel = memo<TaskBulkActionsPanelProps>(({ onClose, tasks }) => {
- const { t } = useTranslation('chat');
+ const { t } = useTranslation(['chat', 'common', 'topic']);
const selectedIds = useTaskSelectionStore((s) => s.selectedIds);
const { run, running } = useTaskBatchActions();
const { allowed: canEdit } = usePermission('create_content');
@@ -96,16 +98,34 @@ const TaskBulkActionsPanel = memo<TaskBulkActionsPanelProps>(({ onClose, tasks }
const [page, setPage] = useState<Page>();
const [search, setSearch] = useState('');
- useFetchAgentList();
- const allAgents = useHomeStore(homeAgentListSelectors.allAgents);
- const agents = useMemo(() => {
- const seen = new Set<string>();
- return allAgents.filter((item) => {
- if (item.type !== 'agent' || seen.has(item.id)) return false;
- seen.add(item.id);
- return true;
+ // The same agents, in the same groups, as the single-task picker. Private
+ // agents get their own scope; picking one makes the selection's public
+ // tasks private first, behind a confirmation (see `assignAgent`).
+ const { inboxAgent, privateAgentIds, recentIds, rememberAssignee, scopes } =
+ useAssigneeAgentScopes({
+ offerPrivate: true,
+ privateTitle: t('taskManager.agentSelector.privateGroup', { ns: 'topic' }),
});
- }, [allAgents]);
+ const recentAgents = useMemo(
+ () =>
+ pickRecentAssignees(
+ recentIds,
+ scopes.flatMap((scope) => scope.sections.flatMap((section) => section.agents)),
+ ),
+ [recentIds, scopes],
+ );
+ const agentGroups = useMemo(
+ () =>
+ scopes.flatMap((scope) =>
+ scope.sections.map((section) => ({
+ agents: section.agents,
+ // cmdk groups do not nest, so a section names its scope too.
+ heading: [scope.title, section.title].filter(Boolean).join(' · ') || undefined,
+ id: section.id,
+ })),
+ ),
+ [scopes],
+ );
const selectedTasks = useMemo(() => {
const ids = new Set(selectedIds);
@@ -140,6 +160,66 @@ const TaskBulkActionsPanel = memo<TaskBulkActionsPanelProps>(({ onClose, tasks }
});
};
+ const assignAgent = (agent: SidebarAgentItem) => {
+ const action = { kind: 'update', patch: { assigneeAgentId: agent.id } } as const;
+ const targets = privateAgentIds.has(agent.id)
+ ? pickTasksToPrivatize(selectedTasks, userId)
+ : [];
+ if (targets.length === 0) {
+ rememberAssignee(agent.id);
+ act(action);
+ return;
+ }
+
+ onClose();
+ // A public task only takes a private agent once it is private itself. The
+ // single-task picker asks before doing that; so does the batch, instead of
+ // letting the server skip every public task.
+ const takeOverCount = targets.filter((target) => target.takeOwnership).length;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: (
+ <BulkAssignPrivateConfirmContent count={targets.length} takeOverCount={takeOverCount} />
+ ),
+ okButtonProps: { danger: true },
+ okText: t('taskList.bulk.assignPrivate.ok'),
+ onOk: () => {
+ // Recent records what was assigned, so a cancelled pick leaves it alone.
+ rememberAssignee(agent.id);
+ void run(action, {
+ prepare: (ids) => {
+ const selected = new Set(ids);
+ return privatizeTasks(targets.filter((target) => selected.has(target.id)));
+ },
+ });
+ },
+ title: t('taskList.bulk.assignPrivate.title', { count: selectedIds.length }),
+ });
+ };
+
+ const renderAgent = (agent: SidebarAgentItem, sectionId: string) => {
+ const name = agentDisplayName(agent) ?? agent.id;
+ return (
+ <Item
+ disabled={disabled}
+ key={`${sectionId}:${agent.id}`}
+ label={name}
+ // An agent can be listed under Recent and its group; values stay unique.
+ value={`agent ${sectionId} ${agent.id} ${name}`}
+ icon={
+ <AgentAvatar
+ agentId={agent.id}
+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}
+ name={name}
+ shape={'square'}
+ size={20}
+ />
+ }
+ onSelect={() => assignAgent(agent)}
+ />
+ );
+ };
+
const copyIds = async () => {
const identifiers = selectedTasks.map((task) => task.identifier).join('\n');
await copyToClipboard(identifiers);
@@ -319,36 +399,31 @@ const TaskBulkActionsPanel = memo<TaskBulkActionsPanelProps>(({ onClose, tasks }
)}
{page === 'agent' && (
- <Command.Group>
- <Item
- disabled={disabled}
- icon={<Icon className={styles.icon} icon={UserRoundXIcon} />}
- label={t('taskList.bulk.unassignAgent')}
- value={'unassigned none'}
- onSelect={() => act({ kind: 'update', patch: { assigneeAgentId: null } })}
- />
- {agents.map((agent) => {
- const name = agentDisplayName(agent) ?? agent.id;
- return (
- <Item
- disabled={disabled}
- key={agent.id}
- label={name}
- value={`agent ${agent.id} ${name}`}
- icon={
- <AgentAvatar
- agentId={agent.id}
- avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}
- name={name}
- shape={'square'}
- size={20}
- />
- }
- onSelect={() => act({ kind: 'update', patch: { assigneeAgentId: agent.id } })}
- />
- );
- })}
- </Command.Group>
+ <>
+ <Command.Group>
+ <Item
+ disabled={disabled}
+ icon={<Icon className={styles.icon} icon={UserRoundXIcon} />}
+ label={t('taskList.bulk.unassignAgent')}
+ value={'unassigned none'}
+ onSelect={() => act({ kind: 'update', patch: { assigneeAgentId: null } })}
+ />
+ {inboxAgent && renderAgent(inboxAgent, 'inbox')}
+ </Command.Group>
+ {/* Recent only helps before typing; a search lists each match once. */}
+ {!search && recentAgents.length > 0 && (
+ <Command.Group
+ heading={t('taskManager.agentSelector.recentGroup', { ns: 'topic' })}
+ >
+ {recentAgents.map((agent) => renderAgent(agent, 'recent'))}
+ </Command.Group>
+ )}
+ {agentGroups.map((group) => (
+ <Command.Group heading={group.heading} key={group.id}>
+ {group.agents.map((agent) => renderAgent(agent, group.id))}
+ </Command.Group>
+ ))}
+ </>
)}
</Command.List>
</Command>
diff --git a/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.test.ts b/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.test.ts
new file mode 100644
index 00000000000..a209de098f6
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { privatizeTasks } from './privatizeTasks';
+
+vi.mock('@/services/task', () => ({ taskService: { updateVisibility: vi.fn() } }));
+
+describe('privatizeTasks', () => {
+ it('makes each task private, taking over teammates’ tasks, and counts failures', async () => {
+ const update = vi.fn(async (id: string) => {
+ if (id === 'locked') throw new Error('Task is being edited by another user');
+ });
+
+ const { failed } = await privatizeTasks(
+ [
+ { id: 'own', takeOwnership: false },
+ { id: 'theirs', takeOwnership: true },
+ { id: 'locked', takeOwnership: false },
+ ],
+ update as never,
+ );
+
+ expect(update).toHaveBeenCalledWith('own', 'private');
+ expect(update).toHaveBeenCalledWith('theirs', 'private', { takeOwnership: true });
+ expect(failed).toEqual(['locked']);
+ });
+
+ it('keeps at most five visibility changes in flight', async () => {
+ let inFlight = 0;
+ let peak = 0;
+ const update = vi.fn(async () => {
+ inFlight++;
+ peak = Math.max(peak, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ inFlight--;
+ });
+
+ await privatizeTasks(
+ Array.from({ length: 12 }, (_, index) => ({ id: `t${index}`, takeOwnership: false })),
+ update as never,
+ );
+
+ expect(update).toHaveBeenCalledTimes(12);
+ expect(peak).toBe(5);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.ts b/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.ts
new file mode 100644
index 00000000000..498d49bdee5
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/privatizeTasks.ts
@@ -0,0 +1,36 @@
+import { taskService } from '@/services/task';
+
+import type { TaskToPrivatize } from './taskSelectionModel';
+
+/** Visibility changes in flight at once; each one locks and rewrites a subtree. */
+const PRIVATIZE_CONCURRENCY = 5;
+
+/**
+ * Make each task private (taking over a teammate's task) ahead of a batch
+ * assignment to a private agent. A task that cannot go private (edited by
+ * someone else, running subtasks, subtasks by other members…) stays public and
+ * the batch then reports it as skipped, so failures are counted, not thrown.
+ */
+export const privatizeTasks = async (
+ targets: readonly TaskToPrivatize[],
+ update: typeof taskService.updateVisibility = taskService.updateVisibility,
+): Promise<{ failed: string[] }> => {
+ const failed: string[] = [];
+ let next = 0;
+ const worker = async () => {
+ while (next < targets.length) {
+ const target = targets[next++];
+ try {
+ await (target.takeOwnership
+ ? update(target.id, 'private', { takeOwnership: true })
+ : update(target.id, 'private'));
+ } catch {
+ failed.push(target.id);
+ }
+ }
+ };
+ await Promise.all(
+ Array.from({ length: Math.min(PRIVATIZE_CONCURRENCY, targets.length) }, worker),
+ );
+ return { failed };
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts
index 8c0512b18db..1cbf3fa02e1 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts
@@ -5,6 +5,7 @@ import {
countTasksCreatedByOthers,
isEditableTarget,
mergeOutcomes,
+ pickTasksToPrivatize,
pruneSelection,
selectRange,
toggleSelection,
@@ -78,3 +79,23 @@ describe('taskSelectionModel', () => {
expect(countTasksCreatedByOthers([], 'me')).toBe(0);
});
});
+
+describe('pickTasksToPrivatize', () => {
+ it('picks the public tasks that are not running and flags teammates’ tasks as takeovers', () => {
+ expect(
+ pickTasksToPrivatize(
+ [
+ { createdByUserId: 'me', id: 'own', status: 'backlog', visibility: 'public' },
+ { createdByUserId: 'other', id: 'theirs', status: 'paused', visibility: 'public' },
+ { createdByUserId: 'me', id: 'private', status: 'backlog', visibility: 'private' },
+ { createdByUserId: 'other', id: 'running', status: 'running', visibility: 'public' },
+ { id: 'legacy', status: 'backlog', visibility: null },
+ ],
+ 'me',
+ ),
+ ).toEqual([
+ { id: 'own', takeOwnership: false },
+ { id: 'theirs', takeOwnership: true },
+ ]);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts
index d50e6045a18..a5a70c6e57c 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts
@@ -83,3 +83,31 @@ export const countTasksCreatedByOthers = (
if (!userId) return 0;
return tasks.filter((task) => !!task.createdByUserId && task.createdByUserId !== userId).length;
};
+
+export interface TaskToPrivatize {
+ id: string;
+ /** Another member created it: going private takes it over as the caller's own. */
+ takeOwnership: boolean;
+}
+
+/**
+ * The selected tasks that must go private before a private agent can be
+ * assigned to them, as the single-task picker does after its confirmation.
+ * A running task keeps its assignee (the batch skips it), so it is left as it
+ * is rather than made private for nothing.
+ */
+export const pickTasksToPrivatize = (
+ tasks: readonly {
+ createdByUserId?: string | null;
+ id: string;
+ status?: string | null;
+ visibility?: string | null;
+ }[],
+ userId: string | null | undefined,
+): TaskToPrivatize[] =>
+ tasks
+ .filter((task) => task.visibility === 'public' && task.status !== 'running')
+ .map((task) => ({
+ id: task.id,
+ takeOwnership: !!task.createdByUserId && task.createdByUserId !== userId,
+ }));
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
index f62363eb78f..a449d22f731 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
@@ -78,6 +78,33 @@ describe('useTaskBatchActions', () => {
expect([...keep.keys()]).toEqual(['a']);
});
+ it('runs the prepare step after the overlay and before the batch request', async () => {
+ const order: string[] = [];
+ beginOptimistic.mockImplementationOnce(() => {
+ order.push('overlay');
+ return overlay;
+ });
+ batchUpdate.mockImplementation(async () => {
+ order.push('batch');
+ return { failed: [], skipped: [], updated: ['a', 'b'] };
+ });
+ const prepare = vi.fn(async (ids: string[]) => {
+ order.push(`prepare:${ids.join(',')}`);
+ });
+ useTaskSelectionStore.getState().prune(new Set(['a', 'b']));
+ useTaskSelectionStore.getState().selectAll(['a', 'b']);
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ await act(() =>
+ result.current.run(
+ { kind: 'update', patch: { assigneeAgentId: 'agt_private' } },
+ { prepare },
+ ),
+ );
+
+ expect(order).toEqual(['overlay', 'prepare:a,b', 'batch']);
+ });
+
it('shows the result and clears the selection before the server answers', async () => {
let resolve!: (value: unknown) => void;
batchUpdate.mockReturnValue(new Promise((r) => (resolve = r)));
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
index d374032d0cf..b57aaa3f68c 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
@@ -21,6 +21,15 @@ import { useBackgroundTaskListRefresh } from './useBackgroundTaskListRefresh';
export type { TaskBatchAction, TaskBatchStatus } from './optimisticBatch';
+export interface TaskBatchRunOptions {
+ /**
+ * Work the batch depends on, run in the request queue ahead of it (after the
+ * optimistic overlay is up), e.g. making tasks private before a private
+ * agent is assigned to them. It receives the selected ids.
+ */
+ prepare?: (ids: string[]) => Promise<unknown>;
+}
+
const runChunk = (action: TaskBatchAction, ids: string[]): Promise<TaskBatchResponse> => {
switch (action.kind) {
case 'archive': {
@@ -56,7 +65,7 @@ export const useTaskBatchActions = () => {
const { undo } = useTaskBatchUndo();
const run = useCallback(
- async (action: TaskBatchAction) => {
+ async (action: TaskBatchAction, runOptions?: TaskBatchRunOptions) => {
const ids = [...useTaskSelectionStore.getState().selectedIds];
if (ids.length === 0) return;
@@ -70,6 +79,7 @@ export const useTaskBatchActions = () => {
let requestError: unknown;
await enqueueBatchRequest(async () => {
try {
+ await runOptions?.prepare?.(ids);
// Sequential: each chunk is already a set-based write on the server,
// and ordering keeps a later chunk from racing an earlier one.
for (const chunk of chunkIds(ids)) outcomes.push(await runChunk(action, chunk));
diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
index 40e8703c211..c891b9773bd 100644
--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx
@@ -1,4 +1,3 @@
-import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';
import { agentDisplayName } from '@lobechat/types';
import {
confirmModal,
@@ -10,7 +9,6 @@ import {
Text,
Tooltip,
} from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronRight, UserRoundX } from 'lucide-react';
import type { CSSProperties, KeyboardEvent, ReactNode } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -22,26 +20,19 @@ import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import AgentItem from '@/features/PageEditor/Copilot/AgentSelector/AgentItem';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
-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 { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
import {
- type AssigneeAgentSection,
- buildAssigneeAgentSections,
filterAssigneeSections,
matchesAssigneeSearch,
pickRecentAssignees,
- pushRecentAssignee,
shouldOfferPrivateAgents,
} from './assigneeAgentSections';
+import { useAssigneeAgentScopes } from './useAssigneeAgentScopes';
interface AssigneeAgentSelectorProps {
/** Offer the "unassigned" option; off where an owner is required. */
@@ -79,12 +70,6 @@ type PickerRow =
title: string;
};
-interface PickerScope {
- id: string;
- sections: AssigneeAgentSection[];
- title?: string;
-}
-
const RECENT_SECTION_ID = 'recent';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -102,6 +87,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: transparent;
outline: none;
+ /* The global focus ring would box the whole popover top; the divider takes its place. */
+ &:focus-visible {
+ border-block-end-color: ${cssVar.colorPrimary};
+ }
+
&::placeholder {
color: ${cssVar.colorTextPlaceholder};
}
@@ -189,30 +179,9 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
const updateTask = useTaskStore((s) => s.updateTask);
const updateTaskVisibility = useTaskStore((s) => s.updateTaskVisibility);
const currentUserId = useUserStore(userProfileSelectors.userId);
- const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);
- const agentGroups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
- const ungroupedAgents = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
- const privateAgentGroups = useHomeStore(homeAgentListSelectors.privateAgentGroups, isEqual);
- const privatePinnedAgents = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
- const privateUngroupedAgents = useHomeStore(
- homeAgentListSelectors.privateUngroupedAgents,
- isEqual,
- );
- const hasPrivateAgents = useHomeStore(homeAgentListSelectors.hasPrivateAgents);
- const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
-
- const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const inboxMeta = useAgentStore((s) =>
- inboxAgentId ? agentSelectors.getAgentMetaById(inboxAgentId)(s) : undefined,
- );
-
- useFetchAgentList();
-
- 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);
+ const workspaceId = useActiveWorkspaceId();
const {
offer: offerPrivateAgents,
@@ -227,79 +196,16 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
workspaceId,
});
- const scopes = useMemo<PickerScope[]>(() => {
- const labels = {
- pinned: t('navPanel.pinned', { ns: 'common' }),
- ungrouped: t('defaultList', { ns: 'chat' }),
- };
- const result: PickerScope[] = [];
-
- if (offerPrivateAgents)
- result.push({
- id: 'private',
- sections: buildAssigneeAgentSections({
- groups: privateAgentGroups,
- labels,
- pinned: privatePinnedAgents,
- scope: 'private',
- ungrouped: privateUngroupedAgents,
- }),
- title: takesOver
- ? t('taskManager.agentSelector.privateGroupTakesOver', { ns: 'topic' })
- : offerPrivateOnPublic
- ? t('taskManager.agentSelector.privateGroupMakesPrivate', { ns: 'topic' })
- : 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,
+ const { inboxAgent, isAgentListInit, privateAgentIds, recentIds, rememberAssignee, scopes } =
+ useAssigneeAgentScopes({
+ offerPrivate: offerPrivateAgents,
+ privateTitle: takesOver
+ ? t('taskManager.agentSelector.privateGroupTakesOver', { ns: 'topic' })
+ : offerPrivateOnPublic
+ ? t('taskManager.agentSelector.privateGroupMakesPrivate', { ns: 'topic' })
+ : t('taskManager.agentSelector.privateGroup', { ns: 'topic' }),
});
- return result;
- }, [
- agentGroups,
- hasPrivateAgents,
- offerPrivateAgents,
- offerPrivateOnPublic,
- pinnedAgents,
- privateAgentGroups,
- privatePinnedAgents,
- privateUngroupedAgents,
- t,
- takesOver,
- 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)),
- );
- 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 recentAgents = useMemo(
() =>
@@ -395,24 +301,9 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0);
}, [currentAgentId, flatOptions, query]);
- const privateAgentIds = useMemo(
- () =>
- new Set(
- scopes
- .find((scope) => scope.id === 'private')
- ?.sections.flatMap((section) => section.agents.map((agent) => agent.id)),
- ),
- [scopes],
- );
-
const assignAgent = useCallback(
(agentId: string | null, agent?: SidebarAgentItem) => {
- if (agentId) {
- const current = useGlobalStore.getState().status.recentAssigneeAgentIds?.[recentKey];
- updateSystemStatus({
- recentAssigneeAgentIds: { [recentKey]: pushRecentAssignee(current, agentId) },
- });
- }
+ if (agentId) rememberAssignee(agentId);
if (onChange) {
onChange(agentId);
return;
@@ -437,7 +328,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(
},
);
},
- [onChange, recentKey, taskIdentifier, updateSystemStatus, updateTask],
+ [onChange, rememberAssignee, taskIdentifier, updateTask],
);
const handleAgentChange = useCallback(
diff --git a/src/features/AgentTasks/features/useAssigneeAgentScopes.ts b/src/features/AgentTasks/features/useAssigneeAgentScopes.ts
new file mode 100644
index 00000000000..41de1a713cc
--- /dev/null
+++ b/src/features/AgentTasks/features/useAssigneeAgentScopes.ts
@@ -0,0 +1,170 @@
+import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';
+import { agentDisplayName } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { type SidebarAgentItem } from '@/database/repositories/home';
+import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+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 {
+ type AssigneeAgentSection,
+ buildAssigneeAgentSections,
+ pushRecentAssignee,
+} from './assigneeAgentSections';
+
+export interface AssigneeAgentScope {
+ id: 'private' | 'workspace';
+ sections: AssigneeAgentSection[];
+ /** Omitted when the workspace list is the only scope, so it keeps no header. */
+ title?: string;
+}
+
+interface UseAssigneeAgentScopesParams {
+ /** List the user's private agents in their own scope, ahead of the workspace's. */
+ offerPrivate: boolean;
+ /** Header of the private scope; it says what picking one does to the task. */
+ privateTitle: string;
+}
+
+/**
+ * The agents an assignee picker offers, laid out like the sidebar: the user's
+ * private agents and the workspace's, each split into pinned, sidebar groups
+ * and the rest; plus the inbox when no group lists it. Shared by the single
+ * task picker and the batch actions panel so both group agents the same way.
+ */
+export const useAssigneeAgentScopes = ({
+ offerPrivate,
+ privateTitle,
+}: UseAssigneeAgentScopesParams) => {
+ const { t } = useTranslation(['chat', 'common', 'topic']);
+
+ useFetchAgentList();
+
+ const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);
+ const agentGroups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
+ const ungroupedAgents = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
+ const privateAgentGroups = useHomeStore(homeAgentListSelectors.privateAgentGroups, isEqual);
+ const privatePinnedAgents = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
+ const privateUngroupedAgents = useHomeStore(
+ homeAgentListSelectors.privateUngroupedAgents,
+ isEqual,
+ );
+ const hasPrivateAgents = useHomeStore(homeAgentListSelectors.hasPrivateAgents);
+ const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
+
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const inboxMeta = useAgentStore((s) =>
+ inboxAgentId ? agentSelectors.getAgentMetaById(inboxAgentId)(s) : undefined,
+ );
+
+ const workspaceId = useActiveWorkspaceId();
+ const recentKey = workspaceId ?? 'personal';
+ const recentIds = useGlobalStore((s) => s.status.recentAssigneeAgentIds?.[recentKey]);
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+
+ const scopes = useMemo<AssigneeAgentScope[]>(() => {
+ const labels = {
+ pinned: t('navPanel.pinned', { ns: 'common' }),
+ ungrouped: t('defaultList', { ns: 'chat' }),
+ };
+ const result: AssigneeAgentScope[] = [];
+
+ if (offerPrivate)
+ result.push({
+ id: 'private',
+ sections: buildAssigneeAgentSections({
+ groups: privateAgentGroups,
+ labels,
+ pinned: privatePinnedAgents,
+ scope: 'private',
+ ungrouped: privateUngroupedAgents,
+ }),
+ title: privateTitle,
+ });
+
+ result.push({
+ id: 'workspace',
+ sections: buildAssigneeAgentSections({
+ groups: agentGroups,
+ labels,
+ pinned: pinnedAgents,
+ scope: 'workspace',
+ ungrouped: ungroupedAgents,
+ }),
+ title: hasPrivateAgents
+ ? t('taskManager.agentSelector.workspaceGroup', { ns: 'topic' })
+ : undefined,
+ });
+
+ return result;
+ }, [
+ agentGroups,
+ hasPrivateAgents,
+ offerPrivate,
+ pinnedAgents,
+ privateAgentGroups,
+ privatePinnedAgents,
+ privateTitle,
+ privateUngroupedAgents,
+ t,
+ 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)),
+ );
+ 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 privateAgentIds = useMemo(
+ () =>
+ new Set(
+ scopes
+ .find((scope) => scope.id === 'private')
+ ?.sections.flatMap((section) => section.agents.map((agent) => agent.id)),
+ ),
+ [scopes],
+ );
+
+ /** Move a picked agent to the front of this workspace's Recent list. */
+ const rememberAssignee = useCallback(
+ (agentId: string) => {
+ const current = useGlobalStore.getState().status.recentAssigneeAgentIds?.[recentKey];
+ updateSystemStatus({
+ recentAssigneeAgentIds: { [recentKey]: pushRecentAssignee(current, agentId) },
+ });
+ },
+ [recentKey, updateSystemStatus],
+ );
+
+ return {
+ hasPrivateAgents,
+ inboxAgent,
+ isAgentListInit,
+ privateAgentIds,
+ recentIds,
+ rememberAssignee,
+ scopes,
+ workspaceId,
+ };
+};