From 677cbc7468c42f2bce33e350f56e452da409a00a Mon Sep 17 00:00:00 2001 From: wttwins Date: Mon, 29 Dec 2025 01:41:00 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E9=97=AE=E9=A2=98=E5=92=8C=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=EF=BC=8C=E6=94=B9=E8=BF=9B=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=A8=B3=E5=AE=9A=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/unit/ai/gemini-retry.test.ts | 70 ++++++++++++++-------- src/app/practice/page.tsx | 2 +- src/components/correction-editor.tsx | 3 +- src/components/settings-dialog.tsx | 8 +-- src/lib/ai/gemini-provider.ts | 2 +- 5 files changed, 50 insertions(+), 35 deletions(-) diff --git a/src/__tests__/unit/ai/gemini-retry.test.ts b/src/__tests__/unit/ai/gemini-retry.test.ts index 39a8d623..e4b6cb16 100644 --- a/src/__tests__/unit/ai/gemini-retry.test.ts +++ b/src/__tests__/unit/ai/gemini-retry.test.ts @@ -1,5 +1,4 @@ - -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; // Mock dependencies vi.mock('@google/genai', () => { @@ -42,12 +41,14 @@ import { GeminiProvider } from '@/lib/ai/gemini-provider'; describe('GeminiProvider Retry Logic', () => { let provider: GeminiProvider; - let mockGenerateContent: any; + let mockGenerateContent: ReturnType; beforeEach(() => { vi.clearAllMocks(); + // Use fake timers with auto-advance to avoid manual timer management issues + vi.useFakeTimers({ shouldAdvanceTime: true }); provider = new GeminiProvider({ apiKey: 'test-key' }); - // @ts-ignore + // @ts-expect-error - accessing private property for testing mockGenerateContent = provider.ai.models.generateContent; }); @@ -56,24 +57,19 @@ describe('GeminiProvider Retry Logic', () => { }); it('should retry on network error and eventually succeed', async () => { - vi.useFakeTimers(); - mockGenerateContent .mockRejectedValueOnce(new Error('fetch failed')) .mockRejectedValueOnce(new Error('network timeout')) - .mockResolvedValue({ + .mockResolvedValueOnce({ text: 'QAAn数学', usageMetadata: {} }); - const promise = provider.analyzeImage('base64data'); - - // Advance timers to trigger retries - await vi.runAllTimersAsync(); - - const result = await promise; + // With shouldAdvanceTime: true, fake timers will auto-advance + const result = await provider.analyzeImage('base64data'); expect(result).toBeDefined(); + expect(result.questionText).toBe('Q'); // Initial call + 2 retries = 3 calls expect(mockGenerateContent).toHaveBeenCalledTimes(3); }); @@ -81,30 +77,52 @@ describe('GeminiProvider Retry Logic', () => { it('should throw immediately on non-retryable error', async () => { mockGenerateContent.mockRejectedValue(new Error('AI_AUTH_ERROR: Invalid API Key')); - // No need for fake timers as it should fail immediately + // Should fail immediately without retrying await expect(provider.analyzeImage('base64data')) .rejects .toThrow('AI_AUTH_ERROR'); + // Only 1 call, no retries for auth errors expect(mockGenerateContent).toHaveBeenCalledTimes(1); }); it('should give up after max retries', async () => { - vi.useFakeTimers(); - mockGenerateContent.mockRejectedValue(new Error('fetch failed')); - const promise = provider.analyzeImage('base64data'); - - // Attach the expectation promise BEFORE triggering the timers that cause the rejection - const validationPromise = expect(promise).rejects.toThrow('AI_CONNECTION_FAILED'); - - // Advance time to exhaust all retries - await vi.runAllTimersAsync(); - - // Await the validation - await validationPromise; + // With shouldAdvanceTime: true, fake timers will auto-advance through all retries + await expect(provider.analyzeImage('base64data')) + .rejects + .toThrow('AI_CONNECTION_FAILED'); + // 3 attempts total (1 initial + 2 retries) expect(mockGenerateContent).toHaveBeenCalledTimes(3); }); + + it('should retry on 503 service unavailable', async () => { + mockGenerateContent + .mockRejectedValueOnce(new Error('503 Service Unavailable')) + .mockResolvedValueOnce({ + text: 'QAAn数学', + usageMetadata: {} + }); + + const result = await provider.analyzeImage('base64data'); + + expect(result).toBeDefined(); + expect(mockGenerateContent).toHaveBeenCalledTimes(2); + }); + + it('should retry on connection reset', async () => { + mockGenerateContent + .mockRejectedValueOnce(new Error('ECONNRESET')) + .mockResolvedValueOnce({ + text: 'QAAn数学', + usageMetadata: {} + }); + + const result = await provider.analyzeImage('base64data'); + + expect(result).toBeDefined(); + expect(mockGenerateContent).toHaveBeenCalledTimes(2); + }); }); diff --git a/src/app/practice/page.tsx b/src/app/practice/page.tsx index 0a8e2c4a..1ca5b7d0 100644 --- a/src/app/practice/page.tsx +++ b/src/app/practice/page.tsx @@ -68,7 +68,7 @@ function PracticeContent() { errorItemId, language, difficulty - }, { timeout: config?.timeouts?.analyze || 180000 }); + }, { timeout }); setQuestion(data); } catch (error: any) { console.error(error); diff --git a/src/components/correction-editor.tsx b/src/components/correction-editor.tsx index 454837a8..72db127f 100644 --- a/src/components/correction-editor.tsx +++ b/src/components/correction-editor.tsx @@ -36,7 +36,6 @@ interface CorrectionEditorProps { export function CorrectionEditor({ initialData, onSave, onCancel, imagePreview, initialSubjectId, aiTimeout }: CorrectionEditorProps) { const [data, setData] = useState({ - ...initialData, ...initialData, subjectId: initialSubjectId, gradeSemester: "", @@ -95,7 +94,7 @@ export function CorrectionEditor({ initialData, onSave, onCancel, imagePreview, frontendLogger.info('[Reanswer]', 'Sending request', { timeout: aiTimeout }); - const result = await apiClient.post<{ answerText: string; analysis: string; knowledgePoints: string[] }>("/api/reanswer", requestBody, { timeout: aiTimeout }); + const result = await apiClient.post<{ answerText: string; analysis: string; knowledgePoints: string[] }>("/api/reanswer", requestBody, { timeout: aiTimeout || 180000 }); setData(prev => ({ ...prev, diff --git a/src/components/settings-dialog.tsx b/src/components/settings-dialog.tsx index 3cf8ddf2..ec05ff3f 100644 --- a/src/components/settings-dialog.tsx +++ b/src/components/settings-dialog.tsx @@ -484,7 +484,6 @@ export function SettingsDialog() { -
- - - - + + + ); } diff --git a/src/lib/ai/gemini-provider.ts b/src/lib/ai/gemini-provider.ts index 26fde1d4..e2becbcd 100644 --- a/src/lib/ai/gemini-provider.ts +++ b/src/lib/ai/gemini-provider.ts @@ -42,7 +42,7 @@ export class GeminiProvider implements AIService { } private async retryOperation(operation: () => Promise, maxRetries: number = 3): Promise { - let lastError: any; + let lastError: unknown; for (let attempt = 1; attempt <= maxRetries; attempt++) { try {