Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(signin): say at once when there is no display to sign in from

shukieshah569480f0acc9
diff --git a/cli/beacon/cmd/endpoint_cowork.go b/cli/beacon/cmd/endpoint_cowork.go
index da98ee18..7b938bcd 100644
--- a/cli/beacon/cmd/endpoint_cowork.go
+++ b/cli/beacon/cmd/endpoint_cowork.go
@@ -5,6 +5,7 @@ import (
"context"
"crypto/rand"
"encoding/base64"
+ "errors"
"fmt"
"net"
"os"
@@ -16,6 +17,7 @@ import (
"syscall"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations/cowork"
)
@@ -59,7 +61,7 @@ func runEndpointCoworkSetup(cmdCtx context.Context) error {
ResourceAttributes: resourceAttributes,
})
if endpointOpts.coworkOpen {
- if err := dashboard.OpenBrowser(cowork.AdminURL); err != nil {
+ if err := openCoworkAdmin(); err != nil {
_ = tunnel.Stop()
return err
}
@@ -84,11 +86,22 @@ func runEndpointCoworkSetup(cmdCtx context.Context) error {
ResourceAttributes: resourceAttributes,
})
if endpointOpts.coworkOpen {
- return dashboard.OpenBrowser(cowork.AdminURL)
+ return openCoworkAdmin()
}
return nil
}
+// openCoworkAdmin opens the Cowork admin page. With no display to open it on, the setup already
+// printed names the URL, so that is not a failure.
+func openCoworkAdmin() error {
+ err := dashboard.OpenBrowser(cowork.AdminURL)
+ if errors.Is(err, auth.ErrNoDisplay) {
+ fmt.Printf("Not opening a browser (%v).\n", err)
+ return nil
+ }
+ return err
+}
+
func runEndpointCoworkValidate() error {
cfg := loadOrDefaultConfig()
status := cowork.GetStatus(cfg.LogPath)
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index 4ac6baea..3930cce7 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -2,11 +2,13 @@ package cmd
import (
"encoding/json"
+ "errors"
"fmt"
"io"
"os"
"strings"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
@@ -81,7 +83,12 @@ func runEndpointDashboard(cmd *cobra.Command, args []string) error {
}
if endpointOpts.dashboardOpen {
if err := dashboard.OpenBrowser(url); err != nil {
- return err
+ // Over SSH the dashboard is still worth serving: forward its port and open it on
+ // the client.
+ if !errors.Is(err, auth.ErrNoDisplay) {
+ return err
+ }
+ fmt.Printf("Not opening a browser (%v).\n", err)
}
}
return dashboardListenAndServe(dashboard.Options{
diff --git a/cli/beacon/cmd/endpoint_onboarding.go b/cli/beacon/cmd/endpoint_onboarding.go
index 40916fc2..747b4af5 100644
--- a/cli/beacon/cmd/endpoint_onboarding.go
+++ b/cli/beacon/cmd/endpoint_onboarding.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/managedprivacy"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/onboarding"
@@ -57,6 +58,7 @@ var (
onboardingRunWizard = onboarding.RunWizard
onboardingAccountInspect = account.Inspect
onboardingAccountLogin = account.Login
+ onboardingDisplayCheck = auth.CheckDisplay
onboardingAccountSave = account.Save
onboardingClock = time.Now
// destinationAskable reports whether the destination question makes sense here: an
@@ -162,6 +164,7 @@ func runAccountOnboarding(cmd *cobra.Command, profile *onboarding.Profile, desti
PresetDestination: preset,
PresetPrivacyMode: profile.Onboarding.PrivacyMode,
NoBrowser: endpointOpts.noBrowser,
+ NoDisplay: onboardingDisplayCheck(),
Now: onboardingClock,
SignInTimeout: account.LoginWait,
// Signing in happens inside the wizard so the full-screen UI is never torn
@@ -179,6 +182,7 @@ func runAccountOnboarding(cmd *cobra.Command, profile *onboarding.Profile, desti
URL: prompt.URL,
WillOpen: prompt.WillOpen,
BrowserErr: prompt.BrowserErr,
+ SSHForward: account.SSHForwardCommand(prompt.Port),
})
},
})
diff --git a/cli/beacon/cmd/endpoint_onboarding_display_test.go b/cli/beacon/cmd/endpoint_onboarding_display_test.go
new file mode 100644
index 00000000..7b0d9ffc
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_onboarding_display_test.go
@@ -0,0 +1,48 @@
+package cmd
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/onboarding"
+)
+
+type recordingReporter struct{ prompts []onboarding.SignInPrompt }
+
+func (r *recordingReporter) Prompt(p onboarding.SignInPrompt) { r.prompts = append(r.prompts, p) }
+
+// The wizard can only skip a sign-in that cannot finish if it is told there is no display, and the
+// SSH path only works if it is handed the port to forward.
+func TestOnboardingTellsTheWizardAboutAMissingDisplay(t *testing.T) {
+ h := newOnboardingHarness(t)
+ h.accountStatus = account.Status{}
+
+ prevCheck, prevLogin := onboardingDisplayCheck, onboardingAccountLogin
+ t.Cleanup(func() { onboardingDisplayCheck, onboardingAccountLogin = prevCheck, prevLogin })
+ onboardingDisplayCheck = func() error { return fmt.Errorf("%w: this is an SSH session", auth.ErrNoDisplay) }
+ onboardingAccountLogin = func(_ context.Context, opts account.LoginOptions) (*account.Session, error) {
+ opts.OnPrompt(account.LoginPrompt{URL: "https://beacon.sh/cli/auth?port=54123", Port: 54123})
+ return nil, errors.New("stop here")
+ }
+
+ var noDisplay error
+ reporter := &recordingReporter{}
+ onboardingRunWizard = func(_ io.Reader, _ io.Writer, opts onboarding.WizardOptions) (onboarding.WizardResult, error) {
+ noDisplay = opts.NoDisplay
+ _, _ = opts.SignIn(context.Background(), onboarding.SignInRequest{NoBrowser: true}, reporter)
+ return onboarding.WizardResult{}, onboarding.ErrWizardCancelled
+ }
+
+ _, _ = h.run(t)
+ if !errors.Is(noDisplay, auth.ErrNoDisplay) {
+ t.Fatalf("WizardOptions.NoDisplay = %v, want ErrNoDisplay", noDisplay)
+ }
+ if len(reporter.prompts) != 1 || reporter.prompts[0].SSHForward != "ssh -L 54123:127.0.0.1:54123 <this machine>" {
+ t.Fatalf("prompts = %#v, want the port forward for 54123", reporter.prompts)
+ }
+}
diff --git a/cli/beacon/internal/account/login.go b/cli/beacon/internal/account/login.go
index f9edb106..b4975f06 100644
--- a/cli/beacon/internal/account/login.go
+++ b/cli/beacon/internal/account/login.go
@@ -69,6 +69,9 @@ type LoginPrompt struct {
BrowserErr error
// Timeout is how long Login will wait before giving up.
Timeout time.Duration
+ // Port is the loopback port the sign-in redirects to. Signing in from another computer over
+ // SSH means forwarding it: ssh -L Port:127.0.0.1:Port.
+ Port int
}
type clientInfo struct {
@@ -176,23 +179,31 @@ func Login(ctx context.Context, opts LoginOptions) (*Session, error) {
return nil, fmt.Errorf("start Beacon sign-in: %w", err)
}
- loginURL := buildLoginURL(baseURL, pkce.State, callback.Port())
+ port := callback.Port()
+ loginURL := buildLoginURL(baseURL, pkce.State, port)
report := opts.OnPrompt
if report != nil {
out = io.Discard
} else {
report = func(LoginPrompt) {}
}
- report(LoginPrompt{URL: loginURL, WillOpen: !opts.NoBrowser, Timeout: timeout})
+ report(LoginPrompt{URL: loginURL, WillOpen: !opts.NoBrowser, Timeout: timeout, Port: port})
if opts.NoBrowser {
- fmt.Fprintf(out, "Open this URL to sign in to Beacon:\n%s\n", loginURL)
- } else {
- fmt.Fprintf(out, "Opening %s in your browser...\n", baseURL)
- if err := openBrowser(loginURL); err != nil {
- report(LoginPrompt{URL: loginURL, BrowserErr: err, Timeout: timeout})
+ printLoginURL(out, loginURL, port)
+ } else if err := openBrowser(loginURL); err != nil {
+ report(LoginPrompt{URL: loginURL, BrowserErr: err, Timeout: timeout, Port: port})
+ if errors.Is(err, auth.ErrNoDisplay) {
+ // Said at once, not after the wait times out: the redirect has to land on this
+ // machine, so the person needs the URL and the port to forward, not a spinner.
+ msg := err.Error()
+ fmt.Fprintf(out, "%s%s.\n", strings.ToUpper(msg[:1]), msg[1:])
+ fmt.Fprintln(out, "Sign-in finishes when beacon.sh redirects a browser back to this machine.")
+ } else {
fmt.Fprintln(out, "Could not open a browser automatically.")
- fmt.Fprintf(out, "Open this URL to sign in to Beacon:\n%s\n", loginURL)
}
+ printLoginURL(out, loginURL, port)
+ } else {
+ fmt.Fprintf(out, "Opening %s in your browser...\n", baseURL)
}
fmt.Fprintln(out, "Waiting for Beacon sign-in...")
@@ -269,6 +280,18 @@ func ResolveBaseURL(flagValue string) string {
return strings.TrimRight(value, "/")
}
+// printLoginURL shows the sign-in URL and how to use it from another computer.
+func printLoginURL(out io.Writer, loginURL string, port int) {
+ fmt.Fprintf(out, "Open this URL to sign in to Beacon:\n%s\n", loginURL)
+ fmt.Fprintf(out, "From another computer over SSH, forward the port first: %s\n", SSHForwardCommand(port))
+}
+
+// SSHForwardCommand is the port forward that lets a browser on the SSH client finish a sign-in
+// that redirects to port on this machine.
+func SSHForwardCommand(port int) string {
+ return fmt.Sprintf("ssh -L %d:127.0.0.1:%d <this machine>", port, port)
+}
+
func buildLoginURL(baseURL, state string, port int) string {
u, err := url.Parse(baseURL + LoginPagePath)
if err != nil {
diff --git a/cli/beacon/internal/account/login_display_test.go b/cli/beacon/internal/account/login_display_test.go
new file mode 100644
index 00000000..ff47e365
--- /dev/null
+++ b/cli/beacon/internal/account/login_display_test.go
@@ -0,0 +1,64 @@
+package account
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Over SSH, or on a machine with no display, xdg-open starts and then fails, and the start was
+// all Login used to check. It printed "Opening https://beacon.sh in your browser...", showed no
+// URL, and waited out the whole timeout. It has to say why at once and show the URL and the port
+// to forward.
+func TestLoginWithoutADisplayShowsTheURLAtOnce(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("the display check is Linux-only, and the real opener elsewhere would open a browser")
+ }
+ service := newFakeAuthService(t)
+
+ // An xdg-open that "succeeds", the way the real one does when it has nowhere to go.
+ bin := t.TempDir()
+ marker := filepath.Join(t.TempDir(), "xdg-open-ran")
+ script := "#!/bin/sh\ntouch '" + marker + "'\nexit 0\n"
+ if err := os.WriteFile(filepath.Join(bin, "xdg-open"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
+ t.Setenv("DISPLAY", "")
+ t.Setenv("WAYLAND_DISPLAY", "")
+ t.Setenv("SSH_CONNECTION", "10.0.0.5 51000 10.0.0.9 22")
+
+ var out bytes.Buffer
+ _, err := Login(context.Background(), LoginOptions{
+ BaseURL: service.server.URL,
+ Out: &out,
+ Timeout: 200 * time.Millisecond,
+ })
+ if err == nil {
+ t.Fatal("nothing approved the sign-in, so Login should have timed out")
+ }
+ // Given a moment in case the opener was started asynchronously.
+ time.Sleep(100 * time.Millisecond)
+ if _, statErr := os.Stat(marker); statErr == nil {
+ t.Fatal("xdg-open ran in an SSH session with no display")
+ }
+ text := out.String()
+ for _, want := range []string{
+ "this is an SSH session",
+ "redirects a browser back to this machine",
+ service.server.URL + LoginPagePath + "?",
+ "ssh -L ",
+ } {
+ if !strings.Contains(text, want) {
+ t.Fatalf("login output is missing %q:\n%s", want, text)
+ }
+ }
+ if strings.Contains(text, "in your browser...") {
+ t.Fatalf("login claimed a browser was opening:\n%s", text)
+ }
+}
diff --git a/cli/beacon/internal/auth/browser.go b/cli/beacon/internal/auth/browser.go
index 39ba9b0b..ccb51e83 100644
--- a/cli/beacon/internal/auth/browser.go
+++ b/cli/beacon/internal/auth/browser.go
@@ -1,22 +1,75 @@
package auth
import (
+ "errors"
"fmt"
+ "os"
"os/exec"
"runtime"
+ "strings"
)
+// ErrNoDisplay means a browser opened here would not be seen by the person running Beacon.
+// CheckDisplay and OpenBrowser wrap it with the reason.
+var ErrNoDisplay = errors.New("no browser can be opened on this machine")
+
+// Variables so tests can drive the Linux branch from any OS without starting a browser.
+var (
+ browserGOOS = runtime.GOOS
+ browserEnv = os.Getenv
+ startBrowser = func(cmd *exec.Cmd) error { return cmd.Start() }
+)
+
+// CheckDisplay reports, on Linux, whether there is a display to open a browser on. It returns nil
+// elsewhere, and nil when it cannot tell.
+//
+// This has to be decided before exec'ing anything. xdg-open with no display fails only after Start
+// has returned nil, so the failure never reached the caller: sign-in said a browser was opening,
+// showed no URL, and waited five minutes for a redirect that could not come.
+//
+// An SSH session counts as no display even when DISPLAY is set. There DISPLAY is usually a desktop
+// session's, inherited through tmux or exported by hand, and a browser opened on it appears on a
+// screen the person at the SSH client cannot see. The exception is X11 forwarding (ssh -X), whose
+// DISPLAY names a host, as in localhost:10.0: the browser then runs here and shows up on the
+// client, so the loopback redirect still works.
+func CheckDisplay() error {
+ if browserGOOS != "linux" {
+ return nil
+ }
+ display := browserEnv("DISPLAY")
+ if browserEnv("SSH_CONNECTION") != "" || browserEnv("SSH_TTY") != "" {
+ if forwardedX11(display) {
+ return nil
+ }
+ return fmt.Errorf("%w: this is an SSH session", ErrNoDisplay)
+ }
+ if display == "" && browserEnv("WAYLAND_DISPLAY") == "" {
+ return fmt.Errorf("%w: DISPLAY and WAYLAND_DISPLAY are not set", ErrNoDisplay)
+ }
+ return nil
+}
+
+// forwardedX11 reports whether an X display names a remote host, which is what ssh -X sets. A
+// local session's display has no host part (":0") or names the unix socket.
+func forwardedX11(display string) bool {
+ host, _, ok := strings.Cut(display, ":")
+ return ok && host != "" && host != "unix" && !strings.HasPrefix(host, "/")
+}
+
func OpenBrowser(url string) error {
var cmd *exec.Cmd
- switch runtime.GOOS {
+ switch browserGOOS {
case "darwin":
cmd = exec.Command("open", url)
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "linux":
+ if err := CheckDisplay(); err != nil {
+ return err
+ }
cmd = exec.Command("xdg-open", url)
default:
- return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
+ return fmt.Errorf("unsupported platform: %s", browserGOOS)
}
- return cmd.Start()
+ return startBrowser(cmd)
}
diff --git a/cli/beacon/internal/auth/browser_test.go b/cli/beacon/internal/auth/browser_test.go
new file mode 100644
index 00000000..bac092bc
--- /dev/null
+++ b/cli/beacon/internal/auth/browser_test.go
@@ -0,0 +1,86 @@
+package auth
+
+import (
+ "errors"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+// fakeBrowserHost points OpenBrowser at a pretend OS and environment and records what it would
+// have exec'd.
+func fakeBrowserHost(t *testing.T, goos string, env map[string]string) *[]string {
+ t.Helper()
+ prevGOOS, prevEnv, prevStart := browserGOOS, browserEnv, startBrowser
+ t.Cleanup(func() { browserGOOS, browserEnv, startBrowser = prevGOOS, prevEnv, prevStart })
+ var started []string
+ browserGOOS = goos
+ browserEnv = func(key string) string { return env[key] }
+ startBrowser = func(cmd *exec.Cmd) error {
+ started = append(started, filepath.Base(cmd.Path))
+ return nil
+ }
+ return &started
+}
+
+func TestOpenBrowserChecksForADisplayOnLinux(t *testing.T) {
+ const ssh = "10.0.0.5 51000 10.0.0.9 22"
+ cases := []struct {
+ name string
+ goos string
+ env map[string]string
+ noDisplay bool
+ reason string
+ }{
+ {name: "X session", goos: "linux", env: map[string]string{"DISPLAY": ":0"}},
+ {name: "Wayland session", goos: "linux", env: map[string]string{"WAYLAND_DISPLAY": "wayland-0"}},
+ {name: "no display", goos: "linux", env: map[string]string{}, noDisplay: true,
+ reason: "no browser can be opened on this machine: DISPLAY and WAYLAND_DISPLAY are not set"},
+ {name: "SSH session", goos: "linux", env: map[string]string{"SSH_CONNECTION": ssh}, noDisplay: true,
+ reason: "no browser can be opened on this machine: this is an SSH session"},
+ // tmux started on the desktop and attached over SSH keeps the desktop's DISPLAY.
+ {name: "SSH with an inherited local DISPLAY", goos: "linux",
+ env: map[string]string{"SSH_CONNECTION": ssh, "DISPLAY": ":0"}, noDisplay: true},
+ {name: "SSH with an inherited Wayland display", goos: "linux",
+ env: map[string]string{"SSH_TTY": "/dev/pts/3", "WAYLAND_DISPLAY": "wayland-0"}, noDisplay: true},
+ {name: "SSH with X11 forwarding", goos: "linux",
+ env: map[string]string{"SSH_CONNECTION": ssh, "DISPLAY": "localhost:10.0"}},
+ // macOS and Windows are not checked: their openers do not fail silently.
+ {name: "macOS", goos: "darwin", env: map[string]string{"SSH_CONNECTION": ssh}},
+ {name: "Windows", goos: "windows", env: map[string]string{}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ started := fakeBrowserHost(t, tc.goos, tc.env)
+ err := OpenBrowser("https://beacon.sh/cli/auth?port=54123")
+ if tc.noDisplay {
+ if !errors.Is(err, ErrNoDisplay) {
+ t.Fatalf("OpenBrowser = %v, want ErrNoDisplay", err)
+ }
+ if tc.reason != "" && err.Error() != tc.reason {
+ t.Fatalf("error = %q, want %q", err, tc.reason)
+ }
+ if len(*started) != 0 {
+ t.Fatalf("started %v with nowhere to show a browser", *started)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("OpenBrowser = %v, want nil", err)
+ }
+ if len(*started) != 1 {
+ t.Fatalf("started %v, want exactly one opener", *started)
+ }
+ })
+ }
+}
+
+func TestOpenBrowserUsesXdgOpenOnLinux(t *testing.T) {
+ started := fakeBrowserHost(t, "linux", map[string]string{"DISPLAY": ":1"})
+ if err := OpenBrowser("https://beacon.sh"); err != nil {
+ t.Fatal(err)
+ }
+ if len(*started) != 1 || (*started)[0] != "xdg-open" {
+ t.Fatalf("started %v, want xdg-open", *started)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.go
index 3bd4db24..4f764207 100644
--- a/cli/beacon/internal/endpoint/dashboard/server.go
+++ b/cli/beacon/internal/endpoint/dashboard/server.go
@@ -7,12 +7,11 @@ import (
"io/fs"
"net"
"net/http"
- "os/exec"
- "runtime"
"strconv"
"strings"
"time"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
@@ -390,17 +389,10 @@ func URL(addr string) string {
return "http://" + addr
}
+// OpenBrowser is auth.OpenBrowser, which checks for a display on Linux before exec'ing xdg-open.
+// This used to be a second copy of the opener without that check.
func OpenBrowser(url string) error {
- var cmd *exec.Cmd
- switch runtime.GOOS {
- case "darwin":
- cmd = exec.Command("open", url)
- case "windows":
- cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
- default:
- cmd = exec.Command("xdg-open", url)
- }
- return cmd.Start()
+ return auth.OpenBrowser(url)
}
func parseQuery(r *http.Request, fallbackLimit int) EventQuery {
diff --git a/cli/beacon/internal/onboarding/wizard.go b/cli/beacon/internal/onboarding/wizard.go
index 7678b003..31b39874 100644
--- a/cli/beacon/internal/onboarding/wizard.go
+++ b/cli/beacon/internal/onboarding/wizard.go
@@ -29,6 +29,9 @@ type SignInPrompt struct {
URL string
WillOpen bool
BrowserErr error
+ // SSHForward is the port forward that lets a browser on another computer finish this
+ // sign-in, shown next to a URL the user opens themselves.
+ SSHForward string
}
// Reporter is how a sign-in in progress tells the wizard what is happening. It is
@@ -63,6 +66,10 @@ type WizardOptions struct {
SignIn SignInFunc
// NoBrowser presents the URL to open rather than claiming one will open.
NoBrowser bool
+ // NoDisplay is why no browser can be opened on this machine, or nil when one can. When set,
+ // and NoBrowser is not, the wizard does not start a sign-in that cannot finish: it goes
+ // straight to recovery and says why.
+ NoDisplay error
// Now is injectable so elapsed time renders deterministically in tests.
Now func() time.Time
// SignInTimeout is rendered as a countdown. The real deadline lives in SignIn.
@@ -114,7 +121,10 @@ type wizardModel struct {
signInErr error
// attempt counts sign-in attempts, so a report from an abandoned one can be
// told apart from the current one's.
- attempt int
+ attempt int
+ // noDisplay is set while recovery is showing because no browser can be opened here,
+ // rather than because an attempt failed.
+ noDisplay bool
startedAt time.Time
now time.Time
frame int
@@ -180,10 +190,11 @@ var (
func newWizardModel(options WizardOptions) wizardModel {
screen := welcomeScreen
result := WizardResult{Destination: options.PresetDestination, PrivacyMode: options.PresetPrivacyMode}
+ needSignIn := false
if options.DestinationOnly {
switch {
case !options.SignedIn:
- screen = signInScreen
+ needSignIn = true
case options.PresetDestination == DestinationAsymptote:
screen = managedDisclosureScreen
case options.PresetDestination != "":
@@ -192,7 +203,29 @@ func newWizardModel(options WizardOptions) wizardModel {
screen = destinationScreen
}
}
- return wizardModel{options: options, result: result, screen: screen}
+ model := wizardModel{options: options, result: result, screen: screen}
+ if needSignIn {
+ model.needSignIn()
+ }
+ return model
+}
+
+// needSignIn moves to the sign-in screen, or, when there is no display to open a browser on,
+// straight to recovery.
+//
+// A sign-in finishes by redirecting a browser back to this machine. With no display, or over SSH,
+// the browser Beacon opens is one nobody sees, and the attempt used to sit on the wait screen for
+// five minutes before anything said so. The missing display is the failure, so it is reported as
+// one, before any attempt starts.
+func (m *wizardModel) needSignIn() {
+ if m.options.NoDisplay != nil && !m.options.NoBrowser {
+ m.signInErr = m.options.NoDisplay
+ m.noDisplay = true
+ m.selected = 0
+ m.screen = signInFailedScreen
+ return
+ }
+ m.screen = signInScreen
}
func RunWizard(in io.Reader, out io.Writer, options WizardOptions) (WizardResult, error) {
@@ -247,7 +280,7 @@ func (m wizardModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
// ending the install: the browser may simply not have opened.
if m.screen == signInWaitScreen {
m.stopSignIn()
- m.screen = signInScreen
+ m.needSignIn()
return m, nil
}
return m.cancelAndQuit()
@@ -289,6 +322,7 @@ func (m wizardModel) startSignIn() (tea.Model, tea.Cmd) {
ctx, cancel := context.WithCancel(context.Background())
m.cancelSignIn = cancel
m.signInErr = nil
+ m.noDisplay = false
m.prompt = SignInPrompt{}
m.startedAt = m.clock()
m.now = m.startedAt
@@ -357,7 +391,7 @@ func (m wizardModel) advance() (tea.Model, tea.Cmd) {
case welcomeScreen:
switch {
case !m.options.SignedIn:
- m.screen = signInScreen
+ m.needSignIn()
case m.options.PresetDestination == DestinationAsymptote:
m.screen = managedDisclosureScreen
case m.options.PresetDestination != "":
@@ -431,6 +465,25 @@ type recoveryChoice struct {
// finish, or a local-first tool becomes uninstallable without tribal knowledge of
// an environment variable.
func (m wizardModel) recoveryChoices() []recoveryChoice {
+ local := recoveryChoice{
+ id: "local",
+ label: "Finish setup without an account",
+ detail: "Install Beacon with telemetry kept on this machine. Connect later with `beacon endpoint connect`.",
+ }
+ cancel := recoveryChoice{id: "cancel", label: "Cancel setup", detail: "Stop without installing."}
+ if m.noDisplay {
+ // No retry: trying again cannot find a display. Finishing locally comes first because
+ // it is the choice that works from here.
+ return []recoveryChoice{
+ local,
+ {
+ id: "manual",
+ label: "Show the sign-in URL",
+ detail: "Open it in a browser on this machine, or on your own computer after forwarding the port it names over SSH.",
+ },
+ cancel,
+ }
+ }
choices := []recoveryChoice{
{id: "retry", label: "Try signing in again", detail: "Open beacon.sh and wait for the browser again."},
}
@@ -441,14 +494,7 @@ func (m wizardModel) recoveryChoices() []recoveryChoice {
detail: "Open the address yourself, in a browser on this machine.",
})
}
- return append(choices,
- recoveryChoice{
- id: "local",
- label: "Finish setup without an account",
- detail: "Install Beacon with telemetry kept on this machine. Connect later with `beacon endpoint connect`.",
- },
- recoveryChoice{id: "cancel", label: "Cancel setup", detail: "Stop without installing."},
- )
+ return append(choices, local, cancel)
}
func (m wizardModel) recover() (tea.Model, tea.Cmd) {
@@ -514,14 +560,24 @@ func (m wizardModel) View() string {
body = "Open this URL to sign in:"
}
raw = m.prompt.URL
+ if m.prompt.URL != "" && m.prompt.SSHForward != "" && (!m.prompt.WillOpen || m.prompt.BrowserErr != nil) {
+ raw += "\n\n" + wizardDim.Render("From another computer over SSH, forward the port first:") +
+ "\n" + m.prompt.SSHForward
+ }
if m.prompt.URL != "" {
raw += "\n\n" + wizardDim.Render(m.waitStatus())
}
case signInFailedScreen:
title = "Sign-in did not finish"
+ if m.noDisplay {
+ title = "No browser on this machine"
+ }
if m.signInErr != nil {
body = wizardWarn.Render(m.signInErr.Error()) + "\n\n"
}
+ if m.noDisplay {
+ body += "Sign-in finishes when beacon.sh redirects a browser back to this machine.\n\n"
+ }
var rows []string
for index, choice := range m.recoveryChoices() {
line := " " + choice.label
diff --git a/cli/beacon/internal/onboarding/wizard_nodisplay_test.go b/cli/beacon/internal/onboarding/wizard_nodisplay_test.go
new file mode 100644
index 00000000..4acc49fc
--- /dev/null
+++ b/cli/beacon/internal/onboarding/wizard_nodisplay_test.go
@@ -0,0 +1,141 @@
+package onboarding
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+var errSSHSession = errors.New("no browser can be opened on this machine: this is an SSH session")
+
+// countingSignIn is a sign-in that records every attempt and never finishes on its own.
+func countingSignIn(requests chan<- SignInRequest) SignInFunc {
+ return func(ctx context.Context, req SignInRequest, _ Reporter) (Account, error) {
+ requests <- req
+ <-ctx.Done()
+ return Account{}, ctx.Err()
+ }
+}
+
+func recoveryIDs(model wizardModel) []string {
+ var ids []string
+ for _, choice := range model.recoveryChoices() {
+ ids = append(ids, choice.id)
+ }
+ return ids
+}
+
+// With no display, the browser Beacon opens is one nobody sees, and the wizard used to wait five
+// minutes on it before saying anything. It now says so before any attempt starts.
+func TestNoDisplayGoesStraightToRecovery(t *testing.T) {
+ requests := make(chan SignInRequest, 4)
+ model := signInWizard(t, countingSignIn(requests))
+ model.options.NoDisplay = errSSHSession
+ model.screen = welcomeScreen
+
+ model, _ = advanceWizard(t, model, "enter")
+ if model.screen == signInWaitScreen {
+ t.Fatal("the wizard waited for a browser on a machine with no display")
+ }
+ if model.screen != signInFailedScreen {
+ t.Fatalf("screen = %v, want recovery straight after welcome", model.screen)
+ }
+ select {
+ case req := <-requests:
+ t.Fatalf("a sign-in started (%#v) with no display to finish it on", req)
+ case <-time.After(50 * time.Millisecond):
+ }
+
+ if got, want := strings.Join(recoveryIDs(model), ","), "local,manual,cancel"; got != want {
+ t.Fatalf("recovery choices = %s, want %s", got, want)
+ }
+ flat := strings.Join(strings.Fields(model.View()), " ")
+ for _, want := range []string{
+ "No browser on this machine",
+ "this is an SSH session",
+ "redirects a browser back to this machine",
+ "Finish setup without an account",
+ "Show the sign-in URL",
+ } {
+ if !strings.Contains(flat, want) {
+ t.Fatalf("recovery screen missing %q:\n%s", want, flat)
+ }
+ }
+ if strings.Contains(flat, "Try signing in again") {
+ t.Fatalf("retrying cannot find a display, so it must not be offered:\n%s", flat)
+ }
+
+ // The default choice finishes locally.
+ model, _ = advanceWizard(t, model, "enter")
+ if model.screen != confirmScreen || !model.result.WithoutAccount || model.result.Destination != DestinationLocal {
+ t.Fatalf("screen = %v result = %#v, want a local finish without an account", model.screen, model.result)
+ }
+}
+
+// Reinstalling after an earlier setup starts at the sign-in step, and takes the same path.
+func TestNoDisplayDestinationOnlyStartsAtRecovery(t *testing.T) {
+ model := newWizardModel(WizardOptions{DestinationOnly: true, NoDisplay: errSSHSession, SignIn: neverReturns})
+ if model.screen != signInFailedScreen {
+ t.Fatalf("screen = %v, want recovery", model.screen)
+ }
+}
+
+// Showing the URL is the SSH path: the user forwards the callback port and opens the URL on their
+// own computer. The command has to be on screen, unwrapped, while the sign-in waits.
+func TestNoDisplayShowURLNamesThePortToForward(t *testing.T) {
+ requests := make(chan SignInRequest, 4)
+ model := signInWizard(t, countingSignIn(requests))
+ model.options.NoDisplay = errSSHSession
+ model.screen = welcomeScreen
+ model, _ = advanceWizard(t, model, "enter")
+
+ for i, id := range recoveryIDs(model) {
+ if id == "manual" {
+ model.selected = i
+ }
+ }
+ model, _ = advanceWizard(t, model, "enter")
+ t.Cleanup(func() { model.stopSignIn() })
+ if model.screen != signInWaitScreen {
+ t.Fatalf("screen = %v, want the waiting screen", model.screen)
+ }
+ select {
+ case req := <-requests:
+ if !req.NoBrowser {
+ t.Fatalf("request = %#v, want the browser suppressed", req)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("showing the URL never started a sign-in")
+ }
+
+ forward := "ssh -L 54123:127.0.0.1:54123 <this machine>"
+ next, _ := model.Update(signInPromptMsg{attempt: 1, prompt: SignInPrompt{
+ URL: "https://beacon.sh/cli/auth?port=54123&state=" + strings.Repeat("a", 43),
+ SSHForward: forward,
+ }})
+ model = next.(wizardModel)
+ if view := model.View(); !strings.Contains(view, forward) {
+ t.Fatalf("waiting screen should show %q on one line:\n%s", forward, view)
+ }
+
+ // A failure of that attempt is an ordinary failure: retry is offered again.
+ next, _ = model.Update(signInDoneMsg{attempt: 1, err: errors.New("timed out")})
+ model = next.(wizardModel)
+ if ids := recoveryIDs(model); ids[0] != "retry" {
+ t.Fatalf("recovery after a real attempt = %v, want retry first", ids)
+ }
+}
+
+// --no-browser already asks for the URL, so a missing display changes nothing.
+func TestNoBrowserFlagKeepsTheSignInScreenWithoutADisplay(t *testing.T) {
+ model := signInWizard(t, neverReturns)
+ model.options.NoDisplay = errSSHSession
+ model.options.NoBrowser = true
+ model.screen = welcomeScreen
+ model, _ = advanceWizard(t, model, "enter")
+ if model.screen != signInScreen {
+ t.Fatalf("screen = %v, want the sign-in screen", model.screen)
+ }
+}
diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdx
index 3f98c142..92962d2b 100644
--- a/docs/cli/account-auth.mdx
+++ b/docs/cli/account-auth.mdx
@@ -35,6 +35,22 @@ session, use a browser on the remote host or forward the callback port shown in
the printed URL; opening it on an unrelated workstation without port forwarding
redirects to that workstation's localhost and cannot complete the remote login.
+On Linux, `beacon login` does not try to open a browser when there is no display
+(`DISPLAY` and `WAYLAND_DISPLAY` unset) or in an SSH session. It says so, prints the
+URL and the port forward to run, and waits:
+
+```text
+No browser can be opened on this machine: this is an SSH session.
+Sign-in finishes when beacon.sh redirects a browser back to this machine.
+Open this URL to sign in to Beacon:
+https://beacon.sh/cli/auth?port=43121&state=...
+From another computer over SSH, forward the port first: ssh -L 43121:127.0.0.1:43121 <this machine>
+Waiting for Beacon sign-in...
+```
+
+Run the `ssh -L` command in a second terminal on your own computer, then open the URL
+there. The port changes on every attempt.
+
The session is stored at `~/.beacon/auth/session.json` in a `0700` directory with file mode `0600`. Human and JSON command output never includes the access token. Tokens expire rather than refreshing indefinitely; run `beacon login` again after expiry.
Use `--auth-url` or `BEACON_AUTH_URL` only for a self-hosted or development authentication service. Non-loopback authentication URLs must use HTTPS.
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index 40e27145..06e620bc 100644
--- a/docs/cli/endpoint-install.mdx
+++ b/docs/cli/endpoint-install.mdx
@@ -31,7 +31,7 @@ The `claude` harness writes both Claude Code's OpenTelemetry settings and its us
| `--otlp-http-port <port>` | Local OTLP HTTP port. Defaults to `4318` |
| `--collector <path>` | Path to a `beacon-otelcol` binary |
| `--no-start` | Write files without starting the collector service |
-| `--no-browser` | During interactive setup, print the sign-in URL instead of opening a browser. Useful where no browser can be opened, though the URL still has to be opened on this machine |
+| `--no-browser` | During interactive setup, print the sign-in URL instead of opening a browser. Useful where no browser can be opened. Open the URL on this machine, or on another computer after forwarding the port it names over SSH |
| `--service <kind>` | Service manager to use: `auto` (default), `launchd`, `systemd`, or `none` for a supervised collector process |
| `--dry-run` | Print planned actions without changing endpoint files or services |
| `--include-runtime-metrics` | Include generic process, runtime, and harness operational OTLP metrics in Beacon JSONL. By default, low-signal metrics such as process CPU, memory, Node.js event loop, V8 heap, GitHub Copilot CLI, and OpenClaw operational metrics are filtered out |
diff --git a/docs/cli/endpoint-onboarding.mdx b/docs/cli/endpoint-onboarding.mdx
index 0012e8bb..2d4d0589 100644
--- a/docs/cli/endpoint-onboarding.mdx
+++ b/docs/cli/endpoint-onboarding.mdx
@@ -42,6 +42,19 @@ the wizard offers to try again, to show the URL for you to open yourself, or to
finish setup without an account and keep telemetry on this machine. Pass
`--no-browser` to `beacon endpoint install` to start in that mode.
+On Linux, the wizard checks for a display before it starts. With no `DISPLAY` or
+`WAYLAND_DISPLAY`, or in an SSH session, it goes straight to that screen and says why,
+because sign-in finishes by redirecting a browser back to this machine. The choices
+are:
+
+- **Finish setup without an account** (the default): a local install.
+- **Show the sign-in URL**: open it on this machine, or on your own computer after
+ forwarding the port it names. The wizard prints the command, for example
+ `ssh -L 43121:127.0.0.1:43121 <this machine>`.
+- **Cancel setup**.
+
+An SSH session with X11 forwarding (`ssh -X`) counts as having a display.
+
Signing in establishes account identity only. It does not register a managed endpoint,
start Vector, or send telemetry. Beacon Managed is preselected; choose Local explicitly
to opt out of managed forwarding.