Files
magpie/internal/gateway/opencode_session.go
T
JoeyWu-tech 55a190f195 gateway: conversations opened on one fixed message no longer share an id (#3938)
keeyangyy (#3938): with no session header, conversationID named a
conversation by the raw bytes of its first user message alone. Some
agents open every conversation on a message they write themselves and
send what the user typed as the next user message:

  {"role":"user","content":"<environment_context>cwd=/w/proj ...</environment_context>"},
  {"role":"user","content":"the question the user actually typed"}

That message is the same in every conversation started in one folder,
so all of them had one id: under Stays = session each new one was kept
on the account that answered the first, and rotate never moved on.

conversationOpening now says what is hashed, from the first user
message on (Chat and Anthropic messages, Responses input, Gemini
contents, where an omitted role is the user's):

- A first user message that holds anything of the user's own is hashed
  alone, as the request has it, exactly as before: their words
  (userWords, which already tells an <environment_context> or
  <user_instructions> block or an instruction file from what the user
  typed), an image, a file or a recording (userOpens). So is one that
  holds a tool's result.
- One the agent wrote alone is hashed with the user messages after it,
  in order, through the first that holds the user's own. A system or
  developer message between them is passed over.
- A reply, a call, its output, reasoning, a tool's result (Gemini's
  function result too), an item without a role (Chat, Responses) or
  one that can't be read ends the opening. With nothing of the user's
  before it, the first message is hashed alone, as before.

Every later turn repeats the opening before the first reply, so the id
holds through the conversation. A Responses input that is one string
is hashed as before.

An opening of several messages is hashed as writeOpening reads them,
one after another: every object's members in key order with no space
between, no cache_control at any depth, and a content of one text part
as that part's text. An agent marks its newest user message for the
cache and moves the mark on next turn, so the typed message's bytes
change at turn 2; some spell a marked message as a list of one part and
an unmarked one as a plain string (dsh does). Hashed as sent, an
opening of several would get a new id at its second turn, and on
/v1/messages under rotate that turn would go to the other key as a new
conversation (below). writeOpening reads the messages where they are:
the id of a 1.1 MB body whose opening holds a screenshot allocates
about 10 KB (TestOpeningHashReadsInPlace).

Every conversation whose first user message is the user's own keeps
the id it has, so no stick record needs moving. One that opened on an
agent's message and is under way when this lands gets an id of its own
on its next turn and is routed once as a new conversation: it may move
to another account, and its cache there starts over. The record they
all shared stays under the old id.

A tool's result (Anthropic clients send it as a user message) ends the
opening: it answers a call the model made, so the opening is over. A
history that starts with one was cut by its client (magpie takes such
orphans, TestMessagesOrphanToolResultWithoutACallBecomesText). Its
opening is gone, and whatever was taken in after the cut would move the
id each time the client cuts again, so its first message is hashed
alone, as before.

Not the issue's "first two user messages", nor every user message up
to the first reply: in an ordinary conversation the second user message
is the next turn, so the id would move when it arrives, and every
record would need the migration the issue describes. And a run of
every user message takes in what dsh sends after the typed prompt, its
runtime context, where the Context page finds dsh's sessions by the
typed prompt's hash alone; TestDshSessionConvsAreTheGatewayIDs and
TestDshRoutesCarryTheSessionConvs go red under such a run (below).

What reads the id moves with it: stickKey (session, turn and strict
affinity, and rotate's spread of new conversations), the Routing
trace's conv (convOf), a sealed task's lead (leadProvider,
loggedAnswerers), extraBody's ${sessionId}, Kilo's task and session
headers (KiloClient), X-Magpie-Conversation to plugins and OpenCode's
x-opencode-session fallback (openCodeSeed). A group rule's key reads
conversationID without a body, beside firstWords, which already passes
over the agent's blocks, so it doesn't change. One reader rebuilds the
id itself: sessions' dshConvs, which the Context page joins dsh's
sessions by (joinConvs). It hashes dsh's typed prompt, a first user
message of the user's own, which is still hashed alone, so its ids stay
the same. Nothing else in sessions, gui or elsewhere rebuilds a
"magpie-" id. The comments that named the first user message, and the
Gateway routing and Providers and accounts pages, say what the id is
now.

Siblings left for a decision, each in an issue filed with this
patch: #3988, ChatGPT accounts (conversationKey in
internal/provider/codex_request.go, for a client that sends no
prompt_cache_key), and #3989, Antigravity accounts (antigravitySession
in internal/provider/google.go). Both hash the first user message in the
provider package, and userWords is the gateway's.

Not changed: a fixed first message that userWords doesn't read as the
agent's is still hashed alone, so the conversations an agent opens on
it still share one id. A first user message hashed alone is hashed as
the request has it, cache mark and all, so a client without a session
header that marks that message on its first turn only gets a new id at
its second, as before. An agent that answers its own first message
with a fixed reply before the user's turn ends the opening at that
reply, so its first message is hashed alone too.

What was run (tree 523c770b, on origin/main a5315c70, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- This commit's tree alone: not run. It is a6037f68 rebased: its
  internal/ diff is the same (one patch-id), and
  docs/subsystems/gateway-routing.md was merged by hand beside main's
  new One try row. At the next commit's tree (71364f08), which adds a
  line to userWords' list and tests: this commit's tests, every break
  below again, -race, vet and the full suite, recorded in the next
  commit.

The rest is what was run for a6037f68, at tree e8fc1eee on origin/main
e9dd8e83, the same code (not this tree):
- New: TestConversationsOnOneEnvironmentMessageAreApart, on Chat,
  Messages, Responses and Gemini bodies, the last with and without
  roles. The issue's two conversations from one folder get two ids,
  neither the environment message's own, and each keeps its id on its
  next turn. A conversation that opens in the user's words has
  "magpie-" and the hex of sha256(its first user message)[:12], alone,
  on a later turn and with the agent's message after it. A screenshot
  after the agent's message opens a conversation as words do. A
  developer or system message between them doesn't move the id. dsh's
  turn, its runtime context marked for the cache, has the typed
  message's own. A history cut at a tool's result keeps its first
  message's own, and so do these after the agent's message: a tool's
  result, a Chat message without a role, a Responses call, its output
  or reasoning, and a Gemini function's result, in a user content or
  in its own role. A Responses string input is hashed as before.
  TestCacheMarkMovingOnKeepsTheID: the issue's opening on Messages,
  Chat and Responses, the mark on each turn's newest user message,
  turns 1, 2 and 3 with one id, the typed message going on unmarked as
  one part, as a plain string or with a screenshot, and on Chat marked
  on the message itself. TestOpeningHashReadsInPlace: the 1.1 MB body
  above under image_input_test.go's bar of an eighth of the body.
  TestNewConversationsInOneFolderAreRoutedApart: two keys, rotate,
  Stays = session, no session header. On /v1/chat/completions the two
  conversations are each "first", on different keys with different
  convs, and each next turn stays on its key as "session" with its
  conv. On /v1/messages a third conversation, its mark moving on, is
  "first" and turns 2 and 3 stay on its key as "session" with its conv.
- Broken by hand, each red:
  - back to the first user message alone (the old rule):
    TestConversationsOnOneEnvironmentMessageAreApart on all five bodies
    ("two conversations opened on one environment message": one id, the
    message's own; and the screenshot case),
    TestCacheMarkMovingOnKeepsTheID (each of its ten first turns the
    environment message's own),
    TestOpeningHashReadsInPlace ("the environment message was hashed
    alone") and TestNewConversationsInOneFolderAreRoutedApart (the
    second conversation on k1 as "session", with the first's conv).
  - every consecutive user message, unread: the five bodies' cases
    with the agent's message after the user's, the screenshot cases,
    dsh's two turns, the cut history, the tool's result after the
    agent's message and Gemini's function result in a user content,
    and TestDshSessionConvsAreTheGatewayIDs and
    TestDshRoutesCarryTheSessionConvs (the turn's conv not among the
    session's).
  - a tool's result taken into the opening, and passed over like a
    developer message: the cut history, the tool's result after the
    agent's message and Gemini's function result, each way.
  - a system or developer message ending the opening: the Chat and
    Responses pairs.
  - an image, a file or a recording not counted as the user's: the
    screenshot case on all five bodies.
  - an item without a role passed over like a developer message: the
    Chat message without a role and the Responses call, output and
    reasoning.
  - Gemini's functionResponse not read as a tool's result: its case.
  - an opening of several hashed as sent:
    TestCacheMarkMovingOnKeepsTheID at turns 2 and 3 in all ten
    spellings, and on /v1/messages turn 2 went to k2 as "first" with a
    new conv, where turn 1 was on k1.
  - cache marks kept: the screenshot spellings and the message marked
    on Chat, at turns 2 and 3 (a one-part content is read as its text
    either way).
  - a content of one text part not read as its text: the three plain
    string spellings at turns 2 and 3.
  - each string copied before it is hashed: TestOpeningHashReadsInPlace,
    2,233,788 bytes an id.
- With their neighbours, -v: TestConversationID, the Dsh tests in
  gateway and sessions, TestContextDshSessionTitles,
  TestImageWalkReadsTextOnlyTurnsInPlace, the orphan tool result tests,
  TestClaudeConversationKeepsItsAccountsCache, and the affinity,
  rotate, strict, sticks, session route, OpenCode, extra body,
  WorkBuddy session and gateway conversation tests: 115 tests in
  gateway, sessions, gui and provider pass (154 with subtests).
- -race -count=5: TestConversationsOnOneEnvironmentMessageAreApart,
  TestCacheMarkMovingOnKeepsTheID,
  TestNewConversationsInOneFolderAreRoutedApart, TestAffinity,
  TestRotateSpreadsSessions, TestRotateSpreadsABurstOfNewConversations,
  TestGeminiFallbackSessionAffinity, TestSticksWrittenBehind, the three
  TestStrictAffinity tests, the two dsh conv tests and
  TestClaudeConversationKeepsItsAccountsCache: 14 tests, 5 of 5 each.
  -race -count=3: TestOpeningHashReadsInPlace and
  TestImageWalkReadsTextOnlyTurnsInPlace, 3 of 3 each (the id under
  -race: 17 to 32 KB).
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  build -tags nogui for linux and darwin, and go vet and go build for
  windows without the tag: exit 0 each. go vet and go build without
  the tag on linux: exit 1 (this box has no GTK or WebKitGTK dev
  packages).
- go test -tags nogui -count=1 -timeout 45m ./... (tools/suite.sh, Bun
  1.4.2, log kept; 8m23s, load 21 at its start): 71 packages ok, 5
  red, none in what this changes: agent TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141), TestCodexDriftReached (#3398) and the two
  Reasonix tests (#3641); edit TestWriteAtomicReadOnlyHardLink and
  testenv TestProgram (umask 077, #3640); gateway
  TestPluginToldWhereTheAgentWorks (#3675), the package ran to its
  end, so the new tests passed in it too; gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649).

Not tried: keeyangyy's own client, or any real agent end to end.

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).
2026-11-03 20:38:11 +08:00

110 lines
4.8 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"slices"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// openCodeSeed names the conversation a request to OpenCode's gateway is a
// turn of, for its x-opencode-session (provider.OpenCodeClient): the
// client's own x-opencode-session when it sent one, else the session the
// client names (X-Magpie-Session, Codex's session_id, Claude Code's
// session, Pi's affinity: sessionOf), else the body's prompt_cache_key
// (Codex's thread), else how the conversation opens
// (conversationID). OpenCode itself sends one session id for every turn of
// a session (packages/core/src/session/affinity.ts), and Zen and Go route
// a session to the backend that has its prompt cached: every turn of one
// conversation names the same, and two conversations never one. Without
// the cache key, two of Codex's conversations in one folder, which open on
// the same environment message, were one session.
func openCodeSeed(in http.Header, body []byte) string {
if v := strings.TrimSpace(in.Get("x-opencode-session")); v != "" {
return v
}
if v := sessionOf(in); v != "" {
return v
}
if k := strings.TrimSpace(gjson.GetBytes(body, "prompt_cache_key").String()); k != "" {
return "prompt_cache_key\x00" + k
}
return conversationID(in, body)
}
// logOpenCodeRefusal writes to magpie's log what went to OpenCode's
// gateway with a request it refused: where, the names of the headers sent
// (never a value), and whether x-opencode-session was among them, by its
// first 8 characters. OpenCode answers a request without one 400
// "Request is missing x-opencode-session and cannot be routed
// efficiently" (luci on Discord), and this tells that apart from a
// session the user's own header pins every conversation to.
func logOpenCodeRefusal(p provider.Provider, req *http.Request, status int) {
var names []string
for k := range req.Header {
names = append(names, strings.ToLower(k))
}
slices.Sort(names)
session := "missing"
if v := req.Header.Get("x-opencode-session"); v != "" {
session = v[:min(len(v), 8)] + "…"
for k, v := range p.Headers {
// ${sessionId} in it is each conversation's own
if strings.EqualFold(k, "x-opencode-session") && !strings.Contains(v, provider.SessionPlaceholder) && !strings.Contains(v, provider.ThreadPlaceholder) {
session += " (the provider's own header: one session for every conversation)"
}
}
}
log.Printf("opencode: %s answered %d to %s %s%s; x-opencode-session %s; headers sent: %s",
p.ID, status, req.Method, req.URL.Host, req.URL.Path, session, strings.Join(names, ", "))
}
// errorKeys are the fields any error an API answers carries, in its own
// body or in an error object of it: a body none of them name says nothing
// of why.
var errorKeys = []string{"error", "message", "msg", "code", "type", "param", "detail", "reason", "description"}
// openCodeBare is said in the 502 openCodeBareRefusal makes of a bare 400,
// for restAfterMarked to rest nobody for it.
const openCodeBare = "which is no error, not an API reply"
// openCodeBareRefusal is res as the 502 it stands for, when OpenCode's
// gateway answers a request with a 400 whose body is no error at all:
// {"model":"deepseek-v4.1-flash"}, the model's name and nothing else
// (#3740, s-leeq), with nothing in or out and no reply id. The same
// request is answered some seconds later (s-leeq's timelines: four to six
// 400s over 13s to 25s, then a 200 of the same prompt), so it is read as
// the 502 such a failure is: a group's next member is asked, and a lone
// provider is asked again within its patience, which outlasts that
// window, where the 400 ended the turn at once. It is tied to the request
// (in s-leeq's day, 30 of 214 requests carrying ~246K tokens of tools
// failed so and none of 420 carrying under 1K), so nobody rests for it
// (restAfterMarked): the key goes on serving the requests it serves. A
// 400 that names anything, as the missing x-opencode-session refusal
// does, goes on as it came, as does a body that isn't a JSON object.
func openCodeBareRefusal(req *http.Request, res *http.Response) *http.Response {
if res == nil || res.StatusCode != http.StatusBadRequest || res.Body == nil ||
req == nil || !provider.OpenCodeURL(req.URL.String()) {
return res
}
b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
// what wasn't read is read after what was: a body is never cut
res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body}
var v map[string]any
if len(b) == 64<<10 || json.Unmarshal(bytes.TrimSpace(b), &v) != nil {
return res
}
for _, k := range errorKeys {
if _, ok := v[k]; ok {
return res
}
}
return asBadGateway(res, "", "answered "+res.Status+" with "+clipRunes(strings.TrimSpace(string(b)), 200)+", "+openCodeBare)
}