Skip to content

Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.

perf(list): keep long histories smooth with zero visual or feel change

Deepender256122690d1ba7
diff --git a/electron/main/drag.ts b/electron/main/drag.ts
index a403796..3ba131c 100644
--- a/electron/main/drag.ts
+++ b/electron/main/drag.ts
@@ -255,14 +255,25 @@ export function prefetchFileIcons(paths: string[]): void {
if (!iconCache.has(ext)) {
app.getFileIcon(p, { size: 'normal' }).then((icon) => {
if (icon && !icon.isEmpty()) {
+ // Store under the extension only — the previous per-full-path second
+ // entry grew the map without bound across a long session.
iconCache.set(ext, icon)
- iconCache.set(p, icon)
+ trimIconCache()
}
}).catch(() => {})
}
}
}
+/** Hard cap for both caches sharing this map, oldest entries evicted first. */
+function trimIconCache(): void {
+ while (iconCache.size > ICON_CACHE_MAX) {
+ const first = iconCache.keys().next().value
+ if (first === undefined) break
+ iconCache.delete(first)
+ }
+}
+
/** A clean 1x1 transparent fallback so Windows uses default OS file icon without green box. */
const TRANSPARENT_PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
diff --git a/electron/main/index.ts b/electron/main/index.ts
index 41faa12..1f7e192 100644
--- a/electron/main/index.ts
+++ b/electron/main/index.ts
@@ -8,7 +8,7 @@
* 3. On 'window-all-closed' we DON'T quit (the panel is hidden, not closed).
* 4. Quit from the tray menu tears everything down cleanly.
*/
-import { app, BrowserWindow, nativeImage, protocol, session } from 'electron'
+import { app, BrowserWindow, protocol, session } from 'electron'
import { APP_CONFIG, runtime } from './config'
import { ensureDirs, PATHS } from '../store/paths'
import { createWindow, getMainWindow, setInteractive, setVisible, startCursorPoll, stopCursorPoll, stopHeartbeat, setHotZoneWidth, registerTaskbarCreatedListener } from './window'
@@ -26,6 +26,7 @@ import { extname, normalize } from 'node:path'
import { existsSync, createReadStream } from 'node:fs'
import { createHash } from 'node:crypto'
import { resolveStoredImage } from './imageProtocol'
+import { getThumbnailPayload, thumbnailCacheControl } from './thumbnailCache'
// Edge-Drop renders a small, mostly static transparent panel. Chromium's GPU
// process costs substantially more memory (~150–250 MB) than the iGPU compositing
@@ -164,12 +165,13 @@ function registerImageProtocol(): void {
// multi-megapixel file to Chromium merely to paint a 50–240px card.
if (request.url.startsWith(`${APP_CONFIG.imageProtocol}://thumb/`)) {
const rawTarget = request.url.slice(`${APP_CONFIG.imageProtocol}://thumb/`.length)
- const filePath = rawTarget.startsWith('file/')
+ const isFileThumb = rawTarget.startsWith('file/')
+ const filePath = isFileThumb
? normalize(decodeURIComponent(rawTarget.slice('file/'.length)))
: resolveStoredImage(PATHS.imagesDir(), rawTarget)?.filePath
if (!filePath || !existsSync(filePath)) return new Response('Not found', { status: 404 })
- return createThumbnailResponse(filePath)
+ return createThumbnailResponse(filePath, !isFileThumb, request)
}
// Support streaming full-resolution local image files: edgelocal://file/<encodedPath>
@@ -224,11 +226,12 @@ function registerImageProtocol(): void {
}
/**
- * Encodes a display-sized PNG so renderer image decodes are strictly bounded.
- * The full-resolution source remains available through edgelocal:// for the
- * preview flyout and drag/paste flows.
+ * Serve a bounded thumbnail with proper HTTP caching: long immutable freshness
+ * for content-addressed captures, short freshness + ETag/304 for external
+ * files. Payloads come from the LRU thumbnail engine so repeated requests do
+ * zero decode work in the main process.
*/
-function createThumbnailResponse(filePath: string): Response {
+function createThumbnailResponse(filePath: string, isStoredCapture: boolean, request?: Request): Response {
const ext = extname(filePath).toLowerCase()
// SVG files are vector XML documents; stream them directly with correct MIME type
// rather than failing inside nativeImage.createFromPath (which only supports raster bitmaps).
@@ -244,28 +247,21 @@ function createThumbnailResponse(filePath: string): Response {
})
}
- const MAX_THUMBNAIL_EDGE_PX = 240
- const image = nativeImage.createFromPath(filePath)
- if (image.isEmpty()) return new Response('Unsupported image', { status: 415 })
-
- const { width, height } = image.getSize()
- const scale = Math.min(1, MAX_THUMBNAIL_EDGE_PX / Math.max(width, height))
- const thumbnail = scale < 1
- ? image.resize({
- width: Math.max(1, Math.round(width * scale)),
- height: Math.max(1, Math.round(height * scale)),
- quality: 'good'
- })
- : image
-
- return new Response(thumbnail.toPNG(), {
- status: 200,
- headers: new Headers({
- 'Content-Type': 'image/png',
- // The source file can change or be deleted; do not retain stale thumbs.
- 'Cache-Control': 'no-cache'
- })
+ const payload = getThumbnailPayload(filePath)
+ if (!payload) return new Response('Unsupported image', { status: 415 })
+
+ const headers = new Headers({
+ 'Content-Type': payload.contentType,
+ 'Cache-Control': thumbnailCacheControl(isStoredCapture),
+ 'ETag': payload.etag
})
+
+ const inm = request?.headers.get('if-none-match')
+ if (inm && inm === payload.etag) {
+ return new Response(null, { status: 304, headers })
+ }
+
+ return new Response(new Uint8Array(payload.body), { status: 200, headers })
}
// Silence unused import in environments where setVisible isn't referenced
diff --git a/electron/main/thumbnailCache.ts b/electron/main/thumbnailCache.ts
new file mode 100644
index 0000000..2db94e2
--- /dev/null
+++ b/electron/main/thumbnailCache.ts
@@ -0,0 +1,131 @@
+/**
+ * Bounded thumbnail production + caching for the edgelocal://thumb/ route.
+ *
+ * WHY: every thumbnail request used to decode the FULL original screenshot
+ * (a 4K capture is ~33 MB of raw bitmap), resize to 240 px, PNG-encode, and
+ * throw everything away — while telling the renderer `no-cache`, guaranteeing
+ * the same expensive work repeated on every list reorder/scroll. With
+ * hundreds of image cards this starved the CPU exactly while animations run.
+ *
+ * Now:
+ * - A tiny LRU (64 entries, ~1.5 MB worst case) serves hot thumbnails as
+ * pre-encoded buffers with zero decode work.
+ * - Responses carry validators (ETag -> 304) and long freshness for
+ * content-addressed captures, so Chromium reuses its decoded bitmap and
+ * rarely asks again at all.
+ *
+ * Keys include mtime+size so externally replaced files are never served stale.
+ */
+import { statSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { nativeImage } from 'electron'
+
+const MAX_THUMBNAIL_EDGE_PX = 240
+const LRU_MAX_ENTRIES = 64
+
+export interface ThumbnailPayload {
+ etag: string
+ contentType: string
+ body: Buffer
+}
+
+const lru = new Map<string, ThumbnailPayload>()
+
+function lruGet(key: string): ThumbnailPayload | undefined {
+ const hit = lru.get(key)
+ if (!hit) return undefined
+ // Refresh insertion order for LRU semantics.
+ lru.delete(key)
+ lru.set(key, hit)
+ return hit
+}
+
+function lruPut(key: string, value: ThumbnailPayload): void {
+ lru.delete(key)
+ lru.set(key, value)
+ if (lru.size > LRU_MAX_ENTRIES) {
+ const oldest = lru.keys().next().value
+ if (oldest !== undefined) lru.delete(oldest)
+ }
+}
+
+/** Test hook: drop all cached thumbnails. */
+export function clearThumbnailCache(): void {
+ lru.clear()
+}
+
+/** Test hook: number of cached payloads. */
+export function thumbnailCacheSize(): number {
+ return lru.size
+}
+
+interface FileFacts {
+ mtimeMs: number
+ size: number
+}
+
+function readFacts(filePath: string): FileFacts | null {
+ try {
+ const st = statSync(filePath)
+ if (!st.isFile()) return null
+ return { mtimeMs: Math.floor(st.mtimeMs), size: st.size }
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Produce (or fetch from LRU) the encoded 240 px PNG for a raster image.
+ * Returns null when the source cannot be read or decoded.
+ */
+export function getThumbnailPayload(filePath: string): ThumbnailPayload | null {
+ const facts = readFacts(filePath)
+ if (!facts) return null
+
+ const key = `${filePath}|${facts.mtimeMs}:${facts.size}`
+ const cached = lruGet(key)
+ if (cached) return cached
+
+ try {
+ const img = nativeImage.createFromPath(filePath)
+ if (img.isEmpty()) return null
+
+ const { width, height } = img.getSize()
+ const scale = Math.min(1, MAX_THUMBNAIL_EDGE_PX / Math.max(width, height))
+ const thumb =
+ scale < 1
+ ? img.resize({
+ width: Math.max(1, Math.round(width * scale)),
+ height: Math.max(1, Math.round(height * scale)),
+ quality: 'good'
+ })
+ : img
+
+ const body = thumb.toPNG()
+ const payload: ThumbnailPayload = {
+ // Content-fingerprint validator: any change to the source file flips
+ // mtime/size, producing a fresh key AND a fresh etag together.
+ etag: `"${createHash('sha256').update(`${filePath}|${facts.mtimeMs}:${facts.size}`).digest('hex')}"`,
+ contentType: 'image/png',
+ body
+ }
+ lruPut(key, payload)
+ return payload
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Cache policy for a thumbnail response.
+ * - Stored captures (`edgelocal://thumb/<imageId>`) are content-addressed:
+ * the id is minted once per capture and its bytes are never rewritten, so
+ * the representation is effectively immutable.
+ * - External file thumbnails may change on disk; give them short freshness
+ * plus mandatory-ish revalidation via ETag.
+ */
+export function thumbnailCacheControl(isStoredCapture: boolean): string {
+ return isStoredCapture
+ ? 'private, max-age=31536000, immutable'
+ : 'private, max-age=300'
+}
diff --git a/src/components/ClipboardItem.tsx b/src/components/ClipboardItem.tsx
index 28280bd..aa15266 100644
--- a/src/components/ClipboardItem.tsx
+++ b/src/components/ClipboardItem.tsx
@@ -21,6 +21,8 @@ import { MAX_STACK } from '../../shared/types'
import type { DragRequest } from '../../shared/types'
import { useStore } from '../store/appStore'
import { useDragOut } from '../hooks/useDragOut'
+import { useRelativeTimeTick } from '../hooks/useRelativeTimeTick'
+import { itemRenderKey } from '../lib/itemSignature'
import { basename, formatBytes, previewText, relativeTime, formatImageDisplayName } from '../lib/format'
import { getFileKind } from '../lib/fileType'
import { playButtonClickSound, playToggleSound, playDeleteSound, playCardExpandSound } from '../lib/soundEffects'
@@ -51,15 +53,16 @@ const ClipboardItemBase = forwardRef<HTMLDivElement, Props>(({ item }, ref) => {
const [expanded, setExpanded] = useState(false)
const open = useStore((s) => s.open)
- const [, setTimeTick] = useState(0)
+
+ // Shared clock: one refcounted interval refreshes every mounted card's
+ // relative-time label in a single batched pass (replaces the per-card
+ // setInterval, which scaled terribly across hundreds of cards).
+ useRelativeTimeTick()
useEffect(() => {
if (!open) {
setExpanded(false)
- return
}
- const timer = window.setInterval(() => setTimeTick((n) => n + 1), 30000)
- return () => window.clearInterval(timer)
}, [open])
const isPreviewing = useStore((s) => s.previewItemId) === item.id
@@ -828,4 +831,25 @@ function KindBadge({ item }: { item: ClipboardItemDto }) {
}
}
-export const ClipboardItemCard = memo(ClipboardItemBase)
+/**
+ * Memo comparator backed by a value-based render key: every `state:items`
+ * push recreates all DTO objects, so shallow identity compare would re-render
+ * the entire list on each push. This skips the re-render unless any field the
+ * card actually displays changed. Store-subscription-driven updates (open,
+ * previewing) and local state (copied/expanded) are unaffected — memo only
+ * gates prop-driven renders.
+ */
+export const ClipboardItemCard = memo(
+ ClipboardItemBase,
+ (prevProps, nextProps) => {
+ const prev = prevProps.item
+ const next = nextProps.item
+ return (
+ prev.id === next.id &&
+ prev.pinned === next.pinned &&
+ prev.hitCount === next.hitCount &&
+ prev.capturedAt === next.capturedAt &&
+ itemRenderKey(prev) === itemRenderKey(next)
+ )
+ }
+)
diff --git a/src/hooks/useRelativeTimeTick.ts b/src/hooks/useRelativeTimeTick.ts
new file mode 100644
index 0000000..8489db6
--- /dev/null
+++ b/src/hooks/useRelativeTimeTick.ts
@@ -0,0 +1,82 @@
+/**
+ * Shared 30-second clock for relative-time labels ("5m ago").
+ *
+ * WHY: every card used to start its own setInterval. With hundreds of cards
+ * that meant N independent timers firing at unaligned moments — N scattered
+ * render passes across every 30s window, plus timer churn on every
+ * mount/unmount while scrolling. One refcounted interval serves all
+ * subscribers, producing a single batched render pass per tick.
+ *
+ * BEHAVIOUR PARITY: the old per-card intervals only ran while the panel was
+ * open (cards stay mounted when the blade is closed — they are merely hidden).
+ * This module mirrors that exactly: the interval exists only while there is
+ * at least one subscriber AND the shelf is open, so idle cost stays zero.
+ */
+import { useEffect, useState } from 'react'
+import { useStore } from '../store/appStore'
+
+const TICK_MS = 30000
+
+let tick = 0
+let timer: number | undefined
+let subscribers = 0
+const listeners = new Set<() => void>()
+
+function emit(): void {
+ tick++
+ for (const listener of listeners) listener()
+}
+
+function syncTimer(): void {
+ const shouldRun = subscribers > 0 && useStore.getState().open
+ if (shouldRun && timer === undefined) {
+ timer = window.setInterval(emit, TICK_MS)
+ } else if (!shouldRun && timer !== undefined) {
+ window.clearInterval(timer)
+ timer = undefined
+ }
+}
+
+function acquire(): void {
+ subscribers++
+ syncTimer()
+}
+
+function release(): void {
+ subscribers--
+ if (subscribers <= 0) subscribers = 0
+ syncTimer()
+}
+
+// Keep the clock gated on panel visibility (parity with the old per-card
+// behaviour). Wired once at module load; the listener itself does nothing
+// unless the open flag actually flipped.
+if (typeof window !== 'undefined') {
+ let lastOpen = !!useStore.getState().open
+ useStore.subscribe((state) => {
+ if (!!state.open === lastOpen) return
+ lastOpen = !!state.open
+ syncTimer()
+ })
+}
+
+/**
+ * Subscribes the calling component to the shared clock. The component simply
+ * re-renders on each tick so its `relativeTime(capturedAt)` label refreshes;
+ * the returned value itself is intentionally unused.
+ */
+export function useRelativeTimeTick(): number {
+ const [, force] = useState(0)
+
+ useEffect(() => {
+ const listener = (): void => force((n) => n + 1)
+ listeners.add(listener)
+ acquire()
+ return () => {
+ listeners.delete(listener)
+ release()
+ }
+ }, [])
+
+ return tick
+}
diff --git a/src/lib/itemSignature.ts b/src/lib/itemSignature.ts
new file mode 100644
index 0000000..5f4aac4
--- /dev/null
+++ b/src/lib/itemSignature.ts
@@ -0,0 +1,41 @@
+/**
+ * Stable render-identity key for clipboard item cards.
+ *
+ * WHY: every `state:items` push serialises the whole history into brand-new
+ * DTO objects. React.memo's default shallow prop compare then sees "new
+ * object" for every card and re-renders the entire list on each push — even
+ * though hundreds of items did not change. This key captures exactly the
+ * fields a card renders, so the memo comparator can prove two pushes are
+ * visually identical for a given card and skip its re-render entirely.
+ *
+ * Any field a card actually displays is included. Fields added to the DTO in
+ * the future must be mirrored here ONLY if they start being rendered.
+ */
+import type { ClipboardItemDto } from '../../shared/types'
+
+export function itemRenderKey(item: ClipboardItemDto): string {
+ const d = item.data
+ switch (d.kind) {
+ case 'text':
+ // text feeds both the plain preview and the offline link-preview card;
+ // isUrl switches the whole body layout. html/isColor included for
+ // future-proofing at negligible cost (text is capped at 300 chars).
+ return `t|${d.isUrl ? 1 : 0}|${d.isColor ? 1 : 0}|${d.text}|${d.html ?? ''}`
+ case 'image':
+ return `i|${d.imageId}|${d.width}x${d.height}|${d.bytes}|${d.ext ?? ''}|${d.source ?? ''}|${d.fileName ?? ''}|${d.preview}`
+ case 'image-collection':
+ return `c|${d.images
+ .map((i) => `${i.imageId},${i.width},${i.height},${i.bytes},${i.ext ?? ''},${i.preview}`)
+ .join(';')}`
+ case 'files': {
+ const entries =
+ d.entries
+ ?.map(
+ (en) =>
+ `${en.name},${en.size},${en.isImage ? 1 : 0},${en.isDirectory ? 1 : 0},${en.preview ?? ''}`
+ )
+ .join(';') ?? ''
+ return `f|${d.paths.join('\n')}|${entries}`
+ }
+ }
+}
diff --git a/src/styles/item.css b/src/styles/item.css
index 986f418..9b55455 100644
--- a/src/styles/item.css
+++ b/src/styles/item.css
@@ -19,6 +19,18 @@
overflow: hidden;
}
+/* Performance culling — invisible to users.
+ Cards outside the scroll viewport skip style/layout/paint of their whole
+ subtree; scrolling near them renders them normally. The `auto` keyword
+ remembers each card's real measured height after first paint, so scrollbar
+ geometry stays exact while `96px` is only the first-guess fallback for
+ never-rendered cards. Scoped to the scroll list so flyouts/overlays are
+ untouched. */
+.list-stack .item {
+ content-visibility: auto;
+ contain-intrinsic-size: auto 96px;
+}
+
.item:hover {
background: rgba(255, 255, 255, 0.085);
border-color: rgba(255, 255, 255, 0.24);
diff --git a/tests/itemSignature.test.ts b/tests/itemSignature.test.ts
new file mode 100644
index 0000000..224b3e8
--- /dev/null
+++ b/tests/itemSignature.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest'
+import { itemRenderKey } from '../src/lib/itemSignature'
+import type { ClipboardItemDto } from '../shared/types'
+
+function textItem(over: Partial<Extract<ClipboardItemDto['data'], { kind: 'text' }>> = {}): ClipboardItemDto {
+ return {
+ id: 't1',
+ capturedAt: 111,
+ hitCount: 1,
+ pinned: false,
+ data: { kind: 'text', text: 'hello world', isUrl: false, ...over }
+ }
+}
+
+function imageItem(over: Partial<Extract<ClipboardItemDto['data'], { kind: 'image' }>> = {}): ClipboardItemDto {
+ return {
+ id: 'i1',
+ capturedAt: 222,
+ hitCount: 1,
+ pinned: false,
+ data: {
+ kind: 'image',
+ imageId: 'img-1',
+ width: 1920,
+ height: 1080,
+ bytes: 50000,
+ ext: 'png',
+ preview: 'edgelocal://thumb/img-1',
+ ...over
+ }
+ }
+}
+
+describe('itemRenderKey — memo comparator foundation', () => {
+ it('produces identical keys for identical content with DIFFERENT object identities', () => {
+ // This is the exact production scenario: every state:items push rebuilds
+ // all DTO objects; identity-based memo compare used to defeat React.memo.
+ const a = imageItem()
+ const b = JSON.parse(JSON.stringify(imageItem())) as ClipboardItemDto
+ expect(a === b).toBe(false)
+ expect(itemRenderKey(a)).toBe(itemRenderKey(b))
+ })
+
+ it('text: any rendered field change flips the key', () => {
+ const base = itemRenderKey(textItem())
+ expect(itemRenderKey(textItem({ text: 'changed' }))).not.toBe(base)
+ expect(itemRenderKey(textItem({ isUrl: true }))).not.toBe(base)
+ })
+
+ it('image: thumbnail/dimension/size changes flip the key', () => {
+ const base = itemRenderKey(imageItem())
+ expect(itemRenderKey(imageItem({ preview: 'edgelocal://thumb/other' }))).not.toBe(base)
+ expect(itemRenderKey(imageItem({ bytes: 123456 }))).not.toBe(base)
+ expect(itemRenderKey(imageItem({ width: 800, height: 600 }))).not.toBe(base)
+ expect(itemRenderKey(imageItem({ fileName: 'shot.png' }))).not.toBe(base)
+ })
+
+ it('collection: adding/removing/replacing an image flips the key', () => {
+ const make = (ids: string[]): ClipboardItemDto => ({
+ id: 'c1',
+ capturedAt: 1,
+ hitCount: 1,
+ pinned: false,
+ data: {
+ kind: 'image-collection',
+ images: ids.map((imageId) => ({ imageId, width: 10, height: 10, bytes: 5, preview: `u/${imageId}` }))
+ }
+ })
+ const base = itemRenderKey(make(['a', 'b']))
+ expect(itemRenderKey(make(['a']))).not.toBe(base)
+ expect(itemRenderKey(make(['a', 'b', 'c']))).not.toBe(base)
+ expect(itemRenderKey(make(['b', 'a']))).not.toBe(base) // order matters visually
+ expect(itemRenderKey(make(['a', 'b']))).toBe(base)
+ })
+
+ it('files: path or entry metadata changes flip the key; identical bundles do not', () => {
+ const make = (
+ paths: string[] = ['/docs/a.pdf', '/docs/b.txt'],
+ entryOverrides: Partial<{ size: number; preview: string }> = {}
+ ): ClipboardItemDto => ({
+ id: 'f1',
+ capturedAt: 1,
+ hitCount: 1,
+ pinned: false,
+ data: {
+ kind: 'files',
+ paths,
+ entries: paths.map((p) => ({
+ name: p,
+ ext: 'pdf',
+ size: 10,
+ isImage: false,
+ ...entryOverrides
+ }))
+ }
+ })
+ const base = itemRenderKey(make())
+ expect(itemRenderKey(make())).toBe(base)
+ expect(itemRenderKey(make(undefined, { size: 999 }))).not.toBe(base)
+ expect(itemRenderKey(make(undefined, { preview: 'edgelocal://thumb/file/x' }))).not.toBe(base)
+ expect(itemRenderKey(make(['/docs/b.txt', '/docs/a.pdf']))).not.toBe(base)
+ })
+
+ it('top-level card fields are compared by the memo wrapper, key stays data-only by design', () => {
+ // The comparator checks pinned/hitCount/capturedAt/id separately from the
+ // render key, so the key itself intentionally ignores them.
+ const a = imageItem()
+ const b = imageItem()
+ b.pinned = true
+ b.hitCount = 7
+ expect(itemRenderKey(a)).toBe(itemRenderKey(b))
+ })
+})
diff --git a/tests/thumbnailCache.test.ts b/tests/thumbnailCache.test.ts
new file mode 100644
index 0000000..b1c56b2
--- /dev/null
+++ b/tests/thumbnailCache.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+
+const calls = vi.hoisted(() => ({ createFromPath: 0 }))
+
+vi.mock('electron', () => ({
+ nativeImage: {
+ createFromPath: vi.fn((_p: string) => {
+ calls.createFromPath++
+ return {
+ isEmpty: () => false,
+ getSize: () => ({ width: 1920, height: 1080 }),
+ resize: () => ({ toPNG: () => Buffer.from([0x89, 0x50, 0x4e, 0x47]) }),
+ toPNG: () => Buffer.from([0x89, 0x50, 0x4e, 0x47])
+ }
+ })
+ }
+}))
+
+import {
+ clearThumbnailCache,
+ getThumbnailPayload,
+ thumbnailCacheControl,
+ thumbnailCacheSize
+} from '../electron/main/thumbnailCache'
+
+describe('thumbnailCache — bounded LRU + validators', () => {
+ let dir: string
+
+ beforeEach(() => {
+ dir = join(tmpdir(), `ed-thumbcache-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ mkdirSync(dir, { recursive: true })
+ clearThumbnailCache()
+ calls.createFromPath = 0
+ })
+
+ afterEach(() => {
+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }
+ })
+
+ function makePng(name: string): string {
+ const p = join(dir, name)
+ writeFileSync(p, Buffer.from('fake-image-bytes'))
+ return p
+ }
+
+ it('produces an encoded payload with content type and validator etag', () => {
+ const p = makePng('a.png')
+ const payload = getThumbnailPayload(p)
+ expect(payload).not.toBeNull()
+ expect(payload!.contentType).toBe('image/png')
+ expect(payload!.etag).toMatch(/^"[0-9a-f]{64}"$/)
+ expect(Buffer.isBuffer(payload!.body)).toBe(true)
+ })
+
+ it('serves repeat requests from the LRU with ZERO re-decodes of the source', () => {
+ const p = makePng('b.png')
+ const first = getThumbnailPayload(p)!
+ expect(calls.createFromPath).toBe(1)
+
+ for (let i = 0; i < 5; i++) {
+ expect(getThumbnailPayload(p)).toBe(first) // same cached object identity
+ }
+ expect(calls.createFromPath).toBe(1)
+ })
+
+ it('regenerates when the source file changes (mtime bumped)', () => {
+ const p = makePng('c.png')
+ const first = getThumbnailPayload(p)!
+ const firstEtag = first.etag
+
+ // Force a fresh mtime deterministically (same-size rewrite alone could
+ // keep the timestamp identical on coarse filesystems).
+ writeFileSync(p, Buffer.from('changed-image-bytes!'))
+ const future = new Date(Date.now() + 5000)
+ utimesSync(p, future, future)
+
+ const second = getThumbnailPayload(p)!
+ expect(second.etag).not.toBe(firstEtag)
+ expect(calls.createFromPath).toBe(2)
+ })
+
+ it('returns null for missing or unreadable sources without caching anything', () => {
+ expect(getThumbnailPayload(join(dir, 'missing.png'))).toBeNull()
+ expect(thumbnailCacheSize()).toBe(0)
+ })
+
+ it('never exceeds the LRU bound regardless of request count', () => {
+ for (let i = 0; i < 80; i++) {
+ getThumbnailPayload(makePng(`f${i}.png`))
+ }
+ expect(thumbnailCacheSize()).toBeLessThanOrEqual(64)
+ })
+
+ it('evicts oldest entries first (LRU order preserved under churn)', () => {
+ const survivors: Array<ReturnType<typeof getThumbnailPayload>> = []
+ for (let i = 0; i < 60; i++) {
+ survivors.push(getThumbnailPayload(makePng(`old${i}.png`)))
+ }
+ // Push the map past its cap; the earliest payloads must be evicted.
+ for (let i = 0; i < 10; i++) {
+ getThumbnailPayload(makePng(`new${i}.png`))
+ }
+ expect(thumbnailCacheSize()).toBeLessThanOrEqual(64)
+ // Old entries beyond capacity are gone; a re-request re-decodes instead
+ // of returning stale objects.
+ expect(getThumbnailPayload(join(dir, 'old0.png'))).not.toBe(survivors[0])
+ })
+
+ it('cache policy: stored captures are immutable, external files stay revalidated', () => {
+ expect(thumbnailCacheControl(true)).toContain('immutable')
+ expect(thumbnailCacheControl(false)).not.toContain('immutable')
+ expect(thumbnailCacheControl(false)).toMatch(/max-age=\d+/)
+ })
+})