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): stop Explorer and spreadsheet copies from double-capturing

Deepender25902c89b9b651
diff --git a/electron/clipboard/ClipboardWatcher.ts b/electron/clipboard/ClipboardWatcher.ts
index 94ebd16..c744c42 100644
--- a/electron/clipboard/ClipboardWatcher.ts
+++ b/electron/clipboard/ClipboardWatcher.ts
@@ -1,38 +1,62 @@
/**
- * Polls the system clipboard and reports genuinely new content.
+ * Reports genuinely new clipboard content.
*
- * Electron has no native clipboard-changed event, so we sample on an interval.
- * To avoid creating duplicate items (and to avoid re-reading the expensive
- * image bytes every tick) we keep a cheap signature of the last seen state and
- * only do the full `readClipboard()` work when it changes.
+ * Windows Explorer delay-renders formats after a copy (paths, then bitmap,
+ * then extra shell data). Each render bumps the sequence number. Reading the
+ * clipboard inside WM_CLIPBOARDUPDATE forces the next render and looks like
+ * many copies of the same files. We therefore:
+ * 1. Detect change via GetClipboardSequenceNumber only (no OpenClipboard).
+ * 2. Reset a settle window on every bump and capture once it is quiet.
+ * 3. Ignore a second capture of the same content for a short coalescing
+ * window so late Explorer thumbnails do not bump hitCount.
+ * 4. Never re-read a just-captured file list during that window — another
+ * OpenClipboard restarts Explorer's delay-render and hitCount climbs.
+ * 5. If the path list is unchanged, ignore later sequence bumps entirely.
+ * Closing Explorer flushes delayed formats (WM_RENDERALLFORMATS) seconds
+ * later and would otherwise look like a second copy.
+ * A slow interval remains as a fallback if the OS message is missed.
*/
import { clipboard } from 'electron'
import { createId } from '../store/ids'
-import { readClipboard, clipboardSignature } from './formats'
+import {
+ readClipboard,
+ clipboardSignature,
+ getClipboardSequenceNumber,
+ clipboardHasFileNameW,
+ clipboardTextContent,
+ clipboardFilesContentKey
+} from './formats'
+import { contentSignature } from '../store/signature'
import type { ItemData } from '../../shared/types'
/**
- * Fired when genuinely new content lands on the clipboard. For image captures
+ * Fired when genuinely new clipboard content lands on the clipboard. For image captures
* the raw PNG bytes are handed over as the second argument so the store can
* persist them without re-reading the clipboard.
*/
export type NewItemHandler = (data: ItemData, imagePng?: Buffer) => void
-function getContentSignature(sig: string): string {
- return sig.replace(/^seq:\d+:/, '')
-}
+/** Ignore a second capture of identical content this soon (Explorer late formats). */
+const COALESCE_MS = 500
+/** Extra settles to wait when Explorer advertised files that are not readable yet. */
+const MAX_INCOMPLETE_RETRIES = 4
export class ClipboardWatcher {
private timer: NodeJS.Timeout | null = null
private settleTimer: NodeJS.Timeout | null = null
private lastSig = 'empty'
+ private lastSeq = 0
+ private lastCapturedKey = ''
+ private lastCapturedAt = 0
private paused = false
+ private reading = false
+ private incompleteTries = 0
private readonly intervalMs: number
private readonly settleMs: number
private onNew: NewItemHandler | null = null
private onHint: (() => void) | null = null
- constructor(intervalMs = 300, settleMs = 50) {
+ constructor(intervalMs = 300, settleMs = 220) {
this.intervalMs = intervalMs
this.settleMs = settleMs
}
@@ -48,57 +72,158 @@ export class ClipboardWatcher {
this.onHint = onHint ?? null
// Seed the signature so we don't re-fire for whatever is already on the
// clipboard at startup (the user didn't "just" copy it).
- this.lastSig = clipboardSignature()
+ this.lastSeq = getClipboardSequenceNumber()
+ this.lastSig = this.lastSeq > 0 ? `seq:${this.lastSeq}` : clipboardSignature()
this.timer = setInterval(() => this.pollTick(), this.intervalMs)
}
/** Run one poll immediately (WM_CLIPBOARDUPDATE). Safe if not started. */
nudge(): void {
- if (!this.onNew || this.paused) return
+ if (!this.onNew || this.paused || this.reading) return
this.pollTick()
}
- private pollTick(): void {
- if (this.paused || !this.onNew) return
- const sig = clipboardSignature()
- if (sig === this.lastSig) return
+ private inCoalesceWindow(now = Date.now()): boolean {
+ return this.lastCapturedKey !== '' && now - this.lastCapturedAt < COALESCE_MS
+ }
- this.lastSig = sig
- try {
- this.onHint?.()
- } catch (err) {
- console.error('[ClipboardWatcher] onHint failed:', err)
+ /**
+ * Explorer keeps bumping the sequence number as delayed formats appear,
+ * and again when the source window closes (WM_RENDERALLFORMATS).
+ * Reading the clipboard to inspect them retriggers that pipeline.
+ *
+ * Same file list: absorb with no time limit — closing Explorer is not a copy.
+ * Text/image: absorb only inside the short coalesce window so a real re-copy
+ * of the same text still counts.
+ */
+ private absorbLateExplorerFormats(now: number): boolean {
+ if (!this.lastCapturedKey) return false
+ if (this.lastCapturedKey.startsWith('files|')) {
+ const next = clipboardFilesContentKey()
+ if (next === null) return false
+ if (next === this.lastCapturedKey) return true
+ // FileNameW is first-file-only when CF_UNICODETEXT is missing. Explorer
+ // close still has that first path; a different drop does not.
+ const lastPaths = this.lastCapturedKey.slice('files|'.length).split('\n')
+ const nextPaths = next.slice('files|'.length).split('\n')
+ return nextPaths.length === 1 && lastPaths.includes(nextPaths[0])
+ }
+ if (!this.inCoalesceWindow(now)) return false
+ if (this.lastCapturedKey.startsWith('image|')) return !clipboardHasFileNameW()
+ if (this.lastCapturedKey.startsWith('text|')) {
+ const t = clipboardTextContent()
+ return t !== null && this.lastCapturedKey === `text|${t}`
}
+ return false
+ }
- if (this.settleTimer) clearTimeout(this.settleTimer)
+ private pollTick(): void {
+ if (this.paused || !this.onNew || this.reading) return
- const capturedSig = sig
- this.settleTimer = setTimeout(async () => {
- this.settleTimer = null
- if (this.paused || !this.onNew) return
- const stableSig = clipboardSignature()
+ const seq = getClipboardSequenceNumber()
+ if (seq > 0) {
+ if (seq === this.lastSeq) return
+ this.lastSeq = seq
+ } else {
+ const sig = clipboardSignature()
+ if (sig === this.lastSig) return
+ this.lastSig = sig
+ }
- if (getContentSignature(stableSig) !== getContentSignature(capturedSig) && stableSig !== capturedSig) {
- return
+ const now = Date.now()
+ if (this.absorbLateExplorerFormats(now)) {
+ this.lastCapturedAt = now
+ if (this.settleTimer) {
+ clearTimeout(this.settleTimer)
+ this.settleTimer = null
+ }
+ return
+ }
+
+ const alreadySettling = this.settleTimer !== null
+ if (this.settleTimer) clearTimeout(this.settleTimer)
+ if (!alreadySettling && !this.inCoalesceWindow(now)) {
+ try {
+ this.onHint?.()
+ } catch (err) {
+ console.error('[ClipboardWatcher] onHint failed:', err)
}
+ }
- this.lastSig = stableSig
+ this.settleTimer = setTimeout(() => {
+ void this.commitCapture()
+ }, this.settleMs)
+ }
+ private async commitCapture(): Promise<void> {
+ this.settleTimer = null
+ if (this.paused || !this.onNew) return
+
+ const seqWhenSettled = this.lastSeq
+ this.reading = true
+ try {
const data = await readClipboard()
- if (!data) return
+ // Absorb sequence bumps caused by our own OpenClipboard / format requests.
+ this.lastSeq = getClipboardSequenceNumber()
+ this.lastSig = this.lastSeq > 0 ? `seq:${this.lastSeq}` : clipboardSignature()
+ if (!data) {
+ if (this.incompleteTries < MAX_INCOMPLETE_RETRIES) {
+ this.incompleteTries++
+ this.settleTimer = setTimeout(() => {
+ void this.commitCapture()
+ }, this.settleMs)
+ } else {
+ this.incompleteTries = 0
+ }
+ return
+ }
+ this.incompleteTries = 0
+ let png: Buffer | undefined
if (data.kind === 'image') {
const img = clipboard.readImage()
- const png = img.toPNG()
+ png = img.toPNG()
data.imageId = createId()
data.bytes = png.length
data.ext = 'png'
- this.onNew(data, png)
- } else {
- this.onNew(data)
+ this.lastSeq = getClipboardSequenceNumber()
}
- }, this.settleMs)
+
+ const key = contentSignature(data)
+ const now = Date.now()
+ const sameAsLast = key === this.lastCapturedKey
+ const filesUnchanged = sameAsLast && data.kind === 'files'
+ if (sameAsLast && (filesUnchanged || now - this.lastCapturedAt < COALESCE_MS)) {
+ // Same payload. Files stay absorbed for as long as the path list is
+ // unchanged (Explorer window close is not a copy). Other kinds only
+ // coalesce briefly so a real re-copy of the same text still counts.
+ this.lastCapturedAt = now
+ return
+ }
+ this.lastCapturedKey = key
+ this.lastCapturedAt = now
+
+ if (data.kind === 'image') this.onNew(data, png)
+ else this.onNew(data)
+ } finally {
+ this.reading = false
+ const seqNow = getClipboardSequenceNumber()
+ if (this.settleTimer) {
+ // Incomplete file list: retry is already scheduled. Only restart if
+ // a newer copy landed after that read.
+ if (seqNow !== this.lastSeq) this.pollTick()
+ return
+ }
+ if (seqNow !== this.lastSeq) {
+ this.pollTick()
+ } else if (seqNow !== seqWhenSettled) {
+ // Seq moved during our read. Explorer delay-renders of a file list
+ // are absorbed without another OpenClipboard; a real new copy is not.
+ this.lastSeq = seqWhenSettled
+ this.pollTick()
+ }
+ }
}
/** Temporarily stop recording (incognito mode or self-copy) without tearing down the timer. */
@@ -111,7 +236,8 @@ export class ClipboardWatcher {
// When resuming, refresh the signature so we ignore whatever was copied
// during the paused state (e.g. self-copies or incognito copies).
if (!paused) {
- this.lastSig = clipboardSignature()
+ this.lastSeq = getClipboardSequenceNumber()
+ this.lastSig = this.lastSeq > 0 ? `seq:${this.lastSeq}` : clipboardSignature()
}
}
@@ -142,7 +268,9 @@ export class ClipboardWatcher {
clearTimeout(this.settleTimer)
this.settleTimer = null
}
- this.lastSig = clipboardSignature()
+ this.incompleteTries = 0
+ this.lastSeq = getClipboardSequenceNumber()
+ this.lastSig = this.lastSeq > 0 ? `seq:${this.lastSeq}` : clipboardSignature()
}
/**
@@ -162,7 +290,11 @@ export class ClipboardWatcher {
clearTimeout(this.settleTimer)
this.settleTimer = null
}
+ this.incompleteTries = 0
this.lastSig = '__post-paste__'
+ this.lastSeq = -1
+ this.lastCapturedKey = ''
+ this.lastCapturedAt = 0
}
stop(): void {
diff --git a/electron/clipboard/formats.ts b/electron/clipboard/formats.ts
index 6b86374..1e101c4 100644
--- a/electron/clipboard/formats.ts
+++ b/electron/clipboard/formats.ts
@@ -107,6 +107,84 @@ function readFileListFast(): string[] | null {
}
}
+/**
+ * True when FileNameW currently holds at least one path.
+ *
+ * Cheap peek used by the watcher during the post-capture coalesce window.
+ * Reads only FileNameW (not CF_BITMAP / FileContents), so it does not
+ * retrigger Explorer's delayed-render pipeline.
+ */
+export function clipboardHasFileNameW(): boolean {
+ try {
+ const buf = clipboard.readBuffer(CF_FILE_LIST)
+ return !!(buf && buf.length >= 4)
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Content key for the file drop currently on the clipboard, matching
+ * `contentSignature` for `kind: 'files'`.
+ *
+ * Uses FileNameW plus CF_UNICODETEXT (Explorer writes every selected path as
+ * plain text). Does not request CF_BITMAP / FileContents, so it will not
+ * retrigger delayed rendering.
+ *
+ * Closing an Explorer window sends WM_RENDERALLFORMATS and bumps the sequence
+ * number without changing the path list — the watcher compares this key to
+ * the last capture and ignores that flush.
+ */
+export function clipboardFilesContentKey(): string | null {
+ try {
+ const buf = clipboard.readBuffer(CF_FILE_LIST)
+ if (!buf || buf.length < 4) return null
+ const fromName = buf
+ .toString('utf16le')
+ .split('\u0000')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ if (!fromName.length) return null
+
+ let paths = fromName
+ try {
+ const raw = clipboard.readText()
+ if (raw) {
+ const lines = raw
+ .split(/\r?\n/)
+ .map((s) => s.trim().replace(/^"(.*)"$/, '$1'))
+ .filter(Boolean)
+ if (lines.length >= fromName.length && lines.includes(fromName[0])) {
+ paths = lines
+ }
+ }
+ } catch {
+ /* FileNameW only */
+ }
+
+ return `files|${paths.join('\n')}`
+ } catch {
+ return null
+ }
+}
+
+/**
+ * True when the clipboard is advertising a real file drop (Explorer, desktop,
+ * etc.) even if the path list is not readable yet. FileGroupDescriptor alone
+ * is NOT enough — browsers use that for "Copy Image" virtual files.
+ */
+function clipboardAdvertisesFileList(): boolean {
+ if (clipboardHasFileNameW()) return true
+ try {
+ return clipboard.availableFormats().some((f) => {
+ const l = f.toLowerCase()
+ return l === 'filenamew' || l === 'filename' || l.includes('shell idlist')
+ })
+ } catch {
+ return false
+ }
+}
+
/**
* Build a `FileNameW` buffer suitable for `clipboard.writeBuffer()`.
*
@@ -289,6 +367,52 @@ export function isClipboardExcluded(): boolean {
* Async snapshot of the current clipboard into a single ItemData, or null.
*
* Order matters: a file copy should win over its text fallback, an image wins
+/** HTML kept on an item for rich paste. Larger blobs stall persist, IPC, and React. */
+export const MAX_ITEM_HTML_CHARS = 32_768
+const HEAVY_TEXT_CHARS = 8_192
+const HEAVY_TEXT_LINES = 40
+
+function countNewlines(s: string, limit: number): number {
+ let n = 0
+ for (let i = 0; i < s.length && n < limit; i++) {
+ if (s.charCodeAt(i) === 10) n++
+ }
+ return n
+}
+
+function isHeavyTabularText(text: string): boolean {
+ if (!text.includes('\t')) return false
+ return text.length > HEAVY_TEXT_CHARS || countNewlines(text, HEAVY_TEXT_LINES) >= HEAVY_TEXT_LINES
+}
+
+/** Scan a short prefix only — Excel HTML for a large range can be many MB. */
+function htmlLooksLikeRichDocument(html: string): boolean {
+ if (!html) return false
+ const head = html.length > 4096 ? html.slice(0, 4096) : html
+ return /<table\b|<tr\b|<td\b|<th\b|google-sheets|data-sheets|urn:schemas-microsoft-com:office:spreadsheet|excel|<html\b|<body\b|<p\b|<pre\b|<code\b|<ul\b|<ol\b|<li\b/i.test(head)
+}
+
+/**
+ * Normalize clipboard text the same way `readClipboard` stores it, so the
+ * watcher can cheap-compare a late Explorer/Excel format against the last capture
+ * without decoding HTML or bitmaps.
+ */
+export function normalizeClipboardText(rawText: string): string {
+ return rawText.includes('\t') ? rawText.replace(/\r?\n+$/, '') : rawText.trim()
+}
+
+/** Plain-text snapshot for coalesce checks. Does not read HTML or images. */
+export function clipboardTextContent(): string | null {
+ try {
+ const raw = clipboard.readText()
+ if (!raw) return null
+ const n = normalizeClipboardText(raw)
+ return n || null
+ } catch {
+ return null
+ }
+}
+
/**
* Helper to determine whether a clipboard payload containing an image and text
* is intended as an image (e.g. Snipping Tool window capture, browser "Copy Image",
@@ -313,28 +437,8 @@ export function isScreenshotOrImageIntent(hasImage: boolean, rawText: string, ra
const lines = rawText.split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
if (lines.length > 1) return false
- // 3. Spreadsheet HTML markup tags & rich office metadata
- const lowerHtml = rawHtml.toLowerCase()
- if (
- lowerHtml.includes('<table') ||
- lowerHtml.includes('<tr') ||
- lowerHtml.includes('<td') ||
- lowerHtml.includes('<th') ||
- lowerHtml.includes('google-sheets') ||
- lowerHtml.includes('data-sheets') ||
- lowerHtml.includes('urn:schemas-microsoft-com:office:spreadsheet') ||
- lowerHtml.includes('excel') ||
- lowerHtml.includes('<html') ||
- lowerHtml.includes('<body') ||
- lowerHtml.includes('<p') ||
- lowerHtml.includes('<pre') ||
- lowerHtml.includes('<code') ||
- lowerHtml.includes('<ul') ||
- lowerHtml.includes('<ol') ||
- lowerHtml.includes('<li')
- ) {
- return false
- }
+ // 3. Spreadsheet HTML markup tags & rich office metadata (prefix only)
+ if (htmlLooksLikeRichDocument(rawHtml)) return false
// 4. If text is long (> 200 chars), it is a text document, not a window title
if (rawText.length > 200) return false
@@ -358,16 +462,22 @@ export function isScreenshotOrImageIntent(hasImage: boolean, rawText: string, ra
* distribute rows and columns across the cell grid rather than dumping text into one cell.
*/
export function formatTabularDataForClipboard(text: string, rawHtml?: string): { text: string; html?: string } {
- if (!text) return { text: '', html: rawHtml }
+ if (!text) return { text: '', html: rawHtml && rawHtml.length <= MAX_ITEM_HTML_CHARS ? rawHtml : undefined }
// Normalize all line breaks to CRLF (\r\n) for Windows
const crlfText = text.replace(/\r?\n/g, '\r\n')
+ const htmlIfSmall = rawHtml && rawHtml.length <= MAX_ITEM_HTML_CHARS ? rawHtml : undefined
// Check if content has tab characters indicating column separators
if (text.includes('\t')) {
- // If rawHtml already contains a standard table tag, use it
- if (rawHtml && /<table\b[^>]*>/i.test(rawHtml)) {
- return { text: crlfText, html: rawHtml }
+ // If rawHtml already contains a standard table tag, use it — but never
+ // paste megabytes of Excel CF_HTML back; TSV+CRLF is enough for the grid.
+ if (htmlIfSmall && /<table\b[^>]*>/i.test(htmlIfSmall)) {
+ return { text: crlfText, html: htmlIfSmall }
+ }
+
+ if (isHeavyTabularText(text)) {
+ return { text: crlfText }
}
// Otherwise, generate a clean, standard HTML table from the TSV content
@@ -389,7 +499,7 @@ export function formatTabularDataForClipboard(text: string, rawHtml?: string): {
return { text: crlfText, html: htmlTable }
}
- return { text: crlfText, html: rawHtml }
+ return { text: crlfText, html: htmlIfSmall }
}
/**
@@ -410,18 +520,37 @@ export async function readClipboard(): Promise<ItemData | null> {
const files = await readFileListAsync()
if (files && files.length) return { kind: 'files', paths: files }
- const img = clipboard.readImage()
- const hasImage = !img.isEmpty()
+ // Explorer advertises FileNameW / Shell IDList before the path list is
+ // readable. Falling through to the preview bitmap would record a screenshot
+ // of the first file, then a second files card when the paths arrive.
+ if (clipboardAdvertisesFileList()) return null
+
+ // Text first. Excel/Sheets copies of a large range put a huge CF_BITMAP of
+ // the selection plus megabytes of CF_HTML. Decoding those on the UI thread
+ // stalls the window; shipping the HTML through persist/IPC makes it jitter.
const rawText = clipboard.readText()
- const rawHtml = clipboard.readHTML()
const trimmedText = rawText.trim()
+ const heavyTable = isHeavyTabularText(rawText)
+ const skipBitmap = rawText.includes('\t') || countNewlines(rawText, 2) >= 2
+
+ let rawHtml = ''
+ if (!heavyTable) {
+ rawHtml = clipboard.readHTML()
+ }
const trimmedHtml = rawHtml.trim()
const localFromHtml = localPathFromClipboardFileUrl(trimmedHtml) || localPathFromClipboardFileUrl(trimmedText)
if (localFromHtml) return { kind: 'files', paths: [localFromHtml] }
+ let hasImage = false
+ let img: ReturnType<typeof clipboard.readImage> | null = null
+ if (!skipBitmap) {
+ img = clipboard.readImage()
+ hasImage = !img.isEmpty()
+ }
+
// Snipping Tool (Window mode, Freeform, Rectangular) or browser images:
- if (isScreenshotOrImageIntent(hasImage, trimmedText, trimmedHtml)) {
+ if (img && isScreenshotOrImageIntent(hasImage, trimmedText, trimmedHtml)) {
const size = img.getSize()
return {
kind: 'image',
@@ -437,10 +566,11 @@ export async function readClipboard(): Promise<ItemData | null> {
// Text intent (Notepad, Word, VS Code text copy, Excel/Google Sheets tabular copy, rich HTML copy)
if (trimmedText) {
let html: string | undefined
- if (trimmedHtml && trimmedHtml !== trimmedText) html = rawHtml
+ if (trimmedHtml && trimmedHtml !== trimmedText && rawHtml.length <= MAX_ITEM_HTML_CHARS) {
+ html = rawHtml
+ }
- // When text contains tabs (\t), preserve the exact TSV representation (including leading/trailing tabs for empty columns)
- const textToStore = rawText.includes('\t') ? rawText.replace(/\r?\n+$/, '') : trimmedText
+ const textToStore = normalizeClipboardText(rawText)
const isUrl = URL_RE.test(trimmedText)
const isColor = COLOR_HEX_RE.test(trimmedText)
@@ -449,7 +579,7 @@ export async function readClipboard(): Promise<ItemData | null> {
}
// Fallback to image if no text
- if (hasImage) {
+ if (hasImage && img) {
const size = img.getSize()
return {
kind: 'image',
@@ -496,9 +626,16 @@ export function clipboardSignature(): string {
return `${seqPrefix}files:${files.join('\n')}`
}
+ const rawUntrimmed = clipboard.readText()
+ // Spreadsheet copies carry a huge selection bitmap. Fingerprint the TSV
+ // only — toBitmap() of a 1500-row range stalls the window.
+ if (rawUntrimmed.includes('\t') || countNewlines(rawUntrimmed, 2) >= 2) {
+ return `${seqPrefix}text:${normalizeClipboardText(rawUntrimmed)}`
+ }
+
const img = clipboard.readImage()
const hasImage = !img.isEmpty()
- const rawText = clipboard.readText().trim()
+ const rawText = rawUntrimmed.trim()
const rawHtml = clipboard.readHTML().trim()
if (isScreenshotOrImageIntent(hasImage, rawText, rawHtml)) {
diff --git a/electron/main/state.ts b/electron/main/state.ts
index 5e54590..33704a3 100644
--- a/electron/main/state.ts
+++ b/electron/main/state.ts
@@ -18,7 +18,7 @@ import { runtime } from './config'
import { getMainWindow, registerClipboardUpdateListener } from './window'
const store = new ItemStore((removed) => forgetStagedItems(removed))
-const watcher = new ClipboardWatcher(600)
+const watcher = new ClipboardWatcher(600, 220)
let pruneTimer: ReturnType<typeof setInterval> | null = null
let wakeTimer: ReturnType<typeof setTimeout> | null = null
diff --git a/electron/store/ItemStore.ts b/electron/store/ItemStore.ts
index 67469f8..1af9f97 100644
--- a/electron/store/ItemStore.ts
+++ b/electron/store/ItemStore.ts
@@ -25,6 +25,7 @@ import {
import { PATHS } from './paths'
import { createId } from './ids'
import { contentSignature } from './signature'
+import { MAX_ITEM_HTML_CHARS } from '../clipboard/formats'
/** Maps a signature -> item id so dedup is O(1). */
interface Index {
@@ -110,6 +111,10 @@ export class ItemStore {
it.data.text = it.data.previewText
migratedAnyPayloads = true
}
+ if (it.data.html && it.data.html.length > MAX_ITEM_HTML_CHARS) {
+ delete it.data.html
+ migratedAnyPayloads = true
+ }
}
}
@@ -248,13 +253,18 @@ export class ItemStore {
const id = createId()
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)
+ if (data.kind === 'text') {
+ if (data.html && data.html.length > MAX_ITEM_HTML_CHARS) {
+ delete data.html
+ }
+ if (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)
+ }
}
}
@@ -787,6 +797,20 @@ export class ItemStore {
data: { ...it.data, entries }
}
}
+ if (it.data.kind === 'text') {
+ const d = it.data
+ return {
+ ...it,
+ data: {
+ kind: 'text',
+ text: d.text,
+ isUrl: d.isUrl,
+ isColor: d.isColor,
+ hasFullPayload: d.hasFullPayload,
+ previewText: d.previewText
+ }
+ }
+ }
return { ...it, data: it.data }
})
}
diff --git a/src/App.tsx b/src/App.tsx
index 1602821..7556fb5 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -81,6 +81,7 @@ export default function App() {
useStore.getState().setUpdateDownloaded(info)
})
const offCopyFlare = edge.onCopyFlare(() => {
+ if (useStore.getState().isInternalCopying) return
useStore.getState().triggerCopyFlare()
})
return () => {
diff --git a/src/lib/itemSignature.ts b/src/lib/itemSignature.ts
index 5f4aac4..d271ab2 100644
--- a/src/lib/itemSignature.ts
+++ b/src/lib/itemSignature.ts
@@ -18,9 +18,9 @@ export function itemRenderKey(item: ClipboardItemDto): string {
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 ?? ''}`
+ // isUrl switches the whole body layout. Do not include html: Excel
+ // CF_HTML can be megabytes and cards never render it.
+ return `t|${d.isUrl ? 1 : 0}|${d.isColor ? 1 : 0}|${d.text}`
case 'image':
return `i|${d.imageId}|${d.width}x${d.height}|${d.bytes}|${d.ext ?? ''}|${d.source ?? ''}|${d.fileName ?? ''}|${d.preview}`
case 'image-collection':
diff --git a/src/store/appStore.ts b/src/store/appStore.ts
index 88afbad..61ee8aa 100644
--- a/src/store/appStore.ts
+++ b/src/store/appStore.ts
@@ -206,12 +206,6 @@ export const useStore = create<AppState>((set, get) => ({
isStoreBuild: isStoreBuild ?? false,
hydrated: true
})
- edge.onCopyFlare(() => {
- if (!get().isInternalCopying) {
- console.log('[appStore] OS copy event detected! Triggering copy flare indicator')
- get().triggerCopyFlare()
- }
- })
},
manualCheckState: { status: 'idle' },
@@ -279,7 +273,7 @@ export const useStore = create<AppState>((set, get) => ({
await edge.installUpdate()
},
- setItems: (items, meta) => {
+ setItems: (items, _meta) => {
const prevItems = get().items
if (
prevItems.length === items.length &&
@@ -287,30 +281,9 @@ export const useStore = create<AppState>((set, get) => ({
) {
return
}
- const prevTop = prevItems.length > 0 ? prevItems[0] : null
- const newTop = items.length > 0 ? items[0] : null
-
- if (get().hydrated && newTop) {
- const isDifferentId = !prevTop || newTop.id !== prevTop.id
- const isNewCapturedAt = prevTop && newTop.capturedAt !== prevTop.capturedAt
- // 'usage' meta = bookkeeping push from a manual drag-out (recency bump
- // after a successful external drop). The user is moving content, not
- // capturing it - the copy indicator must stay dark.
- const isUsageBookkeeping = meta?.reason === 'usage'
- // 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 && !isUsageBookkeeping) {
- get().triggerCopyFlare()
- }
- }
+ // Copy confirmation is owned by `ui:copy-flare` (App.tsx). Firing it again
+ // here replayed the indicator after a slow capture (large spreadsheet)
+ // finished — the hint already showed it ~780ms earlier.
set({ items })
},
setSettings: (next) => set({ settings: next }),
diff --git a/tests/clipboardWatcher.test.ts b/tests/clipboardWatcher.test.ts
index 7dc9fee..a04f41b 100644
--- a/tests/clipboardWatcher.test.ts
+++ b/tests/clipboardWatcher.test.ts
@@ -4,9 +4,27 @@ import * as formats from '../electron/clipboard/formats'
describe('ClipboardWatcher Re-Copy Detection & Flare Flow', () => {
let watcher: ClipboardWatcher
+ let mockSeq = 100
+ let mockText = 'Hello'
+ let mockItem: { kind: 'text'; text: string } | { kind: 'files'; paths: string[] } = { kind: 'text', text: 'Hello' }
+ let hasFileNameW = false
beforeEach(() => {
vi.useFakeTimers()
+ mockSeq = 100
+ mockText = 'Hello'
+ mockItem = { kind: 'text', text: 'Hello' }
+ hasFileNameW = false
+ vi.spyOn(formats, 'getClipboardSequenceNumber').mockImplementation(() => mockSeq)
+ vi.spyOn(formats, 'clipboardSignature').mockImplementation(() => `seq:${mockSeq}:text:${mockText}`)
+ vi.spyOn(formats, 'readClipboard').mockImplementation(async () => mockItem)
+ vi.spyOn(formats, 'clipboardHasFileNameW').mockImplementation(() => hasFileNameW)
+ vi.spyOn(formats, 'clipboardTextContent').mockImplementation(() =>
+ mockItem.kind === 'text' ? mockItem.text : null
+ )
+ vi.spyOn(formats, 'clipboardFilesContentKey').mockImplementation(() =>
+ mockItem.kind === 'files' && hasFileNameW ? `files|${mockItem.paths.join('\n')}` : null
+ )
})
afterEach(() => {
@@ -15,105 +33,249 @@ describe('ClipboardWatcher Re-Copy Detection & Flare Flow', () => {
vi.restoreAllMocks()
})
- it('detects re-copies of the identical item when the OS sequence number increments', async () => {
- let mockSeq = 100
- let mockText = 'Hello Edge-Drop'
-
- vi.spyOn(formats, 'clipboardSignature').mockImplementation(() => `seq:${mockSeq}:text:${mockText}`)
- vi.spyOn(formats, 'readClipboard').mockImplementation(async () => ({ kind: 'text', text: mockText }))
-
- const onNew = vi.fn()
- watcher = new ClipboardWatcher(50)
- watcher.start(onNew)
+ async function startWatcher(onNew = vi.fn(), onHint = vi.fn()) {
+ watcher = new ClipboardWatcher(50, 200)
+ watcher.start(onNew, onHint)
+ await vi.advanceTimersByTimeAsync(60)
+ return { onNew, onHint }
+ }
- // Initially seeded — no callback on tick 1
+ async function copyAndSettle() {
await vi.advanceTimersByTimeAsync(60)
+ await vi.advanceTimersByTimeAsync(220)
+ }
+
+ it('detects re-copies of the identical item when the OS sequence number increments', async () => {
+ mockSeq = 100
+ mockText = 'Hello Edge-Drop'
+ mockItem = { kind: 'text', text: 'Hello Edge-Drop' }
+ const { onNew } = await startWatcher()
expect(onNew).not.toHaveBeenCalled()
- // 1. User copies the exact same text again in the OS (sequence number increments)
mockSeq = 101
- await vi.advanceTimersByTimeAsync(60) // interval tick
- await vi.advanceTimersByTimeAsync(160) // settling window timeout
-
+ await copyAndSettle()
expect(onNew).toHaveBeenCalledTimes(1)
expect(onNew).toHaveBeenCalledWith({ kind: 'text', text: 'Hello Edge-Drop' })
- // 2. Ticks without any new copy action do NOT fire
await vi.advanceTimersByTimeAsync(200)
expect(onNew).toHaveBeenCalledTimes(1)
- // 3. User copies the exact same text a third time (sequence number increments again)
+ await vi.advanceTimersByTimeAsync(400)
mockSeq = 102
- await vi.advanceTimersByTimeAsync(60)
- await vi.advanceTimersByTimeAsync(160)
-
+ await copyAndSettle()
expect(onNew).toHaveBeenCalledTimes(2)
})
it('detects brand new items when content changes', async () => {
- let mockSeq = 200
- let mockText = 'First Item'
+ mockSeq = 200
+ mockText = 'First Item'
+ mockItem = { kind: 'text', text: 'First Item' }
+ const { onNew } = await startWatcher()
+ expect(onNew).not.toHaveBeenCalled()
- vi.spyOn(formats, 'clipboardSignature').mockImplementation(() => `seq:${mockSeq}:text:${mockText}`)
- vi.spyOn(formats, 'readClipboard').mockImplementation(async () => ({ kind: 'text', text: mockText }))
+ mockSeq = 201
+ mockText = 'Second Item'
+ mockItem = { kind: 'text', text: 'Second Item' }
+ await copyAndSettle()
- const onNew = vi.fn()
- watcher = new ClipboardWatcher(50)
- watcher.start(onNew)
+ expect(onNew).toHaveBeenCalledTimes(1)
+ expect(onNew).toHaveBeenCalledWith({ kind: 'text', text: 'Second Item' })
+ })
+
+ it('fires onHint once per burst, before settle, and coalesces sequence bumps', async () => {
+ mockSeq = 400
+ mockText = 'Hint First'
+ mockItem = { kind: 'text', text: 'Hint First' }
+ const { onNew, onHint } = await startWatcher()
+ expect(onHint).not.toHaveBeenCalled()
+ mockSeq = 401
await vi.advanceTimersByTimeAsync(60)
+ expect(onHint).toHaveBeenCalledTimes(1)
expect(onNew).not.toHaveBeenCalled()
- // Change to a new item
- mockSeq = 201
- mockText = 'Second Item'
+ mockSeq = 402
+ await vi.advanceTimersByTimeAsync(60)
+ mockSeq = 403
await vi.advanceTimersByTimeAsync(60)
- await vi.advanceTimersByTimeAsync(160)
+ expect(onHint).toHaveBeenCalledTimes(1)
+ expect(onNew).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(220)
expect(onNew).toHaveBeenCalledTimes(1)
- expect(onNew).toHaveBeenCalledWith({ kind: 'text', text: 'Second Item' })
})
- it('fires onHint immediately when the sequence number changes, before settle', async () => {
- let mockSeq = 400
- let mockText = 'Hint First'
+ it('does not recapture identical content that arrives as a late Explorer format', async () => {
+ mockSeq = 500
+ mockText = 'Same Files'
+ mockItem = { kind: 'text', text: 'Same Files' }
+ const { onNew } = await startWatcher()
- vi.spyOn(formats, 'clipboardSignature').mockImplementation(() => `seq:${mockSeq}:text:${mockText}`)
- vi.spyOn(formats, 'readClipboard').mockImplementation(async () => ({ kind: 'text', text: mockText }))
+ mockSeq = 501
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
- const onNew = vi.fn()
- const onHint = vi.fn()
- watcher = new ClipboardWatcher(50, 150)
- watcher.start(onNew, onHint)
+ mockSeq = 502
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+ })
- await vi.advanceTimersByTimeAsync(60)
- expect(onHint).not.toHaveBeenCalled()
+ it('does not fire a second copy indicator for late Explorer formats', async () => {
+ mockSeq = 510
+ mockText = 'Flare Once'
+ mockItem = { kind: 'text', text: 'Flare Once' }
+ const { onNew, onHint } = await startWatcher()
- mockSeq = 401
+ mockSeq = 511
+ await copyAndSettle()
+ expect(onHint).toHaveBeenCalledTimes(1)
+ expect(onNew).toHaveBeenCalledTimes(1)
+
+ mockSeq = 512
+ await copyAndSettle()
+ expect(onHint).toHaveBeenCalledTimes(1)
+ expect(onNew).toHaveBeenCalledTimes(1)
+ })
+
+ it('absorbs Explorer file-list delay-renders without re-reading the clipboard', async () => {
+ mockSeq = 600
+ mockItem = { kind: 'files', paths: ['C:\\a.png', 'C:\\b.png'] }
+ hasFileNameW = true
+ const { onNew, onHint } = await startWatcher()
+
+ mockSeq = 601
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+ expect(formats.readClipboard).toHaveBeenCalledTimes(1)
+
+ mockSeq = 602
await vi.advanceTimersByTimeAsync(60)
+ mockSeq = 603
+ await copyAndSettle()
+
+ expect(onNew).toHaveBeenCalledTimes(1)
expect(onHint).toHaveBeenCalledTimes(1)
- expect(onNew).not.toHaveBeenCalled()
+ expect(formats.readClipboard).toHaveBeenCalledTimes(1)
+ })
- await vi.advanceTimersByTimeAsync(160)
+ it('does not recapture the same Explorer files when the source window later flushes delayed formats', async () => {
+ mockSeq = 1000
+ mockItem = { kind: 'files', paths: ['C:\\a.png', 'C:\\b.png'] }
+ hasFileNameW = true
+ const { onNew, onHint } = await startWatcher()
+
+ mockSeq = 1001
+ await copyAndSettle()
expect(onNew).toHaveBeenCalledTimes(1)
+ expect(onHint).toHaveBeenCalledTimes(1)
+
+ await vi.advanceTimersByTimeAsync(5000)
+
+ mockSeq = 1002
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+ expect(onHint).toHaveBeenCalledTimes(1)
+ expect(formats.readClipboard).toHaveBeenCalledTimes(1)
})
- it('respects paused state during self-copy and incognito mode', async () => {
- let mockSeq = 300
- let mockText = 'Initial'
+ it('still captures a different file list after an Explorer copy', async () => {
+ mockSeq = 1100
+ mockItem = { kind: 'files', paths: ['C:\\a.png', 'C:\\b.png'] }
+ hasFileNameW = true
+ const { onNew } = await startWatcher()
- vi.spyOn(formats, 'clipboardSignature').mockImplementation(() => `seq:${mockSeq}:text:${mockText}`)
- vi.spyOn(formats, 'readClipboard').mockImplementation(async () => ({ kind: 'text', text: mockText }))
+ mockSeq = 1101
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+
+ await vi.advanceTimersByTimeAsync(5000)
+ mockSeq = 1102
+ mockItem = { kind: 'files', paths: ['C:\\c.png'] }
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(2)
+ expect(onNew).toHaveBeenLastCalledWith({ kind: 'files', paths: ['C:\\c.png'] })
+ })
- const onNew = vi.fn()
- watcher = new ClipboardWatcher(50)
- watcher.start(onNew)
+ it('still captures a different copy that lands inside the coalesce window', async () => {
+ mockSeq = 700
+ mockText = 'Alpha'
+ mockItem = { kind: 'text', text: 'Alpha' }
+ const { onNew } = await startWatcher()
+
+ mockSeq = 701
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+
+ mockSeq = 702
+ mockText = 'Beta'
+ mockItem = { kind: 'text', text: 'Beta' }
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(2)
+ expect(onNew).toHaveBeenLastCalledWith({ kind: 'text', text: 'Beta' })
+ })
+
+ it('captures a genuine recopy after paste invalidates the signature', async () => {
+ mockSeq = 800
+ mockText = 'Paste Then Copy'
+ mockItem = { kind: 'text', text: 'Paste Then Copy' }
+ const { onNew } = await startWatcher()
+
+ mockSeq = 801
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(1)
+
+ watcher.invalidateSignature()
+ mockSeq = 802
+ await copyAndSettle()
+ expect(onNew).toHaveBeenCalledTimes(2)
+ })
+
+ it('captures a copy that arrives while a previous read is in flight', async () => {
+ mockSeq = 900
+ mockText = 'First'
+ mockItem = { kind: 'text', text: 'First' }
+
+ let hangFirst = true
+ let releaseRead: () => void = () => {}
+ vi.spyOn(formats, 'readClipboard').mockImplementation(() => {
+ const snapshot = mockItem
+ if (hangFirst) {
+ hangFirst = false
+ return new Promise((resolve) => {
+ releaseRead = () => resolve(snapshot)
+ })
+ }
+ return Promise.resolve(snapshot)
+ })
+
+ const { onNew } = await startWatcher()
+ mockSeq = 901
+ await vi.advanceTimersByTimeAsync(60)
+ await vi.advanceTimersByTimeAsync(220)
+ expect(onNew).not.toHaveBeenCalled()
+
+ mockSeq = 902
+ mockItem = { kind: 'text', text: 'Second' }
+ watcher.nudge()
+ releaseRead()
+ await vi.advanceTimersByTimeAsync(0)
+ await vi.advanceTimersByTimeAsync(220)
+ expect(onNew).toHaveBeenCalledTimes(2)
+ expect(onNew).toHaveBeenLastCalledWith({ kind: 'text', text: 'Second' })
+ })
+
+ it('respects paused state during self-copy and incognito mode', async () => {
+ mockSeq = 300
+ mockText = 'Initial'
+ mockItem = { kind: 'text', text: 'Initial' }
+ const { onNew } = await startWatcher()
watcher.setPaused(true)
mockSeq = 301
mockText = 'Copied While Paused'
- await vi.advanceTimersByTimeAsync(300)
+ mockItem = { kind: 'text', text: 'Copied While Paused' }
+ await vi.advanceTimersByTimeAsync(400)
expect(onNew).not.toHaveBeenCalled()
})
diff --git a/tests/snippingTool.test.ts b/tests/snippingTool.test.ts
index bcee3b4..e93e9e4 100644
--- a/tests/snippingTool.test.ts
+++ b/tests/snippingTool.test.ts
@@ -244,4 +244,24 @@ describe('Windows Snipping Tool & Clipboard Image Detection (#41)', () => {
const sig = clipboardSignature()
expect(sig).toContain('text:Name\tScore')
})
+
+ it('does not treat an Explorer file copy as an image while FileNameW is advertised but unread', async () => {
+ const mockBgra = Buffer.alloc(64 * 64 * 4, 32)
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 64, height: 64 }),
+ toBitmap: () => mockBgra,
+ toPNG: () => Buffer.from('mock-png-bytes')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['FileNameW', 'CF_HDROP', 'CF_DIB', 'CF_BITMAP'],
+ text: '',
+ html: '',
+ image: mockImage
+ })
+
+ const result = await readClipboard()
+ expect(result).toBeNull()
+ })
})
diff --git a/tests/spreadsheetClipboard.test.ts b/tests/spreadsheetClipboard.test.ts
index 1dec6fb..af9be55 100644
--- a/tests/spreadsheetClipboard.test.ts
+++ b/tests/spreadsheetClipboard.test.ts
@@ -119,4 +119,39 @@ describe('Spreadsheet Tabular Clipboard Formatting', () => {
expect(item.html).toContain('<table>')
}
})
+
+ it('does not decode the selection bitmap or keep megabyte HTML for a large spreadsheet copy', async () => {
+ const rows = Array.from({ length: 1500 }, (_, i) => `r${i}\tc${i}\tval${i}`).join('\n')
+ const hugeHtml = `<table>${'<tr><td>x</td></tr>'.repeat(1500)}</table>`
+ const mockImage = {
+ isEmpty: () => false,
+ getSize: () => ({ width: 4000, height: 40000 }),
+ toBitmap: () => Buffer.alloc(4000 * 40000 * 4),
+ toPNG: () => Buffer.from('should-not-run')
+ }
+
+ ;(clipboard as any).__setMockState({
+ formats: ['CF_UNICODETEXT', 'HTML Format', 'CF_DIB', 'CF_BITMAP'],
+ text: rows,
+ html: hugeHtml,
+ image: mockImage
+ })
+
+ const item = await readClipboard()
+ expect(item).not.toBeNull()
+ expect(item?.kind).toBe('text')
+ if (item?.kind === 'text') {
+ expect(item.text.startsWith('r0\tc0\tval0')).toBe(true)
+ expect(item.html).toBeUndefined()
+ }
+ expect(clipboard.readImage).not.toHaveBeenCalled()
+ expect(clipboard.readHTML).not.toHaveBeenCalled()
+ })
+
+ it('does not synthesize a giant HTML table when pasting a large TSV', () => {
+ const rows = Array.from({ length: 1500 }, (_, i) => `r${i}\tc${i}`).join('\n')
+ const result = formatTabularDataForClipboard(rows)
+ expect(result.text.includes('\r\n')).toBe(true)
+ expect(result.html).toBeUndefined()
+ })
})