🤯 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-signal): bound nightly review pagination (#18307)
Neko340c86534159
diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.tsindex 734f8ba6704..a55c162aec3 100644--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts@@ -1,21 +1,16 @@import { Hono } from 'hono';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { scheduleNightlyReview } from '../scheduleNightlyReview';const mocks = vi.hoisted(() => ({- dispatchNightlyReviewRequests: vi.fn(),- getServerDB: vi.fn(),+ triggerPaginateUsers: vi.fn(),}));-vi.mock('@/database/server', () => ({- getServerDB: mocks.getServerDB,-}));--vi.mock('@/server/services/agentSignal/services', () => ({- createServerNightlyReviewScheduleService: () => ({- dispatchNightlyReviewRequests: mocks.dispatchNightlyReviewRequests,- }),+vi.mock('@/server/workflows/agentSignal/nightlyReview', () => ({+ AgentSignalNightlyReviewWorkflow: {+ triggerPaginateUsers: mocks.triggerPaginateUsers,+ },}));const createApp = () => {@@ -29,23 +24,34 @@ const createApp = () => {describe('scheduleNightlyReview', () => {beforeEach(() => {vi.clearAllMocks();- mocks.getServerDB.mockResolvedValue({});- mocks.dispatchNightlyReviewRequests.mockResolvedValue({ enqueued: 2, skipped: 1 });+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-05-03T18:30:00.000Z'));+ mocks.triggerPaginateUsers.mockResolvedValue({ workflowRunId: 'nightly-page-1' });+ });++ afterEach(() => {+ vi.useRealTimers();});it('uses bounded defaults when QStash sends an empty body', async () => {/*** @example- * expect(response.status).toBe(200);+ * expect(response.status).toBe(202);*/const response = await createApp().request('/cron-hourly-nightly-self-review', {method: 'POST',});- await expect(response.json()).resolves.toEqual({ enqueued: 2, skipped: 1, success: true });- expect(mocks.dispatchNightlyReviewRequests).toHaveBeenCalledWith({+ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toEqual({+ scheduled: true,+ success: true,+ workflowRunId: 'nightly-page-1',+ });+ expect(mocks.triggerPaginateUsers).toHaveBeenCalledWith({cursor: undefined,- limit: 500,+ pageSize: 50,+ requestedAt: '2026-05-03T18:30:00.000Z',targetLimit: 20,whitelist: undefined,});@@ -54,7 +60,7 @@ describe('scheduleNightlyReview', () => {it('forwards valid scheduler options from the request body', async () => {/*** @example- * expect(dispatchNightlyReviewRequests).toHaveBeenCalledWith(options);+ * expect(triggerPaginateUsers).toHaveBeenCalledWith(options);*/const response = await createApp().request('/cron-hourly-nightly-self-review', {body: JSON.stringify({@@ -67,10 +73,16 @@ describe('scheduleNightlyReview', () => {method: 'POST',});- await expect(response.json()).resolves.toEqual({ enqueued: 2, skipped: 1, success: true });- expect(mocks.dispatchNightlyReviewRequests).toHaveBeenCalledWith({- cursor: { createdAt: new Date('2026-05-04T00:00:00.000Z'), id: 'user-1' },- limit: 100,+ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toEqual({+ scheduled: true,+ success: true,+ workflowRunId: 'nightly-page-1',+ });+ expect(mocks.triggerPaginateUsers).toHaveBeenCalledWith({+ cursor: { createdAt: '2026-05-04T00:00:00.000Z', id: 'user-1' },+ pageSize: 100,+ requestedAt: '2026-05-03T18:30:00.000Z',targetLimit: 5,whitelist: ['user-1'],});diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.tsindex 296c3e66fd8..91537a7c65d 100644--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts@@ -3,12 +3,15 @@ import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import { isRecord } from '@lobechat/utils';import type { Context } from 'hono';-import { getServerDB } from '@/database/server';-import type { DispatchNightlyReviewRequestsOptions } from '@/server/services/agentSignal/services';-import { createServerNightlyReviewScheduleService } from '@/server/services/agentSignal/services';+import {+ AgentSignalNightlyReviewWorkflow,+ type NightlyReviewWorkflowCursor,+} from '@/server/workflows/agentSignal/nightlyReview';-const DEFAULT_USER_LIMIT = 500;+const DEFAULT_USER_PAGE_SIZE = 50;+const HARD_MAX_USER_PAGE_SIZE = 200;const DEFAULT_TARGET_LIMIT = 20;+const HARD_MAX_TARGET_LIMIT = 50;const CRON_SPAN_NAME = 'agent_signal.cron.hourly_nightly_self_review';/**@@ -23,9 +26,9 @@ export interface ScheduleNightlyReviewPayload {id: string;};/**- * Maximum eligible users to scan in one dispatch pass.+ * Maximum eligible users read by each pagination workflow.*- * @default 500+ * @default 50*/limit?: number;/**@@ -38,8 +41,10 @@ export interface ScheduleNightlyReviewPayload {whitelist?: string[];}-const readPositiveInteger = (value: unknown, fallback: number) => {- return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback;+const readBoundedPositiveInteger = (value: unknown, fallback: number, maximum: number) => {+ return typeof value === 'number' && Number.isInteger(value) && value > 0+ ? Math.min(value, maximum)+ : fallback;};const readWhitelist = (value: unknown) => {@@ -52,7 +57,7 @@ const readWhitelist = (value: unknown) => {return whitelist.length > 0 ? whitelist : undefined;};-const readCursor = (value: unknown): DispatchNightlyReviewRequestsOptions['cursor'] | undefined => {+const readCursor = (value: unknown): NightlyReviewWorkflowCursor | undefined => {if (!isRecord(value)) return;const createdAt = typeof value.createdAt === 'string' ? new Date(value.createdAt) : undefined;@@ -60,7 +65,7 @@ const readCursor = (value: unknown): DispatchNightlyReviewRequestsOptions['cursoif (!createdAt || Number.isNaN(createdAt.getTime()) || !id) return;- return { createdAt, id };+ return { createdAt: createdAt.toISOString(), id };};const readPayload = async (c: Context): Promise<ScheduleNightlyReviewPayload> => {@@ -70,25 +75,25 @@ const readPayload = async (c: Context): Promise<ScheduleNightlyReviewPayload> =>};/**- * Dispatches Agent Signal nightly review request sources from a QStash cron call.+ * Starts the layered Agent Signal nightly review scheduler from a QStash cron call.** Use when:- * - A QStash Schedule or local QStash publish call needs to fan out nightly review source events- * - Cron should enqueue source events but leave actual review execution to Agent Signal workflows+ * - A QStash Schedule or local QStash publish call needs to start cursor pagination+ * - Cron must return before database scanning and per-user source enqueueing begin** Expects:* - The route is protected by {@link qstashAuth} in `agent-signal/index.ts`- * - QStash or the caller may omit a JSON body, in which case bounded defaults are used+ * - QStash or the caller may omit a JSON body, in which case bounded page defaults are used** Returns:- * - A JSON summary with enqueue and skip counts+ * - HTTP 202 with the root pagination workflow id** Call stack:** scheduleNightlyReview- * -> {@link createServerNightlyReviewScheduleService}- * -> dispatchNightlyReviewRequests- * -> enqueueAgentSignalSourceEvent+ * -> {@link AgentSignalNightlyReviewWorkflow.triggerPaginateUsers}+ * -> paginateNightlyReviewUsers+ * -> executeNightlyReviewUser*/export async function scheduleNightlyReview(c: Context) {return tracer.startActiveSpan(CRON_SPAN_NAME, async (span) => {@@ -96,35 +101,41 @@ export async function scheduleNightlyReview(c: Context) {const payload = await readPayload(c);const options = {cursor: readCursor(payload.cursor),- limit: readPositiveInteger(payload.limit, DEFAULT_USER_LIMIT),- targetLimit: readPositiveInteger(payload.targetLimit, DEFAULT_TARGET_LIMIT),+ pageSize: readBoundedPositiveInteger(+ payload.limit,+ DEFAULT_USER_PAGE_SIZE,+ HARD_MAX_USER_PAGE_SIZE,+ ),+ requestedAt: new Date().toISOString(),+ targetLimit: readBoundedPositiveInteger(+ payload.targetLimit,+ DEFAULT_TARGET_LIMIT,+ HARD_MAX_TARGET_LIMIT,+ ),whitelist: readWhitelist(payload.whitelist),- } satisfies DispatchNightlyReviewRequestsOptions;+ };span.setAttributes({- 'agent.signal.cron.limit': options.limit,+ 'agent.signal.cron.limit': options.pageSize,'agent.signal.cron.target_limit': options.targetLimit,'agent.signal.cron.whitelist_count': options.whitelist?.length ?? 0,...(options.cursor? {- 'agent.signal.cron.cursor_created_at': options.cursor.createdAt.toISOString(),+ 'agent.signal.cron.cursor_created_at': options.cursor.createdAt,'agent.signal.cron.cursor_user_id': options.cursor.id,}: {}),});- const db = await getServerDB();- const service = createServerNightlyReviewScheduleService(db);- const summary = await service.dispatchNightlyReviewRequests(options);+ const result = await AgentSignalNightlyReviewWorkflow.triggerPaginateUsers(options);span.setAttributes({- 'agent.signal.cron.enqueued': summary.enqueued,- 'agent.signal.cron.skipped': summary.skipped,'agent.signal.cron.success': true,+ 'agent.signal.cron.workflow_run_id': result.workflowRunId,});span.setStatus({ code: SpanStatusCode.OK });- return c.json({ success: true, ...summary });+ return c.json({ scheduled: true, success: true, workflowRunId: result.workflowRunId }, 202);} catch (error) {console.error('[agent-signal/cron-hourly-nightly-self-review] Error:', error);span.setAttribute('agent.signal.cron.success', false);diff --git a/apps/server/src/router-hono/workflows/agent-signal/index.ts b/apps/server/src/router-hono/workflows/agent-signal/index.tsindex 7653e8b273d..b54c253c491 100644--- a/apps/server/src/router-hono/workflows/agent-signal/index.ts+++ b/apps/server/src/router-hono/workflows/agent-signal/index.ts@@ -8,11 +8,43 @@ import type { AgentSignalWorkflowRunPayload } from '@/server/workflows/agentSignimport { qstashAuth } from '../middlewares/qstashAuth';import { createWorkflowQstashClient } from '../qstashClient';import { scheduleNightlyReview } from './handlers/scheduleNightlyReview';+import {+ executeNightlyReviewUser,+ executeNightlyReviewUserOptions,+ paginateNightlyReviewUsers,+ paginateNightlyReviewUsersOptions,+} from './workflows/nightlyReview';const app = new Hono();app.post('/cron-hourly-nightly-self-review', qstashAuth(), scheduleNightlyReview);+app.post(+ '/paginate-nightly-review-users',+ serve(+ withOtelMetricsForUpstashWorkflows(paginateNightlyReviewUsers, {+ url: '/api/workflows/agent-signal/paginate-nightly-review-users',+ }),+ {+ ...paginateNightlyReviewUsersOptions,+ qstashClient: createWorkflowQstashClient(),+ },+ ),+);++app.post(+ '/execute-nightly-review-user',+ serve(+ withOtelMetricsForUpstashWorkflows(executeNightlyReviewUser, {+ url: '/api/workflows/agent-signal/execute-nightly-review-user',+ }),+ {+ ...executeNightlyReviewUserOptions,+ qstashClient: createWorkflowQstashClient(),+ },+ ),+);+app.post('/run',serve<AgentSignalWorkflowRunPayload>(diff --git a/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.ts b/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.tsnew file mode 100644index 00000000000..bed8dc2ca79--- /dev/null+++ b/apps/server/src/router-hono/workflows/agent-signal/workflows/__tests__/nightlyReview.test.ts@@ -0,0 +1,170 @@+import type { WorkflowContext } from '@upstash/workflow';+import { describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';+import type { NightlyReviewScheduleService } from '@/server/services/agentSignal/services';+import type {+ AgentSignalNightlyReviewWorkflow,+ ExecuteNightlyReviewUserPayload,+ PaginateNightlyReviewUsersPayload,+} from '@/server/workflows/agentSignal/nightlyReview';++import type { NightlyReviewWorkflowDependencies } from '../nightlyReview';+import { executeNightlyReviewUser, paginateNightlyReviewUsers } from '../nightlyReview';++const createContext = <TPayload>(payload: TPayload): WorkflowContext<TPayload> => {+ const run = vi.fn(async (_stepName: string, handler: () => Promise<unknown>) => {+ const result = await handler();++ // NOTICE:+ // Tests must reproduce Upstash's persisted JSON round trip between workflow steps.+ // The SDK context is not constructible outside a live workflow request.+ // Source/context: `apps/server/src/workflows/step.ts` documents Date -> string replay behavior.+ // Removal condition: replace this mock when Upstash ships a public workflow context test helper.+ // eslint-disable-next-line unicorn/prefer-structured-clone -- structuredClone preserves Date.+ return JSON.parse(JSON.stringify(result)) as unknown;+ });++ return { requestPayload: payload, run } as unknown as WorkflowContext<TPayload>;+};++const createService = (): NightlyReviewScheduleService => ({+ dispatchNightlyReviewForUser: vi.fn().mockResolvedValue({ enqueued: 1, skipped: 0 }),+ listEligibleUsersPage: vi.fn().mockResolvedValue({ users: [] }),+});++const createDependencies = (service: NightlyReviewScheduleService) => {+ const triggerExecuteUser = vi+ .fn<typeof AgentSignalNightlyReviewWorkflow.triggerExecuteUser>()+ .mockResolvedValue({ workflowRunId: 'execute-run' });+ const triggerPaginateUsers = vi+ .fn<typeof AgentSignalNightlyReviewWorkflow.triggerPaginateUsers>()+ .mockResolvedValue({ workflowRunId: 'paginate-run' });+ const dependencies: NightlyReviewWorkflowDependencies = {+ createScheduleService: () => service,+ getDb: async () => ({}) as unknown as LobeChatDatabase,+ triggerExecuteUser,+ triggerPaginateUsers,+ };++ return { dependencies, triggerExecuteUser, triggerPaginateUsers };+};++describe('nightly review layered workflows', () => {+ it('reads one cursor page, fans it out in bounded chunks, and schedules the next cursor', async () => {+ /**+ * @example+ * expect(result).toMatchObject({ scheduledBatches: 3, scheduledUsers: 45 });+ */+ const service = createService();+ const users = Array.from({ length: 45 }, (_, index) => ({+ createdAt: new Date(Date.UTC(2026, 0, index + 1)),+ id: `user-${index + 1}`,+ timezone: 'Asia/Shanghai',+ }));+ vi.mocked(service.listEligibleUsersPage).mockResolvedValue({+ nextCursor: {+ createdAt: users.at(-1)!.createdAt,+ id: users.at(-1)!.id,+ },+ users,+ });+ const { dependencies, triggerExecuteUser, triggerPaginateUsers } = createDependencies(service);+ const context = createContext<PaginateNightlyReviewUsersPayload>({+ pageSize: 50,+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 20,+ });++ await expect(paginateNightlyReviewUsers(context, dependencies)).resolves.toEqual({+ hasNextPage: true,+ scheduledBatches: 3,+ scheduledUsers: 45,+ success: true,+ });+ expect(service.listEligibleUsersPage).toHaveBeenCalledOnce();+ expect(triggerExecuteUser).not.toHaveBeenCalled();+ expect(triggerPaginateUsers).toHaveBeenCalledTimes(4);+ expect(+ triggerPaginateUsers.mock.calls.slice(0, 3).map(([payload]) => payload.users?.length),+ ).toEqual([20, 20, 5]);+ expect(triggerPaginateUsers).toHaveBeenLastCalledWith({+ cursor: {+ createdAt: users.at(-1)!.createdAt.toISOString(),+ id: users.at(-1)!.id,+ },+ pageSize: 50,+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 20,+ whitelist: undefined,+ });+ });++ it('turns one fan-out chunk into one execution workflow per user without querying a page', async () => {+ /**+ * @example+ * expect(triggerExecuteUser).toHaveBeenCalledTimes(2);+ */+ const service = createService();+ const { dependencies, triggerExecuteUser, triggerPaginateUsers } = createDependencies(service);+ const context = createContext<PaginateNightlyReviewUsersPayload>({+ pageSize: 50,+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 20,+ users: [+ {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ {+ createdAt: '2026-01-02T00:00:00.000Z',+ id: 'user-2',+ timezone: 'Asia/Shanghai',+ },+ ],+ });++ await expect(paginateNightlyReviewUsers(context, dependencies)).resolves.toEqual({+ scheduledUsers: 2,+ success: true,+ });+ expect(triggerExecuteUser).toHaveBeenCalledTimes(2);+ expect(triggerPaginateUsers).not.toHaveBeenCalled();+ expect(service.listEligibleUsersPage).not.toHaveBeenCalled();+ });++ it('executes exactly one user with restored Date values', async () => {+ /**+ * @example+ * expect(service.dispatchNightlyReviewForUser).toHaveBeenCalledOnce();+ */+ const service = createService();+ const { dependencies } = createDependencies(service);+ const context = createContext<ExecuteNightlyReviewUserPayload>({+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 5,+ user: {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ });++ await expect(executeNightlyReviewUser(context, dependencies)).resolves.toEqual({+ enqueued: 1,+ skipped: 0,+ success: true,+ userId: 'user-1',+ });+ expect(service.dispatchNightlyReviewForUser).toHaveBeenCalledWith({+ requestedAt: new Date('2026-05-03T18:30:00.000Z'),+ targetLimit: 5,+ user: {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ });+ });+});diff --git a/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.tsnew file mode 100644index 00000000000..972d2363688--- /dev/null+++ b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts@@ -0,0 +1,279 @@+import type { WorkflowContext } from '@upstash/workflow';+import { chunk } from 'es-toolkit/compat';++import { getServerDB } from '@/database/server';+import { createServerNightlyReviewScheduleService } from '@/server/services/agentSignal/services';+import {+ AgentSignalNightlyReviewWorkflow,+ type ExecuteNightlyReviewUserPayload,+ NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY,+ NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,+ type NightlyReviewWorkflowUser,+ type PaginateNightlyReviewUsersPayload,+} from '@/server/workflows/agentSignal/nightlyReview';+import { parseWorkflowDate, runStep } from '@/server/workflows/step';++const DEFAULT_PAGE_SIZE = 50;+const HARD_MAX_PAGE_SIZE = 200;+const DEFAULT_TARGET_LIMIT = 20;+const HARD_MAX_TARGET_LIMIT = 50;+const USER_FAN_OUT_CHUNK_SIZE = 20;++/** Dependencies that isolate nightly-review workflow orchestration from storage and child triggers. */+export interface NightlyReviewWorkflowDependencies {+ /** Creates the database-backed scheduler service used inside durable steps. */+ createScheduleService?: typeof createServerNightlyReviewScheduleService;+ /** Resolves the main database connection used by scheduler steps. */+ getDb?: typeof getServerDB;+ /** Triggers the single-user execution layer. */+ triggerExecuteUser?: typeof AgentSignalNightlyReviewWorkflow.triggerExecuteUser;+ /** Triggers a fan-out chunk or the next cursor page. */+ triggerPaginateUsers?: typeof AgentSignalNightlyReviewWorkflow.triggerPaginateUsers;+}++const boundedInteger = (value: number | undefined, fallback: number, maximum: number) =>+ Math.min(Math.max(Math.floor(value ?? fallback), 1), maximum);++const serializeUser = (user: {+ createdAt: string;+ id: string;+ timezone?: string | null;+}): NightlyReviewWorkflowUser => ({+ createdAt: user.createdAt,+ id: user.id,+ timezone: user.timezone,+});++/**+ * Processes one cursor page or one bounded fan-out chunk of nightly-review users.+ *+ * Use when:+ * - Upstash invokes the pagination layer after the cron entry+ * - A parent page splits users into bounded fan-out chunks+ *+ * Expects:+ * - `requestedAt` remains unchanged across the complete pagination tree+ * - Database pages are ordered by `createdAt, id`+ *+ * Returns:+ * - Page/chunk scheduling counts and the next cursor, without executing review logic inline+ *+ * Call stack:+ *+ * paginateNightlyReviewUsers+ * -> createServerNightlyReviewScheduleService+ * -> listEligibleUsersPage+ * -> {@link AgentSignalNightlyReviewWorkflow.triggerPaginateUsers}+ * -> {@link AgentSignalNightlyReviewWorkflow.triggerExecuteUser}+ */+export const paginateNightlyReviewUsers = async (+ context: WorkflowContext<PaginateNightlyReviewUsersPayload>,+ dependencies: NightlyReviewWorkflowDependencies = {},+) => {+ const payload = context.requestPayload;+ if (!payload?.requestedAt) {+ return { error: 'Missing requestedAt in payload', success: false };+ }++ parseWorkflowDate(payload.requestedAt, 'Invalid nightly review requestedAt');++ const pageSize = boundedInteger(payload.pageSize, DEFAULT_PAGE_SIZE, HARD_MAX_PAGE_SIZE);+ const targetLimit = boundedInteger(+ payload.targetLimit,+ DEFAULT_TARGET_LIMIT,+ HARD_MAX_TARGET_LIMIT,+ );+ const triggerExecuteUser =+ dependencies.triggerExecuteUser ?? AgentSignalNightlyReviewWorkflow.triggerExecuteUser;+ const triggerPaginateUsers =+ dependencies.triggerPaginateUsers ?? AgentSignalNightlyReviewWorkflow.triggerPaginateUsers;++ if (payload.users && payload.users.length > 0) {+ await Promise.all(+ payload.users.map((user) =>+ runStep(context, `agent-signal:nightly-review:execute:${user.id}`, () =>+ triggerExecuteUser({+ requestedAt: payload.requestedAt,+ targetLimit,+ user,+ }),+ ),+ ),+ );++ return { scheduledUsers: payload.users.length, success: true };+ }++ const cursor = payload.cursor+ ? {+ createdAt: parseWorkflowDate(+ payload.cursor.createdAt,+ 'Invalid nightly review pagination cursor',+ ),+ id: payload.cursor.id,+ }+ : undefined;+ const createScheduleService =+ dependencies.createScheduleService ?? createServerNightlyReviewScheduleService;+ const getDb = dependencies.getDb ?? getServerDB;+ const page = await runStep(+ context,+ `agent-signal:nightly-review:list-users:${cursor?.id ?? 'root'}`,+ async () => {+ const db = await getDb();+ const service = createScheduleService(db);++ return service.listEligibleUsersPage({+ cursor,+ limit: pageSize,+ whitelist: payload.whitelist,+ });+ },+ );++ const users = page.users.map(serializeUser);+ const batches = chunk(users, USER_FAN_OUT_CHUNK_SIZE);++ await Promise.all(+ batches.map((batchUsers, index) =>+ runStep(context, `agent-signal:nightly-review:fanout:${index + 1}/${batches.length}`, () =>+ triggerPaginateUsers({+ pageSize,+ requestedAt: payload.requestedAt,+ targetLimit,+ users: batchUsers,+ whitelist: payload.whitelist,+ }),+ ),+ ),+ );++ const nextCursor = page.nextCursor+ ? {+ createdAt: page.nextCursor.createdAt,+ id: page.nextCursor.id,+ }+ : undefined;++ if (nextCursor) {+ await runStep(context, `agent-signal:nightly-review:next-page:${nextCursor.id}`, () =>+ triggerPaginateUsers({+ cursor: nextCursor,+ pageSize,+ requestedAt: payload.requestedAt,+ targetLimit,+ whitelist: payload.whitelist,+ }),+ );+ }++ return {+ hasNextPage: Boolean(nextCursor),+ scheduledBatches: batches.length,+ scheduledUsers: users.length,+ success: true,+ };+};++/**+ * Executes nightly-review scheduling for exactly one user.+ *+ * Use when:+ * - The pagination layer has emitted one user item+ *+ * Expects:+ * - The payload contains one stable user and the root schedule timestamp+ *+ * Returns:+ * - Per-user enqueue and skip counts+ *+ * Call stack:+ *+ * executeNightlyReviewUser+ * -> createServerNightlyReviewScheduleService+ * -> dispatchNightlyReviewForUser+ * -> enqueueAgentSignalSourceEvent+ */+export const executeNightlyReviewUser = async (+ context: WorkflowContext<ExecuteNightlyReviewUserPayload>,+ dependencies: NightlyReviewWorkflowDependencies = {},+) => {+ const payload = context.requestPayload;+ if (!payload?.requestedAt || !payload.user?.createdAt || !payload.user.id) {+ return { error: 'Missing requestedAt or user in payload', success: false };+ }++ const requestedAt = parseWorkflowDate(payload.requestedAt, 'Invalid nightly review requestedAt');+ const createdAt = parseWorkflowDate(+ payload.user.createdAt,+ 'Invalid nightly review user creation timestamp',+ );+ const targetLimit = boundedInteger(+ payload.targetLimit,+ DEFAULT_TARGET_LIMIT,+ HARD_MAX_TARGET_LIMIT,+ );+ const createScheduleService =+ dependencies.createScheduleService ?? createServerNightlyReviewScheduleService;+ const getDb = dependencies.getDb ?? getServerDB;+ const summary = await runStep(+ context,+ `agent-signal:nightly-review:dispatch-user:${payload.user.id}`,+ async () => {+ const db = await getDb();+ const service = createScheduleService(db);++ return service.dispatchNightlyReviewForUser({+ requestedAt,+ targetLimit,+ user: {+ createdAt,+ id: payload.user.id,+ timezone: payload.user.timezone,+ },+ });+ },+ );++ return { ...summary, success: true, userId: payload.user.id };+};++/**+ * Serve options for serialized cursor pagination.+ *+ * Use when:+ * - Registering the paginate route with Upstash Workflow+ *+ * Expects:+ * - Trigger-side pagination uses the same flow-control key+ *+ * Returns:+ * - One active pagination run with bounded delivery rate+ */+export const paginateNightlyReviewUsersOptions = {+ flowControl: {+ key: NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,+ parallelism: 1,+ ratePerSecond: 5,+ },+};++/**+ * Serve options for bounded per-user execution.+ *+ * Use when:+ * - Registering the execute-user route with Upstash Workflow+ *+ * Expects:+ * - Trigger-side execution uses the same flow-control key+ *+ * Returns:+ * - At most five concurrent user executions+ */+export const executeNightlyReviewUserOptions = {+ flowControl: {+ key: NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY,+ parallelism: 5,+ ratePerSecond: 5,+ },+};diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.tsindex 6368187e34b..d8cd7db51c1 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts@@ -33,7 +33,7 @@ vi.mock('@/server/services/agentSignal/emitter', () => ({enqueueAgentSignalSourceEvent: mocks.enqueueAgentSignalSourceEvent,}));-const createDeps = (now: Date) => ({+const createDeps = () => ({enqueueSource: vi.fn<(input: AgentSignalSourceEventInput<'agent.nightly_review.requested'>) => Promise<unknown>@@ -51,7 +51,6 @@ const createDeps = (now: Date) => ({timezone: 'Asia/Shanghai',},]),- now: () => now,});beforeEach(() => {@@ -63,12 +62,23 @@ afterEach(() => {});describe('nightlyReviewScheduleService', () => {- describe('dispatchNightlyReviewRequests', () => {+ describe('dispatchNightlyReviewForUser', () => {it('enqueues Shanghai user nightly review sources with previous full local day window', async () => {- const deps = createDeps(new Date('2026-05-03T18:30:00.000Z'));+ /**+ * @example+ * expect(summary).toEqual({ enqueued: 1, skipped: 0 });+ */+ const deps = createDeps();const service = createSelfReviewScheduleService(deps);- const summary = await service.dispatchNightlyReviewRequests();+ const summary = await service.dispatchNightlyReviewForUser({+ requestedAt: new Date('2026-05-03T18:30:00.000Z'),+ user: {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ });expect(summary).toEqual({ enqueued: 1, skipped: 0 });expect(deps.listActiveAgentTargets).toHaveBeenCalledWith({@@ -94,92 +104,45 @@ describe('nightlyReviewScheduleService', () => {});it('skips users outside the local night window without enqueueing', async () => {- const deps = createDeps(new Date('2026-05-03T20:30:00.000Z'));+ /**+ * @example+ * expect(summary.skipped).toBe(1);+ */+ const deps = createDeps();const service = createSelfReviewScheduleService(deps);- const summary = await service.dispatchNightlyReviewRequests();+ const summary = await service.dispatchNightlyReviewForUser({+ requestedAt: new Date('2026-05-03T20:30:00.000Z'),+ user: {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ });expect(summary).toEqual({ enqueued: 0, skipped: 1 });expect(deps.listActiveAgentTargets).not.toHaveBeenCalled();expect(deps.enqueueSource).not.toHaveBeenCalled();});- it('traverses every page of eligible users with a keyset cursor', async () => {- const deps = createDeps(new Date('2026-05-03T18:30:00.000Z'));- deps.listEligibleUsers- .mockResolvedValueOnce([- {- createdAt: new Date('2026-01-01T00:00:00.000Z'),- id: 'user-1',- timezone: 'Asia/Shanghai',- },- {- createdAt: new Date('2026-02-01T00:00:00.000Z'),- id: 'user-2',- timezone: 'Asia/Shanghai',- },- ])- .mockResolvedValueOnce([- {- createdAt: new Date('2026-03-01T00:00:00.000Z'),- id: 'user-3',- timezone: 'Asia/Shanghai',- },- {- createdAt: new Date('2026-04-01T00:00:00.000Z'),- id: 'user-4',- timezone: 'Asia/Shanghai',- },- ])- .mockResolvedValueOnce([]);- const service = createSelfReviewScheduleService(deps);-- const summary = await service.dispatchNightlyReviewRequests({ limit: 2 });-- expect(summary).toEqual({ enqueued: 4, skipped: 0 });- expect(deps.listEligibleUsers).toHaveBeenCalledTimes(3);- expect(deps.listEligibleUsers).toHaveBeenNthCalledWith(1, {- cursor: undefined,- limit: 2,- whitelist: undefined,- });- expect(deps.listEligibleUsers).toHaveBeenNthCalledWith(2, {- cursor: { createdAt: new Date('2026-02-01T00:00:00.000Z'), id: 'user-2' },- limit: 2,- whitelist: undefined,- });- expect(deps.listEligibleUsers).toHaveBeenNthCalledWith(3, {- cursor: { createdAt: new Date('2026-04-01T00:00:00.000Z'), id: 'user-4' },- limit: 2,- whitelist: undefined,- });- expect(deps.enqueueSource).toHaveBeenCalledTimes(4);- });-- it('stops paginating after the first page when no limit is provided', async () => {- const deps = createDeps(new Date('2026-05-03T18:30:00.000Z'));- const service = createSelfReviewScheduleService(deps);-- await service.dispatchNightlyReviewRequests();-- expect(deps.listEligibleUsers).toHaveBeenCalledTimes(1);- });-it('falls back to UTC for invalid timezone values without throwing', async () => {- const deps = createDeps(new Date('2026-05-04T02:30:00.000Z'));- deps.listEligibleUsers.mockResolvedValue([- {- createdAt: new Date('2026-01-01T00:00:00.000Z'),- id: 'user-1',- timezone: 'Invalid/Zone',- },- ]);+ /**+ * @example+ * expect(source.payload.timezone).toBe('UTC');+ */+ const deps = createDeps();const service = createSelfReviewScheduleService(deps);- await expect(service.dispatchNightlyReviewRequests()).resolves.toEqual({- enqueued: 1,- skipped: 0,- });+ await expect(+ service.dispatchNightlyReviewForUser({+ requestedAt: new Date('2026-05-04T02:30:00.000Z'),+ user: {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Invalid/Zone',+ },+ }),+ ).resolves.toEqual({ enqueued: 1, skipped: 0 });expect(deps.enqueueSource).toHaveBeenCalledWith(expect.objectContaining<Partial<AgentSignalSourceEventInput<'agent.nightly_review.requested'>>@@ -196,8 +159,60 @@ describe('nightlyReviewScheduleService', () => {});});+ describe('listEligibleUsersPage', () => {+ it('returns one page and a stable cursor without scanning the next page inline', async () => {+ /**+ * ROOT CAUSE:+ *+ * The old service treated `limit` as a page size inside `while (true)`, retaining one cron+ * request while it traversed the complete user table and enqueued every target.+ *+ * Before: one call consumed page 1, page 2, and the terminal empty page.+ * After: one call consumes page 1 only; a durable workflow owns the returned cursor.+ *+ * @example+ * expect(deps.listEligibleUsers).toHaveBeenCalledOnce();+ */+ const deps = createDeps();+ deps.listEligibleUsers.mockResolvedValue([+ {+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ {+ createdAt: new Date('2026-02-01T00:00:00.000Z'),+ id: 'user-2',+ timezone: 'Asia/Shanghai',+ },+ ]);+ const service = createSelfReviewScheduleService(deps);++ const page = await service.listEligibleUsersPage({ limit: 2 });++ expect(page).toEqual({+ nextCursor: {+ createdAt: new Date('2026-02-01T00:00:00.000Z'),+ id: 'user-2',+ },+ users: expect.arrayContaining([+ expect.objectContaining({ id: 'user-1' }),+ expect.objectContaining({ id: 'user-2' }),+ ]),+ });+ expect(deps.listEligibleUsers).toHaveBeenCalledOnce();+ expect(deps.listEligibleUsers).toHaveBeenCalledWith({ limit: 2 });+ expect(deps.listActiveAgentTargets).not.toHaveBeenCalled();+ expect(deps.enqueueSource).not.toHaveBeenCalled();+ });+ });+describe('buildNightlyReviewSourceId', () => {it('produces a stable nightly review source id', () => {+ /**+ * @example+ * expect(sourceId).toBe('nightly-review:user-1:agent-1:2026-05-04');+ */expect(buildNightlyReviewSourceId({agentId: 'agent-1',@@ -210,8 +225,10 @@ describe('nightlyReviewScheduleService', () => {describe('createServerNightlyReviewScheduleService', () => {it('calls the model methods and enqueues source payloads through the server adapter', async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-05-03T18:30:00.000Z'));+ /**+ * @example+ * expect(summary.enqueued).toBe(1);+ */mocks.listEligibleUsers.mockResolvedValue([{createdAt: new Date('2026-01-01T00:00:00.000Z'),@@ -228,14 +245,19 @@ describe('nightlyReviewScheduleService', () => {const db = {} as unknown as LobeChatDatabase;const service = createServerNightlyReviewScheduleService(db);- const summary = await service.dispatchNightlyReviewRequests({+ const page = await service.listEligibleUsersPage({cursor: { createdAt: new Date('2026-01-01T00:00:00.000Z'), id: 'cursor-user' },limit: 10,- targetLimit: 3,whitelist: ['user-1'],});+ const summary = await service.dispatchNightlyReviewForUser({+ requestedAt: new Date('2026-05-03T18:30:00.000Z'),+ targetLimit: 3,+ user: page.users[0]!,+ });expect(summary).toEqual({ enqueued: 1, skipped: 0 });+ expect(page.nextCursor).toBeUndefined();expect(mocks.modelConstructor).toHaveBeenCalledWith(db);expect(mocks.listEligibleUsers).toHaveBeenCalledWith({cursor: { createdAt: new Date('2026-01-01T00:00:00.000Z'), id: 'cursor-user' },diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.tsindex f455b7e45fa..d79c610ecf9 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts@@ -28,7 +28,7 @@ export interface NightlyReviewAgentTarget {/** User candidate returned by the nightly review scheduler data boundary. */export interface NightlyReviewEligibleUser {/** User creation time used by stable scheduler pagination. */- createdAt?: Date;+ createdAt: Date;/** Stable user id. */id: string;/** IANA timezone for local night-window evaluation. */@@ -83,18 +83,30 @@ export interface NightlyReviewScheduleAdapters {listEligibleUsers: (input?: ListNightlyReviewEligibleUsersInput,) => Promise<NightlyReviewEligibleUser[]>;- /**- * Supplies the scheduler dispatch time.- *- * @default Uses the current wall-clock time when omitted.- */- now?: () => Date;}-/** Options for one nightly review dispatch pass. */-export interface DispatchNightlyReviewRequestsOptions extends ListNightlyReviewEligibleUsersInput {- /** Maximum active agents to enqueue for each eligible in-window user. */+/** Options for listing exactly one page of nightly review user candidates. */+export interface ListNightlyReviewEligibleUsersPageOptions extends ListNightlyReviewEligibleUsersInput {+ /** Maximum eligible users returned by this page. */+ limit: number;+}++/** One cursor-paginated page of nightly review user candidates. */+export interface NightlyReviewEligibleUsersPage {+ /** Cursor to pass to the next pagination workflow, when another page may exist. */+ nextCursor?: NightlyReviewScheduleCursor;+ /** Users in this bounded page. */+ users: NightlyReviewEligibleUser[];+}++/** Options for dispatching nightly review sources for exactly one user. */+export interface DispatchNightlyReviewForUserOptions {+ /** UTC instant shared by every user execution started from the same schedule run. */+ requestedAt: Date;+ /** Maximum active agents to enqueue for this user. */targetLimit?: number;+ /** One user candidate owned by this execution. */+ user: NightlyReviewEligibleUser;}/** Summary returned by one nightly review dispatch pass. */@@ -108,22 +120,40 @@ export interface NightlyReviewScheduleSummary {/** Nightly review scheduler service API. */export interface NightlyReviewScheduleService {/**- * Dispatches nightly review request sources for users currently in their local night window.+ * Dispatches nightly review request sources for exactly one user.** Use when:- * - A shared cron or QStash schedule performs one central dispatch pass- * - Cron should only produce source events and leave review execution to AgentSignal handlers+ * - The execution workflow owns one user from a paginated scheduler page+ * - Review execution should remain bounded by the per-user target limit** Expects:- * - Adapters return users and targets without side effects except `enqueueSource`- * - `now` is a UTC instant shared by all users in the pass+ * - `requestedAt` is shared by every user execution from the same schedule run+ * - The user came from {@link listEligibleUsersPage}** Returns:- * - A summary with enqueue and skip counts for observability+ * - A summary with enqueue and skip counts for this user*/- dispatchNightlyReviewRequests: (- options?: DispatchNightlyReviewRequestsOptions,+ dispatchNightlyReviewForUser: (+ options: DispatchNightlyReviewForUserOptions,) => Promise<NightlyReviewScheduleSummary>;++ /**+ * Lists exactly one stable cursor page of users.+ *+ * Use when:+ * - The pagination workflow needs one bounded page before fan-out+ * - A next workflow invocation will continue from the returned cursor+ *+ * Expects:+ * - `limit` is a positive, externally bounded page size+ * - The adapter sorts users by `createdAt, id`+ *+ * Returns:+ * - The current users and a next cursor only when the page is full+ */+ listEligibleUsersPage: (+ options: ListNightlyReviewEligibleUsersPageOptions,+ ) => Promise<NightlyReviewEligibleUsersPage>;}interface LocalNightWindow {@@ -176,96 +206,65 @@ const getLocalNightWindow = (now: Date, timezone: string | null | undefined): Lo* - Invalid timezone values can be safely normalized to UTC** Returns:- * - A scheduler service with one dispatch method+ * - A scheduler service with bounded page-listing and single-user dispatch methods*/export const createSelfReviewScheduleService = (adapters: NightlyReviewScheduleAdapters,): NightlyReviewScheduleService => {return {- dispatchNightlyReviewRequests: async (options = {}) => {+ dispatchNightlyReviewForUser: async (options) => {return tracer.startActiveSpan(- 'agent_signal.nightly_review.schedule.dispatch',+ 'agent_signal.nightly_review.schedule.execute_user',{attributes: {- 'agent.signal.nightly.limit': options.limit ?? 0,'agent.signal.nightly.target_limit': options.targetLimit ?? 0,- 'agent.signal.nightly.whitelist_count': options.whitelist?.length ?? 0,+ 'agent.signal.nightly.user_id': options.user.id,},},async (span) => {try {- const now = adapters.now?.() ?? new Date();+ const now = options.requestedAt;let enqueued = 0;let skipped = 0;let targetCount = 0;- let userCount = 0;-- // Traverse every page of eligible users. `listEligibleUsers` is- // keyset-paginated (createdAt, id); without a cursor the caller- // would repeatedly scan the same oldest `limit` users and never- // reach users beyond row `limit` (e.g. when the lab filter was- // removed and all users are candidates).- let cursor = options.cursor;- while (true) {- const users = await adapters.listEligibleUsers({- cursor,- limit: options.limit,- whitelist: options.whitelist,- });- if (users.length === 0) break;- userCount += users.length;+ const localWindow = getLocalNightWindow(now, options.user.timezone);- for (const user of users) {- const localWindow = getLocalNightWindow(now, user.timezone);-- if (!localWindow.withinWindow) {- skipped += 1;- continue;- }+ if (!localWindow.withinWindow) {+ skipped = 1;+ } else {+ const targets = await adapters.listActiveAgentTargets({+ limit: options.targetLimit,+ userId: options.user.id,+ windowEnd: localWindow.reviewWindowEnd,+ windowStart: localWindow.reviewWindowStart,+ });- const targets = await adapters.listActiveAgentTargets({- limit: options.targetLimit,- userId: user.id,- windowEnd: localWindow.reviewWindowEnd,- windowStart: localWindow.reviewWindowStart,+ targetCount = targets.length;++ for (const target of targets) {+ await adapters.enqueueSource({+ payload: {+ agentId: target.agentId,+ localDate: localWindow.localDate,+ requestedAt: now.toISOString(),+ reviewWindowEnd: localWindow.reviewWindowEnd.toISOString(),+ reviewWindowStart: localWindow.reviewWindowStart.toISOString(),+ timezone: localWindow.timezone,+ userId: options.user.id,+ },+ sourceId: buildNightlyReviewSourceId({+ agentId: target.agentId,+ localDate: localWindow.localDate,+ userId: options.user.id,+ }),+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: now.getTime(),});-- targetCount += targets.length;-- for (const target of targets) {- await adapters.enqueueSource({- payload: {- agentId: target.agentId,- localDate: localWindow.localDate,- requestedAt: now.toISOString(),- reviewWindowEnd: localWindow.reviewWindowEnd.toISOString(),- reviewWindowStart: localWindow.reviewWindowStart.toISOString(),- timezone: localWindow.timezone,- userId: user.id,- },- sourceId: buildNightlyReviewSourceId({- agentId: target.agentId,- localDate: localWindow.localDate,- userId: user.id,- }),- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,- timestamp: now.getTime(),- });- enqueued += 1;- }+ enqueued += 1;}-- // Stop when the last page returned fewer rows than the page- // size (or when no limit is set and the query is unbounded).- if (options.limit === undefined || users.length < options.limit) break;-- const lastUser = users[users.length - 1];- if (!lastUser.createdAt) break;- cursor = { createdAt: lastUser.createdAt, id: lastUser.id };}- span.setAttribute('agent.signal.nightly.user_count', userCount);span.setAttribute('agent.signal.nightly.target_count', targetCount);span.setAttribute('agent.signal.nightly.enqueued', enqueued);span.setAttribute('agent.signal.nightly.skipped', skipped);@@ -282,6 +281,46 @@ export const createSelfReviewScheduleService = (});span.recordException(error as Error);+ throw error;+ } finally {+ span.end();+ }+ },+ );+ },+ listEligibleUsersPage: async (options) => {+ return tracer.startActiveSpan(+ 'agent_signal.nightly_review.schedule.list_user_page',+ {+ attributes: {+ 'agent.signal.nightly.limit': options.limit,+ 'agent.signal.nightly.whitelist_count': options.whitelist?.length ?? 0,+ },+ },+ async (span) => {+ try {+ const users = await adapters.listEligibleUsers(options);+ const lastUser = users.at(-1);+ const nextCursor =+ users.length === options.limit && lastUser+ ? { createdAt: lastUser.createdAt, id: lastUser.id }+ : undefined;++ span.setAttribute('agent.signal.nightly.user_count', users.length);+ span.setAttribute('agent.signal.nightly.has_next_page', Boolean(nextCursor));+ span.setStatus({ code: SpanStatusCode.OK });++ return { nextCursor, users };+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly review user pagination failed',+ });+ span.recordException(error as Error);+throw error;} finally {span.end();diff --git a/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts b/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.tsnew file mode 100644index 00000000000..7306d135caa--- /dev/null+++ b/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentSignalNightlyReviewWorkflow } from '../nightlyReview';++const mocks = vi.hoisted(() => ({+ injectActiveTraceHeaders: vi.fn((headers: Headers) => {+ headers.set('traceparent', '00-trace-parent');+ }),+ trigger: vi.fn(),+}));++vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: 'https://public.example.com',+ INTERNAL_APP_URL: 'https://internal.example.com',+ },+}));++vi.mock('@/libs/observability/traceparent', () => ({+ injectActiveTraceHeaders: mocks.injectActiveTraceHeaders,+}));++vi.mock('@/libs/qstash', () => ({+ workflowClient: {+ trigger: mocks.trigger,+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ mocks.trigger.mockResolvedValue({ workflowRunId: 'workflow-1' });+});++describe('AgentSignalNightlyReviewWorkflow', () => {+ it('triggers serialized pagination with global single-run flow control', async () => {+ /**+ * @example+ * expect(trigger).toHaveBeenCalledWith(expect.objectContaining({ flowControl }));+ */+ const payload = {+ pageSize: 50,+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 20,+ };++ await expect(AgentSignalNightlyReviewWorkflow.triggerPaginateUsers(payload)).resolves.toEqual({+ workflowRunId: 'workflow-1',+ });+ expect(mocks.trigger).toHaveBeenCalledWith({+ body: payload,+ flowControl: {+ key: 'agent-signal.nightly-review.paginate-users',+ parallelism: 1,+ },+ headers: { traceparent: '00-trace-parent' },+ url: 'https://internal.example.com/api/workflows/agent-signal/paginate-nightly-review-users',+ });+ });++ it('triggers one user execution with bounded concurrency', async () => {+ /**+ * @example+ * expect(trigger).toHaveBeenCalledWith(expect.objectContaining({ flowControl }));+ */+ const payload = {+ requestedAt: '2026-05-03T18:30:00.000Z',+ targetLimit: 5,+ user: {+ createdAt: '2026-01-01T00:00:00.000Z',+ id: 'user-1',+ timezone: 'Asia/Shanghai',+ },+ };++ await expect(AgentSignalNightlyReviewWorkflow.triggerExecuteUser(payload)).resolves.toEqual({+ workflowRunId: 'workflow-1',+ });+ expect(mocks.trigger).toHaveBeenCalledWith({+ body: payload,+ flowControl: {+ key: 'agent-signal.nightly-review.execute-user',+ parallelism: 5,+ },+ headers: { traceparent: '00-trace-parent' },+ url: 'https://internal.example.com/api/workflows/agent-signal/execute-nightly-review-user',+ });+ });+});diff --git a/apps/server/src/workflows/agentSignal/nightlyReview.ts b/apps/server/src/workflows/agentSignal/nightlyReview.tsnew file mode 100644index 00000000000..628f99247c9--- /dev/null+++ b/apps/server/src/workflows/agentSignal/nightlyReview.ts@@ -0,0 +1,164 @@+import type { FlowControl } from '@upstash/qstash';+import debug from 'debug';++import { appEnv } from '@/envs/app';+import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';+import { workflowClient } from '@/libs/qstash';++const log = debug('lobe-server:workflows:agent-signal:nightly-review');++const WORKFLOW_PATHS = {+ executeUser: '/api/workflows/agent-signal/execute-nightly-review-user',+ paginateUsers: '/api/workflows/agent-signal/paginate-nightly-review-users',+} as const;++/**+ * Stable flow-control key for nightly-review pagination.+ *+ * Use when:+ * - Triggering or serving a pagination workflow+ *+ * Expects:+ * - Trigger-side and serve-side configuration use the same key+ *+ * Returns:+ * - A global serialization key for bounded cursor traversal+ */+export const NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY =+ 'agent-signal.nightly-review.paginate-users';++/**+ * Stable flow-control key for per-user nightly-review execution.+ *+ * Use when:+ * - Triggering or serving a single-user execution workflow+ *+ * Expects:+ * - Trigger-side and serve-side configuration use the same key+ *+ * Returns:+ * - A global concurrency key for bounded user fan-out+ */+export const NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY = 'agent-signal.nightly-review.execute-user';++/** Serialized stable cursor passed between nightly-review pagination workflows. */+export interface NightlyReviewWorkflowCursor {+ /** ISO timestamp of the last user in the previous page. */+ createdAt: string;+ /** Stable id of the last user in the previous page. */+ id: string;+}++/** One user item passed from pagination to a single-user execution workflow. */+export interface NightlyReviewWorkflowUser {+ /** ISO creation timestamp retained for stable item identity across workflow boundaries. */+ createdAt: string;+ /** Stable user id. */+ id: string;+ /** IANA timezone used to determine whether the user is in the local night window. */+ timezone?: string | null;+}++/** Payload for one cursor page or one bounded fan-out chunk. */+export interface PaginateNightlyReviewUsersPayload {+ /** Cursor from the previous page; absent for the first page or a fan-out chunk. */+ cursor?: NightlyReviewWorkflowCursor;+ /** Number of users read from the database in one page. */+ pageSize: number;+ /** UTC instant shared by the complete pagination tree. */+ requestedAt: string;+ /** Maximum active agents dispatched for each user. */+ targetLimit: number;+ /** Users supplied by a fan-out chunk; each is scheduled for one execution workflow. */+ users?: NightlyReviewWorkflowUser[];+ /** Optional user allowlist for targeted backfills and tests. */+ whitelist?: string[];+}++/** Payload for a workflow that processes exactly one nightly-review user. */+export interface ExecuteNightlyReviewUserPayload {+ /** UTC instant shared by the complete pagination tree. */+ requestedAt: string;+ /** Maximum active agents dispatched for this user. */+ targetLimit: number;+ /** The single user owned by this workflow run. */+ user: NightlyReviewWorkflowUser;+}++const getWorkflowUrl = (path: string): string => {+ const baseUrl = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;++ if (!baseUrl) {+ throw new Error('INTERNAL_APP_URL or APP_URL is required to trigger nightly review workflows');+ }++ return new URL(path, baseUrl).toString();+};++const getTriggerHeaders = (): Record<string, string> => {+ const headers = new Headers();++ // Upstash forwards user headers only when they are supplied to `trigger`, so trace context must+ // cross every pagination/execution network hop explicitly.+ injectActiveTraceHeaders(headers);++ return Object.fromEntries(headers.entries());+};++/**+ * Triggers the cursor-pagination and single-user layers of nightly review scheduling.+ *+ * Use when:+ * - The cron entry needs to start a bounded user pagination tree+ * - The pagination layer needs to fan out user executions or continue with the next cursor+ *+ * Expects:+ * - Payload timestamps and cursors are JSON-safe ISO strings+ * - Source-event idempotency remains owned by the Agent Signal execution layer+ *+ * Returns:+ * - Upstash workflow trigger metadata for the newly scheduled child run+ *+ * Call stack:+ *+ * scheduleNightlyReview+ * -> {@link AgentSignalNightlyReviewWorkflow.triggerPaginateUsers}+ * -> paginateNightlyReviewUsers+ * -> {@link AgentSignalNightlyReviewWorkflow.triggerExecuteUser}+ * -> executeNightlyReviewUser+ */+export class AgentSignalNightlyReviewWorkflow {+ /** Triggers one database page or one bounded fan-out chunk. */+ static triggerPaginateUsers(payload: PaginateNightlyReviewUsersPayload) {+ log('Triggering nightly review user pagination payload=%O', {+ cursor: payload.cursor,+ pageSize: payload.pageSize,+ users: payload.users?.length ?? 0,+ });++ return workflowClient.trigger({+ body: payload,+ flowControl: {+ key: NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,+ parallelism: 1,+ } satisfies FlowControl,+ headers: getTriggerHeaders(),+ url: getWorkflowUrl(WORKFLOW_PATHS.paginateUsers),+ });+ }++ /** Triggers one workflow that processes exactly one user. */+ static triggerExecuteUser(payload: ExecuteNightlyReviewUserPayload) {+ log('Triggering nightly review execution userId=%s', payload.user.id);++ return workflowClient.trigger({+ body: payload,+ flowControl: {+ key: NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY,+ parallelism: 5,+ } satisfies FlowControl,+ headers: getTriggerHeaders(),+ url: getWorkflowUrl(WORKFLOW_PATHS.executeUser),+ });+ }+}diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.tsindex df6bc0372ab..2217abf78c4 100644--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { INBOX_SESSION_ID } from '@lobechat/const';+import { sql } from 'drizzle-orm';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';@@ -91,6 +92,37 @@ describe('AgentSignalNightlyReviewModel', () => {},]);});++ /**+ * @example+ * expect(nextPage.map((user) => user.id)).toEqual(['nightly-review-microsecond-next']);+ */+ it('does not repeat a cursor row whose database timestamp has sub-millisecond precision', async () => {+ // ROOT CAUSE:+ //+ // PostgreSQL timestamps can retain microseconds while JavaScript Date and workflow JSON retain+ // only milliseconds. Comparing the truncated Date back to created_at made the cursor row appear+ // newer than itself and caused an unbounded pagination loop.+ //+ // Before: created_at .000123 > replayed cursor .000, so the same user was returned again.+ // After: the cursor id restores the exact (created_at, id) tuple inside PostgreSQL.+ await serverDB.execute(sql`+ INSERT INTO users (id, created_at, updated_at, last_active_at)+ VALUES+ ('nightly-review-microsecond-cursor', '2026-05-01T00:00:00.000123Z', NOW(), NOW()),+ ('nightly-review-microsecond-next', '2026-05-02T00:00:00.000456Z', NOW(), NOW())+ `);++ const model = new AgentSignalNightlyReviewModel(serverDB);+ const firstPage = await model.listEligibleUsers({ limit: 1 });+ const nextPage = await model.listEligibleUsers({+ cursor: { createdAt: firstPage[0].createdAt, id: firstPage[0].id },+ limit: 1,+ });++ expect(firstPage.map((user) => user.id)).toEqual(['nightly-review-microsecond-cursor']);+ expect(nextPage.map((user) => user.id)).toEqual(['nightly-review-microsecond-next']);+ });});describe('listActiveAgentTargets', () => {diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 8a58d82f914..dd7633d495a 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -5,7 +5,6 @@ import {count,countDistinct,eq,- gt,gte,inArray,isNull,@@ -13,11 +12,15 @@ import {or,sql,} from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';+/** Restores the cursor timestamp inside PostgreSQL so workflow JSON never truncates its precision. */+const cursorUsers = alias(users, 'nightly_review_cursor_users');+/*** Normalizes database aggregate timestamps.*@@ -32,9 +35,9 @@ const parseAggregateTimestamp = (value: Date | string) =>/** Cursor for stable user pagination in AgentSignal nightly review scheduling. */export interface ListAgentSignalNightlyReviewUsersCursor {- /** User creation time used as the primary cursor key. */+ /** User creation time retained in the serialized checkpoint for observability. */createdAt: Date;- /** User id used as the tie-break cursor key. */+ /** User id used to restore the exact database cursor tuple. */id: string;}@@ -126,11 +129,15 @@ export class AgentSignalNightlyReviewModel {* - Users sorted by `createdAt, id` for deterministic pagination*/listEligibleUsers = (options: ListAgentSignalNightlyReviewUsersOptions = {}) => {+ const cursorTuple = options.cursor+ ? this.db+ .select({ createdAt: cursorUsers.createdAt, id: cursorUsers.id })+ .from(cursorUsers)+ .where(eq(cursorUsers.id, options.cursor.id))+ .limit(1)+ : undefined;const cursorCondition = options.cursor- ? or(- gt(users.createdAt, options.cursor.createdAt),- and(eq(users.createdAt, options.cursor.createdAt), gt(users.id, options.cursor.id)),- )+ ? sql`(${users.createdAt}, ${users.id}) > (${cursorTuple})`: undefined;const whitelistCondition =