From f7b918faea08939b1f99f74eee2990be09ab17b9 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:16:22 +0100 Subject: [PATCH 1/5] i3: serve node-display-session.open, percent-encoded and recorded as an act (issue 935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit node-display-session gains the verb open: an http or https address opened in the session's default browser through xdg-mime and systemd-run --user, never i3's IPC (which hands a shell a command line). The address is percent-encoded per RFC 3986's unreserved set plus the separators a URL needs, as one argument; a refusal names the reason (scheme, host, length, session, default program, the opener's own failure). Each call that is acted on is written to the log of acts done by hand (seat:mesh-hand-acts.hand-act), with its caller and why. Builds: design 08 sign-in-page §3, §29 --- modules/i3/cmd/i3-tools/main.go | 12 +- modules/i3/cmd/i3-tools/manifest_test.go | 24 ++- modules/i3/cmd/i3-tools/open.go | 229 +++++++++++++++++++++++ modules/i3/cmd/i3-tools/open_test.go | 224 ++++++++++++++++++++++ modules/i3/cmd/i3-tools/tools.go | 6 + modules/i3/module.json | 11 +- 6 files changed, 501 insertions(+), 5 deletions(-) create mode 100644 modules/i3/cmd/i3-tools/open.go create mode 100644 modules/i3/cmd/i3-tools/open_test.go diff --git a/modules/i3/cmd/i3-tools/main.go b/modules/i3/cmd/i3-tools/main.go index a8fd4a857..82de29aa6 100644 --- a/modules/i3/cmd/i3-tools/main.go +++ b/modules/i3/cmd/i3-tools/main.go @@ -53,7 +53,7 @@ func machine() *i3 { if state == "" { state = filepath.Join(home, ".local", "state") } - t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")} + t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), handAct: liveHandAct} t.socket = func() (string, error) { runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid())) i3sock := "" @@ -83,6 +83,16 @@ func tools(t *i3) []stdio.Tool { Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}), Run: call(t.reload), }, + { + Name: "node-display-session.open", + Description: "Open an http or https address in the person's default browser, for any caller over the bus " + + "(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " + + "too long once encoded, no graphical session or no default program for the scheme; the opener's " + + "failure is refused naming its status. Answers once the opener has started: opened within its bound, " + + "or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.", + Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"), + Run: call(t.open), + }, { Name: "node-display-session.workspaces", Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.", diff --git a/modules/i3/cmd/i3-tools/manifest_test.go b/modules/i3/cmd/i3-tools/manifest_test.go index d41fb7adc..5be02a970 100644 --- a/modules/i3/cmd/i3-tools/manifest_test.go +++ b/modules/i3/cmd/i3-tools/manifest_test.go @@ -17,6 +17,7 @@ import ( type manifest struct { Capabilities []string `json:"capabilities"` Requires []string `json:"requires"` + Invokes []string `json:"invokes"` Claims []struct { Name string `json:"name"` Scope string `json:"scope"` @@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any { func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { m := readManifest(t) - if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" { + if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" { t.Fatalf("%+v", m.Claims) } if strings.Join(m.Requires, ",") != "x11-display" { @@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { t.Errorf("the seat's %s is not served", v) } } - if len(served) != len(m.Tools)+3 { + if len(served) != len(m.Tools)+4 { t.Fatalf("served %d, listed %d", len(served), len(m.Tools)) } for _, n := range m.Tools { @@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin } } +// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the +// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's +// served verbs. +func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) { + m := readManifest(t) + if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" { + t.Fatalf("invokes: %v", m.Invokes) + } + served := map[string]bool{} + for _, v := range m.Claims[0].Serves { + served[v] = true + } + if !served["open"] { + t.Fatal("node-display-session does not serve open") + } +} + func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { m := readManifest(t) r := resource(t, m, "session") @@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { pkgs[x["package"].(string)] = true } } - if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 { + if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 { t.Fatalf("%v", pkgs) } a := m.Build.Artifacts[0] diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go new file mode 100644 index 000000000..b48939e68 --- /dev/null +++ b/modules/i3/cmd/i3-tools/open.go @@ -0,0 +1,229 @@ +// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https +// address in the person's default browser, outside i3's own IPC (which hands a shell a command +// line); this verb takes the address as one argument, through the account's own program chooser +// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act +// (ADR 0565 §10): each call that is acted on is written to the log of acts done by hand. +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + stdio "git.novox.be/novox/mesh-sdk/go" + + "i3/internal/desktop" +) + +// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a +// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener +// is left to go on and the answer says opening. A test shortens it with the i3's openBound field. +const defaultOpenTimeout = 10 * time.Second + +// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3). +const openMaxAddress = 2048 + +// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter, +// ended by a colon. +var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`) + +// openKept are the characters open's encoding never touches, beside the unreserved ones (letters, +// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is +// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9). +const openKept = "-._~:/?#[]@&=+%" + +// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme +// other than http or https, no scheme (a file path), no host. +func checkAddressShape(address string) (scheme string, err error) { + m := schemePattern.FindStringSubmatch(address) + if m == nil { + return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address) + } + scheme = strings.ToLower(m[1]) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("a scheme other than http or https: %s", scheme) + } + afterScheme := address[len(m[0]):] + if !strings.HasPrefix(afterScheme, "//") { + return "", fmt.Errorf("no host: %s has no // after its scheme", scheme) + } + rest := afterScheme[2:] + end := strings.IndexAny(rest, "/?#") + authority := rest + if end >= 0 { + authority = rest[:end] + } + if at := strings.LastIndex(authority, "@"); at >= 0 { + authority = authority[at+1:] + } + if authority == "" { + return "", fmt.Errorf("no host") + } + return scheme, nil +} + +// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs +// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form. +// Nothing is refused for a character, and the result is never read by a shell. +func encodeAddress(address string) string { + var b strings.Builder + for i := 0; i < len(address); i++ { + c := address[i] + switch { + case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9': + b.WriteByte(c) + case strings.IndexByte(openKept, c) >= 0: + b.WriteByte(c) + default: + fmt.Fprintf(&b, "%%%02X", c) + } + } + return b.String() +} + +// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason: +// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is +// none. +func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) { + res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme) + name := strings.TrimSpace(res.Stdout) + if !res.OK() || name == "" { + return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme) + } + return name, nil +} + +// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data +// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes +// and arguments. +func entryCommand(entry string) string { + for _, dir := range xdgDataDirs() { + b, err := os.ReadFile(filepath.Join(dir, "applications", entry)) + if err != nil { + continue + } + inEntry := false + for _, line := range strings.Split(string(b), "\n") { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "["): + inEntry = line == "[Desktop Entry]" + case inEntry: + if exec, ok := strings.CutPrefix(line, "Exec="); ok { + if fields := strings.Fields(exec); len(fields) > 0 { + return fields[0] + } + return "" + } + } + } + } + return "" +} + +// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the +// system's (XDG_DATA_DIRS, or its default). +func xdgDataDirs() []string { + dirs := []string{os.Getenv("XDG_DATA_HOME")} + if dirs[0] == "" { + dirs[0] = filepath.Join(desktop.Home(), ".local", "share") + } + extra := os.Getenv("XDG_DATA_DIRS") + if extra == "" { + extra = "/usr/local/share:/usr/share" + } + for _, d := range strings.Split(extra, ":") { + if d != "" { + dirs = append(dirs, d) + } + } + return dirs +} + +// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's +// default browser for the scheme, and answers once the opener has started. +func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { + caller := stdio.CallerOf(map[string]any(a)) + address, err := a.Text("address") + if err != nil { + return nil, err + } + scheme, err := checkAddressShape(address) + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + encoded := encodeAddress(address) + if len(encoded) > openMaxAddress { + err := fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + + s, err := t.d.Find() + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + env := s.Env(t.d.Base) + + program, err := defaultProgram(ctx, t.d, env, scheme) + if err != nil { + t.journalOpen(address, "refused", err.Error()) + return nil, err + } + + bound := t.openBound + if bound == 0 { + bound = defaultOpenTimeout + } + runCtx, cancel := context.WithTimeout(ctx, bound) + defer cancel() + res := t.d.Run(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) + + if !res.OK() && !res.TimedOut { + reason := res.Err().Error() + t.journalOpen(address, "refused", reason) + return nil, fmt.Errorf("the opener failed: %s", reason) + } + + started := "opened" + if res.TimedOut { + started = "opening" + } + command := entryCommand(program) + t.journalOpen(address, started, program) + t.recordHandAct(caller, encoded, program, started) + return map[string]any{"address": encoded, "program": program, "command": command, "started": started}, nil +} + +// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14): +// the address, opened or refused, and the program or the reason. +func (t *i3) journalOpen(address, outcome, programOrReason string) { + fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason) +} + +// recordHandAct writes open's call to the log of acts done by hand (design 08 sign-in-page §29; +// ADR 0565 §10): open is an act, so every call that is acted on (never a refusal before the +// opener ran) is recorded with its caller and why. +func (t *i3) recordHandAct(caller, address, program, started string) { + if t.handAct == nil { + return + } + what := fmt.Sprintf("%s %s in %s", started, address, program) + why := fmt.Sprintf("asked by %s", caller) + if err := t.handAct(what, why); err != nil { + fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err) + } +} + +// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module +// (design 08 sign-in-page §29). +func liveHandAct(what, why string) error { + _, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"}) + return err +} diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go new file mode 100644 index 000000000..f36f139b5 --- /dev/null +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -0,0 +1,224 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "i3/internal/desktop" +) + +// runCall records one call the stood-in opener saw, so a test can check the exact argv it was +// handed (design 08 sign-in-page §29, R2-9: one argument, no shell). +type runCall struct { + name string + args []string +} + +// stubOpener builds an i3 whose session is found (unless find answers an error) and whose +// commands are answered from answers, keyed by the command's name ("xdg-mime", "systemd-run"); +// every call is recorded in calls. +func stubOpener(t *testing.T, find func() (*desktop.Session, error), answers map[string]desktop.Result) (*i3, *[]runCall) { + t.Helper() + calls := &[]runCall{} + run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + *calls = append(*calls, runCall{name, args}) + res, ok := answers[name] + if !ok { + t.Fatalf("unexpected command %s %v", name, args) + } + if res.TimedOut { + <-ctx.Done() + return desktop.Result{TimedOut: true} + } + return res + } + return &i3{d: desktop.Desk{Find: find, Run: run}, openBound: 50 * time.Millisecond}, calls +} + +func foundSession() (*desktop.Session, error) { + return &desktop.Session{}, nil +} + +func writeDesktopEntry(t *testing.T, entry, execLine string) { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_DATA_HOME", dir) + apps := filepath.Join(dir, "applications") + if err := os.MkdirAll(apps, 0o755); err != nil { + t.Fatal(err) + } + text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n" + if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil { + t.Fatal(err) + } +} + +// 935/I-1: every scheme but http and https, and a file path, is refused. +func TestOpenRefusesEveryOtherScheme(t *testing.T) { + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{}) + for _, address := range []string{ + "/etc/passwd", // no scheme: a file path + "file:///etc/passwd", // a scheme other than http or https + "ftp://example.net/f", // a scheme other than http or https + "mailto:a@example.net", // a scheme other than http or https, no // + "http://", // no host + "https:///path", // no host + } { + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { + t.Errorf("%s: not refused", address) + } + } + if len(*calls) != 0 { + t.Fatalf("a refused address never reaches the opener: %v", *calls) + } +} + +// 935/I-1: an address over 2048 bytes once encoded is refused. +func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{}) + address := "https://example.net/" + strings.Repeat("a", 2048) + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { + t.Fatal("not refused") + } +} + +// 935/I-1: with no graphical session it refuses, as its other tools answer. +func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { + x, _ := stubOpener(t, func() (*desktop.Session, error) { + return nil, &desktop.NoSession{Reason: "none"} + }, map[string]desktop.Result{}) + _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if !desktop.IsNoSession(err) { + t.Fatalf("%v", err) + } +} + +// 935/I-1: no default program for the scheme is refused. +func TestOpenRefusesWithNoDefaultProgram(t *testing.T) { + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: ""}, + }) + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil { + t.Fatal("not refused") + } + for _, c := range *calls { + if c.name == "systemd-run" { + t.Fatal("the opener never runs with no default program") + } + } +} + +// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its +// UTF-8 form, and the address reaches the opener as one argument, never a shell command line. +func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + address := `https://example.net/a'b;c d$(e),f"g` + got, err := run(t, x, "node-display-session.open", map[string]any{"address": address}) + if err != nil { + t.Fatal(err) + } + want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g` + answer := got.(map[string]any) + if answer["address"] != want { + t.Fatalf("got %q, want %q", answer["address"], want) + } + var last runCall + for _, c := range *calls { + if c.name == "systemd-run" { + last = c + } + } + if len(last.args) == 0 || last.args[len(last.args)-1] != want { + t.Fatalf("the address is not the opener's last, whole argument: %v", last.args) + } + for _, a := range last.args { + if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") { + t.Fatalf("an argument still carries a shell character: %q", a) + } + } +} + +// 935/I-3: an opener that fails is refused with its status and names no program. +func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 1, Stderr: "no such unit"}, + }) + _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err == nil || !strings.Contains(err.Error(), "no such unit") { + t.Fatalf("%v", err) + } +} + +// 935/I-3: an opener that ends well answers opened with the program. +func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err != nil { + t.Fatal(err) + } + answer := got.(map[string]any) + if answer["started"] != "opened" || answer["program"] != "browser.desktop" || answer["command"] != "firefox" { + t.Fatalf("%+v", answer) + } +} + +// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer +// names the program only once the opener started). +func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {TimedOut: true}, + }) + got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) + if err != nil { + t.Fatal(err) + } + answer := got.(map[string]any) + if answer["started"] != "opening" || answer["program"] != "browser.desktop" { + t.Fatalf("%+v", answer) + } +} + +// DQ-7: each call that is acted on writes one act to the log of acts done by hand, with its caller +// and why; a refusal before the opener ran writes none. +func TestOpenWritesOneActDoneByHand(t *testing.T) { + writeDesktopEntry(t, "browser.desktop", "firefox %u") + x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ + "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, + "systemd-run": {Code: 0}, + }) + var recorded []string + x.handAct = func(what, why string) error { + recorded = append(recorded, what+"|"+why) + return nil + } + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil { + t.Fatal(err) + } + if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") { + t.Fatalf("%v", recorded) + } + + recorded = nil + if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil { + t.Fatal("expected a refusal") + } + if len(recorded) != 0 { + t.Fatalf("a refusal before the opener ran writes no act: %v", recorded) + } +} diff --git a/modules/i3/cmd/i3-tools/tools.go b/modules/i3/cmd/i3-tools/tools.go index 0142b6963..5835985a5 100644 --- a/modules/i3/cmd/i3-tools/tools.go +++ b/modules/i3/cmd/i3-tools/tools.go @@ -19,6 +19,12 @@ type i3 struct { configDir string layouts string watcher *Watcher + // handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29); + // nil in a test that does not check it. + handAct func(what, why string) error + // openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens + // it so a still-running opener is seen without waiting out the real bound. + openBound time.Duration } func (t *i3) ask(kind uint32, payload string, out any) error { diff --git a/modules/i3/module.json b/modules/i3/module.json index 315b77deb..02dafc062 100644 --- a/modules/i3/module.json +++ b/modules/i3/module.json @@ -16,10 +16,14 @@ "serves": [ "reload", "workspaces", - "windows" + "windows", + "open" ] } ], + "invokes": [ + "seat:mesh-hand-acts.hand-act" + ], "tools": [ "i3_focus", "i3_move", @@ -68,6 +72,11 @@ "type": "package", "package": "dex" }, + { + "id": "package-xdg-utils", + "type": "package", + "package": "xdg-utils" + }, { "id": "config-dir", "type": "directory", From 2b0b234db2e1014cb45a0652663af16e06484215 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:16:57 +0100 Subject: [PATCH 2/5] i3: README for open (issue 935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documents the verb, its refusals, the percent-encoding and that each call that is acted on is written to the log of acts done by hand; names the package xdg-utils and that i3 hears nothing of the uplink. Builds: design 08 sign-in-page §31 --- modules/i3/README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/modules/i3/README.md b/modules/i3/README.md index ec5defdd3..bb8b631f7 100644 --- a/modules/i3/README.md +++ b/modules/i3/README.md @@ -5,7 +5,8 @@ The window manager as a module (novox/hq ADR 0208, research 026, to-be 42 phase - **Claims `node-display-session`** and serves its verbs `reload`, `workspaces` and `windows`. - **Requires `x11-display`**, which only `xorg` on the same machine provides. - **Packages:** `i3-wm`, and `dex`, which the configuration has always run for XDG autostart. `dex` - was missing on the desktop, so its autostart entries never started there. + was missing on the desktop, so its autostart entries never started there. `xdg-utils` (ADR 0303 §2), + for `open`'s `xdg-mime` and `xdg-open`. - **Environment** (ADR 0203): `XDG_CURRENT_DESKTOP=i3` and `XDG_SESSION_DESKTOP=i3`. They reach shells, the session (through `xorg`'s block) and the user manager (`environment.d`). The portal keys off the first. @@ -49,6 +50,7 @@ own business. | `node-display-session.reload` | a | checks, then reloads, keeping windows. Refused with the errors when the check fails; `force` reloads anyway | | `node-display-session.workspaces` | r | number, name, output, visible, focused, urgent | | `node-display-session.windows` | r | container id, X id, class, instance, role, title, workspace, output, focused, urgent, floating, fullscreen, scratchpad, marks; narrowed to one workspace | +| `node-display-session.open` | a | opens an http or https address in the session's default browser, for any caller over the bus | | `i3_focus` | d | a window by criteria, or a workspace | | `i3_move` | d | windows to a workspace or output; a workspace to an output | | `i3_layout_save` | d | a workspace's arrangement as a named layout of placeholders (class, instance, role), in `~/.local/state/mesh/i3/layouts/` | @@ -65,6 +67,33 @@ value a caller gives is quoted before it reaches an i3 command. With no i3 runni `{"error": "no-graphical-session", …}`. The bundle's binary is `i3-tools`, so nothing that looks for `i3` by name finds it. +## `open` (novox/hq design 08 sign-in-page §3, §29, §30, §31; issue 935) + +Opens an address in the session's default browser, for any caller over the bus — the sign-in +reaction (`networkmanager`'s watcher) never calls it, so this is for every other caller. It does not +go through i3's IPC `exec`, which hands a shell a command line; instead it asks the account's own +program chooser (`xdg-mime query default x-scheme-handler/`) and starts the program through +the account's service manager (`systemd-run --user --collect --quiet --wait -- xdg-open
`), +the address as one argument, never a shell. The run is bound to 10 s: within it, success answers +`opened` and a failure is refused naming the opener's status; still running at the bound, the page +may still be opening, so the run is left to go on and the answer says `opening`. `program` and +`command` (the desktop entry and the first word of its `Exec` line) are given only once the opener +started. + +**Refused**, naming the reason: a scheme other than `http` or `https` (named), no scheme (a file +path), no host, an address over 2048 bytes once encoded, no graphical session running, no default +program for the scheme, the opener ending with a failure (its status named). + +**The encoding** (RFC 3986): letters, digits, `-` `.` `_` `~` and the separators `:` `/` `?` `#` `[` +`]` `@` `&` `=` `+` `%` are kept as they are; every other character — a space, a quote, `;`, `$(`, +a comma among them — is percent-encoded, as the bytes of its UTF-8 form. Nothing is refused for a +character, and no shell ever reads the address. + +**Every call that is acted on is written to the log of acts done by hand** +(`seat:mesh-hand-acts.hand-act`), with its caller and why; a call refused before the opener ran +writes no act. It hears nothing of the uplink and reads no kept event at its own start: `i3` consumes +no `node-uplink` event (ADR 0689 §3). + ## What it improves over today's configuration Both workstations ran the same configuration. These changes are against it: From c12d0027e85a26e871fe455ad2adb3a8e062fc79 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:17:51 +0100 Subject: [PATCH 3/5] retired-words: add captive portal (the glossary's sign-in page, issue 935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds: design 08 sign-in-page §32 --- retired-words | 1 + 1 file changed, 1 insertion(+) diff --git a/retired-words b/retired-words index c7a00a95a..577b69406 100644 --- a/retired-words +++ b/retired-words @@ -2,6 +2,7 @@ # *Not:* words with no scope or with (tools). A copy, so a catalogue merge needs nothing else; novox/hq's # words.py compares it with the glossary. Regenerate with: python3 00-META/checks/words.py --list tools build machine +captive portal catalogue change plan control plane From a94f9f14aab92e7a8cbb0179bd8fae8d6787cee9 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:53:45 +0100 Subject: [PATCH 4/5] i3: open's own non-killing opener run, the generated answer type, a hand-act on every call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code review round 1 (C-5, C-6, note (b)): - open's opener now runs through its own openerRun, which stops waiting at its bound without sending any signal, instead of internal/desktop's Exec, which kills the command's process group at its deadline; a browser started under the account's service manager is never torn down by open's own 10 s bound (DMC-8). - open imports mesh-contracts' generated nodedisplaysession package at the zero version and answers with its OpenAnswer type and Started constants; main.go names the tool from its Seat and VerbOpen constants. - Every call to open, refused or not, writes one act to the log of acts done by hand (DQ-7 says "each call"), not only one that reaches the opener. Builds: design 08 sign-in-page §3, §29 --- modules/i3/cmd/i3-tools/main.go | 6 +- modules/i3/cmd/i3-tools/open.go | 111 +++++++++++++++++------ modules/i3/cmd/i3-tools/open_test.go | 130 ++++++++++++++++----------- modules/i3/cmd/i3-tools/tools.go | 3 + modules/i3/go.mod | 5 +- 5 files changed, 175 insertions(+), 80 deletions(-) diff --git a/modules/i3/cmd/i3-tools/main.go b/modules/i3/cmd/i3-tools/main.go index 82de29aa6..cb9a4ba33 100644 --- a/modules/i3/cmd/i3-tools/main.go +++ b/modules/i3/cmd/i3-tools/main.go @@ -14,6 +14,7 @@ import ( "path/filepath" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" stdio "git.novox.be/novox/mesh-sdk/go" "i3/internal/desktop" @@ -53,7 +54,8 @@ func machine() *i3 { if state == "" { state = filepath.Join(home, ".local", "state") } - t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), handAct: liveHandAct} + t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), + handAct: liveHandAct, opener: openerRun} t.socket = func() (string, error) { runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid())) i3sock := "" @@ -84,7 +86,7 @@ func tools(t *i3) []stdio.Tool { Run: call(t.reload), }, { - Name: "node-display-session.open", + Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen, Description: "Open an http or https address in the person's default browser, for any caller over the bus " + "(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " + "too long once encoded, no graphical session or no default program for the scheme; the opener's " + diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go index b48939e68..491fb23d6 100644 --- a/modules/i3/cmd/i3-tools/open.go +++ b/modules/i3/cmd/i3-tools/open.go @@ -2,18 +2,24 @@ // address in the person's default browser, outside i3's own IPC (which hands a shell a command // line); this verb takes the address as one argument, through the account's own program chooser // (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act -// (ADR 0565 §10): each call that is acted on is written to the log of acts done by hand. +// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead +// answer note (b), DQ-7: "each call"). package main import ( + "bytes" "context" + "errors" "fmt" "os" + "os/exec" "path/filepath" "regexp" "strings" + "syscall" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" stdio "git.novox.be/novox/mesh-sdk/go" "i3/internal/desktop" @@ -144,36 +150,93 @@ func xdgDataDirs() []string { return dirs } +// openerRun runs the opener (systemd-run --wait -- xdg-open ...): it stops waiting at its bound +// without killing what it started (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5), unlike +// internal/desktop's Exec (run.go), which kills the command's process group at its deadline. A page +// still opening at the bound is left to open: the browser outlives this call either way, since it +// runs under the account's own service manager (systemd-run --user), not as this process's child. +func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + res := desktop.Result{Command: append([]string{name}, args...)} + cmd := exec.Command(name, args...) + cmd.Env = env + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if stdin != nil { + cmd.Stdin = bytes.NewReader(stdin) + } + var out, errb bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errb + if err := cmd.Start(); err != nil { + res.Code = 127 + res.Stderr = err.Error() + return res + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case err := <-done: + res.Stdout, res.Stderr = out.String(), errb.String() + var exit *exec.ExitError + switch { + case err == nil: + case errors.As(err, &exit): + res.Code = exit.ExitCode() + if res.Code < 0 { + res.Code = 128 + } + default: + res.Code = 1 + if res.Stderr == "" { + res.Stderr = err.Error() + } + } + case <-ctx.Done(): + // Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running; + // the goroutine above still reads its exit, harmlessly, once it does. + res.TimedOut = true + } + return res +} + // open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's // default browser for the scheme, and answers once the opener has started. -func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { +func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) { caller := stdio.CallerOf(map[string]any(a)) - address, err := a.Text("address") + why := fmt.Sprintf("asked by %s", caller) + var address, encoded, program, started string + + defer func() { + switch { + case err != nil: + t.journalOpen(address, "refused", err.Error()) + t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why) + default: + t.journalOpen(address, started, program) + t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why) + } + }() + + address, err = a.Text("address") if err != nil { return nil, err } scheme, err := checkAddressShape(address) if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } - encoded := encodeAddress(address) + encoded = encodeAddress(address) if len(encoded) > openMaxAddress { - err := fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) - t.journalOpen(address, "refused", err.Error()) + err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) return nil, err } s, err := t.d.Find() if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } env := s.Env(t.d.Base) - program, err := defaultProgram(ctx, t.d, env, scheme) + program, err = defaultProgram(ctx, t.d, env, scheme) if err != nil { - t.journalOpen(address, "refused", err.Error()) return nil, err } @@ -183,22 +246,23 @@ func (t *i3) open(ctx context.Context, a desktop.Args) (any, error) { } runCtx, cancel := context.WithTimeout(ctx, bound) defer cancel() - res := t.d.Run(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) + runner := t.opener + if runner == nil { + runner = openerRun + } + res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) if !res.OK() && !res.TimedOut { - reason := res.Err().Error() - t.journalOpen(address, "refused", reason) - return nil, fmt.Errorf("the opener failed: %s", reason) + err = fmt.Errorf("the opener failed: %s", res.Err().Error()) + return nil, err } - started := "opened" + started = nodedisplaysession.OpenAnswerStartedOpened if res.TimedOut { - started = "opening" + started = nodedisplaysession.OpenAnswerStartedOpening } command := entryCommand(program) - t.journalOpen(address, started, program) - t.recordHandAct(caller, encoded, program, started) - return map[string]any{"address": encoded, "program": program, "command": command, "started": started}, nil + return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil } // journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14): @@ -207,15 +271,12 @@ func (t *i3) journalOpen(address, outcome, programOrReason string) { fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason) } -// recordHandAct writes open's call to the log of acts done by hand (design 08 sign-in-page §29; -// ADR 0565 §10): open is an act, so every call that is acted on (never a refusal before the -// opener ran) is recorded with its caller and why. -func (t *i3) recordHandAct(caller, address, program, started string) { +// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page +// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why. +func (t *i3) recordHandAct(what, why string) { if t.handAct == nil { return } - what := fmt.Sprintf("%s %s in %s", started, address, program) - why := fmt.Sprintf("asked by %s", caller) if err := t.handAct(what, why); err != nil { fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err) } diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go index f36f139b5..71c60e1d1 100644 --- a/modules/i3/cmd/i3-tools/open_test.go +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" + "i3/internal/desktop" ) @@ -18,25 +20,44 @@ type runCall struct { args []string } -// stubOpener builds an i3 whose session is found (unless find answers an error) and whose -// commands are answered from answers, keyed by the command's name ("xdg-mime", "systemd-run"); -// every call is recorded in calls. -func stubOpener(t *testing.T, find func() (*desktop.Session, error), answers map[string]desktop.Result) (*i3, *[]runCall) { +// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime +// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is +// never reached). Every call, to either, is recorded in calls. +func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) { t.Helper() calls := &[]runCall{} run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { *calls = append(*calls, runCall{name, args}) - res, ok := answers[name] - if !ok { - t.Fatalf("unexpected command %s %v", name, args) + if name != "xdg-mime" { + t.Fatalf("unexpected command on the session's own run: %s %v", name, args) } + return xdgMime + } + var wrapped desktop.Runner + if opener != nil { + wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + *calls = append(*calls, runCall{name, args}) + return opener(ctx, env, stdin, name, args...) + } + } else { + wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + t.Fatalf("the opener never runs: %s %v", name, args) + return desktop.Result{} + } + } + return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls +} + +// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real +// still-running opener would appear to this call). +func resultOpener(res desktop.Result) desktop.Runner { + return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { if res.TimedOut { <-ctx.Done() return desktop.Result{TimedOut: true} } return res } - return &i3{d: desktop.Desk{Find: find, Run: run}, openBound: 50 * time.Millisecond}, calls } func foundSession() (*desktop.Session, error) { @@ -59,7 +80,7 @@ func writeDesktopEntry(t *testing.T, entry, execLine string) { // 935/I-1: every scheme but http and https, and a file path, is refused. func TestOpenRefusesEveryOtherScheme(t *testing.T) { - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{}) + x, calls := stubOpener(t, foundSession, desktop.Result{}, nil) for _, address := range []string{ "/etc/passwd", // no scheme: a file path "file:///etc/passwd", // a scheme other than http or https @@ -73,13 +94,13 @@ func TestOpenRefusesEveryOtherScheme(t *testing.T) { } } if len(*calls) != 0 { - t.Fatalf("a refused address never reaches the opener: %v", *calls) + t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls) } } // 935/I-1: an address over 2048 bytes once encoded is refused. func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{}) + x, _ := stubOpener(t, foundSession, desktop.Result{}, nil) address := "https://example.net/" + strings.Repeat("a", 2048) if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil { t.Fatal("not refused") @@ -90,7 +111,7 @@ func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) { func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { x, _ := stubOpener(t, func() (*desktop.Session, error) { return nil, &desktop.NoSession{Reason: "none"} - }, map[string]desktop.Result{}) + }, desktop.Result{}, nil) _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if !desktop.IsNoSession(err) { t.Fatalf("%v", err) @@ -99,36 +120,26 @@ func TestOpenRefusesWithNoGraphicalSession(t *testing.T) { // 935/I-1: no default program for the scheme is refused. func TestOpenRefusesWithNoDefaultProgram(t *testing.T) { - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: ""}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil) if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil { t.Fatal("not refused") } - for _, c := range *calls { - if c.name == "systemd-run" { - t.Fatal("the opener never runs with no default program") - } - } } // 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its // UTF-8 form, and the address reaches the opener as one argument, never a shell command line. func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, calls := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) address := `https://example.net/a'b;c d$(e),f"g` got, err := run(t, x, "node-display-session.open", map[string]any{"address": address}) if err != nil { t.Fatal(err) } want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g` - answer := got.(map[string]any) - if answer["address"] != want { - t.Fatalf("got %q, want %q", answer["address"], want) + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Address != want { + t.Fatalf("got %q, want %q", answer.Address, want) } var last runCall for _, c := range *calls { @@ -149,10 +160,8 @@ func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) { // 935/I-3: an opener that fails is refused with its status and names no program. func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 1, Stderr: "no such unit"}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, + resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"})) _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err == nil || !strings.Contains(err.Error(), "no such unit") { t.Fatalf("%v", err) @@ -162,16 +171,13 @@ func TestOpenRefusesWhenTheOpenerFails(t *testing.T) { // 935/I-3: an opener that ends well answers opened with the program. func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err != nil { t.Fatal(err) } - answer := got.(map[string]any) - if answer["started"] != "opened" || answer["program"] != "browser.desktop" || answer["command"] != "firefox" { + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" { t.Fatalf("%+v", answer) } } @@ -180,28 +186,48 @@ func TestOpenAnswersOpenedWithTheProgram(t *testing.T) { // names the program only once the opener started). func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {TimedOut: true}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true})) got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}) if err != nil { t.Fatal(err) } - answer := got.(map[string]any) - if answer["started"] != "opening" || answer["program"] != "browser.desktop" { + answer := got.(nodedisplaysession.OpenAnswer) + if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" { t.Fatalf("%+v", answer) } } -// DQ-7: each call that is acted on writes one act to the log of acts done by hand, with its caller -// and why; a refusal before the opener ran writes none. -func TestOpenWritesOneActDoneByHand(t *testing.T) { +// C-5: cmd/i3-tools runs the opener with its own run (openerRun, not internal/desktop's Exec, which +// kills a command's process group at its deadline, run.go:82-86): it stops waiting at its bound +// without killing what it started, so an opener still running past the bound keeps running and +// finishes on its own. +func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) { + marker := filepath.Join(t.TempDir(), "ran") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + start := time.Now() + res := openerRun(ctx, os.Environ(), nil, "sh", "-c", "sleep 0.15; touch "+marker) + if !res.TimedOut { + t.Fatalf("expected TimedOut, got %+v", res) + } + if since := time.Since(start); since > 200*time.Millisecond { + t.Fatalf("openerRun waited past its own bound: %s", since) + } + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if _, err := os.Stat(marker); err == nil { + return // the process kept running after openerRun gave up waiting, and finished: not killed + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("the opener process was killed: it never finished past the bound") +} + +// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its +// caller and why — a successful one and a refused one alike. +func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) { writeDesktopEntry(t, "browser.desktop", "firefox %u") - x, _ := stubOpener(t, foundSession, map[string]desktop.Result{ - "xdg-mime": {Code: 0, Stdout: "browser.desktop\n"}, - "systemd-run": {Code: 0}, - }) + x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0})) var recorded []string x.handAct = func(what, why string) error { recorded = append(recorded, what+"|"+why) @@ -218,7 +244,7 @@ func TestOpenWritesOneActDoneByHand(t *testing.T) { if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil { t.Fatal("expected a refusal") } - if len(recorded) != 0 { - t.Fatalf("a refusal before the opener ran writes no act: %v", recorded) + if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") { + t.Fatalf("a refusal writes an act too (note (b)): %v", recorded) } } diff --git a/modules/i3/cmd/i3-tools/tools.go b/modules/i3/cmd/i3-tools/tools.go index 5835985a5..73c812006 100644 --- a/modules/i3/cmd/i3-tools/tools.go +++ b/modules/i3/cmd/i3-tools/tools.go @@ -25,6 +25,9 @@ type i3 struct { // openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens // it so a still-running opener is seen without waiting out the real bound. openBound time.Duration + // opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5) + // unless a test replaces it to control the opener's outcome directly. + opener desktop.Runner } func (t *i3) ask(kind uint32, payload string, out any) error { diff --git a/modules/i3/go.mod b/modules/i3/go.mod index 645d3fdbe..c5901cd6d 100644 --- a/modules/i3/go.mod +++ b/modules/i3/go.mod @@ -2,7 +2,10 @@ module i3 go 1.26.0 -require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +require ( + git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +) require ( github.com/klauspost/compress v1.20.1 // indirect From 9a3149df88e14b6332e16b499357c280d6fc54e5 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 01:13:18 +0100 Subject: [PATCH 5/5] i3: test the opener's no-kill run with pipes, never a real sleep MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Code review round 2 (C-5 follow-up). openerRun's core is now runWithoutKilling(ctx, *exec.Cmd), callable directly by a test with a command of its own. The test's child blocks reading its stdin (a pipe held open past the bound); after confirming TimedOut, the test closes the pipe to unblock it, then waits on the child's own end (a byte written to an extra file just before it exits, read with a plain blocking read) instead of sleeping and polling for a marker file. A kill at the bound now leaves that read empty, which the test checked by reintroducing the old signal and watching it fail. Builds: design 08 sign-in-page §3, §29 --- modules/i3/cmd/i3-tools/open.go | 22 ++++++++---- modules/i3/cmd/i3-tools/open_test.go | 53 +++++++++++++++++++--------- 2 files changed, 53 insertions(+), 22 deletions(-) diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go index 491fb23d6..8721fff9b 100644 --- a/modules/i3/cmd/i3-tools/open.go +++ b/modules/i3/cmd/i3-tools/open.go @@ -150,19 +150,29 @@ func xdgDataDirs() []string { return dirs } -// openerRun runs the opener (systemd-run --wait -- xdg-open ...): it stops waiting at its bound -// without killing what it started (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5), unlike -// internal/desktop's Exec (run.go), which kills the command's process group at its deadline. A page -// still opening at the bound is left to open: the browser outlives this call either way, since it -// runs under the account's own service manager (systemd-run --user), not as this process's child. +// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: it +// stops waiting at its bound without killing what it started (design 08 sign-in-page §18, §29; +// DMC-8, lead answer C-5), unlike internal/desktop's Exec (run.go), which kills the command's +// process group at its deadline. A page still opening at the bound is left to open: the browser +// outlives this call either way, since it runs under the account's own service manager +// (systemd-run --user), not as this process's child. func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { - res := desktop.Result{Command: append([]string{name}, args...)} cmd := exec.Command(name, args...) cmd.Env = env cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if stdin != nil { cmd.Stdin = bytes.NewReader(stdin) } + return runWithoutKilling(ctx, cmd) +} + +// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without +// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on, +// never torn down by the bound that only governs how long this call waits. A test calls this +// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started +// process is never killed, without a real sleep on either side. +func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result { + res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)} var out, errb bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &errb if err := cmd.Start(); err != nil { diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go index 71c60e1d1..3a16ae8b8 100644 --- a/modules/i3/cmd/i3-tools/open_test.go +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -3,8 +3,10 @@ package main import ( "context" "os" + "os/exec" "path/filepath" "strings" + "syscall" "testing" "time" @@ -197,30 +199,49 @@ func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) { } } -// C-5: cmd/i3-tools runs the opener with its own run (openerRun, not internal/desktop's Exec, which -// kills a command's process group at its deadline, run.go:82-86): it stops waiting at its bound -// without killing what it started, so an opener still running past the bound keeps running and -// finishes on its own. +// C-5: cmd/i3-tools runs the opener with its own run (runWithoutKilling, not internal/desktop's +// Exec, which kills a command's process group at its deadline, run.go:82-86): it stops waiting at +// its bound without killing what it started. The child blocks reading its stdin, a pipe this test +// holds open past the bound and only then closes; once unblocked, the child writes one byte on an +// extra file before it exits, its own end, which this test waits on instead of sleeping — a byte +// the child could reach only by surviving the bound, never by being killed at it. func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) { - marker := filepath.Join(t.TempDir(), "ran") + stdinR, stdinW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer stdinW.Close() + doneR, doneW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer doneR.Close() + + cmd := exec.Command("sh", "-c", "cat >/dev/null; printf x >&3") + cmd.Stdin = stdinR + cmd.ExtraFiles = []*os.File{doneW} + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // as openerRun starts it + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() - start := time.Now() - res := openerRun(ctx, os.Environ(), nil, "sh", "-c", "sleep 0.15; touch "+marker) + res := runWithoutKilling(ctx, cmd) + stdinR.Close() + doneW.Close() // this process's own copy: only the child's, closed when it exits, is left if !res.TimedOut { t.Fatalf("expected TimedOut, got %+v", res) } - if since := time.Since(start); since > 200*time.Millisecond { - t.Fatalf("openerRun waited past its own bound: %s", since) + + // Unblock the child: were it killed at the bound, this would reach nobody. + if err := stdinW.Close(); err != nil { + t.Fatal(err) } - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if _, err := os.Stat(marker); err == nil { - return // the process kept running after openerRun gave up waiting, and finished: not killed - } - time.Sleep(10 * time.Millisecond) + // Wait on the child's own end: blocks until the child writes its byte and exits, closing its + // copy of doneW: never a timer, never a kill. + b := make([]byte, 1) + n, _ := doneR.Read(b) + if n != 1 || b[0] != 'x' { + t.Fatalf("the opener process was killed instead of left to finish: read %d byte(s)", n) } - t.Fatal("the opener process was killed: it never finished past the bound") } // DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its