diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11d3f3d1..b3e8e882 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,6 +123,17 @@ nix build .#checks.x86_64-linux.kde-rounded-corners-komorebi-install nix build .#checks.x86_64-linux.kwin-effect-geometry-change-komorebi-install ``` +## Plasma guests to develop in + +[`nix/dev`](nix/dev) has NixOS guests with Plasma for trying a change by hand, +on an Apple silicon Mac: two that QEMU runs and a disk image for UTM. +[`docs/dev/utm.md`](docs/dev/utm.md) says how to build and run them, and what a +builder has to be. They install komorebi with the NixOS module, and carry +nothing of the person who uses them: a key, a password or a configuration of +yours goes into the guest when it runs, never into these files. The +`plasma-guests-eval` check evaluates them, and the VM suite `rdp` runs their +RDP server, [`nix/dev/krdp.nix`](nix/dev/krdp.nix). + ## Continuous integration [`ci.yaml`](.github/workflows/ci.yaml) runs on every pull request and on every diff --git a/README.md b/README.md index e33bf031..00a6b2ea 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,12 @@ with the NixOS module, so every one of them runs komorebi as the module installs it. `just vm NAME` runs one; [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) has the details, including how to run them on a Mac. +To try komorebi by hand in a real Plasma session, the flake has Plasma guests +to develop in, for an Apple silicon Mac: two that QEMU runs, one with a session +that can be reached over RDP, and a disk image for UTM, which renders on the +Mac's GPU. [`docs/dev/utm.md`](docs/dev/utm.md) says how to build and run them; +`plasma-guests-eval` evaluates them on every system. + ## How it fits together The daemon decides where every window goes and asks the compositor to put it @@ -349,7 +355,8 @@ and [`docs/cli`](docs/cli) has a page for every `komorebic` subcommand, which [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md) describes the model, [`docs/dev/DESIGN.md`](docs/dev/DESIGN.md) says why it is built that way, [`docs/dev/PLATFORM.md`](docs/dev/PLATFORM.md) what it needs from KDE Plasma, -and [`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work. +[`docs/dev/vm-tests.md`](docs/dev/vm-tests.md) how the VM tests work, and +[`docs/dev/utm.md`](docs/dev/utm.md) how to develop in a Plasma guest. ## License diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 534350d4..bb560e49 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -1216,7 +1216,8 @@ With `services.komorebi.enable`, the module: The VM tests run on machines built with it ([vm-tests.md](vm-tests.md)). Their headless node runs the daemon in test sessions, with a template unit, `komorebi@NAME`, that runs the module's `execStart` on the session's private bus. The session node logs in to Plasma, which starts the -module's unit. +module's unit. The Plasma guests to develop in ([utm.md](utm.md)) install komorebi with the module +too. | Rule | Enforced by | Proof | Escape hatch | |---|---|---|---| diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 769a9b4d..b6106a7b 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -809,3 +809,19 @@ every suite has passed against, and the module warns above it. `services.komorebi.kwin.untestedIsError` turns the warning into an error. The two versions are written down in that one file, which the module imports and anything else can read with `nix eval`. + +## Why is there a guest for UTM? + +Because the QEMU in nixpkgs cannot give a guest a GPU on a Mac. Its `virtio-gpu` is 2D only, so +KWin composites on the guest's CPUs with llvmpipe, and KRDP encodes every frame on the same CPUs, +which is slow to use (it was not benchmarked). That QEMU cannot be rebuilt with GL from nixpkgs on +a Mac: virglrenderer and libepoxy build on `aarch64-darwin`, and ANGLE does not. krunkit 1.2.1 +accepts a `virtio-gpu` device and then ignores it. UTM's QEMU has `virtio-gpu-gl`, which renders +the guest's OpenGL on the Mac's GPU through VirGL and shows the guest in a window of its own, with +no RDP in between. + +The disk is made with `nixos-install` from a running guest, and not with nixpkgs' disk image +builders: those boot a virtual machine as part of the build, so they need a builder with KVM, and +a Linux builder that is itself a virtual machine on the Mac, as `darwin.linux-builder` is, has no +nested KVM. `nixos-install` is a plain program, in a guest that runs at the speed of the Mac's own +virtualization. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 90561500..90458578 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -796,3 +796,34 @@ At time of writing (2026-10-27): - KRDP 6.8.1, Plasma's RDP server, does not start without a TLS certificate and key, although its `--help` says it generates one; it logs the error and keeps running with nothing listening. `xrdp` is not an option, since there is no X11 session to start. + +### RDP into the session + +The session guests to develop in ([utm.md](utm.md)) run KRDP as a user unit of the session, +[`nix/dev/krdp.nix`](../../nix/dev/krdp.nix): `krdpserver --plasma`, which asks KWin for the +screen and for input through its own Wayland protocols (KRDP's desktop file lists +`zkde_screencast_unstable_v1` and `org_kde_kwin_fake_input`), so no portal asks the user first. The +unit makes a self-signed certificate, and logs in the session's user with a password the user +writes to a file; without the file it does not start. At time of writing (2026-10-27), with KWin +and KRDP 6.8.1 and FreeRDP 3.32.2: + +- KRDP sends the screen as H.264 only, encoded with x264 in software when there is no VAAPI device + (Constrained Baseline, level 6.0), and every frame is encoded on the guest's CPUs. +- FreeRDP decodes H.264 with OpenH264 when it is built with it, as nixpkgs builds it, and OpenH264 + decodes nothing of KRDP's video: it reports a bitstream error on the first frame + (`DecodeFrame2 state: 0x0004`) and no picture after it, and the client's window stays black. + FreeRDP built without OpenH264 decodes with FFmpeg, and shows the desktop: the guests install that + build. +- The VM suite `rdp` checks, in the session node under KVM: that the unit does not start before it + has a password and listens on port 3389 once it has one (a listener in the guest, which `ss` + sees: QEMU's port forwarding accepts a connection whether or not anything listens behind it); + that FreeRDP's client is let in with the password and not with another (`/auth-only`); and that + the picture the client gets, on an X server of its own, is the display: thousands of colors, + within 16 of 255 on average of a screenshot taken right after it (6.7 and 6.6 in two runs, 2.9 + seconds after the client started). +- Keys over RDP are not verified end to end. KRDP injects them into KWin through + `org_kde_kwin_fake_input`, which, read from the sources, puts them through the input pipeline + of KWin that KDE's global shortcuts are part of. No test sends one: aardwolf, a client that can + script keys, fails NTLM against KRDP, FreeRDP's client cannot script keys, and a client inside + the session would send each key back to itself. Whether a key pressed in an RDP client reaches a + global shortcut is therefore not known; no check from a real client has been recorded. diff --git a/docs/dev/utm.md b/docs/dev/utm.md new file mode 100644 index 00000000..67d4d108 --- /dev/null +++ b/docs/dev/utm.md @@ -0,0 +1,180 @@ +# Plasma guests to develop in + +The VM tests boot a machine, run a scenario and power it off. To try komorebi by hand against a +real KWin, the flake has three NixOS guests with Plasma 6 that stay up, all `aarch64-linux`, for +an Apple silicon Mac: + +| Guest | Runs under | What it is | +|---|---|---| +| `plasma-vm` | QEMU from nixpkgs, with HVF | Plasma installed, no login: a console and ssh, to run `kwin_wayland --virtual` and build komorebi from the repository | +| `plasma-vm-session` | QEMU from nixpkgs, with HVF | the same, plus a Plasma Wayland session that logs in by itself, komorebi running in it, and an RDP server | +| `plasma-utm` | [UTM](https://mac.getutm.app), with a GPU | the session guest as a disk image that boots by UEFI | + +They are `nixosConfigurations` of the flake, made from +[`nix/dev/plasma-vm.nix`](../../nix/dev/plasma-vm.nix), +[`nix/dev/plasma-utm.nix`](../../nix/dev/plasma-utm.nix) and +[`nix/dev/krdp.nix`](../../nix/dev/krdp.nix). Each one installs komorebi with the flake's NixOS +module, `services.komorebi`, so the komorebi in a guest is the one of the commit the guest was +built from, and in the session guests the module's unit starts it at login. They carry no key, +no password and no configuration of anyone's. + +The QEMU in nixpkgs has no 3D, so in the QEMU guests KWin composites on the CPU (llvmpipe) and +every frame then has to be encoded to reach an RDP client. That is slow. UTM's QEMU has +`virtio-gpu-gl`, which gives the guest OpenGL through Mesa's VirGL, rendered on the Mac's GPU, and +UTM shows the guest in a window of its own, so there is no RDP in the path at all. + +## What a builder has to be + +A Mac cannot build a Linux system, so the guests are built on a builder: a machine with Nix that +builds for `aarch64-linux` and that the Mac can reach as a remote store, such as +`ssh-ng://builder@localhost`. Any builder will do: the one `nix run nixpkgs#darwin.linux-builder` +starts, a Linux machine on the network, or the one the VM tests use on a Mac +([vm-tests.md](vm-tests.md#running-a-test-on-a-mac)). A Plasma system is a closure of about 10 GB, +and the builder needs room for it and for its build: the defaults of `darwin.linux-builder` (one +core, 3 GB of memory, a 20 GB disk) are too small. Six cores and 10 GB of memory worked, at time +of writing (2026-10-27). + +The examples below use the same variables as `scripts/vm-mac`: + +```sh +export KOMOREBI_BUILDER=ssh-ng://builder@localhost # the store URL of your builder +export NIX_SSHOPTS="-p 31022 -i $HOME/.ssh/builder_ed25519 -o IdentitiesOnly=yes" # if it needs them +``` + +## The QEMU guests + +The system is built on the builder and copied back, and only the QEMU runner, which is a program +for the Mac, is built on the Mac. A QEMU guest runs the system of its `vmVariant` (which adds the +disk and the shared directory), not the system of the configuration itself: + +```sh +guest=plasma-vm-session # or plasma-vm +config=".#nixosConfigurations.$guest.config" +system=$(nix build "$config.virtualisation.vmVariant.system.build.toplevel" \ + --eval-store auto --store "$KOMOREBI_BUILDER" --no-link --print-out-paths) +nix copy --from "$KOMOREBI_BUILDER" --substitute-on-destination --no-check-sigs "$system" +nix build "$config.system.build.vm" --builders '' -o .vm/result-$guest +``` + +The guest mounts the directory `KOMOREBI_REPO` names at `/repo`, and makes its disk, +`plasma-vm.qcow2` or `plasma-vm-session.qcow2`, in the directory it is started from on its first +start, and keeps it there. `.vm` is ignored by git: + +```sh +cd .vm && KOMOREBI_REPO=$PWD/.. ./result-$guest/bin/run-$guest-vm +``` + +The terminal is the guest's console, logged in as the user `komorebi`, who can use `sudo` with no +password. ssh is forwarded from `localhost:2222` (`plasma-vm`) or `localhost:2223` +(`plasma-vm-session`) and takes keys only: put yours in `~/.ssh/authorized_keys` from the console +once, and the disk keeps it. Both guests can run at once. + +In the guest, `/repo` is the repository and `CARGO_TARGET_DIR` is in the guest's home, since a +target directory on the shared directory is slow. The session guest shows nothing on the Mac; it +is reached over RDP ([below](#rdp)). + +## The UTM disk + +UTM boots `plasma-utm` from a disk image. The image is made by installing the system onto a blank +disk from a running Linux system with `nixos-install`, which needs no virtualization on the +builder: here, the `plasma-vm` guest, which has the tools for it. Build both systems first: the +`plasma-vm` runner as above, and the `plasma-utm` system, on the builder, copied back: + +```sh +system=$(nix build .#nixosConfigurations.plasma-utm.config.system.build.toplevel \ + --eval-store auto --store "$KOMOREBI_BUILDER" --no-link --print-out-paths) +nix copy --from "$KOMOREBI_BUILDER" --substitute-on-destination --no-check-sigs "$system" +``` + +The closure goes into the guest as one file that `nix-store --export` writes, and not through the +guest's view of the Mac's store: macOS stores files whose names differ only by case under other +names (`~nix~case~hack~1`), which a guest reading the directory sees, and nix then rejects the +hashes. An export undoes that. Then boot `plasma-vm` with a blank disk of 40 GB attached: + +```sh +mkdir -p .vm/utm && cd .vm +nix-store --export $(nix-store -qR "$system") > utm/plasma-utm.closure +echo "$system" > utm/plasma-utm.system +nix shell nixpkgs#qemu --command qemu-img create -f raw utm/plasma.raw 40G +QEMU_OPTS="-drive file=$PWD/utm/plasma.raw,format=raw,if=none,id=utm -device virtio-blk-pci,drive=utm" \ + KOMOREBI_REPO=$PWD/.. ./result-plasma-vm/bin/run-plasma-vm-vm +``` + +In the guest's console, partition the disk, which is `/dev/vdb`, and install the system onto it: + +```sh +sudo parted -s /dev/vdb -- mklabel gpt mkpart ESP fat32 1MiB 512MiB set 1 esp on mkpart nixos ext4 512MiB 100% +sudo mkfs.vfat -F 32 -n ESP /dev/vdb1 +sudo mkfs.ext4 -q -L nixos /dev/vdb2 +sudo mount /dev/vdb2 /mnt && sudo mkdir -p /mnt/boot && sudo mount /dev/vdb1 /mnt/boot +sudo nix-store --import --store /mnt < /repo/.vm/utm/plasma-utm.closure > /dev/null +sudo nixos-install --system "$(cat /repo/.vm/utm/plasma-utm.system)" --root /mnt --no-root-passwd --no-channel-copy +sudo umount /mnt/boot /mnt && sudo poweroff +``` + +Back on the Mac, in `.vm`, the raw disk becomes the qcow2 that UTM is pointed at (about 12 GB +used of 40): + +```sh +nix shell nixpkgs#qemu --command qemu-img convert -O qcow2 utm/plasma.raw utm/plasma.qcow2 +rm utm/plasma.raw utm/plasma-utm.closure +``` + +## Point UTM at it + +1. Install UTM (`brew install --cask utm`, or from its website). +2. New VM → **Virtualize** → **Linux**. Leave the boot ISO empty. Give it 8192 MB and 6 cores. + (The wizard insists on a new disk; delete it in step 3.) +3. Before the first start, open the VM's settings: + - **Drives**: remove the new disk, then **Import** `.vm/utm/plasma.qcow2` (interface VirtIO). + - **Display**: *Emulated Display Card* `virtio-gpu-gl-pci (GPU Supported)`. New Linux VMs get + it by default. Renderer backend *Default* (ANGLE on Metal) or *Apple Core OpenGL* (GL 4.1). + - **Network**: *Shared Network* (the guest gets an address the Mac can reach), or *Emulated VLAN* + with port forwards 2224→22 and 3389→3389. + - Name it `plasma-utm`. +4. Start it. sddm logs in by itself and Plasma comes up with komorebi running. + +## Using it + +The VM's window is the desktop: click into it and use it. The pointer is an absolute tablet, so it +moves in and out of the window without being grabbed; if the window does capture it, +**Control+Option** releases it (UTM's default; Command+Option also works, and Control+Option +collides with VoiceOver). The Option key is Alt in the guest. macOS takes a few combinations before +UTM sees them (Control-arrow switches Spaces, and anything with Command), and those never reach the +guest. Resizing the window resizes the guest's screen, and the clipboard is shared (spice-vdagent +runs in the guest). + +To check that the session is on the GPU, from a terminal in the guest (or over ssh, once a key of +yours is in `~/.ssh/authorized_keys`): + +```sh +eglinfo 2>/dev/null | grep -i renderer # virgl (Apple M...) +journalctl --user -b -t kwin_wayland | grep -i "opengl\|renderer" | head +komorebic state | head +``` + +## RDP + +The session guests run KRDP, Plasma's RDP server, as the user unit `krdp`, on port 3389 (forwarded +from `localhost:3389` for `plasma-vm-session`). It logs in the session's user, `komorebi`, with a +password of your choosing, which the unit reads from a file in the guest; until the file is there, +the unit does not start. In the guest: + +```sh +umask 077 && mkdir -p ~/.config/komorebi-vm && cat > ~/.config/komorebi-vm/rdp-password # type it, then Ctrl-D +systemctl --user start krdp +``` + +The server makes a self-signed certificate the first time it starts, so a client warns about it. +The password is passed to `krdpserver` on its command line, which every user of the guest can read +in the process list. [PLATFORM.md](PLATFORM.md#rendering-in-virtual-machines-and-over-rdp) says what +is known about RDP into the session, and what is not. + +## What is not known + +At time of writing (2026-10-27), the guests made from these files have been built on an +`aarch64-linux` machine, and not booted: no test covers them, and `plasma-guests-eval` only +evaluates them. The RDP server is the exception: the VM suite `rdp` runs the same unit in the test +session. That KWin 6.8 runs well on VirGL under UTM is not known either: the UTM and Mesa notes say +VirGL is the way to render a Linux desktop, and Plasma works on it for other people, but it has not +been measured here. diff --git a/docs/dev/vm-tests.md b/docs/dev/vm-tests.md index 85c86322..775a8250 100644 --- a/docs/dev/vm-tests.md +++ b/docs/dev/vm-tests.md @@ -114,6 +114,11 @@ the pointer from inside the guest, and KWin takes it as a tablet. On aarch64 under HVF, at time of writing (2026-10-27), the session has the Wayland socket after 11 to 19 seconds and a painted desktop after 35 seconds. +A suite's `node` can import a module of the repository: `rdp` imports +[`nix/dev/krdp.nix`](../../nix/dev/krdp.nix), the RDP server of the Plasma +guests to develop in, so that the suite checks the unit those guests run. The +guests themselves, which stay up for a person to use, are in [utm.md](utm.md). + ## The library Suites import from `komorebi_vm`, in diff --git a/flake.nix b/flake.nix index e9522876..8b9e13f4 100644 --- a/flake.nix +++ b/flake.nix @@ -272,6 +272,31 @@ borderEffectFor = guestSystem: self.packages.${guestSystem}.kde-rounded-corners-komorebi; animationEffectFor = guestSystem: self.packages.${guestSystem}.kwin-effect-geometry-change-komorebi; }; + + # The Plasma guests to develop against, evaluated and never built, so that every system + # sees an option that nixpkgs renamed or an assertion that fails. The QEMU guests are + # systems in a VM (`vmVariant`), with a runner for the Mac; UTM's is a system of its own. + plasma-guests-eval = + let + guests = self.nixosConfigurations; + qemuGuest = name: { + ${name} = guests.${name}.config.virtualisation.vmVariant.system.build.toplevel; + "${name}, its runner" = guests.${name}.config.system.build.vm; + }; + builds = + qemuGuest "plasma-vm" + // qemuGuest "plasma-vm-session" + // { + plasma-utm = guests.plasma-utm.config.system.build.toplevel; + }; + lines = lib.mapAttrsToList ( + name: drv: "${name}: ${builtins.unsafeDiscardStringContext drv.drvPath}" + ) builds; + in + pkgs.runCommand "plasma-guests-eval" { } '' + ${lib.concatMapStringsSep "\n" (line: "echo ${lib.escapeShellArg line}") lines} + touch $out + ''; } # The VM tests need QEMU with KVM, so only Linux checks them. A Mac runs the same tests # through legacyPackages..vm, see docs/dev/vm-tests.md. @@ -390,6 +415,30 @@ nixpkgs.overlays = [ self.overlays.default ]; }; nixosModules.komorebi = self.nixosModules.default; + + # Plasma guests to develop against, for an Apple silicon Mac (docs/dev/utm.md): QEMU runs + # the first two under HVF, and UTM boots the third from a disk image + nixosConfigurations = + let + mkPlasmaGuest = + modules: + nixpkgs.lib.nixosSystem { + specialArgs.hostPkgs = nixpkgs.legacyPackages.aarch64-darwin; + modules = [ + self.nixosModules.default + { nixpkgs.hostPlatform = "aarch64-linux"; } + ] + ++ modules; + }; + in + { + plasma-vm = mkPlasmaGuest [ ./nix/dev/plasma-vm.nix ]; + plasma-vm-session = mkPlasmaGuest [ + ./nix/dev/plasma-vm.nix + { komorebi.plasmaVm.session = true; } + ]; + plasma-utm = mkPlasmaGuest [ ./nix/dev/plasma-utm.nix ]; + }; }; }; } diff --git a/nix/dev/krdp.nix b/nix/dev/krdp.nix new file mode 100644 index 00000000..62e7ff89 --- /dev/null +++ b/nix/dev/krdp.nix @@ -0,0 +1,65 @@ +# KRDP, Plasma's RDP server, in the Plasma session of every user who logs in. The session guest +# of plasma-vm.nix enables it, and so does the VM suite `rdp`, which checks that a client can log +# in and get a picture of the desktop (docs/dev/PLATFORM.md says what it does not check). +# +# The password is not in the repository: the unit starts once the user has written one to +# ~/.config/komorebi-vm/rdp-password, and a client logs in with the user's name and that password. +{ + config, + lib, + pkgs, + ... +}: +let + startKrdp = pkgs.writeShellScript "krdp-start" '' + set -eu + dir=$HOME/.config/komorebi-vm + # krdpserver refuses to run without a TLS certificate and key (its --help promises a temporary + # one, but it only checks that the files exist), so make a throwaway self-signed pair + if [ ! -f "$dir/rdp.crt" ] || [ ! -f "$dir/rdp.key" ]; then + ${pkgs.openssl}/bin/openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=komorebi-vm \ + -addext subjectAltName=DNS:localhost,IP:127.0.0.1 -keyout "$dir/rdp.key" -out "$dir/rdp.crt" + chmod 600 "$dir/rdp.key" + fi + # --plasma asks KWin for the screen and for input directly, with no portal prompt to click + exec ${pkgs.kdePackages.krdp}/bin/krdpserver --plasma --address 0.0.0.0 --port 3389 \ + --certificate "$dir/rdp.crt" --certificate-key "$dir/rdp.key" \ + --username "$USER" --password "$(cat "$dir/rdp-password")" + ''; +in +{ + options.komorebi.krdp.enable = lib.mkEnableOption "KRDP, an RDP server, in every Plasma session"; + + config = lib.mkIf config.komorebi.krdp.enable { + environment.systemPackages = [ + pkgs.kdePackages.krdp + # A client, to try the server from inside the guest. FreeRDP decodes H.264 with OpenH264 + # when it is built with it, and OpenH264 shows nothing of the video KRDP sends; without it, + # FreeRDP decodes with FFmpeg (the VM suite `rdp`, docs/dev/PLATFORM.md). + (pkgs.freerdp.override { openh264 = null; }) + ]; + + # krdp streams the screen through pipewire + services.pipewire = { + enable = true; + wireplumber.enable = true; + }; + security.rtkit.enable = true; + + networking.firewall.allowedTCPPorts = [ 3389 ]; + + systemd.user.services.krdp = { + description = "RDP into this Plasma session"; + wantedBy = [ "plasma-workspace.target" ]; + after = [ "plasma-core.target" ]; + # with no password the unit is skipped, not failed: `systemctl --user start krdp` once the + # file is there + unitConfig.ConditionPathExists = "%h/.config/komorebi-vm/rdp-password"; + serviceConfig = { + ExecStart = startKrdp; + Restart = "on-failure"; + RestartSec = 3; + }; + }; + }; +} diff --git a/nix/dev/plasma-utm.nix b/nix/dev/plasma-utm.nix new file mode 100644 index 00000000..969182d0 --- /dev/null +++ b/nix/dev/plasma-utm.nix @@ -0,0 +1,57 @@ +{ lib, pkgs, ... }: + +# The Plasma session guest as a plain disk image, for a hypervisor with a GPU: UTM on Apple Silicon +# runs QEMU with virtio-gpu-gl (virgl over ANGLE/CoreGL), which the QEMU in nixpkgs, and so the +# 9p-booted `plasma-vm-session`, cannot: that one composites with llvmpipe on the CPU. +# +# This is the same session as plasma-vm.nix (komorebi from the module, KRDP), booted from its own +# disk by UEFI instead of from a kernel and the host's /nix/store. docs/dev/utm.md says how to +# install it onto a disk image and point UTM at it. +{ + imports = [ ./plasma-vm.nix ]; + + komorebi.plasmaVm.session = true; + + networking.hostName = lib.mkOverride 40 "plasma-utm"; + + boot.loader = { + grub = { + enable = true; + efiSupport = true; + efiInstallAsRemovable = true; + device = "nodev"; + }; + efi.canTouchEfiVariables = false; + timeout = 1; + }; + + boot.initrd.availableKernelModules = [ + "virtio_pci" + "virtio_blk" + "virtio_net" + "virtio_scsi" + "xhci_pci" + "usbhid" + ]; + # kms from the start, so that sddm has a screen to start on + boot.initrd.kernelModules = [ "virtio_gpu" ]; + boot.kernelParams = [ "console=tty0" ]; + boot.growPartition = true; + + fileSystems."/" = { + device = "/dev/disk/by-label/nixos"; + fsType = "ext4"; + autoResize = true; + }; + fileSystems."/boot" = { + device = "/dev/disk/by-label/ESP"; + fsType = "vfat"; + }; + + # the window follows the guest's resolution, and the clipboard is shared + services.spice-vdagentd.enable = true; + services.qemuGuest.enable = true; + + # to check that the session really is on the GPU: `eglinfo | grep -i renderer` says virgl + environment.systemPackages = [ pkgs.mesa-demos ]; +} diff --git a/nix/dev/plasma-vm.nix b/nix/dev/plasma-vm.nix new file mode 100644 index 00000000..6f9e6c27 --- /dev/null +++ b/nix/dev/plasma-vm.nix @@ -0,0 +1,203 @@ +{ + config, + lib, + pkgs, + hostPkgs, + ... +}: + +# A NixOS Plasma 6 guest to develop and test against a real KWin, with komorebi installed by the +# flake's module, `services.komorebi`, from the flake's packages. The flake builds it for an Apple +# silicon Mac, which runs it under QEMU with HVF; docs/dev/utm.md says how to build and run it. +# +# The guest mounts the repository at /repo, and keeps its disk in the directory it is started +# from, which is best .vm (gitignored): +# +# nix build .#nixosConfigurations.plasma-vm.config.system.build.vm -o .vm/result-plasma-vm +# cd .vm && KOMOREBI_REPO=$PWD/.. ./result-plasma-vm/bin/run-plasma-vm-vm +# +# The console, in the terminal that runs the guest, is logged in as the user `komorebi`. ssh is +# forwarded to localhost:2222 (2223 for the session), for the keys in ~/.ssh/authorized_keys of +# that user, which the guest's disk keeps. +# +# The session variant is the one to live in: Plasma logs in by itself, the module's unit runs +# komorebi in it, and it can be reached over RDP (krdp.nix). +let + cfg = config.komorebi.plasmaVm; +in +{ + imports = [ ./krdp.nix ]; + + options.komorebi.plasmaVm = { + session = lib.mkEnableOption '' + a full autologin Plasma Wayland session (sddm + plasmashell), in addition to the headless + `kwin_wayland --virtual` workflow that is always available from the console and over ssh + ''; + }; + + config = lib.mkMerge [ + { + system.stateVersion = "26.05"; + networking.hostName = "plasma-vm"; + + services.desktopManager.plasma6.enable = true; + programs.dconf.enable = true; + # mesa (llvmpipe over the virtio-gpu render node) so kwin can composite with GL + hardware.graphics.enable = true; + fonts.enableDefaultPackages = true; + + # komorebi and komorebic, from the flake's packages; the unit starts with a Plasma session + services.komorebi.enable = true; + + services.openssh = { + enable = true; + settings = { + PasswordAuthentication = false; + PermitRootLogin = "no"; + }; + }; + + # the way in before any key is in ~/.ssh/authorized_keys: there is no password anywhere + services.getty.autologinUser = "komorebi"; + + users.users.komorebi = { + isNormalUser = true; + uid = 1000; + extraGroups = [ + "wheel" + "video" + "render" + ]; + # keep a user manager (and XDG_RUNTIME_DIR) alive across ssh sessions + linger = true; + }; + security.sudo.wheelNeedsPassword = false; + + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + + environment.systemPackages = with pkgs; [ + # clients to tile: Qt/KDE, GTK3/4 (CSD), Electron-ish via firefox, plain wayland, XWayland + kdePackages.konsole + kdePackages.dolphin + kdePackages.kate + kdePackages.spectacle + firefox + gnome-text-editor + gnome-calculator + foot + xterm + + # poking at KWin + kdePackages.qttools # qdbus6 + dbus + jq + kdotool + strace + + # installing plasma-utm onto a disk image (docs/dev/utm.md) + nixos-install-tools + dosfstools + parted + e2fsprogs + + # building komorebi from /repo in the guest + rustc + cargo + gcc + pkg-config + git + rsync + htop + ]; + + environment.sessionVariables = { + # kwin refuses to load animating effects (including the stock scripted ones) under software + # rendering; llvmpipe is all this vm has + KWIN_EFFECTS_FORCE_ANIMATIONS = "1"; + # always build in guest-local storage; /repo is a 9p mount and is slow for target dirs + CARGO_TARGET_DIR = "/home/komorebi/target"; + }; + + virtualisation.vmVariant = { + virtualisation = { + host.pkgs = hostPkgs; + qemu.forceAccel = true; + cores = 6; + memorySize = 8192; + diskSize = 20 * 1024; + graphics = false; + # no display, but a gpu so there is a drm render node + qemu.options = lib.mkIf (!cfg.session) [ "-device virtio-gpu-pci" ]; + forwardPorts = [ + { + from = "host"; + host.address = "127.0.0.1"; + host.port = if cfg.session then 2223 else 2222; + guest.port = 22; + } + ]; + sharedDirectories.repo = { + # the runner says so when it is not set + source = "\${KOMOREBI_REPO:?set KOMOREBI_REPO to the root of the repository}"; + target = "/repo"; + writable = true; + }; + }; + }; + } + + (lib.mkIf cfg.session { + # a separate disk image (named after the host) and ssh port so both vms can run at once + networking.hostName = lib.mkForce "plasma-vm-session"; + services.displayManager = { + sddm = { + enable = true; + wayland.enable = true; + }; + autoLogin = { + enable = true; + user = "komorebi"; + }; + defaultSession = "plasma"; + }; + # kwin drives virtio-gpu through drm on the primary node; that is the only place mesa's software + # rasterizer can allocate buffers (see docs/dev/PLATFORM.md: the headless --virtual backend + # cannot) + virtualisation.vmVariant.virtualisation.qemu.options = [ + "-device virtio-gpu-pci,xres=1920,yres=1080" + ]; + # an idle lock screen or dimmed display changes how kwin animates and what screenshots show + environment.etc."xdg/kscreenlockerrc".text = '' + [Daemon] + Autolock=false + LockOnResume=false + ''; + # and so does a display that has gone to sleep: with the output off, KWin sends no frame + # callbacks, so clients stop answering resizes and every window stays where it was while komorebi + # asks for another place (found on the UTM guest after it sat idle: black screenshots, nothing tiled) + environment.etc."xdg/powerdevilrc".text = '' + [AC][Display] + DimDisplayWhenIdle=false + TurnOffDisplayWhenIdle=false + + [AC][SuspendAndShutdown] + AutoSuspendAction=0 + ''; + + komorebi.krdp.enable = true; + + # only the host's loopback reaches it + virtualisation.vmVariant.virtualisation.forwardPorts = [ + { + from = "host"; + host.address = "127.0.0.1"; + host.port = 3389; + guest.port = 3389; + } + ]; + }) + ]; +} diff --git a/nix/tests/vm/suites/rdp/default.nix b/nix/tests/vm/suites/rdp/default.nix new file mode 100644 index 00000000..6896c735 --- /dev/null +++ b/nix/tests/vm/suites/rdp/default.nix @@ -0,0 +1,20 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 15; + node = + { pkgs, ... }: + { + # the RDP server of the session guest to develop in + imports = [ ../../../../dev/krdp.nix ]; + komorebi.krdp.enable = true; + + # an X server of the client's own, and what reads its picture back + environment.systemPackages = [ + pkgs.iproute2 + pkgs.netpbm + pkgs.xvfb + pkgs.xwd + ]; + }; +} diff --git a/nix/tests/vm/suites/rdp/test.py b/nix/tests/vm/suites/rdp/test.py new file mode 100644 index 00000000..df55b116 --- /dev/null +++ b/nix/tests/vm/suites/rdp/test.py @@ -0,0 +1,115 @@ +# KRDP, Plasma's RDP server, runs in the Plasma session of the session node as the guest to develop +# in runs it (nix/dev/krdp.nix), and a client logs in and gets a picture of the desktop. What only a +# real session can tell: that the unit starts in the session once it has a password, that KWin lets +# KRDP have the screen without asking, that a client with the password is let in and one without +# it is not, and that the picture the client gets is what the display shows. +# +# The client is FreeRDP's, on an X server of its own (Xvfb), so its picture can be read back and +# compared with a screenshot of the display. A client on the display would be in its own picture. +# No keys are sent: no client could script them against KRDP (docs/dev/PLATFORM.md). +import secrets +import time + +from PIL import Image, ImageChops, ImageStat + +from komorebi_vm import Checks, Kde + +PASSWORD_FILE = "/home/komorebi/.config/komorebi-vm/rdp-password" +# the client's X server, and the size of the display it gets a picture of +X = ":99" +WIDTH, HEIGHT = 1280, 800 + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + + +def active(unit: str) -> bool: + return kde.run(f"systemctl --user is-active --quiet {unit}")[0] == 0 + + +checks.check("komorebi runs in the session", kde.wait_for(lambda: active("komorebi"), timeout=60)) +checks.check("with no password, KRDP does not start", not active("krdp")) + +password = secrets.token_hex(16) +kde.as_user( + f"umask 077 && mkdir -p $(dirname {PASSWORD_FILE}) && printf %s {password} > {PASSWORD_FILE}" +) +kde.systemctl("start", "krdp.service") + + +def listening() -> bool: + return machine.execute("ss -ltnpH 'sport = :3389' | grep -q krdpserver")[0] == 0 + + +checks.check("with a password, KRDP listens on port 3389", kde.wait_for(listening, timeout=60)) + +machine.succeed( + f"setsid nohup Xvfb {X} -screen 0 {WIDTH}x{HEIGHT}x24 > /tmp/xvfb.log 2>&1 < /dev/null &" +) +machine.wait_until_succeeds(f"test -S /tmp/.X11-unix/X{X[1:]}", timeout=30) + + +def client(secret: str, *args: str) -> str: + """The command line of FreeRDP's client, on the client's X server, logging in as komorebi.""" + words = ["xfreerdp", "/v:127.0.0.1", "/u:komorebi", f"/p:{secret}", "/cert:ignore", *args] + return f"env DISPLAY={X} " + " ".join(words) + + +checks.check( + "a client with the password is let in", + machine.execute(client(password, "/auth-only"))[0] == 0, +) +checks.check( + "a client with another password is not", + machine.execute(client("not-" + password, "/auth-only"))[0] != 0, +) + +started = time.monotonic() +machine.succeed( + "setsid nohup " + + client(password, f"/size:{WIDTH}x{HEIGHT}") + + " > /tmp/xfreerdp.log 2>&1 < /dev/null &" +) + + +def client_picture() -> Image.Image: + """What the client shows, read from its X server.""" + machine.succeed(f"xwd -display {X} -root -silent | xwdtopnm > /tmp/rdp.ppm 2>/dev/null") + machine.copy_from_machine("/tmp/rdp.ppm") + return Image.open(machine.out_dir / "rdp.ppm").convert("RGB") + + +def difference(remote: Image.Image, local: Image.Image) -> float: + """The mean difference of the two pictures, from 0 (the same) to 255, over every channel.""" + if remote.size != local.size: + remote = remote.resize(local.size) + return sum(ImageStat.Stat(ImageChops.difference(remote, local)).mean) / 3 + + +def colors(image: Image.Image) -> int: + found = image.getcolors(maxcolors=image.width * image.height) + return len(found) if found is not None else 0 + + +def same_picture() -> bool: + remote = client_picture() + local = kde.shot("display") + diff = difference(remote, local) + print(f"the client's picture: {remote.size}, {colors(remote)} colors, {diff:.1f} from the display") + # a client that has no picture yet shows black, a desktop has thousands of colors, and the video + # KRDP sends is lossy + return colors(remote) > 1000 and diff < 16 + + +checks.check("the client's picture is the display", kde.wait_for(same_picture, timeout=90, interval=2)) +print(f"after {time.monotonic() - started:.1f}s") + +remote = client_picture() +remote.save(machine.out_dir / "client.png") +print(machine.execute("journalctl --no-pager _SYSTEMD_USER_UNIT=krdp.service | tail -n 20")[1]) +print(machine.execute("tail -n 20 /tmp/xfreerdp.log")[1]) + +checks.finish()