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): hand a superseded run to the follow-up, not stuck running (#22090)

Rdmclin2e8653d941f5b
diff --git a/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts b/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts
index 93c0c94726a..018d33a0655 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/__tests__/watchdog.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
findStuckTasks: vi.fn(),
getServerDB: vi.fn(),
notifyTaskRunFailed: vi.fn(),
+ reconcileInterruptedTaskRuns: vi.fn(),
reconcileOrphanedTaskRuns: vi.fn(),
updateStatus: vi.fn(),
}));
@@ -38,6 +39,10 @@ vi.mock('@/server/services/taskLifecycle/reconcile', () => ({
reconcileOrphanedTaskRuns: mocks.reconcileOrphanedTaskRuns,
}));
+vi.mock('@/server/services/taskLifecycle/reconcileInterrupted', () => ({
+ reconcileInterruptedTaskRuns: mocks.reconcileInterruptedTaskRuns,
+}));
+
vi.mock('@/server/services/taskResultBridge', () => ({ TaskResultBridgeService: vi.fn() }));
vi.mock('@/server/services/taskResultBridge/redisStore', () => ({
@@ -58,6 +63,18 @@ describe('task watchdog', () => {
mocks.findRecoverableScopes.mockResolvedValue([]);
mocks.notifyTaskRunFailed.mockResolvedValue(undefined);
mocks.reconcileOrphanedTaskRuns.mockResolvedValue({ converged: [] });
+ mocks.reconcileInterruptedTaskRuns.mockResolvedValue({ paused: [] });
+ });
+
+ it('parks interrupted runs nothing took over on every tick', async () => {
+ mocks.findStuckTasks.mockResolvedValue([]);
+ mocks.reconcileInterruptedTaskRuns.mockResolvedValue({ paused: ['tpc-1'] });
+
+ const { body, status } = await runWatchdog();
+
+ expect(status).toBe(200);
+ expect(mocks.reconcileInterruptedTaskRuns).toHaveBeenCalledTimes(1);
+ expect(body.interrupted).toEqual({ paused: ['tpc-1'] });
});
// A heartbeat timeout is a failure, not a decision: it goes to the
diff --git a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts b/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
index 551e25ec39e..8d15152e963 100644
--- a/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
+++ b/apps/server/src/router-hono/workflows/task/handlers/watchdog.ts
@@ -4,6 +4,7 @@ import type { Context } from 'hono';
import { getServerDB } from '@/database/server';
import { failStuckTasks } from '@/server/services/taskLifecycle/failStuckTasks';
import { reconcileOrphanedTaskRuns } from '@/server/services/taskLifecycle/reconcile';
+import { reconcileInterruptedTaskRuns } from '@/server/services/taskLifecycle/reconcileInterrupted';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { TaskResultCallbackRedisStore } from '@/server/services/taskResultBridge/redisStore';
@@ -19,6 +20,8 @@ const log = debug('lobe-server:workflows:task:watchdog');
* {@link reconcileOrphanedTaskRuns}) β€” the net for a Task the first one
* cannot see, either because it sets no `heartbeatTimeout` or because its
* run ends without ever delivering its terminal state.
+ * 3. A `running` run row whose operation was interrupted and that no run took
+ * over (see {@link reconcileInterruptedTaskRuns}) β€” parked as `paused`.
*
* No per-user authentication: this is a global sweep registered as a QStash
* Schedule (cron). Signature verification is handled by the `qstashAuth`
@@ -35,6 +38,9 @@ export async function watchdog(c: Context) {
// Task would read as `running` forever. Settle those from the
// operation's own end instead.
const reconciled = await reconcileOrphanedTaskRuns(db);
+ // An interrupted run is not an outcome the net above may converge; a run
+ // nothing took over is handed back to a person instead.
+ const interrupted = await reconcileInterruptedTaskRuns(db);
const recoverableCallbacks = await TaskResultCallbackRedisStore.findRecoverableScopes();
const recoveredCallbacks: string[] = [];
@@ -62,15 +68,17 @@ export async function watchdog(c: Context) {
}
log(
- 'Watchdog scan: checked=%d failed=%d orphaned=%d callbacks=%d',
+ 'Watchdog scan: checked=%d failed=%d orphaned=%d interrupted=%d callbacks=%d',
checked,
failed.length,
reconciled.converged.length,
+ interrupted.paused.length,
recoveredCallbacks.length,
);
return c.json({
checked,
failed,
+ interrupted,
orphaned: reconciled,
recoveredCallbacks,
success: true,
diff --git a/apps/server/src/services/aiAgent/composerRun.test.ts b/apps/server/src/services/aiAgent/composerRun.test.ts
index 13fd0c98ca1..34b0d958861 100644
--- a/apps/server/src/services/aiAgent/composerRun.test.ts
+++ b/apps/server/src/services/aiAgent/composerRun.test.ts
@@ -2,23 +2,29 @@ import { describe, expect, it, vi } from 'vitest';
import { startComposerRun } from './composerRun';
+const resolveOwnableRun = vi.hoisted(() => vi.fn());
+
vi.mock('@/server/services/task/topicRun', () => ({
TopicRunService: vi.fn().mockImplementation(function () {
- return { resolveOwnableRun: vi.fn().mockResolvedValue(undefined) };
+ return { resolveOwnableRun };
}),
}));
vi.mock('@/server/services/task/runHooks', () => ({ createTaskRunHooks: vi.fn() }));
-const run = (supersedeLiveRun?: boolean) => {
+const run = (supersedeLiveRun?: boolean, replacesOperationId?: string) => {
const execAgent = vi.fn().mockResolvedValue({ operationId: 'op-2' });
return startComposerRun(
{
- aiAgentService: { execAgent, interruptTask: vi.fn() } as any,
+ aiAgentService: {
+ execAgent,
+ interruptTask: vi.fn(),
+ isOperationInterrupted: vi.fn().mockResolvedValue(true),
+ } as any,
db: {} as any,
supersedeLiveRun,
userId: 'user-1',
},
- { agentId: 'agt-1', appContext: { topicId: 'tpc-1' }, prompt: 'hi' },
+ { agentId: 'agt-1', appContext: { topicId: 'tpc-1' }, prompt: 'hi', replacesOperationId },
).then(() => execAgent.mock.calls[0][0]);
};
@@ -30,4 +36,29 @@ describe('startComposerRun', () => {
it('waits on the topic instead of interrupting its run when told not to supersede', async () => {
await expect(run(false)).resolves.toMatchObject({ interactiveStart: false });
});
+
+ it('tells the Task side which run the send replaces, so it can take the run over', async () => {
+ // A follow-up within seconds of the last reply supersedes a run that is
+ // still `running`; without this the Task never hands the run over.
+ resolveOwnableRun.mockClear().mockResolvedValue(undefined);
+
+ await run(undefined, 'op-1');
+ expect(resolveOwnableRun).toHaveBeenCalledWith('tpc-1', {
+ isStopRequested: expect.any(Function),
+ replacesOperationId: 'op-1',
+ supersedeLiveRun: true,
+ threadId: undefined,
+ });
+ // The interrupt state comes from the runtime the send runs on.
+ const [, send] = resolveOwnableRun.mock.calls[0];
+ await expect(send.isStopRequested('op-1')).resolves.toBe(true);
+
+ await run(false);
+ expect(resolveOwnableRun).toHaveBeenLastCalledWith('tpc-1', {
+ isStopRequested: expect.any(Function),
+ replacesOperationId: undefined,
+ supersedeLiveRun: false,
+ threadId: undefined,
+ });
+ });
});
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index a798e1189f8..a0f76669d4b 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -52,7 +52,7 @@ export type ComposerRunRequest = Pick<
};
export interface ComposerRunContext {
- aiAgentService: Pick<AiAgentService, 'execAgent' | 'interruptTask'>;
+ aiAgentService: Pick<AiAgentService, 'execAgent' | 'interruptTask' | 'isOperationInterrupted'>;
/** Server-derived request provenance; never client-passable. */
clientIp?: string;
db: LobeChatDatabase;
@@ -87,8 +87,20 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
// 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.db, ctx.userId, ctx.workspaceId ?? undefined);
+ //
+ // A follow-up sent while the Task's run is still live replaces that run, so
+ // it takes the run row over from it rather than reopening a settled one β€”
+ // the replaced run ends `interrupted`, which never settles the row itself.
const topicRun = appContext?.topicId
- ? await topicRunService.resolveOwnableRun(appContext.topicId)
+ ? await topicRunService.resolveOwnableRun(appContext.topicId, {
+ replacesOperationId: input.replacesOperationId,
+ // A queued follow-up sent "now" stops the run itself before this
+ // start, and clears the topic marker: the run still reads `running`
+ // here but has already been asked to stop.
+ isStopRequested: (operationId) => ctx.aiAgentService.isOperationInterrupted(operationId),
+ supersedeLiveRun: ctx.supersedeLiveRun ?? true,
+ threadId: appContext.threadId,
+ })
: undefined;
// Recorded on the operation-created boundary and acted on once the
// dispatch has returned.
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index b057dc085be..a0716db3691 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -342,6 +342,14 @@ export class AiAgentService {
return this.agentRuntimeService.executeStep(params);
}
+ /**
+ * Whether someone already asked this run to stop. The run may still be
+ * finishing its current step, so its row can read `running` for a moment.
+ */
+ isOperationInterrupted(operationId: string): Promise<boolean> {
+ return this.agentRuntimeService.isOperationInterrupted(operationId);
+ }
+
/** Continue a run parked in `waiting_for_client` (see AgentRuntimeService). */
resumeFromClientLlmWait(
params: Parameters<AgentRuntimeService['resumeFromClientLlmWait']>[0],
diff --git a/apps/server/src/services/task/topicRun.supersede.integration.test.ts b/apps/server/src/services/task/topicRun.supersede.integration.test.ts
new file mode 100644
index 00000000000..bb8bd087ae5
--- /dev/null
+++ b/apps/server/src/services/task/topicRun.supersede.integration.test.ts
@@ -0,0 +1,391 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import { agentOperations, tasks, taskTopics, topics, users } from '@/database/schemas';
+import { TaskLifecycleService } from '@/server/services/taskLifecycle';
+import { ORPHANED_RUN_GRACE_MS } from '@/server/services/taskLifecycle/reconcile';
+import { reconcileInterruptedTaskRuns } from '@/server/services/taskLifecycle/reconcileInterrupted';
+
+import { TopicRunService } from './topicRun';
+
+/**
+ * The incident: a Task run finished its last reply, the user followed up a few
+ * seconds later, and the follow-up superseded the run before it had settled. The
+ * superseded run ended `interrupted`, which never settles the run row, and the
+ * follow-up did not take the row over because it was still `running` β€” so the
+ * Task stayed `running` with nothing behind it, for every later follow-up too.
+ */
+const userId = 'topic-run-supersede-integration-user';
+
+// 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 T0 = new Date('2026-11-01T10:38:03Z');
+const at = (seconds: number) => new Date(T0.getTime() + seconds * 1000);
+
+let seq = 0;
+
+const seedOperation = async (
+ topicId: string,
+ id: string,
+ values: { createdAt: Date; status: string; trigger?: string },
+) => {
+ await db.insert(agentOperations).values({
+ completedAt: values.status === 'running' ? null : values.createdAt,
+ createdAt: values.createdAt,
+ id,
+ status: values.status as any,
+ topicId,
+ trigger: values.trigger,
+ updatedAt: values.createdAt,
+ userId,
+ });
+};
+
+/** A root Task whose run is `running` under `op-task` on its own topic. */
+const seedRunningTask = async (
+ operation: { status: string; trigger?: string } = { status: 'running', trigger: 'task' },
+) => {
+ seq += 1;
+ const task = await new TaskModel(db, userId).create({ instruction: 'Write the report' });
+ await db.update(tasks).set({ startedAt: T0, status: 'running' }).where(eq(tasks.id, task.id));
+
+ const topicId = `tpc-supersede-${seq}`;
+ const taskOperationId = `op-task-${seq}`;
+ await db.insert(topics).values({ id: topicId, userId });
+ await seedOperation(topicId, taskOperationId, { createdAt: T0, ...operation });
+ await db.insert(taskTopics).values({
+ operationId: taskOperationId,
+ seq: 1,
+ status: 'running',
+ taskId: task.id,
+ topicId,
+ trigger: 'manual',
+ userId,
+ });
+
+ return { task, taskOperationId, topicId };
+};
+
+const readRun = async (topicId: string) =>
+ (await db.select().from(taskTopics).where(eq(taskTopics.topicId, topicId)).limit(1))[0];
+
+const readTask = async (taskId: string) => new TaskModel(db, userId).findById(taskId);
+
+const complete = (
+ task: { id: string; identifier: string },
+ topicId: string,
+ operationId: string,
+ reason = 'done',
+) =>
+ new TaskLifecycleService(db, userId).onTopicComplete({
+ operationId,
+ reason,
+ taskId: task.id,
+ taskIdentifier: task.identifier,
+ topicId,
+ });
+
+beforeEach(async () => {
+ await db.delete(agentOperations).where(eq(agentOperations.userId, userId));
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await db.delete(agentOperations).where(eq(agentOperations.userId, userId));
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe('a follow-up that supersedes a live Task run (real PostgreSQL)', () => {
+ it('takes the run over, and the Task goes to review when the follow-up ends', async () => {
+ const { task, taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+
+ // The composer names the live run it replaces.
+ const link = await service.resolveOwnableRun(topicId, {
+ replacesOperationId: taskOperationId,
+ supersedeLiveRun: true,
+ });
+ expect(link).toMatchObject({ takeOverOperationId: taskOperationId, taskId: task.id });
+
+ // The start interrupts the replaced run, then creates the follow-up.
+ await db
+ .update(agentOperations)
+ .set({ completedAt: at(45), status: 'interrupted' })
+ .where(eq(agentOperations.id, taskOperationId));
+ await seedOperation(topicId, 'op-follow-up', { createdAt: at(45), status: 'running' });
+
+ await expect(service.reopen({ link: link!, operationId: 'op-follow-up' })).resolves.toBe(
+ 'reopened',
+ );
+ expect(await readRun(topicId)).toMatchObject({
+ operationId: 'op-follow-up',
+ status: 'running',
+ });
+
+ // The follow-up is the run that ends the Task's turn.
+ await complete(task, topicId, 'op-follow-up');
+
+ expect((await readRun(topicId)).status).toBe('completed');
+ expect((await readTask(task.id))?.status).toBe('paused');
+ });
+
+ it('takes over from a run a queued follow-up already stopped, before it reads interrupted', async () => {
+ // A queued follow-up sent "now" interrupts the run and clears the topic
+ // marker before it starts, and names no `replacesOperationId`: the run row
+ // and the operation still read `running`, only its interrupt is set.
+ const { task, taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+ const isStopRequested = async (operationId: string) => operationId === taskOperationId;
+
+ const link = await service.resolveOwnableRun(topicId, {
+ isStopRequested,
+ supersedeLiveRun: true,
+ });
+ expect(link?.takeOverOperationId).toBe(taskOperationId);
+
+ await seedOperation(topicId, 'op-send-now', { createdAt: at(14), status: 'running' });
+ await expect(service.reopen({ link: link!, operationId: 'op-send-now' })).resolves.toBe(
+ 'reopened',
+ );
+ await complete(task, topicId, 'op-send-now');
+
+ expect((await readRun(topicId)).status).toBe('completed');
+ expect((await readTask(task.id))?.status).toBe('paused');
+ });
+
+ it('leaves a live run nobody asked to stop, and fails closed on an unreadable interrupt state', async () => {
+ const { topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+
+ await expect(
+ service.resolveOwnableRun(topicId, { isStopRequested: async () => false }),
+ ).resolves.toBeUndefined();
+ await expect(
+ service.resolveOwnableRun(topicId, {
+ isStopRequested: async () => {
+ throw new Error('redis down');
+ },
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('takes over from a run that already ended but never settled the row', async () => {
+ // Every later follow-up of the stuck topic: the run row still names the
+ // interrupted run, and no client tracks it any more.
+ const { task, taskOperationId, topicId } = await seedRunningTask({
+ status: 'interrupted',
+ trigger: 'task',
+ });
+ const service = new TopicRunService(db, userId);
+
+ const link = await service.resolveOwnableRun(topicId, { supersedeLiveRun: true });
+ expect(link?.takeOverOperationId).toBe(taskOperationId);
+
+ await seedOperation(topicId, 'op-later', { createdAt: at(120), status: 'running' });
+ await expect(service.reopen({ link: link!, operationId: 'op-later' })).resolves.toBe(
+ 'reopened',
+ );
+ await complete(task, topicId, 'op-later');
+
+ expect((await readTask(task.id))?.status).toBe('paused');
+ });
+
+ it('takes over from the live foreground run the composer retires', async () => {
+ const { taskOperationId, topicId } = await seedRunningTask({
+ status: 'running',
+ trigger: 'chat',
+ });
+ await db
+ .update(topics)
+ .set({
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-1', operationId: taskOperationId },
+ },
+ })
+ .where(eq(topics.id, topicId));
+
+ const link = await new TopicRunService(db, userId).resolveOwnableRun(topicId, {
+ supersedeLiveRun: true,
+ });
+
+ expect(link?.takeOverOperationId).toBe(taskOperationId);
+ });
+
+ it('leaves a live run that this send does not stop', async () => {
+ // A Task-triggered run is a background producer's: the composer does not
+ // retire it unless the client names it, so the follow-up is a plain turn.
+ const { taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+
+ await expect(
+ service.resolveOwnableRun(topicId, { supersedeLiveRun: true }),
+ ).resolves.toBeUndefined();
+ // A server-started follow-up never retires the run it waits on.
+ await expect(
+ service.resolveOwnableRun(topicId, { supersedeLiveRun: false }),
+ ).resolves.toBeUndefined();
+ expect((await readRun(topicId)).operationId).toBe(taskOperationId);
+ });
+
+ it('never hands the run to a thread send, which stops nothing on the main spine', async () => {
+ const { taskOperationId, topicId } = await seedRunningTask();
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId, {
+ replacesOperationId: taskOperationId,
+ supersedeLiveRun: true,
+ threadId: 'thd-1',
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('leaves a run whose operation wrote no row', async () => {
+ // A run executed on the client never writes one; that proves nothing.
+ const { taskOperationId, topicId } = await seedRunningTask();
+ await db.delete(agentOperations).where(eq(agentOperations.id, taskOperationId));
+
+ await expect(
+ new TopicRunService(db, userId).resolveOwnableRun(topicId, { supersedeLiveRun: true }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('ignores the superseded run when it reports after the follow-up took over', async () => {
+ const { task, taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+ const link = await service.resolveOwnableRun(topicId, {
+ replacesOperationId: taskOperationId,
+ });
+ await seedOperation(topicId, 'op-follow-up', { createdAt: at(45), status: 'running' });
+ await service.reopen({ link: link!, operationId: 'op-follow-up' });
+
+ // The old run's success and an error from tearing it down both arrive late.
+ await complete(task, topicId, taskOperationId, 'done');
+ await complete(task, topicId, taskOperationId, 'error');
+
+ expect(await readRun(topicId)).toMatchObject({
+ operationId: 'op-follow-up',
+ status: 'running',
+ });
+ const stored = await readTask(task.id);
+ expect(stored?.status).toBe('running');
+ expect(stored?.error).toBeNull();
+ });
+});
+
+describe('a superseded run that completes while the follow-up takes over (real PostgreSQL)', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('loses the run row to the follow-up even when it passed the ownership check first', async () => {
+ const { task, taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+ await seedOperation(topicId, 'op-follow-up', { createdAt: at(45), status: 'running' });
+
+ // The old run's completion checks ownership while it still owns the row…
+ const realCheck = TaskTopicModel.prototype.isSupersededOperation;
+ vi.spyOn(TaskTopicModel.prototype, 'isSupersededOperation').mockImplementationOnce(
+ async function (this: TaskTopicModel, ...args) {
+ const superseded = await realCheck.apply(this, args);
+ // …and the follow-up takes the row over right after that check.
+ const link = await service.resolveOwnableRun(topicId, {
+ replacesOperationId: taskOperationId,
+ });
+ await service.reopen({ link: link!, operationId: 'op-follow-up' });
+ return superseded;
+ },
+ );
+
+ await complete(task, topicId, taskOperationId, 'done');
+
+ // The follow-up's live run keeps the row, and the Task keeps running.
+ expect(await readRun(topicId)).toMatchObject({
+ operationId: 'op-follow-up',
+ status: 'running',
+ });
+ expect((await readTask(task.id))?.status).toBe('running');
+ });
+});
+
+describe('a follow-up that reopens the run while its last completion is still settling (real PostgreSQL)', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('leaves the Task to the follow-up instead of pausing it under the live run', async () => {
+ const { task, taskOperationId, topicId } = await seedRunningTask();
+ const service = new TopicRunService(db, userId);
+ // Resolved while the old run still owns a `running` row.
+ const link = await service.resolveOwnableRun(topicId, {
+ replacesOperationId: taskOperationId,
+ });
+ await seedOperation(topicId, 'op-follow-up', { createdAt: at(45), status: 'running' });
+
+ // The old run settles the row first; the follow-up's takeover then misses
+ // and reopens the settled row, while the old completion is still running.
+ const realUpdate = TaskTopicModel.prototype.updateStatus;
+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockImplementationOnce(async function (
+ this: TaskTopicModel,
+ ...args
+ ) {
+ const written = await realUpdate.apply(this, args);
+ await expect(service.reopen({ link: link!, operationId: 'op-follow-up' })).resolves.toBe(
+ 'reopened',
+ );
+ return written;
+ });
+
+ await complete(task, topicId, taskOperationId, 'done');
+
+ expect(await readRun(topicId)).toMatchObject({
+ operationId: 'op-follow-up',
+ status: 'running',
+ });
+ expect((await readTask(task.id))?.status).toBe('running');
+
+ // The follow-up is the run that settles the Task.
+ await complete(task, topicId, 'op-follow-up');
+ expect((await readTask(task.id))?.status).toBe('paused');
+ });
+});
+
+describe('reconcileInterruptedTaskRuns (real PostgreSQL)', () => {
+ const staleBefore = new Date(T0.getTime() + ORPHANED_RUN_GRACE_MS);
+
+ it('parks a Task whose interrupted run nothing took over', async () => {
+ const { task, topicId } = await seedRunningTask({ status: 'interrupted', trigger: 'task' });
+
+ const result = await reconcileInterruptedTaskRuns(db, { staleBefore });
+
+ expect(result.paused).toContain(topicId);
+ expect((await readRun(topicId)).status).toBe('canceled');
+ const stored = await readTask(task.id);
+ // Back to a person β€” not a verdict on the work.
+ expect(stored?.status).toBe('paused');
+ expect(stored?.completedAt).toBeNull();
+ });
+
+ it('leaves a Task whose conversation still has a run going', async () => {
+ const { task, topicId } = await seedRunningTask({ status: 'interrupted', trigger: 'task' });
+ await seedOperation(topicId, 'op-still-going', { createdAt: at(45), status: 'running' });
+
+ const result = await reconcileInterruptedTaskRuns(db, { staleBefore });
+
+ expect(result.paused).not.toContain(topicId);
+ expect((await readRun(topicId)).status).toBe('running');
+ expect((await readTask(task.id))?.status).toBe('running');
+ });
+
+ it('waits out the grace window', async () => {
+ const { task, topicId } = await seedRunningTask({ status: 'interrupted', trigger: 'task' });
+
+ const result = await reconcileInterruptedTaskRuns(db, { staleBefore: T0 });
+
+ expect(result.paused).not.toContain(topicId);
+ expect((await readTask(task.id))?.status).toBe('running');
+ });
+});
diff --git a/apps/server/src/services/task/topicRun.ts b/apps/server/src/services/task/topicRun.ts
index 3089b8b42c2..42ceb485759 100644
--- a/apps/server/src/services/task/topicRun.ts
+++ b/apps/server/src/services/task/topicRun.ts
@@ -1,6 +1,11 @@
+import { isAgentOperationInFlight } from '@lobechat/types';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
import type { LobeChatDatabase } from '@/database/type';
+import { isComposerSupersedableTrigger } from '@/server/services/agentRuntime/foregroundOperation';
export interface TopicRunLink {
/**
@@ -14,6 +19,11 @@ export interface TopicRunLink {
ownerUserId: string;
/** The run row's status, as the Task side last wrote it. */
runStatus: string;
+ /**
+ * Set when the row is still `running` under an operation this send replaces:
+ * the send takes the row over from it instead of reopening a settled one.
+ */
+ takeOverOperationId?: string;
taskId: string;
taskIdentifier: string;
/**
@@ -25,6 +35,27 @@ export interface TopicRunLink {
topicId: string;
}
+/** What the send knows about the run it may replace. */
+export interface TopicRunSendContext {
+ /**
+ * Whether someone already asked this run to stop (its interrupt sentinel is
+ * set). Such a run ends `interrupted` and never settles its row itself.
+ */
+ isStopRequested?: (operationId: string) => Promise<boolean>;
+ /** The run the client asked this send to replace (`replacesOperationId`). */
+ replacesOperationId?: string;
+ /**
+ * Whether this start retires a live foreground run on the topic, as a person
+ * at the composer does. A server-started follow-up waits instead.
+ */
+ supersedeLiveRun?: boolean;
+ /**
+ * Set for a send into a thread. A thread start neither replaces nor retires
+ * the topic's main run, so it can never take a `running` row over.
+ */
+ threadId?: string | null;
+}
+
/** 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. */
@@ -71,16 +102,33 @@ export class TopicRunService {
* 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.
+ * - **the row is `running` under a run this send leaves alone**: that run
+ * still owns it, and a second send is not a second Task run. Taking it over
+ * 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.
+ *
+ * A `running` row is taken over when this send ends the run behind it (see
+ * {@link resolveTakeOver}). That is the common shape of a follow-up: the user
+ * answers within seconds of the last reply, before the run has settled, and
+ * the composer supersedes it. The superseded run ends `interrupted`, which
+ * never settles the row β€” so unless this send takes it over, the Task stays
+ * `running` with nothing behind it.
*/
- async resolveOwnableRun(topicId: string): Promise<TopicRunLink | undefined> {
+ async resolveOwnableRun(
+ topicId: string,
+ send: TopicRunSendContext = {},
+ ): Promise<TopicRunLink | undefined> {
const run = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTopicId(
topicId,
);
- if (!run?.topicId || run.status === 'running') return undefined;
+ if (!run?.topicId) return undefined;
+
+ let takeOverOperationId: string | undefined;
+ if (run.status === 'running') {
+ takeOverOperationId = await this.resolveTakeOver(topicId, run.operationId, send);
+ if (!takeOverOperationId) return undefined;
+ }
const task = await new TaskModel(this.db, this.userId, this.workspaceId).findById(run.taskId);
// An archived task is hidden from every list; its topic stays a plain chat.
@@ -89,12 +137,88 @@ export class TopicRunService {
return {
ownerUserId: task.createdByUserId ?? this.userId,
runStatus: run.status,
+ ...(takeOverOperationId && { takeOverOperationId }),
taskId: run.taskId,
taskIdentifier: task.identifier,
topicId,
};
}
+ /**
+ * The operation a `running` row can be taken over from, if this send ends it
+ * β€” or it has already ended. A thread send ends nothing on the main spine,
+ * and is never granted one:
+ *
+ * - **it is no longer in flight**: interrupted, or ended with its report still
+ * in transit. Nothing will run under it again; its late report, if any, is
+ * ignored once a newer run owns the row (`onTopicComplete`).
+ * - **it was already asked to stop**: a queued follow-up sent "now" stops the
+ * run and clears the topic marker before starting, so neither of the two
+ * rules below can see it.
+ * - **it is the run this send replaces** (`replacesOperationId`): the start
+ * interrupts it before dispatching. Honored only for the caller's own run on
+ * this topic, the same check the start applies before stopping it.
+ * - **it is the topic's live foreground run**, which an interactive send
+ * retires before starting (`supersedeRunningForegroundOperation`): same
+ * conditions β€” the marker holder, `running`, a supersedable trigger, the
+ * caller's own, and not a device-hosted run.
+ *
+ * Anything else is a run that keeps going next to this send.
+ */
+ private async resolveTakeOver(
+ topicId: string,
+ operationId: string | null,
+ send: TopicRunSendContext,
+ ): Promise<string | undefined> {
+ if (!operationId || send.threadId) return undefined;
+
+ const operation = await new AgentOperationModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findById(operationId);
+ // A missing row proves nothing: a run executed on the client never writes
+ // one, and its report could not be told apart from the new run's.
+ if (!operation) return undefined;
+ if (!isAgentOperationInFlight(operation.status)) return operationId;
+
+ if (operation.topicId !== topicId) return undefined;
+
+ // Already asked to stop β€” most often by this very send: a queued follow-up
+ // sent "now" interrupts the run and clears the topic marker before it
+ // starts, so the run still reads `running` but is on its way out.
+ if (await this.isStopRequested(send, operationId)) return operationId;
+
+ // Workspace reads are member-wide: a teammate's live run is never ours to end.
+ if (operation.userId !== this.userId) return undefined;
+
+ if (send.replacesOperationId === operationId) return operationId;
+
+ if (send.supersedeLiveRun === false || operation.status !== 'running') return undefined;
+ if (!isComposerSupersedableTrigger(operation.trigger)) return undefined;
+
+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findById(topicId);
+ const marker = topic?.metadata?.runningOperation;
+ if (marker?.operationId !== operationId || marker.heteroType) return undefined;
+
+ return operationId;
+ }
+
+ /** Fails closed: an unreadable sentinel leaves the run with its owner. */
+ private async isStopRequested(send: TopicRunSendContext, operationId: string) {
+ if (!send.isStopRequested) return false;
+ try {
+ return await send.isStopRequested(operationId);
+ } catch (error) {
+ console.error(
+ '[TopicRunService] failed to read the interrupt state of %s:',
+ operationId,
+ error,
+ );
+ return false;
+ }
+ }
+
/**
* Put the run back in flight, because its topic is live again.
*
@@ -129,7 +253,13 @@ export class TopicRunService {
const task = await taskModel.findById(link.taskId);
if (!task || task.status === 'canceled' || task.archivedAt) return 'refused';
- if (!(await taskTopicModel.reopenSettledRun(topicId, operationId))) return 'already-running';
+ // Take the row over from the run this send replaced; if that run settled
+ // in the meantime, the row is reopened like any settled one.
+ const tookOver =
+ !!link.takeOverOperationId &&
+ (await taskTopicModel.takeOverRunningRun(topicId, link.takeOverOperationId, operationId));
+ if (!tookOver && !(await taskTopicModel.reopenSettledRun(topicId, operationId)))
+ return 'already-running';
await taskTopicModel.clearTopicEnded(topicId);
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 8d0f0cb7cc4..8839ee9b33b 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -144,6 +144,21 @@ export class TaskLifecycleService {
log('onTopicComplete: task=%s topic=%s reason=%s', taskIdentifier, topicId, reason);
+ // A run a follow-up in the same conversation superseded no longer owns the
+ // Task: the follow-up took its run row over and settles it when it ends. A
+ // late report from the old run (its success arriving after the interrupt,
+ // or an error from tearing it down) must not settle the row or move the Task
+ // under the run that is still going.
+ if (topicId && (await this.isSupersededReport(topicId, params.operationId))) {
+ log(
+ 'onTopicComplete: op=%s was superseded on topic=%s β€” ignoring its %s',
+ params.operationId,
+ topicId,
+ reason,
+ );
+ return;
+ }
+
await this.taskModel.updateHeartbeat(taskId);
const currentTask = await this.taskModel.findById(taskId);
@@ -157,7 +172,8 @@ export class TaskLifecycleService {
if (reason === 'done') {
// 1. Update topic status
- if (topicId) await this.taskTopicModel.updateStatus(taskId, topicId, 'completed');
+ if (topicId && !(await this.settleRunRow(taskId, topicId, params.operationId, 'completed')))
+ return;
// 2. Generate handoff summary + topic title (best-effort LLM synthesis).
// It also says which output the run delivered: its earlier report when
@@ -223,6 +239,19 @@ export class TaskLifecycleService {
);
}
+ // A follow-up may have reopened this run while the handoff and brief
+ // above were being written (the row was settled, so it reopens rather
+ // than takes over). The Task is then the follow-up's to settle: moving it
+ // now would pause or complete it under a run that is still going.
+ if (topicId && (await this.isSupersededReport(topicId, params.operationId))) {
+ log(
+ 'onTopicComplete: op=%s was followed up on topic=%s mid-settle β€” leaving the Task to it',
+ params.operationId,
+ topicId,
+ );
+ return;
+ }
+
// 5. Default post-tick transition.
// - Automation task whose own tick requested completion (the
// instruction's end condition was verified as met) β†’ 'completed',
@@ -364,12 +393,16 @@ export class TaskLifecycleService {
);
}
} else if (reason === 'error') {
- if (topicId)
- await this.taskTopicModel.updateStatus(
+ if (
+ topicId &&
+ !(await this.settleRunRow(
taskId,
topicId,
+ params.operationId,
resolveFailedRunStatus(errorMessage),
- );
+ ))
+ )
+ return;
const errorText = errorMessage || 'Unknown error';
@@ -527,6 +560,45 @@ export class TaskLifecycleService {
if (finalTask) await this.maybeRearmHeartbeat(finalTask, reason);
}
+ /**
+ * Write the run row's terminal status for this report, unless a newer
+ * operation took the row over β€” checked inside the write, so a takeover that
+ * lands after the early {@link isSupersededReport} check still wins.
+ *
+ * @returns `false` when the report was superseded and the lifecycle must stop.
+ */
+ private async settleRunRow(
+ taskId: string,
+ topicId: string,
+ operationId: string,
+ status: string,
+ ): Promise<boolean> {
+ const written = await this.taskTopicModel.updateStatus(taskId, topicId, status, {
+ reportedOperationId: operationId,
+ });
+ // Nothing written: either there is no row to keep honest (the runner has
+ // not recorded this run yet), or a newer run owns it.
+ if (written !== false) return true;
+ if (!(await this.isSupersededReport(topicId, operationId))) return true;
+
+ log('onTopicComplete: op=%s lost topic=%s to a follow-up mid-settle', operationId, topicId);
+ return false;
+ }
+
+ /**
+ * Whether this report comes from a run that a newer operation has already
+ * taken the run row over from. Fails open: a lookup failure keeps the
+ * lifecycle's previous behaviour rather than dropping a real completion.
+ */
+ private async isSupersededReport(topicId: string, operationId: string): Promise<boolean> {
+ try {
+ return await this.taskTopicModel.isSupersededOperation(topicId, operationId);
+ } catch (error) {
+ log('superseded-run check failed for op=%s (non-fatal): %O', operationId, error);
+ return false;
+ }
+ }
+
/**
* Settle a successful task and advance its dependency graph.
*
diff --git a/apps/server/src/services/taskLifecycle/reconcileInterrupted.ts b/apps/server/src/services/taskLifecycle/reconcileInterrupted.ts
new file mode 100644
index 00000000000..43367f1c611
--- /dev/null
+++ b/apps/server/src/services/taskLifecycle/reconcileInterrupted.ts
@@ -0,0 +1,123 @@
+import debug from 'debug';
+
+import type { InterruptedRunningTopic } from '@/database/models/task';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { ORPHANED_RUN_GRACE_MS } from './reconcile';
+
+const log = debug('task-lifecycle:reconcile-interrupted');
+
+/**
+ * The run status an interrupted run is settled with β€” the same one a user's
+ * Stop (`TaskService.cancelTopic`) writes.
+ */
+const INTERRUPTED_RUN_STATUS = 'canceled';
+
+export interface ReconcileInterruptedRunsOptions {
+ /** Cap on the rows settled in one pass, so a backlog drains over ticks. */
+ limit?: number;
+ /** Override the grace window. Tests use it to age a fixture. */
+ staleBefore?: Date;
+}
+
+export interface ReconcileInterruptedRunsResult {
+ checked: number;
+ /** Rows whose settle failed; they stay `running` for the next pass. */
+ failed: string[];
+ /** Topic ids whose Task this pass moved to `paused`. */
+ paused: string[];
+ /** Rows another writer settled or took over first. */
+ skipped: string[];
+}
+
+/**
+ * Park Tasks whose run was interrupted and that nothing took over.
+ *
+ * An interrupt never settles a run: when a user follows up in the run's
+ * conversation, the follow-up takes the run row over and settles it when it
+ * ends. If no follow-up took it over, the row stays `running` under an
+ * operation that will never report again, and so does the Task.
+ *
+ * The Task is moved to `paused` β€” the state a user's own Stop leaves it in β€”
+ * not `failed` or `completed`: an interrupt is not a verdict on the work, so it
+ * goes back to a person. A topic with any operation still in flight is left
+ * alone (see `TaskModel.findInterruptedRunningTopics`), so a Task that is still
+ * continuing is never parked under it.
+ */
+export const reconcileInterruptedTaskRuns = async (
+ db: LobeChatDatabase,
+ options: ReconcileInterruptedRunsOptions = {},
+): Promise<ReconcileInterruptedRunsResult> => {
+ const staleBefore = options.staleBefore ?? new Date(Date.now() - ORPHANED_RUN_GRACE_MS);
+ const rows = await TaskModel.findInterruptedRunningTopics(db, {
+ limit: options.limit,
+ staleBefore,
+ });
+
+ const paused: string[] = [];
+ const skipped: string[] = [];
+ const failed: string[] = [];
+
+ for (const row of rows) {
+ try {
+ if (await parkInterruptedRun(db, row)) {
+ paused.push(row.topicId);
+ // The Task is parked without a brief, so leave the trail here.
+ console.info('[task-reconcile] paused task after an interrupted run nothing took over', {
+ operationId: row.operationId,
+ taskId: row.taskId,
+ topicId: row.topicId,
+ });
+ } else skipped.push(row.topicId);
+ } catch (error) {
+ failed.push(row.topicId);
+ console.error('[task-reconcile] interrupted run settle failed: %O', { error, row });
+ }
+ }
+
+ log(
+ 'interrupted runs: checked=%d paused=%d skipped=%d failed=%d',
+ rows.length,
+ paused.length,
+ skipped.length,
+ failed.length,
+ );
+
+ return { checked: rows.length, failed, paused, skipped };
+};
+
+/**
+ * Settle one interrupted run and park its Task, as one unit.
+ *
+ * The row moves only while it is still `running` under the interrupted
+ * operation, so a follow-up that took it over in the meantime β€” or a user's
+ * Stop that settled it β€” wins, and the sweep reports a skip.
+ */
+const parkInterruptedRun = async (
+ db: LobeChatDatabase,
+ row: InterruptedRunningTopic,
+): Promise<boolean> =>
+ db.transaction(async (tx) => {
+ const workspaceId = row.workspaceId ?? undefined;
+ const taskTopicModel = new TaskTopicModel(tx, row.userId, workspaceId);
+
+ if (
+ !(await taskTopicModel.claimRunIfRunning(
+ row.topicId,
+ row.operationId,
+ INTERRUPTED_RUN_STATUS,
+ ))
+ )
+ return false;
+ await taskTopicModel.markTopicEnded(row.topicId, INTERRUPTED_RUN_STATUS);
+
+ // Only from `running`: a Task the user already moved on keeps its state.
+ await new TaskModel(tx, row.userId, workspaceId).updateStatusIfCurrent(
+ row.taskId,
+ 'running',
+ 'paused',
+ );
+ return true;
+ });
diff --git a/packages/database/src/models/__tests__/task.orphanedRuns.test.ts b/packages/database/src/models/__tests__/task.orphanedRuns.test.ts
index 92570df8eaf..db3d65a0c35 100644
--- a/packages/database/src/models/__tests__/task.orphanedRuns.test.ts
+++ b/packages/database/src/models/__tests__/task.orphanedRuns.test.ts
@@ -180,6 +180,59 @@ describe('TaskModel.findOrphanedRunningTopics', () => {
});
});
+describe('TaskModel.findInterruptedRunningTopics', () => {
+ const findInterrupted = () => TaskModel.findInterruptedRunningTopics(serverDB, { staleBefore });
+
+ /** Another operation on the same topic, e.g. the follow-up that is still going. */
+ const seedTopicOperation = (topicId: string, status: 'done' | 'running' | 'waiting_for_human') =>
+ serverDB.insert(agentOperations).values({
+ completedAt: longAgo,
+ id: `op-follow-up-${topicId}-${status}`,
+ status,
+ topicId,
+ userId,
+ updatedAt: longAgo,
+ });
+
+ it('returns a running run whose interrupted operation nothing took over', async () => {
+ const { operationId, taskId, topicId } = await seed({ operationStatus: 'interrupted' });
+
+ const rows = await findInterrupted();
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ operationId, taskId, taskIdentifier: 'T-1', topicId, userId });
+ });
+
+ it('ignores a run whose topic still has an operation in flight', async () => {
+ // The conversation is still going: the Task is continuing, not stuck.
+ const running = await seed({ operationStatus: 'interrupted' });
+ await seedTopicOperation(running.topicId, 'running');
+ const parked = await seed({ operationStatus: 'interrupted' });
+ await seedTopicOperation(parked.topicId, 'waiting_for_human');
+
+ expect(await findInterrupted()).toHaveLength(0);
+ });
+
+ it('still returns it once the other operations on the topic have ended', async () => {
+ const { topicId } = await seed({ operationStatus: 'interrupted' });
+ await seedTopicOperation(topicId, 'done');
+
+ expect(await findInterrupted()).toHaveLength(1);
+ });
+
+ it('ignores runs ended any other way, inside the grace window, or already settled', async () => {
+ await seed({ operationStatus: 'error' });
+ await seed({ operationStatus: 'done' });
+ await seed({ operationStatus: 'running' });
+ await seed({ endedAt: new Date('2026-10-02T16:00:00Z'), operationStatus: 'interrupted' });
+ await seed({ operationStatus: 'interrupted', taskStatus: 'paused' });
+ await seed({ operationStatus: 'interrupted', runStatus: 'canceled' });
+ await seed({ operationStatus: 'interrupted', parentOperationId: 'op-parent' });
+
+ expect(await findInterrupted()).toHaveLength(0);
+ });
+});
+
describe('TaskRunClaimRepo', () => {
it('flips a run that still names its own operation out of `running`', async () => {
const { operationId, topicId } = await seed();
diff --git a/packages/database/src/models/__tests__/task.surface.test.ts b/packages/database/src/models/__tests__/task.surface.test.ts
index 14e7af1df9a..5bb8cf4f206 100644
--- a/packages/database/src/models/__tests__/task.surface.test.ts
+++ b/packages/database/src/models/__tests__/task.surface.test.ts
@@ -124,6 +124,7 @@ describe('TaskModel public surface', () => {
it('keeps the static methods', () => {
expect(
[
+ 'findInterruptedRunningTopics',
'findOrphanedRunningTopics',
'findStuckTasks',
'getScheduledTasks',
diff --git a/packages/database/src/models/__tests__/taskTopic.takeOver.test.ts b/packages/database/src/models/__tests__/taskTopic.takeOver.test.ts
new file mode 100644
index 00000000000..0edc11f16fc
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskTopic.takeOver.test.ts
@@ -0,0 +1,147 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentOperations, tasks, taskTopics, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskTopicModel } from '../taskTopic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-topic-takeover-test-user-id';
+const taskId = 'task-takeover-1';
+const topicId = 'tpc-takeover-1';
+
+const readRun = async () =>
+ (await serverDB.select().from(taskTopics).where(eq(taskTopics.topicId, topicId)).limit(1))[0];
+
+const model = () => new TaskTopicModel(serverDB, userId);
+
+const seedOperation = (id: string, createdAt: Date) =>
+ serverDB.insert(agentOperations).values({ createdAt, id, status: 'running', topicId, userId });
+
+/** A Task whose run is still `running` under `op-old`. */
+const seed = async ({ runStatus = 'running', operationId = 'op-old' } = {}) => {
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: taskId,
+ identifier: 'T-1',
+ instruction: 'do the thing',
+ seq: 1,
+ status: 'running',
+ });
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ await serverDB.insert(taskTopics).values({
+ operationId,
+ seq: 1,
+ status: runStatus,
+ taskId,
+ topicId,
+ trigger: 'schedule',
+ userId,
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(agentOperations);
+ 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(agentOperations);
+ await serverDB.delete(taskTopics);
+ await serverDB.delete(users);
+});
+
+describe('TaskTopicModel.takeOverRunningRun', () => {
+ it('hands a running run to the operation that replaced it', async () => {
+ await seed();
+
+ await expect(model().takeOverRunningRun(topicId, 'op-old', 'op-new')).resolves.toBe(true);
+
+ const run = await readRun();
+ expect(run.operationId).toBe('op-new');
+ expect(run.status).toBe('running');
+ // A user's follow-up is not an automation tick.
+ expect(run.trigger).toBe('manual');
+ });
+
+ it('leaves a row another operation already owns', async () => {
+ await seed({ operationId: 'op-other' });
+
+ await expect(model().takeOverRunningRun(topicId, 'op-old', 'op-new')).resolves.toBe(false);
+ expect((await readRun()).operationId).toBe('op-other');
+ });
+
+ it('leaves a run that settled in the meantime', async () => {
+ await seed({ runStatus: 'completed' });
+
+ await expect(model().takeOverRunningRun(topicId, 'op-old', 'op-new')).resolves.toBe(false);
+ const run = await readRun();
+ expect(run.operationId).toBe('op-old');
+ expect(run.status).toBe('completed');
+ });
+});
+
+describe('TaskTopicModel.isSupersededOperation', () => {
+ it('is true for an older operation once a newer one owns the row', async () => {
+ await seed({ operationId: 'op-new' });
+ await seedOperation('op-old', new Date('2026-11-01T10:38:03Z'));
+ await seedOperation('op-new', new Date('2026-11-01T10:38:48Z'));
+
+ await expect(model().isSupersededOperation(topicId, 'op-old')).resolves.toBe(true);
+ await expect(model().isSupersededOperation(topicId, 'op-new')).resolves.toBe(false);
+ });
+
+ it('is false for a newer operation the row does not name yet', async () => {
+ // The runner records a continued run only after its dispatch returns, so a
+ // short run can report while the row still names the previous one.
+ await seed({ operationId: 'op-old', runStatus: 'completed' });
+ await seedOperation('op-old', new Date('2026-11-01T10:38:03Z'));
+ await seedOperation('op-new', new Date('2026-11-01T10:38:48Z'));
+
+ await expect(model().isSupersededOperation(topicId, 'op-new')).resolves.toBe(false);
+ });
+
+ it('is false when either operation is unknown', async () => {
+ await seed({ operationId: 'op-new' });
+ await seedOperation('op-new', new Date('2026-11-01T10:38:48Z'));
+
+ await expect(model().isSupersededOperation(topicId, 'op-missing')).resolves.toBe(false);
+ });
+});
+
+describe('TaskTopicModel.updateStatus guarded by the reporting operation', () => {
+ it('refuses the write of an operation a newer one took the row over from', async () => {
+ await seed({ operationId: 'op-new' });
+ await seedOperation('op-old', new Date('2026-11-01T10:38:03Z'));
+ await seedOperation('op-new', new Date('2026-11-01T10:38:48Z'));
+
+ await expect(
+ model().updateStatus(taskId, topicId, 'completed', { reportedOperationId: 'op-old' }),
+ ).resolves.toBe(false);
+ expect((await readRun()).status).toBe('running');
+ });
+
+ it('writes for the operation the row names, and for a newer one it does not name yet', async () => {
+ await seed({ operationId: 'op-old' });
+ await seedOperation('op-old', new Date('2026-11-01T10:38:03Z'));
+ await seedOperation('op-new', new Date('2026-11-01T10:38:48Z'));
+
+ await expect(
+ model().updateStatus(taskId, topicId, 'failed', { reportedOperationId: 'op-old' }),
+ ).resolves.toBe(true);
+ expect((await readRun()).status).toBe('failed');
+
+ // The runner records a continued run only after its dispatch returns.
+ await expect(
+ model().updateStatus(taskId, topicId, 'completed', { reportedOperationId: 'op-new' }),
+ ).resolves.toBe(true);
+ expect((await readRun()).status).toBe('completed');
+ });
+});
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index ac31a4775b4..f304d14446e 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -31,7 +31,7 @@ import * as documents from './documents';
import * as queries from './queries';
import { resolveRefs } from './refs';
import * as rows from './rows';
-import type { OrphanedRunningTopic } from './scheduling';
+import type { InterruptedRunningTopic, OrphanedRunningTopic } from './scheduling';
import * as scheduling from './scheduling';
import * as transfer from './transfer';
import * as tree from './tree';
@@ -44,7 +44,7 @@ import {
withStaleReposCleared,
} from './utils';
-export type { OrphanedRunningTopic } from './scheduling';
+export type { InterruptedRunningTopic, OrphanedRunningTopic } from './scheduling';
export { isTaskIdentifierUniqueViolation, taskActivityActor } from './utils';
export class TaskModel {
@@ -484,6 +484,13 @@ export class TaskModel {
return scheduling.findOrphanedRunningTopics(db, options);
}
+ static async findInterruptedRunningTopics(
+ db: LobeChatDatabase,
+ options: { limit?: number; staleBefore: Date },
+ ): Promise<InterruptedRunningTopic[]> {
+ return scheduling.findInterruptedRunningTopics(db, options);
+ }
+
// ========== Dependencies ==========
async addDependency(taskId: string, dependsOnId: string, type: string = 'blocks'): Promise<void> {
diff --git a/packages/database/src/models/task/scheduling.ts b/packages/database/src/models/task/scheduling.ts
index f43a9c82786..7754e96239f 100644
--- a/packages/database/src/models/task/scheduling.ts
+++ b/packages/database/src/models/task/scheduling.ts
@@ -1,4 +1,5 @@
import type { AgentOperationStatus, TaskItem, TaskRunTrigger } from '@lobechat/types';
+import { IN_FLIGHT_OPERATION_STATUS_LIST } from '@lobechat/types';
import { and, eq, inArray, isNotNull, isNull, notInArray, sql } from 'drizzle-orm';
import type { AgentOperationError } from '../../schemas/agentOperations';
@@ -162,3 +163,68 @@ export const findOrphanedRunningTopics = async (
.limit(limit)
);
};
+
+/** One `running` Task run left behind by an interrupted operation β€” see the finder. */
+export interface InterruptedRunningTopic {
+ operationId: string;
+ taskId: string;
+ taskIdentifier: string;
+ topicId: string;
+ userId: string;
+ workspaceId: string | null;
+}
+
+/**
+ * Running Task runs whose operation was interrupted and that nothing took over.
+ *
+ * An interrupt is not an outcome: the run's hook does not settle the row, on
+ * purpose, because the run that interrupted it β€” a follow-up the user sent in
+ * the same conversation β€” normally takes the row over and settles it when it
+ * ends. When nothing took it over (the follow-up could not, or the run was
+ * stopped some other way and nobody settled the row), the Task reads as
+ * `running` forever. {@link findOrphanedRunningTopics} deliberately leaves
+ * `interrupted` out, because converging it as a failure would mislabel it.
+ *
+ * A row is only returned when *no* operation on its topic is still in flight:
+ * a conversation that is still going is a Task that is still continuing, even
+ * when the row has not been handed to the run that is doing the work.
+ */
+export const findInterruptedRunningTopics = async (
+ db: LobeChatDatabase,
+ options: { limit?: number; staleBefore: Date },
+): Promise<InterruptedRunningTopic[]> => {
+ const { limit = 200, staleBefore } = options;
+
+ return db
+ .select({
+ operationId: agentOperations.id,
+ taskId: tasks.id,
+ taskIdentifier: tasks.identifier,
+ topicId: sql<string>`${taskTopics.topicId}`,
+ userId: tasks.createdByUserId,
+ workspaceId: tasks.workspaceId,
+ })
+ .from(taskTopics)
+ .innerJoin(agentOperations, eq(taskTopics.operationId, agentOperations.id))
+ .innerJoin(tasks, eq(taskTopics.taskId, tasks.id))
+ .where(
+ and(
+ eq(taskTopics.status, 'running'),
+ eq(tasks.status, 'running'),
+ isNotNull(taskTopics.topicId),
+ isNull(agentOperations.parentOperationId),
+ eq(agentOperations.status, 'interrupted'),
+ sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt}) < ${staleBefore}`,
+ sql`not exists (
+ select 1 from ${agentOperations} as live
+ where live.topic_id = ${taskTopics.topicId}
+ and live.status in (${sql.join(
+ IN_FLIGHT_OPERATION_STATUS_LIST.map((status) => sql`${status}`),
+ sql`, `,
+ )})
+ )`,
+ ),
+ )
+ .orderBy(sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt})`)
+ .limit(limit);
+};
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index e9d5a22f59f..66a4c5fd500 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -5,7 +5,9 @@ import {
} from '@lobechat/const/goal';
import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';
import { and, count, desc, eq, gte, inArray, ne, sql } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+import { agentOperations } from '../schemas/agentOperations';
import type { TaskTopicItem } from '../schemas/task';
import { tasks, taskTopics } from '../schemas/task';
import { topics } from '../schemas/topic';
@@ -14,6 +16,23 @@ import { buildWorkspaceWhere } from '../utils/workspace';
import { topicsOwnership } from './task/context';
import { countOf } from './utils/rows';
+/**
+ * The run row is not owned by an operation newer than `operationId`: the
+ * condition {@link TaskTopicModel.isSupersededOperation} reads, written as a
+ * predicate on the row being updated.
+ */
+const notSupersededBy = (operationId: string) => sql`not exists (
+ select 1 from ${agentOperations} as row_operation, ${agentOperations} as reported_operation
+ where row_operation.id = ${taskTopics.operationId}
+ and reported_operation.id = ${operationId}
+ and row_operation.id <> reported_operation.id
+ and row_operation.created_at > reported_operation.created_at
+)`;
+
+/** The operation a run row names, and the one reporting on it. */
+const current = alias(agentOperations, 'current_operation');
+const reported = alias(agentOperations, 'reported_operation');
+
export const TERMINAL_TOPIC_STATUSES = new Set([
'canceled',
'completed',
@@ -95,15 +114,41 @@ export class TaskTopicModel {
.onConflictDoNothing();
}
- async updateStatus(taskId: string, topicId: string, status: string): Promise<void> {
- await this.db
+ /**
+ * Write a run's status.
+ *
+ * With `reportedOperationId`, the write is the completion of that operation
+ * and lands only while no newer operation owns the row β€” see
+ * {@link isSupersededOperation}. The guard is part of the UPDATE itself, so a
+ * follow-up taking the row over between a completion's ownership check and
+ * this write still wins. Returns whether a row was written.
+ */
+ async updateStatus(
+ taskId: string,
+ topicId: string,
+ status: string,
+ options: { reportedOperationId?: string } = {},
+ ): Promise<boolean> {
+ const { reportedOperationId } = options;
+ const rows = await this.db
.update(taskTopics)
.set({ status })
- .where(and(eq(taskTopics.taskId, taskId), eq(taskTopics.topicId, topicId), this.ownership()));
+ .where(
+ and(
+ eq(taskTopics.taskId, taskId),
+ eq(taskTopics.topicId, topicId),
+ this.ownership(),
+ reportedOperationId ? notSupersededBy(reportedOperationId) : undefined,
+ ),
+ )
+ .returning({ topicId: taskTopics.topicId });
+
+ if (reportedOperationId && rows.length === 0) return false;
if (TERMINAL_TOPIC_STATUSES.has(status)) {
await this.markTopicEnded(topicId, status);
}
+ return rows.length > 0;
}
/**
@@ -345,6 +390,70 @@ export class TaskTopicModel {
return result.length > 0;
}
+ /**
+ * Hand a still-`running` run over to the operation that replaced it.
+ *
+ * A user following up in a Task's conversation while its run is still live
+ * interrupts that run (the composer supersedes it). The interrupted run never
+ * settles the row β€” an interrupt is not an outcome β€” so unless the follow-up
+ * takes the row over, the Task stays `running` with nothing behind it.
+ *
+ * Compare-and-swap on the replaced operation: the row moves only while it is
+ * still `running` under `fromOperationId`, so a run that settled in between,
+ * or another send that took the row over first, is never overwritten. The
+ * trigger is restamped `'manual'` for the same reason as
+ * {@link reopenSettledRun}.
+ */
+ async takeOverRunningRun(
+ topicId: string,
+ fromOperationId: string,
+ toOperationId: string,
+ ): Promise<boolean> {
+ const result = await this.db
+ .update(taskTopics)
+ .set({ operationId: toOperationId, trigger: 'manual' })
+ .where(
+ and(
+ eq(taskTopics.topicId, topicId),
+ eq(taskTopics.operationId, fromOperationId),
+ eq(taskTopics.status, 'running'),
+ this.ownership(),
+ ),
+ )
+ .returning({ topicId: taskTopics.topicId });
+
+ return result.length > 0;
+ }
+
+ /**
+ * Whether `operationId` is an older run of this topic that a newer operation
+ * has already replaced on the run row.
+ *
+ * Ordered by the operations' creation, not by mere inequality: the runner
+ * records a run on the row only after its dispatch returns, so a short run can
+ * report before the row names it. That report comes from the *newer* operation
+ * and must go through; only a report from an operation older than the one the
+ * row names is a superseded run's late delivery.
+ */
+ async isSupersededOperation(topicId: string, operationId: string): Promise<boolean> {
+ const [row] = await this.db
+ .select({ topicId: taskTopics.topicId })
+ .from(taskTopics)
+ .innerJoin(current, eq(current.id, taskTopics.operationId))
+ .innerJoin(reported, eq(reported.id, operationId))
+ .where(
+ and(
+ eq(taskTopics.topicId, topicId),
+ ne(taskTopics.operationId, operationId),
+ sql`${current.createdAt} > ${reported.createdAt}`,
+ this.ownership(),
+ ),
+ )
+ .limit(1);
+
+ return !!row;
+ }
+
/** Undo {@link markTopicEnded}'s end stamp for a run that is live again. */
async clearTopicEnded(topicId: string): Promise<void> {
await this.db
diff --git a/packages/types/src/agentOperation.ts b/packages/types/src/agentOperation.ts
index 2fdcbb6b0dc..2fcd5689824 100644
--- a/packages/types/src/agentOperation.ts
+++ b/packages/types/src/agentOperation.ts
@@ -9,13 +9,16 @@ export type AgentOperationStatus =
| 'waiting_for_client'
| 'waiting_for_human';
-const IN_FLIGHT_OPERATION_STATUSES = new Set<AgentOperationStatus>([
+/** Statuses of an operation that has not settled yet β€” see {@link isAgentOperationInFlight}. */
+export const IN_FLIGHT_OPERATION_STATUS_LIST: readonly AgentOperationStatus[] = [
'idle',
'running',
'waiting_for_async_tool',
'waiting_for_client',
'waiting_for_human',
-]);
+];
+
+const IN_FLIGHT_OPERATION_STATUSES = new Set<AgentOperationStatus>(IN_FLIGHT_OPERATION_STATUS_LIST);
/**
* Whether the operation has not settled yet and may still write to its topic or