Skip to content

Commit

Permalink
do not delete unused attachment immediately
Browse files Browse the repository at this point in the history
  • Loading branch information
nbonamy committed Dec 23, 2024
1 parent b4a41ed commit 69d3cab
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
11 changes: 10 additions & 1 deletion src/main/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import Monitor from './monitor'
import path from 'path'
import fs from 'fs'

export const kUnusedDelay = 3600000

const monitor: Monitor = new Monitor(() => notifyBrowserWindows('file-modified', 'history'))

export const historyFilePath = (app: App): string => {
Expand Down Expand Up @@ -112,8 +114,15 @@ const listExistingAttachments = (imagesPath: string): string[] => {
}

// read all files in the images folder
// return only ones created more than 1 hour ago
try {
return fs.readdirSync(imagesPath)
const now = new Date()
return fs.readdirSync(imagesPath).filter(file => {
const filepath = path.join(imagesPath, file)
const stats = fs.statSync(filepath)
const diff = now.getTime() - stats.mtime.getTime()
return diff > kUnusedDelay
})
} catch (error) {
console.error('Error reading images folder:', error)
return []
Expand Down
16 changes: 12 additions & 4 deletions tests/unit/history.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

import { expect, test, vi } from 'vitest'
import { extractAttachmentsFromHistory, listUnusedAttachments, loadHistory, saveHistory } from '../../src/main/history'
import { extractAttachmentsFromHistory, listUnusedAttachments, loadHistory, saveHistory, kUnusedDelay } from '../../src/main/history'
import { App, app } from 'electron'
import Chat from '../../src/models/chat'
import fs from 'fs'
Expand All @@ -17,14 +17,22 @@ vi.mock('fs', async (importOriginal) => {
const mod: any = await importOriginal()
return { default: {
...mod,
unlinkSync: vi.fn(),
writeFileSync: vi.fn(),
existsSync: vi.fn(() => true),
readdirSync: vi.fn(() => [
'image1.png',
'image2.png',
'image3.jpg',
'image4.png'
])
'image4.png',
]),
statSync: vi.fn((file) => {
return {
mtime: file.includes('image3')
? new Date(new Date().getTime() - kUnusedDelay / 1.1)
: new Date(new Date().getTime() - kUnusedDelay * 1.1)
}
})
}}
})

Expand Down Expand Up @@ -130,5 +138,5 @@ test('extract attachments - mixed', async () => {
test('unused attachments', async () => {
expect(listUnusedAttachments({ getPath: () => '' } as unknown as App, [
{ messages: [ { content: 'file://images/image1.png', attachment: { url: 'file://images/image2.png' } } ] },
] as Chat[])).toEqual(['images/image3.jpg','images/image4.png'])
] as Chat[])).toEqual(['images/image4.png'])
})

0 comments on commit 69d3cab

Please sign in to comment.