π€― 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: δΏη Agent ηεΎ ζ’ε€εη trace (#22059)
Mocha6587d989905d
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.trace.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.trace.test.tsnew file mode 100644index 00000000000..663cbeb2f65--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.trace.test.ts@@ -0,0 +1,101 @@+import type { ExecutionSnapshot, ISnapshotStore } from '@lobechat/agent-tracing';+import { describe, expect, it, vi } from 'vitest';++import { type AppendStepParams, OperationTraceRecorder } from '../../OperationTraceRecorder';+import { finishOperation, type StepCompletionDeps } from './completion';++const operationId = 'op_parked';++const stepParams = (stepIndex: number): AppendStepParams => ({+ afterStepSignalEvents: [],+ agentState: { messages: [] },+ beforeStepSignalEvents: [],+ externalRetryCount: 0,+ presentation: {+ executionTimeMs: 1,+ stepType: 'call_tool',+ thinking: false,+ totalCost: 0,+ totalInputTokens: 0,+ totalOutputTokens: 0,+ totalSteps: stepIndex + 1,+ totalTokens: 0,+ },+ startedAt: 0,+ stepIndex,+ stepResult: { events: [], newState: { messages: [] } },+});++describe('parked operation trace handoff', () => {+ it('persists a readable wait before resuming and never overwrites the resumed trajectory', async () => {+ let partial: Partial<ExecutionSnapshot> | null = null;+ let snapshot: ExecutionSnapshot | null = null;+ const store = {+ get: async () => structuredClone(snapshot),+ getLatest: async () => structuredClone(snapshot),+ list: async () => [],+ listPartials: async () => [],+ loadPartial: async () => structuredClone(partial),+ removePartial: async () => {+ partial = null;+ },+ save: async (value: ExecutionSnapshot) => {+ snapshot = structuredClone(value);+ },+ savePartial: async (_id: string, value: Partial<ExecutionSnapshot>) => {+ partial = structuredClone(value);+ },+ } satisfies ISnapshotStore;++ const recorder = new OperationTraceRecorder(store);+ await recorder.appendStep(operationId, stepParams(0));+ await recorder.appendStep(operationId, stepParams(1));+ // The resumed invocation runs immediately when the park-time barrier opens.+ let atHandoff: ExecutionSnapshot | null = null;+ let partialAtHandoff: Partial<ExecutionSnapshot> | null = null;+ const tryResumeParentFromAsyncTool = vi.fn(async () => {+ atHandoff = await store.get();+ partialAtHandoff = await store.loadPartial();+ const resumed = new OperationTraceRecorder(store);+ await resumed.appendStep(operationId, stepParams(2));+ await resumed.appendStep(operationId, stepParams(3));+ await resumed.finalize(operationId, { completionReason: 'done', state: {} });+ });+ const deps = {+ completionLifecycle: {+ dispatchHooks: vi.fn(),+ emitSignalEvents: vi.fn().mockResolvedValue([{ type: 'signal' }]),+ },+ delegate: {},+ determineCompletionReason: () => 'waiting_for_async_tool',+ traceRecorder: recorder,+ tryResumeParentFromAsyncTool,+ userId: 'user_1',+ } as unknown as StepCompletionDeps;++ await finishOperation(deps, {+ invokeAgentSpan: { setAttributes: vi.fn() } as unknown as Parameters<+ typeof finishOperation+ >[1]['invokeAgentSpan'],+ operationId,+ stepIndex: 1,+ stepResult: {+ newState: { status: 'waiting_for_async_tool' },+ } as Parameters<typeof finishOperation>[1]['stepResult'],+ });++ expect(tryResumeParentFromAsyncTool).toHaveBeenCalledOnce();+ expect(atHandoff).toMatchObject({+ completionReason: 'waiting_for_async_tool',+ steps: [{ stepIndex: 0 }, { stepIndex: 1 }],+ totalSteps: 2,+ });+ expect(partialAtHandoff).toMatchObject({ steps: [{ stepIndex: 0 }, { stepIndex: 1 }] });+ expect(await store.get()).toMatchObject({+ completionReason: 'done',+ steps: [{ stepIndex: 0 }, { stepIndex: 1 }, { stepIndex: 2 }, { stepIndex: 3 }],+ totalSteps: 4,+ });+ expect(await store.loadPartial()).toBeNull();+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.tsindex 88d407d02aa..4b72807f2ee 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts@@ -57,31 +57,13 @@ export async function finishOperation(await deps.recordInterventionLifecycleCompletion(operationId, stepResult.newState, stepIndex);}- // Park-time self-check: sub-agents are dispatched mid-step, so a- // fast child can complete BEFORE this op's parked state/row were- // persisted β its resume attempt then no-ops against the status- // guard and nothing retries. Now that both the Redis state and the- // `agent_operations` row (via dispatchHooks β persistCompletion)- // say `waiting_for_async_tool`, re-run the barrier once to recover- // any resume that raced the park.- if (stepResult.newState.status === 'waiting_for_async_tool') {- try {- await deps.tryResumeParentFromAsyncTool({ parentOperationId: operationId });- } catch (selfCheckError) {- log(- '[%s][%d] Park-time async-tool self-check failed (non-fatal): %O',- operationId,- stepIndex,- selfCheckError,- );- }- }-// Finalize tracing snapshot. The error catch below uses the same// recorder so propagated failures still write the canonical S3// snapshot instead of orphaning the partial ().// A client park is no trace boundary: keep the partial so the resumed// steps extend the same trajectory and the real end finalizes it whole.+ // Human/async waits expose a readable snapshot and retain the partial. Write+ // both before the async-tool self-check can resume this id in another invocation.const newStateError = stepResult.newState.error;if (reason === 'waiting_for_client') {await deps.traceRecorder.flushPartial();@@ -109,6 +91,27 @@ export async function finishOperation(});logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason }));+ // Park-time self-check: sub-agents are dispatched mid-step, so a+ // fast child can complete BEFORE this op's parked state/row were+ // persisted β its resume attempt then no-ops against the status+ // guard and nothing retries. Now that both the Redis state and the+ // `agent_operations` row (via dispatchHooks β persistCompletion)+ // say `waiting_for_async_tool`, re-run the barrier once to recover+ // any resume that raced the park. The trace is already durable; do not write+ // it after the barrier can hand execution to another invocation.+ if (stepResult.newState.status === 'waiting_for_async_tool') {+ try {+ await deps.tryResumeParentFromAsyncTool({ parentOperationId: operationId });+ } catch (selfCheckError) {+ log(+ '[%s][%d] Park-time async-tool self-check failed (non-fatal): %O',+ operationId,+ stepIndex,+ selfCheckError,+ );+ }+ }+// Follow-ups the user queued behind this run start as the next turn right// here, instead of after the client hears the run ended and sends them// itself. Only after the hooks above: they persist the terminal row anddiff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.tsindex bca66f3b9ec..e9942db8d62 100644--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts@@ -95,6 +95,48 @@ describe('OperationTraceRecorder partial accumulation', () => {expect(store.savePartial.mock.calls.at(-1)?.[1].steps).toHaveLength(3);});+ it.each(['waiting_for_human', 'waiting_for_async_tool'] as const)(+ 'keeps readable snapshots and the full trajectory across repeated %s resumes',+ async (completionReason) => {+ let partial: Partial<ExecutionSnapshot> | null = null;+ const snapshots: ExecutionSnapshot[] = [];+ store.loadPartial.mockImplementation(async () => structuredClone(partial));+ store.savePartial.mockImplementation(async (_id, value) => {+ partial = structuredClone(value);+ });+ store.removePartial.mockImplementation(async () => {+ partial = null;+ });+ store.save.mockImplementation(async (value) => {+ snapshots.push(structuredClone(value));+ });++ await recorder.appendStep(OPERATION_ID, stepParams(0));+ await recorder.finalize(OPERATION_ID, { completionReason, state: {} });+ expect(snapshots.at(-1)).toMatchObject({+ completionReason,+ steps: [{ stepIndex: 0 }],+ });++ const resumedRecorder = new OperationTraceRecorder(store);+ await resumedRecorder.appendStep(OPERATION_ID, stepParams(1));+ await resumedRecorder.finalize(OPERATION_ID, { completionReason, state: {} });++ const finalRecorder = new OperationTraceRecorder(store);+ await finalRecorder.appendStep(OPERATION_ID, stepParams(2));+ await finalRecorder.finalize(OPERATION_ID, { completionReason: 'done', state: {} });++ expect(snapshots.map((value) => value.steps.map((step) => step.stepIndex))).toEqual([+ [0],+ [0, 1],+ [0, 1, 2],+ ]);+ expect(snapshots.at(-1)?.totalSteps).toBe(3);+ expect(partial).toBeNull();+ expect(store.removePartial).toHaveBeenCalledTimes(1);+ },+ );+it('finalizes from memory and deletes the partial after the final snapshot', async () => {await recorder.appendStep(OPERATION_ID, stepParams(0));await recorder.finalize(OPERATION_ID, { completionReason: 'done', state: {} });diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.tsindex 3863f79da3d..6085f0532fc 100644--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts@@ -299,7 +299,14 @@ export class OperationTraceRecorder {// Forget the partial before deleting it, so a late `appendStep` on this// recorder cannot re-upload the object we just removed.this.discardPartial();- await this.store.removePartial(operationId);+ // Human intervention and async tools can continue this operation id. Keep+ // the partial alongside the readable waiting snapshot until the real end.+ if (+ params.completionReason !== 'waiting_for_human' &&+ params.completionReason !== 'waiting_for_async_tool'+ ) {+ await this.store.removePartial(operationId);+ }} catch (e) {log('[%s] snapshot finalize failed (reason=%s): %O', operationId, params.completionReason, e);}