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.

πŸ› fix(topic-auto-summary): stop dispatch crashing on the second page (#18165)

Arvin Xu42a7e1d09d14
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
index 81122b7b099..4fc09db39bd 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/hourly.test.ts
@@ -1,6 +1,8 @@
import { AsyncTaskStatus } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { hourlyWorkflowHandler } from '../hourly';
const mocks = vi.hoisted(() => ({
@@ -89,7 +91,7 @@ describe('hourlyWorkflowHandler', () => {
*/
const context = {
requestPayload: { dryRun: true },
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
workflowRunId: 'entry-hourly-run',
};
@@ -140,7 +142,7 @@ describe('hourlyWorkflowHandler', () => {
dryRun: true,
hourlyTaskId: '00000000-0000-4000-8000-000000000001',
},
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
};
await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({
@@ -174,7 +176,7 @@ describe('hourlyWorkflowHandler', () => {
const context = {
requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
};
await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({
@@ -207,7 +209,7 @@ describe('hourlyWorkflowHandler', () => {
const context = {
requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
};
await expect(hourlyWorkflowHandler(context as never)).resolves.toEqual({
@@ -225,7 +227,7 @@ describe('hourlyWorkflowHandler', () => {
const context = {
requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
};
await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/personaUpdate.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
index 4aa4827542d..4dd4011954e 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
const mocks = vi.hoisted(() => ({
buildUserPersonaJobInput: vi.fn(),
checkGuard: vi.fn(),
@@ -62,7 +64,7 @@ describe('personaUpdateHandler run guard', () => {
const context = {
requestPayload: { userIds: ['user-1'] },
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
workflowRunId: 'wfr_persona',
};
@@ -97,7 +99,7 @@ describe('personaUpdateHandler run guard', () => {
hourlyTaskId: '00000000-0000-4000-8000-000000000001',
userIds: ['user-1'],
},
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
workflowRunId: 'wfr_persona',
};
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts
index 363bf5715fc..d974817c00d 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processTopicHandler } from '../processTopic';
const mocks = vi.hoisted(() => ({
@@ -64,7 +66,7 @@ vi.mock('../runGuard', () => ({
const createContext = (requestPayload: Record<string, unknown>) => ({
requestPayload,
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
});
describe('processTopicHandler hourly task behavior', () => {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts
index fb35f6aed20..a32b9538789 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processTopicsHandler } from '../processTopics';
const mocks = vi.hoisted(() => ({
@@ -74,7 +76,7 @@ vi.mock('../runGuard', () => ({
const createContext = (requestPayload: Record<string, unknown>) => ({
requestPayload,
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
});
describe('processTopicsHandler hourly task behavior', () => {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts
index c66c0fe2e11..da486bf34e6 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processUserTopicsHandler } from '../processUserTopics';
const mocks = vi.hoisted(() => ({
@@ -64,7 +66,7 @@ vi.mock('../runGuard', () => ({
const createContext = (requestPayload: Record<string, unknown>) => ({
requestPayload,
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
});
describe('processUserTopicsHandler hourly task behavior', () => {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.test.ts
index d695a4f4246..5e1ee030b1d 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUserTopics.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processUserTopicsHandler } from '../processUserTopics';
const mocks = vi.hoisted(() => ({
@@ -49,7 +51,7 @@ vi.mock('../runGuard', () => ({
}));
const createContext = () => ({
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
});
const basePayload = {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts
index fa3eb263b9f..05608cfba83 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processUsersHandler } from '../processUsers';
const mocks = vi.hoisted(() => ({
@@ -63,7 +65,7 @@ vi.mock('../runGuard', () => ({
const createContext = (requestPayload: Record<string, unknown>) => ({
requestPayload,
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
});
describe('processUsersHandler hourly task behavior', () => {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.test.ts
index 0519c0ecb5f..d2f4228b55b 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/processUsers.test.ts
@@ -1,6 +1,8 @@
import { MemorySourceType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { processUsersHandler } from '../processUsers';
const mocks = vi.hoisted(() => ({
@@ -57,7 +59,7 @@ describe('processUsersHandler', () => {
dryRun: true,
sources: [MemorySourceType.ChatTopic],
},
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
} as never);
expect(result).toEqual({
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
index f6d2a2f21fb..9d83054836b 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/__tests__/runGuard.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
const mocks = vi.hoisted(() => ({
assertWorkflowRunAllowed: vi.fn(),
initializeRedis: vi.fn(),
@@ -28,7 +30,7 @@ const { checkGuard, ensureWorkflowStarted } = await import('../runGuard');
const createContext = (payload: unknown, workflowRunId = 'wfr_context') => ({
requestPayload: payload,
- run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ run: createStepRunner(),
workflowRunId,
});
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
index 15c9b2ac07d..174c5626f8e 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/hourly.ts
@@ -11,6 +11,7 @@ import {
MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { parseWorkflowDate, runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import {
@@ -56,7 +57,7 @@ export const hourlyWorkflowHandler = async (
});
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerHourlyTracked(
{
baseUrl,
@@ -86,7 +87,7 @@ export const hourlyWorkflowHandler = async (
});
if (!cancellationGuard.result) return cancellationGuard.response;
- const cancelled = await context.run(cancellationStepName, () =>
+ const cancelled = await runStep(context, cancellationStepName, () =>
isHourlyMemoryExtractionCancelled(hourlyTaskId),
);
if (cancelled) {
@@ -98,11 +99,14 @@ export const hourlyWorkflowHandler = async (
}
const parsedCursor = cursor
- ? { createdAt: new Date(cursor.createdAt), id: cursor.id }
+ ? {
+ createdAt: parseWorkflowDate(
+ cursor.createdAt,
+ 'Invalid cursor date for hourly memory extraction workflow',
+ ),
+ id: cursor.id,
+ }
: undefined;
- if (parsedCursor && Number.isNaN(parsedCursor.createdAt.getTime())) {
- throw new Error('Invalid cursor date for hourly memory extraction workflow');
- }
const executor = await MemoryExtractionExecutor.create();
const listUsersStepName = `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`;
@@ -112,7 +116,7 @@ export const hourlyWorkflowHandler = async (
});
if (!listUsersGuard.result) return listUsersGuard.response;
- const userBatch = await context.run(listUsersStepName, () =>
+ const userBatch = await runStep(context, listUsersStepName, () =>
executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),
);
@@ -144,7 +148,7 @@ export const hourlyWorkflowHandler = async (
});
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
buildWorkflowPayloadInput(
normalizeMemoryExtractionPayload({
@@ -170,7 +174,7 @@ export const hourlyWorkflowHandler = async (
});
if (!cancellationGuard.result) return cancellationGuard.response;
- const cancelled = await context.run(cancellationStepName, () =>
+ const cancelled = await runStep(context, cancellationStepName, () =>
isHourlyMemoryExtractionCancelled(hourlyTaskId),
);
if (cancelled) {
@@ -188,7 +192,7 @@ export const hourlyWorkflowHandler = async (
});
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerHourly(
{
baseUrl,
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/personaUpdate.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/personaUpdate.ts
index 3f0507f0a20..dc7cb694c50 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/personaUpdate.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/personaUpdate.ts
@@ -6,6 +6,7 @@ import {
buildUserPersonaJobInput,
UserPersonaService,
} from '@/server/services/memory/userMemory/persona/service';
+import { runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { isHourlyMemoryExtractionCancelled } from './utils';
@@ -34,7 +35,7 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
});
if (!parsePayloadGuard.result) return parsePayloadGuard.response;
- const payload = await context.run(parsePayloadStepName, () =>
+ const payload = await runStep(context, parsePayloadStepName, () =>
workflowPayloadSchema.parse(context.requestPayload || {}),
);
const db = await getServerDB();
@@ -55,7 +56,7 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
});
if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
- const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ const hourlyCancelled = await runStep(context, hourlyCancellationStepName, () =>
isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
);
if (hourlyCancelled) continue;
@@ -67,7 +68,7 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
});
if (!guard.result) return guard.response;
- await context.run(stepName, async () => {
+ await runStep(context, stepName, async () => {
const jobInput = await buildUserPersonaJobInput(db, userId);
const result = await service.composeWriting({ ...jobInput, userId });
return {
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopic.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopic.ts
index 338ab538686..11a8404e37c 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopic.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopic.ts
@@ -15,6 +15,7 @@ import {
MemoryExtractionExecutor,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { isHourlyMemoryExtractionCancelled } from './utils';
@@ -78,7 +79,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- const cancelled = await context.run(stepName, () =>
+ const cancelled = await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -103,7 +104,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- const hourlyCancelled = await context.run(stepName, () =>
+ const hourlyCancelled = await runStep(context, stepName, () =>
isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
);
if (hourlyCancelled) {
@@ -130,7 +131,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- await context.run(stepName, () =>
+ await runStep(context, stepName, () =>
executor.extractTopic({
asyncTaskId: payload.asyncTaskId,
forceAll: payload.forceAll,
@@ -158,7 +159,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- const hourlyCancelled = await context.run(stepName, () =>
+ const hourlyCancelled = await runStep(context, stepName, () =>
isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
);
if (hourlyCancelled) {
@@ -181,7 +182,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- const cancelled = await context.run(stepName, () =>
+ const cancelled = await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -210,7 +211,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- await context.run(stepName, () =>
+ await runStep(context, stepName, () =>
executor.extractTopic({
asyncTaskId: payload.asyncTaskId,
forceAll: payload.forceAll,
@@ -236,7 +237,7 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return guard.response;
}
- await context.run(stepName, () =>
+ await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopics.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopics.ts
index ed4c1531d17..c0ec8496d59 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopics.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processTopics.ts
@@ -16,6 +16,7 @@ import {
MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { appendHourlyWorkflowRunId, isHourlyMemoryExtractionCancelled } from './utils';
@@ -103,7 +104,7 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return guard.response;
}
- const cancelled = await context.run(stepName, () =>
+ const cancelled = await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -132,7 +133,7 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return hourlyCancellationGuard.response;
}
- const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ const hourlyCancelled = await runStep(context, hourlyCancellationStepName, () =>
isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
);
if (hourlyCancelled) {
@@ -160,7 +161,7 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return guard.response;
}
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerProcessTopic(
userId,
{
@@ -189,8 +190,10 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return hourlyPersonaCancellationGuard.response;
}
- const hourlyPersonaCancelled = await context.run(hourlyPersonaCancellationStepName, () =>
- isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ const hourlyPersonaCancelled = await runStep(
+ context,
+ hourlyPersonaCancellationStepName,
+ () => isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
);
if (hourlyPersonaCancelled) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -213,7 +216,7 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return personaUpdateGuard.response;
}
- const personaUpdateResult = await context.run(personaUpdateStepName, async () => {
+ const personaUpdateResult = await runStep(context, personaUpdateStepName, async () => {
return MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {
extraHeaders: upstashWorkflowExtraHeaders,
hourlyTaskId: payload.hourlyTaskId,
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts
index da5dc6d9d20..6687d9dde4c 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUserTopics.ts
@@ -13,6 +13,7 @@ import {
MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { parseWorkflowDate, runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { appendHourlyWorkflowRunId, isHourlyMemoryExtractionCancelled } from './utils';
@@ -89,7 +90,7 @@ export const processUserTopicsHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const cancelled = await context.run(stepName, () =>
+ const cancelled = await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -109,7 +110,7 @@ export const processUserTopicsHandler = async (
});
if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
- const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ const hourlyCancelled = await runStep(context, hourlyCancellationStepName, () =>
isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
);
if (hourlyCancelled) {
@@ -125,7 +126,10 @@ export const processUserTopicsHandler = async (
const topicCursor =
params.topicCursor && params.topicCursor.userId === userId
? {
- createdAt: new Date(params.topicCursor.createdAt),
+ createdAt: parseWorkflowDate(
+ params.topicCursor.createdAt,
+ 'Invalid topic cursor date in the process-user-topics payload',
+ ),
id: params.topicCursor.id,
}
: undefined;
@@ -136,7 +140,7 @@ export const processUserTopicsHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- topicsFromPayload = await context.run(stepName, async () => {
+ topicsFromPayload = await runStep(context, stepName, async () => {
const filtered = await activeExecutor.filterTopicIdsForUser(
userId,
params.topicIds,
@@ -152,10 +156,10 @@ export const processUserTopicsHandler = async (
});
if (!listTopicsGuard.result) return listTopicsGuard.response;
- const topicBatch = await context.run<{
+ const topicBatch = await runStep<{
cursor?: ListTopicsForMemoryExtractorCursor;
ids: string[];
- }>(listTopicsStepName, () =>
+ }>(context, listTopicsStepName, () =>
topicsFromPayload && topicsFromPayload.length > 0
? Promise.resolve({ ids: topicsFromPayload })
: activeExecutor.getTopicsForUser(
@@ -197,7 +201,7 @@ export const processUserTopicsHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerProcessTopics(
userId,
{
@@ -225,8 +229,10 @@ export const processUserTopicsHandler = async (
return hourlyNextPageCancellationGuard.response;
}
- const hourlyNextPageCancelled = await context.run(hourlyNextPageCancellationStepName, () =>
- isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
+ const hourlyNextPageCancelled = await runStep(
+ context,
+ hourlyNextPageCancellationStepName,
+ () => isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
);
if (hourlyNextPageCancelled) {
return {
@@ -241,17 +247,18 @@ export const processUserTopicsHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () => {
- // NOTICE: Upstash Workflow only supports serializable data into plain JSON,
- // this causes the Date object to be converted into string when passed as parameter from
- // context to child workflow. So we need to convert it back to Date object here.
- const createdAt = new Date(cursor.createdAt);
- if (Number.isNaN(createdAt.getTime())) {
- throw new Error('Invalid cursor date when scheduling next topic page');
- }
-
- return scheduleNextPage(userId, createdAt, cursor.id, nextFanoutCount);
- });
+ const result = await runStep(context, stepName, () =>
+ scheduleNextPage(
+ userId,
+ // The cursor crossed a step boundary, so its timestamp arrives as an ISO string.
+ parseWorkflowDate(
+ cursor.createdAt,
+ 'Invalid cursor date when scheduling next topic page',
+ ),
+ cursor.id,
+ nextFanoutCount,
+ ),
+ );
await appendHourlyWorkflowRunId(params.hourlyTaskId, result.workflowRunId);
}
}
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUsers.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUsers.ts
index 31c1c653c45..32bc69527f2 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUsers.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/processUsers.ts
@@ -4,13 +4,15 @@ import { chunk } from 'es-toolkit/compat';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
-import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';
import {
buildWorkflowPayloadInput,
MemoryExtractionExecutor,
+ type MemoryExtractionPayloadInput,
MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
+ type UserPaginationResult,
} from '@/server/services/memory/userMemory/extract';
+import { parseWorkflowDate, runStep } from '@/server/workflows/step';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
import {
@@ -48,7 +50,7 @@ export const processUsersHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const cancelled = await context.run(stepName, () =>
+ const cancelled = await runStep(context, stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -68,7 +70,7 @@ export const processUsersHandler = async (
});
if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
- const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ const hourlyCancelled = await runStep(context, hourlyCancellationStepName, () =>
isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
);
if (hourlyCancelled) {
@@ -84,14 +86,23 @@ export const processUsersHandler = async (
// this causes the Date object to be converted into string when passed as parameter from
// context to child workflow. So we need to convert it back to Date object here.
const userCursor = params.userCursor
- ? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }
+ ? {
+ createdAt: parseWorkflowDate(
+ params.userCursor.createdAt,
+ 'Invalid cursor date when reading the user page cursor',
+ ),
+ id: params.userCursor.id,
+ }
: undefined;
const getUsersStepName = 'memory:user-memory:extract:get-users';
const getUsersGuard = await checkGuard(context, WORKFLOW_PATH, { stepName: getUsersStepName });
if (!getUsersGuard.result) return getUsersGuard.response;
- const userBatch = await context.run(getUsersStepName, () =>
+ // NOTICE: the explicit type argument keeps both ternary branches on one shape. Left to inference
+ // the step returns a union, and `'cursor' in userBatch` then narrows against a member that has no
+ // `cursor` at all, which erases the cursor's own type.
+ const userBatch = await runStep<UserPaginationResult>(context, getUsersStepName, () =>
params.userIds.length > 0
? { ids: params.userIds }
: executor.getUsers(USER_PAGE_SIZE, userCursor),
@@ -120,7 +131,7 @@ export const processUsersHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUserTopics(
{
...buildWorkflowPayloadInput(params),
@@ -142,7 +153,7 @@ export const processUsersHandler = async (
});
if (!hourlyNextPageCancellationGuard.result) return hourlyNextPageCancellationGuard.response;
- const hourlyNextPageCancelled = await context.run(hourlyNextPageCancellationStepName, () =>
+ const hourlyNextPageCancelled = await runStep(context, hourlyNextPageCancellationStepName, () =>
isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
);
if (hourlyNextPageCancelled) {
@@ -158,7 +169,7 @@ export const processUsersHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- const result = await context.run(stepName, () =>
+ const result = await runStep(context, stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
{
...buildWorkflowPayloadInput({
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
index 43599b706cd..e2a62804b8f 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/runGuard.ts
@@ -4,6 +4,7 @@ import { getRedisConfig } from '@/envs/redis';
import { initializeRedis, isRedisEnabled } from '@/libs/redis';
import { type BaseRedisProvider } from '@/libs/redis/types';
import { assertWorkflowRunAllowed, WorkflowRunGuardError } from '@/server/workflows/runGuard';
+import { runStep } from '@/server/workflows/step';
const getRedis = async (): Promise<BaseRedisProvider | null> => {
const config = getRedisConfig();
@@ -133,7 +134,7 @@ export const ensureWorkflowStarted = (
workflowPath: string,
): Promise<{ started: true }> =>
Promise.resolve(
- context.run(`memory:user-memory:workflow-started:${workflowPath}`, () => ({
+ runStep(context, `memory:user-memory:workflow-started:${workflowPath}`, () => ({
started: true as const,
})),
);
@@ -163,7 +164,8 @@ export const checkGuard = async <
options: MemoryWorkflowRunGuardCheckOptions<TExtra> = {},
): Promise<MemoryWorkflowRunGuardCheck<TExtra>> => {
const { response, stepName } = options;
- const block = await context.run<MemoryWorkflowRunGuardBlock | null>(
+ const block = await runStep<MemoryWorkflowRunGuardBlock | null>(
+ context,
`memory:user-memory:run-guard:${workflowPath}:${stepName ?? 'entry'}`,
async () => {
const redis = await getRedis();
diff --git a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/utils.ts b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/utils.ts
index 619f79d8d87..0461331dcee 100644
--- a/apps/server/src/router-hono/workflows/memory-user-memory/workflows/utils.ts
+++ b/apps/server/src/router-hono/workflows/memory-user-memory/workflows/utils.ts
@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { asyncTasks } from '@/database/schemas';
import { getServerDB } from '@/database/server';
+import { parseWorkflowDate } from '@/server/workflows/step';
/**
* Cursor shape accepted by workflow pagination serializers.
@@ -42,18 +43,13 @@ export interface WorkflowCursorLike {
export const serializeWorkflowCursor = (
cursor: WorkflowCursorLike,
errorMessage = 'Invalid workflow cursor date',
-) => {
+) => ({
// NOTICE:
// Upstash Workflow persists step results as JSON and restores Date values as strings.
- // This cursor can come from a live DB result or a restored context.run result.
- // Keep accepting both shapes until workflow step serialization preserves Date objects.
- const createdAt = new Date(cursor.createdAt);
- if (Number.isNaN(createdAt.getTime())) {
- throw new Error(errorMessage);
- }
-
- return { createdAt: createdAt.toISOString(), id: cursor.id };
-};
+ // This cursor can come from a live DB result or a restored step result.
+ createdAt: parseWorkflowDate(cursor.createdAt, errorMessage).toISOString(),
+ id: cursor.id,
+});
/**
* Checks whether an hourly user-memory extraction task has requested cancellation.
diff --git a/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.test.ts b/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.test.ts
index f005e0435e6..4c414d3b3e7 100644
--- a/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.test.ts
+++ b/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStepRunner } from '@/server/workflows/testing/stepContext';
+
import { dispatchTopicAutoSummary } from './dispatch';
const mocks = vi.hoisted(() => ({
@@ -22,10 +24,7 @@ vi.mock('@/server/workflows/topicAutoSummary', () => ({
}));
const createContext = (requestPayload: Record<string, unknown>) =>
- ({
- requestPayload,
- run: vi.fn(async (_step: string, callback: () => unknown) => callback()),
- }) as never;
+ ({ requestPayload, run: createStepRunner() }) as never;
describe('dispatchTopicAutoSummary', () => {
beforeEach(() => {
@@ -144,4 +143,15 @@ describe('dispatchTopicAutoSummary', () => {
}),
);
});
+
+ it('rejects a malformed cursor instead of querying with an invalid date', async () => {
+ mocks.listCandidates.mockResolvedValue([]);
+
+ await expect(
+ dispatchTopicAutoSummary(
+ createContext({ cursor: { id: 'topic-1', lastMessageUpdatedAt: 'not-a-date' } }),
+ ),
+ ).rejects.toThrow('Invalid topic auto summary cursor timestamp');
+ expect(mocks.listCandidates).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.ts b/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.ts
index bbd06486855..a8a9591abb4 100644
--- a/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.ts
+++ b/apps/server/src/router-hono/workflows/topic-auto-summary/dispatch.ts
@@ -2,6 +2,7 @@ import type { WorkflowContext } from '@upstash/workflow';
import { TopicSummaryModel } from '@/database/models/topicSummary';
import { getServerDB } from '@/database/server';
+import { parseWorkflowDate, runStep } from '@/server/workflows/step';
import {
type DispatchTopicAutoSummaryPayload,
TopicAutoSummaryWorkflow,
@@ -36,14 +37,20 @@ export const dispatchTopicAutoSummary = async (
const remaining = Math.max(maxTopics - processed, 0);
if (remaining === 0) return { processed, scheduled: 0, truncated: true };
+ // `runStep` types the result the way the workflow receives it after Upstash's JSON round trip, so
+ // `lastMessageUpdatedAt` reads as the ISO string it actually is rather than the model's `Date`.
const listCandidates = async (cursor: DispatchTopicAutoSummaryPayload['cursor'], limit: number) =>
- context.run(`topic-auto-summary:list:${cursor?.id ?? 'root'}`, async () => {
+ runStep(context, `topic-auto-summary:list:${cursor?.id ?? 'root'}`, async () => {
const db = await getServerDB();
+
return new TopicSummaryModel(db).listCandidates({
cursor: cursor
? {
id: cursor.id,
- lastMessageUpdatedAt: new Date(cursor.lastMessageUpdatedAt),
+ lastMessageUpdatedAt: parseWorkflowDate(
+ cursor.lastMessageUpdatedAt,
+ 'Invalid topic auto summary cursor timestamp',
+ ),
}
: undefined,
force: payload.force,
@@ -67,7 +74,7 @@ export const dispatchTopicAutoSummary = async (
if (last && hasNextPage)
cursor = {
id: last.id,
- lastMessageUpdatedAt: last.lastMessageUpdatedAt.toISOString(),
+ lastMessageUpdatedAt: last.lastMessageUpdatedAt,
};
if (!last || !hasNextPage || candidates === remaining) break;
}
@@ -90,7 +97,7 @@ export const dispatchTopicAutoSummary = async (
await Promise.all(
candidates.map((candidate) =>
- context.run(`topic-auto-summary:schedule:${candidate.id}`, () =>
+ runStep(context, `topic-auto-summary:schedule:${candidate.id}`, () =>
TopicAutoSummaryWorkflow.triggerExecute({
force: payload.force,
topicId: candidate.id,
@@ -106,12 +113,12 @@ export const dispatchTopicAutoSummary = async (
const hasNextPage =
candidates.length === Math.min(pageSize, remaining) && nextProcessed < maxTopics;
if (last && hasNextPage) {
- await context.run(`topic-auto-summary:next:${last.id}`, () =>
+ await runStep(context, `topic-auto-summary:next:${last.id}`, () =>
TopicAutoSummaryWorkflow.triggerDispatch({
...payload,
cursor: {
id: last.id,
- lastMessageUpdatedAt: last.lastMessageUpdatedAt.toISOString(),
+ lastMessageUpdatedAt: last.lastMessageUpdatedAt,
},
processed: nextProcessed,
}),
diff --git a/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts
index 5c4e7872905..9cfd12b7918 100644
--- a/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts
+++ b/apps/server/src/router-hono/workflows/topic-auto-summary/execute.ts
@@ -2,6 +2,7 @@ import type { WorkflowContext } from '@upstash/workflow';
import { getServerDB } from '@/database/server';
import { TopicAutoSummaryService } from '@/server/services/topicAutoSummary';
+import { runStep } from '@/server/workflows/step';
import type { ExecuteTopicAutoSummaryPayload } from '@/server/workflows/topicAutoSummary';
export const executeTopicAutoSummary = async (
@@ -10,7 +11,7 @@ export const executeTopicAutoSummary = async (
const { force, topicId, userId, workspaceId } = context.requestPayload ?? {};
if (!topicId || !userId) return { error: 'Missing topicId or userId', summarized: false };
- return context.run('topic-auto-summary:generate-and-save', async () => {
+ return runStep(context, 'topic-auto-summary:generate-and-save', async () => {
const db = await getServerDB();
return new TopicAutoSummaryService(db, userId, workspaceId).summarize(topicId, { force });
});
diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.ts
index 0fb09e7ee7c..1a4895e40af 100644
--- a/apps/server/src/services/agentEvalRun/index.ts
+++ b/apps/server/src/services/agentEvalRun/index.ts
@@ -2118,7 +2118,11 @@ export class AgentEvalRunService {
config?: EvalRunConfig | null;
id: string;
metrics?: EvalRunMetrics | null;
- startedAt?: Date | null;
+ /**
+ * Accepts a string because the finalize-run workflow reads this row inside a step, and
+ * Upstash restores step results from JSON β€” the `Date` arrives as an ISO string.
+ */
+ startedAt?: Date | null | string;
};
runTopics: Array<{
evalResult?: EvalRunTopicResult | null;
diff --git a/apps/server/src/workflows/agentSignal/run.ts b/apps/server/src/workflows/agentSignal/run.ts
index a03b20497d8..3f423a5f389 100644
--- a/apps/server/src/workflows/agentSignal/run.ts
+++ b/apps/server/src/workflows/agentSignal/run.ts
@@ -43,6 +43,7 @@ import type { ClientRuntimeCompleteHydrationDiagnostic } from '@/server/services
import { resolveClientRuntimeCompleteFeedbackSource } from '@/server/services/agentSignal/sources/hydration/clientRuntimeComplete';
import type { ClientRuntimeStartHydrationDiagnostic } from '@/server/services/agentSignal/sources/hydration/clientRuntimeStart';
import { resolveClientRuntimeStartFeedbackSource } from '@/server/services/agentSignal/sources/hydration/clientRuntimeStart';
+import { runStep } from '@/server/workflows/step';
import type { AgentSignalWorkflowRunPayload } from './types';
@@ -609,7 +610,8 @@ export const runAgentSignalWorkflow = async (
workspaceId: payload.workspaceId,
})
: undefined;
- const executionResult = await context.run(
+ const executionResult = await runStep(
+ context,
`agent-signal:execute:${normalizedSourceEvent.sourceType}:${normalizedSourceEvent.sourceId}`,
() =>
executeSourceEvent(
diff --git a/apps/server/src/workflows/onboardingTaskRecommendation/process.test.ts b/apps/server/src/workflows/onboardingTaskRecommendation/process.test.ts
index a9964428e9f..c435c8ecd6f 100644
--- a/apps/server/src/workflows/onboardingTaskRecommendation/process.test.ts
+++ b/apps/server/src/workflows/onboardingTaskRecommendation/process.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
import { processOnboardingTaskRecommendations } from './process';
const payload = {
@@ -29,7 +31,7 @@ describe('processOnboardingTaskRecommendations', () => {
requestPayload: payload,
run: async <Result>(name: string, action: () => Promise<Result>) => {
steps.push(name);
- return action();
+ return serializeStepResult(await action());
},
};
diff --git a/apps/server/src/workflows/onboardingTaskRecommendation/process.ts b/apps/server/src/workflows/onboardingTaskRecommendation/process.ts
index 6660d1f20a7..a07624a7c4c 100644
--- a/apps/server/src/workflows/onboardingTaskRecommendation/process.ts
+++ b/apps/server/src/workflows/onboardingTaskRecommendation/process.ts
@@ -8,6 +8,7 @@ import {
type TaskRecommendationProviderResult,
type TaskRecommendationService,
} from '@/server/services/taskRecommendation/service';
+import { runStep } from '@/server/workflows/step';
import {
type ProcessOnboardingTaskRecommendationPayload,
@@ -47,7 +48,7 @@ export const processOnboardingTaskRecommendations = async (
) => {
const payload = ProcessOnboardingTaskRecommendationPayloadSchema.parse(context.requestPayload);
const service = await (dependencies.createService ?? createService)(payload.userId);
- const plan = await context.run('session:begin', () =>
+ const plan = await runStep(context, 'session:begin', () =>
service.begin(payload.topicId, payload.sessionId, payload.sourceFingerprint),
);
await publishOnboardingGenerationProgress(payload.userId, payload.topicId);
@@ -55,7 +56,8 @@ export const processOnboardingTaskRecommendations = async (
const results = await Promise.all(
plan.providerIds.map((providerId) =>
- context.run(
+ runStep(
+ context,
`provider:${providerId}:generate`,
async (): Promise<TaskRecommendationProviderResult> => {
try {
@@ -79,7 +81,7 @@ export const processOnboardingTaskRecommendations = async (
),
),
);
- const session = await context.run('session:commit', () =>
+ const session = await runStep(context, 'session:commit', () =>
service.commit(payload.topicId, payload.sessionId, results),
);
await publishOnboardingGenerationProgress(payload.userId, payload.topicId);
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processCollected.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processCollected.test.ts
index 379f7e14a6e..948cb4fa41e 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processCollected.test.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processCollected.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
import { failRunningUnderstandingWriting, processCollectedUnderstanding } from './processCollected';
const errors = vi.hoisted(() => {
@@ -34,7 +36,7 @@ const createContext = () => {
requestPayload: payload,
run: async <T>(stepName: string, action: () => Promise<T>) => {
steps.push(stepName);
- return action();
+ return serializeStepResult(await action());
},
},
steps,
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts b/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts
index 844ccb72759..cca346cbdd1 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processCollected.ts
@@ -14,6 +14,7 @@ import {
createUnderstandingService,
type UnderstandingService,
} from '@/server/services/understanding/service';
+import { runStep } from '@/server/workflows/step';
import {
type ProcessCollectedUnderstandingPayload,
@@ -53,7 +54,7 @@ export const processCollectedUnderstanding = async (
) => {
const payload = ProcessCollectedUnderstandingPayloadSchema.parse(context.requestPayload);
const service = await (dependencies.createService ?? createService)(payload.userId);
- const result = await context.run('collected:process', async () => {
+ const result = await runStep(context, 'collected:process', async () => {
try {
return await service.processCollected({
expectedSourceFingerprint: payload.sourceFingerprint,
@@ -71,7 +72,7 @@ export const processCollectedUnderstanding = async (
await publishOnboardingGenerationProgress(payload.userId, payload.topicId);
const triggerDetailedPersona = dependencies.triggerDetailedPersona;
if (result.published && triggerDetailedPersona) {
- await context.run('collected:trigger-detailed-persona', () =>
+ await runStep(context, 'collected:trigger-detailed-persona', () =>
triggerDetailedPersona(payload, {
workflowRunId: `onboarding-understanding-detailed-${createHash('sha256')
.update(payload.sessionId)
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts
index d0dfefaa16b..2cf82aa88c5 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
import {
failRunningDetailedUnderstandingPersona,
processDetailedUnderstandingPersona,
@@ -42,7 +44,7 @@ describe('processDetailedUnderstandingPersona', () => {
requestPayload: payload,
run: async <T>(stepName: string, action: () => Promise<T>) => {
steps.push(stepName);
- return action();
+ return serializeStepResult(await action());
},
};
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts
index eef0a6d0090..fbdf8ffb9d0 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processDetailedPersona.ts
@@ -12,6 +12,7 @@ import {
createUnderstandingService,
type UnderstandingService,
} from '@/server/services/understanding/service';
+import { runStep } from '@/server/workflows/step';
import {
type ProcessCollectedUnderstandingPayload,
@@ -65,7 +66,7 @@ export const processDetailedUnderstandingPersona = async (
) => {
const payload = ProcessCollectedUnderstandingPayloadSchema.parse(context.requestPayload);
const service = await (dependencies.createService ?? createService)(payload.userId);
- const result = await context.run('detailed-persona:process', async () => {
+ const result = await runStep(context, 'detailed-persona:process', async () => {
try {
return await service.processDetailedPersona({
expectedSourceFingerprint: payload.sourceFingerprint,
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts
index 554cd9bc708..a6216cd77f3 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.test.ts
@@ -1,6 +1,8 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
+import { serializeStepResult } from '@/server/workflows/testing/stepContext';
+
import {
failRunningUnderstandingProviders,
processUnderstandingProviders,
@@ -49,7 +51,7 @@ const createContext = (requestPayload: unknown) => {
requestPayload,
run: async <T>(stepName: string, action: () => Promise<T>) => {
steps.push(stepName);
- return action();
+ return serializeStepResult(await action());
},
},
invocations,
diff --git a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts b/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts
index 2acdc4c59cc..960fdea375a 100644
--- a/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts
+++ b/apps/server/src/workflows/onboardingUnderstanding/processProviders.ts
@@ -15,6 +15,7 @@ import {
} from '@/server/services/understanding/service';
import type { ProcessOnboardingTaskRecommendationPayload } from '@/server/workflows/onboardingTaskRecommendation';
import { getTaskRecommendationFlowControlKey } from '@/server/workflows/onboardingTaskRecommendation/types';
+import { runStep } from '@/server/workflows/step';
import {
getUnderstandingWritingFlowControlKey,
@@ -83,7 +84,7 @@ export const processUnderstandingProviders = async (
const providers = await Promise.all(
payload.providers.map(async ({ id: providerId, revision }) => {
- const result = await context.run(`provider:${providerId}:${revision}:process`, () =>
+ const result = await runStep(context, `provider:${providerId}:${revision}:process`, () =>
service.processProvider({
providerId,
revision,
@@ -115,7 +116,7 @@ export const processUnderstandingProviders = async (
];
if (payload.triggerTaskRecommendations !== false) {
downstreamTasks.push(
- context.run(`provider:${providerId}:recommend:${result.revision}`, () =>
+ runStep(context, `provider:${providerId}:recommend:${result.revision}`, () =>
// NOTICE:
// Cross-route workflow fan-out must use an absolute QStash trigger.
// context.invoke only replaces the current URL's final path segment, which sent this
diff --git a/apps/server/src/workflows/step.test.ts b/apps/server/src/workflows/step.test.ts
new file mode 100644
index 00000000000..4d113775fef
--- /dev/null
+++ b/apps/server/src/workflows/step.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseWorkflowDate, runStep, type WorkflowStepResult } from './step';
+import { createStepRunner } from './testing/stepContext';
+
+describe('runStep', () => {
+ it('types a step result the way the workflow receives it after the JSON round trip', async () => {
+ const context = { run: createStepRunner() };
+
+ const result = await runStep(context, 'load', () => ({
+ id: 'topic-1',
+ updatedAt: new Date('2026-07-31T10:00:00Z'),
+ }));
+
+ // The compiler now agrees with the runtime: `updatedAt` is a string on both sides.
+ const updatedAt: string = result.updatedAt;
+ expect(updatedAt).toBe('2026-07-31T10:00:00.000Z');
+ expect(context.run).toHaveBeenCalledWith('load', expect.any(Function));
+ });
+
+ it('maps nested and array timestamps, and leaves other values untouched', async () => {
+ const context = { run: createStepRunner() };
+
+ const result = await runStep(context, 'list', () => ({
+ cursor: { createdAt: new Date('2026-07-31T10:00:00Z'), id: 'user-1' },
+ enabled: true,
+ rows: [{ at: new Date('2026-07-31T11:00:00Z') }],
+ total: 2,
+ }));
+
+ const cursorCreatedAt: string = result.cursor.createdAt;
+ const rowAt: string = result.rows[0].at;
+ expect(cursorCreatedAt).toBe('2026-07-31T10:00:00.000Z');
+ expect(rowAt).toBe('2026-07-31T11:00:00.000Z');
+ expect(result.enabled).toBe(true);
+ expect(result.total).toBe(2);
+ });
+
+ it('passes an undefined step result through untouched', async () => {
+ const context = { run: createStepRunner() };
+
+ await expect(runStep(context, 'noop', () => undefined)).resolves.toBeUndefined();
+ });
+});
+
+describe('WorkflowStepResult', () => {
+ it('collapses Date to string while preserving the rest of the shape', () => {
+ type Candidate = { at: Date; nested: { since: Date | null }; tags: string[] };
+ type Serialized = WorkflowStepResult<Candidate>;
+
+ const value: Serialized = { at: 'iso', nested: { since: null }, tags: ['a'] };
+
+ expect(value.at).toBe('iso');
+ });
+});
+
+describe('parseWorkflowDate', () => {
+ it('accepts both a live Date and a round-tripped ISO string', () => {
+ const date = new Date('2026-07-31T10:00:00Z');
+
+ expect(parseWorkflowDate(date).toISOString()).toBe('2026-07-31T10:00:00.000Z');
+ expect(parseWorkflowDate('2026-07-31T10:00:00.000Z').toISOString()).toBe(
+ '2026-07-31T10:00:00.000Z',
+ );
+ });
+
+ it('throws a labelled error instead of letting an Invalid Date reach a query', () => {
+ expect(() => parseWorkflowDate('not-a-date', 'Invalid cursor')).toThrow(
+ 'Invalid cursor: not-a-date',
+ );
+ });
+});
diff --git a/apps/server/src/workflows/step.ts b/apps/server/src/workflows/step.ts
new file mode 100644
index 00000000000..c08bf96d258
--- /dev/null
+++ b/apps/server/src/workflows/step.ts
@@ -0,0 +1,90 @@
+import type { WorkflowContext } from '@upstash/workflow';
+
+/**
+ * A step result as it actually arrives on the consuming side of an Upstash Workflow step.
+ *
+ * Upstash persists every step result as JSON and restores it with `JSON.parse` on replay, so a
+ * `Date` returned from a step comes back as an ISO string. `context.run` types the result as the
+ * callback's return type, which hides that β€” the compiler believes it still holds a `Date`, and
+ * `result.someDate.toISOString()` compiles cleanly right up until it throws in production.
+ *
+ * NOTICE: this deliberately models only the `Date` β†’ `string` collapse, not every JSON effect
+ * (dropped `undefined` properties, `Map`/`Set` emptying). `type-fest`'s `Jsonify` models all of
+ * them, but it also degrades any type carrying an index signature into a loose `JsonObject`, which
+ * costs real precision at call sites that never had a serialization problem. Dates are the failure
+ * mode this codebase actually hits; widen this only when a second one shows up.
+ *
+ * Use when:
+ * - Annotating a helper that wraps a workflow step and returns its result
+ * - Declaring the payload shape a workflow stage receives from an earlier stage
+ */
+export type WorkflowStepResult<T> = T extends Date
+ ? string
+ : T extends (infer TItem)[]
+ ? WorkflowStepResult<TItem>[]
+ : T extends readonly (infer TItem)[]
+ ? readonly WorkflowStepResult<TItem>[]
+ : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+ T extends Function
+ ? T
+ : T extends object
+ ? { [TKey in keyof T]: WorkflowStepResult<T[TKey]> }
+ : T;
+
+/**
+ * Minimal step-running surface of a workflow context.
+ *
+ * `run` never references the context's payload generic, so picking it keeps this helper usable from
+ * any `WorkflowContext<TPayload>` without threading that generic through every call site.
+ */
+type WorkflowStepRunner = Pick<WorkflowContext<never>, 'run'>;
+
+/**
+ * Runs a workflow step and types the result the way the workflow actually receives it.
+ *
+ * Use when:
+ * - Executing any `context.run` step whose result is consumed later in the workflow
+ *
+ * Expects:
+ * - `stepFunction` returns JSON-serializable data (Upstash rejects anything else at the boundary)
+ *
+ * Returns:
+ * - The step result narrowed through {@link WorkflowStepResult}, so `Date` reads as `string`
+ *
+ * Before:
+ * - `const row = await context.run('load', () => model.findById(id))` β€” `row.createdAt` types as
+ * `Date` and `row.createdAt.toISOString()` compiles, then throws on replay
+ *
+ * After:
+ * - `const row = await runStep(context, 'load', () => model.findById(id))` β€” `row.createdAt` types
+ * as `string`, so the same call is a compile error instead of a production TypeError
+ */
+export const runStep = <TResult>(
+ context: WorkflowStepRunner,
+ stepName: string,
+ stepFunction: () => Promise<TResult> | TResult,
+): Promise<WorkflowStepResult<TResult>> =>
+ context.run(stepName, stepFunction) as Promise<WorkflowStepResult<TResult>>;
+
+/**
+ * Parses a timestamp that crossed a workflow boundary back into a `Date`.
+ *
+ * Use when:
+ * - Restoring a cursor timestamp from a workflow payload or a replayed step result
+ * - Handing a boundary-crossed timestamp to a query that needs a real `Date`
+ *
+ * Expects:
+ * - `value` is a `Date` from a live call or an ISO-compatible string from a JSON round trip
+ *
+ * Returns:
+ * - A valid `Date`; throws `errorMessage` rather than letting an `Invalid Date` reach the database
+ */
+export const parseWorkflowDate = (
+ value: Date | string | number,
+ errorMessage = 'Invalid workflow timestamp',
+): Date => {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) throw new Error(`${errorMessage}: ${String(value)}`);
+
+ return date;
+};
diff --git a/apps/server/src/workflows/testing/stepContext.ts b/apps/server/src/workflows/testing/stepContext.ts
new file mode 100644
index 00000000000..a2267142b91
--- /dev/null
+++ b/apps/server/src/workflows/testing/stepContext.ts
@@ -0,0 +1,35 @@
+import { type Mock, vi } from 'vitest';
+
+/**
+ * Replays Upstash Workflow's step serialization for a single step result.
+ *
+ * A step result is persisted as JSON and restored with `JSON.parse`, so a workflow only ever reads
+ * the round-tripped value. Passing the raw return value straight through β€” what a naive
+ * `run: (name, cb) => cb()` mock does β€” tests a shape production never sees, and hides every
+ * `Date`-crossing-a-step bug behind a green suite.
+ */
+export const serializeStepResult = <T>(result: T): T =>
+ // eslint-disable-next-line unicorn/prefer-structured-clone -- structuredClone keeps Date instances alive, which is exactly the serialization being reproduced
+ result === undefined ? result : JSON.parse(JSON.stringify(result));
+
+/**
+ * A `context.run` stub: generic like the real one, and still assertable as a mock.
+ */
+type StepRunnerMock = Mock &
+ (<TResult>(stepName: string, stepFunction: () => Promise<TResult> | TResult) => Promise<TResult>);
+
+/**
+ * Builds a `context.run` stub that serializes step results like Upstash does.
+ *
+ * Use when:
+ * - Stubbing a workflow context in a test that exercises `runStep` / `context.run`
+ *
+ * Returns:
+ * - A `vi.fn()` that awaits the step callback and hands back its JSON round trip
+ */
+export const createStepRunner = (): StepRunnerMock =>
+ // The cast restores the generic call signature that `vi.fn` erases, so the stub satisfies the
+ // step-runner shape `runStep` expects while staying assertable with `toHaveBeenCalledWith`.
+ vi.fn(async (_stepName: string, stepFunction: () => unknown) =>
+ serializeStepResult(await stepFunction()),
+ ) as unknown as StepRunnerMock;
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/execute-test-case/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/execute-test-case/route.ts
index b5f3e7155a5..94354f4eb27 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/execute-test-case/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/execute-test-case/route.ts
@@ -7,6 +7,7 @@ import { getServerDB } from '@/database/server';
import { qstashClient } from '@/libs/qstash';
import { AgentEvalRunWorkflow, type ExecuteTestCasePayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:execute-test-case');
@@ -30,7 +31,7 @@ export const { POST } = serve<ExecuteTestCasePayload>(
const wsId = await resolveAgentEvalRunWorkspace(db, runId);
// Get run to get K value from config
- const run = await context.run('agent-eval-run:get-run', async () => {
+ const run = await runStep(context, 'agent-eval-run:get-run', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
return runModel.findById(runId);
});
@@ -51,7 +52,7 @@ export const { POST } = serve<ExecuteTestCasePayload>(
// Trigger a single run-agent-trajectory workflow.
// For k=1 it executes the agent directly; for k>1 it creates K threads internally.
- await context.run(`agent-eval-run:trajectory:${runId}:${testCaseId}`, () =>
+ await runStep(context, `agent-eval-run:trajectory:${runId}:${testCaseId}`, () =>
AgentEvalRunWorkflow.triggerRunAgentTrajectory({ runId, testCaseId, userId }),
);
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/finalize-run/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/finalize-run/route.ts
index 63b730cadef..0fea7727b39 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/finalize-run/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/finalize-run/route.ts
@@ -8,6 +8,7 @@ import { qstashClient } from '@/libs/qstash';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import { type FinalizeRunPayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:finalize-run');
@@ -36,7 +37,7 @@ export const { POST } = serve<FinalizeRunPayload>(
const wsId = await resolveAgentEvalRunWorkspace(db, runId);
// Step 1: Get run details
- const run = await context.run('agent-eval-run:get-run', async () => {
+ const run = await runStep(context, 'agent-eval-run:get-run', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
return runModel.findById(runId);
});
@@ -51,7 +52,7 @@ export const { POST } = serve<FinalizeRunPayload>(
}
// Step 2: Get all RunTopics (already evaluated in recordTrajectoryCompletion)
- const runTopics = await context.run('agent-eval-run:get-run-topics', async () => {
+ const runTopics = await runStep(context, 'agent-eval-run:get-run-topics', async () => {
const runTopicModel = new AgentEvalRunTopicModel(db, userId, wsId);
return runTopicModel.findByRunId(runId);
});
@@ -59,7 +60,7 @@ export const { POST } = serve<FinalizeRunPayload>(
log('Total RunTopics: %d', runTopics.length);
// Step 3: Aggregate metrics from already-evaluated RunTopics
- const metrics = await context.run('agent-eval-run:aggregate-metrics', async () => {
+ const metrics = await runStep(context, 'agent-eval-run:aggregate-metrics', async () => {
const service = new AgentEvalRunService(db, userId, wsId);
return service.evaluateAndFinalizeRun({
run: { config: run.config, id: runId, metrics: run.metrics, startedAt: run.startedAt },
@@ -82,7 +83,7 @@ export const { POST } = serve<FinalizeRunPayload>(
? 'failed'
: 'completed';
- await context.run('agent-eval-run:update-run', async () => {
+ await runStep(context, 'agent-eval-run:update-run', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
return runModel.update(runId, { metrics, status: runStatus });
});
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route.ts
index 96011c9008f..f62afa83ede 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/paginate-test-cases/route.ts
@@ -11,6 +11,7 @@ import {
type PaginateTestCasesPayload,
} from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const CHUNK_SIZE = 20; // Max items to process directly
const PAGE_SIZE = 50; // Items per page
@@ -44,7 +45,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
await Promise.all(
payloadTestCaseIds.map((testCaseId) =>
- context.run(`agent-eval-run:execute:${testCaseId}`, () =>
+ runStep(context, `agent-eval-run:execute:${testCaseId}`, () =>
AgentEvalRunWorkflow.triggerExecuteTestCase({ runId, testCaseId, userId }),
),
),
@@ -57,7 +58,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
}
// Check if run was aborted before paginating
- const runStatus = await context.run('agent-eval-run:check-abort', async () => {
+ const runStatus = await runStep(context, 'agent-eval-run:check-abort', async () => {
const runModel = new AgentEvalRunModel(db, userId, wsId);
const run = await runModel.findById(runId);
return run?.status;
@@ -69,7 +70,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
}
// Paginate through test cases
- const testCaseBatch = await context.run('agent-eval-run:get-test-cases-page', async () => {
+ const testCaseBatch = await runStep(context, 'agent-eval-run:get-test-cases-page', async () => {
// Get run to find datasetId and userId
const runModel = new AgentEvalRunModel(db, userId, wsId);
const run = await runModel.findById(runId);
@@ -106,7 +107,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
}
// Filter test cases that need execution
- const testCaseIds = await context.run('agent-eval-run:filter-existing', () =>
+ const testCaseIds = await runStep(context, 'agent-eval-run:filter-existing', () =>
AgentEvalRunWorkflow.filterTestCasesNeedingExecution(db, {
runId,
testCaseIds: batchTestCaseIds,
@@ -130,7 +131,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
await Promise.all(
chunks.map((ids, idx) =>
- context.run(`agent-eval-run:fanout:${idx + 1}/${chunks.length}`, () =>
+ runStep(context, `agent-eval-run:fanout:${idx + 1}/${chunks.length}`, () =>
AgentEvalRunWorkflow.triggerPaginateTestCases({ runId, testCaseIds: ids, userId }),
),
),
@@ -141,7 +142,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
await Promise.all(
testCaseIds.map((testCaseId) =>
- context.run(`agent-eval-run:execute:${testCaseId}`, () =>
+ runStep(context, `agent-eval-run:execute:${testCaseId}`, () =>
AgentEvalRunWorkflow.triggerExecuteTestCase({ runId, testCaseId, userId }),
),
),
@@ -152,7 +153,7 @@ export const { POST } = serve<PaginateTestCasesPayload>(
// Schedule next page
if (nextCursor) {
log('Scheduling next page with cursor %s', nextCursor);
- await context.run('agent-eval-run:next-page', () =>
+ await runStep(context, 'agent-eval-run:next-page', () =>
AgentEvalRunWorkflow.triggerPaginateTestCases({ cursor: nextCursor, runId, userId }),
);
} else {
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts
index c360c1ba6fd..e6e6152661b 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/resume-agent-trajectory/route.ts
@@ -7,6 +7,7 @@ import { qstashClient } from '@/libs/qstash';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import type { ResumeAgentTrajectoryPayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:resume-agent-trajectory');
@@ -32,7 +33,7 @@ export const { POST } = serve<ResumeAgentTrajectoryPayload>(
const wsId = await resolveAgentEvalRunWorkspace(db, runId);
const service = new AgentEvalRunService(db, userId, wsId);
- await context.run('resume-agent-trajectory:exec-agent', () =>
+ await runStep(context, 'resume-agent-trajectory:exec-agent', () =>
service.executeResumedTrajectory(payload),
);
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts
index 606b0f61430..47bb04c6f12 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/resume-thread-trajectory/route.ts
@@ -7,6 +7,7 @@ import { qstashClient } from '@/libs/qstash';
import { AgentEvalRunService } from '@/server/services/agentEvalRun';
import type { ResumeThreadTrajectoryPayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:resume-thread-trajectory');
@@ -34,7 +35,7 @@ export const { POST } = serve<ResumeThreadTrajectoryPayload>(
const wsId = await resolveAgentEvalRunWorkspace(db, runId);
const service = new AgentEvalRunService(db, userId, wsId);
- await context.run('resume-thread-trajectory:exec-agent', () =>
+ await runStep(context, 'resume-thread-trajectory:exec-agent', () =>
service.executeResumedThreadTrajectory(payload),
);
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/run-agent-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/run-agent-trajectory/route.ts
index aa85434034f..a1460bbeb8b 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/run-agent-trajectory/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/run-agent-trajectory/route.ts
@@ -10,6 +10,7 @@ import {
type RunAgentTrajectoryPayload,
} from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:run-agent-trajectory');
@@ -33,7 +34,7 @@ export const { POST } = serve<RunAgentTrajectoryPayload>(
const service = new AgentEvalRunService(db, userId, wsId);
// Step 1: Read all required data
- const data = await context.run('agent-eval-run:load-data', () =>
+ const data = await runStep(context, 'agent-eval-run:load-data', () =>
service.loadTrajectoryData(runId, testCaseId),
);
@@ -53,7 +54,7 @@ export const { POST } = serve<RunAgentTrajectoryPayload>(
// Step 2: Branch on k value
if (k > 1) {
// Multi-thread path: create K threads and trigger sub-workflows
- const result = await context.run('agent-eval-run:exec-multi-thread', () =>
+ const result = await runStep(context, 'agent-eval-run:exec-multi-thread', () =>
service.executeMultiThreadTrajectory({ k, run, runId, testCaseId }),
);
@@ -75,13 +76,13 @@ export const { POST } = serve<RunAgentTrajectoryPayload>(
}
// Single execution path (k=1): existing logic
- const result = await context.run('agent-eval-run:exec-agent', () =>
+ const result = await runStep(context, 'agent-eval-run:exec-agent', () =>
service.executeTrajectory({ envPrompt, run, runId, testCase, testCaseId }),
);
// If execAgent failed, record completion and check if run should be finalized
if ('error' in result) {
- await context.run('agent-eval-run:handle-exec-error', async () => {
+ await runStep(context, 'agent-eval-run:handle-exec-error', async () => {
const { allDone } = await service.recordTrajectoryCompletion({
runId,
status: 'error',
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route.ts
index 38ea3dd3045..ffe151fb708 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/run-benchmark/route.ts
@@ -7,6 +7,7 @@ import { getServerDB } from '@/database/server';
import { qstashClient } from '@/libs/qstash';
import { AgentEvalRunWorkflow, type RunBenchmarkPayload } from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:run-benchmark');
@@ -34,7 +35,7 @@ export const { POST } = serve<RunBenchmarkPayload>(
const runModel = new AgentEvalRunModel(db, userId, wsId);
// Get run info
- const run = await context.run('agent-eval-run:get-run', () => runModel.findById(runId));
+ const run = await runStep(context, 'agent-eval-run:get-run', () => runModel.findById(runId));
if (!run) {
return { error: 'Run not found', success: false };
@@ -47,7 +48,7 @@ export const { POST } = serve<RunBenchmarkPayload>(
// Get all test cases
const testCaseModel = new AgentEvalTestCaseModel(db, userId, wsId);
- const allTestCases = await context.run('agent-eval-run:get-test-cases', () =>
+ const allTestCases = await runStep(context, 'agent-eval-run:get-test-cases', () =>
testCaseModel.findByDatasetId(run.datasetId),
);
@@ -64,7 +65,7 @@ export const { POST } = serve<RunBenchmarkPayload>(
}
// Filter test cases that need execution
- const testCaseIds = await context.run('agent-eval-run:filter-existing', () =>
+ const testCaseIds = await runStep(context, 'agent-eval-run:filter-existing', () =>
AgentEvalRunWorkflow.filterTestCasesNeedingExecution(db, {
runId,
testCaseIds: allTestCaseIds,
@@ -103,7 +104,7 @@ export const { POST } = serve<RunBenchmarkPayload>(
}
// Update run status to 'running'
- await context.run('agent-eval-run:update-status', () =>
+ await runStep(context, 'agent-eval-run:update-status', () =>
runModel.update(runId, {
metrics: {
averageScore: 0,
@@ -119,7 +120,7 @@ export const { POST } = serve<RunBenchmarkPayload>(
// Trigger paginate-test-cases workflow
log('Triggering paginate-test-cases for run %s', runId);
- await context.run('agent-eval-run:trigger-paginate', () =>
+ await runStep(context, 'agent-eval-run:trigger-paginate', () =>
AgentEvalRunWorkflow.triggerPaginateTestCases({ runId, userId }),
);
diff --git a/src/app/(backend)/api/workflows/agent-eval-run/run-thread-trajectory/route.ts b/src/app/(backend)/api/workflows/agent-eval-run/run-thread-trajectory/route.ts
index 306d8a55a73..3490881acf9 100644
--- a/src/app/(backend)/api/workflows/agent-eval-run/run-thread-trajectory/route.ts
+++ b/src/app/(backend)/api/workflows/agent-eval-run/run-thread-trajectory/route.ts
@@ -10,6 +10,7 @@ import {
type RunThreadTrajectoryPayload,
} from '@/server/workflows/agentEvalRun';
import { resolveAgentEvalRunWorkspace } from '@/server/workflows/agentEvalRun/utils';
+import { runStep } from '@/server/workflows/step';
const log = debug('lobe-server:workflows:run-thread-trajectory');
@@ -32,13 +33,13 @@ export const { POST } = serve<RunThreadTrajectoryPayload>(
const service = new AgentEvalRunService(db, userId, wsId);
// Step 1: Load run + testCase data
- const data = await context.run('thread-trajectory:load-data', () =>
+ const data = await runStep(context, 'thread-trajectory:load-data', () =>
service.loadTrajectoryData(runId, testCaseId),
);
if ('error' in data) {
// Record thread as errored so aggregation can proceed
- await context.run('thread-trajectory:handle-load-error', async () => {
+ await runStep(context, 'thread-trajectory:handle-load-error', async () => {
await service.recordThreadCompletion({
runId,
status: 'error',
@@ -59,7 +60,7 @@ export const { POST } = serve<RunThreadTrajectoryPayload>(
}
// Step 2: Execute agent for this thread
- const result = await context.run('thread-trajectory:exec-agent', () =>
+ const result = await runStep(context, 'thread-trajectory:exec-agent', () =>
service.executeThreadTrajectory({
envPrompt,
run,
@@ -74,7 +75,7 @@ export const { POST } = serve<RunThreadTrajectoryPayload>(
if ('error' in result) {
// execAgent failed to start β€” thread metadata already written by the service.
// Check if all threads are done and handle finalization.
- await context.run('thread-trajectory:handle-exec-error', async () => {
+ await runStep(context, 'thread-trajectory:handle-exec-error', async () => {
const { allRunDone } = await service.recordThreadCompletion({
runId,
status: 'error',