diff --git a/lib/config/custom-build-vm.nix b/lib/config/custom-build-vm.nix
index 7986e75..7e11bef 100644
--- a/lib/config/custom-build-vm.nix
+++ b/lib/config/custom-build-vm.nix
@@ -122,37 +122,42 @@ in {
                 vm
               else
                 let
-                  command = "${vm}/bin/run-${config.system.name}-vm";
-
-                  prefix =
-                    lib.concatStringsSep " " (
-                      lib.optionals config.virtualisation.runAsRoot (
-                        ["sudo"] ++
-                        lib.optional config.virtualisation.qemu.runInBackground "-b"));
+                  originalCommand = "${vm}/bin/run-${config.system.name}-vm";
 
                   suffix =
                     lib.concatStringsSep " " (
-                      lib.optional
-                        (!config.virtualisation.runAsRoot && config.virtualisation.qemu.runInBackground)
-                        "&");
+                      lib.optional config.virtualisation.qemu.runInBackground "&");
 
-                  wrapped = pkgs.writeShellApplication {
+                  shellApp = pkgs.writeShellApplication {
                     name = "run-${config.system.name}-vm";
                     text = lib.strings.concatLines (
                       [
-                        "${prefix} ${command} ${suffix}"
+                        "${originalCommand} ${suffix}"
                       ] ++ (
                         let
                           spice = config.virtualisation.qemu.spice;
+                          viewerPrefix = "sudo -Eu\"#$SUDO_UID\" ";
                         in
                           (
                             lib.optionals
                               config.virtualisation.virt-viewer
                               [
-                                "${pkgs.virt-viewer}/bin/remote-viewer spice://${lib.escapeShellArg spice.bindAddress}:${toString spice.port}"
+                                "${viewerPrefix}${pkgs.virt-viewer}/bin/remote-viewer spice://${lib.escapeShellArg spice.bindAddress}:${toString spice.port}"
                                 "kill %1"
                               ])));
                   };
+
+                  wrapped =
+                    if !config.virtualisation.runAsRoot
+                    then
+                      shellApp
+                    else
+                      pkgs.writeShellApplication {
+                        name = shellApp.name;
+                        text = ''
+                          sudo -E ${shellApp}/bin/${shellApp.name}
+                        '';
+                      };
                 in
                   pkgs.symlinkJoin {
                     name = packageName;