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): stop a task's running execution before deleting it (#20054)

Arvin Xu1fa77923e88d
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index 4ae10ac8612..247f7b13a5f 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -858,10 +858,9 @@ export const taskRouter = router({
delete: taskProcedureWrite.input(idInput).mutation(async ({ input, ctx }) => {
try {
- const model = ctx.taskModel;
- const task = await resolveOrThrow(model, input.id);
+ const task = await resolveOrThrow(ctx.taskModel, input.id);
assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');
- await model.delete(task.id);
+ await ctx.taskService.deleteTask(task.id);
return { data: task, message: 'Task deleted', success: true };
} catch (error) {
if (error instanceof TRPCError) throw error;
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index ab12a2b3a28..79957be27f3 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -100,6 +100,8 @@ describe('TaskService', () => {
updateWithLog: vi.fn(),
create: vi.fn(),
delete: vi.fn(),
+ deleteIfStatus: vi.fn().mockResolvedValue(true),
+ lockForUpdate: vi.fn().mockResolvedValue(true),
findById: vi.fn(),
findByIds: vi.fn(),
findAllDescendants: vi.fn(),
@@ -1484,6 +1486,153 @@ describe('TaskService', () => {
);
});
+ describe('deleteTask', () => {
+ beforeEach(() => {
+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);
+ mockTaskModel.lockForUpdate.mockResolvedValue(true);
+ mockTaskModel.deleteIfStatus.mockResolvedValue(true);
+ });
+
+ it('interrupts a running execution before deleting the task row', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-live',
+ identifier: 'T-2',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-2');
+
+ expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-live' });
+ expect(interruptTaskMock.mock.invocationCallOrder[0]).toBeLessThan(
+ mockTaskModel.deleteIfStatus.mock.invocationCallOrder[0],
+ );
+ expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-live', 'running');
+ });
+
+ it('keeps the task when its execution cannot be stopped', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-live',
+ identifier: 'T-2',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
+ ]);
+ interruptTaskMock.mockResolvedValueOnce({ success: false });
+
+ await expect(new TaskService(db, userId).deleteTask('T-2')).rejects.toThrow(
+ 'Task interruption was not confirmed',
+ );
+ expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
+ });
+
+ it('refuses to delete a task whose run is still starting', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-starting',
+ identifier: 'T-4',
+ startedAt: new Date(),
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-4')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
+ });
+
+ it('deletes a running task whose start died long ago', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-stale',
+ identifier: 'T-5',
+ startedAt: new Date(Date.now() - 60 * 60 * 1000),
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
+
+ await new TaskService(db, userId).deleteTask('T-5');
+
+ expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-stale', 'running');
+ });
+
+ it('loses to a run that started after the checks instead of orphaning it', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-race',
+ identifier: 'T-6',
+ status: 'backlog',
+ });
+ mockTaskModel.deleteIfStatus.mockResolvedValueOnce(false);
+
+ await expect(new TaskService(db, userId).deleteTask('T-6')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-race', 'backlog');
+ });
+
+ it('loses to a run that recorded a new topic while the delete was interrupting', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-cont',
+ identifier: 'T-8',
+ status: 'running',
+ });
+ const liveA = {
+ operationId: 'op-a',
+ status: 'running',
+ taskId: 'task-cont',
+ topicId: 'topic-a',
+ };
+ const continuedB = {
+ operationId: 'op-b',
+ status: 'running',
+ taskId: 'task-cont',
+ topicId: 'topic-b',
+ };
+ mockTaskTopicModel.findRunningByTaskIds
+ .mockResolvedValueOnce([liveA])
+ .mockResolvedValueOnce([liveA, continuedB]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-8')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-a' });
+ expect(mockTaskModel.lockForUpdate).toHaveBeenCalledWith('task-cont');
+ expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
+ });
+
+ it('treats a task already gone as deleted', async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-gone',
+ identifier: 'T-7',
+ status: 'backlog',
+ });
+ mockTaskModel.lockForUpdate.mockResolvedValueOnce(false);
+
+ await expect(new TaskService(db, userId).deleteTask('T-7')).resolves.toMatchObject({
+ id: 'task-gone',
+ });
+ expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
+ });
+
+ it("does not interrupt the caller's own run", async () => {
+ mockTaskModel.resolve.mockResolvedValue({
+ id: 'task-self',
+ identifier: 'T-3',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-self', status: 'running', taskId: 'task-self', topicId: 'topic-self' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-3', { keepOperationId: 'op-self' });
+
+ expect(interruptTaskMock).not.toHaveBeenCalled();
+ expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-self', 'running');
+ });
+ });
+
describe('updateStatus / scheduleStartedAt', () => {
const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({
automationMode: 'schedule',
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 48e8e2f4c18..8d3cce5f53f 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -55,6 +55,8 @@ const TASK_DETAIL_DIRECT_TOPIC_LIMIT = 100;
*/
const TASK_DETAIL_ACTIVITY_LIMIT = 200;
const TASK_DETAIL_DESCENDANT_TOPIC_LIMIT = 300;
+/** How long after a run starts a task may have no recorded operation yet. */
+const TASK_RUN_STARTING_GRACE_MS = 2 * 60 * 1000;
type DirectTaskTopicActivityRow = Awaited<ReturnType<TaskTopicModel['findWithHandoff']>>[number];
type DescendantTaskTopicActivityRow = Awaited<
@@ -346,6 +348,81 @@ export class TaskService {
await this.topicModel.delete(topicId);
}
+ /**
+ * Delete a task: interrupt its still-running topics first, then remove the
+ * row. Deleting without the interrupt leaves the run executing against a
+ * task that no longer exists β€” its task tools answer "Task not found" and
+ * every document it produces fails the `task_documents` foreign key.
+ *
+ * `keepOperationId` spares the caller's own run (an agent deleting the task
+ * it is executing), which would otherwise interrupt itself mid-tool-call.
+ */
+ async deleteTask(
+ idOrIdentifier: string,
+ options: { keepOperationId?: string } = {},
+ ): Promise<TaskItem> {
+ const task = await this.resolveOrThrow(idOrIdentifier);
+
+ const runningTopics = await this.taskTopicModel.findRunningByTaskIds([task.id]);
+
+ // The runner marks the task `running` before it dispatches the agent and
+ // records the topic / operation only after dispatch returns. A delete in
+ // that window finds nothing to interrupt and would orphan the run it is
+ // about to start. Past the grace window a missing operation means the
+ // start died, and deletion goes ahead.
+ const startedAt = task.startedAt ? new Date(task.startedAt).getTime() : 0;
+ const isStarting =
+ task.status === 'running' &&
+ Date.now() - startedAt < TASK_RUN_STARTING_GRACE_MS &&
+ (runningTopics.length === 0 || runningTopics.some((topic) => !topic.operationId));
+ if (isStarting) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'This task is still starting its run. Try deleting it again in a moment.',
+ });
+ }
+
+ const toInterrupt = runningTopics.filter(
+ (topic) => topic.operationId && topic.operationId !== options.keepOperationId,
+ );
+ if (toInterrupt.length > 0) {
+ const aiAgentService = new AiAgentService(this.db, this.userId, {
+ workspaceId: this.workspaceId,
+ });
+ for (const topic of toInterrupt) {
+ await this.interruptTaskOperation(aiAgentService, topic.operationId!);
+ }
+ }
+
+ // Decide and delete under the task's row lock β€” the same lock a run takes
+ // to record its topic. A run that recorded one after the checks above is
+ // seen here and wins; a run that records later finds the task gone and
+ // stops its own execution. Compare-and-delete on the status as well, so a
+ // run that moved the task on in the meantime is never deleted under.
+ const handled = new Set(runningTopics.map((topic) => topic.operationId));
+ const outcome = await this.db.transaction(async (tx) => {
+ const taskModel = new TaskModel(tx, this.userId, this.workspaceId);
+ if (!(await taskModel.lockForUpdate(task.id))) return 'gone' as const;
+ const nowRunning = await new TaskTopicModel(
+ tx,
+ this.userId,
+ this.workspaceId,
+ ).findRunningByTaskIds([task.id]);
+ if (nowRunning.some((topic) => !handled.has(topic.operationId))) return 'conflict' as const;
+ return (await taskModel.deleteIfStatus(task.id, task.status))
+ ? ('deleted' as const)
+ : ('conflict' as const);
+ });
+ if (outcome === 'conflict') {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message:
+ 'The task changed while it was being deleted (it may have just started). Try again.',
+ });
+ }
+ return task;
+ }
+
/**
* Run the configured review on `content`, persist the result onto the
* target topic, and return the review outcome.
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 99a349427ba..0f0180f0cec 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -156,10 +156,20 @@ export class TaskRunnerService {
);
if (task.status !== 'running') {
- await this.taskModel.updateStatus(task.id, 'running', {
- error: null,
- startedAt: new Date(),
- });
+ // Conditional on the status read above: a task deleted (or started by
+ // another caller) in the meantime must not get an agent dispatched.
+ const started = await this.taskModel.updateStatusIfCurrent(
+ task.id,
+ task.status,
+ 'running',
+ { error: null, startedAt: new Date() },
+ );
+ if (!started) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The task changed or was deleted before its run could start.',
+ });
+ }
weSetRunning = true;
} else if (task.error) {
await this.taskModel.update(task.id, { error: null });
@@ -282,17 +292,43 @@ export class TaskRunnerService {
}
if (result.topicId) {
- if (continueTopicId) {
- await this.taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
- await this.taskTopicModel.updateOperationId(task.id, continueTopicId, result.operationId);
- await this.taskModel.updateCurrentTopic(task.id, continueTopicId);
- } else {
- await this.taskModel.incrementTopicCount(task.id);
- await this.taskModel.updateCurrentTopic(task.id, result.topicId);
- await this.taskTopicModel.add(task.id, result.topicId, {
- operationId: result.operationId,
- seq: (task.totalTopics || 0) + 1,
- trigger,
+ const topicId = result.topicId;
+ // Record the run under the task's row lock (see TaskService.deleteTask).
+ // If the task was deleted while this run was being dispatched, nobody
+ // is left to stop it β€” stop it here instead of orphaning it.
+ const recorded = await this.db.transaction(async (tx) => {
+ const taskModel = new TaskModel(tx, this.userId, this.workspaceId);
+ const taskTopicModel = new TaskTopicModel(tx, this.userId, this.workspaceId);
+ if (!(await taskModel.lockForUpdate(task.id))) return false;
+ if (continueTopicId) {
+ await taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
+ await taskTopicModel.updateOperationId(task.id, continueTopicId, result.operationId);
+ await taskModel.updateCurrentTopic(task.id, continueTopicId);
+ } else {
+ await taskModel.incrementTopicCount(task.id);
+ await taskModel.updateCurrentTopic(task.id, topicId);
+ await taskTopicModel.add(task.id, topicId, {
+ operationId: result.operationId,
+ seq: (task.totalTopics || 0) + 1,
+ trigger,
+ });
+ }
+ return true;
+ });
+ if (!recorded) {
+ const stop = await aiAgentService
+ .interruptTask({ operationId: result.operationId })
+ .catch((error) => {
+ log('runTask: failed to stop orphaned run: %O', error);
+ return undefined;
+ });
+ // Same confirmation gate as TaskService.interruptTaskOperation.
+ const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;
+ throw new TRPCError({
+ code: stopped ? 'NOT_FOUND' : 'INTERNAL_SERVER_ERROR',
+ message: stopped
+ ? 'The task was deleted while its run was starting; the run was stopped.'
+ : `The task was deleted while its run was starting, and stopping that run (operation ${result.operationId}) could not be confirmed.`,
});
}
}
diff --git a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
new file mode 100644
index 00000000000..98903e5a26e
--- /dev/null
+++ b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts
@@ -0,0 +1,136 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+
+import { TaskRunnerService } from './index';
+
+const mocks = vi.hoisted(() => ({
+ execAgent: vi.fn(),
+ interruptTask: vi.fn(),
+}));
+
+vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));
+vi.mock('@/database/models/taskTopic', () => ({ TaskTopicModel: vi.fn() }));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return { getAgentModelConfig: vi.fn() };
+ }),
+}));
+vi.mock('@/database/models/brief', () => ({ BriefModel: vi.fn() }));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return { execAgent: mocks.execAgent, interruptTask: mocks.interruptTask };
+ }),
+}));
+vi.mock('@/server/services/taskLifecycle', () => ({ TaskLifecycleService: vi.fn() }));
+vi.mock('./buildTaskPrompt', () => ({
+ buildTaskPrompt: vi.fn().mockResolvedValue({
+ acceptanceEnabled: false,
+ fileIds: [],
+ prompt: 'do it',
+ }),
+}));
+
+/**
+ * A delete can land while `execAgent` is dispatching, before the run's topic
+ * and operation are recorded β€” so the delete finds nothing to interrupt. The
+ * runner records under the task's row lock; when the task is already gone it
+ * must stop the run it just dispatched instead of leaving it orphaned.
+ */
+describe('TaskRunnerService.runTask vs. a concurrent delete', () => {
+ const task = {
+ assigneeAgentId: 'agt_worker',
+ config: { model: 'm', provider: 'p' },
+ id: 'task-1',
+ identifier: 'T-1',
+ status: 'backlog',
+ totalTopics: 0,
+ };
+ let taskModel: Record<string, ReturnType<typeof vi.fn>>;
+ let taskTopicModel: Record<string, ReturnType<typeof vi.fn>>;
+ const db = {
+ transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn(db),
+ } as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ taskModel = {
+ getCheckpointConfig: vi.fn().mockReturnValue({}),
+ getReviewConfig: vi.fn().mockReturnValue(undefined),
+ incrementTopicCount: vi.fn(),
+ lockForUpdate: vi.fn().mockResolvedValue(true),
+ resolve: vi.fn().mockResolvedValue({ ...task }),
+ update: vi.fn(),
+ updateCurrentTopic: vi.fn(),
+ updateHeartbeat: vi.fn(),
+ updateStatus: vi.fn(),
+ updateStatusIfCurrent: vi.fn().mockResolvedValue({ ...task, status: 'running' }),
+ };
+ taskTopicModel = {
+ add: vi.fn(),
+ findByTaskId: vi.fn().mockResolvedValue([]),
+ updateStatus: vi.fn(),
+ };
+ vi.mocked(TaskModel).mockImplementation(function () {
+ return taskModel as any;
+ });
+ vi.mocked(TaskTopicModel).mockImplementation(function () {
+ return taskTopicModel as any;
+ });
+ mocks.execAgent.mockResolvedValue({
+ operationId: 'op-new',
+ success: true,
+ topicId: 'tpc-new',
+ });
+ mocks.interruptTask.mockResolvedValue({ success: true });
+ });
+
+ it('records the run under the task lock when the task still exists', async () => {
+ await new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' });
+
+ expect(taskModel.lockForUpdate).toHaveBeenCalledWith('task-1');
+ expect(taskTopicModel.add).toHaveBeenCalledWith(
+ 'task-1',
+ 'tpc-new',
+ expect.objectContaining({ operationId: 'op-new' }),
+ );
+ expect(mocks.interruptTask).not.toHaveBeenCalled();
+ });
+
+ it('stops the run it just dispatched when the task was deleted meanwhile', async () => {
+ taskModel.lockForUpdate.mockResolvedValue(false);
+
+ await expect(new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' })).rejects.toThrow(
+ 'The task was deleted while its run was starting',
+ );
+
+ expect(mocks.interruptTask).toHaveBeenCalledWith({ operationId: 'op-new' });
+ expect(taskTopicModel.add).not.toHaveBeenCalled();
+ });
+
+ it.each([{ success: false }, { deviceCancellationConfirmed: false, success: true }])(
+ 'does not claim the orphaned run stopped when the stop is unconfirmed (%j)',
+ async (stop) => {
+ taskModel.lockForUpdate.mockResolvedValue(false);
+ mocks.interruptTask.mockResolvedValue(stop);
+
+ await expect(
+ new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' }),
+ ).rejects.toMatchObject({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: expect.stringContaining('could not be confirmed'),
+ });
+ },
+ );
+
+ it('does not dispatch at all when the task changed before its run could start', async () => {
+ taskModel.updateStatusIfCurrent.mockResolvedValue(null);
+
+ await expect(new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' })).rejects.toThrow(
+ 'The task changed or was deleted before its run could start',
+ );
+
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index c8b30424e32..c489db29546 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -101,6 +101,51 @@ describe('taskRuntime.factory', () => {
});
describe('createTaskRuntime', () => {
+ describe('deleteTask', () => {
+ it('deletes through TaskService so a running execution is stopped first', async () => {
+ const taskModel = {
+ delete: vi.fn(),
+ resolve: vi.fn().mockResolvedValue({ id: 'task-2', identifier: 'T-2', name: 'Report' }),
+ };
+ const taskService = { deleteTask: vi.fn().mockResolvedValue({ id: 'task-2' }) };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ operationId: 'op-caller',
+ taskCaller: {} as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ });
+
+ const result = await runtime.deleteTask({ identifier: 'T-2' });
+
+ expect(result.success).toBe(true);
+ expect(taskService.deleteTask).toHaveBeenCalledWith('task-2', {
+ keepOperationId: 'op-caller',
+ });
+ expect(taskModel.delete).not.toHaveBeenCalled();
+ });
+
+ it('reports a failed stop instead of throwing', async () => {
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ taskCaller: {} as any,
+ taskModel: {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-2', identifier: 'T-2' }),
+ } as any,
+ taskService: {
+ deleteTask: vi.fn().mockRejectedValue(new Error('Task interruption was not confirmed.')),
+ } as any,
+ });
+
+ const result = await runtime.deleteTask({ identifier: 'T-2' });
+
+ expect(result).toMatchObject({
+ content: 'Failed to delete task T-2: Task interruption was not confirmed.',
+ success: false,
+ });
+ });
+ });
+
describe('task comments', () => {
it('adds a comment to the current task with agent attribution', async () => {
const taskCaller = {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index fe41de8f0e4..7dbe1fb8dae 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -367,7 +367,12 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
const task = await taskModel().resolve(args.identifier);
if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
- await taskModel().delete(task.id);
+ try {
+ await taskService().deleteTask(task.id, { keepOperationId: operationId });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to delete task';
+ return { content: `Failed to delete task ${task.identifier}: ${message}`, success: false };
+ }
return {
content: formatTaskDeleted(task.identifier, task.name),
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index c071ee73c9c..94e3eb0b049 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -1024,6 +1024,27 @@ describe('TaskModel', () => {
});
});
+ describe('deleteIfStatus (delete vs. run start)', () => {
+ it('keeps a task that a run started after the delete looked at it', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ // The runner wins the race: backlog β†’ running before the delete lands.
+ await model.updateStatusIfCurrent(task.id, 'backlog', 'running');
+
+ expect(await model.deleteIfStatus(task.id, 'backlog')).toBe(false);
+ expect((await model.findById(task.id))?.status).toBe('running');
+ });
+
+ it('stops the run start when the delete lands first', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+
+ expect(await model.deleteIfStatus(task.id, 'backlog')).toBe(true);
+ expect(await model.updateStatusIfCurrent(task.id, 'backlog', 'running')).toBeNull();
+ });
+ });
+
describe('heartbeat', () => {
it('should update heartbeat timestamp', async () => {
const model = new TaskModel(serverDB, userId);
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index cb3137bc86e..40c8decf603 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -661,6 +661,35 @@ export class TaskModel {
return result.rows.length > 0;
}
+ /**
+ * Row-lock the task for the rest of the enclosing transaction. Serializes a
+ * run recording its topic against a delete deciding there is nothing left to
+ * interrupt. Returns false when the task no longer exists.
+ */
+ async lockForUpdate(id: string): Promise<boolean> {
+ const rows = await this.db
+ .select({ id: tasks.id })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), this.ownership()))
+ .for('update');
+
+ return rows.length > 0;
+ }
+
+ /**
+ * Delete a task only while it still has `status`. Lets a delete that
+ * inspected the task's runs lose cleanly to a run that started meanwhile,
+ * instead of removing the row out from under it.
+ */
+ async deleteIfStatus(id: string, status: string): Promise<boolean> {
+ const deleted = await this.db
+ .delete(tasks)
+ .where(and(eq(tasks.id, id), eq(tasks.status, status), this.ownership()))
+ .returning({ id: tasks.id });
+
+ return deleted.length > 0;
+ }
+
/** See {@link delete}: bulk task deletion likewise leaves Work artifacts intact. */
async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {
// `restrictToCreator` narrows the workspace-wide sweep to rows the caller