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.

✨ feat(agent): inactivity watchdog finalize endpoint + agent-hono migration (#14476)

Arvin Xu608498a950a7
diff --git a/src/app/(backend)/api/agent/[[...route]]/route.ts b/src/app/(backend)/api/agent/[[...route]]/route.ts
new file mode 100644
index 00000000000..92d620741a0
--- /dev/null
+++ b/src/app/(backend)/api/agent/[[...route]]/route.ts
@@ -0,0 +1,6 @@
+import app from '@/server/agent-hono';
+
+const handler = (request: Request) => app.fetch(request);
+
+export const GET = handler;
+export const POST = handler;
diff --git a/src/app/(backend)/api/agent/route.ts b/src/app/(backend)/api/agent/route.ts
deleted file mode 100644
index 9ddeb6850be..00000000000
--- a/src/app/(backend)/api/agent/route.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import debug from 'debug';
-import { type NextRequest } from 'next/server';
-import { NextResponse } from 'next/server';
-
-import { getServerDB } from '@/database/core/db-adaptor';
-import { verifyQStashSignature } from '@/libs/qstash';
-import { AiAgentService } from '@/server/services/aiAgent';
-
-const log = debug('api-route:agent:exec');
-
-/**
- * Verify API key from Authorization header
- * Format: Bearer <api_key>
- */
-function verifyApiKey(request: NextRequest): boolean {
- const apiKey = process.env.AGENT_EXEC_API_KEY;
-
- // If no API key configured, skip verification
- if (!apiKey) {
- log('API key verification disabled (AGENT_EXEC_API_KEY not configured)');
- return false;
- }
-
- const authHeader = request.headers.get('Authorization');
- if (!authHeader?.startsWith('Bearer ')) {
- log('Missing or invalid Authorization header');
- return false;
- }
-
- const providedKey = authHeader.slice(7); // Remove 'Bearer ' prefix
- return providedKey === apiKey;
-}
-
-export async function POST(request: NextRequest) {
- const startTime = Date.now();
-
- // Read raw body for signature verification (must be done before parsing JSON)
- const rawBody = await request.text();
-
- // Verify authentication - either QStash signature or API key
- const isValidQStash = await verifyQStashSignature(request, rawBody);
- const isValidApiKey = verifyApiKey(request);
-
- if (!isValidQStash && !isValidApiKey) {
- return NextResponse.json(
- { error: 'Unauthorized - Valid QStash signature or API key required' },
- { status: 401 },
- );
- }
-
- // Parse body after verification
- let body: any;
- try {
- body = JSON.parse(rawBody);
- } catch {
- return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
- }
-
- try {
- const {
- userId,
- agentId,
- slug,
- prompt,
- appContext,
- autoStart = true,
- existingMessageIds,
- } = body;
-
- // Validate required parameters
- if (!userId) {
- return NextResponse.json({ error: 'userId is required' }, { status: 400 });
- }
-
- if (!agentId && !slug) {
- return NextResponse.json({ error: 'Either agentId or slug is required' }, { status: 400 });
- }
-
- if (!prompt) {
- return NextResponse.json({ error: 'prompt is required' }, { status: 400 });
- }
-
- log(`[exec] Starting agent execution for user ${userId}, agent ${agentId || slug}`);
-
- // Initialize service
- const serverDB = await getServerDB();
- const aiAgentService = new AiAgentService(serverDB, userId);
-
- // Execute agent
- const result = await aiAgentService.execAgent({
- agentId,
- appContext,
- autoStart,
- existingMessageIds,
- prompt,
- slug,
- });
-
- const executionTime = Date.now() - startTime;
-
- log(
- `[exec] Agent execution completed in ${executionTime}ms, operationId: ${result.operationId}`,
- );
-
- return NextResponse.json({
- ...result,
- executionTime,
- });
- } catch (error: any) {
- const executionTime = Date.now() - startTime;
- console.error('[exec] Error in agent execution: %O', error);
-
- return NextResponse.json(
- {
- error: error.message,
- executionTime,
- },
- { status: 500 },
- );
- }
-}
diff --git a/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts b/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts
deleted file mode 100644
index cbe9d0f6f5a..00000000000
--- a/src/app/(backend)/api/agent/tool-result/__tests__/route.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-// @vitest-environment node
-import { NextRequest } from 'next/server';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { POST } from '../route';
-
-// Mock dependencies before import usage
-const mockPipelineExec = vi.fn().mockResolvedValue([]);
-const mockExpire = vi.fn(() => ({ exec: mockPipelineExec }));
-const mockLpush = vi.fn(() => ({ expire: mockExpire }));
-const mockPipeline = vi.fn(() => ({ lpush: mockLpush }));
-
-const mockRedisClient = {
- pipeline: mockPipeline,
-} as any;
-
-const appEnvMock = {
- AGENT_GATEWAY_SERVICE_TOKEN: 'test-token',
-};
-
-vi.mock('@/envs/app', () => ({
- get appEnv() {
- return appEnvMock;
- },
-}));
-
-let currentRedisClient: any = mockRedisClient;
-vi.mock('@/server/modules/AgentRuntime/redis', () => ({
- getAgentRuntimeRedisClient: () => currentRedisClient,
-}));
-
-function buildRequest(body: unknown, token?: string) {
- const headers = new Headers({ 'content-type': 'application/json' });
- if (token) headers.set('authorization', `Bearer ${token}`);
- return new NextRequest('https://test.com/api/agent/tool-result', {
- body: JSON.stringify(body),
- headers,
- method: 'POST',
- });
-}
-
-const validBody = {
- content: '{"ok":true}',
- success: true,
- toolCallId: 'call-abc',
-};
-
-describe('/api/agent/tool-result POST', () => {
- beforeEach(() => {
- currentRedisClient = mockRedisClient;
- appEnvMock.AGENT_GATEWAY_SERVICE_TOKEN = 'test-token';
- });
-
- afterEach(() => {
- vi.clearAllMocks();
- });
-
- it('returns 503 when AGENT_GATEWAY_SERVICE_TOKEN is not configured', async () => {
- appEnvMock.AGENT_GATEWAY_SERVICE_TOKEN = '';
- const response = await POST(buildRequest(validBody, 'test-token'));
- expect(response.status).toBe(503);
- });
-
- it('returns 401 when authorization header is missing or wrong', async () => {
- const response = await POST(buildRequest(validBody));
- expect(response.status).toBe(401);
-
- const response2 = await POST(buildRequest(validBody, 'wrong-token'));
- expect(response2.status).toBe(401);
- });
-
- it('returns 400 when body is invalid', async () => {
- const response = await POST(buildRequest({ toolCallId: 'x' }, 'test-token'));
- expect(response.status).toBe(400);
- });
-
- it('returns 503 when Redis is unavailable', async () => {
- currentRedisClient = null;
- const response = await POST(buildRequest(validBody, 'test-token'));
- expect(response.status).toBe(503);
- });
-
- it('LPUSHes the payload and sets TTL on happy path', async () => {
- const response = await POST(buildRequest(validBody, 'test-token'));
- expect(response.status).toBe(204);
- expect(mockLpush).toHaveBeenCalledWith(
- 'tool_result:call-abc',
- expect.stringContaining('"toolCallId":"call-abc"'),
- );
- expect(mockExpire).toHaveBeenCalledWith('tool_result:call-abc', 120);
- expect(mockPipelineExec).toHaveBeenCalled();
- });
-
- it('returns 503 when Redis pipeline exec throws', async () => {
- mockPipelineExec.mockRejectedValueOnce(new Error('redis down'));
- const response = await POST(buildRequest(validBody, 'test-token'));
- expect(response.status).toBe(503);
- });
-});
diff --git a/src/app/(backend)/api/agent/tool-result/route.ts b/src/app/(backend)/api/agent/tool-result/route.ts
deleted file mode 100644
index 05b681bd1da..00000000000
--- a/src/app/(backend)/api/agent/tool-result/route.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import debug from 'debug';
-import { type NextRequest, NextResponse } from 'next/server';
-import { z } from 'zod';
-
-import { appEnv } from '@/envs/app';
-import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
-
-const log = debug('api-route:agent:tool-result');
-
-const TOOL_RESULT_TTL_SECONDS = 120;
-
-const ToolResultBodySchema = z.object({
- content: z.string().nullable(),
- error: z
- .object({
- message: z.string(),
- type: z.string().optional(),
- })
- .optional(),
- success: z.boolean(),
- toolCallId: z.string().min(1),
-});
-
-/**
- * Receive a tool execution result from Agent Gateway, originating from a
- * client that executed a server-dispatched tool_execute. The result is
- * LPUSH'd into a per-toolCallId list so the server-side agent loop's BLPOP
- * can wake up and continue.
- *
- * Authenticated with AGENT_GATEWAY_SERVICE_TOKEN (the Gateway is the only
- * trusted caller). Idempotency is not required: BLPOP will pop the first
- * available value; duplicates sit under TTL until they expire.
- */
-export async function POST(request: NextRequest) {
- const serviceToken = appEnv.AGENT_GATEWAY_SERVICE_TOKEN;
- if (!serviceToken) {
- log('AGENT_GATEWAY_SERVICE_TOKEN is not configured');
- return NextResponse.json({ error: 'Service not configured' }, { status: 503 });
- }
-
- const authHeader = request.headers.get('authorization');
- if (authHeader !== `Bearer ${serviceToken}`) {
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
- }
-
- let parsed;
- try {
- const body = await request.json();
- parsed = ToolResultBodySchema.safeParse(body);
- } catch {
- return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
- }
-
- if (!parsed.success) {
- return NextResponse.json(
- { error: 'Invalid body', issues: parsed.error.issues },
- { status: 400 },
- );
- }
-
- const redis = getAgentRuntimeRedisClient();
- if (!redis) {
- log('Redis is not available');
- return NextResponse.json({ error: 'Redis unavailable' }, { status: 503 });
- }
-
- const { toolCallId } = parsed.data;
- const key = `tool_result:${toolCallId}`;
-
- try {
- await redis
- .pipeline()
- .lpush(key, JSON.stringify(parsed.data))
- .expire(key, TOOL_RESULT_TTL_SECONDS)
- .exec();
- log('Persisted tool result for %s (success=%s)', toolCallId, parsed.data.success);
- } catch (error) {
- log('Failed to LPUSH tool result for %s: %O', toolCallId, error);
- return NextResponse.json({ error: 'Redis write failed' }, { status: 503 });
- }
-
- return new NextResponse(null, { status: 204 });
-}
diff --git a/src/server/agent-hono/handlers/__tests__/toolResult.test.ts b/src/server/agent-hono/handlers/__tests__/toolResult.test.ts
new file mode 100644
index 00000000000..e1d72277bc6
--- /dev/null
+++ b/src/server/agent-hono/handlers/__tests__/toolResult.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Import after mocks β€” and import the handler file directly (not via the
+// agent-hono barrel) so we don't trigger Hono module resolution. The handler
+// only imports Hono types, which are erased at runtime.
+import { toolResult } from '../toolResult';
+
+const mockPipelineExec = vi.fn().mockResolvedValue([]);
+const mockExpire = vi.fn(() => ({ exec: mockPipelineExec }));
+const mockLpush = vi.fn(() => ({ expire: mockExpire }));
+const mockPipeline = vi.fn(() => ({ lpush: mockLpush }));
+const mockRedisClient = { pipeline: mockPipeline } as any;
+
+let currentRedisClient: any = mockRedisClient;
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => currentRedisClient,
+}));
+
+/**
+ * Minimal Hono Context stub matching only the surface `toolResult` reaches.
+ * We hand-build this because vitest's module resolver can't load the `hono`
+ * package in this repo (pnpm-isolated, not hoisted), so a real Hono Context
+ * would require fixing repo-level resolution. Testing the handler with a
+ * stub keeps coverage on the redis + zod paths, which is where the value is.
+ */
+function buildContext(body: unknown) {
+ let captured: { status: number; body: any } | undefined;
+ const ctx = {
+ body: (b: any, status: number) => {
+ captured = { body: b, status };
+ return new Response(b, { status });
+ },
+ json: (b: any, status = 200) => {
+ captured = { body: b, status };
+ return Response.json(b, { status });
+ },
+ req: {
+ json: async () => body,
+ },
+ } as any;
+ return { ctx, getCaptured: () => captured };
+}
+
+const validBody = {
+ content: '{"ok":true}',
+ success: true,
+ toolCallId: 'call-abc',
+};
+
+describe('toolResult handler', () => {
+ beforeEach(() => {
+ currentRedisClient = mockRedisClient;
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns 400 when body is invalid', async () => {
+ const { ctx, getCaptured } = buildContext({ toolCallId: 'x' });
+ const res = await toolResult(ctx);
+ expect(res.status).toBe(400);
+ expect(getCaptured()?.body).toMatchObject({ error: 'Invalid body' });
+ });
+
+ it('returns 400 when JSON parse throws', async () => {
+ const ctx = {
+ json: (b: any, status: number) => Response.json(b, { status }),
+ req: {
+ json: async () => {
+ throw new Error('bad json');
+ },
+ },
+ } as any;
+ const res = await toolResult(ctx);
+ expect(res.status).toBe(400);
+ });
+
+ it('returns 503 when Redis is unavailable', async () => {
+ currentRedisClient = null;
+ const { ctx } = buildContext(validBody);
+ const res = await toolResult(ctx);
+ expect(res.status).toBe(503);
+ });
+
+ it('LPUSHes the payload and sets TTL on happy path', async () => {
+ const { ctx } = buildContext(validBody);
+ const res = await toolResult(ctx);
+ expect(res.status).toBe(204);
+ expect(mockLpush).toHaveBeenCalledWith(
+ 'tool_result:call-abc',
+ expect.stringContaining('"toolCallId":"call-abc"'),
+ );
+ expect(mockExpire).toHaveBeenCalledWith('tool_result:call-abc', 120);
+ expect(mockPipelineExec).toHaveBeenCalled();
+ });
+
+ it('returns 503 when Redis pipeline exec throws', async () => {
+ mockPipelineExec.mockRejectedValueOnce(new Error('redis down'));
+ const { ctx } = buildContext(validBody);
+ const res = await toolResult(ctx);
+ expect(res.status).toBe(503);
+ });
+});
diff --git a/src/server/agent-hono/handlers/execAgent.ts b/src/server/agent-hono/handlers/execAgent.ts
new file mode 100644
index 00000000000..c2902af64dd
--- /dev/null
+++ b/src/server/agent-hono/handlers/execAgent.ts
@@ -0,0 +1,63 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+const log = debug('lobe-server:agent:exec');
+
+/**
+ * Start a new agent operation. Body shape:
+ * `{ userId, agentId | slug, prompt, appContext?, autoStart?, existingMessageIds? }`.
+ *
+ * Auth: handled by `qstashOrApiKeyAuth` on the route β€” QStash signature OR
+ * `AGENT_EXEC_API_KEY` Bearer token. Either passes.
+ */
+export async function execAgent(c: Context): Promise<Response> {
+ const startTime = Date.now();
+
+ const body = await c.req.json().catch(() => null);
+ if (!body) return c.json({ error: 'Invalid JSON body' }, 400);
+
+ const {
+ userId,
+ agentId,
+ slug,
+ prompt,
+ appContext,
+ autoStart = true,
+ existingMessageIds,
+ } = body as Record<string, unknown> & { autoStart?: boolean };
+
+ if (!userId) return c.json({ error: 'userId is required' }, 400);
+ if (!agentId && !slug) {
+ return c.json({ error: 'Either agentId or slug is required' }, 400);
+ }
+ if (!prompt) return c.json({ error: 'prompt is required' }, 400);
+
+ log('[exec] Starting agent execution for user %s, agent %s', userId, agentId || slug);
+
+ try {
+ const serverDB = await getServerDB();
+ const aiAgentService = new AiAgentService(serverDB, userId as string);
+
+ const result = await aiAgentService.execAgent({
+ agentId: agentId as string | undefined,
+ appContext: appContext as any,
+ autoStart,
+ existingMessageIds: existingMessageIds as string[] | undefined,
+ prompt: prompt as string,
+ slug: slug as string | undefined,
+ });
+
+ const executionTime = Date.now() - startTime;
+ log('[exec] Completed in %dms, operationId: %s', executionTime, result.operationId);
+
+ return c.json({ ...result, executionTime });
+ } catch (error) {
+ const executionTime = Date.now() - startTime;
+ const message = error instanceof Error ? error.message : 'unknown error';
+ console.error('[exec] Error in agent execution: %O', error);
+ return c.json({ error: message, executionTime }, 500);
+ }
+}
diff --git a/src/server/agent-hono/handlers/finalizeAbandoned.ts b/src/server/agent-hono/handlers/finalizeAbandoned.ts
new file mode 100644
index 00000000000..d94c8025c87
--- /dev/null
+++ b/src/server/agent-hono/handlers/finalizeAbandoned.ts
@@ -0,0 +1,45 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AbandonOperationService } from '@/server/services/agentRuntime';
+
+const log = debug('lobe-server:agent:finalize-abandoned');
+
+/**
+ * Reverse-trigger finalization for an operation whose Vercel function was
+ * killed mid-flight. Called by the agent-gateway DO inactivity watchdog when
+ * an op has gone silent past the threshold β€” see LOBE-8533.
+ *
+ * Body: `{ operationId: string, reason: string }`
+ *
+ * Auth: handled by the `serviceTokenAuth` middleware on the route.
+ */
+export async function finalizeAbandoned(c: Context): Promise<Response> {
+ const startTime = Date.now();
+
+ const body = await c.req.json().catch(() => null);
+ if (!body) return c.json({ error: 'Invalid JSON body' }, 400);
+
+ const { operationId, reason } = body as { operationId?: string; reason?: string };
+ if (!operationId) return c.json({ error: 'operationId is required' }, 400);
+ if (!reason) return c.json({ error: 'reason is required' }, 400);
+
+ log('[%s] finalize-abandoned (reason=%s)', operationId, reason);
+
+ try {
+ const serverDB = await getServerDB();
+ const service = new AbandonOperationService(serverDB);
+ const result = await service.finalizeAbandoned(operationId, reason);
+
+ const executionTime = Date.now() - startTime;
+ log('[%s] finalize-abandoned done in %dms: %O', operationId, executionTime, result);
+
+ return c.json({ ...result, executionTime, operationId, reason });
+ } catch (error) {
+ const executionTime = Date.now() - startTime;
+ const message = error instanceof Error ? error.message : 'unknown error';
+ console.error('[finalize-abandoned] %O', error);
+ return c.json({ error: message, executionTime, operationId }, 500);
+ }
+}
diff --git a/src/server/agent-hono/handlers/toolResult.ts b/src/server/agent-hono/handlers/toolResult.ts
new file mode 100644
index 00000000000..6dd5068bb59
--- /dev/null
+++ b/src/server/agent-hono/handlers/toolResult.ts
@@ -0,0 +1,68 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+import { z } from 'zod';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const log = debug('lobe-server:agent:tool-result');
+
+const TOOL_RESULT_TTL_SECONDS = 120;
+
+const ToolResultBodySchema = z.object({
+ content: z.string().nullable(),
+ error: z
+ .object({
+ message: z.string(),
+ type: z.string().optional(),
+ })
+ .optional(),
+ success: z.boolean(),
+ toolCallId: z.string().min(1),
+});
+
+/**
+ * Receive a tool execution result from agent-gateway, originating from a
+ * client that executed a server-dispatched `tool_execute`. The result is
+ * LPUSH'd into a per-toolCallId list so the server-side agent loop's BLPOP
+ * can wake up and continue.
+ *
+ * Auth: `serviceTokenAuth` on the route (gateway is the only trusted caller).
+ * Idempotency is not required β€” BLPOP pops the first available value;
+ * duplicates sit under TTL until they expire.
+ */
+export async function toolResult(c: Context): Promise<Response> {
+ let parsed;
+ try {
+ const body = await c.req.json();
+ parsed = ToolResultBodySchema.safeParse(body);
+ } catch {
+ return c.json({ error: 'Invalid JSON' }, 400);
+ }
+
+ if (!parsed.success) {
+ return c.json({ error: 'Invalid body', issues: parsed.error.issues }, 400);
+ }
+
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) {
+ log('Redis is not available');
+ return c.json({ error: 'Redis unavailable' }, 503);
+ }
+
+ const { toolCallId } = parsed.data;
+ const key = `tool_result:${toolCallId}`;
+
+ try {
+ await redis
+ .pipeline()
+ .lpush(key, JSON.stringify(parsed.data))
+ .expire(key, TOOL_RESULT_TTL_SECONDS)
+ .exec();
+ log('Persisted tool result for %s (success=%s)', toolCallId, parsed.data.success);
+ } catch (error) {
+ log('Failed to LPUSH tool result for %s: %O', toolCallId, error);
+ return c.json({ error: 'Redis write failed' }, 503);
+ }
+
+ return c.body(null, 204);
+}
diff --git a/src/server/agent-hono/index.ts b/src/server/agent-hono/index.ts
new file mode 100644
index 00000000000..db1123c3213
--- /dev/null
+++ b/src/server/agent-hono/index.ts
@@ -0,0 +1,36 @@
+import { Hono } from 'hono';
+
+import { execAgent } from './handlers/execAgent';
+import { finalizeAbandoned } from './handlers/finalizeAbandoned';
+import { toolResult } from './handlers/toolResult';
+import { qstashOrApiKeyAuth } from './middlewares/qstashOrApiKeyAuth';
+import { serviceTokenAuth } from './middlewares/serviceTokenAuth';
+
+/**
+ * Hono app for `/api/agent/*` endpoints. Mounted via the Next.js optional
+ * catch-all at `src/app/(backend)/api/agent/[[...route]]/route.ts`.
+ *
+ * Routing precedence: existing static `route.ts` files (e.g. `run/route.ts`,
+ * `stream/route.ts`, `gateway/*`, `webhooks/*`) win over the catch-all, so
+ * individual paths can migrate one at a time β€” delete the static `route.ts`
+ * and add the corresponding handler here.
+ */
+const app = new Hono().basePath('/api/agent');
+
+// POST /api/agent β€” start a new agent operation (QStash sig OR API key)
+app.post('/', qstashOrApiKeyAuth(), execAgent);
+
+// POST /api/agent/tool-result β€” gateway-side tool result LPUSH'd to Redis
+app.post('/tool-result', serviceTokenAuth(), toolResult);
+
+// POST /api/agent/finalize-abandoned β€” watchdog reverse-trigger finalize
+app.post('/finalize-abandoned', serviceTokenAuth(), finalizeAbandoned);
+app.get('/finalize-abandoned', (c) =>
+ c.json({
+ healthy: true,
+ message: 'Agent finalize-abandoned endpoint is running',
+ timestamp: new Date().toISOString(),
+ }),
+);
+
+export default app;
diff --git a/src/server/agent-hono/middlewares/qstashOrApiKeyAuth.ts b/src/server/agent-hono/middlewares/qstashOrApiKeyAuth.ts
new file mode 100644
index 00000000000..507dbe7aa06
--- /dev/null
+++ b/src/server/agent-hono/middlewares/qstashOrApiKeyAuth.ts
@@ -0,0 +1,39 @@
+import debug from 'debug';
+import type { MiddlewareHandler } from 'hono';
+
+import { verifyQStashSignature } from '@/libs/qstash';
+
+const log = debug('lobe-server:agent:qstash-or-apikey-auth');
+
+/**
+ * Hono middleware that accepts either a valid QStash signature **or** a
+ * matching `Authorization: Bearer <AGENT_EXEC_API_KEY>` token. Either passes.
+ *
+ * Mirrors the dual-path auth that lived inline in the old
+ * `src/app/(backend)/api/agent/route.ts`. Used by `execAgent` so QStash
+ * scheduled invocations and trusted external callers can both reach it.
+ *
+ * - When `AGENT_EXEC_API_KEY` is unset, the API-key path is disabled and
+ * only the QStash signature can authorize the request.
+ * - The body is consumed via `c.req.text()` to compute the QStash HMAC;
+ * downstream handlers can still call `c.req.json()` thanks to Hono's
+ * bodyCache cross-conversion.
+ */
+export const qstashOrApiKeyAuth = (): MiddlewareHandler => async (c, next) => {
+ const rawBody = await c.req.text();
+ const isValidQStash = await verifyQStashSignature(c.req.raw, rawBody);
+
+ const apiKey = process.env.AGENT_EXEC_API_KEY;
+ let isValidApiKey = false;
+ if (apiKey) {
+ const authHeader = c.req.header('authorization');
+ isValidApiKey = authHeader === `Bearer ${apiKey}`;
+ }
+
+ if (!isValidQStash && !isValidApiKey) {
+ log('Rejected: neither QStash sig nor API key matched on %s', c.req.path);
+ return c.json({ error: 'Unauthorized - Valid QStash signature or API key required' }, 401);
+ }
+
+ await next();
+};
diff --git a/src/server/agent-hono/middlewares/serviceTokenAuth.ts b/src/server/agent-hono/middlewares/serviceTokenAuth.ts
new file mode 100644
index 00000000000..8798832055e
--- /dev/null
+++ b/src/server/agent-hono/middlewares/serviceTokenAuth.ts
@@ -0,0 +1,34 @@
+import debug from 'debug';
+import type { MiddlewareHandler } from 'hono';
+
+import { appEnv } from '@/envs/app';
+
+const log = debug('lobe-server:agent:service-token-auth');
+
+/**
+ * Hono middleware that authenticates requests against
+ * `AGENT_GATEWAY_SERVICE_TOKEN` via the `Authorization: Bearer <token>` header.
+ *
+ * Use for endpoints whose only trusted caller is the agent-gateway worker
+ * (e.g. tool-result, finalize-abandoned). Mirror of the per-route check in
+ * `app/(backend)/api/agent/tool-result/route.ts`.
+ *
+ * - Returns `503 Service not configured` when the env var is unset (matches
+ * the existing tool-result behavior β€” agent gateway should never be talking
+ * to a server with no token).
+ * - Returns `401 Unauthorized` on header mismatch.
+ */
+export const serviceTokenAuth = (): MiddlewareHandler => async (c, next) => {
+ const serviceToken = appEnv.AGENT_GATEWAY_SERVICE_TOKEN;
+ if (!serviceToken) {
+ log('AGENT_GATEWAY_SERVICE_TOKEN is not configured');
+ return c.json({ error: 'Service not configured' }, 503);
+ }
+
+ const authHeader = c.req.header('authorization');
+ if (authHeader !== `Bearer ${serviceToken}`) {
+ return c.json({ error: 'Unauthorized' }, 401);
+ }
+
+ await next();
+};
diff --git a/src/server/services/agentRuntime/AbandonOperationService.ts b/src/server/services/agentRuntime/AbandonOperationService.ts
new file mode 100644
index 00000000000..3b7909ebb03
--- /dev/null
+++ b/src/server/services/agentRuntime/AbandonOperationService.ts
@@ -0,0 +1,147 @@
+import type { ISnapshotStore } from '@lobechat/agent-tracing';
+import type { ChatMessageError } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import debug from 'debug';
+
+import { MessageModel } from '@/database/models/message';
+import type { LobeChatDatabase } from '@/database/type';
+// Direct file import (not the barrel) to avoid pulling in RuntimeExecutors and
+// its workspace-package transitive deps in the unit-test environment.
+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';
+
+import { OperationTraceRecorder } from './OperationTraceRecorder';
+
+const log = debug('lobe-server:abandon-operation');
+
+interface AbandonOperationOptions {
+ coordinator?: AgentRuntimeCoordinator;
+ snapshotStore?: ISnapshotStore | null;
+}
+
+export interface FinalizeAbandonedResult {
+ /** Whether the assistant message was successfully marked as errored. */
+ assistantMessageUpdated: boolean;
+ /** Whether the operation was finalized into a snapshot (false if no partial existed). */
+ finalized: boolean;
+ /** Whether agent state was found in Redis. */
+ found: boolean;
+}
+
+/**
+ * Reverse-trigger finalization for an operation whose Vercel function was
+ * killed mid-flight. Invoked from a fresh function invocation (e.g. from the
+ * agent-gateway DO inactivity watchdog) given just an `operationId`.
+ *
+ * Loads the agent state from Redis, marks it as errored, runs the same
+ * `OperationTraceRecorder.finalize()` path the in-loop error handler would
+ * have run, and updates the dangling assistant message in DB.
+ *
+ * Idempotent: calling twice is a no-op the second time because `finalize()`
+ * removes the partial, so `loadAgentState` may return null or finalize will
+ * skip due to missing partial.
+ */
+export class AbandonOperationService {
+ private readonly coordinator: AgentRuntimeCoordinator;
+ private readonly snapshotStore: ISnapshotStore | null;
+ private readonly traceRecorder: OperationTraceRecorder;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ options?: AbandonOperationOptions,
+ ) {
+ this.coordinator = options?.coordinator ?? new AgentRuntimeCoordinator();
+ this.snapshotStore =
+ options?.snapshotStore !== undefined ? options.snapshotStore : createDefaultSnapshotStore();
+ this.traceRecorder = new OperationTraceRecorder(this.snapshotStore);
+ }
+
+ async finalizeAbandoned(operationId: string, reason: string): Promise<FinalizeAbandonedResult> {
+ const result: FinalizeAbandonedResult = {
+ assistantMessageUpdated: false,
+ finalized: false,
+ found: false,
+ };
+
+ const state = await this.coordinator.loadAgentState(operationId);
+ if (!state) {
+ log('[%s] no agent state in coordinator β€” already cleaned up', operationId);
+ return result;
+ }
+ result.found = true;
+
+ const metadata = (state.metadata ?? {}) as { assistantMessageId?: string; userId?: string };
+ const message = `Operation abandoned: ${reason}`;
+ const error: ChatMessageError = {
+ body: { message },
+ message,
+ type: AgentRuntimeErrorType.AgentRuntimeError,
+ };
+
+ // Synthesize a failed-step record at index = lastCompleted + 1 so consumers
+ // see the operation ended at a step that never produced data.
+ const partial = this.snapshotStore
+ ? await this.snapshotStore.loadPartial(operationId).catch(() => null)
+ : null;
+ const lastStepIndex = partial?.steps?.length
+ ? Math.max(...partial.steps.map((s) => s.stepIndex))
+ : -1;
+ const failedStep = { startedAt: Date.now(), stepIndex: lastStepIndex + 1 };
+
+ // Mutate state for finalize β€” recorder reads cost / tokens / metadata off this.
+ const finalState = { ...state, error, status: 'error' as const };
+
+ if (this.snapshotStore) {
+ await this.traceRecorder.finalize(operationId, {
+ completionReason: 'error',
+ error: { message, type: String(error.type) },
+ failedStep,
+ state: finalState,
+ });
+ // finalize swallows its own errors via try/catch, so we treat reaching
+ // this line as success. If the partial was missing we still mark the
+ // assistant message β€” that's the more important user-visible signal.
+ result.finalized = partial !== null;
+ }
+
+ if (metadata.userId && metadata.assistantMessageId) {
+ try {
+ const messageModel = new MessageModel(this.db, metadata.userId);
+ await messageModel.update(metadata.assistantMessageId, { error });
+ result.assistantMessageUpdated = true;
+ } catch (e) {
+ log('[%s] assistant message update failed (non-fatal): %O', operationId, e);
+ }
+ }
+
+ try {
+ await this.coordinator.deleteAgentOperation(operationId);
+ } catch (e) {
+ log('[%s] coordinator cleanup failed (non-fatal): %O', operationId, e);
+ }
+
+ log('[%s] abandoned op finalized (reason=%s): %O', operationId, reason, result);
+ return result;
+ }
+}
+
+function createDefaultSnapshotStore(): ISnapshotStore | null {
+ if (process.env.ENABLE_AGENT_S3_TRACING === '1') {
+ try {
+ const { S3SnapshotStore } = require('@/server/modules/AgentTracing');
+ return new S3SnapshotStore();
+ } catch {
+ /* S3SnapshotStore not available */
+ }
+ }
+
+ if (process.env.NODE_ENV === 'development') {
+ try {
+ const { FileSnapshotStore } = require('@lobechat/agent-tracing');
+ return new FileSnapshotStore();
+ } catch {
+ /* agent-tracing not available */
+ }
+ }
+
+ return null;
+}
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index ee5df77c701..06ab7c07d7b 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -30,6 +30,7 @@ import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
import { isAbortError, throwIfAborted } from './abort';
import { hookDispatcher } from './hooks';
+import { OperationTraceRecorder } from './OperationTraceRecorder';
import {
type AgentExecutionParams,
type AgentExecutionResult,
@@ -153,7 +154,7 @@ export class AgentRuntimeService {
private coordinator: AgentRuntimeCoordinator;
private streamManager: IStreamEventManager;
private queueService: QueueService | null;
- private snapshotStore: ISnapshotStore | null;
+ private traceRecorder: OperationTraceRecorder;
private toolExecutionService: ToolExecutionService;
private get baseURL() {
const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';
@@ -176,7 +177,9 @@ export class AgentRuntimeService {
});
this.queueService =
options?.queueService === null ? null : (options?.queueService ?? new QueueService());
- this.snapshotStore = options?.snapshotStore ?? this.createDefaultSnapshotStore();
+ this.traceRecorder = new OperationTraceRecorder(
+ options?.snapshotStore ?? this.createDefaultSnapshotStore(),
+ );
this.agentFactory = options?.agentFactory;
this.serverDB = db;
this.userId = userId;
@@ -882,113 +885,17 @@ export class AgentRuntimeService {
log('[%s] afterStep hook dispatch error: %O', operationId, hookError);
}
- // Record step snapshot via injected snapshot store
- if (this.snapshotStore) {
- try {
- const partial = (await this.snapshotStore.loadPartial(operationId)) ?? { steps: [] };
-
- if (!partial.startedAt) {
- partial.startedAt = Date.now();
- partial.model =
- (agentState?.metadata as any)?.agentConfig?.model ??
- agentState?.modelRuntimeConfig?.model;
- partial.provider =
- (agentState?.metadata as any)?.agentConfig?.provider ??
- agentState?.modelRuntimeConfig?.provider;
- }
-
- if (!partial.steps) partial.steps = [];
-
- // Incremental diff: only store message delta + baseline at reset points
- const prevMessages = agentState?.messages ?? [];
- const afterMessages = stepResult.newState.messages;
- const isCompression = stepResult.events?.some(
- (e: any) => e.type === 'compression_complete',
- );
- const isBaseline = stepIndex === 0 || isCompression;
- // Always store only the newly added messages, even for baseline steps
- const messagesDelta = afterMessages.slice(prevMessages.length);
-
- // Strip heavy/redundant data from events before persisting to snapshot
- const snapshotEvents = [
- ...beforeStepSignalEvents,
- ...((stepResult.events as any[])
- ?.filter((e) => e.type !== 'llm_stream')
- .map((e) => {
- if (e.type === 'done' && e.finalState) {
- // Remove reconstructible fields from finalState:
- // - messages: from messagesBaseline + messagesDelta chain
- // - operationToolSet: from toolsetBaseline (step 0)
- // - toolManifestMap/tools/toolSourceMap: backward-compat copies of operationToolSet
- const {
- messages: _msgs,
- operationToolSet: _ots,
- toolManifestMap: _tmm,
- toolSourceMap: _tsm,
- tools: _tools,
- // activatedStepTools is kept since it's the cumulative record
- ...restState
- } = e.finalState;
- return { ...e, finalState: restState };
- }
- return e;
- }) ?? []),
- ...afterStepSignalEvents,
- ];
-
- // Strip toolResults from payload (already in step.toolsResult)
- let snapshotPayload: unknown = currentContext?.payload;
- if (
- snapshotPayload &&
- typeof snapshotPayload === 'object' &&
- 'toolResults' in snapshotPayload
- ) {
- const { toolResults: _tr, ...restPayload } = snapshotPayload as Record<string, unknown>;
- snapshotPayload = restPayload;
- }
-
- // Compute activatedStepTools delta (newly discovered tools in this step)
- const prevActivated = agentState?.activatedStepTools ?? [];
- const afterActivated = stepResult.newState.activatedStepTools ?? [];
- const activatedStepToolsDelta =
- afterActivated.length > prevActivated.length
- ? afterActivated.slice(prevActivated.length)
- : undefined;
-
- partial.steps.push({
- activatedStepToolsDelta,
- completedAt: Date.now(),
- content: stepPresentationData.content,
- context: {
- payload: snapshotPayload,
- phase: currentContext?.phase ?? 'unknown',
- stepContext: currentContext?.stepContext,
- },
- events: snapshotEvents,
- externalRetryCount,
- executionTimeMs: stepPresentationData.executionTimeMs,
- inputTokens: stepPresentationData.stepInputTokens,
- isCompressionReset: isCompression || undefined,
- messagesBaseline: isBaseline ? prevMessages : undefined,
- messagesDelta,
- outputTokens: stepPresentationData.stepOutputTokens,
- reasoning: stepPresentationData.reasoning,
- startedAt: startAt,
- stepIndex,
- stepType: stepPresentationData.stepType,
- // Store operation-level toolset once at step 0
- toolsetBaseline: stepIndex === 0 ? agentState?.operationToolSet : undefined,
- toolsCalling: stepPresentationData.toolsCalling,
- toolsResult: stepPresentationData.toolsResult,
- totalCost: stepPresentationData.totalCost,
- totalTokens: stepPresentationData.totalTokens,
- });
-
- await this.snapshotStore.savePartial(operationId, partial);
- } catch (e) {
- log('[%s] snapshot step recording failed: %O', operationId, e);
- }
- }
+ await this.traceRecorder.appendStep(operationId, {
+ afterStepSignalEvents,
+ agentState,
+ beforeStepSignalEvents,
+ currentContext,
+ externalRetryCount,
+ presentation: stepPresentationData,
+ startedAt: startAt,
+ stepIndex,
+ stepResult,
+ });
// Update step tracking in state metadata for afterStep hooks (cross-step accumulator)
const hasAfterStepHooks = stepResult.newState.metadata?._hooks?.some(
@@ -1056,9 +963,9 @@ export class AgentRuntimeService {
await this.dispatchCompletionHooks(operationId, stepResult.newState, reason);
// Finalize tracing snapshot. The error catch below uses the same
- // helper so propagated failures still write the canonical S3
+ // recorder so propagated failures still write the canonical S3
// snapshot instead of orphaning the partial (LOBE-8533).
- await this.finalizeSnapshotForOperation(operationId, {
+ await this.traceRecorder.finalize(operationId, {
appendEventsToLastStep: completionSignalEvents,
completionReason: reason,
error: stepResult.newState.error
@@ -1157,7 +1064,7 @@ export class AgentRuntimeService {
// 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, {
+ await this.traceRecorder.finalize(operationId, {
completionReason: 'error',
error: {
message: formattedError.message ?? String(formattedError.type),
@@ -1989,123 +1896,6 @@ 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/OperationTraceRecorder.ts b/src/server/services/agentRuntime/OperationTraceRecorder.ts
new file mode 100644
index 00000000000..ed4dabf2c3f
--- /dev/null
+++ b/src/server/services/agentRuntime/OperationTraceRecorder.ts
@@ -0,0 +1,284 @@
+import type { ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
+import debug from 'debug';
+
+import type { StepCompletionReason, StepPresentationData } from './types';
+
+const log = debug('lobe-server:operation-trace-recorder');
+
+type SignalEvent = { [key: string]: unknown; type: string };
+
+export interface AppendStepParams {
+ afterStepSignalEvents: SignalEvent[];
+ /**
+ * Agent state BEFORE this step ran. Used to derive the message baseline,
+ * activatedStepTools delta, and the partial header (model / provider).
+ */
+ agentState: any;
+ beforeStepSignalEvents: SignalEvent[];
+ currentContext?: { payload?: unknown; phase?: string; stepContext?: unknown };
+ externalRetryCount: number;
+ presentation: StepPresentationData;
+ startedAt: number;
+ stepIndex: number;
+ /**
+ * Result of running this step. Carries new messages, raw events, and the
+ * post-step activatedStepTools list.
+ */
+ stepResult: { events?: unknown[]; newState: any };
+}
+
+export interface FinalizeParams {
+ /**
+ * 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?: SignalEvent[];
+ completionReason: StepCompletionReason;
+ error?: { message: string; type: string };
+ /**
+ * Synthetic step record for the error path. The real failing step never
+ * reached `appendStep` because the executor threw before the partial push,
+ * so the catch caller passes this to keep step counts aligned with the
+ * assistant message that triggered the call. See LOBE-8533.
+ */
+ failedStep?: { startedAt: number; stepIndex: number };
+ state: any;
+}
+
+/**
+ * Encapsulates per-operation trace snapshot accumulation and finalization.
+ *
+ * Built on top of an `ISnapshotStore` (S3 in production, file-system in dev).
+ * The recorder owns:
+ * - Partial header init (model / provider on first step)
+ * - Per-step incremental message diffing + heavy-event stripping
+ * - Finalize into the canonical S3 path on completion or error
+ *
+ * Callers don't need to gate on `enabled` β€” when the underlying store is null,
+ * methods are no-ops.
+ */
+export class OperationTraceRecorder {
+ constructor(private readonly store: ISnapshotStore | null) {}
+
+ get enabled(): boolean {
+ return this.store !== null;
+ }
+
+ async appendStep(operationId: string, params: AppendStepParams): Promise<void> {
+ if (!this.store) return;
+
+ try {
+ const partial = (await this.store.loadPartial(operationId)) ?? { steps: [] };
+
+ this.initPartialHeader(partial, params.agentState);
+
+ if (!partial.steps) partial.steps = [];
+ partial.steps.push(this.buildStepSnapshot(params));
+
+ await this.store.savePartial(operationId, partial);
+ } catch (e) {
+ log('[%s] snapshot step recording failed: %O', operationId, e);
+ }
+ }
+
+ async finalize(operationId: string, params: FinalizeParams): Promise<void> {
+ if (!this.store) return;
+
+ try {
+ const partial = await this.store.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 here β€” the
+ // surrounding `events: [{type: 'error'}]` is the discriminant
+ // consumers 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.store.save(snapshot as any);
+ await this.store.removePartial(operationId);
+ } catch (e) {
+ log('[%s] snapshot finalize failed (reason=%s): %O', operationId, params.completionReason, e);
+ }
+ }
+
+ private initPartialHeader(partial: any, agentState: any): void {
+ if (partial.startedAt) return;
+ partial.startedAt = Date.now();
+ partial.model =
+ (agentState?.metadata as any)?.agentConfig?.model ?? agentState?.modelRuntimeConfig?.model;
+ partial.provider =
+ (agentState?.metadata as any)?.agentConfig?.provider ??
+ agentState?.modelRuntimeConfig?.provider;
+ }
+
+ private buildStepSnapshot(params: AppendStepParams): StepSnapshot {
+ const {
+ agentState,
+ afterStepSignalEvents,
+ beforeStepSignalEvents,
+ currentContext,
+ externalRetryCount,
+ presentation,
+ startedAt,
+ stepIndex,
+ stepResult,
+ } = params;
+
+ // Incremental diff: only store message delta + baseline at reset points.
+ const prevMessages = agentState?.messages ?? [];
+ const afterMessages = stepResult.newState.messages;
+ const isCompression = (stepResult.events as any[])?.some(
+ (e) => e.type === 'compression_complete',
+ );
+ const isBaseline = stepIndex === 0 || isCompression;
+ const messagesDelta = afterMessages.slice(prevMessages.length);
+
+ // Strip heavy/redundant data from events before persisting to snapshot.
+ const snapshotEvents = [
+ ...beforeStepSignalEvents,
+ ...((stepResult.events as any[])
+ ?.filter((e) => e.type !== 'llm_stream')
+ .map((e) => {
+ if (e.type === 'done' && e.finalState) {
+ // Remove reconstructible fields from finalState:
+ // - messages: from messagesBaseline + messagesDelta chain
+ // - operationToolSet: from toolsetBaseline (step 0)
+ // - toolManifestMap/tools/toolSourceMap: backward-compat copies of operationToolSet
+ const {
+ messages: _msgs,
+ operationToolSet: _ots,
+ toolManifestMap: _tmm,
+ toolSourceMap: _tsm,
+ tools: _tools,
+ // activatedStepTools is kept since it's the cumulative record
+ ...restState
+ } = e.finalState;
+ return { ...e, finalState: restState };
+ }
+ return e;
+ }) ?? []),
+ ...afterStepSignalEvents,
+ ];
+
+ // Strip toolResults from payload (already in step.toolsResult).
+ let snapshotPayload: unknown = currentContext?.payload;
+ if (
+ snapshotPayload &&
+ typeof snapshotPayload === 'object' &&
+ 'toolResults' in snapshotPayload
+ ) {
+ const { toolResults: _tr, ...restPayload } = snapshotPayload as Record<string, unknown>;
+ snapshotPayload = restPayload;
+ }
+
+ // Compute activatedStepTools delta (newly discovered tools in this step).
+ const prevActivated = agentState?.activatedStepTools ?? [];
+ const afterActivated = stepResult.newState.activatedStepTools ?? [];
+ const activatedStepToolsDelta =
+ afterActivated.length > prevActivated.length
+ ? afterActivated.slice(prevActivated.length)
+ : undefined;
+
+ return {
+ activatedStepToolsDelta,
+ completedAt: Date.now(),
+ content: presentation.content,
+ context: {
+ payload: snapshotPayload,
+ phase: currentContext?.phase ?? 'unknown',
+ stepContext: currentContext?.stepContext,
+ },
+ events: snapshotEvents,
+ executionTimeMs: presentation.executionTimeMs,
+ externalRetryCount,
+ inputTokens: presentation.stepInputTokens,
+ isCompressionReset: isCompression || undefined,
+ messagesBaseline: isBaseline ? prevMessages : undefined,
+ messagesDelta,
+ outputTokens: presentation.stepOutputTokens,
+ reasoning: presentation.reasoning,
+ startedAt,
+ stepIndex,
+ stepType: presentation.stepType,
+ // Store operation-level toolset once at step 0
+ toolsetBaseline: stepIndex === 0 ? agentState?.operationToolSet : undefined,
+ toolsCalling: presentation.toolsCalling,
+ toolsResult: presentation.toolsResult,
+ totalCost: presentation.totalCost,
+ totalTokens: presentation.totalTokens,
+ };
+ }
+}
diff --git a/src/server/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/src/server/services/agentRuntime/__tests__/AbandonOperationService.test.ts
new file mode 100644
index 00000000000..eba41cc3f2c
--- /dev/null
+++ b/src/server/services/agentRuntime/__tests__/AbandonOperationService.test.ts
@@ -0,0 +1,206 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AbandonOperationService } from '../AbandonOperationService';
+
+const buildStore = () => ({
+ get: vi.fn(),
+ getLatest: vi.fn(),
+ list: vi.fn(),
+ listPartials: vi.fn(),
+ loadPartial: vi.fn(),
+ removePartial: vi.fn().mockResolvedValue(undefined),
+ save: vi.fn().mockResolvedValue(undefined),
+ savePartial: vi.fn().mockResolvedValue(undefined),
+});
+
+const buildCoordinator = (
+ overrides: Partial<{
+ loadAgentState: ReturnType<typeof vi.fn>;
+ deleteAgentOperation: ReturnType<typeof vi.fn>;
+ }> = {},
+) => ({
+ loadAgentState: vi.fn(),
+ deleteAgentOperation: vi.fn().mockResolvedValue(undefined),
+ ...overrides,
+});
+
+const messageUpdateMock = vi.fn().mockResolvedValue({ success: true });
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({ update: messageUpdateMock })),
+}));
+
+const stateWith = (overrides: Record<string, any> = {}) => ({
+ cost: { total: 0.1 },
+ metadata: {
+ agentId: 'agt_x',
+ assistantMessageId: 'msg_assist_1',
+ topicId: 'tpc_x',
+ userId: 'user_x',
+ },
+ status: 'running',
+ stepCount: 5,
+ usage: { llm: { tokens: { total: 1000 } } },
+ ...overrides,
+});
+
+describe('AbandonOperationService', () => {
+ beforeEach(() => {
+ messageUpdateMock.mockClear();
+ });
+
+ it('returns found:false when coordinator has no state', async () => {
+ const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });
+ const store = buildStore();
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_missing', 'inactivity_5m');
+
+ expect(result).toEqual({
+ assistantMessageUpdated: false,
+ finalized: false,
+ found: false,
+ });
+ expect(store.save).not.toHaveBeenCalled();
+ expect(messageUpdateMock).not.toHaveBeenCalled();
+ });
+
+ it('finalizes snapshot and marks assistant message errored when state + partial exist', async () => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue({
+ model: 'deepseek-v4-pro',
+ provider: 'lobehub',
+ startedAt: 1_777_991_958_128,
+ steps: [
+ { stepIndex: 0, stepType: 'call_llm' },
+ { stepIndex: 1, stepType: 'call_tool' },
+ ],
+ });
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
+
+ expect(result.found).toBe(true);
+ expect(result.finalized).toBe(true);
+ expect(result.assistantMessageUpdated).toBe(true);
+
+ // Final snapshot saved
+ expect(store.save).toHaveBeenCalledTimes(1);
+ const saved = store.save.mock.calls[0][0];
+ expect(saved.operationId).toBe('op_x');
+ expect(saved.error?.type).toBe('AgentRuntimeError');
+ expect(saved.error?.message).toContain('inactivity_5m');
+ expect(saved.completionReason).toBe('error');
+ // failedStep synthesized at lastIndex+1
+ expect(saved.steps).toHaveLength(3);
+ const synth = saved.steps[2];
+ expect(synth.stepIndex).toBe(2);
+ expect(synth.events?.[0]?.type).toBe('error');
+
+ // Partial cleaned up
+ expect(store.removePartial).toHaveBeenCalledWith('op_x');
+
+ // Assistant message updated
+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {
+ error: expect.objectContaining({
+ message: expect.stringContaining('inactivity_5m'),
+ type: 'AgentRuntimeError',
+ }),
+ });
+
+ // Coordinator state cleaned
+ expect(coord.deleteAgentOperation).toHaveBeenCalledWith('op_x');
+ });
+
+ it('skips snapshot finalize when no partial exists but still updates message', async () => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue(null);
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_x', 'inactivity_5m');
+
+ expect(result.found).toBe(true);
+ expect(result.finalized).toBe(false); // partial was missing
+ expect(result.assistantMessageUpdated).toBe(true);
+ expect(store.save).not.toHaveBeenCalled();
+ expect(messageUpdateMock).toHaveBeenCalled();
+ });
+
+ it('synthesizes failedStep at index 0 when partial has zero steps', async () => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue({ steps: [], startedAt: 1 });
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ await svc.finalizeAbandoned('op_x', 'reason');
+
+ const saved = store.save.mock.calls[0][0];
+ expect(saved.steps).toHaveLength(1);
+ expect(saved.steps[0].stepIndex).toBe(0);
+ });
+
+ it('does not crash when state has no metadata.assistantMessageId', async () => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith({ metadata: { userId: 'user_x' } })),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }], startedAt: 1 });
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ const result = await svc.finalizeAbandoned('op_x', 'reason');
+
+ expect(result.found).toBe(true);
+ expect(result.finalized).toBe(true);
+ expect(result.assistantMessageUpdated).toBe(false);
+ expect(messageUpdateMock).not.toHaveBeenCalled();
+ });
+
+ it('treats non-fatal errors during message update / coordinator cleanup as best-effort', async () => {
+ const coord = buildCoordinator({
+ loadAgentState: vi.fn().mockResolvedValue(stateWith()),
+ deleteAgentOperation: vi.fn().mockRejectedValue(new Error('redis down')),
+ });
+ const store = buildStore();
+ store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }], startedAt: 1 });
+ messageUpdateMock.mockRejectedValueOnce(new Error('db down'));
+
+ const svc = new AbandonOperationService({} as any, {
+ coordinator: coord as any,
+ snapshotStore: store as any,
+ });
+
+ // Should not throw β€” both failure paths are caught & logged
+ const result = await svc.finalizeAbandoned('op_x', 'reason');
+
+ expect(result.found).toBe(true);
+ expect(result.finalized).toBe(true);
+ expect(result.assistantMessageUpdated).toBe(false);
+ });
+});
diff --git a/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
new file mode 100644
index 00000000000..263e5d61c2d
--- /dev/null
+++ b/src/server/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
@@ -0,0 +1,377 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { OperationTraceRecorder } from '../OperationTraceRecorder';
+import type { StepPresentationData } from '../types';
+
+const buildStore = () => ({
+ get: vi.fn(),
+ getLatest: vi.fn(),
+ list: vi.fn(),
+ listPartials: vi.fn(),
+ loadPartial: vi.fn(),
+ removePartial: vi.fn().mockResolvedValue(undefined),
+ save: vi.fn().mockResolvedValue(undefined),
+ savePartial: vi.fn().mockResolvedValue(undefined),
+});
+
+const buildPresentation = (overrides: Partial<StepPresentationData> = {}): StepPresentationData =>
+ ({
+ content: 'hello',
+ executionTimeMs: 100,
+ reasoning: undefined,
+ stepType: 'call_llm' as const,
+ thinking: false,
+ toolsCalling: undefined,
+ toolsResult: undefined,
+ totalCost: 0,
+ totalInputTokens: 0,
+ totalOutputTokens: 0,
+ totalSteps: 1,
+ totalTokens: 100,
+ ...overrides,
+ }) as StepPresentationData;
+
+describe('OperationTraceRecorder', () => {
+ describe('appendStep', () => {
+ let store: ReturnType<typeof buildStore>;
+ let recorder: OperationTraceRecorder;
+
+ beforeEach(() => {
+ store = buildStore();
+ recorder = new OperationTraceRecorder(store as any);
+ });
+
+ it('initializes the partial header (model + provider + startedAt) on the first append', async () => {
+ store.loadPartial.mockResolvedValue(null);
+
+ await recorder.appendStep('op-1', {
+ afterStepSignalEvents: [],
+ agentState: {
+ messages: [],
+ metadata: { agentConfig: { model: 'claude-sonnet-4-6', provider: 'lobehub' } },
+ },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'user_input' },
+ externalRetryCount: 0,
+ presentation: buildPresentation(),
+ startedAt: 1_777_960_000_000,
+ stepIndex: 0,
+ stepResult: { events: [], newState: { activatedStepTools: [], messages: [] } },
+ });
+
+ const saved = store.savePartial.mock.calls[0][1];
+ expect(saved.model).toBe('claude-sonnet-4-6');
+ expect(saved.provider).toBe('lobehub');
+ expect(typeof saved.startedAt).toBe('number');
+ expect(saved.steps).toHaveLength(1);
+ });
+
+ it('strips llm_stream events and prunes finalState on done events', async () => {
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [] });
+
+ const events = [
+ { type: 'llm_stream', chunk: 'noise' },
+ { type: 'tool_result', id: 'tc-1' },
+ {
+ finalState: {
+ activatedStepTools: [{ id: 'kept' }],
+ messages: ['heavy'],
+ operationToolSet: { manifestMap: {} },
+ otherStateField: 'kept',
+ toolManifestMap: {},
+ toolSourceMap: {},
+ tools: [],
+ },
+ reason: 'done',
+ type: 'done',
+ },
+ ];
+
+ await recorder.appendStep('op-2', {
+ afterStepSignalEvents: [],
+ agentState: { messages: [] },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'tool_result' },
+ externalRetryCount: 0,
+ presentation: buildPresentation(),
+ startedAt: 100,
+ stepIndex: 1,
+ stepResult: { events, newState: { activatedStepTools: [], messages: [] } },
+ });
+
+ const step = store.savePartial.mock.calls[0][1].steps[0];
+ const eventTypes = step.events.map((e: any) => e.type);
+ expect(eventTypes).not.toContain('llm_stream');
+ expect(eventTypes).toContain('done');
+
+ const doneEvent = step.events.find((e: any) => e.type === 'done');
+ expect(doneEvent.finalState.activatedStepTools).toEqual([{ id: 'kept' }]);
+ expect(doneEvent.finalState.otherStateField).toBe('kept');
+ expect(doneEvent.finalState.messages).toBeUndefined();
+ expect(doneEvent.finalState.operationToolSet).toBeUndefined();
+ expect(doneEvent.finalState.toolManifestMap).toBeUndefined();
+ expect(doneEvent.finalState.toolSourceMap).toBeUndefined();
+ expect(doneEvent.finalState.tools).toBeUndefined();
+ });
+
+ it('emits messagesDelta-only beyond step 0 and only stores messagesBaseline when isCompression', async () => {
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [] });
+
+ const prevMessages = [{ role: 'user' }, { role: 'assistant' }];
+ const afterMessages = [...prevMessages, { role: 'tool' }];
+
+ await recorder.appendStep('op-3', {
+ afterStepSignalEvents: [],
+ agentState: { messages: prevMessages },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'tool_result' },
+ externalRetryCount: 0,
+ presentation: buildPresentation({ stepType: 'call_tool' }),
+ startedAt: 200,
+ stepIndex: 5,
+ stepResult: { events: [], newState: { activatedStepTools: [], messages: afterMessages } },
+ });
+
+ const step = store.savePartial.mock.calls[0][1].steps[0];
+ expect(step.messagesDelta).toEqual([{ role: 'tool' }]);
+ expect(step.messagesBaseline).toBeUndefined();
+ expect(step.isCompressionReset).toBeUndefined();
+ });
+
+ it('marks compression resets and persists messagesBaseline at the reset point', async () => {
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [] });
+
+ const prevMessages = [{ role: 'user' }];
+ const afterMessages = [{ role: 'system', summary: true }, { role: 'user' }];
+
+ await recorder.appendStep('op-4', {
+ afterStepSignalEvents: [],
+ agentState: { messages: prevMessages },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'user_input' },
+ externalRetryCount: 0,
+ presentation: buildPresentation(),
+ startedAt: 300,
+ stepIndex: 7,
+ stepResult: {
+ events: [{ type: 'compression_complete' }],
+ newState: { activatedStepTools: [], messages: afterMessages },
+ },
+ });
+
+ const step = store.savePartial.mock.calls[0][1].steps[0];
+ expect(step.isCompressionReset).toBe(true);
+ expect(step.messagesBaseline).toEqual(prevMessages);
+ });
+
+ it('records activatedStepToolsDelta when new tools are activated mid-step', async () => {
+ store.loadPartial.mockResolvedValue({ startedAt: 1, steps: [] });
+
+ await recorder.appendStep('op-5', {
+ afterStepSignalEvents: [],
+ agentState: { activatedStepTools: [{ id: 'a' }], messages: [] },
+ beforeStepSignalEvents: [],
+ currentContext: { phase: 'tool_result' },
+ externalRetryCount: 0,
+ presentation: buildPresentation({ stepType: 'call_tool' }),
+ startedAt: 400,
+ stepIndex: 2,
+ stepResult: {
+ events: [],
+ newState: { activatedStepTools: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], messages: [] },
+ },
+ });
+
+ const step = store.savePartial.mock.calls[0][1].steps[0];
+ expect(step.activatedStepToolsDelta).toEqual([{ id: 'b' }, { id: 'c' }]);
+ });
+ });
+
+ describe('finalize', () => {
+ let store: ReturnType<typeof buildStore>;
+ let recorder: OperationTraceRecorder;
+
+ beforeEach(() => {
+ store = buildStore();
+ recorder = new OperationTraceRecorder(store as any);
+ });
+
+ it('writes the canonical snapshot and removes the partial on success', async () => {
+ store.loadPartial.mockResolvedValue({
+ model: 'claude-sonnet-4-6',
+ provider: 'lobehub',
+ startedAt: 1000,
+ steps: [
+ {
+ completedAt: 1100,
+ executionTimeMs: 100,
+ startedAt: 1000,
+ stepIndex: 0,
+ stepType: 'call_llm',
+ totalCost: 0,
+ totalTokens: 50,
+ },
+ ],
+ });
+
+ await recorder.finalize('op-done', {
+ completionReason: 'done',
+ state: {
+ cost: { total: 0.5 },
+ metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'u-1' },
+ stepCount: 1,
+ usage: { llm: { tokens: { total: 200 } } },
+ },
+ });
+
+ expect(store.save).toHaveBeenCalledTimes(1);
+ const saved = store.save.mock.calls[0][0];
+ expect(saved).toMatchObject({
+ agentId: 'agt-1',
+ completionReason: 'done',
+ operationId: 'op-done',
+ topicId: 'tpc-1',
+ totalCost: 0.5,
+ totalSteps: 1,
+ totalTokens: 200,
+ userId: 'u-1',
+ });
+ expect(store.removePartial).toHaveBeenCalledWith('op-done');
+ });
+
+ it('appends a synthetic failed step when called from the error path', async () => {
+ store.loadPartial.mockResolvedValue({
+ startedAt: 1000,
+ steps: [{ stepIndex: 0, stepType: 'call_llm' }],
+ });
+
+ await recorder.finalize('op-err', {
+ completionReason: 'error',
+ error: { message: 'parent missing', type: 'ConversationParentMissing' },
+ failedStep: { startedAt: 5000, stepIndex: 1 },
+ state: { cost: { total: 0 }, metadata: {}, usage: { llm: { tokens: { total: 100 } } } },
+ });
+
+ const saved = store.save.mock.calls[0][0];
+ const failed = saved.steps.find((s: any) => s.stepIndex === 1);
+ expect(failed).toBeDefined();
+ expect(failed.stepType).toBe('call_tool');
+ expect(failed.events?.[0]).toMatchObject({
+ error: { message: 'parent missing', type: 'ConversationParentMissing' },
+ type: 'error',
+ });
+ expect(saved.error).toMatchObject({ type: 'ConversationParentMissing' });
+ expect(saved.completionReason).toBe('error');
+ });
+
+ it('merges the error event into an existing step when stepIndex collides (success-path append landed before later failure)', async () => {
+ // The success path may have already pushed step 1 to the partial before
+ // a later failure (e.g. saveAgentState throws post-append). The recorder
+ // must NOT duplicate stepIndex=1; it should attach the error event to
+ // the existing record.
+ store.loadPartial.mockResolvedValue({
+ startedAt: 1000,
+ steps: [
+ { events: [{ type: 'llm_result' }], stepIndex: 0, stepType: 'call_llm' },
+ {
+ events: [{ type: 'tool_result' }],
+ stepIndex: 1,
+ stepType: 'call_tool',
+ },
+ ],
+ });
+
+ await recorder.finalize('op-collide', {
+ completionReason: 'error',
+ error: { message: 'redis down', type: 'RedisError' },
+ failedStep: { startedAt: 5000, stepIndex: 1 },
+ state: { metadata: {}, stepCount: 2 },
+ });
+
+ const saved = store.save.mock.calls[0][0];
+ const matching = saved.steps.filter((s: any) => s.stepIndex === 1);
+ expect(matching).toHaveLength(1);
+ // Original tool_result event preserved + new error event appended.
+ const eventTypes = matching[0].events.map((e: any) => e.type);
+ expect(eventTypes).toEqual(['tool_result', 'error']);
+ });
+
+ it('reports totalSteps from the finalized step array, not state.stepCount, on the error path', async () => {
+ // After appending a synthetic failed step (e.g. step 1 from the catch
+ // path), state.stepCount comes from Redis and reflects the last
+ // *completed* step (0). Trusting it here would under-count by one.
+ store.loadPartial.mockResolvedValue({
+ startedAt: 1000,
+ steps: [{ stepIndex: 0, stepType: 'call_llm' }],
+ });
+
+ await recorder.finalize('op-stepcount', {
+ completionReason: 'error',
+ error: { message: 'boom', type: 'InternalServerError' },
+ failedStep: { startedAt: 5000, stepIndex: 1 },
+ state: { metadata: {}, stepCount: 0 },
+ });
+
+ const saved = store.save.mock.calls[0][0];
+ expect(saved.totalSteps).toBe(2);
+ });
+
+ it('skips finalize entirely when no partial exists (op never recorded a step)', async () => {
+ store.loadPartial.mockResolvedValue(null);
+
+ await recorder.finalize('op-empty', {
+ completionReason: 'error',
+ state: { metadata: {} },
+ });
+
+ expect(store.save).not.toHaveBeenCalled();
+ expect(store.removePartial).not.toHaveBeenCalled();
+ });
+
+ it('appends extra signal events to the last step before save', async () => {
+ store.loadPartial.mockResolvedValue({
+ startedAt: 1000,
+ steps: [{ events: [{ type: 'llm_result' }], stepIndex: 0, stepType: 'call_llm' }],
+ });
+
+ await recorder.finalize('op-signal', {
+ appendEventsToLastStep: [{ payload: { foo: 1 }, type: 'agent_signal_complete' }],
+ completionReason: 'done',
+ state: { metadata: {} },
+ });
+
+ const saved = store.save.mock.calls[0][0];
+ const lastStep = saved.steps[0];
+ const signalEvent = lastStep.events.find((e: any) => e.type === 'agent_signal_complete');
+ expect(signalEvent).toBeDefined();
+ expect(signalEvent.payload).toEqual({ foo: 1 });
+ });
+ });
+
+ describe('store=null (snapshot tracing disabled)', () => {
+ it('appendStep is a no-op', async () => {
+ const recorder = new OperationTraceRecorder(null);
+ expect(recorder.enabled).toBe(false);
+ await expect(
+ recorder.appendStep('op-x', {
+ afterStepSignalEvents: [],
+ agentState: {},
+ beforeStepSignalEvents: [],
+ externalRetryCount: 0,
+ presentation: buildPresentation(),
+ startedAt: 0,
+ stepIndex: 0,
+ stepResult: { events: [], newState: { messages: [] } },
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('finalize is a no-op', async () => {
+ const recorder = new OperationTraceRecorder(null);
+ await expect(
+ recorder.finalize('op-x', { completionReason: 'done', state: {} }),
+ ).resolves.toBeUndefined();
+ });
+ });
+});
diff --git a/src/server/services/agentRuntime/index.ts b/src/server/services/agentRuntime/index.ts
index 8159114d6ff..17158473a78 100644
--- a/src/server/services/agentRuntime/index.ts
+++ b/src/server/services/agentRuntime/index.ts
@@ -1,2 +1,3 @@
+export * from './AbandonOperationService';
export * from './AgentRuntimeService';
export * from './types';