🤯 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(userMemories): completely removed serveMany
Neko Ayaka6ad7cd518c66
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic-layers/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic-layers/route.tsdeleted file mode 100644index 95d7fab5ad6..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic-layers/route.ts+++ /dev/null@@ -1,55 +0,0 @@-import { MemorySourceType } from '@lobechat/types';-import { serve } from '@upstash/workflow/nextjs';--import {- MemoryExtractionExecutor,- type MemoryExtractionPayloadInput,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});- if (!params.userIds.length) {- return { message: 'No user id provided for topic batch.', processed: 0, results: [] };- }- if (!params.topicIds.length) {- return { message: 'No topic ids provided for extraction.', processed: 0, results: [] };- }- if (!params.sources.includes(MemorySourceType.ChatTopic)) {- return { message: 'Source not supported in topic batch.', processed: 0, results: [] };- }-- const userId = params.userIds[0];- const executor = await MemoryExtractionExecutor.create();-- const results: {- extracted: boolean;- layers: Record<string, number>;- memoryIds: string[];- topicId: string;- userId: string;- }[] = [];-- for (const topicId of params.topicIds) {- console.log(`[chat-topic][process-topic-layers] Processing topic ${topicId} for user ${userId} with layers:`, params.layers);-- const extracted = await context.run(- `memory:user-memory:extract:users:${userId}:topics:${topicId}:extract-topic-other-layers`,- () =>- executor.extractTopic({- forceAll: params.forceAll,- forceTopics: params.forceTopics,- from: params.from,- layers: params.layers,- source: MemorySourceType.ChatTopic,- to: params.to,- topicId,- userId,- }),- );-- results.push({ ...extracted, topicId, userId });- }-- return { processed: results.length, results };-});diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.tsnew file mode 100644index 00000000000..af7b1f2a78e--- /dev/null+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts@@ -0,0 +1,80 @@+import { LayersEnum, MemorySourceType } from '@lobechat/types';+import { serve } from '@upstash/workflow/nextjs';++import {+ MemoryExtractionExecutor,+ type MemoryExtractionPayloadInput,+ normalizeMemoryExtractionPayload,+} from '@/server/services/memory/userMemory/extract';++const CEP_LAYERS: LayersEnum[] = [LayersEnum.Context, LayersEnum.Experience, LayersEnum.Preference];+const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];++export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {+ const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});++ console.log('[chat-topic][batch] Starting batch topic processing workflow', {+ topicIds: payload.topicIds,+ userIds: payload.userIds,+ });++ if (!payload.userIds.length) {+ return { message: 'No user id provided for topic batch.', processedTopics: 0, processedUsers: 0 };+ }+ if (!payload.topicIds.length) {+ return { message: 'No topic ids provided for extraction.', processedTopics: 0, processedUsers: 0 };+ }+ if (!payload.sources.includes(MemorySourceType.ChatTopic)) {+ return { message: 'Source not supported in topic batch.', processedTopics: 0, processedUsers: 0 };+ }++ const userId = payload.userIds[0];+ const executor = await MemoryExtractionExecutor.create();++ // CEP: run in parallel across the batch+ await Promise.all(+ payload.topicIds.map((topicId, index) =>+ context.run(+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:cep:${index}`,+ () =>+ executor.extractTopic({+ forceAll: payload.forceAll,+ forceTopics: payload.forceTopics,+ from: payload.from,+ layers: CEP_LAYERS,+ source: MemorySourceType.ChatTopic,+ to: payload.to,+ topicId,+ userId,+ }),+ ),+ ),+ );++ // Identity: run sequentially for the batch+ for (const [index, topicId] of payload.topicIds.entries()) {+ await context.run(+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity:${index}`,+ () =>+ executor.extractTopic({+ forceAll: payload.forceAll,+ forceTopics: payload.forceTopics,+ from: payload.from,+ layers: IDENTITY_LAYERS,+ source: MemorySourceType.ChatTopic,+ to: payload.to,+ topicId,+ userId,+ }),+ );+ }++ console.log('[chat-topic][batch] Batch topic processing workflow completed', {+ processedTopics: payload.topicIds.length,+ });++ return {+ processedTopics: payload.topicIds.length,+ processedUsers: payload.userIds.length,+ };+});diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/[workflowId]/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/[workflowId]/route.tsdeleted file mode 100644index fcf38351a38..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/[workflowId]/route.ts+++ /dev/null@@ -1,10 +0,0 @@-import { serveMany } from '@upstash/workflow/nextjs';--import { TOPIC_WORKFLOW_NAMES } from '@/server/services/memory/userMemory/extract';-import { cepWorkflow, identityWorkflow, orchestratorWorkflow } from '../workflows';--export const { POST } = serveMany({- [TOPIC_WORKFLOW_NAMES.orchestrator]: orchestratorWorkflow,- [TOPIC_WORKFLOW_NAMES.cep]: cepWorkflow,- [TOPIC_WORKFLOW_NAMES.identity]: identityWorkflow,-});diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/batch/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/batch/route.tsdeleted file mode 100644index 0339127cdbe..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/batch/route.ts+++ /dev/null@@ -1,33 +0,0 @@-import { serve } from '@upstash/workflow/nextjs';--import {- type MemoryExtractionPayloadInput,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--import { orchestratorWorkflow } from '../workflows';--export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {- const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});-- console.log('[chat-topic][batch] Starting batch topic processing workflow', {- topicIds: payload.topicIds,- userIds: payload.userIds,- });-- const { body, isCanceled, isFailed } = await context.invoke('memory:user-memory:extract:topics:batch', {- body: context.requestPayload,- workflow: orchestratorWorkflow,- });-- console.log('[chat-topic][batch] Batch topic processing workflow invoked', {- body,- isCanceled,- isFailed,- });-- return {- processedTopics: payload.topicIds.length,- processedUsers: payload.userIds.length,- };-});diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/workflows.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/workflows.tsdeleted file mode 100644index 76bcc0bd01f..00000000000--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/workflows.ts+++ /dev/null@@ -1,210 +0,0 @@-import { LayersEnum, MemorySourceType } from '@lobechat/types';-import { createWorkflow } from '@upstash/workflow/nextjs';--import {- MemoryExtractionExecutor,- type MemoryExtractionPayloadInput,- TOPIC_WORKFLOW_NAMES,- normalizeMemoryExtractionPayload,-} from '@/server/services/memory/userMemory/extract';--type ExtractionResult = {- extracted: boolean;- layers: Record<string, number>;- memoryIds: string[];- topicId: string;- userId: string;-};--// NOTICE: CEP stands for Context, Experience, Preference layers-const CEP_LAYERS: LayersEnum[] = [LayersEnum.Context, LayersEnum.Experience, LayersEnum.Preference];-const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];-const CEP_PARALLEL_BATCH_SIZE = 4;--const intersectLayers = (requested: LayersEnum[], allowed: LayersEnum[]) => {- if (!requested.length) return allowed;-- const requestedSet = new Set(requested);- return allowed.filter((layer) => requestedSet.has(layer));-};--export const createLayerWorkflow = (allowedLayers: LayersEnum[]) =>- createWorkflow<MemoryExtractionPayloadInput, { processed: number; results: ExtractionResult[] }>(- async (context) => {- console.log('[chat-topic][layer] Starting layer processing workflow', {- allowedLayers,- });-- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});- if (!params.userIds.length) {- return { message: 'No user id provided for topic batch.', processed: 0, results: [] };- }- if (!params.topicIds.length) {- return { message: 'No topic ids provided for extraction.', processed: 0, results: [] };- }- if (!params.sources.includes(MemorySourceType.ChatTopic)) {- return { message: 'Source not supported in topic batch.', processed: 0, results: [] };- }-- const userId = params.userIds[0];- // NOTICE:- // - if [contexts, preferences, experiences] are requested, we extract all 3 layers- // - if [identity] is requested, we extract only identity layer- // - if [contexts, preferences, experiences, identity] are requested, while allowedLayers is [contexts, preferences, experiences],- // we will extract only [contexts, preferences, experiences], [identity] will be filtered out- const layers = intersectLayers(params.layers, allowedLayers);- if (!layers.length) {- return { message: 'No layers to extract for requested batch.', processed: 0, results: [] };- }-- const executor = await MemoryExtractionExecutor.create();-- const results: ExtractionResult[] = [];-- for (const topicId of params.topicIds) {- console.log(`[chat-topic][layer] ${allowedLayers} processor processing topic ${topicId} for user ${userId} with layers:`, layers);-- const extracted = await context.run(- `memory:user-memory:extract:users:${userId}:topics:${topicId}:extract-topic-${layers.join(- '-',- )}`,- () =>- executor.extractTopic({- forceAll: params.forceAll,- forceTopics: params.forceTopics,- from: params.from,- layers,- source: MemorySourceType.ChatTopic,- to: params.to,- topicId,- userId,- }),- );-- console.log(`[chat-topic][layer] ${allowedLayers} processor finished topic ${topicId} for user ${userId}:`, extracted);-- results.push({ ...extracted, topicId, userId });- }-- return { processed: results.length, results };- },- );--export const cepWorkflow = createLayerWorkflow(CEP_LAYERS);-export const identityWorkflow = createLayerWorkflow(IDENTITY_LAYERS);--export const orchestratorWorkflow = createWorkflow<- MemoryExtractionPayloadInput,- {- nextIdentityCursor: number | null;- processedCep: number;- processedIdentity: number;- }->(async (context) => {- console.log('[chat-topic][orchestrator] Starting orchestrator workflow');-- const params = normalizeMemoryExtractionPayload(context.requestPayload || {});- if (!params.userIds.length) {- return {- message: 'No user id provided for topic batch.',- nextIdentityCursor: null,- processedCep: 0,- processedIdentity: 0,- };- }- if (!params.topicIds.length) {- return {- message: 'No topic ids provided for extraction.',- nextIdentityCursor: null,- processedCep: 0,- processedIdentity: 0,- };- }- if (!params.sources.includes(MemorySourceType.ChatTopic)) {- return {- message: 'Source not supported in topic batch.',- nextIdentityCursor: null,- processedCep: 0,- processedIdentity: 0,- };- }-- const userId = params.userIds[0];- const topicIds = params.topicIds;-- let cepIndex = 0;- let identityIndex = params.identityCursor ?? 0;-- const invokeCep = (batch: string[], batchIndex: number) =>- context.invoke(`memory:user-memory:extract:users:${userId}:topics:cep-batch:${batchIndex}`, {- body: { ...params, identityCursor: undefined, topicIds: batch, userId, userIds: [userId] },- flowControl: { key: `memory:user:${userId}:cep`, parallelism: 1 },- workflow: cepWorkflow,- });-- const invokeIdentity = (topicId: string, pointer: number) =>- context.invoke(`memory:user-memory:extract:users:${userId}:topics:identity:${pointer}`, {- body: {- ...params,- identityCursor: undefined,- topicIds: [topicId],- userId,- userIds: [userId],- },- flowControl: { key: `memory:user:${userId}:identity`, parallelism: 1 },- workflow: identityWorkflow,- });-- while (cepIndex < topicIds.length || identityIndex < topicIds.length) {- console.log('[chat-topic][orchestrator] Orchestrator progress', {- cepIndex,- identityIndex,- totalTopics: topicIds.length,- });-- if (cepIndex < topicIds.length) {- console.log('[chat-topic][orchestrator] Invoking CEP batch', { cepIndex });-- const cepBatch = topicIds.slice(cepIndex, cepIndex + CEP_PARALLEL_BATCH_SIZE);- const tasks: Promise<any>[] = [invokeCep(cepBatch, cepIndex)];-- const shouldRunIdentity = identityIndex < cepIndex && identityIndex < topicIds.length;- if (shouldRunIdentity) {- tasks.push(invokeIdentity(topicIds[identityIndex], identityIndex));- }-- await Promise.all(tasks);- console.log('[chat-topic][orchestrator] Finished CEP batch', { cepIndex });-- cepIndex += cepBatch.length;- if (shouldRunIdentity) {- identityIndex += 1;- }- } else if (identityIndex < topicIds.length) {- console.log('[chat-topic][orchestrator] Invoking remaining identity extraction', {- identityIndex,- topicId: topicIds[identityIndex],- });-- await invokeIdentity(topicIds[identityIndex], identityIndex);-- console.log('[chat-topic][orchestrator] Finished identity extraction', { identityIndex });- identityIndex += 1;- } else {- console.warn('[chat-topic][orchestrator] Unexpected state in orchestrator workflow');-- break;- }- }-- return {- nextIdentityCursor: identityIndex >= topicIds.length ? null : identityIndex,- processedCep: Math.min(cepIndex, topicIds.length),- processedIdentity: identityIndex - (params.identityCursor ?? 0),- };-});--// Explicitly set workflow ids to ensure context.invoke works-cepWorkflow.workflowId = TOPIC_WORKFLOW_NAMES.cep;-identityWorkflow.workflowId = TOPIC_WORKFLOW_NAMES.identity;-orchestratorWorkflow.workflowId = TOPIC_WORKFLOW_NAMES.orchestrator;diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.tsindex 0ab28844c72..79fb5505c68 100644--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts@@ -1,6 +1,4 @@import { serve } from '@upstash/workflow/nextjs';-import { chunk } from 'es-toolkit/compat';-import type { ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';import {MemoryExtractionExecutor,@@ -9,10 +7,11 @@ import {buildWorkflowPayloadInput,normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';+import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';import { MemorySourceType } from '@lobechat/types';const TOPIC_PAGE_SIZE = 50;-const TOPIC_BATCH_SIZE = 10;+const TOPIC_BATCH_SIZE = 4;export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {const params = normalizeMemoryExtractionPayload(context.requestPayload || {});@@ -87,25 +86,22 @@ export const { POST } = serve<MemoryExtractionPayloadInput>(async (context) => {const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;- const batches = chunk(ids, TOPIC_BATCH_SIZE);- // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path- // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow- // URLs would inherit that base and lose the desired /process-topics/workflows prefix.- await Promise.all(- batches.map((topicIds, index) =>- context.run(- `memory:user-memory:extract:users:${userId}:process-topics-batch:${index}`,- () =>- MemoryExtractionWorkflowService.triggerProcessTopics({- ...buildWorkflowPayloadInput(params),- topicCursor: undefined,- topicIds,- userId,- userIds: [userId],- }),- ),- ),- );+ await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {+ // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path+ // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow+ // URLs would inherit that base and lose the desired /process-topics/workflows prefix.+ await context.run(+ `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,+ () =>+ MemoryExtractionWorkflowService.triggerProcessTopics({+ ...buildWorkflowPayloadInput(params),+ topicCursor: undefined,+ topicIds,+ userId,+ userIds: [userId],+ }),+ );+ });if (!topicsFromPayload && cursor) {await context.run(diff --git a/src/server/services/memory/userMemory/__tests__/topicBatching.test.ts b/src/server/services/memory/userMemory/__tests__/topicBatching.test.tsnew file mode 100644index 00000000000..d489b83f81a--- /dev/null+++ b/src/server/services/memory/userMemory/__tests__/topicBatching.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it, vi } from 'vitest';++import { forEachBatchSequential } from '../topicBatching';++describe('forEachBatchSequential', () => {+ it('processes batches sequentially with the given size', async () => {+ const handler = vi.fn().mockResolvedValue(undefined);+ await forEachBatchSequential([1, 2, 3, 4, 5], 2, handler);++ expect(handler).toHaveBeenCalledTimes(3);+ expect(handler).toHaveBeenNthCalledWith(1, [1, 2], 0);+ expect(handler).toHaveBeenNthCalledWith(2, [3, 4], 1);+ expect(handler).toHaveBeenNthCalledWith(3, [5], 2);+ });++ it('throws when batch size is not positive', async () => {+ await expect(+ forEachBatchSequential([1, 2, 3], 0, async () => {}),+ ).rejects.toThrowError('batchSize must be greater than 0');+ });+});diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.tsindex 8d2d242199b..6dcf10852fa 100644--- a/src/server/services/memory/userMemory/extract.ts+++ b/src/server/services/memory/userMemory/extract.ts@@ -1762,18 +1762,11 @@ export class MemoryExtractionExecutor {}const WORKFLOW_PATHS = {- topicBatch:- '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/workflows/batch',+ topicBatch: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',userTopics: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics',users: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-users',} as const;-export const TOPIC_WORKFLOW_NAMES = {- cep: 'process-topics-extract-layers-cep',- identity: 'process-topics-extract-layers-identity',- orchestrator: 'process-topics-extract-layers-orchestrator',-} as const;-const getWorkflowUrl = (path: string, baseUrl: string) => {const url = new URL(path, baseUrl);diff --git a/src/server/services/memory/userMemory/topicBatching.ts b/src/server/services/memory/userMemory/topicBatching.tsnew file mode 100644index 00000000000..cdda7c1d0fe--- /dev/null+++ b/src/server/services/memory/userMemory/topicBatching.ts@@ -0,0 +1,14 @@+export const forEachBatchSequential = async <T>(+ items: T[],+ batchSize: number,+ handler: (batch: T[], batchIndex: number) => Promise<void>,+) => {+ if (batchSize <= 0) throw new Error('batchSize must be greater than 0');++ for (let start = 0, batchIndex = 0; start < items.length; start += batchSize, batchIndex += 1) {+ const batch = items.slice(start, start + batchSize);+ if (batch.length === 0) continue;+ // Sequential: wait for each batch before moving to the next+ await handler(batch, batchIndex);+ }+};