π€― 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(file): keep files waiting for a parse slot from timing out (#22813)
Mocha6e90dc881913
diff --git a/apps/server/src/routers/async/__tests__/file.test.ts b/apps/server/src/routers/async/__tests__/file.test.tsindex 1592c8d7fa3..ff9bd1332a5 100644--- a/apps/server/src/routers/async/__tests__/file.test.ts+++ b/apps/server/src/routers/async/__tests__/file.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -340,7 +341,7 @@ describe('fileRouter.parseFileToChunks β NoSuchKey + internal:// branches', ()// f3 waits four minutes behind the two running filesawait vi.advanceTimersByTimeAsync(4 * 60 * 1000);- expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith('task_f3', expect.anything());+ expect(documentServiceMock.parseFile).not.toHaveBeenCalledWith('f3');const admittedAt = new Date();gates[0].resolve();await vi.advanceTimersByTimeAsync(0);@@ -360,6 +361,63 @@ describe('fileRouter.parseFileToChunks β NoSuchKey + internal:// branches', ()}});+ it('keeps a queued task fresh for status polling beyond the parse timeout', async () => {+ vi.useFakeTimers();+ const stuck = deferred();+ let runs: Promise<unknown>[] = [];+ try {+ const taskStates = new Map<+ string,+ { createdAt: Date; error: unknown; status: AsyncTaskStatus }+ >(+ ['f1', 'f2', 'f3'].map((id) => [+ 'task_' + id,+ { createdAt: new Date(), error: null, status: AsyncTaskStatus.Processing },+ ]),+ );+ asyncTaskModelMock.update.mockImplementation(async (id: string, value: object) => {+ const previous = taskStates.get(id) ?? {+ createdAt: new Date(),+ error: null,+ status: AsyncTaskStatus.Processing,+ };+ taskStates.set(id, { ...previous, ...value });+ });+ fileServiceMock.getFileByteArray.mockResolvedValue(new Uint8Array([1]));+ chunkServiceMock.chunkContent.mockImplementation(async () => {+ await stuck.promise;+ return { chunks: [{ index: 0, text: 'hello', type: 'DocumentChunk' }] };+ });+ const caller = fileRouter.createCaller(mockCtx);+ runs = ['f1', 'f2', 'f3'].map((id) =>+ caller.parseFileToChunks({ fileId: id, taskId: 'task_' + id }),+ );+ // Model the watchdog on every poll while both parse slots stay occupied.+ for (let minute = 0; minute < 10; minute++) {+ await vi.advanceTimersByTimeAsync(60_000);+ const task = taskStates.get('task_f3');+ expect(task).toBeDefined();+ if (task && Date.now() - task.createdAt.getTime() > ASYNC_TASK_TIMEOUT) {+ task.status = AsyncTaskStatus.Error;+ }+ expect(task?.status).toBe(AsyncTaskStatus.Processing);+ }+ expect(fileServiceMock.getFileByteArray).toHaveBeenCalledTimes(2);+ stuck.resolve();+ await vi.advanceTimersByTimeAsync(0);+ await Promise.all(runs);+ expect(taskStates.get('task_f3')?.status).toBe(AsyncTaskStatus.Success);+ const updatesAfterCompletion = asyncTaskModelMock.update.mock.calls.length;+ await vi.advanceTimersByTimeAsync(ASYNC_TASK_TIMEOUT * 2);+ expect(asyncTaskModelMock.update).toHaveBeenCalledTimes(updatesAfterCompletion);+ } finally {+ stuck.resolve();+ await vi.advanceTimersByTimeAsync(0);+ await Promise.allSettled(runs);+ vi.useRealTimers();+ }+ });+it('does not keep a parse slot while the embedding task of a finished file runs', async () => {const embedding = deferred();chunkServiceMock.asyncEmbeddingFileChunks.mockImplementation(() => embedding.promise);diff --git a/apps/server/src/routers/async/file.ts b/apps/server/src/routers/async/file.tsindex 38120214895..e4f1e2d6ad6 100644--- a/apps/server/src/routers/async/file.ts+++ b/apps/server/src/routers/async/file.ts@@ -489,6 +489,27 @@ export const fileRouter = router({}};- return withParseSlot(parse);+ // Status polling expires tasks by createdAt, even before they get a parse slot.+ // Keep waiting tasks fresh so the UI never sees a transient timeout and stops polling.+ const refreshWaitingTask = () =>+ asyncTaskModel.update(input.taskId, { createdAt: new Date() });+ await refreshWaitingTask();+ let refreshing: Promise<unknown> = Promise.resolve();+ const heartbeat = setInterval(() => {+ refreshing = refreshing.then(refreshWaitingTask).catch((error) => {+ console.error('[parseFileToChunks] failed to refresh queued task:', error);+ });+ }, ASYNC_TASK_TIMEOUT / 2);++ try {+ return await withParseSlot(async (slot) => {+ clearInterval(heartbeat);+ // Drain an in-flight refresh before parsing changes this task's status or clock.+ await refreshing;+ return parse(slot);+ });+ } finally {+ clearInterval(heartbeat);+ }}),});