𤯠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
š fix(task): keep members' comments and runs visible to a private task's creator (#21948)
Rdmclin28bdbcf73e4df
diff --git a/packages/database/src/models/task/context.ts b/packages/database/src/models/task/context.tsindex 8e4299d8a30..a03c71adf02 100644--- a/packages/database/src/models/task/context.ts+++ b/packages/database/src/models/task/context.ts@@ -1,4 +1,4 @@-import { and, eq, isNull, type SQL, sql } from 'drizzle-orm';+import { and, eq, exists, isNull, or, type SQL, sql } from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import {@@ -66,19 +66,36 @@ export const taskOwnership = (ctx: TaskModelContext) =>);/**- * Ownership predicate for task child tables (deps / docs / comments) that- * use a `userId` column instead of `createdByUserId`. Pass `visibility` for- * tables that mirror the parent task's visibility column; leave it omitted- * for tables that stay workspace-shared (e.g. comments).+ * Ownership predicate for task child tables (deps / docs / topics / comments /+ * activities) that use a `userId` column instead of `createdByUserId`. Pass+ * `visibility` for tables that mirror the parent task's visibility column;+ * leave it omitted for tables that stay workspace-shared.+ *+ * A private row is visible to its author and to the creator of the task it+ * belongs to. Rows written by other members while the task was public go+ * private with it, and the creator must keep seeing them ā the task is still+ * theirs. Other members still see only public rows and their own.*/export const childOwnership = (ctx: TaskModelContext,cols: {+ taskId: AnyPgColumn;userId: AnyPgColumn;visibility?: AnyPgColumn;workspaceId: AnyPgColumn;},-) => buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, cols);+) => {+ const base = buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, cols);+ if (!ctx.workspaceId || !cols.visibility) return base;++ const ownTask = exists(+ ctx.db+ .select({ one: sql`1` })+ .from(tasks)+ .where(and(eq(tasks.id, cols.taskId), eq(tasks.createdByUserId, ctx.userId))),+ );+ return or(base, and(eq(cols.workspaceId, ctx.workspaceId), ownTask)) as SQL;+};/*** Workspace-wide ownership for `tasks.seq` / `identifier` allocation ā@@ -110,15 +127,17 @@ export const taskOwnershipSql = (ctx: TaskModelContext, alias?: string) => {export const depsOwnership = (ctx: TaskModelContext) =>childOwnership(ctx, {+ taskId: taskDependencies.taskId,userId: taskDependencies.userId,visibility: taskDependencies.visibility,workspaceId: taskDependencies.workspaceId,});-/** Only used by the demotion cascade in `TaskModel.updateVisibility` ā regular- * taskTopics reads/writes live in `TaskTopicModel`. */+/** The demotion cascade in `TaskModel.updateVisibility` and every+ * `TaskTopicModel` read/write share this predicate. */export const topicsOwnership = (ctx: TaskModelContext) =>childOwnership(ctx, {+ taskId: taskTopics.taskId,userId: taskTopics.userId,visibility: taskTopics.visibility,workspaceId: taskTopics.workspaceId,@@ -126,6 +145,7 @@ export const topicsOwnership = (ctx: TaskModelContext) =>export const docsOwnership = (ctx: TaskModelContext) =>childOwnership(ctx, {+ taskId: taskDocuments.taskId,userId: taskDocuments.userId,visibility: taskDocuments.visibility,workspaceId: taskDocuments.workspaceId,@@ -133,6 +153,7 @@ export const docsOwnership = (ctx: TaskModelContext) =>export const commentsOwnership = (ctx: TaskModelContext) =>childOwnership(ctx, {+ taskId: taskComments.taskId,userId: taskComments.userId,visibility: taskComments.visibility,workspaceId: taskComments.workspaceId,@@ -140,6 +161,7 @@ export const commentsOwnership = (ctx: TaskModelContext) =>export const activitiesOwnership = (ctx: TaskModelContext) =>childOwnership(ctx, {+ taskId: taskActivities.taskId,userId: taskActivities.userId,visibility: taskActivities.visibility,workspaceId: taskActivities.workspaceId,diff --git a/packages/database/src/models/task/documents.ts b/packages/database/src/models/task/documents.tsindex ee77bd1e856..fb31b09486f 100644--- a/packages/database/src/models/task/documents.ts+++ b/packages/database/src/models/task/documents.ts@@ -109,7 +109,9 @@ export const getTreePinnedDocuments = async (const recursiveOwnership = taskOwnershipSql(ctx, 't');const docsOwnership = ctx.workspaceId? sql`td.workspace_id = ${ctx.workspaceId}- AND (td.visibility = 'public' OR td.user_id = ${ctx.userId})`+ AND (td.visibility = 'public' OR td.user_id = ${ctx.userId}+ OR EXISTS (SELECT 1 FROM tasks ot+ WHERE ot.id = td.task_id AND ot.created_by_user_id = ${ctx.userId}))`: sql`td.user_id = ${ctx.userId} AND td.workspace_id IS NULL`;// Guard the referenced document row itself: `td.visibility` is a// write-time mirror of the TASK's visibility, so a document independentlydiff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 81f020e3361..590ef8a216d 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -11,6 +11,7 @@ import { tasks, taskTopics } from '../schemas/task';import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';+import { topicsOwnership } from './task/context';export const TERMINAL_TOPIC_STATUSES = new Set(['canceled',@@ -33,15 +34,10 @@ export class TaskTopicModel {this.workspaceId = workspaceId;}+ // Same rule as the other task child rows: a private run is visible to the+ // member who ran it and to the task's creator.private ownership = () =>- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- {- userId: taskTopics.userId,- visibility: taskTopics.visibility,- workspaceId: taskTopics.workspaceId,- },- );+ topicsOwnership({ db: this.db, userId: this.userId, workspaceId: this.workspaceId });/** Look up the parent task's visibility so newly added topics mirror it. */private async getTaskVisibility(taskId: string): Promise<'private' | 'public'> {diff --git a/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts b/packages/database/src/repositories/taskSubtree/__tests__/index.test.tsindex 8d90c75472d..fd1ba346991 100644--- a/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts+++ b/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts@@ -4,7 +4,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import { TaskModel } from '../../../models/task';-import { acceptances, topics, users, workspaces } from '../../../schemas';+import { TaskTopicModel } from '../../../models/taskTopic';+import { acceptances, documents, topics, users, workspaces } from '../../../schemas';import { taskTopics } from '../../../schemas/task';import type { LobeChatDatabase } from '../../../type';import { TaskSubtreeRepository } from '../index';@@ -13,6 +14,7 @@ const serverDB: LobeChatDatabase = await getTestDB();const userId = 'task-subtree-repo-user';const userId2 = 'task-subtree-repo-user-2';+const userId3 = 'task-subtree-repo-user-3';const subtreeRepo = (uid: string, workspaceId?: string) =>new TaskSubtreeRepository(serverDB, uid, workspaceId);@@ -24,7 +26,7 @@ const createTopic = async (id: string, uid = userId) => {beforeEach(async () => {await serverDB.delete(users);- await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }, { id: userId3 }]);});afterEach(async () => {@@ -230,6 +232,86 @@ describe('TaskSubtreeRepository', () => {expect(historical.visibility).toBe('private');});+ it('should keep other membersā comments, runs and activity visible to the creator after demotion', async () => {+ // Bob commented on and ran Alice's public task. Demotion pulls those+ // rows private with the task; Alice still owns the task and must keep+ // seeing them, while Bob and other members no longer can.+ const alice = new TaskModel(serverDB, userId, wsId);+ const bob = new TaskModel(serverDB, userId2, wsId);+ const carol = new TaskModel(serverDB, userId3, wsId);++ const task = await alice.create({ instruction: 'shared then private', visibility: 'public' });+ await bob.addComment({+ authorUserId: userId2,+ content: 'bob was here',+ taskId: task.id,+ userId: userId2,+ });+ const bobTopicId = await createTopic('bob-run-topic-id', userId2);+ await new TaskTopicModel(serverDB, userId2, wsId).add(task.id, bobTopicId, { seq: 1 });+ await bob.addActivity({+ actorUserId: userId2,+ payload: { fromId: null, toId: userId2 },+ taskId: task.id,+ type: 'assignee_user',+ });+ const [bobDoc] = await serverDB+ .insert(documents)+ .values({+ fileType: 'markdown',+ source: 'test',+ sourceType: 'api',+ title: 'bob notes',+ totalCharCount: 0,+ totalLineCount: 0,+ userId: userId2,+ workspaceId: wsId,+ })+ .returning();+ await bob.pinDocument(task.id, bobDoc.id);++ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'private');++ const aliceComments = await alice.getComments(task.id);+ expect(aliceComments.map((c) => c.content)).toEqual(['bob was here']);+ const aliceTopics = await new TaskTopicModel(serverDB, userId, wsId).findByTaskId(task.id);+ expect(aliceTopics.map((t) => t.topicId)).toEqual([bobTopicId]);+ expect(await alice.getActivities(task.id)).toHaveLength(1);+ expect(Object.keys((await alice.getTreePinnedDocuments(task.id)).nodeMap)).toEqual([+ bobDoc.id,+ ]);++ // Alice can also edit and delete them, as any member could while public.+ await expect(alice.updateComment(aliceComments[0].id, 'edited')).resolves.toBeTruthy();++ // Carol, another member, sees none of it.+ expect(await carol.getComments(task.id)).toHaveLength(0);+ expect(await new TaskTopicModel(serverDB, userId3, wsId).findByTaskId(task.id)).toHaveLength(+ 0,+ );+ expect(await carol.getActivities(task.id)).toHaveLength(0);+ });++ it('should keep private-era rows hidden from other members after promotion', async () => {+ const alice = new TaskModel(serverDB, userId, wsId);+ const bob = new TaskModel(serverDB, userId2, wsId);+ const carol = new TaskModel(serverDB, userId3, wsId);++ const task = await alice.create({ instruction: 'round trip', visibility: 'public' });+ await bob.addComment({+ authorUserId: userId2,+ content: 'public-era note from bob',+ taskId: task.id,+ userId: userId2,+ });+ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'private');+ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'public');++ // The creator keeps seeing it; a member who was never let in does not.+ expect(await alice.getComments(task.id)).toHaveLength(1);+ expect(await carol.getComments(task.id)).toHaveLength(0);+ });+it('should cascade publicāprivate demotion into task_comments and task_topics', async () => {// Inverse of the two non-cascade tests above: comment/topic visibility// is a write-time mirror of the task used as a JOIN-free authorization