agent: Antigravity's effort is picked in its row, as its app can't say one (#4838)

MDX-Tom (#4838): Antigravity's app lists the gateway's models by id, with
no level control of its own, so a request for one of Antigravity's
families of levels (gemini-3.8-flash -> -high/-low) went at the level the
app asked or the family's default, and nothing in magpie could change it.
Their plugins PR #655 forced a level in middleware, over any level the
request carried and on every model named like gemini/flash, for every
agent. This puts it in core instead, as Cursor Private Inference has
since #1003: Antigravity's agent row gets an effort field, kept in
magpie (provider.AgentEffort "antigravity"), whose levels are those of
the models it lists (cursorLocalEfforts is now pickedEfforts(agent)).
The gateway already asks an agent's requests for its picked level; on an
Antigravity account that picks the family's variant (AntigravitySentID)
and its thinkingLevel. With none picked the requests go as they asked.
The field is shown only while the app is on magpie's gateway, and
nothing is written to the app's settings.json.

Run on mote at the pushed head (on a858e53fa): gofmt -l clean;
GOOS=linux (nogui) and GOOS=windows go vet of internal/agent and
internal/gateway ok; -run TestAntigravity|TestCursorLocal|TestClaudeDesktop
in internal/agent ok; -run TestAntigravity|TestAgentEffort|TestCodeAssist|
TestCursorLocal in internal/gateway ok. On b295d1196: go test
./internal/agent ok (196s). Before the rebase on 443e53d6b: internal/agent,
internal/provider ok; internal/gateway red only on
TestCodexPoolSaysTheClientsVersion (#4807, passes alone 3/3);
internal/gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, red
on untouched 443e53d6b the same way on mote).

Broken by hand: without the field, TestAntigravityEffort is red ("no
effort field"); with the gateway's agentPick taken out,
TestAntigravityAgentEffort is red (both picks went as -high at "").

Not tried: a real Antigravity account and the real app's picker; the
agy CLI row has no such field (its own /model can say a level). No GUI
suite run: the field renders through the agent row's generic effort
field (cursor-local-effort.test.cjs), no new API call or layout.
This commit is contained in:
yetone
2026-11-03 11:27:31 +08:00
parent a858e53fa9
commit a92cc3f331
6 changed files with 204 additions and 9 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ something else shows up as drift.
| WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users/<user>/.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\<user>\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) |
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`, carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models by id with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |
## Runtime path
+1 -1
View File
@@ -290,7 +290,7 @@ recorded as a prediction failure (`noPrediction`).
- A member the user unchecked in its provider's model list is skipped (`unpicked` in [`group.go`](../../internal/provider/group.go), in `membersOff`; #3911, timonwong): the provider has picks and its served models lack it, as the Routing page strikes it, and the Routing card says it is not ready (`provider.ResolveRoute`). A provider with no picks still routes a model its list lacks (#2642), a decision model is still a decision group's, and a request naming the model itself still reaches it (`resolveIn` takes any `provider/model` of a provider that is on). `group_model_pick_test.go`.
- A member's suffix may join several levels with `+` (`provider/model:low+xhigh`, Garydesu on X): the agent picks among them. `provider.MemberLevels` splits it into `Member.Levels` and leaves `Effort` empty, so it isn't fixed; one level is still a fixed effort. The suffix is kept lowest first, each level once, and the whole stays the member's id, so its rules, fast, off and weight are keyed by it as for any member. The gateway fits the agent's ask to the member's own levels (`groupLevels` returns the candidate's `levels` first), and the group lists those for it to agents (`buildGroupEntries`), intersected with the other members' as usual. In the GUI the member's reasoning menu has "Several levels…". Tests: `TestMemberSeveralLevels` (provider), `TestMemberSeveralLevelsFollowAgent` (gateway), `group-member-levels.test.cjs`.
- A group offers agents the reasoning levels its members have in common (`groupEntries` in [`group.go`](../../internal/provider/group.go)), or the ones it names (`Group.Levels`, #295). A member that doesn't follow the agent's effort is left out of that: one fixed at an effort, one whose levels nothing knows (#597), one that thinks with no levels, one the user made reasonless, and one known not to think (`Entry.Quiet`), which the gateway sends no reasoning ask (`withoutReasoningAsk`, [`quiet.go`](../../internal/gateway/quiet.go)). A quiet member used to empty the group's levels, so Codex got its entry with no `supported_reasoning_levels`, showed no effort control and ran at its own medium (#2127, `TestGroupQuietMemberKeepsCodexEffortControl`).
- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then the effort the rule that put the member first sets (`Rule.UseEffort`), then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003, and Antigravity's, #4838). On an Antigravity account the level picks the family's variant, as a request's own effort does (`AntigravitySentID`, `TestAntigravityAgentEffort`). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then the effort the rule that put the member first sets (`Rule.UseEffort`), then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
- In models.dev, entries from `deepseek`, `kimi-code-plan-cn` and `kimi-code-plan-global` gain `none` only when they have both a `toggle` and effort levels; the DeepSeek and Kimi APIs accepted that value in [#1098](https://github.com/yetone/magpie/issues/1098). Other providers keep their listed levels because their APIs may reject `none`; toggle-only entries remain level-less ([`mdModel.efforts`](../../internal/catalog/catalog.go)).
- Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 or 422 whose error names `extra_body`, `include_thoughts` or thinking at all (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, its least, or at the model's lowest level where it has no `minimal` (`geminiLevels`: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (`geminiRefusedLevel`): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (`levelRefused`), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own `none` or `minimal` that Gemini turns away this way is asked again at the model's lowest level (`onEffort`), and that level goes at the lowest from then on (`turnedAway`); the other still goes as sent, as AI Studio takes `none` from gemini-3.8-flash. A refusal that names the levels the model takes (`effortLevelsNamed`, Command Code's for Qoder's `none`) marks reasoning off as a whole (`offRefused`): both go at the lowest from then on; one that lists the other among the levels taken (`otherOffNamed`, quoted, OpenAI's for gpt-5.1's `minimal`) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking.
- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses a turn's effort on a `{role: "system"}` message (`withoutTurnEffort`: a relay's "messages.1.output_config: Extra inputs are not permitted", or OpenRouter's "Mid-conversation reasoning effort (configuration_update) is not supported on <model>" on DeepSeek and GLM, #3696; `TestOpenRouterTurnEffortLeftOut`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).
+17
View File
@@ -35,6 +35,7 @@ import (
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
)
const (
@@ -191,6 +192,22 @@ func antigravity(home string) *Agent {
}
return withVia(group("Antigravity", own), "antigravity", magpieID+"/")
},
}, {
// how hard its models reason: the app's picker lists the
// gateway's models by id, with no control of its own for a
// level, so Antigravity's own families went at the level
// the app asked or their default (MDX-Tom, #4838). The
// gateway asks its requests for the level picked here
// (provider.AgentEffort), and with none they go as it asks.
Key: "effort", Label: "effort",
Get: func() string { return provider.AgentEffort("antigravity") },
Set: func(v string) error { return provider.SetAgentEffort("antigravity", v) },
Options: func(map[string]string) []Option {
if !wired() {
return nil
}
return pickedEfforts("antigravity")
},
}},
}
}
+54
View File
@@ -9,6 +9,7 @@ import (
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
@@ -278,3 +279,56 @@ func TestAntigravityDetected(t *testing.T) {
t.Fatal("not found by its backend's file")
}
}
// Antigravity's picker lists the gateway's models by id, with no level of
// its own to pick (MDX-Tom, #4838): its effort is picked in its row among
// the levels the models it lists have, the default first, kept in magpie
// for the gateway to ask, and offered only while it is on magpie.
func TestAntigravityEffort(t *testing.T) {
home := antigravityHome(t)
path := filepath.Join(home, ".antigravity", "settings.json")
os.MkdirAll(filepath.Dir(path), 0o755)
os.WriteFile(path, []byte(antigravityUser), 0o600)
if err := provider.Save(provider.Provider{ID: "think", Name: "Think", Chat: "https://think.test/v1", Key: "key", Models: []string{"gemini-3.8-flash"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("think", "https://think.test/v1", []catalog.Model{{ID: "gemini-3.8-flash", Efforts: []string{"low", "high"}}}); err != nil {
t.Fatal(err)
}
a := antigravity(home)
f := a.Field("effort")
if f == nil {
t.Fatal("no effort field")
}
values := func() []string {
var out []string
for _, o := range f.Options(map[string]string{}) {
out = append(out, o.Value)
}
return out
}
if got := values(); got != nil {
t.Fatalf("offered %q while on the user's own gateway", got)
}
if err := a.Field("model").Set("magpie/think/gemini-3.8-flash"); err != nil {
t.Fatal(err)
}
if got := values(); !slices.Equal(got, []string{"", "low", "high"}) {
t.Fatalf("offered %q", got)
}
if err := f.Set("high"); err != nil {
t.Fatal(err)
}
if got, kept := f.Get(), provider.AgentEffort("antigravity"); got != "high" || kept != "high" {
t.Fatalf("picked high: shown %q, kept %q", got, kept)
}
if err := f.Set("hard"); err == nil {
t.Fatal("a word that isn't a level was kept")
}
if !sameJSON(string(antigravityFile(t, path)["gateway"]), map[string]any{"enabled": true, "url": gateway.URL(), "apiKey": agentKey("antigravity"), "wireProtocol": "openai"}) {
t.Errorf("the pick touched the app's file: %s", readFile(path))
}
if err := f.Set(""); err != nil || provider.AgentEffort("antigravity") != "" {
t.Fatalf("back to the default: %v, kept %q", err, provider.AgentEffort("antigravity"))
}
}
+8 -7
View File
@@ -316,7 +316,7 @@ func cursorLocal() *Agent {
if !cursorLocalWired() {
return nil
}
return cursorLocalEfforts()
return pickedEfforts(CursorLocalID)
},
}},
Notice: func() string {
@@ -325,12 +325,13 @@ func cursorLocal() *Agent {
}
}
// cursorLocalEfforts are the levels Cursor Private Inference's effort is
// picked among: the default, its requests going as it asks, then every
// level a model its list shows has (low, medium and high for models that
// reason with levels unknown). None when no model it lists reasons.
func cursorLocalEfforts() []Option {
shown, _ := provider.CatalogFor(CursorLocalID)
// pickedEfforts are the levels an agent's effort picked in magpie
// (provider.AgentEffort: Cursor Private Inference, Antigravity) is picked
// among: the default, its requests going as it asks, then every level a
// model its list shows has (low, medium and high for models that reason
// with levels unknown). None when no model it lists reasons.
func pickedEfforts(agent string) []Option {
shown, _ := provider.CatalogFor(agent)
has, reasons := map[string]bool{}, false
for _, e := range shown {
reasons = reasons || e.Reasoning
@@ -0,0 +1,123 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// Antigravity's app lists the gateway's models by id and has no level of
// its own to pick (MDX-Tom, #4838): with an effort picked for it in
// magpie, its requests for one of Antigravity's families of levels go out
// as the variant at that level, told that level; with none picked they go
// as before, and another agent's requests never take its pick.
func TestAntigravityAgentEffort(t *testing.T) {
fresh(t)
logins := []map[string]any{{
"agent": "antigravity", "user": "a@example.com", "on": true,
"auth": map[string]any{"access_token": "a@example.com", "refresh_token": "ref-a", "project": "p1",
"expiry_date": time.Now().Add(time.Hour).UnixMilli()},
}}
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "logins.json"), mustJSON(logins), 0o600); err != nil {
t.Fatal(err)
}
// the family as Antigravity lists it: High first, then Low
list := `{"models":{
"gemini-3.8-flash-high":{"displayName":"Gemini 3.8 Flash (High)","maxTokens":1048576,"quotaInfo":{"remainingFraction":1}},
"gemini-3.8-flash-low":{"displayName":"Gemini 3.8 Flash (Low)","maxTokens":1048576,"quotaInfo":{"remainingFraction":1}}},
"agentModelSorts":[{"displayName":"Recommended","groups":[{"modelIds":["gemini-3.8-flash-high","gemini-3.8-flash-low"]}]}]}`
old := http.DefaultClient
http.DefaultClient = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
var body string
switch {
case strings.HasSuffix(r.URL.Path, "latest-arm64-mac.yml"):
body = "version: 2.9.1\n"
case strings.Contains(r.URL.Path, ":loadCodeAssist"):
body = `{"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"p1"}`
case strings.Contains(r.URL.Path, ":fetchAvailableModels"):
body = list
default:
return nil, fmt.Errorf("unexpected request to %s", r.URL)
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
})}
t.Cleanup(func() { http.DefaultClient = old })
p, _ := provider.Find("antigravity")
if _, err := p.Fetch(t.Context()); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var sent []byte
s := New()
s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
sent = b
mu.Unlock()
rec := httptest.NewRecorder()
rec.Header().Set("Content-Type", "text/event-stream")
io.WriteString(rec, sse(`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":3}}}`))
return rec.Result(), nil
})}
// the id the envelope went out under and the level it was told
asked := func(agent string) (string, string) {
t.Helper()
postFrom(t, s, agent, "/v1/chat/completions", `{"model":"antigravity/gemini-3.8-flash","stream":false,"messages":[{"role":"user","content":"hi"}]}`)
mu.Lock()
defer mu.Unlock()
var env struct {
Model string `json:"model"`
Request struct {
GenerationConfig struct {
ThinkingConfig struct {
ThinkingLevel string `json:"thinkingLevel"`
} `json:"thinkingConfig"`
} `json:"generationConfig"`
} `json:"request"`
}
if err := json.Unmarshal(sent, &env); err != nil {
t.Fatalf("%v: %s", err, sent)
}
return env.Model, env.Request.GenerationConfig.ThinkingConfig.ThinkingLevel
}
base, baseLevel := asked("antigravity")
if base == "" {
t.Fatal("no request went out")
}
for _, c := range []struct{ pick, model, level string }{
{"high", "gemini-3.8-flash-high", "high"},
{"low", "gemini-3.8-flash-low", "low"},
} {
if err := provider.SetAgentEffort("antigravity", c.pick); err != nil {
t.Fatal(err)
}
if m, l := asked("antigravity"); m != c.model || l != c.level {
t.Errorf("picked %s: went as %s at %q, want %s at %q", c.pick, m, l, c.model, c.level)
}
// another agent's request goes as it asks
if m, l := asked("opencode"); m != base || l != baseLevel {
t.Errorf("picked %s for Antigravity, opencode's went as %s at %q, want %s at %q", c.pick, m, l, base, baseLevel)
}
}
if err := provider.SetAgentEffort("antigravity", ""); err != nil {
t.Fatal(err)
}
if m, l := asked("antigravity"); m != base || l != baseLevel {
t.Errorf("taken off: went as %s at %q, want %s at %q", m, l, base, baseLevel)
}
}