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(acceptance): don't interrupt the run delivering its own task (#21272)

Rdmclin21141237081eb
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index ffb58289b00..67fc780cf10 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -258,7 +258,7 @@ export class TaskLifecycleService {
const completionRequestedByCurrentOperation =
(
currentTask.context as {
- completion?: { requestedByOperationId?: string };
+ completion?: { requestedByOperationId?: string | null };
} | null
)?.completion?.requestedByOperationId === params.operationId;
@@ -280,7 +280,14 @@ export class TaskLifecycleService {
await this.recordAutomationRecovery(currentTask);
await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });
} else if (!verifyBound && completionRequestedByCurrentOperation) {
- await this.completeTask(currentTask);
+ // The request is consumed with the status write: a rejected acceptance
+ // delivery can withdraw it while the handoff / brief above runs, and
+ // then the run ends as an undelivered one, paused for review.
+ const completed = await this.completeTask(currentTask, params.operationId);
+ if (!completed)
+ await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'paused', {
+ error: null,
+ });
} else if (!verifyBound && params.runTrigger === 'goal' && !currentTask.parentTaskId) {
await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'completed', {
completedAt: new Date(),
@@ -496,19 +503,21 @@ export class TaskLifecycleService {
* lifecycle service). The dynamic import keeps that module cycle out of
* initialization while preserving the runner's single cascade implementation.
*/
- private async completeTask(task: TaskItem): Promise<void> {
- const completedTask = await this.taskModel.updateStatusIfCurrent(
- task.id,
- 'running',
- 'completed',
- {
- completedAt: new Date(),
- error: null,
- },
- );
+ /**
+ * @param requestedByOperationId completes only while this run's deferred
+ * completion request still holds, consuming it in the same write.
+ * @returns whether this call completed the task.
+ */
+ private async completeTask(task: TaskItem, requestedByOperationId?: string): Promise<boolean> {
+ const completedTask = requestedByOperationId
+ ? await this.taskModel.completeIfCompletionRequested(task.id, requestedByOperationId)
+ : await this.taskModel.updateStatusIfCurrent(task.id, 'running', 'completed', {
+ completedAt: new Date(),
+ error: null,
+ });
if (!completedTask) {
- log('task=%s no longer running β€” skipping completion cascade', task.identifier);
- return;
+ log('task=%s not completed β€” no longer running or request withdrawn', task.identifier);
+ return false;
}
if (completedTask.parentTaskId) {
@@ -522,6 +531,7 @@ export class TaskLifecycleService {
await new TaskRunnerService(this.db, this.userId, this.workspaceId).cascadeOnCompletion(
task.id,
);
+ return true;
}
/**
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index 022e649b6ce..5134e443615 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -75,6 +75,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
let service: TaskLifecycleService;
let updateStatus: ReturnType<typeof vi.fn>;
let updateStatusIfCurrent: ReturnType<typeof vi.fn>;
+ let completeIfCompletionRequested: ReturnType<typeof vi.fn>;
let updateContext: ReturnType<typeof vi.fn>;
let findById: ReturnType<typeof vi.fn>;
let updateHeartbeat: ReturnType<typeof vi.fn>;
@@ -93,6 +94,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
updateStatus = vi.fn().mockResolvedValue(null);
updateStatusIfCurrent = vi.fn();
+ completeIfCompletionRequested = vi.fn();
updateContext = vi.fn().mockResolvedValue(null);
findById = vi.fn();
updateHeartbeat = vi.fn().mockResolvedValue(undefined);
@@ -104,6 +106,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const taskModel = (service as any).taskModel;
taskModel.updateStatus = updateStatus;
taskModel.updateStatusIfCurrent = updateStatusIfCurrent;
+ taskModel.completeIfCompletionRequested = completeIfCompletionRequested;
taskModel.updateContext = updateContext;
taskModel.findById = findById;
taskModel.updateHeartbeat = updateHeartbeat;
@@ -276,7 +279,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
automationMode: null,
context: { completion: { requestedByOperationId: 'op-1' } },
});
- updateStatusIfCurrent.mockResolvedValue({ ...task, status: 'completed' });
+ completeIfCompletionRequested.mockResolvedValue({ ...task, status: 'completed' });
findById.mockResolvedValue(task);
await service.onTopicComplete({
@@ -287,14 +290,35 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
- completedAt: expect.any(Date),
- error: null,
- });
+ // The request is consumed by the same write that completes the task.
+ expect(completeIfCompletionRequested).toHaveBeenCalledWith('task-1', 'op-1');
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');
});
+ it('pauses for review when the request was withdrawn while the topic was settling', async () => {
+ // A rejected acceptance delivery withdrew the request after the task was first read.
+ const task = baseTask({
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-1' } },
+ });
+ findById.mockResolvedValue(task);
+ completeIfCompletionRequested.mockResolvedValue(null);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(cascadeOnCompletion).not.toHaveBeenCalled();
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'paused', {
+ error: null,
+ });
+ });
+
it.each(['schedule', 'heartbeat'] as const)(
'%s task whose own tick met the end condition β†’ completed instead of re-armed',
async (automationMode) => {
diff --git a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
index a4da32ec596..f1f9e0a24b5 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({
setDecision: vi.fn(),
taskFindById: vi.fn(),
taskResolve: vi.fn(),
+ taskWithdrawCompletionRequest: vi.fn(),
taskServiceUpdateStatus: vi.fn(),
taskUpdateStatusIfCurrent: vi.fn(),
updatePolicyStatus: vi.fn(),
@@ -51,6 +52,7 @@ vi.mock('@/database/models/task', () => ({
return {
findById: mocks.taskFindById,
resolve: mocks.taskResolve,
+ withdrawCompletionRequest: mocks.taskWithdrawCompletionRequest,
updateStatusIfCurrent: mocks.taskUpdateStatusIfCurrent,
};
}),
@@ -88,6 +90,8 @@ describe('AcceptanceService task lifecycle', () => {
mocks.taskResolve.mockResolvedValue({ automationMode: null, id: 'task_1', status: 'running' });
// The row read back after the completion write.
mocks.taskFindById.mockResolvedValue({ id: 'task_1', status: 'completed' });
+ mocks.taskServiceUpdateStatus.mockResolvedValue({});
+ mocks.taskWithdrawCompletionRequest.mockResolvedValue(true);
});
describe('delivered β†’ task completed', () => {
@@ -115,6 +119,28 @@ describe('AcceptanceService task lifecycle', () => {
});
});
+ it('hands the publishing run to the completion so the task does not interrupt it', async () => {
+ // An agent ingesting acceptance for the task it is running: interrupting
+ // that run mid-command surfaced as a refused tool call and stopped it.
+ mocks.listByAcceptance.mockResolvedValue([
+ {
+ id: 'run-1',
+ metadata: { origin: { operationId: 'op-self' } },
+ roundIndex: 1,
+ status: null,
+ },
+ ]);
+ mocks.taskServiceUpdateStatus.mockResolvedValue({ completionDeferred: true });
+ mocks.taskFindById.mockResolvedValue({ id: 'task_1', status: 'running' });
+
+ await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');
+ expect(mocks.taskServiceUpdateStatus).toHaveBeenCalledWith({
+ id: 'task_1',
+ operationId: 'op-self',
+ status: 'completed',
+ });
+ });
+
it('leaves a server-verified round to driveTaskFromVerify', async () => {
// A failed round may still be auto-repaired; settle drives the task once.
mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'failed' }]);
@@ -235,6 +261,30 @@ describe('AcceptanceService task lifecycle', () => {
);
});
+ it('withdraws a deferred completion when the reject lands while it is being deferred', async () => {
+ // The reject read the task before the marker existed, so it had nothing to withdraw.
+ const deferredTask = {
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-self' } },
+ id: 'task_1',
+ status: 'running',
+ };
+ mocks.taskResolve
+ .mockResolvedValueOnce({ automationMode: null, id: 'task_1', status: 'running' })
+ .mockResolvedValueOnce({ automationMode: null, id: 'task_1', status: 'running' })
+ .mockResolvedValue(deferredTask);
+ mocks.taskServiceUpdateStatus.mockImplementationOnce(async () => {
+ stored.status = 'rejected';
+ return { completionDeferred: true };
+ });
+ mocks.taskFindById.mockResolvedValueOnce(deferredTask);
+
+ await expect(service().completeTaskForDelivery('acc-1', 'task_1', 'op-self')).resolves.toBe(
+ 'rejected',
+ );
+ expect(mocks.taskWithdrawCompletionRequest).toHaveBeenCalledWith('task_1', 'op-self');
+ });
+
it('reports the completion as skipped when the task could not be completed', async () => {
// completeTaskSubject swallows the failure; the row still reads running.
mocks.taskServiceUpdateStatus.mockRejectedValueOnce(new Error('interrupt failed'));
@@ -249,6 +299,42 @@ describe('AcceptanceService task lifecycle', () => {
});
});
+ describe('accepted while the delivering run is still going', () => {
+ beforeEach(() => {
+ mocks.findById.mockResolvedValue(taskAcceptance('delivered'));
+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1 }]);
+ mocks.taskResolve.mockResolvedValue({
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-self' } },
+ id: 'task_1',
+ status: 'running',
+ });
+ });
+
+ it('keeps waiting for that run on accept instead of interrupting it', async () => {
+ await service().accept('acc-1');
+
+ expect(mocks.taskServiceUpdateStatus).toHaveBeenCalledWith({
+ id: 'task_1',
+ operationId: 'op-self',
+ status: 'completed',
+ });
+ });
+
+ it('keeps waiting for that run when a merged pull request accepts it', async () => {
+ await service().acceptFromScmMerge('acc-1', {
+ number: 1,
+ repoFullName: 'lobehub/lobehub',
+ } as any);
+
+ expect(mocks.taskServiceUpdateStatus).toHaveBeenCalledWith({
+ id: 'task_1',
+ operationId: 'op-self',
+ status: 'completed',
+ });
+ });
+ });
+
describe('rejected β†’ task reopened', () => {
beforeEach(() => {
mocks.findById.mockResolvedValue(taskAcceptance('delivered'));
@@ -283,6 +369,40 @@ describe('AcceptanceService task lifecycle', () => {
await service().reject('acc-1', 'Fix the header');
expect(mocks.taskUpdateStatusIfCurrent).not.toHaveBeenCalled();
+ expect(mocks.taskWithdrawCompletionRequest).not.toHaveBeenCalled();
+ });
+
+ it('withdraws a completion still waiting for the delivering run to end', async () => {
+ // Otherwise onTopicComplete would complete a task whose delivery was rejected.
+ mocks.taskResolve.mockResolvedValue({
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-self' } },
+ id: 'task_1',
+ status: 'running',
+ });
+
+ await service().reject('acc-1', 'Fix the header');
+ expect(mocks.taskWithdrawCompletionRequest).toHaveBeenCalledWith('task_1', 'op-self');
+ expect(mocks.taskUpdateStatusIfCurrent).not.toHaveBeenCalled();
+ });
+
+ it('reopens the task when the delivering run completed it before the withdrawal', async () => {
+ mocks.taskResolve.mockResolvedValue({
+ automationMode: null,
+ context: { completion: { requestedByOperationId: 'op-self' } },
+ id: 'task_1',
+ status: 'running',
+ });
+ mocks.taskWithdrawCompletionRequest.mockResolvedValue(false);
+ mocks.taskFindById.mockResolvedValue({ id: 'task_1', status: 'completed' });
+
+ await service().reject('acc-1', 'Fix the header');
+ expect(mocks.taskUpdateStatusIfCurrent).toHaveBeenCalledWith(
+ 'task_1',
+ 'completed',
+ 'paused',
+ { completedAt: null },
+ );
});
it('leaves a Goal graph task to its coordinator', async () => {
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
index e2e570a77d4..d313ddd68f0 100644
--- a/apps/server/src/services/verify/acceptanceService/index.ts
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -340,12 +340,20 @@ export class AcceptanceService {
// transition: a completion that failed once is retried by the next round,
// report or flow event instead of leaving the task open for good. An
// already-completed task is a no-op.
+ //
+ // The round records the Agent Run that published it. When that run is the
+ // task's own (an agent ingesting acceptance for the task it executes), the
+ // completion waits for the run to end rather than interrupting it.
if (
status === 'delivered' &&
(!current.status || current.status === 'delivered') &&
acceptance.subjectType === 'task'
)
- await this.completeTaskForDelivery(acceptanceId, acceptance.subjectId);
+ await this.completeTaskForDelivery(
+ acceptanceId,
+ acceptance.subjectId,
+ current.metadata?.origin?.operationId,
+ );
return status;
};
diff --git a/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
index 41b0f59683a..79d42827386 100644
--- a/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
+++ b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
@@ -13,28 +13,44 @@ const log = debug('lobe-server:verify-acceptance');
* accept (e.g. the round failed but the user accepted anyway) and when an
* ingested round delivers. Best-effort: a task error must not undo the
* recorded acceptance.
+ *
+ * `callerOperationId` is the Agent Run that published the delivery. When that
+ * run is the task's own running topic, completion is deferred to the end of
+ * the run instead of interrupting it mid-tool-call (the agent would read the
+ * interrupt as a refused command and stop). A later completion of the same
+ * delivery (accept, merged PR) keeps waiting for the run already pending.
*/
export const completeTaskSubject = async (
deps: AcceptanceServiceDeps,
subjectId: string,
+ callerOperationId?: string,
): Promise<void> => {
try {
const taskModel = new TaskModel(deps.db, deps.userId, deps.workspaceId);
const task = await taskModel.resolve(subjectId);
if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) return;
+ const operationId = callerOperationId ?? pendingCompletionOperation(task);
// TaskService cascades checkpoint / sibling rollup / downstream unlock β€”
// the same completion path settle.ts drives on a passed verify.
- await new TaskService(deps.db, deps.userId, deps.workspaceId).updateStatus({
+ const result = await new TaskService(deps.db, deps.userId, deps.workspaceId).updateStatus({
id: task.id,
+ ...(operationId ? { operationId } : {}),
status: 'completed',
});
- log('acceptance β†’ task %s completed', task.id);
+ if (result.completionDeferred)
+ log('acceptance β†’ task %s completes when run %s ends', task.id, operationId);
+ else log('acceptance β†’ task %s completed', task.id);
} catch (error) {
log('completeTaskSubject failed (non-fatal): %O', error);
}
};
+/** The run a deferred completion waits for β€” see {@link completeTaskSubject}. */
+const pendingCompletionOperation = (task: { context?: unknown }) =>
+ (task.context as { completion?: { requestedByOperationId?: string | null } } | null)?.completion
+ ?.requestedByOperationId ?? undefined;
+
/**
* The task whose status follows its acceptance's lifecycle: delivered β†’
* completed, rejected β†’ reopened. Goal graph tasks are driven by their
@@ -60,12 +76,14 @@ export const resolveLifecycleTask = async (deps: AcceptanceServiceDeps, subjectI
*
* @returns `completed` when the task now reads completed, `rejected` when a
* reject won, `skipped` when the task does not follow the acceptance or could
- * not be completed.
+ * not be completed β€” including a completion deferred to the end of
+ * `callerOperationId`'s run (see {@link completeTaskSubject}).
*/
export const completeTaskForDelivery = async (
deps: AcceptanceServiceDeps,
acceptanceId: string,
subjectId: string,
+ callerOperationId?: string,
): Promise<'completed' | 'rejected' | 'skipped'> => {
try {
const task = await resolveLifecycleTask(deps, subjectId);
@@ -75,19 +93,25 @@ export const completeTaskForDelivery = async (
if (before?.status === 'rejected') return 'rejected';
if (before?.status !== 'delivered') return 'skipped';
- await completeTaskSubject(deps, task.id);
+ await completeTaskSubject(deps, task.id, callerOperationId);
// `completeTaskSubject` is best-effort and swallows its own failures (e.g. a
// running operation that could not be interrupted). Only a task that really
// reads completed counts β€” anything else lets the caller fall back.
const written = await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(task.id);
- if (written?.status !== 'completed') return 'skipped';
+ // A completion deferred to the caller's run is re-checked like a written
+ // one: a reject that read the task before the deferral had nothing to withdraw.
+ const deferred =
+ written?.status === 'running' &&
+ !!callerOperationId &&
+ pendingCompletionOperation(written) === callerOperationId;
+ if (written?.status !== 'completed' && !deferred) return 'skipped';
const after = await deps.acceptanceModel.findPolicyById(acceptanceId);
if (after?.status === 'rejected') {
await reopenRejectedTaskSubject(deps, task.id);
return 'rejected';
}
- return 'completed';
+ return deferred ? 'skipped' : 'completed';
} catch (error) {
log('completeTaskForDelivery failed (non-fatal): %O', error);
return 'skipped';
@@ -98,21 +122,37 @@ export const completeTaskForDelivery = async (
* Rejecting a delivery reopens the task it completed, so the task is not left
* reading "done" while its repair is pending. Only a completed task moves β€”
* one the user already paused, canceled or restarted keeps its own state.
+ *
+ * A delivery from the task's own run is completed only once that run ends
+ * (see {@link completeTaskSubject}); a reject landing before then withdraws
+ * the pending completion, so the run ends the way an undelivered one would.
*/
export const reopenRejectedTaskSubject = async (
deps: AcceptanceServiceDeps,
subjectId: string,
): Promise<void> => {
try {
- const task = await resolveLifecycleTask(deps, subjectId);
+ let task = await resolveLifecycleTask(deps, subjectId);
+ const taskModel = new TaskModel(deps.db, deps.userId, deps.workspaceId);
+
+ if (task?.status === 'running') {
+ const pending = pendingCompletionOperation(task);
+ if (!pending) return;
+
+ if (await taskModel.withdrawCompletionRequest(task.id, pending)) {
+ log(
+ 'acceptance rejected β†’ task %s pending completion by run %s withdrawn',
+ task.id,
+ pending,
+ );
+ return;
+ }
+ // The run consumed the request first and completed the task: reopen it.
+ task = await taskModel.findById(task.id);
+ }
if (task?.status !== 'completed') return;
- await new TaskModel(deps.db, deps.userId, deps.workspaceId).updateStatusIfCurrent(
- task.id,
- 'completed',
- 'paused',
- { completedAt: null },
- );
+ await taskModel.updateStatusIfCurrent(task.id, 'completed', 'paused', { completedAt: null });
log('acceptance rejected β†’ task %s reopened as paused', task.id);
} catch (error) {
log('reopenRejectedTaskSubject failed (non-fatal): %O', error);
diff --git a/packages/database/src/models/__tests__/task.completionRequest.test.ts b/packages/database/src/models/__tests__/task.completionRequest.test.ts
new file mode 100644
index 00000000000..b0ec979ff14
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.completionRequest.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-completion-request-user';
+const otherUserId = 'task-completion-request-user-2';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+/** A running task whose completion waits for `op-self` to end. */
+const createPendingTask = async (model: TaskModel) => {
+ const task = await model.create({ instruction: 'Deliver' });
+ await model.updateStatus(task.id, 'running');
+ await model.updateContext(task.id, {
+ completion: { requestedByOperationId: 'op-self' },
+ scheduler: { tickMessageId: 'msg-1' },
+ });
+ return task;
+};
+
+const requestOf = (task: { context?: unknown } | null) =>
+ (task?.context as { completion?: { requestedByOperationId?: string | null } } | null)?.completion
+ ?.requestedByOperationId;
+
+describe('TaskModel deferred completion request', () => {
+ describe('completeIfCompletionRequested', () => {
+ it('completes the task and consumes the request in one write', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await createPendingTask(model);
+
+ const completed = await model.completeIfCompletionRequested(task.id, 'op-self');
+
+ expect(completed?.status).toBe('completed');
+ expect(completed?.completedAt).toBeInstanceOf(Date);
+ expect(requestOf(completed)).toBeNull();
+ // Other context namespaces survive.
+ expect((completed?.context as any)?.scheduler).toEqual({ tickMessageId: 'msg-1' });
+ });
+
+ it('leaves the task running once the request was withdrawn', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await createPendingTask(model);
+
+ expect(await model.withdrawCompletionRequest(task.id, 'op-self')).toBe(true);
+ expect(await model.completeIfCompletionRequested(task.id, 'op-self')).toBeNull();
+ expect((await model.findById(task.id))?.status).toBe('running');
+ });
+
+ it('ignores a request held by another run', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await createPendingTask(model);
+
+ expect(await model.completeIfCompletionRequested(task.id, 'op-other')).toBeNull();
+ expect((await model.findById(task.id))?.status).toBe('running');
+ });
+
+ it("does not complete another user's task", async () => {
+ const task = await createPendingTask(new TaskModel(serverDB, otherUserId));
+
+ expect(
+ await new TaskModel(serverDB, userId).completeIfCompletionRequested(task.id, 'op-self'),
+ ).toBeNull();
+ });
+ });
+
+ describe('withdrawCompletionRequest', () => {
+ it('clears the request on a running task', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await createPendingTask(model);
+
+ expect(await model.withdrawCompletionRequest(task.id, 'op-self')).toBe(true);
+ const found = await model.findById(task.id);
+ expect(found?.status).toBe('running');
+ expect(requestOf(found)).toBeNull();
+ });
+
+ it('reports false once the run already consumed the request', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await createPendingTask(model);
+
+ await model.completeIfCompletionRequested(task.id, 'op-self');
+
+ expect(await model.withdrawCompletionRequest(task.id, 'op-self')).toBe(false);
+ expect((await model.findById(task.id))?.status).toBe('completed');
+ });
+ });
+});
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index 121d69aa2e4..73d91a8f0d0 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -273,6 +273,14 @@ export class TaskModel {
return rows.updateStatusIfCurrent(this.ctx, id, currentStatus, status, extra);
}
+ async completeIfCompletionRequested(id: string, operationId: string): Promise<TaskItem | null> {
+ return rows.completeIfCompletionRequested(this.ctx, id, operationId);
+ }
+
+ async withdrawCompletionRequest(id: string, operationId: string): Promise<boolean> {
+ return rows.withdrawCompletionRequest(this.ctx, id, operationId);
+ }
+
async batchUpdateStatus(ids: string[], status: string): Promise<number> {
return rows.batchUpdateStatus(this.ctx, ids, status);
}
diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.ts
index 64b27854023..92e1346952a 100644
--- a/packages/database/src/models/task/rows.ts
+++ b/packages/database/src/models/task/rows.ts
@@ -300,6 +300,67 @@ export const updateStatusIfCurrent = async (
return task ?? null;
};
+/** `context.completion.requestedByOperationId` β€” the run a deferred completion waits for. */
+const completionRequest = sql`${tasks.context} -> 'completion' ->> 'requestedByOperationId'`;
+const withoutCompletionRequest = sql`jsonb_set(${tasks.context}, '{completion,requestedByOperationId}', 'null'::jsonb)`;
+
+/**
+ * Completes a running task whose deferred completion `operationId` still holds,
+ * consuming the request in the same write. Returns null when the request was
+ * withdrawn (or the task left `running`) first.
+ */
+export const completeIfCompletionRequested = async (
+ ctx: TaskModelContext,
+ id: string,
+ operationId: string,
+): Promise<TaskItem | null> => {
+ const [task] = await ctx.db
+ .update(tasks)
+ .set({
+ completedAt: new Date(),
+ context: withoutCompletionRequest,
+ error: null,
+ status: 'completed',
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(tasks.id, id),
+ eq(tasks.status, 'running'),
+ sql`${completionRequest} = ${operationId}`,
+ taskOwnership(ctx),
+ ),
+ )
+ .returning();
+
+ return task ?? null;
+};
+
+/**
+ * Withdraws a running task's deferred completion by `operationId`. Returns
+ * false when the run already consumed it (or the task left `running`).
+ */
+export const withdrawCompletionRequest = async (
+ ctx: TaskModelContext,
+ id: string,
+ operationId: string,
+): Promise<boolean> => {
+ const updated = await ctx.db
+ .update(tasks)
+ .set({ context: withoutCompletionRequest, updatedAt: new Date() })
+ .where(
+ and(
+ eq(tasks.id, id),
+ eq(tasks.status, 'running'),
+ sql`${completionRequest} = ${operationId}`,
+ taskOwnership(ctx),
+ ),
+ )
+ .returning({ id: tasks.id });
+
+ return updated.length > 0;
+};
+
export const batchUpdateStatus = async (
ctx: TaskModelContext,
ids: string[],