routing: a conversation held to its native compaction's account says so, not "the only account on" (#2639)

A turn carrying a native compaction goes only to the account that
sealed it, so the route's order has one account, and Routing's first
line read "{who} is the only account on for {model}". On #2639 that
read as the other account not serving the model. The route now names
the sealer (Route.Compaction, compactionWho), and Routing says the
conversation stays on it because only it can read the compaction, and
that a new conversation uses the others. Translated in zh, zh-TW, ja
and de.

Run on origin/main f191d6423 with this change:
- TestNativeCompactionRouteNamesItsWriter: green; with Compaction taken
  off the route in gateway.go by hand, red (compaction "").
- go test -run 'NativeCompaction|Compact|TestCodex|Trace|Route|
  TestProtection' ./internal/gateway: ok. go vet ./internal/gateway on
  darwin, GOOS=linux and GOOS=windows -tags nogui: ok. gofmt -l clean.
- routing-compaction.test.cjs (chromium and webkit; en zh zh-TW ja de)
  with i18n-keys: 13/13; with the client.js line removed by hand,
  routing-compaction 10/10 red.

Earlier, on dccfefdf7 with an older series around this change (since
landed by bf931f82c in another form, so dropped here): full suite once,
go vet ./... on all three OSes ok, go test -timeout 45m ./... every
package ok except internal/gui's 7 real-window AppKit tests killed at
their deadlines at load ~290 (#2645). The routing-*, panel-routing* and
i18n-keys GUI files, one at a time: reds only in routing-bodies,
routing-keys-fold, routing-model-rest and routing-request-metrics, red
the same on origin/main 84cd686af (28 there, 25 with this; #2658,
#2559, #2571). Not run on f191d6423: the full suite.
This commit is contained in:
yetone
2026-10-17 19:29:07 +08:00
parent 04e8aa8f10
commit 717b69f78a
8 changed files with 203 additions and 2 deletions
+1 -1
View File
@@ -139,7 +139,7 @@ recorded as a prediction failure (`noPrediction`).
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Carrying reasoning across APIs (an envelope) isn't done.
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
- A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge.
- A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`.
+1 -1
View File
@@ -2220,7 +2220,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
capture.tools = tools
}
tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784)
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: pl.left})
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Compaction: compactionWho(checkpoint), Subagent: subagent, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: pl.left})
if watched != nil {
watched.routeID = tr.ID
}
+9
View File
@@ -359,6 +359,15 @@ func keepCandidates(cands []candidate, pl planned, keep func(candidate) bool) ([
return cands, pl, len(cands) > 0 || len(pl.held) > 0 || len(pl.capped) > 0
}
// compactionWho is who sealed the native compaction cp, for the trace;
// "" for none.
func compactionWho(cp *checkpointWriter) string {
if cp == nil {
return ""
}
return cp.Who
}
// checkpointError is what Codex is told when the compaction a request
// carries was sealed by a key or account the request can't go to now:
// why, as magpie's own settings say, and what lets the conversation go on
@@ -1,12 +1,18 @@
package gateway
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
@@ -539,3 +545,91 @@ func TestNativeCompactionWriterGoneSaysWhy(t *testing.T) {
})
}
}
// #2639: a turn carrying a native compaction goes only to the account
// that sealed it, and its route says so (Compaction), for Routing to say
// that is why no other account was asked, not that it is the only one on.
func TestNativeCompactionRouteNamesItsWriter(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"))
noRests()
t.Cleanup(noRests)
claims := func(m map[string]any) string {
b, _ := json.Marshal(m)
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
}
auth := func(email, acct string) map[string]any {
return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
"id_token": claims(map[string]any{"email": email}),
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "who": acct}),
"refresh_token": "r-" + acct, "account_id": acct}}
}
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
os.WriteFile(filepath.Join(home, ".codex", "auth.json"), mustJSON(auth("pro@example.com", "acct-pro")), 0o600)
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), mustJSON([]map[string]any{
{"agent": "codex", "user": "biz@example.com", "on": true, "seen": time.Now(), "auth": auth("biz@example.com", "acct-biz")},
}), 0o600)
provider.ForgetAccounts()
t.Cleanup(provider.ForgetAccounts)
var mu sync.Mutex
var tried []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
if strings.HasSuffix(r.URL.Path, "/models") {
io.WriteString(w, `{"models":[{"slug":"gpt-5.5","visibility":"list"}]}`)
return
}
mu.Lock()
tried = append(tried, r.Header.Get("chatgpt-account-id"))
mu.Unlock()
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
old := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = old })
p, err := provider.Find("codex")
if err != nil {
t.Fatal(err)
}
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
wroteCheckpoint("gAAAAB-sealed-by-biz", candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{User: "biz@example.com"}}, model: "gpt-5.5"})
s := New()
ask := func(session, body string) Route {
t.Helper()
tried = nil
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))
req.Header.Set("session_id", session)
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Fatalf("%s: %d %s", session, rec.Code, rec.Body.String())
}
for _, r := range s.Trace(context.Background(), 0, 0).Routes {
if r.Session == session {
return r
}
}
t.Fatalf("%s: no route traced", session)
return Route{}
}
r := ask("sealed-1", `{"model":"codex/gpt-5.5","stream":true,"input":[{"type":"compaction","encrypted_content":"gAAAAB-sealed-by-biz"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`)
if strings.Join(tried, ",") != "acct-biz" || r.Compaction != "codex@biz@example.com" || len(r.Order) != 1 {
t.Fatalf("sealed: tried %v, compaction %q, order %+v", tried, r.Compaction, r.Order)
}
r = ask("plain-1", `{"model":"codex/gpt-5.5","stream":true,"input":"ping"}`)
if r.Compaction != "" || len(r.Order) != 2 {
t.Fatalf("no compaction: compaction %q, order %+v", r.Compaction, r.Order)
}
}
+4
View File
@@ -58,6 +58,10 @@ type Route struct {
Rule *RuleHit `json:"rule,omitempty"` // the group's rules for it, when it has any
SealedTask bool `json:"sealedTask,omitempty"` // only ChatGPT accounts can read this subagent's task
LeadAccount string `json:"leadAccount,omitempty"` // the parent account put first for a sealed task
// Compaction: the key or account that sealed the native compaction
// the request carries, the only one it went to (#1099): Routing says
// so, not that it is the only one on for the model (#2639)
Compaction string `json:"compaction,omitempty"`
// Subagent is a Codex or Claude Desktop subagent's request put on
// the model set for its subagents, or kept on the one asked for and why
Subagent *SubagentPick `json:"subagent,omitempty"`
@@ -559,6 +559,7 @@ function routingPage(part) {
if (!f) return t("Nothing could take {model}.", { model: r.model });
const w = who(f);
if (r.sealedTask && r.leadAccount === f.id) return t("{who} goes first: it answered the parent agent and may be needed to read this encrypted task.", { who: w });
if (r.compaction && r.order.length === 1) return t("{who} compacted this conversation natively, and only it can read that compaction, so the conversation stays on it: other accounts aren't asked. Start a new conversation to use them.", { who: w });
if (r.order.length === 1) {
if (f.rest) return t("{who} is the only one, so it's tried though it is resting.", { who: w });
return f.kind === "account" ? t("{who} is the only account on for {model} — nothing to choose between.", { who: w, model: wentOn(r) })
@@ -445,6 +445,7 @@ magpie.strings({
"This subagent task is encrypted. Only ChatGPT accounts can read it; other providers (such as Claude) are excluded regardless of quota.": "子代理任务已加密,只能使用 ChatGPT 账号;其他供应商(如 Claude)不参与选择,无论剩余多少额度。",
"This subagent task is encrypted. Only ChatGPT accounts can read it.": "子代理任务已加密,只能使用 ChatGPT 账号。",
"{who} goes first: it answered the parent agent and may be needed to read this encrypted task.": "{who} 回答了主代理,因此优先用它读取这条加密任务。",
"{who} compacted this conversation natively, and only it can read that compaction, so the conversation stays on it: other accounts aren't asked. Start a new conversation to use them.": "{who} 原生压缩了这条对话,只有它能读取这份压缩,所以对话留在它上面,不会问其他账号。开一个新对话即可使用其他账号。",
"{agent} requested a subagent; magpie selects its model within this routing group.": "{agent} 请求了子代理,由 magpie 在此路由组内选择模型。",
"{agent} requested a subagent on {model}.": "{agent} 请求了使用 {model} 的子代理。",
"{agent} requested a subagent on {model} and it stayed there: its subagents are set to {to}, but {why}.": "{agent} 请求了使用 {model} 的子代理,并保留在该模型上:它的子代理设为 {to},但{why}。",
@@ -971,6 +972,7 @@ magpie.strings({
"This subagent task is encrypted. Only ChatGPT accounts can read it; other providers (such as Claude) are excluded regardless of quota.": "子代理任務已加密,只能使用 ChatGPT 帳號;其他供應商(如 Claude)不參與選擇,無論剩餘多少額度。",
"This subagent task is encrypted. Only ChatGPT accounts can read it.": "子代理任務已加密,只能使用 ChatGPT 帳號。",
"{who} goes first: it answered the parent agent and may be needed to read this encrypted task.": "{who} 回答了主代理,因此優先用它讀取這條加密任務。",
"{who} compacted this conversation natively, and only it can read that compaction, so the conversation stays on it: other accounts aren't asked. Start a new conversation to use them.": "{who} 原生壓縮了這條對話,只有它能讀取這份壓縮,所以對話留在它上面,不會問其他帳號。開一個新對話即可使用其他帳號。",
"{agent} requested a subagent; magpie selects its model within this routing group.": "{agent} 請求了子代理,由 magpie 在此路由組內選擇模型。",
"{agent} requested a subagent on {model}.": "{agent} 請求了使用 {model} 的子代理。",
"{agent} requested a subagent on {model} and it stayed there: its subagents are set to {to}, but {why}.": "{agent} 請求了使用 {model} 的子代理,並保留在該模型上:它的子代理設為 {to},但{why}。",
@@ -1495,6 +1497,7 @@ magpie.strings({
"This subagent task is encrypted. Only ChatGPT accounts can read it; other providers (such as Claude) are excluded regardless of quota.": "このサブエージェントのタスクは暗号化されています。読めるのは ChatGPT アカウントだけで、他のプロバイダ(Claude など)はクォータに関係なく除外されます。",
"This subagent task is encrypted. Only ChatGPT accounts can read it.": "このサブエージェントのタスクは暗号化されています。読めるのは ChatGPT アカウントだけです。",
"{who} goes first: it answered the parent agent and may be needed to read this encrypted task.": "{who} が先です:親エージェントに応答しており、この暗号化されたタスクを読むのに必要な可能性があります。",
"{who} compacted this conversation natively, and only it can read that compaction, so the conversation stays on it: other accounts aren't asked. Start a new conversation to use them.": "{who} がこの会話をネイティブに圧縮しており、その圧縮を読めるのはこのアカウントだけなので、会話はここに留まり、他のアカウントには送られません。他のアカウントを使うには新しい会話を始めてください。",
"{agent} requested a subagent; magpie selects its model within this routing group.": "{agent} がサブエージェントをリクエストしました。モデルは magpie がこのルーティンググループ内で選びます。",
"{agent} requested a subagent on {model}.": "{agent} が {model} のサブエージェントをリクエストしました。",
"{agent} requested a subagent on {model} and it stayed there: its subagents are set to {to}, but {why}.": "{agent} が {model} のサブエージェントをリクエストし、そのモデルのままになりました。サブエージェントは {to} に設定されていますが、{why}。",
@@ -2021,6 +2024,7 @@ magpie.strings({
"This subagent task is encrypted. Only ChatGPT accounts can read it; other providers (such as Claude) are excluded regardless of quota.": "Diese Subagenten-Aufgabe ist verschlüsselt. Nur ChatGPT-Konten können sie lesen; andere Anbieter (etwa Claude) sind unabhängig vom Kontingent ausgeschlossen.",
"This subagent task is encrypted. Only ChatGPT accounts can read it.": "Diese Subagent-Aufgabe ist verschlüsselt. Nur ChatGPT-Konten können sie lesen.",
"{who} goes first: it answered the parent agent and may be needed to read this encrypted task.": "{who} kommt zuerst: Es hat dem übergeordneten Agenten geantwortet und wird eventuell zum Lesen dieser verschlüsselten Aufgabe gebraucht.",
"{who} compacted this conversation natively, and only it can read that compaction, so the conversation stays on it: other accounts aren't asked. Start a new conversation to use them.": "{who} hat diese Unterhaltung nativ komprimiert, und nur es kann diese Komprimierung lesen, also bleibt die Unterhaltung dort: andere Konten werden nicht gefragt. Starte eine neue Unterhaltung, um sie zu nutzen.",
"{agent} requested a subagent; magpie selects its model within this routing group.": "{agent} hat einen Subagenten angefordert; magpie wählt sein Modell innerhalb dieser Weiterleitungsgruppe.",
"{agent} requested a subagent on {model}.": "{agent} hat einen Subagent mit {model} angefordert.",
"{agent} requested a subagent on {model} and it stayed there: its subagents are set to {to}, but {why}.": "{agent} hat einen Subagent mit {model} angefordert, und er blieb dort: Seine Subagenten sind auf {to} gesetzt, aber {why}.",
@@ -0,0 +1,89 @@
// Routing says a conversation stays on the account that compacted it
// natively (#1099), not that the account is the only one on for the model,
// which read as magpie not moving to the others (#2639).
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 assets = path.resolve(__dirname, "../assets");
const now = new Date();
const at = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
const account = {
id: "codex@biz@example.com", provider: "codex", name: "Codex", who: "biz@example.com",
kind: "account", agent: "codex", model: "gpt-6-astra", routing: "pace",
known: true, used: 45, pace: 1, due: new Date(now.getTime() + 3 * 36e5).toISOString(),
};
const route = (id, fields) => {
const r = {
id, seq: id, time: at(1), agent: "codex", model: "codex/gpt-6-astra", provider: "codex",
order: [account], done: true, status: 200, ms: 900, tokens: 1200, ...fields,
};
r.tries = [{ id: account.id, model: account.model, start: at(1), done: true, status: 200, ms: 900 }];
return r;
};
const routes = [
route(102, { compaction: account.id }),
route(101, {}),
];
function serve(lang) {
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({
contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};`,
});
if (url.pathname === "/wails/runtime.js") return request.fulfill({
contentType: "text/javascript", body: "export const Window = {};",
});
if (url.pathname === "/api/state") return json({
agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }],
profiles: [], settings: { lang, theme: "light" },
});
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((resolve) => setTimeout(resolve, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 102, totals: { requests: routes.length }, routes });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await request.fulfill({ body: await fs.readFile(file), contentType });
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: a natively compacted conversation says why it stays`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width: 1100, height: 1200 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
const pinned = { en: /compacted this conversation natively/, zh: /原生压缩了这条对话/, "zh-TW": /原生壓縮了這條對話/, ja: /ネイティブに圧縮/, de: /nativ komprimiert/ }[lang];
const only = { en: /only account on for/, zh: /唯一启用的账号/, "zh-TW": /唯一啟用的帳號/, ja: /有効なアカウントは/, de: /einzige/ }[lang];
const why = () => page.locator(".rt-steps li.why").first().textContent();
await page.locator(".rt-req").first().click();
await page.waitForFunction(() => document.querySelector(".rt-steps li.why"));
assert.match(await why(), pinned);
assert.match(await why(), /biz@example\.com/);
assert.doesNotMatch(await why(), only);
await page.locator(".rt-req").nth(1).click();
await page.waitForFunction((pattern) => !new RegExp(pattern).test(document.querySelector(".rt-steps li.why").textContent), pinned.source);
assert.doesNotMatch(await why(), pinned);
assert.deepEqual(errors, []);
});
}
}