🤯 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-runtime): finalize trace snapshot on error path (#14440)
Arvin Xu7bf923d762f9
diff --git a/src/features/Conversation/store/slices/data/reducer.test.ts b/src/features/Conversation/store/slices/data/reducer.test.tsindex 586451d7894..02b331bb515 100644--- a/src/features/Conversation/store/slices/data/reducer.test.ts+++ b/src/features/Conversation/store/slices/data/reducer.test.ts@@ -63,7 +63,7 @@ describe('messagesReducer', () => {const payload: MessageDispatch = { type: 'unimplementedType' };expect(() => messagesReducer(initialState, payload)).toThrowError(- '未实现的 dispatch type,请检查 reducer',+ 'Unimplemented dispatch type, check reducer',);});});diff --git a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsxindex 6ca80345bf7..686514f4c2d 100644--- a/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx+++ b/src/features/DailyBrief/__tests__/BriefCardActions.test.tsx@@ -119,7 +119,7 @@ describe('BriefCardActions', () => {it('should fallback to DEFAULT_BRIEF_ACTIONS when actions prop is null', () => {renderWithRouter(<BriefCardActions actions={null} briefId="brief-2" briefType="decision" />);- expect(screen.getByText('✅ 确认')).toBeInTheDocument();+ expect(screen.getByText('✅ Confirm')).toBeInTheDocument();});it('should hardcode primary action label to "Confirm complete" for result briefs', () => {diff --git a/src/server/routers/mobile/index.ts b/src/server/routers/mobile/index.tsindex 5bd9503b009..b0a50e13a86 100644--- a/src/server/routers/mobile/index.ts+++ b/src/server/routers/mobile/index.ts@@ -14,8 +14,8 @@ import { briefRouter } from '../lambda/brief';import { chunkRouter } from '../lambda/chunk';import { configRouter } from '../lambda/config';import { documentRouter } from '../lambda/document';-import { homeRouter } from '../lambda/home';import { fileRouter } from '../lambda/file';+import { homeRouter } from '../lambda/home';import { knowledgeBaseRouter } from '../lambda/knowledgeBase';import { marketRouter } from '../lambda/market';import { messageRouter } from '../lambda/message';diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 2c4d354a641..c34f1293f07 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -450,6 +450,12 @@ export class AgentRuntimeService {};}+ // Hoisted so the error-path snapshot finalize can record an+ // approximate startedAt for the failing step. The inner `startAt` at the+ // runtime.step() call site stays as the authoritative start for the+ // success path.+ const stepStartAt = Date.now();+try {log('[%s][%d] Start step executing...', operationId, stepIndex);@@ -1048,65 +1054,26 @@ export class AgentRuntimeService {// Dispatch completion hooksawait this.dispatchCompletionHooks(operationId, stepResult.newState, reason);- // Finalize tracing snapshot via injected snapshot store- if (this.snapshotStore) {- try {- const partial = await this.snapshotStore.loadPartial(operationId);-- if (partial) {- if (completionSignalEvents.length > 0 && partial.steps?.length) {- const lastStep = partial.steps.at(-1);-- if (lastStep) {- lastStep.events = [...(lastStep.events ?? []), ...completionSignalEvents];- }+ // Finalize tracing snapshot. The error catch below uses the same+ // helper so propagated failures still write the canonical S3+ // snapshot instead of orphaning the partial (LOBE-8533).+ await this.finalizeSnapshotForOperation(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ error: stepResult.newState.error+ ? {+ message:+ this.extractErrorMessage(stepResult.newState.error) ??+ JSON.stringify(stepResult.newState.error),+ type: String(+ stepResult.newState.error.type ??+ stepResult.newState.error.errorType ??+ 'unknown',+ ),}-- const metadata = agentState?.metadata as any;- const snapshot = {- agentId: metadata?.agentId,- completedAt: Date.now(),- completionReason: reason,- error: stepResult.newState.error- ? {- message:- this.extractErrorMessage(stepResult.newState.error) ??- JSON.stringify(stepResult.newState.error),- type: String(- stepResult.newState.error.type ??- stepResult.newState.error.errorType ??- 'unknown',- ),- }- : undefined,- model: partial.model,- operationId,- provider: partial.provider,- retryDelayExpression:- typeof metadata?.queueRetryDelay === 'string'- ? metadata.queueRetryDelay- : undefined,- startedAt: partial.startedAt ?? Date.now(),- steps: (partial.steps ?? []).sort((a, b) => a.stepIndex - b.stepIndex),- totalCost: stepResult.newState.cost?.total ?? 0,- totalSteps: stepResult.newState.stepCount,- totalTokens: stepResult.newState.usage?.llm?.tokens?.total ?? 0,- topicId: metadata?.topicId,- traceId: operationId,- userId: metadata?.userId,- externalRetryCount:- typeof metadata?.externalRetryCount === 'number'- ? metadata.externalRetryCount- : undefined,- };-- await this.snapshotStore.save(snapshot as any);- await this.snapshotStore.removePartial(operationId);- }- } catch (e) {- log('[%s] snapshot finalization failed: %O', operationId, e);- }- }+ : undefined,+ state: stepResult.newState,+ });}return {@@ -1176,6 +1143,29 @@ export class AgentRuntimeService {// Dispatch onComplete + onError hooksawait this.dispatchCompletionHooks(operationId, finalStateWithError, 'error');+ // Finalize the partial snapshot into the canonical S3 path so the+ // failed op is observable in the same place as a successful run.+ // Without this, propagated errors (e.g. markPersistFatal from+ // RuntimeExecutors) leave the partial as an orphan at+ // `_partial/<op>.json` and the canonical+ // `agent-traces/<agentId>/<topicId>/<op>.json` returns 404 — see+ // LOBE-8533.+ //+ // `failedStep` synthesizes a step record for the failure because the+ // real step never reached `appendStepToPartial` — it threw before the+ // success path could push it. Without this synthetic step, the+ // snapshot's step count would lag the assistant message that+ // triggered the failing call.+ await this.finalizeSnapshotForOperation(operationId, {+ completionReason: 'error',+ error: {+ message: formattedError.message ?? String(formattedError.type),+ type: String(formattedError.type),+ },+ failedStep: { startedAt: stepStartAt, stepIndex },+ state: finalStateWithError,+ });+throw error;} finally {// Release lock so legitimate retries or next operations can proceed.@@ -1988,6 +1978,123 @@ export class AgentRuntimeService {return undefined;}+ /**+ * Finalize the partial snapshot for an operation into the final S3 path.+ *+ * Centralizes the success-path finalize and the error-path finalize so a+ * propagated exception (e.g. `markPersistFatal` from RuntimeExecutors) still+ * lands in the same trace bucket as a normal completion. Without this, the+ * partial sits orphaned at `_partial/<op>.json` and the canonical+ * `agent-traces/<agentId>/<topicId>/<op>.json` returns 404 — see LOBE-8533.+ *+ * `failedStep` is for the error path: when the failing step never reached+ * `appendStepToPartial`, callers from `catch` pass it to keep step counts+ * aligned with the assistant message that triggered the call. If the+ * partial already contains a step with the same `stepIndex` (the+ * success-path append landed before a later persist/queue failure), the+ * error event is merged into the existing record instead of duplicating+ * the step.+ */+ private async finalizeSnapshotForOperation(+ operationId: string,+ params: {+ /**+ * Events to merge into the last partial step before save. Used by the+ * success path to attach agentSignal completion events to the trailing+ * step. Error path leaves this empty.+ */+ appendEventsToLastStep?: Array<{ [key: string]: unknown; type: string }>;+ completionReason: StepCompletionReason;+ error?: { message: string; type: string };+ failedStep?: { stepIndex: number; startedAt: number };+ state: any;+ },+ ): Promise<void> {+ if (!this.snapshotStore) return;++ try {+ const partial = await this.snapshotStore.loadPartial(operationId);+ if (!partial) {+ // No partial recorded — nothing to finalize. Skip rather than write an+ // empty snapshot.+ return;+ }++ if (params.appendEventsToLastStep?.length && partial.steps?.length) {+ const lastStep = partial.steps.at(-1);+ if (lastStep) {+ lastStep.events = [...(lastStep.events ?? []), ...params.appendEventsToLastStep];+ }+ }++ if (params.failedStep) {+ if (!partial.steps) partial.steps = [];+ // The success path may have already appended this step to the partial+ // before a later failure (e.g. saveAgentState or queue scheduling+ // throwing post-append). In that case attach the error event to the+ // existing record instead of pushing a duplicate stepIndex — duplicates+ // corrupt ordering and per-step metrics in trace reconstruction.+ const existing = partial.steps.find((s) => s.stepIndex === params.failedStep!.stepIndex);+ if (existing) {+ if (params.error) {+ existing.events = [...(existing.events ?? []), { error: params.error, type: 'error' }];+ }+ } else {+ const now = Date.now();+ partial.steps.push({+ completedAt: now,+ events: params.error ? [{ error: params.error, type: 'error' }] : undefined,+ executionTimeMs: now - params.failedStep.startedAt,+ startedAt: params.failedStep.startedAt,+ stepIndex: params.failedStep.stepIndex,+ // StepSnapshot.stepType is strictly 'call_llm' | 'call_tool';+ // persist-fatal originates in the tool path, so 'call_tool' is the+ // truthful label. LLM-side failures still map to 'call_tool' here —+ // the surrounding `events: [{type: 'error'}]` is the discriminant+ // consumers should read.+ stepType: 'call_tool',+ totalCost: params.state?.cost?.total ?? 0,+ totalTokens: params.state?.usage?.llm?.tokens?.total ?? 0,+ });+ }+ }++ const metadata = (params.state?.metadata ?? {}) as any;+ const finalizedSteps = (partial.steps ?? []).sort((a, b) => a.stepIndex - b.stepIndex);+ const snapshot = {+ agentId: metadata?.agentId,+ completedAt: Date.now(),+ completionReason: params.completionReason,+ error: params.error,+ externalRetryCount:+ typeof metadata?.externalRetryCount === 'number'+ ? metadata.externalRetryCount+ : undefined,+ model: partial.model,+ operationId,+ provider: partial.provider,+ retryDelayExpression:+ typeof metadata?.queueRetryDelay === 'string' ? metadata.queueRetryDelay : undefined,+ startedAt: partial.startedAt ?? Date.now(),+ steps: finalizedSteps,+ topicId: metadata?.topicId,+ totalCost: params.state?.cost?.total ?? 0,+ // Trust the finalized step array over `state.stepCount`: on the error+ // path stepCount comes from Redis and reflects the last completed step,+ // so it lags behind the synthetic failed step we just appended.+ totalSteps: finalizedSteps.length || (params.state?.stepCount ?? 0),+ totalTokens: params.state?.usage?.llm?.tokens?.total ?? 0,+ traceId: operationId,+ userId: metadata?.userId,+ };++ await this.snapshotStore.save(snapshot as any);+ await this.snapshotStore.removePartial(operationId);+ } catch (e) {+ log('[%s] snapshot finalize failed (reason=%s): %O', operationId, params.completionReason, e);+ }+ }+/*** Decide whether to continue execution*/diff --git a/src/server/services/agentRuntime/__tests__/executeStep.test.ts b/src/server/services/agentRuntime/__tests__/executeStep.test.tsindex 2d133b9b112..11caf749d55 100644--- a/src/server/services/agentRuntime/__tests__/executeStep.test.ts+++ b/src/server/services/agentRuntime/__tests__/executeStep.test.ts@@ -596,3 +596,305 @@ describe('AgentRuntimeService.executeStep - Redis failure in error handler', ()dispatchSpy.mockRestore();});});++describe('AgentRuntimeService.executeStep - error-path snapshot finalize (LOBE-8533)', () => {+ it('finalizes a snapshot with completionReason=error and a synthetic failed step when the executor throws', async () => {+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ // A partial WITH steps already recorded — simulates a tool dispatch+ // that succeeded for several prior steps before persist-fatal hit.+ loadPartial: vi.fn().mockResolvedValue({+ startedAt: 1_777_960_000_000,+ steps: [+ {+ stepIndex: 0,+ stepType: 'call_llm',+ startedAt: 1_777_960_000_000,+ completedAt: 1_777_960_001_000,+ executionTimeMs: 1000,+ totalCost: 0,+ totalTokens: 100,+ },+ ],+ }),+ removePartial: vi.fn().mockResolvedValue(undefined),+ save: vi.fn().mockResolvedValue(undefined),+ savePartial: vi.fn().mockResolvedValue(undefined),+ };++ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: null,+ snapshotStore: snapshotStore as any,+ });+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ coordinator.releaseStepLock = vi.fn().mockResolvedValue(undefined);+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);++ // First load returns a running state to enter step execution; second+ // load (in the catch) returns the same so finalStateWithError carries+ // metadata.+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ lastModified: new Date().toISOString(),+ metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ status: 'running',+ stepCount: 1,+ });+ coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);++ // Force the runtime.step path to throw — simulates markPersistFatal+ // bubbling up from RuntimeExecutors.+ const persistFatal = new Error('parent message missing');+ (persistFatal as any).errorType = 'ConversationParentMissing';+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({+ runtime: { step: vi.fn().mockRejectedValue(persistFatal) },+ });++ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(+ service.executeStep({+ context: { phase: 'tool_use' } as any,+ operationId: 'op-fatal-1',+ stepIndex: 1,+ }),+ ).rejects.toThrow();++ // The op MUST land in the canonical S3 path with completionReason=error+ expect(snapshotStore.save).toHaveBeenCalledTimes(1);+ const saved = snapshotStore.save.mock.calls[0][0];+ expect(saved).toMatchObject({+ agentId: 'agt-1',+ completionReason: 'error',+ operationId: 'op-fatal-1',+ topicId: 'tpc-1',+ userId: 'user-1',+ });+ expect(saved.error).toMatchObject({ type: 'ConversationParentMissing' });++ // The failing step must be appended so the snapshot's step count tracks+ // the assistant message that triggered the failed call (otherwise the+ // partial would lag by one and the dangling tool_use would still look+ // unattributed).+ const failedStep = saved.steps.find((s: any) => s.stepIndex === 1);+ expect(failedStep).toBeDefined();+ expect(failedStep.events?.[0]).toMatchObject({ type: 'error' });++ expect(snapshotStore.removePartial).toHaveBeenCalledWith('op-fatal-1');++ dispatchSpy.mockRestore();+ });++ it('skips finalize when there is no partial (op never recorded a step)', async () => {+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ loadPartial: vi.fn().mockResolvedValue(null),+ removePartial: vi.fn().mockResolvedValue(undefined),+ save: vi.fn().mockResolvedValue(undefined),+ savePartial: vi.fn().mockResolvedValue(undefined),+ };++ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: null,+ snapshotStore: snapshotStore as any,+ });+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ coordinator.releaseStepLock = vi.fn().mockResolvedValue(undefined);+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ lastModified: new Date().toISOString(),+ metadata: {},+ status: 'running',+ stepCount: 0,+ });+ coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);++ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({+ runtime: { step: vi.fn().mockRejectedValue(new Error('boom')) },+ });+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(+ service.executeStep({+ context: { phase: 'user_input' } as any,+ operationId: 'op-no-partial',+ stepIndex: 0,+ }),+ ).rejects.toThrow();++ // No partial -> nothing to finalize. Don't write an empty snapshot.+ expect(snapshotStore.save).not.toHaveBeenCalled();+ expect(snapshotStore.removePartial).not.toHaveBeenCalled();++ dispatchSpy.mockRestore();+ });++ it('reports totalSteps from the finalized step array, not stepCount, on the error path', async () => {+ // Partial has step 0 from a prior successful step. The catch path will+ // synthesize step 1 for the failure. After finalize, partial.steps.length+ // is 2 — but Redis-loaded stepCount is still 1 (last completed step+ // before failure). The snapshot must report 2.+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ loadPartial: vi.fn().mockResolvedValue({+ startedAt: 1_777_960_000_000,+ steps: [+ {+ stepIndex: 0,+ stepType: 'call_llm',+ startedAt: 1_777_960_000_000,+ completedAt: 1_777_960_001_000,+ executionTimeMs: 1000,+ totalCost: 0,+ totalTokens: 100,+ },+ ],+ }),+ removePartial: vi.fn().mockResolvedValue(undefined),+ save: vi.fn().mockResolvedValue(undefined),+ savePartial: vi.fn().mockResolvedValue(undefined),+ };++ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: null,+ snapshotStore: snapshotStore as any,+ });+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ coordinator.releaseStepLock = vi.fn().mockResolvedValue(undefined);+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ lastModified: new Date().toISOString(),+ metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ status: 'running',+ stepCount: 1,+ });+ coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);++ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({+ runtime: { step: vi.fn().mockRejectedValue(new Error('boom')) },+ });+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(+ service.executeStep({+ context: { phase: 'tool_use' } as any,+ operationId: 'op-totalsteps',+ stepIndex: 1,+ }),+ ).rejects.toThrow();++ expect(snapshotStore.save).toHaveBeenCalledTimes(1);+ const saved = snapshotStore.save.mock.calls[0][0];+ expect(saved.steps).toHaveLength(2);+ expect(saved.totalSteps).toBe(2);++ dispatchSpy.mockRestore();+ });++ it('does not duplicate a step when the failing index was already appended to the partial', async () => {+ // Simulates: success-path append wrote stepIndex=1 to the partial during+ // a prior attempt, then a later failure (e.g. queue scheduling threw)+ // sent the operation into a retry whose catch path synthesizes the same+ // stepIndex. The error event must be merged into the existing record+ // instead of pushing a duplicate that corrupts ordering and metrics.+ const snapshotStore = {+ get: vi.fn(),+ getLatest: vi.fn(),+ list: vi.fn(),+ listPartials: vi.fn(),+ loadPartial: vi.fn().mockResolvedValue({+ startedAt: 1_777_960_000_000,+ steps: [+ {+ stepIndex: 0,+ stepType: 'call_llm',+ startedAt: 1_777_960_000_000,+ completedAt: 1_777_960_001_000,+ executionTimeMs: 1000,+ totalCost: 0,+ totalTokens: 100,+ },+ {+ stepIndex: 1,+ stepType: 'call_tool',+ startedAt: 1_777_960_002_000,+ completedAt: 1_777_960_003_000,+ events: [{ type: 'done' }],+ executionTimeMs: 1000,+ totalCost: 0,+ totalTokens: 50,+ },+ ],+ }),+ removePartial: vi.fn().mockResolvedValue(undefined),+ save: vi.fn().mockResolvedValue(undefined),+ savePartial: vi.fn().mockResolvedValue(undefined),+ };++ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: null,+ snapshotStore: snapshotStore as any,+ });+ const coordinator = (service as any).coordinator;+ const streamManager = (service as any).streamManager;++ coordinator.tryClaimStep = vi.fn().mockResolvedValue(true);+ coordinator.releaseStepLock = vi.fn().mockResolvedValue(undefined);+ streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);+ // stepCount=1 so the layer-2 early-exit guard (stepCount > stepIndex) does+ // not skip this attempt — we want the catch path to run.+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ lastModified: new Date().toISOString(),+ metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ status: 'running',+ stepCount: 1,+ });+ coordinator.saveAgentState = vi.fn().mockResolvedValue(undefined);++ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({+ runtime: { step: vi.fn().mockRejectedValue(new Error('queue down')) },+ });+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(+ service.executeStep({+ context: { phase: 'tool_use' } as any,+ operationId: 'op-dedup',+ stepIndex: 1,+ }),+ ).rejects.toThrow();++ expect(snapshotStore.save).toHaveBeenCalledTimes(1);+ const saved = snapshotStore.save.mock.calls[0][0];++ // Exactly one step per index — no duplicates from the synthetic append.+ expect(saved.steps).toHaveLength(2);+ expect(saved.steps.map((s: any) => s.stepIndex)).toEqual([0, 1]);++ // The original stepIndex=1 record is preserved, with the error event+ // appended after the existing 'done' event.+ const merged = saved.steps.find((s: any) => s.stepIndex === 1);+ expect(merged.events).toHaveLength(2);+ expect(merged.events[0]).toMatchObject({ type: 'done' });+ expect(merged.events[1]).toMatchObject({ type: 'error' });++ dispatchSpy.mockRestore();+ });+});