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(goal): close a retired node's pending acceptance (#21962)

Lobehub Coderc47b32e5e6ee
diff --git a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
index d02abe9d20d..1a09ee61059 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { isClosedByRetirement } from '@lobechat/utils/verify/acceptanceStatus';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AcceptanceService } from '../acceptanceService';
@@ -15,6 +16,8 @@ const mocks = vi.hoisted(() => ({
findReportByRun: vi.fn(),
goalFindByGraphTask: vi.fn(),
goalLockById: vi.fn(),
+ isRetiredGoalTask: vi.fn(),
+ settleTaskPolicyStatus: vi.fn(),
listByAcceptance: vi.fn(),
setDecision: vi.fn(),
taskFindById: vi.fn(),
@@ -31,6 +34,7 @@ vi.mock('@/database/models/acceptance', () => ({
return {
findById: mocks.findById,
findPolicyById: mocks.findPolicyById,
+ settleTaskPolicyStatus: mocks.settleTaskPolicyStatus,
updatePolicyStatus: mocks.updatePolicyStatus,
updateStatus: mocks.updateStatus,
};
@@ -91,6 +95,19 @@ describe('AcceptanceService task lifecycle', () => {
mocks.findPolicyById.mockImplementation((...args: unknown[]) => mocks.findById(...args));
mocks.goalFindByGraphTask.mockResolvedValue(undefined);
mocks.goalLockById.mockImplementation(async (id: string) => ({ archivedAt: null, id }));
+ mocks.isRetiredGoalTask.mockResolvedValue(false);
+ // Mirrors AcceptanceModel.settleTaskPolicyStatus: closes a settled status on
+ // a retired goal node, keeps a user's terminal decision, writes on change.
+ mocks.settleTaskPolicyStatus.mockImplementation(async (id: string, status: string) => {
+ const row = await mocks.findById(id);
+ if (row?.status === 'accepted' || row?.status === 'closed') return row.status;
+ const next =
+ isClosedByRetirement(status) && (await mocks.isRetiredGoalTask(row?.subjectId))
+ ? 'closed'
+ : status;
+ if (next !== row?.status) await mocks.updatePolicyStatus(id, next);
+ return next;
+ });
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' });
@@ -229,6 +246,48 @@ describe('AcceptanceService task lifecycle', () => {
await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');
expect(mocks.updatePolicyStatus).toHaveBeenCalledWith('acc-1', 'delivered');
});
+
+ describe('a round that settles after its goal node was retired', () => {
+ // Retirement closes only what is already waiting; a round still verifying
+ // lands later and must not reopen a sign-off for work the Goal dropped.
+ beforeEach(() => {
+ mocks.isRetiredGoalTask.mockResolvedValue(true);
+ });
+
+ it.each([
+ ['delivered', 'failed'],
+ ['delivered', 'delivered'],
+ ['errored', 'errored'],
+ ])('closes instead of %s (round %s) and leaves the task alone', async (_, roundStatus) => {
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', roundIndex: 1, status: roundStatus },
+ ]);
+
+ await expect(service().recomputeStatus('acc-1')).resolves.toBe('closed');
+ expect(mocks.isRetiredGoalTask).toHaveBeenCalledWith('task_1');
+ expect(mocks.updatePolicyStatus).toHaveBeenCalledWith('acc-1', 'closed');
+ expect(mocks.taskServiceUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it('closes a round that comes back only planned', async () => {
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', roundIndex: 1, status: 'planned' },
+ ]);
+
+ await expect(service().recomputeStatus('acc-1')).resolves.toBe('closed');
+ expect(mocks.updatePolicyStatus).toHaveBeenCalledWith('acc-1', 'closed');
+ });
+
+ it('keeps a round still verifying open', async () => {
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', roundIndex: 1, status: 'verifying' },
+ ]);
+ stored.status = 'planned';
+
+ await expect(service().recomputeStatus('acc-1')).resolves.toBe('verifying');
+ expect(mocks.updatePolicyStatus).toHaveBeenCalledWith('acc-1', 'verifying');
+ });
+ });
});
describe('a reject racing the completion', () => {
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
index 1496d75378a..7ce1f1855c3 100644
--- a/apps/server/src/services/verify/acceptanceService/index.ts
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -376,9 +376,18 @@ export class AcceptanceService {
if (acceptance.status === 'rejected' && current.userDecision === 'reject') return 'rejected';
const report = await this.reportModel.findByRun(current.id);
- const status = statusFromRound(current, Boolean(report));
+ const derived = statusFromRound(current, Boolean(report));
+ // A task acceptance settles under a row lock that also closes it when its
+ // goal node has been retired: a round still verifying at retirement lands
+ // here afterwards, and the Goal discarded that node's outcome, so it must
+ // not reopen a sign-off request for dropped work.
+ const status =
+ acceptance.subjectType === 'task'
+ ? ((await this.acceptanceModel.settleTaskPolicyStatus(acceptanceId, derived)) ?? derived)
+ : derived;
if (status !== acceptance.status) {
- await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);
+ if (acceptance.subjectType !== 'task')
+ await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);
notifyAcceptance(acceptanceId, 'session');
log('acceptance %s β†’ %s (from round %d)', acceptanceId, status, current.roundIndex);
}
diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.ts
index 2e8b9284d3f..d454b63ea32 100644
--- a/packages/database/src/models/__tests__/goalGraph.test.ts
+++ b/packages/database/src/models/__tests__/goalGraph.test.ts
@@ -4,8 +4,18 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agents, goalNodes, goals, tasks, topics, users, workspaces } from '../../schemas';
+import {
+ acceptances,
+ agents,
+ goalNodes,
+ goals,
+ tasks,
+ topics,
+ users,
+ workspaces,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import { AcceptanceModel } from '../acceptance';
import { GoalModel } from '../goal';
import { GoalGraphModel } from '../goalGraph';
import { TaskModel } from '../task';
@@ -271,6 +281,98 @@ describe('GoalGraphModel', () => {
expect(await graphModel.getNodeStatus(goal.id, node!.id)).toBe('retired');
});
+ it('closes the acceptance a retired node was still waiting on', async () => {
+ // A retired node's delivery is discarded; left `delivered`, its acceptance
+ // kept asking the owner to sign off on work the Goal had already dropped.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Retire sign-off' });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Replaced' });
+ const verifying = await graphModel.createNode(goal.id, { kind: 'task', title: 'Judging' });
+ const taskModel = new TaskModel(serverDB, userId);
+ const task = await taskModel.create({ instruction: 'Delivered work' });
+ const judged = await taskModel.create({ instruction: 'Still judged' });
+ await graphModel.bindTask(goal.id, node!.id, task.id);
+ await graphModel.bindTask(goal.id, verifying!.id, judged.id);
+ const [delivered, inFlight] = await serverDB
+ .insert(acceptances)
+ .values([
+ { status: 'delivered', subjectId: task.id, subjectType: 'task', userId },
+ { status: 'verifying', subjectId: judged.id, subjectType: 'task', userId },
+ ])
+ .returning();
+
+ await graphModel.updateNodeStatus(goal.id, node!.id, 'retired', 'replaced by a new plan');
+ await graphModel.updateNodeStatus(goal.id, verifying!.id, 'retired');
+
+ const rows = await serverDB.select().from(acceptances);
+ const statusOf = (id: string) => rows.find((row) => row.id === id);
+ expect(statusOf(delivered.id)).toMatchObject({ status: 'closed' });
+ expect(statusOf(delivered.id)?.completedAt).toBeInstanceOf(Date);
+ // A round still running is left to land; only a settled wait is closed.
+ expect(statusOf(inFlight.id)).toMatchObject({ status: 'verifying' });
+ });
+
+ it.each(['pending', 'planned', 'rejected'] as const)(
+ 'closes a %s acceptance when its node is retired before delivering',
+ async (status) => {
+ // Dispatch files the acceptance as `pending` before any round exists; a
+ // node retired then has no round left to settle, so retirement is the
+ // only chance to take it off the active list.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Early retire' });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Dropped early' });
+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'Not yet run' });
+ await graphModel.bindTask(goal.id, node!.id, task.id);
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ status, subjectId: task.id, subjectType: 'task', userId })
+ .returning();
+
+ await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');
+
+ const [row] = await serverDB
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.id, acceptance.id));
+ expect(row).toMatchObject({ status: 'closed' });
+ expect(row.completedAt).toBeInstanceOf(Date);
+ },
+ );
+
+ it('settles a task acceptance closed once its goal node is retired', async () => {
+ // A round still verifying at retirement lands afterwards: the settle closes
+ // it under the row lock retirement also takes, while a live step still
+ // moves to `delivered` and a user's decision is never overwritten.
+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Late settle' });
+ const retired = await graphModel.createNode(goal.id, { kind: 'task', title: 'Dropped' });
+ const live = await graphModel.createNode(goal.id, { kind: 'task', title: 'Live' });
+ const taskModel = new TaskModel(serverDB, userId);
+ const dropped = await taskModel.create({ instruction: 'Dropped work' });
+ const running = await taskModel.create({ instruction: 'Live work' });
+ const decided = await taskModel.create({ instruction: 'Accepted work' });
+ await graphModel.bindTask(goal.id, retired!.id, dropped.id);
+ await graphModel.bindTask(goal.id, live!.id, running.id);
+ const [late, onLive, accepted] = await serverDB
+ .insert(acceptances)
+ .values([
+ { status: 'verifying', subjectId: dropped.id, subjectType: 'task', userId },
+ { status: 'verifying', subjectId: running.id, subjectType: 'task', userId },
+ { status: 'accepted', subjectId: decided.id, subjectType: 'task', userId },
+ ])
+ .returning();
+ await graphModel.updateNodeStatus(goal.id, retired!.id, 'retired');
+
+ const acceptanceModel = new AcceptanceModel(serverDB, userId);
+ expect(await acceptanceModel.settleTaskPolicyStatus(late.id, 'delivered')).toBe('closed');
+ expect(await acceptanceModel.settleTaskPolicyStatus(onLive.id, 'delivered')).toBe('delivered');
+ expect(await acceptanceModel.settleTaskPolicyStatus(accepted.id, 'delivered')).toBe('accepted');
+
+ const rows = await serverDB.select().from(acceptances);
+ const rowOf = (id: string) => rows.find((row) => row.id === id);
+ expect(rowOf(late.id)).toMatchObject({ status: 'closed' });
+ expect(rowOf(late.id)?.completedAt).toBeInstanceOf(Date);
+ expect(rowOf(onLive.id)).toMatchObject({ completedAt: null, status: 'delivered' });
+ expect(rowOf(accepted.id)).toMatchObject({ status: 'accepted' });
+ });
+
it('treats a same-status write as a no-op instead of churning the graph', async () => {
// Re-activating an already-active node must not bump `updatedAt` or append
// an event: a coordinator retry loop does this on every tick, and the
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
index ea87433c04e..f33748f2c0c 100644
--- a/packages/database/src/models/acceptance.ts
+++ b/packages/database/src/models/acceptance.ts
@@ -5,6 +5,7 @@ import type {
AcceptanceStatus,
AcceptanceSubjectType,
} from '@lobechat/types';
+import { isClosedByRetirement } from '@lobechat/utils/verify/acceptanceStatus';
import type { SQL } from 'drizzle-orm';
import { and, desc, eq, exists, inArray, isNull, lt, ne, not, or, sql } from 'drizzle-orm';
@@ -315,6 +316,55 @@ export class AcceptanceModel {
});
};
+ /**
+ * Settle a task acceptance's rollup status, closing it instead when the task
+ * is a retired step of a goal graph (the Goal discards a retired node's
+ * outcome, so nothing is left to sign off). Returns the status now stored.
+ *
+ * The acceptance row is locked before the goal node is read, and node
+ * retirement locks the same row (GoalGraphModel.updateNodeStatus), so the two
+ * cannot interleave: whichever commits second sees the other's write. A
+ * user's `accepted` / `closed` that landed meanwhile is kept.
+ */
+ settleTaskPolicyStatus = async (
+ id: string,
+ status: AcceptanceStatus,
+ ): Promise<AcceptanceStatus | undefined> => {
+ const policyScope = buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },
+ );
+ return this.db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ status: acceptances.status, subjectId: acceptances.subjectId })
+ .from(acceptances)
+ .where(and(eq(acceptances.id, id), policyScope))
+ .for('update');
+ if (!row) return undefined;
+ const current = row.status as AcceptanceStatus;
+ if (current === 'accepted' || current === 'closed') return current;
+
+ let next = status;
+ if (isClosedByRetirement(status)) {
+ const [retired] = await tx
+ .select({ id: goalNodes.id })
+ .from(goalNodes)
+ .where(and(eq(goalNodes.taskId, row.subjectId), eq(goalNodes.status, 'retired')))
+ .limit(1);
+ if (retired) next = 'closed';
+ }
+ if (next !== current)
+ await tx
+ .update(acceptances)
+ .set({
+ completedAt: TERMINAL_ACCEPTANCE_STATUSES.has(next) ? new Date() : null,
+ status: next,
+ })
+ .where(eq(acceptances.id, id));
+ return next;
+ });
+ };
+
/**
* The status of many subjects' acceptances in one read β€” for list surfaces
* that must know each row's state without a request per row. Exact where the
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index f231a8ed001..9c10e57c865 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -15,6 +15,7 @@ import type {
GoalStatus,
} from '@lobechat/types';
import { experimentStatus } from '@lobechat/utils/goalGraph';
+import { ACCEPTANCE_STATUSES_CLOSED_BY_RETIREMENT } from '@lobechat/utils/verify/acceptanceStatus';
import {
and,
asc,
@@ -39,6 +40,7 @@ import {
goalNodeWorkVersions,
} from '../schemas/goalGraph';
import { briefs, tasks } from '../schemas/task';
+import { acceptances } from '../schemas/verify';
import { works, workVersions } from '../schemas/work';
import type { LobeChatDatabase, Transaction } from '../type';
import { notTrashed } from '../utils/softDelete';
@@ -1005,6 +1007,34 @@ export class GoalGraphModel {
reason,
taskId: node.taskId ?? undefined,
});
+ // A retired node's delivery will never be judged: its outcome is
+ // discarded (see GoalService completion). Left open β€” awaiting sign-off,
+ // a first round that never comes (`pending` / `planned`), or rework after
+ // a reject β€” its acceptance stays in the active list for work the Goal
+ // already dropped. Close it in the same transaction so the node and its
+ // acceptance reach their terminal states together. A round still
+ // verifying is left to land; settling it closes it (recomputeStatus).
+ if (status === 'retired' && node.taskId) {
+ // Lock the acceptance whatever its status: a round settling right now
+ // (AcceptanceModel.settleTaskPolicyStatus) holds the same lock while it
+ // checks for retirement, so a `verifying` row skipped here cannot be
+ // written back to `delivered` after this commits unseen.
+ await tx
+ .select({ id: acceptances.id })
+ .from(acceptances)
+ .where(and(eq(acceptances.subjectType, 'task'), eq(acceptances.subjectId, node.taskId)))
+ .for('update');
+ await tx
+ .update(acceptances)
+ .set({ completedAt: new Date(), status: 'closed' })
+ .where(
+ and(
+ eq(acceptances.subjectType, 'task'),
+ eq(acceptances.subjectId, node.taskId),
+ inArray(acceptances.status, [...ACCEPTANCE_STATUSES_CLOSED_BY_RETIREMENT]),
+ ),
+ );
+ }
return node;
});
diff --git a/packages/utils/src/verify/acceptanceStatus.ts b/packages/utils/src/verify/acceptanceStatus.ts
index e9b74d36e16..d0425cf5d76 100644
--- a/packages/utils/src/verify/acceptanceStatus.ts
+++ b/packages/utils/src/verify/acceptanceStatus.ts
@@ -38,3 +38,20 @@ export const statusFromRound = (
}
}
};
+
+/**
+ * Acceptance states that retiring the task's goal node closes. A retired node's
+ * outcome is discarded, so nothing it is still waiting for β€” a sign-off, a
+ * first round, or rework after a reject β€” will come. A round still `verifying`
+ * / `repairing` is left to land; settling then closes it (recomputeStatus).
+ */
+export const ACCEPTANCE_STATUSES_CLOSED_BY_RETIREMENT = [
+ 'pending',
+ 'planned',
+ 'delivered',
+ 'errored',
+ 'rejected',
+] as const satisfies readonly AcceptanceStatus[];
+
+export const isClosedByRetirement = (status: string): boolean =>
+ (ACCEPTANCE_STATUSES_CLOSED_BY_RETIREMENT as readonly string[]).includes(status);
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
index b4036c8b98d..f2622379e49 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts
@@ -283,6 +283,48 @@ describe('buildGoalGraphView', () => {
expect(view.byId.w1).toMatchObject({ isStale: false, isVerifying: true });
});
+ it('stops asking for a sign-off on a retired node', () => {
+ // The node's delivery is discarded; a `delivered` acceptance beside the
+ // "retired" tag asked the owner to confirm work the Goal had dropped.
+ const view = buildGoalGraphView(
+ snapshot({
+ acceptances: {
+ w1: { id: 'acc-1', status: 'delivered' },
+ w2: { id: 'acc-2', status: 'errored' },
+ w3: { id: 'acc-3', status: 'delivered' },
+ w4: { id: 'acc-4', status: 'pending' },
+ w5: { id: 'acc-5', status: 'rejected' },
+ w6: { id: 'acc-6', status: 'verifying' },
+ },
+ events: [
+ event('w1', 'retired', 30),
+ event('w2', 'retired', 30),
+ event('w4', 'retired', 30),
+ event('w5', 'retired', 30),
+ event('w6', 'retired', 30),
+ ],
+ nodes: [
+ node('w1', { status: 'retired', taskId: 'task-1' }),
+ node('w2', { status: 'retired', taskId: 'task-2' }),
+ node('w3', { status: 'active', taskId: 'task-3' }),
+ node('w4', { status: 'retired', taskId: 'task-4' }),
+ node('w5', { status: 'retired', taskId: 'task-5' }),
+ node('w6', { status: 'retired', taskId: 'task-6' }),
+ ],
+ }),
+ NOW,
+ );
+
+ expect(view.byId.w1.acceptance).toEqual({ id: 'acc-1', status: 'closed' });
+ expect(view.byId.w2.acceptance).toEqual({ id: 'acc-2', status: 'closed' });
+ expect(view.byId.w3.acceptance).toEqual({ id: 'acc-3', status: 'delivered' });
+ // Retired before its first round, or after a reject: nothing is coming.
+ expect(view.byId.w4.acceptance).toEqual({ id: 'acc-4', status: 'closed' });
+ expect(view.byId.w5.acceptance).toEqual({ id: 'acc-5', status: 'closed' });
+ // A round still being judged lands first; the server closes it on settle.
+ expect(view.byId.w6.acceptance).toEqual({ id: 'acc-6', status: 'verifying' });
+ });
+
it('gives up on a delivery the coordinator itself would no longer wait for', () => {
// Past the coordinator's settle grace the verify run really is stuck, and
// the honest reading flips back to lost.
diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
index 0b31a13c600..dc1fb719556 100644
--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts
@@ -13,6 +13,7 @@ import type {
WorkType,
} from '@lobechat/types';
import { experimentMembers } from '@lobechat/utils/goalGraph';
+import { isClosedByRetirement } from '@lobechat/utils/verify/acceptanceStatus';
/**
* Read model for the Goal process-control surface.
@@ -36,6 +37,16 @@ export const RECENT_DONE = 2;
const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);
+/**
+ * A retired node's delivery is discarded, so its acceptance no longer waits on
+ * anyone. The server closes it on retirement; this covers rows retired before
+ * it did, and a round that landed after β€” neither should ask for a sign-off.
+ */
+const nodeAcceptance = (node: GoalGraphNode, acceptance: GoalNodeAcceptance): GoalNodeAcceptance =>
+ node.status === 'retired' && isClosedByRetirement(acceptance.status)
+ ? { ...acceptance, status: 'closed' }
+ : acceptance;
+
export type GoalAttemptOutcome = 'passed' | 'failed' | 'retired' | 'running';
export interface GoalAttempt {
@@ -477,7 +488,7 @@ export const buildGoalGraphView = (
node.kind === 'experiment'
? [...members].flatMap((id) => artifactsByNode.get(id) ?? [])
: (artifactsByNode.get(node.id) ?? []),
- ...(acceptances?.[node.id] ? { acceptance: acceptances[node.id] } : {}),
+ ...(acceptances?.[node.id] ? { acceptance: nodeAcceptance(node, acceptances[node.id]) } : {}),
...(assignees?.[node.id] ? { assigneeAgentId: assignees[node.id] } : {}),
attempts,
...(closedReason ? { closedReason } : {}),