// Package gui hosts the desktop app: a tray panel and a regular window that // share one small web UI. The UI talks to Go over a tiny JSON API served by // the same handler that serves the static assets, so no binding generator or // bundler is involved. package gui import ( "bytes" "cmp" "context" "crypto/sha256" "embed" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "maps" "mime" "net/http" "os" "path" "path/filepath" "regexp" "runtime" "slices" "strconv" "strings" "sync" "time" "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/autostart" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/fonts" "github.com/yetone/magpie/internal/fx" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/library" "github.com/yetone/magpie/internal/mcpauth" "github.com/yetone/magpie/internal/middleware" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/profile" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/redact" "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/update" "github.com/yetone/magpie/internal/usage" ) // cliBehind is the terminal's magpie command when it's a copied file rather // than the installer's link — a copy can't follow updates (#531's lesson) — // told once, and only until the user dismisses it for this version. The // check is a bare Lstat: telling a *stale* copy from a current one would // mean running the old binary, and `magpie version` isn't read-only — it // migrates the user's settings first, with the old build's migrations. Only // `magpie update`, which the user started, reads versions (update.StaleCLI). // "" when the command is the link or absent, this isn't the Mac, or the // advice was dismissed for this version. func cliBehind() string { cliBehindOnce.Do(func() { cli := update.CopiedCLI() if cli == "" { return } if cliQuiet() { return } cliBehindMu.Lock() cliBehindVal = tilde(cli) cliBehindMu.Unlock() }) cliBehindMu.Lock() defer cliBehindMu.Unlock() return cliBehindVal } // cliQuiet is whether the advice was dismissed for this version; the // dismiss is kept per version, so the next app update asks once more. // cliQuietFile holds the version it was dismissed at. const cliQuietFile = "cli-behind-quiet" func cliQuiet() bool { b, err := os.ReadFile(filepath.Join(settings.Dir(), cliQuietFile)) return err == nil && strings.TrimSpace(string(b)) == Version } // setCLIQuiet dismisses the advice until the next version. func setCLIQuiet() error { if err := os.MkdirAll(settings.Dir(), 0o755); err != nil { return err } return os.WriteFile(filepath.Join(settings.Dir(), cliQuietFile), []byte(Version+"\n"), 0o644) } // cliBehindRoutes serves the advice's "Hide until the next version". func cliBehindRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/cli-behind/quiet", func(rw http.ResponseWriter, r *http.Request) { if err := setCLIQuiet(); err != nil { fail(rw, err) return } cliBehindMu.Lock() cliBehindVal = "" // kept away until the next version; the Once already ran cliBehindMu.Unlock() rw.WriteHeader(http.StatusNoContent) }) // Settings' Command line: what `magpie` runs in each shell, and this // app's put there when asked (update.AddCLI); shell names the one whose // profile gets ~/.local/bin mux.HandleFunc("GET /api/cli", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, update.ReadCLI()) }) mux.HandleFunc("POST /api/cli", func(rw http.ResponseWriter, r *http.Request) { var in struct { Shell string `json:"shell"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) return } v, err := update.AddCLI(in.Shell) if err != nil { fail(rw, err) return } writeJSON(rw, v) }) } var cliBehindOnce = new(sync.Once) // a var so tests can ask again var cliBehindMu sync.Mutex // the dismiss handler writes cliBehindVal while state() reads it on other goroutines var cliBehindVal string // Version is the build's version string, shown in Settings. var Version = "dev" //go:embed assets var assets embed.FS // Windows is what the API needs from the host application. type Windows interface { HidePanel() // ShowMain brings the window up, on the named tab when view is set. ShowMain(view string) Quit() // OpenURL hands a link to the system browser. The error is the browser's // not starting, which a sign-in shows with its link (#2043). OpenURL(url string) error // OpenFolder shows a folder in the system file manager. OpenFolder(path string) error // ChooseFolder asks for a folder in the system's picker: "" when the // user cancels it. ChooseFolder(title string) (string, error) // Copy puts text on the system clipboard, which the page's own // navigator.clipboard can't always reach from inside the app. Copy(text string) bool // FitPanel asks for the panel to be tall enough for its content. FitPanel(height int, g Glide) // TintPanel paints the panel's tint behind the page, where the system // keeps up with the panel's size; false when it can't, for the page to // go on painting it itself. TintPanel(rgba [4]uint8, ms int) bool // TintTitleBar paints the window's title bar the page's colour, where // the system draws one (Windows); false where there is none to paint. TintTitleBar(rgba [4]uint8, dark bool) bool // SetTextSize zooms the window's and the panel's pages to percent // (settings.TextSizes), the panel's size with them. SetTextSize(percent int) } type fieldJSON struct { Key string `json:"key"` Label string `json:"label"` Value string `json:"value"` Options []agent.Option `json:"options"` } type agentJSON struct { ID string `json:"id"` Name string `json:"name"` Icon string `json:"icon"` Path string `json:"path"` Fields []fieldJSON `json:"fields"` // Drift: its config no longer does what magpie set, and how to set it again Drift *agent.Drift `json:"drift,omitempty"` // Wired: magpie is in its config, which its menu's Disconnect takes out Wired bool `json:"wired,omitempty"` // Import: an app that takes magpie by its own link (Cindy), and // whether it has magpie already; omitted when the app has no status reader Import string `json:"import,omitempty"` Added *bool `json:"added,omitempty"` // Launch: the command that starts an agent taking the gateway only // from its environment (agy) on magpie, to copy Launch string `json:"launch,omitempty"` // Typed: what starts it on magpie typed in a new terminal, a function // magpie gave the user's shells (agy); the launch is for one open now Typed string `json:"typed,omitempty"` // Models: how many of the catalog its lists show, for an agent that // picks among it (agent_models.go) Models *modelCountJSON `json:"models,omitempty"` // Menu: its own model menu is the models picked here, no one model to // start on (agent.ListsModels): ZCode's, Cursor Private Inference's Menu bool `json:"menu,omitempty"` // NoNames: its own list doesn't name magpie's models as Names in agents' // lists says (agent.NoNames), for that setting to say so NoNames bool `json:"noNames,omitempty"` // Source: what an agent not connected runs on now (agent.Source), and // Stale: copies of a connected one still running on the list they // started with (agent.Stale), for the line under its name Source string `json:"source,omitempty"` Stale int `json:"stale,omitempty"` // StaleCopies: those copies, each with what it is and when it // started, for the opened row to say which is left to reopen and how StaleCopies []agent.StaleCopy `json:"staleCopies,omitempty"` // AppRestart: its desktop app (Claude Desktop, WorkBuddy) running on // what it read before magpie's last change, for the row's Restart // (agent.AppBehind) AppRestart *agent.AppRun `json:"appRestart,omitempty"` // Joined: connected with its own models still in its list (Codex // signed in with ChatGPT, agent.Agent.Join) Joined bool `json:"joined,omitempty"` // AppOut: magpie is Codex's provider while the ChatGPT account it is // signed in to is used up (agent.Agent.AppOut), which turns the Codex // app's ChatGPT side off until the reset AppOut *appOutJSON `json:"appOut,omitempty"` // Failover: not connected, yet its requests go through magpie for // account failover alone (agent.Agent.FailingOver, #1385) Failover bool `json:"failover,omitempty"` // CLIMissing: its settings are here, its CLI isn't (#843), which // the row says with none of its settings offered (#2177), and Install // another agent offers it again where magpie knows how CLIMissing bool `json:"cliMissing,omitempty"` Native *agent.NativeState `json:"native,omitempty"` } // clientJSON is an agent, or another client the gateway knows, as a // request from it is drawn. type clientJSON struct { ID string `json:"id"` Name string `json:"name"` Icon string `json:"icon"` } type profileJSON struct { Name string `json:"name"` Summary string `json:"summary"` // Library is what the profile gives out from the library, for one // saved with its setup Library *profileLibraryJSON `json:"library,omitempty"` // Agents is what it holds, by agent, to be read before it is applied // (#467); a value that reads as a key or a token is left out Agents []profile.Group `json:"agents"` // InUse: the setup is this profile now, applying it would change // nothing (profile.InUse); the page marks it so (superhtoooth on X: // nothing said which profile was in use) InUse bool `json:"inUse,omitempty"` } type profileLibraryJSON struct { Servers int `json:"servers"` // given to at least one agent Skills int `json:"skills"` // given to at least one agent Instructions bool `json:"instructions"` // some agent gets them } type stateJSON struct { Agents []agentJSON `json:"agents"` Clients []clientJSON `json:"clients"` // who a request may come from, by id Profiles []profileJSON `json:"profiles"` Catalog string `json:"catalog"` Notice string `json:"notice,omitempty"` // advice after a change, e.g. "restart Codex" // Connected is how the 「接入」 switch chose the model the agent starts // on, in the answer to agents/connect (agent.Connection) Connected *agent.Connection `json:"connected,omitempty"` // CLIBehind is the terminal's magpie command, told to the user when // it's a copied file rather than the installer's link: a copy can't // follow updates (#531's lesson). "" when it's the link or absent, or // the advice was dismissed for this version. CLIBehind string `json:"cliBehind,omitempty"` Settings settings.Settings `json:"settings"` // FX is the dollar-to-yuan rate the cny currency choice shows costs at, // here too (not only in settingsJSON) so a cost drawn before the reader // ever opens Settings already converts, if cny was chosen last time. FX fxJSON `json:"fx"` // Unlisted are the models kept for routing groups, which the pickers // don't offer: a filter that finds one of them says why it isn't there Unlisted []unlistedJSON `json:"unlisted,omitempty"` // Recovered are magpie's files a crash left unreadable (all zero, // #1505) that were read from their last good generation: the page // tells the user once each Recovered []lastgood.Note `json:"recovered,omitempty"` // Last: this is the state kept from the last read (laststate.go), for // the page to draw while the fresh one is read Last bool `json:"last,omitempty"` // Served is how many models magpie serves, groups left out: the Get // started card's first step ("add a model source") is done once // there is one, agents found or not Served int `json:"served"` } // unlistedJSON is a model of a provider kept for routing groups, and the // groups ("group/") it is used through, none when it is in no group. type unlistedJSON struct { ID string `json:"id"` Name string `json:"name"` Provider string `json:"provider"` Icon string `json:"icon,omitempty"` Groups []string `json:"groups"` } // unlistedModels lists provider.Unlisted for the page. func unlistedModels() []unlistedJSON { es := provider.Unlisted() if len(es) == 0 { return nil } in := provider.MemberGroups() out := make([]unlistedJSON, 0, len(es)) for _, e := range es { gs := in[e.ID] if gs == nil { gs = []string{} } out = append(out, unlistedJSON{ID: e.ID, Name: e.Name, Provider: e.Provider.Name, Icon: e.Provider.Icon, Groups: gs}) } return out } // fxJSON is a USD→CNY rate as the UI shows it: the number a cost is // multiplied by, when it was last learned (unset for Fallback, never // learned from anywhere), and whether that's stale — the Settings page's // currency row puts these in its tooltip. type fxJSON struct { Rate float64 `json:"rate"` At *time.Time `json:"at,omitempty"` Stale bool `json:"stale"` } // currentFX is the rate known now, never waited for: a stale one is asked // for behind it and shown on the next look (#541: the state waited up to // 4s on the network after each TTL, at every morning's start-up). func currentFX() fxJSON { r := fx.Soon() out := fxJSON{Rate: r.CNYPerUSD, Stale: r.Stale()} if !r.At.IsZero() { at := r.At out.At = &at } return out } // settingsJSON is the Settings page: the two choices plus the facts it shows. type settingsJSON struct { settings.Settings Version string `json:"version"` Dir string `json:"dir"` // where magpie keeps its files, as shown Gateway string `json:"gateway"` // the local endpoint // Builtins are the built-in plugins: each one's switch, whether it // runs and what of it is in use (builtins.go) Builtins []builtinJSON `json:"builtins"` // JSRoutings are the routings JS gateway plugins serve now // ("/"), for the routing pickers JSRoutings []middleware.Routing `json:"jsRoutings"` // PublicURL is MAGPIE_PUBLIC_URL while other machines are let in // (shared, or MAGPIE_ADDR on the network): where they reach the // gateway, shown beside the local address agents here are pointed at // (#1551) PublicURL string `json:"publicURL,omitempty"` // MAGPIE_ADDR, when it sets the gateway's address over Settings' port AddrEnv string `json:"addrEnv,omitempty"` // MAGPIE_ALLOW_IPS, when it sets the allow list over Settings', and // the list it sets; OnNetwork: MAGPIE_ADDR listens on the network, so // the list is shown even while sharing is off AllowIPsEnv string `json:"allowIPsEnv,omitempty"` AllowIPsFromEnv []string `json:"allowIPsFromEnv,omitempty"` OnNetwork bool `json:"onNetwork,omitempty"` // Dir is the data folder beside a portable magpie (#508) Portable bool `json:"portable,omitempty"` // WSL is whether there is WSL to look in for agents (Windows), for // Settings' Detect agents in WSL (#1264) WSL bool `json:"wsl,omitempty"` // Rekeyed is what an agent beyond loopback, given the sharing key, // couldn't be set again with when sharing changed (agent.Rekey) Rekeyed string `json:"rekeyed,omitempty"` // Notice is a Settings row's warning when a setting can't take effect: // the Codex subagents row when Codex's own multi_agent_v2 is on in the // config magpie routes (#141) Notice string `json:"notice,omitempty"` // Mac apps that explicitly handle .command files, for resumed sessions. TerminalApps []terminalChoice `json:"terminalApps,omitempty"` TerminalDefault string `json:"terminalDefault,omitempty"` OTelEnv bool `json:"otelEnv,omitempty"` // NoAccountsEnv is MAGPIE_NO_ACCOUNTS set, which keeps account // discovery off for this run whatever Settings has (#1535) NoAccountsEnv bool `json:"noAccountsEnv,omitempty"` // whether the page is in gateway mode and why (gatewayMode); Web says // it is served by magpie web, where the mode can be set GatewayOn bool `json:"gatewayOn,omitempty"` GatewayWhy string `json:"gatewayWhy,omitempty"` Web bool `json:"web,omitempty"` // NoVideo: this app's webview would crash on a