From df4ce2bf8f46c14bbb01cb69bc59164c823d8abb Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Fri, 20 Nov 2026 18:42:01 +0000 Subject: [PATCH] Add hosts from the tailnet, and switch between them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server chip's card now lists the hosts to switch to: this machine, then the hosts the local server keeps, the one shown marked, and an Add host… button. The palette does the same, under Rex.app's action names: client.host.switch lists the hosts, and client.host.add the tailnet's machines, this one first, then those online, each with its OS. Choosing a machine looks for Rex on it, as rex-rune's picker does, and says so in the palette. If a server answers, the machine is saved as a host, named as the tailnet names it, so rex -S and other clients know it too, and the window switches to it. If not, the palette says why: no Rex server, with the command that turns on built-in Tailscale; the machine being offline; or a Rex server that didn't let this device in, with its reason. A 403 counts as a Rex server refusing only when it carries Rex's {"error": ...} reason: on this tailnet, another program on a machine's port 443 answers 403 too, and isn't Rex. The chip's tag shows CONNECTING or RECONNECTING while that is under way, and FAILED, with the reason in the card, when a switch doesn't work. Tests add a machine with no Rex and one with Rex, standing in for tailnet addresses, check the host is saved and the window switches, and switch back from the hosts list; and tell a Rex 403 from another. --- internal/rex/control.go | 27 ++++- internal/rex/endpoint.go | 6 ++ internal/rex/endpoint_test.go | 37 +++++++ internal/tailnet/tailnet.go | 4 + internal/ui/actions.go | 8 ++ internal/ui/hostpicker.go | 189 ++++++++++++++++++++++++++++++++++ internal/ui/palette.go | 83 ++++++++++++++- internal/ui/server.go | 108 +++++++++++++++++-- internal/ui/servers.go | 4 + internal/ui/servers_test.go | 61 +++++++++++ internal/ui/ui.go | 4 +- 11 files changed, 519 insertions(+), 12 deletions(-) create mode 100644 internal/ui/hostpicker.go diff --git a/internal/rex/control.go b/internal/rex/control.go index bbe060c..58c6317 100644 --- a/internal/rex/control.go +++ b/internal/rex/control.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "fmt" + "io" + "net/http" "runtime" "strconv" "sync" @@ -184,7 +186,7 @@ func Dial(ctx context.Context, ep Endpoint, info ClientInfo) (*Conn, error) { // dial opens a WebSocket to path on ep with the given subprotocol. func dial(ctx context.Context, ep Endpoint, path, subprotocol string) (*websocket.Conn, error) { - ws, _, err := websocket.Dial(ctx, ep.url(path), &websocket.DialOptions{ + ws, resp, err := websocket.Dial(ctx, ep.url(path), &websocket.DialOptions{ HTTPClient: ep.httpClient(), Subprotocols: []string{subprotocol}, // Data connections are never compressed, and the control @@ -192,6 +194,18 @@ func dial(ctx context.Context, ep Endpoint, path, subprotocol string) (*websocke CompressionMode: websocket.CompressionDisabled, }) if err != nil { + if resp != nil && resp.StatusCode == http.StatusForbidden { + // A Rex server that doesn't let the caller in, such as a + // Tailscale user its access rules don't allow, says why, as + // {"error": "..."}. Another program's 403 is just not Rex. + var body struct { + Error string `json:"error"` + } + data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + if json.Unmarshal(data, &body) == nil && body.Error != "" { + return nil, &ForbiddenError{Endpoint: ep, Reason: body.Error} + } + } return nil, fmt.Errorf("rex: connect to %s: %w", ep, err) } if ws.Subprotocol() != subprotocol { @@ -201,6 +215,17 @@ func dial(ctx context.Context, ep Endpoint, path, subprotocol string) (*websocke return ws, nil } +// ForbiddenError is a Rex server that answered but didn't let this client +// in, such as a Tailscale user its access rules don't allow. +type ForbiddenError struct { + Endpoint Endpoint + Reason string // the server's +} + +func (e *ForbiddenError) Error() string { + return fmt.Sprintf("rex: %s didn't let this client in: %s", e.Endpoint, e.Reason) +} + // Welcome returns the server's welcome. func (c *Conn) Welcome() *Welcome { return &c.welcome } diff --git a/internal/rex/endpoint.go b/internal/rex/endpoint.go index 2e52a40..a10b9bb 100644 --- a/internal/rex/endpoint.go +++ b/internal/rex/endpoint.go @@ -211,6 +211,12 @@ func DialAny(ctx context.Context, eps []Endpoint, info ClientInfo) (*Conn, Endpo if err == nil { return c, ep, nil } + var forbidden *ForbiddenError + if errors.As(err, &forbidden) { + // A server is there and has said no: the other + // addresses would reach the same one. + return nil, Endpoint{}, err + } errs = append(errs, err) if ctx.Err() != nil { break diff --git a/internal/rex/endpoint_test.go b/internal/rex/endpoint_test.go index b12ab95..c006615 100644 --- a/internal/rex/endpoint_test.go +++ b/internal/rex/endpoint_test.go @@ -1,7 +1,14 @@ package rex_test import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" "reflect" + "strconv" + "strings" "testing" "100gex/internal/rex" @@ -47,3 +54,33 @@ func TestCandidates(t *testing.T) { t.Errorf("String() = %q", got) } } + +// TestForbidden checks a 403 with Rex's {"error": ...} reads as a server +// that refused, and any other 403 as no Rex server at all. +func TestForbidden(t *testing.T) { + rexLike := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(`{"error": "tailnet user bob@example.com is not allowed"}`)) + })) + defer rexLike.Close() + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + })) + defer other.Close() + + ep := func(s *httptest.Server) rex.Endpoint { + u, _ := url.Parse(s.URL) + port, _ := strconv.Atoi(u.Port()) + return rex.Endpoint{Host: u.Hostname(), Port: port} + } + _, err := rex.Dial(context.Background(), ep(rexLike), rex.ClientInfo{}) + var forbidden *rex.ForbiddenError + if !errors.As(err, &forbidden) || !strings.Contains(forbidden.Reason, "bob@example.com") { + t.Errorf("Rex's 403: %v, want a ForbiddenError with its reason", err) + } + _, err = rex.Dial(context.Background(), ep(other), rex.ClientInfo{}) + if err == nil || errors.As(err, &forbidden) { + t.Errorf("another program's 403: %v, want a plain failure", err) + } +} diff --git a/internal/tailnet/tailnet.go b/internal/tailnet/tailnet.go index 8771878..00a5ee3 100644 --- a/internal/tailnet/tailnet.go +++ b/internal/tailnet/tailnet.go @@ -217,6 +217,10 @@ func Probe(ctx context.Context, address string) (rex.Endpoint, error) { ctx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() c, ep, err := rex.DialAny(ctx, eps, rex.ClientInfo{Kind: "app", Name: "100gex (looking for Rex)"}) + var forbidden *rex.ForbiddenError + if errors.As(err, &forbidden) { + return rex.Endpoint{}, err // a server, which said no + } if err != nil { return rex.Endpoint{}, fmt.Errorf("%w at %s: %v", ErrNoRex, address, err) } diff --git a/internal/ui/actions.go b/internal/ui/actions.go index 481512c..1075c89 100644 --- a/internal/ui/actions.go +++ b/internal/ui/actions.go @@ -138,6 +138,14 @@ var actions = func() map[string]action { u.palette.toggle(paletteSessions) return nil }, true}, + {info("client.host.switch", "Switch Host", "Host"), func(u *UI, _ actionArgs) error { + u.openPalette(paletteHosts) + return nil + }, true}, + {info("client.host.add", "Add Remote Host…", "Host"), func(u *UI, _ actionArgs) error { + u.openPalette(paletteMachines) + return nil + }, true}, {info("session.new", "New Session", "Session"), func(u *UI, _ actionArgs) error { u.ws.NewSession() return nil diff --git a/internal/ui/hostpicker.go b/internal/ui/hostpicker.go new file mode 100644 index 0000000..e05d697 --- /dev/null +++ b/internal/ui/hostpicker.go @@ -0,0 +1,189 @@ +package ui + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "100gex/internal/hosts" + "100gex/internal/rex" + "100gex/internal/tailnet" +) + +// Hosts and tailnet machines, for the server chip's card and the palette. + +// localTarget is what reaches the local server. +const localTarget = "" + +// fetchSaved asks the local server for the saved hosts, for the chip's card +// and the palette's host list. +func (u *UI) fetchSaved() { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + saved, err := hosts.Saved(ctx) + u.mu.Lock() + u.server.saved, u.server.savedErr = saved, err + u.mu.Unlock() + u.notify() + }() +} + +// hostItems lists the hosts to switch to: this machine, then the saved +// hosts, then a way to add one. The server shown, reached by target and +// called label, is marked current. +func hostItems(saved []rex.Host, target, label string) []paletteItem { + items := []paletteItem{{ + title: "This machine", + detail: "local", + host: true, + target: localTarget, + current: target == localTarget, + }} + sort.Slice(saved, func(i, j int) bool { return saved[i].Label < saved[j].Label }) + for _, h := range saved { + detail := "" + if len(h.Endpoints) > 0 { + detail = h.Endpoints[0] + } + items = append(items, paletteItem{ + title: h.Label, + detail: detail, + host: true, + target: h.Label, + current: label != "" && label == h.Label, + }) + } + return append(items, paletteItem{title: "Add host…", detail: "from your tailnet", action: "client.host.add"}) +} + +// machineItems lists the tailnet's machines: this one, then those online, +// then the rest, each by name. +func machineItems(ms []tailnet.Machine) []paletteItem { + sort.SliceStable(ms, func(i, j int) bool { + rank := func(m tailnet.Machine) int { + switch { + case m.ThisMachine: + return 0 + case m.Online: + return 1 + } + return 2 + } + return rank(ms[i]) < rank(ms[j]) + }) + items := make([]paletteItem, 0, len(ms)) + for i := range ms { + m := ms[i] + detail := m.OSName() + switch { + case m.ThisMachine: + detail = "this machine" + case !m.Online: + detail += " · offline" + } + items = append(items, paletteItem{title: m.Name, detail: detail, machine: &m}) + } + return items +} + +// loadPalette fetches what a host or machine list shows, in the +// background, and hands it to the palette. +func (u *UI) loadPalette(mode paletteMode) { + target, label := u.srv.target, u.srv.label // read here, on the drawing goroutine + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + var items []paletteItem + var err error + switch mode { + case paletteHosts: + var saved []rex.Host + saved, err = hosts.Saved(ctx) + if err != nil { + // Without the local server there are no saved hosts, + // but switching back to it, or adding one, still works. + err = nil + } + items = hostItems(saved, target, label) + case paletteMachines: + var ms []tailnet.Machine + ms, err = tailnet.Machines(ctx) + items = machineItems(ms) + } + u.mu.Lock() + u.paletteLoaded = &paletteLoad{mode: mode, items: items, err: err} + u.mu.Unlock() + u.notify() + }() +} + +// paletteLoad is a list loaded for the palette. +type paletteLoad struct { + mode paletteMode + items []paletteItem + err error +} + +// addMachine looks for a Rex server on a tailnet machine. If one answers, +// it saves the machine as a host, named as the tailnet names it, and +// switches to it. The palette says what's happening meanwhile. +func (u *UI) addMachine(m tailnet.Machine) { + if m.ThisMachine { + u.palette.close() + u.Connect(localTarget) + return + } + u.palette.status, u.palette.statusErr = fmt.Sprintf("Looking for Rex on %s…", m.Name), false + go func() { + _, err := tailnet.Probe(context.Background(), m.Address) + u.mu.Lock() + defer u.mu.Unlock() + if err != nil { + msg := fmt.Sprintf("No Rex server answered on %s.", m.Name) + var forbidden *rex.ForbiddenError + switch { + case !m.Online: + msg = fmt.Sprintf("%s is offline.", m.Name) + case errors.As(err, &forbidden): + msg = fmt.Sprintf("%s's Rex server didn't let this device in: %s.", m.Name, forbidden.Reason) + case errors.Is(err, tailnet.ErrNoRex): + msg += " On it, run rex server tailscale enable." + } + u.paletteStatus = &paletteStatus{text: msg, err: true} + u.notify() + return + } + u.paletteStatus = &paletteStatus{text: "", done: true, machine: m} + u.notify() + }() +} + +// paletteStatus is news for the palette from a goroutine. +type paletteStatus struct { + text string + err bool + done bool // the machine has a Rex server: save it and switch + machine tailnet.Machine // the machine, when done +} + +// finishAddMachine saves a machine found to run Rex, and switches to it. +func (u *UI) finishAddMachine(m tailnet.Machine) { + u.palette.close() + target := m.Address + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := hosts.Save(ctx, m.Name, m.Address); err != nil { + u.report(fmt.Errorf("save host %s: %w", m.Name, err)) + } + }() + u.Connect(target) + u.mu.Lock() + if u.connecting != nil { + u.connecting.label = m.Name + } + u.mu.Unlock() +} diff --git a/internal/ui/palette.go b/internal/ui/palette.go index a971327..2884fe8 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -16,6 +16,7 @@ import ( "gioui.org/widget" "gioui.org/widget/material" + "100gex/internal/tailnet" "100gex/internal/theme" ) @@ -25,6 +26,8 @@ type paletteMode int const ( paletteCommands paletteMode = iota // every action paletteSessions // the server's sessions + paletteHosts // this machine and the saved hosts + paletteMachines // the tailnet's machines, to add as hosts ) // paletteItem is one line of the palette. @@ -34,7 +37,10 @@ type paletteItem struct { keys string // the shortcut, if any action string // the action to run, for commands session string // the session to switch to, for sessions - current bool // the session shown now + host bool // switch to target, for hosts + target string // what reaches the host: "" for this machine + machine *tailnet.Machine + current bool // the session or host shown now haystack string // what a search matches against, lower case } @@ -52,6 +58,11 @@ type palette struct { query string focus bool // ask for keyboard focus on the next frame backdrop struct{} + + loading bool // the list is still being fetched + loadErr error // why it couldn't be + status string // news about the item chosen, such as a host being looked for + statusErr bool } func (p *palette) toggle(mode paletteMode) { @@ -64,6 +75,17 @@ func (p *palette) toggle(mode paletteMode) { p.editor.SetText("") p.query, p.items = "\x00", nil // rebuilt on the next frame p.list.Axis = layout.Vertical + p.loading, p.loadErr, p.status, p.statusErr = false, nil, "", false +} + +// openPalette opens the palette in a mode, fetching what it lists if that +// takes a while. +func (u *UI) openPalette(mode paletteMode) { + u.palette.toggle(mode) + if u.palette.open && (mode == paletteHosts || mode == paletteMachines) { + u.palette.loading = true + u.loadPalette(mode) + } } func (p *palette) close() { @@ -198,7 +220,29 @@ func (u *UI) layoutPalette(gtx layout.Context) { if !p.open { return } - if p.items == nil { + u.mu.Lock() + loaded, status := u.paletteLoaded, u.paletteStatus + u.paletteLoaded, u.paletteStatus = nil, nil + u.mu.Unlock() + if loaded != nil && loaded.mode == p.mode && p.loading { + p.loading, p.loadErr = false, loaded.err + p.items, p.query = loaded.items, "\x00" + for i, it := range p.items { + if it.current { + p.selected = i + } + } + } + if status != nil { + if status.done { + u.finishAddMachine(status.machine) + return + } + p.status, p.statusErr = status.text, status.err + } + if p.loading { + // Nothing to list until the fetch is back. + } else if p.items == nil { if p.mode == paletteSessions { p.items = u.sessionItems() for i, it := range p.items { @@ -290,8 +334,13 @@ func (u *UI) layoutPalette(gtx layout.Context) { } title, hint := "Commands", "Run a command…" - if p.mode == paletteSessions { + switch p.mode { + case paletteSessions: title, hint = "Sessions", "Go to a session…" + case paletteHosts: + title, hint = "Hosts", "Switch to a host…" + case paletteMachines: + title, hint = "Add a host", "Find a machine on your tailnet…" } theme.Box{Fill: theme.White, Shadow: theme.ShadowLarge, Padding: layout.UniformInset(16)}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { // Swallow clicks on the palette, so they don't reach the backdrop. @@ -312,8 +361,25 @@ func (u *UI) layoutPalette(gtx layout.Context) { return e.Layout(gtx) }) }), - layout.Rigid(layout.Spacer{Height: 12}.Layout), layout.Rigid(func(gtx layout.Context) layout.Dimensions { + text, c := p.status, theme.Ink + switch { + case p.loading: + text, c = "Loading…", theme.Muted + case p.loadErr != nil: + text, c = p.loadErr.Error(), theme.Red + case p.statusErr: + c = theme.Red + } + if text == "" { + return layout.Spacer{Height: 12}.Layout(gtx) + } + return layout.Inset{Top: 10, Bottom: 10}.Layout(gtx, u.theme.Label(13, text, c, font.SemiBold).Layout) + }), + layout.Rigid(func(gtx layout.Context) layout.Dimensions { + if p.loading { + return layout.Dimensions{} + } return u.layoutPaletteList(gtx) }), ) @@ -388,8 +454,17 @@ func (u *UI) choose() { return } it := p.items[p.shown[p.selected]] + if it.machine != nil { + // The palette stays open, saying what it finds. + u.addMachine(*it.machine) + return + } p.close() switch { + case it.host: + if !it.current { + u.Connect(it.target) + } case it.session != "": u.ws.Switch(it.session) case it.action != "": diff --git a/internal/ui/server.go b/internal/ui/server.go index 4a56fd6..35512b4 100644 --- a/internal/ui/server.go +++ b/internal/ui/server.go @@ -33,9 +33,14 @@ type serverChip struct { backdrop struct{} card struct{} - // Fetched once, in the background; guarded by UI.mu. - version string - account string + // Fetched in the background; guarded by UI.mu. + version string + account string + saved []rex.Host // the local server's hosts + savedErr error + + hostClicks map[string]*widget.Clickable // by target + addHost widget.Clickable } // fetchServerDetails asks the server for what the chip's card shows that @@ -114,10 +119,21 @@ var chipTagNudge unit.Dp = 2 func (u *UI) layoutServerChip(gtx layout.Context) layout.Dimensions { if u.server.click.Clicked(gtx) { u.server.open = !u.server.open + if u.server.open { + u.fetchSaved() + } } name, where := u.serverName() tag, tagFill, tagFg := strings.ToUpper(where), theme.Yellow, theme.Ink - if !u.connected() { + state, connectErr := u.connectState() + switch { + case state == "reconnecting": + tag, tagFill, tagFg = "RECONNECTING", theme.Lavender, theme.Ink + case state != "" && connectErr != nil: + tag, tagFill, tagFg = "FAILED", theme.Red, theme.White + case state != "": + tag, tagFill, tagFg = "CONNECTING", theme.Lavender, theme.Ink + case !u.connected(): tag, tagFill, tagFg = "OFFLINE", theme.Red, theme.White } bar := color.NRGBA{} @@ -211,6 +227,13 @@ func (u *UI) layoutServerCard(gtx layout.Context) { } } rows = append(rows, row{"Tailscale", tailscale}) + if state, err := u.connectState(); state != "" { + value := state + "…" + if err != nil { + value = "couldn't: " + err.Error() + } + rows = append([]row{{"Now", value}}, rows...) + } gtx.Constraints.Min = image.Point{} gtx.Constraints.Max.X = gtx.Dp(360) @@ -237,18 +260,91 @@ func (u *UI) layoutServerCard(gtx layout.Context) { }), layout.Flexed(1, func(gtx layout.Context) layout.Dimensions { c := theme.Ink - if r.label == "Connection" && !u.connected() { + if (r.label == "Connection" && !u.connected()) || strings.HasPrefix(r.value, "couldn't") { c = theme.Red } - return u.theme.Label(13, r.value, c, font.SemiBold).Layout(gtx) + l := u.theme.Label(13, r.value, c, font.SemiBold) + l.MaxLines = 3 + return l.Layout(gtx) }), ) }) })) } + children = append(children, u.hostRows(gtx)...) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) }) } // serverCardTop is where the server card's top sits: just under the chip. const serverCardTop = theme.TitlebarHigh - 4 + +// hostRows lays out the card's list of hosts to switch to, with the one +// shown marked, and a button to add one from the tailnet. +func (u *UI) hostRows(gtx layout.Context) []layout.FlexChild { + if u.server.addHost.Clicked(gtx) { + u.server.open = false + u.openPalette(paletteMachines) + } + u.mu.Lock() + saved := append([]rex.Host(nil), u.server.saved...) + u.mu.Unlock() + items := hostItems(saved, u.srv.target, u.srv.label) + items = items[:len(items)-1] // the card has a button to add a host + if u.server.hostClicks == nil { + u.server.hostClicks = make(map[string]*widget.Clickable) + } + rows := []layout.FlexChild{ + layout.Rigid(func(gtx layout.Context) layout.Dimensions { + return layout.Inset{Top: 10, Bottom: 8}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + return theme.Highlighted(gtx, u.theme.Display(16, "Hosts", theme.Ink)) + }) + }), + } + for _, it := range items { + click := u.server.hostClicks[it.target] + if click == nil { + click = new(widget.Clickable) + u.server.hostClicks[it.target] = click + } + if click.Clicked(gtx) && !it.current { + u.server.open = false + u.Connect(it.target) + } + rows = append(rows, layout.Rigid(func(gtx layout.Context) layout.Dimensions { + return layout.Inset{Bottom: 6}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + return click.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + content := func(gtx layout.Context) layout.Dimensions { + weight := font.Medium + if it.current { + weight = font.Bold + } + return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, + layout.Rigid(u.theme.Label(13, it.title, theme.Ink, weight).Layout), + layout.Rigid(layout.Spacer{Width: 8}.Layout), + layout.Flexed(1, u.theme.Label(11, it.detail, theme.Muted, font.Normal).Layout), + ) + } + padding := layout.Inset{Top: 5, Bottom: 5, Left: 10, Right: 8} + if it.current { + return theme.Box{Fill: theme.White, Accent: theme.Purple, Padding: padding}.Layout(gtx, content) + } + padding.Left += theme.AccentWide + m := op.Record(gtx.Ops) + dims := padding.Layout(gtx, content) + call := m.Stop() + if click.Hovered() { + theme.Fill(gtx, theme.Hover, image.Rectangle{Max: dims.Size}) + } + call.Add(gtx.Ops) + return dims + }) + }) + })) + } + rows = append(rows, layout.Rigid(func(gtx layout.Context) layout.Dimensions { + return layout.Inset{Top: 6}.Layout(gtx, theme.Button{Theme: u.theme, Clickable: &u.server.addHost, Label: "Add host…"}.Layout) + })) + return rows +} diff --git a/internal/ui/servers.go b/internal/ui/servers.go index 3aa9af1..6891eef 100644 --- a/internal/ui/servers.go +++ b/internal/ui/servers.go @@ -24,6 +24,7 @@ type server struct { // connecting is a switch to another server, or a reconnect, under way. type connecting struct { target string + label string // what to call the server, if target doesn't say reconnect bool err error // why the last attempt failed } @@ -104,6 +105,9 @@ func (u *UI) dial(c *connecting, session string) { u.notify() return } + if label == "" { + label = c.label + } u.next = &server{conn: conn, ws: ws, label: label, target: c.target} u.notify() } diff --git a/internal/ui/servers_test.go b/internal/ui/servers_test.go index a743531..a0861ee 100644 --- a/internal/ui/servers_test.go +++ b/internal/ui/servers_test.go @@ -1,12 +1,17 @@ package ui import ( + "context" "errors" + "strconv" + "strings" "testing" + "100gex/internal/hosts" "100gex/internal/rex" "100gex/internal/rex/rextest" "100gex/internal/rexsession" + "100gex/internal/tailnet" ) // TestSwitchServer switches the window to another server, which shows its @@ -61,3 +66,59 @@ func TestReconnect(t *testing.T) { t.Error("not connected after reconnecting") } } + +// TestAddHost adds a machine as a host, as the host picker does once a +// person chooses one from the tailnet, and switches back with the hosts +// list. The machine is a server's network listener, standing in for a +// tailnet address. +func TestAddHost(t *testing.T) { + local := rextest.Start(t) + t.Setenv(rex.ServerEnv, local.Endpoint.String()) // where hosts are kept + port := rextest.FreePort(t) + studio := rextest.StartArgs(t, "", "--extra-listen", "http://127.0.0.1:"+strconv.Itoa(port), "--allow-anonymous") + sidLocal, _ := rextest.NewSession(t, local.Dial(t, "setup"), rextest.RawCat...) + sidStudio, _ := rextest.NewSession(t, studio.Dial(t, "setup"), rextest.RawCat...) + + h := startUI(t, local, local.Dial(t, "100gex-test"), sidLocal) + h.u.SetTarget("", "") // the local server + h.until("the local session", func(f rexsession.Frame) bool { return f.View.SessionID == sidLocal && f.Ready() }) + + // A machine with no Rex server says so, and the window stays. + h.u.palette.toggle(paletteMachines) + h.u.addMachine(tailnet.Machine{Name: "attic", Address: "127.0.0.1:" + strconv.Itoa(rextest.FreePort(t)), Online: true}) + h.until("the palette to say there's no Rex", func(rexsession.Frame) bool { + return h.u.palette.statusErr && strings.Contains(h.u.palette.status, "No Rex server answered on attic") + }) + + // A machine with one is saved as a host, and the window switches to it. + h.u.addMachine(tailnet.Machine{Name: "studio", Address: "127.0.0.1:" + strconv.Itoa(port), Online: true}) + h.until("studio's session", func(f rexsession.Frame) bool { return f.View.SessionID == sidStudio && f.Ready() }) + if name, where := h.u.serverName(); name != "studio" || where != "remote" { + t.Errorf("server chip says %s, %s; want studio, remote", name, where) + } + if h.u.palette.open { + t.Error("the palette is still open after switching") + } + h.until("studio to be saved", func(rexsession.Frame) bool { + saved, err := hosts.Saved(context.Background()) + return err == nil && len(saved) == 1 && saved[0].Label == "studio" + }) + + // The hosts list marks studio, and switches back to this machine. + h.u.openPalette(paletteHosts) + h.until("the hosts", func(rexsession.Frame) bool { return !h.u.palette.loading && len(h.u.palette.shown) == 3 }) + var titles []string + for _, i := range h.u.palette.shown { + it := h.u.palette.items[i] + titles = append(titles, it.title) + if it.current != (it.title == "studio") { + t.Errorf("host %s: current = %v", it.title, it.current) + } + } + if strings.Join(titles, ",") != "This machine,studio,Add host…" { + t.Errorf("hosts = %v", titles) + } + h.u.palette.selected = 0 + h.u.choose() + h.until("this machine again", func(f rexsession.Frame) bool { return f.View.SessionID == sidLocal && f.Ready() }) +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 1f8c1db..aa879e5 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -101,7 +101,9 @@ type UI struct { watched *server // the server whose events count next *server // connected, waiting to be shown connecting *connecting - newKeymapConn *rex.Conn // the connection newKeymap came from + paletteLoaded *paletteLoad // a list fetched for the palette + paletteStatus *paletteStatus // news for the palette + newKeymapConn *rex.Conn // the connection newKeymap came from newKeymap *keymap.Keymap newServerActions map[string]rex.ActionInfo newBindings []rex.KeyBinding -- knotmirror 0.0.1