π€― 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: fail refused async tasks, guard JWT expiry and image types (#23135)
YuTengjing864bba4926f9
diff --git a/apps/server/src/routers/async/rejection.test.ts b/apps/server/src/routers/async/rejection.test.tsnew file mode 100644index 00000000000..c599415e832--- /dev/null+++ b/apps/server/src/routers/async/rejection.test.ts@@ -0,0 +1,78 @@+import { TRPCClientError } from '@trpc/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ ASYNC_REJECTION_WINDOW_MS,+ isAsyncCallRejectedBeforeRun,+ keepAliveForAsyncRejection,+} from './rejection';++const { afterUnscoped } = vi.hoisted(() => ({ afterUnscoped: vi.fn() }));++vi.mock('@/server/utils/scheduleAfterResponse', () => ({ afterUnscoped }));++const scheduledWork = () => afterUnscoped.mock.calls.at(-1)![0] as () => Promise<void>;++const settledWithin = async (work: Promise<void>, ms: number) => {+ let settled = false;+ void work.then(() => (settled = true));+ await vi.advanceTimersByTimeAsync(ms);+ return settled;+};++describe('isAsyncCallRejectedBeforeRun', () => {+ it('only matches a refusal from the auth middleware', () => {+ const refused = new TRPCClientError('expired', {+ result: { error: { data: { code: 'UNAUTHORIZED' } } },+ } as any);++ expect(isAsyncCallRejectedBeforeRun(refused)).toBe(true);+ expect(isAsyncCallRejectedBeforeRun(new TRPCClientError('fetch failed'))).toBe(false);+ expect(isAsyncCallRejectedBeforeRun(new Error('UNAUTHORIZED'))).toBe(false);+ });+});++describe('keepAliveForAsyncRejection', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ afterUnscoped.mockClear();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps the request alive until the async call settles', async () => {+ let settle!: () => void;+ const call = new Promise<void>((resolve) => (settle = resolve));+ keepAliveForAsyncRejection(call, call);+ const work = scheduledWork()();++ expect(await settledWithin(work, 1000)).toBe(false);+ settle();+ expect(await settledWithin(work, 0)).toBe(true);+ });++ it('lets the cleanup of a refusal near the window end run past it', async () => {+ let refuse!: (error: Error) => void;+ const call = new Promise<void>((_, reject) => (refuse = reject));+ // The refund takes 5s once the refusal arrives+ const handled = call.catch(() => new Promise<void>((resolve) => setTimeout(resolve, 5000)));+ keepAliveForAsyncRejection(call, handled);+ const work = scheduledWork()();++ expect(await settledWithin(work, ASYNC_REJECTION_WINDOW_MS - 1000)).toBe(false);+ refuse(new Error('UNAUTHORIZED'));+ expect(await settledWithin(work, 4999)).toBe(false);+ expect(await settledWithin(work, 1)).toBe(true);+ });++ it('stops waiting once the window ends for a call still running', async () => {+ const call = new Promise(() => {});+ keepAliveForAsyncRejection(call, call);+ const work = scheduledWork()();++ expect(await settledWithin(work, ASYNC_REJECTION_WINDOW_MS - 1)).toBe(false);+ expect(await settledWithin(work, 1)).toBe(true);+ });+});diff --git a/apps/server/src/routers/async/rejection.ts b/apps/server/src/routers/async/rejection.tsnew file mode 100644index 00000000000..fcab791c5b2--- /dev/null+++ b/apps/server/src/routers/async/rejection.ts@@ -0,0 +1,51 @@+import { TRPCClientError } from '@trpc/client';++import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';++/**+ * The async router refused the call in its auth middleware (for example, an internal+ * JWT that expired while the async function cold-started), so the procedure never ran+ * and nothing else will update the task. Other request failures (a proxy timing out a+ * long generation, a dropped connection) may come from a procedure that is still running.+ */+export const isAsyncCallRejectedBeforeRun = (error: unknown) =>+ error instanceof TRPCClientError && error.data?.code === 'UNAUTHORIZED';++/**+ * How long the submitting request stays alive after its response to hear back from the+ * async router. A refusal arrives once the async function has cold-started, well within+ * this window; a call still pending after it is running the generation itself.+ */+export const ASYNC_REJECTION_WINDOW_MS = 30_000;++/**+ * Keep the request alive so a fire-and-forget async call's failure handling (failing the+ * task, refunding the precharge) still runs on hosts that freeze unawaited work after the+ * response, such as Vercel.+ *+ * Only the wait for the call is bounded by {@link ASYNC_REJECTION_WINDOW_MS}: waiting for+ * the whole call would hold the request for the full generation (up to the async task+ * timeout). Once the call settles inside the window, `handled` runs to completion, so a+ * refund that starts near the end of the window is not cut off. The unscoped hand-off+ * keeps this wait off the agent step loop's scheduled-work flush.+ *+ * @param call The raw async call.+ * @param handled `call` with its failure handling attached.+ */+export const keepAliveForAsyncRejection = (call: Promise<unknown>, handled: Promise<unknown>) => {+ afterUnscoped(async () => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const windowEnd = new Promise<'window'>((resolve) => {+ timer = setTimeout(() => resolve('window'), ASYNC_REJECTION_WINDOW_MS);+ });+ const settled = call.then(+ () => 'settled' as const,+ () => 'settled' as const,+ );++ const outcome = await Promise.race([settled, windowEnd]);+ clearTimeout(timer);++ if (outcome === 'settled') await handled;+ });+};diff --git a/apps/server/src/routers/lambda/__tests__/music.test.ts b/apps/server/src/routers/lambda/__tests__/music.test.tsindex ff88e6aab99..4067f7cd9a8 100644--- a/apps/server/src/routers/lambda/__tests__/music.test.ts+++ b/apps/server/src/routers/lambda/__tests__/music.test.ts@@ -1,3 +1,4 @@+import { TRPCClientError } from '@trpc/client';import { beforeEach, describe, expect, it, vi } from 'vitest';import { chargeAfterGenerate } from '@/business/server/music-generation/chargeAfterGenerate';@@ -351,4 +352,41 @@ describe('musicRouter.createMusic (lambda)', () => {expect.objectContaining({ isError: true, prechargeResult: { key: 'brk-1' } }),);});+ it('fails every task and refunds when the async router refuses the call', async () => {+ setupTransaction();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(chargeBeforeGenerate).mockResolvedValue({ prechargeResult: { key: 'brk-1' } });+ // An internal JWT that expired before the async function verified it+ mockAsyncCreateMusic.mockRejectedValue(+ new TRPCClientError('Invalid JWT token', {+ result: { error: { code: -32001, data: { code: 'UNAUTHORIZED' }, message: '' } },+ } as any),+ );++ const result = await musicRouter.createCaller(ctx as any).createMusic(defaultInput);+ await vi.waitFor(() => expect(chargeAfterGenerate).toHaveBeenCalled());++ expect(result.success).toBe(true);+ for (const taskId of ['task-1', 'task-2'])+ expect(asyncTaskUpdate).toHaveBeenCalledWith(+ taskId,+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ expect(chargeAfterGenerate).toHaveBeenCalledWith(+ expect.objectContaining({ isError: true, prechargeResult: { key: 'brk-1' } }),+ );+ });++ it('leaves the tasks to the async router when only the response fails', async () => {+ setupTransaction();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ // A proxy timing out a long generation: the async router may still be running it+ mockAsyncCreateMusic.mockRejectedValue(new Error('fetch failed'));++ await musicRouter.createCaller(ctx as any).createMusic(defaultInput);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(asyncTaskUpdate).not.toHaveBeenCalled();+ expect(chargeAfterGenerate).not.toHaveBeenCalled();+ });});diff --git a/apps/server/src/routers/lambda/image/index.test.ts b/apps/server/src/routers/lambda/image/index.test.tsindex a86a06d66ac..95d522d45d6 100644--- a/apps/server/src/routers/lambda/image/index.test.ts+++ b/apps/server/src/routers/lambda/image/index.test.ts@@ -1,3 +1,4 @@+import { TRPCClientError } from '@trpc/client';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';@@ -725,6 +726,48 @@ describe('imageRouter', () => {}});+ it('fails and refunds a task right away when the async router refuses the call', async () => {+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ // An internal JWT that expired before the async function verified it+ const rejection = new TRPCClientError('Invalid JWT token', {+ result: { error: { code: -32001, data: { code: 'UNAUTHORIZED' }, message: '' } },+ } as any);+ mockAsyncCallerCreateImage.mockResolvedValueOnce(undefined).mockRejectedValueOnce(rejection);+ mockChargeBeforeGenerate.mockResolvedValue({+ prechargeItems: [{ reservationKey: 'k-1' }, { reservationKey: 'k-2' }],+ });++ try {+ const caller = imageRouter.createCaller(createMockCtx());+ const result = await caller.createImage(createDefaultInput());+ await vi.waitFor(() => expect(mockChargeAfterGenerate).toHaveBeenCalledTimes(1));++ expect(result.success).toBe(true);+ const rejectedTaskId = result.data.generations[1].asyncTaskId;+ expect(mockAsyncTaskModelUpdate).toHaveBeenCalledTimes(1);+ expect(mockAsyncTaskModelUpdate).toHaveBeenCalledWith(+ rejectedTaskId,+ expect.objectContaining({+ error: expect.objectContaining({+ body: expect.objectContaining({+ detail: 'start async task error: Invalid JWT token',+ }),+ }),+ status: AsyncTaskStatus.Error,+ }),+ );+ expect(mockChargeAfterGenerate).toHaveBeenCalledWith(+ expect.objectContaining({+ isError: true,+ metadata: expect.objectContaining({ asyncTaskId: rejectedTaskId }),+ prechargeResult: { reservationKey: 'k-2' },+ }),+ );+ } finally {+ consoleErrorSpy.mockRestore();+ }+ });+it('should handle async caller creation failure', async () => {mockCreateAsyncCaller.mockRejectedValue(new Error('Caller creation failed'));diff --git a/apps/server/src/routers/lambda/image/index.ts b/apps/server/src/routers/lambda/image/index.tsindex 658314eb51f..d8601098e2b 100644--- a/apps/server/src/routers/lambda/image/index.ts+++ b/apps/server/src/routers/lambda/image/index.ts@@ -5,6 +5,7 @@ import { ChatErrorType } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { and, eq } from 'drizzle-orm';+import pMap from 'p-map';import { z } from 'zod';import { chargeAfterGenerate } from '@/business/server/image-generation/chargeAfterGenerate';@@ -22,6 +23,10 @@ import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerGlobalConfig } from '@/server/globalConfig';import { createAsyncCaller } from '@/server/routers/async/caller';+import {+ isAsyncCallRejectedBeforeRun,+ keepAliveForAsyncRejection,+} from '@/server/routers/async/rejection';import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';import { FileService } from '@/server/services/file';import {@@ -43,6 +48,9 @@ import {const log = debug('lobe-image:lambda');+/** Bounds the task updates and refunds when failing a large batch at once. */+const FAIL_UNSTARTED_CONCURRENCY = 5;+const imageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;@@ -396,6 +404,62 @@ export const imageRouter = router({// Step 2: Trigger background image generation tasks.log('Starting async image generation tasks');+ /**+ * Marks tasks the async router never ran as failed and reconciles their+ * billing: with no async run, its failure handling cannot fire for them.+ */+ const failUnstartedTasks = async (+ tasks: { asyncTaskId: string; index: number }[],+ error: unknown,+ ) => {+ const message =+ 'start async task error: ' + (error instanceof Error ? error.message : 'Unknown error');++ await pMap(+ tasks,+ async ({ asyncTaskId }) => {+ try {+ await asyncTaskModel.update(asyncTaskId, {+ error: new AsyncTaskError(AsyncTaskErrorType.ServerError, message),+ status: AsyncTaskStatus.Error,+ });+ } catch (updateError) {+ console.error('Failed to update task status:', updateError);+ }+ },+ { concurrency: FAIL_UNSTARTED_CONCURRENCY },+ );++ if (!ENABLE_BUSINESS_FEATURES || !prechargeItems?.length) return;++ await pMap(+ tasks,+ async ({ asyncTaskId, index }) => {+ const prechargeItem = prechargeItems[index];+ if (prechargeItem === undefined) return;+ try {+ await chargeAfterGenerate({+ isError: true,+ metadata: {+ ...ctx.spendOrigin,+ asyncTaskId,+ generationBatchId: createdBatch.id,+ modelId: model,+ topicId: generationTopicId,+ },+ prechargeResult: prechargeItem,+ provider,+ userId,+ workspaceId: wsId,+ });+ } catch (chargeError) {+ console.error('Failed to reconcile billing for failed task:', chargeError);+ }+ },+ { concurrency: FAIL_UNSTARTED_CONCURRENCY },+ );+ };+try {log('Creating unified async caller for userId: %s', userId);@@ -407,82 +471,43 @@ export const imageRouter = router({log('Unified async caller created successfully for userId: %s', ctx.userId);log('Processing %d async image generation tasks', generationsWithTasks.length);- // Fire-and-forget: trigger async tasks without awaiting- // These calls go to the async router which handles them independently- // Do not schedule here; the async router handles these tasks independently.- generationsWithTasks.forEach(({ generation, asyncTaskId }) => {+ // Fire-and-forget: trigger async tasks without awaiting. The async router+ // handles them independently; the response only waits briefly for a refusal.+ generationsWithTasks.forEach(({ generation, asyncTaskId }, index) => {log('Starting background async task %s for generation %s', asyncTaskId, generation.id);- asyncCaller.image- .createImage({- generationBatchId: createdBatch.id,- generationId: generation.id,- generationTopicId,- model,- params: generationParams,- provider,- taskId: asyncTaskId,- workspaceId: wsId,- })+ const call = asyncCaller.image.createImage({+ generationBatchId: createdBatch.id,+ generationId: generation.id,+ generationTopicId,+ model,+ params: generationParams,+ provider,+ taskId: asyncTaskId,+ workspaceId: wsId,+ });+ const handled = call// The async router owns the task's status and billing once the request// reaches it; a failed HTTP response here (e.g. a proxy timing out a// long generation) does not mean the task failed, so only log it.- .catch((error: unknown) => {+ // A call its auth middleware refused never ran, so fail that task now+ // instead of leaving it pending until the status poll times it out.+ .catch(async (error: unknown) => {console.error('Async image task %s request failed: %O', asyncTaskId, error);+ if (isAsyncCallRejectedBeforeRun(error))+ await failUnstartedTasks([{ asyncTaskId, index }], error);});+ keepAliveForAsyncRejection(call, handled);});log('All %d background async image generation tasks started', generationsWithTasks.length);} catch (e) {- console.error('Failed to process async tasks:', e);console.error('Failed to process async tasks: %O', e);- // If overall failure occurs, update all task statuses to failed- try {- await Promise.allSettled(- generationsWithTasks.map(({ asyncTaskId }) =>- asyncTaskModel.update(asyncTaskId, {- error: new AsyncTaskError(- AsyncTaskErrorType.ServerError,- 'start async task error: ' + (e instanceof Error ? e.message : 'Unknown error'),- ),- status: AsyncTaskStatus.Error,- }),- ),- );- } catch (batchUpdateError) {- console.error('Failed to update batch task statuses:', batchUpdateError);- }-- // The async router never ran for these tasks, so its failure billing- // reconciliation cannot fire β reconcile each generation's billing- // handle here instead of leaving it dangling.- if (ENABLE_BUSINESS_FEATURES && prechargeItems?.length) {- await Promise.allSettled(- generationsWithTasks.map(async ({ asyncTaskId }, index) => {- const prechargeItem = prechargeItems[index];- if (prechargeItem === undefined) return;- try {- await chargeAfterGenerate({- isError: true,- metadata: {- ...ctx.spendOrigin,- asyncTaskId,- generationBatchId: createdBatch.id,- modelId: model,- topicId: generationTopicId,- },- prechargeResult: prechargeItem,- provider,- userId,- workspaceId: wsId,- });- } catch (chargeError) {- console.error('Failed to reconcile billing for failed task:', chargeError);- }- }),- );- }+ await failUnstartedTasks(+ generationsWithTasks.map(({ asyncTaskId }, index) => ({ asyncTaskId, index })),+ e,+ );}const createdGenerations = generationsWithTasks.map((item) => ({diff --git a/apps/server/src/routers/lambda/music/index.ts b/apps/server/src/routers/lambda/music/index.tsindex e13a02ab5d2..540857aebd2 100644--- a/apps/server/src/routers/lambda/music/index.ts+++ b/apps/server/src/routers/lambda/music/index.ts@@ -25,6 +25,10 @@ import {import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { createAsyncCaller } from '@/server/routers/async/caller';+import {+ isAsyncCallRejectedBeforeRun,+ keepAliveForAsyncRejection,+} from '@/server/routers/async/rejection';import { FileService } from '@/server/services/file';import { resolveMusicModelCard } from '@/server/services/generation/musicModel';import {@@ -221,35 +225,11 @@ export const musicRouter = router({log('Created batch %s with %d generations', batch.id, tasks.length);- try {- const asyncCaller = await createAsyncCaller({ userId });-- // Fire-and-forget: the async router owns task status and billing from here on. A failed- // HTTP response (e.g. a proxy timing out a long generation) does not mean the task- // failed, so only log it.- asyncCaller.music- .createMusic({- asyncTaskCreatedAt: tasks[0].asyncTaskCreatedAt,- generationBatchId: batch.id,- generationTopicId,- model,- params: generationParams,- prechargeResult: prechargeResult ?? undefined,- provider,- spendOrigin: ctx.spendOrigin,- tasks: tasks.map(({ asyncTaskId, generation }) => ({- asyncTaskId,- generationId: generation.id,- })),- webhookToken,- workspaceId: wsId,- })- .catch((error: unknown) => {- console.error('[music] Async music request for batch %s failed: %O', batch.id, error);- });- } catch (error) {- console.error('[music] Failed to start the async music task:', error);-+ /**+ * Marks every task as failed and refunds the pre-charge: the async router+ * never ran, so its own failure handling cannot fire for this batch.+ */+ const failUnstartedBatch = async (error: unknown) => {// Best effort: one failed status write must not stop the others or the refund belowawait pMap(tasks,@@ -266,27 +246,58 @@ export const musicRouter = router({{ concurrency: 5 },);- // The async router never ran, so refund the pre-charge here- if (prechargeResult) {- try {- await chargeAfterGenerate({- isError: true,- metadata: {- asyncTaskId: tasks[0].asyncTaskId,- generationBatchId: batch.id,- modelId: resolvedModelId,- topicId: generationTopicId,- },- model: resolvedModelId,- prechargeResult,- provider,- userId,- workspaceId: wsId,- });- } catch (chargeError) {- console.error('[music] chargeAfterGenerate failed:', chargeError);- }+ if (!prechargeResult) return;+ try {+ await chargeAfterGenerate({+ isError: true,+ metadata: {+ asyncTaskId: tasks[0].asyncTaskId,+ generationBatchId: batch.id,+ modelId: resolvedModelId,+ topicId: generationTopicId,+ },+ model: resolvedModelId,+ prechargeResult,+ provider,+ userId,+ workspaceId: wsId,+ });+ } catch (chargeError) {+ console.error('[music] chargeAfterGenerate failed:', chargeError);}+ };++ try {+ const asyncCaller = await createAsyncCaller({ userId });++ // Fire-and-forget: the async router owns task status and billing from here on. A failed+ // HTTP response (e.g. a proxy timing out a long generation) does not mean the task+ // failed, so only log it. A call its auth middleware refused never ran, so fail the+ // batch now instead of leaving it pending until the status poll times it out.+ const call = asyncCaller.music.createMusic({+ asyncTaskCreatedAt: tasks[0].asyncTaskCreatedAt,+ generationBatchId: batch.id,+ generationTopicId,+ model,+ params: generationParams,+ prechargeResult: prechargeResult ?? undefined,+ provider,+ spendOrigin: ctx.spendOrigin,+ tasks: tasks.map(({ asyncTaskId, generation }) => ({+ asyncTaskId,+ generationId: generation.id,+ })),+ webhookToken,+ workspaceId: wsId,+ });+ const handled = call.catch(async (error: unknown) => {+ console.error('[music] Async music request for batch %s failed: %O', batch.id, error);+ if (isAsyncCallRejectedBeforeRun(error)) await failUnstartedBatch(error);+ });+ keepAliveForAsyncRejection(call, handled);+ } catch (error) {+ console.error('[music] Failed to start the async music task:', error);+ await failUnstartedBatch(error);}return {diff --git a/apps/server/src/services/file/inlineImages.test.ts b/apps/server/src/services/file/inlineImages.test.tsindex cae6f16db67..448bb8d2002 100644--- a/apps/server/src/services/file/inlineImages.test.ts+++ b/apps/server/src/services/file/inlineImages.test.ts@@ -97,6 +97,16 @@ describe('resolveInlineImages', () => {);});+ it('drops image formats models cannot read', async () => {+ mocks.resolveFileIdsFromUrls.mockResolvedValue(['file_dwg']);+ mocks.resolveAttachmentMetadata.mockResolvedValue([+ // Browsers report AutoCAD drawings as `image/vnd.dwg`+ { fileType: 'image/vnd.dwg', id: 'file_dwg', name: 'a.dwg', size: 1, url: 'https://x/a' },+ ]);++ await expect(resolveInlineImages(ctx, '')).resolves.toEqual([]);+ });+it('does not touch the database without images', async () => {await expect(resolveInlineImages(ctx, 'plain text')).resolves.toEqual([]);expect(mocks.resolveFileIdsFromUrls).not.toHaveBeenCalled();diff --git a/apps/server/src/services/file/inlineImages.ts b/apps/server/src/services/file/inlineImages.tsindex f586be5734a..a9372d0212f 100644--- a/apps/server/src/services/file/inlineImages.ts+++ b/apps/server/src/services/file/inlineImages.ts@@ -1,3 +1,4 @@+import { isModelImageFileType } from '@/database/models/message/attachments';import type { LobeChatDatabase } from '@/database/type';import { extractFinalReplyImageUrls } from '@/server/services/agentRuntime/finalReplyImages';@@ -26,7 +27,7 @@ export interface InlineImage {* be handed over as image input.** Only the caller's files resolve (scoped by user / workspace); other links,- * missing files and non-image files are dropped. `excludeIds` skips images+ * missing files and files that are not model-readable images are dropped. `excludeIds` skips images* already delivered as attachments.*/export const resolveInlineImages = async (@@ -44,6 +45,6 @@ export const resolveInlineImages = async (const items = await resolveAttachmentMetadata({ ...scope, fileIds });return items- .filter((item) => item.fileType.startsWith('image') && !!item.url)+ .filter((item) => isModelImageFileType(item.fileType) && !!item.url).map(({ id, url }) => ({ id, url }));};diff --git a/apps/server/src/services/linear/startSyncJob.ts b/apps/server/src/services/linear/startSyncJob.tsindex 48a6ec81cf3..7890b1c0375 100644--- a/apps/server/src/services/linear/startSyncJob.ts+++ b/apps/server/src/services/linear/startSyncJob.ts@@ -6,6 +6,7 @@ import { AsyncTaskModel } from '@/database/models/asyncTask';import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';import type { LobeChatDatabase } from '@/database/type';import { createAsyncCaller } from '@/server/routers/async';+import { isAsyncCallRejectedBeforeRun } from '@/server/routers/async/rejection';import { after } from '@/server/utils/scheduleAfterResponse';import { toLinearSyncJobView } from './syncJob';@@ -142,7 +143,7 @@ const dispatchJob = async (// An error without an answer (a dropped connection) may still be on// its way to the router, which must be able to claim it; that job// times out as unclaimed if it never arrives.- if (!isRejectedHandOff(error)) {+ if (!isAsyncCallRejectedBeforeRun(error)) {console.error('[linear-sync] hand-off of sync %s failed: %O', taskId, error);if (isAnsweredHandOff(error)) await fail();return;@@ -171,7 +172,3 @@ const dispatchJob = async (const isAnsweredHandOff = (error: unknown) =>error instanceof TRPCClientError &&(error.meta?.response !== undefined || error.cause instanceof SyntaxError);--/** The async router refused the call before running it, so the job is still unclaimed. */-const isRejectedHandOff = (error: unknown) =>- error instanceof TRPCClientError && error.data?.code === 'UNAUTHORIZED';diff --git a/packages/database/src/models/__tests__/messages/message.fileKinds.test.ts b/packages/database/src/models/__tests__/messages/message.fileKinds.test.tsnew file mode 100644index 00000000000..24cc76b210f--- /dev/null+++ b/packages/database/src/models/__tests__/messages/message.fileKinds.test.ts@@ -0,0 +1,60 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { files, messages, messagesFiles, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { MessageModel } from '../../message';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'message-file-kinds-test';+const messageModel = new MessageModel(serverDB, userId);+const postProcessUrl = async (path: string | null) => `https://cdn.example.com/${path}`;++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(messages).values({+ content: 'a photo, a CAD drawing, a voice note and a clip',+ id: 'fk-message',+ role: 'user',+ userId,+ });+ await serverDB.insert(files).values([+ { fileType: 'image/jpeg', id: 'fk-photo', name: 'photo.jpg', size: 100, url: 'photo', userId },+ // Browsers report AutoCAD drawings as `image/vnd.dwg`; no vision model reads them+ { fileType: 'image/vnd.dwg', id: 'fk-dwg', name: 'plan.dwg', size: 100, url: 'dwg', userId },+ { fileType: 'audio/mpeg', id: 'fk-audio', name: 'note.mp3', size: 100, url: 'audio', userId },+ { fileType: 'video/mp4', id: 'fk-video', name: 'clip.mp4', size: 100, url: 'video', userId },+ ]);+ await serverDB.insert(messagesFiles).values([+ { fileId: 'fk-photo', messageId: 'fk-message', userId },+ { fileId: 'fk-dwg', messageId: 'fk-message', userId },+ { fileId: 'fk-audio', messageId: 'fk-message', userId },+ { fileId: 'fk-video', messageId: 'fk-message', userId },+ ]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('MessageModel attachment kinds', () => {+ it.each([+ ['query', () => messageModel.query({}, { postProcessUrl })],+ ['queryByIds', () => messageModel.queryByIds(['fk-message'], { postProcessUrl })],+ ])(+ '%s keeps image formats models cannot read out of imageList and leaves audio and video alone',+ async (_, run) => {+ const [message] = await run();++ expect(message.imageList?.map((image) => image.id)).toEqual(['fk-photo']);+ expect(message.fileList?.map((file) => file.id)).toEqual(['fk-dwg']);+ // Audio and video keep their own lists+ expect(message.audioList?.map((audio) => audio.id)).toEqual(['fk-audio']);+ expect(message.videoList?.map((video) => video.id)).toEqual(['fk-video']);+ },+ );+});diff --git a/packages/database/src/models/message/attachments.ts b/packages/database/src/models/message/attachments.tsindex dd806a41687..50e5a4b2977 100644--- a/packages/database/src/models/message/attachments.ts+++ b/packages/database/src/models/message/attachments.ts@@ -117,3 +117,42 @@ export const materializeChatAudioItem = ({url,};};++/**+ * Image formats that vision models accept. Only these are sent to the model as+ * images; other `image/*` uploads (a CAD drawing reported as `image/vnd.dwg`, SVG,+ * TIFF) stay ordinary files, because providers reject the whole request on an+ * unsupported image format.+ */+const MODEL_IMAGE_MIME_TYPES = new Set([+ 'image/gif',+ 'image/jpeg',+ 'image/jpg',+ 'image/png',+ 'image/webp',+]);++const mimeTypeOf = (fileType: string | null | undefined) =>+ (fileType || '').split(';')[0].trim().toLowerCase();++/** Whether a file of this MIME type can be handed to a model as an image. */+export const isModelImageFileType = (fileType: string | null | undefined) =>+ MODEL_IMAGE_MIME_TYPES.has(mimeTypeOf(fileType));++/** Splits a message's related files into the image, video, audio and file lists it renders. */+export const groupMessageFilesByKind = <T extends { fileType: string | null }>(files: T[]) => {+ const imageList: T[] = [];+ const videoList: T[] = [];+ const audioList: T[] = [];+ const fileList: T[] = [];++ for (const file of files) {+ const mimeType = mimeTypeOf(file.fileType);+ if (isModelImageFileType(mimeType)) imageList.push(file);+ else if (mimeType.startsWith('video')) videoList.push(file);+ else if (mimeType.startsWith('audio')) audioList.push(file);+ else fileList.push(file);+ }++ return { audioList, fileList, imageList, videoList };+};diff --git a/packages/database/src/models/message/queryByIds.ts b/packages/database/src/models/message/queryByIds.tsindex f59ed24c842..b9f4e2618ea 100644--- a/packages/database/src/models/message/queryByIds.ts+++ b/packages/database/src/models/message/queryByIds.ts@@ -33,6 +33,7 @@ import {FILE_URL_POST_PROCESS_CONCURRENCY,fileDocumentColumns,fileDocumentsOrder,+ groupMessageFilesByKind,materializeChatAudioItem,toFileDocumentsMap,} from './attachments';@@ -265,15 +266,7 @@ export class MessageByIdsQueries extends MessageScope {documentsMap = toFileDocumentsMap(documentsList);}- const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));- const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));- const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));- const fileList = relatedFileList.filter(- (i) =>- !(i.fileType || '').startsWith('image') &&- !(i.fileType || '').startsWith('video') &&- !(i.fileType || '').startsWith('audio'),- );+ const { audioList, fileList, imageList, videoList } = groupMessageFilesByKind(relatedFileList);// 4. Build thread mapconst threadMap = new Map(diff --git a/packages/database/src/models/message/queryWithWhere.ts b/packages/database/src/models/message/queryWithWhere.tsindex c536a4815ad..5fd77cccb76 100644--- a/packages/database/src/models/message/queryWithWhere.ts+++ b/packages/database/src/models/message/queryWithWhere.ts@@ -14,7 +14,11 @@ import {import { and, desc, eq, isNull, lt, or } from 'drizzle-orm';import { messagePlugins, messages, messageTranslates, messageTTS, users } from '../../schemas';-import { createChatImageItem, materializeChatAudioItem } from './attachments';+import {+ createChatImageItem,+ groupMessageFilesByKind,+ materializeChatAudioItem,+} from './attachments';import type { MessageByIdsQueries } from './queryByIds';import type { MessageRelationQueries } from './relations';import type { MessageScopeArgs } from './scope';@@ -254,15 +258,7 @@ export class MessagePageQueries extends MessageScope {return [];}- const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));- const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));- const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));- const fileList = relatedFileList.filter(- (i) =>- !(i.fileType || '').startsWith('image') &&- !(i.fileType || '').startsWith('video') &&- !(i.fileType || '').startsWith('audio'),- );+ const { audioList, fileList, imageList, videoList } = groupMessageFilesByKind(relatedFileList);const threadMap = this.relations.createThreadMap(threadData);diff --git a/packages/env/src/__tests__/auth.test.ts b/packages/env/src/__tests__/auth.test.tsindex 1566cdfcc25..061e4fc79f4 100644--- a/packages/env/src/__tests__/auth.test.ts+++ b/packages/env/src/__tests__/auth.test.ts@@ -25,4 +25,25 @@ describe('getAuthConfig', () => {expect(getAuthConfig().AUTH_ADDITIONAL_TRUSTED_ORIGINS).toBe('https://gateway.example.com');});+ it.each(['15s', '1m', '90 seconds', '2h'])(+ 'accepts INTERNAL_JWT_EXPIRATION %s',+ async (value) => {+ vi.stubEnv('INTERNAL_JWT_EXPIRATION', value);++ const { getAuthConfig } = await import('../auth');++ expect(getAuthConfig().INTERNAL_JWT_EXPIRATION).toBe(value);+ },+ );++ // jose's setExpirationTime throws on these, failing every internal JWT signature+ it.each(['15', '15 s ago', '-15s', 'soon'])(+ 'rejects INTERNAL_JWT_EXPIRATION %s at load',+ async (value) => {+ vi.stubEnv('INTERNAL_JWT_EXPIRATION', value);+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(import('../auth')).rejects.toThrow(/Invalid environment variables/);+ },+ );});diff --git a/packages/env/src/auth.ts b/packages/env/src/auth.tsindex 2ddf8f7488d..1001b374504 100644--- a/packages/env/src/auth.ts+++ b/packages/env/src/auth.ts@@ -1,6 +1,16 @@import { createEnv } from '@t3-oss/env-core';import { z } from 'zod';+/**+ * The positive, relative subset of the time spans jose's `setExpirationTime` accepts.+ * jose throws "Invalid time period format" on anything else (a bare `15` has no unit),+ * which would otherwise only surface when the first internal JWT is signed, failing+ * every async task. Signs and `ago` are left out because they produce an expired token.+ * @see https://github.com/panva/jose/blob/main/src/lib/jwt_claims_set.ts+ */+const INTERNAL_JWT_EXPIRATION_PATTERN =+ /^\d+(?:\.\d+)? ?(?:seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;+declare global {// eslint-disable-next-line @typescript-eslint/no-namespacenamespace NodeJS {@@ -201,7 +211,13 @@ export const getAuthConfig = () => {ENABLE_OIDC: z.boolean(),// Internal JWT expiration time (e.g., '10s', '1m', '1h')- INTERNAL_JWT_EXPIRATION: z.string().default('30s'),+ INTERNAL_JWT_EXPIRATION: z+ .string()+ .regex(+ INTERNAL_JWT_EXPIRATION_PATTERN,+ 'INTERNAL_JWT_EXPIRATION needs a positive duration with a unit, e.g. "15s" or "1m"',+ )+ .default('30s'),},runtimeEnv: {