Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(hyprland): preserve loaders and write configs atomically (#2742)

十方空烬 · Ember ☄️9ce28e8fce24
diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.js
index 053799bfe..df7c5e548 100644
--- a/src/helpers/hotkeyManager.js
+++ b/src/helpers/hotkeyManager.js
@@ -1771,7 +1771,8 @@ class HotkeyManager extends EventEmitter {
getHyprlandConfigStatus() {
if (!this.hyprlandManager) return null;
- return HyprlandShortcutManager.getHyprlandConfigStatus();
+ const status = HyprlandShortcutManager.getHyprlandConfigStatus();
+ return { ...status, canWrite: status.canWrite && !this.hyprlandManager.persistencePending };
}
isUsingKDE() {
diff --git a/src/helpers/hyprlandShortcut.js b/src/helpers/hyprlandShortcut.js
index 9593c47e5..4675a987d 100644
--- a/src/helpers/hyprlandShortcut.js
+++ b/src/helpers/hyprlandShortcut.js
@@ -2,6 +2,7 @@ const { execFileSync } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
+const { randomUUID } = require("crypto");
const debugLogger = require("./debugLogger");
const DBUS_SERVICE_NAME = "com.openwhispr.App";
@@ -78,6 +79,96 @@ const MANAGED_HEADER_VARIANTS = new Set([
"If you delete this file, also remove the matching source line from your Hyprland config.",
]);
+/** @returns {{ code: string, topLevelLines: boolean[] }} */
+function getLuaCodeStructure(content) {
+ // Keep quoted literals, but ignore comments and long strings containing example code.
+ const code = content.replace(
+ /"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|--\[(=*)\[[\s\S]*?(?:\]\1\]|$)|--[^\n]*|\[(=*)\[[\s\S]*?(?:\]\2\]|$)/g,
+ (token) => (/^["']/.test(token) ? token : token.replace(/[^\r\n]/g, " "))
+ );
+ const structure = code
+ .replace(/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'/g, (token) =>
+ token.replace(/[^\r\n]/g, " ")
+ )
+ .split("\n");
+ let depth = 0;
+ const topLevelLines = structure.map((line) => {
+ const topLevel = depth === 0;
+ for (const token of line.match(/\b(?:function|if|do|repeat|end|until)\b|[()[\]{}]/g) || []) {
+ depth += /^(?:end|until|[)\]}])$/.test(token) ? -1 : 1;
+ }
+ return topLevel;
+ });
+ return { code, topLevelLines };
+}
+
+/** @returns {boolean} */
+function hasLuaLoadDirective({ code, topLevelLines }, bindsPath) {
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const quoted = `${escape(JSON.stringify(bindsPath))}|${escape(
+ `'${bindsPath.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`
+ )}`;
+ const loader = new RegExp(
+ `^\\s*(?:(?:require|dofile)\\s*(?:\\(\\s*(?:${quoted})\\s*\\)|(?:${quoted}))|` +
+ `pcall\\s*\\(\\s*(?:require|dofile)\\s*,\\s*(?:${quoted})\\s*\\))\\s*;?\\s*(?=\\r?\\n|$)`
+ );
+ let offset = 0;
+ for (const [index, line] of code.split("\n").entries()) {
+ if (topLevelLines[index] && /^\s*return\b/.test(line)) break;
+ if (topLevelLines[index] && loader.test(code.slice(offset))) return true;
+ offset += line.length + 1;
+ }
+ return false;
+}
+
+/** @returns {{ target: string, metadata: import("fs").Stats | null }} */
+function getWritableConfigTarget(filePath) {
+ let entry;
+ try {
+ entry = fs.lstatSync(filePath);
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ // Resolve existing links before replacing: rename must update the dotfile
+ // target, never replace the user's symlink with a regular file.
+ const target = entry ? fs.realpathSync(filePath) : filePath;
+ const metadata = entry ? fs.statSync(target) : null;
+ if (metadata && (!metadata.isFile() || metadata.nlink > 1)) {
+ throw new Error(`Cannot atomically replace non-regular or hard-linked config: ${filePath}`);
+ }
+ if (metadata) fs.accessSync(target, fs.constants.W_OK);
+ fs.accessSync(path.dirname(target), fs.constants.W_OK | fs.constants.X_OK);
+ return { target, metadata };
+}
+
+function writeConfigAtomically(filePath, content) {
+ const { target, metadata } = getWritableConfigTarget(filePath);
+ const temp = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`);
+ let fd;
+ try {
+ fd = fs.openSync(temp, "wx", 0o600);
+ fs.writeFileSync(fd, content, "utf-8");
+ if (metadata) {
+ const current = fs.fstatSync(fd);
+ if (current.uid !== metadata.uid || current.gid !== metadata.gid) {
+ fs.fchownSync(fd, metadata.uid, metadata.gid);
+ }
+ }
+ fs.fchmodSync(fd, metadata ? metadata.mode & 0o7777 : 0o666 & ~process.umask());
+ fs.fsyncSync(fd);
+ fs.closeSync(fd);
+ fd = undefined;
+ fs.renameSync(temp, target);
+ } finally {
+ if (fd !== undefined) fs.closeSync(fd);
+ try {
+ fs.unlinkSync(temp);
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ }
+}
+
function isManagedHeaderLine(line) {
return MANAGED_HEADER_VARIANTS.has(line.trim().replace(/^(#|--)\s*/, ""));
}
@@ -449,7 +540,7 @@ class HyprlandShortcutManager {
}
const newContent = buildManagedBindsContent([...userLines, ...bindLines], config.format);
- fs.writeFileSync(config.bindsPath, newContent, "utf-8");
+ if (newContent !== content) writeConfigAtomically(config.bindsPath, newContent);
}
_persistBinds(config, desiredBinds) {
@@ -470,11 +561,16 @@ class HyprlandShortcutManager {
throw err;
}
+ const luaStructure = config.format === "lua" ? getLuaCodeStructure(content) : null;
+ if (luaStructure && hasLuaLoadDirective(luaStructure, config.bindsPath)) return true;
+
const sourceLine =
config.format === "lua"
? `pcall(require, ${JSON.stringify(config.bindsPath)})`
: `source = ${config.bindsPath}`;
- const lines = content.split("\n").filter((line) => {
+ const lines = content.split("\n").filter((line, index) => {
+ // Removing a nested call can invalidate its surrounding expression.
+ if (luaStructure && !luaStructure.topLevelLines[index]) return true;
if (!line.includes(BINDS_FILENAMES[config.format])) return true;
const trimmed = line.trim();
return config.format === "lua"
@@ -498,7 +594,7 @@ class HyprlandShortcutManager {
const newContent = lines.join("\n");
if (newContent === content) return true;
- fs.writeFileSync(config.path, newContent, "utf-8");
+ writeConfigAtomically(config.path, newContent);
debugLogger.log(`[HyprlandShortcut] Added binding load directive to ${config.path}`);
return true;
}
@@ -615,24 +711,15 @@ class HyprlandShortcutManager {
static getHyprlandConfigStatus() {
const config = getHyprlandConfig();
const mainConfig = config.path;
- const configDir = path.dirname(mainConfig);
const status = {
path: mainConfig,
canWrite: false,
};
try {
- fs.accessSync(mainConfig, fs.constants.F_OK | fs.constants.W_OK);
- if (!fs.statSync(mainConfig).isFile()) {
- throw new Error(`Hyprland config is not a file: ${mainConfig}`);
- }
- fs.accessSync(configDir, fs.constants.W_OK);
- if (fs.existsSync(config.bindsPath)) {
- fs.accessSync(config.bindsPath, fs.constants.W_OK);
- if (!fs.statSync(config.bindsPath).isFile()) {
- throw new Error(`Managed binds path is not a file: ${config.bindsPath}`);
- }
- }
+ fs.accessSync(mainConfig, fs.constants.F_OK);
+ getWritableConfigTarget(mainConfig);
+ getWritableConfigTarget(config.bindsPath);
status.canWrite = true;
} catch (err) {
debugLogger.log(
diff --git a/test/helpers/hotkeyHyprlandSlots.test.js b/test/helpers/hotkeyHyprlandSlots.test.js
index a372458e3..8b091f6ad 100644
--- a/test/helpers/hotkeyHyprlandSlots.test.js
+++ b/test/helpers/hotkeyHyprlandSlots.test.js
@@ -25,8 +25,25 @@ require.cache[require.resolve("electron")] = {
};
const HotkeyManager = require("../../src/helpers/hotkeyManager.js");
+const HyprlandShortcutManager = require("../../src/helpers/hyprlandShortcut.js");
const hyprlandTest = process.platform === "linux" ? test : test.skip;
+test("Hyprland persistence failures remain visible until a successful retry", (context) => {
+ context.mock.method(HyprlandShortcutManager, "getHyprlandConfigStatus", () => ({
+ path: "/config/hyprland.lua",
+ canWrite: true,
+ }));
+ const manager = new HotkeyManager();
+ manager.hyprlandManager = { persistencePending: true };
+
+ assert.deepEqual(manager.getHyprlandConfigStatus(), {
+ path: "/config/hyprland.lua",
+ canWrite: false,
+ });
+ manager.hyprlandManager.persistencePending = false;
+ assert.equal(manager.getHyprlandConfigStatus().canWrite, true);
+});
+
async function withHyprland(fn) {
const saved = {
XDG_SESSION_TYPE: process.env.XDG_SESSION_TYPE,
diff --git a/test/helpers/hyprlandConfigPersistence.test.js b/test/helpers/hyprlandConfigPersistence.test.js
new file mode 100644
index 000000000..b67fd2083
--- /dev/null
+++ b/test/helpers/hyprlandConfigPersistence.test.js
@@ -0,0 +1,178 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+const load = Module._load;
+let Manager;
+Module._load = function (request, parent, isMain) {
+ if (request === "child_process") {
+ return {
+ execFileSync() {
+ throw new Error("Unexpected compositor command");
+ },
+ };
+ }
+ if (request === "./debugLogger") return { log() {} };
+ return load.call(this, request, parent, isMain);
+};
+try {
+ Manager = require("../../src/helpers/hyprlandShortcut");
+} finally {
+ Module._load = load;
+}
+
+function fixture(fn) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hyprland-config-test-"));
+ const config = {
+ path: path.join(dir, "hyprland.lua"),
+ bindsPath: path.join(dir, "openwhispr-binds.lua"),
+ format: "lua",
+ };
+ try {
+ return fn(new Manager(), config, dir);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+for (const [name, loader] of [
+ ["pcall whitespace", (p) => ` pcall ( require , ${JSON.stringify(p)} ) -- managed load`],
+ ["pcall without space", (p) => `pcall(require,${JSON.stringify(p)})`],
+ ["require", (p) => `require ( '${p}' )`],
+ ["dofile", (p) => `dofile ( ${JSON.stringify(p)} );`],
+ ["pcall dofile", (p) => `pcall ( dofile, '${p}' )`],
+ ["require without parentheses", (p) => `require '${p}'`],
+ ["multiline pcall", (p) => `pcall(\n require, -- loader\n ${JSON.stringify(p)}\n)`],
+ ["multiline dofile", (p) => `dofile(\n '${p}'\n)`],
+]) {
+ test(`keeps an existing ${name} loader byte- and inode-identical`, () =>
+ fixture((manager, config) => {
+ const content = `-- user config\n${loader(config.bindsPath)}\nreturn {}\n`;
+ fs.writeFileSync(config.path, content);
+ const before = fs.statSync(config.path);
+ assert.equal(manager._ensureSourceInMainConfig(config), true);
+ assert.equal(fs.readFileSync(config.path, "utf8"), content);
+ assert.equal(fs.statSync(config.path).ino, before.ino);
+ assert.equal(fs.statSync(config.path).mtimeMs, before.mtimeMs);
+ }));
+}
+
+test("replaces the main config atomically through a symlink, preserving its target mode", () =>
+ fixture((manager, config, dir) => {
+ const target = path.join(dir, "chezmoi-source.lua");
+ const original = "-- keep user settings\nreturn {}\n";
+ fs.writeFileSync(target, original, { mode: 0o640 });
+ const realTarget = fs.realpathSync(target);
+ fs.symlinkSync(target, config.path);
+ let replacements = 0;
+ const rename = fs.renameSync;
+ fs.renameSync = (from, to) => {
+ if (to === realTarget) {
+ replacements++;
+ assert.equal(fs.readFileSync(target, "utf8"), original);
+ assert.match(fs.readFileSync(from, "utf8"), /pcall\(require,/);
+ }
+ return rename(from, to);
+ };
+ try {
+ assert.equal(manager._ensureSourceInMainConfig(config), true);
+ } finally {
+ fs.renameSync = rename;
+ }
+ assert.equal(replacements, 1);
+ assert.equal(fs.lstatSync(config.path).isSymbolicLink(), true);
+ assert.equal(fs.statSync(target).mode & 0o777, 0o640);
+ assert.equal(fs.readFileSync(target, "utf8").includes(original.split("\n")[0]), true);
+ assert.deepEqual(fs.readdirSync(dir).sort(), ["chezmoi-source.lua", "hyprland.lua"]);
+ }));
+
+for (const [name, content] of [
+ ["line comment", (p) => `-- require("${p}")\n`],
+ ["long comment", (p) => `--[=[\nrequire("${p}")\n]=]\n`],
+ ["long string", (p) => `local example = [[\nrequire("${p}")\n]]\n`],
+ ["conditional", (p) => `if false then\nrequire("${p}")\nend\n`],
+ ["function body", (p) => `local function unused()\nrequire("${p}")\nend\n`],
+]) {
+ test(`does not treat a ${name} as an active top-level loader`, () =>
+ fixture((manager, config) => {
+ fs.writeFileSync(config.path, content(config.bindsPath));
+ assert.equal(manager._ensureSourceInMainConfig(config), true);
+ assert.match(fs.readFileSync(config.path, "utf8"), /pcall\(require,/);
+ }));
+}
+
+for (const [name, expression] of [
+ ["table", (loader) => `false and {\n ${loader}\n}`],
+ ["parenthesized expression", (loader) => `false and (\n ${loader}\n)`],
+ ["call argument", (loader) => `false and tostring(\n ${loader}\n)`],
+]) {
+ test(`adds an unconditional loader without damaging a skipped ${name}`, () =>
+ fixture((manager, config) => {
+ const loader = `pcall(require, ${JSON.stringify(config.bindsPath)})`;
+ const prefix = `local optional = ${expression(loader)}\n`;
+ fs.writeFileSync(config.path, `${prefix}return {}\n`);
+
+ assert.equal(manager._ensureSourceInMainConfig(config), true);
+ assert.equal(fs.readFileSync(config.path, "utf8"), `${prefix}${loader}\nreturn {}\n`);
+ const before = fs.statSync(config.path);
+ assert.equal(manager._ensureSourceInMainConfig(config), true);
+ assert.equal(fs.statSync(config.path).ino, before.ino);
+ }));
+}
+
+test("failed atomic replacement leaves the original target and symlink intact", () =>
+ fixture((manager, config, dir) => {
+ const target = path.join(dir, "source.lua");
+ fs.writeFileSync(target, "-- unchanged\n", { mode: 0o600 });
+ fs.symlinkSync(target, config.path);
+ const rename = fs.renameSync;
+ fs.renameSync = () => {
+ throw new Error("synthetic rename failure");
+ };
+ try {
+ assert.throws(() => manager._ensureSourceInMainConfig(config), /synthetic rename failure/);
+ } finally {
+ fs.renameSync = rename;
+ }
+ assert.equal(fs.readFileSync(target, "utf8"), "-- unchanged\n");
+ assert.equal(fs.lstatSync(config.path).isSymbolicLink(), true);
+ assert.deepEqual(fs.readdirSync(dir).sort(), ["hyprland.lua", "source.lua"]);
+ }));
+
+test("does not replace a dangling config symlink", () =>
+ fixture((manager, config, dir) => {
+ fs.symlinkSync(path.join(dir, "missing.lua"), config.path);
+ assert.equal(manager._ensureSourceInMainConfig(config), false);
+ assert.equal(fs.lstatSync(config.path).isSymbolicLink(), true);
+ }));
+
+test("does not break a hard-linked config when a load directive is missing", () =>
+ fixture((manager, config, dir) => {
+ fs.writeFileSync(config.path, "-- shared inode\n");
+ const alias = path.join(dir, "hardlink.lua");
+ fs.linkSync(config.path, alias);
+ assert.throws(() => manager._ensureSourceInMainConfig(config), /hard-linked/);
+ assert.equal(fs.statSync(config.path).ino, fs.statSync(alias).ino);
+ assert.equal(fs.readFileSync(config.path, "utf8"), "-- shared inode\n");
+ }));
+
+test("repeating persistence leaves both an existing loader and unchanged managed binds untouched", () =>
+ fixture((manager, config, dir) => {
+ fs.writeFileSync(config.path, `pcall(require,${JSON.stringify(config.bindsPath)})\n`);
+ const target = path.join(dir, "managed.lua");
+ fs.writeFileSync(target, "-- user bind comment\n", { mode: 0o640 });
+ fs.symlinkSync(target, config.bindsPath);
+ manager._persistBinds(config, {});
+ const main = fs.statSync(config.path);
+ const binds = fs.statSync(target);
+ manager._persistBinds(config, {});
+ assert.equal(fs.statSync(config.path).ino, main.ino);
+ assert.equal(fs.statSync(config.path).mtimeMs, main.mtimeMs);
+ assert.equal(fs.statSync(target).ino, binds.ino);
+ assert.equal(fs.statSync(target).mtimeMs, binds.mtimeMs);
+ assert.equal(fs.statSync(target).mode & 0o777, 0o640);
+ assert.equal(fs.lstatSync(config.bindsPath).isSymbolicLink(), true);
+ }));
diff --git a/test/helpers/hyprlandShortcut.test.js b/test/helpers/hyprlandShortcut.test.js
index a681d3208..a582738bb 100644
--- a/test/helpers/hyprlandShortcut.test.js
+++ b/test/helpers/hyprlandShortcut.test.js
@@ -14,6 +14,7 @@ function loadManager(execFileSync) {
delete require.cache[modulePath];
Module._load = function loadWithMocks(request, parent, isMain) {
if (request === "child_process") return { ...childProcess, execFileSync };
+ if (request === "./debugLogger") return { log() {} };
return originalLoad.call(this, request, parent, isMain);
};
try {
@@ -567,7 +568,7 @@ test(
);
test(
- "replaces an old dofile loader before a trailing top-level return",
+ "keeps an existing dofile loader before a trailing top-level return",
withTempHyprConfig(async (configDir) => {
const luaPath = path.join(configDir, "hyprland.lua");
const bindsPath = path.join(configDir, "openwhispr-binds.lua");
@@ -585,10 +586,10 @@ test(
);
const content = fs.readFileSync(luaPath, "utf8");
- const protectedLoader = `pcall(require, "${bindsPath}")`;
- assert.doesNotMatch(content, /dofile\(/);
+ const existingLoader = `dofile("${bindsPath}")`;
+ assert.match(content, /dofile\(/);
assert.equal((content.match(/openwhispr-binds\.lua/g) || []).length, 1);
- assert.ok(content.indexOf(protectedLoader) < content.indexOf("return {}"));
+ assert.ok(content.indexOf(existingLoader) < content.indexOf("return {}"));
})
);
@@ -623,6 +624,41 @@ test(
})
);
+for (const filename of ["hyprland.lua", "openwhispr-binds.lua"]) {
+ test(
+ `reports and recovers from a non-writable symlink target directory for ${filename}`,
+ { skip: process.platform === "win32" || process.getuid?.() === 0 },
+ withTempHyprConfig(async (configDir) => {
+ const targetDir = path.join(configDir, "dotfiles");
+ fs.mkdirSync(targetDir, { recursive: true });
+ const configPath = path.join(configDir, "hyprland.lua");
+ const targetPath = path.join(targetDir, filename);
+ fs.writeFileSync(targetPath, "-- original\n", { mode: 0o644 });
+ if (filename !== "hyprland.lua") fs.writeFileSync(configPath, "-- main config\n");
+ fs.symlinkSync(targetPath, path.join(configDir, filename));
+ const HyprlandShortcutManager = loadManager(successfulHyprctl("lua").execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ fs.chmodSync(targetDir, 0o555);
+ try {
+ assert.equal(await manager.registerKeybinding("F8"), true);
+ assert.equal(manager.persistencePending, true);
+ assert.equal(fs.readFileSync(targetPath, "utf8"), "-- original\n");
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().canWrite, false);
+ } finally {
+ fs.chmodSync(targetDir, 0o755);
+ }
+
+ assert.equal(await manager.registerKeybinding("F8"), true);
+ assert.equal(manager.persistencePending, false);
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().canWrite, true);
+ assert.equal(fs.lstatSync(path.join(configDir, filename)).isSymbolicLink(), true);
+ assert.match(fs.readFileSync(configPath, "utf8"), /pcall\(require,/);
+ assert.match(fs.readFileSync(path.join(configDir, "openwhispr-binds.lua"), "utf8"), /F8/);
+ })
+ );
+}
+
test(
"removes the previous header wording when rewriting managed binds",
withTempHyprConfig(async (configDir) => {