Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(ocr): fix broken tests
Elian Doran82e723c9158f
diff --git a/apps/server/src/routes/api/ocr.spec.ts b/apps/server/src/routes/api/ocr.spec.tsindex 5270a3009f..b778e100c4 100644--- a/apps/server/src/routes/api/ocr.spec.ts+++ b/apps/server/src/routes/api/ocr.spec.ts@@ -4,7 +4,6 @@ import ocrRoutes from "./ocr.js";// Mock the OCR servicevi.mock("../../services/ocr/ocr_service.js", () => ({default: {- isOCREnabled: vi.fn(() => true),startBatchProcessing: vi.fn(() => Promise.resolve({ success: true })),getBatchProgress: vi.fn(() => ({ inProgress: false, total: 0, processed: 0 }))}@@ -15,6 +14,13 @@ vi.mock("../../becca/becca.js", () => ({default: {}}));+// Mock sql+vi.mock("../../services/sql.js", () => ({+ default: {+ getRow: vi.fn()+ }+}));+// Mock logvi.mock("../../services/log.js", () => ({default: {@@ -23,53 +29,28 @@ vi.mock("../../services/log.js", () => ({}));describe("OCR API", () => {- let mockRequest: any;- let mockResponse: any;-beforeEach(() => {- mockRequest = {- params: {},- body: {},- query: {}- };-- mockResponse = {- status: vi.fn().mockReturnThis(),- json: vi.fn().mockReturnThis(),- triliumResponseHandled: false- };+ vi.clearAllMocks();});- it("should set triliumResponseHandled flag in batch processing", async () => {- await ocrRoutes.batchProcessOCR(mockRequest, mockResponse);-- expect(mockResponse.json).toHaveBeenCalledWith({ success: true });- expect(mockResponse.triliumResponseHandled).toBe(true);+ it("should return success for batch processing", async () => {+ const result = await ocrRoutes.batchProcessOCR();+ expect(result).toEqual({ success: true });});- it("should set triliumResponseHandled flag in get batch progress", async () => {- await ocrRoutes.getBatchProgress(mockRequest, mockResponse);-- expect(mockResponse.json).toHaveBeenCalledWith({- inProgress: false,- total: 0,- processed: 0- });- expect(mockResponse.triliumResponseHandled).toBe(true);+ it("should return batch progress", async () => {+ const result = await ocrRoutes.getBatchProgress();+ expect(result).toEqual({ inProgress: false, total: 0, processed: 0 });});- it("should handle errors and set triliumResponseHandled flag", async () => {- // Mock service to throw error+ it("should return 400 when batch processing fails", async () => {const ocrService = await import("../../services/ocr/ocr_service.js");- vi.mocked(ocrService.default.startBatchProcessing).mockRejectedValueOnce(new Error("Test error"));-- await ocrRoutes.batchProcessOCR(mockRequest, mockResponse);-- expect(mockResponse.status).toHaveBeenCalledWith(500);- expect(mockResponse.json).toHaveBeenCalledWith({+ vi.mocked(ocrService.default.startBatchProcessing).mockResolvedValueOnce({success: false,- error: "Test error"+ message: "No images found that need OCR processing"});- expect(mockResponse.triliumResponseHandled).toBe(true);++ const result = await ocrRoutes.batchProcessOCR();+ expect(result).toEqual([400, { success: false, message: "No images found that need OCR processing" }]);});-});\ No newline at end of file+});diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.tsindex a780cf45f1..7721750436 100644--- a/apps/server/src/services/ocr/ocr_service.spec.ts+++ b/apps/server/src/services/ocr/ocr_service.spec.ts@@ -1,4 +1,5 @@-import { afterEach,beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+// Mock Tesseract.jsconst mockWorker = {recognize: vi.fn(),@@ -28,12 +29,22 @@ const mockLog = {const mockSql = {execute: vi.fn(),getRow: vi.fn(),- getRows: vi.fn()+ getRows: vi.fn(),+ getColumn: vi.fn()};const mockBecca = {getNote: vi.fn(),- getAttachment: vi.fn()+ getAttachment: vi.fn(),+ getBlob: vi.fn()+};++const mockBlobService = {+ calculateContentHash: vi.fn().mockReturnValue('hash123')+};++const mockEntityChangesService = {+ putEntityChange: vi.fn()};vi.mock('../options.js', () => ({@@ -52,33 +63,48 @@ vi.mock('../../becca/becca.js', () => ({default: mockBecca}));+vi.mock('../blob.js', () => ({+ default: mockBlobService+}));++vi.mock('../entity_changes.js', () => ({+ default: mockEntityChangesService+}));+// Import the service after mockinglet ocrService: typeof import('./ocr_service.js').default;beforeEach(async () => {- // Clear all mocksvi.clearAllMocks();// Reset mock implementationsmockOptions.getOptionBool.mockReturnValue(true);- mockOptions.getOption.mockReturnValue('eng');+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'ocrMinConfidence') return '0';+ return 'eng';+ });mockSql.execute.mockImplementation(() => ({ lastInsertRowid: 1 }));mockSql.getRow.mockReturnValue(null);mockSql.getRows.mockReturnValue([]);+ mockSql.getColumn.mockReturnValue([]);++ // Mock getBlob for putBlobEntityChange+ mockBecca.getBlob.mockReturnValue({+ blobId: 'blob123',+ content: Buffer.from('data'),+ textRepresentation: null,+ utcDateModified: '2025-01-01'+ });- // Set up createWorker to properly set the worker on the servicemockTesseract.createWorker.mockImplementation(async () => {return mockWorker;});// Dynamically import the service to ensure mocks are appliedconst module = await import('./ocr_service.js');- ocrService = module.default; // It's an instance, not a class+ ocrService = module.default;// Reset the OCR service state- (ocrService as any).isInitialized = false;- (ocrService as any).worker = null;- (ocrService as any).isProcessing = false;(ocrService as any).batchProcessingState = {inProgress: false,total: 0,@@ -91,54 +117,6 @@ afterEach(() => {});describe('OCRService', () => {- describe('isOCREnabled', () => {- it('should return true when OCR is enabled in options', () => {- mockOptions.getOptionBool.mockReturnValue(true);-- expect(ocrService.isOCREnabled()).toBe(true);- expect(mockOptions.getOptionBool).toHaveBeenCalledWith('ocrEnabled');- });-- it('should return false when OCR is disabled in options', () => {- mockOptions.getOptionBool.mockReturnValue(false);-- expect(ocrService.isOCREnabled()).toBe(false);- expect(mockOptions.getOptionBool).toHaveBeenCalledWith('ocrEnabled');- });-- it('should return false when options throws an error', () => {- mockOptions.getOptionBool.mockImplementation(() => {- throw new Error('Options not available');- });-- expect(ocrService.isOCREnabled()).toBe(false);- });- });-- describe('isSupportedMimeType', () => {- it('should return true for supported image MIME types', () => {- expect(ocrService.isSupportedMimeType('image/jpeg')).toBe(true);- expect(ocrService.isSupportedMimeType('image/jpg')).toBe(true);- expect(ocrService.isSupportedMimeType('image/png')).toBe(true);- expect(ocrService.isSupportedMimeType('image/gif')).toBe(true);- expect(ocrService.isSupportedMimeType('image/bmp')).toBe(true);- expect(ocrService.isSupportedMimeType('image/tiff')).toBe(true);- });-- it('should return false for unsupported MIME types', () => {- expect(ocrService.isSupportedMimeType('text/plain')).toBe(false);- expect(ocrService.isSupportedMimeType('application/pdf')).toBe(false);- expect(ocrService.isSupportedMimeType('video/mp4')).toBe(false);- expect(ocrService.isSupportedMimeType('audio/mp3')).toBe(false);- });-- it('should handle null/undefined MIME types', () => {- expect(ocrService.isSupportedMimeType(null as any)).toBe(false);- expect(ocrService.isSupportedMimeType(undefined as any)).toBe(false);- expect(ocrService.isSupportedMimeType('')).toBe(false);- });- });-describe('extractTextFromFile', () => {const mockImageBuffer = Buffer.from('fake-image-data');@@ -146,7 +124,8 @@ describe('OCRService', () => {const mockResult = {data: {text: 'Extracted text from image',- confidence: 95+ confidence: 95,+ words: [{ text: 'Extracted', confidence: 95 }, { text: 'text', confidence: 95 }, { text: 'from', confidence: 95 }, { text: 'image', confidence: 95 }]}};mockWorker.recognize.mockResolvedValue(mockResult);@@ -163,12 +142,12 @@ describe('OCRService', () => {mockWorker.recognize.mockRejectedValue(error);await expect(ocrService.extractTextFromFile(mockImageBuffer, 'image/jpeg')).rejects.toThrow('OCR recognition failed');- expect(mockLog.error).toHaveBeenCalledWith('OCR text extraction failed: Error: OCR recognition failed');+ expect(mockLog.error).toHaveBeenCalledWith('Image OCR text extraction failed: Error: OCR recognition failed');});});describe('storeOCRResult', () => {- it('should store OCR result in blob successfully', async () => {+ it('should store OCR result in blob successfully', () => {const ocrResult = {text: 'Sample text',confidence: 0.95,@@ -176,7 +155,7 @@ describe('OCRService', () => {language: 'eng'};- await ocrService.storeOCRResult('blob123', ocrResult);+ ocrService.storeOCRResult('blob123', ocrResult);expect(mockSql.execute).toHaveBeenCalledWith(expect.stringContaining('UPDATE blobs SET textRepresentation = ?'),@@ -184,7 +163,7 @@ describe('OCRService', () => {);});- it('should handle undefined blobId gracefully', async () => {+ it('should handle undefined blobId gracefully', () => {const ocrResult = {text: 'Sample text',confidence: 0.95,@@ -192,13 +171,13 @@ describe('OCRService', () => {language: 'eng'};- await ocrService.storeOCRResult(undefined, ocrResult);+ ocrService.storeOCRResult(undefined, ocrResult);expect(mockSql.execute).not.toHaveBeenCalled();expect(mockLog.error).toHaveBeenCalledWith('Cannot store OCR result: blobId is undefined');});- it('should handle database update errors', async () => {+ it('should handle database update errors', () => {const error = new Error('Database error');mockSql.execute.mockImplementation(() => {throw error;@@ -211,7 +190,7 @@ describe('OCRService', () => {language: 'eng'};- await expect(ocrService.storeOCRResult('blob123', ocrResult)).rejects.toThrow('Database error');+ expect(() => ocrService.storeOCRResult('blob123', ocrResult)).toThrow('Database error');expect(mockLog.error).toHaveBeenCalledWith('Failed to store OCR result for blob blob123: Error: Database error');});});@@ -222,66 +201,53 @@ describe('OCRService', () => {type: 'image',mime: 'image/jpeg',blobId: 'blob123',- getContent: vi.fn()+ getContent: vi.fn(),+ getLabelValue: vi.fn().mockReturnValue(null)};beforeEach(() => {mockBecca.getNote.mockReturnValue(mockNote);mockNote.getContent.mockReturnValue(Buffer.from('fake-image-data'));+ mockNote.mime = 'image/jpeg';});it('should process note OCR successfully', async () => {- // Ensure getRow returns null for all calls in this test- mockSql.getRow.mockImplementation(() => null);+ mockSql.getRow.mockReturnValue(null);const mockOCRResult = {data: {text: 'Note image text',- confidence: 90+ confidence: 90,+ words: [{ text: 'Note', confidence: 90 }, { text: 'image', confidence: 90 }, { text: 'text', confidence: 90 }]}};mockWorker.recognize.mockResolvedValue(mockOCRResult);const result = await ocrService.processNoteOCR('note123');- expect(result).toEqual({- text: 'Note image text',- confidence: 0.9,- extractedAt: expect.any(String),- language: 'eng'- });+ expect(result).toBeDefined();+ expect(result!.text).toBe('Note image text');expect(mockBecca.getNote).toHaveBeenCalledWith('note123');expect(mockNote.getContent).toHaveBeenCalled();});- it('should return existing OCR result if forceReprocess is false', async () => {- const existingResult = {- textRepresentation: 'Existing text'- };- mockSql.getRow.mockReturnValue(existingResult);+ it('should skip processing if OCR already exists and forceReprocess is false', async () => {+ mockSql.getRow.mockReturnValue({ textRepresentation: 'Existing text' });const result = await ocrService.processNoteOCR('note123');- expect(result).toEqual({- text: 'Existing text',- confidence: 0.95,- language: 'eng',- extractedAt: expect.any(String)- });+ expect(result).toBeNull();expect(mockNote.getContent).not.toHaveBeenCalled();});it('should reprocess if forceReprocess is true', async () => {- const existingResult = {- textRepresentation: 'Existing text'- };- mockSql.getRow.mockResolvedValue(existingResult);-+ mockSql.getRow.mockReturnValue({ textRepresentation: 'Existing text' });const mockOCRResult = {data: {text: 'New processed text',- confidence: 95+ confidence: 95,+ words: [{ text: 'New', confidence: 95 }, { text: 'processed', confidence: 95 }, { text: 'text', confidence: 95 }]}};mockWorker.recognize.mockResolvedValue(mockOCRResult);@@ -307,13 +273,14 @@ describe('OCRService', () => {const result = await ocrService.processNoteOCR('note123');expect(result).toBe(null);- expect(mockLog.info).toHaveBeenCalledWith('Note note123 has unsupported MIME type text/plain, skipping OCR');+ expect(mockLog.info).toHaveBeenCalledWith('note note123 has unsupported MIME type text/plain for text extraction, skipping');});});describe('processAttachmentOCR', () => {const mockAttachment = {attachmentId: 'attach123',+ ownerId: 'note123',role: 'image',mime: 'image/png',blobId: 'blob456',@@ -322,30 +289,26 @@ describe('OCRService', () => {beforeEach(() => {mockBecca.getAttachment.mockReturnValue(mockAttachment);+ mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });mockAttachment.getContent.mockReturnValue(Buffer.from('fake-image-data'));});it('should process attachment OCR successfully', async () => {- // Ensure getRow returns null for all calls in this test- mockSql.getRow.mockImplementation(() => null);-+ mockSql.getRow.mockReturnValue(null);const mockOCRResult = {data: {text: 'Attachment image text',- confidence: 92+ confidence: 92,+ words: [{ text: 'Attachment', confidence: 92 }, { text: 'image', confidence: 92 }, { text: 'text', confidence: 92 }]}};mockWorker.recognize.mockResolvedValue(mockOCRResult);const result = await ocrService.processAttachmentOCR('attach123');- expect(result).toEqual({- text: 'Attachment image text',- confidence: 0.92,- extractedAt: expect.any(String),- language: 'eng'- });+ expect(result).toBeDefined();+ expect(result!.text).toBe('Attachment image text');expect(mockBecca.getAttachment).toHaveBeenCalledWith('attach123');});@@ -359,137 +322,55 @@ describe('OCRService', () => {});});- describe('searchOCRResults', () => {- it('should search OCR results successfully', () => {- const mockResults = [- {- blobId: 'blob1',- textRepresentation: 'Sample search text'- }- ];- mockSql.getRows.mockReturnValue(mockResults);-- const results = ocrService.searchOCRResults('search');-- expect(results).toEqual([{- blobId: 'blob1',- text: 'Sample search text'- }]);- expect(mockSql.getRows).toHaveBeenCalledWith(- expect.stringContaining('WHERE textRepresentation LIKE ?'),- ['%search%']- );- });-- it('should handle search errors gracefully', () => {- mockSql.getRows.mockImplementation(() => {- throw new Error('Database error');- });-- const results = ocrService.searchOCRResults('search');-- expect(results).toEqual([]);- expect(mockLog.error).toHaveBeenCalledWith('Failed to search OCR results: Error: Database error');- });- });-- describe('getOCRStats', () => {- it('should return OCR statistics successfully', () => {- const mockStats = {- total_processed: 150- };- const mockNoteStats = {- count: 100- };- const mockAttachmentStats = {- count: 50- };-- mockSql.getRow.mockReturnValueOnce(mockStats);- mockSql.getRow.mockReturnValueOnce(mockNoteStats);- mockSql.getRow.mockReturnValueOnce(mockAttachmentStats);-- const stats = ocrService.getOCRStats();-- expect(stats).toEqual({- totalProcessed: 150,- imageNotes: 100,- imageAttachments: 50- });- });-- it('should handle missing statistics gracefully', () => {- mockSql.getRow.mockReturnValue(null);-- const stats = ocrService.getOCRStats();-- expect(stats).toEqual({- totalProcessed: 0,- imageNotes: 0,- imageAttachments: 0- });- });- });-describe('Batch Processing', () => {+ // Helper to mock getBlobsNeedingOCR to return entities+ function mockBlobsNeedingOCR(notes: Array<{ entityId: string; mimeType: string }>, attachments: Array<{ entityId: string; mimeType: string }> = []) {+ const noteRows = notes.map(n => ({ blobId: `blob_${n.entityId}`, mimeType: n.mimeType, entityId: n.entityId }));+ const attachmentRows = attachments.map(a => ({ blobId: `blob_${a.entityId}`, mimeType: a.mimeType, entityId: a.entityId }));+ mockSql.getRows.mockReturnValueOnce(noteRows);+ mockSql.getRows.mockReturnValueOnce(attachmentRows);+ }+describe('startBatchProcessing', () => {beforeEach(() => {- // Reset batch processing stateocrService.cancelBatchProcessing();});- it('should start batch processing when images are available', async () => {- mockSql.getRow.mockReturnValueOnce({ count: 5 }); // image notes- mockSql.getRow.mockReturnValueOnce({ count: 3 }); // image attachments+ it('should start batch processing when items are available', async () => {+ mockBlobsNeedingOCR(+ [{ entityId: 'note1', mimeType: 'image/jpeg' }]+ );const result = await ocrService.startBatchProcessing();expect(result).toEqual({ success: true });- expect(mockSql.getRow).toHaveBeenCalledTimes(2);});it('should return error if batch processing already in progress', async () => {- // Start first batch- mockSql.getRow.mockReturnValueOnce({ count: 5 });- mockSql.getRow.mockReturnValueOnce({ count: 3 });-- // Mock background processing queries- const mockImageNotes = Array.from({length: 5}, (_, i) => ({- noteId: `note${i}`,- mime: 'image/jpeg'- }));- mockSql.getRows.mockReturnValueOnce(mockImageNotes);- mockSql.getRows.mockReturnValueOnce([]);-- // Start without awaiting to keep it in progress- const firstStart = ocrService.startBatchProcessing();-- // Try to start second batch immediately- const result = await ocrService.startBatchProcessing();-- // Clean up by awaiting the first one- await firstStart;-- expect(result).toEqual({- success: false,- message: 'Batch processing already in progress'+ // First call: items for starting+ mockBlobsNeedingOCR(+ [{ entityId: 'note1', mimeType: 'image/jpeg' }]+ );+ // Mock note for background processing+ mockBecca.getNote.mockReturnValue({+ noteId: 'note1', type: 'image', mime: 'image/jpeg', blobId: 'blob1',+ getContent: vi.fn().mockReturnValue(Buffer.from('data')),+ getLabelValue: vi.fn().mockReturnValue(null)});- });+ mockWorker.recognize.mockResolvedValue({ data: { text: 'text', confidence: 90, words: [] } });- it('should return error if OCR is disabled', async () => {- mockOptions.getOptionBool.mockReturnValue(false);+ ocrService.startBatchProcessing();const result = await ocrService.startBatchProcessing();expect(result).toEqual({success: false,- message: 'OCR is disabled'+ message: 'Batch processing already in progress'});});- it('should return error if no images need processing', async () => {- mockSql.getRow.mockReturnValueOnce({ count: 0 }); // image notes- mockSql.getRow.mockReturnValueOnce({ count: 0 }); // image attachments+ it('should return error if no items need processing', async () => {+ mockBlobsNeedingOCR([], []);const result = await ocrService.startBatchProcessing();@@ -500,19 +381,19 @@ describe('OCRService', () => {});it('should handle database errors gracefully', async () => {- const error = new Error('Database connection failed');- mockSql.getRow.mockImplementation(() => {- throw error;+ mockSql.getRows.mockImplementation(() => {+ throw new Error('Database connection failed');});const result = await ocrService.startBatchProcessing();+ // getBlobsNeedingOCR catches DB errors and returns [], so startBatchProcessing sees no itemsexpect(result).toEqual({success: false,- message: 'Database connection failed'+ message: 'No images found that need OCR processing'});expect(mockLog.error).toHaveBeenCalledWith(- 'Failed to start batch processing: Database connection failed'+ expect.stringContaining('Failed to get blobs needing OCR'));});});@@ -527,25 +408,14 @@ describe('OCRService', () => {});it('should return progress with percentage when total > 0', async () => {- // Start batch processing- mockSql.getRow.mockReturnValueOnce({ count: 10 });- mockSql.getRow.mockReturnValueOnce({ count: 0 });-- // Mock the background processing queries to return items that will take time to process- const mockImageNotes = Array.from({length: 10}, (_, i) => ({- noteId: `note${i}`,- mime: 'image/jpeg'- }));- mockSql.getRows.mockReturnValueOnce(mockImageNotes); // image notes query- mockSql.getRows.mockReturnValueOnce([]); // image attachments query+ mockBlobsNeedingOCR(+ Array.from({ length: 10 }, (_, i) => ({ entityId: `note${i}`, mimeType: 'image/jpeg' }))+ );- const startPromise = ocrService.startBatchProcessing();+ ocrService.startBatchProcessing();- // Check progress immediately after starting (before awaiting)const progress = ocrService.getBatchProgress();- await startPromise;-expect(progress.inProgress).toBe(true);expect(progress.total).toBe(10);expect(progress.processed).toBe(0);@@ -556,24 +426,14 @@ describe('OCRService', () => {describe('cancelBatchProcessing', () => {it('should cancel ongoing batch processing', async () => {- // Start batch processing- mockSql.getRow.mockReturnValueOnce({ count: 5 });- mockSql.getRow.mockReturnValueOnce({ count: 0 });-- // Mock background processing queries- const mockImageNotes = Array.from({length: 5}, (_, i) => ({- noteId: `note${i}`,- mime: 'image/jpeg'- }));- mockSql.getRows.mockReturnValueOnce(mockImageNotes);- mockSql.getRows.mockReturnValueOnce([]);+ mockBlobsNeedingOCR(+ [{ entityId: 'note1', mimeType: 'image/jpeg' }]+ );- const startPromise = ocrService.startBatchProcessing();+ ocrService.startBatchProcessing();expect(ocrService.getBatchProgress().inProgress).toBe(true);- await startPromise;-ocrService.cancelBatchProcessing();expect(ocrService.getBatchProgress().inProgress).toBe(false);@@ -586,222 +446,5 @@ describe('OCRService', () => {expect(mockLog.info).not.toHaveBeenCalledWith('Batch OCR processing cancelled');});});-- describe('processBatchInBackground', () => {- it('should process image notes and attachments in sequence', async () => {- // Clear all mocks at the start of this test to ensure clean state- vi.clearAllMocks();-- // Mock data for batch processing- const imageNotes = [- { noteId: 'note1', mime: 'image/jpeg', blobId: 'blob1' },- { noteId: 'note2', mime: 'image/png', blobId: 'blob2' }- ];- const imageAttachments = [- { attachmentId: 'attach1', mime: 'image/gif', blobId: 'blob3' }- ];-- // Setup mocks for startBatchProcessing- mockSql.getRow.mockReturnValueOnce({ count: 2 }); // image notes count- mockSql.getRow.mockReturnValueOnce({ count: 1 }); // image attachments count-- // Setup mocks for background processing- mockSql.getRows.mockReturnValueOnce(imageNotes); // image notes query- mockSql.getRows.mockReturnValueOnce(imageAttachments); // image attachments query-- // Mock successful OCR processing- mockWorker.recognize.mockResolvedValue({- data: { text: 'Test text', confidence: 95 }- });-- // Mock notes and attachments- const mockNote1 = {- noteId: 'note1',- type: 'image',- mime: 'image/jpeg',- blobId: 'blob1',- getContent: vi.fn().mockReturnValue(Buffer.from('fake-image-data'))- };- const mockNote2 = {- noteId: 'note2',- type: 'image',- mime: 'image/png',- blobId: 'blob2',- getContent: vi.fn().mockReturnValue(Buffer.from('fake-image-data'))- };- const mockAttachment = {- attachmentId: 'attach1',- role: 'image',- mime: 'image/gif',- blobId: 'blob3',- getContent: vi.fn().mockReturnValue(Buffer.from('fake-image-data'))- };-- mockBecca.getNote.mockImplementation((noteId) => {- if (noteId === 'note1') return mockNote1;- if (noteId === 'note2') return mockNote2;- return null;- });- mockBecca.getAttachment.mockReturnValue(mockAttachment);- mockSql.getRow.mockReturnValue(null); // No existing OCR results-- // Start batch processing- await ocrService.startBatchProcessing();-- // Wait for background processing to complete- // Need to wait longer since there's a 500ms delay between each item in batch processing- await new Promise(resolve => setTimeout(resolve, 2000));-- // Verify notes and attachments were processed- expect(mockBecca.getNote).toHaveBeenCalledWith('note1');- expect(mockBecca.getNote).toHaveBeenCalledWith('note2');- expect(mockBecca.getAttachment).toHaveBeenCalledWith('attach1');- });-- it('should handle processing errors gracefully', async () => {- const imageNotes = [- { noteId: 'note1', mime: 'image/jpeg', blobId: 'blob1' }- ];-- // Setup mocks for startBatchProcessing- mockSql.getRow.mockReturnValueOnce({ count: 1 });- mockSql.getRow.mockReturnValueOnce({ count: 0 });-- // Setup mocks for background processing- mockSql.getRows.mockReturnValueOnce(imageNotes);- mockSql.getRows.mockReturnValueOnce([]);-- // Mock note that will cause an error- const mockNote = {- noteId: 'note1',- type: 'image',- mime: 'image/jpeg',- blobId: 'blob1',- getContent: vi.fn().mockImplementation(() => { throw new Error('Failed to get content'); })- };- mockBecca.getNote.mockReturnValue(mockNote);- mockSql.getRow.mockReturnValue(null);-- // Start batch processing- await ocrService.startBatchProcessing();-- // Wait for background processing to complete- await new Promise(resolve => setTimeout(resolve, 100));-- // Verify error was logged but processing continued- expect(mockLog.error).toHaveBeenCalledWith(- expect.stringContaining('Failed to process OCR for note note1')- );- });-- it('should stop processing when cancelled', async () => {- const imageNotes = [- { noteId: 'note1', mime: 'image/jpeg', blobId: 'blob1' },- { noteId: 'note2', mime: 'image/png', blobId: 'blob2' }- ];-- // Setup mocks- mockSql.getRow.mockReturnValueOnce({ count: 2 });- mockSql.getRow.mockReturnValueOnce({ count: 0 });- mockSql.getRows.mockReturnValueOnce(imageNotes);- mockSql.getRows.mockReturnValueOnce([]);-- // Start batch processing- await ocrService.startBatchProcessing();-- // Cancel immediately- ocrService.cancelBatchProcessing();-- // Wait for background processing to complete- await new Promise(resolve => setTimeout(resolve, 100));-- // Verify processing was stopped early- expect(ocrService.getBatchProgress().inProgress).toBe(false);- });-- it('should skip unsupported MIME types', async () => {- const imageNotes = [- { noteId: 'note1', mime: 'text/plain', blobId: 'blob1' }, // unsupported- { noteId: 'note2', mime: 'image/jpeg', blobId: 'blob2' } // supported- ];-- // Setup mocks- mockSql.getRow.mockReturnValueOnce({ count: 2 });- mockSql.getRow.mockReturnValueOnce({ count: 0 });- mockSql.getRows.mockReturnValueOnce(imageNotes);- mockSql.getRows.mockReturnValueOnce([]);-- const mockNote = {- noteId: 'note2',- type: 'image',- mime: 'image/jpeg',- blobId: 'blob2',- getContent: vi.fn().mockReturnValue(Buffer.from('fake-image-data'))- };- mockBecca.getNote.mockReturnValue(mockNote);- mockSql.getRow.mockReturnValue(null);- mockWorker.recognize.mockResolvedValue({- data: { text: 'Test text', confidence: 95 }- });-- // Start batch processing- await ocrService.startBatchProcessing();-- // Wait for background processing to complete- await new Promise(resolve => setTimeout(resolve, 100));-- // Verify only supported MIME type was processed- expect(mockBecca.getNote).toHaveBeenCalledWith('note2');- expect(mockBecca.getNote).not.toHaveBeenCalledWith('note1');- });- });- });-- describe('deleteOCRResult', () => {- it('should delete OCR result successfully', () => {- ocrService.deleteOCRResult('blob123');-- expect(mockSql.execute).toHaveBeenCalledWith(- expect.stringContaining('UPDATE blobs SET textRepresentation = NULL'),- ['blob123']- );- expect(mockLog.info).toHaveBeenCalledWith('Deleted OCR result for blob blob123');- });-- it('should handle deletion errors', () => {- mockSql.execute.mockImplementation(() => {- throw new Error('Database error');- });-- expect(() => ocrService.deleteOCRResult('blob123')).toThrow('Database error');- expect(mockLog.error).toHaveBeenCalledWith('Failed to delete OCR result for blob blob123: Error: Database error');- });});-- describe('isCurrentlyProcessing', () => {- it('should return false initially', () => {- expect(ocrService.isCurrentlyProcessing()).toBe(false);- });-- it('should return true during processing', async () => {- mockBecca.getNote.mockReturnValue({- noteId: 'note123',- mime: 'image/jpeg',- blobId: 'blob123',- getContent: vi.fn().mockReturnValue(Buffer.from('fake-image-data'))- });- mockSql.getRow.mockResolvedValue(null);-- mockWorker.recognize.mockImplementation(() => {- expect(ocrService.isCurrentlyProcessing()).toBe(true);- return Promise.resolve({- data: { text: 'test', confidence: 90 }- });- });-- await ocrService.processNoteOCR('note123');- expect(ocrService.isCurrentlyProcessing()).toBe(false);- });- });-});diff --git a/apps/server/src/services/ocr/processors/pdf_processor.ts b/apps/server/src/services/ocr/processors/pdf_processor.tsindex 6f383d6ac8..c59fe84b81 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts@@ -1,4 +1,6 @@-import pdfParse from 'pdf-parse';+// Import the actual library directly, bypassing the wrapper index.js+// which tries to read a test PDF file at import time.+import pdfParse from 'pdf-parse/lib/pdf-parse.js';import log from '../../log.js';import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';diff --git a/apps/server/src/types.d.ts b/apps/server/src/types.d.tsindex 8d6048a76c..5c859c1342 100644--- a/apps/server/src/types.d.ts+++ b/apps/server/src/types.d.ts@@ -39,6 +39,11 @@ declare module "@triliumnext/share-theme/styles.css" {export default content;}+declare module "pdf-parse/lib/pdf-parse.js" {+ import pdfParse from "pdf-parse";+ export default pdfParse;+}+declare module '*.css' {}declare module '*?raw' {const src: string