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.

✨ feat(task): set a verified origin on CLI/API task creates (#22361)

Lobehub Coderee06a9dcdf8c
diff --git a/apps/cli/src/commands/task/index.ts b/apps/cli/src/commands/task/index.ts
index 5b050b10712..0183995b256 100644
--- a/apps/cli/src/commands/task/index.ts
+++ b/apps/cli/src/commands/task/index.ts
@@ -30,6 +30,7 @@ import {
} from './label';
import { registerLifecycleCommands } from './lifecycle';
import { formatTaskModel, toCreateModelConfig, toModelConfigPatch } from './model';
+import { type TaskOriginInput, toCreateOrigin } from './origin';
import { registerReviewCommands } from './review';
import { registerTopicCommands } from './topic';
import { resolveAppUrl, resolveAppUrlBuilder, taskPath } from './url';
@@ -584,6 +585,17 @@ export function registerTaskCommand(program: Command) {
)
.option('--model <model>', "Model to run with (default: the assignee agent's model)")
.option('--provider <provider>', 'Provider for --model (default: resolved from the agent)')
+ .option(
+ '--origin-agent <id>',
+ 'Agent to notify when the task finishes (requires --origin-topic)',
+ )
+ .option(
+ '--origin-topic <id>',
+ 'Your conversation (topic) that receives the result card (requires --origin-agent)',
+ )
+ .option('--origin-message <id>', 'Message in the origin topic the task was created from')
+ .option('--origin-operation <id>', 'Operation that created the task')
+ .option('--origin-tool-call <id>', 'Tool call that created the task')
.option('--json [fields]', 'Output JSON')
.action(
async (options: {
@@ -593,11 +605,25 @@ export function registerTaskCommand(program: Command) {
label?: string[];
model?: string;
name?: string;
+ originAgent?: string;
+ originMessage?: string;
+ originOperation?: string;
+ originToolCall?: string;
+ originTopic?: string;
parent?: string;
priority?: string;
provider?: string;
user?: string;
}) => {
+ let origin: TaskOriginInput | undefined;
+ try {
+ origin = toCreateOrigin(options);
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exitCode = 1;
+ return;
+ }
+
const client = await getTrpcClient();
const buildUrl = await resolveAppUrlBuilder(client);
const assigneeUserId = await resolveUserOption(client, options.user);
@@ -616,6 +642,7 @@ export function registerTaskCommand(program: Command) {
if (options.priority) input.priority = Number.parseInt(options.priority, 10);
const modelConfig = toCreateModelConfig(options);
if (modelConfig) input.config = modelConfig;
+ if (origin) input.context = { origin };
const result = await client.task.create.mutate(input);
const url = buildUrl(taskPath(result.data.identifier, result.data.name));
diff --git a/apps/cli/src/commands/task/origin.test.ts b/apps/cli/src/commands/task/origin.test.ts
new file mode 100644
index 00000000000..9dfddf2005d
--- /dev/null
+++ b/apps/cli/src/commands/task/origin.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { toCreateOrigin } from './origin';
+
+describe('toCreateOrigin', () => {
+ it('sends no origin when no origin flag is set', () => {
+ expect(toCreateOrigin({})).toBeUndefined();
+ expect(toCreateOrigin({ originAgent: ' ' })).toBeUndefined();
+ });
+
+ it('builds the origin from trimmed flags, dropping blank optional ids', () => {
+ expect(
+ toCreateOrigin({
+ originAgent: ' agt_1 ',
+ originMessage: 'msg_1',
+ originOperation: '',
+ originToolCall: 'call_1',
+ originTopic: 'tpc_1',
+ }),
+ ).toEqual({ agentId: 'agt_1', messageId: 'msg_1', toolCallId: 'call_1', topicId: 'tpc_1' });
+ });
+
+ it('requires agent and topic together', () => {
+ expect(() => toCreateOrigin({ originTopic: 'tpc_1' })).toThrow(
+ '--origin-agent and --origin-topic must be given together',
+ );
+ expect(() => toCreateOrigin({ originAgent: 'agt_1' })).toThrow();
+ expect(() => toCreateOrigin({ originMessage: 'msg_1' })).toThrow();
+ });
+});
diff --git a/apps/cli/src/commands/task/origin.ts b/apps/cli/src/commands/task/origin.ts
new file mode 100644
index 00000000000..af6ba2003bc
--- /dev/null
+++ b/apps/cli/src/commands/task/origin.ts
@@ -0,0 +1,41 @@
+/**
+ * `--origin-*` flags of `task create`: the conversation the server reports the
+ * finished task back to. The server checks the caller owns that topic and agent.
+ */
+export interface TaskOriginOptions {
+ originAgent?: string;
+ originMessage?: string;
+ originOperation?: string;
+ originToolCall?: string;
+ originTopic?: string;
+}
+
+export interface TaskOriginInput {
+ agentId: string;
+ messageId?: string;
+ operationId?: string;
+ toolCallId?: string;
+ topicId: string;
+}
+
+/** `context.origin` for `task create`, or undefined when no origin flag is set. */
+export const toCreateOrigin = (options: TaskOriginOptions): TaskOriginInput | undefined => {
+ const agentId = options.originAgent?.trim();
+ const topicId = options.originTopic?.trim();
+ const messageId = options.originMessage?.trim();
+ const operationId = options.originOperation?.trim();
+ const toolCallId = options.originToolCall?.trim();
+
+ if (!agentId && !topicId && !messageId && !operationId && !toolCallId) return undefined;
+ // The server can only deliver the result with both: the card goes into the
+ // topic and the agent is woken there.
+ if (!agentId || !topicId) {
+ throw new Error('--origin-agent and --origin-topic must be given together');
+ }
+
+ const origin: TaskOriginInput = { agentId, topicId };
+ if (messageId) origin.messageId = messageId;
+ if (operationId) origin.operationId = operationId;
+ if (toolCallId) origin.toolCallId = toolCallId;
+ return origin;
+};
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.origin.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.origin.integration.test.ts
new file mode 100644
index 00000000000..1c7edc9e36d
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.origin.integration.test.ts
@@ -0,0 +1,145 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { agents, topics } from '@/database/schemas';
+
+import { taskRouter } from '../../task';
+import { cleanupTestUser, createTestContext, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+const seedConversation = async (db: LobeChatDatabase, userId: string) => {
+ const [agent] = await db.insert(agents).values({ userId }).returning();
+ const [topic] = await db.insert(topics).values({ agentId: agent.id, userId }).returning();
+ return { agentId: agent.id, topicId: topic.id };
+};
+
+describe('Task Router context.origin', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let otherUserId: string;
+ let caller: ReturnType<typeof taskRouter.createCaller>;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ otherUserId = await createTestUser(serverDB);
+ caller = taskRouter.createCaller(createTestContext(userId));
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ await cleanupTestUser(serverDB, otherUserId);
+ });
+
+ it("stores an origin on the caller's own conversation", async () => {
+ const own = await seedConversation(serverDB, userId);
+
+ const created = await caller.create({
+ context: { origin: { ...own, operationId: 'op_cli', toolCallId: 'call_cli' } },
+ instruction: 'Report back when done',
+ });
+
+ const stored = await new TaskModel(serverDB, userId).findById(created.data.id);
+ expect(stored?.context).toEqual({
+ origin: { ...own, operationId: 'op_cli', toolCallId: 'call_cli' },
+ });
+ });
+
+ it('creates a task without an origin and leaves context at its default, as before', async () => {
+ const created = await caller.create({ instruction: 'No one to notify' });
+ const withEmptyContext = await caller.create({ context: {}, instruction: 'Still no one' });
+
+ const model = new TaskModel(serverDB, userId);
+ expect((await model.findById(created.data.id))?.context).toEqual({});
+ expect((await model.findById(withEmptyContext.data.id))?.context).toEqual({});
+ });
+
+ it("refuses a forged origin on another user's topic and creates nothing", async () => {
+ const own = await seedConversation(serverDB, userId);
+ const foreign = await seedConversation(serverDB, otherUserId);
+
+ await expect(
+ caller.create({ context: { origin: foreign }, instruction: 'Spam their topic' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND', message: 'Origin conversation not found' });
+ await expect(
+ caller.create({
+ context: { origin: { agentId: own.agentId, topicId: foreign.topicId } },
+ instruction: 'Spam their topic with my agent',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ expect((await caller.list({})).data).toHaveLength(0);
+ });
+
+ it('rejects an origin missing its topic', async () => {
+ const own = await seedConversation(serverDB, userId);
+
+ await expect(
+ caller.create({
+ context: { origin: { agentId: own.agentId } as never },
+ instruction: 'Half an origin',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it("refuses an update that re-points the origin at another user's topic", async () => {
+ const own = await seedConversation(serverDB, userId);
+ const foreign = await seedConversation(serverDB, otherUserId);
+ const created = await caller.create({
+ context: { origin: own },
+ instruction: 'Report back when done',
+ });
+
+ await expect(
+ caller.update({ context: { origin: foreign }, id: created.data.id }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ // Re-saving the stored context unchanged still works.
+ await expect(
+ caller.update({ context: { origin: own }, id: created.data.id, name: 'Renamed' }),
+ ).resolves.toMatchObject({ success: true });
+ const stored = await new TaskModel(serverDB, userId).findById(created.data.id);
+ expect(stored?.context).toEqual({ origin: own });
+ });
+
+ it('keeps origin optional on update: a context without a deliverable origin is stored as sent', async () => {
+ const created = await caller.create({ instruction: 'Report back when done' });
+
+ await expect(
+ caller.update({ context: { note: 'kept' }, id: created.data.id }),
+ ).resolves.toMatchObject({ success: true });
+ await expect(
+ caller.update({ context: { origin: { topicId: 'tpc_partial' } }, id: created.data.id }),
+ ).resolves.toMatchObject({ success: true });
+
+ const stored = await new TaskModel(serverDB, userId).findById(created.data.id);
+ expect(stored?.context).toEqual({ origin: { topicId: 'tpc_partial' } });
+ });
+
+ it('stores the origin ids an update validated, trimmed', async () => {
+ const own = await seedConversation(serverDB, userId);
+ const created = await caller.create({ instruction: 'Report back when done' });
+
+ await caller.update({
+ context: { origin: { agentId: ` ${own.agentId} `, topicId: `${own.topicId} ` } },
+ id: created.data.id,
+ });
+
+ const stored = await new TaskModel(serverDB, userId).findById(created.data.id);
+ expect(stored?.context).toEqual({ origin: own });
+ });
+});
diff --git a/apps/server/src/routers/lambda/task/lifecycle.ts b/apps/server/src/routers/lambda/task/lifecycle.ts
index 21e83dac88d..a8cc406beaf 100644
--- a/apps/server/src/routers/lambda/task/lifecycle.ts
+++ b/apps/server/src/routers/lambda/task/lifecycle.ts
@@ -8,6 +8,10 @@ import { router } from '@/libs/trpc/lambda';
import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
import { assertNotInOpenGoal } from '@/server/services/task/archiveGuard';
import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';
+import {
+ assertTaskOriginAccessible,
+ taskOriginInputSchema,
+} from '@/server/services/task/originValidation';
import {
assertResultingScheduleValid,
schedulePatternSchema,
@@ -32,6 +36,9 @@ const createSchema = z.object({
// schedule-dispatch sweep to pick the task up.
automationMode: z.enum(['heartbeat', 'schedule']).optional(),
config: z.record(z.string(), z.unknown()).optional(),
+ // Only `origin` is caller-settable: the conversation to notify when the task
+ // finishes. The server checks the caller owns it before storing it.
+ context: z.object({ origin: taskOriginInputSchema.optional() }).optional(),
createdByAgentId: z.string().optional(),
description: z.string().optional(),
editorData: z.unknown().optional(),
@@ -121,7 +128,7 @@ export const lifecycleRouter = router({
}
}),
create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {
- const { goal: legacyGoal, labelIds, ...createInput } = input;
+ const { context, goal: legacyGoal, labelIds, ...createInput } = input;
if (legacyGoal !== undefined) {
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -140,11 +147,21 @@ export const lifecycleRouter = router({
throw error;
});
}
+ // Origin is optional: without one the task stores no context, as before.
+ const origin = context?.origin;
+ if (origin) {
+ await assertTaskOriginAccessible(
+ ctx.serverDB,
+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
+ origin,
+ );
+ }
try {
const parsedVerify = taskVerifyConfigPatchSchema.safeParse(createInput.config?.verify);
const { verify: _legacyVerify, ...taskConfig } = createInput.config ?? {};
const task = await ctx.taskService.createTask({
...createInput,
+ ...(origin && { context: { origin } }),
parentTaskId: createInput.parentTaskId
? (await resolveTaskOrThrow(ctx.taskModel, createInput.parentTaskId)).id
: undefined,
diff --git a/apps/server/src/services/task/originValidation.integration.test.ts b/apps/server/src/services/task/originValidation.integration.test.ts
new file mode 100644
index 00000000000..745e495bcb0
--- /dev/null
+++ b/apps/server/src/services/task/originValidation.integration.test.ts
@@ -0,0 +1,240 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ agents,
+ chatGroups,
+ chatGroupsAgents,
+ messages,
+ topics,
+ users,
+ workspaces,
+} from '@/database/schemas';
+
+import { assertTaskOriginAccessible, assertTaskOriginPatchAllowed } from './originValidation';
+
+const userId = 'task-origin-owner';
+const otherUserId = 'task-origin-other';
+const workspaceId = 'task-origin-ws';
+
+// Module-level, like the database model tests: the first call migrates a
+// fresh database, which can outlast a hook timeout on a loaded CI shard.
+const db: LobeChatDatabase = await getTestDB();
+
+const seedConversation = async (
+ owner: string,
+ key: string,
+ options: { visibility?: 'private' | 'public'; workspaceId?: string } = {},
+) => {
+ const [agent] = await db
+ .insert(agents)
+ .values({
+ id: `agt_${key}`,
+ userId: owner,
+ visibility: options.visibility ?? 'private',
+ workspaceId: options.workspaceId,
+ })
+ .returning();
+ const [topic] = await db
+ .insert(topics)
+ .values({
+ agentId: agent.id,
+ id: `tpc_${key}`,
+ userId: owner,
+ workspaceId: options.workspaceId,
+ })
+ .returning();
+ const [message] = await db
+ .insert(messages)
+ .values({
+ agentId: agent.id,
+ content: 'hello',
+ id: `msg_${key}`,
+ role: 'user',
+ topicId: topic.id,
+ userId: owner,
+ workspaceId: options.workspaceId,
+ })
+ .returning();
+ return { agentId: agent.id, messageId: message.id, topicId: topic.id };
+};
+
+const cleanup = async () => {
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+};
+
+describe('assertTaskOriginAccessible (real PostgreSQL)', () => {
+ beforeEach(async () => {
+ await cleanup();
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ });
+
+ afterEach(cleanup);
+
+ it("accepts the caller's own agent conversation", async () => {
+ const own = await seedConversation(userId, 'own');
+
+ await expect(assertTaskOriginAccessible(db, { userId }, own)).resolves.toBeUndefined();
+ });
+
+ it("rejects a topic owned by another user, even with the caller's own agent", async () => {
+ const own = await seedConversation(userId, 'own');
+ const foreign = await seedConversation(otherUserId, 'foreign');
+
+ await expect(assertTaskOriginAccessible(db, { userId }, { ...foreign })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ message: 'Origin conversation not found',
+ });
+ await expect(
+ assertTaskOriginAccessible(
+ db,
+ { userId },
+ { agentId: own.agentId, topicId: foreign.topicId },
+ ),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it("rejects a teammate's topic in the same workspace", async () => {
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'origin', primaryOwnerId: userId, slug: workspaceId });
+ // A public agent is usable by every member, but the topic is still the
+ // teammate's conversation — the bridge would wake their session.
+ const teammate = await seedConversation(otherUserId, 'teammate', {
+ visibility: 'public',
+ workspaceId,
+ });
+
+ await expect(
+ assertTaskOriginAccessible(db, { userId, workspaceId }, teammate),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ assertTaskOriginAccessible(db, { userId: otherUserId, workspaceId }, teammate),
+ ).resolves.toBeUndefined();
+ });
+
+ it("rejects another user's private agent placed on the caller's topic", async () => {
+ const own = await seedConversation(userId, 'own');
+ const foreign = await seedConversation(otherUserId, 'foreign');
+
+ await expect(
+ assertTaskOriginAccessible(
+ db,
+ { userId },
+ { agentId: foreign.agentId, topicId: own.topicId },
+ ),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it("rejects an agent that is not the topic's agent", async () => {
+ const own = await seedConversation(userId, 'own');
+ const second = await seedConversation(userId, 'second');
+
+ await expect(
+ assertTaskOriginAccessible(db, { userId }, { agentId: second.agentId, topicId: own.topicId }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Origin agent does not belong to the origin topic',
+ });
+ });
+
+ it('accepts a member agent of a group topic', async () => {
+ const member = await seedConversation(userId, 'member');
+ const outsider = await seedConversation(userId, 'outsider');
+ const [group] = await db
+ .insert(chatGroups)
+ .values({ id: 'grp_origin', title: 'Group', userId })
+ .returning();
+ await db
+ .insert(chatGroupsAgents)
+ .values({ agentId: member.agentId, chatGroupId: group.id, userId });
+ const [groupTopic] = await db
+ .insert(topics)
+ .values({ groupId: group.id, id: 'tpc_group', userId })
+ .returning();
+
+ await expect(
+ assertTaskOriginAccessible(
+ db,
+ { userId },
+ { agentId: member.agentId, topicId: groupTopic.id },
+ ),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertTaskOriginAccessible(
+ db,
+ { userId },
+ { agentId: outsider.agentId, topicId: groupTopic.id },
+ ),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('rejects a message that is not in the origin topic', async () => {
+ const own = await seedConversation(userId, 'own');
+ const second = await seedConversation(userId, 'second');
+
+ await expect(
+ assertTaskOriginAccessible(db, { userId }, { ...own, messageId: second.messageId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('requires agentId and topicId together', async () => {
+ const own = await seedConversation(userId, 'own');
+
+ await expect(
+ assertTaskOriginAccessible(db, { userId }, { topicId: own.topicId }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
+
+describe('assertTaskOriginPatchAllowed (real PostgreSQL)', () => {
+ beforeEach(async () => {
+ await cleanup();
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ });
+
+ afterEach(cleanup);
+
+ it('lets an unchanged or cleared origin through without re-checking', async () => {
+ // A stored origin pointing at a conversation the caller cannot see, as
+ // a teammate's tool-created task would carry.
+ const foreign = await seedConversation(otherUserId, 'foreign');
+
+ await expect(
+ assertTaskOriginPatchAllowed(db, { userId }, foreign, { ...foreign, operationId: 'op_2' }),
+ ).resolves.toEqual({ ...foreign, operationId: 'op_2' });
+ await expect(
+ assertTaskOriginPatchAllowed(db, { userId }, foreign, undefined),
+ ).resolves.toBeUndefined();
+ });
+
+ it("rejects re-pointing an origin at another user's conversation", async () => {
+ const own = await seedConversation(userId, 'own');
+ const foreign = await seedConversation(otherUserId, 'foreign');
+
+ await expect(assertTaskOriginPatchAllowed(db, { userId }, own, foreign)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(
+ assertTaskOriginPatchAllowed(db, { userId }, undefined, foreign),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('stores an origin the bridge cannot deliver to as sent, like before', async () => {
+ const partial = { topicId: 'tpc_x' };
+
+ await expect(assertTaskOriginPatchAllowed(db, { userId }, undefined, partial)).resolves.toBe(
+ partial,
+ );
+ await expect(assertTaskOriginPatchAllowed(db, { userId }, undefined, null)).resolves.toBeNull();
+ });
+
+ it('rejects a deliverable origin with non-string ids', async () => {
+ await expect(
+ assertTaskOriginPatchAllowed(db, { userId }, undefined, { agentId: 1, topicId: 'tpc_x' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
diff --git a/apps/server/src/services/task/originValidation.ts b/apps/server/src/services/task/originValidation.ts
new file mode 100644
index 00000000000..4e4708f7745
--- /dev/null
+++ b/apps/server/src/services/task/originValidation.ts
@@ -0,0 +1,128 @@
+import type { TaskOriginContext } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+import { assertAgentUsableBy } from '@/database/utils/agent-access';
+
+/**
+ * Caller-supplied `context.origin`: the conversation a finished task reports
+ * back to. `TaskResultBridgeService` inserts a `taskCallback` card into
+ * `topicId` and wakes `agentId` there, so both are required together.
+ */
+export const taskOriginInputSchema = z.object({
+ agentId: z.string().trim().min(1),
+ messageId: z.string().trim().min(1).optional(),
+ operationId: z.string().trim().min(1).optional(),
+ toolCallId: z.string().trim().min(1).optional(),
+ topicId: z.string().trim().min(1),
+});
+
+interface OriginAccessCtx {
+ userId: string;
+ workspaceId?: string;
+}
+
+// One message for every "not yours" case, so a caller cannot use the error to
+// probe whether someone else's topic, agent or message exists.
+const originNotFound = () =>
+ new TRPCError({ code: 'NOT_FOUND', message: 'Origin conversation not found' });
+
+/**
+ * Reject an origin the caller does not own. The bridge later writes into the
+ * origin topic and runs the origin agent, so a forged pointer would plant a
+ * callback card in a teammate's conversation and wake their agent.
+ *
+ * - the topic must be the caller's own conversation (in a workspace,
+ * `TopicModel` scope matches every member's topics, so pin `userId`);
+ * - the agent must be usable by the caller and must be the topic's agent —
+ * or, for a group topic, a member of that group;
+ * - an optional `messageId` must be a message in that topic.
+ */
+export async function assertTaskOriginAccessible(
+ db: LobeChatDatabase,
+ ctx: OriginAccessCtx,
+ origin: TaskOriginContext,
+): Promise<void> {
+ const { agentId, messageId, topicId } = origin;
+ if (!agentId || !topicId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Origin requires both agentId and topicId',
+ });
+ }
+
+ const topic = await new TopicModel(db, ctx.userId, ctx.workspaceId).findById(topicId);
+ if (!topic || topic.userId !== ctx.userId) throw originNotFound();
+
+ try {
+ await assertAgentUsableBy(db, agentId, ctx);
+ } catch (error) {
+ if (error instanceof TRPCError && error.code === 'NOT_FOUND') throw originNotFound();
+ throw error;
+ }
+
+ if (topic.agentId !== agentId) {
+ const inGroup =
+ !!topic.groupId &&
+ (
+ await new ChatGroupModel(db, ctx.userId, ctx.workspaceId).getGroupAgents(topic.groupId)
+ ).some((member) => member.agentId === agentId);
+ if (!inGroup) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Origin agent does not belong to the origin topic',
+ });
+ }
+ }
+
+ if (messageId) {
+ const message = await new MessageModel(db, ctx.userId, ctx.workspaceId).findById(messageId);
+ if (!message || message.topicId !== topicId) throw originNotFound();
+ }
+}
+
+const sameOrigin = (a?: TaskOriginContext, b?: TaskOriginContext) =>
+ (a?.agentId ?? null) === (b?.agentId ?? null) &&
+ (a?.topicId ?? null) === (b?.topicId ?? null) &&
+ (a?.messageId ?? null) === (b?.messageId ?? null);
+
+// What `TaskResultBridgeService` treats as a delivery target: it delivers
+// whenever both ids are truthy, so the check must cover exactly those origins.
+const isDeliverable = (origin: unknown): boolean => {
+ if (!origin || typeof origin !== 'object') return false;
+ const { agentId, topicId } = origin as Record<string, unknown>;
+ return !!agentId && !!topicId;
+};
+
+/**
+ * `task.update` replaces the whole `context` column, and clients ship the
+ * current context back unchanged. Origin stays optional there, as it was
+ * before: no origin, or one the bridge cannot deliver to (missing agent or
+ * topic), is stored as sent. Only a deliverable target that changed (agent,
+ * topic or anchor message) is checked, so re-saving a tool-created origin
+ * keeps working while pointing a task at someone else's topic does not.
+ * Returns the origin to store: the normalized one when checked, otherwise the
+ * one that was sent.
+ */
+export async function assertTaskOriginPatchAllowed(
+ db: LobeChatDatabase,
+ ctx: OriginAccessCtx,
+ current: TaskOriginContext | undefined,
+ next: unknown,
+): Promise<unknown> {
+ if (!isDeliverable(next)) return next;
+ const parsed = taskOriginInputSchema.safeParse(next);
+ if (!parsed.success) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Invalid context.origin: agentId and topicId must be non-empty strings',
+ });
+ }
+ if (!sameOrigin(current, parsed.data)) await assertTaskOriginAccessible(db, ctx, parsed.data);
+ // Return the parsed (trimmed) origin so the row stores exactly what was checked.
+ return parsed.data;
+}
diff --git a/apps/server/src/services/task/patchValidation.ts b/apps/server/src/services/task/patchValidation.ts
index c14053d02d4..57670673529 100644
--- a/apps/server/src/services/task/patchValidation.ts
+++ b/apps/server/src/services/task/patchValidation.ts
@@ -1,3 +1,4 @@
+import type { TaskContext } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import type { AgentModel } from '@/database/models/agent';
@@ -8,6 +9,7 @@ import type { EditLockService } from '@/server/services/editLock';
import type { TaskService } from '@/server/services/task';
import { assertArchivedTaskStaysIdle } from './archiveGuard';
+import { assertTaskOriginPatchAllowed } from './originValidation';
import { assertResultingScheduleValid } from './scheduleValidation';
import { findTaskOrThrow, resolveTaskOrThrow } from './utils';
@@ -32,6 +34,7 @@ export interface TaskPatchFields {
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
automationMode?: string | null;
+ context?: Record<string, unknown>;
editorData?: unknown;
instruction?: string | null;
schedulePattern?: string | null;
@@ -121,7 +124,8 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
ctx: TaskPatchInvariantContext,
params: { data: Data; id: string; parentTaskId?: string | null },
): Promise<{ data: Data & { parentTaskId?: string | null }; resolved: ResolvedTask }> {
- const { data, id, parentTaskId } = params;
+ const { id, parentTaskId } = params;
+ let { data } = params;
await assertAssigneeAgentBelongsToUser(
ctx.serverDB,
@@ -132,6 +136,17 @@ export async function resolveTaskPatchInvariants<Data extends TaskPatchFields>(
const resolved = await resolveTaskOrThrow(ctx.taskModel, id);
assertResultingScheduleValid(resolved, data);
assertArchivedTaskStaysIdle(resolved, data);
+ // `context` replaces the whole column, origin included: a changed origin
+ // must point at the caller's own conversation like it must at create time.
+ if (data.context !== undefined) {
+ const origin = await assertTaskOriginPatchAllowed(
+ ctx.serverDB,
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ (resolved.context as TaskContext | null)?.origin,
+ data.context?.origin,
+ );
+ if (origin !== undefined) data = { ...data, context: { ...data.context, origin } };
+ }
// Collaborative edit lock: reject writes to a workspace task another member
// is actively editing. Inert until a client acquires the lock.
diff --git a/packages/builtin-skills/src/task/references/commands.md b/packages/builtin-skills/src/task/references/commands.md
index 0d36afecea4..c52105b652b 100644
--- a/packages/builtin-skills/src/task/references/commands.md
+++ b/packages/builtin-skills/src/task/references/commands.md
@@ -8,8 +8,9 @@
- `--label`: Tasks carrying any of these labels (repeatable / comma-separated; a label group name matches any label in it)
- `--tree`: Display as tree structure
- `lh task view <id>` - View task details (instruction, documents, activities)
-- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--parent <id>] [--priority <0-4>] [--label <name>]` - Create task
+- `lh task create -i <instruction> [-n <name>] [--agent <id>] [--parent <id>] [--priority <0-4>] [--label <name>] [--origin-agent <id> --origin-topic <id>]` - Create task
- Priority: 0=none, 1=urgent, 2=high, 3=normal, 4=low
+ - `--origin-agent` / `--origin-topic` (optional): the conversation to report back to when the task finishes (a result card is posted there and that agent continues). Pass both together; to be notified in your current conversation, use `$LOBEHUB_AGENT_ID` and `$LOBEHUB_TOPIC_ID`. The topic must be your own conversation.
- `lh task edit <id> [-n <name>] [-i <instruction>] [--status <status>] [--priority <0-4>] [--agent <id>] [--label <name>] [--remove-label <name>]` - Update task
- `lh task delete <id> [--yes]` - Delete task
- `lh task clear [--yes]` - Delete all tasks