🤯 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): stabilize QStash step startup (#16829)
Arvin Xuc05d4bccfa3e
diff --git a/apps/server/src/services/queue/__tests__/QueueService.test.ts b/apps/server/src/services/queue/__tests__/QueueService.test.tsindex 8be60e6dcc0..dc50277dc51 100644--- a/apps/server/src/services/queue/__tests__/QueueService.test.ts+++ b/apps/server/src/services/queue/__tests__/QueueService.test.ts@@ -6,18 +6,32 @@ const mockAppEnv = {enableQueueAgentRuntime: false,};+const qstashMocks = vi.hoisted(() => ({+ client: vi.fn(),+ publishJSON: vi.fn(),+}));+vi.mock('@/envs/app', () => ({appEnv: mockAppEnv,}));+vi.mock('@/libs/qstash', () => ({+ OtelQstashClient: qstashMocks.client.mockImplementation(() => ({+ publishJSON: qstashMocks.publishJSON,+ })),+}));+describe('QueueService', () => {beforeEach(() => {vi.resetModules();// Reset to default local modemockAppEnv.enableQueueAgentRuntime = false;+ qstashMocks.client.mockClear();+ qstashMocks.publishJSON.mockReset();});afterEach(() => {+ vi.useRealTimers();vi.clearAllMocks();});@@ -146,6 +160,50 @@ describe('QueueService', () => {// Cleanupdelete process.env.QSTASH_TOKEN;});++ it('should wait locally for sub-second QStash delays before publishing', async () => {+ vi.useFakeTimers();+ qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });++ const { QStashQueueServiceImpl } = await import('../impls/qstash');+ const impl = new QStashQueueServiceImpl({ qstashToken: 'test-qstash-token' });+ const result = impl.scheduleMessage({+ context: { phase: 'user_input' } as any,+ delay: 50,+ endpoint: 'https://example.com/api/agent/run',+ operationId: 'op-test',+ priority: 'high',+ stepIndex: 0,+ });++ await vi.advanceTimersByTimeAsync(49);+ expect(qstashMocks.publishJSON).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(1);+ await expect(result).resolves.toBe('msg-test');++ const request = qstashMocks.publishJSON.mock.calls[0][0];+ expect(request).not.toHaveProperty('delay');+ expect(request.body.timestamp).toEqual(expect.any(Number));+ });++ it('should pass second-granularity delays through to QStash', async () => {+ qstashMocks.publishJSON.mockResolvedValue({ messageId: 'msg-test' });++ const { QStashQueueServiceImpl } = await import('../impls/qstash');+ const impl = new QStashQueueServiceImpl({ qstashToken: 'test-qstash-token' });++ await impl.scheduleMessage({+ context: { phase: 'user_input' } as any,+ delay: 1500,+ endpoint: 'https://example.com/api/agent/run',+ operationId: 'op-test',+ priority: 'high',+ stepIndex: 0,+ });++ expect(qstashMocks.publishJSON.mock.calls[0][0]).toMatchObject({ delay: 2 });+ });});describe('isQueueAgentRuntimeEnabled', () => {diff --git a/apps/server/src/services/queue/impls/qstash.ts b/apps/server/src/services/queue/impls/qstash.tsindex 528e52e42a7..8c88e957a78 100644--- a/apps/server/src/services/queue/impls/qstash.ts+++ b/apps/server/src/services/queue/impls/qstash.ts@@ -7,6 +7,15 @@ import { type QueueServiceImpl } from './type';const log = debug('lobe-server:service:queue:qstash');+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++const toQStashDelaySeconds = (delayMs: number): number | undefined => {+ if (delayMs <= 0) return undefined;+ if (delayMs < 1000) return undefined;++ return Math.round(delayMs / 1000);+};+/*** QStash queue service implementation*/@@ -35,8 +44,17 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {} = message;try {+ // QStash publish delays are second-granularity (`10s`, `1m`, or numeric+ // seconds). Preserve the runtime's small settling windows, such as the+ // initial 50ms, by waiting before publishing instead of collapsing them to+ // immediate delivery.+ if (delay > 0 && delay < 1000) {+ await sleep(delay);+ }+log('Initialized QStash queue service');const qstashClient = new OtelQstashClient({ token: this.config.qstashToken });+ const qstashDelay = toQStashDelaySeconds(delay);const request = {body: {context,@@ -46,10 +64,7 @@ export class QStashQueueServiceImpl implements QueueServiceImpl {stepIndex,timestamp: Date.now(),},- // QStash delay granularity is whole seconds, so sub-second step delays- // can't be expressed. Ceiling them up padded every step to a full second;- // instead dispatch immediately (0) and only delay for >= 1s intents.- delay: delay >= 1000 ? Math.round(delay / 1000) : 0,+ ...(qstashDelay === undefined ? {} : { delay: qstashDelay }),headers: {'Content-Type': 'application/json','X-Agent-Operation-Id': operationId,diff --git a/src/server/agent-hono/handlers/__tests__/runStep.test.ts b/src/server/agent-hono/handlers/__tests__/runStep.test.tsindex ba0c7f138f8..4cae3fa6837 100644--- a/src/server/agent-hono/handlers/__tests__/runStep.test.ts+++ b/src/server/agent-hono/handlers/__tests__/runStep.test.ts@@ -7,6 +7,7 @@ import { runStep, runStepHealth } from '../runStep';const mockGetOperationMetadata = vi.fn();const mockExecuteStep = vi.fn();+const mockGetServerDB = vi.hoisted(() => vi.fn());vi.mock('@/server/modules/AgentRuntime', () => ({AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({@@ -21,10 +22,27 @@ vi.mock('@/server/services/aiAgent', () => ({}));vi.mock('@/database/core/db-adaptor', () => ({- getServerDB: vi.fn().mockResolvedValue({} as any),+ getServerDB: mockGetServerDB,}));-function buildContext(opts: { body?: unknown; jsonThrows?: boolean; retried?: string }) {+function buildOperationDiagnosticDB(row?: any) {+ return {+ select: vi.fn(() => ({+ from: vi.fn(() => ({+ where: vi.fn(() => ({+ limit: vi.fn().mockResolvedValue(row ? [row] : []),+ })),+ })),+ })),+ };+}++function buildContext(opts: {+ body?: unknown;+ jsonThrows?: boolean;+ messageId?: string;+ retried?: string;+}) {const captures: Array<{ body: any; status: number; headers?: Record<string, string> }> = [];const ctx = {json: (b: any, status = 200, headers?: Record<string, string>) => {@@ -32,8 +50,12 @@ function buildContext(opts: { body?: unknown; jsonThrows?: boolean; retried?: streturn Response.json(b, { status, headers });},req: {- header: (name: string) =>- name.toLowerCase() === 'upstash-retried' ? opts.retried : undefined,+ header: (name: string) => {+ const normalized = name.toLowerCase();+ if (normalized === 'upstash-retried') return opts.retried;+ if (normalized === 'upstash-message-id') return opts.messageId;+ return undefined;+ },json: opts.jsonThrows? async () => {throw new Error('bad json');@@ -54,6 +76,7 @@ describe('runStep handler', () => {beforeEach(() => {mockGetOperationMetadata.mockReset();mockExecuteStep.mockReset();+ mockGetServerDB.mockResolvedValue({} as any);});afterEach(() => {@@ -77,6 +100,16 @@ describe('runStep handler', () => {it('returns 401 when operation metadata has no userId', async () => {mockGetOperationMetadata.mockResolvedValue(null);+ mockGetServerDB.mockResolvedValue(+ buildOperationDiagnosticDB({+ completedAt: null,+ startedAt: new Date('2026-07-07T03:23:44.015Z'),+ status: 'running',+ stepCount: null,+ traceS3Key: null,+ }),+ );+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});const { ctx, getCaptures } = buildContext({ body: validBody });const res = await runStep(ctx);@@ -84,6 +117,48 @@ describe('runStep handler', () => {expect(res.status).toBe(401);expect(getCaptures()[0].body).toEqual({ error: 'Invalid operation or unauthorized' });expect(mockExecuteStep).not.toHaveBeenCalled();+ expect(JSON.parse(warnSpy.mock.calls[0][0])).toMatchObject({+ dbRow: {+ exists: true,+ startedAt: '2026-07-07T03:23:44.015Z',+ status: 'running',+ stepCount: null,+ traceS3KeyPresent: false,+ },+ event: 'agent.run_step.missing_operation_metadata',+ metadataPresent: false,+ operationId: 'op-1',+ stepIndex: 2,+ upstashRetried: null,+ });+ warnSpy.mockRestore();+ });++ it('includes QStash retry and message IDs in missing metadata diagnostics', async () => {+ mockGetOperationMetadata.mockResolvedValue({});+ mockGetServerDB.mockResolvedValue(buildOperationDiagnosticDB());+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const { ctx } = buildContext({+ body: validBody,+ messageId: 'msg-123',+ retried: '3',+ });++ await runStep(ctx);++ expect(JSON.parse(warnSpy.mock.calls[0][0])).toMatchObject({+ dbRow: {+ exists: false,+ status: null,+ },+ metadataHasUserId: false,+ metadataPresent: true,+ operationId: 'op-1',+ qstashMessageId: 'msg-123',+ stepIndex: 2,+ upstashRetried: '3',+ });+ warnSpy.mockRestore();});it('steps through AiAgentService scoped to the operation workspace', async () => {diff --git a/src/server/agent-hono/handlers/runStep.ts b/src/server/agent-hono/handlers/runStep.tsindex ffec2325685..2736ee6f163 100644--- a/src/server/agent-hono/handlers/runStep.ts+++ b/src/server/agent-hono/handlers/runStep.ts@@ -1,12 +1,57 @@import debug from 'debug';+import { eq } from 'drizzle-orm';import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';+import { agentOperations } from '@/database/schemas/agentOperations';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';import { AiAgentService } from '@/server/services/aiAgent';const log = debug('lobe-server:agent:run-step');+const toIsoString = (value: Date | string | null | undefined): null | string => {+ if (!value) return null;+ if (value instanceof Date) return value.toISOString();+ return value;+};++const getQStashMessageId = (c: Context): string | undefined =>+ c.req.header('upstash-message-id') ??+ c.req.header('upstash-messageid') ??+ c.req.header('message-id');++async function getOperationRowDiagnostic(operationId: string) {+ try {+ const serverDB = await getServerDB();+ const [row] = await serverDB+ .select({+ completedAt: agentOperations.completedAt,+ startedAt: agentOperations.startedAt,+ status: agentOperations.status,+ stepCount: agentOperations.stepCount,+ traceS3Key: agentOperations.traceS3Key,+ })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);++ return {+ completedAt: toIsoString(row?.completedAt),+ exists: Boolean(row),+ startedAt: toIsoString(row?.startedAt),+ status: row?.status ?? null,+ stepCount: row?.stepCount ?? null,+ traceS3KeyPresent: Boolean(row?.traceS3Key),+ };+ } catch (error) {+ return {+ error: error instanceof Error ? error.message : String(error),+ exists: null,+ status: null,+ };+ }+}+/*** Execute a single agent step. Invoked by QStash with the body* `{ operationId, stepIndex, context, humanInput?, approvedToolCall?, ... }`.@@ -58,7 +103,20 @@ export async function runStep(c: Context): Promise<Response> {const metadata = await coordinator.getOperationMetadata(operationId);if (!metadata?.userId) {- log(`[${operationId}] Invalid operation or no userId found`);+ const dbRow = await getOperationRowDiagnostic(operationId);+ const diagnostic = {+ dbRow,+ event: 'agent.run_step.missing_operation_metadata',+ metadataHasUserId: Boolean(metadata?.userId),+ metadataPresent: Boolean(metadata),+ operationId,+ qstashMessageId: getQStashMessageId(c),+ stepIndex,+ upstashRetried: c.req.header('upstash-retried') ?? null,+ };++ log(`[${operationId}] Invalid operation or no userId found: %O`, diagnostic);+ console.warn(JSON.stringify(diagnostic));return c.json({ error: 'Invalid operation or unauthorized' }, 401);}