🤯 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): private agents on public tasks — make private or take over (#21937)
Rdmclin2a46df00e7c7d
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex fd841161570..4712ea44fe2 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -1870,6 +1870,109 @@ describe('Task Router Integration', () => {expect(strandedCreate).toHaveLength(0);});+ it('should let a member take over another member’s public task as their private task', async () => {+ otherUserId = await createTestUser(serverDB);+ const workspaceId = 'task-take-over-workspace';+ const { tasks, workspaces, workspaceMembers } = await import('@/database/schemas');+ const { eq } = await import('drizzle-orm');+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Task Take Over Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId, workspaceId },+ { role: 'member', userId: otherUserId!, workspaceId },+ ]);+ const ownerCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });+ const memberCaller = taskRouter.createCaller({+ ...createTestContext(otherUserId!),+ workspaceId,+ });++ const root = await ownerCaller.create({+ assigneeUserId: userId,+ automationMode: 'schedule',+ instruction: 'Owner task',+ schedulePattern: '0 9 * * *',+ visibility: 'public',+ });+ const child = await ownerCaller.create({+ instruction: 'Owner subtask',+ parentTaskId: root.data.id,+ });++ // Without opting in, a non-creator still cannot demote it.+ await expect(+ memberCaller.updateVisibility({ id: root.data.id, visibility: 'private' }),+ ).rejects.toThrow('Only the task creator can make this task private');++ const taken = await memberCaller.updateVisibility({+ id: root.data.id,+ takeOwnership: true,+ visibility: 'private',+ });+ expect(taken.data).toMatchObject({+ assigneeUserId: null,+ automationMode: null,+ createdByUserId: otherUserId,+ status: 'backlog',+ visibility: 'private',+ });++ const [childRow] = await serverDB+ .select({ createdByUserId: tasks.createdByUserId, visibility: tasks.visibility })+ .from(tasks)+ .where(eq(tasks.id, child.data.id));+ expect(childRow).toEqual({ createdByUserId: otherUserId, visibility: 'private' });++ // The previous creator no longer sees it.+ await expect(ownerCaller.find({ id: root.data.id })).rejects.toThrow();+ });++ it('should not take over a task while a subtask is running', async () => {+ otherUserId = await createTestUser(serverDB);+ const workspaceId = 'task-take-over-running-workspace';+ const { tasks, workspaces, workspaceMembers } = await import('@/database/schemas');+ const { eq } = await import('drizzle-orm');+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Task Take Over Running Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId, workspaceId },+ { role: 'member', userId: otherUserId!, workspaceId },+ ]);+ const ownerCaller = taskRouter.createCaller({ ...createTestContext(userId), workspaceId });+ const memberCaller = taskRouter.createCaller({+ ...createTestContext(otherUserId!),+ workspaceId,+ });++ const root = await ownerCaller.create({ instruction: 'Busy root', visibility: 'public' });+ const child = await ownerCaller.create({+ instruction: 'Busy subtask',+ parentTaskId: root.data.id,+ });+ await serverDB.update(tasks).set({ status: 'running' }).where(eq(tasks.id, child.data.id));++ await expect(+ memberCaller.updateVisibility({+ id: root.data.id,+ takeOwnership: true,+ visibility: 'private',+ }),+ ).rejects.toThrow('Cannot take over this task while it or a subtask is running');+ const [rootRow] = await serverDB+ .select({ createdByUserId: tasks.createdByUserId, visibility: tasks.visibility })+ .from(tasks)+ .where(eq(tasks.id, root.data.id));+ expect(rootRow).toEqual({ createdByUserId: userId, visibility: 'public' });+ });+it('should keep private tasks creator-only for human assignees', async () => {otherUserId = await createTestUser(serverDB);const workspaceId = 'task-private-assignee-workspace';@@ -1906,21 +2009,19 @@ describe('Task Router Integration', () => {wsCaller.update({ assigneeUserId: otherUserId, id: privateTask.data.id }),).rejects.toThrow('A private task can only be assigned to its creator');- // Demoting a member-assigned public task to private is rejected until unassigned.+ // Demoting a member-assigned public task to private unassigns the member,+ // who could no longer open it.const publicTask = await wsCaller.create({assigneeUserId: otherUserId,instruction: 'Public task assigned to member',visibility: 'public',});- await expect(- wsCaller.updateVisibility({ id: publicTask.data.id, visibility: 'private' }),- ).rejects.toThrow('A private task can only be assigned to its creator');- await wsCaller.update({ assigneeUserId: null, id: publicTask.data.id });const demoted = await wsCaller.updateVisibility({id: publicTask.data.id,visibility: 'private',});expect(demoted.data.visibility).toBe('private');+ expect(demoted.data.assigneeUserId).toBeNull();});it('should preserve the responsible assignee independently of automation', async () => {diff --git a/apps/server/src/routers/lambda/task/update.ts b/apps/server/src/routers/lambda/task/update.tsindex bb5ea4f7061..57803e6b5f6 100644--- a/apps/server/src/routers/lambda/task/update.ts+++ b/apps/server/src/routers/lambda/task/update.ts@@ -2,6 +2,7 @@ import { TASK_STATUSES } from '@lobechat/builtin-tool-task';import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { TaskTakeOverError } from '@/database/repositories/taskSubtree';import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';import { router } from '@/libs/trpc/lambda';@@ -159,10 +160,25 @@ export const updateRouter = router({}}),updateVisibility: taskProcedureWrite- .input(idInput.merge(z.object({ visibility: z.enum(['private', 'public']) })))+ .input(+ idInput.merge(+ z.object({+ // A member making someone else's public task private takes it over:+ // it becomes their private task. Opt-in, so a plain demotion by a+ // non-creator still fails instead of silently moving the task.+ takeOwnership: z.boolean().optional(),+ visibility: z.enum(['private', 'public']),+ }),+ ),+ ).mutation(async ({ input, ctx }) => {try {const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);+ const takeOwnership =+ !!ctx.workspaceId &&+ !!input.takeOwnership &&+ input.visibility === 'private' &&+ resolved.createdByUserId !== ctx.userId;// Mirror the edit-lock contract from `update`: reject visibility flips// while another workspace member is actively editing this task. Without@@ -181,11 +197,10 @@ export const updateRouter = router({// The creator can always change visibility on their own tasks. In// workspace mode, workspace owners may still promote other members'- // tasks (mirrors the transferTask policy at line ~1166), but demoting- // to private stays creator-only: the task would land in- // the creator's private list, so an owner-initiated demotion just- // appropriates another member's data.- if (ctx.workspaceId && resolved.createdByUserId !== ctx.userId) {+ // tasks (mirrors the transferTask policy at line ~1166). Demoting+ // someone else's task leaves it in the creator's private list, so a+ // non-creator may only demote by taking the task over as their own.+ if (ctx.workspaceId && resolved.createdByUserId !== ctx.userId && !takeOwnership) {if (input.visibility === 'private') {throw new TRPCError({code: 'FORBIDDEN',@@ -226,16 +241,10 @@ export const updateRouter = router({}}- // Demoting a member-assigned task to private would strand the- // assignee: the task disappears from their view while still carrying- // their name. Reject early — unassign first, then demote.- if (input.visibility === 'private') {- ctx.taskService.assertAssigneeUserVisibilityCompat(- input.visibility,- resolved.assigneeUserId,- resolved.createdByUserId,- );- }+ // A member assignee does not block demotion: the subtree write clears+ // every assignee other than the creator in the same transaction, since+ // the task disappears from that member's view (see+ // `setSubtreeVisibility`).// A private assignee agent on a public task breaks the visibility// invariant. Reject early — reassign first, then promote.@@ -252,7 +261,16 @@ export const updateRouter = router({ctx.taskService.assertParentVisibilityCompat(input.visibility, parent?.visibility);}- const updated = await ctx.taskSubtree.updateVisibility(resolved.id, input.visibility);+ // A takeover re-checks running runs and hidden private subtasks under+ // the subtree lock (`TaskTakeOverError`).+ const updated = await ctx.taskSubtree+ .updateVisibility(resolved.id, input.visibility, { takeOwnership })+ .catch((error: unknown) => {+ if (error instanceof TaskTakeOverError) {+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });+ }+ throw error;+ });if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });return { data: updated, message: 'Task visibility updated', success: true };} catch (error) {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 7560f13fca1..7863b87178a 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2446,6 +2446,7 @@"taskDetail.latestActivity.topicFromSubtask": "{{identifier}} · {{topic}}","taskDetail.latestActivity.topicWithSeq": "Topic #{{seq}}: {{title}}","taskDetail.latestActivity.untitledTopic": "Untitled topic",+ "taskDetail.makePrivate.errorOtherCreators": "This task has subtasks created by other members. Move or remove them before making it private.","taskDetail.modelConfig": "Model Override","taskDetail.navigation": "Navigation","taskDetail.nextRunCountdown": "Next run in {{countdown}}",@@ -2544,6 +2545,13 @@"taskDetail.subIssueOf": "Sub-issue of","taskDetail.subtaskInstructionPlaceholder": "Describe the sub-task...","taskDetail.subtasks": "Subtasks",+ "taskDetail.takeOver.confirmHint": "This task belongs to another member. It and its subtasks become your private task: its creator and other members lose access, and its schedule or heartbeat is turned off.",+ "taskDetail.takeOver.confirmOk": "Take over",+ "taskDetail.takeOver.confirmTitle": "Take this task over as your private task?",+ "taskDetail.takeOver.errorHiddenSubtasks": "This task has private subtasks its creator kept to themselves, so it cannot be taken over.",+ "taskDetail.takeOver.errorRunning": "This task or one of its subtasks is running. Take it over once the run finishes.",+ "taskDetail.takeOver.menuLabel": "Take over as private",+ "taskDetail.takeOver.success": "Taken over as your private task","taskDetail.titlePlaceholder": "Task title","taskDetail.topicDrawer.collapse": "Restore conversation panel","taskDetail.topicDrawer.expand": "Expand conversation panel",diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 60cf2ddbac8..4cbabe65bea 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -293,8 +293,16 @@"sidebar.expandAll": "Expand all groups","sidebar.title": "Topics","taskManager.agent": "Task Agent",+ "taskManager.agentSelector.makePrivateConfirm.hint": "This agent is private, so the task and its subtasks become private before it is assigned. Members assigned to them are unassigned.",+ "taskManager.agentSelector.makePrivateConfirm.ok": "Make private and assign",+ "taskManager.agentSelector.makePrivateConfirm.title": "Assign to a private agent?","taskManager.agentSelector.privateGroup": "Private",+ "taskManager.agentSelector.privateGroupMakesPrivate": "Private · makes this task private",+ "taskManager.agentSelector.privateGroupTakesOver": "Private · takes this task over as yours","taskManager.agentSelector.recentGroup": "Recently assigned",+ "taskManager.agentSelector.takeOverConfirm.hint": "This agent is private, so the task and its subtasks become your private task before it is assigned. Its creator and other members lose access, and its schedule or heartbeat is turned off.",+ "taskManager.agentSelector.takeOverConfirm.ok": "Take over and assign",+ "taskManager.agentSelector.takeOverConfirm.title": "Take this task over as yours?","taskManager.agentSelector.workspaceGroup": "Workspace","taskManager.welcome": "Ask me about your tasks","temp": "Temporary",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex f6edd83eaff..8e1a003f516 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2446,6 +2446,7 @@"taskDetail.latestActivity.topicFromSubtask": "{{identifier}} · {{topic}}","taskDetail.latestActivity.topicWithSeq": "话题 #{{seq}}:{{title}}","taskDetail.latestActivity.untitledTopic": "未命名话题",+ "taskDetail.makePrivate.errorOtherCreators": "此任务包含其他成员创建的子任务,请先移走或删除这些子任务,再设为私人。","taskDetail.modelConfig": "模型覆盖","taskDetail.navigation": "导航","taskDetail.nextRunCountdown": "{{countdown}} 后执行",@@ -2544,6 +2545,13 @@"taskDetail.subIssueOf": "隶属于","taskDetail.subtaskInstructionPlaceholder": "描述这个子任务…","taskDetail.subtasks": "子任务",+ "taskDetail.takeOver.confirmHint": "此任务由其他成员创建。确认后它及其子任务将成为你的私人任务:创建者和其他成员将无法再看到它,定时与心跳会被关闭。",+ "taskDetail.takeOver.confirmOk": "收归",+ "taskDetail.takeOver.confirmTitle": "收归为你的私人任务?",+ "taskDetail.takeOver.errorHiddenSubtasks": "此任务包含创建者设为私人的子任务,无法收归。",+ "taskDetail.takeOver.errorRunning": "此任务或其子任务正在运行,请等运行结束后再收归。",+ "taskDetail.takeOver.menuLabel": "收归为我的私人任务",+ "taskDetail.takeOver.success": "已收归为你的私人任务","taskDetail.titlePlaceholder": "输入任务标题…","taskDetail.topicDrawer.collapse": "恢复对话面板","taskDetail.topicDrawer.expand": "展开对话面板",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex c13c02b8834..a2440e0c54f 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -293,8 +293,16 @@"sidebar.expandAll": "展开所有分组","sidebar.title": "话题","taskManager.agent": "任务助手",+ "taskManager.agentSelector.makePrivateConfirm.hint": "该助理为私人助理,指派前任务及其子任务会先设为私人,已指派的成员会被移除。",+ "taskManager.agentSelector.makePrivateConfirm.ok": "设为私人并指派",+ "taskManager.agentSelector.makePrivateConfirm.title": "指派给私人助理?","taskManager.agentSelector.privateGroup": "私人",+ "taskManager.agentSelector.privateGroupMakesPrivate": "私人 · 任务将设为私人",+ "taskManager.agentSelector.privateGroupTakesOver": "私人 · 任务将收归为你的私人任务","taskManager.agentSelector.recentGroup": "最近指派",+ "taskManager.agentSelector.takeOverConfirm.hint": "该助理为私人助理,指派前任务及其子任务会先收归为你的私人任务。创建者和其他成员将无法再看到它,定时与心跳会被关闭。",+ "taskManager.agentSelector.takeOverConfirm.ok": "收归并指派",+ "taskManager.agentSelector.takeOverConfirm.title": "收归为你的私人任务?","taskManager.agentSelector.workspaceGroup": "工作区","taskManager.welcome": "有什么任务问题想问我?","temp": "临时",diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.tsindex 7e8f22c0e78..2cdf74e307d 100644--- a/packages/database/src/models/task/index.ts+++ b/packages/database/src/models/task/index.ts@@ -193,6 +193,14 @@ export class TaskModel {return rows.countTasksBlockingAgentDemotion(this.ctx, assigneeAgentId, agentOwnerUserId);}+ async lockWholeSubtree(rootId: string): Promise<{ id: string; status: string }[]> {+ return tree.lockWholeSubtree(this.ctx, rootId);+ }++ async takeOverSubtree(taskIds: string[]): Promise<void> {+ return tree.takeOverSubtree(this.ctx, taskIds);+ }+async subtreeHasOtherCreators(rootTaskId: string, creatorUserId: string): Promise<boolean> {return rows.subtreeHasOtherCreators(this.ctx, rootTaskId, creatorUserId);}diff --git a/packages/database/src/models/task/tree.ts b/packages/database/src/models/task/tree.tsindex e26eb36b93f..bb827b13b44 100644--- a/packages/database/src/models/task/tree.ts+++ b/packages/database/src/models/task/tree.ts@@ -1,5 +1,5 @@import type { TaskItem } from '@lobechat/types';-import { and, eq, inArray, sql } from 'drizzle-orm';+import { and, eq, inArray, isNotNull, ne, sql } from 'drizzle-orm';import {taskActivities,@@ -189,6 +189,23 @@ export const setSubtreeVisibility = async (const stamp = new Date();return ctx.db.transaction(async (tx) => {+ // A private task is creator-only, so a member assignee would keep a task+ // they can no longer open. Unassign them before the root is read back+ // below; the creator's own assignment and the agent assignee stay.+ if (visibility === 'private') {+ await tx+ .update(tasks)+ .set({ assigneeUserId: null })+ .where(+ and(+ inArray(tasks.id, taskIds),+ taskOwnership(ctx),+ isNotNull(tasks.assigneeUserId),+ ne(tasks.assigneeUserId, tasks.createdByUserId),+ ),+ );+ }+// Update the root with RETURNING so we read the post-update row in the// same statement. A second SELECT filtered by `ownership()` would self-// cancel when a workspace owner demotes another member's task to private:@@ -244,6 +261,55 @@ export const setSubtreeVisibility = async (});};+/**+ * Row-lock every task of a subtree for the enclosing transaction, whatever its+ * visibility, and return their statuses. A takeover authorizes the root it can+ * see, then must act on the whole subtree: private subtasks the caller cannot+ * see and runs starting concurrently both have to be caught under the lock.+ */+export const lockWholeSubtree = async (+ ctx: TaskModelContext,+ rootId: string,+): Promise<{ id: string; status: string }[]> => {+ if (!ctx.workspaceId) return [];+ const result = await ctx.db.execute(sql`+ WITH RECURSIVE task_tree AS (+ SELECT id FROM tasks WHERE id = ${rootId} AND workspace_id = ${ctx.workspaceId}+ UNION ALL+ SELECT t.id FROM tasks t JOIN task_tree tt ON t.parent_task_id = tt.id+ )+ SELECT id, status FROM tasks+ WHERE id IN (SELECT id FROM task_tree) AND is_deleted IS NOT TRUE+ FOR UPDATE+ `);+ return result.rows as { id: string; status: string }[];+};++/**+ * Make the caller the creator of a task subtree, for a member taking another+ * member's public task private as their own. Only the `tasks` rows change: the+ * child rows keep their authors and stay readable through the creator branch+ * of `childOwnership`.+ *+ * Automation stops: runs are attributed to the creator, so the previous+ * creator's queued schedule/heartbeat ticks no longer match the row, and an+ * armed `scheduled` task would otherwise look live with nothing driving it.+ * It returns to `backlog` (`paused` reads as "awaiting review" in the UI); the+ * new creator re-arms it if they want it.+ */+export const takeOverSubtree = async (ctx: TaskModelContext, taskIds: string[]): Promise<void> => {+ if (taskIds.length === 0) return;+ await ctx.db+ .update(tasks)+ .set({+ automationMode: null,+ createdByUserId: ctx.userId,+ status: sql`CASE WHEN ${tasks.status} = 'scheduled' THEN 'backlog' ELSE ${tasks.status} END`,+ updatedAt: new Date(),+ })+ .where(and(inArray(tasks.id, taskIds), taskOwnership(ctx)));+};+/*** Delete the given tasks (owned child rows cascade through their FKs).* Acceptances belong to the verify aggregate; `TaskSubtreeRepository`diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex d9ec54f8ed7..c9a129f21ce 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -181,6 +181,10 @@ export class WorkModel {deleteWork = (params: DeleteWorkParams) => writes.deleteWork(this.ctx, params);+ /** See {@link writes.reassignTaskWorksOwner}. */+ reassignTaskWorksOwner = (taskIds: string[], fromUserId: string): Promise<void> =>+ writes.reassignTaskWorksOwner(this.ctx, taskIds, fromUserId);+/** See {@link writes.setTaskWorksVisibility}. */setTaskWorksVisibility = (taskIds: string[], visibility: WorkVisibility): Promise<void> =>writes.setTaskWorksVisibility(this.ctx, taskIds, visibility);diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.tsindex 48ce9254985..bd58d172401 100644--- a/packages/database/src/models/work/writes.ts+++ b/packages/database/src/models/work/writes.ts@@ -374,6 +374,35 @@ export const setTaskWorksVisibility = async ();};+/**+ * Re-home the Work rows of tasks whose creator changed (a member taking a task+ * over), in the same transaction as the task write. A task Work's `userId` is+ * the task owner, so a row left on the previous creator would stay theirs and+ * drop out of the new owner's lists once the task goes private.+ *+ * Scoped by workspace only: the caller is authorized on the tasks, not on the+ * previous creator's Work rows.+ */+export const reassignTaskWorksOwner = async (+ ctx: WorkContext,+ taskIds: string[],+ fromUserId: string,+): Promise<void> => {+ if (taskIds.length === 0 || !ctx.workspaceId) return;++ await ctx.db+ .update(works)+ .set({ userId: ctx.userId })+ .where(+ and(+ eq(works.resourceType, 'task'),+ inArray(works.resourceId, taskIds),+ eq(works.userId, fromUserId),+ eq(works.workspaceId, ctx.workspaceId),+ ),+ );+};+/*** User-initiated removal of one Work card by its own id. Meant for orphaned* Works (the backing task / document is gone — see `resourceDeleted`), wherediff --git a/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts b/packages/database/src/repositories/taskSubtree/__tests__/index.test.tsindex fd1ba346991..59c2df41192 100644--- a/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts+++ b/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts@@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import { TaskModel } from '../../../models/task';import { TaskTopicModel } from '../../../models/taskTopic';-import { acceptances, documents, topics, users, workspaces } from '../../../schemas';+import { WorkModel } from '../../../models/work';+import { acceptances, documents, topics, users, works, workspaces } from '../../../schemas';import { taskTopics } from '../../../schemas/task';import type { LobeChatDatabase } from '../../../type';import { TaskSubtreeRepository } from '../index';@@ -147,6 +148,133 @@ describe('TaskSubtreeRepository', () => {expect(reload?.visibility).toBe('private');});+ it('should unassign other members across the subtree when demoting to private', async () => {+ // A private task is creator-only: a member assignee could no longer open+ // it, so demotion clears them. The creator's own assignment stays.+ const alice = new TaskModel(serverDB, userId, wsId);++ const root = await alice.create({+ assigneeUserId: userId2,+ instruction: 'Root assigned to Bob',+ visibility: 'public',+ });+ const childForBob = await alice.create({+ assigneeUserId: userId2,+ instruction: 'Child assigned to Bob',+ parentTaskId: root.id,+ visibility: 'public',+ });+ const childForAlice = await alice.create({+ assigneeUserId: userId,+ instruction: 'Child assigned to Alice',+ parentTaskId: root.id,+ visibility: 'public',+ });++ const demoted = await subtreeRepo(userId, wsId).updateVisibility(root.id, 'private');+ expect(demoted?.assigneeUserId).toBeNull();++ expect((await alice.findById(childForBob.id))?.assigneeUserId).toBeNull();+ expect((await alice.findById(childForAlice.id))?.assigneeUserId).toBe(userId);+ });++ it('should hand the subtree to the caller when taking it over as private', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const bob = new TaskModel(serverDB, userId2, wsId);++ const root = await alice.create({+ automationMode: 'schedule',+ instruction: 'Alice root',+ schedulePattern: '0 9 * * *',+ visibility: 'public',+ });+ await alice.update(root.id, { status: 'scheduled' });+ const child = await alice.create({ instruction: 'Alice child', parentTaskId: root.id });+ await alice.addComment({+ authorUserId: userId,+ content: 'alice context',+ taskId: root.id,+ userId,+ });++ const taken = await subtreeRepo(userId2, wsId).updateVisibility(root.id, 'private', {+ takeOwnership: true,+ });+ expect(taken).toMatchObject({+ automationMode: null,+ createdByUserId: userId2,+ status: 'backlog',+ visibility: 'private',+ });+ expect((await bob.findById(child.id))?.createdByUserId).toBe(userId2);++ // Bob keeps Alice's comment (author unchanged); Alice loses the task.+ const comments = await bob.getComments(root.id);+ expect(comments.map((c) => [c.content, c.authorUserId])).toEqual([['alice context', userId]]);+ expect(await alice.findById(root.id)).toBeNull();+ });++ it('should refuse a takeover that would leave the creator’s private subtasks behind', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const root = await alice.create({ instruction: 'Public root', visibility: 'public' });+ await alice.create({+ instruction: 'Alice private child',+ parentTaskId: root.id,+ visibility: 'private',+ });++ await expect(+ subtreeRepo(userId2, wsId).updateVisibility(root.id, 'private', { takeOwnership: true }),+ ).rejects.toThrow('private subtasks you cannot see');+ expect(await alice.findById(root.id)).toMatchObject({+ createdByUserId: userId,+ visibility: 'public',+ });+ });++ it('should refuse a takeover while a subtask is running', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const root = await alice.create({ instruction: 'Public root', visibility: 'public' });+ const child = await alice.create({ instruction: 'Busy child', parentTaskId: root.id });+ await alice.update(child.id, { status: 'running' });++ await expect(+ subtreeRepo(userId2, wsId).updateVisibility(root.id, 'private', { takeOwnership: true }),+ ).rejects.toThrow('while it or a subtask is running');+ expect((await alice.findById(root.id))?.createdByUserId).toBe(userId);+ });++ it('should move the task’s Work to the member taking it over', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const root = await alice.create({ instruction: 'Registered task', visibility: 'public' });+ const work = await new WorkModel(serverDB, userId, wsId).registerTask({+ changeType: 'created',+ taskId: root.id,+ toolIdentifier: 'lobe-task',+ toolName: 'createTask',+ });+ expect(work?.userId).toBe(userId);++ await subtreeRepo(userId2, wsId).updateVisibility(root.id, 'private', {+ takeOwnership: true,+ });++ const [row] = await serverDB+ .select({ userId: works.userId, visibility: works.visibility })+ .from(works)+ .where(eq(works.resourceId, root.id));+ expect(row).toEqual({ userId: userId2, visibility: 'private' });+ });++ it('should keep member assignees when promoting to public', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const task = await alice.create({ instruction: 'Private', visibility: 'private' });+ await alice.update(task.id, { assigneeUserId: userId2 });++ const promoted = await subtreeRepo(userId, wsId).updateVisibility(task.id, 'public');+ expect(promoted?.assigneeUserId).toBe(userId2);+ });+it('should NOT cascade updateVisibility into historical task_comments', async () => {// Comments are event-shaped historical rows whose visibility is fixed at// write time. Promoting the parent task to public must not retroactivelydiff --git a/packages/database/src/repositories/taskSubtree/index.ts b/packages/database/src/repositories/taskSubtree/index.tsindex ca17d871866..3e24b7b0c72 100644--- a/packages/database/src/repositories/taskSubtree/index.ts+++ b/packages/database/src/repositories/taskSubtree/index.ts@@ -5,6 +5,18 @@ import { TaskModel } from '../../models/task';import { WorkModel } from '../../models/work';import type { LobeChatDatabase } from '../../type';+/** Why a takeover was refused; checked under the subtree lock. */+export class TaskTakeOverError extends Error {+ constructor(readonly reason: 'hidden_subtasks' | 'running') {+ super(+ reason === 'running'+ ? 'Cannot take over this task while it or a subtask is running.'+ : 'Cannot take over this task while it has private subtasks you cannot see.',+ );+ this.name = 'TaskTakeOverError';+ }+}+/*** Cross-aggregate write flows over a task subtree. A task's visibility is* mirrored onto its Work rows, and its acceptances (verify aggregate) are keyed@@ -30,7 +42,11 @@ export class TaskSubtreeRepository {* - the root task and every descendant in `tasks`;* - `task_dependencies` and `task_documents` whose `task_id` is in the set;* - the indexed visibility mirror on the tasks' Work rows, so gallery/list- * queries cannot observe a stale public row after demotion.+ * queries cannot observe a stale public row after demotion;+ * - on demotion, `assignee_user_id` is cleared wherever it names someone+ * other than the task's creator, who could no longer open the task;+ * - with `takeOwnership`, the caller becomes the subtree's creator first+ * and its automation stops (see `takeOverSubtree`).** `task_topics` and `task_comments` are direction-sensitive. Their* `visibility` column is a write-time mirror of the parent task used as a@@ -47,16 +63,46 @@ export class TaskSubtreeRepository {* (either missing or owned by another workspace member). Callers should* gate authorization (creator-only / admin) before invoking this.*/- async updateVisibility(id: string, visibility: 'private' | 'public'): Promise<TaskItem | null> {+ async updateVisibility(+ id: string,+ visibility: 'private' | 'public',+ options: { takeOwnership?: boolean } = {},+ ): Promise<TaskItem | null> {const taskModel = this.taskModel();const root = await taskModel.findById(id);if (!root) return null;if (root.visibility === visibility) return root;const descendantIds = (await taskModel.findAllDescendants(root.id)).map((d) => d.id);+ // Taking a task over only applies on the way to private, and only when the+ // subtree is not already the caller's.+ const takeOver =+ !!options.takeOwnership && visibility === 'private' && root.createdByUserId !== this.userId;return this.db.transaction(async (tx) => {const db = tx as LobeChatDatabase;+ // Ownership moves first, so the visibility write below already treats+ // the caller as the creator (and unassigns the previous one).+ if (takeOver) {+ const taskIds = [root.id, ...descendantIds];+ const locked = await this.taskModel(db).lockWholeSubtree(root.id);+ // A private subtask the previous creator kept to themselves is not the+ // caller's to take, and leaving it behind would split the subtree.+ const visible = new Set(taskIds);+ if (locked.some((task) => !visible.has(task.id))) {+ throw new TaskTakeOverError('hidden_subtasks');+ }+ // Runs are attributed to the creator; a live one would finish as the+ // previous creator.+ if (locked.some((task) => task.status === 'running')) {+ throw new TaskTakeOverError('running');+ }+ await this.taskModel(db).takeOverSubtree(taskIds);+ await new WorkModel(db, this.userId, this.workspaceId).reassignTaskWorksOwner(+ taskIds,+ root.createdByUserId,+ );+ }const updated = await this.taskModel(db).setSubtreeVisibility(root.id,descendantIds,diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 46c719ed439..dba632e97f8 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2225,6 +2225,18 @@ export default {'taskDetail.publishToWorkspace.confirmOk': 'Publish','taskDetail.publishToWorkspace.errorPrivateAgent':'This task is assigned to a private agent. Reassign to a workspace agent, or publish the agent first.',+ 'taskDetail.makePrivate.errorOtherCreators':+ 'This task has subtasks created by other members. Move or remove them before making it private.',+ 'taskDetail.takeOver.confirmHint':+ 'This task belongs to another member. It and its subtasks become your private task: its creator and other members lose access, and its schedule or heartbeat is turned off.',+ 'taskDetail.takeOver.confirmOk': 'Take over',+ 'taskDetail.takeOver.confirmTitle': 'Take this task over as your private task?',+ 'taskDetail.takeOver.errorHiddenSubtasks':+ 'This task has private subtasks its creator kept to themselves, so it cannot be taken over.',+ 'taskDetail.takeOver.errorRunning':+ 'This task or one of its subtasks is running. Take it over once the run finishes.',+ 'taskDetail.takeOver.menuLabel': 'Take over as private',+ 'taskDetail.takeOver.success': 'Taken over as your private task','createGoal.addCriterion': 'Add criterion','createGoal.costBudgetHint':diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 107b62938e3..3d5285d07a3 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -325,8 +325,18 @@ export default {'sidebar.expandAll': 'Expand all groups','sidebar.title': 'Topics','taskManager.agent': 'Task Agent',+ 'taskManager.agentSelector.makePrivateConfirm.hint':+ 'This agent is private, so the task and its subtasks become private before it is assigned. Members assigned to them are unassigned.',+ 'taskManager.agentSelector.makePrivateConfirm.ok': 'Make private and assign',+ 'taskManager.agentSelector.makePrivateConfirm.title': 'Assign to a private agent?','taskManager.agentSelector.privateGroup': 'Private',+ 'taskManager.agentSelector.privateGroupMakesPrivate': 'Private · makes this task private',+ 'taskManager.agentSelector.privateGroupTakesOver': 'Private · takes this task over as yours','taskManager.agentSelector.recentGroup': 'Recently assigned',+ 'taskManager.agentSelector.takeOverConfirm.hint':+ 'This agent is private, so the task and its subtasks become your private task before it is assigned. Its creator and other members lose access, and its schedule or heartbeat is turned off.',+ 'taskManager.agentSelector.takeOverConfirm.ok': 'Take over and assign',+ 'taskManager.agentSelector.takeOverConfirm.title': 'Take this task over as yours?','taskManager.agentSelector.workspaceGroup': 'Workspace','taskManager.welcome': 'Ask me about your tasks','temp': 'Temporary',diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailAssignee.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailAssignee.tsxindex b440b9fb637..0f14fd1d4b9 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailAssignee.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailAssignee.tsx@@ -20,6 +20,7 @@ const TaskDetailAssignee = memo(() => {const status = useTaskStore(taskDetailSelectors.activeTaskStatus) as TaskStatus | undefined;const assigneeAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);const visibility = useTaskStore(taskDetailSelectors.activeTaskVisibility);+ const createdByUserId = useTaskStore(taskDetailSelectors.activeTaskCreatedByUserId);const assigneeMeta = useAgentDisplayMeta(assigneeAgentId);// Same source as the home list so the runtime tag stays consistent.const assigneeHeterogeneousType = useHomeStore(@@ -33,6 +34,7 @@ const TaskDetailAssignee = memo(() => {<AssigneeAgentSelectorcurrentAgentId={assigneeAgentId}disabled={status === 'running'}+ taskCreatorId={createdByUserId}taskIdentifier={taskId}taskVisibility={visibility}>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsxindex ca532ebe6e1..478fc09d907 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx@@ -180,23 +180,28 @@ describe('TaskDetailHeaderActions', () => {expect(mocks.dropdownItems.map((item) => item?.key)).toContain('makePrivate');});- it('hides "make private" from a workspace owner who is not the creator ', () => {- mocks.isWorkspaceOwner = true;+ it('offers a non-creator member to take the public task over as private', () => {mocks.taskState.taskDetailMap = {'T-1': { createdByUserId: 'someone-else', visibility: 'public' },};render(<TaskDetailHeaderActions />);+ const item = mocks.dropdownItems.find((i) => i?.key === 'makePrivate') as+ { label?: string; onClick?: () => void } | undefined;+ expect(item?.label).toBe('taskDetail.takeOver.menuLabel');+ item?.onClick?.();- expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('makePrivate');- });-- it('hides "make private" from non-creator members', () => {- mocks.taskState.taskDetailMap = {- 'T-1': { createdByUserId: 'someone-else', visibility: 'public' },+ const opts = mocks.confirmModal.mock.calls[0][0] as {+ okButtonProps?: { danger?: boolean };+ onOk: () => Promise<void>;+ title: string;};- render(<TaskDetailHeaderActions />);-- expect(mocks.dropdownItems.map((item) => item?.key)).not.toContain('makePrivate');+ expect(opts.title).toBe('taskDetail.takeOver.confirmTitle');+ expect(opts.okButtonProps?.danger).toBe(true);+ return opts.onOk().then(() => {+ expect(mocks.updateTaskVisibility).toHaveBeenCalledWith('T-1', 'private', {+ takeOwnership: true,+ });+ });});it('hides "make private" on private tasks', () => {diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsxindex f7e509d1b11..22d4b9b9ba5 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx@@ -117,26 +117,47 @@ const TaskDetailHeaderActions = memo(() => {});}, [canEditTask, taskId, t, updateTaskVisibility]);+ // Someone else's public task can only go private as the caller's own: it is+ // taken over, which the confirmation spells out.+ const takesOver = !!currentUserId && !!createdByUserId && createdByUserId !== currentUserId;+const triggerMakePrivate = useCallback(() => {if (!canEditTask) return;if (!taskId) return;confirmModal({cancelText: t('cancel', { ns: 'common' }),- content: <VisibilityConfirmContent variant="makePrivate" />,+ content: (+ <>+ <VisibilityConfirmContent variant="makePrivate" />+ {takesOver && (+ <div style={{ marginTop: 8, opacity: 0.7 }}>{t('taskDetail.takeOver.confirmHint')}</div>+ )}+ </>+ ),okButtonProps: { danger: true },- okText: t('makePrivate.confirm.ok', { ns: 'common' }),+ okText: takesOver+ ? t('taskDetail.takeOver.confirmOk')+ : t('makePrivate.confirm.ok', { ns: 'common' }),onOk: async () => {try {- await updateTaskVisibility(taskId, 'private');- toast.success(t('makePrivate.success', { ns: 'common' }));+ await (takesOver+ ? updateTaskVisibility(taskId, 'private', { takeOwnership: true })+ : updateTaskVisibility(taskId, 'private'));+ toast.success(+ takesOver+ ? t('taskDetail.takeOver.success')+ : t('makePrivate.success', { ns: 'common' }),+ );} catch {// store action already surfaced a targeted toast; swallow so the// confirm modal doesn't bubble a second error to base-ui.}},- title: t('makePrivate.confirm.title', { ns: 'common' }),+ title: takesOver+ ? t('taskDetail.takeOver.confirmTitle')+ : t('makePrivate.confirm.title', { ns: 'common' }),});- }, [canEditTask, taskId, t, updateTaskVisibility]);+ }, [canEditTask, taskId, t, takesOver, updateTaskVisibility]);const menuItems = useMemo<DropdownItem[]>(() => {if (!taskId) return [];@@ -195,19 +216,17 @@ const TaskDetailHeaderActions = memo(() => {}: null;- // Inverse transition: only the task creator can pull a- // published task back to private ( — an owner demoting another- // member's task would appropriate it into the creator's private list);- // everyone else doesn't see the entry at all (the server enforces the- // same rule as a backstop).- const canMakePrivate = !!currentUserId && createdByUserId === currentUserId;+ // Inverse transition: the creator pulls a published task back to private;+ // any other member takes it over as their own private task.const makePrivateItem: DropdownItem | null =- activeWorkspaceId && visibility === 'public' && canMakePrivate+ activeWorkspaceId && visibility === 'public' && !!currentUserId? {disabled: !canEditTask,icon: <Icon icon={EyeOffIcon} />,key: 'makePrivate',- label: t('makePrivate', { ns: 'common' }),+ label: takesOver+ ? t('taskDetail.takeOver.menuLabel')+ : t('makePrivate', { ns: 'common' }),onClick: triggerMakePrivate,}: null;@@ -241,8 +260,8 @@ const TaskDetailHeaderActions = memo(() => {hasContent,activeWorkspaceId,visibility,- createdByUserId,currentUserId,+ takesOver,t,triggerDelete,toggleArchive,diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsxindex 1f89577042f..cf25920b85d 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx@@ -147,6 +147,7 @@ const SubtaskTitle = memo<{ task: TaskDetailSubtask }>(({ task }) => {<AssigneeAgentSelectorcurrentAgentId={task.assignee?.id ?? null}disabled={isRunning}+ taskCreatorId={task.createdByUserId}taskIdentifier={task.id}taskVisibility={task.visibility}>diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsxindex 5efc5ebbaa5..a401c25c447 100644--- a/src/features/AgentTasks/features/AgentTaskItem.tsx+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx@@ -173,6 +173,7 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, routeScope = 'agent', variant<AssigneeAgentSelectorcurrentAgentId={task.assigneeAgentId}disabled={status === 'running'}+ taskCreatorId={task.createdByUserId}taskIdentifier={task.id}taskVisibility={task.visibility}>diff --git a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx b/src/features/AgentTasks/features/AssigneeAgentSelector.tsxindex f8dc39bab1e..40e8703c211 100644--- a/src/features/AgentTasks/features/AssigneeAgentSelector.tsx+++ b/src/features/AgentTasks/features/AssigneeAgentSelector.tsx@@ -1,6 +1,15 @@import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';-import { createStaticStyles, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';+import {+ confirmModal,+ createStaticStyles,+ cssVar,+ Flexbox,+ Icon,+ Popover,+ 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';@@ -12,6 +21,7 @@ import { type SidebarAgentItem } from '@/database/repositories/home';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';@@ -20,6 +30,8 @@ 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,@@ -28,6 +40,7 @@ import {matchesAssigneeSearch,pickRecentAssignees,pushRecentAssignee,+ shouldOfferPrivateAgents,} from './assigneeAgentSections';interface AssigneeAgentSelectorProps {@@ -41,6 +54,11 @@ interface AssigneeAgentSelectorProps {/** Why `disabled` holds; defaults to the running-Task explanation. */disabledReason?: string;onChange?: (agentId: string | null) => void;+ /**+ * The task's creator. On a public task, lets its creator pick a private+ * agent: confirming makes the task private first, then assigns it.+ */+ taskCreatorId?: string | null;taskIdentifier?: string;taskVisibility?: 'private' | 'public' | null;}@@ -156,6 +174,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(disabled,disabledReason,onChange,+ taskCreatorId,taskIdentifier,taskVisibility,}) => {@@ -168,6 +187,8 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const keyboardMovedRef = useRef(false);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);@@ -193,6 +214,19 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(const collapsedGroups = useGlobalStore((s) => s.status.assigneeAgentSelectorCollapsedGroups);const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ const {+ offer: offerPrivateAgents,+ privatizes: offerPrivateOnPublic,+ takesOver,+ } = shouldOfferPrivateAgents({+ currentUserId,+ hasOnChange: !!onChange,+ taskCreatorId,+ taskIdentifier,+ taskVisibility,+ workspaceId,+ });+const scopes = useMemo<PickerScope[]>(() => {const labels = {pinned: t('navPanel.pinned', { ns: 'common' }),@@ -200,7 +234,7 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(};const result: PickerScope[] = [];- if (taskVisibility !== 'public')+ if (offerPrivateAgents)result.push({id: 'private',sections: buildAssigneeAgentSections({@@ -210,7 +244,11 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(scope: 'private',ungrouped: privateUngroupedAgents,}),- title: t('taskManager.agentSelector.privateGroup', { ns: 'topic' }),+ title: takesOver+ ? t('taskManager.agentSelector.privateGroupTakesOver', { ns: 'topic' })+ : offerPrivateOnPublic+ ? t('taskManager.agentSelector.privateGroupMakesPrivate', { ns: 'topic' })+ : t('taskManager.agentSelector.privateGroup', { ns: 'topic' }),});const workspaceSections = buildAssigneeAgentSections({@@ -232,12 +270,14 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(}, [agentGroups,hasPrivateAgents,+ offerPrivateAgents,+ offerPrivateOnPublic,pinnedAgents,privateAgentGroups,privatePinnedAgents,privateUngroupedAgents,t,- taskVisibility,+ takesOver,ungroupedAgents,]);@@ -355,11 +395,18 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0);}, [currentAgentId, flatOptions, query]);- const handleAgentChange = useCallback(+ 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 (!canEditTask || agentId === (currentAgentId ?? null)) return;- setKey((value) => value + 1);- setSearch('');if (agentId) {const current = useGlobalStore.getState().status.recentAssigneeAgentIds?.[recentKey];updateSystemStatus({@@ -370,34 +417,89 @@ const AssigneeAgentSelector = memo<AssigneeAgentSelectorProps>(onChange(agentId);return;}- if (taskIdentifier)- void updateTask(- taskIdentifier,- { assigneeAgentId: agentId },- // The picker is the one place that already holds the chosen agent's- // display metadata, so it hands it over for the optimistic feed row.- {- optimisticAssignee: agent- ? {- // A group agent carries a member-avatar list; the feed row- // only knows how to draw a single image.- avatar: typeof agent.avatar === 'string' ? agent.avatar : null,- id: agent.id,- name: agentDisplayName(agent),- type: 'agent',- }- : undefined,- },- );+ if (!taskIdentifier) return;+ return updateTask(+ taskIdentifier,+ { assigneeAgentId: agentId },+ // The picker is the one place that already holds the chosen agent's+ // display metadata, so it hands it over for the optimistic feed row.+ {+ optimisticAssignee: agent+ ? {+ // A group agent carries a member-avatar list; the feed row+ // only knows how to draw a single image.+ avatar: typeof agent.avatar === 'string' ? agent.avatar : null,+ id: agent.id,+ name: agentDisplayName(agent),+ type: 'agent',+ }+ : undefined,+ },+ );+ },+ [onChange, recentKey, taskIdentifier, updateSystemStatus, updateTask],+ );++ const handleAgentChange = useCallback(+ (agentId: string | null, agent?: SidebarAgentItem) => {+ if (!canEditTask || agentId === (currentAgentId ?? null)) return;+ setKey((value) => value + 1);+ setSearch('');++ if (!offerPrivateOnPublic || !taskIdentifier || !agentId || !privateAgentIds.has(agentId)) {+ void assignAgent(agentId, agent);+ return;+ }++ // The task goes private before the private agent is assigned; if that+ // fails, the store has already explained why and nothing is assigned.+ // Someone else's task becomes the picker's own private task.+ const copy = takesOver+ ? {+ hint: t('taskManager.agentSelector.takeOverConfirm.hint', { ns: 'topic' }),+ ok: t('taskManager.agentSelector.takeOverConfirm.ok', { ns: 'topic' }),+ title: t('taskManager.agentSelector.takeOverConfirm.title', { ns: 'topic' }),+ }+ : {+ hint: t('taskManager.agentSelector.makePrivateConfirm.hint', { ns: 'topic' }),+ ok: t('taskManager.agentSelector.makePrivateConfirm.ok', { ns: 'topic' }),+ title: t('taskManager.agentSelector.makePrivateConfirm.title', { ns: 'topic' }),+ };+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: (+ <>+ <VisibilityConfirmContent variant="makePrivate" />+ <div style={{ marginTop: 8, opacity: 0.7 }}>{copy.hint}</div>+ </>+ ),+ okButtonProps: { danger: true },+ okText: copy.ok,+ onOk: async () => {+ try {+ await (takesOver+ ? updateTaskVisibility(taskIdentifier, 'private', { takeOwnership: true })+ : updateTaskVisibility(taskIdentifier, 'private'));+ } catch {+ // The store action already surfaced a targeted toast; swallow so+ // the confirm modal doesn't bubble a second error to base-ui.+ return;+ }+ await assignAgent(agentId, agent);+ },+ title: copy.title,+ });},[+ assignAgent,canEditTask,currentAgentId,- onChange,- recentKey,+ offerPrivateOnPublic,+ privateAgentIds,+ t,+ takesOver,taskIdentifier,- updateSystemStatus,- updateTask,+ updateTaskVisibility,],);diff --git a/src/features/AgentTasks/features/assigneeAgentSections.test.ts b/src/features/AgentTasks/features/assigneeAgentSections.test.tsindex 283e1a452de..0ef9ba32501 100644--- a/src/features/AgentTasks/features/assigneeAgentSections.test.ts+++ b/src/features/AgentTasks/features/assigneeAgentSections.test.ts@@ -8,6 +8,7 @@ import {MAX_RECENT_ASSIGNEES,pickRecentAssignees,pushRecentAssignee,+ shouldOfferPrivateAgents,} from './assigneeAgentSections';const agent = (id: string, extra: Partial<SidebarAgentItem> = {}): SidebarAgentItem => ({@@ -99,3 +100,52 @@ describe('recent assignees', () => {expect(pushRecentAssignee(full, 'f')).toHaveLength(MAX_RECENT_ASSIGNEES);});});++describe('shouldOfferPrivateAgents', () => {+ const creatorOnPublicTask = {+ currentUserId: 'user-a',+ hasOnChange: false,+ taskCreatorId: 'user-a',+ taskIdentifier: 'T-1',+ taskVisibility: 'public' as const,+ workspaceId: 'ws-1',+ };+ const hidden = { offer: false, privatizes: false, takesOver: false };++ it('offers private agents on a non-public task without privatizing it', () => {+ const plain = { offer: true, privatizes: false, takesOver: false };+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, taskVisibility: 'private' })).toEqual(+ plain,+ );+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, taskVisibility: null })).toEqual(+ plain,+ );+ });++ it('lets the creator of a public workspace task keep it while privatizing it', () => {+ expect(shouldOfferPrivateAgents(creatorOnPublicTask)).toEqual({+ offer: true,+ privatizes: true,+ takesOver: false,+ });+ });++ it('lets another member take a public workspace task over', () => {+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, currentUserId: 'user-b' })).toEqual({+ offer: true,+ privatizes: true,+ takesOver: true,+ });+ });++ it('keeps private agents hidden on a public task outside a persisted workspace task', () => {+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, taskCreatorId: undefined })).toEqual(+ hidden,+ );+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, hasOnChange: true })).toEqual(hidden);+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, taskIdentifier: undefined })).toEqual(+ hidden,+ );+ expect(shouldOfferPrivateAgents({ ...creatorOnPublicTask, workspaceId: null })).toEqual(hidden);+ });+});diff --git a/src/features/AgentTasks/features/assigneeAgentSections.ts b/src/features/AgentTasks/features/assigneeAgentSections.tsindex f44cc329e50..4cdb232fc1d 100644--- a/src/features/AgentTasks/features/assigneeAgentSections.ts+++ b/src/features/AgentTasks/features/assigneeAgentSections.ts@@ -103,3 +103,35 @@ export const pickRecentAssignees = (*/export const pushRecentAssignee = (current: string[] | undefined, agentId: string): string[] =>[agentId, ...(current ?? []).filter((id) => id !== agentId)].slice(0, MAX_RECENT_ASSIGNEES);++/**+ * A public task only takes a private agent once it is private itself, so on a+ * public workspace task picking one makes the task private first (behind a+ * confirmation). Its creator keeps it; anyone else takes it over as their own+ * private task. A caller that owns the change through `onChange` (e.g. a+ * create form) keeps the plain public list.+ */+export const shouldOfferPrivateAgents = ({+ currentUserId,+ hasOnChange,+ taskCreatorId,+ taskIdentifier,+ taskVisibility,+ workspaceId,+}: {+ currentUserId?: string | null;+ hasOnChange: boolean;+ taskCreatorId?: string | null;+ taskIdentifier?: string;+ taskVisibility?: 'private' | 'public' | null;+ workspaceId?: string | null;+}): { offer: boolean; privatizes: boolean; takesOver: boolean } => {+ if (taskVisibility !== 'public') return { offer: true, privatizes: false, takesOver: false };+ const privatizes =+ !hasOnChange && !!taskIdentifier && !!workspaceId && !!currentUserId && !!taskCreatorId;+ return {+ offer: privatizes,+ privatizes,+ takesOver: privatizes && taskCreatorId !== currentUserId,+ };+};diff --git a/src/services/task.ts b/src/services/task.tsindex d80a6e9e0bb..482a66b8e62 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -134,8 +134,11 @@ class TaskService {visibility?: 'private' | 'public';}) => lambdaClient.task.create.mutate(params);- updateVisibility = async (id: string, visibility: 'private' | 'public') =>- lambdaClient.task.updateVisibility.mutate({ id, visibility });+ updateVisibility = async (+ id: string,+ visibility: 'private' | 'public',+ options?: { takeOwnership?: boolean },+ ) => lambdaClient.task.updateVisibility.mutate({ id, visibility, ...options });update = async (id: string,diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex a3d25c2dc34..daa2b0209a3 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -42,6 +42,7 @@ vi.mock('@/services/task', () => ({reorderSubtasks: vi.fn(),unpinDocument: vi.fn(),update: vi.fn(),+ updateVisibility: vi.fn(),},}));@@ -969,6 +970,35 @@ describe('TaskDetailSliceAction', () => {});});+ describe('updateTaskVisibility', () => {+ it('resolves once the change is saved even when the refresh fails', async () => {+ vi.mocked(taskService.updateVisibility).mockResolvedValue({} as any);+ const refreshTaskList = vi.fn().mockRejectedValue(new Error('network down'));+ useTaskStore.setState({ refreshTaskList } as any);+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(+ useTaskStore.getState().updateTaskVisibility('T-1', 'private'),+ ).resolves.toBeUndefined();+ expect(taskService.updateVisibility).toHaveBeenCalledWith('T-1', 'private');+ expect(toast.error).not.toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('rejects with a targeted toast when the change itself is refused', async () => {+ vi.mocked(taskService.updateVisibility).mockRejectedValue(+ new Error('Cannot make this task private while it has subtasks created by other members.'),+ );++ await expect(useTaskStore.getState().updateTaskVisibility('T-1', 'private')).rejects.toThrow(+ 'subtasks created by other members',+ );+ expect(toast.error).toHaveBeenCalledWith(+ expect.stringContaining('subtasks created by other members'),+ );+ });+ });+describe('deleteTask', () => {it('should remove from map, clear activeTaskId, and return deleted task data', async () => {useTaskStore.setState({diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 8de3084f375..5641fff69a9 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -489,10 +489,15 @@ export class TaskDetailSliceActionImpl {}};- updateTaskVisibility = async (id: string, visibility: 'private' | 'public'): Promise<void> => {+ updateTaskVisibility = async (+ id: string,+ visibility: 'private' | 'public',+ options?: { takeOwnership?: boolean },+ ): Promise<void> => {try {- await taskService.updateVisibility(id, visibility);- await Promise.all([this.#get().refreshTaskList(), this.internal_refreshTaskDetail(id)]);+ await (options+ ? taskService.updateVisibility(id, visibility, options)+ : taskService.updateVisibility(id, visibility));} catch (error) {// Surfaces a specific actionable error when the task's assignee is a// private agent. The generic "failed" toast hides what the user must@@ -500,6 +505,11 @@ export class TaskDetailSliceActionImpl {// or publish the agent first.const raw = (error as { message?: string })?.message ?? '';const isPrivateAgentBlock = /public task cannot be assigned to a private agent/i.test(raw);+ const isOtherCreatorsBlock = /subtasks created by other members/i.test(raw);+ const isRunningBlock = /cannot take over this task while it or a subtask is running/i.test(+ raw,+ );+ const isHiddenSubtasksBlock = /private subtasks you cannot see/i.test(raw);toast.error(isPrivateAgentBlock? t('taskDetail.publishToWorkspace.errorPrivateAgent', {@@ -507,13 +517,39 @@ export class TaskDetailSliceActionImpl {'This task is assigned to a private agent. Reassign to a workspace agent, or publish the agent first.',ns: 'chat',})- : t('createTask.visibility.changeFailed', {- defaultValue: 'Failed to change task visibility',- ns: 'chat',- }),+ : isOtherCreatorsBlock+ ? t('taskDetail.makePrivate.errorOtherCreators', {+ defaultValue:+ 'This task has subtasks created by other members. Move or remove them before making it private.',+ ns: 'chat',+ })+ : isRunningBlock+ ? t('taskDetail.takeOver.errorRunning', {+ defaultValue:+ 'This task or one of its subtasks is running. Take it over once the run finishes.',+ ns: 'chat',+ })+ : isHiddenSubtasksBlock+ ? t('taskDetail.takeOver.errorHiddenSubtasks', {+ defaultValue:+ 'This task has private subtasks its creator kept to themselves, so it cannot be taken over.',+ ns: 'chat',+ })+ : t('createTask.visibility.changeFailed', {+ defaultValue: 'Failed to change task visibility',+ ns: 'chat',+ }),);throw error;}++ // The write is committed; a failed refresh must not read as a failed+ // change, or a caller chaining on it (assigning a private agent) would stop.+ try {+ await Promise.all([this.#get().refreshTaskList(), this.internal_refreshTaskDetail(id)]);+ } catch (error) {+ console.error('[task:updateTaskVisibility] refresh failed', error);+ }};updateTask = async (