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(store): align AppX launch-at-login and file interop with the GitHub exe
Deepender251e99facc1f1a
diff --git a/electron/clipboard/formats.ts b/electron/clipboard/formats.tsindex fcdaae4..fd416c9 100644--- a/electron/clipboard/formats.ts+++ b/electron/clipboard/formats.ts@@ -32,8 +32,9 @@ export function getClipboardSequenceNumber(): number {}return 0}-import { getSystemPowerShellPath } from '../main/powershell'+import { getSystemPowerShellPath, getWritableCwd } from '../main/powershell'import { filterValidPaths } from '../main/pathValidation'+import { isStoreBuild } from '../main/config'const execFileAsync = promisify(execFile)@@ -70,7 +71,7 @@ async function readFileListAsync(): Promise<string[] | null> {'-Command','Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::GetFileDropList()'],- { encoding: 'utf8', timeout: 2000 }+ { encoding: 'utf8', timeout: 2000, windowsHide: true, ...(isStoreBuild() ? { cwd: getWritableCwd() } : {}) })if (stdout) {const paths = filterValidPaths(stdout.split(/\r?\n/).map((l) => l.trim()))diff --git a/electron/main/config.ts b/electron/main/config.tsindex f15389b..b38304c 100644--- a/electron/main/config.ts+++ b/electron/main/config.ts@@ -1,4 +1,7 @@/** App-wide constants and environment flags for the main process. */+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { app } from 'electron'/** Mutable runtime flags (kept separate from the frozen config object). */export const runtime = {@@ -6,6 +9,36 @@ export const runtime = {quitting: false}+/**+ * StartupTask Id declared in resources/appx/startup-extensions.xml.+ * Must stay in sync with that file.+ */+export const STORE_STARTUP_TASK_ID = 'EdgeDropStartup'++/**+ * True when running as the Microsoft Store / MSIX package.+ * The GitHub NSIS .exe never sets these signals.+ */+export function isStoreBuild(): boolean {+ if (process.windowsStore || process.env.APP_BUILD_TARGET === 'store') {+ return true+ }+ try {+ if (app.isPackaged) {+ const pkgPath = join(app.getAppPath(), 'package.json')+ if (existsSync(pkgPath)) {+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { buildTarget?: string }+ if (pkg.buildTarget === 'store') {+ return true+ }+ }+ }+ } catch {+ /* unpackaged tests / app-not-ready */+ }+ return false+}+export const APP_CONFIG = {appName: 'Edge-Drop',/** Custom protocol used to serve local image files to the renderer securely. */diff --git a/electron/main/drag.ts b/electron/main/drag.tsindex d54d9e7..cf3f960 100644--- a/electron/main/drag.ts+++ b/electron/main/drag.ts@@ -15,9 +15,9 @@*/import { app, nativeImage, type WebContents } from 'electron'import { Resvg } from '@resvg/resvg-js'-import { copyFileSync, writeFileSync, existsSync } from 'node:fs'+import { copyFileSync, mkdirSync, writeFileSync, existsSync } from 'node:fs'import { join, extname } from 'node:path'-import { PATHS } from '../store/paths'+import { getUnpackagedTempDir, toUnpackagedFilePaths } from '../store/paths'import type { DragRequest, ItemData } from '../../shared/types'import { getStore } from './state'import { getFileKind } from '../../src/lib/fileType'@@ -88,12 +88,14 @@ interface Staged {/** Resolve the item to a concrete file path to hand to the OS. */export function stageDragFile(data: ItemData, capturedAt?: number): Staged | null {- const temp = PATHS.tempDir()+ const temp = getUnpackagedTempDir()+ mkdirSync(temp, { recursive: true })switch (data.kind) {case 'files': {const real = data.paths.filter((p) => existsSync(p))if (!real.length) return null- return { file: real[0], files: real }+ const exposed = toUnpackagedFilePaths(real)+ return { file: exposed[0], files: exposed }}case 'image': {const src = getStore().getImagePath(data.imageId, data.ext)diff --git a/electron/main/index.ts b/electron/main/index.tsindex 4cc7a54..3b179ef 100644--- a/electron/main/index.ts+++ b/electron/main/index.ts@@ -13,7 +13,9 @@ import { APP_CONFIG, runtime } from './config'import { ensureDirs, cleanTemp, 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, syncLoginItemSettings } from './ipc'+import { registerIpc, registerSendListeners } from './ipc'+import { reconcileLaunchAtLoginOnStartup } from './loginItems'+import { isStoreBuild } from './config'import { prewarmDragIcons } from './drag'import { initState, getWatcher, loadSettings, saveSettings, pushState, stopStateTimers, getStore } from './state'import { initAutoUpdater } from './updater'@@ -84,8 +86,11 @@ app.on('before-quit', () => {})app.whenReady().then(() => {- // Set App User Model ID so native notifications are branded as "Edge-Drop" on Windows- app.setAppUserModelId('com.edgedrop.app')+ // GitHub NSIS needs an explicit AUMID. Store packages already have one from+ // the AppX identity; overriding it breaks toasts and taskbar grouping.+ if (!isStoreBuild()) {+ app.setAppUserModelId('com.edgedrop.app')+ }ensureDirs()cleanTemp()@@ -122,8 +127,12 @@ app.whenReady().then(() => {}, 2000)}setHotZoneWidth(settings.hotZoneWidth || 3)-- syncLoginItemSettings(settings.launchAtLogin)++ void reconcileLaunchAtLoginOnStartup().then((reconciled) => {+ pushState.settings(reconciled)+ }).catch((err) => {+ console.error('[Main] Failed to reconcile launch-at-login with Windows:', err)+ })registerIncognitoApplier((v) => getWatcher().setPaused(v))getWatcher().setPaused(settings.incognito)pushState.settings(settings)diff --git a/electron/main/ipc.ts b/electron/main/ipc.tsindex cc97cb5..ee46262 100644--- a/electron/main/ipc.ts+++ b/electron/main/ipc.ts@@ -6,10 +6,9 @@* is a compile-time error rather than a runtime one.*/import { app, ipcMain, clipboard, nativeImage, shell, net } from 'electron'-import { existsSync, readFileSync } from 'node:fs'-import { join } from 'node:path'+import { existsSync } from 'node:fs'import { execFile } from 'node:child_process'-import { psHost, getSystemPowerShellPath } from './powershell'+import { psHost, getSystemPowerShellPath, getWritableCwd } from './powershell'import { filterValidPaths, isExistingFilePath } from './pathValidation'import { type InvokeMap, type InvokeChannel, type SendMap, type SendChannel } from '../../shared/ipc'import { getStore, loadSettings, saveSettings, pushState, addFiles, getWatcher } from './state'@@ -22,6 +21,11 @@ import { clipboardSignature } from '../clipboard/formats'import type { ItemData, MergeResult } from '../../shared/types'import { quitAndInstallUpdate, checkForUpdatesManual, startUpdateDownload, syncAutoUpdaterState } from './updater'import { createId } from '../store/ids'+import { isStoreBuild } from './config'+import { applyLaunchAtLogin, refreshLaunchAtLoginFromOs } from './loginItems'+import { toUnpackagedFilePath, toUnpackagedFilePaths } from '../store/paths'++export { isStoreBuild }/*** Returns true if the current system clipboard content matches the given item data.@@ -64,7 +68,7 @@ function simulatePaste(): void {'-NonInteractive','-Command',"Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('^v')"- ], (fallbackErr) => {+ ], { windowsHide: true, ...(isStoreBuild() ? { cwd: getWritableCwd() } : {}) }, (fallbackErr) => {if (fallbackErr) console.error('[Main] simulatePaste fallback error:', fallbackErr)})})@@ -83,7 +87,7 @@ function simulatePaste(): void {* Paths are base64-encoded so any character (spaces, quotes, Unicode) is safe.*/async function writeFileListToClipboard(rawPaths: string[]): Promise<void> {- const validPaths = filterValidPaths(rawPaths)+ const validPaths = toUnpackagedFilePaths(filterValidPaths(rawPaths))if (process.platform === 'win32' && validPaths.length > 0) {try {const addLines = validPaths@@ -147,49 +151,12 @@ function handle<C extends InvokeChannel>(ipcMain.handle(channel, (_e, ...args) => fn(...(args as InvokeMap[C]['args'])))}-/** Detects whether the app is packaged and running as a Microsoft Store (MSIX) build. */-export function isStoreBuild(): boolean {- if (process.windowsStore || process.env.APP_BUILD_TARGET === 'store') {- return true- }- try {- if (app.isPackaged) {- const pkgPath = join(app.getAppPath(), 'package.json')- if (existsSync(pkgPath)) {- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))- if (pkg.buildTarget === 'store') {- return true- }- }- }- } catch {- /* ignore */- }- return false-}--/** Synchronizes launch at login settings with Windows Registry, resolving path drift after updates. */-export function syncLoginItemSettings(launchAtLogin?: boolean): void {- if (!app.isPackaged) return+/** Apply launch-at-login to the OS and return the state Windows actually kept. */+export async function syncLoginItemSettings(launchAtLogin?: boolean): Promise<void> {const wantLaunch = launchAtLogin ?? loadSettings().launchAtLogin- try {- const exePath = app.getPath('exe')- if (wantLaunch) {- app.setLoginItemSettings({- openAtLogin: true,- path: exePath,- args: ['--hidden'],- name: 'Edge-Drop'- })- } else {- app.setLoginItemSettings({- openAtLogin: false,- path: exePath,- name: 'Edge-Drop'- })- }- } catch (err) {- console.error('[IPC] Failed to sync login item settings:', err)+ const result = await applyLaunchAtLogin(wantLaunch)+ if (!result.ok) {+ console.error('[IPC] launch-at-login apply did not stick. wanted=', wantLaunch, 'result=', result)}}@@ -556,7 +523,11 @@ export function registerIpc(): void {return success})- handle('settings:update', (patch) => {+ handle('startup:refresh', async () => {+ return refreshLaunchAtLoginFromOs()+ })++ handle('settings:update', async (patch) => {// When the user explicitly picks a display, also persist its geometry so// the next reboot can re-identify the monitor via fuzzy bounds matching// even after Windows re-assigns numeric display IDs.@@ -576,9 +547,17 @@ export function registerIpc(): void {}}}- const next = saveSettings(enrichedPatch)+ let next = saveSettings(enrichedPatch)if (patch.launchAtLogin !== undefined) {- syncLoginItemSettings(next.launchAtLogin)+ const applied = await applyLaunchAtLogin(patch.launchAtLogin)+ if (applied.enabled !== next.launchAtLogin) {+ next = saveSettings({ launchAtLogin: applied.enabled })+ }+ if (applied.blockedByUser && patch.launchAtLogin) {+ toast('Windows blocked launch at login. Enable Edge-Drop in Settings → Apps → Startup.', 'info')+ } else if (!applied.ok) {+ toast('Could not update launch at login.', 'error')+ }}if (patch.hotZoneWidth !== undefined) {setHotZoneWidth(patch.hotZoneWidth)@@ -725,7 +704,7 @@ export async function writeItemToClipboard(data: ItemData): Promise<void> {const paths: string[] = []for (const img of dto.data.images) {const src = getStore().getImagePath(img.imageId, img.ext)- if (existsSync(src)) paths.push(src)+ if (existsSync(src)) paths.push(toUnpackagedFilePath(src))}if (paths.length > 0) {// For multi-image collections, write all file refs atomically.diff --git a/electron/main/loginItems.ts b/electron/main/loginItems.tsnew file mode 100644index 0000000..af118e8--- /dev/null+++ b/electron/main/loginItems.ts@@ -0,0 +1,178 @@+/**+ * Launch-at-login.+ *+ * GitHub NSIS: Electron Run keys. Older builds used different value names, so+ * enable/disable clears every name Task Manager might still list.+ *+ * Store / AppX: Windows.ApplicationModel.StartupTask only —+ * getStatus / enable (RequestEnableAsync) / disable. Same API as+ * electron-winstore-auto-launch. Electron setLoginItemSettings is not used.+ */+import { app } from 'electron'+import { isStoreBuild } from './config'+import { loadSettings, saveSettings } from '../store/settings'+import type { Settings } from '../../shared/types'+import { disable, enable, getStatus, StartupTaskState } from './storeStartup'++export { StartupTaskState }++/** Historical + current Run-key names written by this app. */+export const GITHUB_LOGIN_ITEM_NAMES = [+ 'Edge-Drop',+ 'com.edgedrop.app',+ 'electron.app.Edge-Drop'+] as const++export const CANONICAL_LOGIN_ITEM_NAME = 'Edge-Drop'++export interface LaunchAtLoginResult {+ enabled: boolean+ blockedByUser: boolean+ ok: boolean+}++export function isOurLoginExe(candidate: string | undefined, exePath: string): boolean {+ if (!candidate) return false+ const a = candidate.replace(/\//g, '\\').toLowerCase()+ const b = exePath.replace(/\//g, '\\').toLowerCase()+ return a === b+}++function resultFromState(state: number | null, wantEnabled?: boolean): LaunchAtLoginResult {+ if (state === null) {+ if (wantEnabled === undefined) {+ return { enabled: loadSettings().launchAtLogin, blockedByUser: false, ok: false }+ }+ return { enabled: !wantEnabled, blockedByUser: false, ok: false }+ }+ const enabled = state === StartupTaskState.Enabled || state === StartupTaskState.EnabledByPolicy+ return {+ enabled,+ blockedByUser: state === StartupTaskState.DisabledByUser || state === StartupTaskState.DisabledByPolicy,+ ok: wantEnabled === undefined ? true : enabled === wantEnabled+ }+}++function readGithubLaunchAtLogin(): LaunchAtLoginResult {+ const exePath = app.getPath('exe')+ const seen = app.getLoginItemSettings({+ path: exePath,+ args: ['--hidden']+ })+ const items = seen.launchItems ?? []+ const ours = items.filter((item) => isOurLoginExe(item.path, exePath))+ const enabled = ours.some((item) => item.enabled) || (!!seen.executableWillLaunchAtLogin && ours.length > 0)+ return {+ enabled,+ blockedByUser: ours.some((item) => !item.enabled) && !enabled,+ ok: true+ }+}++function applyGithubLaunchAtLogin(wantLaunch: boolean): LaunchAtLoginResult {+ const exePath = app.getPath('exe')+ const extraNames = new Set<string>(GITHUB_LOGIN_ITEM_NAMES)+ try {+ const items = app.getLoginItemSettings({ path: exePath }).launchItems ?? []+ for (const item of items) {+ if (item.name && isOurLoginExe(item.path, exePath)) extraNames.add(item.name)+ }+ } catch {+ /* ignore */+ }++ for (const name of extraNames) {+ app.setLoginItemSettings({+ openAtLogin: false,+ path: exePath,+ name+ })+ }++ if (wantLaunch) {+ app.setLoginItemSettings({+ openAtLogin: true,+ path: exePath,+ args: ['--hidden'],+ name: CANONICAL_LOGIN_ITEM_NAME,+ enabled: true+ })+ }++ return readGithubLaunchAtLogin()+}++export async function readLaunchAtLogin(): Promise<LaunchAtLoginResult> {+ if (!app.isPackaged) {+ return { enabled: loadSettings().launchAtLogin, blockedByUser: false, ok: true }+ }+ if (isStoreBuild()) {+ return resultFromState(await getStatus())+ }+ return readGithubLaunchAtLogin()+}++let appliesInFlight = 0++export async function applyLaunchAtLogin(wantLaunch: boolean): Promise<LaunchAtLoginResult> {+ appliesInFlight+++ try {+ if (!app.isPackaged) {+ return { enabled: wantLaunch, blockedByUser: false, ok: true }+ }+ if (isStoreBuild()) {+ try {+ const state = wantLaunch ? await enable() : await disable()+ return resultFromState(state, wantLaunch)+ } catch (err) {+ console.error('[LoginItems] Store StartupTask update failed:', err)+ return { enabled: !wantLaunch, blockedByUser: false, ok: false }+ }+ }+ try {+ const result = applyGithubLaunchAtLogin(wantLaunch)+ return { ...result, ok: result.enabled === wantLaunch }+ } catch (err) {+ console.error('[LoginItems] GitHub Run-key update failed:', err)+ return { enabled: !wantLaunch, blockedByUser: false, ok: false }+ }+ } finally {+ appliesInFlight--+ }+}++export async function reconcileLaunchAtLoginOnStartup(): Promise<Settings> {+ const settings = loadSettings()+ if (!app.isPackaged) return settings++ const os = await readLaunchAtLogin()+ if (!os.ok) return settings++ if (settings.launchAtLogin === false && os.enabled) {+ const applied = await applyLaunchAtLogin(false)+ if (applied.enabled !== settings.launchAtLogin) {+ return saveSettings({ launchAtLogin: applied.enabled })+ }+ return settings+ }++ if (settings.launchAtLogin === true && !os.enabled) {+ return saveSettings({ launchAtLogin: false })+ }++ if (settings.launchAtLogin && os.enabled && !isStoreBuild()) {+ applyGithubLaunchAtLogin(true)+ }++ return loadSettings()+}++export async function refreshLaunchAtLoginFromOs(): Promise<Settings> {+ if (appliesInFlight > 0) return loadSettings()+ const os = await readLaunchAtLogin()+ if (!os.ok) return loadSettings()+ if (os.enabled !== loadSettings().launchAtLogin) {+ return saveSettings({ launchAtLogin: os.enabled })+ }+ return loadSettings()+}diff --git a/electron/main/powershell.ts b/electron/main/powershell.tsindex 8804bd3..5d19223 100644--- a/electron/main/powershell.ts+++ b/electron/main/powershell.ts@@ -1,10 +1,20 @@import { spawn, ChildProcess } from 'node:child_process'+import { existsSync } from 'node:fs'+import { isStoreBuild } from './config'export function getSystemPowerShellPath(): string {const systemRoot = process.env.SystemRoot || 'C:\\Windows'return `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}+/** Writable cwd so packaged (WindowsApps) launches don't inherit a read-only working directory. */+export function getWritableCwd(): string {+ for (const candidate of [process.env.TEMP, process.env.TMP, process.env.USERPROFILE]) {+ if (candidate && existsSync(candidate)) return candidate+ }+ return 'C:\\Windows\\Temp'+}+class PersistentPowerShell {private proc: ChildProcess | null = nullprivate queue: { command: string; resolve: () => void; reject: (err: Error) => void }[] = []@@ -23,7 +33,8 @@ class PersistentPowerShell {try {this.proc = spawn(this.powershellPath, ['-NoProfile', '-NonInteractive', '-Command', '-'], {stdio: ['pipe', 'pipe', 'ignore'],- windowsHide: true+ windowsHide: true,+ ...(isStoreBuild() ? { cwd: getWritableCwd() } : {})})this.proc.stdout?.on('data', (data) => {diff --git a/electron/main/state.ts b/electron/main/state.tsindex ccb040e..c402f2b 100644--- a/electron/main/state.ts+++ b/electron/main/state.ts@@ -13,7 +13,7 @@ import { MAX_STACK } from '../../shared/types'import { createId } from '../store/ids'import { nativeImage, BrowserWindow, powerMonitor } from 'electron'import { readFileSync } from 'node:fs'-import { PATHS } from '../store/paths'+import { isStagedTempPath } from '../store/paths'import { prefetchFileIcons } from './drag'import { runtime } from './config'import { getMainWindow } from './window'@@ -180,7 +180,7 @@ export function addFiles(paths: string[]): AddFilesResult {// Prevent duplicating items when a user accidentally drops our own staged temp// files back into the app. Real files are deduplicated automatically by path,// but images are staged to temp-drag and would otherwise get new IDs.- const clean = paths.filter((p) => !p.startsWith(PATHS.tempDir()))+ const clean = paths.filter((p) => !isStagedTempPath(p))if (clean.length === 0) return { stacksCreated: 0 }const imageExts = /\.(png|jpe?g|gif|webp|bmp|svg|avif|ico|tiff?|jfif|pjpeg|pjp)$/idiff --git a/electron/main/storeStartup.ts b/electron/main/storeStartup.tsnew file mode 100644index 0000000..e1d51c0--- /dev/null+++ b/electron/main/storeStartup.ts@@ -0,0 +1,83 @@+/**+ * Store launch-at-login: the same three calls as electron-winstore-auto-launch+ * (getStatus / enable / disable).+ *+ * That npm package cannot run on Electron 34 — its NodeRT native addon will not+ * compile (`/std:c++20` vs `/ZW`). These methods call the identical WinRT API+ * (StartupTask.GetAsync / RequestEnableAsync / Disable) from a tiny in-package+ * helper that has AppX identity. No registry writes. No PowerShell.+ */+import { execFile } from 'node:child_process'+import { existsSync } from 'node:fs'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { app } from 'electron'+import { STORE_STARTUP_TASK_ID } from './config'++const execFileAsync = promisify(execFile)++export const StartupTaskState = {+ Disabled: 0,+ DisabledByUser: 1,+ Enabled: 2,+ DisabledByPolicy: 3,+ EnabledByPolicy: 4+} as const++export function resolveStartupHelperPath(): string | null {+ const candidates: string[] = []+ if (typeof process.resourcesPath === 'string' && process.resourcesPath) {+ candidates.push(join(process.resourcesPath, 'startup', 'EdgeDropStartup.exe'))+ }+ try {+ const appPath = app.getAppPath()+ candidates.push(join(appPath, '..', 'startup', 'EdgeDropStartup.exe'))+ candidates.push(join(appPath, 'resources', 'startup', 'EdgeDropStartup.exe'))+ } catch {+ /* tests / app not ready */+ }+ candidates.push(join(process.cwd(), 'resources', 'startup', 'EdgeDropStartup.exe'))+ return candidates.find((path) => path && existsSync(path)) ?? null+}++function parseState(stdout: string): number | null {+ const match = String(stdout).trim().match(/^(\d+)\s*$/m)+ if (!match) return null+ const state = Number(match[1])+ return Number.isInteger(state) ? state : null+}++async function run(action: 'get' | 'enable' | 'disable'): Promise<number | null> {+ const exe = resolveStartupHelperPath()+ if (!exe) {+ console.error('[StoreStartup] helper missing')+ return null+ }+ try {+ const result = await execFileAsync(exe, [action, STORE_STARTUP_TASK_ID], {+ encoding: 'utf8',+ timeout: 20000,+ windowsHide: true,+ cwd: process.env.TEMP || process.cwd()+ })+ const stdout = typeof result === 'string' ? result : String((result as { stdout?: string }).stdout ?? '')+ return parseState(stdout)+ } catch (err) {+ console.error('[StoreStartup] helper failed:', err)+ return null+ }+}++export async function getStatus(): Promise<number | null> {+ return run('get')+}++export async function enable(): Promise<number | null> {+ return run('enable')+}++export async function disable(): Promise<number | null> {+ return run('disable')+}++export { parseState as parseStartupHelperState }diff --git a/electron/main/updater.ts b/electron/main/updater.tsindex 72c8ae3..22a62fe 100644--- a/electron/main/updater.ts+++ b/electron/main/updater.ts@@ -1,5 +1,5 @@import { app, net } from 'electron'-import { isStoreBuild } from './ipc'+import { isStoreBuild } from './config'import { pushState } from './state'import { getSettings } from '../store/settings'diff --git a/electron/preload/index.ts b/electron/preload/index.tsindex 9ca81e8..7086a02 100644--- a/electron/preload/index.ts+++ b/electron/preload/index.ts@@ -162,6 +162,7 @@ const api = {getReleases: () => invoke('app:get-releases'),updateSettings: (patch: Partial<InvokeResult<'settings:update'>>) =>invoke('settings:update', patch),+ refreshLaunchAtLogin: () => invoke('startup:refresh'),setInteractive: (value: boolean) => invoke('window:set-interactive', value),setPreviewMode: (active: boolean) => invoke('window:set-preview-mode', active),pauseHotkey: (paused: boolean) => invoke('hotkey:pause', paused),diff --git a/electron/store/paths.ts b/electron/store/paths.tsindex 1f0da21..826178d 100644--- a/electron/store/paths.ts+++ b/electron/store/paths.ts@@ -5,9 +5,12 @@* and self-cleaning. Image files are kept in their own folder so the JSON index* stays small and fast to read/write.*/-import { mkdirSync } from 'node:fs'-import { join } from 'node:path'+import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'+import { extname, join, sep } from 'node:path'+import { createHash } from 'node:crypto'+import { homedir } from 'node:os'import { app } from 'electron'+import { isStoreBuild } from '../main/config'const root = () => app.getPath('userData')@@ -30,21 +33,82 @@ export const PATHS = {trayIcon: () => join(app.getAppPath(), 'resources', 'tray.png')} as const+/**+ * Directory other Win32 processes can open.+ *+ * GitHub NSIS: same as PATHS.tempDir() (userData/temp) — unchanged.+ * Store/MSIX: USERPROFILE\AppData\Local\Temp\Edge-Drop. Packaged APPDATA is+ * virtualized; Explorer/Word/PowerShell do not see those redirected writes.+ */+export function getUnpackagedTempDir(): string {+ if (isStoreBuild()) {+ return join(homedir(), 'AppData', 'Local', 'Temp', 'Edge-Drop')+ }+ return PATHS.tempDir()+}++/** True when `p` is one of our own staged drag/clipboard temp files. */+export function isStagedTempPath(p: string): boolean {+ if (!p) return false+ const roots = new Set([PATHS.tempDir(), getUnpackagedTempDir()])+ return [...roots].some((rootDir) => {+ if (!rootDir) return false+ if (p === rootDir) return true+ const prefix = rootDir.endsWith('\\') || rootDir.endsWith('/') ? rootDir : rootDir + sep+ return p.startsWith(prefix)+ })+}++function needsUnpackagedCopy(filePath: string): boolean {+ if (!isStoreBuild() || !filePath) return false+ const lower = filePath.toLowerCase()+ if (lower.includes('\\packages\\') || lower.includes('\\windowsapps\\')) return true+ try {+ return lower.startsWith(PATHS.root().toLowerCase())+ } catch {+ return false+ }+}++/**+ * Path an unpackaged process (PowerShell, Explorer, Photoshop) can open.+ * No-op on the GitHub .exe. On Store, copies package-private files into the+ * real user temp so CF_HDROP / FromFile targets resolve.+ */+export function toUnpackagedFilePath(filePath: string): string {+ if (!needsUnpackagedCopy(filePath) || !existsSync(filePath)) return filePath+ const dir = getUnpackagedTempDir()+ mkdirSync(dir, { recursive: true })+ const stamp = createHash('sha1').update(filePath).digest('hex').slice(0, 10)+ const dest = join(dir, `${stamp}${extname(filePath) || ''}`)+ try {+ copyFileSync(filePath, dest)+ return dest+ } catch (err) {+ console.error('[paths] Failed to stage unpackaged copy of', filePath, err)+ return filePath+ }+}++export function toUnpackagedFilePaths(filePaths: string[]): string[] {+ return filePaths.map(toUnpackagedFilePath)+}+/** Idempotently create every directory the app needs. Safe to call repeatedly. */export function ensureDirs(): void {for (const dir of [PATHS.imagesDir(), PATHS.payloadsDir(), PATHS.tempDir()]) {mkdirSync(dir, { recursive: true })}+ if (isStoreBuild()) {+ mkdirSync(getUnpackagedTempDir(), { recursive: true })+ }}-/** Remove old temp drag files left over from a previous session. */-export function cleanTemp(): void {- // Best-effort; failures are non-fatal.+function emptyDir(dir: string): void {try {- const fs = require('node:fs') as typeof import('node:fs')- for (const entry of fs.readdirSync(PATHS.tempDir())) {+ for (const entry of readdirSync(dir)) {try {- fs.rmSync(join(PATHS.tempDir(), entry), { force: true })+ rmSync(join(dir, entry), { force: true })} catch {/* ignore individual file errors */}@@ -53,3 +117,12 @@ export function cleanTemp(): void {/* dir may not exist yet */}}++/** Remove old temp drag files left over from a previous session. */+export function cleanTemp(): void {+ emptyDir(PATHS.tempDir())+ const unpackaged = getUnpackagedTempDir()+ if (unpackaged !== PATHS.tempDir()) {+ emptyDir(unpackaged)+ }+}diff --git a/package-lock.json b/package-lock.jsonindex 024b8be..5abf6a3 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "edge-drop",- "version": "0.2.7",+ "version": "0.2.9","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "edge-drop",- "version": "0.2.7",+ "version": "0.2.9","license": "Apache-2.0","dependencies": {"@iconify-json/cuida": "^1.2.5",diff --git a/package.json b/package.jsonindex 33a0fd7..bb1d507 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "edge-drop",- "version": "0.2.7",+ "version": "0.2.9","description": "Edge-Drop — a clipboard manager that lives on the left edge of your screen and expands on hover.","author": "Edge-Drop","license": "Apache-2.0",@@ -31,8 +31,21 @@"files": ["out/**/*","resources/**/*",+ "!resources/startup/**/*.exe","package.json"],+ "extraResources": [+ {+ "from": "resources/startup/EdgeDropStartup.exe",+ "to": "startup/EdgeDropStartup.exe"+ }+ ],+ "asarUnpack": [+ "**/*.{node,dll}",+ "**/node_modules/koffi/**/*",+ "**/node_modules/@koromix/**/*",+ "**/node_modules/@resvg/**/*"+ ],"publish": {"provider": "github","owner": "Deepender25",@@ -69,7 +82,12 @@"publisher": "CN=55FECDC4-7144-4A41-98FC-056C003F76FD","publisherDisplayName": "Deepender","applicationId": "EdgeDrop",- "displayName": "Edge Drop"+ "displayName": "Edge Drop",+ "capabilities": [+ "runFullTrust",+ "internetClient"+ ],+ "customExtensionsPath": "resources/appx/startup-extensions.xml"}},"devDependencies": {@@ -101,4 +119,4 @@"svg-path-bbox": "^2.1.0","zustand": "^4.5.2"}-}\ No newline at end of file+}diff --git a/resources/appx/startup-extensions.xml b/resources/appx/startup-extensions.xmlnew file mode 100644index 0000000..7237ebe--- /dev/null+++ b/resources/appx/startup-extensions.xml@@ -0,0 +1,3 @@+ <desktop:Extension Category="windows.startupTask" Executable="app\Edge-Drop.exe" EntryPoint="Windows.FullTrustApplication">+ <desktop:StartupTask TaskId="EdgeDropStartup" Enabled="true" DisplayName="Edge-Drop" />+ </desktop:Extension>diff --git a/resources/startup/EdgeDropStartup.cs b/resources/startup/EdgeDropStartup.csnew file mode 100644index 0000000..1a3a848--- /dev/null+++ b/resources/startup/EdgeDropStartup.cs@@ -0,0 +1,108 @@+// Official Windows.ApplicationModel.StartupTask caller.+// Windows GUI process (no console). Must live inside the AppX.+using System;+using System.Runtime.InteropServices;+using System.Threading;+using Windows.ApplicationModel;+using Windows.Foundation;++internal static class Program+{+ private const uint PM_REMOVE = 1;++ [StructLayout(LayoutKind.Sequential)]+ private struct MSG+ {+ public IntPtr hwnd;+ public uint message;+ public IntPtr wParam;+ public IntPtr lParam;+ public uint time;+ public int ptX;+ public int ptY;+ }++ [DllImport("user32.dll")]+ private static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint min, uint max, uint remove);++ [DllImport("user32.dll")]+ private static extern bool TranslateMessage(ref MSG lpMsg);++ [DllImport("user32.dll")]+ private static extern IntPtr DispatchMessage(ref MSG lpMsg);++ [STAThread]+ private static int Main(string[] args)+ {+ try+ {+ string action = args.Length > 0 ? args[0].Trim().ToLowerInvariant() : "get";+ string taskId = args.Length > 1 ? args[1] : "EdgeDropStartup";++ StartupTask task = Wait(StartupTask.GetAsync(taskId));++ if (action == "enable")+ {+ WriteState((int)Wait(task.RequestEnableAsync()));+ return 0;+ }++ if (action == "disable")+ {+ task.Disable();+ }++ WriteState((int)task.State);+ return 0;+ }+ catch (Exception ex)+ {+ Console.Error.WriteLine("ERR " + ex.GetType().Name + " " + ex.Message);+ return 21;+ }+ }++ private static void WriteState(int state)+ {+ Console.Out.WriteLine(state.ToString());+ Console.Out.Flush();+ }++ private static void Pump()+ {+ MSG msg;+ while (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))+ {+ TranslateMessage(ref msg);+ DispatchMessage(ref msg);+ }+ }++ private static T Wait<T>(IAsyncOperation<T> op)+ {+ if (op.Status == AsyncStatus.Started)+ {+ using (ManualResetEvent ev = new ManualResetEvent(false))+ {+ op.Completed = delegate { try { ev.Set(); } catch { } };+ DateTime deadline = DateTime.UtcNow.AddSeconds(20);+ while (op.Status == AsyncStatus.Started)+ {+ Pump();+ if (ev.WaitOne(20)) break;+ if (DateTime.UtcNow > deadline)+ {+ throw new TimeoutException("StartupTask async timeout");+ }+ }+ }+ }++ if (op.Status != AsyncStatus.Completed)+ {+ throw new InvalidOperationException("async-status-" + op.Status + "-" + op.ErrorCode);+ }++ return op.GetResults();+ }+}diff --git a/resources/startup/EdgeDropStartup.exe b/resources/startup/EdgeDropStartup.exenew file mode 100644index 0000000..8cb7547Binary files /dev/null and b/resources/startup/EdgeDropStartup.exe differdiff --git a/scripts/compile-startup-helper.ps1 b/scripts/compile-startup-helper.ps1new file mode 100644index 0000000..b655083--- /dev/null+++ b/scripts/compile-startup-helper.ps1@@ -0,0 +1,23 @@+$ErrorActionPreference = 'Stop'+$root = Split-Path -Parent $PSScriptRoot+$src = Join-Path $root 'resources\startup\EdgeDropStartup.cs'+$out = Join-Path $root 'resources\startup\EdgeDropStartup.exe'+$csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'+$winrt = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\System.Runtime.WindowsRuntime.dll'+$runtime = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\System.Runtime.dll'+$winmd = 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd'++if (-not (Test-Path $winmd)) {+ $winmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' -Filter Windows.winmd -Recurse |+ Select-Object -First 1 -ExpandProperty FullName+}++if (-not (Test-Path $csc)) { throw "csc.exe not found: $csc" }+if (-not (Test-Path $winrt)) { throw "System.Runtime.WindowsRuntime.dll not found: $winrt" }+if (-not (Test-Path $runtime)) { throw "System.Runtime.dll not found: $runtime" }+if (-not $winmd -or -not (Test-Path $winmd)) { throw 'Windows.winmd not found (install the Windows SDK)' }+if (-not (Test-Path $src)) { throw "missing $src" }++& $csc /nologo /target:winexe /platform:anycpu /optimize+ "/out:$out" "/r:$winrt" "/r:$runtime" "/r:$winmd" $src+if ($LASTEXITCODE -ne 0) { throw "csc failed with $LASTEXITCODE" }+Write-Output "compiled $out"diff --git a/shared/bridge.ts b/shared/bridge.tsindex a08f3b3..1030528 100644--- a/shared/bridge.ts+++ b/shared/bridge.ts@@ -35,6 +35,7 @@ export interface EdgeApi {mergeItems: (sourceId: string, targetId: string) => Promise<import('./types').MergeResult>splitItem: (req: import('./types').DragRequest) => Promise<boolean>updateSettings: (patch: Partial<Settings>) => Promise<Settings>+ refreshLaunchAtLogin: () => Promise<Settings>setInteractive: (value: boolean) => Promise<void>setPreviewMode: (active: boolean) => Promise<void>pauseHotkey: (paused: boolean) => Promise<void>diff --git a/shared/ipc.ts b/shared/ipc.tsindex 632b051..296c127 100644--- a/shared/ipc.ts+++ b/shared/ipc.ts@@ -65,6 +65,9 @@ export interface InvokeMap {/** Update a persisted setting. */'settings:update': { args: [patch: Partial<Settings>]; result: Settings }+ /** Re-read launch-at-login from Windows and persist it into settings. */+ 'startup:refresh': { args: []; result: Settings }+/** Pause/resume global shortcut registration temporarily (e.g. while recording a new hotkey). */'hotkey:pause': { args: [paused: boolean]; result: void }diff --git a/src/components/Settings.tsx b/src/components/Settings.tsxindex 14cef72..9d9e7f5 100644--- a/src/components/Settings.tsx+++ b/src/components/Settings.tsx@@ -73,6 +73,13 @@ export function Settings({ inlineIndicatorStyle }: { inlineIndicatorStyle?: boolwindow.edge.getDisplays().then(setDisplays).catch(() => {})}, [])+ useEffect(() => {+ const pull = () => { void useStore.getState().refreshLaunchAtLogin() }+ pull()+ const timer = window.setInterval(pull, 2000)+ return () => window.clearInterval(timer)+ }, [])+const updateDownloaded = updateInfo?.downloaded ? { version: updateInfo.latestVersion } : nullconst autoUpdates = settings.autoUpdates ?? true@@ -328,7 +335,12 @@ export function Settings({ inlineIndicatorStyle }: { inlineIndicatorStyle?: bool</div><Togglechecked={settings.launchAtLogin}- onChange={(v) => patch({ launchAtLogin: v })}+ onChange={(v) => {+ useStore.setState((s) => ({+ settings: { ...s.settings, launchAtLogin: v }+ }))+ void patch({ launchAtLogin: v })+ }}/></div>diff --git a/src/store/appStore.ts b/src/store/appStore.tsindex 4d8c63e..977dd29 100644--- a/src/store/appStore.ts+++ b/src/store/appStore.ts@@ -103,6 +103,7 @@ interface AppState {paste: (id: string) => Promise<void>pasteSubitem: (req: DragRequest) => Promise<void>patchSettings: (patch: Partial<Settings>) => Promise<void>+ refreshLaunchAtLogin: () => Promise<void>setTutorialStep: (step: number) => void}@@ -387,6 +388,15 @@ export const useStore = create<AppState>((set, get) => ({set({ settings: next })},+ async refreshLaunchAtLogin() {+ try {+ const next = await edge.refreshLaunchAtLogin()+ if (next) set({ settings: next })+ } catch {+ /* ignore */+ }+ },+setTutorialStep: (step) => {set({ tutorialStep: step })edge.broadcastTutorialStep(step)diff --git a/tests/dragDrop.test.ts b/tests/dragDrop.test.tsindex 5d93c32..8aa22a4 100644--- a/tests/dragDrop.test.ts+++ b/tests/dragDrop.test.ts@@ -7,7 +7,10 @@ vi.mock('../electron/store/paths', () => ({PATHS: {tempDir: () => 'C:\\mock\\temp',imagesDir: () => 'C:\\mock\\images'- }+ },+ getUnpackagedTempDir: () => 'C:\\mock\\temp',+ toUnpackagedFilePath: (p: string) => p,+ toUnpackagedFilePaths: (ps: string[]) => ps}))vi.mock('../electron/main/state', () => ({@@ -23,7 +26,8 @@ vi.mock('node:fs', () => ({return false}),copyFileSync: vi.fn(),- writeFileSync: vi.fn()+ writeFileSync: vi.fn(),+ mkdirSync: vi.fn()}))describe('formatScreenshotFilename', () => {diff --git a/tests/storeBuildDetect.test.ts b/tests/storeBuildDetect.test.tsnew file mode 100644index 0000000..6312c20--- /dev/null+++ b/tests/storeBuildDetect.test.ts@@ -0,0 +1,149 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'++const appState = vi.hoisted(() => ({+ isPackaged: false,+ appPath: 'C:\\__no_such_edge_drop_app__'+}))++vi.mock('electron', () => ({+ app: {+ get isPackaged() {+ return appState.isPackaged+ },+ getAppPath: () => appState.appPath,+ getPath: (name: string) => (name === 'userData' ? 'C:\\mock\\userData' : `C:\\mock\\${name}`)+ }+}))++import { isStoreBuild, STORE_STARTUP_TASK_ID } from '../electron/main/config'++function setWindowsStore(value: boolean | undefined): void {+ if (value === undefined) {+ delete (process as NodeJS.Process & { windowsStore?: boolean }).windowsStore+ return+ }+ Object.defineProperty(process, 'windowsStore', {+ value,+ configurable: true,+ enumerable: true,+ writable: true+ })+}++describe('isStoreBuild — every detection signal', () => {+ let tempDirs: string[] = []++ beforeEach(() => {+ delete process.env.APP_BUILD_TARGET+ setWindowsStore(undefined)+ appState.isPackaged = false+ appState.appPath = 'C:\\__no_such_edge_drop_app__'+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ setWindowsStore(undefined)+ appState.isPackaged = false+ for (const dir of tempDirs) {+ try { rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }+ }+ tempDirs = []+ })++ function writePackagedJson(body: unknown): string {+ const dir = mkdtempSync(join(tmpdir(), 'ed-build-'))+ tempDirs.push(dir)+ writeFileSync(join(dir, 'package.json'), typeof body === 'string' ? body : JSON.stringify(body))+ appState.isPackaged = true+ appState.appPath = dir+ return dir+ }++ it('is false for unpackaged GitHub / dev (no signals)', () => {+ expect(isStoreBuild()).toBe(false)+ })++ it('is false when APP_BUILD_TARGET is the GitHub stamp', () => {+ process.env.APP_BUILD_TARGET = 'github'+ expect(isStoreBuild()).toBe(false)+ })++ it('is false for lookalike env values (case, whitespace, empty)', () => {+ process.env.APP_BUILD_TARGET = 'STORE'+ expect(isStoreBuild()).toBe(false)+ process.env.APP_BUILD_TARGET = 'store '+ expect(isStoreBuild()).toBe(false)+ process.env.APP_BUILD_TARGET = ''+ expect(isStoreBuild()).toBe(false)+ process.env.APP_BUILD_TARGET = 'msix'+ expect(isStoreBuild()).toBe(false)+ })++ it('is true when APP_BUILD_TARGET=store even if unpackaged', () => {+ process.env.APP_BUILD_TARGET = 'store'+ expect(isStoreBuild()).toBe(true)+ })++ it('is true when process.windowsStore is true', () => {+ setWindowsStore(true)+ expect(isStoreBuild()).toBe(true)+ })++ it('windowsStore wins over a github env stamp', () => {+ process.env.APP_BUILD_TARGET = 'github'+ setWindowsStore(true)+ expect(isStoreBuild()).toBe(true)+ })++ it('is false when windowsStore is explicitly false and nothing else is set', () => {+ setWindowsStore(false)+ expect(isStoreBuild()).toBe(false)+ })++ it('is true when packaged package.json has buildTarget store', () => {+ writePackagedJson({ buildTarget: 'store', name: 'edge-drop' })+ expect(isStoreBuild()).toBe(true)+ })++ it('is false when packaged package.json has buildTarget github', () => {+ writePackagedJson({ buildTarget: 'github', name: 'edge-drop' })+ expect(isStoreBuild()).toBe(false)+ })++ it('is false when packaged package.json has no buildTarget', () => {+ writePackagedJson({ name: 'edge-drop', version: '0.2.7' })+ expect(isStoreBuild()).toBe(false)+ })++ it('is false (and does not throw) when packaged package.json is missing', () => {+ const dir = mkdtempSync(join(tmpdir(), 'ed-build-empty-'))+ tempDirs.push(dir)+ appState.isPackaged = true+ appState.appPath = dir+ expect(() => isStoreBuild()).not.toThrow()+ expect(isStoreBuild()).toBe(false)+ })++ it('is false (and does not throw) when packaged package.json is malformed', () => {+ writePackagedJson('{ not-json')+ expect(() => isStoreBuild()).not.toThrow()+ expect(isStoreBuild()).toBe(false)+ })++ it('is false when unpackaged even if a store-stamped package.json exists on disk', () => {+ const dir = mkdtempSync(join(tmpdir(), 'ed-build-unpkg-'))+ tempDirs.push(dir)+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ buildTarget: 'store' }))+ appState.isPackaged = false+ appState.appPath = dir+ expect(isStoreBuild()).toBe(false)+ })++ it('keeps STORE_STARTUP_TASK_ID as a non-empty identifier', () => {+ expect(STORE_STARTUP_TASK_ID).toMatch(/^[A-Za-z][A-Za-z0-9]*$/)+ expect(STORE_STARTUP_TASK_ID.length).toBeGreaterThan(3)+ })+})diff --git a/tests/storeDragStaging.test.ts b/tests/storeDragStaging.test.tsnew file mode 100644index 0000000..4f58c41--- /dev/null+++ b/tests/storeDragStaging.test.ts@@ -0,0 +1,145 @@+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'+import type { ItemData } from '../shared/types'++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)),+ getFileIcon: vi.fn(() => Promise.resolve({ isEmpty: () => true }))+ },+ nativeImage: {+ createFromBuffer: vi.fn(() => ({ isEmpty: () => true }))+ }+}))++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:os')>()+ return {+ ...actual,+ homedir: () => fsRoots.home+ }+})++vi.mock('../electron/main/state', () => ({+ getStore: () => ({+ getImagePath: (imageId: string, ext = 'png') =>+ join(fsRoots.userData, 'images', `${imageId}.${ext}`)+ })+}))++import { stageDragFile } from '../electron/main/drag'++const stamp = new Date(2026, 7, 15, 22, 30, 45).getTime()++describe('stageDragFile uses the correct staging root per build', () => {+ beforeEach(() => {+ delete process.env.APP_BUILD_TARGET+ fsRoots.home = join(tmpdir(), `ed-drag-home-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ fsRoots.userData = join(tmpdir(), `ed-drag-ud-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ mkdirSync(join(fsRoots.userData, 'images'), { recursive: true })+ mkdirSync(join(fsRoots.userData, 'temp'), { recursive: true })+ mkdirSync(fsRoots.home, { recursive: true })+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ try { rmSync(fsRoots.home, { recursive: true, force: true }) } catch { /* ignore */ }+ try { rmSync(fsRoots.userData, { recursive: true, force: true }) } catch { /* ignore */ }+ })++ function writeImage(id: string): string {+ const p = join(fsRoots.userData, 'images', `${id}.png`)+ writeFileSync(p, `png-${id}`)+ return p+ }++ it('exe image: copies into userData/temp, not the Store interop folder', () => {+ writeImage('img_exe')+ const staged = stageDragFile({+ kind: 'image',+ imageId: 'img_exe',+ width: 10,+ height: 10,+ bytes: 8,+ ext: 'png'+ }, stamp)+ expect(staged).not.toBeNull()+ expect(staged!.file.startsWith(join(fsRoots.userData, 'temp'))).toBe(true)+ expect(staged!.file).toContain('Screenshot 2026-08-15 22.30.45.png')+ expect(existsSync(staged!.file)).toBe(true)+ expect(readFileSync(staged!.file, 'utf8')).toBe('png-img_exe')+ expect(existsSync(join(fsRoots.home, 'AppData', 'Local', 'Temp', 'Edge-Drop'))).toBe(false)+ })++ it('store image: copies into the real user Local\\Temp\\Edge-Drop folder', () => {+ process.env.APP_BUILD_TARGET = 'store'+ writeImage('img_store')+ const staged = stageDragFile({+ kind: 'image',+ imageId: 'img_store',+ width: 10,+ height: 10,+ bytes: 8,+ ext: 'png'+ }, stamp)+ const interop = join(fsRoots.home, 'AppData', 'Local', 'Temp', 'Edge-Drop')+ expect(staged).not.toBeNull()+ expect(staged!.file.startsWith(interop)).toBe(true)+ expect(staged!.file.startsWith(join(fsRoots.userData, 'temp'))).toBe(false)+ expect(existsSync(staged!.file)).toBe(true)+ expect(readFileSync(staged!.file, 'utf8')).toBe('png-img_store')+ })++ it('exe files: keeps the original user paths (does not copy)', () => {+ const doc = join(fsRoots.home, 'Documents', 'report.pdf')+ mkdirSync(join(fsRoots.home, 'Documents'), { recursive: true })+ writeFileSync(doc, 'pdf')+ const staged = stageDragFile({ kind: 'files', paths: [doc] })+ expect(staged).toEqual({ file: doc, files: [doc] })+ })++ it('store files: remaps package-private images but leaves user documents untouched', () => {+ process.env.APP_BUILD_TARGET = 'store'+ const pkgImg = writeImage('inside')+ const doc = join(fsRoots.home, 'Documents', 'notes.txt')+ mkdirSync(join(fsRoots.home, 'Documents'), { recursive: true })+ writeFileSync(doc, 'txt')+ const staged = stageDragFile({ kind: 'files', paths: [pkgImg, doc] })+ expect(staged).not.toBeNull()+ expect(staged!.files).toHaveLength(2)+ expect(staged!.files![0]).not.toBe(pkgImg)+ expect(staged!.files![0]).toContain(join('AppData', 'Local', 'Temp', 'Edge-Drop'))+ expect(staged!.files![1]).toBe(doc)+ expect(readFileSync(staged!.files![0], 'utf8')).toBe('png-inside')+ })++ it('store text: writes the snippet into the unpackaged interop dir', () => {+ process.env.APP_BUILD_TARGET = 'store'+ const data: ItemData = { kind: 'text', text: 'hello store drag', isUrl: false }+ const staged = stageDragFile(data)+ expect(staged).not.toBeNull()+ expect(staged!.file).toContain(join('AppData', 'Local', 'Temp', 'Edge-Drop'))+ expect(readFileSync(staged!.file, 'utf8')).toBe('hello store drag')+ })++ it('returns null when an image file is missing on disk', () => {+ const staged = stageDragFile({+ kind: 'image',+ imageId: 'missing',+ width: 1,+ height: 1,+ bytes: 1,+ ext: 'png'+ }, stamp)+ expect(staged).toBeNull()+ })+})diff --git a/tests/storeLoginApply.test.ts b/tests/storeLoginApply.test.tsnew file mode 100644index 0000000..622e2ec--- /dev/null+++ b/tests/storeLoginApply.test.ts@@ -0,0 +1,96 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const store = vi.hoisted(() => ({+ get: vi.fn(async () => 2 as number | null),+ enable: vi.fn(async () => 2 as number | null),+ disable: vi.fn(async () => 0 as number | null)+}))++const mocks = vi.hoisted(() => ({+ isPackaged: true,+ exePath: 'C:\\Program Files\\WindowsApps\\Deepender.EdgeDrop_0.2.9.0_x64__aqnvcnjbf5ns8\\app\\Edge-Drop.exe',+ loadSettings: vi.fn(() => ({ launchAtLogin: false })),+ saveSettings: vi.fn((patch: Record<string, unknown>) => ({ launchAtLogin: false, ...patch }))+}))++vi.mock('electron', () => ({+ app: {+ get isPackaged() {+ return mocks.isPackaged+ },+ getPath: (name: string) => (name === 'exe' ? mocks.exePath : 'C:\\mock\\userData'),+ getAppPath: () => 'C:\\mock\\app',+ setLoginItemSettings: vi.fn(),+ getLoginItemSettings: vi.fn(() => ({ launchItems: [], executableWillLaunchAtLogin: false }))+ }+}))++vi.mock('../electron/store/settings', () => ({+ loadSettings: () => mocks.loadSettings(),+ saveSettings: (patch: Record<string, unknown>) => mocks.saveSettings(patch)+}))++vi.mock('../electron/main/storeStartup', () => ({+ getStatus: () => store.get(),+ enable: () => store.enable(),+ disable: () => store.disable(),+ StartupTaskState: {+ Disabled: 0,+ DisabledByUser: 1,+ Enabled: 2,+ DisabledByPolicy: 3,+ EnabledByPolicy: 4+ }+}))++import { applyLaunchAtLogin, refreshLaunchAtLoginFromOs } from '../electron/main/loginItems'++describe('Store applyLaunchAtLogin uses only enable / disable / getStatus', () => {+ beforeEach(() => {+ process.env.APP_BUILD_TARGET = 'store'+ mocks.isPackaged = true+ mocks.loadSettings.mockReturnValue({ launchAtLogin: false })+ store.get.mockReset()+ store.enable.mockReset()+ store.disable.mockReset()+ store.get.mockResolvedValue(0)+ store.enable.mockResolvedValue(2)+ store.disable.mockResolvedValue(0)+ mocks.saveSettings.mockClear()+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ })++ it('On calls enable(), Off calls disable()', async () => {+ const on = await applyLaunchAtLogin(true)+ expect(store.enable).toHaveBeenCalledOnce()+ expect(store.disable).not.toHaveBeenCalled()+ expect(on).toEqual({ enabled: true, blockedByUser: false, ok: true })++ store.enable.mockClear()+ const off = await applyLaunchAtLogin(false)+ expect(store.disable).toHaveBeenCalledOnce()+ expect(store.enable).not.toHaveBeenCalled()+ expect(off).toEqual({ enabled: false, blockedByUser: false, ok: true })+ })++ it('DisabledByUser is reported so the toggle is not treated as a generic failure', async () => {+ store.enable.mockResolvedValue(1)+ const result = await applyLaunchAtLogin(true)+ expect(result).toEqual({ enabled: false, blockedByUser: true, ok: false })+ })++ it('refresh does not overwrite settings while enable is still running', async () => {+ mocks.loadSettings.mockReturnValue({ launchAtLogin: false })+ let release: ((value: number) => void) | undefined+ store.enable.mockImplementation(() => new Promise((resolve) => { release = resolve }))+ const pending = applyLaunchAtLogin(true)+ const mid = await refreshLaunchAtLoginFromOs()+ expect(mocks.saveSettings).not.toHaveBeenCalled()+ expect(mid.launchAtLogin).toBe(false)+ release!(2)+ expect((await pending).ok).toBe(true)+ })+})diff --git a/tests/storeLoginItem.test.ts b/tests/storeLoginItem.test.tsnew file mode 100644index 0000000..6fe6cbe--- /dev/null+++ b/tests/storeLoginItem.test.ts@@ -0,0 +1,194 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ isPackaged: true,+ setLoginItemSettings: vi.fn(),+ getLoginItemSettings: vi.fn(() => ({+ launchItems: [] as Array<{ name: string; path: string; enabled: boolean; args?: string[] }>,+ executableWillLaunchAtLogin: false+ })),+ exePath: 'C:\\Users\\yadav\\AppData\\Local\\Programs\\Edge-Drop\\Edge-Drop.exe',+ loadSettings: vi.fn(() => ({ launchAtLogin: true })),+ saveSettings: vi.fn((patch: Record<string, unknown>) => ({ launchAtLogin: true, ...patch }))+}))++vi.mock('electron', () => ({+ app: {+ get isPackaged() {+ return mocks.isPackaged+ },+ getPath: (name: string) => (name === 'exe' ? mocks.exePath : 'C:\\mock\\userData'),+ setLoginItemSettings: (...args: unknown[]) => mocks.setLoginItemSettings(...args),+ getLoginItemSettings: (...args: unknown[]) => mocks.getLoginItemSettings(...args),+ getVersion: () => '0.2.7',+ getAppPath: () => 'C:\\mock\\app',+ disableHardwareAcceleration: vi.fn(),+ enableSandbox: vi.fn(),+ requestSingleInstanceLock: vi.fn(() => true),+ setAppUserModelId: vi.fn(),+ commandLine: { appendSwitch: vi.fn() },+ on: vi.fn(),+ whenReady: vi.fn(() => new Promise(() => {})),+ quit: vi.fn()+ },+ clipboard: { clear: vi.fn(), writeImage: vi.fn(), readImage: vi.fn(), write: vi.fn(), writeText: vi.fn() },+ nativeImage: { createFromPath: vi.fn(), createFromDataURL: vi.fn() },+ protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() },+ ipcMain: { on: vi.fn(), handle: vi.fn() },+ BrowserWindow: { fromWebContents: vi.fn() },+ powerMonitor: { on: vi.fn(), removeAllListeners: vi.fn() },+ shell: { showItemInFolder: vi.fn(), openExternal: vi.fn() },+ net: { request: vi.fn(), fetch: vi.fn() }+}))++vi.mock('../electron/main/state', () => ({+ loadSettings: () => mocks.loadSettings(),+ saveSettings: (patch: Record<string, unknown>) => mocks.saveSettings(patch),+ getStore: vi.fn(),+ getWatcher: vi.fn(),+ addFiles: vi.fn(),+ pushState: { items: vi.fn(), settings: vi.fn(), togglePanel: vi.fn() }+}))++vi.mock('../electron/store/settings', () => ({+ loadSettings: () => mocks.loadSettings(),+ saveSettings: (patch: Record<string, unknown>) => mocks.saveSettings(patch)+}))++vi.mock('../electron/main/powershell', () => ({+ psHost: { run: vi.fn() },+ getSystemPowerShellPath: () => 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ getWritableCwd: () => 'C:\\Temp'+}))++import { applyLaunchAtLogin, reconcileLaunchAtLoginOnStartup, GITHUB_LOGIN_ITEM_NAMES } from '../electron/main/loginItems'+import { syncLoginItemSettings } from '../electron/main/ipc'++describe('GitHub exe launch-at-login (orphan Run keys)', () => {+ beforeEach(() => {+ delete process.env.APP_BUILD_TARGET+ mocks.isPackaged = true+ mocks.setLoginItemSettings.mockReset()+ mocks.getLoginItemSettings.mockReset()+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [],+ executableWillLaunchAtLogin: false+ })+ mocks.loadSettings.mockReturnValue({ launchAtLogin: true })+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ })++ it('unpackaged / dev: does not write Run keys', async () => {+ mocks.isPackaged = false+ const result = await applyLaunchAtLogin(true)+ expect(result).toEqual({ enabled: true, blockedByUser: false, ok: true })+ expect(mocks.setLoginItemSettings).not.toHaveBeenCalled()+ })++ it('enable: clears every historical name then writes Edge-Drop with --hidden and enabled:true', async () => {+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [+ { name: 'Edge-Drop', path: mocks.exePath, enabled: true, args: ['--hidden'] }+ ],+ executableWillLaunchAtLogin: true+ })+ const result = await applyLaunchAtLogin(true)+ expect(result.ok).toBe(true)+ expect(result.enabled).toBe(true)+ for (const name of GITHUB_LOGIN_ITEM_NAMES) {+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith({+ openAtLogin: false,+ path: mocks.exePath,+ name+ })+ }+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith({+ openAtLogin: true,+ path: mocks.exePath,+ args: ['--hidden'],+ name: 'Edge-Drop',+ enabled: true+ })+ })++ it('disable: removes every historical name, including leftovers Task Manager still lists', async () => {+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [+ { name: 'com.edgedrop.app', path: mocks.exePath, enabled: false, args: [] },+ { name: 'Edge-Drop', path: mocks.exePath, enabled: false, args: ['--hidden'] }+ ],+ executableWillLaunchAtLogin: false+ })+ const result = await applyLaunchAtLogin(false)+ expect(result.enabled).toBe(false)+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith({+ openAtLogin: false,+ path: mocks.exePath,+ name: 'com.edgedrop.app'+ })+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith({+ openAtLogin: false,+ path: mocks.exePath,+ name: 'Edge-Drop'+ })+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith({+ openAtLogin: false,+ path: mocks.exePath,+ name: 'electron.app.Edge-Drop'+ })+ expect(mocks.setLoginItemSettings).not.toHaveBeenCalledWith(expect.objectContaining({ openAtLogin: true }))+ })++ it('reads Task Manager disabled items as not launching', async () => {+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [+ { name: 'Edge-Drop', path: mocks.exePath, enabled: false, args: ['--hidden'] }+ ],+ executableWillLaunchAtLogin: false+ })+ const result = await applyLaunchAtLogin(false)+ expect(result.enabled).toBe(false)+ expect(result.blockedByUser).toBe(true)+ })++ it('startup reconcile: Task Manager off + settings still on → settings become off (OS wins)', async () => {+ mocks.loadSettings.mockReturnValue({ launchAtLogin: true })+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [{ name: 'Edge-Drop', path: mocks.exePath, enabled: false }],+ executableWillLaunchAtLogin: false+ })+ const next = await reconcileLaunchAtLoginOnStartup()+ expect(mocks.saveSettings).toHaveBeenCalledWith({ launchAtLogin: false })+ expect(next.launchAtLogin).toBe(false)+ })++ it('startup reconcile: settings off + leftover enabled Run key → retries disable', async () => {+ mocks.loadSettings.mockReturnValue({ launchAtLogin: false })+ mocks.getLoginItemSettings+ .mockReturnValueOnce({+ launchItems: [{ name: 'com.edgedrop.app', path: mocks.exePath, enabled: true }],+ executableWillLaunchAtLogin: true+ })+ .mockReturnValue({+ launchItems: [],+ executableWillLaunchAtLogin: false+ })+ await reconcileLaunchAtLoginOnStartup()+ expect(mocks.setLoginItemSettings).toHaveBeenCalledWith(expect.objectContaining({+ openAtLogin: false,+ name: 'com.edgedrop.app'+ }))+ })++ it('ipc syncLoginItemSettings forwards to applyLaunchAtLogin', async () => {+ mocks.getLoginItemSettings.mockReturnValue({+ launchItems: [],+ executableWillLaunchAtLogin: false+ })+ await syncLoginItemSettings(false)+ expect(mocks.setLoginItemSettings).toHaveBeenCalled()+ })+})diff --git a/tests/storePackaging.test.ts b/tests/storePackaging.test.tsnew file mode 100644index 0000000..ca97149--- /dev/null+++ b/tests/storePackaging.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest'+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { STORE_STARTUP_TASK_ID } from '../electron/main/config'++const root = join(__dirname, '..')++function read(rel: string): string {+ return readFileSync(join(root, rel), 'utf8')+}++describe('GitHub vs Store packaging contracts (on-disk, not assumed)', () => {+ const pkg = JSON.parse(read('package.json')) as {+ scripts: Record<string, string>+ dependencies: Record<string, string>+ build: {+ asarUnpack: string[]+ extraResources?: Array<{ from: string; to: string }>+ files?: string[]+ appx: {+ identityName: string+ publisher: string+ applicationId: string+ displayName: string+ capabilities: string[]+ customExtensionsPath: string+ addAutoLaunchExtension?: boolean+ }+ publish: { provider: string; owner: string; repo: string }+ nsis: { artifactName: string }+ }+ }++ it('stamps buildTarget=github on the NSIS script and buildTarget=store on the AppX scripts', () => {+ expect(pkg.scripts['build:github']).toContain('--win nsis')+ expect(pkg.scripts['build:github']).toContain('buildTarget=github')+ expect(pkg.scripts['build:store']).toContain('--win appx')+ expect(pkg.scripts['build:store']).toContain('buildTarget=store')+ expect(pkg.scripts['build:msix']).toContain('--win appx')+ expect(pkg.scripts['build:msix']).toContain('buildTarget=store')+ expect(pkg.scripts['build:win']).toBe('npm run build:github')+ })++ it('declares the Store identity and required capabilities', () => {+ expect(pkg.build.appx.identityName).toBe('Deepender.EdgeDrop')+ expect(pkg.build.appx.publisher).toMatch(/^CN=/)+ expect(pkg.build.appx.applicationId).toBe('EdgeDrop')+ expect(pkg.build.appx.capabilities).toEqual(expect.arrayContaining(['runFullTrust', 'internetClient']))+ expect(pkg.build.appx.capabilities).not.toContain('broadFileSystemAccess')+ })++ it('points customExtensionsPath at a file that actually exists', () => {+ const rel = pkg.build.appx.customExtensionsPath+ expect(rel).toBeTruthy()+ expect(existsSync(join(root, rel))).toBe(true)+ })++ it('does not enable electron-builder SlackStartup auto-launch (we own the TaskId)', () => {+ expect(pkg.build.appx.addAutoLaunchExtension).not.toBe(true)+ expect(pkg.dependencies['electron-winstore-auto-launch']).toBeUndefined()+ expect(pkg.dependencies['@nodert-win10-au/windows.applicationmodel']).toBeUndefined()+ })++ it('ships the windowless StartupTask helper outside the asar', () => {+ expect(pkg.build.files).toEqual(expect.arrayContaining(['!resources/startup/**/*.exe']))+ expect(pkg.build.extraResources).toEqual(expect.arrayContaining([+ { from: 'resources/startup/EdgeDropStartup.exe', to: 'startup/EdgeDropStartup.exe' }+ ]))+ expect(existsSync(join(root, 'resources/startup/EdgeDropStartup.exe'))).toBe(true)+ expect(existsSync(join(root, 'resources/startup/EdgeDropStartup.cs'))).toBe(true)+ })++ it('unpacks native addons the Store package must load from disk', () => {+ const unpack = pkg.build.asarUnpack.join('\n')+ expect(unpack).toMatch(/koffi/)+ expect(unpack).toMatch(/@resvg/)+ expect(unpack).toMatch(/\{node,dll\}/)+ })++ it('keeps GitHub Releases as the NSIS publish source and NSIS artifact name', () => {+ expect(pkg.build.publish).toEqual({+ provider: 'github',+ owner: 'Deepender25',+ repo: 'Edge-Drop'+ })+ expect(pkg.build.nsis.artifactName).toContain('${version}')+ expect(pkg.build.nsis.artifactName).toMatch(/\.\$\{ext\}$/)+ })++ it('StartupTask XML uses the same TaskId as STORE_STARTUP_TASK_ID and launches Edge-Drop.exe', () => {+ const xml = read('resources/appx/startup-extensions.xml')+ expect(xml).toContain('Category="windows.startupTask"')+ expect(xml).toContain('EntryPoint="Windows.FullTrustApplication"')+ expect(xml).toContain('Executable="app\\Edge-Drop.exe"')+ expect(xml).toContain(`TaskId="${STORE_STARTUP_TASK_ID}"`)+ expect(xml).not.toContain('SlackStartup')+ expect(xml).toContain('Enabled="true"')+ expect(xml).toContain('DisplayName="Edge-Drop"')+ })++ it('electron-builder still injects customExtensionsPath into the AppX Extensions block', () => {+ const target = read('node_modules/app-builder-lib/out/targets/AppxTarget.js')+ expect(target).toContain('customExtensionsPath')+ expect(target).toContain('windows.startupTask')+ expect(target).toMatch(/extensions \+= await/)+ })++ it('main process only sets the custom AUMID on the GitHub build', () => {+ const src = read('electron/main/index.ts')+ expect(src).toMatch(/if\s*\(\s*!isStoreBuild\(\)\s*\)\s*\{[\s\S]*setAppUserModelId\('com\.edgedrop\.app'\)/)+ expect(src).not.toMatch(/setAppUserModelId\([\s\S]*isStoreBuild\(\)/)+ })++ it('Settings hides the in-app updater on Store builds', () => {+ const src = read('src/components/Settings.tsx')+ expect(src).toContain('{!isStoreBuild && (')+ expect(src).toContain('behaviour.autoUpdatesTitle')+ expect(src).toContain('hasUpdatePrompt = !isStoreBuild &&')+ })++ it('updater module hard-returns on Store for every public entry', () => {+ const src = read('electron/main/updater.ts')+ expect(src).toMatch(/export function quitAndInstallUpdate[\s\S]*if \(isStoreBuild\(\)\) return/)+ expect(src).toMatch(/export function syncAutoUpdaterState[\s\S]*if \(isStoreBuild\(\)/)+ expect(src).toMatch(/export async function checkForUpdatesManual[\s\S]*if \(isStoreBuild\(\)\)/)+ expect(src).toMatch(/export async function startUpdateDownload[\s\S]*if \(isStoreBuild\(\)/)+ expect(src).toMatch(/export function initAutoUpdater[\s\S]*if \(isStoreBuild\(\)\)/)+ })+})diff --git a/tests/storePaths.test.ts b/tests/storePaths.test.tsnew file mode 100644index 0000000..606157c--- /dev/null+++ b/tests/storePaths.test.ts@@ -0,0 +1,230 @@+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'+import { createHash } from 'node:crypto'++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+ }+})++import {+ PATHS,+ cleanTemp,+ ensureDirs,+ getUnpackagedTempDir,+ isStagedTempPath,+ toUnpackagedFilePath,+ toUnpackagedFilePaths+} from '../electron/store/paths'++function expectedStoreTemp(): string {+ return join(fsRoots.home, 'AppData', 'Local', 'Temp', 'Edge-Drop')+}++function sha10(filePath: string): string {+ return createHash('sha1').update(filePath).digest('hex').slice(0, 10)+}++describe('Store vs exe filesystem interop', () => {+ beforeEach(() => {+ delete process.env.APP_BUILD_TARGET+ fsRoots.home = join(tmpdir(), `ed-home-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ fsRoots.userData = join(tmpdir(), `ed-ud-${Date.now()}-${Math.random().toString(16).slice(2)}`)+ mkdirSync(fsRoots.home, { recursive: true })+ mkdirSync(fsRoots.userData, { recursive: true })+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ try { rmSync(fsRoots.home, { recursive: true, force: true }) } catch { /* ignore */ }+ try { rmSync(fsRoots.userData, { recursive: true, force: true }) } catch { /* ignore */ }+ })++ describe('getUnpackagedTempDir', () => {+ it('exe: is exactly userData/temp (same string as PATHS.tempDir)', () => {+ expect(getUnpackagedTempDir()).toBe(PATHS.tempDir())+ expect(getUnpackagedTempDir()).toBe(join(fsRoots.userData, 'temp'))+ })++ it('store: is the real user Local\\Temp\\Edge-Drop, not userData', () => {+ process.env.APP_BUILD_TARGET = 'store'+ const dir = getUnpackagedTempDir()+ expect(dir).toBe(expectedStoreTemp())+ expect(dir).not.toBe(PATHS.tempDir())+ expect(dir.toLowerCase()).not.toContain('packages')+ expect(dir.toLowerCase()).not.toContain('windowsapps')+ })+ })++ describe('ensureDirs / cleanTemp', () => {+ it('exe: creates images, payloads, temp under userData and does not create the Store interop folder', () => {+ ensureDirs()+ expect(existsSync(PATHS.imagesDir())).toBe(true)+ expect(existsSync(PATHS.payloadsDir())).toBe(true)+ expect(existsSync(PATHS.tempDir())).toBe(true)+ expect(existsSync(expectedStoreTemp())).toBe(false)+ })++ it('store: also creates the unpackaged Local\\Temp\\Edge-Drop directory', () => {+ process.env.APP_BUILD_TARGET = 'store'+ ensureDirs()+ expect(existsSync(PATHS.imagesDir())).toBe(true)+ expect(existsSync(expectedStoreTemp())).toBe(true)+ })++ it('exe: cleanTemp removes only files inside userData/temp', () => {+ ensureDirs()+ const keep = join(PATHS.imagesDir(), 'keep.png')+ const staged = join(PATHS.tempDir(), 'ghost.txt')+ writeFileSync(keep, 'image')+ writeFileSync(staged, 'tmp')+ cleanTemp()+ expect(existsSync(keep)).toBe(true)+ expect(existsSync(staged)).toBe(false)+ })++ it('store: cleanTemp empties both userData/temp and the unpackaged interop dir', () => {+ process.env.APP_BUILD_TARGET = 'store'+ ensureDirs()+ const ud = join(PATHS.tempDir(), 'ud.txt')+ const interop = join(expectedStoreTemp(), 'io.txt')+ writeFileSync(ud, 'a')+ writeFileSync(interop, 'b')+ cleanTemp()+ expect(existsSync(ud)).toBe(false)+ expect(existsSync(interop)).toBe(false)+ })+ })++ describe('isStagedTempPath', () => {+ it('exe: treats userData/temp children as staged and other folders as real', () => {+ const staged = join(PATHS.tempDir(), 'Snippet_abc.txt')+ const real = join(fsRoots.userData, 'images', 'x.png')+ expect(isStagedTempPath(staged)).toBe(true)+ expect(isStagedTempPath(PATHS.tempDir())).toBe(true)+ expect(isStagedTempPath(real)).toBe(false)+ expect(isStagedTempPath('')).toBe(false)+ })++ it('exe: does not treat a sibling folder whose name only shares a prefix as staged', () => {+ expect(isStagedTempPath(PATHS.tempDir() + '-evil\\file.png')).toBe(false)+ expect(isStagedTempPath(join(fsRoots.userData, 'temp2', 'x'))).toBe(false)+ })++ it('store: treats both userData/temp and the unpackaged interop dir as staged', () => {+ process.env.APP_BUILD_TARGET = 'store'+ expect(isStagedTempPath(join(PATHS.tempDir(), 'a.png'))).toBe(true)+ expect(isStagedTempPath(join(expectedStoreTemp(), 'b.png'))).toBe(true)+ expect(isStagedTempPath(join(fsRoots.home, 'Documents', 'c.png'))).toBe(false)+ })+ })++ describe('toUnpackagedFilePath — exe must be a no-op', () => {+ it('returns the original path even when the file lives under userData', () => {+ ensureDirs()+ const src = join(PATHS.imagesDir(), 'shot.png')+ writeFileSync(src, 'png-bytes')+ expect(toUnpackagedFilePath(src)).toBe(src)+ expect(existsSync(expectedStoreTemp())).toBe(false)+ })++ it('returns the original path for ordinary user documents', () => {+ const src = join(fsRoots.home, 'Documents', 'doc.pdf')+ mkdirSync(join(fsRoots.home, 'Documents'), { recursive: true })+ writeFileSync(src, 'pdf')+ expect(toUnpackagedFilePath(src)).toBe(src)+ })+ })++ describe('toUnpackagedFilePath — Store copies package-private files', () => {+ beforeEach(() => {+ process.env.APP_BUILD_TARGET = 'store'+ })++ it('copies a userData image into Local\\Temp\\Edge-Drop with a stable hash name', () => {+ ensureDirs()+ const src = join(PATHS.imagesDir(), 'img_abc.png')+ writeFileSync(src, 'real-png-bytes')+ const dest = toUnpackagedFilePath(src)+ expect(dest).not.toBe(src)+ expect(dest).toBe(join(expectedStoreTemp(), `${sha10(src)}.png`))+ expect(existsSync(dest)).toBe(true)+ expect(readFileSync(dest, 'utf8')).toBe('real-png-bytes')+ })++ it('copies files whose path is under Packages\\ (virtualized package root)', () => {+ const pkg = join(fsRoots.home, 'AppData', 'Local', 'Packages', 'Deepender.EdgeDrop_test', 'LocalCache', 'shot.png')+ mkdirSync(join(pkg, '..'), { recursive: true })+ writeFileSync(pkg, 'pkg-bytes')+ const dest = toUnpackagedFilePath(pkg)+ expect(dest).not.toBe(pkg)+ expect(dest.startsWith(expectedStoreTemp())).toBe(true)+ expect(readFileSync(dest, 'utf8')).toBe('pkg-bytes')+ })++ it('copies files whose path is under WindowsApps\\', () => {+ const winapps = join(fsRoots.home, 'WindowsApps', 'Deepender.EdgeDrop', 'resources', 'icon.png')+ mkdirSync(join(winapps, '..'), { recursive: true })+ writeFileSync(winapps, 'icon')+ const dest = toUnpackagedFilePath(winapps)+ expect(dest).not.toBe(winapps)+ expect(readFileSync(dest, 'utf8')).toBe('icon')+ })++ it('does not copy ordinary user files that already live outside the package', () => {+ const docs = join(fsRoots.home, 'Documents', 'invoice.pdf')+ mkdirSync(join(fsRoots.home, 'Documents'), { recursive: true })+ writeFileSync(docs, 'pdf-bytes')+ expect(toUnpackagedFilePath(docs)).toBe(docs)+ })++ it('returns the original path when the source file does not exist', () => {+ const missing = join(PATHS.imagesDir(), 'gone.png')+ expect(toUnpackagedFilePath(missing)).toBe(missing)+ })++ it('returns empty string unchanged', () => {+ expect(toUnpackagedFilePath('')).toBe('')+ })++ it('maps a mixed list without rewriting user files', () => {+ ensureDirs()+ const pkgFile = join(PATHS.imagesDir(), 'a.png')+ const userFile = join(fsRoots.home, 'Documents', 'b.pdf')+ mkdirSync(join(fsRoots.home, 'Documents'), { recursive: true })+ writeFileSync(pkgFile, 'a')+ writeFileSync(userFile, 'b')+ const out = toUnpackagedFilePaths([pkgFile, userFile])+ expect(out).toHaveLength(2)+ expect(out[0]).not.toBe(pkgFile)+ expect(out[1]).toBe(userFile)+ })++ it('returns the original path when the copy cannot write the destination', () => {+ ensureDirs()+ const src = join(PATHS.imagesDir(), 'fail.png')+ writeFileSync(src, 'x')+ const dest = join(expectedStoreTemp(), `${sha10(src)}.png`)+ mkdirSync(dest, { recursive: true })+ expect(toUnpackagedFilePath(src)).toBe(src)+ })+ })+})diff --git a/tests/storePowershell.test.ts b/tests/storePowershell.test.tsnew file mode 100644index 0000000..f960555--- /dev/null+++ b/tests/storePowershell.test.ts@@ -0,0 +1,131 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { existsSync, mkdirSync, rmSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'++const spawn = vi.hoisted(() =>+ vi.fn(() => ({+ stdout: { on: vi.fn() },+ stdin: { write: vi.fn() },+ on: vi.fn(),+ kill: vi.fn()+ }))+)++vi.mock('node:child_process', () => ({+ spawn,+ execFile: vi.fn()+}))++vi.mock('electron', () => ({+ app: {+ isPackaged: false,+ getAppPath: () => 'C:\\mock\\app',+ getPath: () => 'C:\\mock\\userData'+ }+}))++import { getSystemPowerShellPath, getWritableCwd } from '../electron/main/powershell'++describe('getSystemPowerShellPath', () => {+ const prev = process.env.SystemRoot++ afterEach(() => {+ if (prev === undefined) delete process.env.SystemRoot+ else process.env.SystemRoot = prev+ })++ it('uses SystemRoot when set', () => {+ process.env.SystemRoot = 'D:\\Windows'+ expect(getSystemPowerShellPath()).toBe(+ 'D:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'+ )+ })++ it('falls back to C:\\Windows when SystemRoot is unset', () => {+ delete process.env.SystemRoot+ expect(getSystemPowerShellPath()).toBe(+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'+ )+ })+})++describe('getWritableCwd', () => {+ const prev = {+ TEMP: process.env.TEMP,+ TMP: process.env.TMP,+ USERPROFILE: process.env.USERPROFILE+ }+ const realDir = join(tmpdir(), `ed-cwd-${Date.now()}`)+ const missing = join(tmpdir(), `ed-cwd-missing-${Date.now()}-nope`)++ beforeEach(() => {+ mkdirSync(realDir, { recursive: true })+ })++ afterEach(() => {+ process.env.TEMP = prev.TEMP+ process.env.TMP = prev.TMP+ process.env.USERPROFILE = prev.USERPROFILE+ try { rmSync(realDir, { recursive: true, force: true }) } catch { /* ignore */ }+ })++ it('prefers TEMP when that directory exists', () => {+ process.env.TEMP = realDir+ process.env.TMP = missing+ process.env.USERPROFILE = missing+ expect(getWritableCwd()).toBe(realDir)+ expect(existsSync(getWritableCwd())).toBe(true)+ })++ it('uses TMP when TEMP is missing', () => {+ process.env.TEMP = missing+ process.env.TMP = realDir+ process.env.USERPROFILE = missing+ expect(getWritableCwd()).toBe(realDir)+ })++ it('uses USERPROFILE when TEMP and TMP are missing', () => {+ process.env.TEMP = missing+ process.env.TMP = missing+ process.env.USERPROFILE = realDir+ expect(getWritableCwd()).toBe(realDir)+ })++ it('falls back to C:\\Windows\\Temp when none of the env dirs exist', () => {+ process.env.TEMP = missing+ process.env.TMP = missing+ process.env.USERPROFILE = missing+ expect(getWritableCwd()).toBe('C:\\Windows\\Temp')+ })+})++describe('PersistentPowerShell spawn options', () => {+ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ })++ it('GitHub exe: does not force a cwd (inherits process cwd)', async () => {+ delete process.env.APP_BUILD_TARGET+ spawn.mockClear()+ vi.resetModules()+ await import('../electron/main/powershell')+ if (process.platform !== 'win32') return+ expect(spawn).toHaveBeenCalled()+ const opts = spawn.mock.calls[0][2] as { cwd?: string; windowsHide?: boolean }+ expect(opts.windowsHide).toBe(true)+ expect(opts.cwd).toBeUndefined()+ })++ it('Store: sets cwd to a writable directory', async () => {+ process.env.APP_BUILD_TARGET = 'store'+ spawn.mockClear()+ vi.resetModules()+ const mod = await import('../electron/main/powershell')+ if (process.platform !== 'win32') return+ expect(spawn).toHaveBeenCalled()+ const opts = spawn.mock.calls[0][2] as { cwd?: string; windowsHide?: boolean }+ expect(opts.windowsHide).toBe(true)+ expect(opts.cwd).toBe(mod.getWritableCwd())+ })+})diff --git a/tests/storeStartup.test.ts b/tests/storeStartup.test.tsnew file mode 100644index 0000000..1b7e713--- /dev/null+++ b/tests/storeStartup.test.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { STORE_STARTUP_TASK_ID } from '../electron/main/config'++const exec = vi.hoisted(() => ({+ calls: [] as Array<{ file: string; args: string[]; opts: Record<string, unknown> }>,+ stdout: '2\r\n',+ fail: false+}))++vi.mock('electron', () => ({+ app: {+ getAppPath: () => join(__dirname, '..'),+ isPackaged: true,+ getPath: () => 'C:\\mock\\userData'+ }+}))++vi.mock('node:child_process', () => ({+ execFile: (file: string, args: string[], opts: unknown, cb?: Function) => {+ const callback = typeof opts === 'function' ? opts : cb+ const options = typeof opts === 'function' ? {} : (opts as Record<string, unknown>)+ exec.calls.push({ file, args, opts: options })+ if (exec.fail) {+ callback?.(Object.assign(new Error('helper failed'), { stdout: '', stderr: 'ERR' }), '', 'ERR')+ return+ }+ callback?.(null, exec.stdout, '')+ }+}))++import { disable, enable, getStatus, parseStartupHelperState } from '../electron/main/storeStartup'++const helperPath = join(__dirname, '..', 'resources', 'startup', 'EdgeDropStartup.exe')++describe('Store StartupTask (getStatus / enable / disable)', () => {+ beforeEach(() => {+ exec.calls = []+ exec.stdout = '2\r\n'+ exec.fail = false+ })++ it('helper exists as a Windows GUI process', () => {+ expect(existsSync(helperPath)).toBe(true)+ const buf = readFileSync(helperPath)+ const pe = buf.readUInt32LE(0x3c)+ expect(buf.readUInt16LE(pe + 24 + 68)).toBe(2)+ })++ it('parses the helper state line', () => {+ expect(parseStartupHelperState('2\r\n')).toBe(2)+ expect(parseStartupHelperState('0')).toBe(0)+ expect(parseStartupHelperState('1\n')).toBe(1)+ expect(parseStartupHelperState('ERR')).toBeNull()+ })++ it('enable / disable / getStatus launch the helper hidden with the manifest TaskId', async () => {+ await enable()+ await disable()+ exec.stdout = '0\n'+ await getStatus()+ expect(exec.calls.map((c) => c.args)).toEqual([+ ['enable', STORE_STARTUP_TASK_ID],+ ['disable', STORE_STARTUP_TASK_ID],+ ['get', STORE_STARTUP_TASK_ID]+ ])+ for (const call of exec.calls) {+ expect(call.file).toBe(helperPath)+ expect(call.opts.windowsHide).toBe(true)+ expect(call.file).not.toMatch(/powershell/i)+ expect(call.args.join(' ')).not.toMatch(/Invoke-CommandInDesktopPackage/)+ }+ })++ it('returns null when the helper fails so On is not faked', async () => {+ exec.fail = true+ expect(await enable()).toBeNull()+ })+})diff --git a/tests/storeUpdater.test.ts b/tests/storeUpdater.test.tsnew file mode 100644index 0000000..6cf4fcf--- /dev/null+++ b/tests/storeUpdater.test.ts@@ -0,0 +1,124 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ version: '0.2.7',+ netRequest: vi.fn(),+ updateAvailable: vi.fn(),+ getSettings: vi.fn(() => ({ autoUpdates: true }))+}))++vi.mock('electron', () => ({+ app: {+ getVersion: () => mocks.version,+ isPackaged: true,+ getAppPath: () => 'C:\\mock\\app',+ getPath: () => 'C:\\mock\\userData'+ },+ net: {+ request: (...args: unknown[]) => mocks.netRequest(...args)+ }+}))++vi.mock('../electron/main/state', () => ({+ pushState: {+ updateAvailable: (...args: unknown[]) => mocks.updateAvailable(...args),+ updateDownloaded: vi.fn()+ }+}))++vi.mock('../electron/store/settings', () => ({+ getSettings: () => mocks.getSettings()+}))++import {+ checkForUpdatesManual,+ initAutoUpdater,+ quitAndInstallUpdate,+ startUpdateDownload,+ syncAutoUpdaterState+} from '../electron/main/updater'++function mockGithubRelease(tag: string, statusCode = 200): void {+ mocks.netRequest.mockImplementation(() => {+ const handlers: Record<string, Array<(...a: unknown[]) => void>> = {}+ return {+ setHeader: vi.fn(),+ abort: vi.fn(),+ on: (ev: string, cb: (...a: unknown[]) => void) => {+ (handlers[ev] ??= []).push(cb)+ },+ end: () => {+ const response = {+ statusCode,+ on: (ev: string, cb: (chunk?: string) => void) => {+ if (ev === 'data') cb(JSON.stringify({ tag_name: tag }))+ if (ev === 'end') cb()+ }+ }+ for (const cb of handlers.response ?? []) cb(response)+ }+ }+ })+}++describe('auto-updater isolation', () => {+ beforeEach(() => {+ delete process.env.APP_BUILD_TARGET+ mocks.netRequest.mockReset()+ mocks.updateAvailable.mockReset()+ mocks.netRequest.mockImplementation(() => {+ throw new Error('net.request must not run on the Store build')+ })+ })++ afterEach(() => {+ delete process.env.APP_BUILD_TARGET+ })++ describe('Store build', () => {+ beforeEach(() => {+ process.env.APP_BUILD_TARGET = 'store'+ })++ it('checkForUpdatesManual reports up-to-date at the running version and never touches the network', async () => {+ const result = await checkForUpdatesManual()+ expect(result).toEqual({ status: 'up-to-date', version: '0.2.7' })+ expect(mocks.netRequest).not.toHaveBeenCalled()+ expect(mocks.updateAvailable).not.toHaveBeenCalled()+ })++ it('quitAndInstallUpdate / startUpdateDownload / sync / init are no-ops', async () => {+ expect(() => quitAndInstallUpdate()).not.toThrow()+ await expect(startUpdateDownload()).resolves.toBeUndefined()+ expect(() => syncAutoUpdaterState()).not.toThrow()+ expect(() => initAutoUpdater()).not.toThrow()+ expect(mocks.netRequest).not.toHaveBeenCalled()+ })+ })++ describe('GitHub exe build', () => {+ it('checkForUpdatesManual reports available when GitHub latest is newer', async () => {+ mockGithubRelease('v0.2.8')+ const result = await checkForUpdatesManual()+ expect(result).toEqual({ status: 'available', version: '0.2.8' })+ expect(mocks.netRequest).toHaveBeenCalled()+ expect(mocks.updateAvailable).toHaveBeenCalledWith({ version: '0.2.8' })+ })++ it('checkForUpdatesManual reports up-to-date when GitHub latest matches', async () => {+ mockGithubRelease('v0.2.7')+ const result = await checkForUpdatesManual()+ expect(result).toEqual({ status: 'up-to-date', version: '0.2.7' })+ expect(mocks.updateAvailable).not.toHaveBeenCalled()+ })++ it('checkForUpdatesManual hits the Edge-Drop releases endpoint', async () => {+ mockGithubRelease('v0.2.7')+ await checkForUpdatesManual()+ expect(mocks.netRequest).toHaveBeenCalledWith(expect.objectContaining({+ method: 'GET',+ url: 'https://api.github.com/repos/Deepender25/Edge-Drop/releases/latest'+ }))+ })+ })+})