Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227package cli
import ( "context" "fmt" "net" "net/url" "os" "os/exec" "path/filepath" "slices" "strconv" "strings" "syscall" "time"
"albedo/cli/internal/config" "albedo/cli/internal/daemon" "albedo/cli/internal/qr" "albedo/cli/internal/webui"
"github.com/spf13/cobra")
func backgroundWeb(cmd *cobra.Command, deps Dependencies, options webui.Options, save, stop, rotate, noOpen bool) error { home := config.HomeDir() if err := os.MkdirAll(home, 0o700); err != nil { return err } manifest, manifestErr := webui.ReadManifest(webui.ManifestPath()) alive := manifestErr == nil && webui.ManifestAlive(manifest) running := manifest.Options if alive && !stop { if cmd.Flags().Changed("port") && options.Port != running.Port || cmd.Flags().Changed("local") && options.Local != running.Local || cmd.Flags().Changed("public-url") && options.Public != running.Public || cmd.Flags().Changed("tailnet-https") && options.TailnetHTTPS != running.TailnetHTTPS || (cmd.Flags().Changed("allow") || save) && !options.SameAllow(running) { return fmt.Errorf("albedo web is already serving with different options; run albedo web --stop first") } } if alive && (stop || rotate) { if err := stopWeb(manifest.PID); err != nil { return err } alive = false } if rotate && manifestErr == nil { // Restart how the last server was published, even if it died without // removing web.json: its tailscale handler still points at the port. options = manifest.Options } if stop { // A server that died without cleaning up left its handler behind. if manifest.TailnetHTTPS { releaseTailnet(cmd, manifest.Port) } _, err := fmt.Fprintln(cmd.OutOrStdout(), "albedo web is off") return err } if alive && save { conn, err := deps.Application.Connect(cmd.Context()) if err != nil { return err } settings, err := daemon.GetSettings(cmd.Context(), conn) if err != nil { return err } if err := daemon.SaveWebAllow(cmd.Context(), conn, settings.UI.ETag, options.Allow); err != nil { return err } } if !alive { if rotate { if err := os.Remove(webui.KeyPath()); err != nil && !os.IsNotExist(err) { return err } } executable, err := os.Executable() if err != nil { return err } args := serveArgs(options) if save { args = append(args, "--save") } logPath := filepath.Join(home, "web.log") log, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err != nil { return err } defer log.Close() child := exec.Command(executable, args...) child.SysProcAttr = &syscall.SysProcAttr{Setsid: true} child.Stdout, child.Stderr = log, log if err := child.Start(); err != nil { return err } done := make(chan error, 1) go func() { done <- child.Wait() }() ctx, cancel := context.WithTimeout(cmd.Context(), webGrace) defer cancel() ticker := time.NewTicker(25 * time.Millisecond) defer ticker.Stop() for { manifest, _ = webui.ReadManifest(webui.ManifestPath()) if manifest.PID == child.Process.Pid && webui.ManifestAlive(manifest) { break } select { case err := <-done: output, _ := os.ReadFile(logPath) return fmt.Errorf("web server did not start: %s (%v)", strings.TrimSpace(string(output)), err) case <-ctx.Done(): // Stopped rather than killed, so a tailscale handler it // created is removed on the way out. _ = stopWeb(child.Process.Pid) <-done return fmt.Errorf("web server startup: %w (check %s)", ctx.Err(), logPath) case <-ticker.C: } } } key, err := os.ReadFile(webui.KeyPath()) if err != nil { return err } return printWebLinks(cmd, deps, string(key), manifest, noOpen)}
// serveArgs is the command line that starts this server in the background, so// the child reaches the same networks and prints the same origin. A recorded// origin that no longer parses is left out, rather than handed to the child to// reject.func serveArgs(options webui.Options) []string { args := []string{"web", "--serve", "--no-open", "--port", strconv.Itoa(options.Port)} for _, network := range options.Allow { args = append(args, "--allow", network) } if options.Local { args = append(args, "--local") } switch public := options.PublicOrigin(); { case options.TailnetHTTPS: args = append(args, "--tailnet-https") case public != nil: args = append(args, "--public-url", public.String()) } return args}
// webGrace is how long a background server may take to start or stop: a claim// on tailscale serve runs up to five tailscale commands.const webGrace = 30 * time.Second
// stopWeb asks a web server to stop, waits while it removes its tailscale// handler and web.json, and kills it if it does not stop in time.func stopWeb(pid int) error { if err := syscall.Kill(pid, syscall.SIGTERM); err != nil { return err } until := time.Now().Add(webGrace) for syscall.Kill(pid, 0) == nil { if time.Now().After(until) { _ = syscall.Kill(pid, syscall.SIGKILL) return fmt.Errorf("web server %d did not stop, so it was killed", pid) } time.Sleep(25 * time.Millisecond) } return nil}
// releaseTailnet removes the tailscale serve handler for the listener on port,// even after Ctrl-C, and says so when it cannot.func releaseTailnet(cmd *cobra.Command, port int) { if err := webui.NewServe(port).Release(context.WithoutCancel(cmd.Context())); err != nil { fmt.Fprintf(cmd.ErrOrStderr(), "could not remove the tailscale serve handler: %v\n", err) }}
// printWebLinks prints the link that signs this machine in, the links other// devices reach the server by, and a QR code of the first of those.func printWebLinks(cmd *cobra.Command, deps Dependencies, key string, manifest webui.Manifest, noOpen bool) error { out := cmd.OutOrStdout() direct := func(host string) string { return webui.LaunchLink(&url.URL{Scheme: "http", Host: net.JoinHostPort(host, strconv.Itoa(manifest.Port))}, key) } link := direct("127.0.0.1") var reachable []string public := manifest.PublicOrigin() if public != nil { link = webui.LaunchLink(public, key) reachable = append(reachable, link) } if _, err := fmt.Fprintf(out, "albedo web is serving at %s\n", link); err != nil { return err } // A public origin on the tailnet's own name is this machine over https; its // direct http links would only lose the secure origin (notifications, // clipboard). tailnetPublic := public != nil && slices.Contains(manifest.Names, public.Hostname()) if len(manifest.Names) > 0 && !tailnetPublic { onTailnet := direct(manifest.Names[0]) fmt.Fprintf(out, " on your tailnet: %s\n", onTailnet) reachable = append(reachable, onTailnet) } for _, address := range manifest.Addresses { if tailnetPublic && webui.TailscaleNetwork.Contains(net.ParseIP(address)) { continue } shared := direct(address) fmt.Fprintf(out, " on the network: %s\n", shared) reachable = append(reachable, shared) } // Only a link another device can reach is worth scanning. if len(reachable) > 0 && deps.Terminal != nil && deps.Terminal.Capable { if code, err := qr.Encode(reachable[0]); err == nil { fmt.Fprintf(out, "\n%s", code.Render()) } } if !noOpen && deps.Terminal != nil && deps.Terminal.OpenBrowser != nil { deps.Terminal.OpenBrowser(link) } return nil}