π€― 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): register a CLI run's Works before publishing agent_runtime_end (#23606)
Inneid82e6d2cce05
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex 5528dc6f587..a1260a81c97 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -304,7 +304,10 @@ export class CompletionLifecycle {{ content: input.deliverable ?? '', role: 'assistant' },],host: { hooks: input.serializedHooks },- metadata: { assistantMessageId: input.assistantMessageId },+ metadata: {+ assistantMessageId: input.assistantMessageId,+ ...(input.worksRegistered && { _fileWorksRegistered: true }),+ },...(input.shareVisitor && { principal: { actor: { shareVisitor: input.shareVisitor } } }),origin: {agentId: input.agentId,@@ -329,6 +332,13 @@ export class CompletionLifecycle {return registerFileWorks(this.deps(), operationId, state);}+ // Feed the result back as `worksRegistered` so completeOperation's backstop skips a second scan.+ async registerOperationWorks(input: OperationCompletionInput): Promise<boolean> {+ const state = this.buildStateFromInput(input);+ await this.registerFileWorks(input.operationId, state);+ return (state.metadata as { _fileWorksRegistered?: boolean })._fileWorksRegistered === true;+ }+/*** The single terminal-completion entry for every path that does NOT have the* in-process runtime's rich `state` in hand: heterogeneous CLI exitdiff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.tsindex dcaa0e8bcf9..fa6b80da362 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/types.ts@@ -80,6 +80,7 @@ export interface OperationCompletionInput {/** Trace / usage aggregates (llm calls, tokens, tool calls). */usage?: unknown;userId?: string;+ worksRegistered?: boolean;}/** Options shared by {@link CompletionLifecycle.completeOperation} / `dispatchHooks`. */diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/finishWorks.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/finishWorks.test.tsnew file mode 100644index 00000000000..29e11611f72--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/__tests__/finishWorks.test.ts@@ -0,0 +1,75 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';++import { HeterogeneousAgentService } from '..';+import { HeteroTraceRecorder } from '../HeteroTraceRecorder';++const finish = async (result: 'error' | 'success') => {+ const order: string[] = [];+ vi.spyOn(HeteroTraceRecorder.prototype, 'finalize').mockResolvedValue(undefined as any);+ const registerFileWorks = vi+ .spyOn(CompletionLifecycle.prototype, 'registerFileWorks')+ .mockImplementation(async (_operationId, state) => {+ order.push('works');+ state.metadata._fileWorksRegistered = true;+ });+ const dispatchHooks = vi+ .spyOn(CompletionLifecycle.prototype, 'dispatchHooks')+ .mockResolvedValue(undefined);+ const publishStreamEvent = vi.fn(async (_operationId: string, event: { type: string }) => {+ if (event.type === 'agent_runtime_end') order.push('end');+ return 'ok';+ });+ const service = new HeterogeneousAgentService({} as any, 'user-1', {+ agentOperationModel: { findById: vi.fn(async () => ({ metadata: {} })) } as any,+ persistenceHandler: { finish: vi.fn(async () => undefined) } as any,+ snapshotStore: null,+ streamEventManager: { publishStreamEvent } as any,+ topicModel: {+ settleRunningOperation: vi.fn(async () => ({+ assistantMessageId: 'asst-1',+ status: 'settled',+ })),+ updateMetadata: vi.fn(async () => undefined),+ } as any,+ });++ await service.heteroFinish({ agentType: 'codex', operationId: 'op-1', result, topicId: 'tpc-1' });++ return { dispatchHooks, order, registerFileWorks };+};++describe('HeterogeneousAgentService.heteroFinish β Works', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('registers the run Works before publishing agent_runtime_end', async () => {+ const { order, registerFileWorks } = await finish('success');++ expect(order).toEqual(['works', 'end']);+ expect(registerFileWorks).toHaveBeenCalledWith(+ 'op-1',+ expect.objectContaining({+ metadata: expect.objectContaining({ assistantMessageId: 'asst-1' }),+ origin: expect.objectContaining({ topicId: 'tpc-1' }),+ }),+ );+ });++ it('tells the completion lifecycle the Works are registered so it does not scan again', async () => {+ const { dispatchHooks } = await finish('success');++ const [, state] = dispatchHooks.mock.calls[0] as [string, any];+ expect(state.metadata._fileWorksRegistered).toBe(true);+ });++ it('leaves a failed run to the completion lifecycle', async () => {+ const { order, registerFileWorks } = await finish('error');++ expect(registerFileWorks).not.toHaveBeenCalled();+ expect(order).toEqual(['end']);+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 0fcd16b57bd..cde04bc1126 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -598,11 +598,13 @@ export class HeterogeneousAgentService {// Emit a terminal `agent_runtime_end` so renderer subscribers shut down even// if the CLI stream missed it. A stale callback that belongs to neither the// root operation nor one of its children returns above.- await this.streamEventManager.publishStreamEvent(operationId, {- data: endData,- stepIndex: 0,- type: 'agent_runtime_end',- });+ const publishRuntimeEnd = () =>+ this.streamEventManager.publishStreamEvent(operationId, {+ data: endData,+ stepIndex: 0,+ type: 'agent_runtime_end',+ });+ if (result !== 'success') await publishRuntimeEnd();// Drive the run's lifecycle hooks (onComplete / onError) through the same// `hookDispatcher` the normal LLM runtime uses, so the task lifecycle@@ -744,40 +746,46 @@ export class HeterogeneousAgentService {// and on success the delivery-checker card + verify gate run against the task's// plan. `completeOperation` owns the (formerly hand-rolled) synthetic-state// build, so the goal+reply turns and trace aggregates are mapped in ONE place.- await new CompletionLifecycle(this.db, this.userId, this.workspaceId, {+ const lifecycle = new CompletionLifecycle(this.db, this.userId, this.workspaceId, {includeShareVisitor: !!this.shareVisitor,- }).completeOperation(- {- agentId,- assistantMessageId,- cost: { total: totals?.totalCost ?? null },- deliverable: lastAssistantContent ?? '',- error: error ?? undefined,- goal: goalContent,- // Backfilled executed model/provider β the verify gate bails when absent.- model: totals?.model,- operationId,- orchestrationRole,- provider: totals?.provider,- serializedHooks,- shareVisitor: this.shareVisitor,- stepCount: totals?.stepCount ?? null,- topicId,- usage: {- llm: {- apiCalls: totals?.llmCalls ?? null,- tokens: {- input: totals?.totalInputTokens ?? null,- output: totals?.totalOutputTokens ?? null,- total: totals?.totalTokens ?? null,- },+ });+ const completionInput = {+ agentId,+ assistantMessageId,+ cost: { total: totals?.totalCost ?? null },+ deliverable: lastAssistantContent ?? '',+ error: error ?? undefined,+ goal: goalContent,+ // Backfilled executed model/provider β the verify gate bails when absent.+ model: totals?.model,+ operationId,+ orchestrationRole,+ provider: totals?.provider,+ serializedHooks,+ shareVisitor: this.shareVisitor,+ stepCount: totals?.stepCount ?? null,+ topicId,+ usage: {+ llm: {+ apiCalls: totals?.llmCalls ?? null,+ tokens: {+ input: totals?.totalInputTokens ?? null,+ output: totals?.totalOutputTokens ?? null,+ total: totals?.totalTokens ?? null,},- tools: { totalCalls: totals?.toolCalls ?? null },},- userId: this.userId,+ tools: { totalCalls: totals?.toolCalls ?? null },},- completionReason,- );+ userId: this.userId,+ };+ // The client refetches messages on `agent_runtime_end`; Works registered after it+ // (the lifecycle backstop) leave the Work card missing until a manual reload.+ let worksRegistered = false;+ if (result === 'success') {+ worksRegistered = await lifecycle.registerOperationWorks(completionInput);+ await publishRuntimeEnd();+ }+ await lifecycle.completeOperation({ ...completionInput, worksRegistered }, completionReason);log('heteroFinish: dispatched completion lifecycle for op=%s result=%s', operationId, result);// Follow-ups the user queued behind this run start as the next turn here,