Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(task): reopen a run when the user answers it in its conversation (#20582)

Arvin Xu0e323ed636c4
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
index 5c0778d2362..4595e28e945 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
@@ -5,6 +5,8 @@ import {
agentsToSessions,
messages,
sessions,
+ tasks,
+ taskTopics,
threads,
topics,
workspaces,
@@ -21,6 +23,7 @@ import {
assertCanPerformResourceAction,
getResourceMeta,
} from '@/server/services/resourcePermission';
+import { TopicRunService } from '@/server/services/task/topicRun';
import { aiAgentRouter } from '../aiAgent';
import { cleanupTestUser, createTestUser } from './integration/setup';
@@ -37,11 +40,18 @@ vi.mock('@/database/core/db-adaptor', () => ({
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(function () {
return {
- createOperation: vi.fn().mockResolvedValue({
- success: true,
- operationId: 'mock-operation-id',
- autoStarted: true,
- messageId: 'mock-message-id',
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
}),
};
}),
@@ -247,6 +257,70 @@ describe('AI Agent Router Integration Tests', () => {
expect(createOperationCalls()).toEqual([false, false]);
});
+ // Answering the same finished run twice concurrently: both sends resolve the
+ // row as ownable and dispatch, but only the first can reopen it β€” the second
+ // gets `already-running`. Its completion hook would otherwise settle a row it
+ // does not own (`onTopicComplete` completes the topic by id, without checking
+ // the operation), finishing the winner's run early and overwriting its
+ // handoff. The loser must be stopped, not left running. (Codex on #20582)
+ it('stops a send that loses the reopen race instead of letting its hook settle the winner', async () => {
+ const taskId = `task-race-${Date.now()}`;
+ const topicId = `tpc-race-${Date.now()}`;
+
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: taskId,
+ identifier: 'T-RACE',
+ instruction: 'run',
+ seq: 1,
+ status: 'completed',
+ });
+ await serverDB.insert(topics).values({
+ completedAt: new Date('2026-10-01T00:00:00Z'),
+ id: topicId,
+ status: 'completed',
+ userId,
+ });
+ await serverDB.insert(taskTopics).values({
+ operationId: 'op-original',
+ seq: 1,
+ status: 'completed',
+ taskId,
+ topicId,
+ userId,
+ });
+
+ // The concurrent winner takes the row between this send's lookup and its
+ // own reopen, so the reopen loses the race.
+ const reopen = vi
+ .spyOn(TopicRunService.prototype, 'reopen')
+ .mockResolvedValue('already-running');
+ const stop = vi
+ .spyOn(AiAgentService.prototype, 'interruptTask')
+ .mockResolvedValue({ success: true } as any);
+
+ try {
+ const caller = aiAgentRouter.createCaller(createTestContext());
+
+ await expect(
+ caller.execAgent({
+ agentId: testAgentId,
+ appContext: { topicId },
+ prompt: 'second answer',
+ }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+
+ expect(reopen).toHaveBeenCalledTimes(1);
+ // The operation that lost the race is the one stopped β€” it is never left
+ // running with a completion hook attached.
+ expect(stop).toHaveBeenCalledTimes(1);
+ expect(stop.mock.calls[0][0].operationId).toBe(reopen.mock.calls[0][0].operationId);
+ } finally {
+ reopen.mockRestore();
+ stop.mockRestore();
+ }
+ });
+
it('should create a new topic when topicId is not provided', async () => {
const caller = aiAgentRouter.createCaller(createTestContext());
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 77a594af178..ab55b7d3271 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -102,6 +102,8 @@ import {
HeteroOperationPrincipalError,
resolveActiveHeteroOperationPrincipal,
} from '@/server/services/heterogeneousAgent/operationPrincipal';
+import { createTaskRunHooks } from '@/server/services/task/runHooks';
+import { type TopicRunReopenOutcome, TopicRunService } from '@/server/services/task/topicRun';
const log = debug('lobe-server:ai-agent-router');
@@ -2547,6 +2549,25 @@ export const aiAgentRouter = router({
);
if (bridged) return bridged;
+ // A message typed into a Task's own conversation continues that Task's
+ // run β€” and the composer dispatches it, not `runTask`. Everything the Task
+ // side needs for this run is attached here: the hook that settles the run
+ // when it ends, and the reopen that puts its run row back in flight.
+ // Without the pair, an answered run is invisible to the Task: the run card
+ // keeps the finished state of the run it replied to, `cancelTopic` refuses
+ // to stop the live one, and the detail page stops polling for it.
+ const topicRunService = new TopicRunService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const topicRun = appContext?.topicId
+ ? await topicRunService.resolveOwnableRun(appContext.topicId)
+ : undefined;
+ // Recorded on the operation-created boundary and acted on once the
+ // dispatch has returned.
+ let reopenOutcome: TopicRunReopenOutcome | undefined;
+
const result = await ctx.aiAgentService.execAgent({
acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
@@ -2573,6 +2594,29 @@ export const aiAgentRouter = router({
deviceId,
localDeviceId,
existingMessageIds,
+ ...(topicRun && {
+ hooks: createTaskRunHooks({
+ db: ctx.serverDB,
+ taskId: topicRun.taskId,
+ taskIdentifier: topicRun.taskIdentifier,
+ trigger: 'manual',
+ // The Task's creator, not the caller: the completion callback
+ // resolves the workspace from `tasks.createdByUserId`, so passing a
+ // workspace member would make that lookup miss and strand the run.
+ userId: topicRun.ownerUserId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ }),
+ // Before the run's first step, so a short run can never finish β€” and
+ // have its own completion hook settle the row β€” ahead of the reopen.
+ onOperationCreated: async (operationId) => {
+ reopenOutcome = await topicRunService
+ .reopen({ link: topicRun, operationId })
+ .catch((error) => {
+ console.error('[aiAgent.execAgent] failed to reopen the task run: %O', error);
+ return 'refused' as const;
+ });
+ },
+ }),
fileIds,
mentionedAgents,
parentMessageId,
@@ -2591,6 +2635,36 @@ export const aiAgentRouter = router({
userAgent: ctx.userAgent ?? undefined,
userInterventionConfig,
});
+ // The run was dispatched but it did not take the Task's run row over. Two
+ // ways that happens: the Task was retired while the run was starting (the
+ // write failed or there is no row to keep honest), or a concurrent send on
+ // the same topic won the reopen and already owns the row. In both cases
+ // the run's hooks are already attached for the whole run, and
+ // `onTopicComplete` settles the topic row by id without checking which
+ // operation owns it β€” so letting this run continue would let the loser
+ // settle a row it does not own, finishing the winner's run ahead of it and
+ // overwriting its handoff/result. Stop it, exactly as the runner stops the
+ // run it dispatched under the same race.
+ if (reopenOutcome === 'refused' || reopenOutcome === 'already-running') {
+ const lostTheRow = reopenOutcome === 'already-running';
+ const stop = await ctx.aiAgentService
+ .interruptTask({ operationId: result.operationId })
+ .catch((error) => {
+ console.error('[aiAgent.execAgent] failed to stop the orphaned task run: %O', error);
+ return undefined;
+ });
+ // Same confirmation gate as `TaskService.interruptTaskOperation`.
+ const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;
+ throw new TRPCError({
+ code: stopped ? 'CONFLICT' : 'INTERNAL_SERVER_ERROR',
+ message: stopped
+ ? lostTheRow
+ ? 'Another run is already live on this task; this duplicate send was stopped.'
+ : 'This task run could not be recorded while it was starting; the run was stopped.'
+ : `This task run could not be recorded while it was starting, and stopping it (operation ${result.operationId}) could not be confirmed.`,
+ });
+ }
+
return toClientExecAgentResult(result);
} catch (error: any) {
console.error('execAgent failed: %O', error);
diff --git a/apps/server/src/services/task/runHooks.test.ts b/apps/server/src/services/task/runHooks.test.ts
new file mode 100644
index 00000000000..9a752ecd7e2
--- /dev/null
+++ b/apps/server/src/services/task/runHooks.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { LobeChatDatabase } from '@/database/type';
+
+import { createTaskRunHooks } from './runHooks';
+
+const { onTopicComplete } = vi.hoisted(() => ({ onTopicComplete: vi.fn() }));
+
+vi.mock('@/server/services/taskLifecycle', () => ({
+ TaskLifecycleService: vi.fn().mockImplementation(function () {
+ return { onTopicComplete };
+ }),
+}));
+
+describe('createTaskRunHooks', () => {
+ const db = {} as LobeChatDatabase;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ onTopicComplete.mockResolvedValue(undefined);
+ });
+
+ it('settles the run through onTopicComplete when it ends', async () => {
+ const [hook] = createTaskRunHooks({
+ db,
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ trigger: 'manual',
+ userId: 'user-1',
+ });
+
+ expect(hook.type).toBe('onComplete');
+
+ await hook.handler?.({
+ errorMessage: 'boom',
+ lastAssistantContent: 'the answer',
+ operationId: 'op-1',
+ reason: 'done',
+ topicId: 'tpc-1',
+ } as any);
+
+ expect(onTopicComplete).toHaveBeenCalledWith({
+ errorCode: undefined,
+ errorMessage: 'boom',
+ lastAssistantContent: 'the answer',
+ operationId: 'op-1',
+ reason: 'done',
+ runTrigger: 'manual',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ topicId: 'tpc-1',
+ });
+ });
+
+ it('defaults a run that reported no reason to a clean finish', async () => {
+ const [hook] = createTaskRunHooks({
+ db,
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ userId: 'user-1',
+ });
+
+ await hook.handler?.({ operationId: 'op-1', topicId: 'tpc-1' } as any);
+
+ expect(onTopicComplete).toHaveBeenCalledWith(expect.objectContaining({ reason: 'done' }));
+ });
+
+ it('carries the run 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({
+ db,
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ trigger: 'schedule',
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+
+ expect(hook.webhook).toMatchObject({
+ body: { runTrigger: 'schedule', taskId: 'task-1', taskIdentifier: 'T-1', userId: 'user-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.ts
new file mode 100644
index 00000000000..4634148c59c
--- /dev/null
+++ b/apps/server/src/services/task/runHooks.ts
@@ -0,0 +1,64 @@
+import type { TaskRunTrigger } from '@lobechat/types';
+
+import type { LobeChatDatabase } from '@/database/type';
+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
+import { TaskLifecycleService } from '@/server/services/taskLifecycle';
+
+export interface TaskRunHookParams {
+ db: LobeChatDatabase;
+ taskId: string;
+ taskIdentifier: string;
+ /**
+ * What opened this run. The lifecycle reads it to tell an ad-hoc run apart
+ * from an automation tick (only ticks spend the attempt budget), so it is part
+ * of the contract this hook carries β€” not the caller's local bookkeeping.
+ */
+ trigger?: TaskRunTrigger;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * The hooks that attach a Task's lifecycle to one of its runs.
+ *
+ * A run reaches the Task only through `onTopicComplete`, and the hook that
+ * delivers it is registered at dispatch β€” so every entry point that dispatches
+ * into a Task's topic has to register it. There are two: the runner (`runTask`,
+ * which owns scheduled, heartbeat and ad-hoc runs) and the composer, when a user
+ * answers a finished run in that run's own conversation. Leaving the composer
+ * out is not a cosmetic gap: the answered run would then reach no Task-side row
+ * at all β€” the run keeps the finished state of the run it replied to, no
+ * handoff/result is written for the answer, and the Task never transitions.
+ */
+export const createTaskRunHooks = (params: TaskRunHookParams): AgentHook[] => {
+ const { db, taskId, taskIdentifier, trigger, userId, workspaceId } = params;
+
+ return [
+ {
+ handler: async (event) => {
+ await new TaskLifecycleService(db, userId, workspaceId).onTopicComplete({
+ errorCode: event.errorType,
+ errorMessage: event.errorMessage,
+ lastAssistantContent: event.lastAssistantContent,
+ operationId: event.operationId,
+ reason: event.reason || 'done',
+ runTrigger: trigger,
+ taskId,
+ taskIdentifier,
+ topicId: event.topicId,
+ });
+ },
+ id: 'task-on-complete',
+ type: 'onComplete' as const,
+ webhook: {
+ // `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 },
+ delivery: 'qstash' as const,
+ fallback: 'none' as const,
+ url: '/api/workflows/task/on-topic-complete',
+ },
+ },
+ ];
+};
diff --git a/apps/server/src/services/task/topicRun.test.ts b/apps/server/src/services/task/topicRun.test.ts
new file mode 100644
index 00000000000..077b74d4c63
--- /dev/null
+++ b/apps/server/src/services/task/topicRun.test.ts
@@ -0,0 +1,195 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { TopicRunService } from './topicRun';
+
+vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));
+vi.mock('@/database/models/taskTopic', () => ({ TaskTopicModel: vi.fn() }));
+
+/**
+ * A user answering a finished run in that run's own conversation starts the
+ * next run β€” from the composer, not `runTask`. The Task side has to follow it,
+ * or the run card keeps reading as finished while the agent works and the Task
+ * never leaves its old terminal state.
+ */
+describe('TopicRunService', () => {
+ // `reopen` writes the run row and the topic's end stamp as one unit. The mock
+ // runs the body against the same object, so the models patched onto it apply
+ // inside the transaction too.
+ const db = {
+ transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn(db),
+ } as unknown as LobeChatDatabase;
+ const userId = 'user-1';
+ const topicId = 'tpc-1';
+
+ const taskModel = {
+ findById: vi.fn(),
+ lockForUpdate: vi.fn(),
+ updateStatusIfCurrent: vi.fn(),
+ };
+ const taskTopicModel = {
+ clearTopicEnded: vi.fn(),
+ findByTopicId: vi.fn(),
+ reopenSettledRun: vi.fn(),
+ };
+
+ /** As the service returns it. */
+ const link = {
+ ownerUserId: 'owner-1',
+ runStatus: 'completed',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ topicId,
+ };
+ /** As the run row comes back from the model. */
+ const run = { status: 'completed', taskId: 'task-1', topicId };
+ /** As the Task comes back from the model. */
+ const task = {
+ createdByUserId: 'owner-1',
+ identifier: 'T-1',
+ status: 'completed',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (TaskModel as any).mockImplementation(function () {
+ return taskModel;
+ });
+ (TaskTopicModel as any).mockImplementation(function () {
+ return taskTopicModel;
+ });
+
+ taskModel.findById.mockResolvedValue(task);
+ taskModel.lockForUpdate.mockResolvedValue(true);
+ taskModel.updateStatusIfCurrent.mockResolvedValue({ status: 'running' });
+ taskTopicModel.clearTopicEnded.mockResolvedValue(undefined);
+ taskTopicModel.findByTopicId.mockResolvedValue(null);
+ taskTopicModel.reopenSettledRun.mockResolvedValue(true);
+ });
+
+ describe('resolveOwnableRun', () => {
+ it('leaves an ordinary conversation alone', async () => {
+ // The common case on the send path, and the one that must stay free: no
+ // run row means this topic is not a Task's, so nothing else is read.
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun('tpc-plain'),
+ ).resolves.toBeUndefined();
+
+ expect(taskModel.findById).not.toHaveBeenCalled();
+ });
+
+ it('resolves the run, its Task and the Task owner', async () => {
+ taskTopicModel.findByTopicId.mockResolvedValue(run);
+
+ await expect(new TopicRunService(db, userId).resolveOwnableRun(topicId)).resolves.toEqual(
+ link,
+ );
+ });
+
+ it('falls back to the caller when the Task has no recorded creator', async () => {
+ taskTopicModel.findByTopicId.mockResolvedValue(run);
+ taskModel.findById.mockResolvedValue({ ...task, createdByUserId: null });
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId),
+ ).resolves.toMatchObject({ ownerUserId: userId });
+ });
+
+ it('refuses a run a live run already owns', async () => {
+ // A second send is not a second Task run: taking the row over would steal
+ // the operation id cancellation interrupts, and attaching a completion
+ // hook would let this send settle the row while that run is still going.
+ taskTopicModel.findByTopicId.mockResolvedValue({ ...run, status: 'running' });
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId),
+ ).resolves.toBeUndefined();
+ expect(taskModel.findById).not.toHaveBeenCalled();
+ });
+
+ it('refuses a run whose Task was canceled', async () => {
+ // There is no Task-side row left to keep honest, and settling one could
+ // move a canceled Task back out of its terminal state. The message still
+ // sends β€” as an ordinary turn in the conversation.
+ taskTopicModel.findByTopicId.mockResolvedValue(run);
+ taskModel.findById.mockResolvedValue({ ...task, status: 'canceled' });
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId),
+ ).resolves.toBeUndefined();
+ });
+
+ it('refuses a run whose Task is gone', async () => {
+ taskTopicModel.findByTopicId.mockResolvedValue(run);
+ taskModel.findById.mockResolvedValue(null);
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId),
+ ).resolves.toBeUndefined();
+ });
+ });
+
+ describe('reopen', () => {
+ it('puts the run back in flight and takes the Task back to running', async () => {
+ const outcome = await new TopicRunService(db, userId).reopen({
+ link,
+ operationId: 'op-answer',
+ });
+
+ expect(outcome).toBe('reopened');
+ expect(taskModel.lockForUpdate).toHaveBeenCalledWith('task-1');
+ expect(taskTopicModel.reopenSettledRun).toHaveBeenCalledWith(topicId, 'op-answer');
+ expect(taskTopicModel.clearTopicEnded).toHaveBeenCalledWith(topicId);
+ expect(taskModel.updateStatusIfCurrent).toHaveBeenCalledWith(
+ 'task-1',
+ 'completed',
+ 'running',
+ expect.objectContaining({ error: null }),
+ );
+ });
+
+ it('writes under the Task owner, not the member who answered the run', async () => {
+ await new TopicRunService(db, 'member-2').reopen({ link, operationId: 'op-answer' });
+
+ expect(TaskModel).toHaveBeenCalledWith(expect.anything(), 'owner-1', undefined);
+ expect(TaskTopicModel).toHaveBeenCalledWith(expect.anything(), 'owner-1', undefined);
+ });
+
+ it('reports a run a newer operation has taken over without writing anything', async () => {
+ taskTopicModel.reopenSettledRun.mockResolvedValue(false);
+
+ const outcome = await new TopicRunService(db, userId).reopen({
+ link,
+ operationId: 'op-queued',
+ });
+
+ expect(outcome).toBe('already-running');
+ expect(taskTopicModel.clearTopicEnded).not.toHaveBeenCalled();
+ expect(taskModel.updateStatusIfCurrent).not.toHaveBeenCalled();
+ });
+
+ it('refuses a Task retired while the run was starting', async () => {
+ // The caller stops the run on this outcome: its hooks are already
+ // attached, and a run the Task side never recorded must not be allowed to
+ // settle the Task.
+ taskModel.findById.mockResolvedValue({ ...task, status: 'canceled' });
+
+ await expect(
+ new TopicRunService(db, userId).reopen({ link, operationId: 'op-answer' }),
+ ).resolves.toBe('refused');
+ expect(taskTopicModel.reopenSettledRun).not.toHaveBeenCalled();
+ });
+
+ it('refuses a Task deleted while the run was starting', async () => {
+ taskModel.lockForUpdate.mockResolvedValue(false);
+
+ await expect(
+ new TopicRunService(db, userId).reopen({ link, operationId: 'op-answer' }),
+ ).resolves.toBe('refused');
+ expect(taskTopicModel.reopenSettledRun).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/task/topicRun.ts b/apps/server/src/services/task/topicRun.ts
new file mode 100644
index 00000000000..fbe61851650
--- /dev/null
+++ b/apps/server/src/services/task/topicRun.ts
@@ -0,0 +1,143 @@
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import type { LobeChatDatabase } from '@/database/type';
+
+export interface TopicRunLink {
+ /**
+ * The Task's creator, which is the identity the completion callback reads:
+ * `/api/workflows/task/on-topic-complete` derives the workspace from
+ * `tasks.createdByUserId = userId`. A workspace member answering someone
+ * else's run must hand the owner over β€” passing the member would make that
+ * lookup miss and settle the run in personal scope, where the workspace row
+ * is invisible, leaving it stuck `running`.
+ */
+ ownerUserId: string;
+ /** The run row's status, as the Task side last wrote it. */
+ runStatus: string;
+ taskId: string;
+ taskIdentifier: string;
+ /**
+ * The conversation the row belongs to β€” the one the user typed into, and the
+ * one the reopen is keyed on. A run the server placed on a topic of its own is
+ * not a continuation of this row; if that ever happened, the row left behind
+ * is settled by the orphaned-run reconciliation like any other lost run.
+ */
+ topicId: string;
+}
+
+/** What reopening a run did, so the caller can tell a no-op from a refusal. */
+export type TopicRunReopenOutcome =
+ /** The row is this operation's: the run is recorded and live. */
+ | 'reopened'
+ /** A newer run owns the row. Nothing was written; leave it alone. */
+ | 'already-running'
+ /** The Task was retired under this send: nothing can be recorded. */
+ | 'refused';
+
+/**
+ * The Task side of a run started in a conversation.
+ *
+ * Runs normally start in `TaskRunnerService.runTask`, which owns both ends of a
+ * Task's bookkeeping: it opens the run row and registers the hook that closes
+ * it. A user answering a finished run in that run's own conversation is the
+ * second entry point β€” dispatched from the composer, never through the runner.
+ * Left out, it is the one run the Task cannot see: the run card keeps the
+ * finished state of the run it replied to, `TaskService.cancelTopic` refuses to
+ * stop the live one, and the detail page stops polling for it.
+ *
+ * Deliberately not a method on `TaskService`, which is the natural home by name
+ * but drags the runner, the scheduler and the review services behind it β€” and
+ * the send path this runs on needs two queries, not that graph.
+ */
+export class TopicRunService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ /**
+ * The run this send can own, if any β€” the whole "is this a Task run?" test for
+ * the composer path.
+ *
+ * `undefined` is the ordinary conversation, which is the common case, plus the
+ * two cases where this send must not take the run over:
+ *
+ * - **the Task is retired** (canceled, or gone): there is no Task-side row to
+ * keep honest, and settling one would resurrect it β€” a default-config Task
+ * can be moved out of `canceled` by a completion. The message still sends,
+ * as an ordinary turn in the conversation.
+ * - **the row is already `running`**: a live run owns it, and a second send is
+ * not a second Task run. Reopening would steal the `operationId` that
+ * cancellation interrupts, and attaching a completion hook would let this
+ * send settle the row while that run is still going.
+ */
+ async resolveOwnableRun(topicId: string): Promise<TopicRunLink | undefined> {
+ const run = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTopicId(
+ topicId,
+ );
+ if (!run?.topicId || run.status === 'running') return undefined;
+
+ const task = await new TaskModel(this.db, this.userId, this.workspaceId).findById(run.taskId);
+ if (!task || task.status === 'canceled') return undefined;
+
+ return {
+ ownerUserId: task.createdByUserId ?? this.userId,
+ runStatus: run.status,
+ taskId: run.taskId,
+ taskIdentifier: task.identifier,
+ topicId,
+ };
+ }
+
+ /**
+ * Put the run back in flight, because its topic is live again.
+ *
+ * The run row and the topic's end stamp are two aggregates, so the pair
+ * commits in one transaction β€” a stamp that failed on its own would leave a
+ * live run stamped as ended. That is also why the model method only writes the
+ * row and this owns the pair.
+ *
+ * Runs on the operation-created boundary, *before* the run's first step: a
+ * short run can otherwise finish β€” and have its completion hook settle the
+ * row β€” while the dispatch is still returning, and a reopen after that would
+ * rewrite a finished run back to `running` with nothing left to settle it.
+ */
+ async reopen(params: {
+ link: TopicRunLink;
+ operationId: string;
+ }): Promise<TopicRunReopenOutcome> {
+ const { link, operationId } = params;
+ const { topicId } = link;
+
+ return this.db.transaction(async (tx) => {
+ const taskModel = new TaskModel(tx, link.ownerUserId, this.workspaceId);
+ const taskTopicModel = new TaskTopicModel(tx, link.ownerUserId, this.workspaceId);
+
+ // The runner's own lock, for the runner's own reason: a Task deleted or
+ // retired while this run was starting has to be observed here rather than
+ // have a live run reopened underneath it.
+ if (!(await taskModel.lockForUpdate(link.taskId))) return 'refused';
+
+ const task = await taskModel.findById(link.taskId);
+ if (!task || task.status === 'canceled') return 'refused';
+
+ if (!(await taskTopicModel.reopenSettledRun(topicId, operationId))) return 'already-running';
+
+ await taskTopicModel.clearTopicEnded(topicId);
+
+ if (task.status !== 'running') {
+ await taskModel.updateStatusIfCurrent(link.taskId, task.status, 'running', {
+ error: null,
+ startedAt: new Date(),
+ });
+ }
+
+ return 'reopened';
+ });
+ }
+}
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index bbc3b5ba237..3124df244d0 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -16,7 +16,7 @@ import { TopicModel } from '@/database/models/topic';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';
-import { TaskLifecycleService } from '@/server/services/taskLifecycle';
+import { createTaskRunHooks } from '@/server/services/task/runHooks';
import { buildTaskPrompt } from './buildTaskPrompt';
import {
@@ -60,7 +60,6 @@ export class TaskRunnerService {
private agentModel: AgentModel;
private briefModel: BriefModel;
private db: LobeChatDatabase;
- private taskLifecycle: TaskLifecycleService;
private taskModel: TaskModel;
private taskTopicModel: TaskTopicModel;
private topicModel: TopicModel;
@@ -77,7 +76,6 @@ export class TaskRunnerService {
this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);
this.topicModel = new TopicModel(db, userId, workspaceId);
this.briefModel = new BriefModel(db, userId, workspaceId);
- this.taskLifecycle = new TaskLifecycleService(db, userId, workspaceId);
}
/**
@@ -216,10 +214,7 @@ export class TaskRunnerService {
const aiAgentService = new AiAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
});
- const taskId = task.id;
const taskIdentifier = task.identifier;
- const taskLifecycle = this.taskLifecycle;
- const userId = this.userId;
const checkpoint = this.taskModel.getCheckpointConfig(task);
const reviewConfig = this.taskModel.getReviewConfig(task);
@@ -291,34 +286,14 @@ export class TaskRunnerService {
additionalPluginIds: pluginIds,
...(typeof taskConfig.model === 'string' && { model: taskConfig.model }),
...(typeof taskConfig.provider === 'string' && { provider: taskConfig.provider }),
- hooks: [
- {
- handler: async (event) => {
- await taskLifecycle.onTopicComplete({
- errorCode: event.errorType,
- errorMessage: event.errorMessage,
- lastAssistantContent: event.lastAssistantContent,
- operationId: event.operationId,
- reason: event.reason || 'done',
- runTrigger: trigger,
- taskId,
- taskIdentifier,
- topicId: event.topicId,
- });
- },
- id: 'task-on-complete',
- type: 'onComplete' as const,
- webhook: {
- // `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 },
- delivery: 'qstash' as const,
- fallback: 'none' as const,
- url: '/api/workflows/task/on-topic-complete',
- },
- },
- ],
+ hooks: createTaskRunHooks({
+ db: this.db,
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ trigger,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ }),
...(attachmentFileIds.length > 0 ? { fileIds: attachmentFileIds } : {}),
...(maxSteps ? { maxSteps } : {}),
prompt,
diff --git a/packages/database/src/models/__tests__/taskTopic.reopenSettledRun.test.ts b/packages/database/src/models/__tests__/taskTopic.reopenSettledRun.test.ts
new file mode 100644
index 00000000000..e9c2c6be685
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskTopic.reopenSettledRun.test.ts
@@ -0,0 +1,115 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { tasks, taskTopics, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskTopicModel } from '../taskTopic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-topic-reopen-test-user-id';
+const taskId = 'task-reopen-1';
+const topicId = 'tpc-reopen-1';
+
+const readRun = async () =>
+ (await serverDB.select().from(taskTopics).where(eq(taskTopics.topicId, topicId)).limit(1))[0];
+
+const readTopic = async () =>
+ (await serverDB.select().from(topics).where(eq(topics.id, topicId)).limit(1))[0];
+
+/** A Task whose run already finished: the state the user answers from. */
+const seed = async ({ runStatus = 'completed', operationId = 'op-original' } = {}) => {
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: taskId,
+ identifier: 'T-1',
+ instruction: 'do the thing',
+ seq: 1,
+ status: 'completed',
+ });
+ await serverDB.insert(topics).values({
+ completedAt: new Date('2026-10-02T10:00:00Z'),
+ id: topicId,
+ status: 'completed',
+ userId,
+ });
+ await serverDB.insert(taskTopics).values({
+ operationId,
+ seq: 1,
+ status: runStatus,
+ taskId,
+ topicId,
+ userId,
+ });
+};
+
+describe('TaskTopicModel.reopenSettledRun', () => {
+ beforeEach(async () => {
+ await serverDB.delete(taskTopics);
+ await serverDB.delete(topics);
+ await serverDB.delete(tasks);
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(taskTopics);
+ await serverDB.delete(users);
+ });
+
+ it('puts a settled run back in flight under the answering operation', async () => {
+ await seed();
+ const model = new TaskTopicModel(serverDB, userId);
+
+ expect(await model.reopenSettledRun(topicId, 'op-answer')).toBe(true);
+
+ const run = await readRun();
+ expect(run).toMatchObject({ operationId: 'op-answer', status: 'running' });
+ // A user replying in the run's conversation is not an automation tick, and
+ // only ticks may spend the attempt budget.
+ expect(run.trigger).toBe('manual');
+ });
+
+ it('keeps the live run’s operation id when a message lands behind it', async () => {
+ // The row is already `running`: this message joins the run in flight, and
+ // the row must keep naming the operation that cancellation interrupts.
+ await seed({ operationId: 'op-live', runStatus: 'running' });
+ const model = new TaskTopicModel(serverDB, userId);
+
+ expect(await model.reopenSettledRun(topicId, 'op-queued')).toBe(false);
+
+ expect(await readRun()).toMatchObject({ operationId: 'op-live', status: 'running' });
+ });
+
+ it('reopens a run the sweep settled as failed', async () => {
+ // Every terminal outcome reopens the same way β€” the point is that the row
+ // is no longer live, not which way it ended.
+ await seed({ operationId: 'op-lost', runStatus: 'failed' });
+
+ expect(await new TaskTopicModel(serverDB, userId).reopenSettledRun(topicId, 'op-answer')).toBe(
+ true,
+ );
+ expect((await readRun()).status).toBe('running');
+ });
+
+ it('leaves the end stamp to the caller', async () => {
+ // The row and the topic's `completedAt` are two aggregates; the caller
+ // commits them together, so a lone reopen must not half-apply the pair.
+ await seed();
+
+ await new TaskTopicModel(serverDB, userId).reopenSettledRun(topicId, 'op-answer');
+
+ expect((await readTopic()).completedAt).toBeInstanceOf(Date);
+ });
+
+ it('does not touch a run owned by someone else', async () => {
+ await seed();
+
+ expect(
+ await new TaskTopicModel(serverDB, 'someone-else').reopenSettledRun(topicId, 'op-x'),
+ ).toBe(false);
+ expect(await readRun()).toMatchObject({ operationId: 'op-original', status: 'completed' });
+ });
+});
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index 21d8e823c79..ca7189e5e03 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -4,7 +4,7 @@ import {
TRANSIENT_FAILED_RUN_STATUS,
} from '@lobechat/const/goal';
import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';
-import { and, count, desc, eq, gte, inArray, sql } from 'drizzle-orm';
+import { and, count, desc, eq, gte, inArray, ne, sql } from 'drizzle-orm';
import type { TaskTopicItem } from '../schemas/task';
import { tasks, taskTopics } from '../schemas/task';
@@ -298,6 +298,42 @@ export class TaskTopicModel {
return result.length > 0;
}
+ /**
+ * Put a settled run back in flight, because its topic is live again.
+ *
+ * A Task's run row is written at the two ends of a run the runner owns: the
+ * runner opens it (`running`, with the operation it dispatched) and the
+ * lifecycle closes it (terminal). A user answering a finished run in that
+ * run's own conversation starts a third kind of run β€” dispatched from the
+ * composer, never through `runTask` β€” so without this the row stays terminal
+ * while the topic it names is visibly working: the run card keeps its finished
+ * state, `TaskService.cancelTopic` refuses to stop the live run, and the
+ * detail page stops polling for it.
+ *
+ * Guarded on the row not already being `running`: a message queued behind a
+ * run that is still going must not steal that run's `operationId`, which is
+ * the only handle cancellation has on it.
+ *
+ * The trigger is restamped as `'manual'` for the same reason it is written at
+ * all: only automation ticks may spend the attempt budget, and a user replying
+ * in the run's conversation is not one. Leaving the previous value would make
+ * an orphaned answer settle as a tick and count against the schedule.
+ *
+ * Only the run row is written; clearing the topic's end stamp is the caller's
+ * to commit alongside it β€” see `TaskRunClaimRepo`.
+ */
+ async reopenSettledRun(topicId: string, operationId: string): Promise<boolean> {
+ const result = await this.db
+ .update(taskTopics)
+ .set({ operationId, status: 'running', trigger: 'manual' })
+ .where(
+ and(eq(taskTopics.topicId, topicId), ne(taskTopics.status, 'running'), this.ownership()),
+ )
+ .returning({ topicId: taskTopics.topicId });
+
+ return result.length > 0;
+ }
+
/** Undo {@link markTopicEnded}'s end stamp for a run that is live again. */
async clearTopicEnded(topicId: string): Promise<void> {
await this.db