Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.
TypeScript clipboardclipboard-managerdesktop-appdrag-and-dropelectronopen-sourceproductivityproductivity-toolwindows
fix(multi-display): versioned work-area cache, pure edge probe, twin determinism, dead-code removal
Deepender250af5da91ce23
diff --git a/electron/main/geometry.ts b/electron/main/geometry.tsindex dd3ade3..d7aa70d 100644--- a/electron/main/geometry.ts+++ b/electron/main/geometry.ts@@ -20,7 +20,6 @@ export interface StickBoundsParams {/** Persisted scale factor — secondary discriminator for identical-geometry monitors. */savedScaleFactor?: numberwindowWidth: number- windowHeight: numbercurrentBounds?: { x: number; y: number }}@@ -73,17 +72,20 @@ export function computeStickBounds(params: StickBoundsParams): StickBoundsResult// geometry (within BOUNDS_TOLERANCE) and optionally the DPI scale factor as a// secondary discriminator when two monitors share the same resolution.if (!display && savedWorkArea) {- const candidates = displays.filter(d => boundsMatch(d.workArea, savedWorkArea))- if (candidates.length === 1) {- // Only one display matches the stored geometry — unambiguous.- display = candidates[0]- } else if (candidates.length > 1 && savedScaleFactor !== undefined) {- // Multiple displays with the same geometry (e.g. dual same-res). Use- // scale factor as a tiebreaker.- const byScale = candidates.find(d => d.scaleFactor === savedScaleFactor)- display = byScale ?? candidates[0]- } else if (candidates.length > 1) {- // Tie with no scale discriminator — take the first candidate.+ let candidates = displays.filter(d => boundsMatch(d.workArea, savedWorkArea))+ if (candidates.length > 1 && savedScaleFactor !== undefined) {+ const byScale = candidates.filter(d => d.scaleFactor === savedScaleFactor)+ if (byScale.length) candidates = byScale+ }+ if (candidates.length > 1) {+ // Identical twins (same geometry AND scale): geometry is exhausted as a+ // discriminator by definition, so anchor on the OS-designated primary -+ // deterministic across reboots, independent of array order.+ const primaryCandidate = candidates.find(d => d.isPrimary)+ if (primaryCandidate) candidates = [primaryCandidate]+ }+ if (candidates.length >= 1) {+ // Only one unambiguous match, or the best-ranked twin.display = candidates[0]}// If candidates.length === 0 the saved display is genuinely gone; fall through.@@ -126,11 +128,7 @@ function findNearestDisplay(displays: DisplayInfo[], point: { x: number; y: numblet nearest: DisplayInfo | undefinedlet minDist = Infinityfor (const d of displays) {- const cx = d.workArea.x + d.workArea.width / 2- const cy = d.workArea.y + d.workArea.height / 2- const dx = cx - point.x- const dy = cy - point.y- const dist = dx * dx + dy * dy+ const dist = centerDistSq(d, point)if (dist < minDist) {minDist = distnearest = d@@ -138,3 +136,12 @@ function findNearestDisplay(displays: DisplayInfo[], point: { x: number; y: numb}return nearest}++/** Squared distance from a display's center to a point (avoids sqrt). */+function centerDistSq(d: DisplayInfo, point: { x: number; y: number }): number {+ const cx = d.workArea.x + d.workArea.width / 2+ const cy = d.workArea.y + d.workArea.height / 2+ const dx = cx - point.x+ const dy = cy - point.y+ return dx * dx + dy * dy+}diff --git a/electron/main/stickProbe.ts b/electron/main/stickProbe.tsnew file mode 100644index 0000000..b048584--- /dev/null+++ b/electron/main/stickProbe.ts@@ -0,0 +1,62 @@+/**+ * Pure edge-probe math extracted from the cursor poll.+ *+ * Zero Electron imports so the EXACT production decision logic can be+ * exercised in unit tests against simulated multi-display topologies -+ * the deepest verification possible without physical hardware.+ *+ * Semantics (must stay byte-equivalent to the original inline block):+ * - client coords = global cursor - stick display workArea origin+ * - garbage guard: |clientX| outside [-5000, 15000] / same for Y+ * - distFromEdge: distance from the stuck edge (left edge => clientX)+ * - inEdge: distFromEdge within [-30, hotZoneWidth]+ */++import type { WorkAreaRect } from './workAreaCache'++export interface StickProbeInput {+ /** Global virtual-desktop cursor point (screen.getCursorScreenPoint()). */+ cursor: { x: number; y: number }+ /** Work area of the display the shelf is stuck to. */+ workArea: WorkAreaRect+ stickPosition: 'left' | 'right'+ /** Physical thickness of the hover trigger band. */+ hotZoneWidth: number+}++export interface StickProbeResult {+ clientX: number+ clientY: number+ /** Distance from the stuck edge; small/negative means "at the edge". */+ distFromEdge: number+ /** True when the cursor dwells inside the trigger band. */+ inEdge: boolean+ /** True when Windows sent implausible coordinates; callers must skip. */+ garbage: boolean+}++/** Distance beyond which the adaptive poll is allowed to throttle down. */+export const FAST_POLL_PROXIMITY_PX = 450++export function probeStickEdge(input: StickProbeInput): StickProbeResult {+ const { cursor, workArea, stickPosition, hotZoneWidth } = input++ const clientX = cursor.x - workArea.x+ const clientY = cursor.y - workArea.y++ const garbage =+ clientX < -5000 || clientX > 15000 || clientY < -5000 || clientY > 15000++ const distFromEdge = stickPosition === 'right'+ ? workArea.width - clientX+ : clientX++ const inEdge = !garbage && distFromEdge >= -30 && distFromEdge <= hotZoneWidth++ return { clientX, clientY, distFromEdge, inEdge, garbage }+}++/** True when this frame qualifies for fast-poll proximity (<= 450px from edge). */+export function isNearProximity(distFromEdge: number): boolean {+ return distFromEdge <= FAST_POLL_PROXIMITY_PX+}diff --git a/electron/main/window.ts b/electron/main/window.tsindex e8d4672..995aee2 100644--- a/electron/main/window.ts+++ b/electron/main/window.ts@@ -1,36 +1,27 @@/*** The edge panel BrowserWindow.*- * The window is the full *expanded* size and sits at the left edge of the- * primary display's work area. It is transparent and frameless, and is normally- * click-through (`setIgnoreMouseEvents(true, { forward: true })`) so the desktop- * stays fully usable. The renderer listens for pointer movement across the whole- * page (which is still delivered even while click-through, thanks to `forward`)- * and toggles interactivity via `setInteractive` once the cursor dwells in the- * hot zone. This is what produces the "invisible until you approach the edge"- * effect without a separate hidden trigger window.- *- * Drag-in support: a separate thin "detector" window is layered behind the- * main panel. Historically it was kept non-click-through so it could receive- * OS dragenter events, but on Windows that made it swallow all desktop clicks- * across the hint-bar band (a transparent always-on-top BrowserWindow still- * hit-tests across a minimum footprint). It is now click-through too; drag-in- * still works because the main-process cursor poll (startCursorPoll) reads the- * OS cursor position independently of mouse events, so it fires during an OS- * file drag — the edge dwell opens the panel and makes the main window+ * The window is the full *expanded* size and sits at the edge of the stick+ * display's work area. It is transparent and frameless, and is normally+ * click-through (`setIgnoreMouseEvents(true, { forward: false })`) so the+ * desktop stays fully usable. Edge detection does NOT rely on DOM pointer+ * events: the main-process cursor poll (startCursorPoll) reads the OS cursor+ * position directly every tick, which also keeps working during OS file+ * drags — the edge dwell opens the panel and makes the main window* interactive, and the drop then lands on the main window.** NOTE: this module must NOT import from state.ts to avoid circular dependencies.*/import { BrowserWindow, screen, shell, powerMonitor, app } from 'electron'import { join } from 'node:path'-import { existsSync } from 'node:fs'import koffi from 'koffi'import { APP_CONFIG } from './config'import { runtime } from './config'import { PATHS } from '../store/paths'import { TRANSLATIONS, en } from '../../src/i18n/translations'import { computeStickBounds } from './geometry'+import { WorkAreaCache } from './workAreaCache'+import { probeStickEdge, isNearProximity } from './stickProbe'import { loadSettings, saveSettings } from '../store/settings'import { isFullscreenAppActive, registerFullscreenActiveListener } from './fullscreen'@@ -101,9 +92,6 @@ export const PANEL_WIDTH = 384export const COLLAPSED_WIDTH = 0let mainWindow: BrowserWindow | null = null-// Kept only by the unused legacy helper at the bottom of this module. The-// detector window is deliberately no longer created at runtime.-let detectorWindow: BrowserWindow | null = nulllet interactive = falseexport let previewActive = false@@ -111,16 +99,22 @@ export let currentHotZoneWidth = 3export let currentStickDisplayId: number | undefinedlet staleIdConsecutiveCount = 0-let cachedWorkArea = { x: 0, y: 0, width: 1920, height: 1080 }+/**+ * Stick-display work area cache (versioned, last-known-good).+ * Rebuilds automatically when the stick display id changes - this is the fix+ * for "switched monitors in Settings but edge detection kept listening to+ * the old screen". See workAreaCache.ts for the full contract.+ */+const workAreaCache = new WorkAreaCache((displayId) => {+ const all = screen.getAllDisplays()+ const stick = all.find(d => d.id === displayId) ?? screen.getPrimaryDisplay()+ return stick?.workArea ? { displayId: stick.id, workArea: stick.workArea } : null+})++/** Force a cache re-read (display topology events). */export function updateCachedWorkArea(): void {- try {- const all = screen.getAllDisplays()- const stick = all.find(d => d.id === currentStickDisplayId) || screen.getPrimaryDisplay()- if (stick && stick.workArea) {- cachedWorkArea = stick.workArea- }- } catch {}+ workAreaCache.refresh(currentStickDisplayId)}export function setHotZoneWidth(width: number): void {@@ -129,7 +123,7 @@ export function setHotZoneWidth(width: number): void {export function setStickDisplayId(id: number | undefined): void {currentStickDisplayId = id- updateCachedWorkArea()+ workAreaCache.refresh(id)}export function getMainWindow(): BrowserWindow | null {@@ -219,8 +213,6 @@ export function setPreviewMode(active: boolean): void {* is ~150ms, so a SLOW tick of 150ms is imperceptible).*/-/** Proximity threshold for entering fast-poll mode (px from the edge). */-const FAST_POLL_PROXIMITY_PX = 450/** Full-speed poll when edge is near. */const POLL_FAST_MS = 16/** Battery-power slow poll (panel closed, cursor far). */@@ -289,23 +281,27 @@ function _pollTick(): void {const pt = screen.getCursorScreenPoint()- if (cachedWorkArea.width === 1920 && cachedWorkArea.height === 1080) {- updateCachedWorkArea()- }- const wa = cachedWorkArea-- // Translate screen coords → stick display client coords.- const clientX = pt.x - wa.x- const clientY = pt.y - wa.y+ // Versioned read: rebuilds automatically whenever the stick display id+ // changed (Settings/tray switch, re-resolution after topology events).+ const wa = workAreaCache.get(currentStickDisplayId)+ if (!wa) return // no successful enumeration yet; retry next tick++ // Pure edge-probe math (unit-tested against simulated multi-display+ // topologies in tests/stickProbeScenarios.test.ts).+ const probe = probeStickEdge({+ cursor: pt,+ workArea: wa,+ stickPosition: settings.stickPosition,+ hotZoneWidth: currentHotZoneWidth+ })+ if (probe.garbage) return- // Guard against garbage values that Windows occasionally sends.- if (clientX < -5000 || clientX > 15000 || clientY < -5000 || clientY > 15000) return+ const clientX = probe.clientX+ const clientY = probe.clientY+ const distFromEdge = probe.distFromEdge// ── Adaptive speed: switch to fast poll when cursor approaches the edge ──- const distFromEdge = settings.stickPosition === 'right'- ? wa.width - clientX // distance from right edge- : clientX // distance from left edge- const nearProximity = distFromEdge <= FAST_POLL_PROXIMITY_PX+ const nearProximity = isNearProximity(distFromEdge)if (nearProximity || interactive) {_lastProximityExitMs = 0 // reset cooldown@@ -330,17 +326,7 @@ function _pollTick(): void {}}- let inEdge = false- switch (settings.stickPosition) {- case 'left':- inEdge = clientX >= -30 && clientX <= currentHotZoneWidth- break- case 'right': {- const d = wa.width - clientX- inEdge = d >= -30 && d <= currentHotZoneWidth- break- }- }+ const inEdge = probe.inEdgeconst newState = inEdge@@ -356,9 +342,7 @@ function _pollTick(): void {// c) Cursor moved >= IPC_MIN_DELTA_PX since last send — avoids spamming// the renderer when the cursor is stationary near the edge.const IPC_MIN_DELTA_PX = 3- const nearEdge = settings.stickPosition === 'right'- ? (wa.width - clientX) <= 450- : clientX <= 450+ const nearEdge = isNearProximity(distFromEdge)const positionChangedEnough =Math.abs(clientX - _lastSentX) >= IPC_MIN_DELTA_PX ||@@ -416,7 +400,6 @@ function getStickGeometry(): { x: number; y: number; width: number; height: numbsavedWorkArea: settings.stickDisplayWorkArea,savedScaleFactor: settings.stickDisplayScaleFactor,windowWidth: currentWindowWidth,- windowHeight: primaryDisplay.workArea.height, // initial hint; result uses resolvedDisplay.workArea.heightcurrentBounds: getMainWindow()?.getBounds()})@@ -498,6 +481,12 @@ function getStickGeometry(): { x: number; y: number; width: number; height: numb}currentStickDisplayId = resolved.id+ // CRITICAL: re-version the poll cache to the freshly resolved display.+ // Without this, Settings/tray display switches moved the WINDOW correctly+ // while edge detection kept measuring against the previous monitor's+ // origin (the "hover secondary does nothing, hover primary opens it on+ // secondary" report).+ workAreaCache.refresh(resolved.id)return { x: result.x, y: result.y, width: result.width, height: result.height }}@@ -747,6 +736,10 @@ export function getDisplayListOptions(): Array<{}const dict = TRANSLATIONS[langCode]const primaryText = dict?.position?.primaryDisplay || en.position.primaryDisplay+ // Localized side tags reuse the fully translated tray words; vertical+ // arrangements get no tag rather than inventing untranslated strings.+ const sideWord = (key: 'left' | 'right'): string =>+ (dict?.tray?.[key]) || en.tray[key] || keyreturn all.map((d, index) => {const isPrimary = d.id === primary.id@@ -760,6 +753,19 @@ export function getDisplayListOptions(): Array<{const physW = Math.round(d.bounds.width * scale)const physH = Math.round(d.bounds.height * scale)const resolution = `${physW}×${physH}`++ // Positional tag so users can tell which entry is which physical panel:+ // non-primary displays on the same row as the primary are tagged with the+ // localized side they sit on ("Display 2 · Right · 2560×1440").+ let positionTag = ''+ if (!isPrimary) {+ const sameRow =+ Math.abs(d.bounds.y - primary.bounds.y) <= Math.max(primary.bounds.height, d.bounds.height) / 2+ if (sameRow) {+ positionTag = ` · ${sideWord(d.bounds.x > primary.bounds.x ? 'right' : 'left')}`+ }+ }+return {id: d.id,bounds: { x: d.bounds.x, y: d.bounds.y, width: d.bounds.width, height: d.bounds.height },@@ -767,7 +773,7 @@ export function getDisplayListOptions(): Array<{scaleFactor: scale,isPrimary,isCurrent: d.id === activeId,- label: `${name} ${resolution}`,+ label: `${name}${positionTag} ${resolution}`,name,resolution}@@ -836,90 +842,3 @@ export function setWindowFocusable(focusable: boolean): void {export function focusMainWindow(): void {setWindowFocusable(true)}--/**- * Thin invisible detector window.- *- * It is click-through just like the main window, so when the panel is collapsed- * it does not steal desktop clicks. It no longer drives opening (the cursor- * poll does that). It is kept around as a fallback drag surface and a no-op- * drag-event absorber; its inline script still forwards file drags to the main- * window via `window.edge.setInteractive(true)` should it ever receive one.- */-function getDetectorBounds(g: { x: number; y: number; width: number; height: number }, stickPosition: string): { x: number; y: number; width: number; height: number } {- if (stickPosition === 'top') {- const detWidth = Math.floor(g.width * 0.3)- return { x: g.x + Math.floor((g.width - detWidth) / 2), y: g.y, width: detWidth, height: 1 }- }- const h = g.height- const detHeight = Math.floor(h * 0.3)- const detY = g.y + Math.floor((h - detHeight) / 2)- return { x: g.x, y: detY, width: 1, height: detHeight }-}--export function createDetectorWindow(x: number, y: number, _w: number, h: number): void {- const detBounds = getDetectorBounds({ x, y, width: _w, height: h }, loadSettings().stickPosition)-- detectorWindow = new BrowserWindow({- x: detBounds.x,- y: detBounds.y,- width: detBounds.width,- height: detBounds.height,- show: false,- frame: false,- fullscreenable: false,- maximizable: false,- movable: false,- resizable: false,- transparent: true,- hasShadow: false,- skipTaskbar: true,- alwaysOnTop: true,- backgroundColor: '#00000000',- roundedCorners: false,- focusable: false,- webPreferences: {- preload: join(__dirname, '../preload/index.cjs'),- contextIsolation: true,- nodeIntegration: false,- sandbox: true,- spellcheck: false- }- })-- // Click-through, like the main window. A non-click-through always-on-top- // window here used to swallow all desktop clicks across the hint-bar band- // even though it was only 1px wide (Windows still hit-tests a transparent- // always-on-top BrowserWindow across a minimum footprint). Keeping it- // click-through means the collapsed panel passes clicks through everywhere.- //- // Drag-in is NOT lost: the main-process cursor poll- // (screen.getCursorScreenPoint) reads the OS cursor position every ~16ms- // regardless of mouse events, so it still fires while an OS file drag is in- // progress — the 120ms edge dwell opens the panel and makes the main window- // interactive, and the drop then lands on the main window.- detectorWindow.setIgnoreMouseEvents(true, { forward: false })-- // Layer behind the main panel (lower always-on-top level).- detectorWindow.setAlwaysOnTop(true, 'normal')-- const devDetectorFile = join(__dirname, '../../resources/detector.html')- const detectorFile = existsSync(devDetectorFile) ? devDetectorFile : join(process.resourcesPath, 'detector.html')- if (existsSync(detectorFile)) {- detectorWindow.loadFile(detectorFile)- }-- detectorWindow.once('ready-to-show', () => {- detectorWindow?.showInactive()- })-- detectorWindow.on('close', (e) => {- if (!runtime.quitting) {- e.preventDefault()- }- })-- detectorWindow.on('closed', () => {- detectorWindow = null- })-}diff --git a/electron/main/workAreaCache.ts b/electron/main/workAreaCache.tsnew file mode 100644index 0000000..2cb7af7--- /dev/null+++ b/electron/main/workAreaCache.ts@@ -0,0 +1,77 @@+/**+ * Versioned cache for the stick display's work area.+ *+ * WHY THIS EXISTS+ * ---------------+ * The cursor poll reads this cache ~60x/sec. Historically the cache was a+ * bare rectangle refreshed by (a) a fragile "equals exactly 1920x1080"+ * sentinel each tick and (b) OS display events - but NOT when the user+ * switched the stick display in Settings or the tray. Result: the window+ * moved to the new monitor while edge detection kept measuring against the+ * OLD monitor's origin, producing the classic report "hovering my second+ * screen does nothing; hovering the PRIMARY screen opens the panel on the+ * secondary".+ *+ * Contract of this cache:+ * - Versioned by stick display id: `get(id)` rebuilds automatically when+ * the value was built for a different id (fixes the stale-frame bug).+ * - Last-known-good retention: a failed enumeration NEVER wipes a working+ * rectangle (the poll keeps flying), but the failure is logged loudly+ * instead of being swallowed.+ * - Returns null only when no successful lookup has EVER happened.+ * - O(1) per call; rebuilds happen only on identity change or explicit+ * refresh() - zero recurring cost, zero retained growth.+ */++export interface WorkAreaRect {+ x: number+ y: number+ width: number+ height: number+}++export interface ResolvedWorkArea {+ displayId: number+ workArea: WorkAreaRect+}++export class WorkAreaCache {+ private entry: { id: number | undefined; workArea: WorkAreaRect } | null = null++ constructor(+ /**+ * Resolves the CURRENT work area for the given stick display id+ * (undefined means "no explicit preference -> primary"). Return null+ * when nothing resolvable exists; throw freely - failures are captured.+ */+ private readonly lookup: (displayId: number | undefined) => ResolvedWorkArea | null+ ) {}++ /**+ * Cached read for the given stick id. Rebuilds automatically when the+ * cache is empty or versioned for a different id.+ */+ get(displayId: number | undefined): WorkAreaRect | null {+ if (!this.entry || this.entry.id !== displayId) {+ this.refresh(displayId)+ }+ return this.entry ? this.entry.workArea : null+ }++ /** Force a re-read (display topology events, stick re-resolution). */+ refresh(displayId: number | undefined): void {+ try {+ const resolved = this.lookup(displayId)+ if (resolved && resolved.workArea) {+ this.entry = { id: displayId, workArea: { ...resolved.workArea } }+ }+ } catch (err) {+ console.error('[WorkAreaCache] refresh failed; retaining last-known-good:', err)+ }+ }++ /** Test/diagnostic introspection. */+ get versionedFor(): number | undefined {+ return this.entry?.id+ }+}diff --git a/resources/detector.html b/resources/detector.htmldeleted file mode 100644index e5a540c..0000000--- a/resources/detector.html+++ /dev/null@@ -1,28 +0,0 @@-<!DOCTYPE html>-<html>-<head>- <meta charset="utf-8">- <style>- * { margin: 0; padding: 0; }- html, body { width: 100%; height: 100%; background: transparent; pointer-events: none; overflow: hidden; }- </style>-</head>-<body>- <script>- document.addEventListener('dragenter', function(e) {- if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.indexOf && e.dataTransfer.types.indexOf('Files') >= 0) {- e.preventDefault();- if (window.edge) window.edge.setInteractive(true);- }- });- document.addEventListener('dragover', function(e) {- if (e.dataTransfer && e.dataTransfer.types && e.dataTransfer.types.indexOf && e.dataTransfer.types.indexOf('Files') >= 0) {- e.preventDefault();- }- });- document.addEventListener('drop', function(e) {- e.preventDefault();- });- </script>-</body>-</html>diff --git a/tests/geometry.test.ts b/tests/geometry.test.tsindex 87cc18b..ed5e306 100644--- a/tests/geometry.test.ts+++ b/tests/geometry.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect } from 'vitest'import { computeStickBounds, type DisplayInfo } from '../electron/main/geometry'function makeDisplay(@@ -11,83 +11,115 @@ function makeDisplay(const PRIMARY = makeDisplay(1, 0, 0, 1920, 1040, { isPrimary: true, scaleFactor: 1 })const SECONDARY = makeDisplay(2, 1920, 0, 1920, 1040, { isPrimary: false, scaleFactor: 1 })-describe('computeStickBounds — original tests', () => {+describe('computeStickBounds � original tests', () => {it('sticks to left edge of primary display', () => {- const r = computeStickBounds({ position: 'left', displays: [PRIMARY], windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY], windowWidth: 384 })expect(r.x).toBe(0); expect(r.y).toBe(0); expect(r.displayId).toBe(1)})it('sticks to right edge of secondary display', () => {- const r = computeStickBounds({ position: 'right', displays: [PRIMARY, SECONDARY], displayId: 2, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'right', displays: [PRIMARY, SECONDARY], displayId: 2, windowWidth: 384 })expect(r.x).toBe(3456); expect(r.displayId).toBe(2)})it('falls back to nearest display via currentBounds', () => {- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, SECONDARY], displayId: undefined, currentBounds: { x: 2100, y: 100 }, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, SECONDARY], displayId: undefined, currentBounds: { x: 2100, y: 100 }, windowWidth: 384 })expect(r.displayId).toBe(2)})})-describe('Fix 1 — isPrimary typed property for Tier-4 fallback', () => {+describe('Fix 1 � isPrimary typed property for Tier-4 fallback', () => {it('secondary listed first: still picks primary via isPrimary flag', () => {const secondaryFirst = [SECONDARY, PRIMARY]- const r = computeStickBounds({ position: 'left', displays: secondaryFirst, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: secondaryFirst, windowWidth: 384 })expect(r.displayId).toBe(1)})it('3-display array with primary last still picks correct primary', () => {const mon3 = makeDisplay(3, 3840, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [SECONDARY, mon3, PRIMARY], windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [SECONDARY, mon3, PRIMARY], windowWidth: 384 })expect(r.displayId).toBe(1)})it('no isPrimary flags: falls back to displays[0]', () => {const noFlags = [makeDisplay(10, 0, 0, 1920, 1040), makeDisplay(20, 1920, 0, 1920, 1040)]- const r = computeStickBounds({ position: 'left', displays: noFlags, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: noFlags, windowWidth: 384 })expect(r.displayId).toBe(10)})})-describe('Fix 4 — Tier-2 fuzzy match uses workArea (not bounds)', () => {+describe('Fix 4 � Tier-2 fuzzy match uses workArea (not bounds)', () => {it('matches secondary across reboot when ID changes but workArea is same', () => {const rebooted = makeDisplay(99, 1920, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, rebooted], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, rebooted], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(99)})- it('bounds-vs-workArea mismatch (40px taskbar) fails Tier-2 → falls to primary', () => {+ it('bounds-vs-workArea mismatch (40px taskbar) fails Tier-2 ? falls to primary', () => {const rebooted = makeDisplay(99, 1920, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, rebooted], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1080 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, rebooted], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1080 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(1)})it('tolerates 7px OS jitter in workArea and still matches', () => {const jittered = makeDisplay(99, 1927, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, jittered], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, jittered], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(99)})it('does NOT match when jitter is 9px (exceeds 8px tolerance)', () => {const tooFar = makeDisplay(99, 1929, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, tooFar], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, tooFar], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(1)})it('uses scaleFactor tiebreaker when two monitors share identical workArea', () => {const hiDpi = makeDisplay(10, 1920, 0, 1920, 1040, { scaleFactor: 1.5 })const loDpi = makeDisplay(11, 1920, 0, 1920, 1040, { scaleFactor: 1.0 })- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, hiDpi, loDpi], displayId: 99, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1.5, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, hiDpi, loDpi], displayId: 99, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1.5, windowWidth: 384 })expect(r.displayId).toBe(10)})})-describe('TV mirror regression — combined scenario', () => {+describe('TV mirror regression � combined scenario', () => {it('fresh install: places on Primary even when secondary is listed first', () => {- const r = computeStickBounds({ position: 'left', displays: [SECONDARY, PRIMARY], windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [SECONDARY, PRIMARY], windowWidth: 384 })expect(r.displayId).toBe(1)})it('saved secondary preference survives reboot with new IDs', () => {const newPrimary = makeDisplay(100, 0, 0, 1920, 1040, { isPrimary: true })const newSecondary = makeDisplay(200, 1920, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [newPrimary, newSecondary], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [newPrimary, newSecondary], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(200); expect(r.x).toBe(1920)})it('TV mirror transient ID change: Tier-2 still finds secondary by workArea', () => {const transientSecondary = makeDisplay(999, 1920, 0, 1920, 1040)- const r = computeStickBounds({ position: 'left', displays: [PRIMARY, transientSecondary], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384, windowHeight: 1040 })+ const r = computeStickBounds({ position: 'left', displays: [PRIMARY, transientSecondary], displayId: 2, savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 }, savedScaleFactor: 1, windowWidth: 384 })expect(r.displayId).toBe(999); expect(r.x).toBe(1920)})++ // ── Twin-monitor tie-break (identical geometry AND scale) ────────────────+ // True twins report near-identical workAreas, so geometry cannot separate+ // them; determinism must come from primary preference instead of array order.+ const twinA = { id: 11, workArea: { x: 1920, y: 0, width: 1920, height: 1040 }, bounds: { x: 1920, y: 0, width: 1920, height: 1080 }, scaleFactor: 1, isPrimary: false }+ const twinB = { id: 22, workArea: { x: 1920, y: 0, width: 1920, height: 1040 }, bounds: { x: 1920, y: 0, width: 1920, height: 1080 }, scaleFactor: 1, isPrimary: true }++ it('breaks identical-twin ambiguity by preferring the OS-designated primary', () => {+ const r = computeStickBounds({+ position: 'left',+ displays: [twinA, twinB], // primary listed SECOND+ displayId: undefined,+ savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 },+ savedScaleFactor: 1,+ windowWidth: 384+ })+ expect(r.displayId).toBe(22)+ })++ it('falls back to deterministic first-candidate when twins have no primary flag', () => {+ const a = { ...twinA }+ const b = { ...twinB, isPrimary: false }+ const r = computeStickBounds({+ position: 'left',+ displays: [a, b],+ displayId: undefined,+ savedWorkArea: { x: 1920, y: 0, width: 1920, height: 1040 },+ savedScaleFactor: 1,+ windowWidth: 384+ })+ expect(r.displayId).toBe(11)+ })})diff --git a/tests/stickProbeScenarios.test.ts b/tests/stickProbeScenarios.test.tsnew file mode 100644index 0000000..6f99ced--- /dev/null+++ b/tests/stickProbeScenarios.test.ts@@ -0,0 +1,328 @@+/**+ * Virtual Multi-Display Simulation Suite+ * ======================================+ *+ * The user cannot attach a second monitor, so this suite reconstructs the+ * ENTIRE production decision pipeline in software and replays real-world+ * hardware scenarios against it:+ *+ * virtual displays ──► WorkAreaCache (REAL production class)+ * ──► computeStickBounds (REAL geometry.ts)+ * ──► probeStickEdge (REAL poll math, extracted)+ *+ * Every scenario below maps 1:1 to a physical situation. The headline case+ * is the exact bug a user reported: "configured on my second monitor,+ * hovering ITS edge does nothing - but hovering the PRIMARY screen's edge+ * pops the panel open on the secondary."+ */+import { describe, expect, it, vi } from 'vitest'+import { WorkAreaCache } from '../electron/main/workAreaCache'+import { computeStickBounds } from '../electron/main/geometry'+import { probeStickEdge, isNearProximity, FAST_POLL_PROXIMITY_PX } from '../electron/main/stickProbe'++/* ------------------------------------------------------------------ */+/* Virtual desktop simulator */+/* ------------------------------------------------------------------ */++interface VDisplay {+ id: number+ x: number; y: number; width: number; height: number+ scaleFactor: number+ isPrimary: boolean+}++function display(id: number, x: number, y: number, width: number, height: number, isPrimary = false, scaleFactor = 1): VDisplay {+ return { id, x, y, width, height, scaleFactor, isPrimary }+}++/** Work area = bounds minus a 40px taskbar at the bottom (Windows default). */+const workAreaOf = (d: VDisplay) => ({ x: d.x, y: d.y, width: d.width, height: d.height - 40 })++class VirtualDesktop {+ displays: VDisplay[]+ primaryId: number++ constructor(displays: VDisplay[]) {+ this.displays = displays+ this.primaryId = displays.find(d => d.isPrimary)!.id+ }++ getAllDisplays() {+ return this.displays.map(d => ({+ id: d.id,+ bounds: { x: d.x, y: d.y, width: d.width, height: d.height },+ workArea: workAreaOf(d),+ scaleFactor: d.scaleFactor,+ isPrimary: d.id === this.primaryId+ }))+ }++ getPrimaryDisplay() {+ return this.getAllDisplays().find(d => d.isPrimary)!+ }+}++/**+ * Production-faithful stick controller: mirrors the exact call sequence of+ * window.ts (getStickGeometry -> setStickDisplayId/refresh -> _pollTick).+ */+class StickController {+ cache: WorkAreaCache+ currentStickDisplayId: number | undefined+ windowBounds: { x: number; y: number } | null = null+ lastProbe: ReturnType<typeof probeStickEdge> | null = null+ stickPosition: 'left' | 'right' = 'left'+ hotZoneWidth = 3+ windowWidth = 384++ constructor(public desktop: VirtualDesktop) {+ this.cache = new WorkAreaCache((displayId) => {+ const all = this.desktop.getAllDisplays()+ const stick = all.find(d => d.id === displayId) ?? this.desktop.getPrimaryDisplay()+ return stick?.workArea ? { displayId: stick.id, workArea: stick.workArea } : null+ })+ }++ /** Mirrors getStickGeometry(): resolve target display, move window, re-version cache. */+ applyStickDisplay(displayId: number | undefined) {+ const result = computeStickBounds({+ position: this.stickPosition,+ displays: this.desktop.getAllDisplays(),+ displayId,+ savedWorkArea: undefined,+ savedScaleFactor: undefined,+ windowWidth: this.windowWidth,+ currentBounds: this.windowBounds ?? undefined+ })+ // Simulated setBounds happens here in production; then the identity ++ // cache refresh that constitute THE FIX:+ this.currentStickDisplayId = result.resolvedDisplay.id+ this.windowBounds = { x: result.x, y: result.y }+ this.cache.refresh(result.resolvedDisplay.id)+ return result+ }++ /** Mirrors one _pollTick against a global cursor point. */+ tick(globalCursor: { x: number; y: number }) {+ const wa = this.cache.get(this.currentStickDisplayId)+ if (!wa) { this.lastProbe = null; return null }+ this.lastProbe = probeStickEdge({+ cursor: globalCursor,+ workArea: wa,+ stickPosition: this.stickPosition,+ hotZoneWidth: this.hotZoneWidth+ })+ return this.lastProbe+ }++ get edgeTriggered(): boolean {+ return this.lastProbe?.inEdge === true+ }++ /** What the OLD buggy code computed: window on new screen, cache stuck on old id. */+ buggyLegacyTick(globalCursor: { x: number; y: number }, staleWorkArea: { x: number; y: number; width: number; height: number }) {+ return probeStickEdge({+ cursor: globalCursor,+ workArea: staleWorkArea,+ stickPosition: this.stickPosition,+ hotZoneWidth: this.hotZoneWidth+ })+ }+}++/* ------------------------------------------------------------------ */+/* Shared topology: laptop + external side-by-side */+/* ------------------------------------------------------------------ */++function sideBySideDesktop(): VirtualDesktop {+ return new VirtualDesktop([+ display(1, 0, 0, 1920, 1080, true), // primary+ display(2, 1920, 0, 2560, 1440) // secondary to the right+ ])+}++describe('SIMULATION — reported bug: hover secondary does nothing, hover primary opens panel on secondary', () => {+ it('REPRODUCES the legacy defect first (proves the test can catch it)', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)++ // Legacy frame: window moved, but cache still held PRIMARY's origin.+ const stalePrimaryFrame = { x: 0, y: 0, width: 1920, height: 1040 }++ // Hover secondary's left edge (global x=1921):+ const onSecondary = ctl.buggyLegacyTick({ x: 1921, y: 500 }, stalePrimaryFrame)+ expect(onSecondary.inEdge).toBe(false) // ← user's "does not appear"++ // Hover primary's left edge (global x=1):+ const onPrimary = ctl.buggyLegacyTick({ x: 1, y: 500 }, stalePrimaryFrame)+ expect(onPrimary.inEdge).toBe(true) // ← user's "appears on secondary"+ })++ it('FIXED: after switching sticks to the secondary, ITS edge triggers and the primary never does', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.stickPosition = 'left'+ ctl.applyStickDisplay(2)++ // Secondary's left edge — global cursor just inside its left boundary.+ expect(ctl.tick({ x: 1921, y: 500 })!.inEdge).toBe(true)+ expect(ctl.tick({ x: 1922, y: 700 })!.inEdge).toBe(true)+ // One pixel OUTSIDE the trigger band: no trigger.+ expect(ctl.tick({ x: 1925, y: 500 })!.inEdge).toBe(false)++ // Primary's interior must be completely inert now.+ expect(ctl.tick({ x: 1, y: 500 })!.inEdge).toBe(false)+ expect(ctl.tick({ x: 0, y: 900 })!.inEdge).toBe(false)+ expect(ctl.tick({ x: 960, y: 540 })!.inEdge).toBe(false)++ // DOCUMENTED SEAM BEHAVIOR: the two monitors are physically adjacent, and+ // the virtual desktop is continuous. The production contract tolerates up+ // to 30px of cross-seam overshoot so the open shelf survives nudging+ // across the boundary — identical to pre-fix behavior and physically+ // indistinguishable from the edge itself.+ expect(ctl.tick({ x: 1919, y: 500 })!.inEdge).toBe(true) // 1px into primary = seam+ expect(ctl.tick({ x: 1890, y: 500 })!.inEdge).toBe(true) // exactly -30 = last buffered px+ expect(ctl.tick({ x: 1889, y: 500 })!.inEdge).toBe(false) // -31 = beyond seam buffer+ })++ it('client coordinates are translated into SECONDARY space (renderer zones stay valid)', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)+ const p = ctl.tick({ x: 1921, y: 613 })!+ expect(p.clientX).toBe(1) // 1px into the secondary+ expect(p.clientY).toBe(613) // untouched vertical+ })++ it('switching BACK to primary restores primary-edge detection instantly', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)+ ctl.applyStickDisplay(1)++ expect(ctl.tick({ x: 2, y: 400 })!.inEdge).toBe(true)+ expect(ctl.tick({ x: 1921, y: 400 })!.inEdge).toBe(false)+ })+})++describe('SIMULATION — right-stick on the secondary', () => {+ it('triggers only at the secondary’s RIGHT edge with correct distance math', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.stickPosition = 'right'+ ctl.applyStickDisplay(2)++ const secRight = 1920 + 2560 // 4480+ const inside = ctl.tick({ x: secRight - 2, y: 300 })!+ expect(inside.inEdge).toBe(true)+ expect(inside.distFromEdge).toBe(2)++ const outside = ctl.tick({ x: secRight - 10, y: 300 })!+ expect(outside.inEdge).toBe(false)++ // Primary's right edge (x=1919) is far from OUR edge: inert.+ expect(ctl.tick({ x: 1919, y: 300 })!.inEdge).toBe(false)+ })+})++describe('SIMULATION — vertically stacked secondary', () => {+ it('detects its own edge with correct Y translation', () => {+ const desktop = new VirtualDesktop([+ display(1, 0, 0, 1920, 1080, true),+ display(2, 0, 1080, 1920, 1440) // directly BELOW the primary+ ])+ const ctl = new StickController(desktop)+ ctl.applyStickDisplay(2)++ const p = ctl.tick({ x: 1, y: 1090 })!+ expect(p.inEdge).toBe(true)+ expect(p.clientX).toBe(1)+ expect(p.clientY).toBe(10) // 1090 - 1080+ })+})++describe('SIMULATION — live topology changes', () => {+ it('monitor physically relocated: OS event refreshes cache, new coordinates detect', () => {+ const desktop = sideBySideDesktop()+ const ctl = new StickController(desktop)+ ctl.applyStickDisplay(2)+ expect(ctl.tick({ x: 1921, y: 100 })!.inEdge).toBe(true)++ // User rearranges: secondary pushed further right (e.g. third monitor added).+ desktop.displays[1] = display(2, 3840, 0, 2560, 1440)+ ctl.desktop = desktop+ ctl.cache.refresh(2) // what handleDisplayChange/updateCachedWorkArea performs++ expect(ctl.tick({ x: 3841, y: 100 })!.inEdge).toBe(true) // new location works+ expect(ctl.tick({ x: 1921, y: 100 })!.inEdge).toBe(false) // old spot no longer an edge of stick+ })++ it('stick monitor unplugged: geometry pass resolves primary, poll relocates without crashing', () => {+ const desktop = sideBySideDesktop()+ const ctl = new StickController(desktop)+ ctl.applyStickDisplay(2)++ // Unplug display 2 entirely.+ desktop.displays = desktop.displays.filter(d => d.id !== 2)++ // PRODUCTION SEQUENCE (window.ts): 'display-removed' -> repositionWindow+ // -> getStickGeometry resolves with display 2 gone; Tier-4 falls back to+ // primary and the tail of getStickGeometry re-versions the poll cache.+ ctl.applyStickDisplay(undefined)++ expect(ctl.currentStickDisplayId).toBe(1)+ expect(ctl.tick({ x: 1, y: 100 })!.inEdge).toBe(true) // primary edge responds+ expect(ctl.tick({ x: 1921, y: 100 })!.inEdge).toBe(false) // dead monitor's spot inert+ })++ it('enumeration THROW mid-session retains last-known-good frame (poll never dies)', () => {+ let explode = false+ const desktop = sideBySideDesktop()+ const ctl = new StickController(desktop)+ // Replace lookup internals via subclassing the cache used by the controller.+ const throwingCache = new WorkAreaCache(() => {+ if (explode) throw new Error('topology enumeration crashed')+ const all = desktop.getAllDisplays()+ const s = all.find(d => d.id === ctl.currentStickDisplayId) ?? desktop.getPrimaryDisplay()+ return { displayId: s.id, workArea: s.workArea }+ })+ ctl.cache = throwingCache+ ctl.applyStickDisplay(2)+ expect(ctl.tick({ x: 1921, y: 50 })!.inEdge).toBe(true)++ explode = true+ const stillAlive = ctl.tick({ x: 1922, y: 60 })+ expect(stillAlive!.inEdge).toBe(true) // last-known-good keeps detection alive+ })+})++describe('SIMULATION — restart equivalence & garbage filtering', () => {+ it('fresh app launch with persisted secondary preference detects immediately on first tick', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.currentStickDisplayId = 2 // restored from settings.json, no switch performed+ expect(ctl.tick({ x: 1921, y: 250 })!.inEdge).toBe(true) // lazy versioned build+ })++ it('garbage coordinates from Windows are filtered before triggering', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)+ expect(ctl.tick({ x: -80000, y: 5 })!.garbage).toBe(true)+ expect(ctl.edgeTriggered).toBe(false)+ })++ it('custom hot-zone thickness is honored on the correct display', () => {+ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)+ ctl.hotZoneWidth = 7+ expect(ctl.tick({ x: 1927, y: 10 })!.inEdge).toBe(true)+ expect(ctl.tick({ x: 1928, y: 10 })!.inEdge).toBe(false)+ })+})++describe('SIMULATION — adaptive proximity thresholds (unchanged feel)', () => {+ it('fast-poll zone boundary sits exactly at 450px on either stick side', () => {+ expect(isNearProximity(FAST_POLL_PROXIMITY_PX)).toBe(true)+ expect(isNearProximity(FAST_POLL_PROXIMITY_PX + 1)).toBe(false)++ const ctl = new StickController(sideBySideDesktop())+ ctl.applyStickDisplay(2)+ expect(isNearProximity(ctl.tick({ x: 1921 + FAST_POLL_PROXIMITY_PX - 1, y: 0 })!.distFromEdge)).toBe(true)+ expect(isNearProximity(ctl.tick({ x: 1921 + FAST_POLL_PROXIMITY_PX + 5, y: 0 })!.distFromEdge)).toBe(false)+ })+})diff --git a/tests/workAreaCache.test.ts b/tests/workAreaCache.test.tsnew file mode 100644index 0000000..0a83bec--- /dev/null+++ b/tests/workAreaCache.test.ts@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { WorkAreaCache, type ResolvedWorkArea, type WorkAreaRect } from '../electron/main/workAreaCache'++const wa = (x: number, width = 1920): WorkAreaRect => ({ x, y: 0, width, height: 1040 })++describe('WorkAreaCache — versioned stick-display cache', () => {+ let errSpy: ReturnType<typeof vi.spyOn>++ beforeEach(() => {+ errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ })++ afterEach(() => {+ errSpy.mockRestore()+ })++ it('builds on first read for the requested stick id', () => {+ const look = vi.fn((id?: number): ResolvedWorkArea | null =>+ id === 2 ? { displayId: 2, workArea: wa(1920) } : { displayId: 1, workArea: wa(0) })+ const cache = new WorkAreaCache(look)++ expect(cache.get(2)).toEqual(wa(1920))+ expect(look).toHaveBeenCalledTimes(1)+ expect(cache.versionedFor).toBe(2)+ })++ it('REBUILDS when the stick id changes — the fix for stale cross-monitor detection', () => {+ const look = vi.fn((id?: number): ResolvedWorkArea | null =>+ id === 2 ? { displayId: 2, workArea: wa(3840) } : { displayId: 1, workArea: wa(0) })+ const cache = new WorkAreaCache(look)++ const primaryFrame = cache.get(1)+ const secondaryFrame = cache.get(2)++ expect(primaryFrame).toEqual(wa(0))+ expect(secondaryFrame).toEqual(wa(3840))+ expect(look).toHaveBeenCalledTimes(2) // once per distinct id+ })++ it('serves repeat reads of the SAME id with zero extra lookups', () => {+ const look = vi.fn(() => ({ displayId: 5, workArea: wa(0) }))+ const cache = new WorkAreaCache(look)+ cache.get(5); cache.get(5); cache.get(5)+ expect(look).toHaveBeenCalledTimes(1)+ })++ it('retains LAST-KNOWN-GOOD rectangle when enumeration throws', () => {+ let shouldThrow = false+ const cache = new WorkAreaCache((id) => {+ if (shouldThrow) throw new Error('display topology exploded')+ return { displayId: 7, workArea: wa(100) }+ })+ const good = cache.get(7)+ expect(good).toEqual(wa(100))++ shouldThrow = true+ // Same id: no rebuild attempted -> cached value survives.+ expect(cache.get(7)).toEqual(wa(100))++ // Different id forces a rebuild attempt; failure keeps the old frame alive.+ expect(cache.get(9)).toEqual(wa(100))+ expect(errSpy).toHaveBeenCalled()+ })++ it('returns null only before the FIRST successful lookup', () => {+ const cache = new WorkAreaCache(() => null)+ expect(cache.get(3)).toBeNull()+ expect(errSpy).not.toHaveBeenCalled() // null result is not an error+ expect(cache.versionedFor).toBeUndefined()+ })++ it('explicit refresh() re-reads even for an unchanged id (topology events)', () => {+ let originX = 0+ const cache = new WorkAreaCache(() => ({ displayId: 4, workArea: wa(originX) }))+ expect(cache.get(4)).toEqual(wa(0))++ originX = -1920 // monitor physically moved to the left side+ cache.refresh(4)+ expect(cache.get(4)).toEqual(wa(-1920))+ })++ it('ignores malformed lookup results instead of caching them', () => {+ let payload: ResolvedWorkArea | null = { displayId: 8, workArea: undefined as unknown as WorkAreaRect }+ const cache = new WorkAreaCache(() => payload)+ expect(cache.get(8)).toBeNull()++ payload = { displayId: 8, workArea: wa(42) }+ expect(cache.get(8)).toEqual(wa(42))+ })+})