Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Isolated config fixtures, never the user's desktop.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeOS from "node:os";
5import * as NodeChildProcess from "node:child_process";
6import * as NodeUtil from "node:util";
7import { afterEach, beforeEach, expect, it as test, vi } from "vite-plus/test";
8import { CaptureShortcutConfig, niriCaptureConfigPath } from "./CaptureShortcutConfig.ts";
9import { captureConfigBinding } from "./captureConfigEdit.ts";
10
11// oxlint-disable-next-line t3code/no-global-process-runtime -- Test collection checks the host before starting these Linux-native filesystem tests.
12const it = test.runIf(process.platform === "linux");
13let directory: string;
14let path: string;
15let setup: CaptureShortcutConfig;
16const tools = {
17 validateNiri: vi.fn<(path: string) => Promise<void>>(),
18 hyprlandBindings:
19 vi.fn<() => Promise<{ modmask: number; key: string; dispatcher: string; arg: string }[]>>(),
20 reloadHyprland: vi.fn<() => Promise<void>>(),
21};
22const appId = "com.t3tools.T3Code";
23const install = { operation: "install", chooseFile: false } as const;
24const target = () => ({ desktop: "niri" as const, path, appId });
25beforeEach(async () => {
26 directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-capture-config-"));
27 path = NodePath.join(directory, "config.kdl");
28 await NodeFSP.writeFile(path, "binds {\n Mod+Q { quit; }\n}\n", { mode: 0o640 });
29 tools.validateNiri.mockReset().mockResolvedValue(undefined);
30 tools.hyprlandBindings.mockReset().mockResolvedValue([]);
31 tools.reloadHyprland.mockReset().mockResolvedValue(undefined);
32 setup = new CaptureShortcutConfig(NodeOS.homedir(), tools);
33});
34afterEach(async () => {
35 await NodeFSP.rm(directory, { recursive: true, force: true });
36});
37
38it("reads without writing, then applies only the approved diff with a backup", async () => {
39 const before = await NodeFSP.readFile(path, "utf8");
40 const preview = await setup.preview(target(), install);
41 expect(await NodeFSP.readFile(path, "utf8")).toBe(before);
42 expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
43 expect(tools.validateNiri).not.toHaveBeenCalled();
44 expect(preview.before).toBe(before);
45 expect(preview.after).toContain("Ctrl+Shift+2");
46 const applied = await setup.apply(preview.id, "niri");
47 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.after);
48 expect(await NodeFSP.readFile(applied.backupPath!, "utf8")).toBe(before);
49 expect((await NodeFSP.stat(path)).mode & 0o777).toBe(0o640);
50 expect(tools.validateNiri).toHaveBeenCalledOnce();
51 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("expired");
52});
53it("refuses apply without a preview or for the wrong desktop", async () => {
54 await expect(setup.apply("invented", "niri")).rejects.toThrow("expired");
55 const preview = await setup.preview(target(), install);
56 await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("expired");
57 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
58});
59it("rechecks Hyprland conflicts before writing", async () => {
60 const hypr = {
61 ...target(),
62 desktop: "hyprland" as const,
63 path: NodePath.join(directory, "hyprland.conf"),
64 };
65 await NodeFSP.writeFile(hypr.path, "# unchanged\n");
66 const preview = await setup.preview(hypr, install);
67 tools.hyprlandBindings.mockResolvedValue([
68 { modmask: 5, key: "2", dispatcher: "exec", arg: "kitty" },
69 ]);
70 await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("already used");
71 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(preview.before);
72});
73it("notices an optional include created while the diff is open", async () => {
74 await NodeFSP.appendFile(path, 'include optional=true "later.kdl"\n');
75 const preview = await setup.preview(target(), install);
76 await NodeFSP.writeFile(
77 NodePath.join(directory, "later.kdl"),
78 "binds {\n Ctrl+Shift+2 { quit; }\n}\n",
79 );
80 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
81 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
82});
83it("invalidates an earlier proposal when another config is opened", async () => {
84 const first = await setup.preview(target(), install);
85 await setup.preview(target(), { ...install, shortcut: "Ctrl+Alt+Y" });
86 await expect(setup.apply(first.id, "niri")).rejects.toThrow("expired");
87});
88it("does not overwrite edits made after preview", async () => {
89 const preview = await setup.preview(target(), install);
90 await NodeFSP.appendFile(path, "// edited elsewhere\n");
91 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
92 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before + "// edited elsewhere\n");
93 expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
94});
95it("rechecks after validation and cleans the staged file on concurrent edits", async () => {
96 const preview = await setup.preview(target(), install);
97 tools.validateNiri.mockImplementation(async () => {
98 await NodeFSP.appendFile(path, "// keep this\n");
99 });
100 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
101 expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
102 expect(await NodeFSP.readFile(path, "utf8")).toContain("keep this");
103});
104it("preserves symlink-managed dotfiles and identifies their actual target", async () => {
105 const link = NodePath.join(directory, "linked.kdl");
106 await NodeFSP.symlink(path, link);
107 const preview = await setup.preview({ ...target(), path: link }, install);
108 expect(preview.path).toBe(link);
109 expect(preview.resolvedPath).toBe(path);
110 await setup.apply(preview.id, "niri");
111 expect((await NodeFSP.lstat(link)).isSymbolicLink()).toBe(true);
112 expect(await NodeFSP.readFile(link, "utf8")).toBe(preview.after);
113});
114it("refuses a symlink retargeted since preview", async () => {
115 const link = NodePath.join(directory, "linked.kdl");
116 const other = NodePath.join(directory, "other.kdl");
117 await NodeFSP.writeFile(other, "binds {}\n");
118 await NodeFSP.symlink(path, link);
119 const preview = await setup.preview({ ...target(), path: link }, install);
120 await NodeFSP.unlink(link);
121 await NodeFSP.symlink(other, link);
122 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
123 expect(await NodeFSP.readFile(other, "utf8")).toBe("binds {}\n");
124});
125it("validates symlinked configs from their original directory so relative includes stay valid", async () => {
126 const active = NodePath.join(directory, "active");
127 await NodeFSP.mkdir(active);
128 const link = NodePath.join(active, "config.kdl");
129 await NodeFSP.symlink(path, link);
130 await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
131 await NodeFSP.writeFile(NodePath.join(active, "keys.kdl"), "binds {}\n");
132 tools.validateNiri.mockImplementation(async (file) => {
133 expect(NodePath.dirname(file)).toBe(active);
134 expect(await NodeFSP.readFile(file, "utf8")).toContain("Ctrl+Shift+2");
135 expect(await NodeFSP.readFile(NodePath.join(NodePath.dirname(file), "keys.kdl"), "utf8")).toBe(
136 "binds {}\n",
137 );
138 });
139 const preview = await setup.preview({ ...target(), path: link }, install);
140 await setup.apply(preview.id, "niri");
141 expect((await NodeFSP.readdir(active)).sort()).toEqual(["config.kdl", "keys.kdl"]);
142 expect((await NodeFSP.lstat(link)).isSymbolicLink()).toBe(true);
143});
144it("does not apply invalid Niri configs", async () => {
145 const preview = await setup.preview(target(), install);
146 tools.validateNiri.mockRejectedValue(new Error("Invalid config"));
147 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("Invalid config");
148 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before);
149 expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
150});
151it("leaves already configured files unchanged, without creating a backup", async () => {
152 await NodeFSP.writeFile(path, `binds { ${captureConfigBinding("niri", appId, "Ctrl+Alt+Y")} }`);
153 const preview = await setup.preview(target(), install);
154 expect(preview.after).toBe(preview.before);
155 expect(preview.shortcut).toBe("Ctrl+Alt+Y");
156 expect(await setup.apply(preview.id, "niri")).toEqual({ backupPath: null, warning: null });
157 expect(await NodeFSP.readdir(directory)).toEqual(["config.kdl"]);
158});
159it("accepts an unchanged capture shortcut reported as a Lua callback", async () => {
160 const hypr = {
161 ...target(),
162 desktop: "hyprland" as const,
163 path: NodePath.join(directory, "bindings.lua"),
164 };
165 const before = `${captureConfigBinding("hyprland-lua", appId, "Ctrl+Shift+2")}\n`;
166 await NodeFSP.writeFile(hypr.path, before);
167 tools.hyprlandBindings.mockResolvedValue([
168 { modmask: 5, key: "2", dispatcher: "__lua", arg: "92" },
169 ]);
170
171 const preview = await setup.preview(hypr, install);
172 expect(preview.after).toBe(before);
173 expect(preview.shortcut).toBe("Ctrl+Shift+2");
174 expect(await setup.apply(preview.id, "hyprland")).toEqual({ backupPath: null, warning: null });
175 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(before);
176 expect((await NodeFSP.readdir(directory)).sort()).toEqual(["bindings.lua", "config.kdl"]);
177 expect(tools.reloadHyprland).not.toHaveBeenCalled();
178
179 const unchanged = await setup.preview(hypr, install);
180 await NodeFSP.appendFile(hypr.path, "-- edited elsewhere\n");
181 await expect(setup.apply(unchanged.id, "hyprland")).rejects.toThrow("changed since");
182 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(before + "-- edited elsewhere\n");
183});
184it.each(["preview", "apply"] as const)(
185 "checks unchanged Hyprland .conf shortcuts for conflicts during %s",
186 async (stage) => {
187 const hypr = {
188 ...target(),
189 desktop: "hyprland" as const,
190 path: NodePath.join(directory, "hyprland.conf"),
191 };
192 const before = `${captureConfigBinding("hyprland", appId, "Ctrl+Shift+2")}\n`;
193 await NodeFSP.writeFile(hypr.path, before);
194 const ownBinding = {
195 modmask: 5,
196 key: "2",
197 dispatcher: "global",
198 arg: `${appId}:capture-window`,
199 };
200 tools.hyprlandBindings.mockResolvedValue([ownBinding]);
201 const unchanged = await setup.preview(hypr, install);
202 expect(unchanged.after).toBe(before);
203 expect(await setup.apply(unchanged.id, "hyprland")).toEqual({
204 backupPath: null,
205 warning: null,
206 });
207
208 const preview = stage === "apply" ? await setup.preview(hypr, install) : undefined;
209 tools.hyprlandBindings.mockResolvedValue([
210 ownBinding,
211 { modmask: 5, key: "2", dispatcher: "exec", arg: "kitty" },
212 ]);
213 await expect(
214 preview ? setup.apply(preview.id, "hyprland") : setup.preview(hypr, install),
215 ).rejects.toThrow("already used");
216 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(before);
217 expect((await NodeFSP.readdir(directory)).sort()).toEqual(["config.kdl", "hyprland.conf"]);
218 expect(tools.reloadHyprland).not.toHaveBeenCalled();
219 },
220);
221it("rejects changing an existing capture shortcut to keys used by another Lua callback", async () => {
222 const hypr = {
223 ...target(),
224 desktop: "hyprland" as const,
225 path: NodePath.join(directory, "bindings.lua"),
226 };
227 const before = `${captureConfigBinding("hyprland-lua", appId, "Ctrl+Alt+Y")}\n`;
228 await NodeFSP.writeFile(hypr.path, before);
229 const request = { ...install, shortcut: "Ctrl+Shift+2" };
230 const occupied = [{ modmask: 5, key: "2", dispatcher: "__lua", arg: "93" }];
231 tools.hyprlandBindings.mockResolvedValue(occupied);
232 await expect(setup.preview(hypr, request)).rejects.toThrow("already used");
233
234 tools.hyprlandBindings.mockResolvedValue([]);
235 const preview = await setup.preview(hypr, request);
236 tools.hyprlandBindings.mockResolvedValue(occupied);
237 await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("already used");
238 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(before);
239});
240it("detects conflicts in included Niri configs without changing either file", async () => {
241 await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
242 await NodeFSP.writeFile(NodePath.join(directory, "keys.kdl"), "binds { Shift+Ctrl+2 { quit; } }");
243 await expect(setup.preview(target(), install)).rejects.toThrow("already used");
244 expect((await NodeFSP.readdir(directory)).sort()).toEqual(["config.kdl", "keys.kdl"]);
245});
246it("detects included config changes before applying", async () => {
247 await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
248 const included = NodePath.join(directory, "keys.kdl");
249 await NodeFSP.writeFile(included, "binds { Ctrl+Alt+Q { quit; } }");
250 const preview = await setup.preview(target(), install);
251 await NodeFSP.writeFile(included, "binds { Ctrl+Shift+2 { quit; } }");
252 await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since");
253});
254it("rejects a conflict from another Hyprland config or dynamic Lua bind", async () => {
255 const hypr = {
256 ...target(),
257 desktop: "hyprland" as const,
258 path: NodePath.join(directory, "bindings.lua"),
259 };
260 await NodeFSP.writeFile(hypr.path, "-- user bindings\n");
261 tools.hyprlandBindings.mockResolvedValue([
262 { modmask: 5, key: "2", dispatcher: "__lua", arg: "92" },
263 ]);
264 await expect(setup.preview(hypr, install)).rejects.toThrow("already used");
265 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe("-- user bindings\n");
266});
267it("reloads Hyprland after apply, but not after read", async () => {
268 const hypr = {
269 ...target(),
270 desktop: "hyprland" as const,
271 path: NodePath.join(directory, "hyprland.conf"),
272 };
273 await NodeFSP.writeFile(hypr.path, "# preferences\n");
274 const preview = await setup.preview(hypr, install);
275 expect(tools.reloadHyprland).not.toHaveBeenCalled();
276 await setup.apply(preview.id, "hyprland");
277 expect(tools.reloadHyprland).toHaveBeenCalledOnce();
278});
279it("reports reload failure separately from a successfully saved config", async () => {
280 const hypr = {
281 ...target(),
282 desktop: "hyprland" as const,
283 path: NodePath.join(directory, "hyprland.conf"),
284 };
285 await NodeFSP.writeFile(hypr.path, "# preferences\n");
286 const preview = await setup.preview(hypr, install);
287 tools.reloadHyprland.mockRejectedValue(new Error("Compositor stopped"));
288 const result = await setup.apply(preview.id, "hyprland");
289 expect(result.warning).toContain("Config saved");
290 expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(preview.after);
291});
292it("does not edit Omarchy's shipped defaults", async () => {
293 const defaults = NodePath.join(directory, "omarchy", "default", "hypr");
294 await NodeFSP.mkdir(defaults, { recursive: true });
295 const file = NodePath.join(defaults, "bindings.conf");
296 await NodeFSP.writeFile(file, "# defaults\n");
297 await expect(
298 setup.preview({ ...target(), desktop: "hyprland", path: file }, install),
299 ).rejects.toThrow("not system or Omarchy");
300});
301it("honors NIRI_CONFIG and XDG_CONFIG_HOME", () => {
302 expect(
303 niriCaptureConfigPath("/home/test", {
304 NIRI_CONFIG: "/custom/test.kdl",
305 XDG_CONFIG_HOME: "/config",
306 }),
307 ).toBe("/custom/test.kdl");
308 expect(niriCaptureConfigPath("/home/test", { XDG_CONFIG_HOME: "/config" })).toBe(
309 "/config/niri/config.kdl",
310 );
311 expect(niriCaptureConfigPath("/home/test", {})).toBe("/home/test/.config/niri/config.kdl");
312});
313it("preserves a UTF-8 BOM through preview and apply", async () => {
314 await NodeFSP.writeFile(path, "\uFEFFbinds {}\r\n");
315 const preview = await setup.preview(target(), install);
316 await setup.apply(preview.id, "niri");
317 expect((await NodeFSP.readFile(path)).subarray(0, 3)).toEqual(Buffer.from([0xef, 0xbb, 0xbf]));
318});
319it("the installed Niri parser accepts the generated edit and its relative includes", async (context) => {
320 try {
321 await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["--version"]);
322 } catch (error) {
323 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
324 context.skip();
325 return;
326 }
327 throw error;
328 }
329 await NodeFSP.appendFile(path, 'include "keys.kdl"\n');
330 await NodeFSP.writeFile(
331 NodePath.join(directory, "keys.kdl"),
332 "binds {\n Ctrl+Alt+Q { quit; }\n}\n",
333 );
334 const checked = new CaptureShortcutConfig(NodeOS.homedir(), {
335 ...tools,
336 validateNiri: async (file) => {
337 await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["validate", "--config", file]);
338 },
339 });
340 const preview = await checked.preview(target(), install);
341 await checked.apply(preview.id, "niri");
342 expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.after);
343});