From 18a8096a39f47668108d9ec35a8f8e746eebf826 Mon Sep 17 00:00:00 2001 From: KitsuneSemCalda Date: Tue, 29 Sep 2026 23:00:54 -0300 Subject: [PATCH 1/5] PKGBUILD: package v0.3.0 Bump to the v0.3.0 tag and its checksum. The GUI links GIO and EGL since the D-Bus display, so depend on glib2 and libglvnd; drop qt6-tools, which the build never used (qmake6 ships in qt6-base). --- packaging/omavm/PKGBUILD | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packaging/omavm/PKGBUILD b/packaging/omavm/PKGBUILD index 12817f6..63d4a3f 100644 --- a/packaging/omavm/PKGBUILD +++ b/packaging/omavm/PKGBUILD @@ -1,14 +1,14 @@ # Maintainer: Arthur Augusto pkgname=omavm -pkgver=0.2.1 +pkgver=0.3.0 pkgrel=1 pkgdesc="Create, run and manage Boxes and Machines on Omarchy" arch=('x86_64') url="https://github.com/KitsuneSemCalda/OmaVM" license=('MIT') -depends=('qt6-base' 'qt6-declarative' 'glibc' 'zlib') -makedepends=('go' 'qt6-tools') +depends=('qt6-base' 'qt6-declarative' 'glib2' 'libglvnd' 'glibc' 'zlib') +makedepends=('go') optdepends=('distrobox: integrated Development Box environments' 'podman: preferred Distrobox container engine' 'docker: alternative Distrobox container engine and legacy Boxes' @@ -16,7 +16,7 @@ optdepends=('distrobox: integrated Development Box environments' 'virtiofsd: share host folders with Machine guests') install=omavm.install source=("$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz") -sha256sums=('edc28b1feca64c73109d840c5a95203be081c30f6263ba9a2855e6ca0b195169') +sha256sums=('c3f261b68abea7545a5b01870546fa6ff5e802fb47577befe3625b048d1a9df3') build() { cd "OmaVM-$pkgver" From cc58285d677645fece5b1fd8ba5518e2200b52d5 Mon Sep 17 00:00:00 2001 From: KitsuneSemCalda Date: Thu, 1 Oct 2026 19:29:40 -0300 Subject: [PATCH 2/5] Clone, Box updates, ephemeral runs, CLI exit codes and lifecycle fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New: - omavm clone (Box via distrobox --clone, Machine via a sparse/reflink copy of its stopped disk with snapshots); "Clone…" says the cost first. A Box clone's commit image goes away with the clone. - omavm update / "Update System" for Boxes (distrobox upgrade), with the package manager's lines as progress on the card. - omavm run --ephemeral: a new Desktop that is deleted when it shuts down; start --ephemeral / "Start Without Keeping Changes" for existing ones (-snapshot, snapshots refused meanwhile). - Stable CLI exit codes (0-6) and {"error": {code, message}} with --json; exec/ssh pass their command's code through. - Progress while creating a Box (image pulled first, layer by layer). - Status says when saved settings wait for a restart, when Travel Mode trimmed CPUs, when the host disk is low, and when a session ended without shutting down. - Per-capability guest integration (clipboard via spice-vdagent's port, shared folder via guest-get-fsinfo) and a one-way clipboard option. - Viewer: disconnect panel with Reconnect; Experience Center is single instance; terminal color strip, scrollback keys and font zoom; the card names the distribution and says what its main action does; creation offers to open the new environment; KVM warning before creating a Desktop. Fixes: - QMP: per-command timeouts, structured errors, and snapshot commands left without a reply reconciled through query-block. - A snapshot gone from the disk no longer blocks removal and retention. - Resume reports a disk-full pause that comes right back; a paused Machine whose shutdown times out is paused again, never left running. - Locked disk, too much memory and unreadable ISOs explained at Start. - The list poll no longer waits 700 ms for an absent guest agent. - make install points the launcher entry at the installed binary. --- CLAUDE.md | 4 + Makefile | 3 + README.md | 80 +++++- cmd/omavm/errors.go | 98 +++++++ cmd/omavm/errors_test.go | 87 ++++++ cmd/omavm/main.go | 199 ++++++++++--- cmd/omavm/testdata/list-status.golden.json | 2 +- contrib/dev.omavm.bar/OmaVM.qml | 12 +- data/dev.omavm.app.desktop | 2 +- docs/TODO.md | 64 ++++- docs/discovery.md | 2 +- docs/ideias/README.md | 12 +- docs/ideias/disco-do-host.md | 2 + docs/ideias/terminal-ptyxis.md | 2 + gui/AppsDialog.qml | 77 ++++- gui/CloneDialog.qml | 101 +++++++ gui/CreateDialog.qml | 28 +- gui/EnvironmentCard.qml | 139 ++++++++- gui/Main.qml | 42 ++- gui/SettingsDialog.qml | 67 ++++- gui/SnapshotsDialog.qml | 11 +- gui/TerminalViewer.qml | 15 +- gui/Viewer.qml | 90 +++++- gui/backend.cpp | 134 ++++++++- gui/backend.h | 29 +- gui/displayview.cpp | 6 +- gui/displayview.h | 5 + gui/main.cpp | 72 ++++- gui/resources.qrc | 1 + gui/singleinstance.cpp | 39 +++ gui/singleinstance.h | 33 +++ gui/terminal.cpp | 34 +++ gui/terminal.h | 15 + gui/terminalview.cpp | 80 +++++- gui/terminalview.h | 4 + gui/tests/backend_refresh_test.cpp | 62 ++++ gui/tests/backend_refresh_test.pro | 4 +- gui/tests/qml/tst_accessibility.qml | 1 + gui/tests/qml/tst_appsdialog.qml | 51 ++++ gui/tests/qml/tst_clonedialog.qml | 43 +++ gui/tests/qml/tst_createdialog.qml | 42 +++ gui/tests/qml/tst_environmentcard.qml | 123 ++++++++ gui/tests/qml/tst_environmentlistmodel.qml | 21 ++ gui/tests/qml/tst_settingsdialog.qml | 26 +- gui/tests/qml_test.cpp | 32 ++- gui/tests/terminal_test.cpp | 18 ++ internal/backend/box/box.go | 19 ++ internal/backend/distrobox/distrobox.go | 117 +++++++- internal/backend/distrobox/pull.go | 98 +++++++ internal/backend/distrobox/pull_test.go | 109 +++++++ internal/backend/distrobox/upgrade_test.go | 49 ++++ internal/backend/qemu/applied.go | 84 ++++++ internal/backend/qemu/applied_test.go | 56 ++++ internal/backend/qemu/clone_test.go | 44 +++ internal/backend/qemu/ephemeral_test.go | 87 ++++++ internal/backend/qemu/guestcaps.go | 94 ++++++ internal/backend/qemu/guestcaps_test.go | 38 +++ internal/backend/qemu/iso_test.go | 17 +- internal/backend/qemu/lifecycle_test.go | 100 ++++++- internal/backend/qemu/qemu.go | 319 +++++++++++++++++++-- internal/backend/qemu/qga.go | 43 ++- internal/backend/qemu/qmp.go | 94 +++++- internal/backend/qemu/qmp_test.go | 248 ++++++++++++++++ internal/backend/qemu/space_test.go | 38 +++ internal/core/backend.go | 60 ++++ internal/core/clipboard_test.go | 46 +++ internal/core/clone_test.go | 90 ++++++ internal/core/environment.go | 42 ++- internal/core/ephemeral_test.go | 48 ++++ internal/core/errors.go | 3 + internal/core/progress.go | 24 ++ internal/core/run.go | 74 +++++ internal/core/run_test.go | 90 ++++++ internal/core/service.go | 118 +++++++- internal/core/snapshotgone_test.go | 44 +++ internal/desktop/desktop.go | 3 + internal/desktop/desktop_test.go | 20 ++ omavm-gui.pro | 4 +- 78 files changed, 4175 insertions(+), 159 deletions(-) create mode 100644 cmd/omavm/errors.go create mode 100644 cmd/omavm/errors_test.go create mode 100644 gui/CloneDialog.qml create mode 100644 gui/singleinstance.cpp create mode 100644 gui/singleinstance.h create mode 100644 gui/tests/qml/tst_appsdialog.qml create mode 100644 gui/tests/qml/tst_clonedialog.qml create mode 100644 internal/backend/distrobox/pull.go create mode 100644 internal/backend/distrobox/pull_test.go create mode 100644 internal/backend/distrobox/upgrade_test.go create mode 100644 internal/backend/qemu/applied.go create mode 100644 internal/backend/qemu/applied_test.go create mode 100644 internal/backend/qemu/clone_test.go create mode 100644 internal/backend/qemu/ephemeral_test.go create mode 100644 internal/backend/qemu/guestcaps.go create mode 100644 internal/backend/qemu/guestcaps_test.go create mode 100644 internal/backend/qemu/qmp_test.go create mode 100644 internal/backend/qemu/space_test.go create mode 100644 internal/core/clipboard_test.go create mode 100644 internal/core/clone_test.go create mode 100644 internal/core/ephemeral_test.go create mode 100644 internal/core/progress.go create mode 100644 internal/core/run.go create mode 100644 internal/core/run_test.go create mode 100644 internal/core/snapshotgone_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 3c8a3ec..8a1f704 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -322,6 +322,10 @@ Continua fora do escopo até necessidade real: guest agent completo, GPU passthr ## Ephemeral Environments & Agentic Workflows - Ambientes descartáveis são um conceito de primeira classe (`omavm run arch --ephemeral`), destruídos ao encerrar, e devem funcionar para Boxes e Machines quando possível. Casos de uso: dev temporário, testes, CI local, agentes, Agentic QA, reprodução de bugs, validação em sistema limpo. +- **Machine descartável — implementado (2026-09-30)**: `omavm start NOME --ephemeral` (e "Start Without Keeping Changes" no card) via capability opcional `core.EphemeralStarter`; o QEMU recebe `-snapshot`, com `TMPDIR` no diretório da Machine para o overlay crescer no mesmo disco cujo `io-error` já é explicado. Nada vai para o domínio: a sessão é reconhecida pelo `-snapshot` no `/proc//cmdline` e aparece como `Status.Ephemeral`. Snapshots são recusados durante a sessão (cairiam no overlay), e Restart preserva o modo. `omavm run --ephemeral --image ISO` (2026-10-01) cria uma Machine nova sem entrada no launcher, roda descartável e a apaga quando ela desliga; a CLI espera, sem daemon, e Ctrl+C a encerra e apaga. Boxes descartáveis continuam por fazer (modo Disposable sobre containers diretos). +- **Clone e Atualizar (2026-10-01)**: `core.Cloner` (Box: `distrobox create --clone`, parada, a imagem de commit sai junto com o clone; Machine: `cp --reflink=auto --sparse=always` do qcow2 parado, com checagem de espaço) e `core.Upgrader` (Box: `distrobox upgrade`, linhas como etapas de progresso). CLI `clone`/`update`, GUI "Clone…" com o custo antes e "Update System". +- **Progresso e aviso de espaço (2026-10-01)**: operações longas reportam etapas reais por `core.WithProgress`/`ReportProgress` (no contexto, sem mudar a interface `Backend`); o Distrobox baixa a imagem antes do `create` e repassa as layers. `create --progress` imprime `progress: ETAPA` no stdout, que a GUI lê enquanto roda. Nunca porcentagem inventada. `Status.Warning` avisa sobre pouco espaço livre (< 4 GiB) sob as Machines. +- **Erros da CLI são contrato (2026-09-30)**: códigos de saída 0 ok, 1 falha, 2 entrada inválida, 3 não encontrado, 4 nome em uso, 5 indisponível, 6 ocupado (`cmd/omavm/errors.go`); `exec`/`ssh` repassam o código do comando; com `--json`, `{"error": {"code", "message"}}` no stdout. Nunca renumerar; erros de uso da linha de comando usam `usagef`. - OmaVM deve ser controlável por humanos e por agentes: criar environments, executar comandos, consultar status, capturar logs, destruir ambientes, criar ambientes efêmeros, testar software em sistema limpo — tudo isso deve ter caminho programático (CLI/Core), nunca só via GUI. ## Open Technical Decisions diff --git a/Makefile b/Makefile index b9bc40d..4597a58 100644 --- a/Makefile +++ b/Makefile @@ -100,6 +100,9 @@ install: build install-quickshell-plugin install -Dm755 bin/omavm $(PREFIX)/bin/omavm install -Dm755 bin/omavm-gui $(PREFIX)/bin/omavm-gui install -Dm644 data/dev.omavm.app.desktop $(PREFIX)/share/applications/dev.omavm.app.desktop + @# The launcher may not have $(PREFIX)/bin on its PATH: point the + @# entry at the installed binary itself. + sed -i 's|^Exec=omavm-gui$$|Exec=$(PREFIX)/bin/omavm-gui|' $(PREFIX)/share/applications/dev.omavm.app.desktop install -Dm644 data/icons/dev.omavm.app.svg $(PREFIX)/share/icons/hicolor/scalable/apps/dev.omavm.app.svg @# One icon per environment color, for launcher entries and the file @# manager (internal/desktop's ColorIcon). diff --git a/README.md b/README.md index 05bae4a..e2ed2b6 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,18 @@ guest's login protects it. Turn it off per Machine with Machines expose the folder to the guest as the virtiofs tag `omavm-share`; inside a Linux guest, mount it with `mount -t virtiofs omavm-share /mnt/omavm-share`. +The shared clipboard can be limited to one way (Settings, or +`omavm settings NAME --clipboard-direction to-host|to-guest|both`): for +example, a guest that may hand text to you but must never see what you +copy. It applies the next time the Machine's window opens. + +A Machine's Settings ("Working with the guest") and `omavm integration NAME` +say, for the clipboard and the shared folder, whether each one works, as +checked on the guest side, or what is missing: `spice-vdagent` for the +clipboard, the mount above for the folder (checked through +`qemu-guest-agent`), or a restart. A setting being on is never reported as +working by itself. + `list` and `status` accept `--json` (in any position, e.g. both `omavm list --json` and `omavm status radic --json` work) for structured output aimed at agents, scripts, and the Quickshell bar @@ -227,6 +239,28 @@ call, asking the container engine once for all Boxes; the GUI refreshes with it. The JSON shapes are covered by golden files in `cmd/omavm/testdata`: changing them is a deliberate, visible diff. +### Exit codes + +A failed command says what to do next through its exit code, so scripts +and agents don't have to parse the message: + +| Code | Meaning | What the caller should do | +|---|---|---| +| 0 | success | — | +| 1 | the system or a backend failed | look at the message; retrying may help | +| 2 | invalid request (arguments, name, values out of range) | fix the request | +| 3 | no environment by that name | create it, or check `omavm list` | +| 4 | an environment by that name already exists | pick another name | +| 5 | not available for this kind of environment or on this computer | don't retry | +| 6 | another operation on that environment is running | wait and retry | + +`omavm exec` and `omavm ssh` exit with the code of the command they ran +(`omavm exec box -- go test ./...` fails the way `go test` did); codes +2–6 still mean omavm itself refused. With `--json`, a failure also prints +`{"error": {"code": "not_found", "message": "…"}}` on stdout; `code` is one +of `failed`, `invalid_input`, `not_found`, `already_exists`, `unsupported`, +`busy`. The message stays on stderr as well. + ## Machines Every Machine has a 1 TiB virtual disk. It is a sparse qcow2 file: it @@ -242,6 +276,29 @@ has; if your disk fills up, the Machine is paused (its card says why) and An installed Machine whose ISO was deleted or moved still starts, from its disk. +`omavm run --ephemeral --image path/to/system.iso` goes further: it +creates a new Desktop, runs it without keeping changes, shows its screen +(`--no-open` for scripts and agents), and deletes it when it shuts down. +Ctrl+C ends and deletes it at once. Nothing is added to the app launcher. + +**Clone…** (or `omavm clone NAME NEW_NAME`) makes a full, independent copy +of a stopped environment: a Desktop's whole disk with its snapshots (it +needs as much free space as that disk uses; on btrfs the copy shares space +until one side changes), or a Box's system (its home folder is shared with +your computer, not copied). A Box's **Update System** (or +`omavm update NAME`) runs `distrobox upgrade`, showing the package +manager's progress on its card. + +**Start Without Keeping Changes** (in the card's menu, or +`omavm start NAME --ephemeral`) runs a session whose disk writes are thrown +away when the Machine shuts down: try an installer, reproduce a bug on a +clean system, or let an agent loose, and get the Machine back exactly as it +was. The card says so while it runs. Restart keeps the session that way; +snapshots can't be taken or deleted until it shuts down, because they +would land in the throwaway disk. The session's writes are kept in a +temporary file next to the Machine's disk, so a long session can fill it +like any other write (the Machine then pauses and says why). + Machines try the installed disk before the ISO, falling back to installation media while the disk is not bootable. After installation, enable **Installation finished — disconnect ISO on next start** in Settings. Shut down and start the @@ -350,11 +407,27 @@ way. make run-gui ``` +Only one Experience Center runs per session: launching it again (from the +launcher, or **Open OmaVM** in a viewer) brings the open one forward. + Environments appear as cards (name, kind, image, status) with Start, Open, Stop and Delete actions — no backend/infrastructure detail is exposed. Creating one starts with a choice between **Desktop** (Machine) and **Development Box** (Box). Then select a local x86_64 installation ISO for a Machine, or a Linux distribution or custom container image for a Box. +While a Box's image downloads, its card shows which layer it is on (the +container engine reports layers, not bytes, so there is no percentage); +`omavm create` shows the same stages in a terminal, and `--progress` +prints them as `progress: STAGE` lines on stdout for programs. + +A running Machine's card says when saved settings (processors, memory, +SSH, the shared folder, installation media) wait for a restart, and when +Travel Mode started it with fewer processors because the computer was on +battery; `omavm status` shows the same. + +A Machine's card warns when the disk holding OmaVM's state has less than +4 GiB free (`omavm status` too): its disk grows as the guest writes, and +the Machine pauses if the space runs out. Install the `omavm` CLI binary alongside `omavm-gui` (same directory or on `PATH`) so a Box's "Open" can attach an interactive shell. Opening a @@ -365,7 +438,12 @@ parser covering cursor addressing, SGR colors including 256-color and truecolor, the alternate screen buffer used by vim/htop/less/tmux, and scrollback), not an external terminal emulator. It shares the same `dev.omavm.viewer` app id as the Machine display viewer below, so the same -optional Hyprland window rule covers both. +optional Hyprland window rule covers both. Like Alacritty, Shift+PageUp/ +PageDown/Home/End scroll back through the output, and Ctrl+=, Ctrl+- and +Ctrl+0 (or Ctrl+wheel) change the font size, which is remembered. A Box +with a color tag shows +it as a thin strip along the top of its terminal, so you can tell which +Box you're in, and that you aren't on the host. A running Machine's card shows a live screenshot of its display (captured via QEMU's QMP `screendump`, refreshed on every action or diff --git a/cmd/omavm/errors.go b/cmd/omavm/errors.go new file mode 100644 index 0000000..9e05e83 --- /dev/null +++ b/cmd/omavm/errors.go @@ -0,0 +1,98 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os/exec" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// Exit codes are a contract with scripts and agents: they say what the +// caller should do next without parsing the message. Documented in the +// README ("Exit codes"); never renumber one. +const ( + exitFailure = 1 // the system or a backend failed; retrying may help + exitUsage = 2 // invalid request: fix the arguments + exitNotFound = 3 // no environment by that name + exitExists = 4 // the name is taken + exitUnsupported = 5 // not available for this kind of environment or host + exitBusy = 6 // another operation on the environment is running +) + +// usageError marks a malformed command line, as opposed to a request the +// Core rejected. +type usageError struct{ err error } + +func (e usageError) Error() string { return e.err.Error() } +func (e usageError) Unwrap() error { return e.err } + +func usagef(format string, args ...any) error { + return usageError{fmt.Errorf(format, args...)} +} + +// errorClass maps an error to its exit code and a stable snake_case code +// for --json output. +func errorClass(err error) (int, string) { + var usage usageError + switch { + case errors.As(err, &usage), errors.Is(err, core.ErrInvalidInput): + return exitUsage, "invalid_input" + case errors.Is(err, core.ErrNotFound), errors.Is(err, core.ErrSnapshotGone): + return exitNotFound, "not_found" + case errors.Is(err, core.ErrAlreadyExists): + return exitExists, "already_exists" + case errors.Is(err, core.ErrUnsupported): + return exitUnsupported, "unsupported" + case errors.Is(err, core.ErrBusy): + return exitBusy, "busy" + } + var kind *core.InvalidKindError + if errors.As(err, &kind) { + return exitUsage, "invalid_input" + } + return exitFailure, "failed" +} + +// exitCodeFor is the process exit code for a failed command. exec and ssh +// pass the remote command's own code through, like ssh and docker exec +// do: `omavm exec box -- go test ./...` must fail the way go test failed. +func exitCodeFor(cmd string, err error) int { + var exitErr *exec.ExitError + if (cmd == "exec" || cmd == "ssh") && errors.As(err, &exitErr) && exitErr.ExitCode() > 0 { + return exitErr.ExitCode() + } + code, _ := errorClass(err) + return code +} + +// writeJSONError reports a failure on stdout for a caller that asked for +// --json: {"error": {"code": "not_found", "message": "..."}}. +func writeJSONError(w io.Writer, err error) { + _, code := errorClass(err) + var body struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + body.Error.Code = code + body.Error.Message = err.Error() + _ = json.NewEncoder(w).Encode(body) +} + +// wantsJSON reports whether a command line asked for --json output. What +// follows "--" belongs to the command run by exec/ssh, not to omavm. +func wantsJSON(args []string) bool { + for _, a := range args { + if a == "--" { + return false + } + if a == "--json" || a == "--json=true" { + return true + } + } + return false +} diff --git a/cmd/omavm/errors_test.go b/cmd/omavm/errors_test.go new file mode 100644 index 0000000..fa19506 --- /dev/null +++ b/cmd/omavm/errors_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os/exec" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestErrorClassesHaveStableExitCodes(t *testing.T) { + tests := []struct { + err error + wantExit int + wantCode string + }{ + {errors.New("qemu crashed"), 1, "failed"}, + {usagef("status: expected exactly one environment name"), 2, "invalid_input"}, + {core.Invalidf("name must not contain /"), 2, "invalid_input"}, + {&core.InvalidKindError{Value: "vm"}, 2, "invalid_input"}, + {fmt.Errorf("start x: %w", core.ErrNotFound), 3, "not_found"}, + {core.ErrAlreadyExists, 4, "already_exists"}, + {core.Unsupportedf("x is a Box"), 5, "unsupported"}, + {core.Busyf("x is being created"), 6, "busy"}, + } + for _, tt := range tests { + exit, code := errorClass(tt.err) + if exit != tt.wantExit || code != tt.wantCode { + t.Errorf("errorClass(%v) = %d, %q; want %d, %q", tt.err, exit, code, tt.wantExit, tt.wantCode) + } + } +} + +func TestUsageErrorsFromRunAreInvalidInput(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + for _, args := range [][]string{ + {"frobnicate"}, + {"status"}, + {"create", "--kind", "box"}, + {"create", "--name", "x", "--bogus"}, + {"snapshot", "create", "vm", "--label"}, + } { + if exit, _ := errorClass(run(args)); exit != exitUsage { + t.Errorf("run(%q) exit = %d, want %d", args, exit, exitUsage) + } + } + if exit, _ := errorClass(run([]string{"status", "nothing-here"})); exit != exitNotFound { + t.Errorf("status of a missing environment exit = %d, want %d", exit, exitNotFound) + } +} + +func TestExecPassesTheCommandExitCodeThrough(t *testing.T) { + err := exec.Command("sh", "-c", "exit 7").Run() + wrapped := fmt.Errorf("exec box: %w", err) + if got := exitCodeFor("exec", wrapped); got != 7 { + t.Fatalf("exec exit = %d, want 7", got) + } + // Elsewhere a failing helper is just a failure of omavm. + if got := exitCodeFor("start", wrapped); got != exitFailure { + t.Fatalf("start exit = %d, want %d", got, exitFailure) + } +} + +func TestJSONErrorShape(t *testing.T) { + var buf bytes.Buffer + writeJSONError(&buf, fmt.Errorf("status x: %w", core.ErrNotFound)) + var got map[string]map[string]string + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got["error"]["code"] != "not_found" || got["error"]["message"] != "status x: environment not found" { + t.Fatalf("unexpected JSON error: %s", buf.String()) + } +} + +func TestWantsJSONIgnoresTheExecutedCommand(t *testing.T) { + if !wantsJSON([]string{"status", "x", "--json"}) { + t.Error("--json after the name not seen") + } + if wantsJSON([]string{"exec", "x", "--", "tool", "--json"}) { + t.Error("--json of the command run by exec taken as omavm's") + } +} diff --git a/cmd/omavm/main.go b/cmd/omavm/main.go index 90c2c77..844a47e 100644 --- a/cmd/omavm/main.go +++ b/cmd/omavm/main.go @@ -12,7 +12,10 @@ import ( "log/slog" "os" "os/exec" + "os/signal" "strings" + "syscall" + "time" "github.com/KitsuneSemCalda/OmaVM/internal/applog" "github.com/KitsuneSemCalda/OmaVM/internal/backend/box" @@ -33,13 +36,21 @@ func main() { defer closeLog() } - if err := run(os.Args[1:]); err != nil { + args := os.Args[1:] + if err := run(args); err != nil { slog.Error("command failed", "error", err) fmt.Fprintln(os.Stderr, "omavm:", err) + cmd := "" + if len(args) > 0 { + cmd = args[0] + } + if wantsJSON(args) { + writeJSONError(os.Stdout, err) + } if os.Getenv("OMAVM_NOTIFY_ERRORS") == "1" { notifyError(err) } - os.Exit(1) + os.Exit(exitCodeFor(cmd, err)) } } @@ -57,7 +68,7 @@ func notifyError(err error) { func run(args []string) error { if len(args) == 0 { printUsage() - return errors.New("no command given") + return usagef("no command given") } qemuBackend, err := qemu.New() @@ -98,6 +109,10 @@ func run(args []string) error { case "create": return cmdCreate(ctx, svc, rest) case "start": + rest, ephemeral := extractBoolFlag(rest, "ephemeral") + if ephemeral { + return cmdSimple(ctx, rest, "start", svc.StartEphemeral) + } return cmdSimple(ctx, rest, "start", svc.Start) case "open": return cmdSimple(ctx, rest, "open", svc.Open) @@ -129,6 +144,13 @@ func run(args []string) error { return cmdExec(ctx, svc, rest) case "ssh": return cmdSSH(ctx, svc, rest) + case "clone": + return cmdClone(ctx, svc, rest) + case "run": + return cmdRun(ctx, svc, rest) + case "update", "upgrade": + rest, progress := extractBoolFlag(rest, "progress") + return cmdSimple(withProgress(ctx, progress), rest, "update", svc.Update) case "rm", "remove": return cmdSimple(ctx, rest, "remove", svc.Remove) case "list", "ls": @@ -138,7 +160,7 @@ func run(args []string) error { return nil default: printUsage() - return fmt.Errorf("unknown command %q", cmd) + return usagef("unknown command %q", cmd) } } @@ -149,11 +171,14 @@ func cmdCreate(ctx context.Context, svc *core.Service, args []string) error { image := fs.String("image", "", "distro image (Box) or boot ISO path (Machine)") cpus := fs.Int("cpus", 0, "virtual CPUs (Machines only, defaults to 2)") memory := fs.Int("memory-mib", 0, "memory in MiB (Machines only, defaults to 2048)") + progress := fs.Bool("progress", false, `print each stage of a long creation on stdout as "progress: STAGE"`) if err := fs.Parse(args); err != nil { - return err + return usageError{err} } + // Stages of a long creation (a Box's image download). + ctx = withProgress(ctx, *progress) if *name == "" { - return errors.New("create: --name is required") + return usagef("create: --name is required") } kind, err := core.ParseEnvironmentKind(*kindStr) if err != nil { @@ -176,9 +201,74 @@ func cmdCreate(ctx context.Context, svc *core.Service, args []string) error { return nil } +// cmdRun: omavm run --ephemeral --image ISO [--name NAME] [--cpus N] +// [--memory-mib N] [--no-open]. Waits for the Machine to shut down, then +// deletes it; Ctrl+C ends it at once. +func cmdRun(ctx context.Context, svc *core.Service, args []string) error { + fs := flag.NewFlagSet("run", flag.ContinueOnError) + ephemeral := fs.Bool("ephemeral", false, "delete the environment when it shuts down (required)") + image := fs.String("image", "", "installation ISO to boot (Desktops)") + name := fs.String("name", "", "name while it runs (default: ephemeral-XXXXXX)") + cpus := fs.Int("cpus", 0, "virtual CPUs (defaults to 2)") + memory := fs.Int("memory-mib", 0, "memory in MiB (defaults to 2048)") + noOpen := fs.Bool("no-open", false, "don't open its display (for scripts and agents)") + if err := fs.Parse(args); err != nil { + return usageError{err} + } + if !*ephemeral { + return usagef("run: only --ephemeral is supported: omavm run --ephemeral --image path/to/system.iso") + } + if fs.NArg() != 0 { + return usagef("run: unexpected arguments %q", fs.Args()) + } + ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) + defer stop() + env := core.Environment{Name: *name, Kind: core.Machine, Image: *image, + Settings: core.EnvironmentSettings{CPUs: *cpus, MemoryMiB: *memory}} + fmt.Fprintln(os.Stderr, "omavm: running without keeping anything; it is deleted when it shuts down (Ctrl+C ends it now)") + created, err := svc.RunEphemeral(ctx, env, !*noOpen, time.Second) + if errors.Is(err, context.Canceled) { + fmt.Printf("ended and deleted %s\n", created.Name) + return nil + } + if err != nil { + return err + } + fmt.Printf("%s shut down and was deleted\n", created.Name) + return nil +} + +// cmdClone: omavm clone NAME NEW_NAME [--progress] +func cmdClone(ctx context.Context, svc *core.Service, args []string) error { + args, progress := extractBoolFlag(args, "progress") + if len(args) != 2 { + return usagef("clone: usage: omavm clone ") + } + ctx = withProgress(ctx, progress) + clone, err := svc.Clone(ctx, args[0], args[1]) + if err != nil { + return err + } + fmt.Printf("cloned %s as %s\n", args[0], clone.Name) + return nil +} + +// withProgress reports the stages of a long operation: on stdout as +// "progress: STAGE" for a program that asked (the GUI), on a terminal for +// a person. Never on a piped stderr, which callers read as the error text. +func withProgress(ctx context.Context, toStdout bool) context.Context { + if toStdout { + return core.WithProgress(ctx, func(stage string) { fmt.Println("progress:", stage) }) + } + if info, err := os.Stderr.Stat(); err == nil && info.Mode()&os.ModeCharDevice != 0 { + return core.WithProgress(ctx, func(stage string) { fmt.Fprintf(os.Stderr, "omavm: %s…\n", stage) }) + } + return ctx +} + func cmdSimple(ctx context.Context, args []string, verb string, fn func(context.Context, string) error) error { if len(args) != 1 { - return fmt.Errorf("%s: expected exactly one environment name", verb) + return usagef("%s: expected exactly one environment name", verb) } return fn(ctx, args[0]) } @@ -190,7 +280,7 @@ func cmdStatus(ctx context.Context, svc *core.Service, args []string) error { // would silently swallow a trailing --json instead of honoring it. args, jsonOut := extractBoolFlag(args, "json") if len(args) != 1 { - return errors.New("status: expected exactly one environment name") + return usagef("status: expected exactly one environment name") } status, err := svc.Status(ctx, args[0]) @@ -205,12 +295,24 @@ func cmdStatus(ctx context.Context, svc *core.Service, args []string) error { } else { fmt.Println(status.State) } + if status.Ephemeral { + fmt.Println("changes in this session are discarded when it shuts down") + } + if status.Warning != "" { + fmt.Println("warning:", status.Warning) + } + if status.TravelMode { + fmt.Println("travel mode: started with fewer CPUs because this computer was on battery") + } + if status.RestartNeeded { + fmt.Println("restart to apply the saved settings") + } return nil } func cmdPreview(ctx context.Context, svc *core.Service, args []string) error { if len(args) != 1 { - return errors.New("preview: expected exactly one environment name") + return usagef("preview: expected exactly one environment name") } path, err := svc.Preview(ctx, args[0]) if err != nil { @@ -222,7 +324,7 @@ func cmdPreview(ctx context.Context, svc *core.Service, args []string) error { func cmdSnapshot(ctx context.Context, svc *core.Service, args []string) error { if len(args) == 0 { - return errors.New("snapshot: expected a subcommand (create, list, go-to, remove)") + return usagef("snapshot: expected a subcommand (create, list, go-to, remove)") } sub, rest := args[0], args[1:] switch sub { @@ -235,7 +337,7 @@ func cmdSnapshot(ctx context.Context, svc *core.Service, args []string) error { return fmt.Errorf("snapshot create: %w", err) } if len(rest) != 1 { - return errors.New("snapshot create: expected exactly one environment name") + return usagef("snapshot create: expected exactly one environment name") } snap, err := svc.CreateSnapshot(ctx, rest[0], label) if err != nil { @@ -246,7 +348,7 @@ func cmdSnapshot(ctx context.Context, svc *core.Service, args []string) error { case "list": rest, jsonOut := extractBoolFlag(rest, "json") if len(rest) != 1 { - return errors.New("snapshot list: expected exactly one environment name") + return usagef("snapshot list: expected exactly one environment name") } snapshots, err := svc.ListSnapshots(ctx, rest[0]) if err != nil { @@ -268,16 +370,16 @@ func cmdSnapshot(ctx context.Context, svc *core.Service, args []string) error { return nil case "go-to": if len(rest) != 2 { - return errors.New("snapshot go-to: usage: omavm snapshot go-to ") + return usagef("snapshot go-to: usage: omavm snapshot go-to ") } return svc.GoToSnapshot(ctx, rest[0], rest[1]) case "remove", "rm": if len(rest) != 2 { - return errors.New("snapshot remove: usage: omavm snapshot remove ") + return usagef("snapshot remove: usage: omavm snapshot remove ") } return svc.RemoveSnapshot(ctx, rest[0], rest[1]) default: - return fmt.Errorf("snapshot: unknown subcommand %q", sub) + return usagef("snapshot: unknown subcommand %q", sub) } } @@ -292,12 +394,12 @@ func cmdApps(ctx context.Context, svc *core.Service, args []string) error { return fmt.Errorf("apps: %w", err) } if len(args) != 1 { - return errors.New("apps: expected exactly one environment name") + return usagef("apps: expected exactly one environment name") } name := args[0] if exportID != "" && unexportID != "" { - return errors.New("apps: choose only one of --export or --unexport") + return usagef("apps: choose only one of --export or --unexport") } if exportID != "" { return svc.ExportApp(ctx, name, exportID) @@ -333,7 +435,7 @@ func cmdApps(ctx context.Context, svc *core.Service, args []string) error { func cmdIntegration(ctx context.Context, svc *core.Service, args []string) error { args, jsonOut := extractBoolFlag(args, "json") if len(args) != 1 { - return errors.New("integration: expected exactly one environment name") + return usagef("integration: expected exactly one environment name") } report, err := svc.Integration(ctx, args[0]) if err != nil { @@ -347,13 +449,19 @@ func cmdIntegration(ctx context.Context, svc *core.Service, args []string) error fmt.Printf(" (%s)", report.Hint) } fmt.Println() + for _, c := range report.Capabilities { + fmt.Printf("%s: %s\n", strings.ToLower(c.Label), strings.ReplaceAll(c.State, "_", " ")) + if c.Hint != "" { + fmt.Printf(" %s\n", c.Hint) + } + } return nil } func cmdHost(ctx context.Context, svc *core.Service, args []string) error { args, jsonOut := extractBoolFlag(args, "json") if len(args) != 0 { - return errors.New("host: takes no arguments") + return usagef("host: takes no arguments") } caps, err := svc.InspectHost(ctx) if err != nil { @@ -377,7 +485,7 @@ func cmdHost(ctx context.Context, svc *core.Service, args []string) error { func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { if len(args) == 0 { - return errors.New("settings: expected an environment name") + return usagef("settings: expected an environment name") } name := args[0] fs := flag.NewFlagSet("settings", flag.ContinueOnError) @@ -391,6 +499,7 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { snapshotLimit := fs.Int("snapshot-limit", 0, "max snapshots to keep, oldest discarded first (1-100)") color := fs.String("color", "", "tag color: "+strings.Join(core.EnvironmentColors, ", ")) shareClipboard := fs.Bool("share-clipboard", false, "share the text clipboard with a Machine's guest, or let programs in a Box's terminal copy to it (on by default)") + clipboardDirection := fs.String("clipboard-direction", "", "limit the shared clipboard to one way: both, to-host or to-guest (Machines only)") travelMode := fs.Bool("travel-mode", false, "use half the CPUs automatically while the host is on battery (on by default)") vulkan := fs.Bool("vulkan", false, "Vulkan acceleration when the host supports it (Machines only, on by default)") ssh := fs.Bool("ssh", false, "reach the Machine with omavm ssh/exec over a local channel any program on this computer can use, Boxes included (Machines only, on by default)") @@ -399,10 +508,10 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { fullscreen := fs.Bool("fullscreen", false, "open the Machine's display fullscreen (Machines only, on by default)") jsonOut := fs.Bool("json", false, "print JSON") if err := fs.Parse(args[1:]); err != nil { - return err + return usageError{err} } if fs.NArg() != 0 { - return errors.New("settings: unexpected positional arguments") + return usagef("settings: unexpected positional arguments") } patch := core.SettingsPatch{} changed := false @@ -430,6 +539,9 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { case "share-clipboard": patch.ShareClipboard = shareClipboard changed = true + case "clipboard-direction": + patch.ClipboardDirection = clipboardDirection + changed = true case "vulkan": patch.Vulkan = vulkan changed = true @@ -463,7 +575,7 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { } }) if modeFlags > 1 { - return errors.New("settings: choose only one of --shared-read-only or --shared-writable") + return usagef("settings: choose only one of --shared-read-only or --shared-writable") } var settings core.EnvironmentSettings var err error @@ -488,7 +600,16 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { fmt.Printf("open the display fullscreen: %t\n", !settings.FullscreenDisabled) fmt.Printf("ssh (reachable by any program on this computer, Boxes included): %t\n", !settings.SSHDisabled) } - fmt.Printf("share clipboard: %t\n", !settings.ClipboardDisabled) + switch { + case settings.ClipboardDisabled: + fmt.Println("share clipboard: false") + case settings.ClipboardDirection == core.ClipboardToHost: + fmt.Println("share clipboard: only from the environment to this computer") + case settings.ClipboardDirection == core.ClipboardToGuest: + fmt.Println("share clipboard: only from this computer to the environment") + default: + fmt.Println("share clipboard: true (both ways)") + } fmt.Printf("travel mode (reduce CPUs on battery): %t\n", !settings.TravelModeDisabled) fmt.Printf("show in the app launcher: %t\n", !settings.LauncherDisabled) if settings.SharedPath != "" { @@ -507,7 +628,7 @@ func cmdSettings(ctx context.Context, svc *core.Service, args []string) error { func cmdExec(ctx context.Context, svc *core.Service, args []string) error { if len(args) < 2 { - return errors.New("exec: usage: omavm exec -- [args...]") + return usagef("exec: usage: omavm exec -- [args...]") } name := args[0] rest := args[1:] @@ -515,7 +636,7 @@ func cmdExec(ctx context.Context, svc *core.Service, args []string) error { rest = rest[1:] } if len(rest) == 0 { - return errors.New("exec: no command given") + return usagef("exec: no command given") } return svc.Exec(ctx, name, rest) } @@ -537,15 +658,15 @@ func cmdSSH(ctx context.Context, svc *core.Service, args []string) error { name, args = args[0], args[1:] } if err := fs.Parse(args); err != nil { - return err + return usageError{err} } if name == "" && fs.NArg() == 1 { name = fs.Arg(0) } else if fs.NArg() != 0 { - return errors.New("ssh: usage: omavm ssh [--user LOGIN] [-- command...]") + return usagef("ssh: usage: omavm ssh [--user LOGIN] [-- command...]") } if name == "" { - return errors.New("ssh: expected a Machine name") + return usagef("ssh: expected a Machine name") } return svc.SSH(ctx, name, *login, command) } @@ -630,7 +751,7 @@ func extractValueFlag(args []string, name string) ([]string, string, error) { } if a == prefix { if i+1 >= len(args) { - return nil, "", fmt.Errorf("%s requires a value", prefix) + return nil, "", usagef("%s requires a value", prefix) } value = args[i+1] i++ @@ -667,8 +788,10 @@ func printUsage() { commands: create --name NAME --kind box|machine --image IMAGE create an environment (a Box needs a - container image, a Machine an ISO) - start NAME start an environment + [--progress] container image, a Machine an ISO); + --progress prints "progress: STAGE" lines + start NAME [--ephemeral] start an environment; --ephemeral (Machines + only) discards this session's changes at shutdown open NAME start (if needed) and attach stop NAME stop an environment restart NAME restart a Machine @@ -680,6 +803,7 @@ commands: host [--json] show what this computer offers Machines settings NAME [--description TEXT] [--cpus N] [--color C] view or change settings [--share-clipboard=BOOL] [--travel-mode=BOOL] (on by default) + [--clipboard-direction both|to-host|to-guest] one-way clipboard (Machines) [--vulkan=BOOL] [--ssh=BOOL] [--fullscreen=BOOL] (Machines only, on by default) [--launcher=BOOL] list in the app launcher (on by default) [--open-in-empty-workspace=BOOL] open in an empty workspace (on by default) @@ -694,6 +818,15 @@ commands: exec NAME -- CMD [ARGS...] run a command inside a Box, or a Machine over SSH ssh NAME [--user LOGIN] [-- CMD...] open a shell in a Machine (guest needs systemd 256+ and sshd; any program here can reach it, Boxes too) + run --ephemeral --image ISO [--name NAME] [--no-open] run a new Desktop that is deleted when it shuts + [--cpus N] [--memory-mib N] down (Ctrl+C ends and deletes it at once) + clone NAME NEW_NAME [--progress] copy a stopped environment: its disk with its + snapshots, or its container (needs that much space) + update NAME [--progress] update a Box's installed software (distrobox upgrade) rm NAME remove an environment - list [--status] [--json] list known environments, with their state`) + list [--status] [--json] list known environments, with their state + +exit codes: 0 ok, 1 failure, 2 invalid request, 3 not found, 4 name taken, +5 unsupported here, 6 busy; exec and ssh return their command's code. +With --json, failures also print {"error": {"code", "message"}} on stdout.`) } diff --git a/cmd/omavm/testdata/list-status.golden.json b/cmd/omavm/testdata/list-status.golden.json index ef46656..90bfe4a 100644 --- a/cmd/omavm/testdata/list-status.golden.json +++ b/cmd/omavm/testdata/list-status.golden.json @@ -1 +1 @@ -[{"id":"0123456789abcdef","name":"dev","image":"fedora:latest","backend":"distrobox","kind":"box","settings":{"color":"green","travel_mode_disabled":true},"status":{"state":"unknown","detail":"Development Boxes need Podman or Docker (install one with: sudo pacman -S podman)"}},{"id":"fedcba9876543210","name":"Desktop Fedora","image":"/isos/fedora.iso","backend":"qemu","kind":"machine","settings":{"description":"work","cpus":4,"memory_mib":4096},"snapshots":[{"id":"clean-install-1a2b3c4d","label":"Clean installation","created_at":"2026-09-27T12:00:00Z"}],"status":{"state":"stopped"},"integration":{"guest_agent":"stopped","hint":"Start the Machine to check guest tools"}}] +[{"id":"0123456789abcdef","name":"dev","image":"fedora:latest","backend":"distrobox","kind":"box","settings":{"color":"green","travel_mode_disabled":true},"status":{"state":"unknown","detail":"Development Boxes need Podman or Docker (install one with: sudo pacman -S podman)"}},{"id":"fedcba9876543210","name":"Desktop Fedora","image":"/isos/fedora.iso","backend":"qemu","kind":"machine","settings":{"description":"work","cpus":4,"memory_mib":4096},"snapshots":[{"id":"clean-install-1a2b3c4d","label":"Clean installation","created_at":"2026-09-27T12:00:00Z"}],"status":{"state":"stopped"},"integration":{"guest_agent":"stopped","hint":"Start the Machine to check guest tools","capabilities":[{"id":"clipboard","label":"Clipboard","state":"not_verified","hint":"Checked while the Machine is running"},{"id":"shared_folder","label":"Shared folder","state":"off","hint":"Choose a folder in Settings to share it"}]}}] diff --git a/contrib/dev.omavm.bar/OmaVM.qml b/contrib/dev.omavm.bar/OmaVM.qml index 96dee4d..264dbbb 100644 --- a/contrib/dev.omavm.bar/OmaVM.qml +++ b/contrib/dev.omavm.bar/OmaVM.qml @@ -93,18 +93,22 @@ BarWidget { tooltipText: "OmaVM — " + root.envCount + " environment" + (root.envCount === 1 ? "" : "s") + ", click to open" iconComponent: Component { Item { + // Same as the shell's own symbolic tray icons + // (/usr/share/omarchy/shell/plugins/bar/widgets/Tray.qml): a hidden + // image kept as a layer, so the effect has a texture to sample, and + // decoded at physical pixels for HiDPI. Image { id: glyphImage anchors.fill: parent source: Qt.resolvedUrl("icon.svg") - sourceSize.width: width * 2 - sourceSize.height: height * 2 + sourceSize.width: Math.round(Math.min(width, height) * Screen.devicePixelRatio) + sourceSize.height: Math.round(Math.min(width, height) * Screen.devicePixelRatio) fillMode: Image.PreserveAspectFit visible: false - asynchronous: true + layer.enabled: true } MultiEffect { - anchors.fill: parent + anchors.fill: glyphImage source: glyphImage colorization: 1 colorizationColor: button.active && button.useActiveColor ? button.activeColor : button.foreground diff --git a/data/dev.omavm.app.desktop b/data/dev.omavm.app.desktop index c22322a..69bb5ca 100644 --- a/data/dev.omavm.app.desktop +++ b/data/dev.omavm.app.desktop @@ -6,6 +6,6 @@ Comment=Create, run and manage Boxes and Machines on Omarchy Exec=omavm-gui Icon=dev.omavm.app Terminal=false -Categories=System;Emulator;Utility; +Categories=System;Emulator; StartupWMClass=dev.omavm.app StartupNotify=true diff --git a/docs/TODO.md b/docs/TODO.md index 8af5c61..74caf42 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -84,11 +84,14 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - **Bug real encontrado e corrigido (2026-09-27), mesma família do achado em "Explicar ajustes automáticos e pendentes" (P2), mas em Create em vez de Configure.** `CreateDialog.qml` sempre enviava `--cpus 2 --memory-mib 2048` (os valores padrão mostrados no passo de resumo) pra `backend.createEnvironment(...)`, mesmo quando o usuário nunca tocava nos `SpinBox` — então **toda Machine criada pela GUI nascia com CPU/memória fixados desde o início**, desligando o Travel Mode permanentemente desde a criação (não só depois de um Save em Settings). Corrigido com o mesmo padrão de "touched" via `SpinBox.onValueModified` já usado em `SettingsDialog.qml`: `CreateDialog.qml` ganhou `cpusTouched`/`memoryTouched`, e `Backend::createEnvironment` (`gui/backend.cpp`/`.h`) só inclui `--cpus`/`--memory-mib` quando de fato tocados. Confirmado via CLI real: `create --kind machine` sem essas flags agora deixa `settings: {}` no `environments.json` bruto (antes desse fix já ficava correto no CLI puro, já que o bug morava só na GUI sempre mandando as flags) — `settings --json` continua mostrando os valores efetivos (2/2048) pra exibição. - [ ] **Levar a criação até o primeiro uso.** Depois de criar, oferecer uma ação direta para abrir o terminal da Development Box ou iniciar e abrir o instalador da Machine. Manter o ambiente criado visível caso a abertura falhe, com erro e nova tentativa no card; evitar criar uma segunda cópia ao repetir a ação. - Aceite: uma pessoa conclui criação → primeiro terminal/instalador sem procurar uma ação no gerenciador; cancelar ou fechar a sugestão deixa o ambiente criado e utilizável depois. Medir os passos e o tempo até o primeiro uso nas duas jornadas, inclusive durante o pull de uma imagem de Box; aproveitar a proposta de [progresso ao criar Box](ideias/progresso-ao-criar-box.md) sem porcentagem fictícia. + - Implementado (2026-10-01): ao terminar a criação, o `CreateDialog` emite `created(nome, tipo)` e a janela pergunta ““nome” is ready”, com **Open Terminal** (Box) ou **Start Installer** (Machine, lembrando de desconectar a mídia depois) e **Later**. Fechar deixa o card pronto; um segundo clique enquanto o primeiro roda é recusado por `backend.open` (`busyEnvironments`), então não abre uma segunda cópia. O progresso do pull da Box aparece no card durante a criação (ver a triagem). Teste: `test_successfulCreationIsAnnounced`. Falta medir passos e tempo até o primeiro uso numa sessão real. - [ ] **Fazer o verbo da ação principal corresponder ao resultado.** Hoje o card parado mostra "Start", mas chama `Backend::open`, que inicia e abre o ambiente. Escolher um rótulo que comunique o resultado para cada estado e tipo, mantendo "iniciar sem abrir" como ação separada somente se houver caso de uso visível. - Aceite: a pessoa prevê se verá terminal/instalador/viewer após o clique; rótulo, nome acessível, tooltip e menu concordam entre si em estados parado, rodando e pausado. Validar também abertura pelo launcher e cliques repetidos. + - Implementado (2026-10-01): Box parada → **Open** (inicia e abre o terminal); Desktop parado → **Start** (inicia e mostra a tela); rodando → **Open**; pausado → **Resume**. Uma dica (tooltip e `Accessible.description`) diz o resultado (“Start demo and show its screen”), e o primeiro item do menu usa o mesmo rótulo. Não há ação separada de “iniciar sem abrir”, porque não apareceu um caso de uso visível (a CLI tem `omavm start`). Teste: `test_primaryActionNamesTheResult`. Falta validar o launcher e cliques repetidos numa sessão real. - [ ] **Tornar pré-requisitos e recursos compreensíveis.** Verificar disponibilidade necessária ao fluxo, memória e espaço; oferecer instrução contextual quando algo impedir a criação. - Aceite: falhas previsíveis são explicadas antes da operação longa; não apresentar porcentagens ou estimativas fictícias. - Implementado parcialmente (2026-09-27): binário ausente de `qemu-img`/`qemu-system-x86_64` agora falha com a mesma dica acionável que `virtiofsd` já tinha ("install it with: sudo pacman -S qemu-desktop"), em vez do erro cru do Go (achado já registrado na auditoria QEMU, ver abaixo). `distrobox` ausente já tinha diagnóstico equivalente antes desta sessão. Faixa de CPU/memória inválida também falha antes de qualquer chamada ao backend (ver item de resumo acima). Ainda faltam: checagem de espaço em disco/memória do host e de acesso a `/dev/kvm` antes da operação (o próprio QEMU recusa e o stderr chega ao usuário, mas não é antecipado). Teste de regressão: `TestMissingBinaryDiagnostic` em `internal/backend/qemu/lifecycle_test.go`. + - Continuação (2026-10-01): **KVM antes da operação**: o diálogo de criação consulta `omavm host --json` (`Backend::refreshHost`, sem estado de ocupado) e, se o KVM não está acessível, a opção Desktop diz que este computador ainda não inicia Desktops, com a instrução de correção do próprio diagnóstico (também na descrição acessível). Não bloqueia a criação: a pessoa pode corrigir depois. No `Start`, se o QEMU falha sem `/dev/kvm` acessível, o erro cru ("Could not access KVM kernel module") vira uma instrução (firmware, grupo `kvm`, novo login), classificado como indisponível (código 5); a checagem só acontece depois de uma falha, para não barrar testes nem hosts com o QEMU falso. **Espaço**: aviso abaixo de 4 GiB livres no card (ver a triagem). Testes: `TestStartWithoutKVMSaysHowToFixIt`, `test_missingKVMIsSaidBeforeCreating`. Falta: memória do host antes do Start (o QEMU aloca sob demanda, então um limite fixo erraria). - [ ] **Fechar o ciclo da instalação.** Explicar quando abrir o instalador, como voltar ao gerenciador e como desconectar a ISO após instalar. Após o desligamento da Machine, apresentar a próxima ação no contexto da mídia de instalação; não presumir que o guest terminou a instalação só porque desligou. - Aceite: criar → instalar → desligar → desconectar ISO → iniciar pelo disco é possível pela GUI, sem a pessoa precisar lembrar uma instrução lida antes da criação. A escolha de manter ou desconectar a ISO é explícita e reversível; testar instalação concluída, instalador interrompido e falha de boot pelo disco. - Implementado parcialmente (2026-09-27): o passo de resumo do `CreateDialog.qml` agora explica o ciclo completo ("iniciar abre o instalador a partir da ISO; depois de instalar, desligue e desconecte a mídia em Settings antes de iniciar pelo disco") antes mesmo da criação — o mecanismo (`--disconnect-iso` em Settings) já existia e não mudou. Falta validar a jornada completa criada→instalada→desconectada→iniciada pelo disco numa sessão real. @@ -121,15 +124,19 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - [ ] **Validar instalação e entrada pelo desktop.** Conferir `make install`, entrada `.desktop`, resolução do ícone e abertura do app pelo launcher em uma sessão Omarchy com o PATH de usuário documentado. - Aceite: OmaVM aparece com nome e ícone corretos no launcher e nas superfícies do shell que exibem ícones; abre sem terminal no host e identifica corretamente sua janela. Registrar separadamente o comportamento ao executar da árvore de fontes sem instalação. - Base: `Makefile`, `data/dev.omavm.app.desktop`, `data/icons/dev.omavm.app.svg`, `gui/main.cpp`. + - Conferido (2026-10-01), sem tocar no sistema: `make install PREFIX= QS_PLUGIN_DIR=` instala os dois binários, a entrada, o ícone em `hicolor/scalable/apps`, os ícones de cor em `share/omavm/icons` e o plugin (só copiado, nunca habilitado). O `desktop-file-validate` apontou `Categories=System;Emulator;Utility;` com duas categorias principais (o app poderia aparecer duas vezes no menu), corrigido para `System;Emulator;`. `Exec=omavm-gui` dependia do `PATH` da sessão gráfica, que aqui inclui `~/.local/bin` mas não precisa incluir para outro `PREFIX`: o `make install` agora grava o caminho absoluto do binário instalado, e o PKGBUILD continua copiando a entrada para `/usr`, onde o nome curto basta. A entrada instalada valida sem avisos. A GUI acha a CLI ao lado dela (`cliPath`) antes do `PATH`. Executando da árvore de fontes, sem instalar, não existe `dev.omavm.app.desktop` nem o ícone no tema, então o shell não tem ícone para a janela (`QIcon::fromTheme` sem resultado). **Não verificado**: abrir pelo launcher e ver nome e ícone numa sessão real. - [ ] **Unificar a identidade do widget com o aplicativo.** Substituir o glifo `▣` pelo ícone oficial ou uma variante monocromática derivada dele, conforme os recursos e convenções do componente da barra. Preservar tamanho, contraste e nome acessível. - Aceite: ícone legível em temas claro/escuro e escalas de P1, sem dependência de glifo de fonte; clique abre o Experience Center, tooltip informa a contagem e atualização acompanha criação/remoção no intervalo configurado. Validar zero ambientes e falha da CLI, sem apresentar falha como contagem confiável. - Base: `contrib/dev.omavm.bar/`; manter habilitação manual e explicar como carregar alterações segundo o ciclo de vida do shell. - Implementado parcialmente: widget e GUI usam SVGs com cores do tema. Falta validar o widget no Quickshell, temas, escalas e estados de erro; manter habilitação manual. + - Ajuste (2026-10-01): o tingimento do ícone na barra usa `MultiEffect` com `colorization`, o mesmo mecanismo que deixou os ícones da GUI pretos em 2026-09-27 (P1, "Validar legibilidade nos temas"). Ao contrário do plugin, o Tray do próprio shell (`/usr/share/omarchy/shell/plugins/bar/widgets/Tray.qml`) liga `layer.enabled: true` na imagem escondida que serve de fonte. Hipótese: era essa a causa do ícone sem cor. O plugin agora segue o mesmo padrão, inclusive o `sourceSize` em pixels físicos. **Não verificado**: fora da tela, o `grabToImage` não captura o `MultiEffect` em nenhuma das duas formas (o controle sem efeito é capturado), e o plugin não foi recarregado no shell real. Para testar: `make install-quickshell-plugin` e recarregar o shell; habilitar continua manual (`omarchy plugin enable`). Falha da CLI esconde o widget, em vez de mostrar uma contagem falsa. - [ ] **Validar troca de tema com o aplicativo aberto.** Conferir gerenciador, diálogos, viewer e terminal, incluindo cores de seleção e foco. Integrar com a escala de texto do Omarchy sem criar preferências de tema paralelas. - Aceite: troca claro/escuro atualiza as superfícies controladas pelo OmaVM sem reinício nem perda de formulário; o conteúdo gráfico do guest mantém o tema escolhido dentro dele. Registrar os resultados de contraste junto à tarefa de P1. - Triagem de 2026-09-28: o Experience Center já observa `colors.toml` e usa a paleta em Material; viewer e terminal iniciavam com fundo/preenchimentos de erro fixos, e o terminal não atualizava as 16 cores após a troca. As duas janelas agora recebem a mesma paleta observada pelo `Backend`; o terminal redesenha as células existentes ao mudar o tema, e mensagens de erro usam superfície e texto do tema. `make build-gui` e os testes QML passaram; viewer e terminal carregaram sem erro de QML em modo offscreen. Falta validar a troca claro/escuro em uma sessão real, com as janelas abertas, e a escala de texto. A adaptação de `muted` para texto foi acrescentada na revisão de P1; cores semânticas ainda exigem avaliação. - [ ] **Completar a experiência do viewer.** Exibir conexão, desconexão, tentativa novamente e retorno ao gerenciador; tornar descobríveis a saída, atalhos e o efeito de fechar a janela. - Aceite: falha de conexão oferece recuperação; fechar o viewer comunica que isso não equivale a desligar a Machine. + - Implementado (2026-10-01): quando a conexão do display acaba (guest desligou, QEMU saiu, conexão recusada), o viewer mostra "Disconnected from NOME" com o motivo e três saídas: **Reconnect** (esconde esta janela e roda `omavm open NOME`, que inicia a Machine se preciso e abre um viewer novo com uma conexão nova; ele recebe `--environment NOME` de `qemu.viewerArgs`), **Open OmaVM** (abre o Experience Center) e **Close**. Ao abrir, um aviso de 6 s no alto diz "Ctrl+Alt+Q closes this window. NOME keeps running; shut it down from OmaVM.", porque em tela cheia não há barra de título. Verificado: `make build-gui`, viewer `offscreen` com fd inválido sem erro de QML, `--environment` coberto em `iso_test.go`. **Não verificado**: o painel e a reconexão numa sessão real com uma Machine desligando, ("Open OmaVM" não duplica mais a janela: o Experience Center virou instância única, ver abaixo). + - Instância única (2026-10-01): um segundo `omavm-gui` sem modo de viewer/terminal conecta em `$XDG_RUNTIME_DIR/omavm-gui.sock` (`gui/singleinstance.*`) e sai. A instância aberta mostra a janela, mesmo que tenha sido fechada enquanto uma ação terminava (cancela a saída pendente), e foca o workspace dela pelo Hyprland, porque no Wayland uma janela não toma o foco sozinha. Um socket deixado por um crash é substituído. Viewers e terminais continuam um por ambiente. Verificado: teste `secondLaunchActivatesTheFirst`; com o binário real, `offscreen`, runtime dir isolado e sem Hyprland, o segundo lançamento sai em 57 ms. **Não verificado**: o foco do workspace numa sessão real. - [ ] **Abrir ambientes em workspaces vazios do Hyprland.** Oferecer uma preferência de abertura entre workspace atual e workspace vazio, lembrando a escolha. Ao abrir um Desktop no modo workspace vazio, selecionar um workspace normal elegível no monitor de origem, abrir o viewer nele e levá-lo ao foco. Manter o Experience Center no workspace de origem. Aplicar a mesma opção ao terminal de Box, sem mover aplicações exportadas automaticamente. - Política: definir vazio como ausência de janelas; considerar também os workspaces ainda não materializados dentro da faixa permitida pela configuração do usuário. Excluir workspaces especiais, reservados por regras pessoais e os visíveis em outro monitor. A seleção deve ser determinística e validada contra a versão instalada do Hyprland. - Reabertura: se já existir um viewer do ambiente, focar sua janela e seu workspace atual, inclusive se o usuário a tiver movido; não abrir outra cópia nem consumir um novo workspace a cada clique. Identificar o ambiente de forma estável, pois o app id compartilhado `dev.omavm.viewer` sozinho não distingue duas Machines ou Boxes. @@ -146,22 +153,28 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - Aceite: foco e entrada permanecem corretos após redimensionar, alternar workspace e voltar ao gerenciador; testar janela tiled e regra opcional de tela cheia, incluindo terminal de Box. Nenhuma regra pessoal é aplicada automaticamente; recurso indisponível tem explicação, sem promessa de resolução dinâmica onde não há suporte. - [ ] **Tornar integração com o guest acionável.** Mostrar clipboard e pasta compartilhada com estado, pré-requisitos e instruções específicas para sistemas suportados; diferenciar não detectado de indisponível. - Aceite: o usuário entende o que funciona e como habilitar o restante sem depender apenas de tooltip; encontra instruções de montagem da pasta e valida copiar/colar texto nos dois sentidos em um guest documentado. Mostrar por capacidade, quando verificável, "pronto", "precisa de componente no guest", "precisa reiniciar" ou "não verificado", com próximo passo concreto. Diferenciar preferência habilitada de funcionamento confirmado e agente QEMU de suporte a clipboard; preferir agentes/protocolos existentes e não apresentar status positivo sem uma verificação real da capacidade. + - Implementado (2026-10-01): `IntegrationReport.Capabilities` (`core.GuestCapability`, estados `ready`, `needs_guest_component`, `needs_restart`, `not_verified`, `off`, cada um com o próximo passo). **Clipboard**: verificado pelo QMP `query-chardev`, onde o canal `clipboard` (`qemu-vdagent`) fica com `frontend-open` quando o `spice-vdagent` do guest abre a porta. É uma verificação do lado do guest, separada do agente QEMU (QGA). **Pasta compartilhada**: `off` sem pasta; `needs_restart` se a sessão começou sem ela; com QGA, `guest-get-fsinfo` procura um `virtiofs` montado (`ready` com o ponto de montagem, ou `needs_guest_component` com o comando `mount -t virtiofs`); sem QGA, `not_verified` com o mesmo comando. Machine parada nunca aparece `ready`. Mostrado em texto no Settings ("Working with the guest", com a dica selecionável para copiar o comando) e no `omavm integration`; golden de `list --status` regravado, só com o campo novo. Validado com o QEMU real sem guest: o canal existe e aparece fechado (`needs_guest_component`). **Não verificado**: os casos `ready` com `spice-vdagent` e `qemu-guest-agent` num guest Linux real, e o copiar/colar nos dois sentidos. Testes: `guestcaps_test.go`, `test_guestCapabilitiesAreSpelledOut`. - [ ] **Persistir preferências de integração bidirecional, opt-out.** Disponibilizar controles por ambiente para clipboard, transferência de arquivos e abertura de links/aplicações. O padrão permite host → guest e guest → host; permitir desativar cada capacidade e restringir uma direção quando o mecanismo suportar essa separação. - Aceite: GUI e CLI consultam e alteram a mesma preferência persistida; reabrir viewer, reiniciar ambiente ou atualizar o registro não reativa uma capacidade explicitamente desabilitada. Ausência de preferência usa o padrão habilitado; mostrar separadamente configurado, disponível e efetivamente ativo. - Aplicação: desligar impede novas trocas ou solicitações na capacidade/direção correspondente; documentar operações em andamento e eventual necessidade de reconexão/reinício. Não apresentar um controle direcional como efetivo quando o backend não consegue aplicá-lo; nesse caso oferecer desativação completa e explicar a limitação. + - Clipboard implementado (2026-10-01): além do opt-out geral (`ClipboardDisabled`), `EnvironmentSettings.ClipboardDirection` limita a um sentido: `to-host` (só o que o guest copia chega a este computador) ou `to-guest`; vazio significa os dois. Persistido no mesmo `environments.json`, então reabrir o viewer, reiniciar ou atualizar o registro não muda a escolha. CLI: `settings NOME --clipboard-direction both|to-host|to-guest`; GUI: lista sob "Share text clipboard" (Machines). Quem aplica é o viewer: `--share-clipboard` aceita `to-host`/`to-guest`, e o `DisplayView` ignora o texto recebido do guest (`to-guest`) ou não envia o do host (`to-host`). Vale ao reabrir a janela da Machine (o canal `qemu-vdagent` existe sempre), e a dica do Settings agora diz isso em vez de "restart". Box: só existe o sentido para o host (OSC 52), e colar é sempre uma tecla deliberada, então `to-guest` numa Box é recusado (`ErrUnsupported`) com a sugestão de desligar. Testes: `TestClipboardDirection`, `TestViewerArgsCarryTheClipboardDirection`, `test_clipboardDirectionRoundTrips`. **Não verificado**: o bloqueio de cada sentido com `spice-vdagent` num guest real. **Sem mecanismo ainda**: transferência de arquivos e abertura de links/aplicações, que não têm o que desligar. - Escopo: clipboard de texto já tem preferência por Machine; auditar e preservar seu comportamento. Transferência de arquivos e abertura de links/apps são evolução descrita em P3, com esta política de defaults definida. Em Boxes, inventariar os caminhos de integração do Distrobox antes de prometer bloqueio, pois compartilhar a home não equivale a um canal de transferência controlado pelo OmaVM. - [ ] **Aprimorar uso diário do terminal de Boxes.** Avaliar seleção, cópia/colagem, scrollback, escala de fonte e mensagens ao encerrar; implementar as lacunas prioritárias mantendo atalhos de aplicações de terminal. - Aceite: validar shell, editor, pager e sessão encerrada com erro; permitir leitura do erro antes de fechar a janela. + - Já feito antes: seleção, cópia e colagem (2026-09-28); sessão encerrada com erro mantém a janela, com o motivo e "Try Again". Implementado (2026-10-01), com os atalhos do Alacritty, o terminal padrão do Omarchy: **scrollback pelo teclado** (Shift+PageUp/PageDown por página, Shift+Home/End para o topo e o fim; na tela alternativa de vim e less as teclas continuam do programa) e **tamanho da fonte** (Ctrl+= ou Ctrl++, Ctrl+-, Ctrl+0, e Ctrl+roda do mouse; de 8 a 48 px, lembrado para os próximos terminais em `~/.config/OmaVM/dev.omavm.viewer.conf`, gravado só quando muda). Ctrl+Shift+- (Ctrl+_, desfazer no readline e no Emacs) continua chegando ao programa. Teste: `viewShortcuts` (`make test-terminal`); terminal rodado `offscreen` com config isolada. **Não verificado** numa sessão real: shell, editor e pager com as teclas novas. - [ ] **Completar exportação de aplicações de Boxes.** Mostrar carregamento, exportação em andamento, resultado e desfazer exportação; testar o lançamento pelo menu do Omarchy. - Aceite: ícone e nome identificam a aplicação; exportar faz o atalho aparecer no launcher e abrir a aplicação da Box correta. Remover do menu retira o atalho e preserva a instalação no ambiente; falha permite nova tentativa sem perder a seleção. - Jornada adicional: com a Box parada, clicar no aplicativo exportado deve iniciar o ambiente e abrir a aplicação sem terminal no host. Validar arquivo como argumento, caminhos com espaços/acentos, reabertura e erro de inicialização; identificar a Box quando duas exportam a mesma aplicação. Reutilizar a integração do Distrobox. + - Implementado (2026-10-01): no `AppsDialog`, a linha do aplicativo em andamento troca o botão por um indicador e diz "Adding to the app menu…" ou "Removing from the app menu…" (sem segundo clique). O resultado aparece em palavras no topo ("“Gimp” is in the app menu.", ou "removed from the app menu; it is still installed in dev"). Uma falha mostra o erro e devolve o mesmo botão na mesma linha. O estado exportado aparece em texto ("In the app menu"), não só na cor do ícone, e cada botão tem nome acessível com o nome do app. Teste: `tst_appsdialog.qml`. Fora: o ícone real de cada aplicação (está dentro da Box; o Distrobox só copia para o host ao exportar) e o teste pelo menu do Omarchy numa sessão real. - [ ] **Explicar ajustes automáticos e pendentes.** Mostrar quando mudanças exigem reinício e quando Travel Mode reduz recursos; diferenciar preferência configurada de valor efetivo. - Aceite: salvar uma descrição não altera inadvertidamente a intenção de configuração de CPU; estados e defaults permanecem coerentes entre GUI e CLI. + - **"Mudanças que exigem reinício" e "Travel Mode reduz recursos" implementados (2026-10-01).** O QEMU guarda na linha de comando o que a sessão recebeu (`-smp`, `-m`, vsock, virtiofs, `-cdrom`). `qemu.sessionAdjustments` compara isso com as configurações salvas e preenche `Status.RestartNeeded` e `Status.TravelMode` (omitidos quando falsos). Travel Mode = menos CPUs que o efetivo, sem CPUs fixados e sem opt-out. Card: "Restart to apply the saved settings" e "Travel Mode: started with fewer processors…"; `omavm status` diz o mesmo. Validado com o QEMU real: recém-iniciada, nada pendente; depois de `--memory-mib 4096`, `restart_needed: true`. Testes: `applied_test.go`, `test_sessionAdjustments`. Fora: Vulkan (a detecção é cara demais para o poll de 3 s), troca de caminho da pasta compartilhada com outra já compartilhada, e Boxes (o limite de CPU do Travel Mode delas exigiria consultar o engine por Box a cada poll). - **"Diferenciar preferência configurada de valor efetivo" implementado (2026-09-27).** Descoberta útil ao investigar o bug abaixo: `backend.environments` (que alimenta `SettingsDialog.qml`) vem de `omavm list --json`, e `Service.List` retorna os ambientes **brutos** (`internal/core/service.go`, nunca resolvidos por `EffectiveSettings()`, ao contrário do retorno de `Settings()`/`Configure()`) — então `settings.cpus` no JSON de list já vem ausente (`omitempty`) quando CPUs nunca foi fixado, sem precisar de nenhuma mudança de API. `SettingsDialog.qml` ganhou `cpusPinned`/`memoryPinned` (checando isso) e uma legenda por campo: "Not pinned yet: adapts automatically, and Travel Mode may reduce it while on battery" vs "Pinned — won't change on its own" vs "Will be pinned to this value on save" (quando `cpusTouched`/`memoryTouched` nesta sessão do diálogo). `qmllint`/`make build-gui` limpos. - **Bug real encontrado e corrigido (2026-09-27), exatamente o cenário do aceite.** `Service.Configure` (`internal/core/service.go`) montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10 só para exibição) e depois persistia essa cópia inteira incondicionalmente — então **qualquer** `Configure`, mesmo alterando só a descrição, gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido explicitamente fixados. Consequência real: `internal/backend/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0`; salvar qualquer coisa em Settings desligava essa redução automática permanentemente, na primeira vez, sem o usuário nunca ter tocado em CPU. A correção original nesta sessão (rastrear "touched" nos `SpinBox` da GUI para só enviar `--cpus`/`--memory-mib` quando o usuário realmente mexeu) foi necessária mas **não suficiente** — o bug real estava no Core, não na GUI, e afetava qualquer chamador (CLI direto incluído). Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto); o valor de retorno de `Configure` continua resolvido (`env.EffectiveSettings()` no fim, depois de persistir), então CLI/GUI continuam mostrando "2 CPUs" mesmo quando nada foi fixado. - Evidência: reproduzido e corrigido com testes reais via CLI (`omavm create --kind machine` seguido de `omavm settings NOME --description "x"`, inspecionando o `environments.json` bruto diretamente — antes da correção: `cpus`/`memory_mib`/`snapshot_limit` apareciam gravados; depois: `settings` ficava só com `{"description":"x"}`, sem nenhum campo de hardware). Teste de regressão novo no Core, `TestConfigureUnrelatedFieldDoesNotPinHardwareDefaults` (`internal/core/service_test.go`) — confirmado que falha sem a correção (revertido manualmente pra provar) e passa com ela; também confirma que um pin explícito (`--cpus 4`) sobrevive a uma edição não relacionada posterior. `go test ./...` (suite inteira) e `make test` (inclui `make test-backend`, ver item de flickering acima) passam. Fix na GUI (rastreamento de "touched" em `SettingsDialog.qml`/`gui/backend.cpp,h`) mantido como complemento — evita reenviar `--cpus`/`--memory-mib` desnecessariamente mesmo com o Core já protegido, e documenta a intenção do usuário de forma mais explícita na camada de UI. - [ ] **Ajustar o Experience Center ao uso real.** Validar identificação da distribuição, previews, nomes longos e listas com 1, 10 e 30 ambientes. Adicionar busca simples se os testes mostrarem dificuldade de localização. - Aceite: o usuário localiza o ambiente por nome sem depender de miniaturas; foco e posição da lista não se perdem ao atualizar. + - Feito (2026-10-01): **distribuição** — o card não mostrava o sistema (UX Principle #5 pede nome, distro, kind e status). Agora a linha do tipo diz "Development Box · Fedora 42" ou "Desktop · Fedora-Workstation-Live-42", a partir da imagem: sem registro, sem `-toolbox`, com nomes conhecidos (`archlinux` vira "Arch Linux") e a tag só quando não é `latest`; numa Machine, o nome da ISO sem caminho nem extensão (`systemName`, testado com presets, registro com porta, digest e ISO). **Nomes longos** — em 320 px o nome é cortado dentro do card e a ação principal continua dentro dele (`test_longNameStaysInsideANarrowCard`); o nome cortado mostra o completo ao passar o mouse. **30 ambientes** — um poll que muda estados com a lista rolada até o fim mantém a posição e o card visível (`test_pollKeepsTheScrollPositionWithThirtyEnvironments`); o custo do poll com 30 Machines foi medido no item de desempenho. Busca não foi adicionada: os testes não mostraram dificuldade de localização, e o aceite pede busca só nesse caso. **Não verificado**: previews numa sessão real e a localização por uma pessoa. ## Qualidade da integração com QEMU — frente transversal @@ -171,13 +184,18 @@ Base da revisão: `internal/backend/qemu/`, contratos em `internal/core/`, CLI e - [ ] **Auditar ciclo de vida e reconciliação de estado.** Conferir consistência entre processo QEMU, registro persistido e estado informado ao CLI/GUI durante start, pause, resume, shutdown, restart e encerramento inesperado. Revisar identificação do processo, arquivos de estado obsoletos e operações concorrentes. Achado e corrigido em 2026-09-29: um `qemu.pid`/`virtiofs.pid` deixado por crash ou reboot, com o pid já reaproveitado por outro processo, fazia a Machine parecer rodando (Start virava no-op) e o Force Stop mandava SIGTERM a esse processo; agora o pid só vale se a linha de comando dele tiver o pidfile/socket da Machine (`processHasArg`, teste `TestStalePidfileOfAnotherProcessIsNotRunning`). Também em 2026-09-28: Force Stop passou a esperar o QEMU sair, porque Delete logo depois falhava. - Aceite: reproduzir falha de inicialização, saída inesperada, reabertura do gerenciador e ações concorrentes por CLI/GUI; não sinalizar sucesso antes da condição esperada nem agir sobre processo alheio. Falha de desligamento preserva a Machine e nunca vira Force Stop automaticamente. Relacionar à atualização de estados de P1. + - Rodada de 2026-10-01 (leitura de `internal/backend/qemu/qemu.go` + QEMU 11.1 real), procurando estados declarados antes de serem verdade. **Resume** depois de uma pausa por disco cheio: o `cont` retorna ok, mas o QEMU volta a pausar na hora se o disco do host continua cheio. Agora o Resume observa o estado por ~300 ms e, se voltou a `io-error`, falha com "paused again: …disk is full…" em vez de reportar sucesso. **Shut Down de uma Machine pausada**: ela é retomada para poder desligar; se o guest não desliga no prazo, antes ficava **rodando** (estado que a pessoa não escolheu). Agora volta a ser pausada, "as it was", e nunca recebe `quit`. Validado com o QEMU real: pausa → Shut Down sem guest → depois de 10 s `paused`, código 1. **Saída inesperada**: pidfile órfão = processo morto ou travado, reportado no status e no log (ver "Melhorar diagnóstico de falhas do QEMU"). **Falha de inicialização**: a Machine nunca fica falsamente ativa (disco preso → `stopped`, ver "Antecipar falhas de inicialização"). Já certos na leitura: Pause e Resume são síncronos no QMP; Stop espera o processo sumir; Force Stop espera sair; o pid só vale com o pidfile da Machine na linha de comando. Testes: `TestResumeThatPausesAgainOnDiskErrorFails`, `TestSlowShutdownOfPausedMachinePausesItAgain` (`gracefulShutdownTimeout` virou variável para o teste). Ainda por reproduzir: reabrir o gerenciador e ações concorrentes pela GUI numa sessão real. - [ ] **Auditar comunicação QMP.** Verificar negociação, associação entre pedidos e respostas, eventos intercalados, erros, desconexão, cancelamento e limites de espera. Avaliar onde eventos ajudam a acompanhar transições dentro do ciclo de vida atual, sem presumir conexão permanente ou criar daemon só para isso. - Aceite: testes focados cobrem resposta de erro, ausência de resposta, conexão interrompida e evento intercalado; chamadas terminam com resultado ou erro identificável. Não repetir automaticamente uma operação mutável cujo resultado ficou desconhecido: reconciliar o estado antes de tentar novamente. + - Auditado e corrigido (2026-10-01), lendo `internal/backend/qemu/qmp.go`. Já estavam certos: o cumprimento e o `qmp_capabilities` em cada conexão; a correlação pedido/resposta (um comando por conexão, então a primeira resposta que não é evento é a dele); os eventos intercalados, ignorados. **Achados corrigidos:** (1) o prazo de 5 s era absoluto desde a conexão e valia para tudo, então um `blockdev-snapshot-internal-sync` de disco grande podia estourar enquanto o QEMU terminava o snapshot, deixando no disco um snapshot que o registro não conhece. Agora o prazo é por comando: 5 s por padrão e 10 min para criar ou apagar snapshot (`qmpSlowTimeout`). (2) Resposta que não chegou (conexão caiu ou prazo acabou) vira `errQMPNoReply` ("the command may or may not have run"), distinta de uma recusa. Criar ou apagar snapshot nesse caso **reconcilia** pelo `query-block` (o snapshot existe ou não no `virtio0`) em vez de repetir ou de dar falha às cegas. Se nem a consulta responde, a falha diz que o resultado não foi confirmado. (3) A recusa do QEMU vira `qmpError{Class, Desc}`, e a mensagem diz "…: Snapshot … does not exist (GenericError)" em vez de `map[class:… desc:…]`. Testes: `qmp_test.go` (erro estruturado, evento antes da resposta, conexão derrubada, silêncio com prazo, snapshot sem resposta reconciliado nos dois sentidos, e falha não confirmada). Formato do `query-block` e do erro conferidos no QEMU 11.1. Não feito: acompanhar transições por eventos, que exigiria uma conexão persistente, ou seja, um daemon. - [ ] **Antecipar falhas de inicialização.** Revisar verificações de acesso ao KVM, executáveis e capacidades necessárias, mídia, permissões, memória/espaço e conflitos de discos ou sockets. Distinguir verificações possíveis antes de iniciar de falhas que só o QEMU pode confirmar. - Aceite: dependência ausente, ISO inválida/inacessível e recurso ocupado produzem diagnóstico contextual, sem deixar o ambiente falsamente ativo. Limpar apenas recursos criados pela tentativa malsucedida e preservar dados anteriores. Alimentar a tarefa de pré-requisitos de P1 com as mesmas regras do backend. + - Implementado (2026-10-01). Antes do QEMU, onde a verificação é determinística: **memória** acima do total do host (`/proc/meminfo`) é recusada com o valor e a correção (código 2); **ISO** é aberta de verdade em vez de só passar pelo `stat`, porque uma imagem sem permissão de leitura fazia o QEMU recusar o start inteiro ("Permission denied"). Agora ela segue a regra da ISO ausente: a Machine inicia pelo disco, e o motivo vai para o log. Pela saída do QEMU, o que só ele confirma: **disco ocupado** por outro processo (`Failed to get "write" lock`) vira `ErrBusy` (código 6) dizendo para fechar o outro programa; **memória indisponível no momento** (`cannot set up guest memory`) vira instrução de fechar programas ou baixar a memória. Saídas desconhecidas continuam como o QEMU disse. Já existiam: binários ausentes, KVM, espaço, sockets velhos apagados no start, e o virtiofsd encerrado se o QEMU falha (só o que a tentativa criou). Validado com o QEMU 11.1 real (disco preso por outro QEMU → código 6 e a Machine continua `stopped`; 262144 MiB num host de 15,7 GiB → código 2). Testes: `TestKnownStartFailuresSayWhatToDo`, `TestStartChecksMemoryAndReadableMedia`. - Duas lacunas pontuais da auditoria anterior corrigidas em 2026-09-27: (1) `qemu-img`/`qemu-system-x86_64` ausentes agora produzem o mesmo tipo de dica acionável que `virtiofsd` já tinha (`qemuBinaryPath`/`runQEMU`/`qemuErr` em `internal/backend/qemu/qemu.go`), em vez do erro cru do Go; (2) `Start()` agora remove também `qmp.sock` obsoleto junto com VNC/QGA, fechando a assimetria de limpeza de sockets identificada. Teste de regressão: `TestMissingBinaryDiagnostic`. Ainda faltam: checagem antecipada de `/dev/kvm`, memória/espaço em disco e conflito de sockets em uso por outro processo (o QEMU já recusa esses casos com stderr repassado, mas sem antecipação). - [ ] **Revisar discos, snapshots e falhas parciais.** Mapear a ordem das alterações no disco, no histórico e no registro, incluindo retenção, restauração e exclusão. Verificar restrições de uso de imagens em execução e espaço disponível, sem tratar uma checagem inicial como garantia contra esgotamento posterior. - Aceite: em ambientes de teste descartáveis, exercitar falha de comando, interrupção entre etapas e espaço insuficiente; registrar estado final, pontos de recuperação preservados e caminho de recuperação. Nenhum sucesso aparente ou descarte silencioso de histórico válido após falha. Vincular as confirmações e avisos às tarefas de snapshots de P0. + - Mapa da ordem (revisado 2026-10-01, `internal/core/service.go`): **criar** = backend cria → registro grava (logo após a confirmação) → retenção apaga o mais antigo no backend → registro o retira, um por vez. **Go To** = backend só, com a Machine parada; o registro não muda. **Remover** = backend apaga → registro retira. Falha antes do registro não deixa sucesso aparente. Um snapshot criado sem resposta do QEMU é reconciliado pelo `query-block` (ver "Auditar comunicação QMP"). + - **Falha parcial corrigida (2026-10-01): snapshot listado no registro mas ausente do disco** (apagado à mão com `qemu-img`, disco trocado). Antes, removê-lo falhava para sempre e, se ele era o mais antigo, **todo snapshot novo** reportava "discarding the oldest failed" e a retenção travava. Agora o backend reconhece as mensagens reais do `qemu-img` (`snapshot not found`, `Failed to load snapshot: No such file or directory`) e do QMP (`… does not exist on device`) como `core.ErrSnapshotGone`. Remover e a retenção tratam isso como já removido: só tiram do registro, com aviso no log. Go To diz "snapshot is no longer in the disk: delete it from the list" (código 3). Validado com o `qemu-img` real (snapshot apagado à mão → Go To código 3 → remover código 0 → lista correta). Teste: `TestSnapshotGoneFromTheDiskIsForgotten`. Ainda aberto: o caso inverso (snapshot no disco que o registro não conhece) só acontece se gravar o registro falhar logo após o backend confirmar; ele fica invisível, sem perda de dados. - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código: `savevm`/`loadvm`/`delvm` (Machine rodando, via `human-monitor-command`) podiam reportar sucesso mesmo quando a operação HMP subjacente falhava.** `qmp.go`'s `human-monitor-command` é um passthrough para comandos legados do monitor humano do QEMU; QEMU reporta falhas desses comandos específicos (tag desconhecida, snapshot corrompido etc.) como texto simples dentro do campo `"return"` da resposta QMP, não como um erro de protocolo QMP (`"error"`). `internal/backend/qemu/qemu.go` só checava o erro de protocolo e descartava o texto de retorno (`_, err := qmpHumanMonitorCommand(...)`) nos três call sites — exatamente o cenário do aceite acima ("nenhum sucesso aparente... após falha"). Pior em `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; se o `loadvm` falhasse silenciosamente dessa forma, o código seguia direto para `cont`, retomando a Machine no estado anterior ao restore (nada foi restaurado) enquanto CLI/GUI reportavam "Go To" como bem-sucedido. - Corrigido checando o texto de retorno (`strings.TrimSpace`) além do erro de protocolo nos três casos; texto não-vazio agora vira erro explícito. Em `GoToSnapshot` especificamente, o `cont` de resume agora é sempre tentado mesmo quando o `loadvm` falhou (a Machine já estava pausada por causa do `stop` anterior; deixá-la travada em pausa por causa de uma falha de restore seria um bug de lifecycle novo e distinto, não uma correção). - Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/qemu/lifecycle_test.go`), com um servidor QMP fake retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` — confirmado que **falha** sem a correção (`GoToSnapshot` retornava `nil`) e passa com ela, incluindo a checagem de que `cont` ainda é enviado. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos. @@ -192,8 +210,15 @@ Base da revisão: `internal/backend/qemu/`, contratos em `internal/core/`, CLI e - Aceite: ponteiro corresponde à imagem exibida, entrada permanece utilizável e falha de conexão oferece recuperação; validar textos acentuados e combinações de teclas do host/guest. Separar testes de protocolo dos testes com desktop guest real e relacionar os resultados às tarefas do viewer de P2. - [ ] **Medir recursos e desempenho antes de ajustar defaults.** Registrar tempo até QMP disponível, abertura do viewer e guest utilizável separadamente; medir CPU/memória em repouso e sob uma carga reproduzível, além de I/O quando houver gargalo demonstrado. Conferir valores configurados e efetivos, incluindo Travel Mode. - Aceite: baseline identifica hardware, versões, guest, carga e repetições; qualquer ajuste de CPU, memória, aceleração ou disco apresenta comparação antes/depois e impacto em compatibilidade e integridade dos dados. Não reduzir garantias de escrita para melhorar números nem introduzir tuning sem ganho medido. + - **Baseline parcial (2026-10-01)**. Host: Intel i5-1135G7 (8 threads), 15,7 GiB, kernel 7.2.5-3-omarchy, QEMU 11.1.1, Go 1.27.1. Guest: **nenhum** (ISO falsa de 1 MiB, então "guest utilizável", carga dentro do guest e I/O não foram medidos). Cinco repetições, estado isolado: + - `omavm start` até o QMP responder: 122–128 ms. + - `omavm list --status --json` (o poll de 3 s da GUI) com 1, 10 e 30 Machines **paradas**: 2, 2–3 e 3 ms. + - O mesmo com 30 Machines e 3 **rodando**: **721–737 ms**, constante com o número de Machines rodando (uma goroutine por Machine). + - QEMU em repouso sem guest (3 instâncias, depois de 20 s): 15% de CPU e 127 MiB de RSS cada. Sem um guest real esse número não serve para ajustar defaults, e nada foi ajustado. + - **Gargalo achado e corrigido**: os ~720 ms eram o `Integration` esperando o `guest-ping` do QGA esgotar o prazo de 700 ms. Sem agente no guest, quem aceita a conexão é o próprio QEMU, que nunca responde. Agora uma consulta `query-chardev` diz se o guest abriu a porta `qga0` (e a do clipboard, que já era consultada). Porta fechada = sem agente, e o ping é pulado. Mesmo resultado ("unavailable"), medido em **7–12 ms** com 1 Machine rodando. Com a porta aberta, o ping continua confirmando que o agente responde. Teste: `TestIntegrationSkipsThePingWhenTheAgentPortIsClosed`. Falta: medir com um guest Linux instalado (boot, viewer aberto, guest ocioso e sob carga), e o Travel Mode na bateria. - [ ] **Melhorar diagnóstico de falhas do QEMU.** Conferir captura de erros de inicialização e execução, contexto da operação, ambiente e horário nos logs. Expor resumo compreensível e detalhes copiáveis sem depender de o usuário localizar processos ou sockets manualmente. - Aceite: uma falha reproduzida pode ser relacionada ao ambiente e à operação tanto pelo CLI quanto pela GUI, com causa técnica disponível e próximo passo quando conhecido. Não registrar conteúdo de clipboard nem arquivos compartilhados; erros permanecem consultáveis conforme P0. + - Implementado (2026-10-01), para o ponto cego da execução: com `-daemonize`, o stderr do QEMU some, e uma Machine cujo processo morria (crash, falta de memória no host, `kill -9`) só aparecia como "Stopped". Confirmado no QEMU 11.1 que ele apaga o próprio pidfile ao sair normalmente (desligamento do guest, Force Stop/`quit`), e que o arquivo fica depois de um `kill -9`. Agora um pidfile sem processo faz o `Status` da Machine parada trazer em `warning` que "a sessão iniciada em DATA terminou sem desligar (o processo foi morto ou travou)", com o próximo passo (`coredumpctl list qemu-system-x86_64`, `journalctl -b -k`). Aparece no card (`statusWarningLabel`) e no `omavm status`. O `Start` seguinte, que sobrescreve essa evidência, registra o ocorrido no log (`WARN previous session ended unexpectedly`, com a Machine e o horário). Validado com o QEMU real (`kill -9` → aviso; Force Stop normal → nenhum aviso; novo Start → linha no log e aviso some). Teste: `TestSessionThatEndedWithoutShuttingDownIsReported`. Falhas de inicialização já chegavam com a saída do QEMU (`qemuErr`) e, sem KVM, com a instrução de correção. Priorizar achados de perda de dados ou lifecycle incorreto em P0; inicialização e recuperação necessárias ao uso básico em P1; integração com guest e melhorias de desempenho comprovadas em P2. Recursos novos continuam sujeitos à descoberta e ao escopo de P3. Definir limiares de desempenho após medir a baseline, sem metas arbitrárias. @@ -205,6 +230,33 @@ A [auditoria de código de 2026-09-27](review-history.md#achados-da-auditoria-20 O [catálogo de propostas](discovery.md) reúne instalação assistida, Blend Mode, arquivos e links bidirecionais, storage, networking, hardware, lifecycle, desempenho e recuperação. Cada proposta mantém seus critérios de aceite e depende de caso de uso, suporte do backend/guest e decisão de escopo antes da implementação. +### Ampliar a cobertura de jornadas e ferramentas Linux + +Estas são investigações de **P3**, não suporte prometido nem autorização para implementar novos backends. Primeiro comparar cada opção com Box (Distrobox) e Machine (QEMU/KVM) existentes. Registrar para cada prova: caso de uso, tipo de isolamento, host e guest testados, pré-requisitos/permissões, tempo até uso, recursos em repouso, integração com o desktop, recuperação e custo de manutenção. Só propor uma nova integração quando a jornada não for atendida pelas ferramentas atuais; documentar a decisão de escopo exigida por [CLAUDE.md](../CLAUDE.md). + +- [ ] **Criar uma matriz de sistemas convidados, não só de ferramentas.** Escolher versões e imagens reproduzíveis de Linux (desktop e servidor), Windows, FreeBSD, OpenBSD, NetBSD e Haiku; incluir outros sistemas apenas quando houver imagem e caso de uso concretos. Partir da Machine x86_64 existente e registrar separadamente o que exigir outra arquitetura ou emulação por software. + - Aceite: para cada combinação, anotar origem da mídia, arquitetura, firmware/boot, instalação, disco/rede, vídeo, entrada, áudio, shutdown, snapshots e recursos host ↔ guest como confirmado, falhou ou não testado. Ter boot ou imagem no viewer não significa que clipboard, pasta compartilhada ou aceleração gráfica funcionem. Publicar limitações por sistema e recuperar falhas sem mudar os defaults de Machines existentes. Referências: [QEMU: arquiteturas e máquinas](https://www.qemu.org/docs/master/system/introduction.html) e [suporte a VirtIO por guest](https://www.qemu.org/docs/master/system/devices/virtio/index.html). +- [ ] **Validar jornadas de desktop e servidor fora do Windows.** Em Linux e ao menos um BSD ou Haiku, testar instalação até reabertura, uso diário e desligamento; em guest de servidor, testar console e acesso remoto sem depender de um desktop gráfico. + - Aceite: documentar teclado/layout, resolução, rede, atualização do guest, compartilhamento de arquivos e cópia de texto quando houver suporte, além de um caminho utilizável quando agentes ou drivers não existirem. Separar o que o QEMU fornece do que cada guest realmente implementa; vincular os achados à matriz de capacidades da frente QEMU. +- [ ] **Comparar caminhos para Windows no desktop.** Montar uma matriz com VM comum (VirtIO/SPICE), VM com GPU dedicada (VFIO + [Looking Glass](https://looking-glass.io/docs/B7/)) e janelas individuais via [FreeRDP/WinApps](https://github.com/winapps-org/winapps). Avaliar também combinação de passthrough com janelas remotas somente se houver caso de uso real. + - Aceite: uma aplicação de escritório e uma carga 3D escolhidas abrem, recebem teclado/mouse e compartilham arquivos/clipboard conforme a capacidade de cada caminho; medir fluidez e latência observáveis, instalação e recuperação. Separar tela inteira de janelas individuais. Informar requisitos de IOMMU, grupos PCI, GPU disponível para o host, display do guest e drivers; nunca automatizar binding VFIO ou prometer GPU virtual 3D no Windows sem validação. O diagnóstico `omavm host` continua apenas informativo. +- [ ] **Comparar gráficos acelerados para guests Linux.** Exercitar VirGL/Venus já disponíveis no QEMU e comparar com renderização sem aceleração e, se houver hardware adequado, passthrough/Looking Glass. Verificar resolução, escala, multi-monitor, áudio, entrada e reabertura do viewer; medir carga no host e aplicação real no guest. + - Aceite: registrar API gráfica, driver, host/guest, resultado e fallback por combinação. A detecção estática de Vulkan e o boot do QEMU não contam como prova de aceleração dentro do guest; manter as validações de display da frente QEMU. +- [ ] **Avaliar interoperabilidade com libvirt sem disputar posse da VM.** Estudar importação ou abertura de uma VM existente, ou exportação em formato utilizável por `virsh`/virt-manager, antes de considerar controle simultâneo. Inventariar XML, discos, firmware, snapshots, redes e permissões que precisariam de tradução. + - Aceite: demonstrar uma ida e volta em ambiente descartável sem alterar a VM original nem iniciar dois gerenciadores sobre o mesmo disco gravável; declarar o que não migra. Se o custo superar o benefício, manter importação/exportação de imagem como caminho menor no [catálogo](discovery.md#importexport-de-imagens). +- [ ] **Reavaliar desenvolvimento em containers por intenção.** Comparar Box/Distrobox com Podman/Docker rootless para tarefa descartável, CI local e aplicações isoladas. Verificar se uma Box cobre o trabalho diário e se um container direto atende melhor a uma execução efêmera; preservar a distinção entre home compartilhada e isolamento. + - Aceite: criar, executar, interromper e limpar uma tarefa com logs e código de saída confiáveis, sem deixar volumes, processos ou atalhos órfãos. Reutilizar mecanismos nativos de Distrobox/Podman em vez de construir um runtime próprio; ligar o resultado à proposta de ambiente descartável. +- [ ] **Investigar containers de sistema.** Comparar a necessidade de uma distribuição Linux com serviços próprios usando [Incus](https://linuxcontainers.org/incus/docs/main/explanation/containers_and_vms/) com Box e Machine atuais. Distinguir container de sistema, container de aplicação e VM; avaliar serviços, snapshots, rede, acesso a arquivos e permissões administrativas. + - Aceite: um serviço de longa duração inicia, reinicia e é removido sem afetar o host; justificar por que Box ou Machine não resolve o caso. Não adicionar um terceiro tipo de ambiente ou backend só porque a ferramenta existe. +- [ ] **Investigar microVMs para execução curta e isolada.** Comparar uma tarefa reproduzível em QEMU/KVM com [Firecracker](https://firecracker-microvm.github.io/) ou [Cloud Hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor), considerando modelo de dispositivos, imagens/kernel, rede, `vsock`, console, permissões e limpeza. + - Aceite: medir tempo até o comando utilizável, memória e custo de preparo/recuperação no mesmo host e carga; decidir se há ganho suficiente para um fluxo descartável. Não tratar microVM como substituta automática do Desktop gráfico. +- [ ] **Avaliar ambientes em outro host somente após uma jornada local completa.** Comparar conexão existente por [libvirt sobre SSH](https://www.libvirt.org/remote) ou Incus remoto com a necessidade de expor um ambiente do OmaVM pela rede. Levantar identidade do host, autenticação, disponibilidade, transferência de arquivos, latência de display e estado quando a conexão cai. + - Aceite: uma sessão de teste desconecta e reconecta sem perder a identidade da Machine nem executar ação no host errado; credenciais não aparecem em logs. Registrar explicitamente o conflito de escopo com a exclusão atual de hosts remotos em `CLAUDE.md` antes de qualquer implementação. +- [ ] **Delimitar ferramentas que não virtualizam um sistema completo.** Comparar Wine/Proton para uma aplicação Windows específica e `systemd-nspawn`/chroot para uma tarefa Linux simples, apenas como orientação de escolha quando forem suficientes. Não apresentar essas opções como Machines nem prometer isolamento equivalente a uma VM. + - Aceite: a escolha Box/Machine continua correta para kernel próprio e fronteira de isolamento; a documentação explica quando encaminhar o usuário a uma ferramenta externa, sem criar wrappers ou fluxos na GUI sem demanda demonstrada. + +**Ordem sugerida de provas:** estabelecer primeiro a matriz de guests com Linux, Windows e ao menos um BSD ou Haiku nas Machines existentes; validar as jornadas de desktop/servidor e a aceleração Linux. Depois, comparar uma tarefa descartável com ferramentas já presentes. Só então avaliar libvirt, Incus, microVMs e passthrough para lacunas concretas. Hosts remotos e novos backends permanecem fora do escopo de implementação até decisão explícita; a matriz acima permite tomar essa decisão com evidência. + ### Triagem das ideias de 2026-09-28 Esta triagem liga as propostas de [docs/ideias](ideias/README.md) às jornadas acima. **Próxima** significa candidata a planejamento após revalidar a lacuna e a jornada correspondente, na prioridade indicada; **condicional** exige primeiro o caso de uso e a decisão de escopo de P3; **adiar** não justifica trabalho agora. Os arquivos vinculados guardam o esboço e os riscos; esta tabela não duplica suas especificações. @@ -212,21 +264,21 @@ Esta triagem liga as propostas de [docs/ideias](ideias/README.md) às jornadas a | Ideia | Encaminhamento | Evidência ou decisão necessária | |---|---|---| | [Copiar do terminal da Box](ideias/terminal-copiar.md) | **Próxima — P0/P2** | Reproduzir o efeito de Super+C e concluir seleção/cópia, inclusive no scrollback; avaliar OSC 52 de escrita separadamente. | -| [Progresso ao criar Box](ideias/progresso-ao-criar-box.md) | **Próxima — P1** | Medir espera real e duração do lock; separar preparação/download de registro sem permitir criação duplicada ou progresso fictício. | -| [Espaço em disco do host](ideias/disco-do-host.md) | **Próxima — P1**, só diagnóstico | Mostrar causa e recuperação de `io-error` e alertar sobre pouco espaço; não prometer que uma checagem inicial impede esgotamento posterior. | +| [Progresso ao criar Box](ideias/progresso-ao-criar-box.md) | **Feito 2026-10-01** | O lock do registro já não cobria o `backend.Create` desde 2026-09-29 (criação em duas fases). Agora o adapter do Distrobox baixa a imagem antes (` image inspect`, depois ` pull`, primeiro engine do `PATH` na ordem do Distrobox) e repassa etapas reais ("layer N", "finishing"), sem porcentagem, por `core.WithProgress`/`ReportProgress` no contexto (a interface `Backend` não mudou). CLI: no terminal, etapas no stderr; `create --progress` imprime `progress: ETAPA` no stdout, e a GUI lê isso enquanto roda (`Backend::progress`, rótulo no card). Falha no pull só registra no log e deixa o `distrobox create` tentar e dar o próprio erro: ele conhece o engine configurado no `distrobox.conf` e o caso do Docker com sudo. Validado com Podman e Distrobox reais (alpine-toolbox: 2 layers, 19 s, Box criada e depois removida, imagem apagada). Testes: `pull_test.go`, `creationReportsProgressStages`. Não feito: o fluxo JSON da API REST do Podman (as linhas do `pull` já dão as mesmas etapas). | +| [Espaço em disco do host](ideias/disco-do-host.md) | **Feito 2026-10-01**, só diagnóstico | `io-error` já era explicado como pausa desde 2026-09-29. Agora `Status.Warning` (omitido quando vazio) avisa com menos de 4 GiB livres no disco do estado das Machines, com a Machine parada (antes do Start) ou rodando: "only 700 MiB free on this computer: the Machine pauses if it runs out". Aparece no card (`statusWarningLabel`) e no `omavm status`. É aviso, não promessa: o guest pode escrever mais do que está livre a qualquer momento. O limite não compara com o crescimento possível do qcow2, porque com o disco esparso de 1 TiB o aviso apareceria sempre. Testes: `space_test.go`, `test_lowSpaceWarning`. | | [Acessibilidade](ideias/acessibilidade.md) | **Próxima — P1** | Completar nomes, estados e ordem de foco; conferir com teclado e leitor de tela numa sessão real. | | [Ambientes no launcher](ideias/ambientes-no-launcher.md) | **Próxima — P2** | Validar uma entrada `.desktop` por ambiente, abertura da Box sem TTY e limpeza de atalhos ao remover/renomear. | -| [Cor no terminal da Box](ideias/terminal-ptyxis.md) | **Próxima — P2**, parte simples | Validar se a identificação visual ajuda a reconhecer a Box; aviso ao fechar processo e nova sessão no mesmo diretório ficam condicionais à detecção confiável do contexto. | +| [Cor no terminal da Box](ideias/terminal-ptyxis.md) | **Cor feita 2026-10-01**; o resto é condicional | Faixa de 4 px no alto do terminal da Box, na cor do ambiente (só nomes da paleta fixa; sem cor, sem faixa). Chega como `--color` pelos dois caminhos: Open na GUI e entrada do launcher, republicada quando a cor muda. Testes: `TestBoxEntryCarriesTheColor`; viewer rodado `offscreen` sem erro de QML. **Não verificado**: a aparência numa sessão real e se a faixa ajuda a reconhecer a Box. O aviso ao fechar com processo rodando e a nova sessão no mesmo diretório continuam dependendo de detectar o contexto dentro da Box (ver o arquivo da ideia). | | [Cor no Nautilus](ideias/cor-no-nautilus.md) | **Próxima — P2**, integração opcional | Confirmar que o metadado GVFS aparece no Nautilus real sem transformar falha de `gio` em falha do ambiente. | -| [CLI para agentes](ideias/cli-para-agentes.md) | **Próxima — contrato da CLI** | Definir e documentar códigos/JSON de erro antes da mudança; validar consumidores existentes, inclusive a GUI. | -| [Machine descartável](ideias/machine-descartavel.md) | **Próxima jornada de produto — P3** | Provar iniciar, usar e encerrar uma sessão sem persistência; distinguir isso de criar um ambiente novo e bloquear snapshots que sumiriam no overlay. | +| [CLI para agentes](ideias/cli-para-agentes.md) | **Feito 2026-09-30** | Códigos 0 sucesso, 1 falha, 2 entrada inválida, 3 não encontrado, 4 nome em uso, 5 indisponível, 6 ocupado (`ErrBusy`, acrescentado ao esboço); `exec`/`ssh` repassam o código do comando executado; com `--json`, `{"error": {"code", "message"}}` no stdout. Documentado no README e no `omavm help`. Consumidores conferidos: a GUI só compara com 0 e lê o stderr; a barra Quickshell trata o objeto de erro como lista vazia (0), como antes. Testes: `cmd/omavm/errors_test.go`; exercitado com o binário real. | +| [Machine descartável](ideias/machine-descartavel.md) | **Feito 2026-09-30** para Machines existentes | `omavm start NAME --ephemeral` e "Start Without Keeping Changes" no card (inicia e abre); capability opcional `core.EphemeralStarter`, `Status.Ephemeral` (omitido quando falso, goldens inalterados); QEMU `-snapshot` com `TMPDIR` no diretório da Machine (o overlay cresce no mesmo disco que o `io-error` já explica). Snapshots recusados (`ErrUnsupported`) durante a sessão, e o SnapshotsDialog diz por quê; iniciar descartável sobre uma sessão normal rodando é recusado; Restart preserva o modo. Validado com QEMU 11 real sem guest: overlay `vl.*` apagado no diretório da Machine, status, recusa de snapshot (código 5) e de sessão normal (código 2). **Não verificado**: Restart preservando o modo com QEMU real (sem guest, o desligamento ACPI não termina) e uso com um guest instalado. **`omavm run --ephemeral` feito 2026-10-01** (liberado pelo usuário): `Service.RunEphemeral` cria a Machine com o launcher desligado, inicia sem guardar mudanças, abre a tela (ou não, com `--no-open`), espera o `Status` dar `stopped` (a CLI fica esperando, sem daemon) e apaga; Ctrl+C/SIGTERM faz Force Stop e apaga, porque nada dela seria guardado. Validado com o QEMU real: `-snapshot`, nenhuma entrada no launcher, `quit` no QMP → apagada; SIGINT → apagada, nenhum QEMU sobrando. Testes: `run_test.go` (com `-race`). Box descartável continua fora: as Backend Rules a reservam ao modo Disposable sobre containers diretos. | | [SSH por vsock](ideias/vsock-ssh.md) | **Condicional — P3** | Validar guest systemd, autenticação e alcance por processos do host/Boxes; manter dispositivo opt-in e expor indisponibilidade em outros guests. | | [Arquivar e exportar/importar](ideias/arquivar-e-exportar.md) | **Condicional — P3** | Demonstrar necessidade de portabilidade/backup independente; decidir manifesto, snapshots, firmware, espaço temporário e recuperação de falha antes do formato. | | [Redimensionar e compactar disco](ideias/disco-do-host.md) | **Condicional — P3** | Separar crescimento de disco, expansão no guest e compactação; testar espaço temporário, snapshots e restauração antes de reescrever imagens. | | [Limites e Travel Mode para Boxes](ideias/box-limites-e-travel-mode.md) | **Condicional — P3** | Medir ganho na bateria e validar cgroups/`podman update` sem perder estado nem produzir OOM surpreendente. | | [Pasta compartilhada automática](ideias/pasta-compartilhada-automatica.md) | **Condicional — P3** | Validar um guest Linux suportado e o ajudante opt-in; manter instrução de montagem manual para os demais. | | [Windows 11 com TPM/Secure Boot](ideias/windows11-tpm-secureboot.md) | **Condicional — P3** | Validar instalação concreta; definir firmware/NVRAM e estado do TPM por Machine nova, sem alterar o boot das existentes. | -| [Ações de Box e Distrobox v2](ideias/boxes-distrobox.md) | **Condicional — P3** | Validar demanda por Clone/Upgrade/uso; testar exportação de apps no v2 quando houver versão estável ou usuário do RC. | +| [Ações de Box e Distrobox v2](ideias/boxes-distrobox.md) | **Clone e Atualizar feitos 2026-10-01** (liberados pelo usuário); uso de CPU/memória e Distrobox v2 continuam condicionais | **Clone** (Box e Machine): `core.Cloner`, `Service.Clone` (reserva o nome como na criação e segura o lock da origem durante a cópia; a cópia herda kind, imagem, configurações e, numa Machine, os snapshots do disco). Box: `distrobox create --clone`, com a Box parada; a imagem de commit que o Distrobox cria (`omavm-…:DATA`) é apagada junto com o clone e recusada, sem dano, enquanto outro clone a usa. Machine: `cp --reflink=auto --sparse=always` do qcow2 parado, depois de checar o espaço livre contra o que o disco ocupa (+1 GiB). CLI `omavm clone NOME NOVO`; GUI "Clone…" com o custo dito antes (UX #10) e "pare primeiro" quando roda. **Atualizar** (Box): `core.Upgrader`, `distrobox upgrade`, cada linha do gerenciador de pacotes vira etapa no card; CLI `omavm update NOME`; GUI "Update System". Validado com o QEMU, o Distrobox e o Podman reais (armazenamento isolado): clone de Machine com snapshot e boot; clone de Box com arquivo de sistema preservado e imagem de commit removida com o clone; update do alpine com as linhas do `apk`. Testes: `clone_test.go` (Core e QEMU), `upgrade_test.go`, `TestIsCloneImage`, `tst_clonedialog.qml`. Fora: clone vinculado (linked) de Machine e o uso de CPU/memória por Box. | | [Preview e damage no display D-Bus](ideias/display-dbus.md) | **Condicional — P2/P3** | Reproduzir preview ausente em guest GL e medir custo do redraw antes de ampliar o viewer; registrar limites atuais de USB/clipboard de imagens. | | [Logs no journal](ideias/logs-no-journal.md) | **Condicional — manutenção** | Mostrar ganho concreto de diagnóstico; definir migração do destino documentado e fallback antes de trocar o log atual. | | [GPU native context](ideias/gpu-native-context.md) | **Adiar — compatibilidade** | Testar em hardware e guest suportados e medir ganho sobre Venus; não inferir suporte no host Intel atual. | diff --git a/docs/discovery.md b/docs/discovery.md index d65624e..3a0aa30 100644 --- a/docs/discovery.md +++ b/docs/discovery.md @@ -9,7 +9,7 @@ Estes itens são hipóteses de evolução. Cada um exige um caso de uso demonstr - [ ] **Instalação mais assistida:** avaliar catálogo pequeno de imagens e download verificável, com origem, tamanho, licença e recuperação de falhas; manter ISO local como caminho completo. - [ ] **Blend Mode para Machines:** demonstrar um fluxo real de aplicação integrada antes de definir infraestrutura. A base de exportação das Boxes não comprova viabilidade para Machines; evitar duplicar indicadores de sistema do host. - [ ] **Transferência de arquivos e arrastar/soltar:** escolher uma combinação host/guest suportada, testar permissões e falhas e preferir capacidades existentes a um protocolo próprio. -- [ ] **Clone e recuperação mais guiada:** validar demanda e capacidades do backend; explicar consumo de disco e dependências antes de oferecer modalidades de clone. +- [ ] **Clone e recuperação mais guiada:** clone completo feito em 2026-10-01 (ver a triagem em `TODO.md`); falta o vinculado e a recuperação guiada. validar demanda e capacidades do backend; explicar consumo de disco e dependências antes de oferecer modalidades de clone. - [ ] **Organização de grandes listas:** validar necessidade de favoritos, grupos e reordenação; quando implementados, persistir o comportamento de verdade. - [ ] **Integrações adicionais:** avaliar áudio, dispositivos e múltiplos monitores por jornada concreta, deixando explícita a matriz de suporte. Não assumir paridade com o Parallels por adotar sua referência de UX. diff --git a/docs/ideias/README.md b/docs/ideias/README.md index 2eea57a..7cc3831 100644 --- a/docs/ideias/README.md +++ b/docs/ideias/README.md @@ -15,21 +15,21 @@ motivo para desligar. | SSH e port forwarding via vsock | **SSH feito 2026-09-28**, ligado por padrão com o custo dito na tela; port forwarding não | [vsock-ssh.md](vsock-ssh.md) | | GPU por native context | Encaixa depois do Venus; hoje só AMD | [gpu-native-context.md](gpu-native-context.md) | | Windows 11 sem ajustes manuais (TPM + Secure Boot) | Encaixa, com cuidado: a OmaVM não é "exclusiva para Windows" | [windows11-tpm-secureboot.md](windows11-tpm-secureboot.md) | -| Distrobox v2 e ações de Box (Clone, Atualizar, uso) | Risco real no export de apps; Clone já é meta do Experience Center | [boxes-distrobox.md](boxes-distrobox.md) | +| Distrobox v2 e ações de Box (Clone, Atualizar, uso) | **Clone (Box e Machine) e Atualizar feitos 2026-10-01**; uso e Distrobox v2 não | [boxes-distrobox.md](boxes-distrobox.md) | | Próximos passos do display D-Bus | Encaixa: refina o viewer atual | [display-dbus.md](display-dbus.md) | | Ambientes no launcher do Omarchy (`.desktop` por ambiente) | **Feito 2026-09-28**, opt-out | [ambientes-no-launcher.md](ambientes-no-launcher.md) | | Terminal da Box sobre libvterm (MIT, usado pelo Qt Creator) | Encaixa, mas é decisão de arquitetura: pede acordo antes | [terminal-libvterm.md](terminal-libvterm.md) | | Copiar do terminal da Box (seleção e OSC 52 só de escrita) | **Feito 2026-09-28**; OSC 52 opt-out | [terminal-copiar.md](terminal-copiar.md) | -| Terminal da Box à la Ptyxis (aviso ao fechar, cor do ambiente, nova sessão no mesmo diretório) | Encaixa: melhora o terminal atual sem daemon | [terminal-ptyxis.md](terminal-ptyxis.md) | -| CLI para agentes: códigos de saída por classe de erro e erros em JSON | Encaixa: agentes são meta do `CLAUDE.md`; muda contrato, documentar antes | [cli-para-agentes.md](cli-para-agentes.md) | +| Terminal da Box à la Ptyxis (aviso ao fechar, cor do ambiente, nova sessão no mesmo diretório) | **Cor feita 2026-10-01** (faixa no alto do terminal); aviso ao fechar e nova sessão não | [terminal-ptyxis.md](terminal-ptyxis.md) | +| CLI para agentes: códigos de saída por classe de erro e erros em JSON | **Feito 2026-09-30** (códigos 0–6, `exec`/`ssh` repassam o código do comando, erro em JSON com `--json`; README "Exit codes") | [cli-para-agentes.md](cli-para-agentes.md) | | Limites de CPU/memória e Travel Mode para Boxes (`podman update`) | **Travel Mode feito 2026-09-28**; limites fixos não | [box-limites-e-travel-mode.md](box-limites-e-travel-mode.md) | | Pasta compartilhada que monta sozinha no guest (tags virtiofs no sysfs) | Encaixa, opt-in no guest; sem agente próprio | [pasta-compartilhada-automatica.md](pasta-compartilhada-automatica.md) | | Cor do ambiente visível no Nautilus (metadados do GVFS em vez do xattr) | **Feito 2026-09-28** | [cor-no-nautilus.md](cor-no-nautilus.md) | | Arquivar (liberar espaço) e exportar/importar ambientes | Encaixa; o formato do manifesto esbarra numa decisão em aberto | [arquivar-e-exportar.md](arquivar-e-exportar.md) | -| Progresso ao criar uma Box (pull separado, fora do lock do registro) | Encaixa: melhora UX e reduz o tempo com o registro travado | [progresso-ao-criar-box.md](progresso-ao-criar-box.md) | +| Progresso ao criar uma Box (pull separado, fora do lock do registro) | **Feito 2026-10-01** (etapas do pull no card e na CLI; o lock já não cobria o create desde 2026-09-29) | [progresso-ao-criar-box.md](progresso-ao-criar-box.md) | | Logs no journal do systemd (protocolo nativo, sem dependência) | Encaixa: substitui a rotação própria pelo journald | [logs-no-journal.md](logs-no-journal.md) | | Acessibilidade: leitor de tela (Orca/AT-SPI) e navegação por teclado | Encaixa: revisão com testes em `make test-qml` | [acessibilidade.md](acessibilidade.md) | | Lista de ambientes como `QAbstractListModel` no C++ | Opcional: a correção em QML já resolve o bug; vale se crescer | [modelo-de-ambientes-em-cpp.md](modelo-de-ambientes-em-cpp.md) | | Catálogo de sistemas para baixar | Conflita com o non-goal "dezenas de distros pré-empacotadas" | [catalogo-de-imagens.md](catalogo-de-imagens.md) | -| Espaço em disco do host; redimensionar e compactar o disco | Encaixa: pequeno, melhora a experiência | [disco-do-host.md](disco-do-host.md) | -| Machine descartável (`-snapshot` do QEMU) | Encaixa: ambientes descartáveis já são meta do `CLAUDE.md` | [machine-descartavel.md](machine-descartavel.md) | +| Espaço em disco do host; redimensionar e compactar o disco | **Aviso de pouco espaço feito 2026-10-01**; redimensionar/compactar não | [disco-do-host.md](disco-do-host.md) | +| Machine descartável (`-snapshot` do QEMU) | **Feito 2026-09-30** para Machines existentes (`start --ephemeral`, menu do card); `omavm run --ephemeral` feito 2026-10-01 | [machine-descartavel.md](machine-descartavel.md) | diff --git a/docs/ideias/disco-do-host.md b/docs/ideias/disco-do-host.md index 79b629f..1049f52 100644 --- a/docs/ideias/disco-do-host.md +++ b/docs/ideias/disco-do-host.md @@ -15,6 +15,8 @@ card mostra só "Error". ## Esboço +**Aviso de pouco espaço implementado (2026-10-01)**: abaixo de 4 GiB livres, o card e `omavm status` avisam que a Machine pausa se o espaço acabar, antes do Start e com ela rodando. Não compara com o crescimento possível do qcow2: com 1 TiB esparso, isso avisaria sempre. + **Primeiro item implementado (2026-09-29)**, junto com o disco padrão de 1 TiB esparso: um `io-error` aparece como pausa com o motivo ("o disco deste computador está cheio; libere espaço e retome"), e Resume continua a diff --git a/docs/ideias/terminal-ptyxis.md b/docs/ideias/terminal-ptyxis.md index e95f500..f4636b4 100644 --- a/docs/ideias/terminal-ptyxis.md +++ b/docs/ideias/terminal-ptyxis.md @@ -34,6 +34,8 @@ decisão antes de implementar. ## 2. Cor do ambiente na janela +**Feito (2026-10-01)**: uma faixa de 4 px no alto do terminal, na cor do ambiente, quando ele tem uma. Vem por `--color` do Open da GUI e da entrada do launcher. + O Ptyxis muda a cor da barra conforme a sessão (container, root). A OmaVM já tem cor por ambiente (Color tags). Mostrar essa cor no terminal (uma faixa fina ou o fundo da barra de status) deixa claro em qual Box se está, diff --git a/gui/AppsDialog.qml b/gui/AppsDialog.qml index 09063de..9eac4e3 100644 --- a/gui/AppsDialog.qml +++ b/gui/AppsDialog.qml @@ -12,6 +12,25 @@ Dialog { // landing after the user has switched to another one (docs/TODO.md P0). readonly property bool matches: backend.appsEnvironment === environment.name property bool requested: false + // The application an export or removal is running for, and how the + // last one ended: each row says what is happening to it, and a failure + // keeps the row and offers the same action again. + property string pendingId: "" + property string pendingName: "" + property bool pendingExport: false + property string resultText: "" + property bool resultFailed: false + + function act(app) { + pendingId = app.id + pendingName = app.name + pendingExport = !app.exported + resultText = "" + if (pendingExport) + backend.exportApp(environment.name, app.id) + else + backend.unexportApp(environment.name, app.id) + } title: qsTr("%1 Applications").arg(environment.name || qsTr("Environment")) modal: true anchors.centerIn: parent @@ -21,6 +40,8 @@ Dialog { Overlay.modal: ThemeScrim {} onOpened: { + pendingId = "" + resultText = "" requested = false if (!dialog.busy) { requested = true @@ -30,6 +51,15 @@ Dialog { Connections { target: backend + function onActionFinished(tag, ok, text) { + if ((tag !== "apps-export" && tag !== "apps-unexport") || dialog.pendingId === "") + return + dialog.resultFailed = !ok + dialog.resultText = !ok ? text + : dialog.pendingExport ? qsTr("“%1” is in the app menu.").arg(dialog.pendingName) + : qsTr("“%1” was removed from the app menu; it is still installed in %2.").arg(dialog.pendingName).arg(dialog.environment.name) + dialog.pendingId = "" + } function onBusyChanged() { if (!dialog.visible || dialog.busy || dialog.requested) return @@ -49,9 +79,18 @@ Dialog { wrapMode: Text.Wrap } + Label { + objectName: "resultLabel" + Layout.fillWidth: true + visible: dialog.resultText !== "" + text: dialog.resultText + color: dialog.resultFailed ? backend.themeRed : backend.themeGreen + wrapMode: Text.Wrap + } + RowLayout { Layout.fillWidth: true - visible: dialog.matches && dialog.busy + visible: dialog.matches && dialog.busy && dialog.pendingId === "" spacing: 8 BusyIndicator { implicitWidth: 18; implicitHeight: 18; running: true } Label { text: qsTr("Refreshing…"); color: backend.themeMuted; font.pixelSize: 12 } @@ -120,7 +159,9 @@ Dialog { } delegate: Pane { id: appRow + objectName: "appRow-" + modelData.name required property var modelData + readonly property bool pending: dialog.pendingId === modelData.id width: ListView.view.width Material.elevation: rowHover.hovered ? 2 : 1 Material.background: backend.themeSurface @@ -137,21 +178,43 @@ Dialog { color: modelData.exported ? backend.themeGreen : backend.themeMuted iconSize: 20 } - Label { + ColumnLayout { Layout.fillWidth: true - text: modelData.name - elide: Text.ElideRight + spacing: 0 + Label { + Layout.fillWidth: true + text: modelData.name + elide: Text.ElideRight + } + // In words, not only the icon's color. + Label { + Layout.fillWidth: true + visible: modelData.exported || appRow.pending + text: appRow.pending + ? (dialog.pendingExport ? qsTr("Adding to the app menu…") : qsTr("Removing from the app menu…")) + : qsTr("In the app menu") + color: backend.themeMuted + font.pixelSize: 12 + elide: Text.ElideRight + } + } + BusyIndicator { + visible: appRow.pending + running: visible + implicitWidth: 24 + implicitHeight: 24 } Button { + objectName: "appAction" + visible: !appRow.pending // "Remove from menu", never bare "Remove": this only // undoes the launcher shortcut, the app stays // installed in the Box (docs/TODO.md P1). text: modelData.exported ? qsTr("Remove from menu") : qsTr("Export") highlighted: !modelData.exported + Accessible.name: (modelData.exported ? qsTr("Remove %1 from the app menu") : qsTr("Export %1")).arg(modelData.name) enabled: !dialog.busy - onClicked: modelData.exported - ? backend.unexportApp(dialog.environment.name, modelData.id) - : backend.exportApp(dialog.environment.name, modelData.id) + onClicked: dialog.act(modelData) } } } diff --git a/gui/CloneDialog.qml b/gui/CloneDialog.qml new file mode 100644 index 0000000..b044c67 --- /dev/null +++ b/gui/CloneDialog.qml @@ -0,0 +1,101 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Controls.Material +import QtQuick.Layouts + +// Clone: a full, independent copy of a stopped environment. Says what is +// copied and what it costs before anything happens (UX Principle #10). +Dialog { + id: dialog + objectName: "cloneDialog" + property var environment: ({}) + readonly property bool machine: environment.kind === "machine" + readonly property bool stopped: environment.status === "stopped" + property bool submitting: false + property string errorText: "" + title: qsTr("Clone %1").arg(environment.name || "") + modal: true + anchors.centerIn: parent + width: Math.min(parent.width - 32, 460) + Overlay.modal: ThemeScrim {} + + onOpened: { + newName.text = qsTr("%1 copy").arg(environment.name || "") + newName.selectAll() + newName.forceActiveFocus() + errorText = "" + submitting = false + } + + Connections { + target: backend + function onActionFinished(tag, ok, text) { + if (tag !== "clone" || !dialog.submitting) return + dialog.submitting = false + if (ok) + dialog.close() + else + dialog.errorText = text + } + } + + ColumnLayout { + anchors.fill: parent + spacing: 12 + Label { + objectName: "cloneCost" + Layout.fillWidth: true + wrapMode: Text.Wrap + color: backend.themeMuted + text: dialog.machine + ? qsTr("Copies the whole disk of %1, snapshots included. It needs as much free space as that disk uses now (on btrfs the copy shares space until one of them changes). The copy is independent: changing one never touches the other.").arg(dialog.environment.name || "") + : qsTr("Copies the system of %1: its installed packages and files outside your home folder. Your home folder is shared with this computer, not copied. The copy is independent: changing one never touches the other.").arg(dialog.environment.name || "") + } + Label { + objectName: "stopFirst" + Layout.fillWidth: true + visible: !dialog.stopped + wrapMode: Text.Wrap + color: backend.themeAccentText + text: dialog.machine ? qsTr("Shut %1 down first: a running system can't be copied.").arg(dialog.environment.name || "") + : qsTr("Stop %1 first: a running Box can't be copied.").arg(dialog.environment.name || "") + } + TextField { + id: newName + objectName: "cloneName" + Layout.fillWidth: true + Accessible.name: qsTr("Name of the copy") + placeholderText: qsTr("Name of the copy") + selectByMouse: true + enabled: !dialog.submitting + onAccepted: cloneButton.clicked() + } + Label { + Layout.fillWidth: true + visible: dialog.errorText !== "" + text: dialog.errorText + color: backend.themeRed + wrapMode: Text.Wrap + } + RowLayout { + Layout.alignment: Qt.AlignRight + Button { + text: qsTr("Cancel") + flat: true + onClicked: dialog.close() + } + Button { + id: cloneButton + objectName: "cloneButton" + text: dialog.submitting ? qsTr("Cloning…") : qsTr("Clone") + highlighted: true + enabled: dialog.stopped && !dialog.submitting && newName.text.trim().length > 0 + onClicked: { + dialog.errorText = "" + dialog.submitting = true + backend.cloneEnvironment(dialog.environment.name, newName.text.trim()) + } + } + } + } +} diff --git a/gui/CreateDialog.qml b/gui/CreateDialog.qml index f75756b..9f449d7 100644 --- a/gui/CreateDialog.qml +++ b/gui/CreateDialog.qml @@ -19,6 +19,8 @@ Dialog { property bool machine: true property string errorText: "" property bool submitting: false + // Created and listed: the window offers to open it right away. + signal created(string name, string kind) property string nameError: "" property bool nameTouched: false // Same reasoning as SettingsDialog.qml's cpusTouched/memoryTouched: @@ -89,7 +91,15 @@ Dialog { // fade — a small touch that makes the wizard read as a sequence // rather than a stack of unrelated screens. property int animatingFromStep: 0 - onOpened: resetForm() + onOpened: { + resetForm() + backend.refreshHost() + } + // Said before anything is created: without hardware virtualization a + // Desktop can be created but won't start. Unknown (no answer from the + // CLI yet) says nothing. + readonly property var kvm: backend.hostCapabilities ? backend.hostCapabilities["kvm"] : undefined + readonly property bool kvmMissing: !!kvm && kvm.available === false onStepChanged: { const forward = step > animatingFromStep animatingFromStep = step @@ -112,6 +122,7 @@ Dialog { if (ok) { dialog.errorText = "" dialog.close() + dialog.created(name.text.trim(), dialog.machine ? "machine" : "box") } else { dialog.errorText = text } @@ -169,7 +180,9 @@ Dialog { Layout.fillWidth: true // The card's text is drawn by its own contentItem. Accessible.name: qsTr("Desktop") - Accessible.description: qsTr("A complete system with its own kernel, from an installation ISO") + Accessible.description: dialog.kvmMissing + ? qsTr("A complete system with its own kernel, from an installation ISO. This computer can't start one yet: hardware virtualization isn't available.") + : qsTr("A complete system with its own kernel, from an installation ISO") checkable: true checked: dialog.machine padding: 16 @@ -212,6 +225,16 @@ Dialog { font.pixelSize: 12 color: backend.themeMuted } + Label { + objectName: "kvmWarning" + Layout.fillWidth: true + visible: dialog.kvmMissing + text: qsTr("This computer can't start Desktops yet: hardware virtualization isn't available to your user. %1.") + .arg(dialog.kvm && dialog.kvm.hint ? dialog.kvm.hint : qsTr("Enable virtualization in the firmware")) + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + color: backend.themeRed + } } onClicked: dialog.machine = true } @@ -329,6 +352,7 @@ Dialog { } TextField { id: name + objectName: "nameField" Layout.fillWidth: true Accessible.name: qsTr("Environment name") placeholderText: qsTr("Environment name") diff --git a/gui/EnvironmentCard.qml b/gui/EnvironmentCard.qml index aca9863..69a4654 100644 --- a/gui/EnvironmentCard.qml +++ b/gui/EnvironmentCard.qml @@ -11,6 +11,7 @@ Pane { signal settingsRequested(var environment) signal snapshotsRequested(var environment) signal appsRequested(var environment) + signal cloneRequested(var environment) // An action of this OmaVM window is running on this environment; // others stay usable meanwhile. readonly property bool busy: !!(backend.busyEnvironments && backend.busyEnvironments[environment.name]) @@ -24,6 +25,44 @@ Pane { // it still has to be stoppable from here. readonly property bool unresponsive: environment.status === "unknown" readonly property bool active: running || paused || transitioning || failed || unresponsive + // The system it runs, readable (UX Principle #5: name, distro, kind, + // status): a Box's image without registry, "-toolbox" or a "latest" + // tag, a Desktop's installation image without its path. + function systemName(env) { + const image = (env && env.image) || "" + if (!image) + return "" + if (env.kind === "machine") { + const file = image.split("/").pop() + return file.replace(/\.iso$/i, "") + } + const known = { fedora: "Fedora", ubuntu: "Ubuntu", debian: "Debian", archlinux: "Arch Linux", + arch: "Arch Linux", alpine: "Alpine", opensuse: "openSUSE", centos: "CentOS", + rockylinux: "Rocky Linux", almalinux: "AlmaLinux" } + let ref = image.split("@")[0] + let tag = "" + const colon = ref.lastIndexOf(":") + if (colon > ref.lastIndexOf("/")) { + tag = ref.slice(colon + 1) + ref = ref.slice(0, colon) + } + let repo = ref.split("/").pop().replace(/-toolbox$/, "") + repo = known[repo] || repo + return tag && tag !== "latest" ? repo + " " + tag : repo + } + readonly property bool machine: environment.kind === "machine" + // The primary action names what the person will see after the click + // (docs/TODO.md P1): a stopped Box's click opens its terminal, so it + // says Open; a stopped Desktop boots first, so Start — and both say + // the rest in the hint. + readonly property string primaryLabel: paused ? qsTr("Resume") + : stopped && machine ? qsTr("Start") + : qsTr("Open") + readonly property string primaryHint: paused ? qsTr("Continue %1 where it was paused").arg(environment.name) + : stopped && machine ? qsTr("Start %1 and show its screen").arg(environment.name) + : stopped ? qsTr("Start %1 and open its terminal").arg(environment.name) + : machine ? qsTr("Show the screen of %1").arg(environment.name) + : qsTr("Open a terminal in %1").arg(environment.name) readonly property color statusColor: failed || unresponsive ? backend.themeRed : running ? backend.themeGreen : paused || transitioning ? backend.themeAccentText @@ -86,18 +125,31 @@ Pane { color: card.environment.settings ? card.environment.settings.color || "transparent" : "transparent" } Label { + id: nameLabel + objectName: "nameLabel" Layout.fillWidth: true text: card.environment.name font.pixelSize: 19 font.weight: Font.DemiBold elide: Text.ElideRight + // A long name cut short is still readable in full. + HoverHandler { id: nameHover } + ToolTip.text: card.environment.name + ToolTip.visible: nameHover.hovered && nameLabel.truncated + ToolTip.delay: 400 } } Label { + objectName: "kindLabel" Layout.fillWidth: true visible: card.width >= 430 - text: card.environment.kind === "machine" ? qsTr("Desktop") : qsTr("Development Box") + text: { + const kind = card.environment.kind === "machine" ? qsTr("Desktop") : qsTr("Development Box") + const system = card.systemName(card.environment) + return system ? kind + " · " + system : kind + } color: backend.themeMuted + elide: Text.ElideRight } Label { Layout.fillWidth: true @@ -150,6 +202,56 @@ Pane { color: card.statusColor wrapMode: Text.WordWrap } + // Before it happens: the host's disk is nearly full, and the + // Machine would pause when it runs out. + Label { + objectName: "statusWarningLabel" + Layout.fillWidth: true + visible: !card.paused && !!card.environment.statusWarning + text: card.environment.statusWarning || "" + color: backend.themeRed + wrapMode: Text.WordWrap + } + // What the running session got differs from its settings: the + // saved ones wait for a restart, or Travel Mode trimmed CPUs. + Label { + objectName: "restartNeededLabel" + Layout.fillWidth: true + visible: card.active && !!card.environment.restartNeeded + text: qsTr("Restart to apply the saved settings") + color: backend.themeAccentText + wrapMode: Text.WordWrap + } + Label { + objectName: "travelModeLabel" + Layout.fillWidth: true + visible: card.active && !!card.environment.travelMode + text: qsTr("Travel Mode: started with fewer processors because this computer was on battery") + color: backend.themeMuted + wrapMode: Text.WordWrap + } + // The stage a long creation reported (which image layer is + // downloading): a real step, never an invented percentage. + Label { + objectName: "progressLabel" + readonly property string stage: (backend.progress && backend.progress[card.environment.name]) || "" + Layout.fillWidth: true + visible: stage !== "" + text: stage + color: backend.themeMuted + wrapMode: Text.WordWrap + Accessible.role: Accessible.StaticText + Accessible.name: stage + } + // Never hidden by width: it says what shutting down will lose. + Label { + objectName: "ephemeralLabel" + Layout.fillWidth: true + visible: card.active && !!card.environment.ephemeral + text: qsTr("Changes in this session are discarded when it shuts down") + color: backend.themeAccentText + wrapMode: Text.WordWrap + } Label { Layout.fillWidth: true visible: card.environment.kind === "machine" && card.width >= 520 && !!card.environment.guestAgent @@ -169,13 +271,14 @@ Pane { // every card must offer (docs/TODO.md P1). Below 500px it shrinks // to an icon-only button instead of disappearing into the menu. readonly property bool compact: card.width < 500 - readonly property string label: card.running || card.failed || card.unresponsive ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start") - text: label + text: card.primaryLabel icon.source: "qrc:/icons/play.svg" display: compact ? AbstractButton.IconOnly : AbstractButton.TextOnly - Accessible.name: label - ToolTip.text: label - ToolTip.visible: compact && hovered + Accessible.name: card.primaryLabel + Accessible.description: card.primaryHint + ToolTip.text: card.primaryHint + ToolTip.visible: hovered + ToolTip.delay: 600 highlighted: true enabled: !card.transitioning && !card.busy onClicked: card.paused ? backend.resume(card.environment.name) @@ -192,11 +295,22 @@ Pane { objectName: "actionsMenu" y: parent.height MenuItem { - text: card.running || card.failed || card.unresponsive ? qsTr("Open") : card.paused ? qsTr("Resume") : qsTr("Start") + text: card.primaryLabel + Accessible.description: card.primaryHint enabled: !card.transitioning && !card.busy onTriggered: card.paused ? backend.resume(card.environment.name) : backend.open(card.environment.name, card.environment.kind) } + MenuItem { + objectName: "startEphemeralItem" + // Try something (an installer, a reproduction) and get + // the Desktop back exactly as it was at shutdown. + text: qsTr("Start Without Keeping Changes") + visible: card.environment.kind === "machine" && !card.active + height: visible ? implicitHeight : 0 + enabled: !card.transitioning && !card.busy + onTriggered: backend.openEphemeral(card.environment.name) + } // A hidden MenuItem keeps its height in a Qt Quick Menu, so each // kind-specific item collapses itself (see tst_environmentcard.qml). MenuItem { @@ -212,6 +326,17 @@ Pane { MenuSeparator {} MenuItem { text: qsTr("Snapshots…"); visible: card.environment.kind === "machine"; height: visible ? implicitHeight : 0; onTriggered: card.snapshotsRequested(card.environment) } MenuItem { text: qsTr("Applications…"); visible: card.environment.kind !== "machine"; height: visible ? implicitHeight : 0; onTriggered: card.appsRequested(card.environment) } + // Long (the package manager downloads updates); its lines + // show on the card as it goes. + MenuItem { + objectName: "updateItem" + text: qsTr("Update System") + visible: card.environment.kind !== "machine" + height: visible ? implicitHeight : 0 + enabled: !card.busy && !card.transitioning + onTriggered: backend.updateEnvironment(card.environment.name) + } + MenuItem { text: qsTr("Clone…"); enabled: !card.busy && !card.transitioning; onTriggered: card.cloneRequested(card.environment) } MenuItem { text: qsTr("Settings…"); onTriggered: card.settingsRequested(card.environment) } MenuItem { text: qsTr("Delete…"); enabled: !card.busy; onTriggered: card.removeRequested(card.environment.name) } } diff --git a/gui/Main.qml b/gui/Main.qml index 6741127..ab05643 100644 --- a/gui/Main.qml +++ b/gui/Main.qml @@ -128,6 +128,10 @@ ApplicationWindow { appsDialog.environment = environment appsDialog.open() } + onCloneRequested: environment => { + cloneDialog.environment = environment + cloneDialog.open() + } } } } @@ -178,8 +182,44 @@ ApplicationWindow { visible: opacity > 0 Behavior on opacity { NumberAnimation { duration: 150; easing.type: Easing.OutCubic } } } - CreateDialog { id: createDialog } + CreateDialog { + id: createDialog + onCreated: (name, kind) => { + firstUse.environmentName = name + firstUse.environmentKind = kind + firstUse.open() + } + } + // Creation leads to first use (docs/TODO.md P1): the terminal or the + // installer is one click away, and "Later" leaves the new card ready. + // backend.open refuses a second click while the first is running, so + // this never starts a second copy. + Dialog { + id: firstUse + objectName: "firstUseDialog" + property string environmentName + property string environmentKind + readonly property bool machine: environmentKind === "machine" + title: qsTr("“%1” is ready").arg(environmentName) + modal: true + anchors.centerIn: parent + width: Math.min(parent.width - 32, 420) + standardButtons: Dialog.Cancel | Dialog.Ok + Component.onCompleted: { + standardButton(Dialog.Cancel).text = qsTr("Later") + } + onAboutToShow: standardButton(Dialog.Ok).text = machine ? qsTr("Start Installer") : qsTr("Open Terminal") + Overlay.modal: ThemeScrim {} + contentItem: Label { + text: firstUse.machine + ? qsTr("Start it now to boot the installation media. When the installation is done, shut it down and disconnect the media in Settings.") + : qsTr("Open its terminal now, or later from its card or the app launcher.") + wrapMode: Text.Wrap + } + onAccepted: backend.open(environmentName, environmentKind) + } SettingsDialog { id: settingsDialog } + CloneDialog { id: cloneDialog } SnapshotsDialog { id: snapshotsDialog } AppsDialog { id: appsDialog } Dialog { diff --git a/gui/SettingsDialog.qml b/gui/SettingsDialog.qml index a36f3ee..56d4d09 100644 --- a/gui/SettingsDialog.qml +++ b/gui/SettingsDialog.qml @@ -61,6 +61,7 @@ Dialog { selectedColor = settings.color || "" // Opt-out: absent/false in the JSON means "not disabled", i.e. on. shareClipboard.checked = !settings.clipboard_disabled + clipboardDirection.currentIndex = Math.max(0, ["both", "to-host", "to-guest"].indexOf(settings.clipboard_direction || "both")) travelMode.checked = !settings.travel_mode_disabled vulkan.checked = !settings.vulkan_disabled launcher.checked = !settings.launcher_disabled @@ -270,9 +271,26 @@ Dialog { : qsTr("Let programs in the Box copy to your clipboard") ToolTip.visible: hovered ToolTip.text: dialog.machine - ? qsTr("Requires spice-vdagent in the guest desktop. Restart the Machine to apply a change.") + ? qsTr("Requires spice-vdagent in the guest desktop. Reopen the Machine's window to apply a change.") : qsTr("Programs like Neovim and tmux can copy text straight to the clipboard. They can never read it. Applies to terminals opened after saving.") } + // One way only, when copying in one direction shouldn't happen + // (a guest that must not see what this computer copies, say). + ComboBox { + id: clipboardDirection + objectName: "clipboardDirection" + visible: dialog.machine && shareClipboard.checked + Layout.fillWidth: true + Layout.leftMargin: 32 + Accessible.name: qsTr("Clipboard direction") + textRole: "text" + valueRole: "value" + model: [ + { value: "both", text: qsTr("Both ways") }, + { value: "to-host", text: qsTr("Only from the guest to this computer") }, + { value: "to-guest", text: qsTr("Only from this computer to the guest") } + ] + } CheckBox { id: travelMode text: qsTr("Travel Mode: reduce CPUs automatically on battery") @@ -320,6 +338,51 @@ Dialog { ToolTip.text: qsTr("Leave fullscreen with Hyprland's own fullscreen key. A window rule of your own for OmaVM's viewer takes precedence.") } + // What works with the guest right now, checked on the guest side + // where OmaVM can (internal/backend/qemu/guestcaps.go), and the + // next step for the rest — in text, not only in a tooltip. + Label { + visible: dialog.machine && guestRepeater.count > 0 + text: qsTr("Working with the guest") + font.pixelSize: 18 + font.weight: Font.DemiBold + } + Repeater { + id: guestRepeater + model: dialog.machine ? (dialog.environment.guestCapabilities || []) : [] + ColumnLayout { + id: capabilityRow + required property var modelData + objectName: "guestCapability-" + modelData.id + Layout.fillWidth: true + spacing: 2 + Label { + Layout.fillWidth: true + text: capabilityRow.modelData.label + ": " + ( + capabilityRow.modelData.state === "ready" ? qsTr("working") + : capabilityRow.modelData.state === "needs_guest_component" ? qsTr("needs a step in the guest") + : capabilityRow.modelData.state === "needs_restart" ? qsTr("applies after a restart") + : capabilityRow.modelData.state === "off" ? qsTr("off") + : qsTr("not checked yet")) + color: capabilityRow.modelData.state === "ready" ? backend.themeGreen : backend.themeForeground + wrapMode: Text.Wrap + } + // Selectable: the mount command is meant to be copied. + TextEdit { + Layout.fillWidth: true + visible: text !== "" + text: capabilityRow.modelData.hint || "" + readOnly: true + selectByMouse: true + wrapMode: Text.Wrap + color: backend.themeMuted + font.pixelSize: 12 + Accessible.role: Accessible.StaticText + Accessible.name: text + } + } + } + Label { visible: dialog.machine text: qsTr("Installation media") @@ -404,7 +467,7 @@ Dialog { onClicked: { dialog.errorText = "" dialog.submitting = true - backend.configure(environment.name, description.text.trim(), cpus.value, dialog.cpusTouched, memory.value, dialog.memoryTouched, dialog.machine, sharedPath.text.trim(), sharedReadOnly.checked, disconnectISO.checked, dialog.selectedColor, shareClipboard.checked, travelMode.checked, vulkan.checked, openInEmptyWorkspace.checked, launcher.checked, ssh.checked, fullscreen.checked) + backend.configure(environment.name, description.text.trim(), cpus.value, dialog.cpusTouched, memory.value, dialog.memoryTouched, dialog.machine, sharedPath.text.trim(), sharedReadOnly.checked, disconnectISO.checked, dialog.selectedColor, shareClipboard.checked, travelMode.checked, vulkan.checked, openInEmptyWorkspace.checked, launcher.checked, ssh.checked, fullscreen.checked, clipboardDirection.currentValue) } } } diff --git a/gui/SnapshotsDialog.qml b/gui/SnapshotsDialog.qml index dbe7e4f..ce612d8 100644 --- a/gui/SnapshotsDialog.qml +++ b/gui/SnapshotsDialog.qml @@ -15,6 +15,9 @@ Dialog { // Going to a snapshot replaces the disk, which QEMU only does with // the Machine shut down. readonly property bool canGoTo: environment.status === "stopped" + // Running without keeping changes: a snapshot would land in the + // session's throwaway disk, so none is taken or deleted until shutdown. + readonly property bool ephemeral: !!environment.ephemeral && environment.status !== "stopped" property string createError: "" property bool creating: false title: qsTr("%1 Snapshots").arg(environment.name || qsTr("Environment")) @@ -79,7 +82,7 @@ Dialog { id: createButton text: dialog.creating ? qsTr("Creating…") : qsTr("Create") highlighted: true - enabled: !dialog.creating && !dialog.busy && newLabel.text.trim().length > 0 + enabled: !dialog.creating && !dialog.busy && !dialog.ephemeral && newLabel.text.trim().length > 0 onClicked: { dialog.createError = "" dialog.creating = true @@ -113,7 +116,9 @@ Dialog { Layout.fillWidth: true visible: !dialog.canGoTo objectName: "runningHint" - text: qsTr("While %1 is running, a snapshot saves its disk as if the power had been cut, without open windows or memory. Shut it down to go to a snapshot.").arg(dialog.environment.name || "") + text: dialog.ephemeral + ? qsTr("%1 is running without keeping changes, so snapshots can't be taken or deleted until it shuts down.").arg(dialog.environment.name || "") + : qsTr("While %1 is running, a snapshot saves its disk as if the power had been cut, without open windows or memory. Shut it down to go to a snapshot.").arg(dialog.environment.name || "") color: backend.themeMuted wrapMode: Text.Wrap font.pixelSize: 12 @@ -195,7 +200,7 @@ Dialog { } ToolButton { text: qsTr("Delete") - enabled: !dialog.busy + enabled: !dialog.busy && !dialog.ephemeral onClicked: { confirmDeleteSnapshot.snapshotId = modelData.id confirmDeleteSnapshot.snapshotLabel = modelData.label diff --git a/gui/TerminalViewer.qml b/gui/TerminalViewer.qml index da70034..20b4a3a 100644 --- a/gui/TerminalViewer.qml +++ b/gui/TerminalViewer.qml @@ -24,9 +24,22 @@ Window { // Box's terminal and a Machine's display fullscreen the same way on // the same dedicated workspace without a second rule to maintain. + // The Box's color tag along the top edge, as Ptyxis colors a container + // session: which Box this is, and a reminder it isn't the host. + Rectangle { + id: colorStrip + objectName: "colorStrip" + // Only the fixed palette names (core.EnvironmentColors) are drawn. + readonly property bool known: ["red", "orange", "yellow", "green", "blue", "purple", "gray"].indexOf(terminalColor) >= 0 + anchors { left: parent.left; right: parent.right; top: parent.top } + height: known ? 4 : 0 + visible: known + color: known ? terminalColor : "transparent" + } + TerminalView { id: view - anchors.fill: parent + anchors { left: parent.left; right: parent.right; top: colorStrip.bottom; bottom: parent.bottom } focus: true envName: terminalEnvName shareClipboard: terminalShareClipboard diff --git a/gui/Viewer.qml b/gui/Viewer.qml index fa65cfd..0a475b9 100644 --- a/gui/Viewer.qml +++ b/gui/Viewer.qml @@ -2,6 +2,7 @@ import QtQuick import QtQuick.Window import QtQuick.Controls import QtQuick.Controls.Material +import QtQuick.Layouts import OmaVM 1.0 Window { @@ -26,6 +27,8 @@ Window { showFullScreen() else show() + closeHint.opacity = 1 + closeHintTimer.start() } // Clipboard sharing is a Machine Settings toggle (opt-out, on by @@ -38,30 +41,99 @@ Window { anchors.fill: parent focus: true shareClipboard: displayShareClipboard + clipboardDirection: displayClipboardDirection connectionFd: displayConnectionFd onConnectionFailed: message => { + closeHint.opacity = 0 errorLabel.text = message errorPanel.visible = true } } - Rectangle { + // The connection to the display ended (the guest shut down, QEMU went + // away, the connection failed): say so and offer the ways back, since + // in fullscreen there is no title bar to close or switch from. + Pane { id: errorPanel + objectName: "disconnectedPanel" anchors.centerIn: parent visible: false width: Math.min(parent.width - 80, 480) - height: errorLabel.implicitHeight + 32 - radius: 8 - color: backend.themeSurface - border.color: backend.themeRed + padding: 20 + Material.background: backend.themeSurface + Material.elevation: 6 - Text { - id: errorLabel - anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter; margins: 16 } - color: backend.themeForeground + ColumnLayout { + anchors.fill: parent + spacing: 12 + Label { + Layout.fillWidth: true + text: qsTr("Disconnected from %1").arg(displayEnvName || qsTr("the Machine")) + font.pixelSize: 18 + font.weight: Font.DemiBold + wrapMode: Text.Wrap + } + Label { + id: errorLabel + Layout.fillWidth: true + color: backend.themeMuted + wrapMode: Text.Wrap + } + RowLayout { + Layout.alignment: Qt.AlignRight + spacing: 8 + Button { + text: qsTr("Open OmaVM") + flat: true + onClicked: backend.showManager() + } + Button { + text: qsTr("Close") + flat: true + onClicked: win.close() + } + Button { + objectName: "reconnectButton" + // `omavm open` starts the Machine if it shut down and + // opens a new viewer; this one goes away first so the + // new one doesn't find it and step aside. + visible: displayEnvName !== "" + text: qsTr("Reconnect") + highlighted: true + onClicked: { + win.hide() + backend.reopenDisplay(displayEnvName) + Qt.quit() + } + } + } + } + } + + // Shown for a few seconds when the viewer opens: fullscreen hides the + // title bar, and closing the window must not read as shutting down. + Pane { + id: closeHint + objectName: "closeHint" + anchors { horizontalCenter: parent.horizontalCenter; top: parent.top; topMargin: 24 } + width: Math.min(parent.width - 48, 560) + padding: 14 + Material.background: backend.themeSurface + Material.elevation: 6 + opacity: 0 + visible: opacity > 0 + Behavior on opacity { NumberAnimation { duration: 250; easing.type: Easing.OutCubic } } + Label { + width: parent.width + text: qsTr("Ctrl+Alt+Q closes this window. %1 keeps running; shut it down from OmaVM.").arg(displayEnvName || qsTr("The Machine")) wrapMode: Text.Wrap horizontalAlignment: Text.AlignHCenter } + Timer { + id: closeHintTimer + interval: 6000 + onTriggered: closeHint.opacity = 0 + } } Shortcut { diff --git a/gui/backend.cpp b/gui/backend.cpp index 9378106..deef909 100644 --- a/gui/backend.cpp +++ b/gui/backend.cpp @@ -1,4 +1,6 @@ #include "backend.h" + +#include #include "colorstoml.h" #include @@ -13,6 +15,7 @@ #include #include +#include #include namespace { @@ -242,6 +245,7 @@ bool Backend::beginBusy(const QString &key, const QString &label) { void Backend::endBusy(const QString &key) { m_busy.remove(key); + m_progress.remove(key); emit busyChanged(); if (m_quitRequested && m_busy.isEmpty()) emit readyToQuit(); @@ -353,6 +357,16 @@ void Backend::refreshImpl(bool silent) { status.value(QStringLiteral("state"))); current.insert(QStringLiteral("statusDetail"), status.value(QStringLiteral("detail"))); + current.insert( + QStringLiteral("restartNeeded"), + status.value(QStringLiteral("restart_needed")).toBool()); + current.insert( + QStringLiteral("travelMode"), + status.value(QStringLiteral("travel_mode")).toBool()); + current.insert(QStringLiteral("statusWarning"), + status.value(QStringLiteral("warning"))); + current.insert(QStringLiteral("ephemeral"), + status.value(QStringLiteral("ephemeral")).toBool()); const QVariantMap integration = current.take(QStringLiteral("integration")).toMap(); if (!integration.isEmpty()) { @@ -360,6 +374,8 @@ void Backend::refreshImpl(bool silent) { integration.value(QStringLiteral("guest_agent"))); current.insert(QStringLiteral("integrationHint"), integration.value(QStringLiteral("hint"))); + current.insert(QStringLiteral("guestCapabilities"), + integration.value(QStringLiteral("capabilities"))); } // Keep the previous preview while the Machine keeps running: // recapturing it every poll made cards flash. The list is @@ -450,6 +466,21 @@ void Backend::run(const QString &key, const QStringList &arguments, return; } auto *process = new QProcess(this); + // "progress: STAGE" lines arrive while the command runs; everything else + // on stdout is its result, shown when it finishes. + auto result = std::make_shared(); + connect(process, &QProcess::readyReadStandardOutput, this, + [this, process, key, result]() { + while (process->canReadLine()) { + const QByteArray line = process->readLine(); + if (line.startsWith("progress: ")) { + m_progress.insert(key, QString::fromUtf8(line.mid(10)).trimmed()); + emit busyChanged(); + } else { + result->append(line); + } + } + }); connect(process, &QProcess::errorOccurred, this, [this, process, tag, key](QProcess::ProcessError error) { if (error != QProcess::FailedToStart) @@ -463,9 +494,10 @@ void Backend::run(const QString &key, const QStringList &arguments, process->deleteLater(); }); connect(process, &QProcess::finished, this, - [this, process, refreshAfter, tag, key](int code) { + [this, process, refreshAfter, tag, key, result](int code) { const QString output = - QString::fromUtf8(process->readAllStandardOutput()).trimmed(); + QString::fromUtf8(*result + process->readAllStandardOutput()) + .trimmed(); const QString errorText = QString::fromUtf8(process->readAllStandardError()).trimmed(); process->deleteLater(); @@ -507,6 +539,8 @@ void Backend::createEnvironment(const QString &name, const QString &image, // pin every new Machine's hardware from birth, permanently disabling // Travel Mode's automatic reduction on battery for it (same bug class // as Backend::configure, docs/TODO.md P2). + if (kind == QStringLiteral("box")) + arguments << QStringLiteral("--progress"); if (kind == QStringLiteral("machine")) { if (cpusTouched) arguments << QStringLiteral("--cpus") << QString::number(cpus); @@ -549,7 +583,7 @@ void Backend::configure(const QString &name, const QString &description, bool disconnectISO, const QString &color, bool shareClipboard, bool travelMode, bool vulkan, bool openInEmptyWorkspace, bool launcher, bool ssh, - bool fullscreen) { + bool fullscreen, const QString &clipboardDirection) { QStringList arguments{QStringLiteral("settings"), name, QStringLiteral("--description"), description, QStringLiteral("--color"), color}; @@ -562,6 +596,8 @@ void Backend::configure(const QString &name, const QString &description, // the terminal (OSC 52) for a Box. arguments << (shareClipboard ? QStringLiteral("--share-clipboard=true") : QStringLiteral("--share-clipboard=false")); + if (machine && !clipboardDirection.isEmpty()) + arguments << QStringLiteral("--clipboard-direction") << clipboardDirection; arguments << (travelMode ? QStringLiteral("--travel-mode=true") : QStringLiteral("--travel-mode=false")); if (machine) { @@ -632,6 +668,61 @@ void Backend::runForApps(const QStringList &arguments, const QString &name, process->start(cliPath(), arguments); } +void Backend::reopenDisplay(const QString &name) const { + QProcess::startDetached(cliPath(), {QStringLiteral("open"), name}); +} + +void Backend::focusManagerWorkspace() const { + if (!hyprlandAvailable()) + return; + hyprctlRepl(QStringLiteral( + "local w = hl.get_windows({ class = 'dev.omavm.app' })\n" + "if #w > 0 then\n" + " hl.dispatch(hl.dsp.focus({ workspace = w[1].workspace.id }))\n" + "end\n"), + nullptr); +} + +void Backend::showManager() const { + QProcess::startDetached(QCoreApplication::applicationFilePath(), {}); +} + +void Backend::cloneEnvironment(const QString &name, const QString &newName) { + // Keyed on the source: it is locked while it is copied, and its card + // shows the stages. + run(name, {QStringLiteral("clone"), name, newName, QStringLiteral("--progress")}, + QStringLiteral("cloning %1").arg(name), QStringLiteral("clone")); +} + +void Backend::updateEnvironment(const QString &name) { + run(name, {QStringLiteral("update"), name, QStringLiteral("--progress")}, + QStringLiteral("updating %1").arg(name), QStringLiteral("update")); +} + +void Backend::refreshHost() { + // Read-only and quick: no busy state, and a failure leaves the map as it + // was (the UI then simply says nothing). + auto *process = new QProcess(this); + connect(process, &QProcess::finished, this, [this, process](int code) { + const QByteArray output = process->readAllStandardOutput(); + process->deleteLater(); + if (code != 0) + return; + QVariantMap next; + for (const QJsonValue &value : QJsonDocument::fromJson(output).array()) { + const QVariantMap capability = value.toObject().toVariantMap(); + next.insert(capability.value(QStringLiteral("id")).toString(), + capability); + } + if (next != m_hostCapabilities) { + m_hostCapabilities = next; + emit hostCapabilitiesChanged(); + } + }); + connect(process, &QProcess::errorOccurred, process, &QObject::deleteLater); + process->start(cliPath(), {QStringLiteral("host"), QStringLiteral("--json")}); +} + void Backend::refreshApps(const QString &name) { if (!beginBusy(name, QStringLiteral("loading applications for %1").arg(name))) @@ -728,6 +819,7 @@ void Backend::open(const QString &name, const QString &kind) { // its launcher entry or with `omavm open`. bool emptyWorkspace = true; bool shareClipboard = true; + QString color; for (const QVariant &item : m_environments) { const QVariantMap env = item.toMap(); if (env.value(QStringLiteral("name")).toString() == name) { @@ -737,6 +829,7 @@ void Backend::open(const QString &name, const QString &kind) { !settings.value(QStringLiteral("empty_workspace_disabled")).toBool(); shareClipboard = !settings.value(QStringLiteral("clipboard_disabled")).toBool(); + color = settings.value(QStringLiteral("color")).toString(); break; } } @@ -750,18 +843,41 @@ void Backend::open(const QString &name, const QString &kind) { const auto flag = [](bool on) { return on ? QStringLiteral("true") : QStringLiteral("false"); }; - QProcess::startDetached( - QCoreApplication::applicationFilePath(), - {QStringLiteral("--terminal"), name, QStringLiteral("--title"), - name + QStringLiteral(" — OmaVM"), QStringLiteral("--share-clipboard"), - flag(shareClipboard), QStringLiteral("--empty-workspace"), - flag(emptyWorkspace)}); + QStringList arguments{QStringLiteral("--terminal"), name, + QStringLiteral("--title"), + name + QStringLiteral(" — OmaVM"), + QStringLiteral("--share-clipboard"), + flag(shareClipboard), + QStringLiteral("--empty-workspace"), + flag(emptyWorkspace)}; + if (!color.isEmpty()) + arguments << QStringLiteral("--color") << color; + QProcess::startDetached(QCoreApplication::applicationFilePath(), + arguments); return; } run(name, {QStringLiteral("open"), name}, QStringLiteral("opening %1").arg(name), QStringLiteral("open")); } +void Backend::openEphemeral(const QString &name) { + const QString tag = QStringLiteral("start-ephemeral:") + name; + auto *connection = new QMetaObject::Connection; + *connection = connect( + this, &Backend::actionFinished, this, + [this, name, tag, connection](const QString &finished, bool ok, + const QString &) { + if (finished != tag) + return; + disconnect(*connection); + delete connection; + if (ok) + open(name, QStringLiteral("machine")); + }); + run(name, {QStringLiteral("start"), name, QStringLiteral("--ephemeral")}, + QStringLiteral("starting %1 without keeping changes").arg(name), tag); +} + void Backend::loadTheme() { const QString currentDir = QDir::homePath() + QStringLiteral("/.local/state/omarchy/current"); diff --git a/gui/backend.h b/gui/backend.h index 4a19813..63cd31f 100644 --- a/gui/backend.h +++ b/gui/backend.h @@ -18,6 +18,13 @@ class Backend final : public QObject { // Environment name -> what is running on it right now. Q_PROPERTY( QVariantMap busyEnvironments READ busyEnvironments NOTIFY busyChanged) + // Environment name -> the stage a long operation reported last + // (`create --progress`), such as which layer of an image is downloading. + Q_PROPERTY(QVariantMap progress READ progress NOTIFY busyChanged) + // `omavm host --json`, keyed by capability id ("kvm", ...): what this + // computer offers Desktops, so the UI can say it before creating one. + Q_PROPERTY(QVariantMap hostCapabilities READ hostCapabilities NOTIFY + hostCapabilitiesChanged) Q_PROPERTY(QString listError READ listError NOTIFY listErrorChanged) Q_PROPERTY(QVariantList apps READ apps NOTIFY appsChanged) Q_PROPERTY(bool appsLoading READ appsLoading NOTIFY appsChanged) @@ -45,6 +52,8 @@ class Backend final : public QObject { bool busy() const { return !m_busy.isEmpty(); } QString busyAction() const; QVariantMap busyEnvironments() const; + QVariantMap progress() const { return m_progress; } + QVariantMap hostCapabilities() const { return m_hostCapabilities; } QString listError() const { return m_listError; } bool appsLoading() const { return m_appsLoading; } QString appsEnvironment() const { return m_appsEnvironment; } @@ -65,6 +74,8 @@ class Backend final : public QObject { // `omavm` mid-operation (a Restart cut between Stop and Start leaves the // Machine off). readyToQuit fires now if idle, else once the action ends. void requestQuit(); + // The window was shown again before the last action finished. + void cancelQuit() { m_quitRequested = false; } Q_INVOKABLE void refresh(); Q_INVOKABLE void poll(); @@ -74,6 +85,8 @@ class Backend final : public QObject { bool memoryTouched); Q_INVOKABLE void start(const QString &name); Q_INVOKABLE void open(const QString &name, const QString &kind); + // Starts a Machine without keeping this session's changes, then opens it. + Q_INVOKABLE void openEphemeral(const QString &name); Q_INVOKABLE void stop(const QString &name); Q_INVOKABLE void restart(const QString &name); Q_INVOKABLE void pause(const QString &name); @@ -86,12 +99,23 @@ class Backend final : public QObject { bool disconnectISO, const QString &color, bool shareClipboard, bool travelMode, bool vulkan, bool openInEmptyWorkspace, bool launcher, - bool ssh, bool fullscreen); + bool ssh, bool fullscreen, + const QString &clipboardDirection = QString()); Q_INVOKABLE void remove(const QString &name); Q_INVOKABLE void createSnapshot(const QString &name, const QString &label); Q_INVOKABLE void goToSnapshot(const QString &name, const QString &id); Q_INVOKABLE void removeSnapshot(const QString &name, const QString &id); Q_INVOKABLE void refreshApps(const QString &name); + Q_INVOKABLE void refreshHost(); + Q_INVOKABLE void cloneEnvironment(const QString &name, const QString &newName); + Q_INVOKABLE void updateEnvironment(const QString &name); + // From a viewer: open the Machine again (a new display connection, in a + // new viewer), or bring up the Experience Center. + Q_INVOKABLE void reopenDisplay(const QString &name) const; + Q_INVOKABLE void showManager() const; + // Brings the Experience Center's workspace into view, for a second + // launch: Wayland doesn't let a window focus itself unasked. + Q_INVOKABLE void focusManagerWorkspace() const; Q_INVOKABLE void exportApp(const QString &name, const QString &id); Q_INVOKABLE void unexportApp(const QString &name, const QString &id); Q_INVOKABLE void copyToClipboard(const QString &text) const; @@ -104,6 +128,7 @@ class Backend final : public QObject { } signals: + void hostCapabilitiesChanged(); void readyToQuit(); void environmentsChanged(); void appsChanged(); @@ -159,6 +184,8 @@ class Backend final : public QObject { QFileSystemWatcher m_themeWatcher; // Key (environment name, "" for the list) -> action label. QMap m_busy; + QVariantMap m_progress; + QVariantMap m_hostCapabilities; bool m_refreshPending = false; QString m_listError; bool m_appsLoading = false; diff --git a/gui/displayview.cpp b/gui/displayview.cpp index 54bc019..a5327c3 100644 --- a/gui/displayview.cpp +++ b/gui/displayview.cpp @@ -139,7 +139,8 @@ DisplayView::DisplayView(QQuickItem *parent) : QQuickItem(parent) { &DisplayView::connectionFailed); connect(&m_client, &DisplayClient::clipboardReceived, this, [this](const QString &text) { - if (!m_shareClipboard || !window() || !window()->isActive()) + if (!m_shareClipboard || !window() || !window()->isActive() || + m_clipboardDirection == QStringLiteral("to-guest")) return; QScopedValueRollback receiving(m_receivingClipboard, true); QGuiApplication::clipboard()->setText(text); @@ -185,7 +186,8 @@ void DisplayView::setShareClipboard(bool enabled) { void DisplayView::syncClipboard() { const bool active = m_shareClipboard && window() && window()->isActive(); m_client.setClipboardEnabled(active); - if (active && !m_receivingClipboard) + if (active && !m_receivingClipboard && + m_clipboardDirection != QStringLiteral("to-host")) m_client.sendClipboard(QGuiApplication::clipboard()->text()); } diff --git a/gui/displayview.h b/gui/displayview.h index a490357..2ad8ead 100644 --- a/gui/displayview.h +++ b/gui/displayview.h @@ -19,6 +19,10 @@ class DisplayView : public QQuickItem { connectionFdChanged) Q_PROPERTY(bool shareClipboard READ shareClipboard WRITE setShareClipboard NOTIFY shareClipboardChanged) + // Limits a shared clipboard to one way: "" (both), "to-host" (only what + // the guest copies reaches this computer) or "to-guest". + Q_PROPERTY(QString clipboardDirection MEMBER m_clipboardDirection NOTIFY + shareClipboardChanged) public: explicit DisplayView(QQuickItem *parent = nullptr); @@ -68,6 +72,7 @@ class DisplayView : public QQuickItem { DisplayClient m_client; int m_connectionFd = -1; bool m_shareClipboard = false; + QString m_clipboardDirection; bool m_receivingClipboard = false; // Latest dma-buf scanout, waiting to be imported on the render thread. diff --git a/gui/main.cpp b/gui/main.cpp index cce8ad8..eca263f 100644 --- a/gui/main.cpp +++ b/gui/main.cpp @@ -1,6 +1,7 @@ #include "backend.h" #include "terminalview.h" #include "displayview.h" +#include "singleinstance.h" #include #include @@ -36,7 +37,8 @@ bool placeViewer(const QString &title, bool emptyWorkspace) { // Qt app to build and package instead of two. connectionFd is a socket // QEMU already accepted (the backend hands it over as an inherited fd). int runViewer(QGuiApplication &app, int connectionFd, const QString &title, - bool shareClipboard, bool emptyWorkspace, bool fullscreen) { + const QString &envName, const QString &clipboardMode, + bool emptyWorkspace, bool fullscreen) { if (!placeViewer(title, emptyWorkspace)) return 0; app.setApplicationName(QStringLiteral("dev.omavm.viewer")); @@ -53,10 +55,21 @@ int runViewer(QGuiApplication &app, int connectionFd, const QString &title, QStringLiteral("displayConnectionFd"), connectionFd); engine.rootContext()->setContextProperty(QStringLiteral("displayTitle"), title); + // Empty when launched by an older omavm: the viewer then can't offer + // to reconnect. + engine.rootContext()->setContextProperty(QStringLiteral("displayEnvName"), + envName); // The Machine's own Settings (opt-out, on by default) decide this — // not a per-window checkbox the user has to remember to re-check. engine.rootContext()->setContextProperty( - QStringLiteral("displayShareClipboard"), shareClipboard); + QStringLiteral("displayShareClipboard"), + clipboardMode != QStringLiteral("false")); + engine.rootContext()->setContextProperty( + QStringLiteral("displayClipboardDirection"), + clipboardMode == QStringLiteral("to-host") || + clipboardMode == QStringLiteral("to-guest") + ? clipboardMode + : QString()); // A personal window rule for the viewer (contrib/hypr/omavm-viewer.lua) // already makes it fullscreen: asking too would toggle it back off. engine.rootContext()->setContextProperty( @@ -76,7 +89,7 @@ int runViewer(QGuiApplication &app, int connectionFd, const QString &title, // (contrib/hypr/omavm-viewer.lua) covers both. int runTerminal(QGuiApplication &app, const QString &envName, const QString &title, bool shareClipboard, - bool emptyWorkspace) { + bool emptyWorkspace, const QString &color) { if (!placeViewer(title, emptyWorkspace)) return 0; app.setApplicationName(QStringLiteral("dev.omavm.viewer")); @@ -95,6 +108,10 @@ int runTerminal(QGuiApplication &app, const QString &envName, // own opt-out setting. engine.rootContext()->setContextProperty( QStringLiteral("terminalShareClipboard"), shareClipboard); + // The environment's color tag, so the window says which Box it is — and + // that it isn't the host. Empty when the Box has none. + engine.rootContext()->setContextProperty(QStringLiteral("terminalColor"), + color); engine.load(QUrl(QStringLiteral("qrc:/TerminalViewer.qml"))); if (engine.rootObjects().isEmpty()) return -1; @@ -122,9 +139,10 @@ int main(int argc, char *argv[]) { QStringLiteral("title"), QStringLiteral("OmaVM")); QCommandLineOption shareClipboardOption( QStringLiteral("share-clipboard"), - QStringLiteral("Whether to share the text clipboard with the guest, " - "or let programs in a Box copy to it"), - QStringLiteral("bool"), QStringLiteral("true")); + QStringLiteral("Share the text clipboard with the guest (true, false, " + "to-host or to-guest for one way only), or let programs " + "in a Box copy to it"), + QStringLiteral("mode"), QStringLiteral("true")); parser.addOption(viewerOption); parser.addOption(terminalOption); parser.addOption(titleOption); @@ -136,7 +154,18 @@ int main(int argc, char *argv[]) { QStringLiteral("fullscreen"), QStringLiteral("Open a Machine's display fullscreen"), QStringLiteral("bool"), QStringLiteral("true")); + QCommandLineOption environmentOption( + QStringLiteral("environment"), + QStringLiteral("The Machine shown by --display-fd, to reconnect to it"), + QStringLiteral("name")); + parser.addOption(environmentOption); + QCommandLineOption colorOption( + QStringLiteral("color"), + QStringLiteral("The environment's color tag, shown along the " + "terminal's top edge"), + QStringLiteral("color")); parser.addOption(shareClipboardOption); + parser.addOption(colorOption); parser.addOption(emptyWorkspaceOption); parser.addOption(fullscreenOption); parser.process(app); @@ -146,12 +175,23 @@ int main(int argc, char *argv[]) { }; if (parser.isSet(viewerOption)) return runViewer(app, parser.value(viewerOption).toInt(), - parser.value(titleOption), on(shareClipboardOption), - on(emptyWorkspaceOption), on(fullscreenOption)); + parser.value(titleOption), + parser.value(environmentOption), + parser.value(shareClipboardOption), on(emptyWorkspaceOption), + on(fullscreenOption)); + // A Box's terminal only copies to this computer (OSC 52). if (parser.isSet(terminalOption)) return runTerminal(app, parser.value(terminalOption), - parser.value(titleOption), on(shareClipboardOption), - on(emptyWorkspaceOption)); + parser.value(titleOption), + on(shareClipboardOption) && + parser.value(shareClipboardOption) != + QStringLiteral("to-guest"), + on(emptyWorkspaceOption), parser.value(colorOption)); + + SingleInstance instance(SingleInstance::defaultSocketPath()); + if (instance.notifyRunning()) + return 0; // the running Experience Center comes forward instead + instance.listen(); app.setApplicationName(QStringLiteral("dev.omavm.app")); app.setDesktopFileName(QStringLiteral("dev.omavm.app")); @@ -170,5 +210,17 @@ int main(int argc, char *argv[]) { engine.load(QUrl(QStringLiteral("qrc:/Main.qml"))); if (engine.rootObjects().isEmpty()) return -1; + // Closing the window only hides it while an action finishes; a second + // launch shows it again. + QObject::connect(&instance, &SingleInstance::activated, &app, [&]() { + if (auto *window = + qobject_cast(engine.rootObjects().first())) { + window->show(); + window->raise(); + window->requestActivate(); + } + backend.cancelQuit(); + backend.focusManagerWorkspace(); + }); return app.exec(); } diff --git a/gui/resources.qrc b/gui/resources.qrc index 5e2e627..b4a6d8d 100644 --- a/gui/resources.qrc +++ b/gui/resources.qrc @@ -5,6 +5,7 @@ EnvironmentListModel.qml CreateDialog.qml SettingsDialog.qml + CloneDialog.qml SnapshotsDialog.qml AppsDialog.qml ThemeScrim.qml diff --git a/gui/singleinstance.cpp b/gui/singleinstance.cpp new file mode 100644 index 0000000..8e404e4 --- /dev/null +++ b/gui/singleinstance.cpp @@ -0,0 +1,39 @@ +#include "singleinstance.h" + +#include +#include + +SingleInstance::SingleInstance(const QString &socketPath, QObject *parent) + : QObject(parent), m_path(socketPath) { + connect(&m_server, &QLocalServer::newConnection, this, [this]() { + while (QLocalSocket *client = m_server.nextPendingConnection()) { + connect(client, &QLocalSocket::disconnected, client, + &QObject::deleteLater); + emit activated(); + client->disconnectFromServer(); + } + }); +} + +bool SingleInstance::notifyRunning() const { + QLocalSocket socket; + socket.connectToServer(m_path); + // A local socket answers at once; a stale file refuses at once. + return socket.waitForConnected(500); +} + +bool SingleInstance::listen() { + m_server.setSocketOptions(QLocalServer::UserAccessOption); + if (m_server.listen(m_path)) + return true; + QLocalServer::removeServer(m_path); + return m_server.listen(m_path); +} + +QString SingleInstance::defaultSocketPath() { + QString dir = + QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation); + if (dir.isEmpty()) + dir = QStandardPaths::writableLocation(QStandardPaths::TempLocation); + return dir + QStringLiteral("/omavm-gui.sock"); +} diff --git a/gui/singleinstance.h b/gui/singleinstance.h new file mode 100644 index 0000000..1632a8d --- /dev/null +++ b/gui/singleinstance.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include + +// One Experience Center per user session: a second launch (the launcher +// clicked twice, "Open OmaVM" from a viewer) asks the running one to come +// forward instead of opening another window over the same environments. +// Viewers and terminals are not single-instance: one per environment. +class SingleInstance : public QObject { + Q_OBJECT + +public: + explicit SingleInstance(const QString &socketPath, QObject *parent = nullptr); + + // True when another instance answered and was asked to come forward; + // this process should then exit. + bool notifyRunning() const; + // Starts answering later launches. A socket left by a crashed instance + // (nobody answers on it) is replaced. + bool listen(); + + // $XDG_RUNTIME_DIR/omavm-gui.sock: per user, gone at logout. + static QString defaultSocketPath(); + +signals: + void activated(); + +private: + QString m_path; + QLocalServer m_server; +}; diff --git a/gui/terminal.cpp b/gui/terminal.cpp index 55f061d..9d21673 100644 --- a/gui/terminal.cpp +++ b/gui/terminal.cpp @@ -1061,6 +1061,40 @@ QPair TerminalSession::wordBounds(int line, int col) const { return {first, last}; } +TerminalSession::ViewShortcut +TerminalSession::viewShortcut(int key, Qt::KeyboardModifiers modifiers) { + const Qt::KeyboardModifiers relevant = + modifiers & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier); + if (relevant == Qt::ShiftModifier) { + switch (key) { + case Qt::Key_PageUp: + return ViewShortcut::PageUp; + case Qt::Key_PageDown: + return ViewShortcut::PageDown; + case Qt::Key_Home: + return ViewShortcut::Top; + case Qt::Key_End: + return ViewShortcut::Bottom; + } + } + // Ctrl+Plus is typed as Ctrl+Shift+= on most layouts. + if (relevant == Qt::ControlModifier || + relevant == (Qt::ControlModifier | Qt::ShiftModifier)) { + switch (key) { + case Qt::Key_Plus: + case Qt::Key_Equal: + return ViewShortcut::ZoomIn; + case Qt::Key_Minus: + return relevant == Qt::ControlModifier ? ViewShortcut::ZoomOut + : ViewShortcut::None; + case Qt::Key_0: + return relevant == Qt::ControlModifier ? ViewShortcut::ZoomReset + : ViewShortcut::None; + } + } + return ViewShortcut::None; +} + bool TerminalSession::isCopyShortcut(int key, Qt::KeyboardModifiers modifiers) { const Qt::KeyboardModifiers relevant = diff --git a/gui/terminal.h b/gui/terminal.h index c274204..7e26225 100644 --- a/gui/terminal.h +++ b/gui/terminal.h @@ -90,6 +90,21 @@ class TerminalSession : public QObject { // otherwise reach it as Ctrl+C. static bool isCopyShortcut(int key, Qt::KeyboardModifiers modifiers); + // Keys the window keeps for itself instead of the program, as Alacritty + // (Omarchy's terminal) does: Shift+PageUp/PageDown/Home/End scroll the + // history; Ctrl+Plus (or =), Ctrl+Minus and Ctrl+0 change the font size. + enum class ViewShortcut { + None, + PageUp, + PageDown, + Top, + Bottom, + ZoomIn, + ZoomOut, + ZoomReset + }; + static ViewShortcut viewShortcut(int key, Qt::KeyboardModifiers modifiers); + // The scrollback followed by the visible screen, as one list of lines. int bufferLineCount() const; QVector bufferLine(int index) const; diff --git a/gui/terminalview.cpp b/gui/terminalview.cpp index 7680877..9357729 100644 --- a/gui/terminalview.cpp +++ b/gui/terminalview.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -36,15 +37,19 @@ QRgb xterm256(int index) { return qRgb(steps[(i / 36) % 6], steps[(i / 6) % 6], steps[i % 6]); } +// Font sizes in pixels; the default is what the terminal always used. +constexpr int kDefaultFontSize = 15; +constexpr int kMinFontSize = 8; +constexpr int kMaxFontSize = 48; + } // namespace TerminalView::TerminalView(QQuickItem *parent) : QQuickPaintedItem(parent) { m_font = QFont(QStringLiteral("monospace")); m_font.setStyleHint(QFont::Monospace); - m_font.setPixelSize(15); - const QFontMetricsF metrics(m_font); - m_cellWidth = metrics.horizontalAdvance(QLatin1Char('M')); - m_cellHeight = metrics.height(); + setFontPixelSize( + QSettings().value(QStringLiteral("terminal/fontPixelSize"), kDefaultFontSize) + .toInt()); loadPalette(); @@ -352,7 +357,67 @@ void TerminalView::paint(QPainter *painter) { } } +void TerminalView::setFontPixelSize(int size) { + size = qBound(kMinFontSize, size, kMaxFontSize); + m_font.setPixelSize(size); + const QFontMetricsF metrics(m_font); + m_cellWidth = metrics.horizontalAdvance(QLatin1Char('M')); + m_cellHeight = metrics.height(); + QSettings settings; + if (settings.value(QStringLiteral("terminal/fontPixelSize"), kDefaultFontSize) + .toInt() != size) + settings.setValue(QStringLiteral("terminal/fontPixelSize"), size); + if (width() > 0 && height() > 0) + updateGridSize(); + update(); +} + +void TerminalView::scrollTo(int offset) { + m_scrollOffset = qBound(0, offset, int(m_session.scrollback().size())); + update(); +} + void TerminalView::keyPressEvent(QKeyEvent *event) { + const int page = qMax(1, int(height() / m_cellHeight) - 1); + switch (TerminalSession::viewShortcut(event->key(), event->modifiers())) { + case TerminalSession::ViewShortcut::None: + break; + case TerminalSession::ViewShortcut::PageUp: + case TerminalSession::ViewShortcut::PageDown: + case TerminalSession::ViewShortcut::Top: + case TerminalSession::ViewShortcut::Bottom: + // Full-screen programs (vim, less) have no history here: the keys + // are theirs. + if (m_session.alternateScreen()) + break; + switch (TerminalSession::viewShortcut(event->key(), event->modifiers())) { + case TerminalSession::ViewShortcut::PageUp: + scrollTo(m_scrollOffset + page); + break; + case TerminalSession::ViewShortcut::PageDown: + scrollTo(m_scrollOffset - page); + break; + case TerminalSession::ViewShortcut::Top: + scrollTo(int(m_session.scrollback().size())); + break; + default: + scrollTo(0); + } + event->accept(); + return; + case TerminalSession::ViewShortcut::ZoomIn: + setFontPixelSize(m_font.pixelSize() + 1); + event->accept(); + return; + case TerminalSession::ViewShortcut::ZoomOut: + setFontPixelSize(m_font.pixelSize() - 1); + event->accept(); + return; + case TerminalSession::ViewShortcut::ZoomReset: + setFontPixelSize(kDefaultFontSize); + event->accept(); + return; + } if (TerminalSession::isCopyShortcut(event->key(), event->modifiers())) { copySelection(QClipboard::Clipboard); event->accept(); @@ -381,6 +446,13 @@ void TerminalView::keyPressEvent(QKeyEvent *event) { } void TerminalView::wheelEvent(QWheelEvent *event) { + if (event->modifiers() & Qt::ControlModifier) { + const int notches = event->angleDelta().y() / 120; + if (notches != 0) + setFontPixelSize(m_font.pixelSize() + notches); + event->accept(); + return; + } if (m_session.alternateScreen()) { event->ignore(); return; diff --git a/gui/terminalview.h b/gui/terminalview.h index 64eee41..2f7f617 100644 --- a/gui/terminalview.h +++ b/gui/terminalview.h @@ -65,6 +65,10 @@ class TerminalView : public QQuickPaintedItem { void updateGridSize(); void loadPalette(); + // Applies a font size in pixels (bounded), remembers it for the next + // terminal, and refits the grid to the window. + void setFontPixelSize(int size); + void scrollTo(int offset); QRgb resolveColor(const TerminalColor &color, bool foreground) const; QVector lineAt(int visibleRow) const; int visibleToBuffer(int visibleRow) const; diff --git a/gui/tests/backend_refresh_test.cpp b/gui/tests/backend_refresh_test.cpp index 210edfe..b53f036 100644 --- a/gui/tests/backend_refresh_test.cpp +++ b/gui/tests/backend_refresh_test.cpp @@ -1,4 +1,5 @@ #include "../backend.h" +#include "../singleinstance.h" #include "../colorstoml.h" #include @@ -24,6 +25,8 @@ private slots: void boxTerminalIsTaggedAsTerminal(); void onlyActiveViewerRulesCount(); void actionsOnDifferentEnvironmentsRunTogether(); + void creationReportsProgressStages(); + void secondLaunchActivatesTheFirst(); void everyThemeTextMeetsAAA(); }; @@ -134,6 +137,65 @@ void BackendRefreshTest::actionsOnDifferentEnvironmentsRunTogether() { QVERIFY(backend.busyEnvironments().isEmpty()); } +// A Box's image download used to show only "Creating…" for minutes. The +// stages `create --progress` prints reach the card while it runs, and are +// neither shown as the command's result nor left behind once it ends. +void BackendRefreshTest::creationReportsProgressStages() { + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString args = dir.filePath(QStringLiteral("args")); + QFile cli(dir.filePath(QStringLiteral("omavm"))); + QVERIFY(cli.open(QIODevice::WriteOnly)); + cli.write("#!/bin/sh\n" + "case \"$1\" in\n" + " create) echo \"$@\" > \"$OMAVM_TEST_ARGS\";\n" + " echo 'progress: Downloading fedora: layer 1'; sleep 0.5;\n" + " echo 'created demo (box, backend=distrobox)' ;;\n" + " list) printf '[]' ;;\n" + "esac\n"); + cli.close(); + QVERIFY(cli.setPermissions(QFile::ReadOwner | QFile::WriteOwner | + QFile::ExeOwner)); + qputenv("OMAVM_TEST_ARGS", args.toUtf8()); + qputenv("PATH", dir.path().toUtf8() + ':' + qgetenv("PATH")); + + Backend backend; + QSignalSpy finished(&backend, &Backend::actionFinished); + backend.createEnvironment(QStringLiteral("demo"), QStringLiteral("fedora"), + QStringLiteral("box"), 2, false, 2048, false); + QTRY_COMPARE_WITH_TIMEOUT( + backend.progress().value(QStringLiteral("demo")).toString(), + QStringLiteral("Downloading fedora: layer 1"), 3000); + QTRY_COMPARE_WITH_TIMEOUT(finished.size(), 1, 5000); + QCOMPARE(finished.at(0).at(2).toString(), + QStringLiteral("created demo (box, backend=distrobox)")); + QVERIFY(backend.progress().isEmpty()); + QFile recorded(args); + QVERIFY(recorded.open(QIODevice::ReadOnly)); + QVERIFY(recorded.readAll().contains("--progress")); +} + +// The launcher clicked twice, or "Open OmaVM" from a viewer, brings the +// running Experience Center forward instead of opening a second one; a +// socket file left by a crash doesn't block the next launch. +void BackendRefreshTest::secondLaunchActivatesTheFirst() { + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString path = dir.filePath(QStringLiteral("omavm-gui.sock")); + + QFile stale(path); + QVERIFY(stale.open(QIODevice::WriteOnly)); + stale.close(); + SingleInstance first(path); + QVERIFY(!first.notifyRunning()); + QVERIFY(first.listen()); + + QSignalSpy activated(&first, &SingleInstance::activated); + SingleInstance second(path); + QVERIFY(second.notifyRunning()); + QTRY_COMPARE_WITH_TIMEOUT(activated.size(), 1, 2000); +} + // Regression: Omarchy's Super+C reached a Box's terminal as Ctrl+C // (SIGINT) because the window lacked the "terminal" tag. void BackendRefreshTest::boxTerminalIsTaggedAsTerminal() { diff --git a/gui/tests/backend_refresh_test.pro b/gui/tests/backend_refresh_test.pro index ffa3098..cd38ba1 100644 --- a/gui/tests/backend_refresh_test.pro +++ b/gui/tests/backend_refresh_test.pro @@ -1,5 +1,5 @@ QT += core gui network testlib CONFIG += c++17 testcase TARGET = backend_refresh_test -SOURCES += backend_refresh_test.cpp ../backend.cpp ../colorstoml.cpp -HEADERS += ../backend.h ../colorstoml.h +SOURCES += backend_refresh_test.cpp ../backend.cpp ../colorstoml.cpp ../singleinstance.cpp +HEADERS += ../backend.h ../colorstoml.h ../singleinstance.h diff --git a/gui/tests/qml/tst_accessibility.qml b/gui/tests/qml/tst_accessibility.qml index 488ffda..b5b3863 100644 --- a/gui/tests/qml/tst_accessibility.qml +++ b/gui/tests/qml/tst_accessibility.qml @@ -21,6 +21,7 @@ Item { function test_cards_data() { return [ { tag: "stopped box", kind: "box", status: "stopped" }, + { tag: "stopped machine", kind: "machine", status: "stopped" }, { tag: "running machine", kind: "machine", status: "running" }, { tag: "paused machine", kind: "machine", status: "paused" }, { tag: "failed machine", kind: "machine", status: "error" }, diff --git a/gui/tests/qml/tst_appsdialog.qml b/gui/tests/qml/tst_appsdialog.qml new file mode 100644 index 0000000..f0753e4 --- /dev/null +++ b/gui/tests/qml/tst_appsdialog.qml @@ -0,0 +1,51 @@ +import QtQuick +import QtTest + +Item { + id: root + width: 800 + height: 700 + + TestCase { + name: "AppsDialog" + when: windowShown + + // The row being exported says so, the result is said in words, and + // a failure keeps the row with the same action to try again. + function test_exportShowsProgressAndResult() { + backend.appsEnvironment = "dev" + backend.appsError = "" + backend.apps = [{ id: "/usr/share/applications/gimp.desktop", name: "Gimp", exported: false }] + const component = Qt.createComponent("qrc:/AppsDialog.qml") + compare(component.status, Component.Ready, component.errorString()) + const dialog = component.createObject(root, { environment: { name: "dev", kind: "box" } }) + dialog.open() + tryVerify(() => dialog.opened) + + dialog.act(backend.apps[0]) + compare(backend.lastCall[0], "exportApp") + compare(backend.lastCall[2], "/usr/share/applications/gimp.desktop") + const row = findChild(dialog.contentItem, "appRow-Gimp") + verify(row.pending) + verify(!findChild(row, "appAction").visible, "no second click while it runs") + + backend.finishAction("apps-export", false, "distrobox-export failed") + verify(!row.pending) + compare(dialog.resultText, "distrobox-export failed") + verify(dialog.resultFailed) + verify(findChild(row, "appAction").visible, "the row offers the action again") + + dialog.act(backend.apps[0]) + backend.finishAction("apps-export", true, "") + compare(dialog.resultText, "“Gimp” is in the app menu.") + + backend.apps = [{ id: "/usr/share/applications/gimp.desktop", name: "Gimp", exported: true }] + dialog.act(backend.apps[0]) + compare(backend.lastCall[0], "unexportApp") + backend.finishAction("apps-unexport", true, "") + compare(dialog.resultText, "“Gimp” was removed from the app menu; it is still installed in dev.") + dialog.destroy() + backend.apps = [] + } + } +} diff --git a/gui/tests/qml/tst_clonedialog.qml b/gui/tests/qml/tst_clonedialog.qml new file mode 100644 index 0000000..37b3cc0 --- /dev/null +++ b/gui/tests/qml/tst_clonedialog.qml @@ -0,0 +1,43 @@ +import QtQuick +import QtTest + +Item { + id: root + width: 800 + height: 700 + + TestCase { + name: "CloneDialog" + when: windowShown + + function open(env) { + const component = Qt.createComponent("qrc:/CloneDialog.qml") + compare(component.status, Component.Ready, component.errorString()) + const d = component.createObject(root, { environment: env }) + d.open() + tryVerify(() => d.opened) + return d + } + + // The cost is said before cloning, and a running environment is + // asked to stop first instead of failing after the click. + function test_costAndStopFirst() { + let d = open({ name: "vm", kind: "machine", status: "running" }) + verify(findChild(d, "cloneCost").text.indexOf("free space") >= 0) + verify(findChild(d, "stopFirst").visible) + verify(!findChild(d, "cloneButton").enabled) + d.destroy() + d = open({ name: "dev", kind: "box", status: "stopped" }) + verify(findChild(d, "cloneCost").text.indexOf("home folder is shared") >= 0) + verify(!findChild(d, "stopFirst").visible) + compare(findChild(d, "cloneName").text, "dev copy") + findChild(d, "cloneButton").clicked() + compare(backend.lastCall[0], "cloneEnvironment") + compare(backend.lastCall[2], "dev copy") + backend.finishAction("clone", false, "name taken") + verify(d.opened, "a failure keeps the dialog open") + compare(d.errorText, "name taken") + d.destroy() + } + } +} diff --git a/gui/tests/qml/tst_createdialog.qml b/gui/tests/qml/tst_createdialog.qml index e6fb0ad..6d86aa2 100644 --- a/gui/tests/qml/tst_createdialog.qml +++ b/gui/tests/qml/tst_createdialog.qml @@ -27,5 +27,47 @@ Item { compare(dialog.validateName("Ação"), "") dialog.destroy() } + + // Creation leads to first use: the window learns which environment + // was created and of which kind, only when it succeeded. + function test_successfulCreationIsAnnounced() { + const component = Qt.createComponent("qrc:/CreateDialog.qml") + const dialog = component.createObject(root) + const spy = createTemporaryObject(signalSpyComponent, root, { target: dialog, signalName: "created" }) + dialog.machine = false + findChild(dialog, "nameField").text = " dev " + backend.finishAction("create", false, "boom") + compare(spy.count, 0) + backend.finishAction("create", true, "") + compare(spy.count, 1) + compare(spy.signalArguments[0][0], "dev") + compare(spy.signalArguments[0][1], "box") + backend.finishAction("start", true, "") + compare(spy.count, 1) + dialog.destroy() + } + } + + TestCase { + name: "CreateDialogHost" + when: windowShown + + // Without KVM a Desktop can be created but never starts: the + // choice says so before anything is created, with the fix. + function test_missingKVMIsSaidBeforeCreating() { + const component = Qt.createComponent("qrc:/CreateDialog.qml") + const dialog = component.createObject(root) + const warning = findChild(dialog, "kvmWarning") + verify(!dialog.kvmMissing, "unknown must say nothing") + backend.hostCapabilities = { kvm: { id: "kvm", available: false, hint: "Add your user to the kvm group" } } + verify(dialog.kvmMissing) + verify(warning.text.indexOf("Add your user to the kvm group") >= 0) + backend.hostCapabilities = { kvm: { id: "kvm", available: true } } + verify(!dialog.kvmMissing) + backend.hostCapabilities = {} + dialog.destroy() + } } + + Component { id: signalSpyComponent; SignalSpy {} } } diff --git a/gui/tests/qml/tst_environmentcard.qml b/gui/tests/qml/tst_environmentcard.qml index 821f3c8..d4b166c 100644 --- a/gui/tests/qml/tst_environmentcard.qml +++ b/gui/tests/qml/tst_environmentcard.qml @@ -45,6 +45,108 @@ Item { verify(!findChild(loader.item, "statusDetailLabel").visible) } + // A nearly full host disk is said before the Machine pauses, on a + // stopped card too (before Start). + function test_lowSpaceWarning() { + const why = "only 700 MiB free on this computer: the Machine pauses if it runs out" + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 320, + environment: { name: "vm", kind: "machine", status: "stopped", statusWarning: why, settings: {} } + }) + tryVerify(() => loader.status === Loader.Ready) + const label = findChild(loader.item, "statusWarningLabel") + verify(label.visible) + compare(label.text, why) + } + + // A running session says when it differs from its settings. + function test_sessionAdjustments() { + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 320, + environment: { name: "vm", kind: "machine", status: "running", restartNeeded: true, travelMode: true, settings: {} } + }) + tryVerify(() => loader.status === Loader.Ready) + verify(findChild(loader.item, "restartNeededLabel").visible) + verify(findChild(loader.item, "travelModeLabel").visible) + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 320, + environment: { name: "vm", kind: "machine", status: "stopped", restartNeeded: true, settings: {} } + }) + tryVerify(() => loader.status === Loader.Ready) + verify(!findChild(loader.item, "restartNeededLabel").visible, "a stopped Machine has nothing to restart") + } + + // The card says which system runs inside, in plain words. + function test_systemName_data() { + return [ + { tag: "preset", kind: "box", image: "fedora:latest", want: "Fedora" }, + { tag: "toolbox with tag", kind: "box", image: "registry.fedoraproject.org/fedora-toolbox:42", want: "Fedora 42" }, + { tag: "library", kind: "box", image: "docker.io/library/archlinux:latest", want: "Arch Linux" }, + { tag: "registry with port", kind: "box", image: "localhost:5000/team/devbox", want: "devbox" }, + { tag: "digest", kind: "box", image: "quay.io/toolbx/ubuntu-toolbox@sha256:abc", want: "Ubuntu" }, + { tag: "iso", kind: "machine", image: "/home/me/ISOs/Fedora-Workstation-Live-42.iso", want: "Fedora-Workstation-Live-42" }, + { tag: "none", kind: "machine", image: "", want: "" } + ] + } + function test_systemName(data) { + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 680, + environment: { name: "x", kind: data.kind, image: data.image, status: "stopped", settings: {} } + }) + tryVerify(() => loader.status === Loader.Ready) + compare(loader.item.systemName(loader.item.environment), data.want) + } + + // Only a Box offers to update its system from here. + function test_updateIsOfferedForBoxes() { + let menu = menuFor("box", "stopped") + verify(findChild(loader.item, "updateItem").visible) + menu.close() + menu = menuFor("machine", "stopped") + verify(!findChild(loader.item, "updateItem").visible) + menu.close() + } + + // A long name at the narrowest width is cut inside the card, never + // pushing the open action out of it (docs/TODO.md P2). + function test_longNameStaysInsideANarrowCard() { + const long = "Fedora de testes do projeto de compiladores com um nome bem comprido" + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 320, + environment: { name: long, kind: "box", status: "stopped", settings: { color: "green" } } + }) + tryVerify(() => loader.status === Loader.Ready) + const card = loader.item + const name = findChild(card, "nameLabel") + const primary = findChild(card, "primaryAction") + tryVerify(() => name.width > 0) + verify(name.truncated, "the name should be cut at 320 px") + const n = name.mapToItem(card, 0, 0) + const p = primary.mapToItem(card, 0, 0) + verify(n.x + name.width <= card.width + 0.5, "name past the card's edge") + verify(primary.visible && p.x + primary.width <= card.width + 0.5, "open action past the card's edge") + } + + // A session that won't keep its changes says so while it runs, and + // only a stopped Desktop offers to start one. + function test_ephemeralSession() { + loader.setSource("qrc:/EnvironmentCard.qml", { + width: 320, + environment: { name: "vm", kind: "machine", status: "running", ephemeral: true, settings: {} } + }) + tryVerify(() => loader.status === Loader.Ready) + verify(findChild(loader.item, "ephemeralLabel").visible) + verify(!findChild(loader.item, "startEphemeralItem").visible) + + let menu = menuFor("machine", "stopped") + verify(findChild(loader.item, "startEphemeralItem").visible) + verify(!findChild(loader.item, "ephemeralLabel").visible) + menu.close() + menu = menuFor("box", "stopped") + verify(!findChild(loader.item, "startEphemeralItem").visible) + menu.close() + } + // A hidden MenuItem still takes its full height in a Qt Quick Menu, // leaving blank rows (a Box's menu had four). function test_hiddenActionsLeaveNoGap_data() { @@ -78,6 +180,27 @@ Item { // QEMU alive but its monitor silent reports "unknown": that must not // read as the initial "Checking…" nor leave the Machine impossible to // stop from the GUI. + // The label says what the click shows (docs/TODO.md P1), and the + // button, its hint and the menu agree. + function test_primaryActionNamesTheResult_data() { + return [ + { tag: "stopped box", kind: "box", status: "stopped", label: "Open", hint: "Start demo and open its terminal" }, + { tag: "stopped machine", kind: "machine", status: "stopped", label: "Start", hint: "Start demo and show its screen" }, + { tag: "running box", kind: "box", status: "running", label: "Open", hint: "Open a terminal in demo" }, + { tag: "running machine", kind: "machine", status: "running", label: "Open", hint: "Show the screen of demo" }, + { tag: "paused machine", kind: "machine", status: "paused", label: "Resume", hint: "Continue demo where it was paused" } + ] + } + function test_primaryActionNamesTheResult(data) { + const menu = menuFor(data.kind, data.status) + const primary = findChild(loader.item, "primaryAction") + compare(primary.text, data.label) + compare(primary.Accessible.name, data.label) + compare(primary.Accessible.description, data.hint) + verify(menuItem(menu, data.label), "the menu's first action must match the button") + menu.close() + } + function test_unresponsiveMachineCanBeForceStopped() { const menu = menuFor("machine", "unknown") compare(findChild(loader.item, "statusLabel").text, "Not responding") diff --git a/gui/tests/qml/tst_environmentlistmodel.qml b/gui/tests/qml/tst_environmentlistmodel.qml index a259c35..4084d9b 100644 --- a/gui/tests/qml/tst_environmentlistmodel.qml +++ b/gui/tests/qml/tst_environmentlistmodel.qml @@ -46,6 +46,27 @@ Item { compare(card.environment.status, "running") } + // With 30 environments scrolled to the end, a poll that changes some + // statuses keeps the list where the person left it. + function test_pollKeepsTheScrollPositionWithThirtyEnvironments() { + const model = loader.item + const list = [] + for (let i = 0; i < 30; i++) + list.push(env("env" + i, "stopped")) + model.sync(list) + compare(model.count, 30) + view.positionViewAtEnd() + tryVerify(() => view.contentY > 0) + const y = view.contentY + const last = view.itemAtIndex(29) + verify(last, "the last card is shown") + list[29] = env("env29", "running") + list[3] = env("env3", "running") + model.sync(list) + compare(view.contentY, y, "a poll moved the list") + compare(view.itemAtIndex(29), last, "the visible card was recreated") + } + function test_insertRemoveAndOrder() { const model = loader.item model.sync([env("a", "stopped"), env("b", "stopped")]) diff --git a/gui/tests/qml/tst_settingsdialog.qml b/gui/tests/qml/tst_settingsdialog.qml index d67b6e4..9939b72 100644 --- a/gui/tests/qml/tst_settingsdialog.qml +++ b/gui/tests/qml/tst_settingsdialog.qml @@ -26,7 +26,8 @@ Item { return { cpusTouched: call[4], memoryTouched: call[6], shareClipboard: call[12], travelMode: call[13], vulkan: call[14], - launcher: call[16], ssh: call[17], fullscreen: call[18] + launcher: call[16], ssh: call[17], fullscreen: call[18], + clipboardDirection: call[19] } } @@ -105,5 +106,28 @@ Item { compare(saved.ssh, false) compare(saved.fullscreen, false) } + + // A one-way clipboard survives reopening Settings and saving. + function test_clipboardDirectionRoundTrips() { + compare(saveUntouched({ clipboard_direction: "to-host" }).clipboardDirection, "to-host") + compare(saveUntouched({ clipboard_direction: "to-guest" }).clipboardDirection, "to-guest") + compare(saveUntouched({}).clipboardDirection, "both") + } + + // Each guest integration says its state and next step in text. + function test_guestCapabilitiesAreSpelledOut() { + const component = Qt.createComponent("qrc:/SettingsDialog.qml") + const d = component.createObject(root, { environment: { name: "vm", kind: "machine", settings: {}, + guestCapabilities: [ + { id: "clipboard", label: "Clipboard", state: "needs_guest_component", hint: "Install spice-vdagent in the guest and sign in to its desktop" }, + { id: "shared_folder", label: "Shared folder", state: "ready", hint: "/home/me is at /mnt/omavm-share in the guest" } + ] } }) + d.open() + tryVerify(() => d.opened) + const clipboard = findChild(d.contentItem, "guestCapability-clipboard") + verify(clipboard, "clipboard row") + verify(findChild(d.contentItem, "guestCapability-shared_folder"), "shared folder row") + d.destroy() + } } } diff --git a/gui/tests/qml_test.cpp b/gui/tests/qml_test.cpp index da5d288..2f0f362 100644 --- a/gui/tests/qml_test.cpp +++ b/gui/tests/qml_test.cpp @@ -13,10 +13,34 @@ class FakeBackend : public QQmlPropertyMap { Q_OBJECT +signals: + void actionFinished(const QString &tag, bool ok, const QString &text); + public: explicit FakeBackend(QObject *parent) : QQmlPropertyMap(this, parent) {} + Q_INVOKABLE void refreshHost() {} + Q_INVOKABLE void cloneEnvironment(const QString &name, const QString &newName) { + insert(QStringLiteral("lastCall"), + QVariantList{QStringLiteral("cloneEnvironment"), name, newName}); + } + Q_INVOKABLE void refreshApps(const QString &) {} + Q_INVOKABLE void exportApp(const QString &name, const QString &id) { + insert(QStringLiteral("lastCall"), + QVariantList{QStringLiteral("exportApp"), name, id}); + } + Q_INVOKABLE void unexportApp(const QString &name, const QString &id) { + insert(QStringLiteral("lastCall"), + QVariantList{QStringLiteral("unexportApp"), name, id}); + } + + // Lets a test finish an action the way the real Backend reports it. + Q_INVOKABLE void finishAction(const QString &tag, bool ok, + const QString &text) { + emit actionFinished(tag, ok, text); + } + Q_INVOKABLE void configure(const QString &name, const QString &description, int cpus, bool cpusTouched, int memoryMiB, bool memoryTouched, bool machine, @@ -24,13 +48,15 @@ class FakeBackend : public QQmlPropertyMap { bool disconnectISO, const QString &color, bool shareClipboard, bool travelMode, bool vulkan, bool openInEmptyWorkspace, bool launcher, - bool ssh, bool fullscreen) { + bool ssh, bool fullscreen, + const QString &clipboardDirection = QString()) { insert(QStringLiteral("lastCall"), QVariantList{QStringLiteral("configure"), name, description, cpus, cpusTouched, memoryMiB, memoryTouched, machine, sharedPath, sharedReadOnly, disconnectISO, color, shareClipboard, travelMode, vulkan, - openInEmptyWorkspace, launcher, ssh, fullscreen}); + openInEmptyWorkspace, launcher, ssh, fullscreen, + clipboardDirection}); } // Audits what a screen reader gets from the accessibility tree under // item: every visible control someone can act on needs a name, and @@ -130,6 +156,8 @@ public slots: backend->insert(QStringLiteral("busy"), false); backend->insert(QStringLiteral("busyAction"), QString()); backend->insert(QStringLiteral("busyEnvironments"), QVariantMap()); + backend->insert(QStringLiteral("progress"), QVariantMap()); + backend->insert(QStringLiteral("hostCapabilities"), QVariantMap()); for (const char *color : {"themeBackground", "themeForeground", "themeAccent", "themeAccentText", "themeSelection", diff --git a/gui/tests/terminal_test.cpp b/gui/tests/terminal_test.cpp index 8699b00..be408ce 100644 --- a/gui/tests/terminal_test.cpp +++ b/gui/tests/terminal_test.cpp @@ -123,6 +123,24 @@ private slots: // Omarchy's universal copy sends Ctrl+Insert; Ctrl+Shift+C is the other // common chord. Plain Ctrl+C must still reach the program as SIGINT. + // The window keeps Alacritty's scrollback and font-size keys; everything + // else, Page Up alone and Ctrl+Shift+0 included, still reaches the program. + void viewShortcuts() { + using VS = TerminalSession::ViewShortcut; + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_PageUp, Qt::ShiftModifier), VS::PageUp); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_PageDown, Qt::ShiftModifier), VS::PageDown); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_Home, Qt::ShiftModifier), VS::Top); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_End, Qt::ShiftModifier), VS::Bottom); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_Equal, Qt::ControlModifier), VS::ZoomIn); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_Plus, Qt::ControlModifier | Qt::ShiftModifier), VS::ZoomIn); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_Minus, Qt::ControlModifier), VS::ZoomOut); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_0, Qt::ControlModifier), VS::ZoomReset); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_PageUp, Qt::NoModifier), VS::None); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_0, Qt::ControlModifier | Qt::ShiftModifier), VS::None); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_Minus, Qt::ControlModifier | Qt::ShiftModifier), VS::None); + QCOMPARE(TerminalSession::viewShortcut(Qt::Key_C, Qt::ControlModifier), VS::None); + } + void copyShortcuts() { QVERIFY(TerminalSession::isCopyShortcut(Qt::Key_Insert, Qt::ControlModifier)); QVERIFY(TerminalSession::isCopyShortcut( diff --git a/internal/backend/box/box.go b/internal/backend/box/box.go index b0ecdf3..40b70c7 100644 --- a/internal/backend/box/box.go +++ b/internal/backend/box/box.go @@ -124,3 +124,22 @@ func (b *Backend) UnexportApp(ctx context.Context, env core.Environment, id stri } return exporter.UnexportApp(ctx, env, id) } + +// Clone copies a Box through Distrobox's own --clone. Boxes on the legacy +// direct-container engine can't: it never had a clone. +func (b *Backend) Clone(ctx context.Context, source, clone core.Environment) error { + cloner, ok := b.forEnv(source).(core.Cloner) + if !ok { + return core.Unsupportedf("legacy container Boxes can't be cloned") + } + return cloner.Clone(ctx, source, clone) +} + +// Upgrade updates a Box's packages through distrobox upgrade. +func (b *Backend) Upgrade(ctx context.Context, env core.Environment) error { + upgrader, ok := b.forEnv(env).(core.Upgrader) + if !ok { + return core.Unsupportedf("legacy container Boxes can't be updated from OmaVM; update them from their terminal") + } + return upgrader.Upgrade(ctx, env) +} diff --git a/internal/backend/distrobox/distrobox.go b/internal/backend/distrobox/distrobox.go index a463422..0ba44d2 100644 --- a/internal/backend/distrobox/distrobox.go +++ b/internal/backend/distrobox/distrobox.go @@ -2,10 +2,14 @@ package distrobox import ( + "bufio" "context" "fmt" + "io" + "log/slog" "os" "os/exec" + "regexp" "strings" "unicode" @@ -59,6 +63,7 @@ func boxName(env core.Environment) string { } func (b *Backend) Create(ctx context.Context, env core.Environment) error { + b.pullImage(ctx, env.Image) return b.run(ctx, "create", "--yes", "--name", boxName(env), "--image", env.Image) } @@ -261,7 +266,43 @@ func (b *Backend) Exec(ctx context.Context, env core.Environment, args []string) } func (b *Backend) Remove(ctx context.Context, env core.Environment) error { - return b.run(ctx, "rm", "--force", boxName(env)) + engine, image, known := containerImage(ctx, boxName(env)) + if err := b.run(ctx, "rm", "--force", boxName(env)); err != nil { + return err + } + // A clone's container was made from a commit of its source + // (distrobox --clone tags it :); nobody else + // knows that image, so it goes with the clone. Refused, harmlessly, + // while another clone still uses it. Pulled images are never touched. + if known && isCloneImage(image) { + if out, err := exec.CommandContext(ctx, engine, "image", "rm", image).CombinedOutput(); err != nil { + slog.Info("clone image kept", "box", env.Name, "image", image, "reason", strings.TrimSpace(string(out))) + } + } + return nil +} + +// containerImage finds which engine holds a container and the image it +// was created from. +func containerImage(ctx context.Context, name string) (engine, image string, ok bool) { + for _, candidate := range containerEngines() { + path, err := exec.LookPath(candidate) + if err != nil { + continue + } + out, err := exec.CommandContext(ctx, path, "container", "inspect", "--format", "{{.Config.Image}}", name).Output() + if err == nil { + return path, strings.TrimSpace(string(out)), true + } + } + return "", "", false +} + +// isCloneImage recognizes the image distrobox --clone commits for a Box +// OmaVM named: "omavm-…:", local, with no registry in front. +func isCloneImage(image string) bool { + repo := strings.TrimPrefix(image, "localhost/") + return strings.HasPrefix(repo, "omavm-") && !strings.Contains(repo, "/") } func (b *Backend) command(ctx context.Context, args ...string) (*exec.Cmd, error) { @@ -300,3 +341,77 @@ func (b *Backend) runInteractive(ctx context.Context, args ...string) error { } return nil } + +// Clone makes clone a copy of source with Distrobox's --clone, which +// commits the source container to an image and creates the new one from +// it. Distrobox refuses a running source ("Cannot clone a running +// container"); this says so first, in OmaVM's words. +func (b *Backend) Clone(ctx context.Context, source, clone core.Environment) error { + status, found, err := b.find(ctx, source) + if err != nil { + return err + } + if !found { + return fmt.Errorf("%w: %s", core.ErrNotFound, missingContainer(source)) + } + if status.State != core.StateStopped { + return core.Invalidf("stop %s first: a running Box can't be copied (omavm stop %s)", source.Name, source.Name) + } + core.ReportProgress(ctx, "Copying %s", source.Name) + return b.run(ctx, "create", "--yes", "--clone", boxName(source), "--name", boxName(clone)) +} + +// Upgrade runs distrobox upgrade, which starts the Box if needed and has +// its package manager update everything (dnf, apt, pacman, ...). Each line +// it prints is reported as a stage: the package manager's own progress. +func (b *Backend) Upgrade(ctx context.Context, env core.Environment) error { + if err := b.requireContainer(ctx, env); err != nil { + return err + } + core.ReportProgress(ctx, "Updating %s", env.Name) + return b.runReporting(ctx, "upgrade", boxName(env)) +} + +var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]`) + +// runReporting runs a distrobox command, reporting each line of its output +// as a progress stage; on failure, the error carries the last lines. +func (b *Backend) runReporting(ctx context.Context, args ...string) error { + cmd, err := b.command(ctx, args...) + if err != nil { + return err + } + reader, writer := io.Pipe() + cmd.Stdout, cmd.Stderr = writer, writer + if err := cmd.Start(); err != nil { + return fmt.Errorf("distrobox %s: %w", strings.Join(args, " "), err) + } + done := make(chan struct{}) + var tail []string + go func() { + defer close(done) + scanner := bufio.NewScanner(reader) + scanner.Buffer(make([]byte, 64*1024), 1024*1024) + for scanner.Scan() { + line := strings.TrimSpace(ansiEscape.ReplaceAllString(scanner.Text(), "")) + if line == "" { + continue + } + tail = append(tail, line) + if len(tail) > 8 { + tail = tail[1:] + } + if len(line) > 120 { + line = line[:120] + "…" + } + core.ReportProgress(ctx, "%s", line) + } + }() + err = cmd.Wait() + writer.Close() + <-done + if err != nil { + return fmt.Errorf("distrobox %s: %w: %s", strings.Join(args, " "), err, strings.Join(tail, "\n")) + } + return nil +} diff --git a/internal/backend/distrobox/pull.go b/internal/backend/distrobox/pull.go new file mode 100644 index 0000000..47d7a2f --- /dev/null +++ b/internal/backend/distrobox/pull.go @@ -0,0 +1,98 @@ +package distrobox + +import ( + "bufio" + "context" + "io" + "log/slog" + "os/exec" + "strconv" + "strings" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// pullImage downloads a new Box's image before `distrobox create`, which +// would download it in silence for minutes. Pulling it here lets the +// caller follow the stages the engine prints (Podman doesn't report bytes: +// containers/podman#24887). distrobox create then finds the image local. +// +// Best-effort: distrobox knows its engine's quirks better (its own config +// file can pick the engine, Docker may need sudo), so when this pull +// fails, distrobox create still gets its own try and its own error. +func (b *Backend) pullImage(ctx context.Context, image string) { + if image == "" { + return + } + engine := "" + for _, candidate := range containerEngines() { + if path, err := exec.LookPath(candidate); err == nil { + engine = path + break + } + } + if engine == "" { + return + } + if exec.CommandContext(ctx, engine, "image", "inspect", image).Run() == nil { + return // already here: nothing to download + } + core.ReportProgress(ctx, "Downloading %s", image) + cmd := exec.CommandContext(ctx, engine, "pull", image) + reader, writer := io.Pipe() + cmd.Stdout, cmd.Stderr = writer, writer + if err := cmd.Start(); err != nil { + slog.Warn("image download failed; leaving it to distrobox", "image", image, "error", err) + return + } + done := make(chan struct{}) + var tail []string + go func() { + defer close(done) + stages := pullStages{image: image} + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + line := scanner.Text() + tail = append(tail, line) + if len(tail) > 5 { + tail = tail[1:] + } + if stage, ok := stages.next(line); ok { + core.ReportProgress(ctx, "%s", stage) + } + } + }() + err := cmd.Wait() + writer.Close() + <-done + if err != nil { + slog.Warn("image download failed; leaving it to distrobox", "image", image, "error", err, "output", strings.Join(tail, "\n")) + core.ReportProgress(ctx, "Preparing %s", image) + return + } + core.ReportProgress(ctx, "Creating the Box from %s", image) +} + +// pullStages turns the lines of `podman pull` or `docker pull` into stages +// a person can follow: which layer is downloading, never a percentage. +type pullStages struct { + image string + layers int +} + +func (p *pullStages) next(line string) (string, bool) { + line = strings.TrimSpace(line) + switch { + // Podman: one "Copying blob" line as each layer starts. + case strings.HasPrefix(line, "Copying blob"): + p.layers++ + return "Downloading " + p.image + ": layer " + strconv.Itoa(p.layers), true + case strings.HasPrefix(line, "Writing manifest"): + return "Downloading " + p.image + ": finishing", true + // Docker: ": Pull complete" as each layer lands. + case strings.HasSuffix(line, ": Pull complete"): + p.layers++ + return "Downloading " + p.image + ": " + strconv.Itoa(p.layers) + " layers done", true + } + return "", false +} diff --git a/internal/backend/distrobox/pull_test.go b/internal/backend/distrobox/pull_test.go new file mode 100644 index 0000000..3895b12 --- /dev/null +++ b/internal/backend/distrobox/pull_test.go @@ -0,0 +1,109 @@ +package distrobox + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestPullStagesFollowLayersWithoutPercentages(t *testing.T) { + podman := []string{ + "Trying to pull registry.fedoraproject.org/fedora-toolbox:42...", + "Getting image source signatures", + "Copying blob sha256:aaa", + "Copying blob sha256:bbb", + "Copying config sha256:ccc", + "Writing manifest to image destination", + "ccc", + } + p := pullStages{image: "fedora"} + var got []string + for _, line := range podman { + if stage, ok := p.next(line); ok { + got = append(got, stage) + } + } + want := []string{"Downloading fedora: layer 1", "Downloading fedora: layer 2", "Downloading fedora: finishing"} + if strings.Join(got, "|") != strings.Join(want, "|") { + t.Fatalf("podman stages = %q, want %q", got, want) + } + + p = pullStages{image: "ubuntu"} + stage, ok := p.next("a1b2c3: Pull complete") + if !ok || stage != "Downloading ubuntu: 1 layers done" { + t.Fatalf("docker stage = %q, %t", stage, ok) + } + if _, ok := p.next("a1b2c3: Downloading [====> ] 12MB/40MB"); ok { + t.Fatal("a progress bar line became a stage") + } +} + +// fakeEngine puts a podman on PATH that has no image yet and prints what +// a real pull prints. +func fakeEngine(t *testing.T, pullExit int) string { + t.Helper() + dir := t.TempDir() + log := filepath.Join(dir, "calls") + script := `#!/bin/sh +echo "$@" >> ` + log + ` +case "$1 $2" in +"image inspect") exit 1 ;; +esac +if [ "$1" = pull ]; then + echo "Trying to pull $2..." >&2 + echo "Copying blob sha256:aaa" >&2 + echo "Writing manifest to image destination" >&2 + exit ` + string(rune('0'+pullExit)) + ` +fi +` + if err := os.WriteFile(filepath.Join(dir, "podman"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + t.Setenv("DBX_CONTAINER_MANAGER", "") + return log +} + +func TestPullImageReportsStages(t *testing.T) { + log := fakeEngine(t, 0) + var stages []string + ctx := core.WithProgress(context.Background(), func(s string) { stages = append(stages, s) }) + (&Backend{}).pullImage(ctx, "fedora") + want := []string{"Downloading fedora", "Downloading fedora: layer 1", "Downloading fedora: finishing", "Creating the Box from fedora"} + if strings.Join(stages, "|") != strings.Join(want, "|") { + t.Fatalf("stages = %q, want %q", stages, want) + } + calls, _ := os.ReadFile(log) + if !strings.Contains(string(calls), "pull fedora") { + t.Fatalf("no pull: %s", calls) + } +} + +func TestFailedPullLeavesItToDistrobox(t *testing.T) { + fakeEngine(t, 1) + var stages []string + ctx := core.WithProgress(context.Background(), func(s string) { stages = append(stages, s) }) + (&Backend{}).pullImage(ctx, "fedora") + if last := stages[len(stages)-1]; last != "Preparing fedora" { + t.Fatalf("after a failed pull the stage is %q", last) + } +} + +func TestIsCloneImage(t *testing.T) { + for image, want := range map[string]bool{ + "localhost/omavm-dev-1a2b3c4d:2026-10-01": true, + "omavm-dev-1a2b3c4d:2026-10-01": true, + "registry.fedoraproject.org/fedora-toolbox:42": false, + "fedora:latest": false, + "quay.io/omavm-org/omavm-box:1": false, + "localhost/someone/omavm-x:1": false, + } { + if got := isCloneImage(image); got != want { + t.Errorf("isCloneImage(%q) = %t, want %t", image, got, want) + } + } +} diff --git a/internal/backend/distrobox/upgrade_test.go b/internal/backend/distrobox/upgrade_test.go new file mode 100644 index 0000000..00eaa4d --- /dev/null +++ b/internal/backend/distrobox/upgrade_test.go @@ -0,0 +1,49 @@ +package distrobox + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func fakeDistroboxUpgrade(t *testing.T, script string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "distrobox"), []byte("#!/bin/sh\n"+script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+":"+os.Getenv("PATH")) +} + +// The package manager's lines become the stages a person follows, without +// the color codes distrobox prints. +func TestRunReportingStreamsCleanLines(t *testing.T) { + fakeDistroboxUpgrade(t, `printf '\033[1;31m Upgrading omavm-dev...\n\033[0m' +echo "Upgrading 3 packages" +echo "" +echo "(1/3) upgrading curl" >&2 +`) + var stages []string + ctx := core.WithProgress(context.Background(), func(s string) { stages = append(stages, s) }) + if err := (&Backend{}).runReporting(ctx, "upgrade", "omavm-dev"); err != nil { + t.Fatal(err) + } + want := "Upgrading omavm-dev...|Upgrading 3 packages|(1/3) upgrading curl" + if strings.Join(stages, "|") != want { + t.Fatalf("stages = %q", stages) + } +} + +func TestRunReportingFailureCarriesTheLastLines(t *testing.T) { + fakeDistroboxUpgrade(t, `echo "error: failed retrieving file 'core.db' from mirror" +exit 1 +`) + err := (&Backend{}).runReporting(context.Background(), "upgrade", "omavm-dev") + if err == nil || !strings.Contains(err.Error(), "failed retrieving file") { + t.Fatalf("expected the package manager's error, got %v", err) + } +} diff --git a/internal/backend/qemu/applied.go b/internal/backend/qemu/applied.go new file mode 100644 index 0000000..5e4b11a --- /dev/null +++ b/internal/backend/qemu/applied.go @@ -0,0 +1,84 @@ +package qemu + +import ( + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// applied is what a running QEMU was started with, read back from its +// command line: the settings that only change on the next Start. +type applied struct { + cpus, memoryMiB int + vsock, virtiofs, cdrom bool +} + +func parseApplied(args []string) applied { + var a applied + for i, arg := range args { + next := "" + if i+1 < len(args) { + next = args[i+1] + } + switch arg { + case "-smp": + a.cpus, _ = strconv.Atoi(next) + case "-m": + a.memoryMiB, _ = strconv.Atoi(next) + case "-cdrom": + a.cdrom = true + case "-device": + a.vsock = a.vsock || strings.HasPrefix(next, "vhost-vsock-pci") + a.virtiofs = a.virtiofs || strings.HasPrefix(next, "vhost-user-fs-pci") + } + } + return a +} + +func (b *Backend) appliedConfig(name string) (applied, bool) { + pid, err := b.readPID(name) + if err != nil { + return applied{}, false + } + cmdline, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "cmdline")) + if err != nil { + return applied{}, false + } + return parseApplied(strings.Split(string(cmdline), "\x00")), true +} + +// sessionAdjustments compares a running session with the saved settings. +// travel: Travel Mode started it with fewer CPUs because the host was on +// battery. restart: a saved setting differs from what the session got and +// only applies on the next start. +func sessionAdjustments(env core.Environment, a applied, vsockAvailable bool) (restart, travel bool) { + want := env.EffectiveSettings() + switch { + case a.cpus == want.CPUs: + case a.cpus < want.CPUs && env.Settings.CPUs == 0 && !want.TravelModeDisabled: + travel = true + default: + restart = true + } + if a.memoryMiB != want.MemoryMiB { + restart = true + } + if (!want.SSHDisabled && vsockAvailable) != a.vsock { + restart = true + } + if (want.SharedPath != "") != a.virtiofs { + restart = true + } + if want.DisconnectISO && a.cdrom { + restart = true + } + if !want.DisconnectISO && !a.cdrom && env.Image != "" { + if _, err := os.Stat(env.Image); err == nil { + restart = true + } + } + return restart, travel +} diff --git a/internal/backend/qemu/applied_test.go b/internal/backend/qemu/applied_test.go new file mode 100644 index 0000000..e819ffb --- /dev/null +++ b/internal/backend/qemu/applied_test.go @@ -0,0 +1,56 @@ +package qemu + +import ( + "os" + "path/filepath" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestParseApplied(t *testing.T) { + a := parseApplied([]string{"qemu-system-x86_64", "-m", "4096", "-smp", "3", "-cdrom", "/x.iso", + "-device", "vhost-user-fs-pci,chardev=virtiofs,tag=omavm-share", "-device", "vhost-vsock-pci,guest-cid=70000"}) + if a != (applied{cpus: 3, memoryMiB: 4096, vsock: true, virtiofs: true, cdrom: true}) { + t.Fatalf("parsed %+v", a) + } +} + +func TestSessionAdjustments(t *testing.T) { + iso := filepath.Join(t.TempDir(), "x.iso") + if err := os.WriteFile(iso, nil, 0o644); err != nil { + t.Fatal(err) + } + // What a default Machine with SSH gets at Start on AC power. + base := applied{cpus: 2, memoryMiB: 2048, vsock: true, cdrom: true} + env := core.Environment{Name: "vm", Kind: core.Machine, Image: iso} + tests := []struct { + name string + change func(*core.Environment, *applied) + restart, travel bool + }{ + {"as started", func(*core.Environment, *applied) {}, false, false}, + {"travel mode on battery", func(_ *core.Environment, a *applied) { a.cpus = 1 }, false, true}, + {"pinned CPUs changed", func(e *core.Environment, _ *applied) { e.Settings.CPUs = 4 }, true, false}, + {"pinned CPUs are never travel mode", func(e *core.Environment, a *applied) { e.Settings.CPUs = 4; a.cpus = 2 }, true, false}, + {"memory changed", func(e *core.Environment, _ *applied) { e.Settings.MemoryMiB = 4096 }, true, false}, + {"ssh turned off", func(e *core.Environment, _ *applied) { e.Settings.SSHDisabled = true }, true, false}, + {"folder shared", func(e *core.Environment, _ *applied) { e.Settings.SharedPath = "/home/x" }, true, false}, + {"iso to disconnect", func(e *core.Environment, _ *applied) { e.Settings.DisconnectISO = true }, true, false}, + {"iso already gone", func(e *core.Environment, a *applied) { e.Settings.DisconnectISO = true; a.cdrom = false }, false, false}, + } + for _, tt := range tests { + e, a := env, base + tt.change(&e, &a) + restart, travel := sessionAdjustments(e, a, true) + if restart != tt.restart || travel != tt.travel { + t.Errorf("%s: restart=%t travel=%t, want %t %t", tt.name, restart, travel, tt.restart, tt.travel) + } + } + // Without vhost-vsock on the host, no SSH channel is expected. + a := base + a.vsock = false + if restart, _ := sessionAdjustments(env, a, false); restart { + t.Error("a host without vsock asked for a restart") + } +} diff --git a/internal/backend/qemu/clone_test.go b/internal/backend/qemu/clone_test.go new file mode 100644 index 0000000..295ad1b --- /dev/null +++ b/internal/backend/qemu/clone_test.go @@ -0,0 +1,44 @@ +package qemu + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestCloneCopiesTheDiskOfAStoppedMachine(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + source := core.Environment{ID: "src", Name: "vm", Kind: core.Machine} + clone := core.Environment{ID: "dst", Name: "vm copy", Kind: core.Machine} + if err := os.MkdirAll(b.dir("src"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(b.diskPath("src"), []byte("qcow2 bytes"), 0o600); err != nil { + t.Fatal(err) + } + if err := b.Clone(context.Background(), source, clone); err != nil { + t.Fatal(err) + } + if data, err := os.ReadFile(b.diskPath("dst")); err != nil || string(data) != "qcow2 bytes" { + t.Fatalf("copy: %q, %v", data, err) + } + if data, _ := os.ReadFile(b.diskPath("src")); string(data) != "qcow2 bytes" { + t.Fatal("the source disk changed") + } +} + +func TestCloneRefusesARunningMachine(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + source := core.Environment{Name: "vm", Kind: core.Machine} + startFakeQEMU(t, b, source.Name) + err := b.Clone(context.Background(), source, core.Environment{ID: "dst", Name: "copy", Kind: core.Machine}) + if !errors.Is(err, core.ErrInvalidInput) { + t.Fatalf("expected shut-down-first, got %v", err) + } + if _, statErr := os.Stat(b.dir("dst")); statErr == nil { + t.Fatal("a refused clone left a directory behind") + } +} diff --git a/internal/backend/qemu/ephemeral_test.go b/internal/backend/qemu/ephemeral_test.go new file mode 100644 index 0000000..27ffef8 --- /dev/null +++ b/internal/backend/qemu/ephemeral_test.go @@ -0,0 +1,87 @@ +package qemu + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestEphemeralStartDiscardsWritesNextToTheDisk(t *testing.T) { + dir := t.TempDir() + capture := filepath.Join(dir, "args") + t.Setenv("OMAVM_TEST_ARGS", capture) + t.Setenv("PATH", dir) + script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$OMAVM_TEST_ARGS\"\necho \"TMPDIR=$TMPDIR\" >> \"$OMAVM_TEST_ARGS\"\n" + if err := os.WriteFile(filepath.Join(dir, "qemu-system-x86_64"), []byte(script), 0o700); err != nil { + t.Fatal(err) + } + b := &Backend{stateDir: dir} + env := core.Environment{Name: "guest", Kind: core.Machine} + + if err := b.Start(context.Background(), env); err != nil { + t.Fatal(err) + } + if data, _ := os.ReadFile(capture); strings.Contains(string(data), "-snapshot\n") { + t.Fatalf("a normal start must keep changes: %s", data) + } + if err := b.StartEphemeral(context.Background(), env); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(capture) + if !strings.Contains(string(data), "-snapshot\n") { + t.Fatalf("ephemeral start without -snapshot: %s", data) + } + if !strings.Contains(string(data), "TMPDIR="+b.dir(b.key(env))) { + t.Fatalf("the overlay must live next to the Machine's disk: %s", data) + } +} + +func TestEphemeralSessionIsReportedAndBlocksSnapshots(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name, "-snapshot") + calls := recordQMP(t, b.qmpPath(env.Name)) + + st, err := b.Status(context.Background(), env) + if err != nil { + t.Fatal(err) + } + if !st.Ephemeral { + t.Fatalf("status does not say changes will be discarded: %+v", st) + } + if _, err := b.CreateSnapshot(context.Background(), env, "x"); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("snapshot in an ephemeral session: %v", err) + } + if err := b.RemoveSnapshot(context.Background(), env, "x"); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("snapshot removal in an ephemeral session: %v", err) + } + for _, c := range calls() { + if strings.HasPrefix(c.Execute, "blockdev-snapshot") { + t.Fatalf("the overlay was snapshotted: %+v", c) + } + } + // Already running without keeping changes: nothing to do. + if err := b.StartEphemeral(context.Background(), env); err != nil { + t.Fatal(err) + } +} + +// A Machine already keeping its changes must not be reported as started +// without keeping them. +func TestEphemeralStartRefusesARunningNormalSession(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + err := b.StartEphemeral(context.Background(), env) + if !errors.Is(err, core.ErrInvalidInput) || !strings.Contains(err.Error(), "shut it down first") { + t.Fatalf("expected a shut-down-first error, got %v", err) + } + if b.isEphemeral(env.Name) { + t.Fatal("normal session reported as ephemeral") + } +} diff --git a/internal/backend/qemu/guestcaps.go b/internal/backend/qemu/guestcaps.go new file mode 100644 index 0000000..447b93a --- /dev/null +++ b/internal/backend/qemu/guestcaps.go @@ -0,0 +1,94 @@ +package qemu + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +const mountHint = "In a Linux guest: sudo mkdir -p /mnt/omavm-share && sudo mount -t virtiofs omavm-share /mnt/omavm-share" + +// guestChecks is what could be checked on a running Machine's guest side; +// nil pointers mean the check couldn't run. +type guestChecks struct { + agent bool // qemu-guest-agent answers + clipboardOpen *bool // spice-vdagent opened the clipboard channel + virtiofsMount *string // where virtiofs is mounted ("" = nowhere) + sessionHasShared bool // the session was started with the folder +} + +// guestCapabilities turns settings and checks into states with a next +// step. A stopped Machine (checks == nil) is never reported ready. +func guestCapabilities(env core.Environment, checks *guestChecks) []core.GuestCapability { + settings := env.EffectiveSettings() + clipboard := core.GuestCapability{ID: "clipboard", Label: "Clipboard"} + switch { + case settings.ClipboardDisabled: + clipboard.State, clipboard.Hint = core.GuestOff, "Turned off in Settings" + case checks == nil || checks.clipboardOpen == nil: + clipboard.State, clipboard.Hint = core.GuestNotVerified, "Checked while the Machine is running" + case *checks.clipboardOpen: + clipboard.State, clipboard.Hint = core.GuestReady, "Text copies both ways while its window is active" + default: + clipboard.State, clipboard.Hint = core.GuestNeedsComponent, "Install spice-vdagent in the guest and sign in to its desktop" + } + + shared := core.GuestCapability{ID: "shared_folder", Label: "Shared folder"} + switch { + case settings.SharedPath == "": + shared.State, shared.Hint = core.GuestOff, "Choose a folder in Settings to share it" + case checks == nil: + shared.State, shared.Hint = core.GuestNotVerified, "Checked while the Machine is running. "+mountHint + case !checks.sessionHasShared: + shared.State, shared.Hint = core.GuestNeedsRestart, "Restart the Machine to share "+settings.SharedPath + case !checks.agent || checks.virtiofsMount == nil: + shared.State, shared.Hint = core.GuestNotVerified, "Install qemu-guest-agent in the guest to check it. "+mountHint + case *checks.virtiofsMount != "": + shared.State, shared.Hint = core.GuestReady, fmt.Sprintf("%s is at %s in the guest", settings.SharedPath, *checks.virtiofsMount) + default: + shared.State, shared.Hint = core.GuestNeedsComponent, mountHint + } + return []core.GuestCapability{clipboard, shared} +} + +// guestChannels reports which virtio-serial ports the guest has opened, +// by chardev label: "clipboard" when spice-vdagent runs, "qga0" when +// qemu-guest-agent does. QEMU shows it as the chardev's frontend being +// open, so this needs nothing from the guest itself. +func guestChannels(qmpPath string) (map[string]bool, error) { + raw, err := qmpExecute(qmpPath, "query-chardev", nil) + if err != nil { + return nil, err + } + var chardevs []struct { + Label string `json:"label"` + FrontendOpen bool `json:"frontend-open"` + } + if err := json.Unmarshal(raw, &chardevs); err != nil { + return nil, err + } + open := map[string]bool{} + for _, c := range chardevs { + open[c.Label] = c.FrontendOpen + } + return open, nil +} + +func (b *Backend) guestChecks(ctx context.Context, env core.Environment, agent bool, channels map[string]bool) *guestChecks { + key := b.key(env) + c := &guestChecks{agent: agent} + if open, ok := channels["clipboard"]; ok { + c.clipboardOpen = &open + } + if a, ok := b.appliedConfig(key); ok { + c.sessionHasShared = a.virtiofs + } + if agent && c.sessionHasShared { + if mount, err := virtiofsMountpoint(ctx, b.qgaPath(key)); err == nil { + c.virtiofsMount = &mount + } + } + return c +} diff --git a/internal/backend/qemu/guestcaps_test.go b/internal/backend/qemu/guestcaps_test.go new file mode 100644 index 0000000..fcdbafc --- /dev/null +++ b/internal/backend/qemu/guestcaps_test.go @@ -0,0 +1,38 @@ +package qemu + +import ( + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestGuestCapabilities(t *testing.T) { + yes, no := true, false + mounted, unmounted := "/mnt/omavm-share", "" + shared := core.EnvironmentSettings{SharedPath: "/home/me/work"} + tests := []struct { + name string + settings core.EnvironmentSettings + checks *guestChecks + clipboard, sharedFolder string + }{ + {"stopped is never ready", shared, nil, core.GuestNotVerified, core.GuestNotVerified}, + {"turned off", core.EnvironmentSettings{ClipboardDisabled: true}, &guestChecks{agent: true, clipboardOpen: &yes}, core.GuestOff, core.GuestOff}, + {"vdagent running, folder mounted", shared, &guestChecks{agent: true, clipboardOpen: &yes, virtiofsMount: &mounted, sessionHasShared: true}, core.GuestReady, core.GuestReady}, + {"no vdagent, folder not mounted", shared, &guestChecks{agent: true, clipboardOpen: &no, virtiofsMount: &unmounted, sessionHasShared: true}, core.GuestNeedsComponent, core.GuestNeedsComponent}, + {"folder shared after start", shared, &guestChecks{agent: true, clipboardOpen: &yes, sessionHasShared: false}, core.GuestReady, core.GuestNeedsRestart}, + {"no guest agent to check the mount", shared, &guestChecks{clipboardOpen: &yes, sessionHasShared: true}, core.GuestReady, core.GuestNotVerified}, + {"channel unreadable", shared, &guestChecks{agent: true, sessionHasShared: true, virtiofsMount: &mounted}, core.GuestNotVerified, core.GuestReady}, + } + for _, tt := range tests { + caps := guestCapabilities(core.Environment{Name: "vm", Kind: core.Machine, Settings: tt.settings}, tt.checks) + if caps[0].State != tt.clipboard || caps[1].State != tt.sharedFolder { + t.Errorf("%s: clipboard=%s shared=%s, want %s %s", tt.name, caps[0].State, caps[1].State, tt.clipboard, tt.sharedFolder) + } + for _, c := range caps { + if c.Hint == "" { + t.Errorf("%s: %s has no next step", tt.name, c.ID) + } + } + } +} diff --git a/internal/backend/qemu/iso_test.go b/internal/backend/qemu/iso_test.go index 3472626..43977a4 100644 --- a/internal/backend/qemu/iso_test.go +++ b/internal/backend/qemu/iso_test.go @@ -50,7 +50,7 @@ func TestStartAttachesTheInstallationMedia(t *testing.T) { // Center placed the window. The viewer now does it, told by Open. func TestViewerIsToldWhereAndHowToOpen(t *testing.T) { args := strings.Join(viewerArgs(core.Environment{Name: "vm", Kind: core.Machine}), " ") - for _, want := range []string{"--empty-workspace true", "--fullscreen true", "--share-clipboard true", "--title vm — OmaVM"} { + for _, want := range []string{"--empty-workspace true", "--fullscreen true", "--share-clipboard true", "--title vm — OmaVM", "--environment vm"} { if !strings.Contains(args, want) { t.Errorf("default viewer args %q lack %q", args, want) } @@ -76,3 +76,18 @@ func TestIOErrorReadsAsPausedWithTheReason(t *testing.T) { t.Fatalf("Machines get a %d-byte disk, want 1 TiB", diskSize) } } + +// The viewer enforces a one-way clipboard; it learns it from its arguments. +func TestViewerArgsCarryTheClipboardDirection(t *testing.T) { + for setting, want := range map[core.EnvironmentSettings]string{ + {}: "--share-clipboard true", + {ClipboardDisabled: true}: "--share-clipboard false", + {ClipboardDirection: "to-host"}: "--share-clipboard to-host", + {ClipboardDirection: "to-guest"}: "--share-clipboard to-guest", + } { + args := strings.Join(viewerArgs(core.Environment{Name: "vm", Kind: core.Machine, Settings: setting}), " ") + if !strings.Contains(args, want) { + t.Errorf("%+v: args %q lack %q", setting, args, want) + } + } +} diff --git a/internal/backend/qemu/lifecycle_test.go b/internal/backend/qemu/lifecycle_test.go index bf6a569..9bfc570 100644 --- a/internal/backend/qemu/lifecycle_test.go +++ b/internal/backend/qemu/lifecycle_test.go @@ -347,13 +347,13 @@ func TestMissingBinaryDiagnostic(t *testing.T) { // startFakeQEMU runs a stand-in for this Machine's QEMU: a long-lived // process with -pidfile on its command line, recorded in // that pidfile, like the real one. -func startFakeQEMU(t *testing.T, b *Backend, name string) *exec.Cmd { +func startFakeQEMU(t *testing.T, b *Backend, name string, extra ...string) *exec.Cmd { t.Helper() if err := os.MkdirAll(b.dir(name), 0700); err != nil { t.Fatal(err) } // "; :" keeps sh from exec'ing sleep, which would drop the arguments. - child := exec.Command("sh", "-c", "sleep 60; :", "qemu-system-x86_64", "-pidfile", b.pidPath(name)) + child := exec.Command("sh", append([]string{"-c", "sleep 60; :", "qemu-system-x86_64", "-pidfile", b.pidPath(name)}, extra...)...) if err := child.Start(); err != nil { t.Fatal(err) } @@ -404,3 +404,99 @@ func TestStalePidfileOfAnotherProcessIsNotRunning(t *testing.T) { t.Fatalf("Force Stop killed an unrelated process: %v", err) } } + +// Without access to /dev/kvm, QEMU's error doesn't say what to do; the +// failure says it, and is classified as unsupported on this computer. +func TestStartWithoutKVMSaysHowToFixIt(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + script := "#!/bin/sh\necho 'Could not access KVM kernel module: No such file or directory' >&2\nexit 1\n" + if err := os.WriteFile(filepath.Join(dir, "qemu-system-x86_64"), []byte(script), 0o700); err != nil { + t.Fatal(err) + } + saved := devRoot + devRoot = t.TempDir() // no kvm node + t.Cleanup(func() { devRoot = saved }) + b := &Backend{stateDir: dir} + err := b.Start(context.Background(), core.Environment{Name: "guest", Kind: core.Machine}) + if !errors.Is(err, core.ErrUnsupported) || !strings.Contains(err.Error(), "kvm group") { + t.Fatalf("expected an actionable KVM error, got %v", err) + } +} + +// QEMU deletes its pidfile on any normal exit; one left behind means the +// process was killed or crashed, and the stopped Machine says so instead +// of looking like it was shut down. +func TestSessionThatEndedWithoutShuttingDownIsReported(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + st, err := b.Status(context.Background(), env) + if err != nil || strings.Contains(st.Warning, "without shutting down") { + t.Fatalf("a Machine that was never started: %+v, %v", st, err) + } + if err := os.MkdirAll(b.dir(env.Name), 0o700); err != nil { + t.Fatal(err) + } + // A pid no process has: the session's QEMU is gone. + if err := os.WriteFile(b.pidPath(env.Name), []byte("2147483646"), 0o600); err != nil { + t.Fatal(err) + } + st, err = b.Status(context.Background(), env) + if err != nil || st.State != core.StateStopped || !strings.Contains(st.Warning, "ended without shutting down") || !strings.Contains(st.Warning, "coredumpctl") { + t.Fatalf("unexpected end not reported: %+v, %v", st, err) + } +} + +func TestKnownStartFailuresSayWhatToDo(t *testing.T) { + env := core.Environment{Name: "guest", Kind: core.Machine} + locked := "qemu-system-x86_64: -drive file=/x/disk.qcow2,if=virtio,format=qcow2: Failed to get \"write\" lock\nIs another process using the image [/x/disk.qcow2]?" + if err := startFailure(env, locked); !errors.Is(err, core.ErrBusy) || !strings.Contains(err.Error(), "in use by another program") { + t.Fatalf("locked disk: %v", err) + } + memory := "qemu-system-x86_64: cannot set up guest memory 'pc.ram': Cannot allocate memory" + if err := startFailure(env, memory); !errors.Is(err, core.ErrUnsupported) || !strings.Contains(err.Error(), "lower its memory") { + t.Fatalf("memory: %v", err) + } + if err := startFailure(env, "qemu-system-x86_64: something else"); err != nil { + t.Fatalf("unknown output must stay as QEMU said it: %v", err) + } +} + +// More memory than the host has is refused before QEMU runs, and an +// installation image this user can't read doesn't stop the Machine from +// starting from its disk. +func TestStartChecksMemoryAndReadableMedia(t *testing.T) { + if _, ok := hostMemoryMiB(); !ok { + t.Skip("no /proc/meminfo") + } + dir := t.TempDir() + capture := filepath.Join(dir, "args") + t.Setenv("OMAVM_TEST_ARGS", capture) + t.Setenv("PATH", dir) + if err := os.WriteFile(filepath.Join(dir, "qemu-system-x86_64"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$OMAVM_TEST_ARGS\"\n"), 0o700); err != nil { + t.Fatal(err) + } + b := &Backend{stateDir: dir} + env := core.Environment{Name: "guest", Kind: core.Machine, Settings: core.EnvironmentSettings{MemoryMiB: 1 << 30}} + if err := b.Start(context.Background(), env); !errors.Is(err, core.ErrInvalidInput) || !strings.Contains(err.Error(), "more than this computer has") { + t.Fatalf("expected a memory error, got %v", err) + } + if _, err := os.Stat(capture); err == nil { + t.Fatal("QEMU ran anyway") + } + + if os.Geteuid() == 0 { + return // root reads anything + } + iso := filepath.Join(t.TempDir(), "x.iso") + if err := os.WriteFile(iso, nil, 0o000); err != nil { + t.Fatal(err) + } + env = core.Environment{Name: "guest", Kind: core.Machine, Image: iso} + if err := b.Start(context.Background(), env); err != nil { + t.Fatal(err) + } + if data, _ := os.ReadFile(capture); strings.Contains(string(data), "-cdrom") { + t.Fatalf("an unreadable ISO was passed to QEMU: %s", data) + } +} diff --git a/internal/backend/qemu/qemu.go b/internal/backend/qemu/qemu.go index 3df74bf..cf2ec55 100644 --- a/internal/backend/qemu/qemu.go +++ b/internal/backend/qemu/qemu.go @@ -33,7 +33,8 @@ import ( // has; when the host fills up, QEMU pauses the Machine (io-error) and // Status says why. const diskSize int64 = 1 << 40 -const gracefulShutdownTimeout = 10 * time.Second + +var gracefulShutdownTimeout = 10 * time.Second // Backend implements core.Backend for Machine environments via // qemu-img and qemu-system-x86_64. It assumes KVM is available @@ -145,16 +146,43 @@ func (b *Backend) Create(ctx context.Context, env core.Environment) error { } func (b *Backend) Start(ctx context.Context, env core.Environment) error { + return b.start(ctx, env, false) +} + +// StartEphemeral starts a session whose disk writes go to a temporary +// overlay QEMU throws away when it exits (-snapshot), so the Machine +// shuts down exactly as it was. The overlay lives in the Machine's state +// directory rather than /var/tmp: it grows on the same disk as the qcow2, +// where a full disk is already explained (ioErrorStatus). +func (b *Backend) StartEphemeral(ctx context.Context, env core.Environment) error { + return b.start(ctx, env, true) +} + +// isEphemeral reports whether the running QEMU was started by +// StartEphemeral, read from its command line like the vsock CID. +func (b *Backend) isEphemeral(name string) bool { + pid, err := b.readPID(name) + return err == nil && processHasArg(pid, "-snapshot") +} + +func (b *Backend) start(ctx context.Context, env core.Environment, ephemeral bool) error { running, err := b.isRunning(b.key(env)) if err != nil { return err } if running { + if ephemeral && !b.isEphemeral(b.key(env)) { + return core.Invalidf("%s is already running and keeping its changes; shut it down first to start without keeping them", env.Name) + } return nil } if err := b.checkNameLength(b.key(env)); err != nil { return err } + if ended := b.unexpectedEnd(b.key(env)); ended != "" { + // Kept in the log: the next Start overwrites the evidence. + slog.Warn("previous session ended unexpectedly", "machine", env.Name, "detail", ended) + } for _, socket := range []string{b.qgaPath(b.key(env)), b.qmpPath(b.key(env))} { if err := os.Remove(socket); err != nil && !errors.Is(err, os.ErrNotExist) { @@ -173,6 +201,9 @@ func (b *Backend) Start(ctx context.Context, env core.Environment) error { } slog.Info("travel mode: reduced CPU allocation while on battery", "machine", env.Name, "cpus", settings.CPUs) } + if total, ok := hostMemoryMiB(); ok && settings.MemoryMiB > total { + return core.Invalidf("%s is set to %d MiB of memory, more than this computer has (%d MiB); lower it in Settings", env.Name, settings.MemoryMiB, total) + } virtiofsRunning := false if settings.SharedPath != "" { if err := b.startVirtiofs(ctx, b.key(env), settings); err != nil { @@ -211,11 +242,19 @@ func (b *Backend) Start(ctx context.Context, env core.Environment) error { "-chardev", "socket,id=virtiofs,path="+b.virtiofsPath(b.key(env)), "-device", "vhost-user-fs-pci,chardev=virtiofs,tag=omavm-share") } + var qemuEnv []string + if ephemeral { + args = append(args, "-snapshot") + qemuEnv = []string{"TMPDIR=" + b.dir(b.key(env))} + } if env.Image != "" && !settings.DisconnectISO { // The disk boots first anyway: an ISO deleted, moved or on a USB // stick that isn't plugged in must not keep an installed Machine // from starting (QEMU refuses a -cdrom it can't open). - if _, err := os.Stat(env.Image); err == nil { + // Opened, not just stat'ed: a file this user can't read makes + // QEMU refuse to start at all ("Permission denied"). + if f, err := os.Open(env.Image); err == nil { + f.Close() args = append(args, "-cdrom", env.Image, "-boot", "order=cd,menu=on") } else { slog.Warn("installation media not found; starting from the disk", "machine", env.Name, "image", env.Image, "error", err) @@ -229,14 +268,14 @@ func (b *Backend) Start(ctx context.Context, env core.Environment) error { return err } } - out, err := runQEMU(ctx, "qemu-system-x86_64", withVsock(args, vsock, cid)...) + out, err := runQEMUEnv(ctx, qemuEnv, "qemu-system-x86_64", withVsock(args, vsock, cid)...) if err != nil && vsock && cidTaken(out) { // Another VM on this host holds the CID: draw a new one. The // guest's SSH host key is remembered per Machine, not per CID. if cid, err = b.guestCID(b.key(env), true); err != nil { return err } - out, err = runQEMU(ctx, "qemu-system-x86_64", withVsock(args, vsock, cid)...) + out, err = runQEMUEnv(ctx, qemuEnv, "qemu-system-x86_64", withVsock(args, vsock, cid)...) } if err != nil { // Two concurrent Start calls can both observe "not running" above @@ -257,6 +296,14 @@ func (b *Backend) Start(ctx context.Context, env core.Environment) error { if virtiofsRunning { _ = b.stopVirtiofs(b.key(env)) } + if known := startFailure(env, out); known != nil { + return known + } + if !canOpenRW(filepath.Join(devRoot, "kvm")) { + // QEMU's own words ("Could not access KVM kernel module") + // don't say what to do about it. + return core.Unsupportedf("this computer can't run Desktops yet: hardware virtualization (/dev/kvm) is missing or not accessible to your user. Enable virtualization in the firmware and add your user to the kvm group, then log in again (QEMU said: %s)", out) + } return qemuErr("qemu-system-x86_64", err, out) } return nil @@ -353,11 +400,22 @@ func displayArgs(openGL, vulkan bool, memoryMiB int, virtiofs bool) []string { } func runQEMU(ctx context.Context, name string, args ...string) (string, error) { + return runQEMUEnv(ctx, nil, name, args...) +} + +// runQEMUEnv is runQEMU with extra environment variables on top of +// OmaVM's own. +func runQEMUEnv(ctx context.Context, env []string, name string, args ...string) (string, error) { path, err := qemuBinaryPath(name) if err != nil { return "", err } - return runOutput(ctx, path, args...) + cmd := exec.CommandContext(ctx, path, args...) + if len(env) > 0 { + cmd.Env = append(os.Environ(), env...) + } + out, err := cmd.CombinedOutput() + return strings.TrimSpace(string(out)), err } // qemuErr wraps a failed qemu-img/qemu-system-x86_64 invocation with the @@ -498,7 +556,9 @@ func viewerArgs(env core.Environment) []string { return []string{ "--display-fd", "3", "--title", env.Name + " — OmaVM", - "--share-clipboard", strconv.FormatBool(!settings.ClipboardDisabled), + // Lets the viewer reconnect after losing the display (omavm open). + "--environment", env.Name, + "--share-clipboard", settings.ClipboardMode(), "--empty-workspace", strconv.FormatBool(!settings.EmptyWorkspaceDisabled), "--fullscreen", strconv.FormatBool(!settings.FullscreenDisabled), } @@ -581,18 +641,35 @@ func (b *Backend) CreateSnapshot(ctx context.Context, env core.Environment, tag } return false, nil } + if b.isEphemeral(b.key(env)) { + return false, errEphemeralSnapshot(env) + } // With the guest agent, the guest flushes and freezes its // filesystems for the instant of the snapshot. thaw := freezeGuest(ctx, b.qgaPath(b.key(env)), env.Name) if thaw != nil { defer thaw() } - if _, err := qmpExecute(b.qmpPath(b.key(env)), "blockdev-snapshot-internal-sync", map[string]any{"device": bootDisk, "name": tag}); err != nil { + if _, err := qmpExecuteTimeout(b.qmpPath(b.key(env)), "blockdev-snapshot-internal-sync", map[string]any{"device": bootDisk, "name": tag}, qmpSlowTimeout); err != nil { + // No reply: look before deciding, rather than report a failure + // for a snapshot that exists (it would sit on the disk, unknown). + if errors.Is(err, errQMPNoReply) { + if names, qerr := qmpDiskSnapshots(b.qmpPath(b.key(env))); qerr == nil && names[tag] { + return thaw == nil, nil + } + } return false, fmt.Errorf("snapshot the disk: %w", err) } return thaw == nil, nil } +// errEphemeralSnapshot: during a session started without keeping changes, +// QEMU's active disk is the temporary overlay, so a snapshot taken through +// QMP would vanish at shutdown and a deletion would miss the real disk. +func errEphemeralSnapshot(env core.Environment) error { + return core.Unsupportedf("%s is running without keeping changes, and a snapshot taken now would be discarded with them; shut it down to manage snapshots", env.Name) +} + // GoToSnapshot restores the disk to a snapshot. Only a stopped Machine: // QEMU refuses to revert a disk-only snapshot under a running system // ("Revert to it offline using qemu-img"), and every snapshot here is @@ -607,6 +684,9 @@ func (b *Backend) GoToSnapshot(ctx context.Context, env core.Environment, tag st } out, err := runQEMU(ctx, "qemu-img", "snapshot", "-a", tag, b.diskPath(b.key(env))) if err != nil { + if strings.Contains(out, "Failed to load snapshot: No such file or directory") { + return fmt.Errorf("%w: delete it from the list (%s)", core.ErrSnapshotGone, out) + } return qemuErr("qemu-img snapshot -a", err, out) } return nil @@ -620,11 +700,26 @@ func (b *Backend) RemoveSnapshot(ctx context.Context, env core.Environment, tag if !running { out, err := runQEMU(ctx, "qemu-img", "snapshot", "-d", tag, b.diskPath(b.key(env))) if err != nil { + if strings.Contains(out, "snapshot not found") { + return fmt.Errorf("%w (%s)", core.ErrSnapshotGone, out) + } return qemuErr("qemu-img snapshot -d", err, out) } return nil } - if _, err := qmpExecute(b.qmpPath(b.key(env)), "blockdev-snapshot-delete-internal-sync", map[string]any{"device": bootDisk, "name": tag}); err != nil { + if b.isEphemeral(b.key(env)) { + return errEphemeralSnapshot(env) + } + if _, err := qmpExecuteTimeout(b.qmpPath(b.key(env)), "blockdev-snapshot-delete-internal-sync", map[string]any{"device": bootDisk, "name": tag}, qmpSlowTimeout); err != nil { + if errors.Is(err, errQMPNoReply) { + if names, qerr := qmpDiskSnapshots(b.qmpPath(b.key(env))); qerr == nil && !names[tag] { + return nil // it is gone: the deletion went through + } + } + var qerr *qmpError + if errors.As(err, &qerr) && strings.Contains(qerr.Desc, "does not exist") { + return fmt.Errorf("%w (%s)", core.ErrSnapshotGone, qerr.Desc) + } return fmt.Errorf("delete the disk snapshot: %w", err) } return nil @@ -639,10 +734,12 @@ func (b *Backend) Stop(ctx context.Context, env core.Environment) error { _ = b.stopVirtiofs(b.key(env)) return nil } + wasPaused := false if status, err := qmpStatus(b.qmpPath(b.key(env))); err == nil && (status == "paused" || status == "suspended") { if err := qmpCommand(b.qmpPath(b.key(env)), "cont"); err != nil { return fmt.Errorf("resume machine before shutdown: %w", err) } + wasPaused = true } // A slow guest must never turn an ordinary shutdown into a power cut. @@ -666,6 +763,13 @@ func (b *Backend) Stop(ctx context.Context, env core.Environment) error { } } } + if wasPaused { + // It was resumed only so it could shut down: put it back the + // way it was found rather than leave it running. + if err := qmpCommand(b.qmpPath(b.key(env)), "stop"); err == nil { + return fmt.Errorf("shutdown is taking longer than expected; the machine was paused again, as it was, to protect your work. Resume it and shut it down from inside, or use Force Stop if necessary") + } + } return fmt.Errorf("shutdown is taking longer than expected; the machine was left running to protect your work. Wait or use Force Stop if necessary") } @@ -675,10 +779,13 @@ func (b *Backend) Restart(ctx context.Context, env core.Environment) error { } else if !running { return b.Start(ctx, env) } + // A session started without keeping changes restarts the same way: + // restarting must not quietly begin keeping them. + ephemeral := b.isEphemeral(b.key(env)) if err := b.Stop(ctx, env); err != nil { return err } - return b.Start(ctx, env) + return b.start(ctx, env, ephemeral) } func (b *Backend) Pause(ctx context.Context, env core.Environment) error { @@ -696,9 +803,31 @@ func (b *Backend) Resume(ctx context.Context, env core.Environment) error { } else if !running { return core.Unsupportedf("machine is not running") } - return qmpCommand(b.qmpPath(b.key(env)), "cont") + if err := qmpCommand(b.qmpPath(b.key(env)), "cont"); err != nil { + return err + } + // A Machine paused because its disk couldn't be written retries the + // write on cont and pauses again at once if the host's disk is still + // full: say so instead of reporting a Resume that didn't hold. + for i := 0; i < resumeChecks; i++ { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(resumeCheckInterval): + } + if status, err := qmpStatus(b.qmpPath(b.key(env))); err == nil && status == "io-error" { + return core.Unsupportedf("%s paused again: %s", env.Name, ioErrorStatus(b.dir(b.key(env))).Detail) + } + } + return nil } +// How long Resume watches for a Machine pausing again on a disk error. +var ( + resumeChecks = 3 + resumeCheckInterval = 100 * time.Millisecond +) + func (b *Backend) ForceStop(ctx context.Context, env core.Environment) error { if running, err := b.isRunning(b.key(env)); err != nil { return err @@ -743,16 +872,121 @@ func (b *Backend) Status(ctx context.Context, env core.Environment) (core.Status return core.Status{}, err } if !running { - return core.Status{State: core.StateStopped}, nil + warnings := []string{} + if ended := b.unexpectedEnd(b.key(env)); ended != "" { + warnings = append(warnings, ended) + } + if low := lowSpaceWarning(b.dir(b.key(env))); low != "" { + warnings = append(warnings, low) + } + return core.Status{State: core.StateStopped, Warning: strings.Join(warnings, "; ")}, nil } status, err := qmpStatus(b.qmpPath(b.key(env))) if err != nil { return core.Status{State: core.StateUnknown, Detail: err.Error()}, nil } + var st core.Status if status == "io-error" { - return ioErrorStatus(b.dir(b.key(env))), nil + st = ioErrorStatus(b.dir(b.key(env))) + } else { + st = statusFromQMP(status) + st.Warning = lowSpaceWarning(b.dir(b.key(env))) + } + st.Ephemeral = b.isEphemeral(b.key(env)) + if a, ok := b.appliedConfig(b.key(env)); ok { + st.RestartNeeded, st.TravelMode = sessionAdjustments(env, a, canOpenRW(vhostVsockPath)) + } + return st, nil +} + +// startFailure turns QEMU's start errors that have a known cause into one +// that says what to do; nil when the output isn't one of them. +func startFailure(env core.Environment, out string) error { + switch { + case strings.Contains(out, `Failed to get "write" lock`): + return core.Busyf("%s's disk is in use by another program (another QEMU, or qemu-img); close it and try again (QEMU said: %s)", env.Name, out) + case strings.Contains(out, "cannot set up guest memory"): + return core.Unsupportedf("this computer doesn't have %d MiB of memory free for %s right now; close some programs or lower its memory in Settings (QEMU said: %s)", env.EffectiveSettings().MemoryMiB, env.Name, out) + } + return nil +} + +// hostMemoryMiB is the host's total memory, from /proc/meminfo. +func hostMemoryMiB() (int, bool) { + data, err := os.ReadFile("/proc/meminfo") + if err != nil { + return 0, false + } + for _, line := range strings.Split(string(data), "\n") { + if rest, ok := strings.CutPrefix(line, "MemTotal:"); ok { + kib, err := strconv.Atoi(strings.TrimSuffix(strings.TrimSpace(rest), " kB")) + if err != nil { + return 0, false + } + return kib / 1024, true + } + } + return 0, false +} + +// unexpectedEnd explains a session that ended without shutting down. QEMU +// deletes its pidfile when it exits, whether the guest powered off or +// Force Stop quit it (checked on QEMU 11.1); a pidfile left behind with no +// QEMU on it means the process was killed or crashed (the host ran out of +// memory, a QEMU bug). Its stderr is gone with -daemonize, so the system's +// own records are where the cause is. +func (b *Backend) unexpectedEnd(name string) string { + info, err := os.Stat(b.pidPath(name)) + if err != nil { + return "" + } + return fmt.Sprintf("the session started %s ended without shutting down (the process was killed or crashed); if it happens again, `coredumpctl list qemu-system-x86_64` or `journalctl -b -k` may show why", + info.ModTime().Local().Format("2006-01-02 15:04")) +} + +// lowSpace is the free space under which a Machine is warned about: its +// sparse disk claims host space as the guest writes, and an update or an +// installer can take a few GiB at once. +const lowSpace = 4 << 30 + +// lowSpaceWarning warns before the host's disk fills up under a Machine, +// when there is still time to free space. It can't promise anything: the +// guest can write more than what is free now at any moment. +func lowSpaceWarning(dir string) string { + free, ok := freeSpace(dir) + if !ok { + return "" + } + return spaceWarning(free) +} + +func spaceWarning(free uint64) string { + if free >= lowSpace { + return "" + } + return fmt.Sprintf("only %s free on this computer: the Machine pauses if it runs out", formatSize(free)) +} + +func freeSpace(dir string) (uint64, bool) { + // A Machine's directory may not exist yet; its disk lands in the + // state directory above it. + for ; dir != "/" && dir != "."; dir = filepath.Dir(dir) { + var fs syscall.Statfs_t + if err := syscall.Statfs(dir, &fs); err == nil { + return fs.Bavail * uint64(fs.Bsize), true + } + } + return 0, false +} + +func formatSize(bytes uint64) string { + if bytes >= 1<<30 { + return fmt.Sprintf("%.1f GiB", float64(bytes)/(1<<30)) + } + if bytes >= 1<<20 { + return fmt.Sprintf("%d MiB", bytes>>20) } - return statusFromQMP(status), nil + return fmt.Sprintf("%d KiB", bytes>>10) } // ioErrorStatus explains a Machine QEMU paused because its disk couldn't @@ -776,12 +1010,21 @@ func (b *Backend) Integration(ctx context.Context, env core.Environment) (core.I return core.IntegrationReport{}, err } if !running { - return core.IntegrationReport{GuestAgent: "stopped", Hint: "Start the Machine to check guest tools"}, nil + return core.IntegrationReport{GuestAgent: "stopped", Hint: "Start the Machine to check guest tools", Capabilities: guestCapabilities(env, nil)}, nil + } + // The agent's port closed means no agent: no need to wait out a ping + // that nobody will answer (it held every poll of the list for 700 ms + // with a guest that has none). Open, the ping confirms it answers. + channels, _ := guestChannels(b.qmpPath(b.key(env))) + agent := false + if open, known := channels["qga0"]; !known || open { + agent = qgaPing(ctx, b.qgaPath(b.key(env))) == nil } - if err := qgaPing(ctx, b.qgaPath(b.key(env))); err != nil { - return core.IntegrationReport{GuestAgent: "unavailable", Hint: "Install and start qemu-guest-agent inside the guest"}, nil + caps := guestCapabilities(env, b.guestChecks(ctx, env, agent, channels)) + if !agent { + return core.IntegrationReport{GuestAgent: "unavailable", Hint: "Install and start qemu-guest-agent inside the guest", Capabilities: caps}, nil } - return core.IntegrationReport{GuestAgent: "connected"}, nil + return core.IntegrationReport{GuestAgent: "connected", Capabilities: caps}, nil } func statusFromQMP(status string) core.Status { @@ -862,3 +1105,45 @@ func runOutput(ctx context.Context, name string, args ...string) (string, error) out, err := cmd.CombinedOutput() return strings.TrimSpace(string(out)), err } + +// cloneMargin is the free space left over after a Machine's disk is +// copied, so the copy doesn't leave the host's disk full. +const cloneMargin = 1 << 30 + +// Clone copies a stopped Machine's disk, internal snapshots included, to +// a new Machine. cp keeps the file sparse and, on a filesystem that +// supports it (btrfs, xfs), shares the blocks until either side writes. +func (b *Backend) Clone(ctx context.Context, source, clone core.Environment) error { + src, dst := b.key(source), b.key(clone) + running, err := b.isRunning(src) + if err != nil { + return err + } + if running { + return core.Invalidf("shut down %s first: its disk can't be copied while it runs", source.Name) + } + if err := b.checkNameLength(dst); err != nil { + return err + } + disk := b.diskPath(src) + info, err := os.Stat(disk) + if err != nil { + return fmt.Errorf("%s's disk: %w", source.Name, err) + } + used := uint64(0) + if st, ok := info.Sys().(*syscall.Stat_t); ok { + used = uint64(st.Blocks) * 512 + } + if free, ok := freeSpace(b.stateDir); ok && free < used+cloneMargin { + return core.Unsupportedf("not enough space to copy %s: its disk uses %s and this computer has %s free", source.Name, formatSize(used), formatSize(free)) + } + if err := os.MkdirAll(b.dir(dst), 0o755); err != nil { + return fmt.Errorf("create machine state dir: %w", err) + } + core.ReportProgress(ctx, "Copying the disk of %s (%s)", source.Name, formatSize(used)) + if out, err := runOutput(ctx, "cp", "--reflink=auto", "--sparse=always", disk, b.diskPath(dst)); err != nil { + _ = os.RemoveAll(b.dir(dst)) + return fmt.Errorf("copy the disk of %s: %w: %s", source.Name, err, out) + } + return nil +} diff --git a/internal/backend/qemu/qga.go b/internal/backend/qemu/qga.go index f7f004b..4dac043 100644 --- a/internal/backend/qemu/qga.go +++ b/internal/backend/qemu/qga.go @@ -87,23 +87,56 @@ func qgaSync(conn net.Conn) (*json.Decoder, error) { } func qgaExecute(conn net.Conn, dec *json.Decoder, command string, timeout time.Duration) error { + _, err := qgaQuery(conn, dec, command, timeout) + return err +} + +// qgaQuery runs an agent command and returns its result. +func qgaQuery(conn net.Conn, dec *json.Decoder, command string, timeout time.Duration) (json.RawMessage, error) { if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil { - return err + return nil, err } if err := json.NewEncoder(conn).Encode(map[string]string{"execute": command}); err != nil { - return fmt.Errorf("%s: %w", command, err) + return nil, fmt.Errorf("%s: %w", command, err) } var reply struct { Return json.RawMessage `json:"return"` Error any `json:"error"` } if err := dec.Decode(&reply); err != nil { - return fmt.Errorf("%s: %w", command, err) + return nil, fmt.Errorf("%s: %w", command, err) } if reply.Error != nil { - return fmt.Errorf("%s: %v", command, reply.Error) + return nil, fmt.Errorf("%s: %v", command, reply.Error) } - return nil + return reply.Return, nil +} + +// virtiofsMountpoint asks the guest agent where a virtiofs filesystem is +// mounted in the guest, "" when none is. +func virtiofsMountpoint(ctx context.Context, socketPath string) (string, error) { + conn, dec, err := qgaDial(ctx, socketPath) + if err != nil { + return "", err + } + defer conn.Close() + raw, err := qgaQuery(conn, dec, "guest-get-fsinfo", 2*time.Second) + if err != nil { + return "", err + } + var filesystems []struct { + Mountpoint string `json:"mountpoint"` + Type string `json:"type"` + } + if err := json.Unmarshal(raw, &filesystems); err != nil { + return "", fmt.Errorf("guest-get-fsinfo: %w", err) + } + for _, fs := range filesystems { + if fs.Type == "virtiofs" { + return fs.Mountpoint, nil + } + } + return "", nil } // fsFreezeTimeout bounds freezing (the guest flushes every filesystem diff --git a/internal/backend/qemu/qmp.go b/internal/backend/qemu/qmp.go index 39e8147..4892ceb 100644 --- a/internal/backend/qemu/qmp.go +++ b/internal/backend/qemu/qmp.go @@ -2,6 +2,7 @@ package qemu import ( "encoding/json" + "errors" "fmt" "net" "os" @@ -9,6 +10,31 @@ import ( "time" ) +// qmpTimeout bounds an ordinary command (and the greeting and handshake); +// qmpSlowTimeout the ones that write a whole disk's metadata. +const ( + qmpTimeout = 5 * time.Second + qmpSlowTimeout = 10 * time.Minute +) + +// errQMPNoReply means a command was sent but its reply never came (the +// connection dropped, or the wait ran out): QEMU may or may not have run +// it. A caller must check the state before trying a mutating command +// again, never just repeat it. +var errQMPNoReply = errors.New("no reply from QEMU; the command may or may not have run") + +// qmpError is QEMU refusing a command: its class (GenericError, +// DeviceNotActive, ...) and its own description. +type qmpError struct { + Command string + Class string `json:"class"` + Desc string `json:"desc"` +} + +func (e *qmpError) Error() string { + return fmt.Sprintf("qmp command %s failed: %s (%s)", e.Command, e.Desc, e.Class) +} + // qmpConn is one QMP session: QMP requires the capabilities handshake on // every new connection, and fd passing (getfd) only lasts for the session // that received the fd. @@ -23,7 +49,7 @@ func qmpDial(socketPath string) (*qmpConn, error) { return nil, fmt.Errorf("dial qmp socket: %w", err) } q := &qmpConn{conn: conn.(*net.UnixConn), dec: json.NewDecoder(conn)} - if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + if err := conn.SetDeadline(time.Now().Add(qmpTimeout)); err != nil { conn.Close() return nil, err } @@ -32,7 +58,7 @@ func qmpDial(socketPath string) (*qmpConn, error) { conn.Close() return nil, fmt.Errorf("read qmp greeting: %w", err) } - if _, err := q.execute("qmp_capabilities", nil, nil); err != nil { + if _, err := q.execute("qmp_capabilities", nil, nil, qmpTimeout); err != nil { conn.Close() return nil, fmt.Errorf("negotiate qmp capabilities: %w", err) } @@ -42,8 +68,13 @@ func qmpDial(socketPath string) (*qmpConn, error) { func (q *qmpConn) Close() error { return q.conn.Close() } // execute sends one command, passing file alongside it (SCM_RIGHTS) when -// non-nil, and returns after its reply. -func (q *qmpConn) execute(command string, arguments map[string]any, file *os.File) (json.RawMessage, error) { +// non-nil, and returns after its reply, waiting at most timeout. One +// command is in flight per connection, so the first reply that isn't an +// event is this command's. +func (q *qmpConn) execute(command string, arguments map[string]any, file *os.File, timeout time.Duration) (json.RawMessage, error) { + if err := q.conn.SetDeadline(time.Now().Add(timeout)); err != nil { + return nil, err + } req := map[string]any{"execute": command} if arguments != nil { req["arguments"] = arguments @@ -62,14 +93,18 @@ func (q *qmpConn) execute(command string, arguments map[string]any, file *os.Fil for { var reply struct { Return json.RawMessage `json:"return"` - Error any `json:"error"` + Error json.RawMessage `json:"error"` Event string `json:"event"` } if err := q.dec.Decode(&reply); err != nil { - return nil, fmt.Errorf("read qmp reply for %s: %w", command, err) + return nil, fmt.Errorf("qmp command %s: %w (%v)", command, errQMPNoReply, err) } - if reply.Error != nil { - return nil, fmt.Errorf("qmp command %s failed: %v", command, reply.Error) + if len(reply.Error) > 0 { + qerr := &qmpError{Command: command} + if err := json.Unmarshal(reply.Error, qerr); err != nil || qerr.Desc == "" { + qerr.Desc = string(reply.Error) + } + return nil, qerr } if reply.Return != nil { return reply.Return, nil @@ -82,12 +117,49 @@ func (q *qmpConn) execute(command string, arguments map[string]any, file *os.Fil // machine's monitor socket. It's intentionally minimal: OmaVM only needs a // handful of commands, not the full QMP protocol. func qmpExecute(socketPath, command string, arguments map[string]any) (json.RawMessage, error) { + return qmpExecuteTimeout(socketPath, command, arguments, qmpTimeout) +} + +func qmpExecuteTimeout(socketPath, command string, arguments map[string]any, timeout time.Duration) (json.RawMessage, error) { q, err := qmpDial(socketPath) if err != nil { return nil, err } defer q.Close() - return q.execute(command, arguments, nil) + return q.execute(command, arguments, nil, timeout) +} + +// qmpDiskSnapshots lists the internal snapshots of the boot disk as QEMU +// sees them right now, to settle a snapshot command left without a reply. +func qmpDiskSnapshots(socketPath string) (map[string]bool, error) { + raw, err := qmpExecute(socketPath, "query-block", nil) + if err != nil { + return nil, err + } + var devices []struct { + Device string `json:"device"` + Inserted *struct { + Image struct { + Snapshots []struct { + Name string `json:"name"` + } `json:"snapshots"` + } `json:"image"` + } `json:"inserted"` + } + if err := json.Unmarshal(raw, &devices); err != nil { + return nil, fmt.Errorf("decode query-block: %w", err) + } + for _, d := range devices { + if d.Device != bootDisk || d.Inserted == nil { + continue + } + names := map[string]bool{} + for _, s := range d.Inserted.Image.Snapshots { + names[s.Name] = true + } + return names, nil + } + return nil, fmt.Errorf("disk %s not found", bootDisk) } // qmpAddDisplayClient hands QEMU one end of a peer-to-peer connection to @@ -99,10 +171,10 @@ func qmpAddDisplayClient(socketPath string, file *os.File) error { } defer q.Close() const fdname = "omavm-display" - if _, err := q.execute("getfd", map[string]any{"fdname": fdname}, file); err != nil { + if _, err := q.execute("getfd", map[string]any{"fdname": fdname}, file, qmpTimeout); err != nil { return err } - _, err = q.execute("add_client", map[string]any{"protocol": "@dbus-display", "fdname": fdname}, nil) + _, err = q.execute("add_client", map[string]any{"protocol": "@dbus-display", "fdname": fdname}, nil, qmpTimeout) return err } diff --git a/internal/backend/qemu/qmp_test.go b/internal/backend/qemu/qmp_test.go new file mode 100644 index 0000000..6ec24ba --- /dev/null +++ b/internal/backend/qemu/qmp_test.go @@ -0,0 +1,248 @@ +package qemu + +import ( + "context" + "encoding/json" + "errors" + "net" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// scriptedQMP answers each connection's greeting and handshake, then hands +// every command to reply, which writes whatever QEMU would (or nothing). +func scriptedQMP(t *testing.T, reply func(command string, enc *json.Encoder, conn net.Conn)) string { + t.Helper() + return scriptedQMPAt(t, filepath.Join(t.TempDir(), "qmp.sock"), reply) +} + +func scriptedQMPAt(t *testing.T, socket string, reply func(command string, enc *json.Encoder, conn net.Conn)) string { + t.Helper() + listener, err := net.Listen("unix", socket) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go func() { + defer conn.Close() + enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) + enc.Encode(map[string]any{"QMP": map[string]any{}}) + for { + var req struct { + Execute string `json:"execute"` + } + if dec.Decode(&req) != nil { + return + } + if req.Execute == "qmp_capabilities" { + enc.Encode(map[string]any{"return": map[string]any{}}) + continue + } + reply(req.Execute, enc, conn) + } + }() + } + }() + return socket +} + +func TestQMPErrorReplyIsStructured(t *testing.T) { + socket := scriptedQMP(t, func(_ string, enc *json.Encoder, _ net.Conn) { + enc.Encode(map[string]any{"error": map[string]any{"class": "DeviceNotActive", "desc": "D-Bus display is not in use"}}) + }) + _, err := qmpExecute(socket, "add_client", nil) + var qerr *qmpError + if !errors.As(err, &qerr) || qerr.Class != "DeviceNotActive" || !strings.Contains(err.Error(), "D-Bus display is not in use") { + t.Fatalf("got %v", err) + } + if errors.Is(err, errQMPNoReply) { + t.Fatal("a refusal is a known result, not a missing reply") + } +} + +func TestQMPEventBeforeTheReplyIsSkipped(t *testing.T) { + socket := scriptedQMP(t, func(_ string, enc *json.Encoder, _ net.Conn) { + enc.Encode(map[string]any{"event": "RESUME", "timestamp": map[string]any{}}) + enc.Encode(map[string]any{"return": map[string]any{"status": "running"}}) + }) + if status, err := qmpStatus(socket); err != nil || status != "running" { + t.Fatalf("status %q, %v", status, err) + } +} + +func TestQMPMissingReplyIsUnknownNotFailure(t *testing.T) { + dropped := scriptedQMP(t, func(_ string, _ *json.Encoder, conn net.Conn) { conn.Close() }) + if _, err := qmpExecute(dropped, "stop", nil); !errors.Is(err, errQMPNoReply) { + t.Fatalf("dropped connection: %v", err) + } + silent := scriptedQMP(t, func(string, *json.Encoder, net.Conn) {}) + start := time.Now() + if _, err := qmpExecuteTimeout(silent, "stop", nil, 200*time.Millisecond); !errors.Is(err, errQMPNoReply) { + t.Fatalf("no reply: %v", err) + } + if time.Since(start) > 2*time.Second { + t.Fatal("the wait wasn't bounded") + } +} + +// A snapshot whose reply never came is looked up before being reported: +// one that exists on the disk must reach the registry, not be lost. +func TestSnapshotWithoutReplyIsReconciled(t *testing.T) { + snapshots := map[string]bool{} + reply := func(command string, enc *json.Encoder, conn net.Conn) { + switch command { + case "blockdev-snapshot-internal-sync": + snapshots["before-upgrade"] = true + conn.Close() // done, but the reply is lost + case "blockdev-snapshot-delete-internal-sync": + delete(snapshots, "before-upgrade") + conn.Close() + case "query-block": + var list []map[string]any + for name := range snapshots { + list = append(list, map[string]any{"name": name}) + } + enc.Encode(map[string]any{"return": []any{map[string]any{"device": bootDisk, "inserted": map[string]any{"image": map[string]any{"snapshots": list}}}}}) + } + } + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + scriptedQMPAt(t, b.qmpPath(env.Name), reply) + if _, err := b.CreateSnapshot(context.Background(), env, "before-upgrade"); err != nil { + t.Fatalf("the snapshot exists, so creating it succeeded: %v", err) + } + if err := b.RemoveSnapshot(context.Background(), env, "before-upgrade"); err != nil { + t.Fatalf("the snapshot is gone, so deleting it succeeded: %v", err) + } +} + +// Without a reply and without the snapshot on the disk, it fails, and the +// error says the outcome wasn't confirmed. +func TestSnapshotWithoutReplyThatDidNotHappenFails(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + scriptedQMPAt(t, b.qmpPath(env.Name), func(command string, enc *json.Encoder, conn net.Conn) { + if command == "query-block" { + enc.Encode(map[string]any{"return": []any{map[string]any{"device": bootDisk, "inserted": map[string]any{"image": map[string]any{}}}}}) + return + } + conn.Close() + }) + _, err := b.CreateSnapshot(context.Background(), env, "before-upgrade") + if !errors.Is(err, errQMPNoReply) || !strings.Contains(err.Error(), "may or may not have run") { + t.Fatalf("expected an unconfirmed failure, got %v", err) + } +} + +// Resume after a disk-full pause: if QEMU pauses again at once (the host's +// disk is still full), Resume says so instead of reporting success. +func TestResumeThatPausesAgainOnDiskErrorFails(t *testing.T) { + for _, tt := range []struct { + status string + fails bool + }{{"io-error", true}, {"running", false}} { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + scriptedQMPAt(t, b.qmpPath(env.Name), func(command string, enc *json.Encoder, _ net.Conn) { + if command == "query-status" { + enc.Encode(map[string]any{"return": map[string]any{"status": tt.status}}) + return + } + enc.Encode(map[string]any{"return": map[string]any{}}) + }) + err := b.Resume(context.Background(), env) + if tt.fails != (err != nil) { + t.Fatalf("status %s after cont: err = %v", tt.status, err) + } + if tt.fails && !strings.Contains(err.Error(), "paused again") { + t.Fatalf("unexplained: %v", err) + } + } +} + +// A paused Machine is resumed so it can shut down; if the guest doesn't, +// it goes back to paused, as it was found, and is never quit. +func TestSlowShutdownOfPausedMachinePausesItAgain(t *testing.T) { + saved := gracefulShutdownTimeout + gracefulShutdownTimeout = 300 * time.Millisecond + t.Cleanup(func() { gracefulShutdownTimeout = saved }) + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + commands := make(chan string, 20) + scriptedQMPAt(t, b.qmpPath(env.Name), func(command string, enc *json.Encoder, _ net.Conn) { + commands <- command + if command == "query-status" { + enc.Encode(map[string]any{"return": map[string]any{"status": "paused"}}) + return + } + enc.Encode(map[string]any{"return": map[string]any{}}) + }) + err := b.Stop(context.Background(), env) + if err == nil || !strings.Contains(err.Error(), "paused again") { + t.Fatalf("expected the Machine back in pause, got %v", err) + } + close(commands) + var sent []string + for c := range commands { + if c == "quit" { + t.Fatal("a slow shutdown must never become a power cut") + } + sent = append(sent, c) + } + if sent[len(sent)-1] != "stop" { + t.Fatalf("last command %v, want stop", sent) + } +} + +// With the agent's port closed in the guest, Integration answers at once +// instead of waiting out a ping nobody will answer (it held every poll of +// the environment list for 700 ms). +func TestIntegrationSkipsThePingWhenTheAgentPortIsClosed(t *testing.T) { + b := &Backend{stateDir: t.TempDir()} + env := core.Environment{Name: "guest", Kind: core.Machine} + startFakeQEMU(t, b, env.Name) + scriptedQMPAt(t, b.qmpPath(env.Name), func(command string, enc *json.Encoder, _ net.Conn) { + enc.Encode(map[string]any{"return": []any{ + map[string]any{"label": "qga0", "frontend-open": false}, + map[string]any{"label": "clipboard", "frontend-open": false}, + }}) + }) + // The agent's socket accepts and never answers, as QEMU's does when + // no agent runs in the guest. + silent, err := net.Listen("unix", b.qgaPath(env.Name)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { silent.Close() }) + go func() { + for { + conn, err := silent.Accept() + if err != nil { + return + } + defer conn.Close() + } + }() + start := time.Now() + report, err := b.Integration(context.Background(), env) + if err != nil || report.GuestAgent != "unavailable" { + t.Fatalf("report %+v, %v", report, err) + } + if elapsed := time.Since(start); elapsed > 300*time.Millisecond { + t.Fatalf("waited %v for an agent whose port is closed", elapsed) + } +} diff --git a/internal/backend/qemu/space_test.go b/internal/backend/qemu/space_test.go new file mode 100644 index 0000000..2e5bf11 --- /dev/null +++ b/internal/backend/qemu/space_test.go @@ -0,0 +1,38 @@ +package qemu + +import ( + "context" + "path/filepath" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestSpaceWarning(t *testing.T) { + for _, tt := range []struct { + free uint64 + want string + }{ + {8 << 30, ""}, + {lowSpace, ""}, + {3<<30 + 1<<29, "only 3.5 GiB free on this computer: the Machine pauses if it runs out"}, + {700 << 20, "only 700 MiB free on this computer: the Machine pauses if it runs out"}, + } { + if got := spaceWarning(tt.free); got != tt.want { + t.Errorf("spaceWarning(%d) = %q, want %q", tt.free, got, tt.want) + } + } +} + +// A Machine whose directory doesn't exist yet is measured on the disk +// that will hold it, and a stopped Machine still reports its state. +func TestFreeSpaceOfAMissingDirectory(t *testing.T) { + if _, ok := freeSpace(filepath.Join(t.TempDir(), "machines", "x")); !ok { + t.Fatal("free space not measured on the parent directory") + } + b := &Backend{stateDir: t.TempDir()} + st, err := b.Status(context.Background(), core.Environment{Name: "guest", Kind: core.Machine}) + if err != nil || st.State != core.StateStopped { + t.Fatalf("status = %+v, %v", st, err) + } +} diff --git a/internal/core/backend.go b/internal/core/backend.go index 59fba91..6d7eaf8 100644 --- a/internal/core/backend.go +++ b/internal/core/backend.go @@ -25,6 +25,18 @@ const ( type Status struct { State State `json:"state"` Detail string `json:"detail,omitempty"` + // Ephemeral means this session's changes are thrown away when the + // environment shuts down (see EphemeralStarter). + Ephemeral bool `json:"ephemeral,omitempty"` + // Warning is something about to go wrong that the state doesn't show, + // such as the host's disk running out under a Machine. + Warning string `json:"warning,omitempty"` + // RestartNeeded means saved settings differ from what the running + // session got; they apply the next time it starts. + RestartNeeded bool `json:"restart_needed,omitempty"` + // TravelMode means the session runs with fewer CPUs than its setting + // because the host was on battery when it started. + TravelMode bool `json:"travel_mode,omitempty"` } // Backend executes the lifecycle of environments of one Kind on top of a @@ -92,8 +104,31 @@ type IntegrationReporter interface { type IntegrationReport struct { GuestAgent string `json:"guest_agent"` Hint string `json:"hint,omitempty"` + // Capabilities says, per host↔guest integration, whether it works, + // as far as OmaVM can check, and the next step when it doesn't. + Capabilities []GuestCapability `json:"capabilities,omitempty"` } +// GuestCapability is one integration with the guest (clipboard, shared +// folder). State is ready only after a real check of the guest side; a +// setting being on is not proof that it works. +type GuestCapability struct { + ID string `json:"id"` + Label string `json:"label"` + State string `json:"state"` + // Hint is the concrete next step, or what "ready" means in use. + Hint string `json:"hint,omitempty"` +} + +// GuestCapability states. +const ( + GuestReady = "ready" // checked on the guest side + GuestNeedsComponent = "needs_guest_component" // something to install or do in the guest + GuestNeedsRestart = "needs_restart" // saved, applies on the next start + GuestNotVerified = "not_verified" // can't be checked right now + GuestOff = "off" // turned off, or not set up +) + // SnapshotManager is an optional Backend capability for environments whose // engine supports point-in-time state capture natively (QEMU/qcow2 internal // snapshots for Machines). The Core owns the meaningful Label and the @@ -155,6 +190,31 @@ type RemoteShell interface { SSH(ctx context.Context, env Environment, login string, command []string) error } +// Upgrader is an optional Backend capability: update the software installed +// in the environment with its own package manager (distrobox upgrade for +// Boxes). A Machine updates from inside its own system instead. +type Upgrader interface { + Upgrade(ctx context.Context, env Environment) error +} + +// Cloner is an optional Backend capability: make clone a full, independent +// copy of source (its disk or container), as source is now. Both stay +// usable afterwards; nothing is shared between them. A backend refuses a +// source that is running, whose state would be copied half-written. +type Cloner interface { + Clone(ctx context.Context, source, clone Environment) error +} + +// EphemeralStarter is an optional Backend capability: start a session +// whose changes are discarded when it shuts down, leaving the environment +// exactly as it was. Nothing is persisted in the domain: it is a property +// of one session, reported back through Status.Ephemeral. Starting an +// environment already running a normal session is ErrInvalidInput, so a +// caller never believes changes will vanish when they won't. +type EphemeralStarter interface { + StartEphemeral(ctx context.Context, env Environment) error +} + // Launcher publishes environments in the host's application launcher, so // one opens like any installed app without going through the Experience // Center first. It is host desktop integration rather than a Backend diff --git a/internal/core/clipboard_test.go b/internal/core/clipboard_test.go new file mode 100644 index 0000000..cb04600 --- /dev/null +++ b/internal/core/clipboard_test.go @@ -0,0 +1,46 @@ +package core_test + +import ( + "context" + "errors" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +func TestClipboardDirection(t *testing.T) { + svc, _, _ := newTestService() + ctx := context.Background() + if _, err := svc.Create(ctx, core.Environment{Name: "vm", Kind: core.Machine, Image: testISO(t)}); err != nil { + t.Fatal(err) + } + if _, err := svc.Create(ctx, core.Environment{Name: "dev", Kind: core.Box, Image: "fedora"}); err != nil { + t.Fatal(err) + } + dir := func(s string) core.SettingsPatch { return core.SettingsPatch{ClipboardDirection: &s} } + + settings, err := svc.Configure(ctx, "vm", dir(core.ClipboardToGuest)) + if err != nil { + t.Fatal(err) + } + if settings.ClipboardToHost() || !settings.ClipboardToGuest() || settings.ClipboardMode() != "to-guest" { + t.Fatalf("to-guest: %+v", settings) + } + if settings, _ = svc.Configure(ctx, "vm", dir(core.ClipboardBoth)); settings.ClipboardDirection != "" || settings.ClipboardMode() != "true" { + t.Fatalf("both must be the stored default: %+v", settings) + } + off := false + if settings, _ = svc.Configure(ctx, "vm", core.SettingsPatch{ShareClipboard: &off}); settings.ClipboardToHost() || settings.ClipboardToGuest() || settings.ClipboardMode() != "false" { + t.Fatalf("off must turn both ways off: %+v", settings) + } + + if _, err := svc.Configure(ctx, "dev", dir(core.ClipboardToGuest)); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("a Box has no way to the guest, got %v", err) + } + if _, err := svc.Configure(ctx, "dev", dir(core.ClipboardToHost)); err != nil { + t.Fatal(err) + } + if _, err := svc.Configure(ctx, "vm", dir("sideways")); !errors.Is(err, core.ErrInvalidInput) { + t.Fatalf("expected invalid input, got %v", err) + } +} diff --git a/internal/core/clone_test.go b/internal/core/clone_test.go new file mode 100644 index 0000000..c9fcee1 --- /dev/null +++ b/internal/core/clone_test.go @@ -0,0 +1,90 @@ +package core_test + +import ( + "context" + "errors" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +type fakeCloneBackend struct { + *fakeSnapshotBackend + cloned map[string]string // clone -> source + failErr error +} + +func (f *fakeCloneBackend) Clone(ctx context.Context, source, clone core.Environment) error { + if f.failErr != nil { + return f.failErr + } + f.cloned[clone.Name] = source.Name + return nil +} + +func TestClone(t *testing.T) { + machine := &fakeCloneBackend{fakeSnapshotBackend: newFakeSnapshotBackend("fake-machine"), cloned: map[string]string{}} + svc := core.NewService(&memStore{}, newFakeBackend("fake-box"), machine) + ctx := context.Background() + color := "green" + if _, err := svc.Create(ctx, core.Environment{Name: "vm", Kind: core.Machine, Image: testISO(t)}); err != nil { + t.Fatal(err) + } + if _, err := svc.Configure(ctx, "vm", core.SettingsPatch{Color: &color}); err != nil { + t.Fatal(err) + } + snap, _ := svc.CreateSnapshot(ctx, "vm", "clean") + + clone, err := svc.Clone(ctx, "vm", " vm copy ") + if err != nil { + t.Fatal(err) + } + if clone.Name != "vm copy" || clone.Kind != core.Machine || clone.Settings.Color != "green" || clone.ID == "" { + t.Fatalf("clone: %+v", clone) + } + if machine.cloned["vm copy"] != "vm" { + t.Fatalf("backend not asked: %v", machine.cloned) + } + if snaps, _ := svc.ListSnapshots(ctx, "vm copy"); len(snaps) != 1 || snaps[0].ID != snap.ID { + t.Fatalf("the copied disk carries the snapshots, so the list must too: %+v", snaps) + } + + if _, err := svc.Clone(ctx, "vm", "vm copy"); !errors.Is(err, core.ErrAlreadyExists) { + t.Fatalf("taken name: %v", err) + } + if _, err := svc.Clone(ctx, "nope", "x"); !errors.Is(err, core.ErrNotFound) { + t.Fatalf("missing source: %v", err) + } + if _, err := svc.Clone(ctx, "vm", "a/b"); !errors.Is(err, core.ErrInvalidInput) { + t.Fatalf("bad name: %v", err) + } + machine.failErr = core.Invalidf("shut down vm first") + if _, err := svc.Clone(ctx, "vm", "second"); !errors.Is(err, core.ErrInvalidInput) { + t.Fatalf("backend refusal: %v", err) + } + if _, err := svc.Status(ctx, "second"); !errors.Is(err, core.ErrNotFound) { + t.Fatalf("a failed clone must leave nothing registered: %v", err) + } +} + +func TestCloneUnsupportedBackend(t *testing.T) { + svc, _, _ := newTestService() + ctx := context.Background() + if _, err := svc.Create(ctx, core.Environment{Name: "dev", Kind: core.Box, Image: "fedora"}); err != nil { + t.Fatal(err) + } + if _, err := svc.Clone(ctx, "dev", "dev2"); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("expected unsupported, got %v", err) + } +} + +func TestUpdateIsForBoxes(t *testing.T) { + svc, _, _ := newTestService() + ctx := context.Background() + if _, err := svc.Create(ctx, core.Environment{Name: "vm", Kind: core.Machine, Image: testISO(t)}); err != nil { + t.Fatal(err) + } + if err := svc.Update(ctx, "vm"); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("a Desktop updates from inside, got %v", err) + } +} diff --git a/internal/core/environment.go b/internal/core/environment.go index 25da6a6..64512f5 100644 --- a/internal/core/environment.go +++ b/internal/core/environment.go @@ -134,8 +134,13 @@ type EnvironmentSettings struct { // here, never a per-session UI checkbox the user has to remember to // re-enable. For a Machine, the clipboard is shared with the guest; // for a Box, programs in its terminal may copy to it (OSC 52). - ClipboardDisabled bool `json:"clipboard_disabled,omitempty"` - TravelModeDisabled bool `json:"travel_mode_disabled,omitempty"` + ClipboardDisabled bool `json:"clipboard_disabled,omitempty"` + // ClipboardDirection limits a shared clipboard to one way: "" (both, + // the default), ClipboardToHost or ClipboardToGuest. A Box only has + // the way to the host (OSC 52); pasting into its terminal is always a + // deliberate keystroke. + ClipboardDirection string `json:"clipboard_direction,omitempty"` + TravelModeDisabled bool `json:"travel_mode_disabled,omitempty"` // VulkanDisabled turns off Vulkan acceleration for a Machine, which is // otherwise on whenever the host supports it. Same inverted storage as // the two above. @@ -199,6 +204,7 @@ type SettingsPatch struct { SnapshotLimit *int Color *string ShareClipboard *bool + ClipboardDirection *string TravelMode *bool Vulkan *bool Launcher *bool @@ -206,3 +212,35 @@ type SettingsPatch struct { OpenInEmptyWorkspace *bool Fullscreen *bool } + +// Clipboard directions (EnvironmentSettings.ClipboardDirection). +const ( + ClipboardBoth = "both" + ClipboardToHost = "to-host" + ClipboardToGuest = "to-guest" +) + +// ClipboardToHost reports whether text copied in the environment may +// reach this computer's clipboard. +func (s EnvironmentSettings) ClipboardToHost() bool { + return !s.ClipboardDisabled && s.ClipboardDirection != ClipboardToGuest +} + +// ClipboardToGuest reports whether text copied on this computer may reach +// the environment's clipboard (Machines only). +func (s EnvironmentSettings) ClipboardToGuest() bool { + return !s.ClipboardDisabled && s.ClipboardDirection != ClipboardToHost +} + +// ClipboardMode is the clipboard setting as one word: "false" (off), +// "true" (both ways), ClipboardToHost or ClipboardToGuest — the value of +// omavm-gui's --share-clipboard. +func (s EnvironmentSettings) ClipboardMode() string { + switch { + case s.ClipboardDisabled: + return "false" + case s.ClipboardDirection == ClipboardToHost || s.ClipboardDirection == ClipboardToGuest: + return s.ClipboardDirection + } + return "true" +} diff --git a/internal/core/ephemeral_test.go b/internal/core/ephemeral_test.go new file mode 100644 index 0000000..cf6816a --- /dev/null +++ b/internal/core/ephemeral_test.go @@ -0,0 +1,48 @@ +package core_test + +import ( + "context" + "errors" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +type fakeEphemeralBackend struct { + *fakeBackend + ephemeral map[string]bool +} + +func (f *fakeEphemeralBackend) StartEphemeral(ctx context.Context, env core.Environment) error { + f.running[env.Name] = true + f.ephemeral[env.Name] = true + return nil +} + +func TestStartEphemeral(t *testing.T) { + box := newFakeBackend("fake-box") + machine := &fakeEphemeralBackend{fakeBackend: newFakeBackend("fake-machine"), ephemeral: map[string]bool{}} + svc := core.NewService(&memStore{}, box, machine) + ctx := context.Background() + if _, err := svc.Create(ctx, core.Environment{Name: "vm", Kind: core.Machine, Image: testISO(t)}); err != nil { + t.Fatal(err) + } + if _, err := svc.Create(ctx, core.Environment{Name: "dev", Kind: core.Box, Image: "fedora"}); err != nil { + t.Fatal(err) + } + if err := svc.StartEphemeral(ctx, "vm"); err != nil { + t.Fatal(err) + } + if !machine.ephemeral["vm"] { + t.Fatal("the backend was not asked for an ephemeral session") + } + if err := svc.StartEphemeral(ctx, "dev"); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("a Box can't start without keeping changes, got %v", err) + } + if box.running["dev"] { + t.Fatal("the Box was started anyway") + } + if err := svc.StartEphemeral(ctx, "missing"); !errors.Is(err, core.ErrNotFound) { + t.Fatalf("expected not found, got %v", err) + } +} diff --git a/internal/core/errors.go b/internal/core/errors.go index 8266fb7..c2aab93 100644 --- a/internal/core/errors.go +++ b/internal/core/errors.go @@ -15,6 +15,9 @@ var ( // ErrBusy means another operation on the environment (its creation // or removal) is still running. ErrBusy = errors.New("environment is busy") + // ErrSnapshotGone means a snapshot the registry lists is no longer in + // the environment's disk (deleted by hand, or the disk was replaced). + ErrSnapshotGone = errors.New("snapshot is no longer in the disk") ) // Invalidf and Unsupportedf build errors that match ErrInvalidInput and diff --git a/internal/core/progress.go b/internal/core/progress.go new file mode 100644 index 0000000..9bf166d --- /dev/null +++ b/internal/core/progress.go @@ -0,0 +1,24 @@ +package core + +import ( + "context" + "fmt" +) + +type progressKey struct{} + +// WithProgress returns a context whose long operations (downloading a +// Box's image) report what they are doing to fn, one short stage at a +// time. Stages describe real steps; no backend invents a percentage it +// doesn't have. +func WithProgress(ctx context.Context, fn func(stage string)) context.Context { + return context.WithValue(ctx, progressKey{}, fn) +} + +// ReportProgress tells the caller of ctx about a stage, if it asked to +// know (WithProgress). +func ReportProgress(ctx context.Context, format string, args ...any) { + if fn, ok := ctx.Value(progressKey{}).(func(string)); ok && fn != nil { + fn(fmt.Sprintf(format, args...)) + } +} diff --git a/internal/core/run.go b/internal/core/run.go new file mode 100644 index 0000000..9aa0ee4 --- /dev/null +++ b/internal/core/run.go @@ -0,0 +1,74 @@ +package core + +import ( + "context" + "fmt" + "log/slog" + "time" +) + +// RunEphemeral runs a new Machine that leaves nothing behind: it is +// created, started without keeping changes, opened when open is true, and +// deleted once it shuts down (omavm run --ephemeral). There is no daemon: +// the caller waits here, checking its state every poll, until the guest +// powers off or ctx is cancelled. Cancelling ends the session at once +// (Force Stop): nothing of it was going to be kept anyway. +// +// Ephemeral Boxes belong to the Disposable mode on direct containers +// (Backend Rules) and aren't offered here. +func (s *Service) RunEphemeral(ctx context.Context, env Environment, open bool, poll time.Duration) (Environment, error) { + if env.Kind != Machine { + return Environment{}, Unsupportedf("only Desktops (Machines) can run ephemeral for now; disposable Boxes are not available yet") + } + if env.Name == "" { + id, err := newID() + if err != nil { + return Environment{}, err + } + env.Name = "ephemeral-" + id[:6] + } + // Here and gone: never listed in the app launcher. + env.Settings.LauncherDisabled = true + created, err := s.Create(ctx, env) + if err != nil { + return Environment{}, err + } + name := created.Name + defer func() { + // The caller's context may be cancelled by now. + cleanup := context.Background() + if status, err := s.Status(cleanup, name); err == nil && status.State != StateStopped { + if err := s.ForceStop(cleanup, name); err != nil { + slog.Warn("ephemeral environment could not be stopped", "environment", name, "error", err) + } + } + if err := s.Remove(cleanup, name); err != nil { + slog.Error("ephemeral environment left behind", "environment", name, "error", err) + } + }() + + if err := s.StartEphemeral(ctx, name); err != nil { + return created, err + } + if open { + if err := s.Open(ctx, name); err != nil { + return created, err + } + } + ticker := time.NewTicker(poll) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return created, fmt.Errorf("ended %s: %w", name, ctx.Err()) + case <-ticker.C: + } + status, err := s.Status(ctx, name) + if err != nil { + continue // a slow answer is not the end of the session + } + if status.State == StateStopped { + return created, nil + } + } +} diff --git a/internal/core/run_test.go b/internal/core/run_test.go new file mode 100644 index 0000000..7c35afd --- /dev/null +++ b/internal/core/run_test.go @@ -0,0 +1,90 @@ +package core_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// runBackend is a Machine whose guest powers off after a few status +// checks, recording what was asked of it. +type runBackend struct { + *fakeEphemeralBackend + checksUntilOff int + forceStopped []string + opened []string +} + +func (r *runBackend) Status(ctx context.Context, env core.Environment) (core.Status, error) { + if r.running[env.Name] { + if r.checksUntilOff == 0 { + r.running[env.Name] = false + } else { + r.checksUntilOff-- + } + } + return r.fakeEphemeralBackend.Status(ctx, env) +} +func (r *runBackend) Open(ctx context.Context, env core.Environment) error { + r.opened = append(r.opened, env.Name) + return nil +} +func (r *runBackend) Restart(ctx context.Context, env core.Environment) error { return nil } +func (r *runBackend) Pause(ctx context.Context, env core.Environment) error { return nil } +func (r *runBackend) Resume(ctx context.Context, env core.Environment) error { return nil } +func (r *runBackend) ForceStop(ctx context.Context, env core.Environment) error { + r.forceStopped = append(r.forceStopped, env.Name) + r.running[env.Name] = false + return nil +} + +func newRunService(checks int) (*core.Service, *runBackend) { + machine := &runBackend{fakeEphemeralBackend: &fakeEphemeralBackend{fakeBackend: newFakeBackend("fake-machine"), ephemeral: map[string]bool{}}, checksUntilOff: checks} + return core.NewService(&memStore{}, newFakeBackend("fake-box"), machine), machine +} + +func TestRunEphemeralDeletesTheMachineWhenItShutsDown(t *testing.T) { + svc, machine := newRunService(2) + created, err := svc.RunEphemeral(context.Background(), core.Environment{Kind: core.Machine, Image: testISO(t)}, true, time.Millisecond) + if err != nil { + t.Fatal(err) + } + if !machine.ephemeral[created.Name] || len(machine.opened) != 1 { + t.Fatalf("not started ephemeral and opened: %+v", machine) + } + if !created.Settings.LauncherDisabled { + t.Fatal("an ephemeral Machine must not appear in the launcher") + } + if _, err := svc.Status(context.Background(), created.Name); !errors.Is(err, core.ErrNotFound) { + t.Fatalf("still registered after shutting down: %v", err) + } + if len(machine.forceStopped) != 0 { + t.Fatal("a guest that powered off must not be force-stopped") + } +} + +func TestRunEphemeralCancelledEndsAndDeletesIt(t *testing.T) { + svc, machine := newRunService(1 << 30) // never powers off on its own + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + created, err := svc.RunEphemeral(ctx, core.Environment{Name: "try", Kind: core.Machine, Image: testISO(t)}, false, time.Millisecond) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected the cancellation, got %v", err) + } + if len(machine.forceStopped) != 1 || machine.forceStopped[0] != "try" { + t.Fatalf("not ended: %v", machine.forceStopped) + } + if _, err := svc.Status(context.Background(), created.Name); !errors.Is(err, core.ErrNotFound) { + t.Fatalf("still registered: %v", err) + } +} + +func TestRunEphemeralIsForMachines(t *testing.T) { + svc, _ := newRunService(0) + if _, err := svc.RunEphemeral(context.Background(), core.Environment{Kind: core.Box, Image: "fedora"}, false, time.Millisecond); !errors.Is(err, core.ErrUnsupported) { + t.Fatalf("expected unsupported, got %v", err) + } +} diff --git a/internal/core/service.go b/internal/core/service.go index 8bbf89c..8359f28 100644 --- a/internal/core/service.go +++ b/internal/core/service.go @@ -4,6 +4,7 @@ import ( "context" "crypto/rand" "encoding/hex" + "errors" "fmt" "log/slog" "os" @@ -440,6 +441,83 @@ func (s *Service) Create(ctx context.Context, env Environment) (Environment, err return created, nil } +// Update updates the software installed in a Box with its package +// manager. The Box's lock is held throughout, like Start. +func (s *Service) Update(ctx context.Context, name string) error { + env, backend, unlock, err := s.acquire(ctx, name) + if err != nil { + return err + } + defer unlock() + upgrader, ok := backend.(Upgrader) + if !ok { + return Unsupportedf("%s is a Desktop: update it from inside its own system", name) + } + if err := upgrader.Upgrade(ctx, env); err != nil { + return fmt.Errorf("update %s: %w", name, err) + } + return nil +} + +// Clone makes newName a full copy of name, as it is now: same kind, +// image and settings, and for a Machine its disk with every snapshot in +// it. The source stays locked while it is copied, so nothing starts it +// halfway through; the copy is registered like a creation (reserved +// first, dropped again if the backend fails). +func (s *Service) Clone(ctx context.Context, name, newName string) (Environment, error) { + newName = strings.TrimSpace(newName) + if err := validateEnvironmentName(newName); err != nil { + return Environment{}, err + } + source, backend, unlockSource, err := s.acquire(ctx, name) + if err != nil { + return Environment{}, err + } + defer unlockSource() + cloner, ok := backend.(Cloner) + if !ok { + return Environment{}, Unsupportedf("%s can't be cloned", name) + } + id, err := newID() + if err != nil { + return Environment{}, err + } + clone := Environment{ + ID: id, + Name: newName, + Image: source.Image, + Backend: source.Backend, + Kind: source.Kind, + Settings: source.Settings, + Snapshots: append([]Snapshot(nil), source.Snapshots...), + } + unlockClone, err := s.store.LockEnvironment(ctx, id) + if err != nil { + return Environment{}, err + } + defer unlockClone() + if err := s.reserve(ctx, clone); err != nil { + return Environment{}, err + } + if err := cloner.Clone(ctx, source, clone); err != nil { + if dropErr := s.drop(ctx, id); dropErr != nil { + return Environment{}, fmt.Errorf("clone %s: %w (and %s could not be taken out of the registry: %v)", name, err, newName, dropErr) + } + return Environment{}, fmt.Errorf("clone %s: %w", name, err) + } + created, err := s.update(ctx, id, func(e *Environment) { e.Operation = "" }) + if err != nil { + removeErr := backend.Remove(ctx, clone) + _ = s.drop(ctx, id) + if removeErr != nil { + return Environment{}, fmt.Errorf("save registry after cloning %s: %w (cleanup also failed, resource may be orphaned: %v)", name, err, removeErr) + } + return Environment{}, fmt.Errorf("save registry after cloning %s: %w", name, err) + } + s.syncLauncher(created) + return created, nil +} + // reserve adds env to the registry marked as being created, if its name // is free. func (s *Service) reserve(ctx context.Context, env Environment) error { @@ -491,6 +569,24 @@ func (s *Service) Start(ctx context.Context, name string) error { return nil } +// StartEphemeral starts a session whose changes are discarded at shutdown. +// The launcher entry isn't touched: it opens the environment normally. +func (s *Service) StartEphemeral(ctx context.Context, name string) error { + env, backend, unlock, err := s.acquire(ctx, name) + if err != nil { + return err + } + defer unlock() + starter, ok := backend.(EphemeralStarter) + if !ok { + return Unsupportedf("%s can't start without keeping changes: only Desktops (Machines) can", name) + } + if err := starter.StartEphemeral(ctx, env); err != nil { + return fmt.Errorf("start %s: %w", name, err) + } + return nil +} + // Open takes no lock: a Box's Open is its interactive shell and lasts as // long as the user keeps it. func (s *Service) Open(ctx context.Context, name string) error { @@ -753,6 +849,21 @@ func (s *Service) Configure(ctx context.Context, name string, patch SettingsPatc // programs in its terminal copy to the host clipboard (OSC 52). settings.ClipboardDisabled = !*patch.ShareClipboard } + if patch.ClipboardDirection != nil { + switch direction := strings.TrimSpace(*patch.ClipboardDirection); direction { + case "", ClipboardBoth: + settings.ClipboardDirection = "" + case ClipboardToHost: + settings.ClipboardDirection = direction + case ClipboardToGuest: + if env.Kind != Machine { + return EnvironmentSettings{}, Unsupportedf("a Box's clipboard only goes to this computer (programs copying from its terminal); turn it off instead") + } + settings.ClipboardDirection = direction + default: + return EnvironmentSettings{}, Invalidf("clipboard direction must be one of: %s, %s, %s", ClipboardBoth, ClipboardToHost, ClipboardToGuest) + } + } if patch.TravelMode != nil { // Both Kinds: a Machine starts with fewer CPUs, a Box's container // is limited in place. @@ -874,7 +985,7 @@ func (s *Service) CreateSnapshot(ctx context.Context, name, label string) (Snaps limit := env.EffectiveSettings().SnapshotLimit for limit > 0 && len(env.Snapshots) > limit { oldest := env.Snapshots[0] - if err := manager.RemoveSnapshot(ctx, env, oldest.ID); err != nil { + if err := manager.RemoveSnapshot(ctx, env, oldest.ID); err != nil && !errors.Is(err, ErrSnapshotGone) { // snap itself is saved; only the retention discard failed. return snap, fmt.Errorf("created %s, but discarding the oldest snapshot for %s failed: %w", label, name, err) } @@ -961,8 +1072,11 @@ func (s *Service) RemoveSnapshot(ctx context.Context, name, id string) error { if findSnapshot(env.Snapshots, id) == -1 { return fmt.Errorf("%w: snapshot %s", ErrNotFound, id) } - if err := manager.RemoveSnapshot(ctx, env, id); err != nil { + if err := manager.RemoveSnapshot(ctx, env, id); err != nil && !errors.Is(err, ErrSnapshotGone) { return fmt.Errorf("remove snapshot on %s: %w", name, err) + } else if err != nil { + // Already gone from the disk: only the registry still lists it. + slog.Warn("snapshot was no longer in the disk; removed from the list", "environment", name, "snapshot", id, "error", err) } _, err = s.update(ctx, env.ID, func(e *Environment) { e.Snapshots = withoutSnapshot(e.Snapshots, id) }) return err diff --git a/internal/core/snapshotgone_test.go b/internal/core/snapshotgone_test.go new file mode 100644 index 0000000..7049a1f --- /dev/null +++ b/internal/core/snapshotgone_test.go @@ -0,0 +1,44 @@ +package core_test + +import ( + "context" + "fmt" + "testing" + + "github.com/KitsuneSemCalda/OmaVM/internal/core" +) + +// A snapshot the registry lists but the disk lost (deleted by hand) must +// not get stuck in the list: removing it, or discarding it as the oldest, +// just forgets it. Before, the oldest such snapshot made every new +// snapshot report a failed discard. +func TestSnapshotGoneFromTheDiskIsForgotten(t *testing.T) { + box := newFakeBackend("fake-box") + machine := newFakeSnapshotBackend("fake-machine") + svc := core.NewService(&memStore{}, box, machine) + ctx := context.Background() + if _, err := svc.Create(ctx, core.Environment{Name: "vm", Kind: core.Machine, Image: testISO(t)}); err != nil { + t.Fatal(err) + } + limit := 2 + if _, err := svc.Configure(ctx, "vm", core.SettingsPatch{SnapshotLimit: &limit}); err != nil { + t.Fatal(err) + } + a, _ := svc.CreateSnapshot(ctx, "vm", "a") + b, _ := svc.CreateSnapshot(ctx, "vm", "b") + + machine.removeErr = fmt.Errorf("%w (qemu-img: snapshot not found)", core.ErrSnapshotGone) + if _, err := svc.CreateSnapshot(ctx, "vm", "c"); err != nil { + t.Fatalf("discarding an oldest snapshot that is already gone must not fail: %v", err) + } + snaps, _ := svc.ListSnapshots(ctx, "vm") + if len(snaps) != 2 || snaps[0].ID != b.ID { + t.Fatalf("expected b and c, got %+v (a=%s)", snaps, a.ID) + } + if err := svc.RemoveSnapshot(ctx, "vm", b.ID); err != nil { + t.Fatalf("removing a snapshot already gone from the disk: %v", err) + } + if snaps, _ = svc.ListSnapshots(ctx, "vm"); len(snaps) != 1 { + t.Fatalf("expected only c, got %+v", snaps) + } +} diff --git a/internal/desktop/desktop.go b/internal/desktop/desktop.go index 34318bf..d66e868 100644 --- a/internal/desktop/desktop.go +++ b/internal/desktop/desktop.go @@ -167,6 +167,9 @@ func (l *Launcher) entry(env core.Environment) []byte { if env.Settings.EmptyWorkspaceDisabled { exec = append(exec, "--empty-workspace", "false") } + if env.Settings.Color != "" { + exec = append(exec, "--color", env.Settings.Color) + } default: // Without omavm-gui, a Box's shell still opens in the user's own // terminal: `omavm open` on a Box is interactive. diff --git a/internal/desktop/desktop_test.go b/internal/desktop/desktop_test.go index dd59bd0..7a28c9e 100644 --- a/internal/desktop/desktop_test.go +++ b/internal/desktop/desktop_test.go @@ -162,6 +162,26 @@ func TestBoxEntryCarriesTheWorkspaceSetting(t *testing.T) { } } +// A Box opened from the launcher shows its color in the terminal, like one +// opened from the Experience Center. +func TestBoxEntryCarriesTheColor(t *testing.T) { + l := testLauncher(t) + env := core.Environment{ID: "abc", Name: "dev", Kind: core.Box, Settings: core.EnvironmentSettings{Color: "green"}} + if err := l.Publish(env); err != nil { + t.Fatal(err) + } + if entry := readEntry(t, l, env); !strings.Contains(entry, `"--color" "green"`) { + t.Fatalf("color not passed to the terminal:\n%s", entry) + } + env.Settings.Color = "" + if err := l.Publish(env); err != nil { + t.Fatal(err) + } + if entry := readEntry(t, l, env); strings.Contains(entry, "--color") { + t.Fatalf("a Box without a color got one:\n%s", entry) + } +} + // Regression: installed from the release tarball (OmaStore), OmaVM isn't // in the icon theme, so entries named a themed icon nothing provides. func TestEntryUsesTheBundledIconOutsideTheIconTheme(t *testing.T) { diff --git a/omavm-gui.pro b/omavm-gui.pro index 374021c..ecb2b29 100644 --- a/omavm-gui.pro +++ b/omavm-gui.pro @@ -5,6 +5,6 @@ CONFIG += c++17 release TARGET = omavm-gui TEMPLATE = app -HEADERS += gui/backend.h gui/displayclient.h gui/displayview.h gui/keymap.h gui/colorstoml.h gui/terminal.h gui/terminalview.h -SOURCES += gui/main.cpp gui/backend.cpp gui/displayclient.cpp gui/displayview.cpp gui/colorstoml.cpp gui/terminal.cpp gui/terminalview.cpp +HEADERS += gui/backend.h gui/displayclient.h gui/displayview.h gui/keymap.h gui/colorstoml.h gui/terminal.h gui/terminalview.h gui/singleinstance.h +SOURCES += gui/main.cpp gui/backend.cpp gui/displayclient.cpp gui/displayview.cpp gui/colorstoml.cpp gui/terminal.cpp gui/terminalview.cpp gui/singleinstance.cpp RESOURCES += gui/resources.qrc From 4c56ba8940bdcb17a8dff7c6b3051cff8ad9deb0 Mon Sep 17 00:00:00 2001 From: KitsuneSemCalda Date: Thu, 1 Oct 2026 19:39:57 -0300 Subject: [PATCH 3/5] qemu: report a missing qemu-system-x86_64 even without KVM Start blamed /dev/kvm whenever it was inaccessible, even when QEMU never ran because the binary was missing, hiding the install hint. CI runners have no KVM, so TestMissingBinaryDiagnostic failed there. The test now runs without KVM too. --- internal/backend/qemu/lifecycle_test.go | 4 ++++ internal/backend/qemu/qemu.go | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/internal/backend/qemu/lifecycle_test.go b/internal/backend/qemu/lifecycle_test.go index 9bfc570..077fb44 100644 --- a/internal/backend/qemu/lifecycle_test.go +++ b/internal/backend/qemu/lifecycle_test.go @@ -321,6 +321,10 @@ func TestBootMediaArguments(t *testing.T) { // raw "executable file not found in $PATH". func TestMissingBinaryDiagnostic(t *testing.T) { t.Setenv("PATH", t.TempDir()) // empty: neither binary resolves + // Like CI: no KVM either, which must not hide the missing binary. + saved := devRoot + devRoot = t.TempDir() + t.Cleanup(func() { devRoot = saved }) b := &Backend{stateDir: t.TempDir()} env := core.Environment{Name: "guest", Kind: core.Machine} diff --git a/internal/backend/qemu/qemu.go b/internal/backend/qemu/qemu.go index cf2ec55..d44e51d 100644 --- a/internal/backend/qemu/qemu.go +++ b/internal/backend/qemu/qemu.go @@ -299,9 +299,11 @@ func (b *Backend) start(ctx context.Context, env core.Environment, ephemeral boo if known := startFailure(env, out); known != nil { return known } - if !canOpenRW(filepath.Join(devRoot, "kvm")) { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && !canOpenRW(filepath.Join(devRoot, "kvm")) { // QEMU's own words ("Could not access KVM kernel module") - // don't say what to do about it. + // don't say what to do about it. Only when QEMU actually ran: + // a missing qemu-system-x86_64 already has its own message. return core.Unsupportedf("this computer can't run Desktops yet: hardware virtualization (/dev/kvm) is missing or not accessible to your user. Enable virtualization in the firmware and add your user to the kvm group, then log in again (QEMU said: %s)", out) } return qemuErr("qemu-system-x86_64", err, out) From acaedeacaa6ec1ad40bc643930d4aa7a84193e04 Mon Sep 17 00:00:00 2001 From: KitsuneSemCalda Date: Thu, 1 Oct 2026 19:43:11 -0300 Subject: [PATCH 4/5] Group backends by Kind under internal/backend machine/qemu, box/distrobox and box/container (the legacy Podman/Docker adapter), next to the box router. Code is unchanged; imports, comments and docs follow the new paths, and CLAUDE.md records the convention. --- CLAUDE.md | 12 ++++++------ cmd/omavm/main.go | 6 +++--- docs/TODO.md | 18 +++++++++--------- docs/ideias/boxes-distrobox.md | 2 +- docs/ideias/vsock-ssh.md | 2 +- docs/review-history.md | 14 +++++++------- gui/SettingsDialog.qml | 4 ++-- gui/backend.cpp | 2 +- gui/terminal.h | 2 +- .../backend/{ => box}/container/container.go | 0 .../{ => box}/container/container_test.go | 0 internal/backend/{ => box}/distrobox/apps.go | 0 .../backend/{ => box}/distrobox/apps_test.go | 0 .../backend/{ => box}/distrobox/distrobox.go | 0 .../{ => box}/distrobox/distrobox_test.go | 0 internal/backend/{ => box}/distrobox/pull.go | 0 .../backend/{ => box}/distrobox/pull_test.go | 0 internal/backend/{ => box}/distrobox/travel.go | 0 .../backend/{ => box}/distrobox/travel_test.go | 0 .../{ => box}/distrobox/upgrade_test.go | 0 internal/backend/{ => machine}/qemu/applied.go | 0 .../backend/{ => machine}/qemu/applied_test.go | 0 .../backend/{ => machine}/qemu/clone_test.go | 0 .../backend/{ => machine}/qemu/disk_test.go | 0 .../backend/{ => machine}/qemu/display_test.go | 0 .../{ => machine}/qemu/ephemeral_test.go | 0 .../backend/{ => machine}/qemu/guestcaps.go | 0 .../{ => machine}/qemu/guestcaps_test.go | 0 .../backend/{ => machine}/qemu/hostcaps.go | 0 .../{ => machine}/qemu/hostcaps_test.go | 0 .../backend/{ => machine}/qemu/hostlink.go | 0 .../{ => machine}/qemu/hostlink_test.go | 0 .../backend/{ => machine}/qemu/iso_test.go | 0 .../{ => machine}/qemu/lifecycle_test.go | 0 .../backend/{ => machine}/qemu/power_test.go | 0 internal/backend/{ => machine}/qemu/qemu.go | 0 .../backend/{ => machine}/qemu/qemu_test.go | 0 internal/backend/{ => machine}/qemu/qga.go | 0 .../backend/{ => machine}/qemu/qga_test.go | 0 internal/backend/{ => machine}/qemu/qmp.go | 0 .../backend/{ => machine}/qemu/qmp_test.go | 0 .../backend/{ => machine}/qemu/space_test.go | 0 .../{ => machine}/qemu/statedir_test.go | 0 .../{ => machine}/qemu/virtiofs_test.go | 0 internal/backend/{ => machine}/qemu/vsock.go | 0 .../backend/{ => machine}/qemu/vsock_test.go | 0 internal/core/service.go | 4 ++-- 47 files changed, 33 insertions(+), 33 deletions(-) rename internal/backend/{ => box}/container/container.go (100%) rename internal/backend/{ => box}/container/container_test.go (100%) rename internal/backend/{ => box}/distrobox/apps.go (100%) rename internal/backend/{ => box}/distrobox/apps_test.go (100%) rename internal/backend/{ => box}/distrobox/distrobox.go (100%) rename internal/backend/{ => box}/distrobox/distrobox_test.go (100%) rename internal/backend/{ => box}/distrobox/pull.go (100%) rename internal/backend/{ => box}/distrobox/pull_test.go (100%) rename internal/backend/{ => box}/distrobox/travel.go (100%) rename internal/backend/{ => box}/distrobox/travel_test.go (100%) rename internal/backend/{ => box}/distrobox/upgrade_test.go (100%) rename internal/backend/{ => machine}/qemu/applied.go (100%) rename internal/backend/{ => machine}/qemu/applied_test.go (100%) rename internal/backend/{ => machine}/qemu/clone_test.go (100%) rename internal/backend/{ => machine}/qemu/disk_test.go (100%) rename internal/backend/{ => machine}/qemu/display_test.go (100%) rename internal/backend/{ => machine}/qemu/ephemeral_test.go (100%) rename internal/backend/{ => machine}/qemu/guestcaps.go (100%) rename internal/backend/{ => machine}/qemu/guestcaps_test.go (100%) rename internal/backend/{ => machine}/qemu/hostcaps.go (100%) rename internal/backend/{ => machine}/qemu/hostcaps_test.go (100%) rename internal/backend/{ => machine}/qemu/hostlink.go (100%) rename internal/backend/{ => machine}/qemu/hostlink_test.go (100%) rename internal/backend/{ => machine}/qemu/iso_test.go (100%) rename internal/backend/{ => machine}/qemu/lifecycle_test.go (100%) rename internal/backend/{ => machine}/qemu/power_test.go (100%) rename internal/backend/{ => machine}/qemu/qemu.go (100%) rename internal/backend/{ => machine}/qemu/qemu_test.go (100%) rename internal/backend/{ => machine}/qemu/qga.go (100%) rename internal/backend/{ => machine}/qemu/qga_test.go (100%) rename internal/backend/{ => machine}/qemu/qmp.go (100%) rename internal/backend/{ => machine}/qemu/qmp_test.go (100%) rename internal/backend/{ => machine}/qemu/space_test.go (100%) rename internal/backend/{ => machine}/qemu/statedir_test.go (100%) rename internal/backend/{ => machine}/qemu/virtiofs_test.go (100%) rename internal/backend/{ => machine}/qemu/vsock.go (100%) rename internal/backend/{ => machine}/qemu/vsock_test.go (100%) diff --git a/CLAUDE.md b/CLAUDE.md index 8a1f704..6b8f2bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -168,13 +168,13 @@ A GUI roda ações de ambientes diferentes ao mesmo tempo (`Backend::busyEnviron **Color tags + Travel Mode — implementado (2026-09-27)**, a partir da pesquisa sobre Parallels Desktop (2026-09-26): `EnvironmentSettings.Color` vem de uma paleta fixa (`core.EnvironmentColors`: red/orange/yellow/green/blue/purple/gray — não hex livre, pra não competir com o tema Omarchy) e é o único mecanismo garantido; a sincronização com o gerenciador de arquivos do host é best-effort em cima disso, nunca uma promessa (Security Model). Só a Machine (QEMU) implementa a capability opcional `core.HostLinker`: `Configure` chama `Link` quando o `--color` muda, criando/atualizando `~/OmaVM/` como symlink pro qcow2 da Machine (dá a ela uma presença real e navegável no filesystem, papel equivalente ao bundle `.pvm` do Parallels) e tentando `setfattr -n user.xdg.tags` nesse link — se `setfattr` não existir ou falhar, a cor interna continua válida mesmo assim, só a integração visual no file manager que não acontece (o Omarchy pode ou não honrar essa xattr, fora do controle da OmaVM). `Remove` chama `Unlink`. Box ainda não implementa `HostLinker` (não tem um único arquivo pra vincular) — a cor fica só interna nesse caso, sem erro. Desde 2026-09-28 o `Link` também grava `metadata::custom-icon` (GVFS, via `gio set --nofollow-symlinks`) no próprio link, apontando para o ícone da cor (`data/icons/colors/.svg`, instalado em `/omavm/icons/`, achado por `desktop.ColorIcon`): é o que o **Nautilus** do Omarchy lê — ele ignora `user.xdg.tags`, que continua gravado para Dolphin/Baloo. Mesmo best-effort. -Travel Mode: `internal/backend/qemu/power.go` lê `/sys/class/power_supply` diretamente (sem depender do `upower`) só no momento do `Start`, não como daemon (`omavmd` continua fora de escopo). Se o host está na bateria, o usuário não fixou `--cpus` explicitamente e `EnvironmentSettings.TravelModeDisabled` está falso (default), o `Start` daquela sessão usa metade dos CPUs padrão (nunca sobrescrevendo o valor persistido) e loga via `slog`. Não reage a uma Machine já rodando quando a energia muda em tempo real — isso exigiria um watcher em background, que é exatamente o primeiro caso de uso concreto que justificaria um `omavmd` de verdade no futuro, mas essa decisão foi propositalmente adiada. +Travel Mode: `internal/backend/machine/qemu/power.go` lê `/sys/class/power_supply` diretamente (sem depender do `upower`) só no momento do `Start`, não como daemon (`omavmd` continua fora de escopo). Se o host está na bateria, o usuário não fixou `--cpus` explicitamente e `EnvironmentSettings.TravelModeDisabled` está falso (default), o `Start` daquela sessão usa metade dos CPUs padrão (nunca sobrescrevendo o valor persistido) e loga via `slog`. Não reage a uma Machine já rodando quando a energia muda em tempo real — isso exigiria um watcher em background, que é exatamente o primeiro caso de uso concreto que justificaria um `omavmd` de verdade no futuro, mas essa decisão foi propositalmente adiada. **Integrações são opt-out (decisão do usuário, 2026-09-28)**: toda integração nova com o host/desktop vem ligada e é desligável por ambiente em Settings — nunca um opt-in que o usuário precisa descobrir. Exceções que continuam manuais: habilitar o plugin Quickshell e a regra Hyprland pessoal (config de terceiros/pessoal que a OmaVM não escreve). Integração com custo de segurança também vem ligada quando o usuário decide assim — como o SSH via vsock —, mas o custo é **dito na tela** (Settings, `--help`, `omavm host`), nunca escondido (Security Model). -**Travel Mode para Boxes — implementado (2026-09-28)**: `internal/backend/distrobox/travel.go`, no Start/Open da Box, usa ` update --cpus` (Podman, ou Docker se for ele que tem o container) por baixo do Distrobox: na bateria, metade dos CPUs; na tomada, todos de volta. Testado contra Podman 6.1 + Distrobox 1.8: o limite vale com o container parado ou rodando e sobrevive a `distrobox enter` e stop/start; `--cpus 0` e `--cpu-quota -1/0` **não** removem um limite, por isso "sem limite" é `--cpus `. Box nunca limitada e na tomada não recebe `update` nenhum. Mesma opção opt-out `TravelModeDisabled` da Machine, agora para os dois Kinds. A leitura de energia saiu de `qemu/power.go` para `internal/power` (dois usos). Limites fixos de CPU/memória por Box continuam não implementados. +**Travel Mode para Boxes — implementado (2026-09-28)**: `internal/backend/box/distrobox/travel.go`, no Start/Open da Box, usa ` update --cpus` (Podman, ou Docker se for ele que tem o container) por baixo do Distrobox: na bateria, metade dos CPUs; na tomada, todos de volta. Testado contra Podman 6.1 + Distrobox 1.8: o limite vale com o container parado ou rodando e sobrevive a `distrobox enter` e stop/start; `--cpus 0` e `--cpu-quota -1/0` **não** removem um limite, por isso "sem limite" é `--cpus `. Box nunca limitada e na tomada não recebe `update` nenhum. Mesma opção opt-out `TravelModeDisabled` da Machine, agora para os dois Kinds. A leitura de energia saiu de `qemu/power.go` para `internal/power` (dois usos). Limites fixos de CPU/memória por Box continuam não implementados. -**SSH em Machines via vsock — implementado (2026-09-28), ligado por padrão por decisão do usuário**: `internal/backend/qemu/vsock.go` adiciona `-device vhost-vsock-pci,guest-cid=N` quando `/dev/vhost-vsock` é acessível e `EnvironmentSettings.SSHDisabled` é falso. O CID é aleatório acima de 65535 (longe dos sequenciais do libvirt), guardado em `/machines//vsock-cid` para a chave do host não mudar; se o QEMU recusar (`unable to set guest cid: Address already in use`, outro VM tem o CID), sorteia outro e tenta uma vez mais. O CID em uso é lido do `/proc//cmdline` do QEMU. `omavm ssh NOME [--user U] [-- CMD]` (capability `core.RemoteShell`) e `omavm exec` numa Machine (antes `ErrUnsupported`; agora `BatchMode=yes`, argumentos citados para o shell remoto) rodam `ssh vsock/` com `systemd-ssh-proxy`; as opções na linha de comando vencem o `ssh_config.d` do systemd, que loga como root e desliga a checagem de chave: aqui o login é o usuário do host e a chave fica em `known_hosts` sob `HostKeyAlias=omavm-` (`accept-new`). O guest precisa de systemd ≥ 256 com sshd; sem isso, erro claro. **Custo de segurança dito na tela**: o CID é global no host, então qualquer processo, Boxes incluídas, alcança o sshd do guest e só o login dele protege — Settings mostra isso em texto (não só tooltip), assim como `--help` e `omavm host`. Validado com QEMU real: sobe sem root, `savevm`/`loadvm` funcionam com o dispositivo, e `omavm ssh` chega ao CID pelo proxy (sem sshd no guest de teste, cai na mensagem de ajuda); login num guest real **não** foi verificado. +**SSH em Machines via vsock — implementado (2026-09-28), ligado por padrão por decisão do usuário**: `internal/backend/machine/qemu/vsock.go` adiciona `-device vhost-vsock-pci,guest-cid=N` quando `/dev/vhost-vsock` é acessível e `EnvironmentSettings.SSHDisabled` é falso. O CID é aleatório acima de 65535 (longe dos sequenciais do libvirt), guardado em `/machines//vsock-cid` para a chave do host não mudar; se o QEMU recusar (`unable to set guest cid: Address already in use`, outro VM tem o CID), sorteia outro e tenta uma vez mais. O CID em uso é lido do `/proc//cmdline` do QEMU. `omavm ssh NOME [--user U] [-- CMD]` (capability `core.RemoteShell`) e `omavm exec` numa Machine (antes `ErrUnsupported`; agora `BatchMode=yes`, argumentos citados para o shell remoto) rodam `ssh vsock/` com `systemd-ssh-proxy`; as opções na linha de comando vencem o `ssh_config.d` do systemd, que loga como root e desliga a checagem de chave: aqui o login é o usuário do host e a chave fica em `known_hosts` sob `HostKeyAlias=omavm-` (`accept-new`). O guest precisa de systemd ≥ 256 com sshd; sem isso, erro claro. **Custo de segurança dito na tela**: o CID é global no host, então qualquer processo, Boxes incluídas, alcança o sshd do guest e só o login dele protege — Settings mostra isso em texto (não só tooltip), assim como `--help` e `omavm host`. Validado com QEMU real: sobe sem root, `savevm`/`loadvm` funcionam com o dispositivo, e `omavm ssh` chega ao CID pelo proxy (sem sshd no guest de teste, cai na mensagem de ajuda); login num guest real **não** foi verificado. **Entrada no launcher por ambiente — implementado (2026-09-28), opt-out**: `internal/desktop` escreve `$XDG_DATA_HOME/applications/dev.omavm.env..desktop` para cada ambiente (nome pelo ID, que nunca muda). `Exec` de Machine é `omavm open NOME` (inicia se preciso e abre o viewer); de Box é `omavm-gui --terminal NOME` (ou `omavm open` com `Terminal=true` sem a GUI). Ícone pela cor do ambiente. A Core só conhece a interface `core.Launcher` (`Service.SetLauncher`, injetada pelo `cmd/omavm`): publica no Create/Configure e também no Start/Open (o que cobre ambientes criados antes), retira no Remove e quando `EnvironmentSettings.LauncherDisabled` (`--launcher=false`, Settings → Automation). Falha de escrita nunca falha a operação. `make uninstall` apaga as entradas (apontariam para binários que sumiram); `omavm` as recria no próximo start. @@ -283,7 +283,7 @@ O posicionamento **estático** da janela do viewer (fullscreen, workspace dedica Duas pegadinhas resolvidas nessa regra (2026-09-26): (1) workspace **especial** (`special:...`) nunca fica visível automaticamente — é um overlay estilo scratchpad que só aparece com `togglespecialworkspace` explícito; por isso a regra usa uma workspace **nomeada** normal (`name:omavm`), que troca a view do monitor sozinha quando a janela abre. (2) `gui/Viewer.qml` não pede fullscreen pelo próprio QML (`visibility: Window.FullScreen`) — pedir dos dois lados (client Wayland e regra do compositor) vira um toggle e cancela um ao outro, deixando a janela destilada em vez de fullscreen. Desde 2026-09-29 (pedido do usuário) o viewer de Machine abre em tela cheia **por padrão** (`EnvironmentSettings.FullscreenDisabled`, opt-out, só Machine; `--fullscreen=false`, Settings → Automation): `gui/main.cpp` só pede tela cheia (`showFullScreen()` no `Viewer.qml`) quando `hasPersonalViewerRule` não acha regra pessoal — com a regra, ela manda e o pedido duplo continua evitado. O terminal de Box não vai para tela cheia: sozinho num workspace vazio ele já ocupa a tela. -**Implementado (2026-09-27)**: o "Open" de uma Development Box também abre dentro do `omavm-gui`, em vez de um terminal externo (`xdg-terminal-exec`, removido). `gui/backend.cpp` relança o próprio binário em modo `--terminal --title ` (mesmo padrão do `--display-fd` de Machine), que carrega `gui/TerminalViewer.qml` reaproveitando de propósito o mesmo app id `dev.omavm.viewer` — a regra Hyprland opt-in acima cobre os dois sem configuração adicional. `internal/backend/distrobox`'s `Open()` (anexação interativa via `distrobox enter`, stdio herdado) não muda: o modo `--terminal` só cria um PTY próprio (`forkpty`, glibc) e executa `omavm open ` dentro dele — o mesmo comando que já funcionava num terminal real — então `omavm open` continua funcionando normalmente para humanos, scripts e agentes fora da GUI. +**Implementado (2026-09-27)**: o "Open" de uma Development Box também abre dentro do `omavm-gui`, em vez de um terminal externo (`xdg-terminal-exec`, removido). `gui/backend.cpp` relança o próprio binário em modo `--terminal --title ` (mesmo padrão do `--display-fd` de Machine), que carrega `gui/TerminalViewer.qml` reaproveitando de propósito o mesmo app id `dev.omavm.viewer` — a regra Hyprland opt-in acima cobre os dois sem configuração adicional. `internal/backend/box/distrobox`'s `Open()` (anexação interativa via `distrobox enter`, stdio herdado) não muda: o modo `--terminal` só cria um PTY próprio (`forkpty`, glibc) e executa `omavm open ` dentro dele — o mesmo comando que já funcionava num terminal real — então `omavm open` continua funcionando normalmente para humanos, scripts e agentes fora da GUI. O emulador (`gui/terminal.h/.cpp`, `gui/terminalview.h/.cpp`) é implementado do zero — mesma razão de licença do antigo cliente RFB (Backend Rules/Coding Principles: projeto MIT, viewers de terminal maduros como QTermWidget são GPL). Parser Ground/Escape/CSI/OSC cobre: movimento e endereçamento de cursor, SGR (16 cores, 256 cores, truecolor `38/48;2`), scrolling region, alternate screen buffer (`?1049`/`?47` — obrigatório pra vim/htop/less/tmux não corromperem a tela primária), scrollback limitado, título via OSC 0/2, e largura de caractere (desde 2026-09-28): CJK e emoji ocupam 2 colunas (célula-cabeça + célula de continuação com `ch` vazio), acentos combinantes se juntam à célula anterior, e escrever sobre metade de um caractere largo apaga a outra metade. Teclado (`TerminalSession::keySequence`, testável sem janela): segue o que `TERM=xterm-256color` promete — modo de aplicação das setas (DECCKM `?1h`, que o ncurses liga via `smkx` e depois só reconhece `\EOA`), modificadores no formato do xterm (`\E[1;5D` para Ctrl+←), `\E[Z` para Shift+Tab e os controles Ctrl+Espaço/`[`/`\`/`]`/`^`/`_`. A largura vem das tabelas Unicode do Qt, não do `wcwidth()` da glibc, que depende do locale (devolve -1 para tudo fora do ASCII com `LANG=C`, como no CI). Copiar (desde 2026-09-28): arrastar seleciona (vira seleção primária; clique do meio cola), clique duplo seleciona palavra/caminho, Ctrl+Shift+C e Ctrl+Insert (o Super+C do Omarchy) copiam — nunca chegam ao programa como Ctrl+C; a seleção não corta caractere largo e sobrevive ao descarte do scrollback (`droppedLines`). OSC 52 só de **escrita** (Neovim/tmux copiam para o host); pedido de leitura (`?`) é ignorado, porque deixaria qualquer coisa na Box ler o clipboard do host. É a mesma configuração opt-out `ClipboardDisabled` da Machine, que agora vale para os dois Kinds (repassada como `--share-clipboard`). O buffer de OSC é limitado (`kMaxOscLength`): um OSC sem terminador antes crescia sem limite. Parâmetros CSI são limitados a 65535, como no xterm (2026-09-29): achado por fuzz com ASan/UBSan, `ESC[2147483647C` com o cursor fora da coluna 0 estourava o int, levava o cursor a uma coluna negativa e o próximo erase escrevia fora da linha — segfault disparável por qualquer programa na Box ou por um `cat` de arquivo. `randomInputKeepsTheScreenConsistent` é um fuzz curto de semente fixa na suíte normal. Fora de escopo por enquanto (falha graciosamente, não quebra): mouse reporting, hyperlinks OSC 8, sixel. A paleta ANSI vem de `colors.toml` (via `gui/colorstoml.h`, extraído de `Backend::loadTheme()` — mesmo parser, dois usos reais agora) em vez de cores fixas, mesmo raciocínio de sync com o tema Omarchy do resto da GUI. Testes em `gui/tests/terminal_test.cpp` (`make test-terminal`) cobrem o parser via `feed()` direto (sem PTY) e dois testes de PTY real (`forkpty`+`execvp`+leitura+escrita via `/bin/sh`/`/bin/cat`). @@ -315,7 +315,7 @@ Lacunas conhecidas, deixadas como fallback honesto em vez de resolvidas por adiv **Conflito conhecido com a regra estática do viewer**: se o usuário já carregou `contrib/hypr/omavm-viewer.lua` (a regra opt-in acima, que fixa `dev.omavm.viewer` sempre no workspace nomeado `name:omavm` em fullscreen), essa regra de janela tem precedência sobre "qual workspace estava focado quando a janela abriu". Desde 2026-09-28 (padrão ligado), `hasPersonalViewerRule()` em `gui/backend.cpp` procura `dev.omavm.viewer` fora de comentários em `~/.config/hypr/**/*.lua|*.conf`; se achar, a OmaVM não troca de workspace (a regra pessoal manda) — senão o usuário ficaria olhando um workspace vazio enquanto a regra move a janela. A config pessoal nunca é reescrita. -**Diagnóstico do host e Vulkan — implementado (2026-09-28), por pedido direto do usuário**: `omavm host [--json]` (capability opcional `core.HostInspector`, só a Machine implementa, em `internal/backend/qemu/hostcaps.go`) informa KVM, OpenGL (render node + `virtio-vga-gl`), Vulkan e se dá para dedicar uma GPU a uma Machine. Só lê o host (sysfs, `/dev`, ICDs do Vulkan): nunca carrega módulo, liga driver ou muda permissão. O item de passthrough é **diagnóstico apenas** — GPU passthrough/VFIO e Looking Glass continuam fora do escopo abaixo (exigem configuração privilegiada do host, inviável com uma GPU só, e o Looking Glass mira guests Windows). Vulkan no guest (Venus: `virtio-vga-gl,blob=on,hostmem=4G,venus=on` + memória memfd) é **ligado por padrão quando a detecção passa** — só Mesa Intel/AMD, ICD instalado com biblioteca presente, `virgl_render_server`, `/dev/udmabuf` gravável — com opt-out por Machine (`EnvironmentSettings.VulkanDisabled`, `--vulkan=false`, Settings → Graphics). A falha do Venus não é detectável no Start (o virglrenderer só inicializa quando o driver do guest fala com a GPU), por isso a detecção é estática. Validado no host (QEMU sobe, Haiku renderiza com blob ligado); a aceleração dentro de um guest Linux **não** foi verificada — o usuário preferiu não baixar uma ISO de teste. +**Diagnóstico do host e Vulkan — implementado (2026-09-28), por pedido direto do usuário**: `omavm host [--json]` (capability opcional `core.HostInspector`, só a Machine implementa, em `internal/backend/machine/qemu/hostcaps.go`) informa KVM, OpenGL (render node + `virtio-vga-gl`), Vulkan e se dá para dedicar uma GPU a uma Machine. Só lê o host (sysfs, `/dev`, ICDs do Vulkan): nunca carrega módulo, liga driver ou muda permissão. O item de passthrough é **diagnóstico apenas** — GPU passthrough/VFIO e Looking Glass continuam fora do escopo abaixo (exigem configuração privilegiada do host, inviável com uma GPU só, e o Looking Glass mira guests Windows). Vulkan no guest (Venus: `virtio-vga-gl,blob=on,hostmem=4G,venus=on` + memória memfd) é **ligado por padrão quando a detecção passa** — só Mesa Intel/AMD, ICD instalado com biblioteca presente, `virgl_render_server`, `/dev/udmabuf` gravável — com opt-out por Machine (`EnvironmentSettings.VulkanDisabled`, `--vulkan=false`, Settings → Graphics). A falha do Venus não é detectável no Start (o virglrenderer só inicializa quando o driver do guest fala com a GPU), por isso a detecção é estática. Validado no host (QEMU sobe, Haiku renderiza com blob ligado); a aceleração dentro de um guest Linux **não** foi verificada — o usuário preferiu não baixar uma ISO de teste. Continua fora do escopo até necessidade real: guest agent completo, GPU passthrough, orchestration distribuída, cloud/remote hosts, marketplace, dezenas de distros, networking editor avançado, plugin system, e o Blend Mode completo (além da base acima). @@ -336,7 +336,7 @@ The following decisions are intentionally unresolved. Do not establish a project The exact directory/package structure beyond the project's basic layout is not yet fixed. Prefer the smallest structure required by the current vertical slice. Do not introduce speculative layers such as `domain/`, `application/`, `infrastructure/`, `ports/`, or `adapters/` solely to conform to an architectural pattern. Refactor the layout only when concrete responsibilities justify the separation. -One concrete constraint **is** settled: no `.go` files directly in the repository root. The Core lives in `internal/core`; binaries live under `cmd/`; backends live under `internal/backend/`. This is a fixed convention, not an open question — keep new code out of the root. +One concrete constraint **is** settled: no `.go` files directly in the repository root. The Core lives in `internal/core`; binaries live under `cmd/`; backends live under `internal/backend/`, grouped by Kind (since 2026-10-01): `machine/qemu`, `box/distrobox`, `box/container` (the legacy Podman/Docker adapter, one package because their CLIs are compatible) and `box` itself (routes each Box to Distrobox or the legacy adapter). A backend never sits under the other Kind's directory. This is a fixed convention, not an open question — keep new code out of the root. ### Template format diff --git a/cmd/omavm/main.go b/cmd/omavm/main.go index 844a47e..fe0e9ea 100644 --- a/cmd/omavm/main.go +++ b/cmd/omavm/main.go @@ -19,9 +19,9 @@ import ( "github.com/KitsuneSemCalda/OmaVM/internal/applog" "github.com/KitsuneSemCalda/OmaVM/internal/backend/box" - "github.com/KitsuneSemCalda/OmaVM/internal/backend/container" - "github.com/KitsuneSemCalda/OmaVM/internal/backend/distrobox" - "github.com/KitsuneSemCalda/OmaVM/internal/backend/qemu" + "github.com/KitsuneSemCalda/OmaVM/internal/backend/box/container" + "github.com/KitsuneSemCalda/OmaVM/internal/backend/box/distrobox" + "github.com/KitsuneSemCalda/OmaVM/internal/backend/machine/qemu" "github.com/KitsuneSemCalda/OmaVM/internal/core" "github.com/KitsuneSemCalda/OmaVM/internal/desktop" ) diff --git a/docs/TODO.md b/docs/TODO.md index 74caf42..dd59492 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -90,7 +90,7 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - Implementado (2026-10-01): Box parada → **Open** (inicia e abre o terminal); Desktop parado → **Start** (inicia e mostra a tela); rodando → **Open**; pausado → **Resume**. Uma dica (tooltip e `Accessible.description`) diz o resultado (“Start demo and show its screen”), e o primeiro item do menu usa o mesmo rótulo. Não há ação separada de “iniciar sem abrir”, porque não apareceu um caso de uso visível (a CLI tem `omavm start`). Teste: `test_primaryActionNamesTheResult`. Falta validar o launcher e cliques repetidos numa sessão real. - [ ] **Tornar pré-requisitos e recursos compreensíveis.** Verificar disponibilidade necessária ao fluxo, memória e espaço; oferecer instrução contextual quando algo impedir a criação. - Aceite: falhas previsíveis são explicadas antes da operação longa; não apresentar porcentagens ou estimativas fictícias. - - Implementado parcialmente (2026-09-27): binário ausente de `qemu-img`/`qemu-system-x86_64` agora falha com a mesma dica acionável que `virtiofsd` já tinha ("install it with: sudo pacman -S qemu-desktop"), em vez do erro cru do Go (achado já registrado na auditoria QEMU, ver abaixo). `distrobox` ausente já tinha diagnóstico equivalente antes desta sessão. Faixa de CPU/memória inválida também falha antes de qualquer chamada ao backend (ver item de resumo acima). Ainda faltam: checagem de espaço em disco/memória do host e de acesso a `/dev/kvm` antes da operação (o próprio QEMU recusa e o stderr chega ao usuário, mas não é antecipado). Teste de regressão: `TestMissingBinaryDiagnostic` em `internal/backend/qemu/lifecycle_test.go`. + - Implementado parcialmente (2026-09-27): binário ausente de `qemu-img`/`qemu-system-x86_64` agora falha com a mesma dica acionável que `virtiofsd` já tinha ("install it with: sudo pacman -S qemu-desktop"), em vez do erro cru do Go (achado já registrado na auditoria QEMU, ver abaixo). `distrobox` ausente já tinha diagnóstico equivalente antes desta sessão. Faixa de CPU/memória inválida também falha antes de qualquer chamada ao backend (ver item de resumo acima). Ainda faltam: checagem de espaço em disco/memória do host e de acesso a `/dev/kvm` antes da operação (o próprio QEMU recusa e o stderr chega ao usuário, mas não é antecipado). Teste de regressão: `TestMissingBinaryDiagnostic` em `internal/backend/machine/qemu/lifecycle_test.go`. - Continuação (2026-10-01): **KVM antes da operação**: o diálogo de criação consulta `omavm host --json` (`Backend::refreshHost`, sem estado de ocupado) e, se o KVM não está acessível, a opção Desktop diz que este computador ainda não inicia Desktops, com a instrução de correção do próprio diagnóstico (também na descrição acessível). Não bloqueia a criação: a pessoa pode corrigir depois. No `Start`, se o QEMU falha sem `/dev/kvm` acessível, o erro cru ("Could not access KVM kernel module") vira uma instrução (firmware, grupo `kvm`, novo login), classificado como indisponível (código 5); a checagem só acontece depois de uma falha, para não barrar testes nem hosts com o QEMU falso. **Espaço**: aviso abaixo de 4 GiB livres no card (ver a triagem). Testes: `TestStartWithoutKVMSaysHowToFixIt`, `test_missingKVMIsSaidBeforeCreating`. Falta: memória do host antes do Start (o QEMU aloca sob demanda, então um limite fixo erraria). - [ ] **Fechar o ciclo da instalação.** Explicar quando abrir o instalador, como voltar ao gerenciador e como desconectar a ISO após instalar. Após o desligamento da Machine, apresentar a próxima ação no contexto da mídia de instalação; não presumir que o guest terminou a instalação só porque desligou. - Aceite: criar → instalar → desligar → desconectar ISO → iniciar pelo disco é possível pela GUI, sem a pessoa precisar lembrar uma instrução lida antes da criação. A escolha de manter ou desconectar a ISO é explícita e reversível; testar instalação concluída, instalador interrompido e falha de boot pelo disco. @@ -103,7 +103,7 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - Aceite: iniciar/parar pelo CLI converge para o estado correto na GUI em até 5 segundos com a janela ativa, no host de teste documentado; não criar daemon apenas para isso. - Implementado e verificado em 2026-09-27 (ver [histórico](review-history.md)): `Timer` em `Main.qml` (3s, só enquanto `win.active`) atualiza os estados; corrigida de junto uma falha latente de atribuição por índice obsoleto em `enrichEnvironment` (`gui/backend.h,cpp`, novo `m_environmentsGeneration`) que o polling tornaria fácil de disparar. Verificado automatizado, sem GUI/humano: Machine criada e iniciada só pelo CLI, GUI nunca tocada, card foi de "Stopped"/"Start" para "Running"/"Open" com preview real em ~4s. Host de teste: Omarchy, Hyprland, `XDG_STATE_HOME` isolado, sem guest OS instalado. - Correção de flickering (2026-09-27): o polling agora usa `backend.poll()` sem alternar o estado visual de operação; o backend preserva status/integração/preview conhecidos e só notifica o modelo quando o valor muda. O preview permanece como miniatura da primeira captura enquanto a Machine está ligada, em vez de recarregar a cada 3s. Teste Qt focado confirma duas consultas idênticas sem `busyChanged` nem atualização redundante de ambientes; build da GUI e execução offscreen passaram. Falta confirmar visualmente na sessão real que a piscada relatada desapareceu. - - Continuação (2026-09-27): o usuário relatou que o viewer da Machine pisca só com o Experience Center aberto. Um cliente RFB em modo shared, conectado aos sockets VNC de duas Machines rodando (Haiku, Hello System), não registrou nenhuma atualização de framebuffer causada por `status`/`integration`/`preview`; o poll não mexe no display do guest. Custo real encontrado: `container.New()` rodava `podman info` em toda invocação do `omavm`, inclusive `list`/`status` de Machines (~330 ms de CPU por chamada, ~19 s de CPU em 25 s de poll com duas Machines). A detecção agora é preguiçosa (`internal/backend/container`), e `omavm list` caiu para ~3 ms. Além disso, um preview que falha (Haiku: `screendump: no surface`) era refeito em todo poll; agora espera 60 s antes de tentar de novo (`m_previewRetryAt`, teste `failedPreviewIsNotRetriedEveryPoll`). Hipótese ainda não confirmada visualmente: os picos de CPU a cada 3 s causavam o travamento percebido no viewer. + - Continuação (2026-09-27): o usuário relatou que o viewer da Machine pisca só com o Experience Center aberto. Um cliente RFB em modo shared, conectado aos sockets VNC de duas Machines rodando (Haiku, Hello System), não registrou nenhuma atualização de framebuffer causada por `status`/`integration`/`preview`; o poll não mexe no display do guest. Custo real encontrado: `container.New()` rodava `podman info` em toda invocação do `omavm`, inclusive `list`/`status` de Machines (~330 ms de CPU por chamada, ~19 s de CPU em 25 s de poll com duas Machines). A detecção agora é preguiçosa (`internal/backend/box/container`), e `omavm list` caiu para ~3 ms. Além disso, um preview que falha (Haiku: `screendump: no surface`) era refeito em todo poll; agora espera 60 s antes de tentar de novo (`m_previewRetryAt`, teste `failedPreviewIsNotRetriedEveryPoll`). Hipótese ainda não confirmada visualmente: os picos de CPU a cada 3 s causavam o travamento percebido no viewer. - Segunda causa, no próprio Experience Center (2026-09-28): a lista usava `backend.environments` (array JS) como model, e o `ListView` recria todos os delegates quando o array muda — confirmado com `qmltestrunner` (o card não é o mesmo objeto depois de uma mudança de status). Cada mudança de status, preview ou guest tools destruía e recriava todos os cards, rodando de novo o fade-in de 220 ms (piscar) e fechando qualquer menu "⋯" aberto. Corrigido com `gui/EnvironmentListModel.qml`, um `ListModel` sincronizado no lugar por nome; teste `tst_environmentlistmodel.qml` (mesmo card após mudança de status; inserir/remover/ordem). Falta confirmar na sessão real que a piscada sumiu. - [ ] **Concluir navegação por teclado e acessibilidade.** Dar nomes acessíveis a ícones e campos, foco visível, ordem de Tab coerente, retorno de foco ao fechar diálogos e indicação de seleção além da cor. - Aceite: criar, abrir, configurar e cancelar uma ação destrutiva são possíveis sem mouse; conferir nomes com leitor de tela. @@ -170,7 +170,7 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op - Aceite: salvar uma descrição não altera inadvertidamente a intenção de configuração de CPU; estados e defaults permanecem coerentes entre GUI e CLI. - **"Mudanças que exigem reinício" e "Travel Mode reduz recursos" implementados (2026-10-01).** O QEMU guarda na linha de comando o que a sessão recebeu (`-smp`, `-m`, vsock, virtiofs, `-cdrom`). `qemu.sessionAdjustments` compara isso com as configurações salvas e preenche `Status.RestartNeeded` e `Status.TravelMode` (omitidos quando falsos). Travel Mode = menos CPUs que o efetivo, sem CPUs fixados e sem opt-out. Card: "Restart to apply the saved settings" e "Travel Mode: started with fewer processors…"; `omavm status` diz o mesmo. Validado com o QEMU real: recém-iniciada, nada pendente; depois de `--memory-mib 4096`, `restart_needed: true`. Testes: `applied_test.go`, `test_sessionAdjustments`. Fora: Vulkan (a detecção é cara demais para o poll de 3 s), troca de caminho da pasta compartilhada com outra já compartilhada, e Boxes (o limite de CPU do Travel Mode delas exigiria consultar o engine por Box a cada poll). - **"Diferenciar preferência configurada de valor efetivo" implementado (2026-09-27).** Descoberta útil ao investigar o bug abaixo: `backend.environments` (que alimenta `SettingsDialog.qml`) vem de `omavm list --json`, e `Service.List` retorna os ambientes **brutos** (`internal/core/service.go`, nunca resolvidos por `EffectiveSettings()`, ao contrário do retorno de `Settings()`/`Configure()`) — então `settings.cpus` no JSON de list já vem ausente (`omitempty`) quando CPUs nunca foi fixado, sem precisar de nenhuma mudança de API. `SettingsDialog.qml` ganhou `cpusPinned`/`memoryPinned` (checando isso) e uma legenda por campo: "Not pinned yet: adapts automatically, and Travel Mode may reduce it while on battery" vs "Pinned — won't change on its own" vs "Will be pinned to this value on save" (quando `cpusTouched`/`memoryTouched` nesta sessão do diálogo). `qmllint`/`make build-gui` limpos. - - **Bug real encontrado e corrigido (2026-09-27), exatamente o cenário do aceite.** `Service.Configure` (`internal/core/service.go`) montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10 só para exibição) e depois persistia essa cópia inteira incondicionalmente — então **qualquer** `Configure`, mesmo alterando só a descrição, gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido explicitamente fixados. Consequência real: `internal/backend/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0`; salvar qualquer coisa em Settings desligava essa redução automática permanentemente, na primeira vez, sem o usuário nunca ter tocado em CPU. A correção original nesta sessão (rastrear "touched" nos `SpinBox` da GUI para só enviar `--cpus`/`--memory-mib` quando o usuário realmente mexeu) foi necessária mas **não suficiente** — o bug real estava no Core, não na GUI, e afetava qualquer chamador (CLI direto incluído). Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto); o valor de retorno de `Configure` continua resolvido (`env.EffectiveSettings()` no fim, depois de persistir), então CLI/GUI continuam mostrando "2 CPUs" mesmo quando nada foi fixado. + - **Bug real encontrado e corrigido (2026-09-27), exatamente o cenário do aceite.** `Service.Configure` (`internal/core/service.go`) montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10 só para exibição) e depois persistia essa cópia inteira incondicionalmente — então **qualquer** `Configure`, mesmo alterando só a descrição, gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido explicitamente fixados. Consequência real: `internal/backend/machine/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0`; salvar qualquer coisa em Settings desligava essa redução automática permanentemente, na primeira vez, sem o usuário nunca ter tocado em CPU. A correção original nesta sessão (rastrear "touched" nos `SpinBox` da GUI para só enviar `--cpus`/`--memory-mib` quando o usuário realmente mexeu) foi necessária mas **não suficiente** — o bug real estava no Core, não na GUI, e afetava qualquer chamador (CLI direto incluído). Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto); o valor de retorno de `Configure` continua resolvido (`env.EffectiveSettings()` no fim, depois de persistir), então CLI/GUI continuam mostrando "2 CPUs" mesmo quando nada foi fixado. - Evidência: reproduzido e corrigido com testes reais via CLI (`omavm create --kind machine` seguido de `omavm settings NOME --description "x"`, inspecionando o `environments.json` bruto diretamente — antes da correção: `cpus`/`memory_mib`/`snapshot_limit` apareciam gravados; depois: `settings` ficava só com `{"description":"x"}`, sem nenhum campo de hardware). Teste de regressão novo no Core, `TestConfigureUnrelatedFieldDoesNotPinHardwareDefaults` (`internal/core/service_test.go`) — confirmado que falha sem a correção (revertido manualmente pra provar) e passa com ela; também confirma que um pin explícito (`--cpus 4`) sobrevive a uma edição não relacionada posterior. `go test ./...` (suite inteira) e `make test` (inclui `make test-backend`, ver item de flickering acima) passam. Fix na GUI (rastreamento de "touched" em `SettingsDialog.qml`/`gui/backend.cpp,h`) mantido como complemento — evita reenviar `--cpus`/`--memory-mib` desnecessariamente mesmo com o Core já protegido, e documenta a intenção do usuário de forma mais explícita na camada de UI. - [ ] **Ajustar o Experience Center ao uso real.** Validar identificação da distribuição, previews, nomes longos e listas com 1, 10 e 30 ambientes. Adicionar busca simples se os testes mostrarem dificuldade de localização. - Aceite: o usuário localiza o ambiente por nome sem depender de miniaturas; foco e posição da lista não se perdem ao atualizar. @@ -180,25 +180,25 @@ Os sete ajustes de GUI foram registrados como implementados: bloqueio durante op A confiabilidade do backend sustenta a experiência da Machine. Os itens abaixo são eixos de investigação, não defeitos confirmados nem autorização para ampliar o escopo funcional. Primeiro auditar a implementação e os testes existentes; para cada lacuna, registrar caminho de código, reprodução, impacto e prioridade. Encerrar como verificado o que já estiver coberto, sem reimplementar capacidades maduras do QEMU. -Base da revisão: `internal/backend/qemu/`, contratos em `internal/core/`, CLI em `cmd/omavm/` e integração com o viewer em `gui/`. Manter controle de infraestrutura no backend e operações de gerenciamento acessíveis pelo Core/CLI. Relacionar os achados às tarefas de P0–P2, evitando abrir tarefas duplicadas para o mesmo problema. +Base da revisão: `internal/backend/machine/qemu/`, contratos em `internal/core/`, CLI em `cmd/omavm/` e integração com o viewer em `gui/`. Manter controle de infraestrutura no backend e operações de gerenciamento acessíveis pelo Core/CLI. Relacionar os achados às tarefas de P0–P2, evitando abrir tarefas duplicadas para o mesmo problema. - [ ] **Auditar ciclo de vida e reconciliação de estado.** Conferir consistência entre processo QEMU, registro persistido e estado informado ao CLI/GUI durante start, pause, resume, shutdown, restart e encerramento inesperado. Revisar identificação do processo, arquivos de estado obsoletos e operações concorrentes. Achado e corrigido em 2026-09-29: um `qemu.pid`/`virtiofs.pid` deixado por crash ou reboot, com o pid já reaproveitado por outro processo, fazia a Machine parecer rodando (Start virava no-op) e o Force Stop mandava SIGTERM a esse processo; agora o pid só vale se a linha de comando dele tiver o pidfile/socket da Machine (`processHasArg`, teste `TestStalePidfileOfAnotherProcessIsNotRunning`). Também em 2026-09-28: Force Stop passou a esperar o QEMU sair, porque Delete logo depois falhava. - Aceite: reproduzir falha de inicialização, saída inesperada, reabertura do gerenciador e ações concorrentes por CLI/GUI; não sinalizar sucesso antes da condição esperada nem agir sobre processo alheio. Falha de desligamento preserva a Machine e nunca vira Force Stop automaticamente. Relacionar à atualização de estados de P1. - - Rodada de 2026-10-01 (leitura de `internal/backend/qemu/qemu.go` + QEMU 11.1 real), procurando estados declarados antes de serem verdade. **Resume** depois de uma pausa por disco cheio: o `cont` retorna ok, mas o QEMU volta a pausar na hora se o disco do host continua cheio. Agora o Resume observa o estado por ~300 ms e, se voltou a `io-error`, falha com "paused again: …disk is full…" em vez de reportar sucesso. **Shut Down de uma Machine pausada**: ela é retomada para poder desligar; se o guest não desliga no prazo, antes ficava **rodando** (estado que a pessoa não escolheu). Agora volta a ser pausada, "as it was", e nunca recebe `quit`. Validado com o QEMU real: pausa → Shut Down sem guest → depois de 10 s `paused`, código 1. **Saída inesperada**: pidfile órfão = processo morto ou travado, reportado no status e no log (ver "Melhorar diagnóstico de falhas do QEMU"). **Falha de inicialização**: a Machine nunca fica falsamente ativa (disco preso → `stopped`, ver "Antecipar falhas de inicialização"). Já certos na leitura: Pause e Resume são síncronos no QMP; Stop espera o processo sumir; Force Stop espera sair; o pid só vale com o pidfile da Machine na linha de comando. Testes: `TestResumeThatPausesAgainOnDiskErrorFails`, `TestSlowShutdownOfPausedMachinePausesItAgain` (`gracefulShutdownTimeout` virou variável para o teste). Ainda por reproduzir: reabrir o gerenciador e ações concorrentes pela GUI numa sessão real. + - Rodada de 2026-10-01 (leitura de `internal/backend/machine/qemu/qemu.go` + QEMU 11.1 real), procurando estados declarados antes de serem verdade. **Resume** depois de uma pausa por disco cheio: o `cont` retorna ok, mas o QEMU volta a pausar na hora se o disco do host continua cheio. Agora o Resume observa o estado por ~300 ms e, se voltou a `io-error`, falha com "paused again: …disk is full…" em vez de reportar sucesso. **Shut Down de uma Machine pausada**: ela é retomada para poder desligar; se o guest não desliga no prazo, antes ficava **rodando** (estado que a pessoa não escolheu). Agora volta a ser pausada, "as it was", e nunca recebe `quit`. Validado com o QEMU real: pausa → Shut Down sem guest → depois de 10 s `paused`, código 1. **Saída inesperada**: pidfile órfão = processo morto ou travado, reportado no status e no log (ver "Melhorar diagnóstico de falhas do QEMU"). **Falha de inicialização**: a Machine nunca fica falsamente ativa (disco preso → `stopped`, ver "Antecipar falhas de inicialização"). Já certos na leitura: Pause e Resume são síncronos no QMP; Stop espera o processo sumir; Force Stop espera sair; o pid só vale com o pidfile da Machine na linha de comando. Testes: `TestResumeThatPausesAgainOnDiskErrorFails`, `TestSlowShutdownOfPausedMachinePausesItAgain` (`gracefulShutdownTimeout` virou variável para o teste). Ainda por reproduzir: reabrir o gerenciador e ações concorrentes pela GUI numa sessão real. - [ ] **Auditar comunicação QMP.** Verificar negociação, associação entre pedidos e respostas, eventos intercalados, erros, desconexão, cancelamento e limites de espera. Avaliar onde eventos ajudam a acompanhar transições dentro do ciclo de vida atual, sem presumir conexão permanente ou criar daemon só para isso. - Aceite: testes focados cobrem resposta de erro, ausência de resposta, conexão interrompida e evento intercalado; chamadas terminam com resultado ou erro identificável. Não repetir automaticamente uma operação mutável cujo resultado ficou desconhecido: reconciliar o estado antes de tentar novamente. - - Auditado e corrigido (2026-10-01), lendo `internal/backend/qemu/qmp.go`. Já estavam certos: o cumprimento e o `qmp_capabilities` em cada conexão; a correlação pedido/resposta (um comando por conexão, então a primeira resposta que não é evento é a dele); os eventos intercalados, ignorados. **Achados corrigidos:** (1) o prazo de 5 s era absoluto desde a conexão e valia para tudo, então um `blockdev-snapshot-internal-sync` de disco grande podia estourar enquanto o QEMU terminava o snapshot, deixando no disco um snapshot que o registro não conhece. Agora o prazo é por comando: 5 s por padrão e 10 min para criar ou apagar snapshot (`qmpSlowTimeout`). (2) Resposta que não chegou (conexão caiu ou prazo acabou) vira `errQMPNoReply` ("the command may or may not have run"), distinta de uma recusa. Criar ou apagar snapshot nesse caso **reconcilia** pelo `query-block` (o snapshot existe ou não no `virtio0`) em vez de repetir ou de dar falha às cegas. Se nem a consulta responde, a falha diz que o resultado não foi confirmado. (3) A recusa do QEMU vira `qmpError{Class, Desc}`, e a mensagem diz "…: Snapshot … does not exist (GenericError)" em vez de `map[class:… desc:…]`. Testes: `qmp_test.go` (erro estruturado, evento antes da resposta, conexão derrubada, silêncio com prazo, snapshot sem resposta reconciliado nos dois sentidos, e falha não confirmada). Formato do `query-block` e do erro conferidos no QEMU 11.1. Não feito: acompanhar transições por eventos, que exigiria uma conexão persistente, ou seja, um daemon. + - Auditado e corrigido (2026-10-01), lendo `internal/backend/machine/qemu/qmp.go`. Já estavam certos: o cumprimento e o `qmp_capabilities` em cada conexão; a correlação pedido/resposta (um comando por conexão, então a primeira resposta que não é evento é a dele); os eventos intercalados, ignorados. **Achados corrigidos:** (1) o prazo de 5 s era absoluto desde a conexão e valia para tudo, então um `blockdev-snapshot-internal-sync` de disco grande podia estourar enquanto o QEMU terminava o snapshot, deixando no disco um snapshot que o registro não conhece. Agora o prazo é por comando: 5 s por padrão e 10 min para criar ou apagar snapshot (`qmpSlowTimeout`). (2) Resposta que não chegou (conexão caiu ou prazo acabou) vira `errQMPNoReply` ("the command may or may not have run"), distinta de uma recusa. Criar ou apagar snapshot nesse caso **reconcilia** pelo `query-block` (o snapshot existe ou não no `virtio0`) em vez de repetir ou de dar falha às cegas. Se nem a consulta responde, a falha diz que o resultado não foi confirmado. (3) A recusa do QEMU vira `qmpError{Class, Desc}`, e a mensagem diz "…: Snapshot … does not exist (GenericError)" em vez de `map[class:… desc:…]`. Testes: `qmp_test.go` (erro estruturado, evento antes da resposta, conexão derrubada, silêncio com prazo, snapshot sem resposta reconciliado nos dois sentidos, e falha não confirmada). Formato do `query-block` e do erro conferidos no QEMU 11.1. Não feito: acompanhar transições por eventos, que exigiria uma conexão persistente, ou seja, um daemon. - [ ] **Antecipar falhas de inicialização.** Revisar verificações de acesso ao KVM, executáveis e capacidades necessárias, mídia, permissões, memória/espaço e conflitos de discos ou sockets. Distinguir verificações possíveis antes de iniciar de falhas que só o QEMU pode confirmar. - Aceite: dependência ausente, ISO inválida/inacessível e recurso ocupado produzem diagnóstico contextual, sem deixar o ambiente falsamente ativo. Limpar apenas recursos criados pela tentativa malsucedida e preservar dados anteriores. Alimentar a tarefa de pré-requisitos de P1 com as mesmas regras do backend. - Implementado (2026-10-01). Antes do QEMU, onde a verificação é determinística: **memória** acima do total do host (`/proc/meminfo`) é recusada com o valor e a correção (código 2); **ISO** é aberta de verdade em vez de só passar pelo `stat`, porque uma imagem sem permissão de leitura fazia o QEMU recusar o start inteiro ("Permission denied"). Agora ela segue a regra da ISO ausente: a Machine inicia pelo disco, e o motivo vai para o log. Pela saída do QEMU, o que só ele confirma: **disco ocupado** por outro processo (`Failed to get "write" lock`) vira `ErrBusy` (código 6) dizendo para fechar o outro programa; **memória indisponível no momento** (`cannot set up guest memory`) vira instrução de fechar programas ou baixar a memória. Saídas desconhecidas continuam como o QEMU disse. Já existiam: binários ausentes, KVM, espaço, sockets velhos apagados no start, e o virtiofsd encerrado se o QEMU falha (só o que a tentativa criou). Validado com o QEMU 11.1 real (disco preso por outro QEMU → código 6 e a Machine continua `stopped`; 262144 MiB num host de 15,7 GiB → código 2). Testes: `TestKnownStartFailuresSayWhatToDo`, `TestStartChecksMemoryAndReadableMedia`. - - Duas lacunas pontuais da auditoria anterior corrigidas em 2026-09-27: (1) `qemu-img`/`qemu-system-x86_64` ausentes agora produzem o mesmo tipo de dica acionável que `virtiofsd` já tinha (`qemuBinaryPath`/`runQEMU`/`qemuErr` em `internal/backend/qemu/qemu.go`), em vez do erro cru do Go; (2) `Start()` agora remove também `qmp.sock` obsoleto junto com VNC/QGA, fechando a assimetria de limpeza de sockets identificada. Teste de regressão: `TestMissingBinaryDiagnostic`. Ainda faltam: checagem antecipada de `/dev/kvm`, memória/espaço em disco e conflito de sockets em uso por outro processo (o QEMU já recusa esses casos com stderr repassado, mas sem antecipação). + - Duas lacunas pontuais da auditoria anterior corrigidas em 2026-09-27: (1) `qemu-img`/`qemu-system-x86_64` ausentes agora produzem o mesmo tipo de dica acionável que `virtiofsd` já tinha (`qemuBinaryPath`/`runQEMU`/`qemuErr` em `internal/backend/machine/qemu/qemu.go`), em vez do erro cru do Go; (2) `Start()` agora remove também `qmp.sock` obsoleto junto com VNC/QGA, fechando a assimetria de limpeza de sockets identificada. Teste de regressão: `TestMissingBinaryDiagnostic`. Ainda faltam: checagem antecipada de `/dev/kvm`, memória/espaço em disco e conflito de sockets em uso por outro processo (o QEMU já recusa esses casos com stderr repassado, mas sem antecipação). - [ ] **Revisar discos, snapshots e falhas parciais.** Mapear a ordem das alterações no disco, no histórico e no registro, incluindo retenção, restauração e exclusão. Verificar restrições de uso de imagens em execução e espaço disponível, sem tratar uma checagem inicial como garantia contra esgotamento posterior. - Aceite: em ambientes de teste descartáveis, exercitar falha de comando, interrupção entre etapas e espaço insuficiente; registrar estado final, pontos de recuperação preservados e caminho de recuperação. Nenhum sucesso aparente ou descarte silencioso de histórico válido após falha. Vincular as confirmações e avisos às tarefas de snapshots de P0. - Mapa da ordem (revisado 2026-10-01, `internal/core/service.go`): **criar** = backend cria → registro grava (logo após a confirmação) → retenção apaga o mais antigo no backend → registro o retira, um por vez. **Go To** = backend só, com a Machine parada; o registro não muda. **Remover** = backend apaga → registro retira. Falha antes do registro não deixa sucesso aparente. Um snapshot criado sem resposta do QEMU é reconciliado pelo `query-block` (ver "Auditar comunicação QMP"). - **Falha parcial corrigida (2026-10-01): snapshot listado no registro mas ausente do disco** (apagado à mão com `qemu-img`, disco trocado). Antes, removê-lo falhava para sempre e, se ele era o mais antigo, **todo snapshot novo** reportava "discarding the oldest failed" e a retenção travava. Agora o backend reconhece as mensagens reais do `qemu-img` (`snapshot not found`, `Failed to load snapshot: No such file or directory`) e do QMP (`… does not exist on device`) como `core.ErrSnapshotGone`. Remover e a retenção tratam isso como já removido: só tiram do registro, com aviso no log. Go To diz "snapshot is no longer in the disk: delete it from the list" (código 3). Validado com o `qemu-img` real (snapshot apagado à mão → Go To código 3 → remover código 0 → lista correta). Teste: `TestSnapshotGoneFromTheDiskIsForgotten`. Ainda aberto: o caso inverso (snapshot no disco que o registro não conhece) só acontece se gravar o registro falhar logo após o backend confirmar; ele fica invisível, sem perda de dados. - - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código: `savevm`/`loadvm`/`delvm` (Machine rodando, via `human-monitor-command`) podiam reportar sucesso mesmo quando a operação HMP subjacente falhava.** `qmp.go`'s `human-monitor-command` é um passthrough para comandos legados do monitor humano do QEMU; QEMU reporta falhas desses comandos específicos (tag desconhecida, snapshot corrompido etc.) como texto simples dentro do campo `"return"` da resposta QMP, não como um erro de protocolo QMP (`"error"`). `internal/backend/qemu/qemu.go` só checava o erro de protocolo e descartava o texto de retorno (`_, err := qmpHumanMonitorCommand(...)`) nos três call sites — exatamente o cenário do aceite acima ("nenhum sucesso aparente... após falha"). Pior em `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; se o `loadvm` falhasse silenciosamente dessa forma, o código seguia direto para `cont`, retomando a Machine no estado anterior ao restore (nada foi restaurado) enquanto CLI/GUI reportavam "Go To" como bem-sucedido. + - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código: `savevm`/`loadvm`/`delvm` (Machine rodando, via `human-monitor-command`) podiam reportar sucesso mesmo quando a operação HMP subjacente falhava.** `qmp.go`'s `human-monitor-command` é um passthrough para comandos legados do monitor humano do QEMU; QEMU reporta falhas desses comandos específicos (tag desconhecida, snapshot corrompido etc.) como texto simples dentro do campo `"return"` da resposta QMP, não como um erro de protocolo QMP (`"error"`). `internal/backend/machine/qemu/qemu.go` só checava o erro de protocolo e descartava o texto de retorno (`_, err := qmpHumanMonitorCommand(...)`) nos três call sites — exatamente o cenário do aceite acima ("nenhum sucesso aparente... após falha"). Pior em `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; se o `loadvm` falhasse silenciosamente dessa forma, o código seguia direto para `cont`, retomando a Machine no estado anterior ao restore (nada foi restaurado) enquanto CLI/GUI reportavam "Go To" como bem-sucedido. - Corrigido checando o texto de retorno (`strings.TrimSpace`) além do erro de protocolo nos três casos; texto não-vazio agora vira erro explícito. Em `GoToSnapshot` especificamente, o `cont` de resume agora é sempre tentado mesmo quando o `loadvm` falhou (a Machine já estava pausada por causa do `stop` anterior; deixá-la travada em pausa por causa de uma falha de restore seria um bug de lifecycle novo e distinto, não uma correção). - - Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/qemu/lifecycle_test.go`), com um servidor QMP fake retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` — confirmado que **falha** sem a correção (`GoToSnapshot` retornava `nil`) e passa com ela, incluindo a checagem de que `cont` ainda é enviado. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos. + - Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/machine/qemu/lifecycle_test.go`), com um servidor QMP fake retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` — confirmado que **falha** sem a correção (`GoToSnapshot` retornava `nil`) e passa com ela, incluindo a checagem de que `cont` ainda é enviado. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos. - **Bug real encontrado e corrigido (2026-09-27), achado por leitura de código, exatamente o cenário do aceite ("descarte silencioso de histórico válido após falha").** `Service.CreateSnapshot` (`internal/core/service.go`) criava o novo snapshot no backend, tentava descartar os mais antigos por causa do limite de retenção, e só persistia tudo — o novo snapshot incluído — num único `store.Save` no final. Se o backend já tivesse criado o novo snapshot com sucesso mas uma remoção de um antigo falhasse no meio (disco cheio, QMP caindo, etc.), a função retornava erro **sem nunca salvar** — perdendo o rastro do snapshot novo (que já existe de verdade no backend, mas o Core não sabe mais dele — um "snapshot fantasma", invisível em `snapshot list`, sem caminho de volta a não ser editando o arquivo de estado à mão). Pior: se ALGUM descarte antigo já tivesse sido bem-sucedido antes da falha, o registro persistido ficava referenciando um snapshot que o backend já apagou. - Corrigido persistindo incrementalmente: salva o novo snapshot imediatamente após o backend confirmar a criação, antes de mexer em retenção; salva de novo após cada descarte bem-sucedido dentro do loop de retenção. Uma falha no meio agora só afeta o passo que realmente falhou — nunca desfaz o que já era real. Em caso de falha na retenção, a função agora retorna o snapshot recém-criado (não mais um valor zerado) junto com o erro, já que ele genuinamente foi criado. - Evidência: teste de regressão novo `TestSnapshotCreatedButRetentionDiscardFailsStillPersistsNewSnapshot` (`internal/core/service_test.go`), usando o `removeErr` já existente em `fakeSnapshotBackend` pra simular a falha — verificado que **falha** sem a correção (revertida manualmente, restaurada depois) e passa com ela. `go build/vet/test` (suite inteira), `make build-gui`, `make test-backend` limpos. diff --git a/docs/ideias/boxes-distrobox.md b/docs/ideias/boxes-distrobox.md index dda3b73..5c2c36a 100644 --- a/docs/ideias/boxes-distrobox.md +++ b/docs/ideias/boxes-distrobox.md @@ -8,7 +8,7 @@ argumentos de `create`/`enter`/`stop`/`rm`/`list`, mas vira um binário (passa a ser `distrobox export`). Apps e binários exportados por Boxes do v1 precisam que a Box seja recriada. -Impacto na OmaVM: `internal/backend/distrobox/apps.go` executa +Impacto na OmaVM: `internal/backend/box/distrobox/apps.go` executa `distrobox enter --name -- distrobox-export --app ` (e `--delete`). O v1 instalado aqui (1.8.2.5) não tem subcomando `export` no host; o export roda dentro da Box. O anúncio do v2 não diz como o export é diff --git a/docs/ideias/vsock-ssh.md b/docs/ideias/vsock-ssh.md index 85d839d..c547aa4 100644 --- a/docs/ideias/vsock-ssh.md +++ b/docs/ideias/vsock-ssh.md @@ -19,7 +19,7 @@ alcançar serviços do guest a partir do host. ## Esboço -1. `internal/backend/qemu`: `-device vhost-vsock-pci,guest-cid=`, com CID +1. `internal/backend/machine/qemu`: `-device vhost-vsock-pci,guest-cid=`, com CID único por Machine (≥ 3) persistido no domínio ou derivado com checagem de colisão. `/dev/vhost-vsock` precisa estar acessível: reportar em `omavm host`. diff --git a/docs/review-history.md b/docs/review-history.md index bbc006f..d1a358d 100644 --- a/docs/review-history.md +++ b/docs/review-history.md @@ -53,9 +53,9 @@ Em progresso (2026-09-27, resposta a "sem animação nem nada"): adicionadas tra ### Achados da auditoria (2026-09-27, leitura de código — não reproduzido em host real) -Auditoria de código de `internal/backend/qemu/` e `internal/core/service.go`. Os itens abaixo não marcam nenhum item acima como concluído (o aceite de cada um exige reprodução, não só leitura); registram caminho de código, reprodução proposta, impacto e prioridade para quando a reprodução acontecer. +Auditoria de código de `internal/backend/machine/qemu/` e `internal/core/service.go`. Os itens abaixo não marcam nenhum item acima como concluído (o aceite de cada um exige reprodução, não só leitura); registram caminho de código, reprodução proposta, impacto e prioridade para quando a reprodução acontecer. -- **Concorrência Start/Start — reproduzida e corrigida (2026-09-27).** Confirmado em ambiente descartável (`XDG_STATE_HOME` isolado, Machine `racetest` sem ISO, `--image ""`): dois `omavm start racetest` disparados em paralelo contra uma Machine parada. Resultado real (não a hipótese original de "dois processos QEMU corrompendo o disco"): **apenas um** `qemu-system-x86_64 -daemonize -pidfile qemu.pid` venceu; o outro falhou rápido com `qemu-system-x86_64: cannot create PID file: Cannot lock pid file: Resource temporarily unavailable` — o próprio `-pidfile` do QEMU usa `flock`, então nenhum segundo processo chegou a existir de fato. O gap real não era corrupção de disco, era esse erro cru vazando para quem perdeu a corrida (parecia uma falha real de start, não "a Machine já está subindo"). Corrigido em `qemu.go`'s `Start()`: se `qemu-system-x86_64` falha, checar `isRunning()` de novo antes de propagar o erro — se a Machine está rodando (a outra chamada venceu), tratar como sucesso idempotente em vez de repassar o erro cru. Reproduzido de novo após a correção: as duas chamadas retornam limpo, um único processo QEMU. `go test ./internal/backend/qemu/...` continua passando. +- **Concorrência Start/Start — reproduzida e corrigida (2026-09-27).** Confirmado em ambiente descartável (`XDG_STATE_HOME` isolado, Machine `racetest` sem ISO, `--image ""`): dois `omavm start racetest` disparados em paralelo contra uma Machine parada. Resultado real (não a hipótese original de "dois processos QEMU corrompendo o disco"): **apenas um** `qemu-system-x86_64 -daemonize -pidfile qemu.pid` venceu; o outro falhou rápido com `qemu-system-x86_64: cannot create PID file: Cannot lock pid file: Resource temporarily unavailable` — o próprio `-pidfile` do QEMU usa `flock`, então nenhum segundo processo chegou a existir de fato. O gap real não era corrupção de disco, era esse erro cru vazando para quem perdeu a corrida (parecia uma falha real de start, não "a Machine já está subindo"). Corrigido em `qemu.go`'s `Start()`: se `qemu-system-x86_64` falha, checar `isRunning()` de novo antes de propagar o erro — se a Machine está rodando (a outra chamada venceu), tratar como sucesso idempotente em vez de repassar o erro cru. Reproduzido de novo após a correção: as duas chamadas retornam limpo, um único processo QEMU. `go test ./internal/backend/machine/qemu/...` continua passando. - Aceite (parcial): a parte Start/Start do item de P0 está reproduzida, corrigida e reverificada. A parte de snapshots (GoToSnapshot concorrente com CreateSnapshot/RemoveSnapshot) ainda não foi reproduzida — ver item abaixo. - **`GoToSnapshot` vs `CreateSnapshot`/`RemoveSnapshot` — reproduzido e corrigido (2026-09-27).** Confirmado em ambiente descartável, Machine parada (`snaprace`, sem ISO): `omavm snapshot create` e `omavm snapshot go-to` disparados em paralelo. Resultado real: nenhuma corrupção nem inconsistência de registro — `qemu-img` tem locking de imagem próprio, então quem perdeu a corrida falhou limpo com `qemu-img: Could not open '...disk.qcow2': Failed to get "write" lock. Is another process using the image?`. O registro (`environments.json`) ficou correto (a criação que falhou nunca foi persistida). O gap real, de novo, era um erro técnico cru vazando para quem perdesse a corrida, não perda de dados. Corrigido fazendo `Service.GoToSnapshot` (`service.go`) segurar o mesmo `store.Lock()` que `CreateSnapshot`/`RemoveSnapshot` já seguram durante toda a chamada ao backend — serializa as três operações no nível do Core em vez de deixar a corrida chegar ao `qemu-img`. Reproduzido de novo após a correção, numa Machine nova: as duas chamadas (`create`/`go-to`) concorrentes terminam com exit 0 e o registro reflete os dois snapshots corretamente. `go test ./...` (suite inteira) continua passando. - Caminho com a Machine **rodando** (savevm/loadvm/delvm via QMP em vez de `qemu-img` direto) também verificado: Machine real ligada (`snaprun`, sem ISO), `create`+`go-to` concorrentes terminam com exit 0 nos dois, registro com os dois snapshots e Machine de volta a "running" após o go-to (o ciclo `stop`/`loadvm`/`cont` de `GoToSnapshot` completou corretamente mesmo serializado atrás do lock). Considerar o item de P0 fechado para os cenários testados; `go test ./...` (suite inteira) passa. @@ -74,7 +74,7 @@ Auditoria de código de `internal/backend/qemu/` e `internal/core/service.go`. O Duas lacunas pontuais já registradas na auditoria acima foram corrigidas nesta sessão: -- **Diagnóstico de binário ausente.** `internal/backend/qemu/qemu.go` ganhou `qemuBinaryPath`/`runQEMU`/`qemuErr`, mesmo padrão de `virtiofsdPath`: `qemu-img`/`qemu-system-x86_64` ausentes agora falham com `" not found (install it with: sudo pacman -S qemu-desktop)"` (nome do pacote conforme `packaging/omavm/PKGBUILD`'s `optdepends`) em vez do erro cru do Go. Aplicado nos cinco pontos de chamada (`Create`, `Start`, `CreateSnapshot`, `GoToSnapshot`, `RemoveSnapshot`). Teste novo: `TestMissingBinaryDiagnostic` (isola `PATH` para um diretório vazio via `t.Setenv`). +- **Diagnóstico de binário ausente.** `internal/backend/machine/qemu/qemu.go` ganhou `qemuBinaryPath`/`runQEMU`/`qemuErr`, mesmo padrão de `virtiofsdPath`: `qemu-img`/`qemu-system-x86_64` ausentes agora falham com `" not found (install it with: sudo pacman -S qemu-desktop)"` (nome do pacote conforme `packaging/omavm/PKGBUILD`'s `optdepends`) em vez do erro cru do Go. Aplicado nos cinco pontos de chamada (`Create`, `Start`, `CreateSnapshot`, `GoToSnapshot`, `RemoveSnapshot`). Teste novo: `TestMissingBinaryDiagnostic` (isola `PATH` para um diretório vazio via `t.Setenv`). - **Limpeza de socket incompleta.** `Start()` agora remove `qmpPath(name)` obsoleto junto com VNC/QGA, fechando a assimetria identificada. Trabalho novo em P1, seguindo a ordem domínio → backend → Core → CLI → GUI: @@ -189,7 +189,7 @@ Retomando após um reset de uso no meio da tarefa (contexto recuperado lendo os Rastreei isso em duas camadas: 1. **GUI** (`gui/SettingsDialog.qml`/`backend.cpp`/`.h`): os `SpinBox` de CPU/memória sempre mostravam o valor *efetivo* (2/2048, já resolvido pelo Core mesmo quando nada estava fixado) e `Backend::configure` sempre reenviava `--cpus`/`--memory-mib` incondicionalmente a cada Save — mesmo salvando só a descrição. Corrigido com rastreamento de "touched": `SpinBox.onValueModified` (dispara só em interação real do usuário, não na atribuição programática em `onOpened`) marca `cpusTouched`/`memoryTouched`; `Backend::configure` ganhou esses dois parâmetros extras e só inclui as flags quando de fato tocado. -2. **Core** (`internal/core/service.go`'s `Configure`) — **a causa raiz real, que o fix da GUI sozinho não resolvia**: `Configure` montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10, pensado só para exibição) e persistia essa cópia inteira de volta incondicionalmente. Resultado: **qualquer** chamada a `Configure` — inclusive via CLI direto, sem GUI nenhuma no meio — gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido fixados, mesmo alterando só a descrição. Consequência real, não hipotética: `internal/backend/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0` — salvar qualquer coisa em Settings desligava essa redução automática pra sempre, na primeira vez, mesmo o usuário nunca tendo tocado em CPU. Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto), retornando `env.EffectiveSettings()` só no final (depois de persistir) pra CLI/GUI continuarem mostrando o valor resolvido para exibição. +2. **Core** (`internal/core/service.go`'s `Configure`) — **a causa raiz real, que o fix da GUI sozinho não resolvia**: `Configure` montava sua cópia de trabalho a partir de `env.EffectiveSettings()` (que substitui CPUs/MemoryMiB/SnapshotLimit não fixados por 2/2048/10, pensado só para exibição) e persistia essa cópia inteira de volta incondicionalmente. Resultado: **qualquer** chamada a `Configure` — inclusive via CLI direto, sem GUI nenhuma no meio — gravava CPUs/MemoryMiB/SnapshotLimit como se tivessem sido fixados, mesmo alterando só a descrição. Consequência real, não hipotética: `internal/backend/machine/qemu/qemu.go`'s `Start` só reduz CPUs no Travel Mode quando o valor bruto persistido é `0` — salvar qualquer coisa em Settings desligava essa redução automática pra sempre, na primeira vez, mesmo o usuário nunca tendo tocado em CPU. Corrigido trocando a base de `env.EffectiveSettings()` para `env.Settings` (bruto), retornando `env.EffectiveSettings()` só no final (depois de persistir) pra CLI/GUI continuarem mostrando o valor resolvido para exibição. Confirmado com reprodução real via CLI (binário compilado, `XDG_STATE_HOME` isolado): `create --kind machine` (sem `--cpus`) seguido de `settings NOME --description "x"`, inspecionando `environments.json` bruto diretamente. Antes da correção: `cpus`/`memory_mib`/`snapshot_limit` apareciam gravados no arquivo mesmo sem terem sido passados. Depois: `settings` fica só com `{"description":"x"}`. Testado também que um pin explícito (`--cpus 4`) sobrevive a uma edição não relacionada posterior — continua fixado. @@ -207,7 +207,7 @@ Evidência: `qmllint`/`make build-gui` limpos; `go build/vet/test` inalterados ( ## Sessão de 2026-09-27 (continuação, /loop): snapshot novo podia "sumir" se o descarte de retenção falhasse -Depois de fechar a família de bugs de pinning de CPU/memória, apliquei o mesmo tipo de auditoria (rastrear cada ponto onde `EffectiveSettings()` é lido, cada `store.Save` e o que exatamente cada função persiste) no resto do Core, pra confirmar que a família de bug estava mesmo fechada e procurar outras do mesmo gênero. Todos os outros usos de `EffectiveSettings()` (`internal/backend/qemu/qemu.go`'s `Start`/`Open`, e `Service.CreateSnapshot`'s leitura do `SnapshotLimit`) já eram só leituras pra decisão/execução, nunca persistidas de volta — confirmados limpos. +Depois de fechar a família de bugs de pinning de CPU/memória, apliquei o mesmo tipo de auditoria (rastrear cada ponto onde `EffectiveSettings()` é lido, cada `store.Save` e o que exatamente cada função persiste) no resto do Core, pra confirmar que a família de bug estava mesmo fechada e procurar outras do mesmo gênero. Todos os outros usos de `EffectiveSettings()` (`internal/backend/machine/qemu/qemu.go`'s `Start`/`Open`, e `Service.CreateSnapshot`'s leitura do `SnapshotLimit`) já eram só leituras pra decisão/execução, nunca persistidas de volta — confirmados limpos. Mas essa mesma auditoria achou um bug diferente, na MESMA função (`Service.CreateSnapshot`): o fluxo cria o snapshot novo no backend, tenta descartar os mais antigos por causa do limite de retenção, e só persistia tudo — o novo snapshot incluído — num único `store.Save` no final da função. Se o backend já tivesse criado o snapshot novo (chamada real, sucesso confirmado) mas uma remoção de snapshot antigo falhasse no meio do loop de retenção (disco cheio, QMP caindo, etc.), a função retornava erro **sem nunca ter salvo nada** — perdendo o rastro do snapshot que genuinamente existe no backend agora, um "fantasma" invisível em `snapshot list`. Se algum descarte antigo já tivesse sido bem-sucedido antes da falha, pior ainda: o registro persistido continuava referenciando um snapshot que o backend já tinha apagado de verdade. @@ -230,10 +230,10 @@ Teste de regressão: `TestCreateRollsBackBackendWhenRegistrySaveFails`. Precisou Depois de fechar a família de bugs de persistência do Core, verifiquei se o padrão "probe caro chamado a toda invocação" corrigido em `container.New()` (`sync.Once`, ver sessão anterior) se repetia em outros backends: `grep -n "^func New\b" internal/backend/*/*.go` mostrou `distrobox.New()` e `box.New()` já leves (retornam a struct direto, sem I/O), e `qemu.New()` só resolve um path (`core.StateDir()` + `filepath.Join`), sem shell out. `cmd/omavm/main.go` confirma que os três são construídos incondicionalmente a cada invocação do CLI (`qemu.New()`, `box.New(distrobox.New(), container.New())`), então o fix de `container.New()` já cobria o único ponto caro que existia. Nada a corrigir aqui — auditoria encerrada sem achado novo. -Segui então para o próximo item não marcado da frente QEMU ("Auditar comunicação QMP") e achei um bug real em `internal/backend/qemu/qmp.go`/`qemu.go`: `human-monitor-command` — o passthrough QMP usado para `savevm`/`loadvm`/`delvm` (snapshots com a Machine rodando) — reporta falhas do comando HMP subjacente (tag desconhecida, snapshot corrompido, etc.) como **texto simples dentro do campo `"return"`** da resposta QMP, não como um erro de protocolo (`"error"`). Isso é uma característica documentada do `human-monitor-command`: ele é um passthrough pro monitor de texto legado, e comandos HMP individuais reportam seus próprios erros escrevendo no stream de saída do monitor (que vira a string de `"return"`), sem propagar isso como falha ao nível QMP. +Segui então para o próximo item não marcado da frente QEMU ("Auditar comunicação QMP") e achei um bug real em `internal/backend/machine/qemu/qmp.go`/`qemu.go`: `human-monitor-command` — o passthrough QMP usado para `savevm`/`loadvm`/`delvm` (snapshots com a Machine rodando) — reporta falhas do comando HMP subjacente (tag desconhecida, snapshot corrompido, etc.) como **texto simples dentro do campo `"return"`** da resposta QMP, não como um erro de protocolo (`"error"`). Isso é uma característica documentada do `human-monitor-command`: ele é um passthrough pro monitor de texto legado, e comandos HMP individuais reportam seus próprios erros escrevendo no stream de saída do monitor (que vira a string de `"return"`), sem propagar isso como falha ao nível QMP. `qemu.go` chamava `qmpHumanMonitorCommand` nos três call sites descartando a string de retorno (`_, err := ...`), checando só o erro de protocolo. Resultado: uma falha real do `savevm`/`loadvm`/`delvm` passava despercebida — exatamente o cenário do aceite de "Revisar discos, snapshots e falhas parciais" ("nenhum sucesso aparente... após falha"). O caso mais grave é `GoToSnapshot`: a Machine é pausada (`stop`) antes do `loadvm`; com o bug, um `loadvm` que falhasse silenciosamente dessa forma seguia direto para `cont` — retomando a Machine no estado anterior ao restore (nada foi de fato restaurado) enquanto CLI/GUI reportavam a operação como bem-sucedida. Corrigido checando `strings.TrimSpace` da string de retorno nos três call sites (`savevm`, `loadvm`, `delvm`); texto não-vazio agora vira um erro explícito com o próprio texto do QEMU. Em `GoToSnapshot` fiz questão de sempre tentar o `cont` de resume mesmo quando o `loadvm` falhou — a Machine já estava pausada por causa do `stop` anterior, e deixá-la travada em pausa por causa de uma falha de restore seria introduzir um bug de lifecycle novo (Machine presa pausada) só para "corrigir" o de snapshot. -Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/qemu/lifecycle_test.go`), reusando o padrão de servidor QMP fake do teste vizinho `TestGoToSnapshotPausesAroundRunningRestore`, mas retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` em vez de `""`. Verificado com o método de sempre: revertido manualmente (backup/restore via `cp`), confirmado que o teste **falha** sem a correção (`GoToSnapshot` retornava `nil`, nenhum erro reportado) e passa com ela — incluindo a checagem de que a sequência de comandos ainda é `["stop", "human-monitor-command", "cont"]`, provando que o resume acontece mesmo no caminho de falha. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos depois. +Evidência: teste de regressão novo `TestGoToSnapshotReportsHMPFailureAndStillResumes` (`internal/backend/machine/qemu/lifecycle_test.go`), reusando o padrão de servidor QMP fake do teste vizinho `TestGoToSnapshotPausesAroundRunningRestore`, mas retornando `"return": "Error: Snapshot 'before-upgrade' not found"` para `human-monitor-command` em vez de `""`. Verificado com o método de sempre: revertido manualmente (backup/restore via `cp`), confirmado que o teste **falha** sem a correção (`GoToSnapshot` retornava `nil`, nenhum erro reportado) e passa com ela — incluindo a checagem de que a sequência de comandos ainda é `["stop", "human-monitor-command", "cont"]`, provando que o resume acontece mesmo no caminho de falha. `go build/vet/test` (suite inteira) e `gofmt -l .` limpos depois. diff --git a/gui/SettingsDialog.qml b/gui/SettingsDialog.qml index 56d4d09..db3859f 100644 --- a/gui/SettingsDialog.qml +++ b/gui/SettingsDialog.qml @@ -29,7 +29,7 @@ Dialog { // the description) must never resend the *displayed* value as an // explicit --cpus/--memory-mib — that would silently pin it, which // disables Travel Mode's automatic reduction on battery - // (internal/backend/qemu/qemu.go's Start only reduces CPUs when the + // (internal/backend/machine/qemu/qemu.go's Start only reduces CPUs when the // raw, persisted setting is unset). Only actually touching a SpinBox // — SpinBox.onValueModified, which fires on user interaction and not // on the programmatic `.value = x` assignment in onOpened — marks it @@ -339,7 +339,7 @@ Dialog { } // What works with the guest right now, checked on the guest side - // where OmaVM can (internal/backend/qemu/guestcaps.go), and the + // where OmaVM can (internal/backend/machine/qemu/guestcaps.go), and the // next step for the rest — in text, not only in a tooltip. Label { visible: dialog.machine && guestRepeater.count > 0 diff --git a/gui/backend.cpp b/gui/backend.cpp index deef909..89aa1d4 100644 --- a/gui/backend.cpp +++ b/gui/backend.cpp @@ -837,7 +837,7 @@ void Backend::open(const QString &name, const QString &kind) { // Relaunch this same omavm-gui binary in its embedded terminal mode // (gui/main.cpp's --terminal, gui/TerminalViewer.qml) — same pattern // as a Machine's Open spawning omavm-gui --display-fd - // (internal/backend/qemu/qemu.go), so a Box opens inside OmaVM's own + // (internal/backend/machine/qemu/qemu.go), so a Box opens inside OmaVM's own // window instead of whatever external terminal emulator the user has // configured. const auto flag = [](bool on) { diff --git a/gui/terminal.h b/gui/terminal.h index 7e26225..7d67ae9 100644 --- a/gui/terminal.h +++ b/gui/terminal.h @@ -36,7 +36,7 @@ struct TerminalCell { }; // Owns a PTY and the child process attached to it (`omavm open `, -// unchanged — see internal/backend/distrobox), and turns the raw byte +// unchanged — see internal/backend/box/distrobox), and turns the raw byte // stream coming back from that child into a grid of TerminalCell plus a // cursor position, via a small Ground/Escape/CSI/OSC state machine. See // gui/README-worthy comment in terminal.cpp for the exact escape-sequence diff --git a/internal/backend/container/container.go b/internal/backend/box/container/container.go similarity index 100% rename from internal/backend/container/container.go rename to internal/backend/box/container/container.go diff --git a/internal/backend/container/container_test.go b/internal/backend/box/container/container_test.go similarity index 100% rename from internal/backend/container/container_test.go rename to internal/backend/box/container/container_test.go diff --git a/internal/backend/distrobox/apps.go b/internal/backend/box/distrobox/apps.go similarity index 100% rename from internal/backend/distrobox/apps.go rename to internal/backend/box/distrobox/apps.go diff --git a/internal/backend/distrobox/apps_test.go b/internal/backend/box/distrobox/apps_test.go similarity index 100% rename from internal/backend/distrobox/apps_test.go rename to internal/backend/box/distrobox/apps_test.go diff --git a/internal/backend/distrobox/distrobox.go b/internal/backend/box/distrobox/distrobox.go similarity index 100% rename from internal/backend/distrobox/distrobox.go rename to internal/backend/box/distrobox/distrobox.go diff --git a/internal/backend/distrobox/distrobox_test.go b/internal/backend/box/distrobox/distrobox_test.go similarity index 100% rename from internal/backend/distrobox/distrobox_test.go rename to internal/backend/box/distrobox/distrobox_test.go diff --git a/internal/backend/distrobox/pull.go b/internal/backend/box/distrobox/pull.go similarity index 100% rename from internal/backend/distrobox/pull.go rename to internal/backend/box/distrobox/pull.go diff --git a/internal/backend/distrobox/pull_test.go b/internal/backend/box/distrobox/pull_test.go similarity index 100% rename from internal/backend/distrobox/pull_test.go rename to internal/backend/box/distrobox/pull_test.go diff --git a/internal/backend/distrobox/travel.go b/internal/backend/box/distrobox/travel.go similarity index 100% rename from internal/backend/distrobox/travel.go rename to internal/backend/box/distrobox/travel.go diff --git a/internal/backend/distrobox/travel_test.go b/internal/backend/box/distrobox/travel_test.go similarity index 100% rename from internal/backend/distrobox/travel_test.go rename to internal/backend/box/distrobox/travel_test.go diff --git a/internal/backend/distrobox/upgrade_test.go b/internal/backend/box/distrobox/upgrade_test.go similarity index 100% rename from internal/backend/distrobox/upgrade_test.go rename to internal/backend/box/distrobox/upgrade_test.go diff --git a/internal/backend/qemu/applied.go b/internal/backend/machine/qemu/applied.go similarity index 100% rename from internal/backend/qemu/applied.go rename to internal/backend/machine/qemu/applied.go diff --git a/internal/backend/qemu/applied_test.go b/internal/backend/machine/qemu/applied_test.go similarity index 100% rename from internal/backend/qemu/applied_test.go rename to internal/backend/machine/qemu/applied_test.go diff --git a/internal/backend/qemu/clone_test.go b/internal/backend/machine/qemu/clone_test.go similarity index 100% rename from internal/backend/qemu/clone_test.go rename to internal/backend/machine/qemu/clone_test.go diff --git a/internal/backend/qemu/disk_test.go b/internal/backend/machine/qemu/disk_test.go similarity index 100% rename from internal/backend/qemu/disk_test.go rename to internal/backend/machine/qemu/disk_test.go diff --git a/internal/backend/qemu/display_test.go b/internal/backend/machine/qemu/display_test.go similarity index 100% rename from internal/backend/qemu/display_test.go rename to internal/backend/machine/qemu/display_test.go diff --git a/internal/backend/qemu/ephemeral_test.go b/internal/backend/machine/qemu/ephemeral_test.go similarity index 100% rename from internal/backend/qemu/ephemeral_test.go rename to internal/backend/machine/qemu/ephemeral_test.go diff --git a/internal/backend/qemu/guestcaps.go b/internal/backend/machine/qemu/guestcaps.go similarity index 100% rename from internal/backend/qemu/guestcaps.go rename to internal/backend/machine/qemu/guestcaps.go diff --git a/internal/backend/qemu/guestcaps_test.go b/internal/backend/machine/qemu/guestcaps_test.go similarity index 100% rename from internal/backend/qemu/guestcaps_test.go rename to internal/backend/machine/qemu/guestcaps_test.go diff --git a/internal/backend/qemu/hostcaps.go b/internal/backend/machine/qemu/hostcaps.go similarity index 100% rename from internal/backend/qemu/hostcaps.go rename to internal/backend/machine/qemu/hostcaps.go diff --git a/internal/backend/qemu/hostcaps_test.go b/internal/backend/machine/qemu/hostcaps_test.go similarity index 100% rename from internal/backend/qemu/hostcaps_test.go rename to internal/backend/machine/qemu/hostcaps_test.go diff --git a/internal/backend/qemu/hostlink.go b/internal/backend/machine/qemu/hostlink.go similarity index 100% rename from internal/backend/qemu/hostlink.go rename to internal/backend/machine/qemu/hostlink.go diff --git a/internal/backend/qemu/hostlink_test.go b/internal/backend/machine/qemu/hostlink_test.go similarity index 100% rename from internal/backend/qemu/hostlink_test.go rename to internal/backend/machine/qemu/hostlink_test.go diff --git a/internal/backend/qemu/iso_test.go b/internal/backend/machine/qemu/iso_test.go similarity index 100% rename from internal/backend/qemu/iso_test.go rename to internal/backend/machine/qemu/iso_test.go diff --git a/internal/backend/qemu/lifecycle_test.go b/internal/backend/machine/qemu/lifecycle_test.go similarity index 100% rename from internal/backend/qemu/lifecycle_test.go rename to internal/backend/machine/qemu/lifecycle_test.go diff --git a/internal/backend/qemu/power_test.go b/internal/backend/machine/qemu/power_test.go similarity index 100% rename from internal/backend/qemu/power_test.go rename to internal/backend/machine/qemu/power_test.go diff --git a/internal/backend/qemu/qemu.go b/internal/backend/machine/qemu/qemu.go similarity index 100% rename from internal/backend/qemu/qemu.go rename to internal/backend/machine/qemu/qemu.go diff --git a/internal/backend/qemu/qemu_test.go b/internal/backend/machine/qemu/qemu_test.go similarity index 100% rename from internal/backend/qemu/qemu_test.go rename to internal/backend/machine/qemu/qemu_test.go diff --git a/internal/backend/qemu/qga.go b/internal/backend/machine/qemu/qga.go similarity index 100% rename from internal/backend/qemu/qga.go rename to internal/backend/machine/qemu/qga.go diff --git a/internal/backend/qemu/qga_test.go b/internal/backend/machine/qemu/qga_test.go similarity index 100% rename from internal/backend/qemu/qga_test.go rename to internal/backend/machine/qemu/qga_test.go diff --git a/internal/backend/qemu/qmp.go b/internal/backend/machine/qemu/qmp.go similarity index 100% rename from internal/backend/qemu/qmp.go rename to internal/backend/machine/qemu/qmp.go diff --git a/internal/backend/qemu/qmp_test.go b/internal/backend/machine/qemu/qmp_test.go similarity index 100% rename from internal/backend/qemu/qmp_test.go rename to internal/backend/machine/qemu/qmp_test.go diff --git a/internal/backend/qemu/space_test.go b/internal/backend/machine/qemu/space_test.go similarity index 100% rename from internal/backend/qemu/space_test.go rename to internal/backend/machine/qemu/space_test.go diff --git a/internal/backend/qemu/statedir_test.go b/internal/backend/machine/qemu/statedir_test.go similarity index 100% rename from internal/backend/qemu/statedir_test.go rename to internal/backend/machine/qemu/statedir_test.go diff --git a/internal/backend/qemu/virtiofs_test.go b/internal/backend/machine/qemu/virtiofs_test.go similarity index 100% rename from internal/backend/qemu/virtiofs_test.go rename to internal/backend/machine/qemu/virtiofs_test.go diff --git a/internal/backend/qemu/vsock.go b/internal/backend/machine/qemu/vsock.go similarity index 100% rename from internal/backend/qemu/vsock.go rename to internal/backend/machine/qemu/vsock.go diff --git a/internal/backend/qemu/vsock_test.go b/internal/backend/machine/qemu/vsock_test.go similarity index 100% rename from internal/backend/qemu/vsock_test.go rename to internal/backend/machine/qemu/vsock_test.go diff --git a/internal/core/service.go b/internal/core/service.go index 8359f28..e540750 100644 --- a/internal/core/service.go +++ b/internal/core/service.go @@ -74,7 +74,7 @@ func (s *Service) backendFor(kind EnvironmentKind) (Backend, error) { // validateEnvironmentName rejects names that would be unsafe once a // Backend turns them into part of a filesystem path. Machines created // before their directory was named by ID still live under their name -// (internal/backend/qemu's key()), where ".." or "/" would let it escape +// (internal/backend/machine/qemu's key()), where ".." or "/" would let it escape // its parent; the launcher and ~/OmaVM links use the name too. Otherwise // intentionally permissive: spaces, accents and most punctuation are // fine. @@ -767,7 +767,7 @@ func (s *Service) Configure(ctx context.Context, name string, patch SettingsPatc // defaults as if explicitly pinned on every single Configure call, // even ones that only touch an unrelated field like Description. // That's a real bug this project hit: it permanently disables Travel - // Mode's automatic CPU reduction (internal/backend/qemu/qemu.go's + // Mode's automatic CPU reduction (internal/backend/machine/qemu/qemu.go's // Start only reduces CPUs when the raw setting is still 0) the first // time anyone saves Settings for any reason (docs/TODO.md P2 // "salvar uma descrição não altera inadvertidamente a intenção de From 2ebf57ff16f0f9aeb203863baec538717a5c39ff Mon Sep 17 00:00:00 2001 From: KitsuneSemCalda Date: Thu, 1 Oct 2026 19:48:39 -0300 Subject: [PATCH 5/5] tst_environmentcard: don't name a variable long Qt 6.4's QML parser still reserves long (an ES3 future reserved word), so the whole file failed to compile on CI; newer Qt accepts it. --- gui/tests/qml/tst_environmentcard.qml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/tests/qml/tst_environmentcard.qml b/gui/tests/qml/tst_environmentcard.qml index d4b166c..2b02df4 100644 --- a/gui/tests/qml/tst_environmentcard.qml +++ b/gui/tests/qml/tst_environmentcard.qml @@ -110,10 +110,10 @@ Item { // A long name at the narrowest width is cut inside the card, never // pushing the open action out of it (docs/TODO.md P2). function test_longNameStaysInsideANarrowCard() { - const long = "Fedora de testes do projeto de compiladores com um nome bem comprido" + const longName = "Fedora de testes do projeto de compiladores com um nome bem comprido" loader.setSource("qrc:/EnvironmentCard.qml", { width: 320, - environment: { name: long, kind: "box", status: "stopped", settings: { color: "green" } } + environment: { name: longName, kind: "box", status: "stopped", settings: { color: "green" } } }) tryVerify(() => loader.status === Loader.Ready) const card = loader.item