settings: a look at one setting takes the shared settings, not a copy

settings.Load() copies the whole Settings (clone + deepCopy of every map
and slice) for each caller. 133 places read one field of it and threw
the rest away: the proxy for every outgoing request (netproxy), the
GitHub token, the China mirror switch, a model's output cap, wire or
price on a gateway request. With a real account in the tray, Load's
clone was 26.6 MB of the 318 MB the process allocated in its first
seven minutes, most of it through netproxy.For on each request.

Each of them now reads settings.Shared(), the read-only settings every
caller is given for the same settings.json. Only reads were changed:
a scalar field (string, bool, int, float) or a map field's index
read. A caller that keeps a whole map or slice, or calls a method on
the settings, still takes Load's copy.
This commit is contained in:
yetone
2026-11-14 14:02:49 +08:00
parent 8a59e76165
commit 667ac8bd6f
78 changed files with 133 additions and 133 deletions
+2 -2
View File
@@ -399,7 +399,7 @@ func LANSecret() string {
// not shared, the usual case, is told by the settings alone, before
// the lock: taken first, every agent's sync (keeping) made and locked
// caller-keys.json.lock, ~100 times in a start's first 20s (#1665)
if !settings.Load().LAN {
if !settings.Shared().LAN {
return ""
}
mu.Lock()
@@ -561,7 +561,7 @@ func Update(action string, in Change) (string, error) {
if i < 0 {
return "", errors.New("Key not found")
}
defaultKey := keys[i].LAN || keys[i].ID == settings.Load().LANKeyID
defaultKey := keys[i].LAN || keys[i].ID == settings.Shared().LANKeyID
if defaultKey {
keys[i].LAN = true
}
+2 -2
View File
@@ -324,7 +324,7 @@ func ScopeBrowser(id string) error {
return ErrNoKey
}
k := &keys[i]
if k.LAN || k.ID == settings.Load().LANKeyID {
if k.LAN || k.ID == settings.Shared().LANKeyID {
return errors.New("The sharing key is given to magpie's own agents, so it can't be held to Magpie Browser")
}
if k.Browser && k.ReadOnly && !k.Issues {
@@ -356,7 +356,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact}
// the default key as Default tells it: marked LAN, or the id the
// settings name (settings read only for an unmarked key)
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
who.Default = k.LAN || (k.ID != "" && settings.Shared().LANKeyID == k.ID)
if who.Default {
who.Admin = ""
}
+2 -2
View File
@@ -46,7 +46,7 @@ func desktopLANURLs() []string {
// (the first, where the network's address changed since), else the gateway's
// own on loopback.
func desktopGateway() string {
pick := settings.Load().DesktopGateway
pick := settings.Shared().DesktopGateway
if pick == "" {
return gateway.URL()
}
@@ -115,7 +115,7 @@ func desktopGatewayField(ps []desktopPaths, apply func() error) Field {
// machines reach the gateway at (gateway.LANURLs, or the one Desktop is
// pointed at), as a profile exported here holds it.
func desktopOurAddress(a *url.URL) bool {
for _, l := range append(gateway.LANURLs(), settings.Load().DesktopGateway) {
for _, l := range append(gateway.LANURLs(), settings.Shared().DesktopGateway) {
u, err := url.Parse(l)
if err == nil && u.Hostname() == a.Hostname() && portOf(u) == portOf(a) {
return true
+3 -3
View File
@@ -29,7 +29,7 @@ const desktopIsolatedKey = ".isolated"
// desktopIsolatedOn says the user turned the isolated Desktop on; a var so
// a test needs no settings file.
var desktopIsolatedOn = func() bool { return settings.Load().DesktopIsolated }
var desktopIsolatedOn = func() bool { return settings.Shared().DesktopIsolated }
// desktopIsolatedSet is the isolated Desktop's folders on goos: its
// userData and its 3p folder are one, Claude-Magpie-3p. The language and
@@ -65,11 +65,11 @@ func desktopIsolatedSet(goos, home string, getenv func(string) string) (desktopP
// desktopIsolatedClaudeOn says the user gave the isolated Desktop's Code
// tab a folder of its own; a var so a test needs no settings file.
var desktopIsolatedClaudeOn = func() bool { return settings.Load().DesktopIsolatedClaude }
var desktopIsolatedClaudeOn = func() bool { return settings.Shared().DesktopIsolatedClaude }
// desktopIsolatedClaudeChosen says the user set that themselves; a var
// so a test needs no settings file.
var desktopIsolatedClaudeChosen = func() bool { return settings.Load().DesktopIsolatedClaudeChosen }
var desktopIsolatedClaudeChosen = func() bool { return settings.Shared().DesktopIsolatedClaudeChosen }
// saveDesktopIsolatedClaude keeps that folder on or off, and chosen when
// the user set it; a var for tests.
+1 -1
View File
@@ -62,7 +62,7 @@ func Rewire(as []*Agent) (moved []string, err error) {
func Rekey(as []*Agent) (moved []string, err error) {
var away []*Agent
for _, a := range as {
if a.Gateway != nil && (onAnotherMachine(a.Gateway()) || a.ID == "claude-desktop" && settings.Load().DesktopGateway != "") {
if a.Gateway != nil && (onAnotherMachine(a.Gateway()) || a.ID == "claude-desktop" && settings.Shared().DesktopGateway != "") {
away = append(away, a)
}
}
+1 -1
View File
@@ -1311,7 +1311,7 @@ var wslOn = runtime.GOOS == "windows"
// wslLooks is whether magpie looks in WSL on its own: there is WSL, and
// Settings' Detect agents in WSL is on (#1264).
func wslLooks() bool { return wslOn && !settings.Load().NoWSLAgents }
func wslLooks() bool { return wslOn && !settings.Shared().NoWSLAgents }
// wslRun runs wsl.exe; a var for tests.
// wslReachScript asks, inside a distro, whether anything answers at $1
+1 -1
View File
@@ -26,7 +26,7 @@ func accountsDiscoveryCmd(args []string) error {
switch {
case !settings.AccountDiscoveryOff():
fmt.Println("account discovery is on: magpie reads your agents' sign-ins and serves them as subscriptions")
case settings.Load().NoAccountDiscovery:
case settings.Shared().NoAccountDiscovery:
fmt.Println("account discovery is off: magpie reads none of your agents' sign-ins and serves no subscription; API-key providers work as before")
default:
fmt.Println("account discovery is off for this run: MAGPIE_NO_ACCOUNTS is set (saved: on)")
+1 -1
View File
@@ -495,7 +495,7 @@ func addAccount(agentID string) error {
return fmt.Errorf("sign-in didn't finish: %s", st.Error)
}
}
linkOnly := settings.Load().SignInLinkOnly
linkOnly := settings.Shared().SignInLinkOnly
if linkOnly {
// the user keeps sign-in pages to a browser of their own
fmt.Println("Open this link in the browser you sign in with:")
+1 -1
View File
@@ -171,7 +171,7 @@ func showModelAPI(ref string) error {
if err != nil {
return err
}
saved, had := settings.Load().ModelAPIs[p.ID+"/"+model]
saved, had := settings.Shared().ModelAPIs[p.ID+"/"+model]
if !provider.ServesModel(*p, model) && !had {
return fmt.Errorf("%s has no model %s (magpie provider models %s lists them)", p.ID, model, p.ID)
}
+3 -3
View File
@@ -847,8 +847,8 @@ func modelCompact(args []string) error {
// (settings.ContextCap).
func modelContextCap(args []string) error {
if len(args) == 0 {
if n := settings.Load().ContextCap; n > 0 {
fmt.Println(bold.Render(tokenCount(n)), muted.Render(map[bool]string{true: "· no model is told a longer window, one you set for it or its provider included · magpie model context-cap own", false: "· no model is told a longer window, unless you set one for it or its provider · magpie model context-cap all"}[settings.Load().ContextCapAll]), muted.Render("· magpie model context-cap off"))
if n := settings.Shared().ContextCap; n > 0 {
fmt.Println(bold.Render(tokenCount(n)), muted.Render(map[bool]string{true: "· no model is told a longer window, one you set for it or its provider included · magpie model context-cap own", false: "· no model is told a longer window, unless you set one for it or its provider · magpie model context-cap all"}[settings.Shared().ContextCapAll]), muted.Render("· magpie model context-cap off"))
} else {
fmt.Println("off", muted.Render("· every model takes its own window · magpie model context-cap <size>"))
}
@@ -1239,7 +1239,7 @@ func modelOutput(args []string) error {
// the command the user is after
if !dropped {
wid, _, _ := strings.Cut(key, "/")
if settings.Load().ModelOutputs[wid+"/*"] > 0 {
if settings.Shared().ModelOutputs[wid+"/*"] > 0 {
return fmt.Errorf("%s has no reply limit of its own; what every model of this provider answers with is what you set for %s, which %s takes away",
key, wid+"/*", resetCommand("output", wid+"/*"))
}
+1 -1
View File
@@ -60,7 +60,7 @@ func modelID(args []string) error {
if replaced != "" {
fmt.Println(muted.Render(" " + replaced + " had that id: it is listed by its own again"))
}
if n := strings.TrimSpace(settings.Load().ModelWires[p.ID+"/"+id]); n != "" {
if n := strings.TrimSpace(settings.Shared().ModelWires[p.ID+"/"+id]); n != "" {
fmt.Println(muted.Render(" a wire name of yours is set for " + p.ID + "/" + id + ": it is asked for as " + n + " (magpie model wire --reset takes it off)"))
}
return nil
+1 -1
View File
@@ -44,7 +44,7 @@ func modelTierCmd(args []string) error {
if err := provider.SetModelTier(p.ID+"/"+model, val); err != nil {
return err
}
fmt.Printf("%s/%s: %s\n", p.ID, model, tierWord(settings.Load().ModelTiers[p.ID+"/"+model]))
fmt.Printf("%s/%s: %s\n", p.ID, model, tierWord(settings.Shared().ModelTiers[p.ID+"/"+model]))
return nil
}
+1 -1
View File
@@ -658,7 +658,7 @@ func pluginLogin(ctx context.Context, name, method string) error {
if a.URL != "" {
// the user may keep sign-in pages to a browser of their own; a
// page the plugin's CLI opened itself is open either way
linkOnly := settings.Load().SignInLinkOnly && !a.Opened
linkOnly := settings.Shared().SignInLinkOnly && !a.Opened
if linkOnly {
fmt.Println("Open this link in the browser you sign in with:")
} else {
+1 -1
View File
@@ -1605,7 +1605,7 @@ func refreshLive(ctx context.Context) {
// network by MAGPIE_ADDR (a server, a Docker image), it takes others with
// an enabled gateway key.
func keyNote() string {
if settings.Load().LAN || gateway.OnNetwork() {
if settings.Shared().LAN || gateway.OnNetwork() {
if gateway.InContainer() {
return "(anything works inside the container; from its host and other machines, an enabled gateway key — magpie gateway-key add <name>)"
}
+1 -1
View File
@@ -996,7 +996,7 @@ var SignInPlan func() string
// plan's allowance), so there it follows the session as Codex's other
// side calls do. A plan magpie can't read keeps Codex's pick.
func AutoReviewModel() string {
v := settings.Load().CodexAutoReview
v := settings.Shared().CodexAutoReview
if v == "" && SignInPlan != nil && strings.EqualFold(strings.TrimSpace(SignInPlan()), "free") {
return settings.CodexAutoReviewSession
}
+1 -1
View File
@@ -59,7 +59,7 @@ const archiveQueue = 16
// is read whole into memory once, for its secrets to be taken out, while
// its call is uploaded, one call at a time.
func archiveLimit() int64 {
mb := settings.Load().RequestArchiveMaxMB
mb := settings.Shared().RequestArchiveMaxMB
if mb <= 0 {
mb = 32
}
+1 -1
View File
@@ -30,7 +30,7 @@ var ErrNotArchived = errors.New("not in the archive on this computer")
// LocalArchiveCap is how large the archive on this computer grows, in
// bytes: settings' RequestArchiveLocalMB, a GiB unless set.
func LocalArchiveCap() int64 {
mb := settings.Load().RequestArchiveLocalMB
mb := settings.Shared().RequestArchiveLocalMB
if mb <= 0 {
mb = 1024
}
+1 -1
View File
@@ -72,7 +72,7 @@ func (e *claudeFull) Error() string {
// what says so: the user's claudeRunsMost, else what this machine's memory
// holds (claudeMemRuns), else 0, no bound.
func claudeRunsMost() (int, string) {
if n := settings.Load().ClaudeRunsMost; n > 0 {
if n := settings.Shared().ClaudeRunsMost; n > 0 {
return n, "claudeRunsMost in settings"
}
return claudeMemRuns()
+3 -3
View File
@@ -1549,7 +1549,7 @@ func claudeMachineWhy(binary claudeCLI) (code, why string) {
{!claudeTUIRuns, "no-shim", "no shim"},
{runtime.GOOS != "darwin" && runtime.GOOS != "linux" && runtime.GOOS != "windows", "os", runtime.GOOS},
{binary.wsl == nil && binary.path == "", "missing", "no Claude Code path"},
{settings.Load().ClaudePrintMode, "off", "the interactive mode is turned off"},
{settings.Shared().ClaudePrintMode, "off", "the interactive mode is turned off"},
} {
if c.is {
return c.code, c.why
@@ -1830,7 +1830,7 @@ func (c claudeCLI) tuiEnv(env []string, configDir string) []string {
// Claude Code's interactive mode, and never as -p: the user hasn't turned
// it off (ClaudePrintMode), and magpie has its shim (claudeTUIRuns).
func claudeTUIOn() bool {
return claudeTUIRuns && !settings.Load().ClaudePrintMode
return claudeTUIRuns && !settings.Shared().ClaudePrintMode
}
// wantTUI is whether req's run is to be the interactive mode: it is on,
@@ -7123,7 +7123,7 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
}
// a client that places its own cache marks keeps Claude Code's prompt:
// its system marks are placed in the run's first message (#1717)
req.leanPrompt = name == "Claude Code" && req.clientCache == nil && settings.Load().ClaudeLeanPrompt
req.leanPrompt = name == "Claude Code" && req.clientCache == nil && settings.Shared().ClaudeLeanPrompt
// the tools of a caller on another computer run there, not where
// Claude Code runs (envUnknownNote)
req.remoteCaller = !local(r)
+5 -5
View File
@@ -31,7 +31,7 @@ func codexTitlesTo(h http.Header, body []byte, ours bool, session func() string)
if !isTitleKind(requestCallKind(h, requestSessionMetadata(h, body))) {
return ""
}
if to := settings.Load().CodexTitles; to != "" {
if to := settings.Shared().CodexTitles; to != "" {
return to
}
return codexSideTo(body, ours, session)
@@ -88,7 +88,7 @@ func codexDescriptionsTo(h http.Header, body []byte, ours bool, session func() s
if !isDescriptionKind(requestCallKind(h, requestSessionMetadata(h, body))) {
return ""
}
if to := settings.Load().CodexDescriptions; to != "" {
if to := settings.Shared().CodexDescriptions; to != "" {
return to
}
// Codex on a magpie model gets no schema upstream (#743), so an empty
@@ -262,7 +262,7 @@ func codexPredictionsTo(h http.Header, body []byte, ours bool, session func() st
if !isPredictionKind(requestCallKind(h, requestSessionMetadata(h, body))) {
return ""
}
if to := settings.Load().CodexPredictions; to != "" {
if to := settings.Shared().CodexPredictions; to != "" {
return to
}
// the app asks on the thread's model, but one of Codex's own when the
@@ -311,7 +311,7 @@ func (s *Server) codexTitle(w http.ResponseWriter, r *http.Request, body []byte,
}
ctx := context.WithValue(r.Context(), titleCheckKey{}, check)
ctx = context.WithValue(ctx, titleShapeKey{}, &shape)
if to == settings.Load().CodexTitles {
if to == settings.Shared().CodexTitles {
// the model picked for titles in magpie's settings, not by the
// caller's key (#882)
ctx = magpieChose(ctx)
@@ -442,7 +442,7 @@ func (s *Server) codexPrediction(w http.ResponseWriter, r *http.Request, body []
return ""
}
ctx := context.WithValue(r.Context(), titleCheckKey{}, check)
if to == settings.Load().CodexPredictions {
if to == settings.Shared().CodexPredictions {
ctx = magpieChose(ctx)
}
s.serve(rec, r.WithContext(ctx), provider.Responses, codexSideEffort(withModel(body, to), to))
+2 -2
View File
@@ -227,7 +227,7 @@ func desktopModels(entries []provider.Entry, knowsMythos bool) []map[string]any
// Untagged, Claude Code asks for its own id of the tier, which
// desktopTurn keeps on the chat's provider (servedBeside).
tierOf := desktopTierOf(DesktopTiers())
longest := settings.Load().DesktopLongest
longest := settings.Shared().DesktopLongest
labels := provider.LabelsFor("claude-desktop", entries)
data := make([]map[string]any, 0, len(entries))
for i, e := range entries {
@@ -283,7 +283,7 @@ func desktopListed1M(e provider.Entry, longest bool) bool { return longest && e.
// DesktopListed1M says Claude Desktop is shown e by its "[1m]" id, which
// its Code tab hands Claude Code, so a session on it has the 1M window.
func DesktopListed1M(e provider.Entry) bool {
return desktopListed1M(e, settings.Load().DesktopLongest)
return desktopListed1M(e, settings.Shared().DesktopLongest)
}
// desktop1MSaid is the description Claude Desktop gives the 1M entry it
+2 -2
View File
@@ -85,7 +85,7 @@ const maxDrawings = 4
// ImageGen while it resolves, else AutoDrawer's. None when it is off or no
// provider draws.
func drawer() (string, bool) {
switch v := settings.Load().ImageGen; v {
switch v := settings.Shared().ImageGen; v {
case "off":
return "", false
case "":
@@ -109,7 +109,7 @@ func Drawer() string {
// when magpie can't find it any more, so that AutoDrawer's draws in its
// place, as VisionMissing is Image recognition's. "" when none is named,
// it is off, or it resolves.
func DrawerMissing() string { return drawerMissing(settings.Load().ImageGen) }
func DrawerMissing() string { return drawerMissing(settings.Shared().ImageGen) }
// drawerMissing is v, an Image generation pick, when magpie can't draw
// with it: pickedMissing's, and a routing group ("group/<id>", 7up6666 on
+1 -1
View File
@@ -3819,7 +3819,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
report = nil
}
cacheReportTry(hw, report)
if streams && !settings.Load().NoLoopGuard {
if streams && !settings.Shared().NoLoopGuard {
// a reply stuck in a loop is ended, not let run to its limit
// (#1359)
hw.loop = &loopGuard{}
+1 -1
View File
@@ -276,7 +276,7 @@ func (s *Server) imageMCPCall(r *http.Request, m mcpMessage) (any, map[string]an
// imageGenOff is the tools' answer while Settings turned image generation
// off, which turns video off with it.
func imageGenOff() (map[string]any, bool) {
if settings.Load().ImageGen != "off" {
if settings.Shared().ImageGen != "off" {
return nil, false
}
return toolResult("Image generation is off in magpie: pick a model for it in Settings → Models → Images → Image generation", true), true
+1 -1
View File
@@ -167,7 +167,7 @@ func OnNetwork() bool {
// remoteKeyed: requests from another machine are answered, with an enabled
// gateway key — while the gateway is shared, or listens on the network.
func remoteKeyed() bool { return settings.Load().LAN || OnNetwork() }
func remoteKeyed() bool { return settings.Shared().LAN || OnNetwork() }
// PublicHost is PublicURL's host, "" when it isn't set.
func PublicHost() string {
+1 -1
View File
@@ -131,7 +131,7 @@ func OwnUnready(name string) string {
if _, ok := drawer(); ok {
return ""
}
if settings.Load().ImageGen == "off" {
if settings.Shared().ImageGen == "off" {
return "Image generation is off in Settings → Models → Images: its tools say so until a model is picked there"
}
return "No model that draws images is set up yet: it draws once a provider with an image model is added, and says so until then"
+5 -5
View File
@@ -100,7 +100,7 @@ func searchFor(ctx context.Context) *CallFor {
// can search for it. Never for magpie's own searcher request, which is
// the provider's search.
func magpieSearches(ctx context.Context, p provider.Provider) bool {
return !searching(ctx) && settings.Load().SearchAll && canSearchFor(p)
return !searching(ctx) && settings.Shared().SearchAll && canSearchFor(p)
}
// searchesItself says whether the provider searches the web by itself when
@@ -321,7 +321,7 @@ func searchedForIt(ctx context.Context, p provider.Provider, from provider.Proto
// themselves, with a small model of theirs, as searching needs no more.
// An explicit "off" leaves only the search APIs.
func searcher() (provider.Provider, string, bool) {
if settings.Load().Searcher == "off" {
if settings.Shared().Searcher == "off" {
return provider.Provider{}, "", false
}
if p, m, why := chosenSearcher(); why == "" && p != nil {
@@ -433,7 +433,7 @@ const (
// its small model, as when none is named. Nil when none is named or
// provider search is explicitly off.
func chosenSearcher() (*provider.Provider, string, string) {
return namedSearcher(settings.Load().Searcher)
return namedSearcher(settings.Shared().Searcher)
}
// namedSearcher is chosenSearcher of v, a searcher as Settings writes it.
@@ -773,14 +773,14 @@ func (s *Server) webSearch(ctx context.Context, query string) (string, []Hit, er
if !searchServed() {
return "", nil, errSearchOff
}
if settings.Load().Searcher == "off" {
if settings.Shared().Searcher == "off" {
if len(provider.SearchAPIs()) == 0 {
return "", nil, errNoSearcher
}
return s.apiSearch(ctx, query)
}
var errs []error
apiFirst := settings.Load().SearchFirst == settings.SearchFirstAPI && len(provider.SearchAPIs()) > 0
apiFirst := settings.Shared().SearchFirst == settings.SearchFirstAPI && len(provider.SearchAPIs()) > 0
if apiFirst {
said, hits, err := s.apiSearch(ctx, query)
if err == nil {
+1 -1
View File
@@ -49,7 +49,7 @@ const (
// glmSearches is whether p is a GLM Coding Plan that searches for its own
// models first: one with a plan's key, while Settings names no searcher.
func glmSearches(p provider.Provider) bool {
return provider.ZhipuSearches(p) && strings.TrimSpace(settings.Load().Searcher) == ""
return provider.ZhipuSearches(p) && strings.TrimSpace(settings.Shared().Searcher) == ""
}
// glmSearch asks p's GLM Coding Plan's search MCP server, with each of its
+1 -1
View File
@@ -57,7 +57,7 @@ func canSearchFor(p provider.Provider) bool {
// or an AI Studio key's own Gemini (geminiKeySearches). Never with provider search Off in Settings (#1483), which
// leaves the search APIs alone, nor with plugins/search off.
func searchesOwn(p provider.Provider) bool {
if !searchServed() || settings.Load().Searcher == "off" {
if !searchServed() || settings.Shared().Searcher == "off" {
return false
}
return provider.KimiCodeSearch(p) != "" || glmSearches(p) || wbSearches(p) || (googleAccount(p) || geminiKeySearches(p)) && searcherModel(p) != ""
+1 -1
View File
@@ -83,7 +83,7 @@ func searchEffort(p provider.Provider, model string) string {
if model == "" || model == codexSearchModel {
return ""
}
return sideEffort(p.ID+"/"+model, settings.Load().SearcherEffort)
return sideEffort(p.ID+"/"+model, settings.Shared().SearcherEffort)
}
// SearchEffortNow is the level the searcher in use is asked at, when one
+1 -1
View File
@@ -52,7 +52,7 @@ var toolResultMarks = map[provider.Protocol][][]byte{
// stoppedToolLoop answers r here when its conversation is stuck in a tool
// loop, and says whether it did.
func (s *Server) stoppedToolLoop(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) bool {
if settings.Load().NoLoopGuard || !mayLoop(from, body) {
if settings.Shared().NoLoopGuard || !mayLoop(from, body) {
return false
}
req, err := parse(from, tailOf(from, body))
+1 -1
View File
@@ -51,7 +51,7 @@ var turnAfter = func() time.Duration {
if TurnDone == nil {
return 0
}
return time.Duration(settings.Load().TurnDoneAlert) * time.Second
return time.Duration(settings.Shared().TurnDoneAlert) * time.Second
}
// turnStale: a session with nothing for this long starts its next turn
+1 -1
View File
@@ -286,7 +286,7 @@ func Videomaker() string {
// names when magpie can't make videos with it any more, so that
// AutoVideomaker's makes them in its place, as DrawerMissing is Image
// generation's. "" when none is named or it resolves.
func VideomakerMissing() string { return VideomakerMissingOf(settings.Load().VideoGen) }
func VideomakerMissing() string { return VideomakerMissingOf(settings.Shared().VideoGen) }
// VideomakerMissingOf is v, a Video generation pick, when magpie can't
// make videos with it: its provider is gone, off or decide-only, or no
+2 -2
View File
@@ -44,7 +44,7 @@ var Env = []string{"GITHUB_TOKEN", "GH_TOKEN"}
// set in Settings, none: the user chose that one over the environment's,
// and the page says requests go without a token till it is replaced.
func Token() (token, from string) {
if t := strings.TrimSpace(settings.Load().GitHubToken); t != "" {
if t := strings.TrimSpace(settings.Shared().GitHubToken); t != "" {
if isRefused(t) {
return "", ""
}
@@ -98,7 +98,7 @@ func markSettingsRefused(t string) {
// that field is changed or magpie restarts, so a stale token costs the user
// the 5,000 an hour it was for and not every check (#3926).
func SettingsRefused() (time.Time, bool) {
now := strings.TrimSpace(settings.Load().GitHubToken)
now := strings.TrimSpace(settings.Shared().GitHubToken)
settingsRefused.Lock()
defer settingsRefused.Unlock()
if settingsRefused.t == "" || now != settingsRefused.t {
+4 -4
View File
@@ -1837,7 +1837,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
Refused string `json:"refused,omitempty"`
}
if err := agent.SetTelemetryAll(in.Off); err != nil {
if settings.Load().AgentTelemetryOff != in.Off {
if settings.Shared().AgentTelemetryOff != in.Off {
fail(rw, err)
return
}
@@ -2128,7 +2128,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
fail(rw, err)
return
}
pct := settings.Load().CodexAsyncCompactPercent
pct := settings.Shared().CodexAsyncCompactPercent
if in.Percent != nil {
pct = *in.Percent
}
@@ -3413,7 +3413,7 @@ type signInOpened struct {
// it went for signInOpened. linkOnly is this sign-in alone kept to its link
// (the window's "Sign in on another computer"), whatever the setting.
func openSignIn(w Windows, st provider.SignInState, linkOnly bool) signInOpened {
if linkOnly || settings.Load().SignInLinkOnly {
if linkOnly || settings.Shared().SignInLinkOnly {
return signInOpened{SignInState: st, LinkOnly: true}
}
var failed string
@@ -3435,7 +3435,7 @@ type mcpSignInOpened struct {
// (settings.SignInLinkOnly), as an account's is. It opened the page in the
// default browser whatever the setting (hkxhkxhkx on X).
func openMCPSignIn(w Windows, st mcpauth.State) mcpSignInOpened {
if settings.Load().SignInLinkOnly {
if settings.Shared().SignInLinkOnly {
return mcpSignInOpened{State: st, LinkOnly: true}
}
if u, err := url.Parse(st.URL); st.URL != "" && (err != nil || !mcpauth.WebURL(u)) {
+8 -8
View File
@@ -409,7 +409,7 @@ func Run(version string, showMain bool, link string) error {
// the pages open at the saved text size: Windows' and Linux's webviews
// take it as they are made (the Zoom options below), the Mac's once
// the app has started (applyZoom)
h.textSize.Store(int64(settings.Load().TextSize))
h.textSize.Store(int64(settings.Shared().TextSize))
zoom := h.zoom()
go stats.Run(version, "app")
handler := devShell(h)
@@ -428,7 +428,7 @@ func Run(version string, showMain bool, link string) error {
}
// a quiet start joins the Dock once started (below): Wails activates
// an app that starts in it
policy := dockPolicy(settings.Load().Dock && !quiet)
policy := dockPolicy(settings.Shared().Dock && !quiet)
webView2Prepare()
h.app = application.New(application.Options{
// Windows and Linux start a new process for a magpie:// link (or a
@@ -502,7 +502,7 @@ func Run(version string, showMain bool, link string) error {
// Command-Q asks first while agents are connected (quitask.go). The
// role's item sends terminate:, which logging out and shutting down
// send too, so it is replaced rather than the app's ShouldQuit set
appQuit = askingQuit(appMenu, trayText(trayLang(settings.Load().Lang, systemLang), "Quit magpie"), func() { go h.AskQuit() })
appQuit = askingQuit(appMenu, trayText(trayLang(settings.Shared().Lang, systemLang), "Quit magpie"), func() { go h.AskQuit() })
h.app.Menu.Set(appMenu)
}
if Started != nil {
@@ -538,7 +538,7 @@ func Run(version string, showMain bool, link string) error {
onFonts = h.fontsChanged
// the menu in the page's language, relabelled when that changes (#301)
labels := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, "", pausedNow())
labels := trayMenuLabels(trayLang(settings.Shared().Lang, systemLang), version, "", pausedNow())
menu := h.app.NewMenu()
open := menu.Add(labels.open).OnClick(func(*application.Context) { h.ShowMain("") })
menu.AddSeparator()
@@ -575,9 +575,9 @@ func Run(version string, showMain bool, link string) error {
quit := menu.Add(labels.quit).OnClick(func(*application.Context) { go h.AskQuit() })
var ready string // the version waiting for a restart; on the main thread
relabel := func() {
l := trayMenuLabels(trayLang(settings.Load().Lang, systemLang), version, ready, pausedNow())
l := trayMenuLabels(trayLang(settings.Shared().Lang, systemLang), version, ready, pausedNow())
if waiting, b := updates.waitingFor(); waiting && ready != "" {
l.restart = trayRestartNow(trayLang(settings.Load().Lang, systemLang), b)
l.restart = trayRestartNow(trayLang(settings.Shared().Lang, systemLang), b)
}
open.SetLabel(l.open)
pause.SetLabel(l.pause)
@@ -709,7 +709,7 @@ func Run(version string, showMain bool, link string) error {
if runtime.GOOS == "darwin" {
go h.flap()
}
if settings.Load().Tray == "window" {
if settings.Shared().Tray == "window" {
h.ShowMain("")
return
}
@@ -754,7 +754,7 @@ func Run(version string, showMain bool, link string) error {
view = uninstallView
}
h.whenReady(func() { h.ShowMain(view) })
} else if quiet && settings.Load().Dock {
} else if quiet && settings.Shared().Dock {
// kept out of the Dock to start (Mac options above), it joins
// now without coming to the front
h.whenReady(func() { setDock(true, false) })
+1 -1
View File
@@ -113,7 +113,7 @@ func searchesNow() []string {
switch {
case by == "":
return apis
case settings.Load().SearchFirst == settings.SearchFirstAPI:
case settings.Shared().SearchFirst == settings.SearchFirstAPI:
return append(apis, by)
}
return append([]string{by}, apis...)
+1 -1
View File
@@ -43,7 +43,7 @@ func gatewayMode(web bool) (bool, string) {
if !web {
return false, ""
}
switch m := settings.Load().GatewayMode; m {
switch m := settings.Shared().GatewayMode; m {
case "on", "off":
return m == "on", m
}
+1 -1
View File
@@ -22,7 +22,7 @@ import (
// reader's language.
func askInstallFolder() {
update.AskFolder = func(suggest string, check func(string) error) string {
w := installWordsFor(trayLang(settings.Load().Lang, systemLang))
w := installWordsFor(trayLang(settings.Shared().Lang, systemLang))
var out string
done := make(chan struct{})
// COM and the dialogs on a thread of their own, which ends with
+3 -3
View File
@@ -35,12 +35,12 @@ func (h *host) makeMain(url string) *application.WebviewWindow {
minW, minH := windowMin(z, 0, 0)
width, height := openSize(settings.Load().Window, minW, minH)
state := application.WindowStateNormal
if runtime.GOOS == "linux" && settings.Load().WindowMaximised {
if runtime.GOOS == "linux" && settings.Shared().WindowMaximised {
state = application.WindowStateMaximised
}
// Windows' title bar in the page's colour from the first frame; the
// page keeps it so as its theme changes (TintTitleBar)
winOpts, winBg := windowChrome(cmp.Or(os.Getenv("MAGPIE_THEME"), settings.Load().Theme))
winOpts, winBg := windowChrome(cmp.Or(os.Getenv("MAGPIE_THEME"), settings.Shared().Theme))
w := h.app.Window.NewWithOptions(application.WebviewWindowOptions{
Name: "main",
Title: "magpie",
@@ -410,7 +410,7 @@ func (h *host) placeAt(w *application.WebviewWindow) (maximise bool) {
}
fitted = false
}
return settings.Load().WindowMaximised && !fitted
return settings.Shared().WindowMaximised && !fitted
}
// putBack moves the main window, not shown yet, to where it was last left
+1 -1
View File
@@ -22,7 +22,7 @@ type modelPriceJSON struct {
func anyModelPrice(model string) modelPriceJSON {
out := modelPriceJSON{Model: model}
if m, ok := settings.Load().ModelPrices[provider.AnyPriceKey(model)]; ok {
if m, ok := settings.Shared().ModelPrices[provider.AnyPriceKey(model)]; ok {
if p, bad := m.Price(); bad == "" {
out.Price = &p
}
+3 -3
View File
@@ -23,13 +23,13 @@ func (h *host) startPanelKey(before int) {
onPanelShortcut = h.bindPanelKey
go func() {
<-h.ready
s := settings.Load().PanelShortcut
s := settings.Shared().PanelShortcut
if s == "" || !panelKeysState().Can {
return
}
if h.bindPanelKey(s) != nil && before != 0 {
awaitExit(before, handedOffWait)
if settings.Load().PanelShortcut == s {
if settings.Shared().PanelShortcut == s {
_ = h.bindPanelKey(s)
}
}
@@ -56,7 +56,7 @@ func (h *host) bindPanelKey(s string) error {
if old != "" && old != s && gs.Register(old, h.panelKeyPressed) == nil {
h.panelKey = old
}
if s == settings.Load().PanelShortcut {
if s == settings.Shared().PanelShortcut {
panelKeyTaken.Store(s)
}
if strings.Contains(err.Error(), "already registered") {
+1 -1
View File
@@ -248,7 +248,7 @@ func registryJSON() plugin.RegistryInUse {
}
func pluginsState(ctx context.Context, w Windows) pluginsJSON {
s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Load().ChinaMirror, Registry: registryJSON()}
s := pluginsJSON{Plugins: []pluginEntryJSON{}, Bun: plugin.HasBun(), BunVer: plugin.BunInUse(), Movable: provider.MoveCandidates(), Picker: w != nil && !isWeb(w), Mirror: settings.Shared().ChinaMirror, Registry: registryJSON()}
l := plugin.Load()
errs := map[string]string{}
names := map[string][]string{}
+1 -1
View File
@@ -1507,7 +1507,7 @@ func providersState() providersJSON {
}
cat, models := provider.CatalogGroups()
s.Gateway = gatewayJSON{URL: gateway.URL(), OnNetwork: gateway.OnNetwork(), Models: models, Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
s.Gateway.LAN = settings.Load().LAN || s.Gateway.OnNetwork
s.Gateway.LAN = settings.Shared().LAN || s.Gateway.OnNetwork
if s.Gateway.LAN {
s.Gateway.LANURLs = gateway.LANURLs()
s.Gateway.LANPublic = gateway.PublicURLs(s.Gateway.LANURLs)
+4 -4
View File
@@ -186,14 +186,14 @@ func (h *host) watchAlerts() {
go n.allowed()
}
// a value masked for the first time (Must2333 on X)
masks := newMaskAlerts(func() bool { return settings.Load().MaskAlert }, func(m maskNote) {
title, body := maskAlertText(trayLang(settings.Load().Lang, systemLang), m, agentName)
masks := newMaskAlerts(func() bool { return settings.Shared().MaskAlert }, func(m maskNote) {
title, body := maskAlertText(trayLang(settings.Shared().Lang, systemLang), m, agentName)
n.sendAs(fmt.Sprintf("%s%d-", maskNotice, m.Key), title, body)
})
gateway.OnMasked = masks.add
// an agent's turn done, past the length set (itieniu on X)
gateway.TurnDone = func(t gateway.TurnEnd) {
title, body := turnDoneText(trayLang(settings.Load().Lang, systemLang), agentName(t.Agent), t)
title, body := turnDoneText(trayLang(settings.Shared().Lang, systemLang), agentName(t.Agent), t)
n.sendAs(turnNotice, title, body)
}
// an account in use signed out, or a Claude sign-in about to end
@@ -201,7 +201,7 @@ func (h *host) watchAlerts() {
// again is
go watchBarkDaily(backendCtx)
go provider.WatchSignIns(backendCtx, func(a provider.SignInAlert) {
title, body := signInText(trayLang(settings.Load().Lang, systemLang), a, time.Now())
title, body := signInText(trayLang(settings.Shared().Lang, systemLang), a, time.Now())
n.sendAs(signInKind(a.Provider), title, body)
})
// until this one has handed the gateway to the new version,
+4 -4
View File
@@ -406,7 +406,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
fail(rw, errors.New("no such session"))
return
}
if err := openTerminal(run, s.Title, settings.Load().SessionTerminal); err != nil {
if err := openTerminal(run, s.Title, settings.Shared().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -452,7 +452,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
fail(rw, errors.New("no command starts this agent"))
return
}
if err := agentTerminal(run, name, settings.Load().SessionTerminal); err != nil {
if err := agentTerminal(run, name, settings.Shared().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -487,7 +487,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
return
}
if in.Open {
if err := openTerminal(c.Command, s.Title, settings.Load().SessionTerminal); err != nil {
if err := openTerminal(c.Command, s.Title, settings.Shared().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -1257,7 +1257,7 @@ func agentCommand(a *agent.Agent) string {
// the app where one is installed, unless the setting codexOpen asks for the
// terminal (Yink88564391 on X).
func codexOpensApp() bool {
return settings.Load().CodexOpen != "terminal" && codexAppInstalled()
return settings.Shared().CodexOpen != "terminal" && codexAppInstalled()
}
// codexAppInstalled and codexAppOpener are the agent package's, vars so a
+2 -2
View File
@@ -127,7 +127,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
fail(rw, err)
return
}
writeJSON(rw, map[string]bool{"recording": settings.Load().GatewayConversations})
writeJSON(rw, map[string]bool{"recording": settings.Shared().GatewayConversations})
})
// speeds: each session's output speed now (gateway.Speeds), for the
// page's curves while it is open. Not under /api/sessions, which
@@ -164,7 +164,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
// asks first when nothing is decided (asked false)
Reads readsJSON `json:"reads"`
}{Reads: readsNow(), Agents: []manageAgentJSON{}, Sessions: []managedJSON{}, Terminal: runtime.GOOS == "darwin" && !isWeb(w),
Trash: trashJSON(looks), TrashDir: tilde(sessions.TrashDir()), Recording: settings.Load().GatewayConversations,
Trash: trashJSON(looks), TrashDir: tilde(sessions.TrashDir()), Recording: settings.Shared().GatewayConversations,
Recorded: sessions.HasGatewayConversations()}
out.Home, _ = os.UserHomeDir()
want := r.URL.Query().Get("agent")
+1 -1
View File
@@ -34,7 +34,7 @@ func takeStable(ctx context.Context) {
if !freshInstall.Load() {
return
}
if !update.Released(Version) || settings.Load().UpdateChannel != "" {
if !update.Released(Version) || settings.Shared().UpdateChannel != "" {
freshInstall.Store(false)
return
}
+3 -3
View File
@@ -33,7 +33,7 @@ import (
// more than the Usage page asks them: their answers are cached for a
// minute, and this reads the cache.
func trayUsageEvery() time.Duration {
return time.Duration(settings.Load().TrayUsageEvery) * time.Minute
return time.Duration(settings.Shared().TrayUsageEvery) * time.Minute
}
// trayCardID names a card for settings.TrayUsage: its provider, and the
@@ -408,7 +408,7 @@ func trayUsageCards(ctx context.Context, lang string, ids []string) []provider.S
}
if currency == "" {
currency, rate = trayCurrency()
noCost = settings.Load().TrayNoCost
noCost = settings.Shared().TrayNoCost
}
cards = append(cards, trayTotalCard(lang, id, trayMoney(trayTotalSum(p), noCost), currency, rate))
}
@@ -580,7 +580,7 @@ func trayIdleTip(lang string, t usage.Totals, currency string, rate float64) str
}
// trayChineseUnits is Settings' 万/亿 choice, read when a count is said.
var trayChineseUnits = func() bool { return settings.Load().ChineseUnits }
var trayChineseUnits = func() bool { return settings.Shared().ChineseUnits }
// trayCount is a count as the Usage page says it (fmtN in app.js): 133M,
// 1.2M, 456K, 8.2K, 950; with Settings' 万/亿 units and magpie in Chinese,
+1 -1
View File
@@ -155,7 +155,7 @@ func (h *host) trayCellClick(id string) {
if id == "" {
return
}
if settings.Load().Tray == "window" {
if settings.Shared().Tray == "window" {
h.ShowMain(quotaView(id))
return
}
+1 -1
View File
@@ -433,7 +433,7 @@ func (u *updater) freshen() {
// the dialog asks for nothing to be downloaded; with downloads
// automatic it names the one waiting, which the restart goes
// into, and takes the notes the feed has for it now (#649)
u.ask(false, !settings.Load().NoAutoDownload)
u.ask(false, !settings.Shared().NoAutoDownload)
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ func webView2Check(app *application.App) bool {
return true
}
log.Printf("magpie: no Microsoft Edge WebView2 Runtime, which magpie's windows need; install it from %s, or use magpie web / magpie tui", webView2Page)
title, body := webView2Notice(trayLang(settings.Load().Lang, systemLang))
title, body := webView2Notice(trayLang(settings.Shared().Lang, systemLang))
if webView2Box(title, body) == idYes {
if err := windows.ShellExecute(0, windows.StringToUTF16Ptr("open"), windows.StringToUTF16Ptr(webView2Page), nil, nil, windows.SW_SHOWNORMAL); err != nil {
log.Println("magpie: opening the WebView2 page:", err)
@@ -148,7 +148,7 @@ func webView2Failed(app *application.App, err error) {
return
}
}
title, body := webView2FailedNotice(trayLang(settings.Load().Lang, systemLang), err.Error(), ver)
title, body := webView2FailedNotice(trayLang(settings.Shared().Lang, systemLang), err.Error(), ver)
procMessageBoxW.Call(0,
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(body))),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))),
+1 -1
View File
@@ -412,7 +412,7 @@ func pageLang(r *http.Request) string {
if l := askedLang(r); l != "" {
return l
}
return notesLang(trayLang(settings.Load().Lang, systemLang))
return notesLang(trayLang(settings.Shared().Lang, systemLang))
}
// askedLang is the language a page names (?lang=): zh for any Chinese, en
+1 -1
View File
@@ -160,7 +160,7 @@ func toGuard() {
}
g := pii.Of(pii.AstrLinkGuard)
g.Download(func() {
if settings.Load().RedactModelName == "" && settings.UseRedactModel(pii.AstrLinkGuard) == nil {
if settings.Shared().RedactModelName == "" && settings.UseRedactModel(pii.AstrLinkGuard) == nil {
pii.Of(pii.PrivacyFilter).Stop()
g.Warm()
}
+5 -5
View File
@@ -152,7 +152,7 @@ func With(ctx context.Context, choice string) context.Context {
// vendors without). Its "" leaves ctx as it is, so they follow the
// global proxy as every other request does.
func Downloads(ctx context.Context) context.Context {
if c := strings.TrimSpace(settings.Load().PluginProxy); c != "" {
if c := strings.TrimSpace(settings.Shared().PluginProxy); c != "" {
return With(ctx, c)
}
return ctx
@@ -161,7 +161,7 @@ func Downloads(ctx context.Context) context.Context {
// EnvDownloads is Env for a program magpie starts to download plugins
// (bun add and update, git): plugin downloads' proxy (Downloads), or,
// when that names none, Env's.
func EnvDownloads(env []string) []string { return EnvWith(settings.Load().PluginProxy, env) }
func EnvDownloads(env []string) []string { return EnvWith(settings.Shared().PluginProxy, env) }
// Choice is the proxy ctx names (With), "" when it names none — for a CLI
// run on a provider's behalf, whose *_PROXY is set from it (EnvWith).
@@ -379,7 +379,7 @@ func (d *dispatch) CloseIdleConnections() {
// For is the proxy a request to u goes through; nil means direct.
func For(u *url.URL) (*url.URL, error) {
switch s := strings.TrimSpace(settings.Load().Proxy); s {
switch s := strings.TrimSpace(settings.Shared().Proxy); s {
case "direct":
return nil, nil
case "":
@@ -416,7 +416,7 @@ func EnvWith(choice string, env []string) []string {
var bypass []string
s := strings.TrimSpace(choice)
if s == "" {
s = strings.TrimSpace(settings.Load().Proxy)
s = strings.TrimSpace(settings.Shared().Proxy)
}
if settings.IsProxyRef(s) {
// a saved proxy that is gone: the CLI goes nowhere, not direct
@@ -508,7 +508,7 @@ func Parse(s string) (*url.URL, error) {
// Describe says, for the settings page, what a request to u would use.
func Describe() (proxy, source string) {
defer func() { proxy = Redact(proxy) }()
switch s := strings.TrimSpace(settings.Load().Proxy); s {
switch s := strings.TrimSpace(settings.Shared().Proxy); s {
case "direct":
return "", "off"
case "":
+1 -1
View File
@@ -55,7 +55,7 @@ var loginEnv = proc.LoginEnvKnown
// registry the user set is never put behind magpie's switch (timwangdev
// on X: plugins from a custom npm registry).
func Registry() RegistryInUse {
if u, err := CleanRegistry(settings.Load().NPMRegistry); err == nil && u != "" {
if u, err := CleanRegistry(settings.Shared().NPMRegistry); err == nil && u != "" {
return RegistryInUse{URL: u, From: FromMagpie}
}
if r, ok := userRegistry(); ok {
+1 -1
View File
@@ -64,7 +64,7 @@ func withAgentWindows(s settings.Settings, agent string, es []Entry) []Entry {
// AgentContexts are the windows agent (its list id, Agent.ListsFor) was set.
func AgentContexts(agent string) map[string]int {
return maps.Clone(settings.Load().AgentContexts[agentKey(agent)])
return maps.Clone(settings.Shared().AgentContexts[agentKey(agent)])
}
// SetAgentContexts gives agent the windows in cs, replacing those it had;
+1 -1
View File
@@ -24,7 +24,7 @@ import (
// listed by it.
// BareModelIDs says whether /v1/models lists models by their bare ids too.
func BareModelIDs() bool { return settings.Load().BareModelIDs }
func BareModelIDs() bool { return settings.Shared().BareModelIDs }
// SetBareModelIDs turns settings.BareModelIDs on or off. The list is built
// for each request, so the next one has the bare ids, or goes without
+1 -1
View File
@@ -178,7 +178,7 @@ func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin
func checkinGate(now time.Time) time.Time {
t := now.In(beijing)
start := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, beijing)
h, m, ok := settings.Clock(settings.Load().CheckinAt)
h, m, ok := settings.Clock(settings.Shared().CheckinAt)
if !ok {
return start
}
+1 -1
View File
@@ -28,4 +28,4 @@ import "github.com/yetone/magpie/internal/settings"
// ClaudeExtraUsage says whether magpie sends a Claude account requests
// once its plan is used up, for Anthropic to bill as extra usage: true
// unless the user turned it off.
func ClaudeExtraUsage() bool { return !settings.Load().ClaudeNoExtraUsage }
func ClaudeExtraUsage() bool { return !settings.Shared().ClaudeNoExtraUsage }
+1 -1
View File
@@ -577,7 +577,7 @@ func codexWarmAtOf() map[string]string {
// CodexWarmAtOf is user's own time of day to start its 5-hour window at,
// "off" for none; false when it follows settings' CodexWarmAts.
func CodexWarmAtOf(user string) (string, bool) {
at, ok := settings.Load().CodexWarmAtOf[strings.ToLower(strings.TrimSpace(user))]
at, ok := settings.Shared().CodexWarmAtOf[strings.ToLower(strings.TrimSpace(user))]
return at, ok
}
+3 -3
View File
@@ -155,7 +155,7 @@ const (
func (g Group) Waits() time.Duration {
n := g.Patience
if n == 0 {
n = settings.Load().GroupPatience
n = settings.Shared().GroupPatience
}
switch {
case n < 0:
@@ -178,7 +178,7 @@ func (g Group) FirstTokenOr() int {
if g.FirstToken != 0 {
return g.FirstToken
}
return settings.Load().GroupFirstToken
return settings.Shared().GroupFirstToken
}
// Sinks is whether one of the group's accounts or keys rate limited with
@@ -186,7 +186,7 @@ func (g Group) FirstTokenOr() int {
// NoSink, else the default for every group (settings' GroupSink). Whether
// its routing can sink at all is the gateway's to say.
func (g Group) Sinks() bool {
return g.Sink || !g.NoSink && settings.Load().GroupSink
return g.Sink || !g.NoSink && settings.Shared().GroupSink
}
// ContextSmallest is a group's Context when agents are told the window of
+1 -1
View File
@@ -313,5 +313,5 @@ func miniMaxSiteAccounts(site string, pp plugin.Provider) []miniMaxAccount {
// KeepMiniMaxCheckedIn checks the MiniMax Code accounts in each day while
// settings say to, as KeepTraeCheckedIn does Trae CN's.
func KeepMiniMaxCheckedIn(ctx context.Context) {
keepCheckedIn(ctx, "minimax", newMiniMaxCheckiner(miniMaxCheckinAccounts), func() bool { return settings.Load().MiniMaxCheckin })
keepCheckedIn(ctx, "minimax", newMiniMaxCheckiner(miniMaxCheckinAccounts), func() bool { return settings.Shared().MiniMaxCheckin })
}
+1 -1
View File
@@ -53,7 +53,7 @@ func (p Provider) modelOf(ctx context.Context) string {
// ModelHeaders are the headers the user gave provider pid's model.
func ModelHeaders(pid, model string) map[string]string {
return settings.Load().ModelHeaders[pid+"/"+model]
return settings.Shared().ModelHeaders[pid+"/"+model]
}
// headersFor are p's Headers with model's after them: a name of the
+3 -3
View File
@@ -181,7 +181,7 @@ func PriceKey(pid, model string) (string, bool) {
return AnyPriceKey(model), false
}
key := pid + "/" + model
if _, under := settings.Load().ModelPrices[key]; under {
if _, under := settings.Shared().ModelPrices[key]; under {
_, there := byIDOrWas(pid)
return key, there
}
@@ -1011,7 +1011,7 @@ func SuffixModeFor(agent string) string { return suffixModeOf(settings.Load(), a
// AgentSuffix is the agent's own mode, "" when it follows every agent's.
func AgentSuffix(agent string) string {
return settings.Load().AgentSuffix[suffixKey(agent)]
return settings.Shared().AgentSuffix[suffixKey(agent)]
}
// suffixKey is the id an agent's own mode is kept by: a WSL copy and a
@@ -1517,7 +1517,7 @@ func DropUpstreamName(key string) (bool, error) {
// already (splitModelRef), so nothing depends on it yet.
func HasUpstreamName(key string) bool {
key = strings.TrimPrefix(strings.TrimSpace(key), "magpie/")
_, ok := settings.Load().ModelWires[key]
_, ok := settings.Shared().ModelWires[key]
return ok
}
+1 -1
View File
@@ -4192,7 +4192,7 @@ func outputKeyOf(id string) (string, error) {
return "", errorf("name a model as provider/model, not %q", id)
}
key := pid + "/" + model
if _, under := settings.Load().ModelOutputs[key]; under {
if _, under := settings.Shared().ModelOutputs[key]; under {
return key, nil
}
if p, ok := byIDOrWas(pid); ok {
+1 -1
View File
@@ -286,5 +286,5 @@ func qoderCheckinAccounts() []qoderCheckinAcct {
// KeepQoderCheckedIn checks the Qoder accounts in each day while settings
// say to, as KeepTraeCheckedIn does Trae CN's.
func KeepQoderCheckedIn(ctx context.Context) {
keepCheckedIn(ctx, "qoder", newQoderCheckiner(qoderCheckinAccounts, time.Now), func() bool { return settings.Load().QoderCheckin })
keepCheckedIn(ctx, "qoder", newQoderCheckiner(qoderCheckinAccounts, time.Now), func() bool { return settings.Shared().QoderCheckin })
}
+1 -1
View File
@@ -41,7 +41,7 @@ func wasAsked(ctx context.Context) bool {
var errNotAsked = errors.New("not read yet: magpie reads allowances only when you ask (Settings → Usage)")
// readsAsked is whether the user has allowances read only when asked.
func readsAsked() bool { return settings.Load().QuotaReads == "asked" }
func readsAsked() bool { return settings.Shared().QuotaReads == "asked" }
// heldRead is whether a read made with ctx is held back: the user has
// allowances read only when asked, and ctx is not one they asked for.
+1 -1
View File
@@ -261,5 +261,5 @@ func traeCheckinAccounts() []traeAccount {
// KeepTraeCheckedIn checks the Trae CN accounts in each day while settings
// say to, as KeepWorkBuddyCheckedIn does WorkBuddy's.
func KeepTraeCheckedIn(ctx context.Context) {
keepCheckedIn(ctx, "trae", newTraeCheckiner(traeCheckinAccounts), func() bool { return settings.Load().TraeCheckin })
keepCheckedIn(ctx, "trae", newTraeCheckiner(traeCheckinAccounts), func() bool { return settings.Shared().TraeCheckin })
}
+1 -1
View File
@@ -613,7 +613,7 @@ func wbPluginAccounts(pp plugin.Provider) []wbAccount {
// settings say to: two minutes after it starts, every wbCheckinEvery after
// that, and as the Beijing day turns, until ctx ends.
func KeepWorkBuddyCheckedIn(ctx context.Context) {
keepCheckedIn(ctx, "workbuddy", newWBCheckiner(), func() bool { return settings.Load().WorkBuddyCheckin })
keepCheckedIn(ctx, "workbuddy", newWBCheckiner(), func() bool { return settings.Shared().WorkBuddyCheckin })
}
// keepCheckedIn runs c while on says to. The clock is looked at every
+2 -2
View File
@@ -75,7 +75,7 @@ func SaveGatewayTurnGeneration(turn GatewayTurn, generation uint64) error {
func saveGatewayTurn(turn GatewayTurn, generation uint64) error {
gatewayMu.Lock()
allowed := settings.Load().GatewayConversations && generation == gatewayGeneration
allowed := settings.Shared().GatewayConversations && generation == gatewayGeneration
gatewayMu.Unlock()
if !allowed || turn.Agent == "" || turn.Session == "" {
return nil
@@ -121,7 +121,7 @@ func saveGatewayTurn(turn GatewayTurn, generation uint64) error {
}
gatewayMu.Lock()
defer gatewayMu.Unlock()
if generation != gatewayGeneration || !settings.Load().GatewayConversations {
if generation != gatewayGeneration || !settings.Shared().GatewayConversations {
return nil
}
dir := filepath.Join(gatewayDir(), turn.Time.UTC().Format(time.DateOnly), gatewayIdentity(turn.Agent, turn.Session))
+1 -1
View File
@@ -34,7 +34,7 @@ const NPMMirror = npmMirror
// China is whether the Plugins page's 「国内镜像」 switch is on
// (settings.ChinaMirror); a var for tests.
var China = func() bool { return settings.Load().ChinaMirror }
var China = func() bool { return settings.Shared().ChinaMirror }
// chinaFirst is the mirror in China asked before raw with the switch on,
// "" when there is none. Only mirrors that serve the same bytes as the
+3 -3
View File
@@ -49,7 +49,7 @@ func Off() bool {
return true
}
}
return settings.Load().NoStats
return settings.Shared().NoStats
}
// Run sends the day's event while magpie runs, as what ("app", "serve"): at
@@ -96,7 +96,7 @@ func Send(ctx context.Context, version, what string, now time.Time) error {
"arch": runtime.GOARCH,
}
var uses []map[string]any
if !settings.Load().NoUsageStats {
if !settings.Shared().NoUsageStats {
u := usage()
active["agents"] = len(u.Agents)
active["providers"] = len(u.Providers)
@@ -137,7 +137,7 @@ func Send(ctx context.Context, version, what string, now time.Time) error {
if res.StatusCode/100 != 2 {
return fmt.Errorf("stats: %s", res.Status)
}
if !settings.Load().NoUsageStats {
if !settings.Shared().NoUsageStats {
provider.PartnerCountsSent(now)
// Discover's counts; the day's event went, so this isn't tried
// again till tomorrow when it fails
+1 -1
View File
@@ -81,7 +81,7 @@ func notProxy(proxy string) string {
func mirrorOf(ctx context.Context) string {
m, _ := ctx.Value(mirrorKey{}).(string)
if m == "" {
m = strings.TrimSpace(settings.Load().UpdateMirror)
m = strings.TrimSpace(settings.Shared().UpdateMirror)
}
if m == "off" || m == "direct" {
return ""
+1 -1
View File
@@ -169,7 +169,7 @@ func MostNotes() int {
// ban risk, lost data) as soon as it is out. usemagpie.ai chooses it from
// the release list (site/worker.js, "The Stable channel"); a release is
// urgent when a line of its notes starts with "**Urgent release:**".
func Stable() bool { return settings.Load().UpdateChannel == settings.UpdateStable }
func Stable() bool { return settings.Shared().UpdateChannel == settings.UpdateStable }
// withChannel is feed asking for Stable's release on the Stable channel,
// and feed as it is on every version.
+1 -1
View File
@@ -11,7 +11,7 @@ import "github.com/yetone/magpie/internal/settings"
// version inside it and every file's hash from it. MAGPIE_UPDATE_FEED, a
// test's feed, is never overridden by it.
func Source() string {
switch s := settings.Load().UpdateSource; s {
switch s := settings.Shared().UpdateSource; s {
case settings.UpdateSourceSite, settings.UpdateSourceGitHub:
return s
}
+1 -1
View File
@@ -114,7 +114,7 @@ func proxied() http.RoundTripper {
type updateProxy struct{ http.RoundTripper }
func (u updateProxy) RoundTrip(req *http.Request) (*http.Response, error) {
if c := strings.TrimSpace(settings.Load().UpdateProxy); c != "" && netproxy.Choice(req.Context()) == "" {
if c := strings.TrimSpace(settings.Shared().UpdateProxy); c != "" && netproxy.Choice(req.Context()) == "" {
req = req.WithContext(netproxy.With(req.Context(), c))
}
return u.RoundTripper.RoundTrip(req)
+1 -1
View File
@@ -71,7 +71,7 @@ const findAge = time.Minute
// Detect agents in WSL off, or when no running distro has it.
func Find(name string) (Tool, bool) {
// Settings' Detect agents in WSL, off, looks in no distro (#1264)
if !On || settings.Load().NoWSLAgents {
if !On || settings.Shared().NoWSLAgents {
return Tool{}, false
}
found.Lock()