π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(hetero): settle the verify plan before dispatching a Task run (#22605)
Arvin Xu65fd1a328a70
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.tsindex c38148d4e76..6b478e3553d 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts@@ -87,6 +87,58 @@ describe('CompletionLifecycle.dispatchHooks β verify plan race', () => {});});+describe('CompletionLifecycle.waitForVerifyPlan', () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ const startWithPendingPlan = async () => {+ const lifecycle = buildLifecycle();+ let settle: () => void = () => {};+ vi.spyOn(verifyServices, 'instantiateVerifyPlanOnStart').mockReturnValue(+ new Promise<void>((resolve) => {+ settle = resolve;+ }),+ );+ await lifecycle.recordStart({ operationId: 'op-1', taskId: 'task-1' } as any);+ return { lifecycle, settle };+ };++ const track = (promise: Promise<void>) => {+ const state = { done: false };+ void promise.then(() => {+ state.done = true;+ });+ return state;+ };++ it('resolves once the plan has settled', async () => {+ const { lifecycle, settle } = await startWithPendingPlan();+ const wait = track(lifecycle.waitForVerifyPlan('op-1'));++ await flushMicrotasks();+ expect(wait.done).toBe(false);++ settle();+ await flushMicrotasks();+ expect(wait.done).toBe(true);+ });++ it('stops waiting at the bound so a slow plan cannot hold the dispatch', async () => {+ const { lifecycle } = await startWithPendingPlan();+ vi.useFakeTimers();+ const wait = lifecycle.waitForVerifyPlan('op-1', 1000);++ await vi.advanceTimersByTimeAsync(1000);+ await expect(wait).resolves.toBeUndefined();+ });++ it('returns at once for an operation with no plan in flight', async () => {+ await expect(buildLifecycle().waitForVerifyPlan('op-none')).resolves.toBeUndefined();+ });+});+describe('CompletionLifecycle.dispatchHooks β async-tool park', () => {afterEach(() => {vi.restoreAllMocks();diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex 4f1a88a6961..8364f811aca 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -82,6 +82,9 @@ export const isSuccessLikeCompletionReason = (reason: string): boolean =>* no-fallback webhook failures are rethrown after terminal persistence so a* queue execution can retry the control-flow handoff.*/+/** Above the p99 of planning a task run (41 s in production). */+const VERIFY_PLAN_DISPATCH_WAIT_MS = 45_000;+export class CompletionLifecycle {private readonly messageModel: MessageModel;private readonly agentOperationModel: AgentOperationModel;@@ -178,6 +181,32 @@ export class CompletionLifecycle {return persisted;}+ /**+ * Wait, within a bound, for the verify plan {@link recordStart} began. A+ * dispatched run keeps working on another machine while this request ends, so+ * work left in flight here can be dropped with the function. Waiting also+ * means the builder can read its criteria from its first command.+ *+ * The bound only keeps a slow plan call from holding the dispatch: past it the+ * run starts anyway and the finish path still creates the plan.+ */+ async waitForVerifyPlan(+ operationId: string,+ timeoutMs = VERIFY_PLAN_DISPATCH_WAIT_MS,+ ): Promise<void> {+ const instantiation = this.verifyPlanInstantiations.get(operationId);+ if (!instantiation) return;++ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ instantiation,+ new Promise<void>((resolve) => {+ timer = setTimeout(resolve, timeoutMs);+ }),+ ]);+ clearTimeout(timer);+ }+/*** Persist terminal state to `agent_operations`. Fire-and-forget: a DB* outage must never block hook dispatch or the executor's terminaldiff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.tsindex 4eb1a0a7e5f..c7ce7318e00 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.branches.test.ts@@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({publishAgentRuntimeInit: vi.fn(),readDeviceSystemInfo: vi.fn(),recordStart: vi.fn(),+ waitForVerifyPlan: vi.fn(),resolveDeviceDispatchAuthorizationFailure: vi.fn(),resolveSandboxSessionConfig: vi.fn(),scheduleTimedOutDispatchConfirmation: vi.fn(),@@ -32,7 +33,11 @@ const mocks = vi.hoisted(() => ({vi.mock('@/server/services/agentRuntime/CompletionLifecycle', () => ({CompletionLifecycle: vi.fn().mockImplementation(function () {- return { completeOperation: mocks.completeOperation, recordStart: mocks.recordStart };+ return {+ completeOperation: mocks.completeOperation,+ recordStart: mocks.recordStart,+ waitForVerifyPlan: mocks.waitForVerifyPlan,+ };}),}));@@ -191,6 +196,7 @@ const finalizeParams = (fields: Record<string, unknown>) => ({beforeEach(() => {vi.clearAllMocks();mocks.recordStart.mockResolvedValue(true);+ mocks.waitForVerifyPlan.mockResolvedValue(undefined);mocks.signHeteroOperationJWT.mockResolvedValue('op-jwt');mocks.signUserJWT.mockResolvedValue('user-jwt');mocks.finalizeHeteroDispatchError.mockResolvedValue(true);@@ -538,6 +544,35 @@ describe('dispatchHeteroAgent β local CLI agents', () => {expect(result).toMatchObject({ status: 'created', success: true, token: 'user-jwt' });});+ // Regression: the plan was started without being waited for, so a dispatch that+ // returned first lost it and the builder's `plan state` read null all run.+ it('holds the dispatch until the verify plan has settled', async () => {+ const { deps } = createDeps();+ let settlePlan = () => {};+ mocks.waitForVerifyPlan.mockReturnValue(+ new Promise<void>((resolve) => {+ settlePlan = resolve;+ }),+ );++ const dispatch = dispatchHeteroAgent(+ deps,+ createCtx({+ boundDeviceId: 'dev-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'claude-code' },+ }),+ createInput('claude-code'),+ );+ await vi.waitFor(() => expect(mocks.waitForVerifyPlan).toHaveBeenCalled());+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(mocks.dispatchAgentRun).not.toHaveBeenCalled();++ settlePlan();+ await dispatch;+ expect(mocks.dispatchAgentRun).toHaveBeenCalledTimes(1);+ });+it('sends the Claude Code account the agent is routed to', async () => {// Without it the device always spawned on its default login, so picking an// account in Manage accounts changed nothing for a device-bound agent.diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.tsindex 7a6e107681b..0e28e691a60 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/index.ts@@ -111,11 +111,8 @@ export const dispatchHeteroAgent = async (// also an authentication prerequisite: every callback// re-authorizes its operation token against this exact principal. Do not// mint a token or dispatch/spawn when persistence fails.- const operationPersisted = await new CompletionLifecycle(- deps.db,- deps.userId,- deps.workspaceId,- ).recordStart({+ const completionLifecycle = new CompletionLifecycle(deps.db, deps.userId, deps.workspaceId);+ const operationPersisted = await completionLifecycle.recordStart({requireReservation: !!input.reservedOperationId,agentId: persistAgentId,appContext: { ...appContext, sourceMessageId: userMessageId },@@ -141,6 +138,11 @@ export const dispatchHeteroAgent = async (await input.onOperationCreated?.(operationId);+ // The builder runs elsewhere and this request ends once it is dispatched, so+ // the plan has to be in place first or the builder finds no criteria to file+ // evidence against.+ await completionLifecycle.waitForVerifyPlan(operationId);+const run: HeteroRun = {agentId: resolvedAgentId,assistantMessageId,