Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions CLAUDE.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
80 changes: 79 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
98 changes: 98 additions & 0 deletions cmd/omavm/errors.go
Original file line number Diff line number Diff line change
@@ -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
}
87 changes: 87 additions & 0 deletions cmd/omavm/errors_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
Loading
Loading