π€― 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): settle runs of a Task its runner did not create (#23444)
AmAzing-7e1562d3aa69
diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.tsindex eea98c3f378..67174ba808c 100644--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.test.ts@@ -1,5 +1,8 @@+import { PgDialect } from 'drizzle-orm/pg-core';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TaskLifecycleService } from '@/server/services/taskLifecycle';+import { onTopicComplete } from './onTopicComplete';const { claim, getServerDB, isRunAlreadySettled, lifecycleOnTopicComplete, markSettled, release } =@@ -44,13 +47,19 @@ const failedRunPayload = {};describe('onTopicComplete webhook', () => {+ let taskRows: { identifier?: string; workspaceId: string | null }[];+ let where: ReturnType<typeof vi.fn>;+beforeEach(() => {- const chain = {+ taskRows = [{ workspaceId: 'ws-1' }];+ const chain: Record<string, unknown> = {from: () => chain,- limit: async () => [{ workspaceId: 'ws-1' }],- where: () => chain,+ limit: async () => taskRows,};+ where = vi.fn(() => chain);+ chain.where = where;getServerDB.mockReset().mockResolvedValue({ select: () => chain });+ vi.mocked(TaskLifecycleService).mockClear();isRunAlreadySettled.mockReset().mockResolvedValue(false);lifecycleOnTopicComplete.mockReset().mockResolvedValue(undefined);claim.mockReset().mockResolvedValue('claimed');@@ -82,6 +91,64 @@ describe('onTopicComplete webhook', () => {expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);});+ describe('a run started by someone other than the Task creator', () => {+ // A teammate, or a bot driving someone else's Task, runs it under their own+ // user id; the hook body carries that runner, not the creator.+ const runnerPayload = { ...failedRunPayload, reason: 'done', userId: 'user-runner' };++ it('looks the Task up by id alone, not by the runner as its creator', async () => {+ const { context } = makeContext(runnerPayload);++ await onTopicComplete(context);++ const { sql } = new PgDialect().sqlToQuery(where.mock.calls[0][0]);+ expect(sql).toContain('"id"');+ expect(sql).not.toContain('created_by_user_id');+ });++ it("settles the run in the Task's workspace", async () => {+ const { context, json } = makeContext(runnerPayload);++ await onTopicComplete(context);++ expect(TaskLifecycleService).toHaveBeenCalledWith(expect.anything(), 'user-runner', 'ws-1');+ expect(lifecycleOnTopicComplete).toHaveBeenCalledTimes(1);+ expect(json).toHaveBeenCalledWith({ success: true });+ });++ it("falls back to the runner's workspace when the Task row is gone", async () => {+ taskRows = [];+ const { context } = makeContext({ ...runnerPayload, workspaceId: 'ws-runner' });++ await onTopicComplete(context);++ expect(isRunAlreadySettled).toHaveBeenCalledWith(+ expect.anything(),+ 'user-runner',+ 'ws-runner',+ expect.objectContaining({ operationId: 'op-1' }),+ );+ expect(TaskLifecycleService).toHaveBeenCalledWith(+ expect.anything(),+ 'user-runner',+ 'ws-runner',+ );+ });++ it('keeps a personal Task personal even when the body names a workspace', async () => {+ taskRows = [{ workspaceId: null }];+ const { context } = makeContext({ ...runnerPayload, workspaceId: 'ws-runner' });++ await onTopicComplete(context);++ expect(TaskLifecycleService).toHaveBeenCalledWith(+ expect.anything(),+ 'user-runner',+ undefined,+ );+ });+ });+it('acks a delayed delivery for a run the sweep already settled without re-applying it', async () => {isRunAlreadySettled.mockResolvedValue(true);const { context, json } = makeContext(failedRunPayload);diff --git a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.tsindex 808e5e8406d..d741efd6f02 100644--- a/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts+++ b/apps/server/src/router-hono/workflows/task/handlers/onTopicComplete.ts@@ -1,6 +1,6 @@import type { TaskRunTrigger } from '@lobechat/types';import debug from 'debug';-import { and, eq } from 'drizzle-orm';+import { eq } from 'drizzle-orm';import type { Context } from 'hono';import { tasks } from '@/database/schemas';@@ -27,7 +27,10 @@ export interface OnTopicCompletePayload {taskId: string;taskIdentifier?: string;topicId?: string;+ /** The runner's user, which is not necessarily the Task's creator. */userId: string;+ /** The runner's workspace scope. Absent from hooks registered before it was added. */+ workspaceId?: string;}export async function onTopicComplete(c: Context) {@@ -61,12 +64,20 @@ export async function onTopicComplete(c: Context) {const db = await getServerDB();// System-level callback: derive workspace from the task row so the// lifecycle service writes briefs / status into the correct workspace.+ //+ // Looked up by id alone. `userId` is whoever ran the Task, and in a+ // workspace that is often not its creator β a teammate, or a bot driving+ // someone else's Task. Requiring the creator here dropped the workspace for+ // those runs, so the lifecycle ran in the runner's personal scope, found+ // neither the Task nor its run row, and acked the delivery without moving+ // either: the Task stayed `running` after its topic had ended. The body's+ // own `workspaceId` covers a Task that is gone by the time the run reports.const [taskRow] = await db.select({ identifier: tasks.identifier, workspaceId: tasks.workspaceId }).from(tasks)- .where(and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId)))+ .where(eq(tasks.id, taskId)).limit(1);- const wsId = taskRow?.workspaceId ?? undefined;+ const wsId = (taskRow ? taskRow.workspaceId : body.workspaceId) ?? undefined;// A delivery delayed past the orphaned-run grace window can land after the// reconciliation sweep already settled this run. Driving the lifecycle againdiff --git a/apps/server/src/services/task/runHooks.test.ts b/apps/server/src/services/task/runHooks.test.tsindex 9a752ecd7e2..a2b6cc4b451 100644--- a/apps/server/src/services/task/runHooks.test.ts+++ b/apps/server/src/services/task/runHooks.test.ts@@ -65,7 +65,7 @@ describe('createTaskRunHooks', () => {expect(onTopicComplete).toHaveBeenCalledWith(expect.objectContaining({ reason: 'done' }));});- it('carries the run in the static webhook body, so a lost socket still settles it', () => {+ it('carries the run and its workspace in the static webhook body, so a lost socket still settles it', () => {// The production callback rebuilds the lifecycle params server-side from// this body β it never sees the in-process handler's closure.const [hook] = createTaskRunHooks({@@ -78,7 +78,15 @@ describe('createTaskRunHooks', () => {});expect(hook.webhook).toMatchObject({- body: { runTrigger: 'schedule', taskId: 'task-1', taskIdentifier: 'T-1', userId: 'user-1' },+ body: {+ runTrigger: 'schedule',+ taskId: 'task-1',+ taskIdentifier: 'T-1',+ userId: 'user-1',+ // The runner may not be the Task's creator, so the callback cannot+ // rebuild the scope from the Task row's creator.+ workspaceId: 'ws-1',+ },url: '/api/workflows/task/on-topic-complete',});});diff --git a/apps/server/src/services/task/runHooks.ts b/apps/server/src/services/task/runHooks.tsindex 4634148c59c..a2ea479691a 100644--- a/apps/server/src/services/task/runHooks.ts+++ b/apps/server/src/services/task/runHooks.ts@@ -54,7 +54,11 @@ export const createTaskRunHooks = (params: TaskRunHookParams): AgentHook[] => {// `runTrigger` rides in the static body so the production webhook// callback (which reconstructs onTopicComplete params server-side)// knows whether this was a manual run or an automation tick.- body: { runTrigger: trigger, taskId, taskIdentifier, userId },+ // `workspaceId` rides along for the same reason: the runner is not+ // always the Task's creator (a teammate or a bot running someone+ // else's Task), so the callback cannot rebuild the scope from the+ // Task's creator alone.+ body: { runTrigger: trigger, taskId, taskIdentifier, userId, workspaceId },delivery: 'qstash' as const,fallback: 'none' as const,url: '/api/workflows/task/on-topic-complete',