diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md index efa86fa13..7d9563816 100644 --- a/apps/computer/local-daemon/README.md +++ b/apps/computer/local-daemon/README.md @@ -1093,21 +1093,27 @@ Agent reads the window again first. Windows Operations get `WindowsToolGuide`. Linux controls the signed-in user's X11 desktop. The driver `local_linux.py` is embedded in the Go binary; it reads windows through AT-SPI and sends input with -`xdotool`. The host needs `python3-pyatspi`, `xdotool`, ImageMagick, `xclip` and a -user systemd manager. The Daemon must run as the desktop user and inherit +`xdotool`. The host needs `python3-pyatspi`, `xdotool`, ImageMagick and `xclip`; +a reachable user systemd manager is used when available, with detached session +fallback otherwise. The Daemon must run as the desktop user and inherit `DISPLAY`, `XAUTHORITY`, `DBUS_SESSION_BUS_ADDRESS` and `XDG_SESSION_TYPE`. With a missing dependency or under Wayland, `check_permissions` explains why; browser and file tools still work. -`open_application` and `open_url` start the program through `systemd-run --user` -with `KillMode=process`, so it outlives the tool call. `xdg-open` hands a URL to -`gio`, which exits as soon as it started the browser; the default control-group -mode would kill the browser with it. `open_url` then waits up to 8 seconds for -the active window or its title to change, and fails when neither does. After -any input, a page that is still loading is read again until it loads, for at -most 8 seconds; the result marks `loading` when it has not. A desktop with no -active window, as right after a GNOME login, still launches: any window that -appears counts as opened. +`open_application` and `open_url` launch the program in its own session inside a +transient user scope (`systemd-run --user --scope` under `app.slice`) when +`org.freedesktop.systemd1` is reachable on the user session bus, or directly +detached otherwise, so launched apps outlive the tool call and Snap apps can +create their own tracking scope without `.service` cgroup rejections. The driver +observes startup briefly and surfaces immediate non-zero exits (with stderr from +the user journal stream, or an unlinked temporary file fallback) as confirmed +errors without waiting 8 seconds or blocking the action record. Otherwise +`open_url` waits up to 8 seconds for the active window or its title to change, +failing with any post-exit launch stderr when neither does. After any input, a +page that is still loading is read again until it loads, for at most 8 seconds; +the result marks `loading` when it has not. A desktop with no active window, as +right after a GNOME login, still launches: any window that appears counts as +opened. `type_text` pastes the text. A terminal emulator gets it on both the clipboard and the primary selection and receives `shift+Insert`, which every common diff --git a/apps/computer/local-daemon/internal/linger/localtools/linux.go b/apps/computer/local-daemon/internal/linger/localtools/linux.go index e5a4b25a6..cd3ddb3bc 100644 --- a/apps/computer/local-daemon/internal/linger/localtools/linux.go +++ b/apps/computer/local-daemon/internal/linger/localtools/linux.go @@ -118,9 +118,8 @@ func (op *operation) linuxComputerCall(ctx context.Context, name string, args js report := map[string]any{} if err = op.perform(lease, action); err == nil { output, state = observe(lease, shot, action.opens(), window, report) - if action.command == "open" && report["window_opened"] == false { - delete(report, "window_opened") - err = errURLNotOpened + if action.opens() && report["window_opened"] == false { + err = launchFailure(lease, action, report) } } else if !errors.Is(err, errOutcomeUnknown) { state = readWindowState(lease) @@ -232,10 +231,12 @@ func (op *operation) runActions(ctx context.Context, args json.RawMessage) (json stopped = fmt.Sprintf("waiting after step %d failed (%v); observe before continuing", done, waitErr) break } - if !opened && action.command == "open" { - done-- - err = errURLNotOpened - break + if !opened && action.opens() { + if launchErr := launchFailure(lease, action, nil); launchErr != nil { + done-- + err = launchErr + break + } } current, activeErr := lease.Action("active-window") if activeErr != nil { @@ -277,11 +278,12 @@ func (op *operation) runActions(ctx context.Context, args json.RawMessage) (json } else if done > 0 && !errors.Is(err, errOutcomeUnknown) { launched := err == nil && done == len(actions) && actions[done-1].opens() output, state = observe(lease, shot, launched, mark, report) - if launched && actions[done-1].command == "open" && report["window_opened"] == false { - delete(report, "window_opened") - done-- - report["completed_steps"] = done - err = errURLNotOpened + if launched && report["window_opened"] == false { + if launchErr := launchFailure(lease, actions[done-1], report); launchErr != nil { + done-- + report["completed_steps"] = done + err = launchErr + } } } else if !errors.Is(err, errOutcomeUnknown) { state = readWindowState(lease) @@ -581,6 +583,29 @@ var ( // ran, so the input is known, but no window or title changed. var errURLNotOpened = errors.New("the URL did not open: no window or tab title changed within 8 s; observe before trying again") +// launchFailure inspects any post-launch error recorded by the driver when a +// launch did not produce a window or title change within launchWait. +func launchFailure(lease *localLinuxLease, action desktopAction, report map[string]any) error { + raw, _ := lease.Action("launch-error", action.command) + detail := string(bytes.TrimSpace(raw)) + if action.command == "open" { + if report != nil { + delete(report, "window_opened") + } + if detail != "" { + return fmt.Errorf("%w: %s", errURLNotOpened, detail) + } + return errURLNotOpened + } + if detail != "" { + if report != nil { + delete(report, "window_opened") + } + return errors.New(detail) + } + return nil +} + // opens reports an action that should bring up a window or tab, so its // result waits for one instead of a fixed pause. func (a desktopAction) opens() bool { return a.command == "run" || a.command == "open" } diff --git a/apps/computer/local-daemon/internal/linger/localtools/linux_launch_test.go b/apps/computer/local-daemon/internal/linger/localtools/linux_launch_test.go new file mode 100644 index 000000000..fa80121d2 --- /dev/null +++ b/apps/computer/local-daemon/internal/linger/localtools/linux_launch_test.go @@ -0,0 +1,466 @@ +package localtools + +import ( + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/mcpproxy" + "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider" +) + +// startFakeLinuxDriver launches a tiny Python JSON-RPC MCP server simulating +// local_linux.py receipts so linux.go launch and error-surfacing paths can be +// verified deterministically on any host OS. +func startFakeLinuxDriver(t *testing.T, script string) *mcpClient { + t.Helper() + python, err := exec.LookPath("python3") + if err != nil { + t.Skip("python3 not available") + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + t.Cleanup(cancel) + client, err := startClient(ctx, python, []string{"-u", "-c", script}, t.TempDir(), os.Environ()) + if err != nil { + t.Fatalf("start fake driver: %v", err) + } + t.Cleanup(func() { + if err := client.close(); err != nil { + t.Errorf("close fake driver: %v", err) + } + }) + return client +} + +func newTestLinuxOperation(t *testing.T, client *mcpClient) (*operation, *Manager) { + t.Helper() + prev := linuxHost + linuxHost = func() bool { return true } + t.Cleanup(func() { linuxHost = prev }) + + root := t.TempDir() + manager, err := New(Options{StateDirectory: filepath.Join(root, "state")}) + if err != nil { + t.Fatal(err) + } + if manager.journal == nil { + journal, err := openJournal(filepath.Join(root, "state", "computer-tools", "action.json")) + if err != nil { + t.Fatal(err) + } + manager.journal = journal + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + t.Cleanup(cancel) + op := &operation{ + manager: manager, + ctx: ctx, + label: "linux-launch-test", + spec: provider.OperationSpec{AgentID: "agent-1", WorkingDirectory: root}, + identity: mcpproxy.OperationIdentity{OperationID: "op-1"}, + linux: client, + } + return op, manager +} + +func TestLinuxOpenURLSurfacesImmediateLaunchErrorWithoutWaiting(t *testing.T) { + script := ` +import base64, json, sys +for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + m = req.get("method") + if m == "initialize": + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}}} + elif m == "tools/call": + cmd = req["params"]["arguments"]["command"] + if cmd == "active-window": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"123").decode()} + elif cmd == "window-title": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"Terminal").decode()} + elif cmd == "open": + payload = {"status": "failed", "error": "xdg-open failed (exited with status 4): /user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-1.service is not a snap cgroup for tag snap.firefox.firefox"} + elif cmd == "semantic-ui": + payload = {"window": "Terminal", "app": "gnome-terminal", "elements": [{"ref": {"path": "1"}, "role": "terminal", "name": "bash"}]} + else: + payload = {"status": "confirmed", "output_base64": ""} + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": json.dumps(payload)}]}} + sys.stdout.write(json.dumps(out) + "\n") + sys.stdout.flush() +` + client := startFakeLinuxDriver(t, script) + op, manager := newTestLinuxOperation(t, client) + + started := time.Now() + raw, err := op.linuxComputerCall(op.ctx, "open_url", json.RawMessage(`{"url":"https://example.com"}`)) + elapsed := time.Since(started) + + if err != nil { + t.Fatalf("unexpected transport error: %v", err) + } + if elapsed > 2*time.Second { + t.Fatalf("open_url waited %v instead of failing fast on launch error", elapsed) + } + var res struct { + IsError bool `json:"isError"` + Content []struct { + Text string `json:"text"` + } `json:"content"` + } + if err := json.Unmarshal(raw, &res); err != nil { + t.Fatalf("unmarshal result: %v (%s)", err, raw) + } + if !res.IsError { + t.Fatalf("expected tool error result, got: %s", raw) + } + if len(res.Content) == 0 || !strings.Contains(res.Content[0].Text, "is not a snap cgroup for tag snap.firefox.firefox") || !strings.Contains(res.Content[0].Text, "status 4") { + t.Fatalf("expected snap cgroup launch error, got: %s", raw) + } + if strings.Contains(res.Content[0].Text, errURLNotOpened.Error()) { + t.Fatalf("should not mask launch failure as generic errURLNotOpened: %s", raw) + } + if manager.journal.blocked() { + t.Fatal("confirmed launch failure must not leave the action journal blocked") + } +} + +func TestLinuxOpenApplicationSurfacesImmediateLaunchErrorWithoutWaiting(t *testing.T) { + script := ` +import base64, json, sys +for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + m = req.get("method") + if m == "initialize": + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}}} + elif m == "tools/call": + cmd = req["params"]["arguments"]["command"] + if cmd == "active-window": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"123").decode()} + elif cmd == "run": + payload = {"status": "failed", "error": "firefox failed (exited with status 4): /user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-2.service is not a snap cgroup for tag snap.firefox.firefox"} + elif cmd == "semantic-ui": + payload = {"window": "Terminal", "app": "gnome-terminal", "elements": [{"ref": {"path": "1"}, "role": "terminal", "name": "bash"}]} + else: + payload = {"status": "confirmed", "output_base64": ""} + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": json.dumps(payload)}]}} + sys.stdout.write(json.dumps(out) + "\n") + sys.stdout.flush() +` + client := startFakeLinuxDriver(t, script) + op, manager := newTestLinuxOperation(t, client) + + started := time.Now() + raw, err := op.linuxComputerCall(op.ctx, "open_application", json.RawMessage(`{"application":"firefox"}`)) + elapsed := time.Since(started) + + if err != nil { + t.Fatalf("unexpected transport error: %v", err) + } + if elapsed > 2*time.Second { + t.Fatalf("open_application waited %v instead of failing fast", elapsed) + } + var res struct { + IsError bool `json:"isError"` + Content []struct { + Text string `json:"text"` + } `json:"content"` + } + if err := json.Unmarshal(raw, &res); err != nil { + t.Fatalf("unmarshal result: %v", err) + } + if !res.IsError || len(res.Content) == 0 || !strings.Contains(res.Content[0].Text, "firefox failed (exited with status 4)") { + t.Fatalf("expected immediate firefox launch error, got: %s", raw) + } + if manager.journal.blocked() { + t.Fatal("confirmed launch failure must not leave the action journal blocked") + } +} + +func TestLinuxPostLaunchDiagnosticsEnrichOpenURLAndLateAppCrash(t *testing.T) { + prevLaunchWait, prevWindowPoll, prevTreeWait := launchWait, windowPoll, launchTreeWait + launchWait, windowPoll, launchTreeWait = 40*time.Millisecond, 10*time.Millisecond, 20*time.Millisecond + t.Cleanup(func() { + launchWait, windowPoll, launchTreeWait = prevLaunchWait, prevWindowPoll, prevTreeWait + }) + + script := ` +import base64, json, sys +for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + m = req.get("method") + if m == "initialize": + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}}} + elif m == "tools/call": + cmd = req["params"]["arguments"]["command"] + args = req["params"]["arguments"].get("args", []) + if cmd == "active-window": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"123").decode()} + elif cmd == "window-title": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"Terminal").decode()} + elif cmd == "launch-error": + mode = args[0] if args else "open" + if mode == "open": + msg = b"async grandchild: is not a snap cgroup for tag snap.firefox.firefox" + else: + msg = b"firefox failed (exited with status 1): profile locked" + payload = {"status": "confirmed", "output_base64": base64.b64encode(msg).decode()} + elif cmd == "semantic-ui": + payload = {"window": "Terminal", "app": "gnome-terminal", "elements": [{"ref": {"path": "1"}, "role": "terminal", "name": "bash"}]} + else: + payload = {"status": "confirmed", "output_base64": ""} + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": json.dumps(payload)}]}} + sys.stdout.write(json.dumps(out) + "\n") + sys.stdout.flush() +` + client := startFakeLinuxDriver(t, script) + op, _ := newTestLinuxOperation(t, client) + + rawURL, err := op.linuxComputerCall(op.ctx, "open_url", json.RawMessage(`{"url":"https://example.com"}`)) + if err != nil { + t.Fatalf("open_url transport err: %v", err) + } + if !strings.Contains(string(rawURL), errURLNotOpened.Error()) || !strings.Contains(string(rawURL), "async grandchild: is not a snap cgroup for tag snap.firefox.firefox") { + t.Fatalf("expected enriched errURLNotOpened, got: %s", rawURL) + } + + rawApp, err := op.linuxComputerCall(op.ctx, "open_application", json.RawMessage(`{"application":"firefox"}`)) + if err != nil { + t.Fatalf("open_application transport err: %v", err) + } + if !strings.Contains(string(rawApp), `"isError":true`) || !strings.Contains(string(rawApp), "profile locked") { + t.Fatalf("expected late crash error for open_application, got: %s", rawApp) + } +} + +func TestLinuxOpenApplicationSlowRunningAppPreservesWindowOpenedFalse(t *testing.T) { + prevLaunchWait, prevWindowPoll, prevTreeWait := launchWait, windowPoll, launchTreeWait + launchWait, windowPoll, launchTreeWait = 30*time.Millisecond, 10*time.Millisecond, 20*time.Millisecond + t.Cleanup(func() { + launchWait, windowPoll, launchTreeWait = prevLaunchWait, prevWindowPoll, prevTreeWait + }) + + script := ` +import base64, json, sys +for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + m = req.get("method") + if m == "initialize": + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}}} + elif m == "tools/call": + cmd = req["params"]["arguments"]["command"] + if cmd == "active-window": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"123").decode()} + elif cmd == "semantic-ui": + payload = {"window": "Terminal", "app": "gnome-terminal", "elements": [{"ref": {"path": "1"}, "role": "terminal", "name": "bash"}]} + else: + payload = {"status": "confirmed", "output_base64": ""} + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": json.dumps(payload)}]}} + sys.stdout.write(json.dumps(out) + "\n") + sys.stdout.flush() +` + client := startFakeLinuxDriver(t, script) + op, _ := newTestLinuxOperation(t, client) + + rawApp, err := op.linuxComputerCall(op.ctx, "open_application", json.RawMessage(`{"application":"gedit"}`)) + if err != nil { + t.Fatalf("open_application transport err: %v", err) + } + if strings.Contains(string(rawApp), `"isError":true`) || !strings.Contains(string(rawApp), `"window_opened\":false`) { + t.Fatalf("expected non-error result with window_opened:false, got: %s", rawApp) + } +} + +func TestLinuxRunActionsStopsImmediatelyOnLaunchFailure(t *testing.T) { + script := ` +import base64, json, sys +calls = [] +for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + m = req.get("method") + if m == "initialize": + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {}}}} + elif m == "tools/call": + cmd = req["params"]["arguments"]["command"] + calls.append(cmd) + if cmd == "active-window": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"123").decode()} + elif cmd == "window-title": + payload = {"status": "confirmed", "output_base64": base64.b64encode(b"Terminal").decode()} + elif cmd == "open": + payload = {"status": "failed", "error": "xdg-open failed (exited with status 4): snap cgroup denied"} + elif cmd == "type": + payload = {"status": "failed", "error": "BUG: second step should never execute"} + elif cmd == "semantic-ui": + payload = {"window": "Terminal", "app": "gnome-terminal", "elements": [{"ref": {"path": "1"}, "role": "terminal", "name": "bash"}]} + else: + payload = {"status": "confirmed", "output_base64": ""} + out = {"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": json.dumps(payload)}]}} + sys.stdout.write(json.dumps(out) + "\n") + sys.stdout.flush() +` + client := startFakeLinuxDriver(t, script) + op, manager := newTestLinuxOperation(t, client) + + started := time.Now() + raw, err := op.runActions(op.ctx, json.RawMessage(`{"actions":[{"tool":"open_url","url":"https://example.com"},{"tool":"type_text","text":"should-not-run"}]}`)) + elapsed := time.Since(started) + + if err != nil { + t.Fatalf("unexpected transport error: %v", err) + } + if elapsed > 2*time.Second { + t.Fatalf("run_actions waited %v instead of failing fast", elapsed) + } + if !strings.Contains(string(raw), `"isError":true`) || !strings.Contains(string(raw), "snap cgroup denied") { + t.Fatalf("expected snap cgroup error from run_actions, got: %s", raw) + } + if strings.Contains(string(raw), "BUG:") { + t.Fatalf("subsequent batch step ran after launch failure: %s", raw) + } + if manager.journal.blocked() { + t.Fatal("confirmed launch failure must not block action journal") + } +} + +func TestLinuxActionEmbeddedDriverLaunchErrorIsConfirmedFailure(t *testing.T) { + python, err := exec.LookPath("python3") + if err != nil { + t.Skip("python3 not available") + } + binDir := t.TempDir() + xdgOpen := filepath.Join(binDir, "xdg-open") + script := "#!/bin/sh\necho '/user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-x.service is not a snap cgroup for tag snap.firefox.firefox' >&2\nexit 4\n" + if err := os.WriteFile(xdgOpen, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + env := append(os.Environ(), "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + client, err := startClient(ctx, python, []string{"-u", "-c", nativeLinuxProgram}, t.TempDir(), env) + if err != nil { + t.Fatalf("start embedded local_linux.py: %v", err) + } + defer func() { + if err := client.close(); err != nil { + t.Errorf("close embedded driver: %v", err) + } + }() + + _, err = linuxAction(ctx, client, "open", "https://example.com") + if err == nil { + t.Fatal("expected launch error from embedded local_linux.py") + } + if errors.Is(err, errOutcomeUnknown) { + t.Fatalf("confirmed launch error must not be classified as errOutcomeUnknown: %v", err) + } + if !strings.Contains(err.Error(), "exited with status 4") || !strings.Contains(err.Error(), "is not a snap cgroup for tag snap.firefox.firefox") { + t.Fatalf("unexpected launch error: %v", err) + } +} + +func TestLinuxEmbeddedDriverFiltersLdPreloadNoiseAndIgnoresStillRunningStderr(t *testing.T) { + python, err := exec.LookPath("python3") + if err != nil { + t.Skip("python3 not available") + } + ldNoise := "ERROR: ld.so: object '/usr/local/lib/syslog.so' from /etc/ld.so.preload cannot be preloaded (cannot open shared object file): ignored." + + t.Run("nonzero_exit_strips_ld_preload_keeps_snap_error", func(t *testing.T) { + binDir := t.TempDir() + xdgOpen := filepath.Join(binDir, "xdg-open") + script := "#!/bin/sh\necho \"" + ldNoise + "\" >&2\necho '/user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-x.service is not a snap cgroup for tag snap.firefox.firefox' >&2\necho \"" + ldNoise + "\" >&2\nexit 4\n" + if err := os.WriteFile(xdgOpen, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + env := append(os.Environ(), "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + client, err := startClient(ctx, python, []string{"-u", "-c", nativeLinuxProgram}, t.TempDir(), env) + if err != nil { + t.Fatalf("start embedded driver: %v", err) + } + defer func() { _ = client.close() }() + + _, err = linuxAction(ctx, client, "open", "https://example.com") + if err == nil { + t.Fatal("expected launch error") + } + if strings.Contains(err.Error(), "cannot be preloaded") { + t.Fatalf("ld.so.preload noise leaked into error: %v", err) + } + if !strings.Contains(err.Error(), "is not a snap cgroup for tag snap.firefox.firefox") { + t.Fatalf("expected snap cgroup error, got: %v", err) + } + }) + + t.Run("exited_zero_with_only_ld_preload_noise_has_empty_launch_error", func(t *testing.T) { + binDir := t.TempDir() + xdgOpen := filepath.Join(binDir, "xdg-open") + script := "#!/bin/sh\necho \"" + ldNoise + "\" >&2\nexit 0\n" + if err := os.WriteFile(xdgOpen, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + env := append(os.Environ(), "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + client, err := startClient(ctx, python, []string{"-u", "-c", nativeLinuxProgram}, t.TempDir(), env) + if err != nil { + t.Fatalf("start embedded driver: %v", err) + } + defer func() { _ = client.close() }() + + if _, err := linuxAction(ctx, client, "open", "https://example.com"); err != nil { + t.Fatalf("unexpected open error: %v", err) + } + detail, err := linuxAction(ctx, client, "launch-error", "open") + if err != nil { + t.Fatalf("launch-error failed: %v", err) + } + if strings.TrimSpace(string(detail)) != "" { + t.Fatalf("expected empty launch-error for ld.so.preload-only exit 0, got: %q", string(detail)) + } + }) + + t.Run("still_running_process_stderr_does_not_pollute_timeout", func(t *testing.T) { + binDir := t.TempDir() + xdgOpen := filepath.Join(binDir, "xdg-open") + script := "#!/bin/sh\necho \"" + ldNoise + "\" >&2\necho 'Gtk-WARNING: harmless startup log' >&2\nsleep 5\n" + if err := os.WriteFile(xdgOpen, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + env := append(os.Environ(), "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + client, err := startClient(ctx, python, []string{"-u", "-c", nativeLinuxProgram}, t.TempDir(), env) + if err != nil { + t.Fatalf("start embedded driver: %v", err) + } + defer func() { _ = client.close() }() + + if _, err := linuxAction(ctx, client, "open", "https://example.com"); err != nil { + t.Fatalf("unexpected open error: %v", err) + } + detail, err := linuxAction(ctx, client, "launch-error", "open") + if err != nil { + t.Fatalf("launch-error failed: %v", err) + } + if strings.TrimSpace(string(detail)) != "" { + t.Fatalf("expected empty launch-error while process is still running, got: %q", string(detail)) + } + }) +} diff --git a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go b/apps/computer/local-daemon/internal/linger/localtools/linux_native.go index ba706e8d2..e30d9895f 100644 --- a/apps/computer/local-daemon/internal/linger/localtools/linux_native.go +++ b/apps/computer/local-daemon/internal/linger/localtools/linux_native.go @@ -53,7 +53,7 @@ func (op *operation) ensureLinux(ctx context.Context) (*mcpClient, error) { func linuxAction(ctx context.Context, client *mcpClient, command string, args ...string) ([]byte, error) { raw, err := client.request(ctx, "tools/call", map[string]any{"name": "action", "arguments": map[string]any{"command": command, "args": args}}) - readOnly := command == "probe" || command == "screenshot" || command == "active-window" || command == "window-title" || command == "accessibility" + readOnly := command == "probe" || command == "screenshot" || command == "active-window" || command == "window-title" || command == "accessibility" || command == "launch-error" if command == "semantic-ui" && len(args) == 1 { var request struct { Kind string `json:"kind"` diff --git a/apps/computer/local-daemon/internal/linger/localtools/local_linux.py b/apps/computer/local-daemon/internal/linger/localtools/local_linux.py index 6e0f4bb79..3d9cf21bf 100644 --- a/apps/computer/local-daemon/internal/linger/localtools/local_linux.py +++ b/apps/computer/local-daemon/internal/linger/localtools/local_linux.py @@ -11,10 +11,14 @@ import ctypes import json import os +import re import shutil import signal +import socket +import stat import subprocess import sys +import tempfile import threading import time import uuid @@ -22,11 +26,7 @@ # Answers go to a private copy of stdout; fd 1 becomes stderr, so a child # such as xdotool never writes a line the daemon would take as an answer. -if __name__ == "__main__": - protocol = os.fdopen(os.dup(1), "w", buffering=1) - os.dup2(2, 1) -else: - protocol = sys.stdout +protocol = sys.stdout outcome = "unsupported" @@ -592,6 +592,7 @@ def release_input(): def exit_driver(): try: release_input() + _close_last_launch() finally: os._exit(0) @@ -619,15 +620,11 @@ def desktop_click(x, y): def stop_driver(*_): try: release_input() + _close_last_launch() finally: raise SystemExit(0) -if __name__ == "__main__": - signal.signal(signal.SIGTERM, stop_driver) - signal.signal(signal.SIGINT, stop_driver) - - # Window classes of terminal emulators, matched case-insensitively: xterm, # GNOME Terminal, Ptyxis, Konsole, kitty, Alacritty, Tilix, Terminator, # WezTerm, foot and rxvt. @@ -683,12 +680,340 @@ def paste_text(value): } -def launch(args): - desktop_env = ["--setenv=" + key + "=" + os.environ[key] for key in ("DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE") if key in os.environ] - # KillMode=process: xdg-open hands the URL to gio, which starts the browser - # and exits at once; the default control-group mode would then kill the - # browser before it opened the page. - command(["systemd-run", "--user", "--quiet", "--collect", "--service-type=exec", "--property=KillMode=process", "--unit=linger-app-" + uuid.uuid4().hex, *desktop_env, "--", *args]) +LAUNCH_SETTLE_SECONDS = 0.8 +LAUNCH_POLL_INTERVAL = 0.02 +LAUNCH_STDERR_RAW_LIMIT = 65536 +LAUNCH_ERROR_TEXT_LIMIT = 500 +JOURNAL_STDOUT_SOCKET = "/run/systemd/journal/stdout" +JOURNAL_PROBE_RETRIES = 6 +JOURNAL_READ_RETRIES = 6 +JOURNAL_RETRY_INTERVAL = 0.03 + +# Benign dynamic-loader preload noise emitted by every subprocess when +# /etc/ld.so.preload references a missing library. Filtered before deciding +# whether meaningful stderr exists and before truncating error text. +_LD_PRELOAD_NOISE_RE = re.compile(r"^ERROR:\s+ld\.so:\s+object\s+.+\s+cannot be preloaded\b") + + +class LaunchError(RuntimeError): + """A desktop launch failed with a confirmed exit status or exec error.""" + + +last_launch = None +_journal_sink_ready = None + + +def _close_last_launch(): + global last_launch + if last_launch is not None: + err_file = last_launch.get("stderr_file") + if err_file is not None: + try: + err_file.close() + except OSError: + pass + last_launch = None + + +def _compact_stderr(text): + lines = [s for line in text.splitlines() if (s := line.strip()) and not _LD_PRELOAD_NOISE_RE.match(s)] + summary = "; ".join(lines) + if len(summary) > LAUNCH_ERROR_TEXT_LIMIT: + summary = "…" + summary[-(LAUNCH_ERROR_TEXT_LIMIT - 1):] + return summary + + +def _read_file_stderr(err_file, limit=LAUNCH_STDERR_RAW_LIMIT): + if err_file is None: + return "" + try: + size = os.fstat(err_file.fileno()).st_size + if size <= 0: + return "" + err_file.seek(max(0, size - limit)) + raw = err_file.read(limit) + except OSError: + return "" + return _compact_stderr(raw.decode("utf-8", errors="replace")) + + +def _open_journal_stream(tag): + """Open a systemd-journald stdout stream socket matching sd_journal_stream_fd().""" + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.connect(JOURNAL_STDOUT_SOCKET) + sock.shutdown(socket.SHUT_RD) + # Standard 7-line header: identifier, unit_id, priority (3=LOG_ERR), + # level_prefix (0), forward_to_syslog/kmsg/console (0). + sock.sendall(f"{tag}\n\n3\n0\n0\n0\n0\n".encode("ascii")) + return sock + except OSError: + sock.close() + raise + + +def _query_journal_raw(tag, env=None, lines=200): + try: + result = subprocess.run( + ["journalctl", "--user", "-q", "--no-pager", "-o", "cat", "-t", tag, "-n", str(lines)], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + env=env, + timeout=2, + ) + except (OSError, subprocess.SubprocessError): + return "" + return result.stdout.decode("utf-8", errors="replace") if result.returncode == 0 and result.stdout else "" + + +def _read_journal_stderr(tag, env=None, retries=JOURNAL_READ_RETRIES): + if not tag: + return "" + saw_noise_only = False + for attempt in range(max(1, retries)): + raw = _query_journal_raw(tag, env=env) + if raw.strip(): + compacted = _compact_stderr(raw) + if compacted: + return compacted + # Allow one brief tick for a trailing error line after preload noise. + if saw_noise_only or attempt + 1 >= retries: + return "" + saw_noise_only = True + if attempt + 1 < retries: + time.sleep(JOURNAL_RETRY_INTERVAL) + return "" + + +def _journal_sink_available(env=None): + """Verify once per driver session that journald stream entries are readable.""" + global _journal_sink_ready + if _journal_sink_ready is not None: + return _journal_sink_ready + path = env.get("PATH") if env else None + if not shutil.which("journalctl", path=path) or not os.path.exists(JOURNAL_STDOUT_SOCKET): + _journal_sink_ready = False + return False + probe_tag = "linger-probe-" + uuid.uuid4().hex[:16] + try: + with _open_journal_stream(probe_tag) as sock: + sock.sendall(b"ok\n") + except OSError: + _journal_sink_ready = False + return False + for attempt in range(max(1, JOURNAL_PROBE_RETRIES)): + if "ok" in _query_journal_raw(probe_tag, env=env, lines=5).splitlines(): + _journal_sink_ready = True + return True + if attempt + 1 < JOURNAL_PROBE_RETRIES: + time.sleep(JOURNAL_RETRY_INTERVAL) + _journal_sink_ready = False + return False + + +def _format_exit_error(label, returncode, stderr_text): + status = f"killed by signal {-returncode}" if returncode < 0 else f"exited with status {returncode}" + return f"{label} failed ({status}): {stderr_text}" if stderr_text else f"{label} failed ({status})" + + +def _systemd_user_bus_has_owner(): + if "Gio" not in globals() or "GLib" not in globals(): + return False + try: + bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) + owned = bus.call_sync( + "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "NameHasOwner", + GLib.Variant("(s)", ("org.freedesktop.systemd1",)), + GLib.VariantType.new("(b)"), + Gio.DBusCallFlags.NO_AUTO_START, + 300, + None, + ) + return bool(owned.unpack()[0]) + except Exception: + return False + + +def _systemd_user_reachable(env): + """Report whether systemd-run --user can reach an active user manager. + + Checks both the user manager's private socket and D-Bus NameHasOwner for + org.freedesktop.systemd1 (without triggering activation) so containers and + sessions with a broken user bus fall back to detached launch cleanly. + """ + if not shutil.which("systemd-run", path=env.get("PATH")): + return False + runtime_dir = env.get("XDG_RUNTIME_DIR") + if not runtime_dir: + return False + private_sock = os.path.join(runtime_dir, "systemd", "private") + try: + if not stat.S_ISSOCK(os.stat(private_sock).st_mode): + return False + except OSError: + return False + return _systemd_user_bus_has_owner() + + +def launch_env(): + """Environment for launched desktop applications. + + Preserves the session environment and fills standard XDG_RUNTIME_DIR and + DBUS_SESSION_BUS_ADDRESS defaults when the user bus socket exists, so + desktop launchers and snapd tracking scopes can reach systemd --user. + """ + env = os.environ.copy() + runtime_dir = env.get("XDG_RUNTIME_DIR") + if not runtime_dir: + candidate = f"/run/user/{os.getuid()}" + try: + info = os.stat(candidate) + if stat.S_ISDIR(info.st_mode) and info.st_uid == os.getuid(): + runtime_dir = candidate + env["XDG_RUNTIME_DIR"] = runtime_dir + except OSError: + pass + if not env.get("DBUS_SESSION_BUS_ADDRESS") and runtime_dir: + bus_path = os.path.join(runtime_dir, "bus") + try: + if stat.S_ISSOCK(os.stat(bus_path).st_mode): + env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=" + bus_path + except OSError: + pass + return env + + +def _systemd_scope_command(args): + # Launch inside a transient user .scope under app.slice rather than a + # transient .service: + # - Matches the systemd XDG desktop app layout (app--.scope), + # preserving the caller's environment and allowing Snap apps (such as + # Ubuntu's snap Firefox) to create their snap..-.scope + # tracking cgroup instead of failing inside a non-snap .service unit. + # - Scopes keep all descendants alive after short-lived launchers like + # xdg-open/gio exit, without needing KillMode=process, and survive the + # driver process group or daemon stopping. + return [ + "systemd-run", "--user", "--scope", "--quiet", "--collect", + "--slice=app.slice", + "--unit=app-linger-" + uuid.uuid4().hex + ".scope", + "--", *args, + ] + + +def _open_stderr_sink(env): + """Return (stderr_fd_obj, close_after_spawn, journal_tag, err_file). + + Prefers a native systemd-journald stream socket when journalctl --user + readback is verified: zero /tmp disk growth over long-lived GUI app + lifetimes, zero SIGPIPE, zero SIG_IGN inheritance, and zero relay processes. + Falls back to an unlinked TemporaryFile on non-systemd/container hosts or + when user journal readback is unavailable. + """ + if _journal_sink_available(env=env): + tag = "linger-launch-" + uuid.uuid4().hex[:16] + try: + return _open_journal_stream(tag), True, tag, None + except OSError: + pass + err_file = tempfile.TemporaryFile() + return err_file, False, None, err_file + + +def _spawn_and_settle(argv, env, label, settle_seconds=None): + if settle_seconds is None: + settle_seconds = LAUNCH_SETTLE_SECONDS + stderr_target, close_after_spawn, journal_tag, err_file = _open_stderr_sink(env) + try: + proc = subprocess.Popen( + argv, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=stderr_target, + env=env, + start_new_session=True, + close_fds=True, + ) + except OSError as error: + stderr_target.close() + raise LaunchError(f"{label} failed to start: {error}") from error + if close_after_spawn: + # The child owns its dup'd fd 2 connected to journald; close the parent + # socket immediately so the driver retains no fd to the stream. + stderr_target.close() + + deadline = time.monotonic() + max(0.0, settle_seconds) + rc = proc.poll() + while rc is None and time.monotonic() < deadline: + remaining = deadline - time.monotonic() + if remaining <= 0: + break + time.sleep(min(LAUNCH_POLL_INTERVAL, remaining)) + rc = proc.poll() + if rc is not None and rc != 0: + if journal_tag is not None: + stderr_text = _read_journal_stderr(journal_tag, env=env) + else: + stderr_text = _read_file_stderr(err_file) + err_file.close() + return proc, rc, stderr_text, None, None + + if rc is None: + # Reap a long-lived child if it exits later while the driver is still + # running, avoiding zombie entries without blocking launch(). + threading.Thread(target=proc.wait, daemon=True).start() + return proc, rc, "", err_file, journal_tag + + +def launch(args, settle_seconds=None): + global last_launch + _close_last_launch() + env = launch_env() + label = os.path.basename(args[0]) if args else "launch" + argv = _systemd_scope_command(args) if _systemd_user_reachable(env) else args + proc, rc, stderr_text, err_file, journal_tag = _spawn_and_settle( + argv, env, label, settle_seconds=settle_seconds + ) + if rc is not None and rc != 0: + raise LaunchError(_format_exit_error(label, rc, stderr_text)) + + last_launch = { + "label": label, + "proc": proc, + "stderr_file": err_file, + "journal_tag": journal_tag, + "env": env, + } + + +def launch_error(mode="open"): + """Diagnostic failure detail for the most recent launch(), if any. + + Only inspects stderr once the launched process has actually exited. A still- + running process (for example cold-start Firefox taking >8s) must not pollute + a timeout with harmless startup stderr or ld.so.preload warnings. + """ + if last_launch is None: + return "" + proc = last_launch["proc"] + rc = proc.poll() + if rc is None: + return "" + label = last_launch["label"] + journal_tag = last_launch.get("journal_tag") + if journal_tag is not None: + stderr_text = _read_journal_stderr(journal_tag, env=last_launch.get("env"), retries=2) + else: + stderr_text = _read_file_stderr(last_launch.get("stderr_file")) + if rc != 0: + return _format_exit_error(label, rc, stderr_text) + if mode == "open" and stderr_text: + return stderr_text + return "" def native_action(name, args): @@ -698,13 +1023,16 @@ def native_action(name, args): raise ValueError("Local Linux desktop requires the signed-in user's X11 session; Wayland is not supported") if not os.environ.get("DISPLAY"): raise ValueError("Local Linux desktop requires DISPLAY; start the Computer from the signed-in user's X11 session") - for executable in ["xdotool", "import", "xclip", "systemd-run"]: + for executable in ["xdotool", "import", "xclip"]: if not shutil.which(executable): raise ValueError("Local Linux desktop dependency is missing: " + executable) if missing: raise ValueError("Local Linux AT-SPI is unavailable: " + missing) command(["xdotool", "getdisplaygeometry"]) return b"ready" + if name == "launch-error": + mode = args[0] if args else "open" + return launch_error(mode).encode("utf-8") if name == "screenshot": return command(["import", "-window", "root", "png:-"]) if name == "accessibility": @@ -739,6 +1067,7 @@ def native_action(name, args): if uri.netloc or os.path.commonpath([path, os.path.expanduser("~")]) != os.path.expanduser("~"): raise ValueError("local URL must be inside the user's home") elif not uri.netloc: raise ValueError("web URL must have a host") + if not shutil.which("xdg-open"): raise ValueError("URL launcher is not installed: xdg-open") begin_input(); launch(["xdg-open", args[0]]) elif name == "type": if len(args) != 1: raise ValueError("type requires text") @@ -792,7 +1121,8 @@ def native_action(name, args): return b"" -if __name__ == "__main__": +def run_server(): + global rpc_id, outcome for line in sys.stdin: request = json.loads(line) if "id" not in request: continue @@ -809,7 +1139,20 @@ def native_action(name, args): values = request["params"]["arguments"] result = native_action(values["command"], values.get("args", [])) if result is not None: reply({"status":"confirmed","output_base64":base64.b64encode(result).decode()}) + except LaunchError as error: + # A confirmed non-zero exit or exec failure during launch means + # the failure is known (not an unknown input outcome), so the + # action journal stays unblocked and the real error surfaces. + reply({"status":"failed","error":str(error)}) except Exception as error: reply({"status":outcome,"error":str(error)}) else: send_rpc({"jsonrpc":"2.0","id":rpc_id,"error":{"code":-32601,"message":"method not found"}}) + + +if __name__ == "__main__": + protocol = os.fdopen(os.dup(1), "w", buffering=1) + os.dup2(2, 1) + signal.signal(signal.SIGTERM, stop_driver) + signal.signal(signal.SIGINT, stop_driver) + run_server() diff --git a/apps/computer/local-daemon/internal/linger/localtools/local_linux_test.py b/apps/computer/local-daemon/internal/linger/localtools/local_linux_test.py new file mode 100644 index 000000000..ad2e23020 --- /dev/null +++ b/apps/computer/local-daemon/internal/linger/localtools/local_linux_test.py @@ -0,0 +1,566 @@ +import importlib.util +import json +import os +import shlex +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +PYTHON_BIN = os.path.realpath(sys.executable) +LD_PRELOAD_NOISE = "ERROR: ld.so: object '/usr/local/lib/syslog.so' from /etc/ld.so.preload cannot be preloaded (cannot open shared object file): ignored." + + +class FakeJournaldServer: + """In-process AF_UNIX stream server speaking systemd's journald stdout protocol.""" + + def __init__(self, sock_path, store_path): + self.sock_path = Path(sock_path) + self.store_path = Path(store_path) + self.headers = {} + self._lock = threading.Lock() + self._stop = threading.Event() + self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._sock.bind(str(self.sock_path)) + self._sock.listen(16) + self._sock.settimeout(0.05) + self._thread = threading.Thread(target=self._accept_loop, daemon=True) + self._thread.start() + + def _accept_loop(self): + while not self._stop.is_set(): + try: + conn, _ = self._sock.accept() + except socket.timeout: + continue + except OSError: + break + threading.Thread(target=self._handle_conn, args=(conn,), daemon=True).start() + + def _handle_conn(self, conn): + try: + reader = conn.makefile("rb") + header = [reader.readline().decode("utf-8", errors="replace").rstrip("\n") for _ in range(7)] + tag = header[0] + with self._lock: + self.headers[tag] = header + for raw in reader: + line = raw.decode("utf-8", errors="replace").rstrip("\n") + with self._lock: + with self.store_path.open("a", encoding="utf-8") as f: + f.write(json.dumps({"tag": tag, "line": line}) + "\n") + except OSError: + pass + finally: + try: + conn.close() + except OSError: + pass + + def close(self): + self._stop.set() + try: + self._sock.close() + except OSError: + pass + self._thread.join(timeout=1.0) + + +def load_local_linux(): + path = Path(__file__).with_name("local_linux.py") + spec = importlib.util.spec_from_file_location("local_linux", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def make_executable(path, content): + path.write_text(content, encoding="utf-8") + path.chmod(0o755) + return path + + +class LocalLinuxLaunchTests(unittest.TestCase): + def setUp(self): + self.mod = load_local_linux() + self.tmpdir = tempfile.TemporaryDirectory() + self.root = Path(self.tmpdir.name) + self.spawned_pids = [] + + def tearDown(self): + self.mod._close_last_launch() + for pid in self.spawned_pids: + try: + os.killpg(pid, signal.SIGKILL) + except OSError: + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + self.tmpdir.cleanup() + + def test_systemd_scope_command_uses_transient_scope_in_app_slice(self): + cmd = self.mod._systemd_scope_command(["xdg-open", "https://example.com"]) + self.assertEqual(cmd[:6], ["systemd-run", "--user", "--scope", "--quiet", "--collect", "--slice=app.slice"]) + self.assertRegex(cmd[6], r"^--unit=app-linger-[0-9a-f]{32}\.scope$") + self.assertEqual(cmd[7:], ["--", "xdg-open", "https://example.com"]) + self.assertNotIn("--service-type=exec", cmd) + self.assertFalse(any(part.endswith(".service") for part in cmd)) + + def test_launch_env_populates_dbus_address_from_runtime_bus_socket(self): + with tempfile.TemporaryDirectory(dir="/tmp") as short_dir: + sock_path = Path(short_dir) / "bus" + srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + srv.bind(str(sock_path)) + with mock.patch.dict(os.environ, {"XDG_RUNTIME_DIR": short_dir}, clear=True): + env = self.mod.launch_env() + self.assertEqual(env["XDG_RUNTIME_DIR"], short_dir) + self.assertEqual(env["DBUS_SESSION_BUS_ADDRESS"], "unix:path=" + str(sock_path)) + finally: + srv.close() + + def test_launch_via_systemd_scope_fast_exit_zero_and_env(self): + recorded = self.root / "argv.txt" + make_executable( + self.root / "systemd-run", + f"""#!/bin/sh +{{ + printf 'DISPLAY=%s\\n' "$DISPLAY" + printf 'DBUS=%s\\n' "$DBUS_SESSION_BUS_ADDRESS" + for arg in "$@"; do + printf 'ARG=%s\\n' "$arg" + done +}} > {shlex.quote(str(recorded))} +while [ "$#" -gt 0 ]; do + if [ "$1" = "--" ]; then + shift + break + fi + shift +done +exec "$@" +""", + ) + fake_xdg = make_executable( + self.root / "xdg-open", + "#!/bin/sh\nexit 0\n", + ) + env = { + "PATH": str(self.root) + os.pathsep + os.environ.get("PATH", ""), + "DISPLAY": ":99", + "DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1010/bus", + } + started = time.monotonic() + with mock.patch.dict(os.environ, env, clear=False), \ + mock.patch.object(self.mod, "_systemd_user_reachable", return_value=True): + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=3.0) + elapsed = time.monotonic() - started + self.assertLess(elapsed, 2.0, "fast exit-0 launcher should not wait the full settle window") + lines = recorded.read_text(encoding="utf-8").splitlines() + self.assertEqual(lines[0], "DISPLAY=:99") + self.assertEqual(lines[1], "DBUS=unix:path=/run/user/1010/bus") + argv = [line[4:] for line in lines[2:] if line.startswith("ARG=")] + self.assertEqual(argv[:5], ["--user", "--scope", "--quiet", "--collect", "--slice=app.slice"]) + self.assertRegex(argv[5], r"^--unit=app-linger-[0-9a-f]{32}\.scope$") + self.assertEqual(argv[6:], ["--", str(fake_xdg), "https://example.com"]) + self.assertEqual(self.mod.launch_error("open"), "") + + def test_launch_immediate_nonzero_snap_cgroup_error_fails_fast(self): + make_executable( + self.root / "systemd-run", + """#!/bin/sh +while [ "$#" -gt 0 ]; do + if [ "$1" = "--" ]; then + shift + break + fi + shift +done +exec "$@" +""", + ) + snap_err = "/user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-f67530ce.service is not a snap cgroup for tag snap.firefox.firefox" + fake_xdg = make_executable( + self.root / "xdg-open", + f"#!/bin/sh\nsleep 0.05\nprintf '%s\\n' {shlex.quote(snap_err)} >&2\nexit 4\n", + ) + env = {"PATH": str(self.root) + os.pathsep + os.environ.get("PATH", "")} + started = time.monotonic() + with mock.patch.dict(os.environ, env, clear=False), \ + mock.patch.object(self.mod, "_systemd_user_reachable", return_value=True): + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=3.0) + elapsed = time.monotonic() - started + self.assertLess(elapsed, 2.0, "immediate non-zero exit must fail fast before settle deadline") + self.assertIn("exited with status 4", str(ctx.exception)) + self.assertIn("is not a snap cgroup for tag snap.firefox.firefox", str(ctx.exception)) + + def test_launch_long_lived_app_detaches_without_sigpipe_or_blocking(self): + pid_file = self.root / "app.pid" + alive_file = self.root / "app.alive" + fake_app = make_executable( + self.root / "fake-gedit", + f"""#!{PYTHON_BIN} +import os, signal, sys, time +# Explicitly restore SIG_DFL for SIGPIPE (matching C/GTK apps) to prove +# writing warnings to stderr after parent closes its handle never kills the app. +signal.signal(signal.SIGPIPE, signal.SIG_DFL) +with open({str(pid_file)!r}, "w") as f: + f.write(f"{{os.getpid()}} {{os.getpgid(0)}}") +for i in range(40): + sys.stderr.write(f"Gtk-WARNING: warning {{i}}\\n") + sys.stderr.flush() + if i == 10: + with open({str(alive_file)!r}, "w") as f: + f.write("still-alive") + time.sleep(0.05) +""", + ) + env = {"PATH": str(self.root)} + started = time.monotonic() + with mock.patch.dict(os.environ, env, clear=False): + self.mod.launch([str(fake_app)], settle_seconds=0.2) + elapsed = time.monotonic() - started + self.assertLess(elapsed, 0.8, "long-lived foreground app must detach after settle window") + + # Close parent's stderr handle (simulating next launch or driver exit) + # and confirm the detached child keeps running and writing to stderr. + self.mod._close_last_launch() + deadline = time.monotonic() + 2.0 + while not alive_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + self.assertTrue(alive_file.exists(), "detached app should survive stderr writes without SIGPIPE") + + pid, pgid = map(int, pid_file.read_text(encoding="utf-8").split()) + self.spawned_pids.append(pid) + self.assertEqual(pid, pgid, "detached app must lead its own process group") + self.assertNotEqual(pgid, os.getpgid(0), "detached app must not share driver process group") + os.kill(pid, 0) # still alive + + def test_launch_skips_systemd_when_user_manager_unreachable_and_never_retries_on_stderr_prose(self): + # 1. When private socket exists but org.freedesktop.systemd1 has no bus + # owner (broken user bus), _systemd_user_reachable returns False and + # launch() runs the app directly without touching systemd-run. + with tempfile.TemporaryDirectory(dir="/tmp") as short_dir: + sd_dir = Path(short_dir) / "systemd" + sd_dir.mkdir() + priv_sock = sd_dir / "private" + srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + srv.bind(str(priv_sock)) + systemd_called = self.root / "systemd-called.txt" + make_executable( + self.root / "systemd-run", + f"#!/bin/sh\necho called > {shlex.quote(str(systemd_called))}\nexit 99\n", + ) + marker = self.root / "ran.txt" + fake_app = make_executable( + self.root / "fake-app", + f"#!/bin/sh\necho ok > {shlex.quote(str(marker))}\nexit 0\n", + ) + env = { + "PATH": str(self.root) + os.pathsep + os.environ.get("PATH", ""), + "XDG_RUNTIME_DIR": short_dir, + } + with mock.patch.dict(os.environ, env, clear=False), \ + mock.patch.object(self.mod, "_systemd_user_bus_has_owner", return_value=False): + self.assertFalse(self.mod._systemd_user_reachable(self.mod.launch_env())) + self.mod.launch([str(fake_app)], settle_seconds=2.0) + self.assertEqual(marker.read_text(encoding="utf-8").strip(), "ok") + self.assertFalse(systemd_called.exists(), "systemd-run must not run when user manager is unreachable") + + # 2. When the private socket is present AND NameHasOwner is True, + # _systemd_user_reachable returns True. + with mock.patch.dict(os.environ, env, clear=False), \ + mock.patch.object(self.mod, "_systemd_user_bus_has_owner", return_value=True): + self.assertTrue(self.mod._systemd_user_reachable(self.mod.launch_env())) + finally: + srv.close() + + # 3. When _systemd_user_reachable is True and the app exits non-zero + # printing D-Bus prose on stderr, launch() MUST fail directly and never + # silently retry/fallback based on stderr text. + runs = self.root / "runs.log" + make_executable( + self.root / "systemd-run", + """#!/bin/sh +while [ "$#" -gt 0 ]; do + if [ "$1" = "--" ]; then + shift + break + fi + shift +done +exec "$@" +""", + ) + bus_err_app = make_executable( + self.root / "bus-err-app", + f"#!/bin/sh\necho run >> {shlex.quote(str(runs))}\necho 'Failed to connect to bus: app dbus warning' >&2\nexit 1\n", + ) + env = {"PATH": str(self.root) + os.pathsep + os.environ.get("PATH", "")} + with mock.patch.dict(os.environ, env, clear=False), \ + mock.patch.object(self.mod, "_systemd_user_reachable", return_value=True): + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(bus_err_app)], settle_seconds=2.0) + self.assertIn("Failed to connect to bus: app dbus warning", str(ctx.exception)) + self.assertEqual(runs.read_text(encoding="utf-8").splitlines(), ["run"], "must not retry app on stderr prose") + + def test_launch_post_settle_crash_reported_by_launch_error(self): + fake_app = make_executable( + self.root / "late-crash", + f"""#!{PYTHON_BIN} +import sys, time +time.sleep(0.15) +sys.stderr.write("late crash reason\\n") +sys.exit(7) +""", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + self.mod.launch([str(fake_app)], settle_seconds=0.05) + deadline = time.monotonic() + 1.0 + err = "" + while not err and time.monotonic() < deadline: + err = self.mod.launch_error("run") + if not err: + time.sleep(0.02) + self.assertIn("exited with status 7", err) + self.assertIn("late crash reason", err) + + def test_async_grandchild_stderr_captured_for_open_url_not_running_app(self): + # Simulate gio open exiting 0 immediately while a forked browser dies + # shortly after and writes a snap cgroup error to inherited stderr. + fake_xdg = make_executable( + self.root / "xdg-open", + f"""#!{PYTHON_BIN} +import subprocess, sys +subprocess.Popen([{PYTHON_BIN!r}, "-c", "import sys, time; time.sleep(0.06); sys.stderr.write('async snap error\\\\n'); sys.exit(1)"]) +sys.exit(0) +""", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=0.5) + deadline = time.monotonic() + 1.5 + detail = "" + while "async snap error" not in detail and time.monotonic() < deadline: + detail = self.mod.launch_error("open") + time.sleep(0.02) + self.assertIn("async snap error", detail) + # For open_application ("run"), exit code 0 / running process should not + # treat stderr noise alone as a crash. + self.assertEqual(self.mod.launch_error("run"), "") + + def test_still_running_process_stderr_does_not_pollute_launch_error(self): + pid_file = self.root / "slow.pid" + fake_app = make_executable( + self.root / "slow-firefox", + f"""#!{PYTHON_BIN} +import os, sys, time +with open({str(pid_file)!r}, "w") as f: + f.write(str(os.getpid())) +sys.stderr.write({LD_PRELOAD_NOISE!r} + "\\n") +sys.stderr.write("Gtk-WARNING: theme parsing error\\n") +sys.stderr.flush() +time.sleep(10) +""", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + self.mod.launch([str(fake_app)], settle_seconds=0.15) + deadline = time.monotonic() + 2.0 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + self.spawned_pids.append(int(pid_file.read_text(encoding="utf-8").strip())) + # Process is still running (proc.poll() is None): neither open nor run + # mode may report its startup stderr as a launch error. + self.assertEqual(self.mod.launch_error("open"), "") + self.assertEqual(self.mod.launch_error("run"), "") + + def test_exited_zero_with_only_ld_preload_noise_returns_empty_launch_error(self): + fake_xdg = make_executable( + self.root / "xdg-open", + f"#!/bin/sh\nprintf '%s\\n%s\\n' {shlex.quote(LD_PRELOAD_NOISE)} {shlex.quote(LD_PRELOAD_NOISE)} >&2\nexit 0\n", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=1.0) + self.assertEqual(self.mod.launch_error("open"), "") + self.assertEqual(self.mod.launch_error("run"), "") + + def test_nonzero_exit_filters_ld_preload_spam_and_preserves_real_snap_error(self): + snap_err = "/user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-1.service is not a snap cgroup for tag snap.firefox.firefox" + # Emit heavy ld.so.preload noise both before and after the real error + # (>2 KiB total) to verify filtering runs before 500-char truncation. + spam = "\n".join([LD_PRELOAD_NOISE] * 25) + fake_xdg = make_executable( + self.root / "xdg-open", + f"#!/bin/sh\nprintf '%s\\n%s\\n%s\\n' {shlex.quote(spam)} {shlex.quote(snap_err)} {shlex.quote(spam)} >&2\nexit 4\n", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=2.0) + msg = str(ctx.exception) + self.assertIn("exited with status 4", msg) + self.assertIn("is not a snap cgroup for tag snap.firefox.firefox", msg) + self.assertNotIn("cannot be preloaded", msg) + + def test_nonzero_exit_with_only_ld_preload_noise_reports_clean_exit_status(self): + fake_xdg = make_executable( + self.root / "xdg-open", + f"#!/bin/sh\nprintf '%s\\n' {shlex.quote(LD_PRELOAD_NOISE)} >&2\nexit 4\n", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=False): + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(fake_xdg), "https://example.com"], settle_seconds=2.0) + self.assertEqual(str(ctx.exception), "xdg-open failed (exited with status 4)") + + def test_journald_stream_sink_captures_errors_without_tmp_file_and_falls_back_when_unreadable(self): + with tempfile.TemporaryDirectory(dir="/tmp") as short_dir: + short = Path(short_dir) + sock_path = short / "journal.sock" + store_path = short / "journal.jsonl" + server = FakeJournaldServer(sock_path, store_path) + try: + make_executable( + self.root / "journalctl", + f"""#!{PYTHON_BIN} +import json, sys +tag = None +for i, arg in enumerate(sys.argv[1:]): + if arg == "-t" and i + 2 <= len(sys.argv[1:]): + tag = sys.argv[i + 2] +if not tag: + sys.exit(0) +try: + with open({str(store_path)!r}, encoding="utf-8") as f: + for raw in f: + entry = json.loads(raw) + if entry["tag"] == tag: + sys.stdout.write(entry["line"] + "\\n") +except FileNotFoundError: + pass +""", + ) + snap_err = "snap-confine: cgroup rejected" + failing_app = make_executable( + self.root / "failing-snap", + f"#!/bin/sh\nprintf '%s\\n%s\\n' {shlex.quote(LD_PRELOAD_NOISE)} {shlex.quote(snap_err)} >&2\nexit 4\n", + ) + long_app = make_executable( + self.root / "long-gui", + f"""#!{PYTHON_BIN} +import os, signal, sys, time +signal.signal(signal.SIGPIPE, signal.SIG_DFL) +with open({str(self.root / "long.pid")!r}, "w") as f: + f.write(str(os.getpid())) +sys.stderr.write("Gtk-WARNING: harmless startup log\\n") +sys.stderr.flush() +time.sleep(10) +""", + ) + env = {"PATH": str(self.root)} + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(self.mod, "JOURNAL_STDOUT_SOCKET", str(sock_path)): + self.mod._journal_sink_ready = None + # 1. Non-zero exit reads filtered stderr via journald stream. + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(failing_app)], settle_seconds=2.0) + self.assertIn("exited with status 4", str(ctx.exception)) + self.assertIn(snap_err, str(ctx.exception)) + self.assertNotIn("cannot be preloaded", str(ctx.exception)) + self.assertTrue(self.mod._journal_sink_ready) + # Verify 7-line sd_journal_stream_fd protocol header. + launch_headers = [h for tag, h in server.headers.items() if tag.startswith("linger-launch-")] + self.assertTrue(launch_headers) + self.assertEqual(launch_headers[0][1:], ["", "3", "0", "0", "0", "0"]) + + # 2. Long-lived app uses journald stream (no /tmp file retained). + self.mod.launch([str(long_app)], settle_seconds=0.15) + self.assertIsNone(self.mod.last_launch["stderr_file"]) + self.assertTrue(self.mod.last_launch["journal_tag"].startswith("linger-launch-")) + self.assertEqual(self.mod.launch_error("open"), "") + deadline = time.monotonic() + 2.0 + pid_file = self.root / "long.pid" + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.02) + self.spawned_pids.append(int(pid_file.read_text(encoding="utf-8").strip())) + + # 3. Unreadable journal (e.g. Storage=none) probes False and + # falls back to TemporaryFile without losing stderr capture. + make_executable(self.root / "journalctl", "#!/bin/sh\nexit 0\n") + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(self.mod, "JOURNAL_STDOUT_SOCKET", str(sock_path)), \ + mock.patch.object(self.mod, "JOURNAL_PROBE_RETRIES", 2), \ + mock.patch.object(self.mod, "JOURNAL_RETRY_INTERVAL", 0.01): + self.mod._journal_sink_ready = None + with self.assertRaises(self.mod.LaunchError) as ctx: + self.mod.launch([str(failing_app)], settle_seconds=2.0) + self.assertFalse(self.mod._journal_sink_ready) + self.assertIn(snap_err, str(ctx.exception)) + self.assertNotIn("cannot be preloaded", str(ctx.exception)) + finally: + server.close() + + def test_probe_succeeds_without_systemd_run_and_open_checks_xdg_open(self): + for tool in ("xdotool", "import", "xclip"): + make_executable(self.root / tool, "#!/bin/sh\necho 1920 1080\n") + env = {"PATH": str(self.root), "DISPLAY": ":99", "XDG_SESSION_TYPE": "x11"} + with mock.patch.dict(os.environ, env, clear=True): + with mock.patch.object(self.mod, "missing", None): + self.assertEqual(self.mod.native_action("probe", []), b"ready") + with self.assertRaisesRegex(ValueError, "URL launcher is not installed: xdg-open"): + self.mod.native_action("open", ["https://example.com"]) + + def test_jsonrpc_driver_returns_failed_status_not_unknown_on_launch_error(self): + snap_err = "/user.slice/user-1010.slice/user@1010.service/app.slice/linger-app-1.service is not a snap cgroup for tag snap.firefox.firefox" + make_executable( + self.root / "xdg-open", + f"#!/bin/sh\nprintf '%s\\n' {shlex.quote(snap_err)} >&2\nexit 4\n", + ) + driver_path = Path(__file__).with_name("local_linux.py") + env = os.environ.copy() + env["PATH"] = str(self.root) + os.pathsep + env.get("PATH", "") + proc = subprocess.Popen( + [PYTHON_BIN, "-u", str(driver_path)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + ) + try: + req = { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "action", "arguments": {"command": "open", "args": ["https://example.com"]}}, + } + proc.stdin.write(json.dumps(req) + "\n") + proc.stdin.flush() + line = proc.stdout.readline() + resp = json.loads(line) + receipt = json.loads(resp["result"]["content"][0]["text"]) + self.assertEqual(receipt["status"], "failed") + self.assertIn("exited with status 4", receipt["error"]) + self.assertIn("is not a snap cgroup for tag snap.firefox.firefox", receipt["error"]) + finally: + proc.terminate() + proc.wait(timeout=5) + proc.stdin.close() + proc.stdout.close() + proc.stderr.close() + + +if __name__ == "__main__": + unittest.main()