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.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
perf: disk-backed text payloads, image thumbnailing, RAM stabilization, and v0.2.6 upgrade migration
Deepender25d52e825c97f4
diff --git a/electron/main/drag.ts b/electron/main/drag.tsindex ba74805..a523602 100644--- a/electron/main/drag.ts+++ b/electron/main/drag.ts@@ -47,37 +47,15 @@ export function resolveDragData(req: DragRequest): ItemData | null {return item.data}-function logDrag(msg: string): void {- try {- const logPath = join(process.cwd(), 'drag_debug.txt')- require('node:fs').appendFileSync(logPath, `[${new Date().toISOString()}] ${msg}\n`, 'utf8')- } catch {}- console.log(`[DragDebug] ${msg}`)-}--/**- * Begin a native OS drag from a specific webContents (the `event.sender` from- * the `ipcMain.on` handler). This is the **only** reliable way to start a drag- * on Windows — `BrowserWindow.getFocusedWindow()` often returns null for this- * edge panel (it is showInactive / skipTaskbar / alwaysOnTop).- */export function startDragOut(sender: WebContents, data: ItemData): void {- logDrag(`startDragOut called for kind=${data.kind}`)const staged = stageDragFile(data)- if (!staged) {- logDrag(`stageDragFile returned null for kind=${data.kind}`)- return- }- logDrag(`staged: file=${staged.file}, files=${JSON.stringify(staged.files)}`)+ if (!staged) returnconst icon = dragIcon(data)- logDrag(`dragIcon result: isEmpty=${icon.isEmpty()}, size=${JSON.stringify(icon.getSize())}`)-const item: Electron.Item = { file: staged.file, icon }if (staged.files) {item.files = staged.files}- logDrag(`calling sender.startDrag with item.file=${item.file}, item.files=${JSON.stringify(item.files)}`)sender.startDrag(item)}@@ -188,19 +166,16 @@ function getFileDragIcon(): Electron.NativeImage {* We use real image thumbnails or custom SVG card stacks rendered via Resvg.*/function dragIcon(data: ItemData): Electron.NativeImage {- logDrag(`dragIcon called for kind=${data.kind}`)try {if (data.kind === 'image' || data.kind === 'image-collection') {const isCollection = data.kind === 'image-collection'const count = isCollection ? data.images.length : 1- logDrag(`image drag requested: count=${count}. Returning custom image card stack icon!`)if (count === 0) return getFileDragIcon()return createFileStackDragIcon(Array(count).fill('image.png'))}if (data.kind === 'files') {const count = data.paths.length- logDrag(`files check: count=${count}, paths=${JSON.stringify(data.paths)}`)if (count === 0) return getFileDragIcon()return createFileStackDragIcon(data.paths)}@@ -208,9 +183,7 @@ function dragIcon(data: ItemData): Electron.NativeImage {if (data.kind === 'text') {return createTextDragIcon(data.text)}- } catch (err: any) {- logDrag(`dragIcon exception: ${err?.stack || err}`)- }+ } catch {}return getFileDragIcon()}@@ -250,7 +223,6 @@ function createFileStackDragIcon(paths: string[]): Electron.NativeImage {const cacheKey = `stack|solid-black|${kinds.map((k) => k.kind).join('-')}|${count}`const cached = iconCache.get(cacheKey)if (cached && !cached.isEmpty()) {- logDrag(`createFileStackDragIcon returning cached for ${cacheKey}`)return cached}@@ -285,11 +257,9 @@ function createFileStackDragIcon(paths: string[]): Electron.NativeImage {</svg>`try {- logDrag(`createFileStackDragIcon calling Resvg for count=${count}`)const resvg = new Resvg(svg, { fitTo: { mode: 'zoom', value: 3 } })const pngData = resvg.render().asPng()const img = nativeImage.createFromBuffer(pngData, { scaleFactor: 3 })- logDrag(`createFileStackDragIcon resvg result: isEmpty=${img.isEmpty()}, size=${JSON.stringify(img.getSize())}`)if (!img.isEmpty()) {iconCache.set(cacheKey, img)if (iconCache.size > ICON_CACHE_MAX) {@@ -298,9 +268,7 @@ function createFileStackDragIcon(paths: string[]): Electron.NativeImage {}return img}- } catch (err: any) {- logDrag(`createFileStackDragIcon resvg error: ${err?.stack || err}`)- }+ } catch {}return getFileDragIcon()}@@ -366,9 +334,7 @@ function createTextDragIcon(text: string): Electron.NativeImage {const pngData = resvg.render().asPng()const img = nativeImage.createFromBuffer(pngData, { scaleFactor: 2 })if (!img.isEmpty()) return img- } catch (err: any) {- logDrag(`createTextDragIcon exception: ${err?.stack || err}`)- }+ } catch {}return getFileDragIcon()}diff --git a/electron/main/imageProtocol.ts b/electron/main/imageProtocol.tsindex 899d3a5..336221a 100644--- a/electron/main/imageProtocol.ts+++ b/electron/main/imageProtocol.ts@@ -1,5 +1,6 @@import { readdirSync } from 'node:fs'import { basename, dirname, extname, join, resolve } from 'node:path'+import { APP_CONFIG } from './config'const IMAGE_MIME_TYPES: Readonly<Record<string, string>> = {png: 'image/png',@@ -23,6 +24,16 @@ export interface StoredImage {contentType: string}+/** URL for a bounded thumbnail of a staged clipboard image. */+export function thumbnailUrlForStoredImage(imageId: string): string {+ return `${APP_CONFIG.imageProtocol}://thumb/${imageId}`+}++/** URL for a bounded thumbnail of an external image file. */+export function thumbnailUrlForFile(filePath: string): string {+ return `${APP_CONFIG.imageProtocol}://thumb/file/${encodeURIComponent(filePath.replace(/\\/g, '/'))}`+}+/*** Resolve an edgelocal image id to the staged file without allowing the id to* select paths or arbitrary file types. Clipboard captures are PNG, whilediff --git a/electron/main/index.ts b/electron/main/index.tsindex 278b732..fe01ed6 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, protocol, session } from 'electron'+import { app, BrowserWindow, nativeImage, protocol, session } from 'electron'import { APP_CONFIG, runtime } from './config'import { ensureDirs, cleanTemp, PATHS } from '../store/paths'import { createWindow, getMainWindow, setInteractive, setVisible, startCursorPoll, stopCursorPoll, stopHeartbeat, setHotZoneWidth } from './window'@@ -34,8 +34,12 @@ app.disableHardwareAcceleration()// Restrict the renderer to a single webContents and forbid remote module usage.app.enableSandbox()-// Expose GC switch for safe idle memory trimming when panel is closed.-app.commandLine.appendSwitch('js-flags', '--expose-gc')+// Keep V8's old-space heap bounded without starving a renderer that is loading+// an existing clipboard history. This deliberately does not restore+// --optimize-for-size: that flag made collections more aggressive and caused+// visible animation hitches. Chromium image/compositor memory is handled by+// the thumbnail path below rather than by this JavaScript heap limit.+app.commandLine.appendSwitch('js-flags', '--max-old-space-size=512 --expose-gc')// ---- single instance -------------------------------------------------------const gotLock = app.requestSingleInstanceLock()@@ -159,6 +163,18 @@ app.on('activate', () => {function registerImageProtocol(): void {protocol.handle(APP_CONFIG.imageProtocol, async (request) => {try {+ // List cards request bounded raster thumbnails. Do not hand an original+ // 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/')+ ? 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)+ }+// Support streaming full-resolution local image files: edgelocal://file/<encodedPath>if (request.url.startsWith(`${APP_CONFIG.imageProtocol}://file/`)) {const rawPath = request.url.slice(`${APP_CONFIG.imageProtocol}://file/`.length)@@ -210,6 +226,36 @@ 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.+ */+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'+ })+ })+}+// Silence unused import in environments where setVisible isn't referenced// after the refactor (kept for second-instance wiring above).void setInteractivediff --git a/electron/main/ipc.ts b/electron/main/ipc.tsindex 69bf3b0..cb25ff7 100644--- a/electron/main/ipc.ts+++ b/electron/main/ipc.ts@@ -13,8 +13,7 @@ import { psHost, getSystemPowerShellPath } from './powershell'import { filterValidPaths, isValidFilePath, isExistingFilePath } from './pathValidation'import { type InvokeMap, type InvokeChannel, type SendMap, type SendChannel } from '../../shared/ipc'import { getStore, loadSettings, saveSettings, pushState, addFiles, getWatcher } from './state'-import { getMainWindow } from './window'-import { setInteractive, setHeartbeatPaused, setHotZoneWidth, repositionWindow, getDisplayListOptions, popUpAndRetract } from './window'+import { sendToMainWindow, setInteractive, setHeartbeatPaused, setHotZoneWidth, repositionWindow, getDisplayListOptions, popUpAndRetract } from './window'import { getOnboardingWindow } from './onboardingWindow'import { rebuildTrayMenu } from './tray'import { startDragOut, resolveDragData } from './drag'@@ -48,10 +47,7 @@ function clipboardMatchesItem(data: ItemData): boolean {/** Fire a transient toast to the renderer (best-effort; renderer may be closed). */function toast(message: string, tone: 'info' | 'error' = 'info'): void {- const win = getMainWindow()- if (win && !win.isDestroyed()) {- win.webContents.send('ui:toast', { id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, message, tone })- }+ sendToMainWindow('ui:toast', { id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, message, tone })}/** Simulate pressing Ctrl+V via PowerShell after returning focus to the previous active window. */@@ -274,6 +270,10 @@ export function registerIpc(): void {return getStore().toDto()})+ handle('item:get-full-text', (id) => {+ return getStore().getFullText(id)+ })+handle('item:copy', async (id) => {const item = getStore().get(id)console.log('[IPC] item:copy id=', id, 'found=', !!item)@@ -281,11 +281,13 @@ export function registerIpc(): void {const watcher = getWatcher()watcher.setPaused(true)- await writeItemToClipboard(item.data)+ const fullText = item.data.kind === 'text' ? getStore().getFullText(id) : undefined+ const itemDataWithFullText = item.data.kind === 'text' && fullText ? { ...item.data, text: fullText } : item.data+ await writeItemToClipboard(itemDataWithFullText)console.log('[IPC] item:copy wrote to clipboard, kind=', item.data.kind)// Promote the copied item to the top of the history stack- getStore().add(item.data, loadSettings().historyLimit)+ getStore().add(itemDataWithFullText, loadSettings().historyLimit)pushState.items()// Unpause after a short delay to allow OS clipboard event to settle.@@ -366,7 +368,9 @@ export function registerIpc(): void {pushState.togglePanel(false)// 2. Write item to system clipboard- await writeItemToClipboard(item.data)+ const fullText = item.data.kind === 'text' ? getStore().getFullText(id) : undefined+ const itemDataWithFullText = item.data.kind === 'text' && fullText ? { ...item.data, text: fullText } : item.data+ await writeItemToClipboard(itemDataWithFullText)console.log('[IPC] item:paste wrote to clipboard, kind=', item.data.kind)// 3. Touch item timestamp if enabled@@ -655,10 +659,12 @@ export function registerSendListeners(): void {/** Write any item payload back onto the system clipboard. */export async function writeItemToClipboard(data: ItemData): Promise<void> {switch (data.kind) {- case 'text':+ case 'text': {+ const textToUse = data.textclipboard.clear()- clipboard.write({ text: data.text, html: data.html })+ clipboard.write({ text: textToUse, html: data.html })break+ }case 'image': {const dto = getStore().toDto().find(diff --git a/electron/main/state.ts b/electron/main/state.tsindex fcaf4c9..ccb040e 100644--- a/electron/main/state.ts+++ b/electron/main/state.ts@@ -42,7 +42,14 @@ function handleSystemWake(): void {/** Initialize persistence + start the clipboard watcher. */export function initState(): void {store.load()- if (loadSettings().clearUnpinnedOnRestart) {++ // One-time v0.2.6 upgrade migration: clear unpinned items once & set default historyLimit to 250+ const currentSettings = loadSettings()+ if (!currentSettings.v026UpgradeCleaned) {+ console.log('[State] Executing one-time v0.2.6 upgrade migration: clearing unpinned items & setting historyLimit to 250...')+ store.clearUnpinned()+ saveSettings({ v026UpgradeCleaned: true, historyLimit: 250 })+ } else if (currentSettings.clearUnpinnedOnRestart) {store.clearUnpinned()}store.pruneExpired(loadSettings().autoDeleteHours)diff --git a/electron/main/window.ts b/electron/main/window.tsindex a825eca..c15e091 100644--- a/electron/main/window.ts+++ b/electron/main/window.ts@@ -73,6 +73,21 @@ export function getMainWindow(): BrowserWindow | null {return mainWindow}+/** Send only while the panel has a live, settled renderer frame. */+export function sendToMainWindow(channel: string, ...args: unknown[]): boolean {+ if (!mainWindow || mainWindow.isDestroyed()) return false+ const contents = mainWindow.webContents+ if (contents.isDestroyed() || contents.isLoadingMainFrame()) return false+ try {+ contents.send(channel, ...args)+ return true+ } catch {+ // A frame can be disposed between the checks above and send(). Renderer+ // hydration obtains the current state once its replacement frame is ready.+ return false+ }+}+/** True when the window currently accepts mouse clicks (blade is "open"). */export function isInteractive(): boolean {return interactive@@ -284,17 +299,15 @@ function _pollTick(): void {lastEdgeState = newState_lastSentX = clientX_lastSentY = clientY- if (!mainWindow.webContents.isDestroyed()) {- mainWindow.webContents.send('window:cursor-edge', {- x: clientX,- y: clientY,- inEdge,- inZone: true,- stickPosition: settings.stickPosition,- displayWidth: wa.width,- displayHeight: wa.height- })- }+ sendToMainWindow('window:cursor-edge', {+ x: clientX,+ y: clientY,+ inEdge,+ inZone: true,+ stickPosition: settings.stickPosition,+ displayWidth: wa.width,+ displayHeight: wa.height+ })}}@@ -382,9 +395,7 @@ function getStickGeometry(): { x: number; y: number; width: number; height: numbstickDisplayWorkArea: recoveredViaBounds ? resolved.workArea : undefined,stickDisplayScaleFactor: recoveredViaBounds ? resolved.scaleFactor : undefined})- if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {- mainWindow.webContents.send('state:settings', settings)- }+ sendToMainWindow('state:settings', settings)if (!recoveredViaBounds) {// Genuinely fell back — briefly show panel on new location.popUpAndRetract(1500)@@ -401,9 +412,7 @@ function getStickGeometry(): { x: number; y: number; width: number; height: numbstickDisplayWorkArea: resolved.workArea,stickDisplayScaleFactor: resolved.scaleFactor})- if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {- mainWindow.webContents.send('state:settings', settings)- }+ sendToMainWindow('state:settings', settings)} else if (settings.stickDisplayId !== undefined && (settings.stickDisplayWorkArea === undefined ||settings.stickDisplayScaleFactor === undefined@@ -460,9 +469,7 @@ export function createWindow(): BrowserWindow {registerFullscreenActiveListener(() => {const settings = loadSettings()if (settings.suppressInFullscreen && (settings.hoverActivation ?? true)) {- if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {- mainWindow.webContents.send('window:toggle', false)- }+ sendToMainWindow('window:toggle', false)setInteractive(false)}})@@ -680,15 +687,15 @@ export function popUpAndRetract(durationMs = 1500): void {const wasAlreadyOpen = interactiveconsole.log(`[Main] Popping up panel briefly to confirm new screen/edge location (wasAlreadyOpen=${wasAlreadyOpen})`)- mainWindow.webContents.send('window:toggle', true)+ sendToMainWindow('window:toggle', true)if (popUpTimer !== null) clearTimeout(popUpTimer)if (!wasAlreadyOpen) {popUpTimer = setTimeout(() => {popUpTimer = null- if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()) {+ if (mainWindow && !mainWindow.isDestroyed()) {console.log('[Main] Retracting panel after brief confirmation pop-up')- mainWindow.webContents.send('window:toggle', false)+ sendToMainWindow('window:toggle', false)}}, durationMs)}diff --git a/electron/preload/index.ts b/electron/preload/index.tsindex 33a70e0..e2d0004 100644--- a/electron/preload/index.ts+++ b/electron/preload/index.ts@@ -143,6 +143,7 @@ const api = {deleteItem: (id: string) => invoke('item:delete', id),deleteBatchItems: (ids: string[]) => invoke('item:delete-batch', ids),clearItems: () => invoke('item:clear'),+ getFullText: (id: string) => invoke('item:get-full-text', id),copyItem: (id: string) => invoke('item:copy', id),copySubitem: (req: import('../../shared/types').DragRequest) => invoke('item:copy-subitem', req),pasteItem: (id: string) => invoke('item:paste', id),diff --git a/electron/store/ItemStore.ts b/electron/store/ItemStore.tsindex aeaf9a3..1e0d329 100644--- a/electron/store/ItemStore.ts+++ b/electron/store/ItemStore.ts@@ -12,6 +12,7 @@import { existsSync, readFileSync, writeFileSync, rmSync, statSync, readdirSync } from 'node:fs'import { join, extname, basename as pathBasename } from 'node:path'import { nativeImage, safeStorage } from 'electron'+import { thumbnailUrlForFile, thumbnailUrlForStoredImage } from '../main/imageProtocol'import {type ClipboardItem,type ClipboardItemDto,@@ -91,18 +92,32 @@ export class ItemStore {if (parsedIndex && Array.isArray(parsedIndex.items)) {this.items = parsedIndex.items.filter((it) => it && it.data && typeof it.id === 'string')++ // Auto-migrate large text items to disk payload files+ let migratedAnyPayloads = false+ for (const it of this.items) {+ if (it.data.kind === 'text') {+ if (!it.data.hasFullPayload && it.data.text.length > 300) {+ this.writeTextPayload(it.id, it.data.text)+ it.data.hasFullPayload = true+ it.data.previewText = it.data.text.slice(0, 300)+ it.data.text = it.data.previewText+ migratedAnyPayloads = true+ }+ }+ }+this.rebuildIndex()// Auto-migrate legacy plain JSON: create backup & upgrade to DPAPI encryption- if (needsMigration) {- console.log('[ItemStore] Migrating legacy plain-text items.json to DPAPI safeStorage encryption...')+ if (needsMigration || migratedAnyPayloads) {+ console.log('[ItemStore] Migrating items.json to DPAPI safeStorage encryption and disk payloads...')try {const backupFile = `${file}.v1.bak`if (!existsSync(backupFile)) {writeFileSync(backupFile, rawBuffer)}this.persist()- console.log('[ItemStore] Auto-migration to DPAPI encryption completed successfully!')} catch (err) {console.error('[ItemStore] Auto-migration backup/persist failed:', err)}@@ -181,6 +196,7 @@ export class ItemStore {if (it.data.kind === 'image-collection') {it.data.images.forEach((img) => this.removeImageFile(img.imageId))}+ if (it.data.kind === 'text') this.removeTextPayload(it.id)stillNeed--} else {survivors.unshift(it)@@ -215,7 +231,18 @@ export class ItemStore {}const id = createId()- const item: ClipboardItem = { id, data, capturedAt: now, hitCount: 1, pinned: false }+ let finalData = data+ if (data.kind === 'text' && data.text.length > 300) {+ this.writeTextPayload(id, data.text)+ finalData = {+ ...data,+ hasFullPayload: true,+ previewText: data.text.slice(0, 300),+ text: data.text.slice(0, 300)+ }+ }++ const item: ClipboardItem = { id, data: finalData, capturedAt: now, hitCount: 1, pinned: false }this.items.unshift(item)this.sigToId.set(sig, id)if (data.kind === 'image') this.writeImageFile(data.imageId)@@ -262,6 +289,7 @@ export class ItemStore {if (removed.data.kind === 'image-collection') {removed.data.images.forEach((img) => this.removeImageFile(img.imageId))}+ if (removed.data.kind === 'text') this.removeTextPayload(removed.id)this.persistSync()}@@ -283,6 +311,7 @@ export class ItemStore {if (removed.data.kind === 'image-collection') {removed.data.images.forEach((img) => this.removeImageFile(img.imageId))}+ if (removed.data.kind === 'text') this.removeTextPayload(removed.id)}this.persistSync()}@@ -492,6 +521,7 @@ export class ItemStore {if (it.data.kind === 'image-collection') {it.data.images.forEach((img) => this.removeImageFile(img.imageId))}+ if (it.data.kind === 'text') this.removeTextPayload(it.id)}}this.items = kept@@ -617,6 +647,37 @@ export class ItemStore {}}+ private textPayloadPath(id: string): string {+ return join(PATHS.payloadsDir(), `${id}.txt`)+ }++ private writeTextPayload(id: string, text: string): void {+ try {+ writeFileSync(this.textPayloadPath(id), text, 'utf8')+ } catch { /* ignore */ }+ }++ private removeTextPayload(id: string): void {+ try {+ const p = this.textPayloadPath(id)+ if (existsSync(p)) rmSync(p, { force: true })+ } catch { /* ignore */ }+ }++ public getFullText(id: string): string {+ const item = this.items.find((x) => x.id === id)+ if (!item || item.data.kind !== 'text') return ''+ if (item.data.hasFullPayload) {+ try {+ const p = this.textPayloadPath(id)+ if (existsSync(p)) {+ return readFileSync(p, 'utf8')+ }+ } catch { /* ignore */ }+ }+ return item.data.text+ }+/* ------------------------------- DTO ----------------------------------- *//** Snapshot the whole list as renderer-safe DTOs (images inlined). */@@ -626,13 +687,13 @@ export class ItemStore {const { kind, imageId, width, height, bytes, ext } = it.datareturn {...it,- data: { kind, imageId, width, height, bytes, ext, preview: `edgelocal://${imageId}` }+ data: { kind, imageId, width, height, bytes, ext, preview: thumbnailUrlForStoredImage(imageId) }}}if (it.data.kind === 'image-collection') {const imagesWithPreviews = it.data.images.map((img) => ({...img,- preview: `edgelocal://${img.imageId}`+ preview: thumbnailUrlForStoredImage(img.imageId)}))return {...it,@@ -646,10 +707,9 @@ export class ItemStore {const entry = buildFileEntry(p)if (entry.isImage && imagePreviewCount < 20) {imagePreviewCount++- const norm = p.replace(/\\/g, '/')return {...entry,- preview: `edgelocal://file/${encodeURIComponent(norm)}`+ preview: thumbnailUrlForFile(p)}}return entrydiff --git a/electron/store/paths.ts b/electron/store/paths.tsindex e2c4ff3..1f0da21 100644--- a/electron/store/paths.ts+++ b/electron/store/paths.ts@@ -14,6 +14,8 @@ const root = () => app.getPath('userData')export const PATHS = {/** userData root. */root,+ /** Directory holding text payloads for large text entries. */+ payloadsDir: () => join(root(), 'payloads'),/** Directory holding one PNG per captured image item. */imagesDir: () => join(root(), 'images'),/** Path to the items index JSON. */@@ -30,7 +32,7 @@ export const PATHS = {/** Idempotently create every directory the app needs. Safe to call repeatedly. */export function ensureDirs(): void {- for (const dir of [PATHS.imagesDir(), PATHS.tempDir()]) {+ for (const dir of [PATHS.imagesDir(), PATHS.payloadsDir(), PATHS.tempDir()]) {mkdirSync(dir, { recursive: true })}}diff --git a/shared/bridge.ts b/shared/bridge.tsindex a12923c..56839f8 100644--- a/shared/bridge.ts+++ b/shared/bridge.ts@@ -15,6 +15,7 @@ export interface EdgeApi {deleteItem: (id: string) => Promise<import('./types').ClipboardItemDto[]>deleteBatchItems: (ids: string[]) => Promise<import('./types').ClipboardItemDto[]>clearItems: () => Promise<import('./types').ClipboardItemDto[]>+ getFullText: (id: string) => Promise<string>removeSubitem: (req: DragRequest) => Promise<boolean>copyItem: (id: string) => Promise<boolean>copySubitem: (req: DragRequest) => Promise<boolean>diff --git a/shared/ipc.ts b/shared/ipc.tsindex 5233a90..c0a029e 100644--- a/shared/ipc.ts+++ b/shared/ipc.ts@@ -31,6 +31,9 @@ export interface InvokeMap {/** Delete every unpinned item. */'item:clear': { args: []; result: ClipboardItemDto[] }+ /** Fetch the full text payload from disk for a large text item on-demand. */+ 'item:get-full-text': { args: [id: string]; result: string }+/** Remove a specific sub-item from a bundle. */'item:remove-subitem': { args: [req: DragRequest]; result: boolean }diff --git a/shared/types.ts b/shared/types.tsindex dd20e6f..55ed6c5 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -13,7 +13,7 @@ export const MAX_STACK = 10/** Discriminated union describing the payload of a clipboard item. */export type ItemData =- | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean }+ | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string }| { kind: 'image'; imageId: string; width: number; height: number; bytes: number; ext?: string }| { kind: 'image-collection'; images: { imageId: string; width: number; height: number; bytes: number; ext?: string }[] }| { kind: 'files'; paths: string[] }@@ -54,7 +54,7 @@ export interface FileEntry {/** Payload sent over IPC: same as ClipboardItem but with inline image previews. */export interface ClipboardItemDto extends Omit<ClipboardItem, 'data'> {data:- | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean }+ | { kind: 'text'; text: string; html?: string; isUrl: boolean; isColor?: boolean; hasFullPayload?: boolean; previewText?: string }| { kind: 'image'; imageId: string; width: number; height: number; bytes: number; preview: string; ext?: string }| { kind: 'image-collection'; images: { imageId: string; width: number; height: number; bytes: number; preview: string; ext?: string }[] }| { kind: 'files'; paths: string[]; previews?: string[]; entries?: FileEntry[] }@@ -170,13 +170,15 @@ export interface Settings {language?: string/** When true, pasting an unpinned item updates its timestamp to move it to the top of Recent. Default: true. */movePastedToTop?: boolean+ /** One-time flag tracking if the v0.2.6 upgrade unpinned history cleanup has run. */+ v026UpgradeCleaned?: boolean}export const DEFAULT_SETTINGS: Settings = {hotZoneHeight: 0.25,hotZoneWidth: 3,movePastedToTop: true,- historyLimit: 500,+ historyLimit: 250,panelHeight: 0.5,incognito: false,launchAtLogin: true,diff --git a/src/components/ClipboardItem.tsx b/src/components/ClipboardItem.tsxindex 26912ad..2157d90 100644--- a/src/components/ClipboardItem.tsx+++ b/src/components/ClipboardItem.tsx@@ -416,6 +416,8 @@ function BundleFluidPreview({><motion.imgsrc={img.preview}+ loading="lazy"+ decoding="async"style={{ width: 50, height: 50, objectFit: 'cover', borderRadius: 4, background: 'rgba(0,0,0,0.5)' }}draggable={false}/>@@ -454,6 +456,8 @@ function BundleFluidPreview({<motion.imgkey={img.imageId}src={img.preview}+ loading="lazy"+ decoding="async"className="bundle-stack-card"animate={{x: realIndex * 20 - 20,@@ -532,6 +536,8 @@ function BundleFluidPreview({<imgsrc={entry.preview}alt=""+ loading="lazy"+ decoding="async"draggable={false}style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 6 }}/>@@ -595,6 +601,8 @@ function BundleFluidPreview({<imgsrc={entry.preview}alt=""+ loading="lazy"+ decoding="async"draggable={false}style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 8 }}/>@@ -655,6 +663,8 @@ function Preview({ item }: { item: ClipboardItemDto }) {className="thumb"src={item.data.preview}alt=""+ loading="lazy"+ decoding="async"draggable={false}/>) : (@@ -681,6 +691,8 @@ function Preview({ item }: { item: ClipboardItemDto }) {className="thumb"src={entry.preview}alt=""+ loading="lazy"+ decoding="async"draggable={false}/>) : (diff --git a/src/components/PreviewFlyout.tsx b/src/components/PreviewFlyout.tsxindex d270e67..d8f2d44 100644--- a/src/components/PreviewFlyout.tsx+++ b/src/components/PreviewFlyout.tsx@@ -557,15 +557,26 @@ function PreviewContent({const { t } = useTranslation()const startDrag = useDragOut()+ const [fullText, setFullText] = useState<string | null>(null)++ useEffect(() => {+ if (item?.data?.kind === 'text' && item.data.hasFullPayload) {+ window.edge.getFullText(item.id).then((t) => setFullText(t)).catch(() => {})+ } else {+ setFullText(null)+ }+ }, [item?.id, item?.data?.hasFullPayload])+if (item.data.kind === 'text') {- const text: string = item.data.text.length > 20000- ? item.data.text.slice(0, 20000) + `\n\n${t('flyout.contentTruncated')}`- : item.data.text+ const activeText = fullText ?? item.data.text+ const text: string = activeText.length > 20000+ ? activeText.slice(0, 20000) + `\n\n${t('flyout.contentTruncated')}`+ : activeTextconst isCode = looksLikeCode(text)const isUrl = item.data.isUrlif (isUrl) {- const info = parseUrlPreview(item.data.text)+ const info = parseUrlPreview(activeText)return (<divonClick={(e) => {@@ -597,12 +608,12 @@ function PreviewContent({<QuickActionButtontitle={t('flyout.openLink')}icon={ExternalLinkIcon}- onClick={() => window.open(item.data.text, '_blank')}+ onClick={() => window.open(activeText, '_blank')}/><QuickActionButtontitle={t('flyout.copyText')}icon={CopyIcon}- onClick={() => navigator.clipboard.writeText(item.data.text)}+ onClick={() => navigator.clipboard.writeText(activeText)}/></div></div>@@ -623,7 +634,7 @@ function PreviewContent({<divonClick={(e) => {e.stopPropagation()- window.open(item.data.text, '_blank')+ window.open(activeText, '_blank')}}style={{padding: '10px 12px',@@ -647,7 +658,7 @@ function PreviewContent({e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.08)'}}>- {item.data.text}+ {activeText}</div></div>)@@ -668,7 +679,7 @@ function PreviewContent({<QuickActionButtontitle={t('flyout.copyText')}icon={CopyIcon}- onClick={() => navigator.clipboard.writeText(item.data.text)}+ onClick={() => navigator.clipboard.writeText(activeText)}/></div><div style={{diff --git a/src/store/appStore.ts b/src/store/appStore.tsindex 886b6ee..4d8c63e 100644--- a/src/store/appStore.ts+++ b/src/store/appStore.ts@@ -328,20 +328,41 @@ export const useStore = create<AppState>((set, get) => ({},async remove(id) {- set({ items: get().items.filter((it) => it.id !== id) })- const items = await edge.deleteItem(id)- set({ items })+ const previousItems = get().items+ set({ items: previousItems.filter((it) => it.id !== id) })+ try {+ const items = await edge.deleteItem(id)+ set({ items })+ } catch {+ // Do not leave the UI claiming an item was deleted when the main-process+ // persistence request failed (for example during a renderer reload).+ set({ items: previousItems })+ get().pushToast({ id: `delete-${Date.now()}`, message: 'Could not delete this item. Please try again.', tone: 'error' })+ }},async clear(ids?: string[]) {if (!ids || ids.length === 0) {- const items = await edge.clearItems()- set({ items })+ const previousItems = get().items+ set({ items: previousItems.filter((it) => it.pinned) })+ try {+ const items = await edge.clearItems()+ set({ items })+ } catch {+ set({ items: previousItems })+ get().pushToast({ id: `clear-${Date.now()}`, message: 'Could not clear history. Please try again.', tone: 'error' })+ }} else {+ const previousItems = get().itemsconst idSet = new Set(ids)- set({ items: get().items.filter((it) => !idSet.has(it.id)) })- const items = await edge.deleteBatchItems(ids)- set({ items })+ set({ items: previousItems.filter((it) => !idSet.has(it.id)) })+ try {+ const items = await edge.deleteBatchItems(ids)+ set({ items })+ } catch {+ set({ items: previousItems })+ get().pushToast({ id: `clear-${Date.now()}`, message: 'Could not clear history. Please try again.', tone: 'error' })+ }}},diff --git a/tests/imageProtocol.test.ts b/tests/imageProtocol.test.tsindex 55b1784..32d80ef 100644--- a/tests/imageProtocol.test.ts+++ b/tests/imageProtocol.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { resolveStoredImage } from '../electron/main/imageProtocol'+import { resolveStoredImage, thumbnailUrlForFile, thumbnailUrlForStoredImage } from '../electron/main/imageProtocol'describe('resolveStoredImage', () => {let imagesDir: string@@ -45,4 +45,13 @@ describe('resolveStoredImage', () => {expect(resolveStoredImage(imagesDir, '../secret')).toBeNull()expect(resolveStoredImage(imagesDir, 'secret.png')).toBeNull()})++ it('uses the bounded thumbnail endpoint for staged images', () => {+ expect(thumbnailUrlForStoredImage('image-abc123')).toBe('edgelocal://thumb/image-abc123')+ })++ it('encodes file thumbnail paths without exposing a raw Windows path', () => {+ expect(thumbnailUrlForFile('C:\\Pictures\\image one.png'))+ .toBe('edgelocal://thumb/file/C%3A%2FPictures%2Fimage%20one.png')+ })})