🤯 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
feat: add createImageBusinessMiddleware to enhance image creation process
YuTengjing954789dc4ebb
diff --git a/src/business/server/trpc-middlewares/async.ts b/src/business/server/trpc-middlewares/async.tsindex 9ac120f9401..4a4c865c99a 100644--- a/src/business/server/trpc-middlewares/async.ts+++ b/src/business/server/trpc-middlewares/async.ts@@ -7,3 +7,7 @@ export const checkEmbeddingUsage = asyncTrpc.middleware(async (opts) => {export const checkBudgetsUsage = asyncTrpc.middleware(async (opts) => {return opts.next();});++export const createImageBusinessMiddleware = asyncTrpc.middleware(async (opts) => {+ return opts.next();+});diff --git a/src/server/routers/async/image.ts b/src/server/routers/async/image.tsindex cd3f2756ab8..7fa7e3c2eec 100644--- a/src/server/routers/async/image.ts+++ b/src/server/routers/async/image.ts@@ -7,6 +7,7 @@ import { type RuntimeImageGenParams } from 'model-bank';import { z } from 'zod';import { chargeAfterGenerate } from '@/business/server/image-generation/chargeAfterGenerate';+import { createImageBusinessMiddleware } from '@/business/server/trpc-middlewares/async';import { AsyncTaskModel } from '@/database/models/asyncTask';import { FileModel } from '@/database/models/file';import { GenerationModel } from '@/database/models/generation';@@ -187,201 +188,212 @@ const categorizeError = (};export const imageRouter = router({- createImage: imageProcedure.input(createImageInputSchema).mutation(async ({ input, ctx }) => {- const { taskId, generationId, generationBatchId, generationTopicId, provider, model, params } =- input;-- log('Starting async image generation: %O', {- generationId,- imageParams: {- cfg: params.cfg,- height: params.height,- steps: params.steps,- width: params.width,- },- model,- prompt: params.prompt,- provider,- taskId,- });-- log('Updating task status to Processing: %s', taskId);- await ctx.asyncTaskModel.update(taskId, { status: AsyncTaskStatus.Processing });-- // Use AbortController to prevent resource leaks- const abortController = new AbortController();- let timeoutId: ReturnType<typeof setTimeout> | null = null;-- const isEditingImage =- Boolean((params as any).imageUrl) || Boolean(params.imageUrls && params.imageUrls.length > 0);-- try {- const imageGenerationPromise = async (signal: AbortSignal) => {- log('Initializing agent runtime for provider: %s', provider);-- const agentRuntime = initModelRuntimeWithUserPayload(provider, ctx.jwtPayload);-- // Check if operation has been cancelled- checkAbortSignal(signal);- log('Agent runtime initialized, calling createImage');- const response = await agentRuntime.createImage!({- model,- params: params as unknown as RuntimeImageGenParams,- });+ createImage: imageProcedure+ .use(createImageBusinessMiddleware)+ .input(createImageInputSchema)+ .mutation(async ({ input, ctx }) => {+ const {+ taskId,+ generationId,+ generationBatchId,+ generationTopicId,+ provider,+ model,+ params,+ } = input;++ log('Starting async image generation: %O', {+ generationId,+ imageParams: {+ cfg: params.cfg,+ height: params.height,+ steps: params.steps,+ width: params.width,+ },+ model,+ prompt: params.prompt,+ provider,+ taskId,+ });- if (!response) {- log('Create image response is empty');- throw new Error('Create image response is empty');- }+ log('Updating task status to Processing: %s', taskId);+ await ctx.asyncTaskModel.update(taskId, { status: AsyncTaskStatus.Processing });- log('Create image response: %O', {- ...response,- imageUrl: response.imageUrl?.startsWith('data:')- ? response.imageUrl.slice(0, IMAGE_URL_PREVIEW_LENGTH) + '...'- : response.imageUrl,- });+ // Use AbortController to prevent resource leaks+ const abortController = new AbortController();+ let timeoutId: ReturnType<typeof setTimeout> | null = null;- const { modelUsage } = response;+ const isEditingImage =+ Boolean((params as any).imageUrl) ||+ Boolean(params.imageUrls && params.imageUrls.length > 0);- if (ENABLE_BUSINESS_FEATURES) {- await chargeAfterGenerate({- metadata: {- asyncTaskId: taskId,- generationBatchId: generationBatchId,- modelId: model,- topicId: generationTopicId,- },- modelUsage,- provider,- userId: ctx.userId,- });- }+ try {+ const imageGenerationPromise = async (signal: AbortSignal) => {+ log('Initializing agent runtime for provider: %s', provider);- // Check if operation has been cancelled- checkAbortSignal(signal);+ const agentRuntime = initModelRuntimeWithUserPayload(provider, ctx.jwtPayload);- log('Image generation successful: %O', {- height: response.height,- imageUrl: response.imageUrl.startsWith('data:')- ? response.imageUrl.slice(0, IMAGE_URL_PREVIEW_LENGTH) + '...'- : response.imageUrl,- width: response.width,- });+ // Check if operation has been cancelled+ checkAbortSignal(signal);+ log('Agent runtime initialized, calling createImage');+ const response = await agentRuntime.createImage!({+ model,+ params: params as unknown as RuntimeImageGenParams,+ });- log('Transforming image for generation');- const { imageUrl, width, height } = response;-- // Extract ComfyUI authentication headers if provider is ComfyUI- let authHeaders: Record<string, string> | undefined;- if (provider === 'comfyui') {- // Use the public interface method to get auth headers- // This avoids accessing private members and exposing credentials- authHeaders = agentRuntime.getAuthHeaders();- if (authHeaders) {- log('Using authentication headers for ComfyUI image download');- } else {- log('No authentication configured for ComfyUI');+ if (!response) {+ log('Create image response is empty');+ throw new Error('Create image response is empty');}- }- const { image, thumbnailImage } = await ctx.generationService.transformImageForGeneration(- imageUrl,- authHeaders,- );+ log('Create image response: %O', {+ ...response,+ imageUrl: response.imageUrl?.startsWith('data:')+ ? response.imageUrl.slice(0, IMAGE_URL_PREVIEW_LENGTH) + '...'+ : response.imageUrl,+ });- // Check if operation has been cancelled- checkAbortSignal(signal);+ const { modelUsage } = response;++ if (ENABLE_BUSINESS_FEATURES) {+ await chargeAfterGenerate({+ metadata: {+ asyncTaskId: taskId,+ generationBatchId: generationBatchId,+ modelId: model,+ topicId: generationTopicId,+ },+ modelUsage,+ provider,+ userId: ctx.userId,+ });+ }- log('Uploading image for generation');- const { imageUrl: uploadedImageUrl, thumbnailImageUrl } =- await ctx.generationService.uploadImageForGeneration(image, thumbnailImage);+ // Check if operation has been cancelled+ checkAbortSignal(signal);- // Check if operation has been cancelled- checkAbortSignal(signal);+ log('Image generation successful: %O', {+ height: response.height,+ imageUrl: response.imageUrl.startsWith('data:')+ ? response.imageUrl.slice(0, IMAGE_URL_PREVIEW_LENGTH) + '...'+ : response.imageUrl,+ width: response.width,+ });- log('Updating generation asset and file');- await ctx.generationModel.createAssetAndFile(- generationId,- {- height: height ?? image.height,- // If imageUrl is base64 data, use uploadedImageUrl instead to avoid storing large base64 in DB- originalUrl: imageUrl.startsWith('data:') ? uploadedImageUrl : imageUrl,- thumbnailUrl: thumbnailImageUrl,- type: 'image',- url: uploadedImageUrl,- width: width ?? image.width,- },- {- fileHash: image.hash,- fileType: image.mime,- metadata: {- generationId,- height: image.height,- path: uploadedImageUrl,- width: image.width,+ log('Transforming image for generation');+ const { imageUrl, width, height } = response;++ // Extract ComfyUI authentication headers if provider is ComfyUI+ let authHeaders: Record<string, string> | undefined;+ if (provider === 'comfyui') {+ // Use the public interface method to get auth headers+ // This avoids accessing private members and exposing credentials+ authHeaders = agentRuntime.getAuthHeaders();+ if (authHeaders) {+ log('Using authentication headers for ComfyUI image download');+ } else {+ log('No authentication configured for ComfyUI');+ }+ }++ const { image, thumbnailImage } = await ctx.generationService.transformImageForGeneration(+ imageUrl,+ authHeaders,+ );++ // Check if operation has been cancelled+ checkAbortSignal(signal);++ log('Uploading image for generation');+ const { imageUrl: uploadedImageUrl, thumbnailImageUrl } =+ await ctx.generationService.uploadImageForGeneration(image, thumbnailImage);++ // Check if operation has been cancelled+ checkAbortSignal(signal);++ log('Updating generation asset and file');+ await ctx.generationModel.createAssetAndFile(+ generationId,+ {+ height: height ?? image.height,+ // If imageUrl is base64 data, use uploadedImageUrl instead to avoid storing large base64 in DB+ originalUrl: imageUrl.startsWith('data:') ? uploadedImageUrl : imageUrl,+ thumbnailUrl: thumbnailImageUrl,+ type: 'image',+ url: uploadedImageUrl,+ width: width ?? image.width,},- name: `${params.prompt.slice(0, FILENAME_MAX_LENGTH)}.${image.extension}`,- // Use first 50 characters of prompt as filename- size: image.size,- url: uploadedImageUrl,- },- );+ {+ fileHash: image.hash,+ fileType: image.mime,+ metadata: {+ generationId,+ height: image.height,+ path: uploadedImageUrl,+ width: image.width,+ },+ name: `${params.prompt.slice(0, FILENAME_MAX_LENGTH)}.${image.extension}`,+ // Use first 50 characters of prompt as filename+ size: image.size,+ url: uploadedImageUrl,+ },+ );- log('Updating task status to Success: %s', taskId);- await ctx.asyncTaskModel.update(taskId, {- status: AsyncTaskStatus.Success,- });+ log('Updating task status to Success: %s', taskId);+ await ctx.asyncTaskModel.update(taskId, {+ status: AsyncTaskStatus.Success,+ });- log('Async image generation completed successfully: %s', taskId);- return { success: true };- };+ log('Async image generation completed successfully: %s', taskId);+ return { success: true };+ };- // Set timeout to cancel operation and prevent resource leaks- timeoutId = setTimeout(() => {- log('Image generation timeout, aborting operation: %s', taskId);- abortController.abort();- }, ASYNC_TASK_TIMEOUT);+ // Set timeout to cancel operation and prevent resource leaks+ timeoutId = setTimeout(() => {+ log('Image generation timeout, aborting operation: %s', taskId);+ abortController.abort();+ }, ASYNC_TASK_TIMEOUT);- const result = await imageGenerationPromise(abortController.signal);+ const result = await imageGenerationPromise(abortController.signal);- // Clean up timeout timer- if (timeoutId) {- clearTimeout(timeoutId);- timeoutId = null;- }+ // Clean up timeout timer+ if (timeoutId) {+ clearTimeout(timeoutId);+ timeoutId = null;+ }- return result;- } catch (error: any) {- // Clean up timeout timer- if (timeoutId) {- clearTimeout(timeoutId);- timeoutId = null;- }+ return result;+ } catch (error: any) {+ // Clean up timeout timer+ if (timeoutId) {+ clearTimeout(timeoutId);+ timeoutId = null;+ }- log('Async image generation failed: %O', {- error: error.message || error,- generationId,- taskId,- });+ log('Async image generation failed: %O', {+ error: error.message || error,+ generationId,+ taskId,+ });- // Improved error categorization logic- const { errorType, errorMessage } = categorizeError(- error,- abortController.signal.aborted,- isEditingImage,- );+ // Improved error categorization logic+ const { errorType, errorMessage } = categorizeError(+ error,+ abortController.signal.aborted,+ isEditingImage,+ );- await ctx.asyncTaskModel.update(taskId, {- error: new AsyncTaskError(errorType, errorMessage),- status: AsyncTaskStatus.Error,- });+ await ctx.asyncTaskModel.update(taskId, {+ error: new AsyncTaskError(errorType, errorMessage),+ status: AsyncTaskStatus.Error,+ });- log('Task status updated to Error: %s, errorType: %s', taskId, errorType);+ log('Task status updated to Error: %s, errorType: %s', taskId, errorType);- return {- message: `Image generation ${taskId} failed: ${errorMessage}`,- success: false,- };- }- }),+ return {+ message: `Image generation ${taskId} failed: ${errorMessage}`,+ success: false,+ };+ }+ }),});