// 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 ( "bufio" "bytes" "cmp" "context" "crypto/sha256" "embed" "encoding/hex" "encoding/json" "errors" "fmt" "io" "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/applog" "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/notices" "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/settingsapi" "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()) }) // Settings › About's Open-source licenses: the notices this binary // carries (notices.Text, THIRD_PARTY_NOTICES) mux.HandleFunc("GET /api/notices", func(rw http.ResponseWriter, r *http.Request) { writeJSON(rw, map[string]string{"text": notices.Text}) }) 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"` // Isolated: Claude Desktop's Claude Magpie app (#5671), only where it // can be (macOS): whether it is on, and the app Isolated *agent.DesktopIsolated `json:"isolated,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"` // AppBack: magpie gave Codex back its ChatGPT account at the reset // and left the Codex app on the app-server it started while magpie // was its provider, which shows no account or usage till it restarts // (provider.CodexAppBack), for the row's Restart AppBack bool `json:"appBack,omitempty"` // AppSnag: the Codex app showed its error page after magpie restarted // its app-server and magpie couldn't reopen it (provider.CodexAppSnagged) AppSnag bool `json:"appSnag,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"` // Command: the line that starts it (agentCommand), which its row menu // copies; Terminal: and opens in a terminal, this system having one Command string `json:"command,omitempty"` Terminal bool `json:"terminal,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"` // ConfigBlocked is the folder this user can't write that keeps magpie // from saving its files (a ~/.config sudo left root's), which the // window offers to make theirs again; "" when magpie can save ConfigBlocked string `json:"configBlocked,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"` // GatewayOther is a magpie of another version serving the gateway in // this one's place, which the Agents page says (gateway_older.go) GatewayOther *gatewaySkew `json:"gatewayOther,omitempty"` } // 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"` // PanelKeys is whether the quick panel's shortcut can be set here // (panelkey.go) PanelKeys panelKeysJSON `json:"panelKeys"` // 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"` // PublicKind is gateway.URLKind's of PublicURL: "local" (a private // network's address), "internet", or "" for a name; the page names // it by that, not as public whatever it is PublicKind string `json:"publicKind,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"` // Log is the log the desktop app writes (applog), as shown; "" for a // magpie writing none (magpie web) Log string `json:"log,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"` // the proxy vendor requests go through now, and where it came from: // settings, environment, system, off or none ProxyNow string `json:"proxyNow"` ProxySource string `json:"proxySource"` // whether magpie opens at login: the system's record, not a setting; // LoginAllow, the record is there but the user switched it off in // System Settings › Login Items, which is where it's allowed again Login bool `json:"login"` LoginAllow bool `json:"loginAllow,omitempty"` // the model that describes images when Vision names none, and those // that can be named VisionAuto string `json:"visionAuto,omitempty"` VisionModels []modelRef `json:"visionModels"` // the Vision the user picked when magpie can't find it any more: // VisionAuto describes in its place, and the row says so VisionMissing string `json:"visionMissing,omitempty"` // VisionNotMarked are the custom providers (AddedByAddress) with a model left // out of VisionModels only because nothing says it takes images: the // user can say so in the provider's Model settings (nexnull on Discord) VisionNotMarked []string `json:"visionNotMarked,omitempty"` // the reasoning levels of the model that describes images now, and the // one it is asked at when one is picked (VisionEffort fitted to them) VisionEfforts []string `json:"visionEfforts,omitempty"` VisionEffortNow string `json:"visionEffortNow,omitempty"` // the models Codex's thread titles may be sent to (CodexTitles, #705) TitleModels []modelRef `json:"titleModels"` // the models a request masking would change may go to as written // (RedactRouteTo): those whose every route is set to go unmasked // (gateway.MaskRoute) MaskRouteModels []modelRef `json:"maskRouteModels"` // what each of the disabled models (#1867) turns off now, by pattern DisabledHits map[string][]string `json:"disabledHits,omitempty"` // the model magpie's generate_image tool draws with when ImageGen // names none, and those that can be named ImageGenAuto string `json:"imageGenAuto,omitempty"` // the ImageGen the user picked when magpie can't find it any more ImageGenMissing string `json:"imageGenMissing,omitempty"` // the listed model the ImageGen the user picked stands for, when it // isn't listed itself: a ChatGPT account's gpt-image-2.5, saved when // magpie listed it, is its one GPT Image (gateway.ListedDrawer, #1865) ImageGenShown string `json:"imageGenShown,omitempty"` ImageGenModels []modelRef `json:"imageGenModels"` // the ImageGen the user picked is one unticked in its provider's // editor since (provider.HiddenDrawers): it still draws, and is // listed, as picked, with the row saying it is hidden ImageGenHidden bool `json:"imageGenHidden,omitempty"` // the model a video request that names none is made with when // VideoGen names none (gateway.AutoVideomaker), the VideoGen picked // when magpie can't find it any more, and those that can be picked: // each provider's video models, a custom provider's the user marked // (#1399) among them, less those unticked in its editor VideoGenAuto string `json:"videoGenAuto,omitempty"` VideoGenMissing string `json:"videoGenMissing,omitempty"` VideoGenModels []modelRef `json:"videoGenModels"` // the web search APIs a model's search goes to when no provider can // search (#419), their keys masked; the ones that can be added; and // the provider that searches first, if one does SearchAPIs []searchAPIJSON `json:"searchAPIs"` SearchVendors []searchVendorJSON `json:"searchVendors"` SearchProvider string `json:"searchProvider,omitempty"` // the providers Settings' Searcher may name, the one magpie picks when // it names none, why the one it names isn't used (gateway.Searcher*), // and the relays said to search that are never picked automatically (#359) SearchChoices []searchChoiceJSON `json:"searchChoices"` SearchAuto string `json:"searchAuto,omitempty"` SearchUnused string `json:"searchUnused,omitempty"` // the reasoning levels of the model that searches now, and the one it // is asked at when one is picked (SearcherEffort fitted to them) SearchEfforts []string `json:"searchEfforts,omitempty"` SearchEffortNow string `json:"searchEffortNow,omitempty"` SearchRelays []string `json:"searchRelays,omitempty"` // the last search the one it names didn't make, since it last // searched: no other provider searched in its place (Gearclickist on // Discord) SearchFailed *searchFailedJSON `json:"searchFailed,omitempty"` // the providers on that aren't offered, as they can't search the web // by themselves (#825) SearchLeftOut []string `json:"searchLeftOut,omitempty"` // the GitHub token the library asks GitHub with, masked, and where it // is from ("settings", GITHUB_TOKEN or GH_TOKEN); never the token GitHubTokenMask string `json:"githubTokenMask,omitempty"` GitHubTokenFrom string `json:"githubTokenFrom,omitempty"` // the token set in Settings was refused by GitHub (401): it is still // shown, masked, while requests go without a token (#3926) GitHubTokenRefused bool `json:"githubTokenRefused,omitempty"` // where other machines reach the gateway while it is shared LANURLs []string `json:"lanURLs,omitempty"` // LANURLs are a container's own addresses, not the host's: the page // offers the one it was opened at instead, or says how to set it LANContainer bool `json:"lanContainer,omitempty"` // where other containers on this host reach the gateway while magpie // runs in one (gateway.ContainerHostURL) LANContainerHost string `json:"lanContainerHost,omitempty"` // those of LANURLs at an internet address, which anyone online can // reach, not only this network LANPublic []string `json:"lanPublic,omitempty"` // when the Codex warm-up last started an account's window CodexWarmed *time.Time `json:"codexWarmed,omitempty"` // and the Claude warm-up ClaudeWarmed *time.Time `json:"claudeWarmed,omitempty"` // the ChatGPT accounts signed in, each of which can have a daily // warm-up time of its own (#957) CodexUsers []string `json:"codexUsers,omitempty"` // and the Claude accounts, which Warm up now picks from ClaudeUsers []string `json:"claudeUsers,omitempty"` // the Codexes here that kept the background compaction's table (and // its share) out of the config at the last sync: too old for it // (before 0.163.0-alpha.8), or of no known version (codex_async.go) CodexAsyncHeld []agent.CodexReader `json:"codexAsyncHeld,omitempty"` // the keys this machine's Codex config has that Codex reads before // Long conversations (model_context_window, // model_auto_compact_token_limit; agent.CodexCompactHeld), written // as the row names them: "[profiles.p] key = value, ..." CodexCompactKeys string `json:"codexCompactKeys,omitempty"` // Claude Code's two prompt-cache lifetimes as it reads them // (agent.TuneRead): the rows beside its compaction in its settings ClaudeCache []claudeCacheJSON `json:"claudeCache,omitempty"` // the magpie model Codex's config runs, when its own window is no // larger than Long conversations' threshold: Codex compacts it at 90% // of that window (codexWindowUnder) CodexWindow *codexRunWindow `json:"codexWindow,omitempty"` // whether a WorkBuddy (China) account is signed in, and each one's // last daily check-in WorkBuddy bool `json:"workbuddy"` WorkBuddyCheckins []provider.WorkBuddyCheckin `json:"workbuddyCheckins,omitempty"` // and a Trae CN account (its plugin's), and theirs (#694) Trae bool `json:"trae"` TraeCheckins []provider.WorkBuddyCheckin `json:"traeCheckins,omitempty"` // and a MiniMax Code (China) account (its plugin's), and theirs (#811) MiniMax bool `json:"minimax"` MiniMaxCheckins []provider.WorkBuddyCheckin `json:"minimaxCheckins,omitempty"` // and a Qoder or Qoder CN account (its plugin's), and theirs Qoder bool `json:"qoder"` QoderCheckins []provider.WorkBuddyCheckin `json:"qoderCheckins,omitempty"` // every account each vendor's daily check-in reaches, and whether the // user left it out (#1902) CheckinAccounts []provider.CheckinAccount `json:"checkinAccounts,omitempty"` // and the plugins' providers that check in themselves (auth.checkin), // each with its switch and its accounts' last check-ins CheckinPlugins []provider.PluginCheckin `json:"checkinPlugins,omitempty"` // FX is the dollar-to-yuan rate the cny currency choice shows costs at FX fxJSON `json:"fx"` // NotifyProblem is why a usage alert set wouldn't be seen: "denied" // (notifications turned off for magpie) or "unavailable" NotifyProblem string `json:"notifyProblem,omitempty"` } // searchAPIJSON is a search API as the Settings page shows it. type searchAPIJSON struct { Vendor string `json:"vendor"` Name string `json:"name"` Key string `json:"key,omitempty"` // masked URL string `json:"url,omitempty"` Ready bool `json:"ready"` // Keys is how many keys it has, Pick how a search picks among them // (provider.SearchPick*), and Quota whether what each has left can be // read (gateway.SearchQuotas) Keys int `json:"keys,omitempty"` Pick string `json:"pick,omitempty"` Quota bool `json:"quota,omitempty"` // Off: switched off, kept but never asked (#2286) Off bool `json:"off,omitempty"` // KeyList is each key in its order, masked, on or off, and resting // (辰林鸭~ on Discord) KeyList []searchKeyJSON `json:"keyList"` } // searchKeyJSON is one key of a search API as its list shows it: never // the key itself, which only Copy and Show ask for. type searchKeyJSON struct { Ref string `json:"ref"` // provider.SearchKeyRef Masked string `json:"masked"` Off bool `json:"off,omitempty"` // Rest is why the gateway asks it last now, RestUntil until when // (gateway.SearchKeyRest) Rest string `json:"rest,omitempty"` RestUntil time.Time `json:"restUntil,omitzero"` } // searchChoiceJSON is a provider that can search for a model that can't, // with the model it searches with when none is named, and its models. type searchChoiceJSON struct { ID string `json:"id"` Name string `json:"name"` Icon string `json:"icon,omitempty"` Small string `json:"small"` SmallName string `json:"smallName,omitempty"` Models []modelRef `json:"models"` // Service is a Kimi Code plan, which searches by its search service: // named by itself, with no model Service bool `json:"service,omitempty"` // Own is a Google sign-in or an AI Studio key, which searches for its // own models first Own bool `json:"own,omitempty"` // Search is a ChatGPT account, which searches by the ChatGPT backend's // search ("/@search") besides its models Search bool `json:"search,omitempty"` } type searchVendorJSON struct { ID string `json:"id"` Name string `json:"name"` KeysURL string `json:"keysURL,omitempty"` NeedURL bool `json:"needURL,omitempty"` // one the user runs // KeyOptional: it can be added with no key (You.com's free search, #1626) KeyOptional bool `json:"keyOptional,omitempty"` // its own address, the one used while no base URL is set (#1580) Base string `json:"base,omitempty"` // Auth: a plugin's API that signs in as the plugin's provider, taking // no key (provider.SearchVendor.Auth) Auth *searchAuthJSON `json:"auth,omitempty"` } // searchAuthJSON is the provider a search API signs in as: its name, and // how many of its accounts are on (0 with none signed in). type searchAuthJSON struct { Name string `json:"name"` SignedIn bool `json:"signedIn"` On int `json:"on"` } func searchState(s *settingsJSON) { names := map[string]string{} for _, e := range provider.Served() { names[e.ID] = cmp.Or(e.Name, e.Model) } s.SearchAPIs, s.SearchVendors = []searchAPIJSON{}, []searchVendorJSON{} for _, a := range provider.StoredSearchAPIs() { j := searchAPIJSON{Vendor: a.Vendor, Name: a.Name(), URL: a.URL, Ready: a.Ready(), Keys: len(a.Keys()), Pick: a.Pick, Quota: gateway.CanReadSearchQuota(a), Off: a.Off} if a.Key != "" { j.Key = a.MaskedKey() } j.KeyList = []searchKeyJSON{} for _, k := range a.SearchKeys() { kj := searchKeyJSON{Ref: provider.SearchKeyRef(k.Key), Masked: provider.MaskSearchKey(k.Key), Off: k.Off} if !k.Off { kj.Rest, kj.RestUntil = gateway.SearchKeyRest(a.Vendor, k.Key) } j.KeyList = append(j.KeyList, kj) } s.SearchAPIs = append(s.SearchAPIs, j) } for _, v := range provider.AllSearchVendors() { j := searchVendorJSON{ID: v.ID, Name: v.Name, KeysURL: v.KeysURL, NeedURL: v.WantsURL(), KeyOptional: v.KeyOptional, Base: v.Base} if v.Auth != "" { name, p := provider.SearchSignIn(v) j.Auth = &searchAuthJSON{Name: name} if p != nil { j.Auth.SignedIn = true j.Auth.On = gateway.SearchAccountsOn(*p) } } s.SearchVendors = append(s.SearchVendors, j) } s.SearchProvider = gateway.Searcher() s.SearchAuto, s.SearchUnused = gateway.AutoSearcher(), gateway.SearcherUnused() s.SearchEfforts, s.SearchEffortNow = gateway.SearchEfforts(), gateway.SearchEffortNow() if f, ok := gateway.SearcherFailed(); ok { s.SearchFailed = &searchFailedJSON{Searcher: f.Searcher, Why: f.Why, NothingFound: f.NothingFound, NotSearched: f.NotSearched, Instead: f.Instead, At: f.At} } s.SearchChoices = []searchChoiceJSON{} for _, c := range gateway.Searchers() { p := c.Provider j := searchChoiceJSON{ID: p.ID, Name: p.Name, Icon: p.Icon, Small: c.Small, SmallName: names[p.ID+"/"+c.Small], Models: []modelRef{}, Service: c.Service, Own: c.Own, Search: c.Search} for _, m := range c.Models { id := p.ID + "/" + m.ID j.Models = append(j.Models, modelRef{ID: id, Name: cmp.Or(names[id], m.Name, m.ID), Provider: p.ID, PName: p.Name, Icon: p.Icon}) } s.SearchChoices = append(s.SearchChoices, j) } for _, p := range gateway.RelaysSaidToSearch() { s.SearchRelays = append(s.SearchRelays, p.Name) } for _, p := range provider.All() { if p.On() && !slices.ContainsFunc(s.SearchChoices, func(c searchChoiceJSON) bool { return c.ID == p.ID }) && !slices.Contains(s.SearchRelays, p.Name) { s.SearchLeftOut = append(s.SearchLeftOut, p.Name) } } } // searchFailedJSON is gateway.SearchFailure as Settings shows it. type searchFailedJSON struct { Searcher string `json:"searcher"` Why string `json:"why,omitempty"` NothingFound bool `json:"nothingFound,omitempty"` NotSearched bool `json:"notSearched,omitempty"` Instead string `json:"instead,omitempty"` // who, named after it, searched in its place At time.Time `json:"at"` } // loginState is whether magpie opens at login, as the system will act on // it. A var for the tests: the real one asks the user's own system. var loginState = autostart.Enabled // codexRunWindow is a model and the window magpie tells Codex it has. type codexRunWindow struct { Model string `json:"model"` Window int `json:"window"` // Size is Window as the page writes a window (contextsText): 128K, 1M; // "n" is its slot in the row's words, which take the struct whole Size string `json:"n"` } func tokensSize(n int) string { switch { case n%1_000_000 == 0: return strconv.Itoa(n/1_000_000) + "M" case n%1000 == 0: return strconv.Itoa(n/1000) + "K" } return strconv.Itoa(n) } // codexKeysText names Codex's config keys as the Long conversations row // shows them, each with its profile and value. func codexKeysText(hs []agent.CodexCompactHold) string { var b []string for _, h := range hs { k := h.Key + " = " + h.Value if h.Profile != "" { k = "[profiles." + h.Profile + "] " + k } b = append(b, k) } return strings.Join(b, ", ") } // codexWindowUnder is model's window when Long conversations' threshold // doesn't come below it, so Codex compacts at 90% of the window instead // (zgjfjfl on Discord, 10-31: a relay's gpt-6-A at 128K, Long // conversations at 544K, compacting near 128K). Under Full window, or // with a threshold set on the model or its provider, it is nil: the row // says what the user chose. A provider's model is looked up at its // provider alone (ServedEntryOf), a group in the catalog, since this is // read on every settings read. func codexWindowUnder(st settings.Settings, model string) *codexRunWindow { if model == "" || st.FullContext { return nil } e, ok := provider.ServedEntryOf(model) if !ok && strings.HasPrefix(model, provider.GroupPrefix) { e, ok = provider.EntryOf(model) } if !ok || e.Context <= 0 || provider.CompactFor(st, e, provider.GroupFinder()) > 0 || st.Working(e.Context) < e.Context { return nil } return &codexRunWindow{Model: model, Window: e.Context, Size: tokensSize(e.Context)} } func settingsState() settingsJSON { s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()} s.AddrEnv = os.Getenv("MAGPIE_ADDR") s.Log = tilde(applog.Current()) s.Builtins = builtinsState() s.PanelKeys = panelKeysState() s.JSRoutings = middleware.Routings() s.OnNetwork = gateway.OnNetwork() if list, env := gateway.AllowIPs(); env { s.AllowIPsEnv, s.AllowIPsFromEnv = os.Getenv(gateway.AllowIPsEnv), list } if s.LAN || gateway.OnNetwork() { s.PublicURL = gateway.PublicURL() s.PublicKind = gateway.URLKind(s.PublicURL) } s.WSL = runtime.GOOS == "windows" s.Web = webPage.Load() s.GatewayOn, s.GatewayWhy = gatewayMode(s.Web) s.LANKey = "" // the retained credential belongs on disk, not in UI state // the GitHub token, masked, and where the library's requests take one // from: Settings, or the environment variable named own := strings.TrimSpace(s.GitHubToken) s.GitHubToken = "" if tok, from := library.GitHubToken(); tok != "" { s.GitHubTokenMask, s.GitHubTokenFrom = provider.Mask(tok), from } else if _, refused := ghtoken.SettingsRefused(); refused && own != "" { // a refused token set here is still the user's: shown as refused, // not as if none were set, while requests go without one (#3926) s.GitHubTokenMask, s.GitHubTokenFrom, s.GitHubTokenRefused = provider.Mask(own), "settings", true } if found, err := discoverTerminals(); err == nil { for _, app := range found.Apps { s.TerminalApps = append(s.TerminalApps, terminalChoice{ID: app.ID, Name: app.Name}) } s.TerminalDefault = found.Default } s.FX = currentFX() if (s.UsageAlert > 0 || s.BalanceAlert > 0 || s.ResetReminder > 0 || s.TurnDoneAlert > 0 || s.MaskAlert) && notifyProblem != nil { s.NotifyProblem = notifyProblem() } s.ProxyNow, s.ProxySource = netproxy.Describe() s.NoAccountsEnv = settings.AccountDiscoveryOff() && !s.NoAccountDiscovery for _, name := range []string{"MAGPIE_OTEL_ENABLED", "MAGPIE_OTEL_ENDPOINT", "MAGPIE_OTEL_HEADERS", "MAGPIE_OTEL_METRICS", "MAGPIE_OTEL_BODIES", "MAGPIE_OTEL_BODIES_WHOLE", "MAGPIE_OTEL_SESSIONS"} { if _, ok := os.LookupEnv(name); ok { s.OTelEnv = true } } login := loginState() s.Login, s.LoginAllow = login != autostart.Off, login == autostart.NeedsAllowing if s.LAN { s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs() s.LANContainerHost = gateway.ContainerHostURL() s.LANPublic = gateway.PublicURLs(s.LANURLs) } s.CodexWarmed, s.ClaudeWarmed = latest(provider.CodexWarmed()), latest(provider.ClaudeWarmed()) s.CodexUsers, s.ClaudeUsers = loginUsers("codex"), loginUsers("claude") s.CodexAsyncHeld = agent.CodexAsyncHeld() s.CodexCompactKeys = codexKeysText(agent.CodexCompactHeld("")) s.ClaudeCache = claudeCacheState() s.CodexWindow = codexWindowUnder(s.Settings.ForAgent("codex"), agent.CodexModel("")) s.WorkBuddy, s.WorkBuddyCheckins = provider.HasWorkBuddy(), provider.WorkBuddyCheckins() s.Trae, s.TraeCheckins = provider.HasTrae(), provider.TraeCheckins() s.MiniMax, s.MiniMaxCheckins = provider.HasMiniMax(), provider.MiniMaxCheckins() s.Qoder, s.QoderCheckins = provider.HasQoder(), provider.QoderCheckins() s.CheckinPlugins = provider.PluginCheckins() s.CheckinAccounts = provider.CheckinAccounts() s.VisionAuto, s.VisionModels, s.VisionMissing = gateway.AutoVision(), []modelRef{}, gateway.VisionMissing() s.VisionEfforts, s.VisionEffortNow = gateway.VisionEfforts(), gateway.VisionEffortNow() for _, e := range provider.Served() { if e.Images && (e.ImageInput == nil || *e.ImageInput) && (e.Group != "" || e.Provider.Ready()) { m := modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon} if e.Group != "" { m.Provider, m.PName = "", e.Group } s.VisionModels = append(s.VisionModels, m) } else if e.Group == "" && !e.Images && e.ImageInput == nil && e.Provider.AddedByAddress() && e.Provider.Ready() && !slices.Contains(s.VisionNotMarked, cmp.Or(e.Provider.Name, e.Provider.ID)) { // unknown, not answered: one its list or the user said no to // (ModelImages) isn't counted s.VisionNotMarked = append(s.VisionNotMarked, cmp.Or(e.Provider.Name, e.Provider.ID)) } } s.TitleModels, s.MaskRouteModels = []modelRef{}, []modelRef{} // only a provider set to go unmasked can take one (most have none) unmaskedAny := slices.ContainsFunc(provider.All(), provider.Provider.SkipsRedaction) for _, pat := range s.DisabledModels { if s.DisabledHits == nil { s.DisabledHits = map[string][]string{} } s.DisabledHits[pat] = provider.DisabledHits(pat) } for _, e := range provider.Served() { if e.Group != "" || e.Provider.Ready() && !e.Provider.DecideOnly() { m := modelRef{ID: e.ID, Name: e.Name, Provider: e.Provider.ID, PName: e.Provider.Name, Icon: e.Provider.Icon} if e.Group != "" { m.Provider, m.PName = "", e.Group } s.TitleModels = append(s.TitleModels, m) if (e.Group != "" || e.Provider.SkipsRedaction()) && unmaskedAny && gateway.MaskRoute(e.ID) { s.MaskRouteModels = append(s.MaskRouteModels, m) } } } searchState(&s) s.ImageGenAuto, s.ImageGenModels, s.ImageGenMissing = gateway.AutoDrawer(), []modelRef{}, gateway.DrawerMissing() for _, p := range provider.All() { if !p.On() || p.DecideOnly() { continue } // those unticked in its editor left out, but the one picked here // (321sssrt on X): a hidden pick still draws, and shows as picked for _, m := range gateway.Drawers(p) { if p.DrawerHidden(m.ID) && gateway.ListedDrawer(s.ImageGen) != p.ID+"/"+m.ID { continue } name := m.Name if name == "" { name = m.ID } s.ImageGenModels = append(s.ImageGenModels, modelRef{ID: p.ID + "/" + m.ID, Name: name, Provider: p.ID, PName: p.Name, Icon: p.Icon, VendorPicks: gateway.VendorPicksDrawer(p)}) } } // the routing groups with a member that draws (7up6666 on X): a // group picked here draws on its members in its routing's order. One // of image models only isn't served to agents (jzw690 on X), so it is // listed from the groups themselves listed := map[string]bool{} for _, e := range provider.Served() { if e.Group != "" && gateway.GroupDraws(e.ID) { listed[e.ID] = true s.ImageGenModels = append(s.ImageGenModels, modelRef{ID: e.ID, Name: e.Name, PName: e.Group}) } } for _, g := range provider.Groups() { if ref := g.Ref(); !g.Hidden && !g.Disabled && !listed[ref] && gateway.GroupDraws(ref) { s.ImageGenModels = append(s.ImageGenModels, modelRef{ID: ref, Name: cmp.Or(g.Name, g.ID), PName: g.ID}) } } if v := gateway.ListedDrawer(s.ImageGen); v != s.ImageGen { s.ImageGenShown = v } s.ImageGenHidden = gateway.DrawerHidden(s.ImageGen) s.VideoGenAuto, s.VideoGenModels, s.VideoGenMissing = gateway.AutoVideomaker(), []modelRef{}, gateway.VideomakerMissing() for _, p := range provider.All() { if !p.On() || p.DecideOnly() { continue } // one unticked in its editor is left out, but the one picked here for _, m := range gateway.Videomakers(p) { if p.VideomakerHidden(m.ID) && s.VideoGen != p.ID+"/"+m.ID { continue } s.VideoGenModels = append(s.VideoGenModels, modelRef{ID: p.ID + "/" + m.ID, Name: cmp.Or(m.Name, m.ID), Provider: p.ID, PName: p.Name, Icon: p.Icon}) } } // the Codex subagents row's warning: magpie's multi-agent V1 doesn't reach // Codex where its own multi_agent_v2 is on in the config magpie routes, and // magpie writes nothing there — the setting is the user's to turn off // (#141). Shown on every read, so the row carries it after a reload too. if s.CodexAgentsV1 { s.Notice = agent.CodexSubAgentsV1Warning() } return s } // latest is the latest of ts, nil when there is none. func latest(ts map[string]time.Time) *time.Time { var out *time.Time for _, t := range ts { if out == nil || t.After(*out) { out = &t } } return out } // onDock puts the app in the Mac's Dock or takes it out as the settings say, // when the Settings page changes them; set by the process that has the app. var onDock func(settings.Settings) // assetTypes are the page's own files' types. The file server takes them // from Windows' registry, which another program may have changed — an SVG // served as something else draws no icon. var assetTypes = map[string]string{".svg": "image/svg+xml", ".png": "image/png", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".html": "text/html; charset=utf-8"} func init() { for ext, t := range assetTypes { mime.AddExtensionType(ext, t) } } // revalidated serves the page's own files to be asked for again each time, // by their content's hash: an embedded file has no date, so they went out // with nothing to check them by, and a cache in front of `magpie web` (a // proxy, a CDN, a tunnel's) could keep an older version's app.js under the // new index.html after an update: a page without what that version added, // such as the request archive switch (Jorben on Discord). An unchanged // file is a 304. // // The page itself names each of its scripts and styles with its content's // hash (app.js?v=…), so a cache that kept a file from before these headers // were sent, and goes on serving it whatever magpie says now, is never asked // for it again: a Docker user behind an HTTPS proxy had v0.1.630's page run // v0.1.582's app.js and routing.js (incognito and a hard refresh alike), // whose first lines looked for an element the page no longer had, and the // page was blank under its tabs. func revalidated(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/") if name == "" { name = "index.html" } b, err := fs.ReadFile(staticFS(), name) if err != nil { next.ServeHTTP(rw, r) return } if r.URL.Path == "/" { b = versionedPage(b) } sum := sha256.Sum256(b) rw.Header().Set("ETag", `"`+hex.EncodeToString(sum[:12])+`"`) rw.Header().Set("Cache-Control", "no-cache") // a file asked for by the address the page names it by, its // content's hash, is the same at that address for good: a browser // keeps it and doesn't ask again, which a slow link to `magpie web` // feels at every load (akic404 on Discord). Another version's hash, // or none, is asked for again as before. if v := r.URL.Query().Get("v"); v != "" && v == hex.EncodeToString(sum[:6]) { rw.Header().Set("Cache-Control", "max-age=31536000, immutable") } if r.URL.Path == "/" { rw.Header().Set("Content-Type", "text/html; charset=utf-8") http.ServeContent(rw, r, "index.html", time.Time{}, bytes.NewReader(b)) return } next.ServeHTTP(rw, r) }) } // pageFile is a script or stylesheet of the page's own, named in it: one // of the page's, or of a built-in plugin's under plugins//. var pageFile = regexp.MustCompile(`(src|href)="([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*\.(?:js|css))"`) // versionedPage is the page with each of its own scripts and stylesheets // named with its content's hash; one not among the page's files (boot.js, // which the API writes) keeps its name. func versionedPage(page []byte) []byte { return pageFile.ReplaceAllFunc(page, func(m []byte) []byte { g := pageFile.FindSubmatch(m) b, err := fs.ReadFile(staticFS(), string(g[2])) if err != nil { return m } sum := sha256.Sum256(b) return []byte(fmt.Sprintf(`%s="%s?v=%s"`, g[1], g[2], hex.EncodeToString(sum[:6]))) }) } // Handler serves the embedded UI and the JSON API. // gw is the gateway this process serves, or nil when another magpie has it // (for now: see startBackend). func Handler(w Windows, gw *gateway.Server) http.Handler { if gw != nil { served.Store(gw) } // magpie web's own page, not the app's served to a browser, which the // app's windows share their settings state with if ownWeb(w) { webPage.Store(true) } mux := http.NewServeMux() mux.Handle("/", devPage(revalidated(http.FileServer(http.FS(staticFS()))))) devRoutes(mux) pluginPageRoutes(mux, isWeb(w)) // boot.js hands the page the saved language and theme before it paints: // they came only with the settings, so the tabs showed English first mux.HandleFunc("GET /boot.js", func(rw http.ResponseWriter, r *http.Request) { s := settings.Load() // and the text size, which the Mac's header measures against the // traffic lights boot := map[string]any{"lang": s.Lang, "theme": s.Theme, "textSize": s.TextSize, "web": isWeb(w)} // and the version that served the page: a browser's page reloads // once another answers in its place (visamzh on X), as after its // own restart to update (backAsNew) boot["version"] = Version if s.Colorblind { boot["colorblind"] = true } if s.ReduceMotion { boot["reduceMotion"] = true } if s.NoBird { boot["noBird"] = true } // a browser tab keeps its own font choice (fonts.js) if !isWeb(w) { boot["uiFont"], boot["codeFont"] = s.UIFont, s.CodeFont } // and whether this app's webview would crash on a