From aa17c8051499a4d82b8b0d058f7250e3025ba7cd Mon Sep 17 00:00:00 2001 From: Vendicated Date: Mon, 2 Nov 2026 23:41:18 +0100 Subject: [PATCH] Fix various potential issues - Screenshare Picker: fix stream never starting on Windows & macOS due to using venmic without linux guard - make Vencord downloads atomic for increased resilience - `--repair`: exit instead of hanging when the download fails - fix relaunch & autostart on AppImage - show an error dialog with prompt to repair when startup fails - Updater: ensure only one Window is opened to avoid issues - update-aur: fix env var names, avoid printing the aur ssh key - use tighter permission request handlers to avoid granting frames broad permissions - prevent the main window from navigating away from Discord - only serve thumbnails over IPC when screenshare picker is open, so renderer can't screenshot system at will - fix Vesktop crashing if saved settings files contain invalid values - write settings atomically, debounce saving window bounds - Reset Vesktop: delete data on next start to avoid issues on Windows due to file locking - handle discord:// deep links while already running - Tray: guard against destroyed Tray Based on findings by Claude Opus 5.5 --- .github/workflows/update-aur-pkg.sh | 7 +- scripts/build/sandboxFix.mjs | 6 +- src/main/autoStart.ts | 10 ++- src/main/constants.ts | 15 +++- src/main/index.ts | 7 +- src/main/ipc.ts | 30 +------ src/main/main.ts | 20 +++-- src/main/mainWindow.ts | 87 +++++++++++++++---- src/main/mediaPermissions.ts | 16 +++- src/main/screenShare.ts | 12 +++ src/main/settings.ts | 10 ++- src/main/splash.ts | 7 +- src/main/tray.ts | 25 +++--- src/main/updater.ts | 6 ++ src/main/utils/clearData.ts | 20 ++--- src/main/utils/ipcWrappers.ts | 2 +- src/main/utils/isDiscordUrl.ts | 14 +++ src/main/utils/relaunch.ts | 28 ++++++ src/main/utils/vencordLoader.ts | 35 +++++--- src/main/venmic.ts | 13 +-- src/renderer/components/ScreenSharePicker.tsx | 27 ++++-- src/renderer/ipcCommands.ts | 4 +- src/shared/IpcEvents.ts | 1 + 23 files changed, 282 insertions(+), 120 deletions(-) create mode 100644 src/main/utils/isDiscordUrl.ts create mode 100644 src/main/utils/relaunch.ts diff --git a/.github/workflows/update-aur-pkg.sh b/.github/workflows/update-aur-pkg.sh index f79f7940..1cd07af3 100644 --- a/.github/workflows/update-aur-pkg.sh +++ b/.github/workflows/update-aur-pkg.sh @@ -4,7 +4,10 @@ set -exuo pipefail cd ~ install -d -m 0700 ~/.ssh +# don't print the key via xtrace +set +x echo "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur +set -x chmod 0600 ~/.ssh/aur cat > ~/.ssh/config <<'EOF' Host aur.archlinux.org @@ -32,7 +35,7 @@ if git diff --cached --quiet; then exit 0 fi -if [[ "$AUR_EVENT_NAME" == workflow_dispatch ]]; then +if [[ "$EVENT_NAME" == workflow_dispatch ]]; then echo "Skipping push for workflow dispatch" exit 0 fi @@ -40,5 +43,5 @@ fi git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" -git commit -m "Update vesktop-bin to $AUR_RELEASE_TAG" +git commit -m "Update vesktop-bin to $RELEASE_TAG" git push diff --git a/scripts/build/sandboxFix.mjs b/scripts/build/sandboxFix.mjs index e7425e41..39a26bf9 100644 --- a/scripts/build/sandboxFix.mjs +++ b/scripts/build/sandboxFix.mjs @@ -46,14 +46,14 @@ export async function applyAppImageSandboxFix() { #!/usr/bin/env bash SCRIPT_DIR="$( cd "$( dirname "\${BASH_SOURCE[0]}" )" && pwd )" -IS_STEAMOS=0 +ARGS=() if [[ "$SteamOS" == "1" && "$SteamGamepadUI" == "1" ]]; then echo "Running Vesktop on SteamOS, disabling sandbox" - IS_STEAMOS=1 + ARGS+=(--no-sandbox) fi -exec "$SCRIPT_DIR/${this.packager.executableName}.bin" "$([ "$IS_STEAMOS" == 1 ] && echo '--no-sandbox')" "$@" +exec "$SCRIPT_DIR/${this.packager.executableName}.bin" "\${ARGS[@]}" "$@" `.trim(); try { diff --git a/src/main/autoStart.ts b/src/main/autoStart.ts index 1f763bbe..d2746002 100644 --- a/src/main/autoStart.ts +++ b/src/main/autoStart.ts @@ -22,9 +22,15 @@ interface AutoStart { } function getEscapedCommandLine() { - const args = process.argv.map(escapeDesktopFileArgument); + // inside an AppImage, argv[0] is a temporary mount + const exe = (app.isPackaged && process.env.APPIMAGE) || process.execPath; + const args = process.argv + .slice(1) // skip the executable path + .filter(arg => arg !== "--start-minimized" && arg !== "-m" && !arg.startsWith("discord://")); + if (Settings.store.autoStartMinimized) args.push("--start-minimized"); - return args; + + return [exe, ...args].map(escapeDesktopFileArgument); } function makeAutoStartLinuxDesktop(): AutoStart { diff --git a/src/main/constants.ts b/src/main/constants.ts index ac9debe0..910285ad 100644 --- a/src/main/constants.ts +++ b/src/main/constants.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { existsSync, mkdirSync } from "fs"; +import { existsSync, mkdirSync, rmSync } from "fs"; import { dirname, join } from "path"; import { app } from "electron"; @@ -21,6 +21,19 @@ export const PORTABLE = export const DATA_DIR = process.env.VENCORD_USER_DATA_DIR || (PORTABLE ? join(vesktopDir, "Data") : join(app.getPath("userData"))); +// Written by "Reset Vesktop". Our data is deleted here on the next start, before anything uses it +export const RESET_MARKER_FILE = join(DATA_DIR, ".reset-pending"); +if (existsSync(RESET_MARKER_FILE)) { + try { + for (const entry of ["sessionData", "settings", "themes", "userAssets", "settings.json", "state.json"]) { + rmSync(join(DATA_DIR, entry), { recursive: true, force: true, maxRetries: 5 }); + } + rmSync(RESET_MARKER_FILE); + } catch (err) { + console.error("Failed to reset Vesktop data:", err); + } +} + mkdirSync(DATA_DIR, { recursive: true }); export const SESSION_DATA_DIR = join(DATA_DIR, "sessionData"); diff --git a/src/main/index.ts b/src/main/index.ts index 181ef123..b12c582e 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -11,7 +11,12 @@ import { downloadVencordFiles } from "./utils/vencordLoader"; if (CommandLine.values.repair) { console.log("Repairing Vesktop..."); - downloadVencordFiles().then(() => app.quit()); + downloadVencordFiles() + .then(() => app.quit()) + .catch(err => { + console.error("Failed to repair Vesktop:", err); + app.exit(1); + }); } else { require("./main"); } diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 7e1daf98..3a37ef56 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -6,23 +6,12 @@ if (process.platform === "linux") import("./venmic"); -import { execFile } from "child_process"; import { readFileSync, watch } from "fs"; import { readFile, stat } from "fs/promises"; import { release } from "os"; import { join } from "path"; -import { - app, - BrowserWindow, - clipboard, - ClipboardItem, - dialog, - IpcMainInvokeEvent, - RelaunchOptions, - session, - shell -} from "electron"; +import { app, BrowserWindow, clipboard, ClipboardItem, dialog, IpcMainInvokeEvent, session, shell } from "electron"; import { IpcEvents } from "../shared/IpcEvents"; import { setBadgeCount } from "./appBadge"; @@ -32,8 +21,8 @@ import { mainWin } from "./mainWindow"; import { Settings, State } from "./settings"; import { handle, handleSync } from "./utils/ipcWrappers"; import { PopoutWindows } from "./utils/popout"; +import { relaunch } from "./utils/relaunch"; import { showWindow } from "./utils/showWindow"; -import { isDeckGameMode, showGamePage } from "./utils/steamOS"; import { isValidVencordInstall } from "./utils/vencordLoader"; import { VENCORD_FILES_DIR } from "./vencordFilesDir"; @@ -75,20 +64,7 @@ handle(IpcEvents.SET_SETTINGS, (_, settings: typeof Settings.store, path?: strin Settings.setData(settings, path); }); -handle(IpcEvents.RELAUNCH, async () => { - const options: RelaunchOptions = { - args: process.argv.slice(1).concat(["--relaunch"]) - }; - if (isDeckGameMode) { - // We can't properly relaunch when running under gamescope, but we can at least navigate to our page in Steam. - await showGamePage(); - } else if (app.isPackaged && process.env.APPIMAGE) { - execFile(process.env.APPIMAGE, options.args); - } else { - app.relaunch(options); - } - app.exit(); -}); +handle(IpcEvents.RELAUNCH, relaunch); handleSync(IpcEvents.IS_USING_CUSTOM_VENCORD_DIR, () => !!State.store.vencordDir); handle(IpcEvents.SHOW_CUSTOM_VENCORD_DIR, async () => { diff --git a/src/main/main.ts b/src/main/main.ts index 00edb879..7fe2a3c5 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -14,7 +14,7 @@ import { app, BrowserWindow, nativeTheme } from "electron"; import { DATA_DIR } from "./constants"; import { createFirstLaunchTour } from "./firstLaunch"; -import { createWindows, mainWin } from "./mainWindow"; +import { createWindows, mainWin, openDeepLink } from "./mainWindow"; import { registerMediaPermissionsHandler } from "./mediaPermissions"; import { registerScreenShareHandler } from "./screenShare"; import { Settings, State } from "./settings"; @@ -92,9 +92,14 @@ function init() { // In the Flatpak on SteamOS the theme is detected as light, but SteamOS only has a dark mode, so we just override it if (isDeckGameMode) nativeTheme.themeSource = "dark"; - app.on("second-instance", (_event, _cmdLine, _cwd, data: any) => { - if (data.IS_DEV) app.quit(); - else if (mainWin) showWindow(mainWin); + app.on("second-instance", (_event, cmdLine, _cwd, data: any) => { + if (data?.IS_DEV) return app.quit(); + if (!mainWin) return; + + const deepLink = cmdLine.find(arg => arg.startsWith("discord://")); + if (deepLink) openDeepLink(deepLink); + + showWindow(mainWin); }); app.whenReady().then(async () => { @@ -134,7 +139,12 @@ async function bootstrap() { // MacOS only event export let darwinURL: string | undefined; app.on("open-url", (_, url) => { - darwinURL = url; + if (mainWin) { + openDeepLink(url); + showWindow(mainWin); + } else { + darwinURL = url; + } }); app.on("window-all-closed", () => { diff --git a/src/main/mainWindow.ts b/src/main/mainWindow.ts index 1ed870b6..93ff3bf6 100644 --- a/src/main/mainWindow.ts +++ b/src/main/mainWindow.ts @@ -10,6 +10,7 @@ import { app, BrowserWindow, BrowserWindowConstructorOptions, + dialog, Menu, MenuItemConstructorOptions, nativeTheme, @@ -18,13 +19,14 @@ import { session } from "electron"; import { IpcCommands, IpcEvents } from "shared/IpcEvents"; +import { debounce } from "shared/utils/debounce"; import { isTruthy } from "shared/utils/guards"; import { once } from "shared/utils/once"; import type { SettingsStore } from "shared/utils/SettingsStore"; import { createAboutWindow } from "./about"; import { CommandLine } from "./cli"; -import { BrowserUserAgent, DEFAULT_HEIGHT, DEFAULT_WIDTH, MIN_HEIGHT, MIN_WIDTH } from "./constants"; +import { BrowserUserAgent, DEFAULT_HEIGHT, DEFAULT_WIDTH, MessageBoxChoice, MIN_HEIGHT, MIN_WIDTH } from "./constants"; import { AppEvents } from "./events"; import { sendRendererCommand } from "./ipcCommands"; import { darwinURL } from "./main"; @@ -32,9 +34,11 @@ import { Settings, State, VencordSettings } from "./settings"; import { createSplashWindow, updateSplashMessage } from "./splash"; import { destroyTray, initTray } from "./tray"; import { clearData } from "./utils/clearData"; -import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; +import { isDiscordUrl } from "./utils/isDiscordUrl"; +import { handleExternalUrl, makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; +import { relaunch } from "./utils/relaunch"; import { applyDeckKeyboardFix, askToApplySteamLayout, isDeckGameMode } from "./utils/steamOS"; -import { downloadVencordFiles, ensureVencordFiles } from "./utils/vencordLoader"; +import { downloadVencordFiles, isValidVencordInstall } from "./utils/vencordLoader"; import { VENCORD_FILES_DIR } from "./vencordFilesDir"; let isQuitting = false; @@ -84,8 +88,7 @@ function initMenuBar(win: BrowserWindow) { label: "Force Update Vencord", async click() { await downloadVencordFiles(); - app.relaunch(); - app.quit(); + relaunch(); }, toolTip: "Vesktop will automatically restart after this operation" }, @@ -99,10 +102,7 @@ function initMenuBar(win: BrowserWindow) { { label: "Relaunch", accelerator: "CmdOrCtrl+Shift+R", - click() { - app.relaunch(); - app.quit(); - } + click: relaunch }, ...(!isDarwin ? [] @@ -206,11 +206,12 @@ function initWindowBoundsListeners(win: BrowserWindow) { win.on("unmaximize", saveState); win.on("restore", saveState); - const saveBounds = () => { - if (win.isMaximized()) return; + // move and resize fire continuously while dragging + const saveBounds = debounce(() => { + if (win.isDestroyed() || win.isMaximized()) return; State.store.windowBounds = win.getBounds(); - }; + }); win.on("resize", saveBounds); win.on("move", saveBounds); @@ -297,6 +298,18 @@ function initStaticTitle(win: BrowserWindow) { }); } +function initNavigationGuard(win: BrowserWindow) { + const onNavigate = (e: Electron.Event<{ url: string; isMainFrame: boolean }>) => { + if (!e.isMainFrame || isDiscordUrl(e.url)) return; + + e.preventDefault(); + handleExternalUrl(e.url); + }; + + win.webContents.on("will-navigate", onNavigate); + win.webContents.on("will-redirect", onNavigate); +} + function getWindowBoundsOptions(): BrowserWindowConstructorOptions { // We want the default window behaviour to apply in game mode since it expects everything to be fullscreen and maximized. if (isDeckGameMode) return {}; @@ -430,6 +443,7 @@ function createMainWindow() { initMenuBar(win); makeLinksOpenExternally(win); + initNavigationGuard(win); initSettingsListeners(win); initSpellCheck(win); initDevtoolsListeners(win); @@ -448,17 +462,33 @@ function createMainWindow() { const runVencordMain = once(() => require(join(VENCORD_FILES_DIR, "vencordDesktopMain.js"))); +// discord://-/channels/@me -> /channels/@me +function getDeepLinkPath(uri: string | undefined) { + if (!uri || !URL.canParse(uri)) return; + + return new URL(uri).pathname; +} + export function loadUrl(uri: string | undefined) { const branch = Settings.store.discordBranch; const subdomain = branch === "canary" || branch === "ptb" ? `${branch}.` : ""; + const path = getDeepLinkPath(uri)?.slice(1) || "app"; // we do not rely on 'did-finish-load' because it fires even if loadURL fails which triggers early detruction of the splash mainWin - .loadURL(`https://${subdomain}discord.com/${uri ? new URL(uri).pathname.slice(1) || "app" : "app"}`) + .loadURL(`https://${subdomain}discord.com/${path}`) .then(() => AppEvents.emit("appLoaded")) .catch(error => retryUrl(error.url, error.code)); } +// Navigates within Discord instead of reloading, used for links opened while we're already running +export function openDeepLink(uri: string) { + const path = getDeepLinkPath(uri); + if (!path) return; + + sendRendererCommand(IpcCommands.NAVIGATE, path).catch(err => console.error("Failed to open deep link", uri, err)); +} + const retryDelay = 1000; function retryUrl(url: string, description: string) { console.log(`retrying in ${retryDelay}ms`); @@ -466,6 +496,22 @@ function retryUrl(url: string, description: string) { setTimeout(() => loadUrl(url), retryDelay); } +async function showStartupError(error: unknown) { + const { response } = await dialog.showMessageBox({ + type: "error", + message: "Vesktop failed to start", + detail: `${error}\n\nRepair will re-download Vencord and restart Vesktop.`, + buttons: ["Repair", "Quit"], + defaultId: MessageBoxChoice.Default, + cancelId: MessageBoxChoice.Cancel + }); + + if (response === MessageBoxChoice.Cancel) return app.exit(1); + + updateSplashMessage("Repairing Vencord..."); + downloadVencordFiles().then(relaunch, showStartupError); +} + export async function createWindows() { const startMinimized = CommandLine.values["start-minimized"]; @@ -477,10 +523,19 @@ export async function createWindows() { if (isDeckGameMode) splash.setFullScreen(true); } - await ensureVencordFiles(); - runVencordMain(); + try { + if (!(await isValidVencordInstall(VENCORD_FILES_DIR))) { + updateSplashMessage("Downloading Vencord..."); + await downloadVencordFiles(); + } - mainWin = createMainWindow(); + runVencordMain(); + + mainWin = createMainWindow(); + } catch (err) { + console.error("Failed to start Vesktop:", err); + return showStartupError(err); + } AppEvents.on("appLoaded", () => { splash?.destroy(); diff --git a/src/main/mediaPermissions.ts b/src/main/mediaPermissions.ts index 6e7e6646..ce1b4e57 100644 --- a/src/main/mediaPermissions.ts +++ b/src/main/mediaPermissions.ts @@ -6,13 +6,23 @@ import { session, systemPreferences } from "electron"; +import { isDiscordUrl } from "./utils/isDiscordUrl"; + +// Electron grants every permission by default. Only allow them for Discord, not for other sites +// (e.g. opened via openLinksWithElectron) or our own views export function registerMediaPermissionsHandler() { - if (process.platform !== "darwin") return; + // webContents is null for some checks (e.g. notifications and cross-origin subframes), so go by origin + session.defaultSession.setPermissionCheckHandler((_webContents, _permission, requestingOrigin, details) => + isDiscordUrl(details.embeddingOrigin ?? requestingOrigin) + ); + + session.defaultSession.setPermissionRequestHandler(async (webContents, _permission, callback, details) => { + // check the top level url so that frames embedded by Discord (e.g. YouTube) keep working + if (!isDiscordUrl(webContents.getURL())) return callback(false); - session.defaultSession.setPermissionRequestHandler(async (_webContents, permission, callback, details) => { let granted = true; - if ("mediaTypes" in details) { + if (process.platform === "darwin" && "mediaTypes" in details) { if (details.mediaTypes?.includes("audio")) { granted &&= await systemPreferences.askForMediaAccess("microphone"); } diff --git a/src/main/screenShare.ts b/src/main/screenShare.ts index 676db330..3459bc94 100644 --- a/src/main/screenShare.ts +++ b/src/main/screenShare.ts @@ -12,14 +12,21 @@ import { IpcCommands, IpcEvents } from "shared/IpcEvents"; import { sendRendererCommand } from "./ipcCommands"; import { handle } from "./utils/ipcWrappers"; +import { isDiscordUrl } from "./utils/isDiscordUrl"; const isWayland = process.platform === "linux" && (process.env.XDG_SESSION_TYPE === "wayland" || !!process.env.WAYLAND_DISPLAY); const supportsLoopbackWithoutChrome = process.platform === "win32" && Number(release().split(".").pop()) >= 19045; +// Sources shown in the currently open picker. Only serve thumbnails for these, +// otherwise the renderer could silently take screenshots of any window or screen +let pickerSourceIds = new Set(); + export function registerScreenShareHandler() { handle(IpcEvents.CAPTURER_GET_LARGE_THUMBNAIL, async (_, id: string) => { + if (!pickerSourceIds.has(id)) return; + const sources = await desktopCapturer.getSources({ types: ["window", "screen"], thumbnailSize: { @@ -31,6 +38,9 @@ export function registerScreenShareHandler() { }); session.defaultSession.setDisplayMediaRequestHandler(async (request, callback) => { + // the handler applies to the whole session, so other sites (e.g. opened via openLinksWithElectron) would get our picker + if (!isDiscordUrl(request.frame?.top?.url)) return callback(null); + // request full resolution on wayland right away because we always only end up with one result anyway const width = isWayland ? 1920 : 176; const sources = await desktopCapturer @@ -69,6 +79,7 @@ export function registerScreenShareHandler() { return; } + pickerSourceIds = new Set(data.map(s => s.id)); const choice = await sendRendererCommand(IpcCommands.SCREEN_SHARE_PICKER, { screens: data, skipPicker: false @@ -76,6 +87,7 @@ export function registerScreenShareHandler() { console.error("Error during screenshare picker", e); return null; }); + pickerSourceIds.clear(); if (!choice) return callback(null); diff --git a/src/main/settings.ts b/src/main/settings.ts index d78b1a11..9397f67b 100644 --- a/src/main/settings.ts +++ b/src/main/settings.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { mkdirSync, readFileSync, writeFileSync } from "fs"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "fs"; import { dirname, join } from "path"; import { type Settings as TVencordSettings } from "@vencord/types/Vencord"; @@ -23,7 +23,9 @@ function loadSettings(file: string, name: string, defaul try { const content = readFileSync(file, "utf8"); try { - settings = JSON.parse(content); + const parsed = JSON.parse(content); + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) settings = parsed; + else console.error(`Ignoring ${name}.json because it is not an object`); } catch (err) { console.error(`Failed to parse ${name}.json:`, err); } @@ -37,7 +39,9 @@ function loadSettings(file: string, name: string, defaul store.addGlobalChangeListener(o => { try { mkdirSync(dirname(file), { recursive: true }); - writeFileSync(file, JSON.stringify(o, null, 4)); + // write to a temp file first to avoid potential corruption + writeFileSync(file + ".tmp", JSON.stringify(o, null, 4)); + renameSync(file + ".tmp", file); } catch (err) { console.error(`Failed to save settings to ${name}.json:`, err); } diff --git a/src/main/splash.ts b/src/main/splash.ts index b5a87f19..afbada3a 100644 --- a/src/main/splash.ts +++ b/src/main/splash.ts @@ -13,6 +13,7 @@ import { Settings } from "./settings"; import { loadView } from "./vesktopStatic"; let splash: BrowserWindow | undefined; +let message = ""; export function createSplashWindow(startMinimized = false) { splash = new BrowserWindow({ @@ -23,6 +24,9 @@ export function createSplashWindow(startMinimized = false) { } }); + // messages sent before the page finished loading are lost, so resend the latest one + splash.webContents.on("did-finish-load", () => updateSplashMessage(message)); + const { splashBackground, splashColor, splashTheming, splashPixelated } = Settings.store; const params = new URLSearchParams(); @@ -37,6 +41,7 @@ export function createSplashWindow(startMinimized = false) { return splash; } -export function updateSplashMessage(message: string) { +export function updateSplashMessage(newMessage: string) { + message = newMessage; if (splash && !splash.isDestroyed()) splash.webContents.send("update-splash-message", message); } diff --git a/src/main/tray.ts b/src/main/tray.ts index 40711c12..1d2c322c 100644 --- a/src/main/tray.ts +++ b/src/main/tray.ts @@ -11,29 +11,32 @@ import { AppEvents } from "./events"; import { Settings } from "./settings"; import { resolveAssetPath } from "./userAssets"; import { clearData } from "./utils/clearData"; +import { relaunch } from "./utils/relaunch"; import { showWindow } from "./utils/showWindow"; import { downloadVencordFiles } from "./utils/vencordLoader"; -let tray: Tray; +let tray: Tray | undefined; let trayVariant: "tray" | "trayUnread" = "tray"; +// resolve the image before checking tray, as it might get destroyed in the meantime AppEvents.on("userAssetChanged", async asset => { - if (tray && (asset === "tray" || asset === "trayUnread")) { - tray.setImage(await resolveAssetPath(trayVariant)); - } + if (asset !== "tray" && asset !== "trayUnread") return; + + const image = await resolveAssetPath(trayVariant); + tray?.setImage(image); }); AppEvents.on("setTrayVariant", async variant => { if (trayVariant === variant) return; trayVariant = variant; - if (!tray) return; - - tray.setImage(await resolveAssetPath(trayVariant)); + const image = await resolveAssetPath(trayVariant); + tray?.setImage(image); }); export function destroyTray() { tray?.destroy(); + tray = undefined; } export async function initTray(win: BrowserWindow, setIsQuitting: (val: boolean) => void) { @@ -57,8 +60,7 @@ export async function initTray(win: BrowserWindow, setIsQuitting: (val: boolean) label: "Repair Vencord", async click() { await downloadVencordFiles(); - app.relaunch(); - app.quit(); + relaunch(); } }, { @@ -72,10 +74,7 @@ export async function initTray(win: BrowserWindow, setIsQuitting: (val: boolean) }, { label: "Restart", - click() { - app.relaunch(); - app.quit(); - } + click: relaunch }, { label: "Quit", diff --git a/src/main/updater.ts b/src/main/updater.ts index e12fc9fd..944f77cd 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -15,6 +15,7 @@ import { PORTABLE } from "./constants"; import { State } from "./settings"; import { handle } from "./utils/ipcWrappers"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; +import { showWindow } from "./utils/showWindow"; import { loadView } from "./vesktopStatic"; let updaterWindow: BrowserWindow | null = null; @@ -45,6 +46,11 @@ handle(IpcEvents.UPDATER_OPEN, async () => { }); function openUpdater(update: UpdateInfo) { + if (updaterWindow) { + showWindow(updaterWindow); + return; + } + updaterWindow = new BrowserWindow({ title: "Vesktop Updater", autoHideMenuBar: true, diff --git a/src/main/utils/clearData.ts b/src/main/utils/clearData.ts index bde4b788..2be6cdd4 100644 --- a/src/main/utils/clearData.ts +++ b/src/main/utils/clearData.ts @@ -4,10 +4,12 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { rm } from "fs/promises"; +import { writeFile } from "fs/promises"; -import { app, BrowserWindow, dialog } from "electron"; -import { DATA_DIR, MessageBoxChoice } from "main/constants"; +import { BrowserWindow, dialog } from "electron"; +import { MessageBoxChoice, RESET_MARKER_FILE } from "main/constants"; + +import { relaunch } from "./relaunch"; export async function clearData(win: BrowserWindow) { const { response } = await dialog.showMessageBox(win, { @@ -21,13 +23,7 @@ export async function clearData(win: BrowserWindow) { if (response === MessageBoxChoice.Cancel) return; - win.close(); - - await win.webContents.session.clearStorageData(); - await win.webContents.session.clearCache(); - await win.webContents.session.clearCodeCaches({}); - await rm(DATA_DIR, { force: true, recursive: true }); - - app.relaunch(); - app.quit(); + // Chromium keeps files open while running, so the data is deleted on the next start instead + await writeFile(RESET_MARKER_FILE, ""); + relaunch(); } diff --git a/src/main/utils/ipcWrappers.ts b/src/main/utils/ipcWrappers.ts index 1ce0e6cb..1edcaee9 100644 --- a/src/main/utils/ipcWrappers.ts +++ b/src/main/utils/ipcWrappers.ts @@ -18,7 +18,7 @@ export function validateSender(frame: WebFrameMain | null, event: string) { throw new Error(`ipc[${event}]: Invalid URL ${frame.url}`); } - if (protocol === "file:" || protocol === "vesktop:") return; + if (protocol === "vesktop:") return; if (!DISCORD_HOSTNAMES.includes(hostname)) { throw new Error(`ipc[${event}]: Disallowed hostname ${hostname}`); diff --git a/src/main/utils/isDiscordUrl.ts b/src/main/utils/isDiscordUrl.ts new file mode 100644 index 00000000..f201c14b --- /dev/null +++ b/src/main/utils/isDiscordUrl.ts @@ -0,0 +1,14 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { DISCORD_HOSTNAMES } from "main/constants"; + +export function isDiscordUrl(url: string | undefined) { + if (!url || !URL.canParse(url)) return false; + + const { protocol, hostname } = new URL(url); + return protocol === "https:" && DISCORD_HOSTNAMES.includes(hostname); +} diff --git a/src/main/utils/relaunch.ts b/src/main/utils/relaunch.ts new file mode 100644 index 00000000..2ed84823 --- /dev/null +++ b/src/main/utils/relaunch.ts @@ -0,0 +1,28 @@ +/* + * Vesktop, a desktop app aiming to give you a snappier Discord Experience + * Copyright (c) 2026 Vendicated and Vesktop contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { execFile } from "child_process"; + +import { app } from "electron"; + +import { isDeckGameMode, showGamePage } from "./steamOS"; + +export async function relaunch() { + if (isDeckGameMode) { + // We can't properly relaunch when running under gamescope, but we can at least navigate to our page in Steam. + await showGamePage(); + } else if (app.isPackaged && process.env.APPIMAGE) { + // app.relaunch() would start the binary inside the AppImage mount, which is gone once we exit + app.relaunch({ + execPath: process.env.APPIMAGE, + args: process.argv.slice(1) + }); + } else { + app.relaunch(); + } + + app.exit(); +} diff --git a/src/main/utils/vencordLoader.ts b/src/main/utils/vencordLoader.ts index 758fd660..7bd7a496 100644 --- a/src/main/utils/vencordLoader.ts +++ b/src/main/utils/vencordLoader.ts @@ -5,7 +5,7 @@ */ import { mkdirSync } from "fs"; -import { access, constants as FsConstants, writeFile } from "fs/promises"; +import { access, constants as FsConstants, rename, writeFile } from "fs/promises"; import { join } from "path"; import { VENCORD_FILES_DIR } from "main/vencordFilesDir"; @@ -49,14 +49,29 @@ export async function downloadVencordFiles() { const release = await githubGet("/repos/Vendicated/Vencord/releases/latest"); const { assets }: ReleaseData = await release.json(); + const files = assets.filter(({ name }) => FILES_TO_DOWNLOAD.some(f => name.startsWith(f))); + + mkdirSync(VENCORD_FILES_DIR, { recursive: true }); + + // Download to temp files and only move them into place once all succeeded, + // so an interrupted download can't leave a broken install behind + const results = await Promise.allSettled( + files.map(({ name, browser_download_url }) => + downloadFile( + browser_download_url, + join(VENCORD_FILES_DIR, name + ".tmp"), + {}, + { retryOnNetworkError: true } + ) + ) + ); + const failed = results.find(r => r.status === "rejected"); + if (failed) throw failed.reason; await Promise.all( - assets - .filter(({ name }) => FILES_TO_DOWNLOAD.some(f => name.startsWith(f))) - .map(({ name, browser_download_url }) => - downloadFile(browser_download_url, join(VENCORD_FILES_DIR, name), {}, { retryOnNetworkError: true }) - ) + files.map(({ name }) => rename(join(VENCORD_FILES_DIR, name + ".tmp"), join(VENCORD_FILES_DIR, name))) ); + await writeFile(join(VENCORD_FILES_DIR, "package.json"), "{}"); } const existsAsync = (path: string) => @@ -68,11 +83,3 @@ export async function isValidVencordInstall(dir: string) { const results = await Promise.all(FILES_TO_DOWNLOAD.map(f => existsAsync(join(dir, f)))); return !results.includes(false); } - -export async function ensureVencordFiles() { - if (await isValidVencordInstall(VENCORD_FILES_DIR)) return; - - mkdirSync(VENCORD_FILES_DIR, { recursive: true }); - - await Promise.all([downloadVencordFiles(), writeFile(join(VENCORD_FILES_DIR, "package.json"), "{}")]); -} diff --git a/src/main/venmic.ts b/src/main/venmic.ts index e605a44c..d0b929a5 100644 --- a/src/main/venmic.ts +++ b/src/main/venmic.ts @@ -7,11 +7,12 @@ import { join } from "path"; import type { LinkData, Node, PatchBay as PatchBayType } from "@vencord/venmic"; -import { app, ipcMain } from "electron"; +import { app } from "electron"; import { IpcEvents } from "shared/IpcEvents"; import { STATIC_DIR } from "shared/paths"; import { Settings } from "./settings"; +import { handle } from "./utils/ipcWrappers"; let PatchBay: typeof PatchBayType | undefined; let patchBayInstance: PatchBayType | undefined; @@ -99,7 +100,7 @@ function buildLinkData({ include, exclude }: { include?: Node[]; exclude?: Node[ return data; } -ipcMain.handle(IpcEvents.VIRT_MIC_LIST, () => { +handle(IpcEvents.VIRT_MIC_LIST, () => { const audioPid = getRendererAudioServicePid(); const { granularSelect } = Settings.store.audio ?? {}; @@ -111,16 +112,16 @@ ipcMain.handle(IpcEvents.VIRT_MIC_LIST, () => { return targets ? { ok: true, targets, hasPipewirePulse } : { ok: false, isGlibCxxOutdated }; }); -ipcMain.handle(IpcEvents.VIRT_MIC_START, (_, include: Node[]) => { +handle(IpcEvents.VIRT_MIC_START, (_, include: Node[]) => { return obtainVenmic()?.link(buildLinkData({ include })); }); -ipcMain.handle(IpcEvents.VIRT_MIC_START_SYSTEM, (_, exclude: Node[]) => { +handle(IpcEvents.VIRT_MIC_START_SYSTEM, (_, exclude: Node[]) => { return obtainVenmic()?.link(buildLinkData({ exclude })); }); -ipcMain.handle(IpcEvents.VIRT_MIC_UNMUTE, () => { +handle(IpcEvents.VIRT_MIC_UNMUTE, () => { return obtainVenmic()?.unmute(); }); -ipcMain.handle(IpcEvents.VIRT_MIC_STOP, () => obtainVenmic()?.unlink()); +handle(IpcEvents.VIRT_MIC_STOP, () => obtainVenmic()?.unlink()); diff --git a/src/renderer/components/ScreenSharePicker.tsx b/src/renderer/components/ScreenSharePicker.tsx index df1c75b9..ed9713bc 100644 --- a/src/renderer/components/ScreenSharePicker.tsx +++ b/src/renderer/components/ScreenSharePicker.tsx @@ -152,16 +152,25 @@ export function openScreenSharePicker(screens: Source[], skipPicker: boolean) { submit={async v => { didSubmit = true; - if (v.includeSources && v.includeSources !== "None") { - if (v.includeSources === "Entire System") { - await VesktopNative.virtmic.startSystem( - !v.excludeSources || isSpecialSource(v.excludeSources) ? [] : v.excludeSources - ); - } else { - await VesktopNative.virtmic.start(v.includeSources); + if (isLinux) { + try { + if (v.includeSources && v.includeSources !== "None") { + if (v.includeSources === "Entire System") { + await VesktopNative.virtmic.startSystem( + !v.excludeSources || isSpecialSource(v.excludeSources) + ? [] + : v.excludeSources + ); + } else { + await VesktopNative.virtmic.start(v.includeSources); + } + } else { + await VesktopNative.virtmic.stop(); + } + } catch (e) { + // still start the stream, just without audio + logger.error("Failed to set up venmic", e); } - } else { - await VesktopNative.virtmic.stop(); } resolve(v); diff --git a/src/renderer/ipcCommands.ts b/src/renderer/ipcCommands.ts index 4d73f022..003c743c 100644 --- a/src/renderer/ipcCommands.ts +++ b/src/renderer/ipcCommands.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ -import { SettingsRouter } from "@vencord/types/webpack/common"; +import { NavigationRouter, SettingsRouter } from "@vencord/types/webpack/common"; import { IpcCommands } from "shared/IpcEvents"; import { openScreenSharePicker } from "./components/ScreenSharePicker"; @@ -45,6 +45,8 @@ export function offIpcCommand(channel: string) { /* Generic Handlers */ +onIpcCommand(IpcCommands.NAVIGATE, (path: string) => NavigationRouter.transitionTo(path)); + onIpcCommand(IpcCommands.NAVIGATE_SETTINGS, () => { SettingsRouter.openUserSettings("my_account_panel"); }); diff --git a/src/shared/IpcEvents.ts b/src/shared/IpcEvents.ts index 03c9c345..963ac37c 100644 --- a/src/shared/IpcEvents.ts +++ b/src/shared/IpcEvents.ts @@ -85,6 +85,7 @@ export const enum IpcCommands { RPC_GAME = "rpc:game", RPC_RESET = "rpc:reset", + NAVIGATE = "navigate", NAVIGATE_SETTINGS = "navigate:settings", GET_LANGUAGES = "navigator.languages",