grok: with no size typed, Grok Build compacts at its own 85% of the window (@taktoshilite on X)
@taktoshilite: the Grok config magpie writes says auto_compact_threshold_percent = 25-something and 50-something, so a 1M model compacts at a quarter of its window; they asked for ~90%. Cause:4f94b8a82wrote each model's whole window as context_window plus a percent from Long conversations. Its default is settings.WorkingWindow, 272K (Codex's own window), so a 1M model got 27% and a 524288 one 51%. Grok Build's own default is 85 (resolve/compaction.rs, DEFAULT_AUTO_COMPACT_THRESHOLD_PERCENT), 80 for xAI's own models in default_models.json. Change: settings.ForAgent("grok") reads magpie's default (no global size, no Grok entry) as Full window, so no percent is written and Grok Build uses its own 85% (1M compacts near 850K). A size the user picks still goes in: a global or Grok-only size writes its percent (900K on a 1M model = 90), and Grok's own {} entry keeps 272K. A percent typed by hand in ~/.grok/config.toml is kept as before (grokOwnPercent). The stale 27/51 magpie wrote is dropped on the next sync, since the stash marks it as magpie's. CLI (`magpie model compact`) and the Grok Build sheet say Grok compacts at its own threshold; sub text translated into zh, zh-TW, ja, de. docs/subsystems/agent-wiring.md says so. Tests: - TestGrokCompactsAtItsOwnPercentByDefault (internal/agent): catalog windows 1M and 524288, an old config with magpie's 27/51; default writes none, Grok {} gives 27/51, 900K gives 90, a hand-set 90 stays. - TestGrokFollowsItsOwnThresholdByDefault (internal/settings). - grok-compact.test.cjs: Grok sheet shows Full pressed, posts own at on a click, 900K shows 900k; Claude's row unchanged; en/zh/zh-TW/ja/de, Chromium + WebKit, 900px and 420px. Run (mote, at e702accf9's tree on origin/main64ae6e206): - Red on the old code: with settings.go and model_cli.go from64ae6e206, the agent test fails "magpie's default: big 27%, mid 51%" (the reporter's numbers) and the settings test fails at "default". - go test -count=1 -tags nogui ./internal/settings ./internal/agent ./internal/cli ./internal/provider: all ok (agent 288s, provider 170s) - go vet (those packages), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean - gofmt -l: clean. - GUI: grok-compact, agent-compact, i18n-keys, agent-prefs, compact-at pass; agent-details-ready 32 of 36 red, the same 32 at64ae6e206alone ("ends ~80px short and jumps", #6373). Not tried: a real Grok Build conversation compacting at 85% on a 1M model; the full Go suite (mote and mica were over their cores).
This commit is contained in:
@@ -128,7 +128,7 @@ something else shows up as drift.
|
||||
- NewMax (newmax.cc, an Electron app on the Claude Agent SDK) keeps its settings as JSON in the row `app` of the `settings` table of `newmax.db`, a SQLite database in WAL mode in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` on every system (`newMax` in [`newmax.go`](../../internal/agent/newmax.go); its main bundle's `configureAppDataPaths`, `loadPersistedAppSettings` and the renderer's `mergeProviders`, v1.1.22). magpie adds one entry to `providers` in the shape NewMax's own import writes, `id: magpie-gateway` (its own preset is `magpie`, its import's ids hold `%3A`), `apiFormat: anthropic` at the gateway's root (NewMax appends `/v1/messages`) with `ANTHROPIC_AUTH_TOKEN` and a key naming NewMax, at most 20 models (`MAX_MODELS`) as `models` and `enabledModels` with their context windows, and its id at the end of `providerOrder`. The row is edited in place in one immediate transaction, so every other byte stays; the user's `name` and `enabled` for magpie's entry and the fields NewMax adds to it stay through a sync, and a sync with nothing to change doesn't write. A row that isn't a JSON object, or whose `providers` or `providerOrder` isn't a list, is left alone. With no row (NewMax at its defaults), magpie writes one with its entry alone, as NewMax lays its defaults and presets under the row; with no database yet, it asks to open NewMax once. Disconnect takes the entry and the id out, sets a pick of it back to `default`, and takes the row out when only what magpie made is left. NewMax holds its settings in memory and writes the whole row back whenever one changes, so a change is refused while `NewMax` (`newmax` on Linux) runs (Windows can't be asked, so the notice says to quit it first). The model is picked in NewMax's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder or `NewMax.app` (`cc.newmax.desktop`).
|
||||
- LiveAgent (Stack-Cairn/LiveAgent v2, a Tauri app) runs its models through K-brain, a Go backend it starts with its data folder, which keeps every provider in `config.json` there: `$LIVEAGENT_HOME`, else `$K_BRAIN_HOME`, else the folder `~/.liveagent/data-dir.json` points to (`{"path": …}`, set when the user moves LiveAgent's data), else `~/.liveagent` on every system (`liveAgent` in [`liveagent.go`](../../internal/agent/liveagent.go); LiveAgent's `data_home.rs` and `kbrain_backend.rs`, K-brain v0.107.12's `internal/config`). The file is JSONC in Pi's provider shape, decoded with unknown fields refused, so magpie writes only K-brain's fields. K-brain asks all of a provider's models on its one API, so magpie writes up to three providers and puts each model on the one of the API it is served on natively (`catalog.Model.APIs`, as dsh's routes): `providers.magpie-responses` for Responses and `providers.magpie` for every other OpenAI-side model (Chat Completions), each `type: codex` with `api` and `requestFormat` as LiveAgent's own settings write an OpenAI-compatible provider, `baseUrl` the gateway's `/v1` (K-brain appends only `/chat/completions` or `/responses`); `providers.magpie-anthropic` for Messages, `type: claude_code` and `api: anthropic-messages`, `baseUrl` the gateway's root (K-brain appends `/v1` and posts to `/messages` with `X-Api-Key`). LiveAgent's settings lock an Anthropic provider's API and let the user switch an OpenAI one between Chat Completions and Responses; a sync keeps the format they picked (Discord, xiaoxiaofei). A provider left with no model is taken out. Each has a key naming LiveAgent, `activeModels: null` (every model on), magpie's order as `modelOrder`, and `models` sorted by id as K-brain writes them, with each one's display name, context window, output limit and `input: [text, image]` when it takes images. Comments and every other key stay. Through a sync the user's name for each entry, the models they turned off (`activeModels`), their order and the fields K-brain adds (its `metadata`) stay; a model that moves to another of magpie's providers (a `config.json` from before, with every model on one Anthropic `magpie`) brings its name and off with it, and a pick of it follows; a model new to magpie's list is on and goes last, and a sync with nothing to change doesn't write. A model of magpie's the user deleted in LiveAgent, or a whole provider of magpie's, stays out until they put it back or magpie is turned off and on for LiveAgent (zero2sin on Discord: every sync, so every restart, wrote magpie's twenty or thirty models back): magpie keeps, per `config.json`, which of its models and providers LiveAgent has had (`liveAgentKept`, in the stash). One magpie added while LiveAgent ran is pending under the processes then (`liveAgentPIDs`), since LiveAgent's next save drops a model it never read: missing under those processes, or after they quit, it is written again; once other processes run it counts as had. On Windows, which can't be asked what runs, each counts as had at once. A default (or compact) model still K-brain's own, `model1` of its endpoint-less `demo` provider, becomes magpie's first; one the user picked stays. A file K-brain wouldn't read as providers (not an object, `providers` not an object, a top-level `models`, one provider written bare) is left alone. Disconnect takes magpie's entries out and a pick of them back to K-brain's default; a file left with no provider gets K-brain's `demo` back, since K-brain takes one with none as written over and restores `config.json.bak`, which can still hold magpie's; a file with nothing but what magpie made goes. LiveAgent's backend makes the file as `{}` when there is none (so a disconnect that takes the file away is undone the next start, harmlessly), reads it when it starts and writes it whole whenever a setting changes, so a change is refused while `liveagent` or `k-brain` runs (Windows can't be asked, so the notice says to quit it first). A model id another provider of the user's lists too has its metadata shared by K-brain, so a sync may write that model's limits back each time. The model is picked in LiveAgent's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder, `LiveAgent.app` (`com.xiaofei.liveagent`) or its Windows install. Its logo is the app's own 64px icon (`src-tauri/icons/64x64.png`, MIT) in an SVG.
|
||||
- DevEco Code (Huawei's OpenCode fork, #1885) is wired as OpenCode is (`deveco` in [`agents.go`](../../internal/agent/agents.go)): magpie's provider goes into the first of `deveco.jsonc`, `deveco.json` and `config.json` in `~/.config/deveco` (the one DevEco merges last, so the one that wins), or in `$DEVECO_CONFIG_DIR` when that is absolute, read after them. 0.2.3 sends `deveco/0.2.3 ai-sdk/…` to a provider of its config, but much of the OpenCode code it keeps still sends OpenCode's own User-Agent (`opencode/<version>`), so its provider's key is `magpie-deveco` (`openCodeKeyAt`), not the plain `magpie` OpenCode and MiMo Code send, and Check asks for that key. Its npm package has no Linux binary, so no install command is offered there (`cliSpec.only`).
|
||||
- Grok Build keeps magpie's models as one `[model."magpie/<provider>/<model>"]` table each in `config.toml` under `$GROK_HOME`, else `~/.grok` (`grok` in [`grok.go`](../../internal/agent/grok.go)), each on the gateway's `/v1` with magpie's key. Grok Build takes `api_backend` per model table, `"chat_completions"` (its default), `"responses"` or `"messages"` (Anthropic Messages), and sends each to `base_url` joined with `/chat/completions`, `/responses` or `/messages` (the "Supported API Backends" page bundled in its binary; grok 1.0.67). magpie writes each model's native API (`grokBackend`, from `catalog.Model.APIs` as Pi, droid and dsh pick theirs; uk.jent on Discord), so the gateway relays the request as it is: Responses for a model served best there, Messages for a Claude on an Anthropic endpoint, Chat for the rest, a group whose members differ, or one not known. Each table's `context_window` is the model's whole window (the catalog's), which Grok Build sends with and shows; it compacts at a percent of it, `auto_compact_threshold_percent` in the `[model.<id>]` table, else `[session]`'s, else 85 (`resolve_auto_compact_threshold_percent` and `DEFAULT_AUTO_COMPACT_THRESHOLD_PERCENT` in xai-org/grok-build; `GROK_AUTO_COMPACT_THRESHOLD_PERCENT` above all). Where Long conversations has Codex compact (`grokCompactAt`, codexcat's rule: a threshold set on the model or its provider, else `settings.Working` of the model's window, none under Full window) goes in as that percent of the window written, rounded down (`grokPercent`); none leaves Grok's 85. magpie once wrote the threshold as the window, so a 1M model told 300K compacted at 255K and never had its 1M (@xiancrong on X); a table an older magpie wrote that way, its threshold on record, gets the whole window back. A `[session]` percent is the user's for every model, so magpie writes no per-model one over it. Long conversations is in Grok Build's sheet on the Agents page (`AGENT_PREFS`). A `context_window` or `auto_compact_threshold_percent` the user set in one of magpie's tables by hand stays through a sync and a new pick (uk.jent on Discord: dozens of 1M models set to 300K one by one): what magpie last gave each model is stashed (`grok:<path>:windows`, `grok:<path>:percents`), and a value other than it is the user's (`grokOwnWindow`, `grokOwnPercent`). With no record of windows yet (a config an older magpie wrote, which gave every model its whole window), a value other than the model's whole window and other than magpie's now is taken for the user's; a percent magpie has no record of giving is the user's. Disconnect drops the records with the tables. `TestGrokKeepsAWindowSetByHand`, `TestGrokKeepsAWindowSetBeforeTheRecord`, `TestGrokWindowFollowsLongConversations`, `TestGrokWindowIsTheModelsAndCompactsAtThePercent`, `TestGrokKeepsTheUsersCompactPercent`.
|
||||
- Grok Build keeps magpie's models as one `[model."magpie/<provider>/<model>"]` table each in `config.toml` under `$GROK_HOME`, else `~/.grok` (`grok` in [`grok.go`](../../internal/agent/grok.go)), each on the gateway's `/v1` with magpie's key. Grok Build takes `api_backend` per model table, `"chat_completions"` (its default), `"responses"` or `"messages"` (Anthropic Messages), and sends each to `base_url` joined with `/chat/completions`, `/responses` or `/messages` (the "Supported API Backends" page bundled in its binary; grok 1.0.67). magpie writes each model's native API (`grokBackend`, from `catalog.Model.APIs` as Pi, droid and dsh pick theirs; uk.jent on Discord), so the gateway relays the request as it is: Responses for a model served best there, Messages for a Claude on an Anthropic endpoint, Chat for the rest, a group whose members differ, or one not known. Each table's `context_window` is the model's whole window (the catalog's), which Grok Build sends with and shows; it compacts at a percent of it, `auto_compact_threshold_percent` in the `[model.<id>]` table, else `[session]`'s, else 85 (`resolve_auto_compact_threshold_percent` and `DEFAULT_AUTO_COMPACT_THRESHOLD_PERCENT` in xai-org/grok-build; `GROK_AUTO_COMPACT_THRESHOLD_PERCENT` above all). Where Long conversations has Codex compact (`grokCompactAt`, codexcat's rule: a threshold set on the model or its provider, else `settings.Working` of the model's window, none under Full window) goes in as that percent of the window written, rounded down (`grokPercent`); none leaves Grok's 85. With no size typed for Grok Build or for every agent, magpie's default (`settings.WorkingWindow`, Codex's 272K) is not Grok Build's: `settings.ForAgent("grok")` reads it as Full window, so no percent is written and Grok Build compacts where it does itself, 85% of the window (xAI's own models come with 80 in its `default_models.json`). Written as a percent, 272K had a 1M model compact at 27% and a 512K one at 51% (@taktoshilite on X). 272K picked for Grok Build itself, a size typed for every agent and a threshold set on a model or provider still go in; the Agents page's row shows Full window for that default and the CLI's `magpie model compact grok` says Grok Build's own threshold (`GrokOwnCompact`). `TestGrokCompactsAtItsOwnPercentByDefault`. magpie once wrote the threshold as the window, so a 1M model told 300K compacted at 255K and never had its 1M (@xiancrong on X); a table an older magpie wrote that way, its threshold on record, gets the whole window back. A `[session]` percent is the user's for every model, so magpie writes no per-model one over it. Long conversations is in Grok Build's sheet on the Agents page (`AGENT_PREFS`). A `context_window` or `auto_compact_threshold_percent` the user set in one of magpie's tables by hand stays through a sync and a new pick (uk.jent on Discord: dozens of 1M models set to 300K one by one): what magpie last gave each model is stashed (`grok:<path>:windows`, `grok:<path>:percents`), and a value other than it is the user's (`grokOwnWindow`, `grokOwnPercent`). With no record of windows yet (a config an older magpie wrote, which gave every model its whole window), a value other than the model's whole window and other than magpie's now is taken for the user's; a percent magpie has no record of giving is the user's. Disconnect drops the records with the tables. `TestGrokKeepsAWindowSetByHand`, `TestGrokKeepsAWindowSetBeforeTheRecord`, `TestGrokWindowFollowsLongConversations`, `TestGrokWindowIsTheModelsAndCompactsAtThePercent`, `TestGrokKeepsTheUsersCompactPercent`.
|
||||
- Droid keeps magpie's models as `customModels` entries in `~/.factory/settings.json` (`droidIn` in [`droid.go`](../../internal/agent/droid.go)), each with `provider` `openai` (Responses, `baseUrl` the gateway's `/v1`), `anthropic` (the gateway root) or `generic-chat-completion-api` (Chat, `/v1`). droid reads a custom model's `model` itself and, at every session start, warns about one whose name looks like OpenAI's (`/\bgpt[-_.]?\d/i`, `/codex/i`, `/\bo[1-9](?:[-_.]|$)/i`) on any provider but `openai`, or like a Claude (`/claude|haiku|sonnet|opus/i`) on neither `anthropic` nor `bedrock-converse` (droid 0.231.0's bundle, `xs` and `g2`; ji233 on Discord: `ultrafast/gpt-6.1-sol` on Chat). So `droidWants` puts such a model on the provider droid asks for, whatever its provider speaks, and the gateway translates; any other model goes on its `APIs`, as Pi, omp and dsh pick theirs. A `provider`, `displayName`, `maxContextLimit`, `maxOutputTokens` or `noImageSupport` the user changed in one of magpie's entries stays through a sync and a new pick (`droidMerge`): what magpie last gave each entry is stashed (`droid:<path>:wrote`), and a value other than it is the user's; keys magpie doesn't write stay too, droid's `index` aside. `baseUrl` follows the entry's provider and `apiKey` is the wiring, both put back at every sync. With no record (entries an older magpie wrote, which every sync wrote over anyway), magpie's values are taken. Disconnect drops the record with the entries. `TestDroidWantsItsOwnRule`, `TestDroidProviderByName`, `TestDroidKeepsAnEntryEditedByHand`.
|
||||
- A provider of the user's own in an OpenCode config that sends to magpie's gateway and lists the model, as a layout of one provider per family of magpie's models has, stays theirs: a magpie model picked there is written as `<theirs>/<model>`, with no `provider.magpie` beside it (`ownGatewayProvider` in [`agents.go`](../../internal/agent/agents.go)), and a model on one named as a provider of magpie's counts as magpie's (`openCodeSpelled`). Both read such a provider under `provider` and under `providers`, OpenCode 2's spelling, which OpenChamber's provider form writes; a name under both is the one under `providers`, as OpenCode 2 reads it (#3915, `TestOpenCodeKeepsItsOwnGatewayProvidersUnderProviders`).
|
||||
- Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use.
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -563,6 +564,8 @@ func TestGrokWindowFollowsLongConversations(t *testing.T) {
|
||||
t.Fatalf("%s: percents pro %d, flash %d, want %d and %d", when, p, f, pro, flash)
|
||||
}
|
||||
}
|
||||
set(func(s *settings.Settings) {})
|
||||
want("magpie's default: Grok Build's own threshold", -1, -1)
|
||||
set(func(s *settings.Settings) { s.CompactAt = 300000 })
|
||||
want("compact at 300K", 30, -1)
|
||||
set(func(s *settings.Settings) { s.FullContext = true })
|
||||
@@ -583,3 +586,91 @@ func TestGrokWindowFollowsLongConversations(t *testing.T) {
|
||||
set(func(s *settings.Settings) { s.AgentCompacts = map[string]settings.AgentCompact{"codex": {Full: true}} })
|
||||
want("codex's full window reached grok", 30, -1)
|
||||
}
|
||||
|
||||
// With no size typed for Grok Build or for every agent, Grok Build compacts
|
||||
// where it does itself, 85% of the window: magpie's default for every
|
||||
// agent, Codex's 272K, went in as a percent, so a 1M model compacted at 27%
|
||||
// and a 512K one at 51% (@taktoshilite on X: "100 万的上下文用不了多少就开始
|
||||
// 压缩了"). Windows from the vendor's list, none typed, as theirs were. A
|
||||
// table magpie gave 27 on that default gets none, Grok Build's own; 272K
|
||||
// picked for Grok Build itself, and a percent the user set, stay.
|
||||
func TestGrokCompactsAtItsOwnPercentByDefault(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("GROK_HOME", filepath.Join(home, "grok"))
|
||||
path := filepath.Join(home, "grok", "config.toml")
|
||||
if err := provider.Save(provider.Provider{ID: "v", Name: "V", Chat: "https://example.test/v1", Key: "k", Models: []string{"big", "mid"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := catalog.SaveLive("v", "https://example.test/v1", []catalog.Model{{ID: "big", Context: 1000000}, {ID: "mid", Context: 524288}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
percents := func() (int, int) {
|
||||
t.Helper()
|
||||
had, err := grokHadIn(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
get := func(id string) int {
|
||||
if n, ok := had.percents[id]; ok {
|
||||
return n
|
||||
}
|
||||
return -1
|
||||
}
|
||||
return get("v/big"), get("v/mid")
|
||||
}
|
||||
sync := func() {
|
||||
t.Helper()
|
||||
if err := grok(home).Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
save := func(s settings.Settings) {
|
||||
t.Helper()
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// what the magpie before this one wrote on the default: 27, on record
|
||||
stash(map[string]string{"grok:" + path + ":percents": `{"v/big":27,"v/mid":51}`})
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
old := "[models]\ndefault = \"magpie/v/big\"\n\n" +
|
||||
"[model.\"magpie/v/big\"]\nmodel = \"v/big\"\nbase_url = \"http://127.0.0.1:3425/v1\"\napi_key = \"magpie\"\ncontext_window = 1000000\nauto_compact_threshold_percent = 27\n\n" +
|
||||
"[model.\"magpie/v/mid\"]\nmodel = \"v/mid\"\nbase_url = \"http://127.0.0.1:3425/v1\"\napi_key = \"magpie\"\ncontext_window = 524288\nauto_compact_threshold_percent = 51\n"
|
||||
if err := os.WriteFile(path, []byte(old), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sync()
|
||||
if big, mid := percents(); big != -1 || mid != -1 {
|
||||
raw, _ := os.ReadFile(path)
|
||||
t.Fatalf("magpie's default: big %d%%, mid %d%%, want none (Grok Build's own 85)\n%s", big, mid, raw)
|
||||
}
|
||||
if w, _ := grokWindowsIn(path); w["v/big"] != 1000000 || w["v/mid"] != 524288 {
|
||||
t.Fatalf("windows %v", w)
|
||||
}
|
||||
// 272K picked for Grok Build itself is the user's
|
||||
save(settings.Settings{AgentCompacts: map[string]settings.AgentCompact{"grok": {}}})
|
||||
sync()
|
||||
if big, mid := percents(); big != 27 || mid != 51 {
|
||||
t.Fatalf("272K picked for Grok Build: big %d%%, mid %d%%, want 27 and 51", big, mid)
|
||||
}
|
||||
// so is a size typed for every agent
|
||||
save(settings.Settings{CompactAt: 900000})
|
||||
sync()
|
||||
if big, mid := percents(); big != 90 || mid != -1 {
|
||||
t.Fatalf("900K for every agent: big %d%%, mid %d%%, want 90 and none", big, mid)
|
||||
}
|
||||
// back to the default, a percent set by hand stays
|
||||
save(settings.Settings{})
|
||||
sync()
|
||||
if err := edit.SetTOMLKey(path, `model."magpie/v/big"`, "auto_compact_threshold_percent", 90); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sync()
|
||||
if big, mid := percents(); big != 90 || mid != -1 {
|
||||
t.Fatalf("big set by hand to 90: big %d%%, mid %d%%", big, mid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -896,6 +896,8 @@ func agentCompact(agent string, args []string) error {
|
||||
s := settings.Load()
|
||||
own, has := s.AgentCompacts[agent]
|
||||
switch a := s.ForAgent(agent); {
|
||||
case !has && agent == "grok" && s.GrokOwnCompact():
|
||||
fmt.Println("every", muted.Render(fmt.Sprintf("· %s, as every agent's is magpie's default · magpie model compact %s <size>|off", grokOwnWords, agent)))
|
||||
case !has:
|
||||
fmt.Println("every", muted.Render(fmt.Sprintf("· %s follows every agent's (%s) · magpie model compact %s <size>|off", agent, compactWords(a), agent)))
|
||||
case own.Full:
|
||||
@@ -920,10 +922,18 @@ func agentCompact(agent string, args []string) error {
|
||||
if err := provider.SetAgentCompact(agent, c); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(green.Render("✓"), agent+":", compactWords(settings.Load().ForAgent(agent)))
|
||||
words := compactWords(settings.Load().ForAgent(agent))
|
||||
if agent == "grok" && settings.Load().GrokOwnCompact() {
|
||||
words = grokOwnWords
|
||||
}
|
||||
fmt.Println(green.Render("✓"), agent+":", words)
|
||||
return nil
|
||||
}
|
||||
|
||||
// grokOwnWords says Grok Build compacts where it does itself
|
||||
// (settings.GrokOwnCompact).
|
||||
const grokOwnWords = "Grok Build compacts at its own threshold (85% of the model's window unless its config says otherwise)"
|
||||
|
||||
// modelAgentWindow says or sets the windows one agent is told
|
||||
// (settings.AgentContexts): model=size pairs replace those it had, off
|
||||
// takes them away.
|
||||
|
||||
@@ -11,7 +11,13 @@ const compactFill = function (list, a) {
|
||||
const row = el("div", "row pref agent-compact");
|
||||
row.dataset.agent = kind;
|
||||
const who = el("div", "who"), box = el("div");
|
||||
who.append(el("div", "name", t("Long conversations")), el("div", "sub", t("{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.", { agent: a.name })));
|
||||
// Grok Build compacts at a percent of the window of its own, and with no
|
||||
// size typed for it or for every agent, that is where it compacts
|
||||
// (settings.ForAgent: @taktoshilite on X, a 1M model compacted at 27%)
|
||||
const sub = kind === "grok"
|
||||
? t("Grok Build compacts at 85% of the window, or at the size picked; a smaller size is faster and cheaper. magpie's models only: a subscription's own models keep their own.")
|
||||
: t("{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.", { agent: a.name });
|
||||
who.append(el("div", "name", t("Long conversations")), el("div", "sub", sub));
|
||||
row.append(who, box);
|
||||
// what Codex's own config holds back, said under the row (renderAgentPrefs)
|
||||
const held = el("div", "compact-helds");
|
||||
@@ -24,7 +30,7 @@ const compactFill = function (list, a) {
|
||||
const key = JSON.stringify([own, s.compactAt, s.fullContext]);
|
||||
if (key === drawn) return;
|
||||
drawn = key;
|
||||
const full = own ? !!own.full : !!s.fullContext;
|
||||
const full = own ? !!own.full : !!s.fullContext || (kind === "grok" && !s.compactAt);
|
||||
const at = own ? own.at || 0 : s.compactAt || 0;
|
||||
const set = (body) => writingPrefs(api("settings/agent-compact", { agent: kind, own: true, ...body }))
|
||||
.then((ns) => { prefs = ns; renderSettings(); if (row.isConnected) draw(); }).catch(settingsErr);
|
||||
|
||||
@@ -1563,6 +1563,7 @@ const I18N = {
|
||||
"Codex subagents on any model": "Codex 子代理可用任意模型",
|
||||
"Long conversations": "长对话",
|
||||
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} 在 272K 或选定的大小时压缩;完整窗口更慢更贵。只作用于 magpie 的模型,订阅自带的模型不受影响。",
|
||||
"Grok Build compacts at 85% of the window, or at the size picked; a smaller size is faster and cheaper. magpie's models only: a subscription's own models keep their own.": "Grok Build 在窗口的 85% 处压缩,或在选定的大小时压缩;更小的大小更快更省。只作用于 magpie 的模型,订阅自带的模型不受影响。",
|
||||
"Long conversations in {agent}": "{agent} 的长对话",
|
||||
"Each model's own": "各模型自己的",
|
||||
"each model on the API its provider serves": "各模型走其服务商原生的 API",
|
||||
@@ -7087,6 +7088,7 @@ const I18N = {
|
||||
"Codex subagents on any model": "Codex 子代理可用任意模型",
|
||||
"Long conversations": "長對話",
|
||||
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} 在 272K 或選定的大小時壓縮;完整視窗更慢更貴。只作用於 magpie 的模型,訂閱自帶的模型不受影響。",
|
||||
"Grok Build compacts at 85% of the window, or at the size picked; a smaller size is faster and cheaper. magpie's models only: a subscription's own models keep their own.": "Grok Build 在視窗的 85% 處壓縮,或在選定的大小時壓縮;更小的大小更快更省。只作用於 magpie 的模型,訂閱自帶的模型不受影響。",
|
||||
"Long conversations in {agent}": "{agent} 的長對話",
|
||||
"Each model's own": "各模型自己的",
|
||||
"each model on the API its provider serves": "各模型走其服務商原生的 API",
|
||||
@@ -12561,6 +12563,7 @@ const I18N = {
|
||||
"Codex subagents on any model": "Codex のサブエージェントで任意のモデル",
|
||||
"Long conversations": "長い会話",
|
||||
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} は 272K か選んだサイズで圧縮します。ウィンドウ全体は遅く高価です。対象は magpie のモデルのみで、サブスクリプション自身のモデルは影響を受けません。",
|
||||
"Grok Build compacts at 85% of the window, or at the size picked; a smaller size is faster and cheaper. magpie's models only: a subscription's own models keep their own.": "Grok Build はウィンドウの 85% か選んだサイズで圧縮します。小さいサイズほど速く安価です。対象は magpie のモデルのみで、サブスクリプション自身のモデルは影響を受けません。",
|
||||
"Long conversations in {agent}": "{agent} の長い会話",
|
||||
"Each model's own": "各モデルのまま",
|
||||
"each model on the API its provider serves": "各モデルをそのプロバイダーの API で",
|
||||
@@ -18084,6 +18087,7 @@ const I18N = {
|
||||
"Codex subagents on any model": "Codex-Subagenten auf jedem Modell",
|
||||
"Long conversations": "Lange Unterhaltungen",
|
||||
"{agent} compacts at 272K or the size picked; the full window is slower and costlier. magpie's models only: a subscription's own models keep their own.": "{agent} komprimiert bei 272K oder der gewählten Größe; das volle Fenster ist langsamer und teurer. Nur für magpie-Modelle: Modelle eines Abos bleiben unverändert.",
|
||||
"Grok Build compacts at 85% of the window, or at the size picked; a smaller size is faster and cheaper. magpie's models only: a subscription's own models keep their own.": "Grok Build komprimiert bei 85 % des Fensters oder bei der gewählten Größe; eine kleinere Größe ist schneller und günstiger. Nur für magpie-Modelle: Modelle eines Abos bleiben unverändert.",
|
||||
"Long conversations in {agent}": "Lange Unterhaltungen in {agent}",
|
||||
"Each model's own": "Je Modell sein eigenes",
|
||||
"each model on the API its provider serves": "Jedes Modell über die API seines Anbieters",
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Grok Build's Long conversations with no size typed for it or for every
|
||||
// agent shows Full window: Grok Build then compacts at its own 85% of the
|
||||
// window (settings.ForAgent; @taktoshilite on X, magpie's 272K had a 1M
|
||||
// model compact at 27%), and the row says so. Claude Code's row still
|
||||
// shows 272K, a size typed for every agent shows on Grok Build's too, and
|
||||
// Compact at sends Grok Build's own 272K. Every language, Chromium and
|
||||
// WebKit, wide and narrow; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
function serve(lang, posts, compactAt) {
|
||||
let settings = { theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.900", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], titleModels: [], workbuddyCheckins: [], lanURLs: [], redactWords: [], trayUsageEvery: 3, ...(compactAt ? { compactAt } : {}) };
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [agentRow("claude", "Claude Code"), agentRow("grok", "Grok Build")], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/settings/agent-compact") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push({ path: url.pathname, body });
|
||||
const own = { ...(settings.agentCompacts || {}) };
|
||||
if (body.own) own[body.agent] = { ...(body.at && body.at !== 272000 ? { at: body.at } : {}), ...(body.full ? { full: true } : {}) };
|
||||
else delete own[body.agent];
|
||||
settings = { ...settings, agentCompacts: own };
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/settings/full-context") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push({ path: url.pathname, body });
|
||||
settings = { ...settings, fullContext: body.on, ...(body.at !== undefined ? { compactAt: body.at === 272000 ? 0 : body.at } : {}) };
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") posts.push({ path: url.pathname, body: req.postDataJSON() });
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
try {
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
|
||||
} catch {
|
||||
await route.fulfill({ status: 404, body: "" });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const subs = {
|
||||
en: "Grok Build compacts at 85% of the window",
|
||||
zh: "Grok Build 在窗口的 85% 处压缩",
|
||||
"zh-TW": "Grok Build 在視窗的 85% 處壓縮",
|
||||
ja: "Grok Build はウィンドウの 85%",
|
||||
de: "Grok Build komprimiert bei 85 % des Fensters",
|
||||
};
|
||||
|
||||
const pressed = (row, seg) => row.locator(`.segs button[data-seg="${seg}"]`).getAttribute("aria-pressed");
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(subs)) {
|
||||
for (const width of [900, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: Grok Build compacts at its own percent by default`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const open = async (compactAt) => {
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts, compactAt));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=agents");
|
||||
return { page, errors, posts };
|
||||
};
|
||||
const { page, errors, posts } = await open(0);
|
||||
await openAgentSettings(page, "grok");
|
||||
const row = page.locator('.agent-compact[data-agent="grok"]');
|
||||
await row.waitFor();
|
||||
await page.waitForFunction(() => document.querySelector('.agent-compact[data-agent="grok"] .segs button[data-seg="full"]')?.getAttribute("aria-pressed") === "true");
|
||||
assert.equal(await pressed(row, "at"), "false");
|
||||
assert(await row.locator("input.compact-num").isHidden(), "the size field shows under Full window");
|
||||
assert((await row.locator(".sub").textContent()).includes(subs[lang]), await row.locator(".sub").textContent());
|
||||
// Compact at is Grok Build's own 272K
|
||||
await row.locator('.segs button[data-seg="at"]').click();
|
||||
await page.waitForFunction(() => document.querySelector('.agent-compact[data-agent="grok"] input.compact-num')?.hidden === false);
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/agent-compact", body: { agent: "grok", own: true, full: false, at: 0 } });
|
||||
assert.equal(await pressed(row, "at"), "true");
|
||||
const over = await row.evaluate((r) => r.scrollWidth - r.clientWidth);
|
||||
assert(over <= 1, `the row overflows by ${over}px`);
|
||||
assert.deepEqual(errors, []);
|
||||
// a size typed for every agent is Grok Build's too
|
||||
const typed = await open(900000);
|
||||
await openAgentSettings(typed.page, "grok");
|
||||
const row2 = typed.page.locator('.agent-compact[data-agent="grok"]');
|
||||
await row2.waitFor();
|
||||
await typed.page.waitForFunction(() => document.querySelector('.agent-compact[data-agent="grok"] .segs button[data-seg="at"]')?.getAttribute("aria-pressed") === "true");
|
||||
assert.equal(await row2.locator("input.compact-num").inputValue(), "900k");
|
||||
assert.deepEqual(typed.errors, []);
|
||||
// Claude Code's default is still 272K
|
||||
const fresh = await open(0);
|
||||
await openAgentSettings(fresh.page, "claude");
|
||||
const row3 = fresh.page.locator('.agent-compact[data-agent="claude"]');
|
||||
await row3.waitFor();
|
||||
await fresh.page.waitForFunction(() => document.querySelector('.agent-compact[data-agent="claude"] .segs button[data-seg="at"]')?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(fresh.errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package settings
|
||||
|
||||
import "testing"
|
||||
|
||||
// Grok Build reads magpie's default for every agent as its whole window,
|
||||
// where it compacts at its own percent (@taktoshilite on X), while a size
|
||||
// typed for every agent or for Grok Build, and Codex's and Claude Code's
|
||||
// default, are as they were.
|
||||
func TestGrokFollowsItsOwnThresholdByDefault(t *testing.T) {
|
||||
var s Settings
|
||||
if g := s.ForAgent("grok"); !g.FullContext || g.Compact() != 0 || !s.GrokOwnCompact() {
|
||||
t.Fatalf("default: grok full %v, at %d", g.FullContext, g.Compact())
|
||||
}
|
||||
for _, k := range []string{"codex", "claude"} {
|
||||
if n := s.ForAgent(k).Compact(); n != WorkingWindow {
|
||||
t.Fatalf("%s's default %d", k, n)
|
||||
}
|
||||
}
|
||||
s.CompactAt = 400000
|
||||
if n := s.ForAgent("grok").Compact(); n != 400000 || s.GrokOwnCompact() {
|
||||
t.Fatalf("400K for every agent: grok %d", n)
|
||||
}
|
||||
s.CompactAt = 0
|
||||
s.AgentCompacts = map[string]AgentCompact{"grok": {}}
|
||||
if n := s.ForAgent("grok").Compact(); n != WorkingWindow || s.GrokOwnCompact() {
|
||||
t.Fatalf("272K picked for grok: %d", n)
|
||||
}
|
||||
s.AgentCompacts = map[string]AgentCompact{"codex": {At: 300000}}
|
||||
if g := s.ForAgent("grok"); !g.FullContext {
|
||||
t.Fatalf("codex's own reached grok: %+v", g.Compact())
|
||||
}
|
||||
}
|
||||
@@ -1783,13 +1783,33 @@ var CompactAgents = []string{"codex", "claude", "grok"}
|
||||
|
||||
// ForAgent is s as the agent of that kind reads Long conversations: its
|
||||
// own AgentCompact in CompactAt and FullContext, when it has one.
|
||||
//
|
||||
// Grok Build with none of its own, under magpie's default for every agent
|
||||
// (no size typed, so WorkingWindow), runs to the whole window, where Grok
|
||||
// Build compacts at a percent of its own (GrokOwnCompact). WorkingWindow
|
||||
// is Codex's, what OpenAI tells it for its own models; written into Grok
|
||||
// Build as a percent it compacted a 1M model at 27% and a 512K one at 53%
|
||||
// (@taktoshilite on X). A size the user typed, for every agent or for
|
||||
// Grok Build, still holds.
|
||||
func (s Settings) ForAgent(kind string) Settings {
|
||||
if c, ok := s.AgentCompacts[kind]; ok {
|
||||
s.CompactAt, s.FullContext = c.At, c.Full
|
||||
} else if kind == "grok" && s.CompactAt == 0 {
|
||||
s.FullContext = true
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// GrokOwnCompact says Grok Build runs to the whole window only because it
|
||||
// has no Long conversations of its own and every agent's is magpie's
|
||||
// default (ForAgent): it compacts where Grok Build itself does, 85% of the
|
||||
// window unless the user's [session] says otherwise (grok-build's
|
||||
// DEFAULT_AUTO_COMPACT_THRESHOLD_PERCENT; xAI's own models come with 80).
|
||||
func (s Settings) GrokOwnCompact() bool {
|
||||
_, own := s.AgentCompacts["grok"]
|
||||
return !own && s.CompactAt == 0 && !s.FullContext
|
||||
}
|
||||
|
||||
// Compact is where a conversation on a longer window is compacted when
|
||||
// neither its model nor its provider says (ModelCompacts): CompactAt,
|
||||
// else WorkingWindow, and 0 under FullContext, the model's whole window.
|
||||
|
||||
Reference in New Issue
Block a user