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.

fix(clipboard): unify paste/drag file handling, lifecycle temp cleanup, honest failures

Deepender25dfe3fca77254
diff --git a/electron/main/drag.ts b/electron/main/drag.ts
index 6ac9e97..a403796 100644
--- a/electron/main/drag.ts
+++ b/electron/main/drag.ts
@@ -21,6 +21,7 @@ import { getUnpackagedTempDir, toUnpackagedFilePaths } from '../store/paths'
import type { DragRequest, ItemData } from '../../shared/types'
import { getStore } from './state'
import { getFileKind } from '../../src/lib/fileType'
+import { recordStagedFiles } from './stagedTemp'
function stampForFilename(capturedAt?: number): string {
const d = capturedAt ? new Date(capturedAt) : new Date()
@@ -89,9 +90,9 @@ export function resolveDragData(req: DragRequest): { data: ItemData; capturedAt?
return { data: item.data, capturedAt: item.capturedAt }
}
-export function startDragOut(sender: WebContents, data: ItemData, capturedAt?: number): void {
+export function startDragOut(sender: WebContents, data: ItemData, capturedAt?: number): boolean {
const staged = stageDragFile(data, capturedAt)
- if (!staged) return
+ if (!staged) return false
const icon = dragIcon(data)
const item: Electron.Item = { file: staged.file, icon }
@@ -99,6 +100,7 @@ export function startDragOut(sender: WebContents, data: ItemData, capturedAt?: n
item.files = staged.files
}
sender.startDrag(item)
+ return true
}
/* ------------------------------------------------------------------ */
@@ -223,6 +225,15 @@ export function stageDragFile(data: ItemData, capturedAt?: number): Staged | nul
const first = stagedCache.keys().next().value
if (first) stagedCache.delete(first)
}
+ // Lifecycle tracking: register generated artifacts with the staged-temp
+ // manager so they are reaped when their owning history item dies.
+ // Only paths inside our managed temp roots are recorded — original user
+ // files exposed by `files` bundles are never tracked.
+ try {
+ recordStagedFiles(data, result.files ?? [result.file])
+ } catch {
+ /* ignore — staging itself already succeeded */
+ }
}
return result
diff --git a/electron/main/index.ts b/electron/main/index.ts
index bf4afac..41faa12 100644
--- a/electron/main/index.ts
+++ b/electron/main/index.ts
@@ -10,7 +10,7 @@
*/
import { app, BrowserWindow, nativeImage, protocol, session } from 'electron'
import { APP_CONFIG, runtime } from './config'
-import { ensureDirs, cleanTemp, PATHS } from '../store/paths'
+import { ensureDirs, PATHS } from '../store/paths'
import { createWindow, getMainWindow, setInteractive, setVisible, startCursorPoll, stopCursorPoll, stopHeartbeat, setHotZoneWidth, registerTaskbarCreatedListener } from './window'
import { createTray, registerIncognitoApplier, refreshTray } from './tray'
import { registerIpc, registerSendListeners } from './ipc'
@@ -21,6 +21,7 @@ import { initState, getWatcher, loadSettings, saveSettings, pushState, stopState
import { initAutoUpdater } from './updater'
import { createOnboardingWindow } from './onboardingWindow'
import { startFullscreenMonitor, stopFullscreenMonitor, triggerFullscreenCheck } from './fullscreen'
+import { flushStagedTempRegistry } from './stagedTemp'
import { extname, normalize } from 'node:path'
import { existsSync, createReadStream } from 'node:fs'
import { createHash } from 'node:crypto'
@@ -79,6 +80,9 @@ app.on('before-quit', () => {
try {
getStore().persistSync()
} catch { /* ignore */ }
+ try {
+ flushStagedTempRegistry()
+ } catch { /* ignore */ }
try {
const { globalShortcut } = require('electron')
globalShortcut.unregisterAll()
@@ -93,7 +97,9 @@ app.whenReady().then(() => {
}
ensureDirs()
- cleanTemp()
+ // NOTE: temp cleanup is intentionally NOT a blind wipe anymore. Staged drag
+ // and paste artifacts are lifecycle-managed (see stagedTemp.ts) and are
+ // reconciled against living history inside initState().
// Lock the renderer session down: block all permission requests by default.
const ses = session.defaultSession
diff --git a/electron/main/ipc.ts b/electron/main/ipc.ts
index e0cdb13..feaa4ad 100644
--- a/electron/main/ipc.ts
+++ b/electron/main/ipc.ts
@@ -85,10 +85,14 @@ function simulatePaste(): void {
* text. PowerShell's Clipboard.SetFileDropList writes CF_HDROP + FileNameW +
* Shell IDList Array + all other shell formats in a single atomic transaction.
* Paths are base64-encoded so any character (spaces, quotes, Unicode) is safe.
+ *
+ * Returns false when no valid path remained (e.g. every source file was
+ * deleted since capture) so callers can surface an explicit error.
*/
-async function writeFileListToClipboard(rawPaths: string[]): Promise<void> {
+async function writeFileListToClipboard(rawPaths: string[]): Promise<boolean> {
const validPaths = toUnpackagedFilePaths(filterValidPaths(rawPaths))
- if (process.platform === 'win32' && validPaths.length > 0) {
+ if (validPaths.length === 0) return false
+ if (process.platform === 'win32') {
try {
const addLines = validPaths
.map(p => `$c.Add([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(p, 'utf8').toString('base64')}')))|Out-Null`)
@@ -100,19 +104,44 @@ async function writeFileListToClipboard(rawPaths: string[]): Promise<void> {
'[Windows.Forms.Clipboard]::SetFileDropList($c)'
].join(';')
await psHost.run(script, 3000)
- return
+ return true
} catch (err) {
console.error('[ipc] writeFileListToClipboard PowerShell failed, using text fallback:', err)
}
}
- // Non-Windows fallback: plain text paths (best-effort)
- if (validPaths.length > 0) {
- clipboard.clear()
- clipboard.writeText(validPaths.join('\r\n'))
+ // Non-Windows / PowerShell failure fallback: plain text paths (best-effort)
+ clipboard.clear()
+ clipboard.writeText(validPaths.join('\r\n'))
+ return true
+}
+
+/**
+ * Write a full-resolution bitmap onto the system clipboard.
+ *
+ * Deliberately does NOT fall back to the low-res renderer preview: silently
+ * pasting a 240px thumbnail when the original vanished is worse than an
+ * explicit failure. Returns false so callers can show a precise toast.
+ */
+export async function writeImageToClipboard(imagePath: string | null): Promise<boolean> {
+ if (imagePath && existsSync(imagePath)) {
+ try {
+ const img = nativeImage.createFromPath(imagePath)
+ if (!img.isEmpty()) {
+ clipboard.clear()
+ clipboard.writeImage(img)
+ return true
+ }
+ } catch (err) {
+ console.error('[ipc] writeImageToClipboard nativeImage.createFromPath failed:', err)
+ }
}
+ return false
}
-/** Bitmap for apps that read CF_DIB, plus a named file so Explorer paste keeps our filename. */
+/**
+ * Bitmap for apps that read CF_DIB, plus a named file so Explorer paste keeps
+ * our friendly filename. Atomic multi-format write via PowerShell DataObject.
+ */
async function writeImageWithNamedFile(imagePath: string, namedPath: string): Promise<boolean> {
if (process.platform !== 'win32') return false
try {
@@ -140,34 +169,6 @@ async function writeImageWithNamedFile(imagePath: string, namedPath: string): Pr
}
}
-export async function writeImageToClipboard(imagePath: string | null, previewDataUrl?: string): Promise<void> {
- // If we have the full image path on disk, load the nativeImage directly from path
- if (imagePath && existsSync(imagePath)) {
- try {
- const img = nativeImage.createFromPath(imagePath)
- if (!img.isEmpty()) {
- clipboard.clear()
- clipboard.writeImage(img)
- return
- }
- } catch (err) {
- console.error('[ipc] writeImageToClipboard nativeImage.createFromPath failed:', err)
- }
- }
-
- // Fallback if imagePath was missing but previewDataUrl exists
- if (previewDataUrl) {
- try {
- const img = nativeImage.createFromDataURL(previewDataUrl)
- if (!img.isEmpty()) {
- clipboard.clear()
- clipboard.writeImage(img)
- return
- }
- } catch { /* ignore */ }
- }
-}
-
/**
* Type-checked registration helper: guarantees the handler's return matches the
* contract declared in InvokeMap.
@@ -247,6 +248,13 @@ export function registerIpc(): void {
handle('item:delete', (id) => {
const item = getStore().get(id)
+ // Resolve clipboard ownership BEFORE mutating the store: if this exact
+ // content still sits on the system clipboard it must be cleared first so
+ // the staged-temp cleanup that runs inside delete() can never yank a
+ // file out from under a live OS clipboard reference.
+ if (item && clipboardMatchesItem(item.data)) {
+ clipboard.clear()
+ }
getStore().delete(id)
// If the deleted item is still on the system clipboard, clear the clipboard.
// This is the fix for the copy→delete→copy cycle bug:
@@ -266,6 +274,11 @@ export function registerIpc(): void {
handle('item:delete-batch', (ids) => {
if (!ids || ids.length === 0) return getStore().toDto()
const items = ids.map((id) => getStore().get(id)).filter(Boolean)
+ // Clear matching clipboard content before the batch removal triggers
+ // staged-temp cleanup (same ownership rule as single delete).
+ if (items.some((item) => item && clipboardMatchesItem(item.data))) {
+ clipboard.clear()
+ }
getStore().deleteBatch(ids)
if (items.some((item) => item && clipboardMatchesItem(item.data))) {
clipboard.clear()
@@ -276,11 +289,13 @@ export function registerIpc(): void {
})
handle('item:clear', () => {
- getStore().clearUnpinned()
// Clear the system clipboard unconditionally: the user wiped their history,
// so whatever is on the clipboard should not zombie-reappear, and clearing
// ensures any subsequent re-copy of the same content is detectable.
- clipboard.clear()
+ // Clear the system clipboard unconditionally and BEFORE the store wipe:
+ // the user wiped their history, so whatever is on the clipboard should
+ // not zombie-reappear, and every removed item's staged temp files become
+ // safe to reap inside clearUnpinned().
getWatcher().resyncSignature()
pushState.items()
return getStore().toDto()
@@ -299,7 +314,17 @@ export function registerIpc(): void {
watcher.setPaused(true)
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)
+ const ok = await writeItemToClipboard(itemDataWithFullText, item.capturedAt)
+ if (!ok) {
+ // Source content (e.g. the staged image file) is unrecoverable. Do not
+ // promote a dead item to the top of history — tell the user instead.
+ console.log('[IPC] item:copy aborted — source content unavailable')
+ toast('Original image no longer available', 'error')
+ setTimeout(() => {
+ watcher.setPaused(loadSettings().incognito)
+ }, 200)
+ return false
+ }
console.log('[IPC] item:copy wrote to clipboard, kind=', item.data.kind)
// Promote the copied item to the top of the history stack
@@ -325,16 +350,15 @@ export function registerIpc(): void {
if (dto.data.kind === 'files' && req.paths && req.paths.length > 0) {
// Write real file references so pasting into Explorer copies the file,
// not a path string.
- await writeFileListToClipboard(req.paths)
- wrote = true
+ wrote = await writeFileListToClipboard(req.paths)
+ if (!wrote) toast('Original file no longer available', 'error')
} else if (dto.data.kind === 'image-collection' && req.imageId) {
const img = dto.data.images.find((i) => i.imageId === req.imageId)
if (img) {
// Single image from a collection: write full bitmap + file reference atomically.
- const src = getStore().getImagePath(img.imageId, img.ext)
- const preview = img.preview ?? ''
- await writeImageToClipboard(src && existsSync(src) ? src : null, preview)
- wrote = true
+ const src = getStore().resolveStoredImagePath(img.imageId, img.ext)
+ wrote = await writeImageToClipboard(src)
+ if (!wrote) toast('Original image no longer available', 'error')
}
}
@@ -376,6 +400,19 @@ export function registerIpc(): void {
console.log('[IPC] item:paste id=', id, 'found=', !!item)
if (!item) return false
+ // Fast pre-flight BEFORE any UI state changes: if the source content is
+ // unrecoverable (e.g. the staged image file vanished), abort with an
+ // explicit message while the panel is still open — never close the shelf
+ // and then silently paste nothing / a blurry thumbnail.
+ if (
+ (item.data.kind === 'image' && !getStore().resolveStoredImagePath(item.data.imageId, item.data.ext)) ||
+ (item.data.kind === 'image-collection' && !getStore().hasRecoverableCollectionImage(item.data.images))
+ ) {
+ console.log('[IPC] item:paste aborted — source image no longer available')
+ toast('Original image no longer available', 'error')
+ return false
+ }
+
const watcher = getWatcher()
watcher.setPaused(true)
@@ -386,7 +423,12 @@ export function registerIpc(): void {
// 2. Write item to system clipboard
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)
+ const ok = await writeItemToClipboard(itemDataWithFullText, item.capturedAt)
+ if (!ok) {
+ // Extremely rare race: source vanished between pre-check and write.
+ toast('Original image no longer available', 'error')
+ return false
+ }
console.log('[IPC] item:paste wrote to clipboard, kind=', item.data.kind)
// 3. Touch item timestamp if enabled
@@ -435,16 +477,14 @@ export function registerIpc(): void {
try {
let wrote = false
if (dto.data.kind === 'files' && req.paths && req.paths.length > 0) {
- await writeFileListToClipboard(req.paths)
- wrote = true
+ wrote = await writeFileListToClipboard(req.paths)
} else if (dto.data.kind === 'image-collection' && req.imageId) {
const img = dto.data.images.find((i) => i.imageId === req.imageId)
if (img) {
// Single image from a collection: write full bitmap + file reference atomically.
- const src = getStore().getImagePath(img.imageId, img.ext)
- const preview = img.preview ?? ''
- await writeImageToClipboard(src && existsSync(src) ? src : null, preview)
- wrote = true
+ const src = getStore().resolveStoredImagePath(img.imageId, img.ext)
+ wrote = await writeImageToClipboard(src)
+ if (!wrote) toast('Original image no longer available', 'error')
}
}
@@ -683,19 +723,38 @@ export function registerSendListeners(): void {
const { data, capturedAt } = resolved
console.log('[IPC] start-drag: kind=', data.kind)
+ // Usage accounting parity with click-to-paste: a whole-item drag counts
+ // as a use. Bumps hitCount and moves unpinned items to the top, gated
+ // behind the same movePastedToTop setting paste uses. Sub-item drags
+ // (one file out of a bundle, one image out of a collection) deliberately
+ // do not reorder history - same rule as item:paste-subitem.
+ const isWholeItemDrag = !(req.paths && req.paths.length > 0) && !req.imageId
+
// Pause the always-on-top heartbeat for the duration of the drag.
// The heartbeat fires SetWindowPos(HWND_TOPMOST) every 500 ms, which
// pushes our window in front of the DWM drag-ghost image — making the
// dragged item appear to vanish ~0.5 s into any drag gesture.
setHeartbeatPaused(true)
- startDragOut(sender, data, capturedAt)
+ const dragStarted = startDragOut(sender, data, capturedAt)
console.log('[IPC] start-drag returned, sending drag-end')
sender.send('item:drag-end')
// Re-enable the heartbeat now that the drag is over.
setHeartbeatPaused(false)
+ if (dragStarted && isWholeItemDrag) {
+ // Usage accounting parity with click-to-paste: a whole-item drag counts
+ // as a use — hitCount bump + optional move to top via the same
+ // movePastedToTop setting paste uses. Sub-item drags never reorder
+ // history (same rule as item:paste-subitem). Applied after the gesture
+ // finishes so nothing extra runs inside the OLE drag loop.
+ if (loadSettings().movePastedToTop !== false && getStore().get(req.id)) {
+ getStore().touch(req.id)
+ }
+ pushState.items()
+ }
+
// Workaround for Electron/Windows not firing drop events on the source window:
// Check if the user dropped the item back onto our window!
const { screen, BrowserWindow } = require('electron')
@@ -717,93 +776,101 @@ export function registerSendListeners(): void {
})
}
-/** Write any item payload back onto the system clipboard. */
-export async function writeItemToClipboard(data: ItemData): Promise<void> {
+/**
+ * Write any item payload back onto the system clipboard.
+ *
+ * CONTRACT: every kind resolves its concrete files through the SAME staging
+ * engine the native drag-out uses (`stageDragFile`), so paste and drag can
+ * never disagree about filenames or content. Returns false when nothing was
+ * written (e.g. every source image vanished from disk) so callers can show an
+ * explicit error instead of silently degrading quality.
+ */
+export async function writeItemToClipboard(data: ItemData, capturedAt?: number): Promise<boolean> {
switch (data.kind) {
case 'text': {
const formatted = formatTabularDataForClipboard(data.text, data.html)
clipboard.clear()
clipboard.write({ text: formatted.text, html: formatted.html })
- break
+ return true
}
case 'image': {
- const dto = getStore().toDto().find(
- (d) => d.data.kind === 'image' && d.data.imageId === data.imageId
- )
- if (dto && dto.data.kind === 'image') {
- const src = getStore().getImagePath(dto.data.imageId, dto.data.ext)
- const staged = src && existsSync(src) ? stageDragFile(data, dto.capturedAt) : null
- if (staged?.file && src && existsSync(src)) {
- const named = toUnpackagedFilePath(staged.file)
- const ok = await writeImageWithNamedFile(toUnpackagedFilePath(src), named)
- if (ok) break
- }
- await writeImageToClipboard(src && existsSync(src) ? src : null, dto.data.preview)
+ // Fix: recover via directory scan before giving up; abort explicitly
+ // when the original is unrecoverable instead of pasting a blurry
+ // low-res preview.
+ const src = getStore().resolveStoredImagePath(data.imageId, data.ext)
+ if (!src) return false
+
+ const staged = stageDragFile(data, capturedAt)
+ if (staged?.file && existsSync(staged.file)) {
+ // Full-res bitmap + friendly-named file reference in one atomic
+ // multi-format write, so Explorer keeps "Screenshot …" naming while
+ // pixel-oriented apps get CF_DIB.
+ const named = toUnpackagedFilePath(staged.file)
+ if (await writeImageWithNamedFile(toUnpackagedFilePath(src), named)) return true
}
- break
+ // Fallback: full-resolution bitmap only (no filename reference).
+ return writeImageToClipboard(src)
}
case 'image-collection': {
- // Write all image file references so pasting into Explorer copies all files.
- // Also write the first image as bitmap so single-image paste targets work.
- const dto = getStore().toDto().find(
- (d) => d.data.kind === 'image-collection'
- )
- if (dto && dto.data.kind === 'image-collection') {
- const paths: string[] = []
- for (const img of dto.data.images) {
- const src = getStore().getImagePath(img.imageId, img.ext)
- if (existsSync(src)) paths.push(toUnpackagedFilePath(src))
- }
- if (paths.length > 0) {
- // For multi-image collections, write all file refs atomically.
- // Also include the first image as bitmap using DataObject.
- const firstImg = dto.data.images[0]
- const firstPreview = firstImg?.preview ?? ''
- if (paths.length === 1) {
- // Single resolved path: use full atomic image+file write
- await writeImageToClipboard(paths[0], firstPreview)
- } else {
- // Multiple files: write CF_HDROP for all + bitmap for first
- try {
- const addLines = paths
- .map(p => `$c.Add([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(p, 'utf8').toString('base64')}')))|Out-Null`)
- .join(';')
- const b64First = Buffer.from(paths[0], 'utf8').toString('base64')
- const script = [
- 'Add-Type -AssemblyName System.Windows.Forms',
- 'Add-Type -AssemblyName System.Drawing',
- `$fp=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64First}'))`,
- '$bmp=[Drawing.Image]::FromFile($fp)',
- '$d=New-Object Windows.Forms.DataObject',
- '$d.SetImage($bmp)',
- '$c=New-Object System.Collections.Specialized.StringCollection',
- addLines,
- '$d.SetFileDropList($c)',
- '[Windows.Forms.Clipboard]::SetDataObject($d,$true)',
- '$bmp.Dispose()'
- ].join(';')
- await psHost.run(script, 3000)
- } catch (err) {
- console.error('[ipc] image-collection clipboard write failed:', err)
- // Fallback: write first image bitmap only
- try {
- const img = nativeImage.createFromDataURL(firstPreview)
- if (!img.isEmpty()) { clipboard.clear(); clipboard.writeImage(img) }
- } catch { /* ignore */ }
- }
- }
- }
+ // Fix: stage through the shared engine so every file gets the same
+ // indexed pretty names drag-out produces ("Screenshot … (2).png")
+ // instead of raw storage ids ("<hex>.png").
+ const staged = stageDragFile(data, capturedAt)
+ const stagedFiles = staged?.files ?? []
+ if (stagedFiles.length === 0) return false
+
+ const firstImg = data.images[0]
+ const firstSrc = firstImg
+ ? getStore().resolveStoredImagePath(firstImg.imageId, firstImg.ext)
+ : null
+
+ if (stagedFiles.length === 1 && firstSrc) {
+ const named = toUnpackagedFilePath(stagedFiles[0])
+ if (await writeImageWithNamedFile(toUnpackagedFilePath(firstSrc), named)) return true
+ return writeImageToClipboard(firstSrc)
+ }
+
+ if (!firstSrc) {
+ // No bitmap recoverable — the surviving named file references are
+ // still perfectly valid for Explorer-style targets.
+ return writeFileListToClipboard(stagedFiles)
+ }
+
+ // Multi-file: all pretty-named refs + first image as bitmap.
+ try {
+ const exposed = stagedFiles.map((p) => toUnpackagedFilePath(p))
+ const addLines = exposed
+ .map(p => `$c.Add([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(p, 'utf8').toString('base64')}')))|Out-Null`)
+ .join(';')
+ const b64First = Buffer.from(toUnpackagedFilePath(firstSrc), 'utf8').toString('base64')
+ const script = [
+ 'Add-Type -AssemblyName System.Windows.Forms',
+ 'Add-Type -AssemblyName System.Drawing',
+ `$fp=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64First}'))`,
+ '$bmp=[Drawing.Image]::FromFile($fp)',
+ '$d=New-Object Windows.Forms.DataObject',
+ '$d.SetImage($bmp)',
+ '$c=New-Object System.Collections.Specialized.StringCollection',
+ addLines,
+ '$d.SetFileDropList($c)',
+ '[Windows.Forms.Clipboard]::SetDataObject($d,$true)',
+ '$bmp.Dispose()'
+ ].join(';')
+ await psHost.run(script, 3000)
+ } catch (err) {
+ console.error('[ipc] image-collection clipboard write failed:', err)
+ // Full-resolution fallback for the first image (never a low-res preview).
+ return writeImageToClipboard(firstSrc)
}
- break
+ return true
}
case 'files':
// Write real file references so pasting into Explorer copies the files,
// not path strings.
- await writeFileListToClipboard(data.paths)
- break
+ return writeFileListToClipboard(data.paths)
}
}
diff --git a/electron/main/stagedTemp.ts b/electron/main/stagedTemp.ts
new file mode 100644
index 0000000..60cae3f
--- /dev/null
+++ b/electron/main/stagedTemp.ts
@@ -0,0 +1,209 @@
+/**
+ * Staged-temp artifact lifecycle manager.
+ *
+ * WHY THIS EXISTS
+ * ---------------
+ * Drag-out and image paste stage copies of clipboard content into the temp
+ * dirs (pretty-named screenshots, snippet .txt files, Store-interop copies).
+ * Historically `cleanTemp()` wiped ALL of those on every app start, which:
+ * 1. Broke external references to recently staged files (e.g. a Word doc
+ * holding the file reference written by paste).
+ * 2. Let files accumulate for items that were deleted from history while
+ * the app kept running.
+ *
+ * This module ties every staged file's lifetime to its owner's lifetime:
+ * - `recordStagedFiles()` — staging registers what it created.
+ * - `forgetStagedItems()` — ItemStore removal hooks evict the artifacts
+ * of dead items immediately.
+ * - `reconcileTempOnStartup()`— one cheap launch-time sweep removes crash
+ * orphans and anything no living item owns,
+ * replacing the old wipe-everything pass.
+ *
+ * RESOURCE CONTRACT: everything here is event-driven. The only recurring cost
+ * is a debounced (150 ms) tiny JSON write after user-triggered staging, plus
+ * one directory scan at startup. No timers, no watchers, no polling.
+ */
+import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { PATHS, getUnpackagedTempDir, isStagedTempPath } from '../store/paths'
+import { contentSignature } from '../store/signature'
+import type { ItemData } from '../../shared/types'
+
+interface RegistryEntry {
+ /** Content signature of the owning history item. */
+ sig: string
+ /** Absolute paths of generated artifacts we may delete. */
+ files: string[]
+}
+
+const REGISTRY_VERSION = 1
+/** Hard cap so a pathological session cannot grow the file unboundedly. */
+const MAX_REGISTRY_ENTRIES = 512
+
+let entries: RegistryEntry[] = []
+let loaded = false
+let persistTimer: ReturnType<typeof setTimeout> | null = null
+
+/**
+ * Lazy, failure-tolerant load. A missing/corrupt registry yields an empty
+ * list; reconcileTempOnStartup then treats every temp artifact as unowned and
+ * clears it once (identical to the legacy cleanTemp behaviour), after which
+ * the registry rebuilds from fresh staging. Self-healing by construction.
+ */
+function ensureLoaded(): void {
+ if (loaded) return
+ loaded = true
+ try {
+ const raw = readFileSync(PATHS.stagedTempRegistryFile(), 'utf8')
+ const parsed = JSON.parse(raw) as { v?: number; entries?: unknown }
+ if (parsed && Array.isArray(parsed.entries)) {
+ entries = parsed.entries.filter(
+ (e): e is RegistryEntry =>
+ !!e &&
+ typeof (e as RegistryEntry).sig === 'string' &&
+ Array.isArray((e as RegistryEntry).files) &&
+ (e as RegistryEntry).files.every((f) => typeof f === 'string')
+ )
+ }
+ } catch {
+ entries = []
+ }
+}
+
+function persistSync(): void {
+ if (persistTimer !== null) {
+ clearTimeout(persistTimer)
+ persistTimer = null
+ }
+ try {
+ writeFileSync(
+ PATHS.stagedTempRegistryFile(),
+ JSON.stringify({ v: REGISTRY_VERSION, entries }, null, 2),
+ 'utf8'
+ )
+ } catch {
+ /* non-fatal: worst case the next startup sweep reaps orphans */
+ }
+}
+
+function schedulePersist(): void {
+ if (persistTimer !== null) clearTimeout(persistTimer)
+ persistTimer = setTimeout(() => {
+ persistTimer = null
+ persistSync()
+ }, 150)
+ // Never keep the process alive just for a registry flush.
+ ;(persistTimer as unknown as { unref?: () => void }).unref?.()
+}
+
+/**
+ * Register the artifacts produced by a successful `stageDragFile` call.
+ * Only paths inside our managed temp roots are recorded — original user
+ * files exposed by `files` bundles are NEVER tracked (deleting those would
+ * destroy real user data).
+ */
+export function recordStagedFiles(data: ItemData, stagedFiles: string[]): void {
+ try {
+ const ours = stagedFiles.filter((p) => p && isStagedTempPath(p))
+ if (ours.length === 0) return
+ ensureLoaded()
+ const sig = contentSignature(data)
+ const existing = entries.find((e) => e.sig === sig)
+ if (existing) {
+ const merged = new Set(existing.files)
+ for (const f of ours) merged.add(f)
+ existing.files = [...merged]
+ } else {
+ entries.push({ sig, files: ours })
+ if (entries.length > MAX_REGISTRY_ENTRIES) {
+ // Drop the oldest entry. Its artifacts become sweep-managed: they are
+ // removed at the next startup reconciliation unless restaged first.
+ entries.shift()
+ }
+ }
+ schedulePersist()
+ } catch {
+ /* ignore — staging itself already succeeded */
+ }
+}
+
+/**
+ * Delete every registered artifact owned by the given (just-removed) history
+ * items. Called from the ItemStore removal hook, which fires only after the
+ * IPC layer has already resolved system-clipboard ownership (either the live
+ * clipboard was cleared because it held this exact content, or it holds
+ * something else entirely), so removing the shadow is always safe here.
+ */
+export function forgetStagedItems(removed: readonly { data: ItemData }[]): void {
+ if (!removed || removed.length === 0) return
+ try {
+ ensureLoaded()
+ let changed = false
+ for (const item of removed) {
+ const sig = contentSignature(item.data)
+ const idx = entries.findIndex((e) => e.sig === sig)
+ if (idx === -1) continue
+ const [dead] = entries.splice(idx, 1)
+ changed = true
+ for (const f of dead.files) {
+ try {
+ if (existsSync(f)) rmSync(f, { force: true })
+ } catch {
+ /* individual file errors must not block siblings */
+ }
+ }
+ }
+ if (changed) schedulePersist()
+ } catch {
+ /* ignore */
+ }
+}
+
+/**
+ * Startup reconciliation. Keeps every artifact whose owning signature is
+ * still alive in history; deletes all other managed-temp contents (crash
+ * orphans, leftovers of deleted items, legacy pre-registry junk). Runs once
+ * per launch — a few milliseconds even with hundreds of files.
+ */
+export function reconcileTempOnStartup(liveItems: readonly { data: ItemData }[]): void {
+ ensureLoaded()
+ const liveSigs = new Set(liveItems.map((it) => contentSignature(it.data)))
+
+ const protectedFiles = new Set<string>()
+ const survivingEntries: RegistryEntry[] = []
+ for (const entry of entries) {
+ if (liveSigs.has(entry.sig)) {
+ survivingEntries.push(entry)
+ for (const f of entry.files) protectedFiles.add(f)
+ }
+ }
+ entries = survivingEntries
+
+ const roots = new Set([PATHS.tempDir(), getUnpackagedTempDir()])
+ for (const rootDir of roots) {
+ if (!rootDir) continue
+ let names: string[] = []
+ try {
+ names = readdirSync(rootDir)
+ } catch {
+ continue /* dir missing is fine */
+ }
+ for (const name of names) {
+ const full = join(rootDir, name)
+ if (protectedFiles.has(full)) continue
+ try {
+ rmSync(full, { recursive: true, force: true })
+ } catch {
+ /* ignore individual failures */
+ }
+ }
+ }
+
+ persistSync()
+}
+
+/** Flush pending debounce writes synchronously (app shutdown). */
+export function flushStagedTempRegistry(): void {
+ ensureLoaded()
+ persistSync()
+}
diff --git a/electron/main/state.ts b/electron/main/state.ts
index 74993d5..e67ea58 100644
--- a/electron/main/state.ts
+++ b/electron/main/state.ts
@@ -13,10 +13,11 @@ import { MAX_STACK } from '../../shared/types'
import { BrowserWindow, powerMonitor } from 'electron'
import { isStagedTempPath } from '../store/paths'
import { prefetchFileIcons } from './drag'
+import { forgetStagedItems, reconcileTempOnStartup } from './stagedTemp'
import { runtime } from './config'
import { getMainWindow } from './window'
-const store = new ItemStore()
+const store = new ItemStore((removed) => forgetStagedItems(removed))
const watcher = new ClipboardWatcher(600)
let pruneTimer: ReturnType<typeof setInterval> | null = null
let wakeTimer: ReturnType<typeof setTimeout> | null = null
@@ -41,6 +42,16 @@ function handleSystemWake(): void {
export function initState(): void {
store.load()
+ // Reconcile staged temp artifacts with the freshly loaded history: files
+ // owned by living items survive, everything else (crash orphans, deleted
+ // items' leftovers, legacy pre-registry junk) is removed once. This replaces
+ // the old wipe-everything cleanTemp() pass. Runs once — milliseconds.
+ try {
+ reconcileTempOnStartup(store.list())
+ } catch (err) {
+ console.error('[State] Staged temp reconciliation failed:', err)
+ }
+
// One-time v0.2.6 upgrade migration: clear unpinned items once & set default historyLimit to 250
const currentSettings = loadSettings()
if (!currentSettings.v026UpgradeCleaned) {
diff --git a/electron/store/ItemStore.ts b/electron/store/ItemStore.ts
index ef04e0a..847f0a6 100644
--- a/electron/store/ItemStore.ts
+++ b/electron/store/ItemStore.ts
@@ -24,32 +24,38 @@ import {
} from '../../shared/types'
import { PATHS } from './paths'
import { createId } from './ids'
-
-/** Stable, content-based key used for deduplication. */
-function signature(data: ItemData): string {
- switch (data.kind) {
- case 'text':
- return `text|${data.text}`
- case 'image':
- return data.bytes && data.bytes > 0 ? `image|${data.width}x${data.height}|${data.bytes}` : `image|${data.imageId}`
- case 'image-collection':
- return `image-collection|${data.images.map((i) => `${i.width}x${i.height}|${i.bytes || i.imageId}`).join(',')}`
- case 'files':
- return `files|${data.paths.join('\n')}`
- }
-}
+import { contentSignature } from './signature'
/** Maps a signature -> item id so dedup is O(1). */
interface Index {
items: ClipboardItem[]
}
+/**
+ * Invoked with every batch of items permanently removed from history, no
+ * matter which door removed them (manual delete, batch delete, clear,
+ * auto-delete prune, or silent capacity eviction). The staged-temp lifecycle
+ * manager uses it to reap orphaned artifacts.
+ */
+export type ItemsRemovedListener = (removed: readonly ClipboardItem[]) => void
+
export class ItemStore {
private items: ClipboardItem[] = []
private sigToId = new Map<string, string>()
/** Small, bounded thumbnails for renderer DTOs. Original image bytes stay on disk. */
private previewCache = new Map<string, string>()
+ constructor(private readonly onRemoved?: ItemsRemovedListener) {}
+
+ private notifyRemoved(removed: ClipboardItem[]): void {
+ if (removed.length === 0) return
+ try {
+ this.onRemoved?.(removed)
+ } catch (err) {
+ console.error('[ItemStore] onRemoved listener failed:', err)
+ }
+ }
+
/** Load persisted state from disk. Called once at startup. */
load(): void {
try {
@@ -136,7 +142,7 @@ export class ItemStore {
private rebuildIndex(): void {
this.sigToId.clear()
- for (const it of this.items) this.sigToId.set(signature(it.data), it.id)
+ for (const it of this.items) this.sigToId.set(contentSignature(it.data), it.id)
}
private persistTimer: ReturnType<typeof setTimeout> | null = null
@@ -187,22 +193,25 @@ export class ItemStore {
if (this.items.length <= limit) return
const need = this.items.length - limit
const survivors: ClipboardItem[] = []
+ const evicted: ClipboardItem[] = []
let stillNeed = need
for (let i = this.items.length - 1; i >= 0; i--) {
const it = this.items[i]
if (stillNeed > 0 && !it.pinned) {
- this.sigToId.delete(signature(it.data))
+ this.sigToId.delete(contentSignature(it.data))
if (it.data.kind === 'image') this.removeImageFile(it.data.imageId)
if (it.data.kind === 'image-collection') {
it.data.images.forEach((img) => this.removeImageFile(img.imageId))
}
if (it.data.kind === 'text') this.removeTextPayload(it.id)
+ evicted.push(it)
stillNeed--
} else {
survivors.unshift(it)
}
}
this.items = survivors
+ this.notifyRemoved(evicted)
}
/**
@@ -213,7 +222,7 @@ export class ItemStore {
if (data.kind === 'text' && data.text.length > 500000) {
data = { ...data, text: data.text.slice(0, 500000) }
}
- const sig = signature(data)
+ const sig = contentSignature(data)
const existingId = this.sigToId.get(sig)
const now = Date.now()
@@ -284,13 +293,14 @@ export class ItemStore {
const idx = this.items.findIndex((x) => x.id === id)
if (idx < 0) return
const [removed] = this.items.splice(idx, 1)
- this.sigToId.delete(signature(removed.data))
+ this.sigToId.delete(contentSignature(removed.data))
if (removed.data.kind === 'image') this.removeImageFile(removed.data.imageId)
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()
+ this.notifyRemoved([removed])
}
deleteBatch(ids: string[]): void {
@@ -306,7 +316,7 @@ export class ItemStore {
})
for (const removed of toRemove) {
- this.sigToId.delete(signature(removed.data))
+ this.sigToId.delete(contentSignature(removed.data))
if (removed.data.kind === 'image') this.removeImageFile(removed.data.imageId)
if (removed.data.kind === 'image-collection') {
removed.data.images.forEach((img) => this.removeImageFile(img.imageId))
@@ -314,6 +324,7 @@ export class ItemStore {
if (removed.data.kind === 'text') this.removeTextPayload(removed.id)
}
this.persistSync()
+ this.notifyRemoved(toRemove)
}
merge(sourceId: string, targetId: string): MergeResult {
@@ -387,15 +398,15 @@ export class ItemStore {
}
// Update target item
- this.sigToId.delete(signature(tgt.data))
+ this.sigToId.delete(contentSignature(tgt.data))
tgt.data = newData
- this.sigToId.set(signature(newData), tgt.id)
+ this.sigToId.set(contentSignature(newData), tgt.id)
tgt.capturedAt = Date.now() // bump time
// Remove source item completely but DO NOT delete its underlying files/images
// because they are now owned by the target!
const [removed] = this.items.splice(srcIdx, 1)
- this.sigToId.delete(signature(removed.data))
+ this.sigToId.delete(contentSignature(removed.data))
this.persist()
return { ok: true }
@@ -524,43 +535,47 @@ export class ItemStore {
clearUnpinned(): void {
const kept: ClipboardItem[] = []
+ const removed: ClipboardItem[] = []
for (const it of this.items) {
if (it.pinned) kept.push(it)
else {
- this.sigToId.delete(signature(it.data))
+ this.sigToId.delete(contentSignature(it.data))
if (it.data.kind === 'image') this.removeImageFile(it.data.imageId)
if (it.data.kind === 'image-collection') {
it.data.images.forEach((img) => this.removeImageFile(img.imageId))
}
if (it.data.kind === 'text') this.removeTextPayload(it.id)
+ removed.push(it)
}
}
this.items = kept
this.persistSync()
+ this.notifyRemoved(removed)
}
pruneExpired(hours: number): boolean {
if (!hours || hours <= 0) return false
const cutoff = Date.now() - hours * 3600 * 1000
const kept: ClipboardItem[] = []
- let removedAny = false
+ const expired: ClipboardItem[] = []
for (const it of this.items) {
if (it.pinned || it.capturedAt >= cutoff) {
kept.push(it)
} else {
- removedAny = true
- this.sigToId.delete(signature(it.data))
+ expired.push(it)
+ this.sigToId.delete(contentSignature(it.data))
if (it.data.kind === 'image') this.removeImageFile(it.data.imageId)
if (it.data.kind === 'image-collection') {
it.data.images.forEach((img) => this.removeImageFile(img.imageId))
}
}
}
- if (removedAny) {
+ if (expired.length > 0) {
this.items = kept
this.persistSync()
+ this.notifyRemoved(expired)
}
- return removedAny
+ return expired.length > 0
}
get(id: string): ClipboardItem | undefined {
@@ -640,6 +655,37 @@ export class ItemStore {
return join(PATHS.imagesDir(), `${imageId}.png`)
}
+ /**
+ * Resolve the on-disk path for a stored image, recovering via a directory
+ * scan when the exact extension path is missing (e.g. the capture was
+ * re-staged with a different ext). Returns null only when the image is
+ * genuinely unrecoverable — callers must surface that to the user instead
+ * of silently degrading to low-res previews.
+ */
+ public resolveStoredImagePath(imageId: string, ext?: string): string | null {
+ if (!imageId) return null
+ if (ext) {
+ const cleanExt = ext.startsWith('.') ? ext.slice(1) : ext
+ const primary = join(PATHS.imagesDir(), `${imageId}.${cleanExt}`)
+ if (existsSync(primary)) return primary
+ }
+ // Recovery: scan the images dir for any extension matching this id.
+ try {
+ const scanned = this.imagePath(imageId, undefined)
+ if (existsSync(scanned)) return scanned
+ } catch { /* ignore */ }
+ return null
+ }
+
+ /**
+ * True when at least one image of a collection is still recoverable on
+ * disk. Used as a fast pre-check so paste can abort with an explicit error
+ * before mutating any UI state.
+ */
+ public hasRecoverableCollectionImage(images: Array<{ imageId: string; ext?: string }>): boolean {
+ return images.some((img) => this.resolveStoredImagePath(img.imageId, img.ext) !== null)
+ }
+
private removeImageFile(imageId: string): void {
for (const key of this.previewCache.keys()) {
if (key.startsWith(imageId)) this.previewCache.delete(key)
diff --git a/electron/store/paths.ts b/electron/store/paths.ts
index 826178d..d09c90b 100644
--- a/electron/store/paths.ts
+++ b/electron/store/paths.ts
@@ -25,6 +25,12 @@ export const PATHS = {
indexFile: () => join(root(), 'items.json'),
/** Path to the settings JSON. */
settingsFile: () => join(root(), 'settings.json'),
+ /**
+ * Registry correlating staged temp artifacts with the history entries that
+ * own them. Lives OUTSIDE the temp dirs so cleanup sweeps never mistake it
+ * for debris.
+ */
+ stagedTempRegistryFile: () => join(root(), 'temp-staged.json'),
/** Scratch dir for temp files handed to native drag-out. */
tempDir: () => join(root(), 'temp'),
/** App icon (used by window + native drag image). */
diff --git a/electron/store/signature.ts b/electron/store/signature.ts
new file mode 100644
index 0000000..395e3bc
--- /dev/null
+++ b/electron/store/signature.ts
@@ -0,0 +1,22 @@
+/**
+ * Stable, content-based key used for item deduplication and for correlating
+ * staged temp artifacts with the history entries that own them.
+ *
+ * Single source of truth: the ItemStore dedup index and the staged-temp
+ * registry MUST agree on identity, otherwise lifecycle cleanup would either
+ * delete files that are still owned (data loss) or leak them forever.
+ */
+import type { ItemData } from '../../shared/types'
+
+export function contentSignature(data: ItemData): string {
+ switch (data.kind) {
+ case 'text':
+ return `text|${data.text}`
+ case 'image':
+ return data.bytes && data.bytes > 0 ? `image|${data.width}x${data.height}|${data.bytes}` : `image|${data.imageId}`
+ case 'image-collection':
+ return `image-collection|${data.images.map((i) => `${i.width}x${i.height}|${i.bytes || i.imageId}`).join(',')}`
+ case 'files':
+ return `files|${data.paths.join('\n')}`
+ }
+}
diff --git a/src/store/appStore.ts b/src/store/appStore.ts
index d7bbcae..cdb3f25 100644
--- a/src/store/appStore.ts
+++ b/src/store/appStore.ts
@@ -255,7 +255,17 @@ export const useStore = create<AppState>((set, get) => ({
if (get().hydrated && newTop) {
const isDifferentId = !prevTop || newTop.id !== prevTop.id
const isNewCapturedAt = prevTop && newTop.capturedAt !== prevTop.capturedAt
- if ((isDifferentId || isNewCapturedAt) && !get().isInternalCopying) {
+ // Suppress the flare while the mutation originated from this renderer
+ // session itself:
+ // - isInternalCopying: click copy/paste flows (main rewrites the OS
+ // clipboard, which is NOT a fresh capture).
+ // - internalDragReq: a native drag-out that just ended. Main bumps the
+ // item's usage (hitCount/capturedAt, move-to-top) and pushes the list
+ // immediately after 'item:drag-end', which is still inside this
+ // window — Panel.tsx only clears internalDragReq 150ms later. Without
+ // this guard the usage bump would masquerade as a fresh capture and
+ // flash the edge copy indicator on every drag-out.
+ if ((isDifferentId || isNewCapturedAt) && !get().isInternalCopying && !get().internalDragReq) {
get().triggerCopyFlare()
}
}
diff --git a/tests/imageClipboard.test.ts b/tests/imageClipboard.test.ts
index 0a9849e..6e97990 100644
--- a/tests/imageClipboard.test.ts
+++ b/tests/imageClipboard.test.ts
@@ -114,14 +114,21 @@ describe('writeImageToClipboard (#44)', () => {
expect(clipboard.writeImage).toHaveBeenCalledTimes(1)
})
- it('uses previewDataUrl fallback if image file is missing on disk', async () => {
+ it('aborts with false and never degrades to a low-res preview when the image file is missing', async () => {
const missingPath = 'C:\\mock\\images\\missing.png'
- const fallbackDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg=='
- await writeImageToClipboard(missingPath, fallbackDataUrl)
+ const result = await writeImageToClipboard(missingPath)
- expect(nativeImage.createFromDataURL).toHaveBeenCalledWith(fallbackDataUrl)
- expect(clipboard.clear).toHaveBeenCalledTimes(1)
- expect(clipboard.writeImage).toHaveBeenCalledTimes(1)
+ // Fix contract: silent quality degradation is worse than explicit failure.
+ expect(result).toBe(false)
+ expect(nativeImage.createFromDataURL).not.toHaveBeenCalled()
+ expect(clipboard.clear).not.toHaveBeenCalled()
+ expect(clipboard.writeImage).not.toHaveBeenCalled()
+ })
+
+ it('reports success explicitly when the full-resolution bitmap was written', async () => {
+ const validPath = 'C:\\mock\\images\\valid.png'
+ const result = await writeImageToClipboard(validPath)
+ expect(result).toBe(true)
})
it('does not throw or corrupt clipboard when image is null/empty', async () => {
diff --git a/tests/itemStoreRemovalHooks.test.ts b/tests/itemStoreRemovalHooks.test.ts
new file mode 100644
index 0000000..543088d
--- /dev/null
+++ b/tests/itemStoreRemovalHooks.test.ts
@@ -0,0 +1,191 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+
+const fsRoots = vi.hoisted(() => ({
+ home: '',
+ userData: ''
+}))
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: false,
+ getAppPath: () => join(fsRoots.userData, 'app'),
+ getPath: (name: string) => (name === 'userData' ? fsRoots.userData : join(fsRoots.userData, name))
+ },
+ nativeImage: {
+ createFromPath: () => ({ isEmpty: () => true })
+ },
+ safeStorage: {
+ isEncryptionAvailable: () => false
+ }
+}))
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:os')>()
+ return {
+ ...actual,
+ homedir: () => fsRoots.home
+ }
+})
+
+import { ItemStore } from '../electron/store/ItemStore'
+import type { ClipboardItem, ItemData } from '../shared/types'
+
+function textData(t: string): ItemData {
+ return { kind: 'text', text: t, isUrl: false }
+}
+
+describe('ItemStore removal hooks (staged-temp lifecycle wiring)', () => {
+ beforeEach(() => {
+ fsRoots.userData = join(tmpdir(), `ed-store-ud-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ fsRoots.home = join(tmpdir(), `ed-store-home-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ mkdirSync(fsRoots.userData, { recursive: true })
+ mkdirSync(fsRoots.home, { recursive: true })
+ })
+
+ afterEach(() => {
+ try { rmSync(fsRoots.userData, { recursive: true, force: true }) } catch { /* ignore */ }
+ try { rmSync(fsRoots.home, { recursive: true, force: true }) } catch { /* ignore */ }
+ })
+
+ function makeStore(): { store: ItemStore; removed: ClipboardItem[][] } {
+ const removed: ClipboardItem[][] = []
+ const store = new ItemStore((batch) => removed.push([...batch]))
+ return { store, removed }
+ }
+
+ it('notifies with the removed item on delete()', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('alpha'), 10)
+ const id = store.list()[0].id
+
+ store.delete(id)
+
+ expect(removed).toHaveLength(1)
+ expect(removed[0]).toHaveLength(1)
+ expect(removed[0][0].id).toBe(id)
+ })
+
+ it('notifies once per batch on deleteBatch()', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('one'), 10)
+ store.add(textData('two'), 10)
+ const ids = store.list().map((i) => i.id)
+
+ store.deleteBatch(ids)
+
+ expect(removed).toHaveLength(1)
+ expect(removed[0].map((r) => r.id).sort()).toEqual([...ids].sort())
+ })
+
+ it('clearUnpinned() notifies with every unpinned item and spares pinned ones', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('pinned-keeper'), 10)
+ store.setPinned(store.list()[0].id, true)
+ store.add(textData('recent-a'), 10)
+ store.add(textData('recent-b'), 10)
+
+ store.clearUnpinned()
+
+ const flat = removed.flat()
+ expect(flat).toHaveLength(2)
+ expect(flat.every((r) => r.data.kind === 'text' && r.data.text !== 'pinned-keeper')).toBe(true)
+ expect(store.list()).toHaveLength(1)
+ })
+
+ it('pruneExpired() notifies only with expired items', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('old-item'), 10)
+ const oldId = store.list()[0].id
+ // Backdate past the cutoff.
+ ;(store.list()[0] as { capturedAt: number }).capturedAt = Date.now() - 2 * 3600 * 1000
+ store.add(textData('fresh-item'), 10)
+
+ const changed = store.pruneExpired(1)
+
+ expect(changed).toBe(true)
+ expect(removed).toHaveLength(1)
+ expect(removed[0]).toHaveLength(1)
+ expect(removed[0][0].id).toBe(oldId)
+ expect(store.list()).toHaveLength(1)
+ })
+
+ it('silent capacity eviction (trim) notifies with the evicted oldest unpinned item', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('first'), 2)
+ const firstId = store.list()[store.list().length - 1].id
+ store.add(textData('second'), 2)
+ store.add(textData('third'), 2)
+
+ expect(store.list()).toHaveLength(2)
+ expect(removed).toHaveLength(1)
+ expect(removed[0]).toHaveLength(1)
+ expect(removed[0][0].id).toBe(firstId)
+ })
+
+ it('merge() transfers ownership without firing removal hooks', () => {
+ const { store, removed } = makeStore()
+ store.add(textData('src'), 10)
+ store.add(textData('tgt'), 10)
+ const ids = store.list().map((i) => i.id)
+
+ const result = store.merge(ids[1], ids[0])
+
+ expect(result.ok).toBe(false) // text items cannot merge — no ownership change
+ expect(removed).toHaveLength(0)
+ })
+})
+
+describe('ItemStore image recovery (no silent low-res fallback)', () => {
+ beforeEach(() => {
+ fsRoots.userData = join(tmpdir(), `ed-recov-ud-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ fsRoots.home = join(tmpdir(), `ed-recov-home-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ mkdirSync(join(fsRoots.userData, 'images'), { recursive: true })
+ mkdirSync(fsRoots.home, { recursive: true })
+ })
+
+ afterEach(() => {
+ try { rmSync(fsRoots.userData, { recursive: true, force: true }) } catch { /* ignore */ }
+ try { rmSync(fsRoots.home, { recursive: true, force: true }) } catch { /* ignore */ }
+ })
+
+ function newStore(): ItemStore {
+ return new ItemStore()
+ }
+
+ it('resolves the exact extension path when present', () => {
+ const p = join(fsRoots.userData, 'images', 'img1.png')
+ writeFileSync(p, 'png')
+ expect(newStore().resolveStoredImagePath('img1', 'png')).toBe(p)
+ })
+
+ it('recovers via directory scan when the recorded extension no longer matches', () => {
+ const jpgPath = join(fsRoots.userData, 'images', 'img2.jpg')
+ writeFileSync(jpgPath, 'jpeg-bytes')
+ expect(newStore().resolveStoredImagePath('img2', 'png')).toBe(jpgPath)
+ })
+
+ it('returns null when the image is genuinely unrecoverable', () => {
+ expect(newStore().resolveStoredImagePath('missing', 'png')).toBe(null)
+ expect(newStore().resolveStoredImagePath('', 'png')).toBe(null)
+ })
+
+ it('hasRecoverableCollectionImage() requires at least one surviving image', () => {
+ const store = newStore()
+ writeFileSync(join(fsRoots.userData, 'images', 'alive.png'), 'a')
+
+ expect(store.hasRecoverableCollectionImage([{ imageId: 'alive', ext: 'png' }, { imageId: 'dead', ext: 'png' }])).toBe(true)
+ expect(store.hasRecoverableCollectionImage([{ imageId: 'dead', ext: 'png' }])).toBe(false)
+ })
+
+ it('reports missing files as unrecoverable after they are deleted from disk', () => {
+ const store = newStore()
+ const p = join(fsRoots.userData, 'images', 'vanishing.png')
+ writeFileSync(p, 'b')
+ expect(store.resolveStoredImagePath('vanishing', 'png')).toBe(p)
+ existsSync(p) && rmSync(p)
+ expect(store.resolveStoredImagePath('vanishing', 'png')).toBe(null)
+ })
+})
diff --git a/tests/stagedTempLifecycle.test.ts b/tests/stagedTempLifecycle.test.ts
new file mode 100644
index 0000000..2f7f1d5
--- /dev/null
+++ b/tests/stagedTempLifecycle.test.ts
@@ -0,0 +1,154 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+
+const fsRoots = vi.hoisted(() => ({
+ home: '',
+ userData: ''
+}))
+
+vi.mock('electron', () => ({
+ app: {
+ isPackaged: false,
+ getAppPath: () => join(fsRoots.userData, 'app'),
+ getPath: (name: string) => (name === 'userData' ? fsRoots.userData : join(fsRoots.userData, name))
+ }
+}))
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:os')>()
+ return {
+ ...actual,
+ homedir: () => fsRoots.home
+ }
+})
+
+type StagedTempModule = typeof import('../electron/main/stagedTemp')
+
+let mod: StagedTempModule
+
+/** Image capture whose bytes live in the permanent images dir. */
+function imageData(id: string) {
+ return { kind: 'image' as const, imageId: id, width: 10, height: 10, bytes: 8, ext: 'png' }
+}
+
+describe('staged temp lifecycle (registry + ownership cleanup)', () => {
+ beforeEach(async () => {
+ delete process.env.APP_BUILD_TARGET
+ fsRoots.userData = join(tmpdir(), `ed-staged-ud-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ fsRoots.home = join(tmpdir(), `ed-staged-home-${Date.now()}-${Math.random().toString(16).slice(2)}`)
+ mkdirSync(join(fsRoots.userData, 'temp'), { recursive: true })
+ mkdirSync(fsRoots.home, { recursive: true })
+ // Fresh module instance per test (registry state is module-scoped).
+ vi.resetModules()
+ mod = await import('../electron/main/stagedTemp')
+ })
+
+ afterEach(() => {
+ delete process.env.APP_BUILD_TARGET
+ try { rmSync(fsRoots.userData, { recursive: true, force: true }) } catch { /* ignore */ }
+ try { rmSync(fsRoots.home, { recursive: true, force: true }) } catch { /* ignore */ }
+ })
+
+ function stageArtifact(name: string): string {
+ const p = join(fsRoots.userData, 'temp', name)
+ writeFileSync(p, `bytes-${name}`)
+ return p
+ }
+
+ function registryOnDisk(): { v: number; entries: Array<{ sig: string; files: string[] }> } {
+ return JSON.parse(readFileSync(join(fsRoots.userData, 'temp-staged.json'), 'utf8'))
+ }
+
+ it('keeps owned artifacts through startup reconciliation and reaps unknown strays', () => {
+ const owned = stageArtifact('Screenshot 2026-08-24 10.00.00.png')
+ const stray = stageArtifact('Screenshot 2026-08-24 09.00.00.png')
+ const data = imageData('img_live')
+
+ mod.recordStagedFiles(data, [owned])
+ mod.flushStagedTempRegistry()
+
+ expect(existsSync(join(fsRoots.userData, 'temp-staged.json'))).toBe(true)
+ expect(registryOnDisk().entries).toHaveLength(1)
+
+ mod.reconcileTempOnStartup([ { id: 'a', data, capturedAt: Date.now(), hitCount: 1, pinned: false } ])
+
+ expect(existsSync(owned)).toBe(true)
+ expect(existsSync(stray)).toBe(false)
+ })
+
+ it('deletes registered artifacts immediately when their owning item is removed', () => {
+ const f1 = stageArtifact('Image 2026-08-24 11.00.00.png')
+ const f2 = stageArtifact('Snippet_abc.txt')
+ const img = imageData('img_dead')
+ const text = { kind: 'text' as const, text: 'note', isUrl: false }
+
+ mod.recordStagedFiles(img, [f1])
+ mod.recordStagedFiles(text, [f2])
+
+ mod.forgetStagedItems([
+ { id: 'x', data: img, capturedAt: 1, hitCount: 1, pinned: false },
+ { id: 'y', data: text, capturedAt: 1, hitCount: 1, pinned: false }
+ ])
+
+ expect(existsSync(f1)).toBe(false)
+ expect(existsSync(f2)).toBe(false)
+ })
+
+ it('never tracks or deletes original user files exposed by files bundles', () => {
+ const docs = join(fsRoots.home, 'Documents')
+ mkdirSync(docs, { recursive: true })
+ const userDoc = join(docs, 'report.pdf')
+ writeFileSync(userDoc, 'pdf-bytes')
+
+ const data = { kind: 'files' as const, paths: [userDoc] }
+ mod.recordStagedFiles(data, [userDoc])
+ mod.flushStagedTempRegistry()
+
+ // Outside the managed temp roots -> nothing may be registered.
+ expect(registryOnDisk().entries).toHaveLength(0)
+
+ mod.forgetStagedItems([{ id: 'z', data, capturedAt: 1, hitCount: 1, pinned: false }])
+ expect(existsSync(userDoc)).toBe(true)
+ })
+
+ it('persists the registry so a restart protects recently used artifacts', async () => {
+ const kept = stageArtifact('Screenshot 2026-08-24 12.00.00.png')
+ const data = imageData('img_persist')
+
+ mod.recordStagedFiles(data, [kept])
+ mod.flushStagedTempRegistry()
+
+ // Simulate an app restart: brand-new module instance, same userData.
+ vi.resetModules()
+ mod = await import('../electron/main/stagedTemp')
+ mod.reconcileTempOnStartup([ { id: 'p', data, capturedAt: Date.now(), hitCount: 1, pinned: false } ])
+
+ expect(existsSync(kept)).toBe(true)
+ })
+
+ it('treats a missing/corrupt registry as unowned and clears managed temp once (legacy parity)', () => {
+ const junk1 = stageArtifact('Screenshot 2026-08-01 00.00.00.png')
+ const junk2 = stageArtifact('Snippet_old.txt')
+ writeFileSync(join(fsRoots.userData, 'temp-staged.json'), '{not json!')
+
+ mod.reconcileTempOnStartup([])
+
+ expect(existsSync(junk1)).toBe(false)
+ expect(existsSync(junk2)).toBe(false)
+ })
+
+ it('removes registry entries of dead items during reconciliation', () => {
+ const dead = stageArtifact('Screenshot 2026-08-24 13.00.00.png')
+ const deadData = imageData('img_gone')
+ mod.recordStagedFiles(deadData, [dead])
+ mod.flushStagedTempRegistry()
+
+ // Reconcile where the owning item no longer exists.
+ mod.reconcileTempOnStartup([])
+
+ expect(existsSync(dead)).toBe(false)
+ expect(registryOnDisk().entries).toHaveLength(0)
+ })
+})