From ae7dc10ae284f79042ddf8fcddbfb4becc3cdffe Mon Sep 17 00:00:00 2001 From: bborn Date: Sun, 18 Oct 2026 20:03:14 +0800 Subject: [PATCH 01/92] docker: the image is Debian 12 slim, so the Cursor and Devin CLIs magpie installs at sign-in run in it (#2834, bborn2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit magpie installs a subscription's CLI at sign-in with its vendor's `curl … | bash` (internal/provider/install.go: Cursor, Devin, Grok Build). The distroless image had no curl and no /usr/bin/env (the installers' shebang), so that install couldn't run there, and only Grok Build had a native fallback. bborn2 reported that a Cursor CLI installed by hand failed with "cannot execute: required file not found". The image is now debian:12-slim with ca-certificates and curl. It keeps the nonroot user at uid/gid 65532, HOME and XDG under /config, the healthcheck, and magpie on PATH. Size: 157MB against 82MB for origin/main's image, both built here on arm64. Running a feature magpie offers is worth the 75MB. Changed in review: dropped the branch's GOPROXY build arg, a separate goal. The comments in install.go and install_test.go that said the image has no curl now say "had". docs/reference.md and the site's Docker page (en, zh, ja) say Debian with bash and curl instead of distroless with busybox. Run, with OrbStack's docker: - docker build of this tree and of d783df46c's Dockerfile: 157MB vs 82MB. - docker run of the new image: health "healthy", user nonroot (id 65532). `curl https://cursor.com/install -fsS | bash` exit 0, then `~/.local/bin/cursor-agent --version` printed 2026.10.16-e3cb207. Devin's install.sh installed devin v3000.11.92 (its trailing `devin setup` said "Login canceled" with no terminal, as on any host). `devin --version` printed 3000.11.92. bash and `magpie version` run. - Old image: `which curl` finds none, and /usr/bin/env doesn't exist. - A volume written by the old image (file owned 65532) was read and written by the new image. - gofmt -l clean; go vet darwin, linux (nogui) and windows clean. - Full `go test -tags nogui -timeout 45m ./...`: every package ok except internal/agent and internal/gateway, which timed out at 45m mid-test (TestConnectSaysHow, TestLargeRequestEndpoints) under a load average of about 200 from parallel suites. This commit changes no code those packages build, only comments in internal/provider, which passed (992s), so they weren't rerun. Not tried: a Grok Build install inside the image, and a full in-magpie Cursor/Devin sign-in with a real account in the container. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 38 +++++++++++++------------------ docs/reference.md | 7 +++--- internal/provider/install.go | 8 ++++--- internal/provider/install_test.go | 2 +- site/public/docs/docker.html | 2 +- site/public/docs/ja/docker.html | 2 +- site/public/docs/zh/docker.html | 2 +- 7 files changed, 29 insertions(+), 32 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1daa2a719..9199eac4e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,31 +12,25 @@ RUN CGO_ENABLED=0 go build -tags nogui -trimpath \ -ldflags "-s -w -X main.version=${VERSION}" -o /out/magpie . \ && mkdir -p /config/home /config/cache /config/data /config/state -# A shell for the container's terminal: NAS panels (Synology, 1Panel, -# Portainer) open /bin/bash or /bin/sh, and distroless has neither, so a -# terminal there failed with "stat /bin/bash: no such file or directory". -# Debian 12's bash (with the libtinfo it links), which runs on the glibc of -# distroless's own Debian 12, and busybox for ls, cat and the like. -FROM debian:12-slim AS shell -RUN mkdir -p /out/bin /out/lib \ - && cp /bin/bash /out/bin/bash \ - && cp -L "$(ldd /bin/bash | awk '/libtinfo/ {print $3}')" /out/lib/ +# Debian, not distroless: a subscription's CLI is installed with its +# vendor's `curl … | bash` (Cursor, Devin, Grok Build), and the CLI it +# installs is a glibc binary that needs a full system's loader and +# libraries. distroless with a copied curl ran the installer, but Cursor's +# cursor-agent then failed with "cannot execute: required file not found". +# Debian 12 has the glibc, libgcc and libstdc++ the plugins' Bun needs too, +# and bash for a NAS panel's terminal. nonroot keeps distroless's uid 65532, +# so a volume made by an older image stays writable. +FROM debian:12-slim -FROM busybox:1.37-uclibc AS busybox - -# cc, not static: plugins run on Bun, which magpie downloads on first use -# and which needs glibc (static has no libc at all, and Bun's musl build -# would need musl). cc is static plus glibc, libgcc and libstdc++. -FROM gcr.io/distroless/cc-debian12:nonroot +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd -g 65532 nonroot \ + && useradd -u 65532 -g nonroot -d /config/home -s /bin/bash nonroot COPY --from=build /out/magpie /magpie -COPY --from=busybox /bin/busybox /bin/busybox -COPY --from=shell /out/bin/bash /bin/bash -COPY --from=shell /out/lib/ /usr/lib/ -# busybox's commands, and magpie on PATH, so `magpie accounts add …` works -# in that terminal -USER root -RUN ["/bin/busybox", "sh", "-c", "/bin/busybox --install -s /bin && mkdir -p /usr/local/bin && ln -s /magpie /usr/local/bin/magpie"] +# magpie on PATH, so `magpie accounts add …` works in that terminal +RUN ln -s /magpie /usr/local/bin/magpie USER nonroot COPY --from=build --chown=65532:65532 /config /config diff --git a/docs/reference.md b/docs/reference.md index bfd30b4f3..e1106c862 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -2230,9 +2230,10 @@ uses the service's gateway. ### Docker -`docker build` makes a server image: the terminal-only binary on -distroless (`cc`, for the glibc the plugins' Bun needs) with bash and -busybox for a terminal in the container (`docker exec -it magpie bash`, or a +`docker build` makes a server image: the terminal-only binary on Debian 12 +slim, with bash and curl, so a vendor's `curl … | bash` installer runs and +the CLI it installs (Cursor's, Devin's, Grok Build) finds the glibc it links, +as the plugins' Bun does, and a terminal opens in the container (`docker exec -it magpie bash`, or a NAS panel's terminal; `magpie` is on its PATH), run as nonroot, with everything it keeps in a volume at `/config`: magpie's own files (`/config/magpie`), the sign-ins kept where their agent keeps them (HOME is diff --git a/internal/provider/install.go b/internal/provider/install.go index 0bdfad9cb..ed0a351f5 100644 --- a/internal/provider/install.go +++ b/internal/provider/install.go @@ -22,7 +22,7 @@ import ( // agentCLI is a CLI a subscription runs through: how to find it, and the // vendor's install one-liners for a POSIX shell and for PowerShell. native, // when there is one, does what the shell one does without a shell, for a -// magpie with none (its Docker image has no bash, curl or wget). setup: the +// magpie with none (its Docker image had no bash, curl or wget until #2834). setup: the // installer ends by running the CLI's own setup, which asks how to sign in; // magpie signs in itself once the CLI is there. type agentCLI struct { @@ -148,8 +148,10 @@ func runUntilInstalled(ctx context.Context, cmd *exec.Cmd, c agentCLI) ([]byte, // bash, and curl, which every one-liner (and the scripts behind them) // downloads with. magpie's Docker image had none of them, and the install // failed there with "exec: bash: not found". Since 7bfe3137 it has bash and -// busybox's wget but still no curl, and the one-liner failed there too. A -// var so tests can say there is none. +// busybox's wget but still no curl, and the one-liner failed there too. +// Since #2834 it is Debian with bash and curl, and the CLIs the one-liners +// install find the loader and libraries they link. A var so tests can say +// there is none. var shellInstallerRuns = func() bool { for _, p := range []string{"bash", "curl"} { if _, err := exec.LookPath(p); err != nil { diff --git a/internal/provider/install_test.go b/internal/provider/install_test.go index d0460c5a6..7fb727692 100644 --- a/internal/provider/install_test.go +++ b/internal/provider/install_test.go @@ -98,7 +98,7 @@ func waitPast(t *testing.T, id, state string) SignInState { return SignInState{} } -// magpie's Docker image has bash and busybox's wget but no curl, which every +// magpie's Docker image had bash and busybox's wget but no curl, which every // vendor's one-liner downloads with: there the native installer is used func TestShellInstallerNeedsCurl(t *testing.T) { if runtime.GOOS == "windows" { diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index 9269ebdea..defe1d07a 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -93,7 +93,7 @@ Volume/config: providers, keys, sign-ins, plugins and usage Usernonroot (uid 65532) -

The image holds magpie’s terminal-only build on distroless, with bash and busybox for a terminal in the container. It runs magpie serve (the gateway alone) unless given another command. The container finds no agents to wire, so magpie in it is a gateway: the agents that use it run elsewhere.

+

The image holds magpie’s terminal-only build on Debian 12 slim, with bash for a terminal in the container and curl for the installers of the CLIs some subscriptions sign in with (Cursor, Devin, Grok Build). It runs magpie serve (the gateway alone) unless given another command. The container finds no agents to wire, so magpie in it is a gateway: the agents that use it run elsewhere.

Run it

Run it with the browser UI, a key for that page you keep across restarts, and both ports on the host’s loopback only:

diff --git a/site/public/docs/ja/docker.html b/site/public/docs/ja/docker.html index 43302c61c..550632cb8 100644 --- a/site/public/docs/ja/docker.html +++ b/site/public/docs/ja/docker.html @@ -93,7 +93,7 @@ ボリューム/config:プロバイダ、キー、サインイン、プラグイン、使用量 ユーザーnonroot(uid 65532) -

イメージに入っているのはターミナル専用ビルドの magpie で、distroless をベースに、コンテナ内でターミナルを使うための bash と busybox を含みます。コマンドを指定しなければ magpie serve(ゲートウェイのみ)を実行します。コンテナ内には設定するエージェントがないので、ここでの magpie はゲートウェイです。それを使うエージェントはほかのマシンで動きます。

+

イメージに入っているのはターミナル専用ビルドの magpie で、Debian 12 slim をベースに、コンテナ内でターミナルを使うための bash と、一部のサブスクリプションのサインインに必要な CLI(Cursor、Devin、Grok Build)をインストールするための curl を含みます。コマンドを指定しなければ magpie serve(ゲートウェイのみ)を実行します。コンテナ内には設定するエージェントがないので、ここでの magpie はゲートウェイです。それを使うエージェントはほかのマシンで動きます。

起動する

ブラウザ UI 付きで、再起動しても変わらないページ用のキーを渡し、両方のポートをホストのループバックだけに公開して起動します。

diff --git a/site/public/docs/zh/docker.html b/site/public/docs/zh/docker.html index 5ac2be38f..9d12a9787 100644 --- a/site/public/docs/zh/docker.html +++ b/site/public/docs/zh/docker.html @@ -93,7 +93,7 @@ 数据卷/config:供应商、密钥、登录、插件和用量 用户nonroot(uid 65532) -

镜像里是 magpie 的纯终端版本,基于 distroless,并带了 bash 和 busybox,方便在容器里开终端。不指定命令时运行 magpie serve(只有网关)。容器里找不到需要配置的 Agent,所以这里的 magpie 是一个网关:用它的 Agent 运行在别的机器上。

+

镜像里是 magpie 的纯终端版本,基于 Debian 12 slim,带 bash,方便在容器里开终端,也带 curl,用来安装部分订阅登录时需要的 CLI(Cursor、Devin、Grok Build)。不指定命令时运行 magpie serve(只有网关)。容器里找不到需要配置的 Agent,所以这里的 magpie 是一个网关:用它的 Agent 运行在别的机器上。

运行

带 Web 界面运行,给页面一个重启后不变的 key,两个端口都只发布在宿主机的回环地址上:

From 11173c8a20bf8e74b10ca08b509c7675c62dadb3 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 18 Oct 2026 02:23:03 +0800 Subject: [PATCH 02/92] gateway: a long Computer Use turn fits each screenshot once, not every turn (fflake33 on Discord) fflake33 (magpie 0.1.1279, macOS) sent Codex Computer Use turns of 570K-680K tokens with hundreds of screenshots through the Responses route to codex/gpt-6.1-sol: 26.5s and 52.7s of the 41.7s and 71s to the first token were magpie's own work, sampled in image resize, JPEG decode/encode and JSON. The causes, from a pprof CPU and alloc profile of a synthetic turn (160 distinct 2940x1912 JPEG screenshots, 112 MB body): - codexImagesFit's cache of fitted images was a map cleared at 64 entries, so past 64 screenshots every image of every turn was decoded, resized and JPEG-encoded again: ~19s CPU a turn (triangleResize 42 GB allocated over 3 turns). - It looked each part up by path from the top of the body (gjson "input.%d.content.%d"), reading the 112 MB body again for every image: ~9s CPU a turn. What changed: - codexImagesFit walks the body once (ForEach over items and parts, at their offsets) and splices only the changed image strings; the rest of the body goes byte for byte as before. - The cache (fitted) is an LRU keyed by sha256 of the limits and data URL, bounded at 256 MB of fitted bytes and 8192 entries, letting go of what goes unsent for an hour. It holds the encoded bytes, not the base64. A request looks all its images up before keeping any it made, so a conversation larger than the budget still finds what was kept since its last turn. - Images not kept are made side by side, at most min(4, GOMAXPROCS) at once (each holds ~100 MB for a Retina screenshot); the same image twice in one request is made once. - Sibling: the describer's cache (vision.go sights) was FIFO at 256, so a text-only model sent 300 screenshots described every one again each turn. It is now LRU at 2048 (a description is a few KB). Numbers, codex_images_timing_test.go (MAGPIE_TURN_TIMING=1), magpie's time before the fake upstream had the request, 160-163 screenshots, run back to back at load ~15-60 on this M-series mac: - before (de671719a): turns 1-4 31.4s, 30.6s, 31.7s, 35.2s; CPU 27.5-28.4s per turn (pprof labels per turn) - after: turn 1 7.5s (18.4s CPU, 160 images made in parallel), turns 2-4 2.7s, 2.6s, 5.2s; CPU 2.4-2.6s per turn The ~2.4s left per 112 MB turn is whole-body JSON passes (decodeJSON with jsonValid and RawMessage clones, parseResponses, codexBody's re-marshal, ~0.4-0.8s each); not changed here, as each needs its byte-for-byte output re-proven. echo_ts (Codex through magpie on Copilot ~10x slower, no images): the same timing test on a Copilot account with no images measured magpie's local work at ~3ms (33 KB), ~13ms (215 KB) and ~56ms (989 KB) per turn on the old code at low load, the same on the new. That is not a 10x, so its cause is elsewhere and is not fixed here. Tests, each broken by hand and seen red: - TestCodexScreenshotsAreNotFittedAgainEachTurn: 100 then 101 distinct screenshots; the second turn makes only its new one, and sends the others as the same bytes. Clear-at-64 restored: "made 65 images again". - TestCodexFittedImagesPastTheBudget: 30 images over a budget of 10; turns 2 and 3 make 20 each, held bytes within budget. Keeping each image as it is made: 30 of 30 each turn; budget unchecked: held past it. - TestCodexFittedImagesLetGoWhenIdle. - TestManyImagesDescribedOnce: 300 images twice to a text-only model are described 300 times. sightsKept 256 restored: 576. Run: gofmt -l (clean); go vet ./... on darwin, GOOS=linux and GOOS=windows -tags nogui; go test -race on the gateway's TestCodex*, TestManyImagesDescribedOnce and TestTextOnlyModel* (ok); full `set -o pipefail; go test -timeout 45m ./...` at ab88ffd55 (this change on origin/main 2026-10-18 21:4x): every package ok except internal/agent, which hit the 45m package timeout under load ~200 (running TestT3CodeKeepsTheUsersSettings at 0s, the known #2544/#2723); alone with -timeout 90m it is ok (4385s, load ~250-350). gateway ok in 2600s, provider ok in 438s. Not tried: a real Computer Use session against ChatGPT; Windows or Linux runs of the timing test. --- internal/gateway/codex_images.go | 338 ++++++++++++++----- internal/gateway/codex_images_test.go | 133 ++++++++ internal/gateway/codex_images_timing_test.go | 203 +++++++++++ internal/gateway/vision.go | 15 +- internal/gateway/vision_test.go | 26 ++ 5 files changed, 631 insertions(+), 84 deletions(-) create mode 100644 internal/gateway/codex_images_timing_test.go diff --git a/internal/gateway/codex_images.go b/internal/gateway/codex_images.go index c2e0554ce..e7c2e844b 100644 --- a/internal/gateway/codex_images.go +++ b/internal/gateway/codex_images.go @@ -2,17 +2,23 @@ package gateway import ( "bytes" + "container/list" "crypto/sha256" "encoding/base64" - "fmt" + "encoding/binary" "image" "image/draw" "image/gif" "image/jpeg" "image/png" + "io" "math" + "runtime" + "slices" "strings" "sync" + "sync/atomic" + "time" "github.com/tidwall/gjson" @@ -37,61 +43,153 @@ func codexImagesFit(p provider.Provider, to provider.Protocol, body []byte) []by if p.Account == nil || p.Account.Agent != "codex" || to != provider.Responses || !bytes.Contains(body, []byte(`input_image`)) { return body } - type swap struct { - at, end int - with string - } - var swaps []swap - var with []int // the input items with an image in them - i := 0 + // One walk of the body: each input item, and the parts of the items + // with an image in them, read where they sit. Looking each part up + // again by its path from the top read the body from its start for + // every image: in a Computer Use turn of 160 screenshots, gigabytes of + // JSON read for one request (fflake33, Discord). + var jobs []fitJob gjson.GetBytes(body, "input").ForEach(func(_, item gjson.Result) bool { - if strings.Contains(item.Raw, "input_image") { - with = append(with, i) + if !strings.Contains(item.Raw, "input_image") { + return true } - i++ + item.ForEach(func(key, parts gjson.Result) bool { + if key.Str != "content" && key.Str != "output" || !parts.IsArray() { + return true + } + parts.ForEach(func(_, part gjson.Result) bool { + // the part's members read once, not once for each + var kind, detail, url gjson.Result + part.ForEach(func(k, v gjson.Result) bool { + // the first of a key given twice, as Get reads it + switch { + case k.Str == "type" && !kind.Exists(): + kind = v + case k.Str == "detail" && !detail.Exists(): + detail = v + case k.Str == "image_url" && !url.Exists(): + url = v + } + return true + }) + if kind.String() != "input_image" { + return true + } + end := url.Index + len(url.Raw) + if url.Type != gjson.String || url.Index <= 0 || end > len(body) || string(body[url.Index:end]) != url.Raw || !strings.HasPrefix(url.Str, "data:") { + return true + } + if limits, ok := codexImageLimits(detail.String()); ok { + jobs = append(jobs, fitJob{at: url.Index, end: end, url: url.Str, l: limits}) + } + return true + }) + return true + }) return true }) - for _, i := range with { - for _, key := range []string{"content", "output"} { - parts := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s", i, key)) - if !parts.IsArray() { - continue - } - for j := range parts.Array() { - part := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d", i, key, j)) - if part.Get("type").String() != "input_image" { - continue - } - url := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d.image_url", i, key, j)) - if url.Type != gjson.String || url.Index <= 0 || !strings.HasPrefix(url.Str, "data:") { - continue - } - limits, ok := codexImageLimits(part.Get("detail").String()) - if !ok { - continue - } - if fit, ok := codexImageFit(url.Str, limits); ok { - swaps = append(swaps, swap{url.Index, url.Index + len(url.Raw), `"` + fit + `"`}) - } - } - } - } - if len(swaps) == 0 { + if len(jobs) == 0 { return body } + fitAll(jobs) + slices.SortFunc(jobs, func(a, b fitJob) int { return a.at - b.at }) // the rest of the request goes byte for byte as it came, for the // prompt cache var out bytes.Buffer - last := 0 - for _, s := range swaps { - out.Write(body[last:s.at]) - out.WriteString(s.with) - last = s.end + last, swapped := 0, false + for _, j := range jobs { + if !j.changed || j.at < last { + continue + } + if !swapped { + out.Grow(len(body)) + swapped = true + } + out.Write(body[last:j.at]) + out.WriteByte('"') + out.WriteString(j.with) + out.WriteByte('"') + last = j.end + } + if !swapped { + return body } out.Write(body[last:]) return out.Bytes() } +// fitJob is one image of a request: where its data URL's JSON string +// sits, the URL, the limits it is fitted to, and what it is sent as. +type fitJob struct { + at, end int + url string + l imageLimits + key [32]byte + with string + changed bool +} + +// fitWorkers is how many images of a request are made again at once: +// each holds a decoded screenshot and its resize, near 100 MB for a +// Retina one. +const fitWorkers = 4 + +// fitAll fits each job's image: as it was kept (fitted), or else made +// again, the images not kept made side by side. +func fitAll(jobs []fitJob) { + fitted.letGo() + var todo []int + for i := range jobs { + j := &jobs[i] + comma := strings.IndexByte(j.url, ',') + if comma < 0 || !strings.HasSuffix(j.url[:comma], ";base64") { + continue + } + j.key = fitKey(j.url, j.l) + if e, ok := fitted.get(j.key); ok { + j.with, j.changed = e.url(), e.data != nil + continue + } + todo = append(todo, i) + } + if len(todo) == 0 { + return + } + // the same screenshot twice in a request is made once + made := map[[32]byte]*fitEntry{} + var order []int + for _, i := range todo { + if _, ok := made[jobs[i].key]; !ok { + made[jobs[i].key] = &fitEntry{} + order = append(order, i) + } + } + next := make(chan int) + var wg sync.WaitGroup + for range min(fitWorkers, runtime.GOMAXPROCS(0), len(order)) { + wg.Add(1) + go func() { + defer wg.Done() + for i := range next { + j := jobs[i] + *made[j.key] = codexImageRefit(j.url[strings.IndexByte(j.url, ',')+1:], j.l) + } + }() + } + for _, i := range order { + next <- i + } + close(next) + wg.Wait() + for _, i := range order { + fitted.put(jobs[i].key, *made[jobs[i].key]) + } + for _, i := range todo { + e := made[jobs[i].key] + jobs[i].with, jobs[i].changed = e.url(), e.data != nil + } +} + type imageLimits struct{ side, patches int } // codexPatch is the patch a Responses model reads an image in. @@ -138,52 +236,130 @@ func (l imageLimits) size(w, h int) (int, int) { // to hold: one past it goes as it came. const codexImageMaxPixels = 80 << 20 -// fitted holds what codexImageFit made of the images a conversation -// sends again on every turn. -var fitted = struct { - sync.Mutex - m map[[32]byte]string -}{m: map[[32]byte]string{}} - -// codexImageFit is a data URL's image as Codex's client would send it, -// and whether that differs from what came. -func codexImageFit(url string, l imageLimits) (string, bool) { - comma := strings.IndexByte(url, ',') - if comma < 0 || !strings.HasSuffix(url[:comma], ";base64") { - return "", false - } - key := sha256.Sum256([]byte(fmt.Sprint(l.side, l.patches, url))) - fitted.Lock() - got, ok := fitted.m[key] - fitted.Unlock() - if ok { - return got, got != "" - } - got = codexImageRefit(url[comma+1:], l) - fitted.Lock() - if len(fitted.m) >= 64 { - clear(fitted.m) - } - fitted.m[key] = got - fitted.Unlock() - return got, got != "" +// fitEntry is what an image is sent as: data in mime, or, with no data, +// the image as it came. +type fitEntry struct { + mime string + data []byte } -// codexImageRefit is the data URL of an image's base64 resized and -// written again, or "" when it goes as it came. -func codexImageRefit(b64 string, l imageLimits) string { +// url is the entry's data URL, or "" for the image as it came. +func (e fitEntry) url() string { + if e.data == nil { + return "" + } + return "data:" + e.mime + ";base64," + base64.StdEncoding.EncodeToString(e.data) +} + +// fitKey names an image's data URL fitted to l. +func fitKey(url string, l imageLimits) [32]byte { + h := sha256.New() + var n [16]byte + binary.LittleEndian.PutUint64(n[:8], uint64(l.side)) + binary.LittleEndian.PutUint64(n[8:], uint64(l.patches)) + h.Write(n[:]) + io.WriteString(h, url) + var k [32]byte + h.Sum(k[:0]) + return k +} + +// fitted holds what codexImageRefit made of the images a conversation +// sends again on every turn, so that a past screenshot is decoded, resized +// and encoded once, not on each turn. It is bounded by the bytes it holds +// (fittedBudget), dropping the least recently used first, and drops what +// no request has sent for fittedIdle. The 64-entry map it replaces was +// cleared when full, so past 64 screenshots every turn made each of them +// again (fflake33, Discord). +// +// A request looks up all its images before it keeps any it made, so a +// conversation larger than the budget still finds the images kept since +// its last turn, rather than dropping each just before it is sent again. +var fitted = &fitCache{m: map[[32]byte]*list.Element{}} + +// fittedBudget is how many bytes of fitted images are kept, and +// fittedIdle how long one is kept unsent. fittedMost bounds the entries, +// as most images go as they came and hold no bytes. +var ( + fittedBudget = 256 << 20 + fittedIdle = time.Hour + fittedMost = 8192 +) + +type fitCache struct { + sync.Mutex + m map[[32]byte]*list.Element + order list.List // of *fitItem, the most recently used first + bytes int +} + +type fitItem struct { + key [32]byte + e fitEntry + used time.Time +} + +// letGo drops what has gone unsent for fittedIdle. +func (c *fitCache) letGo() { + c.Lock() + defer c.Unlock() + now := time.Now() + for back := c.order.Back(); back != nil && now.Sub(back.Value.(*fitItem).used) > fittedIdle; back = c.order.Back() { + c.drop(back) + } +} + +func (c *fitCache) get(k [32]byte) (fitEntry, bool) { + c.Lock() + defer c.Unlock() + el, ok := c.m[k] + if !ok { + return fitEntry{}, false + } + it := el.Value.(*fitItem) + it.used = time.Now() + c.order.MoveToFront(el) + return it.e, true +} + +func (c *fitCache) put(k [32]byte, e fitEntry) { + c.Lock() + defer c.Unlock() + if _, ok := c.m[k]; ok || len(e.data) > fittedBudget { + return + } + for c.bytes+len(e.data) > fittedBudget || len(c.m) >= fittedMost { + c.drop(c.order.Back()) + } + c.m[k] = c.order.PushFront(&fitItem{key: k, e: e, used: time.Now()}) + c.bytes += len(e.data) +} + +func (c *fitCache) drop(el *list.Element) { + it := c.order.Remove(el).(*fitItem) + delete(c.m, it.key) + c.bytes -= len(it.e.data) +} + +// refits counts the images codexImageRefit decodes and writes again. +var refits atomic.Int64 + +// codexImageRefit is an image's base64 resized and written again, or an +// entry with no data when it goes as it came. +func codexImageRefit(b64 string, l imageLimits) fitEntry { raw, err := base64.StdEncoding.DecodeString(b64) if err != nil { - return "" + return fitEntry{} } cfg, format, err := image.DecodeConfig(bytes.NewReader(raw)) if err != nil || cfg.Width*cfg.Height > codexImageMaxPixels { - return "" + return fitEntry{} } w, h := l.size(cfg.Width, cfg.Height) if w == cfg.Width && h == cfg.Height && format != "gif" { - return "" + return fitEntry{} } + refits.Add(1) var src image.Image switch format { case "png": @@ -193,10 +369,10 @@ func codexImageRefit(b64 string, l imageLimits) string { case "gif": src, err = gif.Decode(bytes.NewReader(raw)) default: - return "" + return fitEntry{} } if err != nil { - return "" + return fitEntry{} } if w != cfg.Width || h != cfg.Height { src = triangleResize(src, w, h) @@ -210,9 +386,9 @@ func codexImageRefit(b64 string, l imageLimits) string { err = png.Encode(&out, src) } if err != nil { - return "" + return fitEntry{} } - return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(out.Bytes()) + return fitEntry{mime: mime, data: out.Bytes()} } // triangleResize scales src to w by h with a triangle (linear) filter diff --git a/internal/gateway/codex_images_test.go b/internal/gateway/codex_images_test.go index 47b381868..4c0e815cf 100644 --- a/internal/gateway/codex_images_test.go +++ b/internal/gateway/codex_images_test.go @@ -2,8 +2,10 @@ package gateway import ( "bytes" + "container/list" "encoding/base64" "encoding/json" + "fmt" "image" "image/color" "image/jpeg" @@ -14,6 +16,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/tidwall/gjson" @@ -265,3 +268,133 @@ func TestCodexAccountGetsScreenshotAtCodexSize(t *testing.T) { } t.Logf("%d bytes from the agent, %d to ChatGPT", len(body), len(got)) } + +// freshFitted gives a test a cache of fitted images of its own, with +// budget bytes, and counts the images made again from here. +func freshFitted(t *testing.T, budget int) func() int64 { + t.Helper() + was, wasBudget := fitted, fittedBudget + fitted, fittedBudget = &fitCache{m: map[[32]byte]*list.Element{}}, budget + t.Cleanup(func() { fitted, fittedBudget = was, wasBudget }) + from := refits.Load() + return func() int64 { return refits.Load() - from } +} + +// computerUseRequest is a Responses turn with each of shots as a +// Computer Use tool's screenshot, as Codex sends a conversation's every +// past screenshot again on each turn. +func computerUseRequest(shots []string) []byte { + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%d", i) + input = append(input, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_image", "image_url": shot}}}) + } + b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": input}) + return b +} + +// wideShots are n distinct PNGs wider than Codex sends, each made +// smaller once it is fitted: cheap to make, as a test needs. +func wideShots(t *testing.T, n int) []string { + t.Helper() + out := make([]string, n) + for i := range out { + m := image.NewRGBA(image.Rect(0, 0, 2100, 4)) + for x := 0; x < 2100; x++ { + m.SetRGBA(x, i%4, color.RGBA{byte(i), byte(i >> 8), byte(x), 255}) + } + out[i] = shotURL(t, m, "png") + } + return out +} + +// A long Computer Use conversation (fflake33, Discord: hundreds of +// screenshots) sends every past screenshot again on each turn. Each is +// decoded, resized and written again once; the next turn makes only its +// new one, past the 64 images the cache held, and sends the others as the +// same bytes as before, which the prompt cache needs. +func TestCodexScreenshotsAreNotFittedAgainEachTurn(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 101) + first := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:100])) + if n := made(); n != 100 { + t.Fatalf("the first turn made %d images, want 100", n) + } + next := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots)) + if n := made() - 100; n != 1 { + t.Errorf("the next turn made %d images again, want only its new one", n) + } + for i := range 100 { + path := fmt.Sprintf("input.%d.output.0.image_url", 2*i+1) + was, now := gjson.GetBytes(first, path).String(), gjson.GetBytes(next, path).String() + if was == shots[i] || now != was { + t.Fatalf("screenshot %d: not the same fitted bytes on the next turn", i) + } + } + m, _ := shotDecode(t, gjson.GetBytes(next, "input.201.output.0.image_url").String()) + if m.Bounds().Dx() != 2048 { + t.Errorf("the new screenshot went at %v", m.Bounds()) + } +} + +// Past what the cache may hold, each turn still finds the screenshots kept +// since the last and makes only the rest again. Keeping each image as it +// is made, in a conversation whose images come in the same order each +// turn, would drop each one just before it is sent again and find none. +// What is held stays within the budget. +func TestCodexFittedImagesPastTheBudget(t *testing.T) { + shots := wideShots(t, 30) + one := len(fitKeyEntry(t, shots[0]).data) + made := freshFitted(t, 10*one+one/2) + body := computerUseRequest(shots) + was := int64(0) + for turn := 1; turn <= 3; turn++ { + codexImagesFit(codexAccount(), provider.Responses, body) + n := made() - was + was += n + if turn == 1 && n != 30 || turn > 1 && n != 20 { + t.Errorf("turn %d made %d of 30 images, with 10 kept", turn, n) + } + fitted.Lock() + held := fitted.bytes + fitted.Unlock() + if held > fittedBudget { + t.Errorf("turn %d: %d bytes held, past the budget of %d", turn, held, fittedBudget) + } + } +} + +// fitKeyEntry is shot fitted to Codex's high limits, made directly. +func fitKeyEntry(t *testing.T, shot string) fitEntry { + t.Helper() + e := codexImageRefit(shot[strings.IndexByte(shot, ',')+1:], imageLimits{2048, 2500}) + if e.data == nil { + t.Fatal("the screenshot fits as it came") + } + return e +} + +// What no request has sent for fittedIdle is let go. +func TestCodexFittedImagesLetGoWhenIdle(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 2) + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:1])) + fitted.Lock() + for el := fitted.order.Front(); el != nil; el = el.Next() { + el.Value.(*fitItem).used = time.Now().Add(-fittedIdle - time.Minute) + } + fitted.Unlock() + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[1:])) + fitted.Lock() + n, held := len(fitted.m), fitted.bytes + fitted.Unlock() + if n != 1 || made() != 2 { + t.Errorf("%d kept after the first went idle, %d made", n, made()) + } + if want := len(fitKeyEntry(t, shots[1]).data); held != want { + t.Errorf("%d bytes held, want %d", held, want) + } +} diff --git a/internal/gateway/codex_images_timing_test.go b/internal/gateway/codex_images_timing_test.go new file mode 100644 index 000000000..1d08b5f62 --- /dev/null +++ b/internal/gateway/codex_images_timing_test.go @@ -0,0 +1,203 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "image" + "image/jpeg" + "io" + "math/rand/v2" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime/pprof" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// computerUseShots are n distinct w×h JPEG screenshots as data URLs: a +// desktop with noise along its top, so each is as large as a real one, +// and a stamp that makes each its own. +func computerUseShots(n, w, h int) []string { + base := shotImage(w, h) + noise := rand.New(rand.NewPCG(3, 4)) + for i := 0; i < 200*base.Stride; i++ { + if i%4 != 3 { + base.Pix[i] = byte(noise.Uint32()) + } + } + out := make([]string, n) + var wg sync.WaitGroup + sem := make(chan struct{}, 8) + for i := range n { + wg.Add(1) + sem <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-sem }() + m := image.NewRGBA(base.Rect) + copy(m.Pix, base.Pix) + for y := 300; y < 364; y++ { + for x := 0; x < 64; x++ { + o := y*m.Stride + (x+(i%40)*64)*4 + m.Pix[o], m.Pix[o+1], m.Pix[o+2] = byte(i), byte(i*7), byte(i*13) + } + } + var b bytes.Buffer + jpeg.Encode(&b, m, &jpeg.Options{Quality: 85}) + out[i] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b.Bytes()) + }() + } + wg.Wait() + return out +} + +// computerUseTurn is a long Computer Use conversation as Codex sends it on +// the Responses API: each step a user or assistant message, a tool call +// and the tool's output with its screenshot. +func computerUseTurn(model string, shots []string) []byte { + para := strings.Repeat("Clicked the button in the toolbar, waited for the sheet and read what it says. ", 30) + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%04d", i) + input = append(input, + map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": para}}}, + map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": para}}}, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_text", "text": "screenshot taken"}, + map[string]any{"type": "input_image", "image_url": shot}}}, + ) + } + input = append(input, map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "go on"}}}) + b, _ := json.Marshal(map[string]any{"model": model, "stream": true, "instructions": para, "input": input}) + return b +} + +// turnTimer stands in for an upstream that answers at once, and notes when +// each request reached it: the time from the agent's request to then is +// magpie's own work on it, the upload to a local server aside. +type turnTimer struct { + mu sync.Mutex + arrived time.Time +} + +func (tt *turnTimer) handler(w http.ResponseWriter, r *http.Request) { + tt.mu.Lock() + tt.arrived = time.Now() + tt.mu.Unlock() + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":7,"output_tokens":2}}}`)) +} + +// turn sends body to s and says how long magpie took before the upstream +// had it, and in all. Its CPU profile samples carry the label turn=name, +// for pprof's -tagfocus: on a loaded machine the time a turn's work took +// says more than how long it waited. +func (tt *turnTimer) turn(t *testing.T, s *Server, body []byte, name string) (local, all time.Duration) { + t.Helper() + start := time.Now() + rec := httptest.NewRecorder() + pprof.Do(context.Background(), pprof.Labels("turn", name), func(context.Context) { + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", bytes.NewReader(body))) + }) + all = time.Since(start) + if rec.Code != 200 { + t.Fatalf("status %d: %.300s", rec.Code, rec.Body.String()) + } + tt.mu.Lock() + defer tt.mu.Unlock() + return tt.arrived.Sub(start), all +} + +// TestComputerUseTurnTiming times magpie's own work on a long Computer +// Use turn to a ChatGPT account, as fflake33's (Discord): the first turn, +// and the next, which sends every past screenshot again. Run it with +// MAGPIE_TURN_TIMING=1 (and -cpuprofile/-memprofile to see where). +func TestComputerUseTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Computer Use turn") + } + codexSignedIn(t) + tt := &turnTimer{} + up := httptest.NewServer(http.HandlerFunc(tt.handler)) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + n := 160 + fmt.Sscan(os.Getenv("MAGPIE_TURN_SHOTS"), &n) + start := time.Now() + shots := computerUseShots(n+3, 2940, 1912) + t.Logf("%d screenshots made in %v", n+3, time.Since(start)) + s := New() + for turn := 1; turn <= 4; turn++ { + // each turn adds a screenshot to those sent before + body := computerUseTurn("codex/gpt-5.5", shots[:n+turn-1]) + local, all := tt.turn(t, s, body, fmt.Sprint(turn)) + t.Logf("turn %d: %d images, %d MB: magpie %v before the upstream had it, %v in all", turn, n+turn-1, len(body)>>20, local, all) + } +} + +// TestCopilotLongTurnTiming times magpie's own work on a long Codex turn +// with no images to a Copilot account (echo_ts, Discord). Run it with +// MAGPIE_TURN_TIMING=1. +func TestCopilotLongTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Copilot turn") + } + fresh(t) + cfg := os.Getenv("XDG_CONFIG_HOME") + os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755) + os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{ + "github.com:Iv1.x": map[string]any{"user": "echo", "oauth_token": "gho_timing"}, + }), 0o600) + tt := &turnTimer{} + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/models" { + io.WriteString(w, `{"data":[{"id":"gpt-6.1-sol","name":"GPT-6.1 Sol","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat","supports":{"reasoning_effort":["low","medium","high"]}}}]}`) + return + } + tt.handler(w, r) + })) + t.Cleanup(api.Close) + gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/token") { + json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}}) + return + } + io.WriteString(w, `{"copilot_plan":"individual","access_type_sku":"monthly_subscriber_quota"}`) + })) + t.Cleanup(gh.Close) + oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL + provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user" + t.Cleanup(func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }) + p, err := provider.Find("copilot") + if err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + s := New() + for _, words := range []int{2_000, 30_000, 150_000} { + body := largeConversation(provider.Responses, "copilot/gpt-6.1-sol", words) + for turn := 1; turn <= 3; turn++ { + local, all := tt.turn(t, s, body, fmt.Sprintf("%dk-%d", words/1000, turn)) + t.Logf("%d KB, turn %d: magpie %v before the upstream had it, %v in all", len(body)>>10, turn, local, all) + } + } +} diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index c3a4b8b53..cefc225d7 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "sync" "time" @@ -46,9 +47,11 @@ var visionTimeout, visionWaitMost = 3 * time.Minute, 10 * time.Minute // visionParallel is how many images of a request are described at once. const visionParallel = 4 -// sightsKept is how many descriptions are kept: an agent sends a -// conversation's images again every turn. -const sightsKept = 256 +// sightsKept is how many descriptions are kept, the least recently used +// dropped first: an agent sends a conversation's images again every turn, +// and a long Computer Use one holds hundreds of screenshots (fflake33). +// A description is a few kilobytes. +const sightsKept = 2048 const visionSystem = `You describe images for an AI model that cannot see them. It will answer the user from your description alone, so leave nothing out that it may need. - Transcribe all text exactly as written, keeping its layout: code, terminal output, error messages, logs, UI labels, menus, file names, numbers. @@ -292,6 +295,12 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error key := hex.EncodeToString(sum[:]) s.sightMu.Lock() if e, ok := s.sights[key]; ok { + // used again, so the last to go: a long conversation's first + // images, still sent every turn, outlast those of conversations + // that have ended + if i := slices.Index(s.sightOrder, key); i >= 0 { + s.sightOrder = append(append(s.sightOrder[:i:i], s.sightOrder[i+1:]...), key) + } s.sightMu.Unlock() select { case <-e.done: diff --git a/internal/gateway/vision_test.go b/internal/gateway/vision_test.go index 0f2a55490..427244f99 100644 --- a/internal/gateway/vision_test.go +++ b/internal/gateway/vision_test.go @@ -1,6 +1,8 @@ package gateway import ( + "encoding/base64" + "fmt" "io" "net/http" "net/http/httptest" @@ -211,3 +213,27 @@ func TestSeerPicksAModelThatSees(t *testing.T) { t.Fatal("seer with vision off") } } + +// A long conversation sends every past screenshot again on each turn +// (fflake33, Discord: hundreds of them). Each is described once, not again +// on the next turn once there are more than 256. +func TestManyImagesDescribedOnce(t *testing.T) { + s, u := eyed(t) + const n = 300 + var parts []string + for i := range n { + img := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("screenshot %d", i))) + parts = append(parts, `{"type":"input_image","image_url":"data:image/png;base64,`+img+`"}`) + } + body := `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},` + strings.Join(parts, ",") + `]}]}` + for turn := 1; turn <= 2; turn++ { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("turn %d: %d %.300s", turn, rec.Code, rec.Body.String()) + } + } + if got := len(u.sent("eye")); got != n { + t.Fatalf("%d images described %d times over two turns, want each once", n, got) + } +} From ec7f4743231517dbff3cfb458bf238b4bf17602f Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 00:33:24 +0800 Subject: [PATCH 03/92] gateway: Codex on Copilot is relayed with its web_search, and a translated call's arguments stream (echo_ts) echo_ts (magpie 0.1.1279, macOS): Codex on a GitHub Copilot subscription through magpie was about 10x slower than Copilot directly. Two causes, both in the gateway: - Codex offers web_search on every turn, and magpie counted Copilot as a provider that can't search, so every Codex turn on Copilot was translated for magpie's search instead of relayed. - On that translated path responsesDecoder held a call's argument deltas until the call was done, so Codex saw nothing while the model wrote a command or a patch, then all of it at once. A custom tool (apply_patch) got no custom_tool_call_input deltas at all. Fixes: - search.go: searchesItself counts a Copilot account on Responses. Real check on 2026-10-17 with the owner's account: gpt-5.3-codex, gpt-5.4-mini, gpt-6-luna, grok-4.7 and mai-code-1.1-flash each answered a request offering web_search with web_search_call items and cited pages. searchRank never picks Copilot to search for another provider's models (its premium requests). - gateway.go: a Copilot Responses request whose tools mark an argument "encrypted" (MultiAgentV2's spawn_agent message) is still translated, marks left out (asksSealing in responses.go). Checked on the real account: relayed, Copilot seals the message ("UlQC...", no encrypted_function_args), and the subagent's turn carrying it came back "Encrypted function output content could not be decrypted or decoded". This was already broken for a Copilot turn without web_search; it is fixed for that too. An unsealed agent_message relayed with web_search answers normally (checked). - responses.go: responsesDecoder gives argument deltas as they come. It holds only the deltas that make the arguments whole JSON, until the done events, so #613's case (deltas that disagree with done) still ends with the fuller arguments. The encoder sends a custom tool's input as custom_tool_call_input.delta, read out of the {"input": ...} arguments as they stream (customStream in custom_tool.go, which waits for cut escapes, surrogate pairs and UTF-8), and closes it with custom_tool_call_input.done. - docs/subsystems/gateway-routing.md says the above. Not changed: the HTTP/2 connection. Head-of-line blocking from large uploads on the one connection to Copilot was measured on the real account with a Go client: a 4MB request and a small one 300ms later, 5 rounds x 2, same connection vs a new one. The small request's first byte took 0.93-1.68s on the shared connection, 1.26-4.77s on its own (handshake included), 0.66-1.08s alone. No sign of blocking. Small requests slower while a long session runs (echo_ts, 42.8s vs 17-29s first text, xhigh): nothing in magpie serializes Copilot requests by default (lanes need MaxConcurrency, the RPM gate MaxRPM; Go's h2 windows are 1GB per connection, 4MB per stream). Measured: small requests beside a 412s xhigh stream (16,617 output tokens) were as fast as idle, via magpie 0.8-1.1s first text, direct 1.3-2.0s, sent_ms 1-10ms. One global lock found: copilotMu is held across the token refresh's HTTP call, which stalls every Copilot request only around a refresh, filed as #2762, not changed here. usage.jsonl's own_ms, queued_ms and sent_ms against ttft_ms tell magpie's time from Copilot's. Tests: - TestCallArgsStreamWhenTranslated (function and custom), through the real handler with an upstream that holds the rest of the call until the client has the first delta. - TestResponsesCallArgsStream, TestCustomInputStreams (pieces of 1, 2, 3, 5, 7 bytes and whole). - TestCopilotRelayedUnlessAskedToSeal; TestCopilotUltraSubagentWithWebSearch now expects the subagent relayed with the search. Broken by hand at this tree, each went red: - decoder holding every delta: TestCallArgsStreamWhenTranslated, TestResponsesCallArgsStream; - no custom input delta: TestCallArgsStreamWhenTranslated/custom; - Copilot out of searchesItself: TestCopilotRelayedUnlessAskedToSeal, TestCopilotUltraSubagentWithWebSearch; - the asksSealing check off: the same two. Real use: a built magpie serve in a sandbox HOME (port 3461) with the owner's Copilot account, Codex-shaped requests offering exec_command, apply_patch and web_search to copilot/gpt-5.3-codex: - unmarked: relayed (Copilot's own response ids), apply_patch gave 93 custom_tool_call_input deltas from 3.55s to 11.69s; - with a sealed spawn_agent: translated, apply_patch 117 deltas from 1.45s to 11.73s, exec_command 92 function_call_arguments deltas from 1.55s to 8.16s. Not tried with the Codex binary itself. Run at d783df46c plus this change (load 160-330 from other sessions): gofmt -l clean; go vet ./... for darwin, linux (-tags nogui) and windows ok; go test -timeout 45m ./...: 60 packages ok; internal/agent, internal/gateway and internal/library timed out at 45m (#2544/#2723, #2108, filed #2853), internal/gui's TestSetAnswersWhileDevinAndProvidersHang (#1375) and TestMainWindowCorners (#2645) red. Rerun alone: internal/library ok 1184s; the two gui tests ok; internal/gateway timed out at 45m again (load ~300), then at -timeout 3h ran 2887s with one red, TestClaudeAccountsSpentFallBackToCodex "stream=true: no answer" at its 30s wall wait (filed #2858; -count=3 alone ok). The tests above, after the rebase: ok. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/call_args_stream_test.go | 217 ++++++++++++++++++++++ internal/gateway/codex_ultra_test.go | 59 +++++- internal/gateway/custom_tool.go | 143 ++++++++++++++ internal/gateway/gateway.go | 8 + internal/gateway/responses.go | 172 +++++++++++++++-- internal/gateway/search.go | 14 +- 7 files changed, 585 insertions(+), 29 deletions(-) create mode 100644 internal/gateway/call_args_stream_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ccea32f78..90600cf95 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -172,6 +172,7 @@ recorded as a prediction failure (`noPrediction`). - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. - A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`. - A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (`customToolRefusal` in [`custom_tool.go`](../../internal/gateway/custom_tool.go): DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656) ends the relay: `passthrough` marks the model (`customToolRefused`) and returns not done, and `attempt` translates the request on the same API (`ownAPI`), where each custom tool is offered as a function taking its `input` and a call comes back as the `custom_tool_call` Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (`keepsCompaction`) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (`shapeRefused`): the next member is asked. `TestCustomToolTranslatedWhereRefused`, `TestCustomToolRefusalInGroup`, `TestCustomToolRefusalWordings`. +- A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`. - A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale. - A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`). diff --git a/internal/gateway/call_args_stream_test.go b/internal/gateway/call_args_stream_test.go new file mode 100644 index 000000000..e3da10263 --- /dev/null +++ b/internal/gateway/call_args_stream_test.go @@ -0,0 +1,217 @@ +package gateway + +import ( + "bufio" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// gatedCall is a Responses upstream that streams a call's first argument +// delta and then waits, before the rest of the call, until the test has +// seen that delta reach the client (or gives up). +type gatedCall struct { + name string // the function the upstream calls + first string // its first argument delta + rest string // the rest of its arguments + seen chan struct{} // closed by the test once the client has the first delta + wrote chan struct{} // closed by the upstream as it goes on to the rest +} + +func (g *gatedCall) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + f := w.(http.Flusher) + q := func(s string) string { b, _ := json.Marshal(s); return string(b) } + write := func(lines ...string) { + io.WriteString(w, sse(lines...)) + f.Flush() + } + write(`data: {"type":"response.created","response":{"id":"r1","model":"m"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":""}}`, + `data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.first)+`}`) + select { + case <-g.seen: + case <-time.After(20 * time.Second): + case <-r.Context().Done(): + return + } + close(g.wrote) + args := q(g.first + g.rest) + write(`data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":`+q(g.rest)+`}`, + `data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":`+args+`}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"`+g.name+`","arguments":`+args+`,"status":"completed"}}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":5}}}`) +} + +// A call's arguments reach Codex as the upstream writes them, on the +// translated path its web_search sends a request down (echo_ts on Discord: +// on Copilot, Codex saw nothing for the minutes the model wrote a patch or +// a command, then all of it at once). A function's arguments come as +// function_call_arguments deltas, a custom tool's input (apply_patch) as +// custom_tool_call_input deltas, each before the upstream's call is done; +// the finished items are what they were. +func TestCallArgsStreamWhenTranslated(t *testing.T) { + const patch = "*** Begin Patch\n*** Add File: a.go\n+package a\n+// \"quoted\" \\ é 😀\n*** End Patch\n" + whole, _ := json.Marshal(map[string]string{"input": patch}) + split := 24 // inside the patch: {"input":"*** Begin Pat + for _, c := range []struct { + name, fn string + first, rest string + delta string // the event the client is given the call's text by + wantFirst string // what that event's first delta says + wantItemType string + }{ + {"function", "exec_command", `{"cmd":"go test ./...",`, `"yield_time_ms":1000}`, + "response.function_call_arguments.delta", `{"cmd":"go test ./...",`, "function_call"}, + {"custom", "apply_patch", string(whole[:split]), string(whole[split:]), + "response.custom_tool_call_input.delta", patch[:split-len(`{"input":"`)], "custom_tool_call"}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &gatedCall{name: c.fn, first: c.first, rest: c.rest, seen: make(chan struct{}), wrote: make(chan struct{})} + vendor := httptest.NewServer(up) + t.Cleanup(vendor.Close) + if err := provider.Save(provider.Provider{ID: "rel", Name: "Rel", Key: "k", Responses: vendor.URL + "/v1", Models: []string{"m"}}); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(New().Handler()) + t.Cleanup(srv.Close) + body := `{"model":"rel/m","stream":true,"input":[{"role":"user","content":"add a.go"}], + "tools":[{"type":"function","name":"exec_command","description":"Runs a command.","strict":false, + "parameters":{"type":"object","properties":{"cmd":{"type":"string"},"yield_time_ms":{"type":"number"}},"required":["cmd"]}}, + {"type":"custom","name":"apply_patch","description":"Edits files.","format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}}, + {"type":"web_search"}],"tool_choice":"auto"}` + res, err := http.Post(srv.URL+"/v1/responses", "application/json", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 200 { + b, _ := io.ReadAll(res.Body) + t.Fatalf("%d %s", res.StatusCode, b) + } + var deltas []string + var done map[string]any + early := false + sc := bufio.NewScanner(res.Body) + sc.Buffer(make([]byte, 1<<20), 1<<20) + for sc.Scan() { + data, ok := strings.CutPrefix(sc.Text(), "data: ") + if !ok { + continue + } + var ev struct { + Type string `json:"type"` + Delta string `json:"delta"` + Item map[string]any `json:"item"` + } + if json.Unmarshal([]byte(data), &ev) != nil { + continue + } + switch { + case ev.Type == c.delta: + if len(deltas) == 0 { + select { + case <-up.wrote: + default: + early = true // the upstream is still holding the rest + } + close(up.seen) + } + deltas = append(deltas, ev.Delta) + case ev.Type == "response.output_item.done" && ev.Item["type"] == c.wantItemType: + done = ev.Item + case ev.Type == "response.output_item.done" && done == nil: + // another kind of item: what the call came back as + done = ev.Item + } + } + if !early { + t.Fatalf("no %s before the upstream's call was done: deltas %q", c.delta, deltas) + } + if deltas[0] != c.wantFirst { + t.Errorf("first delta %q, want %q", deltas[0], c.wantFirst) + } + if done == nil || done["type"] != c.wantItemType { + t.Fatalf("finished item %v", done) + } + if c.wantItemType == "custom_tool_call" { + if done["input"] != patch || strings.Join(deltas, "") != patch { + t.Errorf("input %q, deltas %q, want %q", done["input"], strings.Join(deltas, ""), patch) + } + } else if done["arguments"] != c.first+c.rest || strings.Join(deltas, "") != c.first+c.rest { + t.Errorf("arguments %q, deltas %q", done["arguments"], strings.Join(deltas, "")) + } + }) + } +} + +// A custom tool's input read out of its arguments a piece at a time is +// the input the whole arguments hold, wherever the pieces are cut: in an +// escape, between a surrogate pair's halves, inside a character. +func TestCustomInputStreams(t *testing.T) { + patch := "*** Begin Patch\n+\"q\" \\ é 😀 &\t\n*** End Patch\n" + marshalled, _ := json.Marshal(map[string]string{"input": patch}) + for _, c := range []struct{ args, want string }{ + {string(marshalled), patch}, + {`{"input":"\ud83d\ude00 \u00e9\u0041\/\n"}`, "😀 éA/\n"}, + {`{"path":"a.go","input":"x\"y"}`, `x"y`}, + {`{"meta":{"input":"no","list":["input"]},"input":"yes"}`, "yes"}, + {`{ "input" : "spaced" }`, "spaced"}, + {`"a lone string"`, "a lone string"}, + {`{"input":"lone \ud83d half"}`, "lone \ufffd half"}, + {`{"input":5}`, ""}, + {`{"other":"x"}`, ""}, + {`not json`, ""}, + } { + for _, size := range []int{1, 2, 3, 5, 7, len(c.args)} { + var s customStream + var got strings.Builder + for i := 0; i < len(c.args); i += size { + got.WriteString(s.feed(c.args[i:min(i+size, len(c.args))])) + } + if got.String() != c.want { + t.Errorf("%s in pieces of %d: %q, want %q", c.args, size, got.String(), c.want) + } + if c.want != "" && customInput(c.args) != c.want { + t.Errorf("%s: customInput %q", c.args, customInput(c.args)) + } + } + } +} + +// A Responses upstream's argument deltas are given as they come, except +// those that make the arguments whole JSON, which wait for the call's done +// events: what was given and what follows add up to the fuller arguments. +func TestResponsesCallArgsStream(t *testing.T) { + var d responsesDecoder + var got []string + emit := func(ev Event) { + if ev.Kind == KToolArgs { + got = append(got, ev.Text) + } + } + d.decode(`{"type":"response.output_item.added","item":{"type":"function_call","call_id":"c1","name":"f"}}`, emit) + for _, x := range []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`} { + q, _ := json.Marshal(x) + d.decode(`{"type":"response.function_call_arguments.delta","delta":`+string(q)+`}`, emit) + } + if want := []string{`{"cmd":"a}`, `\"]{",`, `"n":[1,{}]`}; strings.Join(got, "|") != strings.Join(want, "|") { + t.Fatalf("before the end %q, want %q", got, want) + } + d.decode(`{"type":"response.function_call_arguments.delta","delta":"}"}`, emit) + if len(got) != 3 { + t.Fatalf("the delta that makes it whole was given before the call's done: %q", got) + } + d.decode(`{"type":"response.output_item.done","item":{"type":"function_call","call_id":"c1","name":"f","arguments":"{\"cmd\":\"a}\\\"]{\",\"n\":[1,{}],\"more\":true}"}}`, emit) + if all := strings.Join(got, ""); all != `{"cmd":"a}\"]{","n":[1,{}],"more":true}` { + t.Fatalf("arguments %s", all) + } +} diff --git a/internal/gateway/codex_ultra_test.go b/internal/gateway/codex_ultra_test.go index b6e13dbc2..787f57e2f 100644 --- a/internal/gateway/codex_ultra_test.go +++ b/internal/gateway/codex_ultra_test.go @@ -177,12 +177,13 @@ func TestCopilotSolOffersUltra(t *testing.T) { } } -// Ultra's subagents with Codex's web_search kept (#656): a request offering -// the search is made again for Copilot rather than relayed, and on that -// path a Copilot lead's spawn_agent comes back to Codex unsealed, with the -// task as written (Copilot not asked to seal it), and the subagent's -// request — the task as MultiAgentV2's agent_message — reaches Copilot as -// the task's text. +// Ultra's subagents with Codex's web_search kept (#656): a lead whose +// spawn_agent marks its message "encrypted" is made again for Copilot +// rather than relayed, as Copilot can't open what it seals, and on that +// path its spawn_agent comes back to Codex unsealed, with the task as +// written (Copilot not asked to seal it). The subagent's request, which +// marks nothing, is relayed with the search (Copilot runs web_search +// itself), the task as MultiAgentV2's agent_message as Codex sent it. func TestCopilotUltraSubagentWithWebSearch(t *testing.T) { c := copilotSol(t) s := New() @@ -240,10 +241,52 @@ func TestCopilotUltraSubagentWithWebSearch(t *testing.T) { if code != 200 { t.Fatalf("subagent: %d %s", code, out) } - sent, _ := json.Marshal(c.last(t)["input"]) - if !strings.Contains(string(sent), task) || strings.Contains(string(sent), "encrypted_content") { + sub := c.last(t) + sent, _ := json.Marshal(sub["input"]) + if !strings.Contains(string(sent), task) || !strings.Contains(string(sent), `"agent_message"`) || strings.Contains(string(sent), "encrypted_content") { t.Fatalf("subagent's input to Copilot: %s", sent) } + if offered, _ := json.Marshal(sub["tools"]); string(offered) != `[{"type":"web_search"}]` { + t.Fatalf("subagent's tools to Copilot: %s", offered) + } +} + +// A Codex turn on Copilot offering web_search is relayed as Codex sent it, +// as Copilot runs the search itself (echo_ts on Discord: translated for +// magpie's search, every turn lost the relay); one whose tools mark an +// argument "encrypted" is made again unmarked, with the search or without, +// since Copilot seals that argument and can't open it on the next turn. +func TestCopilotRelayedUnlessAskedToSeal(t *testing.T) { + c := copilotSol(t) + s := New() + spawn := `{"type":"namespace","name":"collaboration","description":"Sub-agents.","tools":[ + {"type":"function","name":"spawn_agent","strict":false,"description":"Spawns an agent.", + "parameters":{"type":"object","properties":{"message":{"type":"string","encrypted":true}},"required":["message"]}}]}` + exec := `{"type":"function","name":"exec_command","description":"Runs a command, \"encrypted\" or not.","strict":false, + "parameters":{"type":"object","properties":{"cmd":{"type":"string"},"encrypted":{"type":"boolean"}},"required":["cmd"]}}` + for _, tc := range []struct { + name, tools string + relayed bool + }{ + {"search", exec + `,{"type":"web_search"}`, true}, + {"search and a sealed argument", spawn + `,` + exec + `,{"type":"web_search"}`, false}, + {"a sealed argument alone", spawn, false}, + } { + code, out := postTo(t, s, "/v1/responses", `{"model":"copilot/gpt-6-luna","stream":true,"input":[{"role":"user","content":"hi"}],"probe":"as sent","tools":[`+tc.tools+`]}`) + if code != 200 { + t.Fatalf("%s: %d %s", tc.name, code, out) + } + // a field magpie doesn't know goes on only as Codex sent it + body := c.last(t) + sent, _ := json.Marshal(body["tools"]) + relayed := body["probe"] == "as sent" + if relayed != tc.relayed { + t.Errorf("%s: relayed %v, tools to Copilot %s", tc.name, relayed, sent) + } + if !tc.relayed && strings.Contains(string(sent), `"encrypted":true`) { + t.Errorf("%s: Copilot was asked to seal: %s", tc.name, sent) + } + } } // Ultra is Codex's, no API's: a model whose list says "ultra" (ChatGPT's diff --git a/internal/gateway/custom_tool.go b/internal/gateway/custom_tool.go index da54f83a6..715395018 100644 --- a/internal/gateway/custom_tool.go +++ b/internal/gateway/custom_tool.go @@ -4,6 +4,8 @@ import ( "bytes" "encoding/json" "regexp" + "strconv" + "unicode/utf8" ) // Codex offers custom tools on Responses (exec in code mode, apply_patch): @@ -64,3 +66,144 @@ func customIn(v any) bool { } return false } + +// customStream gives a custom tool's input as its call's arguments come, +// a piece at a time: the text of the input string in {"input":"…"} (or of +// a lone JSON string), unescaped, as the custom_tool_call_input deltas a +// client reads while the model writes a patch. What can't be read yet (an +// escape or a character cut off) waits for the next piece. The finished +// item's input is still customInput's of the whole arguments; arguments +// of another shape stream nothing. +type customStream struct { + pend []byte // of the input string, read and not given yet + depth int + str bool // in a string that isn't the input + esc bool // after its backslash + key []byte // the depth-1 key being read, raw + inKey bool // the string being read is that key + want bool // a key is next, at depth 1 + last string // the last depth-1 key + value bool // the depth-1 value next is the input's + in bool // in the input string + over bool // the input is given, or there is none +} + +// feed reads the next piece of the arguments and gives what it adds to +// the input. +func (c *customStream) feed(s string) string { + if c.over { + return "" + } + if c.in { + c.pend = append(c.pend, s...) + return c.take() + } + for i := 0; i < len(s); i++ { + b := s[i] + switch { + case c.str: + if c.inKey { + c.key = append(c.key, b) + } + switch { + case c.esc: + c.esc = false + case b == '\\': + c.esc = true + case b == '"': + c.str = false + if c.inKey { + c.inKey = false + c.last = "" + json.Unmarshal(append([]byte{'"'}, c.key...), &c.last) + } + } + case b == '"' && (c.depth == 0 || c.depth == 1 && c.value): + c.in = true + c.pend = append(c.pend, s[i+1:]...) + return c.take() + case b == '"': + c.str = true + if c.depth == 1 && c.want { + c.inKey, c.key, c.want = true, c.key[:0], false + } + case b == '{' || b == '[': + c.depth++ + if c.depth == 1 && b == '{' { + c.want = true + } + case b == '}' || b == ']': + if c.depth--; c.depth <= 0 { + c.over = true + return "" + } + case b == ':' && c.depth == 1: + c.value = c.last == "input" + case b == ',' && c.depth == 1: + c.want, c.value = true, false + case b == ' ' || b == '\t' || b == '\n' || b == '\r': + case c.depth == 0: + c.over = true // not JSON this reads + return "" + case c.depth == 1: + c.value = false // the input isn't a string + } + } + return "" +} + +// take unescapes what can be read of the input string so far, up to its +// closing quote. +func (c *customStream) take() string { + n, end := 0, false +scan: + for n < len(c.pend) { + switch c.pend[n] { + case '"': + end = true + break scan + case '\\': + switch { + case n+1 >= len(c.pend): + break scan + case c.pend[n+1] != 'u': + n += 2 + case n+6 > len(c.pend): + break scan + case !highSurrogate(c.pend[n+2 : n+6]): + n += 6 + case n+8 > len(c.pend): + break scan + case c.pend[n+6] != '\\' || c.pend[n+7] != 'u': + n += 6 // a lone half, read as JSON reads it + case n+12 > len(c.pend): + break scan // the low half is cut off + default: + n += 12 + } + default: + n++ + } + } + // a character cut off waits too + for k := 0; k < utf8.UTFMax-1 && n > 0 && !end && !utf8.Valid(c.pend[:n]); k++ { + n-- + } + var text string + if json.Unmarshal(append(append([]byte{'"'}, c.pend[:n]...), '"'), &text) != nil { + c.over = true // not a string JSON reads: the finished item says it + return "" + } + c.pend = c.pend[n:] + if end { + c.over, c.pend = true, nil + } + return text +} + +// highSurrogate is whether the four hex digits of a \u escape are the +// first half of a pair. +func highSurrogate(hex []byte) bool { + r, err := strconv.ParseUint(string(hex), 16, 16) + return err == nil && r >= 0xD800 && r < 0xDC00 +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b389f5abe..30b879463 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3540,6 +3540,14 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P if relay && searchAsked(from, body) && (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && !(from == provider.Responses && hasSealedAgentMessage(body)) { relay, ownAPI = false, true } + // Copilot seals an argument the tools mark "encrypted" (spawn_agent's + // message, MultiAgentV2) and then can't open what it sealed: the + // subagent's turn came back "Encrypted function output content could + // not be decrypted or decoded" (2026-10-17, a real account). Translated, + // the marks are left out and the call goes back to Codex unsealed. + if relay && from == provider.Responses && p.Account != nil && p.Account.Agent == "copilot" && asksSealing(body) { + relay, ownAPI = false, true + } // Zen's free models are asked as OpenCode asks them (zenfree.go) if p.OpenCodeFree(model) { relay = false diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index 7419263f2..fe494c915 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -196,6 +196,62 @@ func unsealed(schema json.RawMessage) json.RawMessage { return out } +// asksSealing is a Responses request whose tools mark a parameter +// "encrypted" (MultiAgentV2's spawn_agent message): an upstream that +// honours the mark answers the call with that argument sealed. +func asksSealing(body []byte) bool { + if !bytes.Contains(body, []byte(`"encrypted"`)) { + return false + } + var q struct { + Tools []struct { + Parameters json.RawMessage `json:"parameters"` + Tools []struct { + Parameters json.RawMessage `json:"parameters"` + } `json:"tools"` + } `json:"tools"` + } + if decodeJSON(body, &q) != nil { + return false + } + var mark func(any) bool + mark = func(v any) bool { + switch x := v.(type) { + case map[string]any: + if b, ok := x["encrypted"].(bool); ok && b { + return true + } + for _, c := range x { + if mark(c) { + return true + } + } + case []any: + for _, c := range x { + if mark(c) { + return true + } + } + } + return false + } + marked := func(schema json.RawMessage) bool { + var v any + return bytes.Contains(schema, []byte(`"encrypted"`)) && decodeJSON(schema, &v) == nil && mark(v) + } + for _, t := range q.Tools { + if marked(t.Parameters) { + return true + } + for _, nt := range t.Tools { + if marked(nt.Parameters) { + return true + } + } + } + return false +} + func flatName(namespace, name string) string { return provider.FlatName(namespace, name) } @@ -1270,32 +1326,95 @@ func (u Usage) responses() map[string]any { // responsesDecoder turns a Responses stream into events. // -// A function call's arguments are given once the call is done, not as -// their deltas come: the deltas can leave out what the finished call holds -// (#613: Codex's spawn_agent came back with arguments {} where the request -// was translated, though the upstream's finished call had them), and what -// was sent of a call's arguments can't be taken back. +// A function call's arguments are given as their deltas come: a model +// writing a patch or a command for minutes is seen writing it (echo_ts on +// Discord: Codex on Copilot, translated for its web_search, saw nothing +// until the call was done). The deltas can leave out what the finished +// call holds (#613: Codex's spawn_agent came back with arguments {} where +// the request was translated, though the upstream's finished call had +// them), and what was sent of a call's arguments can't be taken back. So +// the deltas that would make the arguments whole JSON wait for the call's +// done events (jsonWhole), and the call is given what they add to it. type responsesDecoder struct { started bool called bool // a function call was streamed calling bool // a function call is open - args strings.Builder // the open call's argument deltas + sent strings.Builder // the open call's argument deltas given so far + held string // its deltas since they made whole JSON, not given yet + whole jsonWhole // where its deltas stand in their JSON full string // the open call's arguments as its done events give them } -// endCall gives the open call's arguments: the deltas, or what its done -// events give where that holds more. +// argsDelta gives an open call's argument delta, or holds it when with +// it the deltas are whole JSON, which the done events may yet replace. +func (d *responsesDecoder) argsDelta(delta string, emit func(Event)) { + if d.whole.feed(delta) { + d.held += delta + return + } + text := d.held + delta + d.held = "" + d.sent.WriteString(text) + if text != "" { + emit(Event{Kind: KToolArgs, Text: text}) + } +} + +// endCall gives the rest of the open call's arguments: what was held, or +// what its done events give past what was sent where they hold more. func (d *responsesDecoder) endCall(emit func(Event)) { if !d.calling { return } d.calling = false - args := pickArgs(d.args.String(), d.full) - d.args.Reset() - d.full = "" - if args != "" { - emit(Event{Kind: KToolArgs, Text: args}) + sent := d.sent.String() + rest := d.held + if args := pickArgs(sent+d.held, d.full); strings.HasPrefix(args, sent) { + rest = args[len(sent):] } + d.sent.Reset() + d.held, d.full, d.whole = "", "", jsonWhole{} + if rest != "" { + emit(Event{Kind: KToolArgs, Text: rest}) + } +} + +// jsonWhole follows a stream of JSON text, a piece at a time, for whether +// what came so far is a whole object or array. +type jsonWhole struct { + depth int + str, esc bool + began bool +} + +// feed reads the next piece and says whether the text is whole after it. +func (j *jsonWhole) feed(s string) bool { + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case j.esc: + j.esc = false + case j.str: + if c == '\\' { + j.esc = true + } else if c == '"' { + j.str = false + } + case c == '"': + j.str = true + if j.depth == 0 { + j.began = false + } + case c == '{' || c == '[': + j.depth++ + j.began = true + case c == '}' || c == ']': + j.depth-- + case c != ' ' && c != '\t' && c != '\n' && c != '\r' && j.depth == 0: + j.began = false // a value that isn't one, or after one + } + } + return j.began && j.depth == 0 && !j.str } // pickArgs is the fuller of a call's arguments as streamed and as its done @@ -1369,7 +1488,7 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error { emit(Event{Kind: KThink, Text: ev.Delta}) case "response.function_call_arguments.delta": if d.calling { - d.args.WriteString(ev.Delta) + d.argsDelta(ev.Delta, emit) } else { emit(Event{Kind: KToolArgs, Text: ev.Delta}) } @@ -1502,6 +1621,9 @@ type responsesEncoder struct { // collector's last part isn't it once a hidden thinking block (signed // with no text, or redacted) has come after the call (#1786) call Part + // input reads a custom tool's input out of its call's arguments as + // they come + input customStream // a message's output_item.done, and the events after it, wait here // until its phase is known (phase.go, #2437) heldMsg map[string]any @@ -1661,10 +1783,15 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) { args = "{}" } p := e.call - if q := e.named[p.Name]; !q.Search && !q.Custom { + item = callTo(map[string]any{"id": e.itemID, "type": "function_call", "status": "completed", "call_id": p.ID, "arguments": args}, p.Name, e.named) + switch q := e.named[p.Name]; { + case q.Custom: + // as OpenAI ends a custom tool's input deltas + input, _ := item.(map[string]any)["input"].(string) + e.send("response.custom_tool_call_input.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "input": input}) + case !q.Search: e.send("response.function_call_arguments.done", callTo(map[string]any{"item_id": e.itemID, "output_index": e.item, "call_id": p.ID, "arguments": args}, p.Name, e.named)) } - item = callTo(map[string]any{"id": e.itemID, "type": "function_call", "status": "completed", "call_id": p.ID, "arguments": args}, p.Name, e.named) } e.send("response.output_item.done", map[string]any{"output_index": e.item, "item": item}) e.output = append(e.output, item) @@ -1759,14 +1886,21 @@ func (e *responsesEncoder) event(ev Event) { item := callTo(map[string]any{"type": "function_call", "call_id": ev.ID, "arguments": ""}, ev.Name, e.named) e.openItem(ToolCall, itemPrefix(item), item) e.call = Part{Kind: ToolCall, ID: ev.ID, Name: ev.Name} + e.input = customStream{} e.col.add(ev) return case KToolArgs: if e.open == ToolCall && ev.Text != "" { e.text.WriteString(ev.Text) - // a custom tool's input is whole only once its arguments are: - // it goes in the item when that is done - if !e.named[e.call.Name].Custom { + switch q := e.named[e.call.Name]; { + case q.Custom: + // a custom tool's input, as it is read out of the + // arguments: what the model writes of a patch is seen as + // it writes it, as from OpenAI + if in := e.input.feed(ev.Text); in != "" { + e.send("response.custom_tool_call_input.delta", map[string]any{"item_id": e.itemID, "output_index": e.item, "delta": in}) + } + default: e.send("response.function_call_arguments.delta", map[string]any{"item_id": e.itemID, "output_index": e.item, "delta": ev.Text}) } } diff --git a/internal/gateway/search.go b/internal/gateway/search.go index 666646aa5..c5c53389e 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -105,8 +105,14 @@ func searchesItself(p provider.Provider, proto provider.Protocol) bool { saidTo := p.Searches && (proto == provider.Anthropic || proto == provider.Responses) && p.Base(proto) != "" if p.Account != nil { // Grok by its id: moved to its plugin, its account is the plugin's; - // its plugin beside the built-in (grok-plugin) by the plugin's id - return (p.Account.Agent == "codex" || p.ID == "grok" || p.PluginProvider() == "grok") && proto == provider.Responses || + // its plugin beside the built-in (grok-plugin) by the plugin's id. + // Copilot's /responses runs web_search itself for every model it + // serves there: gpt-5.3-codex, gpt-5.4-mini, gpt-6-luna, grok-4.7 + // and mai-code-1.1-flash each answered a request offering it with + // web_search_call items and cited pages (2026-10-17, a real + // account). Translated for magpie's search instead, Codex's every + // turn on Copilot lost the relay (echo_ts on Discord). + return (p.Account.Agent == "codex" || p.Account.Agent == "copilot" || p.ID == "grok" || p.PluginProvider() == "grok") && proto == provider.Responses || p.IsPlugin() && saidTo } if saidTo { @@ -242,6 +248,10 @@ func searchRank(p provider.Provider) int { return 0 case p.Account != nil && p.Account.Agent == "codex": return 1 + case p.Account != nil && p.Account.Agent == "copilot": + // it searches for its own models only: another's searches would + // spend its premium requests, which no one asked for + return -1 case searchesItself(p, provider.Anthropic): return 2 case searchesItself(p, provider.Responses): From 95ef45fda4b3978e94f12954a27d41e5ef1dca85 Mon Sep 17 00:00:00 2001 From: ggbdpq Date: Sun, 18 Oct 2026 21:10:32 +0800 Subject: [PATCH 04/92] agent: a curl-installed opencode's update passes the version its row promised, so it never asks GitHub's API (#2837, ggbdpq) What changed: an opencode 1.19.0 that its own installer put at ~/.opencode/bin/opencode (method curl) asks GitHub's API GET /repos/anomalyco/opencode/releases/latest for the newest release before installing. That request carries no token, so it spends the 60 an hour GitHub answers an address without one. Once those are spent the answer is a 403 and the update stops before its installer runs (ggbdpq: "opencode upgrade: ... 403 GET https://api.github.com/repos/anomalyco/opencode/releases/latest"). cliSpec gains target, for a CLI whose own updater takes the version to install, and opencode sets it. When opencode's own updater is what runs (via "self"), UpdateCLI appends the version it already knows, the row's Latest from npm's opencode-ai, if that is newer than the installed one. The run is then "opencode upgrade 1.19.3". In opencode's source (packages/cli/src/commands/handlers/upgrade.ts) a given target skips latest(), and the curl method passes it to the installer as --version. A stale npm answer appends nothing (Newer), so an update can never become a downgrade. When the lookup fails, the command stays "opencode upgrade". Changed in review: the patch as sent appended the version for every install method. An opencode installed by npm, bun, pnpm or brew then ran `npm install -g --prefix P opencode-ai@latest 1.19.3`, which also asks npm to install a package named "1.19.3", or `brew upgrade opencode 1.19.3`. The append is now limited to via "self". TestUpdateCLIOpenCodeByNpmTakesNoVersion (npm prefix install) guards it. The target comment no longer says 1.19.3 asks npm: opencode's current source asks opencode.ai. Run: - Breaks: without the via guard (the patch as sent), TestUpdateCLIOpenCodeByNpmTakesNoVersion fails with "ran [[.../npm install -g --prefix ... opencode-ai@latest 1.19.3]]". Without the target block, TestUpdateCLIOpenCodeTakesVersion fails at cliupdate_test.go:411 with `ran [[".../bin/opencode" "upgrade"]]`. Both pass restored. - gofmt -l clean; go vet darwin, linux (nogui) and windows ok; go build for all three ok. - Full `go test -tags nogui -timeout 45m ./...` on origin/main d783df46c + this: every package ok except internal/agent and internal/gateway, which hit 45m mid-test under a load average of about 200, and internal/gui's TestSetAnswersWhileDevinAndProvidersHang (10.8s, filed as #1375, output added there). Rerun of agent, gateway and gui with -timeout 120m: all three ok (4061s, 3393s, 564s). After the comment-only edit, `go test ./internal/agent -run TestUpdateCLI` passed again. Not tried: a real opencode 1.19.0 update against GitHub's rate limit. Co-authored-by: yetone --- internal/agent/cliupdate.go | 21 ++++++- internal/agent/cliupdate_test.go | 94 ++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 1 deletion(-) diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index ffbd1ef21..dcebb7e47 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -82,6 +82,17 @@ type cliSpec struct { // latest is the newest version its own updater would install, for one // not published on npm latest func() string + // target: its own updater takes the version to install (opencode + // upgrade 1.19.3), so magpie gives it the one it already knows, as the + // row promised, when that updater is what runs (via "self"): npm's, + // bun's, pnpm's and brew's commands take no version after them. An opencode 1.19.0 from its own installer (method curl) + // asks GitHub's API for the newest release, which answers an address 60 + // times an hour without a token and 403s once that is spent; opencode's + // current source asks opencode.ai instead, but only an update gets + // there (#2837, ggbdpq: + // "opencode upgrade: ... 403 GET https://api.github.com/repos/ + // anomalyco/opencode/releases/latest") + target bool // only are the systems (GOOS) its vendor builds it for, when not all: // on any other its package installs nothing that runs only []string @@ -121,7 +132,7 @@ var cliSpecs = map[string]cliSpec{ } return nil }}, - "opencode": {npm: []string{"opencode-ai"}, brew: []string{"opencode"}, + "opencode": {npm: []string{"opencode-ai"}, brew: []string{"opencode"}, target: true, self: func(bin, real string) []string { if strings.Contains(real, "/.opencode/bin/") { return []string{bin, "upgrade"} @@ -948,6 +959,14 @@ func (a *Agent) UpdateCLI() (CLI, error) { } defer updating.Delete(a.ID) before := installedVersion(real) + if spec.target && u.via == "self" { + // the version the row promised, so its own updater needn't ask + // GitHub's API for the newest (see cliSpec.target); npm, bun, + // pnpm and brew take no version after their command + if v := latestVersion(u); Newer(v, before) { + u.cmd = append(u.cmd, v) + } + } ctx, cancel := context.WithTimeout(context.Background(), updateTimeout) defer cancel() run := runUpdate diff --git a/internal/agent/cliupdate_test.go b/internal/agent/cliupdate_test.go index cf97ef9db..b29cea6f3 100644 --- a/internal/agent/cliupdate_test.go +++ b/internal/agent/cliupdate_test.go @@ -365,6 +365,100 @@ func TestUpdateCLI(t *testing.T) { } } +// An opencode 1.19.0's upgrade asks GitHub's API for the newest release, +// which answers an address 60 times an hour without a token before a 403 +// (ggbdpq: "opencode upgrade: ... 403 GET https://api.github.com/repos/ +// anomalyco/opencode/releases/latest"). magpie gives it the version the row +// promised, which its installer downloads from the release itself. +func TestUpdateCLIOpenCodeTakesVersion(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script as the CLI") + } + tmp, _ := filepath.EvalSymlinks(t.TempDir()) + verFile := filepath.Join(tmp, "version") + os.WriteFile(verFile, []byte("1.19.2\n"), 0o644) + oc := file(t, filepath.Join(tmp, "home/.opencode/bin/opencode"), "#!/bin/sh\n/bin/cat "+verFile+"\n") + bin := link(t, oc, filepath.Join(tmp, "bin/opencode")) + t.Setenv("PATH", filepath.Dir(bin)) + + reg := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/opencode-ai/latest" { + http.NotFound(w, r) + return + } + w.Write([]byte(`{"name":"opencode-ai","version":"1.19.3"}`)) + })) + defer reg.Close() + oldReg, oldRun := npmRegistry, runUpdate + npmRegistry = reg.URL + "/" + versions, latests = memo{}, memo{} + var ran [][]string + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + ran = append(ran, u.cmd) + os.WriteFile(verFile, []byte("1.19.3\n"), 0o644) + return nil, nil + } + t.Cleanup(func() { npmRegistry, runUpdate = oldReg, oldRun; versions, latests = memo{}, memo{} }) + + a := &Agent{ID: "opencode", Name: "OpenCode", Bin: "opencode"} + if c, ok := a.CLI(); !ok || c.Via != "self" || c.Version != "1.19.2" || c.Latest != "1.19.3" || !c.Update { + t.Fatalf("before: %+v", c) + } + if c, err := a.UpdateCLI(); err != nil || c.Version != "1.19.3" || c.Update { + t.Fatalf("after: %+v, %v", c, err) + } + if len(ran) != 1 || !reflect.DeepEqual(ran[0], []string{bin, "upgrade", "1.19.3"}) { + t.Errorf("ran %q", ran) + } +} + +// An opencode npm installed is updated by npm as it was: the version +// opencode's own upgrade takes is never put after npm's install, where npm +// would read it as one more package to install. +func TestUpdateCLIOpenCodeByNpmTakesNoVersion(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script as the CLI") + } + tmp, _ := filepath.EvalSymlinks(t.TempDir()) + prefix := filepath.Join(tmp, "node") + verFile := filepath.Join(tmp, "version") + os.WriteFile(verFile, []byte("1.19.2\n"), 0o644) + file(t, filepath.Join(prefix, "lib/node_modules/opencode-ai/bin/opencode"), "#!/bin/sh\n/bin/cat "+verFile+"\n") + file(t, filepath.Join(prefix, "bin/npm"), "#!/bin/sh\nexit 1\n") + link(t, "../lib/node_modules/opencode-ai/bin/opencode", filepath.Join(prefix, "bin/opencode")) + t.Setenv("PATH", filepath.Join(prefix, "bin")) + + reg := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/opencode-ai/latest" { + http.NotFound(w, r) + return + } + w.Write([]byte(`{"name":"opencode-ai","version":"1.19.3"}`)) + })) + defer reg.Close() + oldReg, oldRun := npmRegistry, runUpdate + npmRegistry = reg.URL + "/" + versions, latests = memo{}, memo{} + var ran [][]string + runUpdate = func(_ context.Context, u *updater) ([]byte, error) { + ran = append(ran, u.cmd) + os.WriteFile(verFile, []byte("1.19.3\n"), 0o644) + return nil, nil + } + t.Cleanup(func() { npmRegistry, runUpdate = oldReg, oldRun; versions, latests = memo{}, memo{} }) + + a := &Agent{ID: "opencode", Name: "OpenCode", Bin: "opencode"} + if c, ok := a.CLI(); !ok || c.Via != "npm" || c.Latest != "1.19.3" || !c.Update { + t.Fatalf("before: %+v", c) + } + if _, err := a.UpdateCLI(); err != nil { + t.Fatal(err) + } + if len(ran) != 1 || !strings.HasSuffix(strings.Join(ran[0], " "), "install -g --prefix "+prefix+" opencode-ai@latest") { + t.Errorf("ran %q", ran) + } +} + // An agent's CLI installed with bun is updated by bun add -g, which can't // use a SOCKS5 proxy (#1409): it is given the bridge in front of it. npm, // which can, is given the proxy as it is. From cc8e8e3bda7e8169978eb23eb237f11388883b4e Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 02:42:18 +0800 Subject: [PATCH 05/92] provider: moved Grok users get plugin 0.1.16, which keeps a sign-in with no email (llllleo9 on X) llllleo9 couldn't add Grok: grok login --device-auth exited 0, and the sign-in failed with "grok login finished without an account". Grok Build 1.0.62 was run in a sandbox against a stand-in auth.x.ai. When the id_token has no email claim (an account signed in through X), the CLI writes "email": null, and plugin 0.1.15 refused a sign-in made beside an already signed-in Grok Build. With GROK_AUTH_PATH set, the CLI kept the sign-in elsewhere. Plugin 0.1.16 (magpie-community/plugins 8cdf2d2) fixes both: - the account is told by its email, else its xAI user id, else the token's sub; - GROK_AUTH_PATH is left out of the login; - a login that leaves nothing says which file it read and what was there. npm view @magpie-community/opencode-grok-auth@0.1.16 --prefer-online shows 0.1.16, which is latest, and its integrity matches the publish run's. This commit raises the mover's min to 0.1.16, so keepMovedCurrent updates moved users. The built-in's own Grok sign-in (runCLISignIn) has no caller left, so the built-in is unchanged. Run at this change, on origin/main ccb2eea15 plus this diff, macOS: - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and go build: clean. - go test ./... -timeout 45m: internal/provider ok (1205s), internal/plugin ok (1244s), and 60 packages ok. - Four packages were red with the machine at load average 195-235, while six other sessions ran benchmarks: - internal/agent timed out at 45m in TestCodexAgentsV1WarnsWhenCodexOwnV2IsOn; - internal/gateway timed out at 45m in TestPluginStreamLargeReplies (#2551); - internal/library timed out at 45m in TestSkillHow; - internal/gui failed TestSetAnswersWhileDevinAndProvidersHang (15.7s, #1375). None of the four reads the mover's min. - A rerun of those four, at load average 420, had not finished a package after 30 minutes. It isn't a record of green. - go test -count=1 -run 'Moved|Mover|Grok' ./internal/provider: ok. Not tried with a real xAI account: whether xAI's token for llllleo9's account lacks the email claim, and whether their Grok Build was already signed in. --- internal/provider/migrate_side.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index 61c0055fb..e0f3d61d1 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -97,7 +97,7 @@ func init() { // names, as the built-in does: the homes stay where they are. movers["grok"] = &mover{ pkg: "@magpie-community/opencode-grok-auth", - min: "0.1.15", // a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223) + min: "0.1.16", // a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked agents: []string{"grok"}, out: func() ([]Moving, error) { var out []Moving From db61143fe7e38e239e6650e3c6beca9ce75db7f4 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 02:57:39 +0800 Subject: [PATCH 06/92] usage: the Sessions and Routing caches copy out the strings they keep, so they no longer pin every decoded block An unpacked block's strings are cut from one allocation (unpackInto). The gateway-sessions projection (gatewayCache) and the vias cache kept a session id, model, agent, provider or effort from nearly every block, and each such substring held the block's whole decoded text: request and response ids and errors included. keptStrings clones each kept value once and interns it, so a cache holds only what it uses. TestSessionCachesHoldNoDecodedBlocks writes 16 blocks x 512 rows with a 1 KB error each, reads GatewaySessions and Vias, drops the snapshot and compares the live heap with and without the caches. Without the fix (both call sites reverted) it is red: "the caches hold 16651 KB for 16 sessions: the decoded text of their blocks (8192 KB)". With it, green -count=3. Measured (macOS, sandbox HOME seeded with 600k gateway calls, the fixed build vs ccb2eea15, the same Usage/Sessions/Routing views opened by Playwright, after GC via /v1/magpie/heap; footprint from `footprint`): - after the views: live heap 618 MB -> 466 MB, footprint 801 -> 670 MB - after warm-up only: live heap 467 -> 390 MB - CPU over the same 9m40s: ~22.4 s both Go is the process that holds memory: on a live v0.1.1208 app the Go process's footprint was 1045 MB, the Bun plugin host 51 MB, the two WebKit WebContent processes 70 and 83 MB. No single commit in v0.1.1225..HEAD is the cause: the shared-slab decode (99fcddeeb) and both caches (c9b826337, 60f896031) predate v0.1.1225. Idle with no page open, HEAD used 1.04 s CPU per 5 min against v0.1.1225's 0.56 s. Not fixed here: the gateway projection is kept once per window (up to 4), the startup heap peaks ~1.5 GB from GOGC doubling the warm-up's live heap, and a synthetic 11k-session history did not reproduce the 1 GB reported. Run at this change on ccb2eea15 (load average ~275-500 from other sessions): - go test ./... -timeout 45m, sandbox HOME: 61 packages ok; internal/agent timed out at 45m; 4 reds in gateway (TestClaudeAccountsSpentFallBackToCodex, TestCodexServedNamesTheAccountThatSigned) and gui (TestPluginPageReadsWhatItDeclared, TestSetAnswersWhileDevinAndProvidersHang). - Those 4 alone: gateway ok 40.8s, gui ok 13.7s. - internal/agent alone (-timeout 45m): timed out again at 2732s under load ~500; the stacks left include a netproxy.Bridge accept loop. internal/agent never calls GatewaySessions or Vias, the only code changed. Not filed from here: the run kept only its last 25 lines, so the test that hung is not named. - internal/usage: ok 123s. - gofmt -l: clean. go vet ./internal/usage/ for darwin, linux (nogui) and windows: clean. --- internal/usage/gateway_sessions.go | 4 +- internal/usage/kept_strings_test.go | 76 +++++++++++++++++++++++++++++ internal/usage/request_snapshot.go | 22 +++++++++ internal/usage/usage.go | 2 + 4 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 internal/usage/kept_strings_test.go diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index dd5cf04e4..888afc7ab 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -178,11 +178,13 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map type dayKey struct{ date, agent, model string } daily := map[dayKey]*GatewayDayUsage{} perSession := map[key]map[dayKey]*GatewayDayUsage{} + keep := keptStrings{} snapshot.visit(since, func(r Record) { if r.IsRejected() || r.IsReported() || r.Session == "" { return } - a := ReportedAs(r.Agent) + a := keep.of(ReportedAs(r.Agent)) + r.Session, r.Model = keep.of(r.Session), keep.of(r.Model) k := key{a, r.Session} if nativeKeys != nil && nativeKeys[a+"|"+r.Session] { return diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.go new file mode 100644 index 000000000..0e03230de --- /dev/null +++ b/internal/usage/kept_strings_test.go @@ -0,0 +1,76 @@ +package usage + +import ( + "bufio" + "crypto/rand" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// An unpacked block's strings share one allocation, so a cache that keeps a +// session id or a model name read from a block must copy it out, or it keeps +// every string of that block: over a long history, the decoded text of all +// of it. This test fills each block with 1 KB of unique error text and gives +// each block its own session, then measures what the Sessions and Routing +// caches hold once the log index itself is let go. +func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) { + resetUsageTest(t) + const blocks, text = 16, 1024 + path := Path() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + w := bufio.NewWriter(f) + at := time.Now().Add(-time.Hour) + noise := make([]byte, text/2) + for b := range blocks { + for range logBlockRows { + rand.Read(noise) + line, _ := json.Marshal(Record{Time: at, Agent: "codex", Session: "s" + string(rune('a'+b)), Provider: "p", Model: "m", Effort: "high", Input: 10, Output: 2, Status: 200, Error: hex.EncodeToString(noise)}) + w.Write(append(line, '\n')) + } + } + if err := w.Flush(); err != nil { + t.Fatal(err) + } + f.Close() + + held := func() uint64 { + var m runtime.MemStats + runtime.GC() + runtime.GC() + runtime.ReadMemStats(&m) + return m.HeapAlloc + } + if got := GatewaySessions(time.Time{}, nil); len(got) != blocks { + t.Fatalf("sessions: %d, want %d", len(got), blocks) + } + if got := Vias(time.Time{}); len(got) != blocks { + t.Fatalf("vias: %d, want %d", len(got), blocks) + } + // the index is kept by design; only what the caches hold is measured + logIndex.Lock() + logIndex.snapshot = nil + logIndex.Unlock() + withCaches := held() + gatewayCache.Lock() + gatewayCache.entries = nil + gatewayCache.Unlock() + viasCache.Lock() + viasCache.value = nil + viasCache.Unlock() + without := held() + decoded := uint64(blocks * logBlockRows * text) + if withCaches > without && withCaches-without > decoded/8 { + t.Fatalf("the caches hold %d KB for %d sessions: the decoded text of their blocks (%d KB)", (withCaches-without)>>10, blocks, decoded>>10) + } +} diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index 29ab2430c..c73300b31 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -12,6 +12,7 @@ import ( "encoding/binary" "math" "slices" + "strings" "sync" "time" "unsafe" @@ -79,6 +80,27 @@ func (c *rowChunk) pack() *rowChunk { func (c *rowChunk) unpack() *rowChunk { return c.unpackInto(nil) } +// keptStrings copies out the strings that a result kept after a read takes +// from the rows it visited. An unpacked block's strings are cut from one +// allocation (unpackInto), so a cache holding one session id from a block +// holds every string of that block: its request and response ids and its +// errors. The Sessions and Routing caches kept a session id from nearly +// every block, and so the decoded text of the whole history: ~200 MB at +// rest for 600k calls. +type keptStrings map[string]string + +func (k keptStrings) of(s string) string { + if s == "" { + return "" + } + if kept, ok := k[s]; ok { + return kept + } + kept := strings.Clone(s) + k[kept] = kept + return kept +} + // unpackInto is unpack decoding the rows into rows when it is large enough: // every field of a row is written, so a reused slice needs no clearing. func (c *rowChunk) unpackInto(into []packedRow) *rowChunk { diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 7bfc5b609..684267961 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -1005,10 +1005,12 @@ func Vias(since time.Time) map[string][]Via { func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { out := map[string][]Via{} + keep := keptStrings{} snapshot.visit(since, func(r Record) { if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" { return } + r.Provider, r.Model, r.Effort = keep.of(r.Provider), keep.of(r.Model), keep.of(r.Effort) k := ReportedAs(r.Agent) + "|" + r.Session vs := out[k] i := slices.IndexFunc(vs, func(v Via) bool { return v.Provider == r.Provider && v.Model == r.Model && v.Effort == r.Effort }) From 24f89cdb14656e421eed4adf1985526ea7c1861a Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 03:10:08 +0800 Subject: [PATCH 07/92] gateway: a streamed reply's text is gathered in a builder, not copied whole on every delta The collector that every encoder embeds (and conversations, hooks, relay status, search, the Claude subscription path) added each text or thinking delta to its part with `p.Text += ev.Text`, copying the whole reply so far on every delta. Quadratic in the reply: a 4000-delta reply copied ~57 KB per delta. It shows most on a translated stream (a Chat upstream served to an Anthropic client), where every chunk is one delta. Now the last part's text grows in a strings.Builder, written into the part when another part is touched or at finish(). Guard: TestCollectorTextLinear fails when collecting a reply allocates more than 16x its size. Before the fix: "collecting a 116014-byte reply allocated 247395704 bytes (2132x)". TestCollectorKeepsEveryDelta checks that every part's text, the signature and the tool args are kept whole. Numbers (a fake upstream, no network, 4000 events, chat -> anthropic stream, CPU from rusage since the box sits at load ~350): before: 166.9 cpu-ms/op, 231 MB/op, 391k allocs/op after: 95.4 cpu-ms/op, 31.3 MB/op, 387k allocs/op BenchmarkCollectorText (4000 deltas): 667 KB/op, 8048 allocs/op after. Passthrough cases were unchanged (small-stream-pass 42 ms, chat pass 94 ms). Run (on ccb2eea15 with this commit and the next one, jsonValid's memo, both in the tree, sandbox HOME, load ~350): - go test -tags nogui ./... -timeout 45m -count=1: 62 packages ok, internal/gateway ok (2694s). Two reds, both in untouched packages and both filed: - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set slow/slow-1 took 10.67s against its 10s bound (#1375). Rerun alone with -count=3, it passed at 4.7s, 2.8s and 7.1s. - internal/agent ran past 45m, with TestWSLMoreAgentsPick running at the deadline (#2544). - gofmt -l internal/: clean. - go vet ./internal/gateway passed. - GOOS=linux and GOOS=windows go vet -tags nogui ./... passed. - go build passed. - TestCollector* pass, and TestCollectorTextLinear is red on the old ir.go. --- internal/gateway/collector_text_test.go | 88 +++++++++++++++++++++++++ internal/gateway/ir.go | 29 +++++++- 2 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/collector_text_test.go diff --git a/internal/gateway/collector_text_test.go b/internal/gateway/collector_text_test.go new file mode 100644 index 000000000..5a5efc67d --- /dev/null +++ b/internal/gateway/collector_text_test.go @@ -0,0 +1,88 @@ +package gateway + +import ( + "runtime" + "strings" + "testing" +) + +// collectStream is a streamed reply as the collector takes it: n deltas +// of thinking, then n of text, then a tool call and more text. +func collectStream(c *collector, n int) { + c.add(Event{Kind: KStart, MsgID: "m", Model: "x"}) + for i := range n { + c.add(Event{Kind: KThink, Text: "think " + string(rune('a'+i%26)) + " "}) + } + c.add(Event{Kind: KSig, Text: "sig"}) + for i := range n { + c.add(Event{Kind: KText, Text: "word " + string(rune('a'+i%26)) + " of the reply, "}) + } + c.add(Event{Kind: KToolStart, ID: "t1", Name: "Read"}) + c.add(Event{Kind: KToolArgs, Text: `{"path":"/a"}`}) + c.add(Event{Kind: KText, Text: "after "}) + c.add(Event{Kind: KText, Text: "the call"}) + c.add(Event{Kind: KStop, Stop: "stop"}) +} + +// The collector's reply is the stream's, delta for delta: each part's +// text whole, in its own part, a part begun after a call its own. +func TestCollectorKeepsEveryDelta(t *testing.T) { + var c collector + collectStream(&c, 500) + res := c.finish() + var think, text strings.Builder + for i := range 500 { + think.WriteString("think " + string(rune('a'+i%26)) + " ") + text.WriteString("word " + string(rune('a'+i%26)) + " of the reply, ") + } + if len(res.Parts) != 4 { + t.Fatalf("parts %+v", res.Parts) + } + if p := res.Parts[0]; p.Kind != Thinking || p.Text != think.String() || p.Signature != "sig" { + t.Errorf("thinking %q sig %q", p.Text[:min(40, len(p.Text))], p.Signature) + } + if p := res.Parts[1]; p.Kind != Text || p.Text != text.String() { + t.Errorf("text %d bytes, want %d", len(p.Text), text.Len()) + } + if p := res.Parts[2]; p.Kind != ToolCall || string(p.Args) != `{"path":"/a"}` { + t.Errorf("call %+v", p) + } + if p := res.Parts[3]; p.Kind != Text || p.Text != "after the call" { + t.Errorf("last text %q", p.Text) + } +} + +// A streamed reply's text is gathered in time linear in its length: the +// collector used to add each delta to the part's string, copying the whole +// reply so far every time, about 57 KB a delta on a 4000-delta reply (a +// Chat upstream to an Anthropic client copied 229 MB to stream 88 KB). +func TestCollectorTextLinear(t *testing.T) { + const n = 4000 + var ms runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&ms) + before := ms.TotalAlloc + var c collector + collectStream(&c, n) + res := c.finish() + runtime.ReadMemStats(&ms) + got := ms.TotalAlloc - before + size := 0 + for _, p := range res.Parts { + size += len(p.Text) + } + // the strings themselves, the builder's doublings, the parts: a few + // times the reply. The quadratic copy was ~150× it here. + if got > uint64(16*size) { + t.Fatalf("collecting a %d-byte reply allocated %d bytes (%.0f×)", size, got, float64(got)/float64(size)) + } +} + +func BenchmarkCollectorText(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + var c collector + collectStream(&c, 4000) + c.finish() + } +} diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index ff2dfd78e..348523f1d 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -460,6 +460,11 @@ type Result struct { type collector struct { res Result args strings.Builder // arguments of the open tool call + // text is what the part at textAt-1 has had added to its text since, + // written into the part by flush: adding each delta to the part's + // string copied the whole reply so far every time + text strings.Builder + textAt int // fresh: a KThinkStart said the next reasoning is a block of its own fresh bool err string @@ -488,6 +493,25 @@ func (c *collector) open() *Part { return nil } +// grow adds s to the text of the part at i, the last one. +func (c *collector) grow(i int, s string) { + if c.textAt != i+1 { + c.flush() + c.text.WriteString(c.res.Parts[i].Text) + c.textAt = i + 1 + } + c.text.WriteString(s) +} + +// flush writes the text grow gathered into its part. +func (c *collector) flush() { + if c.textAt > 0 { + c.res.Parts[c.textAt-1].Text = c.text.String() + c.text = strings.Builder{} + c.textAt = 0 + } +} + func (c *collector) closeTool() { if p := c.last(ToolCall); p != nil && p.Args == nil { s := strings.TrimSpace(c.args.String()) @@ -512,7 +536,7 @@ func (c *collector) add(ev Event) { c.res.Usage.add(ev.Usage) case KText: if p := c.last(Text); p != nil { - p.Text += ev.Text + c.grow(len(c.res.Parts)-1, ev.Text) } else { c.closeTool() c.res.Parts = append(c.res.Parts, Part{Kind: Text, Text: ev.Text}) @@ -522,7 +546,7 @@ func (c *collector) add(ev Event) { return case KThink: if p := c.open(); p != nil { - p.Text += ev.Text + c.grow(len(c.res.Parts)-1, ev.Text) } else { c.closeTool() c.res.Parts = append(c.res.Parts, Part{Kind: Thinking, Text: ev.Text}) @@ -581,6 +605,7 @@ func (c *collector) add(ev Event) { } func (c *collector) finish() Result { + c.flush() c.closeTool() // a reply of tool calls ended "stop" (a relay's end_turn beside its // tool_use blocks, 蓝猫 on Discord) is the client's to run the calls From 938c31424ed935d5e8fcfcb335a7de3fcaa47308 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 03:10:18 +0800 Subject: [PATCH 08/92] gateway: a long request body is checked for valid JSON once, not by every decodeJSON decodeJSON runs jsonValid over its whole input before filling the value, and a request's body goes through it a dozen times on its way: modelOf, parseAnthropicRequest, swapImageBlocks, blocksOf, the prompt builder, conversationID, requestEffort, bodyEffort, streamOf, walkImages... On a 2 MB Anthropic request the repeated checks were ~18% of the CPU of serving it (pprof). jsonValid now remembers the last 8 bodies of 32 KB or more that it found valid, by length and a maphash under a seed of the process's own. Only valid results are kept, so an invalid body is checked (and refused) every time. A false hit needs a 64-bit collision under a seed no caller can see; even then fillJSON still parses the body. Guard: TestDecodeJSONChecksALongBodyOnce counts the byte-by-byte checks of one 84 KB body over six decodes. With the lookup turned off by hand: "a 84087-byte body was checked 6 times over six decodes, want 1". TestDecodeJSONMemoKeepsRefusing: a body changed by one byte at the same length, and a truncated one, are still refused after the valid one was remembered. Numbers (BenchmarkZZHot, a fake upstream with no network, 2 MB request, count 3, CPU from rusage since the box sits at load ~350): big-nostream before 113.4 / 140.1 / 117.1 cpu-ms/op after 107.6 / 98.7 / 99.2 cpu-ms/op big-stream-pass before 134.6 / 151.0 / 161.6 cpu-ms/op after 124.1 / 131.0 / 144.5 cpu-ms/op B/op and allocs/op are unchanged (65.9 MB, 181k; 81.9 MB, 310k), as expected: the check allocates nothing. Run (on ccb2eea15 with this commit and the previous one, the collector fix, both in the tree, sandbox HOME, load ~350): - go test -tags nogui ./... -timeout 45m -count=1: 62 packages ok, internal/gateway ok (2694s). Two reds, both in untouched packages and both filed: - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set slow/slow-1 took 10.67s against its 10s bound (#1375). Rerun alone with -count=3, it passed at 4.7s, 2.8s and 7.1s. - internal/agent ran past 45m, with TestWSLMoreAgentsPick running at the deadline (#2544). - gofmt -l internal/: clean. - go vet ./internal/gateway passed. - GOOS=linux and GOOS=windows go vet -tags nogui ./... passed. - go build passed. - The memo guard is red with the lookup turned off by hand (above). --- internal/gateway/fastjson.go | 54 +++++++++++++++++++ internal/gateway/fastjson_memo_test.go | 72 ++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 internal/gateway/fastjson_memo_test.go diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go index 9eda5f1f0..f6b18fa3f 100644 --- a/internal/gateway/fastjson.go +++ b/internal/gateway/fastjson.go @@ -6,9 +6,11 @@ import ( "encoding/binary" "encoding/json" "errors" + "hash/maphash" "reflect" "slices" "sync" + "sync/atomic" "unicode" "unicode/utf16" "unicode/utf8" @@ -562,9 +564,61 @@ func hex4(s []byte) rune { // jsonMaxDepth is encoding/json's maxNestingDepth. const jsonMaxDepth = 10000 +// validMemoMin is the size from which jsonValid remembers what it found +// valid. A request body is decoded a dozen times or more on its way +// (modelOf, parse, the prompt, the conversation, the effort, the images…), +// and each decodeJSON checked all of it again: ~2.5ms a time at 2 MB, a +// fifth of the CPU of serving it. +const validMemoMin = 32 << 10 + +// validMemo is the last bodies found valid, by length and a hash under a +// seed of this process's own. +var validMemo struct { + sync.Mutex + sums [8]validSum + next int +} + +type validSum struct { + n int + sum uint64 +} + +var validSeed = maphash.MakeSeed() + +// validScanned, when set (tests), is told of each body of validMemoMin or +// more that jsonValid checks byte by byte. +var validScanned atomic.Pointer[func(data []byte)] + // jsonValid is json.Valid, without stepping through each byte by a call: // the grammar, and the depth past which encoding/json gives up, are its. +// A long body found valid is remembered, and not checked again. func jsonValid(data []byte) bool { + if len(data) < validMemoMin { + return jsonCheck(data) + } + s := validSum{len(data), maphash.Bytes(validSeed, data)} + validMemo.Lock() + known := slices.Contains(validMemo.sums[:], s) + validMemo.Unlock() + if known { + return true + } + if f := validScanned.Load(); f != nil { + (*f)(data) + } + if !jsonCheck(data) { + return false + } + validMemo.Lock() + validMemo.sums[validMemo.next] = s + validMemo.next = (validMemo.next + 1) % len(validMemo.sums) + validMemo.Unlock() + return true +} + +// jsonCheck is jsonValid's check itself. +func jsonCheck(data []byte) bool { i := skipJSONSpace(data, 0) i, ok := validJSONValue(data, i, 0) return ok && skipJSONSpace(data, i) == len(data) diff --git a/internal/gateway/fastjson_memo_test.go b/internal/gateway/fastjson_memo_test.go new file mode 100644 index 000000000..52e9189b0 --- /dev/null +++ b/internal/gateway/fastjson_memo_test.go @@ -0,0 +1,72 @@ +package gateway + +import ( + "bytes" + "strings" + "sync/atomic" + "testing" +) + +// memoBody is a request body past validMemoMin, unique to the test. +func memoBody(tag string) []byte { + return []byte(`{"model":"` + tag + `","messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt ", 6000) + `"}]}`) +} + +// countScans counts jsonValid's byte-by-byte checks of bodies equal to b. +func countScans(t *testing.T, b []byte) *atomic.Int32 { + var n atomic.Int32 + f := func(data []byte) { + if bytes.Equal(data, b) { + n.Add(1) + } + } + validScanned.Store(&f) + t.Cleanup(func() { validScanned.Store(nil) }) + return &n +} + +// A long body decoded by each reader of a request is checked for valid +// JSON once, not by every decodeJSON: at 2 MB each check cost ~2.5ms, and +// a request's body went through a dozen of them. +func TestDecodeJSONChecksALongBodyOnce(t *testing.T) { + body := memoBody(t.Name()) + scans := countScans(t, body) + for range 6 { + var v struct { + Model string `json:"model"` + } + if err := decodeJSON(body, &v); err != nil || v.Model != t.Name() { + t.Fatalf("decode: %v %q", err, v.Model) + } + } + if n := scans.Load(); n != 1 { + t.Fatalf("a %d-byte body was checked %d times over six decodes, want 1", len(body), n) + } +} + +// What is remembered is a valid body: an invalid one, or a valid one +// changed by a byte at the same length, is checked again and refused. +func TestDecodeJSONMemoKeepsRefusing(t *testing.T) { + body := memoBody(t.Name()) + var v map[string]any + if err := decodeJSON(body, &v); err != nil { + t.Fatal(err) + } + bad := bytes.Clone(body) + bad[len(bad)-1] = '!' + for range 3 { + var w map[string]any + if err := decodeJSON(bad, &w); err == nil { + t.Fatal("a body with a broken end decoded") + } + } + trunc := body[:len(body)-1] + var w map[string]any + if err := decodeJSON(trunc, &w); err == nil { + t.Fatal("a truncated body decoded") + } + if !jsonValid(body) || jsonValid(bad) { + t.Fatal("jsonValid's answer changed") + } +} From a595f1559c351551334b0141dbeb28ccd4f0c6f9 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 03:10:39 +0800 Subject: [PATCH 09/92] provider: a request to a routing group builds the groups' entries once, not once per look at every member of every group (colmugx, Yayoi_no_yume on X) colmugx found magpie hotter with groups, and worse since ~v0.1.1225. Yayoi_no_yume saw CPU jump to 100% as soon as a request entered a group, and stay there under concurrency. Cause: one request to a group asked for the groups' entries (groupEntries) five or six times: Catalog from Resolve and IsDecider, and Served from membersImageInput, outputLimit, windowIn and roomy. A direct provider/model request asked through Resolve too. Nothing held that work. Each build: - went through every member of every group, the found auto- ones included, with a linear pass over the whole catalog per member. It copied each large Entry it passed (groupEntries, resolveIn); - since 8f4d091c6 (#2224) ran smallestWindow for every group, not only one set to ContextSmallest. That was a second full pass per member, which is the regression after v0.1.1225; - parsed settings.json again for each group's disabled models (membersIn -> disabledList -> settings.LoadChecked). Fix: - groupEntries is held while a request holds the catalog. heldFrom keys it to the catalog slice it was built from, so it is rebuilt for a rebuilt catalog. Catalog and Served hand out a copy. - Each member's entry is looked up in a map built once per build. - smallestWindow runs only for ContextSmallest. - resolveIn walks by index, not by copying each Entry. - disabledList is held like heldSettings. SetDisabledModels calls Changed, so a change is seen at once. Guards (each fails without its fix, broken by hand): - TestGroupEntriesBuiltOnceWhileHeld: the same build under one Hold. Also checks that a caller's change to Catalog doesn't reach the next caller, that another catalog is built from, and that a save is seen. - TestGroupLooksParseNoSettingsPerGroupWhileHeld: settings parses per look. - BenchmarkGroupEntries (provider) and BenchmarkGroupOverhead / BenchmarkGroupOverheadParallel (gateway). These use fake upstreams: direct vs groups of 1, 4 and 8 members, one with a failing first member and one with a resting first member, at 200KB and 2MB, streamed and not, on a 12x20 and a 30x60 catalog. Numbers. cpu-ms/op is process CPU per request. The machine was at load ~200-430, so wall times are not comparable. - Catalog of 30 providers x 60 shared models, 200KB, non-stream, BenchmarkGroupOverhead, 5x: | Version | direct p0/m1 | groups (g1 g4 g8u gfail grest) | |----------------------|--------------|--------------------------------| | v0.1.1225 (54ba9042d) | 242 | 976 / 1006 / 965 / 966 / 945 | | HEAD ccb2eea15 | 571 | 1462 / 1745 / 1719 / 1758 / 1715 | | this commit | 76 | 93 / 116 / 91 / 114 / 106 | Parallel, HEAD -> this commit: direct 563 -> 73, groups 1355-1625 -> 94-152. The cost of entering a group, over direct: ~+1150 ms at HEAD, ~+15-40 ms now. Memory per group request: 200MB -> 74-79MB. Allocs: 442k -> 128-141k. - BenchmarkGroupEntries, one build of the 30x60 catalog's groups, CPU: HEAD 233 ms; HEAD with smallestWindow gated only 151 ms; this commit 20 ms. - 12x20 catalog, 200KB, HEAD (before): direct 45.5, groups 83-89 cpu-ms/op. v0.1.1225: direct 37, groups 85-97. So with a small catalog the overhead is old, not new. It grows with providers x models x groups, which is why colmugx's and Yayoi_no_yume's catalogs feel it. Run at this head: - go test ./... -timeout 45m at load ~430: 60 packages ok, including internal/provider. internal/agent, internal/gateway and internal/library hit the 45m timeout under that load. These were not failures. internal/gui failed two tests: - TestSetAnswersWhileDevinAndProvidersHang ("set slow/slow-1 took 11.9s", over its 10s wall bound) failed in the run and once more alone (16.25s). It passed on the ccb2eea15 checkout (9.95s) and 2 of 2 with -count=2 at this commit. It is a wall-clock bound under load, and this commit doesn't touch its path. - TestMainWindowCorners was killed while measuring and passed rerun. - go test ./internal/gateway -run 'Group|Member|Rout|Fallback|Rest|Window|Image' -count=1: ok (221s) - TestGroupLooksParseNoSettingsPerGroupWhileHeld with disabledList not held: red, "settings.json parsed 50 times in 50 looks" - gofmt -l internal: clean - GOOS=linux go vet -tags nogui ./...: clean - GOOS=windows go vet ./...: clean --- internal/gateway/group_overhead_bench_test.go | 196 ++++++++++++++++++ internal/provider/account_test.go | 2 +- internal/provider/disabled.go | 16 ++ internal/provider/group.go | 54 +++-- internal/provider/group_held_test.go | 136 ++++++++++++ internal/provider/hold.go | 44 ++++ internal/provider/models.go | 20 +- 7 files changed, 444 insertions(+), 24 deletions(-) create mode 100644 internal/gateway/group_overhead_bench_test.go create mode 100644 internal/provider/group_held_test.go diff --git a/internal/gateway/group_overhead_bench_test.go b/internal/gateway/group_overhead_bench_test.go new file mode 100644 index 000000000..9540b1127 --- /dev/null +++ b/internal/gateway/group_overhead_bench_test.go @@ -0,0 +1,196 @@ +package gateway + +import ( + "bytes" + "fmt" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// groupBenchUpstream answers an Anthropic request as it asked: streamed +// when its body says so. Refusing, it answers code with an overloaded +// error. +type groupBenchUpstream struct{ code int } + +const groupBenchReply = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}` + +var groupBenchStream = sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`) + +func (u groupBenchUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + if u.code != 0 { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "3600") + w.WriteHeader(u.code) + io.WriteString(w, `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`) + return + } + if bytes.Contains(b, []byte(`"stream":true`)) { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, groupBenchStream) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, groupBenchReply) +} + +// groupBenchCatalog is a catalog of providers serving models each, the +// same model ids at each (so magpie finds a group of each model), and +// groups of one, four and eight members, one whose first member fails +// every time, and one whose first member is resting. +func groupBenchCatalog(b *testing.B, providers, models int) { + b.Helper() + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + b.Setenv("XDG_CACHE_HOME", b.TempDir()) + good := httptest.NewServer(groupBenchUpstream{}) + b.Cleanup(good.Close) + failing := httptest.NewServer(groupBenchUpstream{code: 500}) + b.Cleanup(failing.Close) + resting := httptest.NewServer(groupBenchUpstream{code: 429}) + b.Cleanup(resting.Close) + var ids []string + for i := range models { + ids = append(ids, fmt.Sprintf("m%d", i)) + } + for i := range providers { + p := provider.Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: ids, Anthropic: good.URL} + if err := provider.Save(p); err != nil { + b.Fatal(err) + } + } + for _, p := range []provider.Provider{ + {ID: "bad", Name: "Bad", Key: "k", Models: ids, Anthropic: failing.URL}, + {ID: "rest", Name: "Rest", Key: "k", Models: ids, Anthropic: resting.URL}, + } { + if err := provider.Save(p); err != nil { + b.Fatal(err) + } + } + if err := settings.Save(settings.Settings{}); err != nil { + b.Fatal(err) + } + for _, g := range []provider.Group{ + {ID: "g1", Name: "G1", Members: []string{"p0/m1"}, Routing: provider.Ordered}, + {ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: provider.Ordered}, + {ID: "g8u", Name: "G8U", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1", "p4/m1", "p5/m1", "p6/m1", "p7/m1"}, Routing: provider.LeastUsed}, + {ID: "gfail", Name: "GFail", Members: []string{"bad/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered}, + {ID: "grest", Name: "GRest", Members: []string{"rest/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered}, + } { + if err := provider.SaveGroup(g); err != nil { + b.Fatal(err) + } + } + // as a user's files are: written a while ago, not just now (a file + // written in the last seconds is read again each time) + old := time.Now().Add(-time.Hour) + filepath.WalkDir(os.Getenv("XDG_CONFIG_HOME"), func(path string, _ fs.DirEntry, _ error) error { + return os.Chtimes(path, old, old) + }) + provider.Changed() +} + +// groupBenchCase is one benchmark's request. +type groupBenchCase struct { + providers, models, words int + stream bool + model string +} + +func (c groupBenchCase) name() string { + return fmt.Sprintf("catalog=%dx%d/%dKB/stream=%v/%s", c.providers, c.models, c.words*4/1000, c.stream, c.model) +} + +// groupBenchCases: a dozen providers of 20 models, with a ~200KB and a +// ~2MB conversation, and a large catalog (30 providers of 60 models, as +// a user of several relays has) with the ~200KB one. +func groupBenchCases() []groupBenchCase { + var out []groupBenchCase + for _, size := range []struct{ providers, models, words int }{{12, 20, 50_000}, {12, 20, 500_000}, {30, 60, 50_000}} { + for _, stream := range []bool{false, true} { + for _, model := range []string{"p0/m1", "group/g1", "group/g4", "group/g8u", "group/gfail", "group/grest"} { + out = append(out, groupBenchCase{size.providers, size.models, size.words, stream, model}) + } + } + } + return out +} + +// groupBenchServer is the gateway with c's catalog, and a request of the +// body c sends that fails the benchmark unless it is answered. +func groupBenchServer(b *testing.B, c groupBenchCase) func() { + noRests() + b.Cleanup(noRests) + groupBenchCatalog(b, c.providers, c.models) + body := largeConversation(provider.Anthropic, c.model, c.words) + if c.stream { + body = bytes.Replace(body, []byte(`"stream":false`), []byte(`"stream":true`), 1) + } + b.SetBytes(int64(len(body))) + h := New().Handler() + do := func() { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", bytes.NewReader(body))) + if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("ok")) { + b.Fatalf("%d %s", rec.Code, rec.Body.String()) + } + } + do() // the resting member rests + return do +} + +// BenchmarkGroupOverhead is a request to a provider's model and the same +// request to routing groups, streamed and not, with a long conversation: +// what magpie adds for a group is the difference. cpu-ms/op is the CPU +// the process spent, which a busy machine doesn't change as it does the +// wall time. +func BenchmarkGroupOverhead(b *testing.B) { + for _, c := range groupBenchCases() { + b.Run(c.name(), func(b *testing.B) { + do := groupBenchServer(b, c) + b.ResetTimer() + cpu, _ := processCPU() + for range b.N { + do() + } + after, _ := processCPU() + b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op") + }) + } +} + +// BenchmarkGroupOverheadParallel is BenchmarkGroupOverhead's requests sent +// at once, as several agents send them. +func BenchmarkGroupOverheadParallel(b *testing.B) { + for _, c := range groupBenchCases() { + if c.stream || c.words > 50_000 { + continue + } + b.Run(c.name(), func(b *testing.B) { + do := groupBenchServer(b, c) + b.ResetTimer() + cpu, _ := processCPU() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + do() + } + }) + after, _ := processCPU() + b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op") + }) + } +} diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go index 3230a4d2c..af677c910 100644 --- a/internal/provider/account_test.go +++ b/internal/provider/account_test.go @@ -68,7 +68,7 @@ func signIn(t *testing.T) string { // isolate keeps tests off the machine's own Claude Code Keychain // logins and forgets anything a previous test cached. -func isolate(t *testing.T) { +func isolate(t testing.TB) { t.Helper() oldKeychain, oldBase, oldExe := claudeKeychain, claudeBase, claudeExecutable oldDevin := DevinExecutable diff --git a/internal/provider/disabled.go b/internal/provider/disabled.go index b35585807..724d14f98 100644 --- a/internal/provider/disabled.go +++ b/internal/provider/disabled.go @@ -34,6 +34,22 @@ var lastDisabled struct { // disabledList is the patterns in force, and unknown when settings.json // couldn't be read and none was read before. func disabledList() (list []string, unknown bool) { + // read once while a request holds the catalog: each group's members + // (membersIn) asked for it, and parsed settings.json each time + r := heldOf("disabled", func() disabledRead { + list, unknown := readDisabled() + return disabledRead{slices.Clip(list), unknown} + }) + return r.list, r.unknown +} + +type disabledRead struct { + list []string + unknown bool +} + +// readDisabled is disabledList read from settings.json now. +func readDisabled() (list []string, unknown bool) { s, err := settings.LoadChecked() lastDisabled.Lock() defer lastDisabled.Unlock() diff --git a/internal/provider/group.go b/internal/provider/group.go index d641b5dd0..feba98c31 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -868,10 +868,34 @@ func membersOff(entries []Entry, all []Group, g Group, off func(pid, model strin // every member fixed, the group offers the levels they are fixed at, so // that an agent still asks it to reason. A group that names its own // levels (Group.Levels) offers those, and so does a group in it for its -// models. +// models. Held while a request holds the catalog (heldFrom). func groupEntries(entries []Entry) []Entry { + return heldFrom("group entries", entries, buildGroupEntries) +} + +// entryOf is where in entries the last entry of provider pid's model is, +// -1 when none is. +type entryOf func(pid, model string) int + +// entriesBy is entryOf for entries, looked up in a map built once rather +// than by a pass over every entry for each member of each group. +func entriesBy(entries []Entry) entryOf { + at := make(map[[2]string]int, len(entries)) + for i := range entries { + at[[2]string{entries[i].Provider.ID, entries[i].Model}] = i + } + return func(pid, model string) int { + if i, ok := at[[2]string{pid, model}]; ok { + return i + } + return -1 + } +} + +func buildGroupEntries(entries []Entry) []Entry { var out []Entry all := groupsIn(entries) + find := entriesBy(entries) for _, g := range all { if g.Hidden || g.Disabled { continue @@ -899,11 +923,10 @@ func groupEntries(entries []Entry) []Entry { images, thinks, ctx, output := false, false, 0, 0 var imageInput *bool unknown, reasonless := false, false - for _, x := range entries { - if x.Provider.ID == m.Provider.ID && x.Model == m.Model { - efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput - unknown, reasonless = levelsUnknown(x), x.Reasonless - } + if j := find(m.Provider.ID, m.Model); j >= 0 { + x := &entries[j] + efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput + unknown, reasonless = levelsUnknown(*x), x.Reasonless } // it reasons when a member does: the gateway sends the // effort to the members that take it, and a member known not @@ -1011,8 +1034,13 @@ func groupEntries(entries []Entry) []Entry { ruledEntry(&e, g.Live(), ms, entries) if g.Context > 0 { e.Context, e.WindowSet = g.Context, true - } else if smallest, typed := smallestWindow(entries, ms); g.Context == ContextSmallest && smallest > 0 { - e.Context, e.WindowSet = smallest, typed + } else if g.Context == ContextSmallest { + // only for a group that follows its smallest member: run for + // every group, it was another pass over the catalog for each + // member of each (8f4d091c6) + if smallest, typed := smallestWindowBy(entries, find, ms); smallest > 0 { + e.Context, e.WindowSet = smallest, typed + } } e.Family = g.Family out = append(out, e) @@ -1029,12 +1057,14 @@ func groupEntries(entries []Entry) []Entry { // group set to 500K itself wasn't). A tie counts as typed: the window is // the user's either way. func smallestWindow(entries []Entry, ms []Member) (n int, typed bool) { + return smallestWindowBy(entries, entriesBy(entries), ms) +} + +func smallestWindowBy(entries []Entry, find entryOf, ms []Member) (n int, typed bool) { for _, m := range ms { ctx, set := 0, false - for _, x := range entries { - if x.Provider.ID == m.Provider.ID && x.Model == m.Model { - ctx, set = x.Context, x.WindowSet - } + if j := find(m.Provider.ID, m.Model); j >= 0 { + ctx, set = entries[j].Context, entries[j].WindowSet } switch { case ctx <= 0: diff --git a/internal/provider/group_held_test.go b/internal/provider/group_held_test.go new file mode 100644 index 000000000..819447c43 --- /dev/null +++ b/internal/provider/group_held_test.go @@ -0,0 +1,136 @@ +package provider + +import ( + "fmt" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// groupHeldFixture is a dozen providers serving the same models, so +// magpie finds a group of each, and a group of the user's of four. +func groupHeldFixture(t *testing.T) { + t.Helper() + isolate(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("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 10 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 12 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + t.Fatal(err) + } + } + if err := settings.Save(settings.Settings{DisabledModels: []string{"p11/m9"}}); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + Changed() +} + +// A request to a group asks for the catalog's groups several times — +// Resolve's Catalog, and Served for the members' images, the reply's +// length and the window — and each built every group's entry again, from +// every member of every group: the burst of CPU at once that a request to +// a group cost with many providers (colmugx and Yayoi_no_yume on X). While +// a request holds the catalog they are built once. +func TestGroupEntriesBuiltOnceWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + entries := providerEntries() + first := groupEntries(entries) + if len(first) < 2 { + t.Fatalf("the fixture has %d groups; the test needs the found ones too", len(first)) + } + if again := groupEntries(entries); &again[0] != &first[0] { + t.Fatal("the groups' entries were built again under one Hold") + } + // what a caller is given is its own to change + c := Catalog() + c[0].Name = "changed" + if Catalog()[0].Name == "changed" || Served()[0].Name == "changed" { + t.Fatal("a change to Catalog's entries reached the next caller's") + } + // another catalog than the one held is built from, not answered for + other := append([]Entry(nil), entries[:len(entries)/2]...) + if got := groupEntries(other); len(got) > 0 && &got[0] == &first[0] { + t.Fatal("the groups of another catalog were the held one's") + } + // a write drops them + if err := SaveGroup(Group{ID: "g4", Name: "Renamed", Members: []string{"p0/m1", "p1/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + found := false + for _, e := range Catalog() { + found = found || e.ID == GroupPrefix+"g4" && e.Name == "Renamed" + } + if !found { + t.Fatal("a group saved under the Hold kept its old entry") + } +} + +// Each group's members (membersIn) asked whether the user disabled them, +// and that parsed settings.json each time: a catalog of found groups +// parsed it once a group, on each of the several looks a request makes. +func TestGroupLooksParseNoSettingsPerGroupWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + Served() // the first look builds what is held + const looks = 50 + before := settings.Parses() + for range looks { + Served() + Groups() + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + t.Fatal("no group g4") + } + } + if n := settings.Parses() - before; n >= looks { + t.Fatalf("settings.json parsed %d times in %d looks at the groups under one Hold", n, looks) + } + // and a model disabled is still left out + for _, e := range Served() { + if e.ID == "p11/m9" { + t.Fatal("a disabled model was served") + } + } +} + +// BenchmarkGroupEntries is the groups' entries of a catalog of 30 +// providers serving the same 60 models (60 groups magpie finds, of 30 +// members each), built afresh: what each request built several times. +func BenchmarkGroupEntries(b *testing.B) { + isolate(b) + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + b.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + b.Setenv("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 60 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 30 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + b.Fatal(err) + } + } + Changed() + entries := providerEntries() + b.ResetTimer() + for range b.N { + buildGroupEntries(entries) + } +} diff --git a/internal/provider/hold.go b/internal/provider/hold.go index e5ec66347..48b2736f7 100644 --- a/internal/provider/hold.go +++ b/internal/provider/hold.go @@ -116,6 +116,50 @@ func heldPlugins() []plugin.Provider { return heldOf("plugins", func() []plugin.Provider { return slices.Clip(plugin.Cached()) }) } +// fromEntries is what was built from a catalog, and which catalog: its +// first entry and its length. +type fromEntries[T any] struct { + at *Entry + n int + v T +} + +// heldFrom is heldOf for what is built from entries: held while a request +// holds the catalog, and built again for another catalog than it was built +// from (providerEntries built afresh after heldFor, or one a caller made). +// A request asks for the groups' entries several times (Catalog, Served), +// and each built them from every member of every group again (the CPU a +// request to a group took at once, with many providers). +func heldFrom[T any](key string, entries []Entry, build func([]Entry) T) T { + var at *Entry + if len(entries) > 0 { + at = &entries[0] + } + held.Lock() + if held.holds == 0 { + held.Unlock() + return build(entries) + } + if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor { + if f := h.v.(fromEntries[T]); f.at == at && f.n == len(entries) { + held.Unlock() + return f.v + } + } + gen := held.gen + held.Unlock() + v := build(entries) + held.Lock() + if held.holds > 0 && held.gen == gen { + if held.built == nil { + held.built = map[string]heldValue{} + } + held.built[key] = heldValue{fromEntries[T]{at, len(entries), v}, time.Now()} + } + held.Unlock() + return v +} + // heldSettings is the settings, read once while a request holds the // catalog: a look at the agents asks them for every model of every agent. // Only for reading — what it gives is shared by the request's look-ups. diff --git a/internal/provider/models.go b/internal/provider/models.go index 9d2060d3c..be33d6441 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -2282,7 +2282,7 @@ type Entry struct { // provider not kept unlisted. A provider switched off has none in it. func Catalog() []Entry { entries := providerEntries() - out := groupEntries(entries) + out := slices.Clone(groupEntries(entries)) // held: the caller's to change kept := unlistedByGroups(entries) for _, e := range entries { if !e.Provider.Unlisted && !kept[e.ID] { @@ -2321,7 +2321,7 @@ func unlistedByGroups(entries []Entry) map[string]bool { // model a routing group can be made of, or a request can name. func Served() []Entry { entries := providerEntries() - return append(groupEntries(entries), entries...) + return append(slices.Clone(groupEntries(entries)), entries...) } // Unlisted are the models Served has and Catalog doesn't: those of the @@ -2522,8 +2522,10 @@ func Resolve(id string) (Provider, string, bool) { } func resolveIn(entries []Entry, id string) (Provider, string, bool) { - for _, e := range entries { - if e.ID == id { + // by index: an Entry, its Provider in it, is large, and a copy of each + // one looked past was most of a group's members resolved (membersIn) + for i := range entries { + if e := &entries[i]; e.ID == id { return e.Provider, e.Model, true } } @@ -2534,15 +2536,11 @@ func resolveIn(entries []Entry, id string) (Provider, string, bool) { return *p, model, true } } - var hits []Entry - for _, e := range entries { - if e.Model == id { - hits = append(hits, e) + for i := range entries { + if e := &entries[i]; e.Model == id { + return e.Provider, e.Model, true // the first that serves it } } - if len(hits) >= 1 { - return hits[0].Provider, hits[0].Model, true - } // not exposed, but some provider lists it var found []Provider for _, p := range heldOf("listed", listedBy)[id] { From 9893ae8216d4e978f9d7db57e59118b1436447d3 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 00:18:45 +0800 Subject: [PATCH 10/92] sessions: a write to one Hermes session parses only that session again (#2776) Hermes keeps every session in one state.db, and a session's parse was reused only while the whole store's revision (state.db and its WAL, size and mtime) stood. Any write moved it, so every Hermes session's messages were read, de-duplicated and decoded again: on each Sessions poll while Hermes ran, and on the first read after a restart if Hermes had run meanwhile (the reporter's 25-40s Sessions page). The store's revision still decides whether anything is read. When it moved, one read transaction now takes a fingerprint of each session (hermesPrintsFor, fingerprints): its sessions row as metadata() reads it, and over its messages and usage rows a count, the ids, and sums of every column parseHermes reads, values or byte lengths (active and compacted, which a rewind or compaction flips in place, and octet_length of content, tool calls and display metadata, which Hermes fills in later). They are kept per store revision. Only sessions whose fingerprint moved are parsed again. A fingerprint that can't be read is "" and reuses nothing, as before. A rewrite of a message to text of the very same byte length with no other column moving is the one change it can miss; said in the code. Tests: TestHermesWriteParsesOnlyItsSession (one message inserted: 1 session parsed again, 4 on the old check; a message rewritten in place is read), TestHermesUnreadFingerprintsParseAgain (an unknown fingerprint reuses nothing; red with the f.rev == "" guard taken out). Measured on a synthetic sandbox HOME (2000 Hermes sessions, 132k messages, 465 MB state.db, beside 3000 Claude Code and 1500 Codex sessions), one message inserted into Hermes before each request, warm index, load average ~250 from other sessions on the machine (CPU time is the stable number): /api/sessions/manage?agent=claude before 2190 ms CPU (11962 ms wall) after 617 ms CPU ( 4669 ms wall) /api/sessions/manage?agent=hermes before 2400 ms CPU (14630 ms wall) after 618 ms CPU ( 6239 ms wall) /api/sessions before 2102 ms CPU (10229 ms wall) after 357 ms CPU ( 3136 ms wall) The fingerprint pass itself over that store: ~0.3 s CPU in sqlite3. Run: go test ./internal/sessions -count=1 (ok, 241s); gofmt -l clean; go vet ./internal/sessions. Full suite and cross-OS vet are recorded on the last commit of this series. --- internal/sessions/hermes.go | 140 ++++++++++++++++++- internal/sessions/hermes_fingerprint_test.go | 99 +++++++++++++ internal/sessions/sessions.go | 3 +- 3 files changed, 240 insertions(+), 2 deletions(-) create mode 100644 internal/sessions/hermes_fingerprint_test.go diff --git a/internal/sessions/hermes.go b/internal/sessions/hermes.go index 1c1869660..43c5e9995 100644 --- a/internal/sessions/hermes.go +++ b/internal/sessions/hermes.go @@ -12,6 +12,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "time" "github.com/yetone/magpie/internal/appdir" @@ -92,6 +93,141 @@ func hermesRevision(path string) string { return strings.Join(parts, ":") } +// hermesPrinted is each store's sessions' fingerprints, as of the store's +// revision they were read at. +var hermesPrinted = struct { + sync.Mutex + stores map[string]hermesPrintSet +}{stores: map[string]hermesPrintSet{}} + +type hermesPrintSet struct { + revision string + prints map[string]string +} + +// hermesPrintsFor is the fingerprint of each session in the store at path, +// read again only when the store's revision moved. nil when they could not +// be read: then no session's parse is reused. +func hermesPrintsFor(path string, h *hermesDB) map[string]string { + hermesPrinted.Lock() + defer hermesPrinted.Unlock() + if set, ok := hermesPrinted.stores[path]; ok && h.revision != "" && set.revision == h.revision { + return set.prints + } + prints := h.fingerprints() + if prints != nil && h.revision != "" { + hermesPrinted.stores[path] = hermesPrintSet{h.revision, prints} + } else { + delete(hermesPrinted.stores, path) + } + return prints +} + +func forgetHermesPrints() { + hermesPrinted.Lock() + hermesPrinted.stores = map[string]hermesPrintSet{} + hermesPrinted.Unlock() +} + +// fingerprints is, for each session, what parseHermes reads of it in a few +// values: its sessions row, and over its messages and usage rows a count, +// the ids, and the sums of every read column's values or byte lengths. A +// row added, removed or rewritten in place (active and compacted flipped +// by a rewind or a compaction, a tool call's content filled in later) +// moves it. Any write moves the whole store's revision, and parsing every +// session again on each one read, de-duplicated and decoded every message +// Hermes ever kept, again and again while it ran (#2776); this reads only +// the tables' pages, in SQLite. A rewrite to text of the very same length, +// with no other column moving, is the one change it can miss. nil when any +// of it could not be read. +func (h *hermesDB) fingerprints() map[string]string { + if !h.sessions["id"] { + return nil + } + tx, err := h.db.BeginTx(context.Background(), nil) + if err != nil { + return nil + } + defer tx.Rollback() + parts := map[string][]string{} + read := func(table, query string) bool { + rows, err := tx.Query(query) + if err != nil { + return false + } + defer rows.Close() + cols, err := rows.Columns() + if err != nil { + return false + } + vals := make([]sql.NullString, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + for rows.Next() { + if rows.Scan(ptrs...) != nil { + return false + } + var b strings.Builder + b.WriteString(table) + b.WriteByte(':') + for _, v := range vals[1:] { + if v.Valid { + b.WriteString(strconv.Quote(v.String)) + } else { + b.WriteString("~") + } + b.WriteByte(',') + } + parts[vals[0].String] = append(parts[vals[0].String], b.String()) + } + return rows.Err() == nil + } + // metadata()'s columns, as it reads them + if !read("s", "SELECT id, "+hermesSelect(h.sessions, []string{"title", "cwd", "model", "billing_provider"}, "''")+", "+ + hermesSelect(h.sessions, []string{"started_at", "ended_at", "last_activity_at", "input_tokens", "output_tokens", + "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_call_count"}, "0")+" FROM sessions") { + return nil + } + column := func(cols map[string]bool, name string) string { + if cols[name] { + return name + } + return "NULL" + } + if h.messages["session_id"] { + q := []string{"session_id", "count(*)", "max(" + hermesExpr(h.messages, "id", "rowid") + ")", "total(" + hermesExpr(h.messages, "id", "rowid") + ")"} + for _, c := range []string{"timestamp", "active", "compacted"} { + q = append(q, "total("+column(h.messages, c)+")") + } + for _, c := range []string{"role", "content", "tool_calls", "tool_call_id", "tool_name", "display_kind", "display_metadata"} { + q = append(q, "total(octet_length("+column(h.messages, c)+"))") + } + if !read("m", "SELECT "+strings.Join(q, ", ")+" FROM messages GROUP BY session_id") { + return nil + } + } + if h.usage["session_id"] { + q := []string{"session_id", "count(*)"} + for _, c := range []string{"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_call_count", "last_seen"} { + q = append(q, "total("+column(h.usage, c)+")") + } + for _, c := range []string{"model", "billing_provider", "task"} { + q = append(q, "total(octet_length("+column(h.usage, c)+"))", "max("+column(h.usage, c)+")", "min("+column(h.usage, c)+")") + } + if !read("u", "SELECT "+strings.Join(q, ", ")+" FROM session_model_usage GROUP BY session_id") { + return nil + } + } + out := make(map[string]string, len(parts)) + for sid, p := range parts { + sum := sha256.Sum256([]byte(strings.Join(p, "|"))) + out[sid] = "fp1:" + hex.EncodeToString(sum[:16]) + } + return out +} + type hermesQuery interface { Query(string, ...any) (*sql.Rows, error) QueryRow(string, ...any) *sql.Row @@ -154,6 +290,7 @@ func hermesFiles() []file { if !store.sessions["id"] { continue } + prints := hermesPrintsFor(path, store) messageLast, usageLast := "0", "0" if store.messages["session_id"] && store.messages["timestamp"] { messageLast = "COALESCE((SELECT MAX(timestamp) FROM messages m WHERE m.session_id = sessions.id), 0)" @@ -185,6 +322,7 @@ func hermesFiles() []file { main: true, mod: hermesTime(max(start, end, last, messageAt, usageAt)), hermes: store, + rev: prints[sid], // "" when unknown: parsed again readOnly: true, }) } @@ -462,7 +600,7 @@ func parseHermes(f file) *state { s.Last = at } } - s.DBRevision = f.hermes.revision + s.DBRevision = f.rev return s } diff --git a/internal/sessions/hermes_fingerprint_test.go b/internal/sessions/hermes_fingerprint_test.go new file mode 100644 index 000000000..18f1e0176 --- /dev/null +++ b/internal/sessions/hermes_fingerprint_test.go @@ -0,0 +1,99 @@ +package sessions + +import ( + "database/sql" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +// A write to one Hermes session moves the whole store's revision. Only that +// session is parsed again (#2776): every session was, each poll while +// Hermes ran. A message rewritten in place, with no row added, still is. +func TestHermesWriteParsesOnlyItsSession(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + t.Setenv("HERMES_HOME", root) + path := hermesFixture(t, root, "", "busy", true) + db, err := sql.Open("sqlite", path+"?_pragma=journal_mode(WAL)") + if err != nil { + t.Fatal(err) + } + defer db.Close() + base := float64(time.Date(2026, 9, 28, 10, 0, 0, 0, time.UTC).Unix()) + for _, sid := range []string{"idle1", "idle2", "idle3"} { + if _, err := db.Exec(`INSERT INTO sessions (id, title, started_at) VALUES (?, NULL, ?)`, sid, base); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES (?, 'user', 'first words', '[]', ?)`, sid, base+1); err != nil { + t.Fatal(err) + } + } + var parsed atomic.Int32 + parseHook = func() { parsed.Add(1) } + t.Cleanup(func() { parseHook = nil }) + + List(0) + parsed.Store(0) + List(0) + if n := parsed.Load(); n != 0 { + t.Fatalf("nothing changed, yet %d parsed again", n) + } + + if _, err := db.Exec(`INSERT INTO messages (session_id, role, content, tool_calls, timestamp) VALUES ('busy', 'user', 'one more', '[]', ?)`, base+20); err != nil { + t.Fatal(err) + } + List(0) + if n := parsed.Load(); n != 1 { + t.Fatalf("one session written, %d parsed again", n) + } + + // in place: the row count, ids and times all stay + parsed.Store(0) + if _, err := db.Exec(`UPDATE messages SET content = 'rewritten first words' WHERE session_id = 'idle2'`); err != nil { + t.Fatal(err) + } + if got := hermesSessionByID(t, hermesID(path, "idle2")).Title; got != "rewritten first words" { + t.Errorf("in-place rewrite not read: title %q", got) + } + if n := parsed.Load(); n != 1 { + t.Fatalf("one message rewritten in place, %d parsed again", n) + } +} + +// Fingerprints that can't be read are unknown: no session's parse is kept. +func TestHermesUnreadFingerprintsParseAgain(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + path := hermesFixture(t, root, "", "s", true) + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + h := newHermesDB(db) + h.revision = hermesRevision(path) + if p := hermesPrintsFor(path, h); p["s"] == "" { + t.Fatalf("fingerprints of a readable store: %v", p) + } + db.Close() + h.revision = "moved" + if p := hermesPrintsFor(path, h); p != nil { + t.Fatalf("a closed store's fingerprints read as %v", p) + } + // the same size and time as what was parsed: only the fingerprint can + // tell it changed, and it is unknown + f := file{agent: "hermes", path: path + "#s", hermes: h, rev: "", mod: time.Unix(1790000000, 0)} + s := state{Mod: f.mod.UnixNano(), DBRevision: ""} + cache = map[string]*state{f.path: &s} + t.Cleanup(func() { cache = nil }) + parsed := 0 + parseHook = func() { parsed++ } + t.Cleanup(func() { parseHook = nil }) + mu.Lock() + refresh([]file{f}, nil) + mu.Unlock() + if parsed != 1 { + t.Fatalf("an unknown fingerprint reused a parse (%d parsed)", parsed) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 5afb21a51..474dd2461 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -755,7 +755,7 @@ func refresh(want, all []file) { if f.cold { continue // in a stopped WSL distro: what was read of it stands } - if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.hermes.revision == "" || s.DBRevision != f.hermes.revision)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { + if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.rev == "" || s.DBRevision != f.rev)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { todo = append(todo, f) } } @@ -975,6 +975,7 @@ func Reset() { directoryCache.Unlock() resetCalls() wslReset() + forgetHermesPrints() mu.Lock() defer mu.Unlock() saved() From 2b2d5fd8e44fa85d585946d48b3d06b569d98bcc Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 00:25:28 +0800 Subject: [PATCH 11/92] sessions: a Hermes store's path is resolved once per listing, not per session (#2776) hermesFiles built each session's id with hermesID(path, sid), which resolves the store's path (filepath.Abs and EvalSymlinks, a stat per folder) and hashes it, for every session of the store, on every listing. Every Sessions endpoint enumerates every agent, so this ran on each poll. hermesStoreID now resolves and hashes once per store; each session's id is that prefix and its own id, the same string as before. Test: TestHermesStoreResolvedOncePerListing counts resolves for a store of 10 sessions (red on the old code: 12 resolves for 10 sessions) and checks a file's key still equals hermesID's. Measured on the synthetic sandbox HOME (2000 Hermes sessions beside 3000 Claude Code and 1500 Codex), warm index: a CPU profile of 9 warm requests (manage?agent=claude, manage?agent=codex, /api/sessions, three times; 33 enumerations) put 0.96 s CPU in hermesID, ~30 ms per enumeration of 2000 sessions. After, that is one resolve per store. Run: go test ./internal/sessions -run TestHermes -count=1 (ok); gofmt -l clean. Full suite and cross-OS vet are recorded on the last commit of this series. --- internal/sessions/hermes.go | 22 +++++++++--- internal/sessions/hermes_fingerprint_test.go | 37 ++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/internal/sessions/hermes.go b/internal/sessions/hermes.go index 43c5e9995..0cdbdae24 100644 --- a/internal/sessions/hermes.go +++ b/internal/sessions/hermes.go @@ -52,7 +52,13 @@ func HermesDirs() []string { return out } +// canonicalHook, when a test sets it, runs on each canonicalHermesPath. +var canonicalHook func() + func canonicalHermesPath(path string) string { + if canonicalHook != nil { + canonicalHook() + } if abs, err := filepath.Abs(path); err == nil { path = abs } @@ -62,11 +68,16 @@ func canonicalHermesPath(path string) string { return filepath.Clean(path) } -func hermesID(path, sid string) string { - // Include the store even for the default profile so selecting another home - // cannot collide with a previously indexed store or a copied session id. +func hermesID(path, sid string) string { return hermesStoreID(path) + "-" + sid } + +// hermesStoreID is what a store's session ids begin with. Include the store +// even for the default profile so selecting another home cannot collide +// with a previously indexed store or a copied session id. Resolving the +// path walks every folder in it (EvalSymlinks), so it is done once per +// store, not once per session. +func hermesStoreID(path string) string { h := sha256.Sum256([]byte(canonicalHermesPath(path))) - return "h" + hex.EncodeToString(h[:8]) + "-" + sid + return "h" + hex.EncodeToString(h[:8]) } type hermesDB struct { @@ -291,6 +302,7 @@ func hermesFiles() []file { continue } prints := hermesPrintsFor(path, store) + storeID := hermesStoreID(path) messageLast, usageLast := "0", "0" if store.messages["session_id"] && store.messages["timestamp"] { messageLast = "COALESCE((SELECT MAX(timestamp) FROM messages m WHERE m.session_id = sessions.id), 0)" @@ -313,7 +325,7 @@ func hermesFiles() []file { if rows.Scan(&sid, &start, &end, &last, &messageAt, &usageAt) != nil || sid == "" { continue } - id := hermesID(path, sid) + id := storeID + "-" + sid out = append(out, file{ agent: "hermes", key: "hermes:" + id, diff --git a/internal/sessions/hermes_fingerprint_test.go b/internal/sessions/hermes_fingerprint_test.go index 18f1e0176..47922716a 100644 --- a/internal/sessions/hermes_fingerprint_test.go +++ b/internal/sessions/hermes_fingerprint_test.go @@ -97,3 +97,40 @@ func TestHermesUnreadFingerprintsParseAgain(t *testing.T) { t.Fatalf("an unknown fingerprint reused a parse (%d parsed)", parsed) } } + +// A store's path is resolved (EvalSymlinks walks every folder in it) once +// per listing, not once per session: 2000 sessions spent ~30ms on it per +// poll (#2776). +func TestHermesStoreResolvedOncePerListing(t *testing.T) { + setup(t) + root := filepath.Join(t.TempDir(), "hermes") + t.Setenv("HERMES_HOME", root) + path := hermesFixture(t, root, "", "s0", true) + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for i := 1; i < 10; i++ { + sid := "s" + string(rune('0'+i)) + if _, err := db.Exec(`INSERT INTO sessions (id, title, started_at) VALUES (?, 'x', 1790000000)`, sid); err != nil { + t.Fatal(err) + } + } + var n atomic.Int32 + canonicalHook = func() { n.Add(1) } + t.Cleanup(func() { canonicalHook = nil }) + mu.Lock() + files := hermesFiles() + closeDBs() + mu.Unlock() + if len(files) != 10 { + t.Fatalf("%d files, want 10", len(files)) + } + if got := int(n.Load()); got >= len(files) { + t.Fatalf("the store's path was resolved %d times for %d sessions", got, len(files)) + } + if want := "hermes:" + hermesID(path, files[0].sid); files[0].key != want { + t.Fatalf("key %q, want %q", files[0].key, want) + } +} From 38f6bee23e278aaf3b49ad9572840c218c1bcde2 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 02:09:23 +0800 Subject: [PATCH 12/92] sessions: the manage page reads its agents' files once, and only the agents it shows (#2776) GET /api/sessions/manage went over every agent's session files three times: sessions.Agents() for the counts, sessions.List(All) only to build the set that keeps a gateway session its agent keeps too from being counted twice, and sessions.ListAgent for the list. List(All) also read every agent's changed files again and put every session together, prices and titles included, to take its id. So a page showing Claude Code's sessions parsed Hermes's and Codex's writes too. sessions.Manage now does it in one pass over the files, under one hold of the locks: the counts, the ids of the sessions of the agents that have gateway sessions (nativeIDs: the id from the file's key, or from its parse for the agents that write it inside the file, idInFile, which are the only ones read), then the picked agent's list. The handler's pick runs as a callback so the counts can include the gateway sessions. A change to an agent not shown and with no gateway sessions waits for a page that shows it. assemble's id rule moved into sessionID, which both use. That set was also wrong in two ways. List leaves out a session nothing was said in and stops at 5000 (All), while the list beside it keeps every one, so a gateway session whose agent's file was empty (or among the oldest of more than 5000) was counted twice and listed once. The set is now every native session, the same as the list's, and POST /api/sessions/delete, which tells a listed gateway session from a native one, uses it too (sessions.NativeIDs). docs/subsystems/gateway-sessions.md says so. Tests: - TestManageReadsOnlyTheAgentsItShows: Codex's files changed, Claude Code's page parses none of them; asked for Codex's ids it reads them; the native ids equal the list's, the empty session included. Red with Manage reading every file as List(All) did ("read 2 of them"). - TestManageCountsAGatewaySessionTheAgentKeepsOnce: a gateway session whose Claude Code file has nothing said in it is counted once. Red on the old handler: "one session listed, counted [{claude 2}]". Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex, 2000 Hermes sessions; no gateway sessions), CPU time of the request (load average ~250 from other sessions, so wall times are noisy), the parent bbee24810 against this change, the same run of each: first manage?agent=claude after a restart 2164 -> 627 ms CPU (15697 -> 10554 ms wall) warm manage?agent=claude 173-222 ms -> 64-88 ms CPU warm manage?agent=hermes 176-243 ms -> 56-70 ms CPU warm manage?agent=codex 237-269 ms -> 155-162 ms CPU (after its first, which reads Codex's model/effort) Run: go test ./internal/sessions -count=1, go test ./internal/gui -count=1; gofmt -l clean; go vet. Full suite and cross-OS vet are recorded on the last commit of this series. --- docs/subsystems/gateway-sessions.md | 7 +- internal/gui/sessions_manage.go | 92 ++++++++++----------- internal/gui/sessions_manage_native_test.go | 61 ++++++++++++++ internal/sessions/manage.go | 89 +++++++++++++++++++- internal/sessions/manage_read_test.go | 77 +++++++++++++++++ internal/sessions/sessions.go | 29 +++++-- 6 files changed, 299 insertions(+), 56 deletions(-) create mode 100644 internal/gui/sessions_manage_native_test.go create mode 100644 internal/sessions/manage_read_test.go diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 812e620dc..e26c7672b 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -40,7 +40,12 @@ by its prompt. `passOnCaller` sends the mark on to a remote magpie beside the session, and no vendor is sent either (`TestDshMarksSessionAndCompaction`). When the same identity is present in a native session, the native session wins -and the gateway projection is omitted. Gateway projections have no path, +and the gateway projection is omitted. On `/api/sessions/manage`, in its +counts as in its list, and on `/api/sessions/delete`, a native session is any +session file the agent keeps, one nothing was said in too, with no limit +(`sessions.NativeIDs`); one pass over the agents' files (`sessions.Manage`) +reads only the agent shown and the agents with gateway sessions (#2776). +Gateway projections have no path, resume command or terminal action: the agent's own files of them are not on this computer. Their rows carry `gateway: true`; the Sessions page groups them under "Seen through the gateway" rather than "No folder", and their size is the diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.go index 7b6cd6b0e..f56017237 100644 --- a/internal/gui/sessions_manage.go +++ b/internal/gui/sessions_manage.go @@ -130,55 +130,58 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { Trash: trashJSON(looks), TrashDir: tilde(sessions.TrashDir()), Recording: settings.Load().GatewayConversations, Recorded: sessions.HasGatewayConversations()} want := r.URL.Query().Get("agent") - counts := map[string]*manageAgentJSON{} - for _, a := range sessions.Agents() { - j := manageAgentJSON{AgentCount: a, Name: a.Agent, Icon: "generic"} - if l := looks[a.Agent]; l != nil { - j.Name, j.Icon = l.SharedName(), l.Icon - } - counts[a.Agent] = &j - } gateway := listedGateway(usage.GatewaySessions(time.Time{}, nil)) - nativeCounts := map[string]map[string]bool{} - for _, s := range sessions.List(sessions.All) { - if nativeCounts[s.Agent] == nil { - nativeCounts[s.Agent] = map[string]bool{} - } - nativeCounts[s.Agent][s.ID] = true + // a gateway session its agent keeps too is counted once; only the + // agents with gateway sessions, and the one shown, are read (#2776) + of := map[string]bool{} + for _, g := range gateway { + of[g.Agent] = true } - for _, s := range gateway { - if nativeCounts[s.Agent][s.ID] { - continue - } - j := counts[s.Agent] - if j == nil { - j = &manageAgentJSON{AgentCount: sessions.AgentCount{Agent: s.Agent}, Name: s.Agent, Icon: "generic"} - if l := looks[s.Agent]; l != nil { + view := sessions.Manage(of, func(agents []sessions.AgentCount, native map[string]map[string]bool) string { + counts := map[string]*manageAgentJSON{} + for _, a := range agents { + j := manageAgentJSON{AgentCount: a, Name: a.Agent, Icon: "generic"} + if l := looks[a.Agent]; l != nil { j.Name, j.Icon = l.SharedName(), l.Icon } - counts[s.Agent] = j + counts[a.Agent] = &j } - j.Count++ - // what magpie keeps of it can be deleted, whatever the agent - j.Deletable = true - } - for _, j := range counts { - out.Agents = append(out.Agents, *j) - } - sort.Slice(out.Agents, func(i, j int) bool { - if out.Agents[i].Count != out.Agents[j].Count { - return out.Agents[i].Count > out.Agents[j].Count + for _, s := range gateway { + if native[s.Agent][s.ID] { + continue + } + j := counts[s.Agent] + if j == nil { + j = &manageAgentJSON{AgentCount: sessions.AgentCount{Agent: s.Agent}, Name: s.Agent, Icon: "generic"} + if l := looks[s.Agent]; l != nil { + j.Name, j.Icon = l.SharedName(), l.Icon + } + counts[s.Agent] = j + } + j.Count++ + // what magpie keeps of it can be deleted, whatever the agent + j.Deletable = true } - return out.Agents[i].Agent < out.Agents[j].Agent + for _, j := range counts { + out.Agents = append(out.Agents, *j) + } + sort.Slice(out.Agents, func(i, j int) bool { + if out.Agents[i].Count != out.Agents[j].Count { + return out.Agents[i].Count > out.Agents[j].Count + } + return out.Agents[i].Agent < out.Agents[j].Agent + }) + if _, ok := counts[want]; ok { + return want + } + if len(out.Agents) > 0 { + return out.Agents[0].Agent + } + return "" }) - if _, ok := counts[want]; ok { - out.Agent = want - } - if out.Agent == "" && len(out.Agents) > 0 { - out.Agent = out.Agents[0].Agent - } + out.Agent = view.Agent if out.Agent != "" { - list := sessions.ListAgent(out.Agent) + list := view.Sessions var modelEffort map[string][]sessions.ModelEffort if out.Agent == "codex" { modelEffort = usage.CodexModelEffort(usage.All) @@ -243,12 +246,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { return } // the gateway sessions as listed: those with no native session - native := map[string]bool{} - for _, s := range sessions.List(sessions.All) { - if s.Agent == in.Agent { - native[s.ID] = true - } - } + native := sessions.NativeIDs(map[string]bool{in.Agent: true})[in.Agent] listed := map[string]usage.GatewaySession{} for _, g := range listedGateway(usage.GatewaySessions(time.Time{}, nil)) { if g.Agent == in.Agent && !native[g.ID] { diff --git a/internal/gui/sessions_manage_native_test.go b/internal/gui/sessions_manage_native_test.go new file mode 100644 index 000000000..5d2a76934 --- /dev/null +++ b/internal/gui/sessions_manage_native_test.go @@ -0,0 +1,61 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" +) + +// A gateway session whose agent keeps it too is one session, in the count +// as in the list, though nothing was said in the agent's own file: the +// count told them apart through List, which leaves such a file out (and +// stops at 5000), while the list kept every one (#2776). +func TestManageCountsAGatewaySessionTheAgentKeepsOnce(t *testing.T) { + h := sandboxHome(t) + sessions.Reset() + t.Cleanup(sessions.Reset) + const id = "3c9e1f2a-5b6d-4e7f-8a9b-0c1d2e3f4a5b" + dir := filepath.Join(h, ".claude", "projects", "-work-app") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + line := `{"type":"file-history-snapshot","messageId":"m","snapshot":{"messageId":"m","trackedFileBackups":{},"timestamp":"2026-09-19T08:00:00.000Z"},"isSnapshotUpdate":false}` + "\n" + if err := os.WriteFile(filepath.Join(dir, id+".jsonl"), []byte(line), 0o644); err != nil { + t.Fatal(err) + } + usage.Append(usage.Record{Time: time.Now().Add(-2 * time.Hour), Agent: "claude", Session: id, Provider: "deepseek", Model: "deepseek-flash", Input: 40, Output: 9, Status: 200}) + mux := http.NewServeMux() + sessionManageRoutes(mux, folderOnly{}) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/sessions/manage?agent=claude", nil)) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var m struct { + Agents []struct { + Agent string `json:"agent"` + Count int `json:"count"` + } `json:"agents"` + Agent string `json:"agent"` + Sessions []struct { + ID string `json:"id"` + Gateway bool `json:"gateway"` + } `json:"sessions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil { + t.Fatal(err) + } + if m.Agent != "claude" || len(m.Sessions) != 1 || m.Sessions[0].ID != id || m.Sessions[0].Gateway { + t.Fatalf("listed %q: %+v", m.Agent, m.Sessions) + } + if len(m.Agents) != 1 || m.Agents[0].Count != 1 { + t.Fatalf("one session listed, counted %+v", m.Agents) + } +} diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index 46c3bc6fc..da52f5cd2 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -78,8 +78,12 @@ func Agents() []AgentCount { mu.Lock() defer mu.Unlock() defer closeDBs() + return agentCounts(allFiles()) +} + +func agentCounts(all []file) []AgentCount { n := map[string]map[string]bool{} - for _, f := range allFiles() { + for _, f := range all { if n[f.agent] == nil { n[f.agent] = map[string]bool{} } @@ -101,6 +105,47 @@ func Agents() []AgentCount { // ListAgent is every session of one agent, the most recently active first, // with no limit; one nothing was said in is listed too, to be cleared away. func ListAgent(agent string) []Managed { + dbReadMu.Lock() + defer dbReadMu.Unlock() + mu.Lock() + defer mu.Unlock() + loadCache() + defer closeDBs() + return listAgent(agent, allFiles()) +} + +// NativeIDs are the ids of every session the agents named keep themselves, +// by agent: one nothing was said in too, as ListAgent lists it. It tells a +// gateway session an agent keeps from one only magpie saw. Only the named +// agents' files are looked at, and of those only the ones whose session id +// is inside the file are read when they changed. +func NativeIDs(agents map[string]bool) map[string]map[string]bool { + dbReadMu.Lock() + defer dbReadMu.Unlock() + mu.Lock() + defer mu.Unlock() + loadCache() + defer closeDBs() + return nativeIDs(agents, allFiles()) +} + +// ManageView is the session management page, read in one pass over every +// agent's files: the agents with sessions, the ids of the sessions of those +// asked for (as NativeIDs), and the agent shown with its sessions (as +// ListAgent). +type ManageView struct { + Agents []AgentCount + Native map[string]map[string]bool + Agent string + Sessions []Managed +} + +// Manage reads the management page. pick, given the counts and the native +// ids of the agents in native, names the agent to list ("" for none); it +// runs under the sessions lock and must not call back into this package. +// Only native's agents and the one picked are read: a change to another +// agent's sessions waits for a page that shows it (#2776). +func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[string]bool) string) ManageView { dbReadMu.Lock() defer dbReadMu.Unlock() mu.Lock() @@ -108,6 +153,48 @@ func ListAgent(agent string) []Managed { loadCache() defer closeDBs() all := allFiles() + v := ManageView{Agents: agentCounts(all), Native: nativeIDs(native, all)} + v.Agent = pick(v.Agents, v.Native) + if v.Agent != "" { + v.Sessions = listAgent(v.Agent, all) + } + return v +} + +// idInFile says which agents' session ids are read from inside the +// session's file, not taken from its name (as assemble does). +func idInFile(agent string) bool { + switch agent { + case "codex", "pi", "omp", "dsh", "grok", "droid": + return true + } + return false +} + +func nativeIDs(agents map[string]bool, all []file) map[string]map[string]bool { + groups := map[string][]file{} + var want []file + for _, f := range all { + if !agents[f.agent] { + continue + } + groups[f.key] = append(groups[f.key], f) + if idInFile(f.agent) { + want = append(want, f) + } + } + refresh(want, all) + out := map[string]map[string]bool{} + for a := range agents { + out[a] = map[string]bool{} + } + for _, fs := range groups { + out[fs[0].agent][sessionID(fs)] = true + } + return out +} + +func listAgent(agent string, all []file) []Managed { groups := map[string][]file{} var mine []file for _, f := range all { diff --git a/internal/sessions/manage_read_test.go b/internal/sessions/manage_read_test.go new file mode 100644 index 000000000..076ed4a77 --- /dev/null +++ b/internal/sessions/manage_read_test.go @@ -0,0 +1,77 @@ +package sessions + +import ( + "os" + "path/filepath" + "sort" + "testing" + "time" +) + +// The management page of one agent reads that agent's changed files, and +// those of the agents whose gateway sessions it tells apart, not every +// agent's (#2776): it read them all to build that set, through List(All). +func TestManageReadsOnlyTheAgentsItShows(t *testing.T) { + _, codex := setup(t) + claude := func([]AgentCount, map[string]map[string]bool) string { return "claude" } + Manage(map[string]bool{}, claude) + now := time.Now() + err := filepath.WalkDir(filepath.Join(codex, "sessions"), func(p string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() { + now = now.Add(time.Second) + return os.Chtimes(p, now, now) + } + return err + }) + if err != nil { + t.Fatal(err) + } + parsed := 0 + parseHook = func() { parsed++ } + t.Cleanup(func() { parseHook = nil }) + + v := Manage(map[string]bool{}, claude) + if parsed != 0 { + t.Fatalf("Codex's files changed and Claude Code's page read %d of them", parsed) + } + if v.Agent != "claude" || len(v.Sessions) == 0 { + t.Fatalf("listed %q with %d sessions", v.Agent, len(v.Sessions)) + } + counted := false + for _, a := range v.Agents { + counted = counted || a.Agent == "codex" && a.Count == 1 + } + if !counted { + t.Fatalf("codex not counted: %+v", v.Agents) + } + + // asked for Codex's ids: its changed files are read, as the id is in them + v = Manage(map[string]bool{"codex": true, "claude": true}, claude) + if parsed == 0 { + t.Fatal("Codex's ids were asked for and its changed files not read") + } + if !v.Native["codex"]["01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd"] { + t.Fatalf("codex ids %v", v.Native["codex"]) + } + // the same ids as the agent's list: one nothing was said in too + var listed, native []string + for _, m := range v.Sessions { + listed = append(listed, m.ID) + } + for id := range v.Native["claude"] { + native = append(native, id) + } + sort.Strings(listed) + sort.Strings(native) + if len(listed) < 2 || len(listed) != len(native) { + t.Fatalf("claude list %v, native ids %v", listed, native) + } + for i := range listed { + if listed[i] != native[i] { + t.Fatalf("claude list %v, native ids %v", listed, native) + } + } + if got := NativeIDs(map[string]bool{"codex": true}); len(got) != 1 || len(got["codex"]) != 1 { + t.Fatalf("NativeIDs: %v", got) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 474dd2461..e59b449c5 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1041,20 +1041,38 @@ func List(limit int) []Session { return out } -// assemble puts a session together from its files' parses. -func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { - // the session's own file first; for Codex the earliest segment +// sortSessionFiles puts a session's own file first; for Codex the earliest +// segment. +func sortSessionFiles(fs []file) { sort.SliceStable(fs, func(i, j int) bool { if fs[i].main != fs[j].main { return fs[i].main } return filepath.Base(fs[i].path) < filepath.Base(fs[j].path) }) +} + +// sessionID is a session's id: its key's, or for an agent that writes it +// inside the file (idInFile), what its own file's parse read. +func sessionID(fs []file) string { + sortSessionFiles(fs) + id := strings.TrimPrefix(fs[0].key, fs[0].agent+":") + if idInFile(fs[0].agent) && fs[0].main { + if st := cache[fs[0].path]; st != nil && st.ID != "" { + id = st.ID + } + } + return id +} + +// assemble puts a session together from its files' parses. +func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { + sortSessionFiles(fs) s := Session{Agent: fs[0].agent, Path: fs[0].path, Models: []Model{}, WSL: fs[0].wsl} for _, f := range fs { s.ReadOnly = s.ReadOnly || f.readOnly } - s.ID = strings.TrimPrefix(fs[0].key, s.Agent+":") + s.ID = sessionID(fs) var custom, named, first string models := map[string]*Model{} for _, f := range fs { @@ -1078,9 +1096,6 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { if first == "" { first = st.First } - if (s.Agent == "codex" || s.Agent == "pi" || s.Agent == "omp" || s.Agent == "dsh" || s.Agent == "grok" || s.Agent == "droid") && st.ID != "" && f.path == fs[0].path { - s.ID = st.ID - } } if s.Agent == "codex" && st.CodexNickname != "" { s.Nickname = st.CodexNickname From 81029fc63c7f2b3f76a0ca816479dff1cada9fc2 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 02:22:28 +0800 Subject: [PATCH 13/92] sessions: the overview's stats and their native sessions come of one pass over the files (#2776) combinedSessionStats, behind /api/sessions/stats and /overview (each range read again in the background when its memo is over 10 s old, so on every 15 s poll of the Sessions page), took sessions.StatsFor and then sessions.List(All) only for the agent|id set that keeps a gateway session the agent keeps too from counting twice: two passes over every agent's files, each refreshing them all. sessions.StatsAndNative gives both from StatsFor's one pass: the same set, a session List would list (one nothing was said in still left out, as before), but with no 5000 limit, so a gateway session whose native one is among the oldest of a long history is no longer counted again. Test: TestStatsAndNativeOnePass: one pass over the files (filesHook, new), and the same keys as List(All) on the fixtures. Red with StatsAndNative written as the old pair of calls: "2 passes over the files". Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex, 2000 Hermes sessions), combinedSessionStats warm after a restart, CPU time (load average ~250, wall times noisy), parent 8e2b1dce6 against this change, 4 rounds each: days=30 94-99 ms -> 57-62 ms CPU days=0 107-130 ms -> 68-74 ms CPU first after a restart (days=30) 558 -> 510 ms CPU Run at this commit (the series' last; it covers 0179cef63, bbee24810 and 8e2b1dce6 too), on a machine at load average ~250-500: - go test ./... -timeout 45m: 60 packages ok, sessions (869.8s), usage ok. Red only under that load, all green when run again: - internal/agent and internal/gateway timed out at 45m in tests that don't touch sessions (TestPiOffersItsOwnOpenAICodexModels, TestVisionSettingPicksTheDescriber). Run again with -timeout 90m: agent ok (1394.2s), gateway ok (1546.9s). - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set took 44.6s under load; it is #1375. Alone: ok. - internal/plugin TestGatewayHookMixedPiPackage: "starting plugins: context deadline exceeded" after 718s (bun's install cache was slow). Alone: ok (163.6s). No issue found for it. - gofmt -l: clean. - GOOS=windows go vet ./...: ok. - GOOS=linux go vet -tags nogui ./...: ok. Without the tag, vet stops in wails v3's own linux files (undefined: pointer, cgo off when vetting across OSes from macOS); go.mod is untouched here. - No GUI assets changed, so the GUI suite was not run. --- internal/gui/sessions.go | 6 +---- internal/sessions/sessions.go | 7 ++++++ internal/sessions/stats.go | 27 +++++++++++++++++++++- internal/sessions/stats_native_test.go | 32 ++++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 internal/sessions/stats_native_test.go diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index fe1b46e62..17ce06eca 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -452,11 +452,7 @@ func statsFor(days int) sessions.Stats { } func combinedSessionStats(days int) sessions.Stats { - st := sessions.StatsFor(days) - nativeKeys := map[string]bool{} - for _, s := range sessions.List(sessions.All) { - nativeKeys[s.Agent+"|"+s.ID] = true - } + st, nativeKeys := sessions.StatsAndNative(days) var since time.Time if days > 0 && st.From != "" { since, _ = time.ParseInLocation(time.DateOnly, st.From, time.Local) diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index e59b449c5..dd96027b5 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -469,7 +469,14 @@ func ccFiles(agent, dir string) []file { } // allFiles are every agent's session files. +// filesHook, when a test sets it, runs on each pass over every agent's +// files. +var filesHook func() + func allFiles() []file { + if filesHook != nil { + filesHook() + } var out []file for _, fs := range [][]file{callFiles(), openCodeFiles(), piFiles(), wslFiles("pi", "omp", "kimi"), zcodeFiles(), dshFiles(), clineFiles(), ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn")), diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index c4aa927fd..c8035dc3e 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -108,7 +108,19 @@ func StatsFor(days int) Stats { // StatsAt is StatsFor as if it were now. func StatsAt(days int, now time.Time) Stats { return statsAt(days, now) } -func statsAt(days int, now time.Time) Stats { +// StatsAndNative is StatsFor, and the agent|id of every session List would +// list, with no limit: what tells a gateway session the agent keeps too +// from one only magpie saw. Both come of one pass over the files, as the +// overview asks for both on every poll (#2776). +func StatsAndNative(days int) (Stats, map[string]bool) { + native := map[string]bool{} + return statsIn(days, time.Now(), native), native +} + +func statsAt(days int, now time.Time) Stats { return statsIn(days, now, nil) } + +// statsIn is statsAt, filling native as StatsAndNative says when not nil. +func statsIn(days int, now time.Time, native map[string]bool) Stats { now = now.In(time.Local) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) var since time.Time @@ -131,6 +143,19 @@ func statsAt(days int, now time.Time) Stats { refresh(files, files) identities := codexIdentitySnapshot(files) taskTitles := codexSubagentTaskTitles(files) + if native != nil { + groups := map[string][]file{} + for _, f := range files { + groups[f.key] = append(groups[f.key], f) + } + price := pricer() + for _, fs := range groups { + // as List: a session nothing was said in is not listed + if s, ok := assemble(fs, price); ok { + native[s.Agent+"|"+s.ID] = true + } + } + } var want []file for _, f := range files { if !f.mod.Before(since) { diff --git a/internal/sessions/stats_native_test.go b/internal/sessions/stats_native_test.go new file mode 100644 index 000000000..66b988563 --- /dev/null +++ b/internal/sessions/stats_native_test.go @@ -0,0 +1,32 @@ +package sessions + +import "testing" + +// The overview's stats and the sessions that tell its gateway sessions +// apart come of one pass over every agent's files (#2776): it took a second +// pass, through List(All), on every refresh. The keys are List's. +func TestStatsAndNativeOnePass(t *testing.T) { + setup(t) + want := map[string]bool{} + for _, s := range List(All) { + want[s.Agent+"|"+s.ID] = true + } + passes := 0 + filesHook = func() { passes++ } + t.Cleanup(func() { filesHook = nil }) + st, native := StatsAndNative(0) + if passes != 1 { + t.Fatalf("%d passes over the files", passes) + } + if len(st.Sessions) == 0 { + t.Fatalf("no stats: %+v", st) + } + if len(native) != len(want) || len(want) < 2 { + t.Fatalf("native %v, List's %v", native, want) + } + for k := range want { + if !native[k] { + t.Fatalf("native %v, List's %v", native, want) + } + } +} From 1a3b9268860263f263a2c832b1f9b6d1b57e3fa0 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 03:52:16 +0800 Subject: [PATCH 14/92] =?UTF-8?q?agent:=20a=20[1m]=20main=20beside=20a=20s?= =?UTF-8?q?maller=20tier=20is=20told=20its=20own=201M,=20the=20tier=20held?= =?UTF-8?q?=20to=20its=20own=20(=E5=A4=9A=E5=96=9D=E7=83=AD=E6=B0=B4=20on?= =?UTF-8?q?=20Discord)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 多喝热水 had Full window on, Claude Code's main on a [1m] DeepSeek 4.1 and a smaller tier beside it. magpie told Claude Code the least tier's window (CLAUDE_CODE_MAX_CONTEXT_TOKENS=246000), so it read 246K as the main model's window and asked why 1M never showed. It is also the window Claude Code falls back to when it stops taking the main for 1M. Now a [1m] main of magpie's beside a tier that isn't takes the layout Desktop already has (desktopPlan): the window told is the main's own (1M), each smaller tier gets modelSettings..autoCompactWindow at its own window, and the working window goes in the top-level autoCompactWindow in place of the env (none under Full window). A [1m] main alone, a Claude main and the user's own env and settings are as before. Run: - TestClaudeContextWindow's new case (tier beside a [1m] main, with and without Full window, then the tier gone) fails on the old code (window "128000", no tier entry, env compact 272000) and passes now. - Real Claude Code 2.1.302 in a sandbox CLAUDE_CONFIG_DIR on the live gateway, main workbuddy/deepseek-v4.1-flash[1m], haiku workbuddy/hy3: /context shows the main at 272k and hy3 at 192k without Full window, and the main at 1m and hy3 at 192k with it. With the old layout's env of 246000, hy3 showed 246k, past its own 192k. A real request on the main replied "ok". - gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... clean; go build ./... ok. - go test -timeout 45m -count=1 ./... at 95ef45fda: every package ok. After rebasing onto a595f1559 (no internal/agent changes there), go test ./internal/agent/ again: ok. --- internal/agent/claude.go | 36 +++++++++++++++++++-------- internal/agent/claude_budget.go | 10 +++++++- internal/agent/claude_context_test.go | 32 +++++++++++++++++++++--- 3 files changed, 64 insertions(+), 14 deletions(-) diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 2d74224eb..e8634ee3e 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -1098,10 +1098,12 @@ func claudeIn(at place) *Agent { return cmp.Or(s.Compact(), -1) } var models []claudeBudget - shown, _ := provider.CatalogFor("claude-desktop") - for _, e := range shown { - if id := gateway.DesktopID(e); claudeName(id) == "" { - models = append(models, claudeBudget{id: id, window: e.Context, long: gateway.DesktopListed1M(e), compact: work(e.ID)}) + if desktopOn() { + shown, _ := provider.CatalogFor("claude-desktop") + for _, e := range shown { + if id := gateway.DesktopID(e); claudeName(id) == "" { + models = append(models, claudeBudget{id: id, window: e.Context, long: gateway.DesktopListed1M(e), compact: work(e.ID)}) + } } } if main != "" { @@ -1115,13 +1117,13 @@ func claudeIn(at place) *Agent { for _, t := range claudeTiers { refs = append(refs, tiers[t]) } - for _, v := range refs { + for i, v := range refs { m, _ := tierAt(v) bare := strings.TrimSuffix(m, "[1m]") if v == "" || claudeModel(bare) || provider.ClaudeGroup(bare) { continue } - models = append(models, claudeBudget{id: spell(v), window: window[bare], long: strings.HasSuffix(v, "[1m]"), compact: work(bare)}) + models = append(models, claudeBudget{id: spell(v), window: window[bare], long: strings.HasSuffix(v, "[1m]"), main: i == 0, compact: work(bare)}) } // the one for every model else, as the variable gave it: none // on a Claude main model, which Anthropic runs to its own @@ -1152,16 +1154,22 @@ func claudeIn(at place) *Agent { // writeWindow tells Claude Code the window of the models it runs on // (claudeWindow). While Claude Desktop runs on magpie too, it is the // largest of theirs and each model below it gets its own - // (desktopPlan); with a CLAUDE_CODE_AUTO_COMPACT_WINDOW of the user's, - // which takes precedence over those, the least of them, as one value - // serves them all. One the user set is theirs. + // (desktopPlan), and so while the main model is a [1m] one beside a + // tier that isn't: the main's own window, with each tier below it held + // to the tier's (多喝热水 on Discord: the least tier's 246K beside a + // [1m] DeepSeek read as the main's window under Full window, and was + // the one it fell back to whenever Claude Code stopped taking it for + // 1M). With a + // CLAUDE_CODE_AUTO_COMPACT_WINDOW of the user's, which takes + // precedence over those, the least of them, as one value serves them + // all. One the user set is theirs. writeWindow := func(main string, tiers map[string]string) error { budgeted = false if env(claudeContextEnv) != "" && !windowOurs() { forget(windowKey) return dropBudgets() } - if desktopOn() && (env(claudeCompactEnv) == "" || compactOurs()) { + if (desktopOn() || claudeLongMain(main) && claudeWindow(main, tiers) > 0) && (env(claudeCompactEnv) == "" || compactOurs()) { top, def, entries := desktopPlan(main, tiers) if top <= 0 { return dropWindow() @@ -2329,6 +2337,14 @@ func claudeOwnCompact(path, model string) bool { return false } +// claudeLongMain says main is a model of magpie's Claude Code takes for 1M +// by its "[1m]", not one of Claude's own, which Anthropic runs to its own. +func claudeLongMain(main string) bool { + m, _ := tierAt(main) + bare := strings.TrimSuffix(m, "[1m]") + return bare != m && !claudeModel(bare) && !provider.ClaudeGroup(bare) +} + // claudeWindow is the context window to tell Claude Code for the models it // runs on, 0 when magpie doesn't know it. One value serves every model not // marked [1m]: the main model's, or when that one is marked, the smallest of diff --git a/internal/agent/claude_budget.go b/internal/agent/claude_budget.go index d9bd14b77..07f78823e 100644 --- a/internal/agent/claude_budget.go +++ b/internal/agent/claude_budget.go @@ -1,6 +1,7 @@ package agent import ( + "cmp" "encoding/json" "strconv" "strings" @@ -25,6 +26,10 @@ type claudeBudget struct { id string // as Claude Code is handed it: its key under modelSettings window int // its window, 0 when unknown long bool // Claude Code takes it for 1M by its id ("[1m]") + // Claude Code's main model: a long one's window is the one told too, + // so the main runs to its own should Claude Code stop taking it for + // 1M, and nothing written reads as holding it to a smaller tier's + main bool // the auto-compact window magpie gives it: 0 for the top-level one // (base), below 0 for none, its whole window compact int @@ -58,8 +63,11 @@ func budgetPath(id string) string { // top to its own window, as magpie can't put theirs right. func claudePlan(models []claudeBudget, base int, theirs map[string]string) (top int, entries map[string]int) { for _, m := range models { - if !m.long && m.window > top { + switch { + case !m.long && m.window > top: top = m.window + case m.long && m.main: + top = max(top, cmp.Or(m.window, claudeLong)) } } for _, m := range models { diff --git a/internal/agent/claude_context_test.go b/internal/agent/claude_context_test.go index fede63d5f..4ecc985ac 100644 --- a/internal/agent/claude_context_test.go +++ b/internal/agent/claude_context_test.go @@ -7,6 +7,7 @@ import ( "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" ) // TestClaudeContextWindow: Claude Code takes a model it doesn't know for a @@ -53,14 +54,39 @@ func TestClaudeContextWindow(t *testing.T) { t.Fatalf("a model of no known window keeps the last one's: %q", window()) } // a 1M model is marked [1m], which Claude Code takes for 1M whatever - // the window says; a tier that isn't is told its own + // the window says; beside a tier that isn't, the window told is the + // main's own, and the tier compacts by its own (多喝热水 on Discord: + // the tier's read as the main's), under Full window and without it set("model", "v/big[1m]") if window() != "" { t.Fatalf("[1m]: %q", window()) } + budget := func(id string) string { v, _ := edit.GetJSON(path, budgetPath(id)); return v } + compact := func() (env, top string) { + env, _ = edit.GetJSON(path, "env."+claudeCompactEnv) + top, _ = edit.GetJSON(path, "autoCompactWindow") + return env, top + } set("haiku", "v/small") - if window() != "128000" { - t.Fatalf("haiku on small beside a [1m] model: %q", window()) + if e, top := compact(); window() != "1000000" || budget("v/small") != "128000" || budget("v/big[1m]") != "" || e != "" || top != "272000" { + t.Fatalf("haiku on small beside a [1m] model: window %q, small %q, big %q, compact env %q, top-level %q", + window(), budget("v/small"), budget("v/big[1m]"), e, top) + } + if err := settings.Save(settings.Settings{FullContext: true}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if e, top := compact(); window() != "1000000" || budget("v/small") != "128000" || e != "" || top != "" { + t.Fatalf("full window: window %q, small %q, compact env %q, top-level %q", window(), budget("v/small"), e, top) + } + if err := settings.Save(settings.Settings{}); err != nil { + t.Fatal(err) + } + set("haiku", "") + if e, top := compact(); window() != "" || budget("v/small") != "" || e != "272000" || top != "" { + t.Fatalf("the tier gone: window %q, small %q, compact env %q, top-level %q", window(), budget("v/small"), e, top) } set("model", "v/mid") if window() != "400000" { From 41f5107b91f1b0457cfad0b00ec0aac42e600ec3 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:07:33 +0800 Subject: [PATCH 15/92] provider: the zed mover's min is 0.1.10, which picks the organization with a plan (plugins#232) Zed 0.1.10 (plugins 5a83674) no longer always uses the default organization. It picks the saved org, then the default, then a personal org, as long as that org has a paid plan and models on, and it moves the account once when an org answers 402. ReneXiong's default org has no plan and the personal one has zed_student, so every request got a 402. Raising the min lets keepMovedCurrent update every moved user. Run at 1a3b92688 (origin/main) plus this change: - npm view @magpie-community/opencode-zed-auth version --prefer-online: 0.1.10 - gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean. - go test -timeout 45m ./...: 56 ok. The machine was at load ~500 from other sessions' test runs, and internal/agent, cli, davsync, gateway, library and provider hit the 45m timeout (#2108 is gateway's). Six named fails were timing under that load: TestIntentClassifierGroup, TestPluginPageReadsWhatItDeclared, TestSetAnswersWhileDevinAndProvidersHang, TestHostOnBunLackingLibsSaysWhich, TestGatewayHookMixedPiPackage and TestAllowancesCountFromTheReading. Each passes alone at the same head (gateway, gui, plugin, and provider with -run 'TestAllowancesCountFromTheReading|Moved|Migrat|Mover|Zed'). - Not run: the timed-out packages again in full, since the load hadn't dropped. This change is one version string in internal/provider. --- internal/provider/migrate_zed.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/provider/migrate_zed.go b/internal/provider/migrate_zed.go index bdb8f7cb5..9f5b15e31 100644 --- a/internal/provider/migrate_zed.go +++ b/internal/provider/migrate_zed.go @@ -13,7 +13,7 @@ import ( func init() { movers["zed"] = &mover{ pkg: "@magpie-community/opencode-zed-auth", - min: "0.1.9", // a signed-in account whose model list was never read says why; 0.1.8: a free account's plan reads "No plan", as the built-in's; 0.1.6: a failure's status and its sign-in mark as the built-in's; a model token refused while listing marks the account + min: "0.1.10", // the organization with a plan is picked, and a 402 for the saved one moves the account (plugins#232); 0.1.9: a signed-in account whose model list was never read says why; 0.1.8: a free account's plan reads "No plan", as the built-in's; 0.1.6: a failure's status and its sign-in mark as the built-in's; a model token refused while listing marks the account agents: []string{"zed"}, out: func() ([]Moving, error) { var out []Moving From 3608ed782e52ea53ae9a3f91d77e0e5d29ca64e4 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 01:02:21 +0800 Subject: [PATCH 16/92] gui: WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS reaches magpie's WebView2 on Windows again (#2753, LuYquan) The reporter's Nahimic DLL gets WebView2's renderer killed by code integrity and the window goes black; the usual workaround, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--disable-features=RendererCodeIntegrity, never reached magpie's renderer. The cause is not WebView2 skipping the variable because magpie passes its own arguments: Wails v3.0.0-beta.24's loader blanks the variable in its package init (webviewloader.preventEnvAndRegistryOverrides), before any magpie code runs. Seen on the Windows box: a debug build's windowsOptions read "". - internal/webview2env reads the variable at init. It imports only syscall, so by Go's init order (first ready package by import path) it is initialized before os, and so before Wails' loader, which needs os. - windowsOptions sorts it into Wails' DisabledFeatures, EnabledFeatures and AdditionalBrowserArgs. Wails writes msSmartScreenProtection plus the user's features as one --disable-features (Chromium keeps only the last of two), one --enable-features, and the rest as written. A list given twice is merged, each feature once. - Nothing is added by default: RendererCodeIntegrity stays on unless the user asks. ProcessFailed: not done. Wails' edge.Chromium has a ProcessFailedCallback, but setupChromium never sets it, the package is under wails/v3/internal (not importable) and a window's chromium is unexported; Wails has no public event for a dead renderer. Reloading on renderer death needs a change in Wails. Run: - gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean. Builds for the three. - go test ./internal/gui -run 'TestWebView2|TestWindowsOptions' on macOS, and the windows/amd64 test binary on the Windows box (sandbox dir, my own process name): TestWebView2ArgsSurviveWailsInit passes there with os="" (Wails blanked it) and disabled=[RendererCodeIntegrity]. - The real app on the Windows box (portable sandbox, MAGPIE_ADDR :3481, USERPROFILE/APPDATA/LOCALAPPDATA redirected) started with "--disable-features=RendererCodeIntegrity --enable-features=msTestFoo --lang=de": every msedgewebview2.exe of it carries one --disable-features with both features, --enable-features=msTestFoo and --lang=de. Before, the same launch showed only --disable-features=msSmartScreenProtection and --lang=zh-CN. Broken by hand: - windowsOptions reading os.Getenv instead of webview2env.Args: on the Windows box TestWebView2ArgsSurviveWailsInit goes red (os="" disabled=[]). - webView2Args ignoring the env (""): TestWebView2ArgsMergeTheUsers red in "the reporter's" and "twice". - --disable-features treated as an other argument: red in three cases, including the one-switch count. Full suite at origin/main 1a3b92688 + this and the #2757/#2755 GUI commits, go test -timeout 45m ./..., sandbox HOME: gofmt -l clean, vet darwin/linux(nogui)/windows clean, 57 packages ok. At load 475-548 from other sessions' suites, agent (#2544, #2723), gateway (#2108, #2191; TestClaudeAccountsSpentFallBackToCodex #2858), library (#2853), davsync, provider and plugin (#2869; TestGatewayHookMixedPiPackage and TestHostOnBunLackingLibsSaysWhich #2865) ran past 45m, and internal/gui had TestSetAnswersWhileDevinAndProvidersHang red (#1375). Rerun alone: internal/gui and internal/webview2env ok. An earlier full run at d783df46c + this alone: 61 ok, the same load reds. No asset changes, so no GUI run. --- internal/gui/app.go | 9 ++- internal/gui/webview2.go | 69 ++++++++++++++++- internal/gui/webview2_args_test.go | 111 ++++++++++++++++++++++++++++ internal/webview2env/webview2env.go | 19 +++++ 4 files changed, 206 insertions(+), 2 deletions(-) create mode 100644 internal/gui/webview2_args_test.go create mode 100644 internal/webview2env/webview2env.go diff --git a/internal/gui/app.go b/internal/gui/app.go index ffad83a8e..9fd474b3e 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -29,6 +29,7 @@ import ( "github.com/yetone/magpie/internal/shortcut" "github.com/yetone/magpie/internal/stats" "github.com/yetone/magpie/internal/update" + "github.com/yetone/magpie/internal/webview2env" ) //go:embed tray.png @@ -281,11 +282,17 @@ func (h *host) zoomWindows() { // windowsOptions are the app's Windows options. Portable, WebView2 keeps // its profile in data\webview2: left to Wails it is %APPDATA%\magpie.exe, // a folder a portable magpie must not leave behind (#508). Installed, it -// stays there, so what the pages kept isn't lost. +// stays there, so what the pages kept isn't lost. The browser arguments +// the user set in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS, which Wails' loader +// blanks before WebView2 can read them, are merged into Wails' own (#2753). func windowsOptions() application.WindowsOptions { + disabled, enabled, other := webView2Args(webview2env.Args) return application.WindowsOptions{ DisableQuitOnLastWindowClosed: true, WebviewUserDataPath: appdir.WebView(), + DisabledFeatures: disabled, + EnabledFeatures: enabled, + AdditionalBrowserArgs: other, } } diff --git a/internal/gui/webview2.go b/internal/gui/webview2.go index 6d545a788..b59d09ffe 100644 --- a/internal/gui/webview2.go +++ b/internal/gui/webview2.go @@ -1,6 +1,10 @@ package gui -import "fmt" +import ( + "fmt" + "slices" + "strings" +) // magpie's windows are WebView2 on Windows, a runtime Windows 10 doesn't // always have. Without it Wails hands the failure to ErrorHandler and exits, @@ -60,3 +64,66 @@ var webView2Words = map[string][2]string{ "Bis dahin öffnet \"magpie web\" magpie im Browser und \"magpie tui\" im Terminal.\r\n\r\n" + "Die Download-Seite jetzt öffnen?"}, } + +// webView2Args sorts what the user put in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS +// (webview2env.Args) into Wails' three options, which it passes as the +// app's own arguments: the features to disable, the ones to enable, and +// every other argument as written. Wails' loader blanks the variable +// itself, so without this a user's --disable-features=RendererCodeIntegrity +// never reached magpie's renderer (#2753, LuYquan: an injected DLL got it +// killed and the window went black). Wails puts its own +// msSmartScreenProtection first in DisabledFeatures and writes the list as +// one --disable-features (and EnabledFeatures as one --enable-features): +// Chromium keeps only the last of a repeated switch, so two would drop one +// of them. A list given more than once is merged, each feature once, in +// the order given. Arguments are split as Windows splits a command line on +// spaces, a double-quoted run kept whole. +func webView2Args(env string) (disabled, enabled, other []string) { + for _, a := range splitArgs(env) { + switch k, v, _ := strings.Cut(a, "="); k { + case "--disable-features": + disabled = addFeatures(disabled, v) + case "--enable-features": + enabled = addFeatures(enabled, v) + default: + other = append(other, a) + } + } + return disabled, enabled, other +} + +// addFeatures adds a comma list's features to have, each once. +func addFeatures(have []string, list string) []string { + for _, f := range strings.Split(strings.Trim(list, `"`), ",") { + if f = strings.TrimSpace(f); f != "" && !slices.Contains(have, f) { + have = append(have, f) + } + } + return have +} + +// splitArgs splits a command line on spaces and tabs outside double quotes, +// keeping each argument as written, its quotes too. +func splitArgs(s string) []string { + var out []string + var cur strings.Builder + quoted := false + for _, r := range s { + switch { + case r == '"': + quoted = !quoted + cur.WriteRune(r) + case (r == ' ' || r == '\t' || r == '\n' || r == '\r') && !quoted: + if cur.Len() > 0 { + out = append(out, cur.String()) + cur.Reset() + } + default: + cur.WriteRune(r) + } + } + if cur.Len() > 0 { + out = append(out, cur.String()) + } + return out +} diff --git a/internal/gui/webview2_args_test.go b/internal/gui/webview2_args_test.go new file mode 100644 index 000000000..b7382bbb6 --- /dev/null +++ b/internal/gui/webview2_args_test.go @@ -0,0 +1,111 @@ +//go:build !nogui + +package gui + +import ( + "fmt" + "os" + "os/exec" + "slices" + "strings" + "testing" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/yetone/magpie/internal/webview2env" +) + +// wailsBrowserArgs is the command line Wails v3.0.0-beta.24 makes from the +// app's Windows options (setupChromium, webview_window_windows.go): its own +// msSmartScreenProtection first among the disabled features, each list +// once as one switch, then the other arguments as given. +func wailsBrowserArgs(o application.WindowsOptions) []string { + var disabled []string + for _, f := range append([]string{"msSmartScreenProtection"}, o.DisabledFeatures...) { + if !slices.Contains(disabled, f) { + disabled = append(disabled, f) + } + } + args := []string{"--disable-features=" + strings.Join(disabled, ",")} + if len(o.EnabledFeatures) > 0 { + args = append(args, "--enable-features="+strings.Join(o.EnabledFeatures, ",")) + } + return append(args, o.AdditionalBrowserArgs...) +} + +// #2753 (LuYquan): magpie's own --disable-features made WebView2 skip the +// user's WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS, so RendererCodeIntegrity +// stayed on and an injected DLL got the renderer killed. Now the user's +// arguments are merged into magpie's: one --disable-features holding both +// lists (Chromium keeps only the last of two), one --enable-features, and +// every other argument as written. +func TestWebView2ArgsMergeTheUsers(t *testing.T) { + for _, c := range []struct { + name, env string + want []string + }{ + {"none set", "", []string{"--disable-features=msSmartScreenProtection"}}, + {"the reporter's", "--disable-features=RendererCodeIntegrity", + []string{"--disable-features=msSmartScreenProtection,RendererCodeIntegrity"}}, + {"twice, with magpie's own and a repeat", `--disable-features=A,msSmartScreenProtection --disable-features="B, A"`, + []string{"--disable-features=msSmartScreenProtection,A,B"}}, + {"enable and others kept", " --enable-features=X,Y\t--remote-debugging-port=9333 --proxy-server=\"http://h:1 x\" --enable-features=Y,Z --lang=de ", + []string{"--disable-features=msSmartScreenProtection", "--enable-features=X,Y,Z", "--remote-debugging-port=9333", `--proxy-server="http://h:1 x"`, "--lang=de"}}, + {"a bare switch", "--disable-features", []string{"--disable-features=msSmartScreenProtection"}}, + } { + t.Run(c.name, func(t *testing.T) { + was := webview2env.Args + t.Cleanup(func() { webview2env.Args = was }) + webview2env.Args = c.env + got := wailsBrowserArgs(windowsOptions()) + if fmt.Sprint(got) != fmt.Sprint(c.want) { + t.Fatalf("WebView2 is started with %q, want %q", got, c.want) + } + n := 0 + for _, a := range got { + if strings.HasPrefix(a, "--disable-features") { + n++ + } + } + if n != 1 { + t.Fatalf("%d --disable-features in %q, Chromium keeps only the last", n, got) + } + }) + } +} + +// Nothing in the defaults turns renderer code integrity off: only a user +// who asks for it gets it (#2753). +func TestWebView2KeepsCodeIntegrityByDefault(t *testing.T) { + was := webview2env.Args + t.Cleanup(func() { webview2env.Args = was }) + webview2env.Args = "" + if got := strings.Join(wailsBrowserArgs(windowsOptions()), " "); strings.Contains(got, "RendererCodeIntegrity") { + t.Fatalf("default arguments %q turn RendererCodeIntegrity off", got) + } +} + +// On Windows Wails' WebView2 loader blanks the variable in its init, which +// runs before magpie's code (#2753: the reporter's flag never arrived). +// The value magpie was started with still reaches the options: this test +// starts its own binary with the variable set, where the loader's init has +// run as in the app. +func TestWebView2ArgsSurviveWailsInit(t *testing.T) { + if os.Getenv("MAGPIE_TEST_WEBVIEW2_CHILD") == "1" { + fmt.Printf("os=%q disabled=%q\n", os.Getenv(webview2env.Name), windowsOptions().DisabledFeatures) + return + } + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(exe, "-test.run=^TestWebView2ArgsSurviveWailsInit$", "-test.count=1") + cmd.Env = append(os.Environ(), "MAGPIE_TEST_WEBVIEW2_CHILD=1", webview2env.Name+"=--disable-features=RendererCodeIntegrity") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("child: %v\n%s", err, out) + } + if !strings.Contains(string(out), `disabled=["RendererCodeIntegrity"]`) { + t.Fatalf("the started value didn't reach the options:\n%s", out) + } + t.Logf("%s", strings.SplitN(string(out), "\n", 2)[0]) +} diff --git a/internal/webview2env/webview2env.go b/internal/webview2env/webview2env.go new file mode 100644 index 000000000..d0d75b93b --- /dev/null +++ b/internal/webview2env/webview2env.go @@ -0,0 +1,19 @@ +// Package webview2env keeps WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS as magpie +// was started with. Wails' WebView2 loader blanks the variable in its own +// init (webviewloader.preventEnvAndRegistryOverrides, so neither it nor the +// registry's policy can change the browser's arguments), before magpie's +// code runs, and a user's --disable-features=RendererCodeIntegrity never +// reached the renderer (#2753). This package reads it first. Go +// initializes, at each step, the first package by import path whose +// imports are all done. This one imports only syscall, so it is ready as +// soon as syscall is, and it sorts before "os"; the loader needs os, so +// os, and the loader after it, can't start while this one waits. +package webview2env + +import "syscall" + +// Name is the variable WebView2 reads extra browser arguments from. +const Name = "WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS" + +// Args is the variable's value when magpie started, "" when it wasn't set. +var Args, _ = syscall.Getenv(Name) From fc78eb5f6b2cf239f0cf87f47bf3bc790790951e Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:38:40 +0800 Subject: [PATCH 17/92] gateway: ClinePass's upstream is read from provider_metadata.gateway.routing.finalProvider (#2847, smart-lty) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClinePass (api.cline.bot) names the provider that answered only in a Chat choice's provider_metadata.gateway.routing.finalProvider: under delta in a stream chunk, and under message in a single body. upstreamOf read only a top-level provider, message.provider and response.provider, so the Routing page's 上游 column, the request log and the usage ledger showed nothing for ClinePass. upstreamOf now also reads finalProvider at those two places, and nowhere else. A choice's content belongs to the model. providerAttempts inside routing lists every provider that was tried, not the one that answered. The cheap pre-check now passes a chunk that carries only "finalProvider". Tests: - TestUpstreamOfClinePass checks: - the real chunk gives deepseek; - the same chunk as one body (message) gives deepseek; - content, tool_call arguments, providerAttempts alone and an object-valued finalProvider give ""; - a top-level provider still wins. - TestClinePassUpstreamRecorded serves the real stream through the Handler on /v1/chat/completions and on /v1/messages (translated). It checks that the route, the try, Recent() and the usage ledger all say deepseek. The fixture testdata/clinepass_stream.sse is a real ClinePass stream: api.cline.bot, deepseek/deepseek-v4.1-flash, captured 2026-10-02 in the MIT-licensed wkeking/clinepass-channel-monitor (internal/channellog/testdata/plain_success.log). It is not the reporter's own bytes; #2847 has none. What was run at 1a3b92688 + this change, on macOS (Go 1.26.8): - gofmt -l: clean. - go vet: darwin, linux (-tags nogui) and windows. - Builds: darwin, linux (nogui) and windows. - go test -run 'TestUpstream|TestClinePass|TestServed' ./internal/gateway: ok. - Broken by hand: with the old upstream.go put back, both new tests go red ("real ClinePass chunk: upstreamOf = \"\"; want deepseek", plus the route, request-log and usage assertions on both paths). - go test -timeout 45m ./... at load average 420-460 (several sessions' suites at once). agent, davsync, gateway, library, plugin and provider ran past the 45m timeout. gui was red on load reds that are already filed: - TestSetAnswersWhileDevinAndProvidersHang: #1375. - TestTrayCellClickReleasedPanel: #2645. - TestClaudeAccountsSpentFallBackToCodex: #2859, also #2858. - TestHostOnBunLackingLibsSaysWhich and TestGatewayHookMixedPiPackage: #2865. - The package timeouts: #2869. Every other package was ok. Not tried: a live ClinePass account in the real app. --- .../gateway/testdata/clinepass_stream.sse | 3 + internal/gateway/upstream.go | 28 +++++- internal/gateway/upstream_test.go | 96 +++++++++++++++++++ 3 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 internal/gateway/testdata/clinepass_stream.sse diff --git a/internal/gateway/testdata/clinepass_stream.sse b/internal/gateway/testdata/clinepass_stream.sse new file mode 100644 index 000000000..9fc780758 --- /dev/null +++ b/internal/gateway/testdata/clinepass_stream.sse @@ -0,0 +1,3 @@ +data: {"id":"gen_01M3YFPP549JB6EP8D4RCXD6EH","object":"chat.completion.chunk","created":1790950726,"model":"deepseek/deepseek-v4.1-flash","choices":[{"index":0,"delta":{"role":"assistant"},"logprobs":null,"finish_reason":null}],"system_fingerprint":"fp_jgawxng80g"} +data: {"choices":[{"delta":{"provider_metadata":{"deepseek":{"choiceIndex":0,"messageRole":"assistant","promptCacheHitTokens":0,"promptCacheMissTokens":37,"responseObject":"chat.completion.chunk","systemFingerprint":"aeb56401ca74e127821c4f9126dcb669"},"gateway":{"cost":"0.00001515","gatewayCost":"0.00001515","generationId":"gen_01M3YFPP549JB6EP8D4RCXD6EH","inferenceCost":"0.00001515","inputInferenceCost":"0.00000555","marketCost":"0.00001515","outputInferenceCost":"0.0000096","routing":{"affinity":{"outcome":"confirmed","pinnedProvider":"deepseek"},"canonicalSlug":"deepseek/deepseek-v4.1-flash","clientSessionId":"sess-ed01ce273d78b615f19287b8325e4aee","clientSessionIdSource":"explicit","fallbacksAvailable":[],"finalProvider":"deepseek","modelAttemptCount":1,"modelAttempts":[{"canonicalSlug":"deepseek/deepseek-v4.1-flash","providerAttemptCount":1,"providerAttempts":[{"credentialType":"system","endTime":1790950726481,"provider":"deepseek","providerRequestId":"4ae0eeb4ebc6bcc03390f31ec70cc26a","providerResponseId":"00b1015b-004f-4132-9223-649fed188560","startTime":1790950725813,"statusCode":200,"success":true}],"success":true}],"originalModelId":"deepseek/deepseek-v4.1-flash","planningReasoning":"Provider set restricted to: deepseek. System credentials planned for: deepseek. Total execution order: deepseek(system)","resolvedProvider":"deepseek","totalProviderAttemptCount":1},"surchargeCost":"0"}}},"finish_reason":"length","index":0,"logprobs":null}],"created":1790950726,"generationId":"gen_01M3YFPP549JB6EP8D4RCXD6EH","id":"gen_01M3YFPP549JB6EP8D4RCXD6EH","model":"deepseek/deepseek-v4.1-flash","object":"chat.completion.chunk","system_fingerprint":"fp_jgawxng80g","usage":{"cache_creation_input_tokens":0,"completion_tokens":16,"completion_tokens_details":{"image_tokens":0,"reasoning_tokens":16},"cost":0.00001515,"cost_details":null,"gateway_cost":0.00001515,"is_byok":false,"market_cost":0.00001515,"prompt_tokens":37,"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0,"video_tokens":0},"total_tokens":53}} +data: [DONE] diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 4b21415ca..90b5c25cc 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -13,11 +13,25 @@ import ( // OpenRouter names it in a top-level "provider" — a Chat body and every // chunk of its stream, an Anthropic Messages body — and in a Messages // stream's message_start, as message.provider (seen 2026-10-05: DeepInfra, -// StreamLake). Its Responses replies name none. +// StreamLake). Its Responses replies name none. ClinePass (api.cline.bot) +// names it in a Chat choice's provider_metadata, as +// gateway.routing.finalProvider: under delta in a stream's chunk, under +// message in one body (#2847, smart-lty). Only those places count: a +// choice's content is the model's, and providerAttempts inside routing +// lists every provider tried, not the one that answered. func upstreamOf(b []byte) string { - if !bytes.Contains(b, []byte(`"provider"`)) { + if !bytes.Contains(b, []byte(`"provider"`)) && !bytes.Contains(b, []byte(`"finalProvider"`)) { return "" } + type routed struct { + ProviderMetadata struct { + Gateway struct { + Routing struct { + FinalProvider json.RawMessage `json:"finalProvider"` + } `json:"routing"` + } `json:"gateway"` + } `json:"provider_metadata"` + } var v struct { Provider json.RawMessage `json:"provider"` Message struct { @@ -26,11 +40,19 @@ func upstreamOf(b []byte) string { Response struct { Provider json.RawMessage `json:"provider"` } `json:"response"` + Choices []struct { + Delta routed `json:"delta"` + Message routed `json:"message"` + } `json:"choices"` } if json.Unmarshal(b, &v) != nil { return "" } - for _, raw := range []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} { + raws := []json.RawMessage{v.Provider, v.Message.Provider, v.Response.Provider} + for _, c := range v.Choices { + raws = append(raws, c.Delta.ProviderMetadata.Gateway.Routing.FinalProvider, c.Message.ProviderMetadata.Gateway.Routing.FinalProvider) + } + for _, raw := range raws { var s string // a request's provider options echoed back are an object if json.Unmarshal(raw, &s) == nil { if s = strings.TrimSpace(s); s != "" && len(s) <= 64 { diff --git a/internal/gateway/upstream_test.go b/internal/gateway/upstream_test.go index 79c7a9491..181277d24 100644 --- a/internal/gateway/upstream_test.go +++ b/internal/gateway/upstream_test.go @@ -1,9 +1,12 @@ package gateway import ( + "bufio" + "bytes" "io" "net/http" "net/http/httptest" + "os" "strings" "testing" "time" @@ -137,3 +140,96 @@ func TestUpstreamOf(t *testing.T) { } } } + +// clinePassStream is a real ClinePass stream (api.cline.bot, DeepSeek V4.1 +// Flash, 2026-10-02), as captured in wkeking/clinepass-channel-monitor's +// testdata/plain_success.log (MIT): its last chunk names the provider that +// answered only in choices[].delta.provider_metadata.gateway.routing. +func clinePassStream(t *testing.T) []string { + t.Helper() + b, err := os.ReadFile("testdata/clinepass_stream.sse") + if err != nil { + t.Fatal(err) + } + var lines []string + sc := bufio.NewScanner(bytes.NewReader(b)) + sc.Buffer(nil, 1<<20) + for sc.Scan() { + if l := sc.Text(); l != "" { + lines = append(lines, l) + } + } + return lines +} + +// ClinePass says the provider behind it as finalProvider in a choice's +// provider_metadata (#2847, smart-lty): under delta in a stream, under +// message in one body. Only there: the model's own text naming it, or the +// list of providers tried, says none. +func TestUpstreamOfClinePass(t *testing.T) { + var last string + for _, l := range clinePassStream(t) { + if d := strings.TrimPrefix(l, "data: "); strings.Contains(d, "finalProvider") { + last = d + } + } + if got := upstreamOf([]byte(last)); got != "deepseek" { + t.Errorf("real ClinePass chunk: upstreamOf = %q; want deepseek", got) + } + whole := strings.Replace(last, `"delta":{"provider_metadata"`, `"message":{"role":"assistant","content":"hi","provider_metadata"`, 1) + if got := upstreamOf([]byte(whole)); got != "deepseek" { + t.Errorf("one body: upstreamOf = %q; want deepseek", got) + } + for in, want := range map[string]string{ + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":"novita"}}}}}]}`: "novita", + `{"choices":[{"delta":{"content":"provider_metadata gateway routing \"finalProvider\":\"deepseek\""}}]}`: "", + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"modelAttempts":[{"providerAttempts":[{"provider":"deepseek"}]}]}}}}}]}`: "", + `{"choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":{"id":"x"}}}}}}]}`: "", + `{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"{\"finalProvider\":\"x\"}"}}]}}]}`: "", + `{"provider":"Novita","choices":[{"delta":{"provider_metadata":{"gateway":{"routing":{"finalProvider":"deepseek"}}}}}]}`: "Novita", + } { + if got := upstreamOf([]byte(in)); got != want { + t.Errorf("upstreamOf(%s) = %q; want %q", in, got, want) + } + } +} + +// The real ClinePass stream's provider reaches the route, its try, the +// request log and the usage ledger, relayed to a Chat client or translated +// to a Messages one (#2847). +func TestClinePassUpstreamRecorded(t *testing.T) { + stream := clinePassStream(t) + for _, path := range []string{"/v1/chat/completions", "/v1/messages"} { + t.Run(path, func(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for _, l := range stream { + io.WriteString(w, l+"\n\n") + } + })) + t.Cleanup(up.Close) + p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"sol"}} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + body := `{"model":"fake/sol","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + r := lastRoute(s) + if r.Upstream != "deepseek" || len(r.Tries) != 1 || r.Tries[0].Upstream != "deepseek" { + t.Errorf("route upstream %q, tries %+v", r.Upstream, r.Tries) + } + if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Upstream != "deepseek" { + t.Errorf("request log: %+v", calls) + } + if u := usage.Load(time.Time{}); len(u) != 1 || u[0].Upstream != "deepseek" { + t.Errorf("usage %+v", u) + } + }) + } +} From 47eb42f1a1ca9ce548add643f23cf61c50cae765 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:53:38 +0800 Subject: [PATCH 18/92] workbuddy: moved users get plugin 0.1.25, where WorkBuddy AI's "x0.34 credits" rates are read, not unknown (magpie-community/plugins#216) WorkBuddy AI's /v3/config gives fast-model, balanced-model and primary-model their credits as "x0.34 credits", "x0.59 credits" and "x3.31 credits" (read live from the owner's account on 2026-10-19). Plugin 0.1.24 read those as unknown, so the three showed no rate. 0.1.25 (plugins c89cee5, bump ab38da6) strips a trailing "credits" unit only; empty, negative, non-finite or other trailing text stays unknown. npm view @magpie-community/opencode-workbuddy-auth version --prefer-online: 0.1.25. The retired built-in has no wbCredits any more, so there is nothing to mirror here. Run on origin/main 1a3b92688 + this change, go1.26.8, load average ~420 from other sessions throughout: - gofmt -l: nothing. go vet ./... ok; GOOS=linux go vet -tags nogui ./... ok; GOOS=windows go vet ./... ok. go build, GOOS=linux go build -tags nogui, GOOS=windows go build ok. - set -o pipefail; go test -timeout 45m ./...: 60 packages ok, 4 FAIL, all load and all in packages this doesn't touch. internal/provider, the one it does, ok (1841s). - internal/agent: 45m timeout, TestClaudeTierPickedAsTheMainModelStays 23s in (#2544, #2723). - internal/gateway: 45m timeout, TestReplyNamesMember 1m7s in (#2870, filed now). - internal/library: 45m timeout (#2853). - internal/gui: TestSetAnswersWhileDevinAndProvidersHang, a set took 18.2s (#1375). Rerun alone -count=3: ok. --- internal/provider/migrate_workbuddy.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/provider/migrate_workbuddy.go b/internal/provider/migrate_workbuddy.go index 7475ce14f..7395f0ba5 100644 --- a/internal/provider/migrate_workbuddy.go +++ b/internal/provider/migrate_workbuddy.go @@ -16,7 +16,7 @@ func init() { for _, w := range []*wbSite{wbCN, wbAI} { movers[w.id] = &mover{ pkg: "@magpie-community/opencode-workbuddy-auth", - min: "0.1.24", // a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) + min: "0.1.25", // WorkBuddy AI's fast, balanced and primary models keep the credit rate its config gives as "x0.34 credits", not unknown (plugins #216); 0.1.24: a refused sign-in on a chat over 2 MiB says the 401 and to sign in again: WorkBuddy's front door resets such a request instead of answering, so it read as 502 ECONNRESET (wyp on Discord); 0.1.23: credits used up leave the free models counted out of the credits window, so an account is not ranked spent for them (plugins #138); 0.1.22: an MCP server's tool schemas reach Kimi and DeepSeek: an enum with no type, or of several types, is typed, and true or false where a schema goes is {} or {"not": {}}, so they aren't 400 11133 "Invalid request parameters" (plugins #122); 0.1.21: a model free only at night (Hy4 preview) is never said free, and a whole-day discount shows the price before it, from WorkBuddy's modelPromotions (plugins #121); 0.1.20: tool results followed by the user's message reach WorkBuddy AI's gemini-3.8-flash, not 400 "the conversation must end with a user message" (plugins #113); 0.1.19: an enterprise account's card shows its credits, from the enterprise meter WorkBuddy's usage page reads (#1904); 0.1.18: WorkBuddy 5.6+ keeps its desktop sign-in encrypted, and the plugin says so and points to the browser sign-in instead of a 502 (plugins #18); 0.1.17: a restricted account's 403 11140 ends in provider.WBRestrictedHint, so it rests 2h as restricted (#1849); 0.1.16: WorkBuddy AI's GLM models are text-only, so magpie's image-describing model reads their images (Yirasumi on Discord); 0.1.15: a system prompt sent as a developer message passes the channel check, an object tool_choice is sent as WorkBuddy takes it, and max_completion_tokens goes as max_tokens so the cap holds (plugins #96); 0.1.14: the Credits window says when the soonest credits left run out, for Smart routing to spend them first (cdredfox on X); an enterprise account names its enterprise, so it lists and uses the enterprise's models, not the personal plan's (plugins #75); a chat's tools get shapes WorkBuddy AI's models take, so ZCode's and DeepSeek Harness's chats on deepseek-v4.1-flash aren't 400 "Invalid request parameters" (wyh on Discord); one user send is one request in the usage list: every step carries one X-Conversation-Request-ID, and both builds name the client (使用端) (plugins #48); credits used up (code 14018) say so, with the nested error message (plugins #25); Codex's and Claude Code's chats pass WorkBuddy's channel check (#182); a failure's status and its sign-in mark as the built-in's; each model's credit rate; the sign-in renewed ahead of time through auth.refresh; the credits' count beside their share (#659) agents: []string{w.id}, out: func() ([]Moving, error) { var out []Moving From 94919109cb3b9d4241bb957c9e571c6f4c236d2f Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:59:57 +0800 Subject: [PATCH 19/92] gateway: a silent HTTP/2 connection to a vendor is pinged and dropped (#2843) pinewhite (#2843, v0.1.1279, Linux): for ~30 minutes every request to group/auto-deepseek-v4-1-flash hung with no first byte. The WorkBuddy member was resting on a 429, so they all went to ClinePass, and usage shows only 499s with in=0. A restart answered the same request in 1.6s. Cause: the gateway's transport (upstreamTransport) speaks HTTP/2 to any vendor that offers it, so every request to api.cline.bot shares one connection. It had no HTTP/2 health check. A connection that goes silent without closing (a local proxy whose own way out died, or a NAT that forgot the flow) stays in the pool. Every new request is multiplexed onto it and waits for the 10-minute ResponseHeaderTimeout while the kernel takes the writes. The agent gives up first, so nothing fails over and nothing rests the member. Restarting dropped the connection. Fix: netproxy.HTTP2Health() (SendPingTimeout 20s, PingTimeout 10s) on upstreamTransport. Go now pings a connection that has had no frame for 20s and closes it when no answer comes within 10s. The requests on it fail as a 502 ("http2: client connection lost"), so a group moves on, and the next request dials a new connection. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut. The same setting goes on http.DefaultTransport in netproxy.Install, the sibling pool that usage cards, catalogs and sign-ins use. Not covered: requests a plugin sends from Bun. Tests (new): - TestSilentHTTP2ConnectionIsDropped: an HTTP/2 TLS httptest vendor behind a TCP relay that can go silent on its open connections (it takes writes, passes nothing). After the relay goes silent, a request must end well inside 10s, and the next one must succeed on a second connection. - TestGroupMovesOnFromSilentHTTP2Connection: the same through the real Handler, with an ordered group a/m then b/m. Once a's connection is silent, the request must get b's reply. - TestInstallChecksHTTP2Connections (netproxy). What was run (worktree on origin/main 1a3b92688, sandbox HOME, pinned GOCACHE/GOMODCACHE, go1.26.8 darwin/arm64): - Red without the fix (HTTP2 lines removed, tests kept): TestSilentHTTP2ConnectionIsDropped FAIL "hung 10.003s, until the client gave up: context deadline exceeded"; TestGroupMovesOnFromSilentHTTP2Connection FAIL "200 after 10.005s; want b's reply"; TestInstallChecksHTTP2Connections FAIL "HTTP/2 after Install: ". - Green with it: those, TestCodexBackendOverHTTP1 and the Stale tests, -race -count=3: ok. - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok. - go test -timeout 45m ./...: 59 packages ok. The machine's load average was 400-460 (other sessions' GUI suites and builds). internal/agent, internal/gateway and internal/library hit the 45m alarm while a test that had just started was running (0-40s in), not stuck in one test. Four tests failed on a time bound: TestIntentClassifierGroup, TestClaudeAccountsSpentFallBackToCodex (gateway), TestSetAnswersWhileDevinAndProvidersHang (gui; a set took 18s against its bar) and TestGatewayHookWaitsForStartingHost (plugin). None of them uses HTTP/2. Rerun alone on this change: gateway, gui and plugin ok. internal/library alone: ok (2220s). internal/agent alone hit 45m again at load ~400, as filed in #2723/#2544 (it doesn't call netproxy.Install or upstreamTransport in a test this touches). The reds are filed: #1813, #2858/#2859, #1375, #2723/#2544, #2853, #2870, and #2871 (new, the plugin one). Not verified: no real ClinePass account behind a proxy that goes silent, so the reporter's path is reproduced with an injected silent relay, not seen live. Not tried on Linux or Windows beyond vet and build. The GUI is not touched, so the GUI suite was not run. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/upstream_h2_silent_test.go | 233 ++++++++++++++++++++ internal/gateway/upstream_transport.go | 2 + internal/netproxy/http2_health_test.go | 23 ++ internal/netproxy/netproxy.go | 23 +- 5 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/upstream_h2_silent_test.go create mode 100644 internal/netproxy/http2_health_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 90600cf95..187780162 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -36,7 +36,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) | -| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) | +| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) | | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) | | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | diff --git a/internal/gateway/upstream_h2_silent_test.go b/internal/gateway/upstream_h2_silent_test.go new file mode 100644 index 000000000..4796d9a18 --- /dev/null +++ b/internal/gateway/upstream_h2_silent_test.go @@ -0,0 +1,233 @@ +package gateway + +import ( + "context" + "crypto/tls" + "crypto/x509" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" +) + +// silentPath sits between the gateway and a vendor and can go silent on +// the connections open through it: it goes on taking what the gateway +// writes, so every write succeeds, and passes nothing either way, as a +// local proxy whose own way out died, or a NAT that forgot the flow, does. +// A connection opened after it went silent passes as before. +type silentPath struct { + ln net.Listener + to string + mu sync.Mutex + open []*silentConn + wg sync.WaitGroup +} + +type silentConn struct { + a, b net.Conn + silent atomic.Bool +} + +func newSilentPath(t *testing.T, to string) *silentPath { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + p := &silentPath{ln: ln, to: to} + p.wg.Add(1) + go func() { + defer p.wg.Done() + for { + a, err := ln.Accept() + if err != nil { + return + } + b, err := net.Dial("tcp", to) + if err != nil { + a.Close() + continue + } + c := &silentConn{a: a, b: b} + p.mu.Lock() + p.open = append(p.open, c) + p.mu.Unlock() + pipe := func(dst, src net.Conn) { + defer p.wg.Done() + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if n > 0 && !c.silent.Load() { + if _, werr := dst.Write(buf[:n]); werr != nil { + return + } + } + if err != nil { + return + } + } + } + p.wg.Add(2) + go pipe(b, a) + go pipe(a, b) + } + }() + t.Cleanup(func() { + p.ln.Close() + p.mu.Lock() + for _, c := range p.open { + c.a.Close() + c.b.Close() + } + p.mu.Unlock() + p.wg.Wait() + }) + return p +} + +// hush silences every connection open now. +func (p *silentPath) hush() int { + p.mu.Lock() + defer p.mu.Unlock() + for _, c := range p.open { + c.silent.Store(true) + } + return len(p.open) +} + +func (p *silentPath) conns() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.open) +} + +// quickPings has the gateway's transports, made after it, ping a quiet +// HTTP/2 connection after 200ms and drop it 300ms later, and trust +// vendor's certificate. +func quickPings(t *testing.T, vendor *httptest.Server) { + pool := x509.NewCertPool() + pool.AddCert(vendor.Certificate()) + wasTLS, wasAfter, wasWait := upstreamTLS, netproxy.PingAfter, netproxy.PingWait + upstreamTLS = &tls.Config{RootCAs: pool, ServerName: "127.0.0.1"} + netproxy.PingAfter, netproxy.PingWait = 200*time.Millisecond, 300*time.Millisecond + t.Cleanup(func() { upstreamTLS, netproxy.PingAfter, netproxy.PingWait = wasTLS, wasAfter, wasWait }) +} + +func h2Vendor(t *testing.T, h http.HandlerFunc) *httptest.Server { + vendor := httptest.NewUnstartedServer(h) + vendor.EnableHTTP2 = true + vendor.StartTLS() + t.Cleanup(vendor.Close) + return vendor +} + +// #2843 (pinewhite): every request of a group to ClinePass hung with no +// first byte for half an hour, and a restart answered the same request in +// 1.6s. Over HTTP/2 every request to a vendor shares one connection, and +// one gone silent without closing (a proxy's way out died, a NAT dropped +// the flow) was kept and given every new request, each waiting up to the +// 10-minute ResponseHeaderTimeout, while the kernel took the writes. The +// gateway's transport now pings a connection quiet for a while and drops +// it when the ping goes unanswered: the request on it fails (so the group +// moves on) and the next one dials a new connection. +func TestSilentHTTP2ConnectionIsDropped(t *testing.T) { + fresh(t) + vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + io.WriteString(w, r.Proto) + }) + path := newSilentPath(t, vendor.Listener.Addr().String()) + quickPings(t, vendor) + s := New() + t.Cleanup(s.client.CloseIdleConnections) + u := "https://" + path.ln.Addr().String() + "/v1/chat/completions" + ask := func(within time.Duration) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), within) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, nil) + res, err := s.client.Do(req) + if err != nil { + return "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return string(b), err + } + if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" { + t.Fatalf("first request: %q, %v; want HTTP/2.0", got, err) + } + if n := path.hush(); n != 1 { + t.Fatalf("%d connections open before the path went silent, want 1", n) + } + // the stalled request ends well before a client gives up (curl -m 55 + // in the report), here 10s against a ping bound of 0.5s + began := time.Now() + _, err := ask(10 * time.Second) + if err == nil { + t.Fatal("a request on the silent connection was answered") + } + if d := time.Since(began); d >= 10*time.Second { + t.Fatalf("a request on the silent connection hung %v, until the client gave up: %v", d, err) + } + // and the one after it goes out on a new connection, without a restart + if got, err := ask(10 * time.Second); err != nil || got != "HTTP/2.0" { + t.Fatalf("request after the silent connection: %q, %v; want HTTP/2.0 on a new connection", got, err) + } + if n := path.conns(); n != 2 { + t.Errorf("%d connections dialled, want 2: the silent one and a new one", n) + } +} + +// The same through a routing group, as in the report: a group's first +// member on a connection gone silent is given up on and the next member +// answers, where before the request hung until its agent gave up and the +// next one hung the same way. +func TestGroupMovesOnFromSilentHTTP2Connection(t *testing.T) { + fresh(t) + vendor := h2Vendor(t, func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"a","choices":[{"message":{"role":"assistant","content":"from a"}}]}`) + }) + path := newSilentPath(t, vendor.Listener.Addr().String()) + quickPings(t, vendor) + if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Models: []string{"m"}, + Chat: "https://" + path.ln.Addr().String() + "/v1"}); err != nil { + t.Fatal(err) + } + serveOn(t, "b", "k", []string{"m"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"b","choices":[{"message":{"role":"assistant","content":"from b"}}]}`) + })) + if err := provider.SaveGroup(provider.Group{Name: "Auto", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + t.Cleanup(s.client.CloseIdleConnections) + ask := func() (int, string, time.Duration) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", + strings.NewReader(`{"model":"group/auto","messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx) + began := time.Now() + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String(), time.Since(began) + } + if code, body, _ := ask(); code != http.StatusOK || !strings.Contains(body, "from a") { + t.Fatalf("first group request: %d %s; want a's reply", code, body) + } + path.hush() + code, body, took := ask() + if code != http.StatusOK || !strings.Contains(body, "from b") { + t.Fatalf("group request with a's connection silent: %d %s after %v; want b's reply", code, body, took) + } +} diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index bce715a1f..d1cadd3db 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -26,6 +26,8 @@ func upstreamTransport() http.RoundTripper { IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true, TLSClientConfig: upstreamTLS, + // a silent HTTP/2 connection is pinged and dropped (#2843) + HTTP2: netproxy.HTTP2Health(), })} } diff --git a/internal/netproxy/http2_health_test.go b/internal/netproxy/http2_health_test.go new file mode 100644 index 000000000..2282ddbde --- /dev/null +++ b/internal/netproxy/http2_health_test.go @@ -0,0 +1,23 @@ +package netproxy + +import ( + "net/http" + "testing" +) + +// http.DefaultClient's HTTP/2 connections (usage cards, catalogs, +// sign-ins) are checked as the gateway's are: one gone silent is pinged +// and dropped rather than given every request after it (#2843). +func TestInstallChecksHTTP2Connections(t *testing.T) { + d, ok := http.DefaultTransport.(*http.Transport) + if !ok { + t.Skip("http.DefaultTransport is not an *http.Transport") + } + was, wasClient, wasProxy := d.HTTP2, http.DefaultClient.Transport, d.Proxy + t.Cleanup(func() { d.HTTP2, http.DefaultClient.Transport, d.Proxy = was, wasClient, wasProxy }) + d.HTTP2 = nil + Install() + if d.HTTP2 == nil || d.HTTP2.SendPingTimeout != PingAfter || d.HTTP2.PingTimeout != PingWait { + t.Fatalf("http.DefaultTransport's HTTP/2 after Install: %+v; want pings after %v, dropped after %v", d.HTTP2, PingAfter, PingWait) + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index abedcb0ad..5c9989cb5 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -25,14 +25,35 @@ import ( // Install routes http.DefaultTransport (and so http.DefaultClient) through // Func, and http.DefaultClient's requests made on a provider's behalf -// (With) through a transport of that provider's proxy (Dispatch). +// (With) through a transport of that provider's proxy (Dispatch). Its +// HTTP/2 connections are checked as the gateway's are (HTTP2Health). func Install() { if t, ok := http.DefaultTransport.(*http.Transport); ok { t.Proxy = Func + if t.HTTP2 == nil { + t.HTTP2 = HTTP2Health() + } http.DefaultClient.Transport = Dispatch(t) } } +// PingAfter and PingWait: an HTTP/2 connection that has had no frame for +// PingAfter is pinged, and dropped when no answer comes within PingWait. +var PingAfter, PingWait = 20 * time.Second, 10 * time.Second + +// HTTP2Health is the HTTP/2 setting of a transport to the vendors. Every +// request to one host shares one HTTP/2 connection, and one gone silent +// without closing (a proxy's way out died, a NAT forgot the flow) was +// given every new request, each waiting for its transport's +// ResponseHeaderTimeout while the kernel took the writes, until a restart +// (#2843). A ping finds it, and the requests on it fail, so a group moves +// on and the next request dials anew. A live vendor answers a ping +// whatever its streams are doing, so a long wait for a first byte is +// never cut by it. +func HTTP2Health() *http.HTTP2Config { + return &http.HTTP2Config{SendPingTimeout: PingAfter, PingTimeout: PingWait} +} + // Func is an http.Transport Proxy function: the proxy the request's // context names (With), or else the global one, which a host on the // user's own network goes around (onLAN). From 2ceff7370f5d2ac4c7e3883e6cddd262852c52d9 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:35:25 +0800 Subject: [PATCH 20/92] gui: the window back reads the state once, not once for visibility and again for focus A window shown again hears visibilitychange and focus together, and each called load(true): two reads of /api/state (every agent's config), with loadCLIs, loadInstalls, the providers and the Usage refresh after each. Under focus-follows-mouse every pointer crossing into the window was one more. loadBack now joins a return to the read asked under a second ago; a return while an older read is still out gets one read after it, however many came meanwhile. Numbers (sandbox HOME, 16 agents, 1230 catalog models, dev build): /api/state is 2.28 MB and ~55 ms of CPU per read (20 reads: 1.11 s). Reads per window return: before 2, after 1. The core's scripts were 1,446,845 bytes, 155 under their budget; loadBack adds 523. Every page needs it, so it is the core's own: coreScriptBudget goes to the new total, 1,447,368, plus 1.5% (1,469,000), as the budget's own rule says. Test: internal/gui/tests/window-back-once.test.cjs counts /api/state reads for a return, a later return, and returns during a held read. On the old app.js: 8 of 8 red, "shown again ... actual 2, expected 1". Run at this head (load average ~500, nine sessions' suites at once): node --test window-back-once.test.cjs, Chromium and WebKit, en and zh, window and panel: 8 of 8 ok. TestCoreScriptBudget ok. GUI files that fire focus or visibility (15 files, both engines): 194 of 196 ok. claude-usage-asked webkit en passes 9 of 9 alone. tray-cell-click webkit zh is red alone 3 of 3, on 1a3b92688's own app.js too: #2686, output added there. go test -p 4 ./... -timeout 45m (HOME a sandbox): 59 packages ok, and: - internal/gui: TestCoreScriptBudget red, fixed here (budget above); TestSetAnswersWhileDevinAndProvidersHang red (13.8s sets), ok alone (12.6s) and the whole package ok alone (391s): #1375, output added. - internal/plugin: TestGatewayHookMixedPiPackage red ("starting plugins: context deadline exceeded"), ok alone (110.8s): #2865, output added. - internal/agent, internal/library, internal/gateway: timed out at 45m. agent timed out alone too (2701.5s): #2544, output added. library is #2853 and gateway #2870. Neither was rerun alone, to keep load off the machine. go vet on darwin, linux (nogui) and windows: clean. gofmt -l: clean. --- internal/gui/assets/app.js | 15 ++- internal/gui/core_budget_test.go | 2 +- internal/gui/tests/window-back-once.test.cjs | 102 +++++++++++++++++++ 3 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 internal/gui/tests/window-back-once.test.cjs diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 71452d638..2c1386a12 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -23383,7 +23383,18 @@ if (mode === "window") { setTimeout(() => { sideGwRead.due = true; sideGwRead(); }, 1500); } -document.addEventListener("visibilitychange", () => { if (!document.hidden) { load(true); wag(); } }); +// loadBack: a window shown again hears visibilitychange and focus together; +// one read for both. A read asked over a second ago gets one more after it. +function loadBack() { + const f = loadBack.flight; + if (f && performance.now() - f.at < 1000) return f.done; + if (f) return (f.next ||= f.done.then(() => loadBack())); + const flight = { at: performance.now() }; + flight.done = load(true).finally(() => { if (loadBack.flight === flight) loadBack.flight = null; }); + loadBack.flight = flight; + return flight.done; +} +document.addEventListener("visibilitychange", () => { if (!document.hidden) { loadBack(); wag(); } }); // an agent's config can be rewritten, or the agent run round magpie, while the // window is up: ask what drifted now and then, and redraw only on a change — // never under an open menu @@ -23433,7 +23444,7 @@ setInterval(async () => { ro.observe($("#usageCost")); new MutationObserver(later).observe(head, { childList: true, subtree: true, characterData: true }); } -window.addEventListener("focus", () => load(true)); +window.addEventListener("focus", () => loadBack()); setInterval(renderUpdateBadge, 15 * 60 * 1000); // a window left open still hears of a new version // renderPluginDot puts a dot on Plugins while a plugin's update waits for // the reader (someone else's plugin, or one pinned; the community's update diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 53375637e..c5f936f92 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_269_000 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397) - coreScriptBudget = 1_447_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612) + coreScriptBudget = 1_469_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5% ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/window-back-once.test.cjs b/internal/gui/tests/window-back-once.test.cjs new file mode 100644 index 000000000..e5041eb74 --- /dev/null +++ b/internal/gui/tests/window-back-once.test.cjs @@ -0,0 +1,102 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The window shown again hears visibilitychange and focus together, and +// under focus-follows-mouse focus each time the pointer crosses in. Each +// of them read the whole state (/api/state, the agents' configs, their +// CLIs, the installs) again: two full reads for one return, and one per +// crossing. One read now serves the returns of the same second; a return +// while an older read is still on its way gets one more read after it, +// however many returns came meanwhile. Chromium and WebKit, English and +// Chinese, the window and the narrow panel. +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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets")); + +function serve(lang, seen) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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") { + if (url.searchParams.get("last") === "1") return json({}); + seen.state++; + if (seen.hold) await seen.hold; + return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true } }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + for (const surface of ["window", "panel"]) { + test(`${engine} ${lang} ${surface}: the window back reads the state once`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: surface === "panel" ? { width: 360, height: 640 } : { width: 1000, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const seen = { state: 0, hold: null }; + await page.clock.install(); + await page.route("**/*", serve(lang, seen)); + await page.goto(surface === "panel" ? "http://magpie.test/?mode=panel" : "http://magpie.test/"); + await page.waitForFunction(() => load.done); + // reads asked for after one of them must come within a moment of it: + // what counts is that the second never comes, so the wait for it is + // a generous one + const quiet = () => new Promise((r) => setTimeout(r, 1500)); + const reach = async (n) => { for (let i = 0; i < 200 && seen.state < n; i++) await new Promise((r) => setTimeout(r, 25)); }; + const back = () => page.evaluate(() => { + document.dispatchEvent(new Event("visibilitychange")); + window.dispatchEvent(new Event("focus")); + }); + const focus = () => page.evaluate(() => window.dispatchEvent(new Event("focus"))); + await quiet(); + const first = seen.state; + + await back(); + await reach(first + 1); + await quiet(); + assert.equal(seen.state - first, 1, "shown again: visibilitychange and focus read the state once"); + await page.clock.runFor(1500); + await focus(); + await reach(first + 2); + await quiet(); + assert.equal(seen.state - first, 2, "a later return reads it again"); + + // a read held on its way: returns a second later each get the one + // read after it, not one each + let release; + seen.hold = new Promise((r) => { release = r; }); + await page.clock.runFor(1500); + await focus(); + await reach(first + 3); + assert.equal(seen.state - first, 3); + await page.clock.runFor(1500); + await focus(); + await focus(); + await back(); + await quiet(); + assert.equal(seen.state - first, 3, "nothing more is asked while the read is on its way"); + seen.hold = null; + release(); + await reach(first + 4); + await quiet(); + assert.equal(seen.state - first, 4, "one read follows the held one, for all the returns while it was out"); + assert.deepEqual(errors, []); + }); + } + } +} From e3c09f4f36feb00cb15c36f8e38ed009e133d650 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:31:02 +0800 Subject: [PATCH 21/92] plugin: a request is told the provider info built once per account, not built again per fetch host.js ran info(provider, key) on every fetch, to hand chat.headers hooks the provider. Each build rebuilt the model list from models.dev and config, read and parsed plugin-auth.json twice, JSON-cloned the list and asked the plugin's provider.models hook, which real plugins (cursor, zed and others) answer by asking the vendor once their own TTL runs out. It ran even when no plugin had a chat.headers hook. infoOf(id, key) now keeps the info per account. Any change to the account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew, take, reload, all through forgetAccount), new provider options, or a new models.dev file builds it again, once. providers() seeds the cache with what it built. The loader, usage and check-in read it too; check's strict build stays direct. chat.headers gets the shared object, as OpenCode hands plugins the provider it keeps, and the request asks for it only when a plugin has a chat.headers hook. Measured (TestPerfScratch harness, not committed; fake plugin, sandbox HOME, loaded machine, two runs each): - {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times. - same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS 87-89 MB -> ~54 MB. - 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per fetch, models hook asked 40 -> 0 times. - idle host CPU ~10-20 ms per 10 s before and after. Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new options each ask it exactly once, and chat.headers and the loader still see fake-1 and every model. Broken by hand twice, red both times: returning no cached info ("20 requests asked the models hook 20 more times, want 0"), and not forgetting it on sign-in ("after a new sign-in ... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf and registers a chat.headers hook for its "info" stage, which red on this change without it (the stage was never entered). Run: go test ./internal/plugin -count=1 ok (159.5s); TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok. --- internal/plugin/host.js | 83 +++++++++++++++----- internal/plugin/host_flow_test.go | 9 ++- internal/plugin/info_once_test.go | 101 +++++++++++++++++++++++++ internal/plugin/testdata/fake/index.js | 2 + 4 files changed, 174 insertions(+), 21 deletions(-) create mode 100644 internal/plugin/info_once_test.go diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 353fc2e39..8656dd20d 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -285,6 +285,22 @@ const hooks = [] // {spec, hooks} const gatewayHooks = [] // {spec, options, onRequest} const loaded = [] // {spec, id, error} const loaders = new Map() // account → options the auth loader returned +// infos are info's answers a request is given, by account: built once, not +// for every fetch, which asked the plugin's models hook (its vendor, once +// its own list's time was up) before each request went. One goes with its +// account's sign-in (forgetAccount), and all with the options the user set +// (setProviderOptions) or a new models.dev catalog; a listing (providers) +// puts its own in. +const infos = new Map() // account → {gen, md, info} +let infoGen = 0 + +// forgetAccount drops what was made of the sign-in at key: its loader's +// options and its info, which the next request makes again. +function forgetAccount(key) { + loaders.delete(key) + infos.delete(key) + infoGen++ +} const sessions = new Map() // oauth sign-in in progress → its authorize result const inflight = new Map() // fetch id → its lifecycle and owned resources const renewing = new Map() // account → its sign-in's renewal under way @@ -886,7 +902,7 @@ function setAuth(key, info) { changeAuth((all) => { all[key] = info }) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } @@ -894,7 +910,7 @@ function removeAuth(key) { changeAuth((all) => { delete all[key] }) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } @@ -984,8 +1000,8 @@ function settle(provider, key) { return false }) if (k) { - loaders.delete(k) - loaders.delete(key) + forgetAccount(k) + forgetAccount(key) send({ event: "auth", provider, account: k }) return k } @@ -1023,7 +1039,7 @@ function makeClient() { all[key] = body }) if (kept !== false) { - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider: providerOf(key), account: key }) } } @@ -1709,6 +1725,26 @@ async function info(id, key, strict) { return out } +// infoOf is info(id, key) as a request has it: the one built for the +// account, until its sign-in or the options change. What it gives is +// shared: the caller must not change it. +async function infoOf(id, key) { + const md = mdev() + const had = infos.get(key) + if (had && had.gen === infoGen && had.md === md) return had.info + const gen = infoGen + const p = await info(id, key) + // a sign-in changed while it was built: the next request builds it again + if (gen === infoGen) infos.set(key, { gen, md, info: p }) + return p +} + +// keepInfo keeps p, info(id, key) just built by a listing, for the +// account's requests. +function keepInfo(key, p, gen) { + if (gen === infoGen && !p.failed) infos.set(key, { gen, md: mdev(), info: p }) +} + // shown is a plugin's string as magpie shows it: trimmed and at most n // characters, "" for anything else. const shown = (v, n) => (typeof v === "string" ? v.trim().slice(0, n) : "") @@ -1827,12 +1863,14 @@ async function providers({ proxies } = {}) { for (const [id, a] of auths()) { const keys = accountsOf(stored, id) const through = (k) => proxies?.[id]?.[k ?? keys[0] ?? ""] ?? proxies?.[id]?.[""] ?? "" + const gen = infoGen const p = await via.run(through(), () => info(id)) + keepInfo(keys[0] ?? id, p, gen) // each account's own models, as the built-ins read each account's: a // plan may serve fewer, or others, than the first account's. One that // can't be read is taken to have them all, or the ones it was last // told to have, as a built-in account whose fetch failed keeps its own. - const own = await Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))) + const own = await Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))) const models = { ...p.models } for (const q of own) for (const [k, m] of Object.entries(q?.models ?? {})) models[k] ??= m const ids = (q) => Object.values(q.models).filter((m) => m.status !== "deprecated").map((m) => m.id) @@ -2106,7 +2144,7 @@ async function renew(provider, key, a) { }) if (kept === false) return unrenewed.delete(key) - loaders.delete(key) + forgetAccount(key) send({ event: "auth", provider, account: key }) send({ event: "signIn", provider, account: key, said: "renewed" }) } @@ -2123,7 +2161,7 @@ async function options(provider, key) { const stored = readAuth()[key] let opts = {} if (a?.loader && stored) { - const p = await info(provider, key) + const p = await infoOf(provider, key) opts = (await inScope(provider, key, () => a.loader(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} } if (!opts.apiKey && stored?.type === "api") opts = { ...opts, apiKey: stored.key } @@ -2180,7 +2218,7 @@ async function usageOf(provider, account) { const key = accountKey(provider, account) if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) - const p = await info(provider, key) + const p = await infoOf(provider, key) const u = (await inScope(provider, key, () => a.usage(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} const when = (v) => { if (v === undefined || v === null || v === "") return "" @@ -2255,7 +2293,7 @@ async function checkinOf(provider, account) { const key = accountKey(provider, account) if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) - const p = await info(provider, key) + const p = await infoOf(provider, key) const r = (await inScope(provider, key, () => a.checkin(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} const num = (v) => (typeof v === "number" && isFinite(v) ? Math.max(0, v) : 0) const message = typeof r.message === "string" ? r.message : "" @@ -2301,13 +2339,19 @@ async function fetchAs(id, record, key, params) { for (const [k, v] of Object.entries(sdkHeaders(npm, o.apiKey))) h.set(k, v) for (const [k, v] of Object.entries(o.headers ?? {})) h.set(k, String(v)) for (const [k, v] of Object.entries(headers ?? {})) h.set(k, v) - // chat.headers: what the plugins add to the request, theirs winning - const p = await info(provider, key) - checkFetch(record) - const m = p.models[model] ?? { id: model, providerID: provider, api: { id: model, npm } } - for (const x of hooks) { + // chat.headers: what the plugins add to the request, theirs winning. + // They are told the provider as info builds it once for the account + // (infoOf), the one object every request is told, as OpenCode tells + // them the provider it keeps + const said = hooks.filter((x) => typeof x.hooks["chat.headers"] === "function") + let p, m + if (said.length) { + p = await infoOf(provider, key) + checkFetch(record) + m = p.models[model] ?? { id: model, providerID: provider, api: { id: model, npm } } + } + for (const x of said) { const fn = x.hooks["chat.headers"] - if (typeof fn !== "function") continue const out = { headers: {} } try { await fn( @@ -2419,6 +2463,9 @@ const handlers = { // plugin reads them when it next asks (#2038) setProviderOptions(p) { chosen = p?.options ?? {} + // a models hook may list by them + infos.clear() + infoGen++ return null }, // check tries one account as a request would: its loader, then its @@ -2464,7 +2511,7 @@ const handlers = { if (!Object.keys(out).length) return false }) for (const k of Object.keys(out)) { - loaders.delete(k) + forgetAccount(k) send({ event: "auth", provider: providerOf(k), account: k }) } return { auths: out } @@ -2476,7 +2523,7 @@ const handlers = { return null }, reload(p) { - for (const k of p.account ? [p.account] : accountsOf(readAuth(), p.provider)) loaders.delete(k) + for (const k of p.account ? [p.account] : accountsOf(readAuth(), p.provider)) forgetAccount(k) return null }, } diff --git a/internal/plugin/host_flow_test.go b/internal/plugin/host_flow_test.go index 54d8eaedc..93ba2e6ba 100644 --- a/internal/plugin/host_flow_test.go +++ b/internal/plugin/host_flow_test.go @@ -84,7 +84,7 @@ const context = vm.createContext({ process: { stdout, stdin: {}, exit: () => { throw Error('unexpected exit') } }, readline: { createInterface: () => rl }, options: async () => ({ fetch: async () => context.reply }), - info: async () => ({ models: {} }), + infoOf: async () => ({ models: {} }), sdkHeaders: () => ({}), bodyOf: () => undefined, accountKey: () => '', via: { run: (_, fn) => fn() }, inScope: (_, key, fn) => fn(), @@ -225,10 +225,13 @@ async function main() { if (stage === 'options') { entered = true; await barrier } return { fetch: async () => { vendorCalls++; return context.reply } } } - context.info = async () => { + context.infoOf = async () => { if (stage === 'info') { entered = true; await barrier } return { models: {} } } + // a request is told the provider only for a chat.headers hook + run('hooks.length = 0') + if (stage === 'info') run('hooks.push({ spec: "t", hooks: { "chat.headers": async () => {} } })') fetchOne() await until(() => entered, 'plugin setup entered its deferred await') assert.equal(run('inflight.get(1).state'), 'setup') @@ -239,7 +242,7 @@ async function main() { await until(idle, 'cancelled setup finishes') assert.equal(vendorCalls, 0, 'cancelled setup never starts vendor') context.options = async () => ({ fetch: async () => { vendorCalls++; return context.reply } }) - context.info = async () => ({ models: {} }) + context.infoOf = async () => ({ models: {} }) fetchOne() await until(idle, 'healthy fetch after cancelled setup') assert.equal(vendorCalls, 1) diff --git a/internal/plugin/info_once_test.go b/internal/plugin/info_once_test.go new file mode 100644 index 000000000..e3ceb50b2 --- /dev/null +++ b/internal/plugin/info_once_test.go @@ -0,0 +1,101 @@ +package plugin + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// A request is told the provider as info builds it once for its account, +// not built again for every fetch: each build asked the plugin's models +// hook, and with it the vendor once the plugin's own list was due, before +// the request went. A new sign-in or new options build it again, once. +func TestFetchBuildsInfoOnce(t *testing.T) { + sandbox(t) + var mu sync.Mutex + var told []string // x-plugin-model, as chat.headers set it, and x-models, as the loader was told them + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + told = append(told, r.Header.Get("x-plugin-model")+" "+r.Header.Get("x-models")) + mu.Unlock() + io.WriteString(w, "ok") + })) + defer srv.Close() + t.Setenv("FAKE_BASE", srv.URL+"/v1") + log := filepath.Join(t.TempDir(), "models.log") + t.Setenv("FAKE_MODELS_LOG", log) + asked := func() int { + b, _ := os.ReadFile(log) + return strings.Count(string(b), "asked") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + fetch := func() { + t.Helper() + res, err := Fetch(ctx, FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: srv.URL + "/v1/chat/completions", Method: "POST", Body: []byte(`{}`)}) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + if string(b) != "ok" { + t.Fatalf("answered %q", b) + } + } + fetch() + n := asked() + for range 20 { + fetch() + } + if got := asked() - n; got != 0 { + t.Fatalf("20 requests asked the models hook %d more times, want 0", got) + } + mu.Lock() + for _, m := range told { + if m != "fake-1 fake-1,fake-claude,fake-gemini" { + t.Fatalf("chat.headers and the loader were told %q, want fake-1 and every model", m) + } + } + mu.Unlock() + + // a new sign-in for the account: built again, once + if err := Restore(ctx, "fakeco", "fakeco", map[string]any{"type": "api", "key": "k2"}); err != nil { + t.Fatal(err) + } + n = asked() + for range 5 { + fetch() + } + if got := asked() - n; got != 1 { + t.Fatalf("after a new sign-in 5 requests asked the models hook %d times, want 1", got) + } + // new options: built again, once + if err := SetProviderOptions(ctx); err != nil { + t.Fatal(err) + } + n = asked() + for range 5 { + fetch() + } + if got := asked() - n; got != 1 { + t.Fatalf("after new options 5 requests asked the models hook %d times, want 1", got) + } +} diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 9981f08a0..7a40501e8 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -240,6 +240,8 @@ export const FakePlugin = async ({ client }) => ({ provider: { id: ID, models: async (p, { auth }) => { + // $FAKE_MODELS_LOG: each time the hook is asked is a line there + if (process.env.FAKE_MODELS_LOG) (await import("node:fs")).appendFileSync(process.env.FAKE_MODELS_LOG, "asked\n") if (auth?.refresh === "r-dead" || auth?.key === "dead") throw new Error("the vendor refused the sign-in") if (auth?.refresh === "r-models-gone") throw Object.assign(new Error("the vendor refused the sign-in"), { signIn: "expired" }) // a sign-in past its time, said in words only, as Grok's plugin says it From 8f37ed57d2a5b096f593c03ab03fdf5d91302be7 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:31:49 +0800 Subject: [PATCH 22/92] plugin: plugin-auth.json is parsed once per version of the file, not on every request Every request read and parsed plugin-auth.json in the host two or three times: accountKey (when no account is named), fresh (is a renewal due), and the plugin's getAuth from its loader's fetch. Reading and parsing a 20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine. readAuth now keeps what it parsed while the file has the same mtime, size and inode, as Go's filememo does. While the file's time is within 2 s of now it also keeps the bytes and compares them, so two same-size writes inside one tick of a coarse clock (Linux) still read as two. A file that doesn't parse is never kept, so the .bak recovery path is unchanged. changeAuth still reads afresh under the lock. The kept object is shared, so what a plugin is handed (getAuth for loader, usage and check-in, the models hook's auth, pi.js's readAuth) is a copy of its own (authCopy). Measured (load average 360-460, so absolute times are inflated): - readAuth on a settled 20 KB file, old and new interleaved in one bun process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read per call. New median 23 us (min 2.3), a stat, and 0 file reads. - whole fetch (TestPerfScratch, not committed, {} body, 400 fetches): host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise. A control run without the big file read 875 us at the same load. Host RSS 53 MB -> 42 MB. Test: TestAuthReadOncePerVersion runs host.js's own auth section in node with readFileSync counted. It checks: - 100 reads of a settled file read it once; - a rewrite is read; - a same-size rewrite with the same mtime is read; - authCopy's copies are the caller's own. Broken by hand twice, red both times: - readAuth made the old uncached read: "a settled file is read once for 100 reads, read 100 times". - bytes of a just-written file not kept: "a same-size rewrite in one tick is read". Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s (pinned pi install under load); in a full package run it hit its 4-minute start deadline ("starting plugins: context deadline exceeded"). --- internal/plugin/auth_read_once_test.go | 81 ++++++++++++++++++++++++++ internal/plugin/host.js | 50 +++++++++++++--- 2 files changed, 122 insertions(+), 9 deletions(-) create mode 100644 internal/plugin/auth_read_once_test.go diff --git a/internal/plugin/auth_read_once_test.go b/internal/plugin/auth_read_once_test.go new file mode 100644 index 000000000..da08ab1cd --- /dev/null +++ b/internal/plugin/auth_read_once_test.go @@ -0,0 +1,81 @@ +package plugin + +import ( + "bytes" + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// TestAuthReadOncePerVersion: host.js reads and parses plugin-auth.json +// once per version of the file, not on every request (its account, its +// renewal and the plugin's getAuth each read it). A file rewritten with +// the same size inside one tick of the file system's clock, which leaves +// the same time, is still read again, and a plugin's copy is its own. +func TestAuthReadOncePerVersion(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, node, "-e", authReadOnceJS, filepath.Join(t.TempDir(), "plugin-auth.json")) + cmd.Stdin = bytes.NewReader(hostJS) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, out) + } +} + +const authReadOnceJS = ` +const assert = require('node:assert/strict') +const realFs = require('node:fs') +const vm = require('node:vm') +const source = realFs.readFileSync(0, 'utf8') +const section = (from, to) => { + const start = source.indexOf(from) + const end = source.indexOf(to, start) + assert.ok(start >= 0 && end > start, 'production section exists') + return source.slice(start, end) +} +const authPath = process.argv[1] +let reads = 0 +const fs = { ...realFs, readFileSync: (p, ...rest) => { + if (p === authPath) reads++ + return realFs.readFileSync(p, ...rest) +} } +const context = vm.createContext({ fs, authPath, Buffer, structuredClone, Date, toErr: () => {}, send: () => {}, pause: () => {} }) +const run = code => vm.runInContext(code, context) +run(section('function parseAuth(', '// writeDurable')) +const past = new Date(Date.now() - 60e3) +const write = (v, at) => { + realFs.writeFileSync(authPath, JSON.stringify(v)) + if (at) realFs.utimesSync(authPath, at, at) +} + +write({ a: { type: 'api', key: 'k1' } }, past) +for (let i = 0; i < 100; i++) assert.equal(run('readAuth()').a.key, 'k1') +assert.equal(reads, 1, 'a settled file is read once for 100 reads, read ' + reads + ' times') + +// written again: read again +write({ a: { type: 'api', key: 'k2' }, b: { type: 'api', key: 'k3' } }, new Date(past.getTime() + 1000)) +assert.equal(run('readAuth()').a.key, 'k2') + +// a file written just now, rewritten with the same size and time (two +// writes inside one tick of the clock): its bytes tell them apart +const now = new Date() +write({ a: { type: 'api', key: 'x1' } }, now) +assert.equal(run('readAuth()').a.key, 'x1') +write({ a: { type: 'api', key: 'x2' } }, now) +assert.equal(run('readAuth()').a.key, 'x2', 'a same-size rewrite in one tick is read') + +// what a plugin is handed is its own to change +const copy = run('authCopy("a")') +copy.key = 'changed' +assert.equal(run('readAuth()').a.key, 'x2') +const all = run('authCopy()') +all.a.key = 'changed' +assert.equal(run('readAuth()').a.key, 'x2') +console.log('ok') +` diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 8656dd20d..ca025abba 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -716,11 +716,10 @@ let authUnread = false // readAuthState is the sign-ins and whether they are known: a file not // there is none, known; one that doesn't read is its .bak's, known, or // none, unknown. -function readAuthState() { - const buf = readFileSteady(authPath) +function readAuthState(buf = readFileSteady(authPath)) { if (buf === null) return { all: {}, known: true } const v = parseAuth(buf.toString("utf8")) - if (v) return { all: v, known: true } + if (v) return { all: v, known: true, own: true } const why = describeBad(buf) let bak = null try { @@ -741,8 +740,41 @@ function readAuthState() { return { all: {}, known: false } } +// authSeen is plugin-auth.json as last parsed, kept while the file has the +// same time, size and inode: every request read and parsed it two or three +// times (its account, its renewal, the plugin's getAuth), ~0.6 ms each for +// a dozen sign-ins. While the file's time is too recent for a second write +// to stamp a later one (Linux's clock is a tick coarse), its bytes are kept +// and compared too, as Go's filememo does. +let authSeen = null // {mtimeMs, size, ino, raw, all} +const AUTH_SETTLED = 2000 + +// readAuth is the sign-ins, shared: the caller must not change them, and +// hands a plugin a copy (authCopy). function readAuth() { - return readAuthState().all + let st = null + try { + st = fs.statSync(authPath) + } catch {} + const e = authSeen + const same = st && e && e.mtimeMs === st.mtimeMs && e.size === st.size && e.ino === st.ino + if (same && !e.raw) return e.all + const buf = readFileSteady(authPath) + if (same && buf && buf.equals(e.raw)) { + if (Date.now() - e.mtimeMs > AUTH_SETTLED) e.raw = null + return e.all + } + const s = readAuthState(buf) + authSeen = st && s.own ? { mtimeMs: st.mtimeMs, size: st.size, ino: st.ino, raw: Date.now() - st.mtimeMs > AUTH_SETTLED ? null : buf, all: s.all } : null + return s.all +} + +// authCopy is readAuth's sign-ins, or the one at key, the plugin's own to +// change. +function authCopy(key) { + const all = readAuth() + const v = key === undefined ? all : all[key] + return v === undefined ? undefined : structuredClone(v) } // writeDurable replaces p with data through a temp file flushed to the @@ -1172,7 +1204,7 @@ async function loadPlugins(list) { } const pis = pi ? list.filter((p) => pi.isPi(p.target)) : [] if (pis.length) { - const h = { readAuth, changeAuth, keyFor, send, directory } + const h = { readAuth: authCopy, changeAuth, keyFor, send, directory } const got = await pi.load(h, pis).catch((e) => pis.map((p) => ({ spec: p.spec, error: String(e?.stack ?? e) }))) for (const r of got) { for (const x of r.hooks ?? []) hooks.push(x) @@ -1692,7 +1724,7 @@ async function info(id, key, strict) { try { const given = JSON.parse(JSON.stringify(out)) const l = { tried: false, lastOk: false } - const next = await listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: all[k] }))) + const next = await listing.run(l, () => inScope(id, k, () => ph.models(given, { auth: authCopy(k) }))) // a hook that asked its vendor, got no list and gave back the one it // was given fell back: magpie keeps the list it had, as a built-in // whose fetch failed keeps the one it fetched last; so does one that @@ -2162,7 +2194,7 @@ async function options(provider, key) { let opts = {} if (a?.loader && stored) { const p = await infoOf(provider, key) - opts = (await inScope(provider, key, () => a.loader(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + opts = (await inScope(provider, key, () => a.loader(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} } if (!opts.apiKey && stored?.type === "api") opts = { ...opts, apiKey: stored.key } loaders.set(key, opts) @@ -2219,7 +2251,7 @@ async function usageOf(provider, account) { if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) const p = await infoOf(provider, key) - const u = (await inScope(provider, key, () => a.usage(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + const u = (await inScope(provider, key, () => a.usage(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} const when = (v) => { if (v === undefined || v === null || v === "") return "" const d = new Date(typeof v === "number" && v < 1e11 ? v * 1000 : v) @@ -2294,7 +2326,7 @@ async function checkinOf(provider, account) { if (!readAuth()[key]) throw new Error("not signed in") await fresh(provider, key) const p = await infoOf(provider, key) - const r = (await inScope(provider, key, () => a.checkin(async () => readAuth()[key], JSON.parse(JSON.stringify(p))))) ?? {} + const r = (await inScope(provider, key, () => a.checkin(async () => authCopy(key), JSON.parse(JSON.stringify(p))))) ?? {} const num = (v) => (typeof v === "number" && isFinite(v) ? Math.max(0, v) : 0) const message = typeof r.message === "string" ? r.message : "" if (!checkinOutcomes.includes(r.outcome)) { From ef75a9a2b54ced3ad6d4622c7154e96b1ca432c0 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:34:32 +0800 Subject: [PATCH 23/92] plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied Every chunk of a plugin's streamed reply went out as JSON.stringify({id, event: "chunk", data}), and stringify scanned every byte of the base64 for something to escape. Base64 has nothing JSON escapes, so chunkLine joins the line from strings instead. The line is byte-for-byte the one stringify made. A Uint8Array chunk that isn't a Buffer (what a Response body hands over) was also copied whole by Buffer.from before it was encoded. It is now viewed: the bytes are encoded before the next read, so nothing else touches them. Measured in bun, old and new interleaved in one process, medians (load average 363-413, so absolute times are inflated). The bench asserts the lines are equal. - 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB) - 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB) - 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB) Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB, so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It checks: - 4 chunk frames; - the bytes come back equal; - JSON.stringify never sees a chunk; - Buffer.from never copies a chunk. Broken by hand twice, red both times: - the frame built as an object again: "chunk frames are joined, not stringified"; - Buffer.from(chunk) again: "chunks are viewed, not copied". Run (load ~420): go test ./internal/plugin -count=1 -run on the host, flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks. --- internal/plugin/host.js | 15 ++++++++--- internal/plugin/host_flow_test.go | 42 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/internal/plugin/host.js b/internal/plugin/host.js index ca025abba..6badab79a 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -112,8 +112,14 @@ function queueLine(line) { // send queues one message, ignoring whether it was written. const send = (msg) => queueLine(JSON.stringify(msg) + "\n").promise -// sendCancelable is send, with a way to give the wait up. -const sendCancelable = (msg) => queueLine(JSON.stringify(msg) + "\n") +// sendCancelable is send, with a way to give the wait up. A string is a +// line made already (chunkLine). +const sendCancelable = (msg) => queueLine(typeof msg === "string" ? msg : JSON.stringify(msg) + "\n") + +// chunkLine is JSON.stringify({id, event: "chunk", data}) + "\n", made by +// joining: base64 has nothing JSON escapes, and stringify scanning every +// byte of it for something to escape cost more than the base64 itself. +const chunkLine = (id, data) => '{"id":' + JSON.stringify(id) + ',"event":"chunk","data":"' + data + '"}\n' // A host cancellation suppresses the answer; a local abort still owes Go // its error. The record, rather than the signal, owns pending wire output. @@ -2431,7 +2437,8 @@ async function fetchAs(id, record, key, params) { // the loop leaves rather than parking on a stream that never drains for await (const chunk of res.body) { checkFetch(record) - const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + // a chunk the stream handed over is this reader's: viewed, not copied + const bytes = Buffer.isBuffer(chunk) ? chunk : ArrayBuffer.isView(chunk) ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.from(chunk) for (let off = 0; off < bytes.length; ) { // one frame at a time, no more than the reader has credited: a // reader that stopped leaves the upstream paused here @@ -2440,7 +2447,7 @@ async function fetchAs(id, record, key, params) { if (n <= 0) break const data = bytes.subarray(off, off + n).toString("base64") gate.spend(n + FRAME_OVERHEAD) - await sendForFetch(record, { id, event: "chunk", data }) + await sendForFetch(record, chunkLine(id, data)) checkFetch(record) off += n } diff --git a/internal/plugin/host_flow_test.go b/internal/plugin/host_flow_test.go index 93ba2e6ba..4c0a52632 100644 --- a/internal/plugin/host_flow_test.go +++ b/internal/plugin/host_flow_test.go @@ -121,6 +121,34 @@ async function main() { assert.equal(await run('gate.take(64)'), 64) run('gate.stop(); gate.add(1)') assert.equal(await run('gate.take(64)'), -1, 'stopped gate refuses remaining credit') + } else if (name === 'chunk-frames') { + const parts = [new Uint8Array([0, 1, 2, 250, 251, 252]), Buffer.from('data: {"a":"\\u00e9 \\"q\\""}\n\n'), new Uint8Array(70 << 10).fill(65)] + context.reply.body = (async function* () { for (const p of parts) yield p })() + let copies = 0 + let stringified = 0 + const realJSON = run('JSON') + context.Buffer = new Proxy(Buffer, { get(target, key) { + if (key !== 'from') return Reflect.get(target, key) + return (...args) => { + if (args.length === 1 && ArrayBuffer.isView(args[0])) copies++ + return target.from(...args) + } + } }) + context.JSON = { parse: realJSON.parse, stringify: (v, ...rest) => { + if (v && v.event === 'chunk') stringified++ + return realJSON.stringify(v, ...rest) + } } + fetchOne() + await until(idle, 'streamed fetch settles') + context.Buffer = Buffer + delete context.JSON + const chunks = lines.filter(msg => msg.event === 'chunk') + assert.ok(chunks.every(msg => msg.id === 1), 'every frame is the fetch\'s') + assert.equal(chunks.length, 4, 'a chunk over 64 KB goes in two frames') + assert.deepEqual(Buffer.concat(chunks.map(msg => Buffer.from(msg.data, 'base64'))), Buffer.concat(parts)) + assert.deepEqual(lines.map(msg => msg.event || 'result'), ['head', 'chunk', 'chunk', 'chunk', 'chunk', 'result']) + assert.equal(stringified, 0, 'chunk frames are joined, not stringified') + assert.equal(copies, 0, 'chunks are viewed, not copied') } else if (name === 'split-chunk') { blockOn = 'chunk' context.reply.body = (async function* () { yield Buffer.alloc(3 * (64 << 10)) })() @@ -651,6 +679,20 @@ func TestFlowBigReplyProd(t *testing.T) { // vendor's head — leave the host able to answer a later request. It is the Go // side of the lifecycle: the host's slots come back, and the JS side's own // finally (covered by construction) lets each request's controller and gate go. +// TestHostFramesChunksCheaply: the body's chunks go out as the same frames, +// but without copying each chunk or stringifying each frame: stringify +// scanned every base64 byte for something to escape, which cost more than +// the base64. +func TestHostFramesChunksCheaply(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + if out, err := runHostJSCase(t, node, "chunk-frames"); err != nil { + t.Fatalf("chunk frames: %v\n%s", err, out) + } +} + func TestFlowAbortDuringSetupStaysHealthy(t *testing.T) { node, err := exec.LookPath("node") if err != nil { From 5774c790bdd62533179b705a1dba8c19cff5d481 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:38:03 +0800 Subject: [PATCH 24/92] plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame) went through json.Unmarshal into message. encoding/json scanned every byte twice (validating, then decoding the string) and cost far more than decoding the base64 itself. chunkFrame reads the one shape host.js's chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line, or one whose data holds a quote or a backslash, still goes through json.Unmarshal. push checks the data is base64 of a frame's size either way, as before. Measured (64 KB frame, json vs chunkFrame, each followed by the base64 decode push does; -cpu 1, 6 runs, load average ~480, so absolute times are inflated): - json.Unmarshal + DecodeString: 7.3-14.0 ms/op, median ~8.7 ms - chunkFrame + DecodeString: 0.11-2.3 ms/op, median ~0.33 ms Test: TestChunkFrameReadsWithoutJSON. Frames json.Marshal'd with a \n, \r\n or no line end must parse and equal what json.Unmarshal makes. It also refuses 11 other shapes, among them: - an escape in the data; - a negative id, or 1e3; - extra fields or trailing bytes; - a 20-digit id; - reordered keys. Broken by hand (chunkFrame always false), it went red: "a chunk frame as host.js writes it ... went through encoding/json". Run (load ~420): go test ./internal/plugin -count=1 -run on the chunk frame, host, flow, stream, chunk, credit and fetch tests: ok (54.0 s). The whole package runs with the final checks. --- internal/plugin/chunk_frame_test.go | 66 +++++++++++++++++++++++++++++ internal/plugin/host.go | 45 +++++++++++++++++++- 2 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 internal/plugin/chunk_frame_test.go diff --git a/internal/plugin/chunk_frame_test.go b/internal/plugin/chunk_frame_test.go new file mode 100644 index 000000000..e73e50e0b --- /dev/null +++ b/internal/plugin/chunk_frame_test.go @@ -0,0 +1,66 @@ +package plugin + +import ( + "encoding/base64" + "encoding/json" + "strings" + "testing" +) + +// TestChunkFrameReadsWithoutJSON: a chunk frame as host.js writes it +// (JSON.stringify({id, event: "chunk", data}), which chunkLine joins by +// hand) is read without encoding/json, and reads the same as through it. +// Any line of another shape goes through encoding/json as before. +func TestChunkFrameReadsWithoutJSON(t *testing.T) { + raw := make([]byte, 70<<10) + for i := range raw { + raw[i] = byte(i * 31) + } + for _, tc := range []struct { + id int64 + data string + }{ + {1, base64.StdEncoding.EncodeToString(raw)}, + {987654321, base64.StdEncoding.EncodeToString([]byte("data: {}\n\n"))}, + {42, "AA=="}, + } { + b, err := json.Marshal(struct { + ID int64 `json:"id"` + Event string `json:"event"` + Data string `json:"data"` + }{tc.id, "chunk", tc.data}) + if err != nil { + t.Fatal(err) + } + for _, line := range []string{string(b) + "\n", string(b), string(b) + "\r\n"} { + got, ok := chunkFrame([]byte(line)) + if !ok { + t.Fatalf("a chunk frame as host.js writes it (%.60q…) went through encoding/json", line) + } + var want message + if err := json.Unmarshal([]byte(line), &want); err != nil { + t.Fatal(err) + } + if got.ID != want.ID || got.Event != want.Event || got.Data != want.Data { + t.Fatalf("read as id %d %q %d bytes, encoding/json reads id %d %q %d bytes", got.ID, got.Event, len(got.Data), want.ID, want.Event, len(want.Data)) + } + } + } + for _, line := range []string{ + `{"id":1,"event":"head","status":200,"headers":{}}`, + `{"id":1,"result":null}`, + `{"id":1,"event":"chunk","data":"QU` + "\\" + `/A"}`, // an escape: JSON reads it otherwise + `{"id":1,"event":"chunk","data":"QUFB\"}`, + `{"id":-1,"event":"chunk","data":"QUFB"}`, + `{"id":1e3,"event":"chunk","data":"QUFB"}`, + `{"id":1,"event":"chunk","data":"QUFB","x":"y"}`, + `{"id":1,"event":"chunk","data":"QUFB"} `, + `{"id":1,"event":"chunk","data":"` + strings.Repeat("A", 8) + `"}x`, + `{"id":12345678901234567890,"event":"chunk","data":"QUFB"}`, + `{"event":"chunk","id":1,"data":"QUFB"}`, + } { + if m, ok := chunkFrame([]byte(line)); ok { + t.Fatalf("%s read as a chunk frame %+v, want it left to encoding/json", line, m) + } + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index b1843548f..e037d29d5 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -2,6 +2,7 @@ package plugin import ( "bufio" + "bytes" "context" "crypto/sha256" _ "embed" @@ -1033,8 +1034,9 @@ func (h *host) read(out io.Reader) { for { line, err := readLine(r, h.lineLimit()) if len(line) > 0 { - var m message - if json.Unmarshal(line, &m) == nil { + if m, ok := chunkFrame(line); ok { + h.dispatch(m) + } else if json.Unmarshal(line, &m) == nil { h.dispatch(m) } } @@ -1057,6 +1059,45 @@ func (h *host) read(out io.Reader) { h.fail(fmt.Errorf("the plugin host quit: %v", err)) } +var ( + chunkHead = []byte(`{"id":`) + chunkMid = []byte(`,"event":"chunk","data":"`) +) + +// chunkFrame is the chunk frame in line when it has exactly the shape +// host.js's chunkLine writes, {"id":N,"event":"chunk","data":"…"}, with +// nothing in the data JSON would escape: the reply's bytes come in these, +// and encoding/json scanned every base64 byte of each, several times what +// decoding them costs. Any other line is not one, and is unmarshalled; push +// checks the data is base64 of a frame's size either way. +func chunkFrame(line []byte) (message, bool) { + line = bytes.TrimSuffix(bytes.TrimSuffix(line, []byte("\n")), []byte("\r")) + rest, ok := bytes.CutPrefix(line, chunkHead) + if !ok { + return message{}, false + } + i := bytes.IndexByte(rest, ',') + if i <= 0 || i > 18 { + return message{}, false + } + var id int64 + for _, c := range rest[:i] { + if c < '0' || c > '9' { + return message{}, false + } + id = id*10 + int64(c-'0') + } + data, ok := bytes.CutPrefix(rest[i:], chunkMid) + if !ok { + return message{}, false + } + data, ok = bytes.CutSuffix(data, []byte(`"}`)) + if !ok || bytes.IndexByte(data, '"') >= 0 || bytes.IndexByte(data, '\\') >= 0 { + return message{}, false + } + return message{ID: id, Event: "chunk", Data: string(data)}, true +} + // readLine reads one '\n'-terminated line, at most max bytes, so a child that // never ends a line cannot make the host allocate without bound. It is // errLineTooLong once max is passed. From d9f6b42cbcde5625065f5bf25654f96a18db2671 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:14:58 +0800 Subject: [PATCH 25/92] sessions: a Grok Build session read before is read on from where it was left, not whole Grok Build only appends to a session's updates.jsonl, but every change to it (and every rewrite of its summary.json, whose size and mtime are folded into the file's) made the Sessions and Usage pages parse the whole file again. parseGrok now keeps a tail (tail.go) with its summary: the offset after the last whole line, the file's head and a sampled prefix hash. The next read goes on from that offset when the file has only grown and the summary still names the same model, created time and parent; the first prompt still coming in chunks carries over too. A file that shrank, or whose head or sampled prefix changed, is read whole again, and a half line at the end waits for the next read. Measured (CPU, getrusage; 50 MB updates.jsonl, a turn appended between reads; the machine was loaded, so CPU time, not wall): before: 46 ms per read after an append (same as the first read) after: 0.2 ms per read after an append; first read 44 ms Tests: TestGrokReadsOnlyWhatWasAppended checks where each read starts (through scanHook) and that every read on from a tail equals a whole read: a line appended is read alone; half a line waits and is counted once; the file cut back to its old bytes, or one byte changed in place in a line it had, is read whole; a summary-only change reads nothing of the updates; a changed model reads whole. TestGrokPromptAcrossReads carries a chunked first prompt across reads. Broken by hand: resume turned off -> red ("after a line appended to 2684 bytes, read from 0"); tail.holds made to trust any grown file -> red ("rewritten in place, read from 3055"). Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/grok.go | 165 +++++++++++++++++++----------- internal/sessions/grow_test.go | 182 +++++++++++++++++++++++++++++++++ internal/sessions/sessions.go | 13 ++- internal/sessions/tail.go | 50 +++++++++ 4 files changed, 347 insertions(+), 63 deletions(-) create mode 100644 internal/sessions/grow_test.go create mode 100644 internal/sessions/tail.go diff --git a/internal/sessions/grok.go b/internal/sessions/grok.go index a0bb3b7ee..a679067d7 100644 --- a/internal/sessions/grok.go +++ b/internal/sessions/grok.go @@ -132,80 +132,123 @@ var ( grokHook = []byte(`"sessionUpdate":"hook_execution"`) ) -// parseGrok reads a session's updates whole, with its summary. -func parseGrok(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time - model := "" +// grokCarry is what a read of a Grok Build session's updates carries on +// with: where it read to, what of its summary the updates were counted +// under, and its first prompt as far as it was read. +type grokCarry struct { + Tail *tail `json:"tail,omitempty"` + Created time.Time `json:"created,omitzero"` + Since time.Time `json:"since,omitzero"` + Model string `json:"model,omitempty"` + Prompt string `json:"prompt,omitempty"` + InPrompt bool `json:"in_prompt,omitempty"` + // the first prompt, before it is told from a tag + Title string `json:"title,omitempty"` +} + +// parseGrok reads a session's updates, with its summary. Grok Build only +// appends to updates.jsonl, so a session read before is read on from where +// that read left off; its summary, rewritten as it goes on, is read again +// each time. When the file was cut short or replaced, or the summary now +// says another time or model the updates are counted under, it is read +// whole again. +func parseGrok(f file, old *state) *state { + var c grokCarry + var m grokSummary + hasM := false if f.manifest != "" { - if m, ok := readGrokSummary(f.manifest); ok { - s.ID, s.Cwd, model = m.Info.ID, m.Info.Cwd, m.CurrentModel - s.Named = title(m.GeneratedTitle) - if s.Named == "" { - s.Named = title(m.SessionSummary) - } - created, _ := time.Parse(time.RFC3339Nano, m.CreatedAt) + if m, hasM = readGrokSummary(f.manifest); hasM { + c.Model = m.CurrentModel + c.Created, _ = time.Parse(time.RFC3339Nano, m.CreatedAt) if m.Parent != "" { // what it copied from its source is older than it - since = created.Truncate(time.Second) + c.Since = c.Created.Truncate(time.Second) } - s.saw(created, f.main) + } else { + m = grokSummary{} } } - prompt, inPrompt := "", false - scan(f.path, 0, func(b []byte) { - at := numTS(b) - if !since.IsZero() && at.Before(since) { - return - } - if bytes.Contains(b, grokHook) { - // its hooks run as it starts and ends too: a session left open - // overnight isn't at work till it is closed - return - } - s.saw(at, f.main) - user := f.main && s.Title == "" && bytes.Contains(b, grokUser) - if !user && inPrompt { - // the first prompt's chunks are over - s.Title, inPrompt = title(prompt), false - } - if !user && !bytes.Contains(b, grokTurn) { - return - } - var l grokLine - if json.Unmarshal(b, &l) != nil { - return - } - u := l.Params.Update - switch u.SessionUpdate { - case "user_message_chunk": - if user && u.Content.Type == "text" { - prompt += u.Content.Text - inPrompt = true - } - case "turn_completed": - if u.Usage == nil { - return - } - date := dateOf(at) - if len(u.Usage.ModelUsage) == 0 { - s.use(date, cmp.Or(model, "grok"), u.Usage.tokens()) - return - } - for name, mu := range u.Usage.ModelUsage { - s.use(date, name, mu.tokens()) - } + var s *state + var off int64 + if o := old; o != nil && o.Grok != nil && o.Grok.Model == c.Model && o.Grok.Created.Equal(c.Created) && o.Grok.Since.Equal(c.Since) && o.Grok.Tail.holds(f.path) { + s, c, off = o.clone(), *o.Grok, o.Grok.Tail.Off + } else { + s = &state{} + if hasM { + s.saw(c.Created, f.main) } + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + s.ID, s.Cwd, s.Named = m.Info.ID, m.Info.Cwd, title(m.GeneratedTitle) + if s.Named == "" { + s.Named = title(m.SessionSummary) + } + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + grokUpdate(s, &c, b, f.main) + return true }) - if inPrompt { - s.Title = title(prompt) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) } - if strings.HasPrefix(s.Title, "<") { - s.Title, s.First = "", untagged(s.Title) + t := c.Title + if c.InPrompt { + t = title(c.Prompt) } + s.Title, s.First = t, "" + if strings.HasPrefix(t, "<") { + s.Title, s.First = "", untagged(t) + } + s.Grok = &c return s } +// grokUpdate counts one line of a session's updates. +func grokUpdate(s *state, c *grokCarry, b []byte, main bool) { + at := numTS(b) + if !c.Since.IsZero() && at.Before(c.Since) { + return + } + if bytes.Contains(b, grokHook) { + // its hooks run as it starts and ends too: a session left open + // overnight isn't at work till it is closed + return + } + s.saw(at, main) + user := main && c.Title == "" && bytes.Contains(b, grokUser) + if !user && c.InPrompt { + // the first prompt's chunks are over + c.Title, c.Prompt, c.InPrompt = title(c.Prompt), "", false + } + if !user && !bytes.Contains(b, grokTurn) { + return + } + var l grokLine + if json.Unmarshal(b, &l) != nil { + return + } + u := l.Params.Update + switch u.SessionUpdate { + case "user_message_chunk": + if user && u.Content.Type == "text" { + c.Prompt += u.Content.Text + c.InPrompt = true + } + case "turn_completed": + if u.Usage == nil { + return + } + date := dateOf(at) + if len(u.Usage.ModelUsage) == 0 { + s.use(date, cmp.Or(c.Model, "grok"), u.Usage.tokens()) + return + } + for name, mu := range u.Usage.ModelUsage { + s.use(date, name, mu.tokens()) + } + } +} + var tsKey = []byte(`"timestamp":`) // numTS reads the time of a line from its first "timestamp" key when it is diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go new file mode 100644 index 000000000..46bb38fa2 --- /dev/null +++ b/internal/sessions/grow_test.go @@ -0,0 +1,182 @@ +package sessions + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" +) + +// grower reads one session file as refresh does, each parse on from the +// one kept before, and checks every such parse against a whole read of the +// same file: a summary read on from where it was is the one a whole read +// makes. start is where the last parse began reading the file. +type grower struct { + t *testing.T + files func() []file + path string + old *state + start int64 +} + +func (g *grower) file() file { + g.t.Helper() + for _, f := range g.files() { + if f.path == g.path { + return f + } + } + g.t.Fatalf("no file %s", g.path) + return file{} +} + +// read parses the file on from the last parse and says where it started. +func (g *grower) read() int64 { + g.t.Helper() + f := g.file() + g.start = -1 + scanHook = func(p string, off int64) { + if p == g.path && g.start < 0 { + g.start = off + } + } + defer func() { scanHook = nil }() + s := parse(f, g.old) + scanHook = nil + whole := parse(f, nil) + got, _ := json.Marshal(s) + want, _ := json.Marshal(whole) + if !bytes.Equal(got, want) { + g.t.Fatalf("read on from %d:\n%s\nread whole:\n%s", g.start, got, want) + } + g.old = s + return g.start +} + +func (g *grower) size() int64 { + g.t.Helper() + fi, err := os.Stat(g.path) + if err != nil { + g.t.Fatal(err) + } + return fi.Size() +} + +func (g *grower) append(s string) { + g.t.Helper() + f, err := os.OpenFile(g.path, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + g.t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteString(s); err != nil { + g.t.Fatal(err) + } +} + +// grows runs the cases every reader of an appended file meets: a line +// appended is the only thing read; half a line waits for the rest and is +// counted once; a file cut short, or replaced by one as long, is read whole +// again. line is a whole line the file may take, with its newline. +func checkGrows(t *testing.T, g *grower, line string) { + t.Helper() + orig, err := os.ReadFile(g.path) + if err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("first read started at %d", at) + } + // a line appended: only it is read + was := g.size() + g.append(line) + if at := g.read(); at != was { + t.Fatalf("after a line appended to %d bytes, read from %d", was, at) + } + // half a line, still being written: it waits for the rest + was = g.size() + half := len(line) / 2 + g.append(line[:half]) + if at := g.read(); at != was { + t.Fatalf("with half a line at %d, read from %d", was, at) + } + g.append(line[half:]) + if at := g.read(); at != was { + t.Fatalf("the half line finished at %d, read from %d", was, at) + } + // cut short: read whole again + if err := os.WriteFile(g.path, orig, 0o644); err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("cut short, read from %d", at) + } + // replaced by another as long, its first line changed: read whole + g.append(line) + g.read() + b, _ := os.ReadFile(g.path) + other := append([]byte(nil), b...) + other[len(orig)-2] ^= 1 // a line it had, changed in place + if bytes.Equal(other, b) { + t.Fatal("not changed") + } + if err := os.WriteFile(g.path, other, 0o644); err != nil { + t.Fatal(err) + } + if at := g.read(); at != 0 { + t.Fatalf("rewritten in place, read from %d", at) + } +} + +// Grok Build appends to a session's updates.jsonl: a turn that ended is +// read alone, not the session again. +func TestGrokReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", grokMain) + g := &grower{t: t, files: grokFiles, path: filepath.Join(dir, "updates.jsonl")} + turn := `{"timestamp":1790496140,"method":"_x.ai/session/update","params":{"sessionId":"` + grokMain + `","update":{"sessionUpdate":"turn_completed","usage":{"inputTokens":200,"outputTokens":6,"cachedReadTokens":100,"cacheCreationTokens":0,"modelUsage":{"grok-4.7-build":{"inputTokens":200,"outputTokens":6,"cachedReadTokens":100,"cacheCreationTokens":0}}}}}}` + "\n" + checkGrows(t, g, turn) + + // its summary rewritten, a title given: nothing of the updates read + g.read() + summary := filepath.Join(dir, "summary.json") + b, _ := os.ReadFile(summary) + os.WriteFile(summary, bytes.Replace(b, []byte(`"generated_title": "Parser port"`), []byte(`"generated_title": "Port of the parser"`), 1), 0o644) + if at, end := g.read(), g.size(); at != end || g.old.Named != "Port of the parser" { + t.Fatalf("summary changed: read from %d of %d, named %q", at, end, g.old.Named) + } + // the model its turns are counted under changed: read whole + b, _ = os.ReadFile(summary) + os.WriteFile(summary, bytes.Replace(b, []byte(`"current_model_id": "grok-4.7"`), []byte(`"current_model_id": "grok-5"`), 1), 0o644) + if at := g.read(); at != 0 { + t.Fatalf("model changed: read from %d", at) + } +} + +// A first prompt still coming in chunks when a read ends goes on in the +// next one. +func TestGrokPromptAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", "0190aaaa-0000-7000-8000-0000000000ee") + os.MkdirAll(dir, 0o755) + os.WriteFile(filepath.Join(dir, "summary.json"), []byte(`{"info":{"id":"0190aaaa-0000-7000-8000-0000000000ee","cwd":"/w"},"created_at":"2026-09-27T08:00:00Z"}`), 0o644) + chunk := func(ts int, text string) string { + return fmt.Sprintf(`{"timestamp":%d,"params":{"update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":%q}}}}`+"\n", ts, text) + } + p := filepath.Join(dir, "updates.jsonl") + os.WriteFile(p, []byte(chunk(1790496001, "Port the ")), 0o644) + g := &grower{t: t, files: grokFiles, path: p} + g.read() + g.append(chunk(1790496002, "parser")) + g.read() + g.append(`{"timestamp":1790496003,"params":{"update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"}}}}` + "\n") + g.read() + g.append(chunk(1790496004, "and more")) + if g.read(); g.old.Title != "Port the parser" { + t.Fatalf("title %q", g.old.Title) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index dd96027b5..8e1be82df 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -210,6 +210,9 @@ type state struct { // Pi: in a forked session, the time it was forked; the lines before // it are the copy of the session it was forked from Since time.Time `json:"since,omitzero"` + // Grok Build: where its updates were read to, and what the read + // carries on with + Grok *grokCarry `json:"grok,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -1170,7 +1173,10 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { // parserFor is the source of truth for both parsing and window admission. // A default line reader is Claude-compatible, including both Qoder variants. type sessionParser struct { - whole func(file) *state + whole func(file) *state + // grow reads a file on from where the kept parse of it left off, when + // the file has only grown since (tail.go), else whole + grow func(file, *state) *state line func(*state, []byte, bool) claude bool } @@ -1188,7 +1194,7 @@ func parserFor(agent string) sessionParser { case "cline": return sessionParser{whole: parseCline} case "grok": - return sessionParser{whole: parseGrok} + return sessionParser{grow: parseGrok} case "kimi": return sessionParser{whole: parseKimi} case "droid": @@ -1217,6 +1223,9 @@ func parse(f file, old *state) *state { if parser.whole != nil { return parser.whole(f) } + if parser.grow != nil { + return parser.grow(f, old) + } // Every source using claudeLine must rebuild a missing transient window. if parser.claude && old != nil && old.Claude == nil { old = nil diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go new file mode 100644 index 000000000..8c6cbbc98 --- /dev/null +++ b/internal/sessions/tail.go @@ -0,0 +1,50 @@ +package sessions + +import "os" + +// tail is where a reader of a file another agent appends to left off: the +// offset after the last whole line it handled, and enough of the file as it +// was to know it again. A summary kept with one reads on from Off when the +// file has only grown, instead of reading it whole again (Grok Build's +// sessions are kept so). A file that shrank, or whose +// start or sampled prefix is no longer what was read, is read whole again: +// it was rewritten or replaced, not appended to. +// +// A packed file (frames of zstd) is read on from the frame at Off, Skip +// bytes into what that frame holds, and Size there is the end of that frame: +// the bytes hashed always take in what is read again. +type tail struct { + Off int64 `json:"off"` + Skip int64 `json:"skip,omitempty"` + Size int64 `json:"size"` + Head string `json:"head"` + HeadSize int `json:"head_size"` + Hash string `json:"hash"` +} + +// markTail is the tail of a file read up to off, its first size bytes the +// ones read and to be found again. +func markTail(path string, off, skip, size int64) *tail { + head := headOf(path) + if int64(len(head)) > size { + head = head[:size] + } + h := prefixHash(path, size) + if h == "" && size > 0 { + return nil + } + return &tail{Off: off, Skip: skip, Size: size, Head: hashHead(head), HeadSize: len(head), Hash: h} +} + +// holds says whether the file at path is still the one t was read from, +// grown or as it was, so it can be read on from t.Off. +func (t *tail) holds(path string) bool { + if t == nil { + return false + } + fi, err := os.Stat(path) + if err != nil || fi.Size() < t.Size || t.Off > t.Size { + return false + } + return sameHead(headOf(path), t.Head, t.HeadSize) && prefixHash(path, t.Size) == t.Hash +} From b9b4c21c5bc1361ff5234ed9be5ebd2dc046a0fc Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:17:18 +0800 Subject: [PATCH 26/92] sessions: a Droid transcript read before is read on from where it was left, not whole Droid only appends to a session's transcript, but every message (and every rewrite of its settings.json, whose size and mtime are folded into the transcript's) made the Sessions and Usage pages parse the whole transcript again. parseDroid now keeps a tail (tail.go) and what the read carries on with: whether the session_start line and a fork's copied lines are behind it, and what the settings' running total was counted as (date, model, tokens). The next read takes that total back (dropUse, which leaves no empty model or day behind, so the summary is the one a whole read makes), reads on from the tail, and counts the total again on the day of the last message. A transcript that shrank or was replaced is read whole again; a half line waits for the next read. Measured (CPU, getrusage; 50 MB transcript, a message appended between reads; machine loaded): before: ~490 ms per read after an append (same as the first read) after: 0.2-1.8 ms per read after an append; first read ~470 ms Tests: TestDroidReadsOnlyWhatWasAppended runs the shared append, half line, cut-short and rewritten-in-place cases, then a message a day later with a grown total (counted once, moved to the new day), then a settings-only change (nothing of the transcript read). Every read on is checked equal to a whole read. TestDroidForkAcrossReads appends a fork's copied lines one read at a time. Broken by hand: resume off -> red ("after a line appended to 825 bytes, read from 0"); the old total not taken back -> red (read on differs from whole). Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/droid.go | 164 ++++++++++++++++++++------------- internal/sessions/grow_test.go | 53 +++++++++++ internal/sessions/sessions.go | 5 +- internal/sessions/tail.go | 29 +++++- 4 files changed, 187 insertions(+), 64 deletions(-) diff --git a/internal/sessions/droid.go b/internal/sessions/droid.go index cbf7473ff..885688508 100644 --- a/internal/sessions/droid.go +++ b/internal/sessions/droid.go @@ -153,68 +153,46 @@ func droidTools(raw json.RawMessage) []string { return out } -// parseDroid reads a session's transcript whole, with its settings. -func parseDroid(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - // a fork's lines up to upto are copies of its source's - upto, copied := "", false - first := true - scan(f.path, 0, func(b []byte) { - var l droidLine - if json.Unmarshal(b, &l) != nil { - return - } - if first { - first = false - var st droidStart - if l.Type == "session_start" && json.Unmarshal(b, &st) == nil { - s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title) - if s.Named == "New Session" { - s.Named = "" // Droid's until it names one - } - if st.LastCwd != "" { - s.Cwd = st.LastCwd - } - upto, copied = st.Forked, st.Forked != "" - } - return - } - if l.Type != "message" { - return - } - if copied { - if l.ID == upto { - copied = false - } - return - } - at := tsAt(b, false) - s.saw(at, f.main) - switch l.Message.Role { - case "user": - text := droidText(l.Message.Content) - if strings.TrimSpace(text) == "" || !f.main { - return - } - if strings.HasPrefix(strings.TrimSpace(text), "<") { - if s.First == "" { - s.First = untagged(text) - } - return - } - s.day(dateOf(at)).Prompts++ - if s.Title == "" { - s.Title = title(text) - } - case "assistant": - if f.main { - s.day(dateOf(at)).Replies++ - } - for _, name := range droidTools(l.Message.Content) { - s.tool(at, name, "") - } - } +// droidCarry is what a read of a Droid transcript carries on with: where +// it read to, whether it has passed the session_start line and a fork's +// copied lines, and what its settings' total was counted as, to be taken +// back when the total moves on. +type droidCarry struct { + Tail *tail `json:"tail,omitempty"` + Started bool `json:"started,omitempty"` + Upto string `json:"upto,omitempty"` + Copied bool `json:"copied,omitempty"` + // the settings' total, as counted + Date string `json:"date,omitempty"` + Model string `json:"model,omitempty"` + Tokens Tokens `json:"tokens,omitzero"` +} + +// parseDroid reads a session's transcript, with its settings. Droid only +// appends to a transcript, so one read before is read on from where that +// read left off, and its settings' running total, counted on the day of +// the last message, is taken back and counted again as it is now. A +// transcript cut short or replaced is read whole again. +func parseDroid(f file, old *state) *state { + var s *state + var c droidCarry + var off int64 + if old != nil && old.Droid != nil && old.Droid.Tail.holds(f.path) { + s, c, off = old.clone(), *old.Droid, old.Droid.Tail.Off + s.dropUse(c.Date, c.Model, c.Tokens) + } else { + s = &state{} + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + droidLineOf(s, &c, b, f.main) + return true }) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) + } + c.Date, c.Model, c.Tokens = "", "", Tokens{} if f.manifest != "" { var st droidSettings if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &st) == nil && st.Usage != nil { @@ -223,12 +201,74 @@ func parseDroid(f file) *state { when = time.Unix(0, s.Mod) } u := st.Usage - s.use(dateOf(when), droidModelName(st.Model), Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) + c.Date, c.Model = dateOf(when), droidModelName(st.Model) + c.Tokens = Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite} + s.use(c.Date, c.Model, c.Tokens) } } + s.Droid = &c return s } +// droidLineOf counts one line of a transcript. +func droidLineOf(s *state, c *droidCarry, b []byte, main bool) { + var l droidLine + if json.Unmarshal(b, &l) != nil { + return + } + if !c.Started { + c.Started = true + var st droidStart + if l.Type == "session_start" && json.Unmarshal(b, &st) == nil { + s.ID, s.Cwd, s.Named = st.ID, st.Cwd, title(st.Title) + if s.Named == "New Session" { + s.Named = "" // Droid's until it names one + } + if st.LastCwd != "" { + s.Cwd = st.LastCwd + } + // a fork's lines up to Upto are copies of its source's + c.Upto, c.Copied = st.Forked, st.Forked != "" + } + return + } + if l.Type != "message" { + return + } + if c.Copied { + if l.ID == c.Upto { + c.Copied = false + } + return + } + at := tsAt(b, false) + s.saw(at, main) + switch l.Message.Role { + case "user": + text := droidText(l.Message.Content) + if strings.TrimSpace(text) == "" || !main { + return + } + if strings.HasPrefix(strings.TrimSpace(text), "<") { + if s.First == "" { + s.First = untagged(text) + } + return + } + s.day(dateOf(at)).Prompts++ + if s.Title == "" { + s.Title = title(text) + } + case "assistant": + if main { + s.day(dateOf(at)).Replies++ + } + for _, name := range droidTools(l.Message.Content) { + s.tool(at, name, "") + } + } +} + // droidSlot is the tail droid gives a custom model's id made of its name // ("custom:Kimi-K2-[Groq]-0"). var droidSlot = regexp.MustCompile(`(-\[[^\]]*\])?-\d+$`) diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go index 46bb38fa2..68d17c93e 100644 --- a/internal/sessions/grow_test.go +++ b/internal/sessions/grow_test.go @@ -180,3 +180,56 @@ func TestGrokPromptAcrossReads(t *testing.T) { t.Fatalf("title %q", g.old.Title) } } + +// Droid appends to a transcript and keeps a running total in its +// settings: a message appended is read alone, and the total, counted on +// the day of the last message, moves with it instead of being counted twice. +func TestDroidReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + dir := filepath.Join(home, ".factory", "sessions", "-work-droid") + g := &grower{t: t, files: droidFiles, path: filepath.Join(dir, droidMain+".jsonl")} + msg := `{"type":"message","id":"m5","timestamp":"2026-09-27T08:03:00.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Fixed"},{"type":"tool_use","id":"t2","name":"Edit","input":{}}]}}` + "\n" + checkGrows(t, g, msg) + + // a day later, the total grown: counted once, on the new day + g.read() + was := g.size() + g.append(`{"type":"message","id":"m6","timestamp":"2026-09-28T09:00:00.000Z","message":{"role":"user","content":"and the logout one"}}` + "\n") + os.WriteFile(filepath.Join(dir, droidMain+".settings.json"), []byte(`{"model":"claude-opus-4-5","tokenUsage":{"inputTokens":300,"outputTokens":80,"cacheCreationTokens":10,"cacheReadTokens":2000}}`), 0o644) + if at := g.read(); at != was { + t.Fatalf("read from %d, not %d", at, was) + } + if d := g.old.Days["2026-09-27"]; d == nil || len(d.Models) != 0 { + t.Fatalf("the total is still on the day before: %+v", d) + } + if m := g.old.Days["2026-09-28"].Models["claude-opus-4-5"]; m.Input != 300 { + t.Fatalf("the total on its day: %+v", g.old.Days["2026-09-28"]) + } + // only the settings changed: nothing of the transcript read + os.WriteFile(filepath.Join(dir, droidMain+".settings.json"), []byte(`{"model":"claude-opus-4-5","tokenUsage":{"inputTokens":400,"outputTokens":90}}`), 0o644) + if at, end := g.read(), g.size(); at != end { + t.Fatalf("settings changed: read from %d of %d", at, end) + } +} + +// A fork's copied lines that end in a later read are still passed over. +func TestDroidForkAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + p := filepath.Join(home, ".factory", "sessions", "-work-droid", droidFork+".jsonl") + b, _ := os.ReadFile(p) + lines := bytes.SplitAfter(b, []byte("\n")) + os.WriteFile(p, bytes.Join(lines[:3], nil), 0o644) + g := &grower{t: t, files: droidFiles, path: p} + g.read() + for _, l := range lines[3:] { + g.append(string(l)) + g.read() + } + if g.old.Title != "Try another way" { + t.Fatalf("title %q", g.old.Title) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 8e1be82df..46cc3fe38 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -213,6 +213,9 @@ type state struct { // Grok Build: where its updates were read to, and what the read // carries on with Grok *grokCarry `json:"grok,omitempty"` + // Droid: where its transcript was read to, and what the read carries + // on with + Droid *droidCarry `json:"droid,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -1198,7 +1201,7 @@ func parserFor(agent string) sessionParser { case "kimi": return sessionParser{whole: parseKimi} case "droid": - return sessionParser{whole: parseDroid} + return sessionParser{grow: parseDroid} case "cursor": return sessionParser{whole: parseCursor} case "codex": diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go index 8c6cbbc98..3d717bcf0 100644 --- a/internal/sessions/tail.go +++ b/internal/sessions/tail.go @@ -6,7 +6,7 @@ import "os" // offset after the last whole line it handled, and enough of the file as it // was to know it again. A summary kept with one reads on from Off when the // file has only grown, instead of reading it whole again (Grok Build's -// sessions are kept so). A file that shrank, or whose +// and Droid's sessions are kept so). A file that shrank, or whose // start or sampled prefix is no longer what was read, is read whole again: // it was rewritten or replaced, not appended to. // @@ -48,3 +48,30 @@ func (t *tail) holds(path string) bool { } return sameHead(headOf(path), t.Head, t.HeadSize) && prefixHash(path, t.Size) == t.Hash } + +// dropUse takes back what use counted, leaving no model or day it made +// with nothing in it: a summary read on from where it was is then the one +// a whole read makes. +func (s *state) dropUse(date, model string, t Tokens) { + if t.zero() { + return + } + s.unuse(date, model, t) + if m, ok := s.Models[model]; ok && m.zero() { + delete(s.Models, model) + if len(s.Models) == 0 { + s.Models = nil + } + } + if d := s.Days[date]; d != nil { + if m, ok := d.Models[model]; ok && m.zero() { + delete(d.Models, model) + if len(d.Models) == 0 { + d.Models = nil + } + } + if len(d.Models) == 0 && d.Active == 0 && d.Hours == nil && d.Prompts == 0 && d.Replies == 0 && d.Tools == nil && d.Skills == nil { + delete(s.Days, date) + } + } +} From e03d495f8324ba014000ee76cb14b0a8f966ed28 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:57:42 +0800 Subject: [PATCH 27/92] sessions: a Kimi Code session read before is read on from where it was left, not whole Kimi Code only appends to a session's wire.jsonl, but every message (and every rewrite of its state.json, whose size and mtime are folded into the wire's) made the Sessions and Usage pages read the whole wire again, a fork's twice: once for its last marker, once to count. parseKimi is now one pass that keeps a tail (tail.go) and what the read carries on with: the session's start, whether it is a fork, and the fork's marker time. A forked marker met in a later read starts the counts over from it, as a whole read does. Title, cwd and name still come from state.json on every read, so a state.json-only change reads none of the wire. A forkedFrom set or cleared reads whole again, and so does a wire that shrank or was replaced; a half line waits. Measured (CPU, getrusage; 50 MB wire, a message appended between reads; machine loaded): before: ~256-278 ms per read after an append (same as the first read) after: 0.3-0.6 ms per read after an append Tests: TestKimiReadsOnlyWhatWasAppended runs the shared append, half line, cut-short and rewritten-in-place cases on a real wire's events, then a state.json title change (nothing of the wire read) and a forkedFrom set (read whole). Every read on is checked equal to a whole read. TestKimiForkMarkerAcrossReads writes a fork's copied lines, then its marker, then its own usage, a read apart each: only the fork's own usage counts. Broken by hand: resume off -> red ("after a line appended to 29089 bytes, read from 0"); the marker's reset removed -> red in TestKimiForkMarkerAcrossReads and TestKimiCodeSessionFork. Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/grow_test.go | 54 +++++++++ internal/sessions/kimi.go | 213 +++++++++++++++++++-------------- internal/sessions/kimi_test.go | 2 +- internal/sessions/sessions.go | 5 +- internal/sessions/tail.go | 4 +- 5 files changed, 182 insertions(+), 96 deletions(-) diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go index 68d17c93e..1324eef26 100644 --- a/internal/sessions/grow_test.go +++ b/internal/sessions/grow_test.go @@ -233,3 +233,57 @@ func TestDroidForkAcrossReads(t *testing.T) { t.Fatalf("title %q", g.old.Title) } } + +// Kimi Code appends to an agent's wire.jsonl: a record appended is read +// alone, and a state.json rewritten reads nothing of the wire. +func TestKimiReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".kimi-code") + kimiSessionsIn(t, dir) + sessions := filepath.Join(dir, "sessions") + slug := "wd_v14-cancel_000000000003" + g := &grower{t: t, files: kimiFiles, path: filepath.Join(sessions, slug, kimiCancel, "agents", "main", "wire.jsonl")} + rec := `{"type":"usage.record","model":"kimi-code/k3","usage":{"inputOther":40,"output":5,"inputCacheRead":900,"inputCacheCreation":0},"usageScope":"turn","time":1784687340000}` + "\n" + checkGrows(t, g, rec) + + g.read() + kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"title": "Cancelled twice", "isCustomTitle": true}) + if at, end := g.read(), g.size(); at != end || g.old.Custom != "Cancelled twice" { + t.Fatalf("state.json changed: read from %d of %d, custom %q", at, end, g.old.Custom) + } + // the session now says it was forked: what it counted is read again + kimiSetState(t, sessions, slug, kimiCancel, map[string]any{"forkedFrom": kimiJune}) + if at := g.read(); at != 0 { + t.Fatalf("made a fork: read from %d", at) + } +} + +// A fork's marker that comes in a later read still ends its copy of its +// source: what was counted before it is taken back. +func TestKimiForkMarkerAcrossReads(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "home", ".kimi-code") + kimiSessionsIn(t, dir) + sessions := filepath.Join(dir, "sessions") + slug := "wd_v14-cancel_000000000003" + src, err := os.ReadFile(filepath.Join(sessions, slug, kimiCancel, "agents", "main", "wire.jsonl")) + if err != nil { + t.Fatal(err) + } + id := "session_f0000000-0000-4000-8000-0000000000aa" + w := filepath.Join(sessions, slug, id, "agents", "main", "wire.jsonl") + os.MkdirAll(filepath.Dir(w), 0o755) + os.WriteFile(w, src, 0o644) + kimiSetState(t, sessions, slug, id, map[string]any{"cwd": "/w", "createdAt": int64(1784687000000), "title": "Again", "forkedFrom": kimiCancel}) + g := &grower{t: t, files: kimiFiles, path: w} + g.read() + g.append(`{"type":"forked","agentId":"main","time":1791700000000}` + "\n") + g.read() + g.append(`{"type":"usage.record","model":"kimi-code/k3","usage":{"inputOther":7,"output":3,"inputCacheRead":0,"inputCacheCreation":0},"usageScope":"turn","time":1791700005000}` + "\n") + g.read() + if g.old.Models["kimi-code/k3"] != (Tokens{Input: 7, Output: 3}) || len(g.old.Models) != 1 { + t.Fatalf("the fork's own: %+v", g.old.Models) + } +} diff --git a/internal/sessions/kimi.go b/internal/sessions/kimi.go index 4ebcaf1ff..42b76fdd6 100644 --- a/internal/sessions/kimi.go +++ b/internal/sessions/kimi.go @@ -196,103 +196,132 @@ var ( kimiCounts = [][]byte{kimiUsageRecord, []byte(`"turn.prompt"`), []byte(`"step.end"`), []byte(`"tool.call"`)} ) -// parseKimi reads one agent's wire file of a session whole, with the -// session's state.json for its own. -func parseKimi(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time - forked := false - if st, ok := kimiStateOf(f.path); ok { - created := kimiTime(st.CreatedAt) - forked = st.ForkedFrom != "" - if forked { - since = created - } - if f.main { - s.Cwd = cmp.Or(st.Cwd, st.WorkDir, kimiIndexedWorkDir(f.path)) - s.Custom, s.Named = st.names() - s.Custom, s.Named = title(s.Custom), title(s.Named) - s.saw(created, true) +// kimiCarry is what a read of a Kimi Code wire file carries on with: +// where it read to, what of state.json its records were counted under, +// and the time before which a fork's records are its source's. +type kimiCarry struct { + Tail *tail `json:"tail,omitempty"` + Created time.Time `json:"created,omitzero"` + Forked bool `json:"forked,omitempty"` + Since time.Time `json:"since,omitzero"` +} + +// parseKimi reads one agent's wire file of a session, with the session's +// state.json for its own. Kimi only appends to a wire file, so one read +// before is read on from where that read left off; state.json, rewritten +// as the session goes on, is read again each time. A file cut short or +// replaced, or a state.json that now says another creation or fork, is +// read whole again. +func parseKimi(f file, old *state) *state { + var c kimiCarry + var st kimiState + hasSt := false + if st, hasSt = kimiStateOf(f.path); hasSt { + c.Created = kimiTime(st.CreatedAt) + c.Forked = st.ForkedFrom != "" + if c.Forked { + c.Since = c.Created } } - // a fork's copy of its source ends at its last marker - skip := 0 - if forked { - n := 0 - scan(f.path, 0, func(b []byte) { - n++ - if bytes.Contains(b, kimiForked) { - var r kimiWire - if json.Unmarshal(b, &r) == nil && r.Type == "forked" { - skip, since = n, time.Time{} - } - } - }) + fresh := func() *state { + s := &state{} + if hasSt && f.main { + s.saw(c.Created, true) + } + return s } - n := 0 - scan(f.path, 0, func(b []byte) { - n++ - if n <= skip { - return - } - count := false - for _, k := range kimiCounts { - if bytes.Contains(b, k) { - count = true - break - } - } - var r kimiWire - if !count { - // only its time: a light read of the rest - var t struct { - Time int64 `json:"time"` - } - if json.Unmarshal(b, &t) == nil { - if at := ms(t.Time); !at.IsZero() && !at.Before(since) { - s.saw(at, f.main) - } - } - return - } - if json.Unmarshal(b, &r) != nil { - return - } - at := ms(r.Time) - if at.IsZero() || at.Before(since) { - return - } - s.saw(at, f.main) - switch r.Type { - case "usage.record": - if u := r.Usage; u != nil && u.InputOther >= 0 && u.Output >= 0 && u.InputCacheRead >= 0 && u.InputCacheCreation >= 0 { - model := cmp.Or(strings.TrimPrefix(r.Model, kimiGateway), "kimi") - s.use(dateOf(at), model, Tokens{Input: u.InputOther, Output: u.Output, CacheRead: u.InputCacheRead, CacheWrite: u.InputCacheCreation}) - } - case "turn.prompt": - if !f.main || r.Origin.Kind != "user" { - return - } - s.day(dateOf(at)).Prompts++ - if s.Title == "" { - var text []string - for _, p := range r.Input { - if p.Type == "text" { - text = append(text, p.Text) - } - } - s.Title = title(strings.Join(text, " ")) - } - case "context.append_loop_event": - switch r.Event.Type { - case "step.end": - if f.main && r.Event.FinishReason == "end_turn" { - s.day(dateOf(at)).Replies++ - } - case "tool.call": - s.tool(at, r.Event.Name, "") + var s *state + var off int64 + if o := old; o != nil && o.Kimi != nil && o.Kimi.Created.Equal(c.Created) && o.Kimi.Forked == c.Forked && o.Kimi.Tail.holds(f.path) { + s, c, off = o.clone(), *o.Kimi, o.Kimi.Tail.Off + } else { + s = fresh() + } + end, err := scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { + if c.Forked && bytes.Contains(b, kimiForked) { + var r kimiWire + if json.Unmarshal(b, &r) == nil && r.Type == "forked" { + // a fork's copy of its source ends at its last marker: + // what was counted before it is its source's + s, c.Since = fresh(), time.Time{} + return true } } + kimiCount(s, b, c.Since, f.main) + return true }) + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, end, 0, end) + } + s.Size, s.Mod = f.size, f.mod.UnixNano() + if hasSt && f.main { + s.Cwd = cmp.Or(st.Cwd, st.WorkDir, kimiIndexedWorkDir(f.path)) + s.Custom, s.Named = st.names() + s.Custom, s.Named = title(s.Custom), title(s.Named) + } + s.Kimi = &c return s } + +// kimiCount counts one record of a wire file, none before since. +func kimiCount(s *state, b []byte, since time.Time, main bool) { + count := false + for _, k := range kimiCounts { + if bytes.Contains(b, k) { + count = true + break + } + } + var r kimiWire + if !count { + // only its time: a light read of the rest + var t struct { + Time int64 `json:"time"` + } + if json.Unmarshal(b, &t) == nil { + if at := ms(t.Time); !at.IsZero() && !at.Before(since) { + s.saw(at, main) + } + } + return + } + if json.Unmarshal(b, &r) != nil { + return + } + at := ms(r.Time) + if at.IsZero() || at.Before(since) { + return + } + s.saw(at, main) + switch r.Type { + case "usage.record": + if u := r.Usage; u != nil && u.InputOther >= 0 && u.Output >= 0 && u.InputCacheRead >= 0 && u.InputCacheCreation >= 0 { + model := cmp.Or(strings.TrimPrefix(r.Model, kimiGateway), "kimi") + s.use(dateOf(at), model, Tokens{Input: u.InputOther, Output: u.Output, CacheRead: u.InputCacheRead, CacheWrite: u.InputCacheCreation}) + } + case "turn.prompt": + if !main || r.Origin.Kind != "user" { + return + } + s.day(dateOf(at)).Prompts++ + if s.Title == "" { + var text []string + for _, p := range r.Input { + if p.Type == "text" { + text = append(text, p.Text) + } + } + s.Title = title(strings.Join(text, " ")) + } + case "context.append_loop_event": + switch r.Event.Type { + case "step.end": + if main && r.Event.FinishReason == "end_turn" { + s.day(dateOf(at)).Replies++ + } + case "tool.call": + s.tool(at, r.Event.Name, "") + } + } +} diff --git a/internal/sessions/kimi_test.go b/internal/sessions/kimi_test.go index e4967bc90..53255462e 100644 --- a/internal/sessions/kimi_test.go +++ b/internal/sessions/kimi_test.go @@ -187,7 +187,7 @@ func TestKimiCodeSessionCounts(t *testing.T) { } sum := func(id string) (prompts, replies, tools int, custom, named string) { for _, f := range byKey["kimi:"+id] { - s := parseKimi(f) + s := parseKimi(f, nil) for _, d := range s.Days { prompts += d.Prompts replies += d.Replies diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 46cc3fe38..71c81ff0d 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -216,6 +216,9 @@ type state struct { // Droid: where its transcript was read to, and what the read carries // on with Droid *droidCarry `json:"droid,omitempty"` + // Kimi Code: where its wire file was read to, and what the read + // carries on with + Kimi *kimiCarry `json:"kimi,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -1199,7 +1202,7 @@ func parserFor(agent string) sessionParser { case "grok": return sessionParser{grow: parseGrok} case "kimi": - return sessionParser{whole: parseKimi} + return sessionParser{grow: parseKimi} case "droid": return sessionParser{grow: parseDroid} case "cursor": diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go index 3d717bcf0..69544e494 100644 --- a/internal/sessions/tail.go +++ b/internal/sessions/tail.go @@ -5,8 +5,8 @@ import "os" // tail is where a reader of a file another agent appends to left off: the // offset after the last whole line it handled, and enough of the file as it // was to know it again. A summary kept with one reads on from Off when the -// file has only grown, instead of reading it whole again (Grok Build's -// and Droid's sessions are kept so). A file that shrank, or whose +// file has only grown, instead of reading it whole again (Grok Build's, +// Droid's and Kimi Code's sessions are kept so). A file that shrank, or whose // start or sampled prefix is no longer what was read, is read whole again: // it was rewritten or replaced, not appended to. // From b3642e72770007e5f30dbed282eed0d70aa5a98d Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 06:36:39 +0800 Subject: [PATCH 28/92] sessions: a dsh session read before is read on from where it was left, not whole dsh only appends to a session file, a line at a time or, packed (.zstd), a frame of lines at a time. Every reply still made the Sessions and Usage pages read, and for a packed file decompress, the whole file again: a packed file "can't be read on from the middle of a frame". It can be read on from the start of one. frames.go walks a file of zstd frames without decoding them (RFC 8878: the frame header, then blocks that each give their length, then the checksum), decodes one frame at a time, and says where to go on from: the frame the first line not yet whole starts in, and how far into what it holds. A frame not yet written whole waits for the next read, and so does a line a frame ends inside of. parseDsh keeps a tail (tail.go) and the header it read, and counts each event as it comes (dshCount) instead of collecting them all first. A fork's inherited end-seed met in a later read starts the counts over from the session's start, keeping its title and name, as the whole read did by cutting at the last one. A file that shrank or was replaced is read whole again. One change from before: a last line not ended by a newline now waits for it, like every other appended file's. Measured (CPU, getrusage; 50 MB of events, a reply appended between reads; packed: 17 MB of frames; machine loaded): plain before: ~110-120 ms per read after an append after: 0.4-2.6 ms per read after an append; first read ~120 ms packed before: ~190-250 ms per read after an append after: 0.4-0.5 ms per read after an append; first read ~260 ms Tests: TestDshReadsOnlyWhatWasAppended runs the shared append, half line, cut-short and rewritten-in-place cases. TestDshPackedReadsOnlyWhatWasAppended appends a frame (read alone), half a frame (waits), a frame ending inside a line and the frame that ends it (read on from the first of the two, the line counted once), then cuts the file short and replaces it with a longer one (read whole). TestDshEndSeedAcrossReads writes a fork's seeded lines, its end-seed and its own, a read apart each. Every read on is checked equal to a whole read. Broken by hand: resume off -> red in both ReadsOnly tests ("after a line appended to 1308 bytes, read from 0", "after a frame appended to 654 bytes, read from 0"); a line split over two frames resumed at the second frame -> red (read on differs from whole); the end-seed reset removed -> red in TestDshEndSeedAcrossReads and TestDsh. Run: go test ./internal/sessions -count=1 -timeout 45m ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/dsh.go | 177 ++++++++++++++++------------ internal/sessions/frames.go | 203 +++++++++++++++++++++++++++++++++ internal/sessions/grow_test.go | 113 ++++++++++++++++++ internal/sessions/sessions.go | 4 +- internal/sessions/tail.go | 14 +-- 5 files changed, 429 insertions(+), 82 deletions(-) create mode 100644 internal/sessions/frames.go diff --git a/internal/sessions/dsh.go b/internal/sessions/dsh.go index 55c0865db..baf62c6c2 100644 --- a/internal/sessions/dsh.go +++ b/internal/sessions/dsh.go @@ -4,7 +4,6 @@ import ( "bufio" "bytes" "encoding/json" - "errors" "fmt" "io" "os" @@ -242,88 +241,118 @@ type dshEvent struct { var dshWanted = [][]byte{[]byte(`"user/message"`), []byte(`"session/title"`), []byte(`"assistant/message"`), []byte(`"session/end-seed"`)} -// parseDsh reads a session file whole: compressed, it can't be read on from -// the middle of a frame. -func parseDsh(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - r, err := dshOpen(f.path) - if err != nil { - return s +// dshCarry is what a read of a dsh session file carries on with: where it +// read to and the header it read first. +type dshCarry struct { + Tail *tail `json:"tail,omitempty"` + Head dshHead `json:"head"` +} + +// parseDsh reads a session file. dsh only appends to one, a line at a time +// or, packed, a frame of lines at a time, so a file read before is read on +// from where that read left off: a packed one from the frame it left off +// in. A file cut short or replaced is read whole again, and a line or frame +// not yet written whole waits for the next read. +func parseDsh(f file, old *state) *state { + var s *state + var c dshCarry + var off, skip int64 + if old != nil && old.Dsh != nil && old.Dsh.Tail.holds(f.path) { + s, c = old.clone(), *old.Dsh + off, skip = c.Tail.Off, c.Tail.Skip + } else { + s = &state{} } - defer r.Close() - br := bufio.NewReaderSize(r, 1<<20) - var h dshHead - var evs []dshEvent - for first := true; ; first = false { - b, err := br.ReadBytes('\n') - if err != nil { - // a line still being written, or a frame cut short - if !errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0 { - break + s.Size, s.Mod = f.size, f.mod.UnixNano() + headed := c.Tail != nil + ok := true + each := func(b []byte) bool { + b = bytes.TrimSpace(b) + if len(b) == 0 || len(b) > maxLine { + return true + } + if !headed { + headed = true + if json.Unmarshal(b, &c.Head) != nil || c.Head.Type != "session" { + ok = false + return false } + s.ID, s.Cwd = c.Head.ID, c.Head.Cwd + s.saw(ms(c.Head.CreatedAt), f.main) + return true } - if b = bytes.TrimSpace(b); len(b) > 0 && len(b) <= maxLine { - if first { - if json.Unmarshal(b, &h) != nil || h.Type != "session" { - return s - } - } else if dshWant(b) { - var e dshEvent - if json.Unmarshal(b, &e) == nil && e.Type != "" { - evs = append(evs, e) - } - } else if t := dshNum(b, "time"); t > 0 { - // only its time and place looked at - e := dshEvent{Time: t} - if n := dshNum(b, "seq"); n >= 0 { - e.Seq = &n - } - evs = append(evs, e) - } - } - if err != nil { - break - } + dshCount(s, &c.Head, b, f.main) + return true } - s.ID, s.Cwd = h.ID, h.Cwd - // the events a fork was seeded with - cut := -1 - if h.Version >= 2 && h.IsSeeded { - for i, e := range evs { - if e.Type == "session/end-seed" && e.Data.Inherited { - cut = i - } - } + var next, nextSkip, end int64 + var err error + if packed(f.path) { + next, nextSkip, end, err = scanFrames(f.path, off, skip, each) + } else { + next, err = scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { return each(b) }) + end = next } - s.saw(ms(h.CreatedAt), f.main) - for i, e := range evs { - inherited := i <= cut || h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength - switch e.Type { - case "user/message": - if f.main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" { - if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") { - s.First = untagged(t) - } else { - s.Title = title(t) - } - } - case "session/title": - if t := title(e.Data.Title); t != "" { - s.Named = t - } - } - if inherited { - continue - } - at := ms(e.Time) - s.saw(at, f.main) - if u := e.Data.Usage; e.Type == "assistant/message" && u != nil && e.Data.Message.Source.Model != "" { - s.use(dateOf(at), e.Data.Message.Source.Model, Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) - } + if !ok { + // not a session's file: only its size and time + return &state{Size: f.size, Mod: f.mod.UnixNano()} } + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, next, nextSkip, end) + } + s.Dsh = &c return s } +// dshCount counts one event of a session file after its header. +func dshCount(s *state, h *dshHead, b []byte, main bool) { + var e dshEvent + if dshWant(b) { + if json.Unmarshal(b, &e) != nil || e.Type == "" { + return + } + } else if t := dshNum(b, "time"); t > 0 { + // only its time and place looked at + e.Time = t + if n := dshNum(b, "seq"); n >= 0 { + e.Seq = &n + } + } else { + return + } + switch e.Type { + case "user/message": + if main && s.Title == "" && s.First == "" && e.Data.Source.Kind == "user" { + if t := ccText(e.Data.Content); strings.HasPrefix(t, "<") { + s.First = untagged(t) + } else { + s.Title = title(t) + } + } + case "session/title": + if t := title(e.Data.Title); t != "" { + s.Named = t + } + case "session/end-seed": + if h.Version >= 2 && h.IsSeeded && e.Data.Inherited { + // the events a fork was seeded with end here: what was + // counted of them is its source's + n := &state{ID: s.ID, Cwd: s.Cwd, Title: s.Title, First: s.First, Named: s.Named, Size: s.Size, Mod: s.Mod} + n.saw(ms(h.CreatedAt), main) + *s = *n + return + } + } + if h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength { + return + } + at := ms(e.Time) + s.saw(at, main) + if u := e.Data.Usage; e.Type == "assistant/message" && u != nil && e.Data.Message.Source.Model != "" { + s.use(dateOf(at), e.Data.Message.Source.Model, Tokens{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) + } +} + func dshWant(b []byte) bool { for _, w := range dshWanted { if bytes.Contains(b, w) { diff --git a/internal/sessions/frames.go b/internal/sessions/frames.go new file mode 100644 index 000000000..520a12674 --- /dev/null +++ b/internal/sessions/frames.go @@ -0,0 +1,203 @@ +package sessions + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "io" + "os" + + "github.com/klauspost/compress/zstd" +) + +// Reading on through a file of zstd frames, as dsh writes its sessions: a +// batch of whole lines a frame, appended. A frame can't be read from its +// middle, but it can be found without decoding it (RFC 8878: its header, +// then blocks that each say how long they are), so a read goes on from the +// frame it left off in, passing over what that frame gave it before. A +// last frame not yet written whole waits for the next read. + +var errFrame = errors.New("not a zstd frame") + +// readFrame reads the frame at r into buf: a zstd frame whole, nil for a +// skippable one. io.ErrUnexpectedEOF when the file ends inside it, io.EOF +// when it ends before it. +func readFrame(r *bufio.Reader, buf []byte) ([]byte, int64, error) { + buf = buf[:0] + var n int64 + take := func(k int) ([]byte, error) { + start := len(buf) + buf = append(buf, make([]byte, k)...) + if _, err := io.ReadFull(r, buf[start:]); err != nil { + if errors.Is(err, io.EOF) { + err = io.ErrUnexpectedEOF + } + return nil, err + } + n += int64(k) + return buf[start:], nil + } + if _, err := r.Peek(1); err != nil { + return nil, 0, io.EOF + } + magic, err := take(4) + if err != nil { + return nil, 0, err + } + m := binary.LittleEndian.Uint32(magic) + if m&0xFFFFFFF0 == 0x184D2A50 { + size, err := take(4) + if err != nil { + return nil, 0, err + } + k := int64(binary.LittleEndian.Uint32(size)) + if d, err := r.Discard(int(k)); err != nil || int64(d) < k { + return nil, 0, io.ErrUnexpectedEOF + } + return nil, n + k, nil + } + if m != 0xFD2FB528 { + return nil, 0, errFrame + } + fhd, err := take(1) + if err != nil { + return nil, 0, err + } + d := fhd[0] + single := d>>5&1 == 1 + extra := 0 + if !single { + extra++ // window descriptor + } + extra += []int{0, 1, 2, 4}[d&3] // dictionary id + switch d >> 6 { + case 0: + if single { + extra++ + } + case 1: + extra += 2 + case 2: + extra += 4 + case 3: + extra += 8 + } + if _, err := take(extra); err != nil { + return nil, 0, err + } + for { + h, err := take(3) + if err != nil { + return nil, 0, err + } + v := uint32(h[0]) | uint32(h[1])<<8 | uint32(h[2])<<16 + size := int(v >> 3) + switch v >> 1 & 3 { + case 1: + size = 1 // RLE: one byte, repeated + case 3: + return nil, 0, errFrame + } + if _, err := take(size); err != nil { + return nil, 0, err + } + if v&1 == 1 { + break + } + } + if d>>2&1 == 1 { + if _, err := take(4); err != nil { + return nil, 0, err + } + } + return buf, n, nil +} + +// scanFrames hands fn each whole line of a file of zstd frames, from the +// frame at off, skip bytes into what that frame holds. It returns where to +// go on from (the frame the first line not yet whole starts in, and how far +// into it) and where the last whole frame read ends. +func scanFrames(path string, off, skip int64, fn func([]byte) bool) (next, nextSkip, end int64, err error) { + if scanHook != nil { + scanHook(path, off) + } + next, nextSkip, end = off, skip, off + f, err := os.Open(path) + if err != nil { + return + } + defer f.Close() + if _, err = f.Seek(off, io.SeekStart); err != nil { + return + } + dec, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), zstd.WithDecoderLowmem(true)) + if err != nil { + return + } + defer dec.Close() + r := bufio.NewReaderSize(f, 1<<20) + var frame, out, pending []byte + at := off + first := true + for { + var n int64 + frame, n, err = readFrame(r, frame) + if err != nil { + // the end, a frame still being written, or not one at all: + // what was read stands, the rest waits for the next read + err = nil + return + } + start := at + at += n + end = at + if frame == nil { + if len(pending) == 0 { + next, nextSkip = at, 0 + } + continue + } + if out, err = dec.DecodeAll(frame, out[:0]); err != nil { + err = nil + end = start + return + } + from := int64(0) + if first { + first = false + if skip > int64(len(out)) { + err = errFrame + return + } + from = skip + } + data := out[from:] + for { + i := bytes.IndexByte(data, '\n') + if i < 0 { + break + } + line := data[:i] + if len(pending) > 0 { + line = append(pending, line...) + pending = pending[:0] + } + if !fn(line) { + return + } + from += int64(i + 1) + data = data[i+1:] + } + if len(data) == 0 { + if len(pending) == 0 { + next, nextSkip = at, 0 + } + continue + } + if len(pending) == 0 { + next, nextSkip = start, from + } + pending = append(pending, data...) + } +} diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go index 1324eef26..3c7aecccb 100644 --- a/internal/sessions/grow_test.go +++ b/internal/sessions/grow_test.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "testing" + + "github.com/klauspost/compress/zstd" ) // grower reads one session file as refresh does, each parse on from the @@ -287,3 +289,114 @@ func TestKimiForkMarkerAcrossReads(t *testing.T) { t.Fatalf("the fork's own: %+v", g.old.Models) } } + +const dshReply = `{"type":"assistant/message","seq":6,"time":1790503290000,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":1,"outputTokens":1,"cacheReadTokens":0}}}` + "\n" + +// dsh appends to a session file a line at a time: a reply is read alone. +func TestDshReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + checkGrows(t, &grower{t: t, files: dshFiles, path: p}, dshReply) +} + +// Packed, dsh appends a frame of lines at a time: a frame appended is read +// alone, from where it starts; a frame not yet written whole waits, and so +// does a line a frame ends inside of, read on from the frame it starts in. +func TestDshPackedReadsOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + plain := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + b, err := os.ReadFile(plain) + if err != nil { + t.Fatal(err) + } + os.Remove(plain) + enc, _ := zstd.NewWriter(nil) + defer enc.Close() + frame := func(s string) []byte { return enc.EncodeAll([]byte(s), nil) } + p := plain + ".zstd" + half := bytes.IndexByte(b[len(b)/2:], '\n') + len(b)/2 + 1 + orig := append(frame(string(b[:half])), frame(string(b[half:]))...) + os.WriteFile(p, orig, 0o644) + g := &grower{t: t, files: dshFiles, path: p} + if at := g.read(); at != 0 { + t.Fatalf("first read started at %d", at) + } + reply := func(seq int) string { + return fmt.Sprintf(`{"type":"assistant/message","seq":%d,"time":%d,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":%d,"outputTokens":1,"cacheReadTokens":0}}}`+"\n", seq, 1790503290000+int64(seq)*1000, seq) + } + // a frame appended: only it is read + was := g.size() + g.append(string(frame(reply(6)))) + if at := g.read(); at != was { + t.Fatalf("after a frame appended to %d bytes, read from %d", was, at) + } + // half a frame, still being written: it waits for the rest + was = g.size() + f := frame(reply(7)) + g.append(string(f[:len(f)/2])) + if at := g.read(); at != was { + t.Fatalf("with half a frame at %d, read from %d", was, at) + } + g.append(string(f[len(f)/2:])) + if at := g.read(); at != was { + t.Fatalf("the half frame finished at %d, read from %d", was, at) + } + // a frame that ends inside a line: the line goes on in the next + // frame, and the next read starts at the frame it starts in, past + // what of that frame it counted + was = g.size() + r9 := reply(9) + g.append(string(frame(reply(8) + r9[:20]))) + if at := g.read(); at != was { + t.Fatalf("a frame ending in a line at %d, read from %d", was, at) + } + g.append(string(frame(r9[20:]))) + if at := g.read(); at != was { + t.Fatalf("the line finished in the next frame, read from %d, not its frame's %d", at, was) + } + if m := g.old.Models["deepseek-v4-flash"]; m.Input != 10+6+7+8+9 { + t.Fatalf("flash, each reply once: %+v", m) + } + // cut short: read whole again + os.WriteFile(p, orig, 0o644) + if at := g.read(); at != 0 { + t.Fatalf("cut short, read from %d", at) + } + // replaced by one longer, its first frame changed: read whole + g.append(string(frame(reply(6)))) + g.read() + other := append(frame(string(bytes.Replace(b[:half], []byte("house rules"), []byte("house_rules"), 1))), frame(string(b[half:]))...) + for len(other) <= int(g.size()) { + other = append(other, frame(reply(6))...) + } + os.WriteFile(p, other, 0o644) + if at := g.read(); at != 0 { + t.Fatalf("replaced, read from %d", at) + } +} + +// A fork's end-seed that comes in a later read still ends what it was +// seeded with: what was counted before it is its source's. +func TestDshEndSeedAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-c", "session.v3.jsonl") + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + cut := bytes.Index(b, []byte(`{"type":"session/end-seed"`)) + rest := bytes.IndexByte(b[cut:], '\n') + cut + 1 + os.WriteFile(p, b[:cut], 0o644) + g := &grower{t: t, files: dshFiles, path: p} + g.read() + g.append(string(b[cut:rest])) + g.read() + g.append(string(b[rest:])) + g.read() + if m := g.old.Models["deepseek-v4-pro"]; m.Input != 50 || len(g.old.Models) != 1 || g.old.Title != "Tidy the build script" { + t.Fatalf("the fork's own: %+v, title %q", g.old.Models, g.old.Title) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 71c81ff0d..44e88442d 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -219,6 +219,8 @@ type state struct { // Kimi Code: where its wire file was read to, and what the read // carries on with Kimi *kimiCarry `json:"kimi,omitempty"` + // dsh: where its file was read to, and its header + Dsh *dshCarry `json:"dsh,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -1196,7 +1198,7 @@ func parserFor(agent string) sessionParser { case "opencode", "zcode": return sessionParser{whole: parseOpenCode} case "dsh": - return sessionParser{whole: parseDsh} + return sessionParser{grow: parseDsh} case "cline": return sessionParser{whole: parseCline} case "grok": diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go index 69544e494..3ceb8553c 100644 --- a/internal/sessions/tail.go +++ b/internal/sessions/tail.go @@ -5,14 +5,14 @@ import "os" // tail is where a reader of a file another agent appends to left off: the // offset after the last whole line it handled, and enough of the file as it // was to know it again. A summary kept with one reads on from Off when the -// file has only grown, instead of reading it whole again (Grok Build's, -// Droid's and Kimi Code's sessions are kept so). A file that shrank, or whose -// start or sampled prefix is no longer what was read, is read whole again: -// it was rewritten or replaced, not appended to. +// file has only grown, instead of reading it whole again (dsh's, Grok +// Build's, Droid's and Kimi Code's sessions are kept so). A file that +// shrank, or whose start or sampled prefix is no longer what was read, is +// read whole again: it was rewritten or replaced, not appended to. // -// A packed file (frames of zstd) is read on from the frame at Off, Skip -// bytes into what that frame holds, and Size there is the end of that frame: -// the bytes hashed always take in what is read again. +// A packed file (frames of zstd, frames.go) is read on from the frame at +// Off, Skip bytes into what that frame holds, and Size there is the end of +// that frame: the bytes hashed always take in what is read again. type tail struct { Off int64 `json:"off"` Skip int64 `json:"skip,omitempty"` From 6d3caf6fa45173454c7b776e44548644530dcfca Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 06:52:03 +0800 Subject: [PATCH 29/92] sessions: a Cline session whose manifest alone changed is not read again Cline keeps a session's messages in one JSON document, rewritten whole, and its title, start and fork in a manifest beside it, whose size and mtime are folded into the session file's. Cline rewrites that manifest on its own (a title given, the session's status touched), and every such rewrite made the Sessions and Usage pages decode the whole messages file again, though nothing in it had changed. parseCline now keeps what its messages were counted from: the messages file's own size and mtime, and the start and fork time the manifest gave then, with the first prompt that names the session. When the messages file is as it was and the manifest still gives the same start and fork, the counts stand and only the manifest is read again for the id, cwd, name and title. Messages rewritten (any size or mtime change), or a start or fork that moved, read them whole again as before. A messages document can't be read on from where it was: it is rewritten, not appended to. Measured (CPU, getrusage; 50 MB messages file, the manifest rewritten between reads; machine loaded): before: ~205-290 ms per read after a manifest change after: 0.1 ms per read after a manifest change; first read ~290 ms Test: TestClineReadsMessagesOnlyWhenTheyChange counts reads of the messages file (clineHook) and checks each read against a whole one: a manifest touched or titled reads none of it, and the title from the first prompt stays; a message changed, the same size at a later time, a fork added and the start moved each read it again. Broken by hand: no resume -> red ("manifest touched: messages read again"); the start and fork not compared -> red (read on differs from whole, after the fork); the carried prompt dropped -> red (read on differs from whole). Run: go test ./internal/sessions -run Cline -count=1 ok, and the whole package green at the previous commit; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/cline.go | 84 ++++++++++++++++++++++----- internal/sessions/grow_test.go | 101 +++++++++++++++++++++++++++++++++ internal/sessions/sessions.go | 4 +- 3 files changed, 173 insertions(+), 16 deletions(-) diff --git a/internal/sessions/cline.go b/internal/sessions/cline.go index 7374e2ce1..4b3d2d150 100644 --- a/internal/sessions/cline.go +++ b/internal/sessions/cline.go @@ -95,38 +95,87 @@ type clineMessage struct { } `json:"metrics"` } -// parseCline reads a session's messages whole, as they are written. -func parseCline(f file) *state { - s := &state{Size: f.size, Mod: f.mod.UnixNano()} - var since time.Time +// clineCarry is what a read of a session's messages.json keeps, to know +// whether it can stand for the next: the file as it was read, and what of +// the manifest its counts were made under. Prompt is the first prompt in +// it that names the session, for when the manifest's doesn't. +type clineCarry struct { + Size int64 `json:"size"` + Mod int64 `json:"mod"` + Since time.Time `json:"since,omitzero"` + Start time.Time `json:"start,omitzero"` + Prompt string `json:"prompt,omitempty"` +} + +// parseCline reads a session's messages whole, as they are written, with +// its manifest. Cline rewrites the manifest on its own (a title given, the +// session touched), so when only that changed and it still says the same +// start and fork, what the messages were counted as stands and only the +// manifest is read again. +func parseCline(f file, old *state) *state { + var since, start time.Time + var m clineManifest + hasM := false if f.manifest != "" { - var m clineManifest if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &m) == nil { - s.ID, s.Cwd = m.SessionID, m.Cwd - s.Named = title(m.Metadata.Title) + hasM = true if m.Metadata.Fork != nil { since, _ = time.Parse(time.RFC3339Nano, m.Metadata.Fork.ForkedAt) } - start, _ := time.Parse(time.RFC3339Nano, m.StartedAt) - if since.IsZero() || !start.Before(since) { - s.saw(start, f.main) + at, _ := time.Parse(time.RFC3339Nano, m.StartedAt) + if since.IsZero() || !at.Before(since) { + start = at } + } + } + name := func(s *state, prompt string) *state { + s.Size, s.Mod = f.size, f.mod.UnixNano() + s.ID, s.Cwd, s.Named, s.Title, s.First = "", "", "", "", "" + if hasM { + s.ID, s.Cwd = m.SessionID, m.Cwd + s.Named = title(m.Metadata.Title) clineTitle(s, m.Prompt) } + if f.main { + clineTitle(s, prompt) + } + return s + } + fi, err := os.Stat(f.path) + if err != nil { + return name(&state{}, "") + } + if o := old; o != nil && o.Cline != nil && o.Cline.Size == fi.Size() && o.Cline.Mod == fi.ModTime().UnixNano() && o.Cline.Since.Equal(since) && o.Cline.Start.Equal(start) { + s := o.clone() + return name(s, o.Cline.Prompt) // the title its messages gave, when the manifest gives none + + } + s := &state{} + s.saw(start, f.main) + c := &clineCarry{Size: fi.Size(), Mod: fi.ModTime().UnixNano(), Since: since, Start: start} + if clineHook != nil { + clineHook(f.path) } b, err := os.ReadFile(f.path) if err != nil { - return s + return name(s, "") } var doc struct { Messages []clineMessage `json:"messages"` } if json.Unmarshal(b, &doc) != nil { - return s + // half written, or not Cline's: read again when it changes + return name(s, "") } + named := false for _, m := range doc.Messages { - if f.main && m.Role == "user" && s.Title == "" && s.First == "" { - clineTitle(s, ccText(m.Content)) + if !named && m.Role == "user" { + // the first prompt that names the session by itself + var t state + text := ccText(m.Content) + if clineTitle(&t, text); t.Title != "" || t.First != "" { + c.Prompt, named = text, true + } } at := ms(m.TS) if !since.IsZero() && at.Before(since) { @@ -137,9 +186,14 @@ func parseCline(f file) *state { s.use(dateOf(at), m.ModelInfo.ID, Tokens{Input: max(0, u.Input-u.CacheRead-u.CacheWrite), Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite}) } } - return s + s.Cline = c + return name(s, c.Prompt) } +// clineHook, when a test sets it, is told each time a messages file is +// read. +var clineHook func(path string) + var ( clineNotice = regexp.MustCompile(`(?s)]*>.*?`) clineInput = regexp.MustCompile(`]*>`) diff --git a/internal/sessions/grow_test.go b/internal/sessions/grow_test.go index 3c7aecccb..a67233d66 100644 --- a/internal/sessions/grow_test.go +++ b/internal/sessions/grow_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "testing" + "time" "github.com/klauspost/compress/zstd" ) @@ -400,3 +401,103 @@ func TestDshEndSeedAcrossReads(t *testing.T) { t.Fatalf("the fork's own: %+v, title %q", g.old.Models, g.old.Title) } } + +// Cline rewrites a session's manifest on its own (a title given, the +// session touched), and its size and time are the session file's: when only +// it changed, the messages are not read again. When they changed, or the +// manifest moved the start or the fork their counts were made under, they +// are. +func TestClineReadsMessagesOnlyWhenTheyChange(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + dir := filepath.Join(home, ".cline", "data", "sessions", clineMain) + path := filepath.Join(dir, clineMain+".messages.json") + manifest := filepath.Join(dir, clineMain+".json") + reads := 0 + clineHook = func(p string) { + if p == path { + reads++ + } + } + t.Cleanup(func() { clineHook = nil }) + at := time.Now() + touch := func(p string) { + at = at.Add(time.Minute) + if err := os.Chtimes(p, at, at); err != nil { + t.Fatal(err) + } + } + edit := func(p, from, to string) { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(b, []byte(from)) { + t.Fatalf("no %q in %s", from, p) + } + os.WriteFile(p, bytes.Replace(b, []byte(from), []byte(to), 1), 0o644) + touch(p) + } + var old *state + // read reads the session on from old and says whether it read its + // messages, checking it against a whole read + read := func() bool { + t.Helper() + var f file + for _, c := range clineFiles() { + if c.path == path { + f = c + } + } + was := reads + s := parse(f, old) + read := reads > was + whole := parse(f, nil) + got, _ := json.Marshal(s) + want, _ := json.Marshal(whole) + if !bytes.Equal(got, want) { + t.Fatalf("read on:\n%s\nread whole:\n%s", got, want) + } + old = s + return read + } + // no title of its own, so the first prompt names it + edit(manifest, `"title": "Importer speed-up"`, `"status": "x"`) + edit(manifest, `"prompt": "Speed up the\nimporter",`, ``) + if !read() { + t.Fatal("first read: messages not read") + } + if old.Title != "Speed up the importer" { + t.Fatalf("title %q", old.Title) + } + // the manifest touched and given a title: the messages are not read + edit(manifest, `"status": "completed"`, `"status": "running"`) + if read() { + t.Fatal("manifest touched: messages read again") + } + edit(manifest, `"status": "x"`, `"title": "Faster importer"`) + if read() || old.Named != "Faster importer" || old.Title != "Speed up the importer" { + t.Fatalf("manifest titled: named %q, title %q", old.Named, old.Title) + } + // a message more: read again + edit(path, `"content": "done",`, `"content": "done, all of it",`) + if !read() { + t.Fatal("messages changed: not read") + } + // the same size, a later time: read again + touch(path) + if !read() { + t.Fatal("messages touched: not read") + } + // made a fork after its first reply: what came before is its source's + edit(manifest, `"metadata": {`, `"metadata": {"fork": {"forkedAt": "2026-09-27T10:01:00.000Z"},`) + if !read() || old.Models["claude-opus-5-5"] != (Tokens{}) { + t.Fatalf("forked: %+v", old.Models) + } + // started at another time: read again + edit(manifest, `"started_at": "2026-09-27T10:00:00.000Z"`, `"started_at": "2026-09-27T10:05:00.000Z"`) + if !read() { + t.Fatal("start moved: not read") + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 44e88442d..f317bbc30 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -221,6 +221,8 @@ type state struct { Kimi *kimiCarry `json:"kimi,omitempty"` // dsh: where its file was read to, and its header Dsh *dshCarry `json:"dsh,omitempty"` + // Cline: the messages file its counts were read from + Cline *clineCarry `json:"cline,omitempty"` } // day is one local date's share of a file: tokens by model, and the time @@ -1200,7 +1202,7 @@ func parserFor(agent string) sessionParser { case "dsh": return sessionParser{grow: parseDsh} case "cline": - return sessionParser{whole: parseCline} + return sessionParser{grow: parseCline} case "grok": return sessionParser{grow: parseGrok} case "kimi": From 11b42c0e2e748e4d2845b76abb081711f3fd17f7 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:41:13 +0800 Subject: [PATCH 30/92] sessions: a Kimi Code wire file read for calls is read on, not whole Kimi Code's calls (#1607) were read by a whole-file reader: every poll of Usage after a session's wire.jsonl grew decoded the whole file again for the one or two records added. Kimi only appends to that file, a record a line, so its calls now go through the line path Claude Code's and Codex's take: lineCallReaders gives readCalls a begin (the session id) and a line reader, and prepareCalls reads a grown file on from where the last read left off, writing only the added calls to the disk shard. A half-written last line waits for the rest; a file cut shorter, or written over, fails the head and prefix checks and is read whole again. That alone did not resume for any main session: Kimi's listing folds state.json's size into the main wire file's, so the prefix hash, taken over the listed size, ran past the end of the file and came back empty, and an empty hash never matches. The hash is now taken over the bytes the reader consumed (Off) rather than the listed size; for a Claude or Codex file with no partial tail the two are the same, so their shards keep their hashes. A title change in state.json still re-lists the file, and now costs a resume, not a whole read. TestKimiCodeForkCountsOnce wrote its subagent files without a final newline, which a line reader keeps as an unfinished line; real wire files end in one (all nine of the reporter's do), so the fixture now does too. Measured (CPU, getrusage; one 50 MB wire.jsonl with a state.json beside it, one record appended between reads, readCalls alone; machine loaded): before: 40-90 ms CPU, 240-980 ms wall per read after an append after: 0.9-1.1 ms CPU, 10-21 ms wall per read after an append; first read ~40-55 ms Test: TestKimiCodeCallsReadOnlyWhatWasAppended (state.json present) checks where each scan starts and what calls come back: appended with a half line after, the half line finished, cut shorter, written over. Broken by hand: no resume for kimi -> red ("read from 0, want 567"); resume without the size/prefix checks -> red ("cut shorter: read from 945, want 0"); the hash over the listed size again -> red ("read from 0, want 567"). Run: go test ./internal/sessions -run 'Kimi|Call|Codex|Claude|Long|Grow| Append|Resume|Prefix|Hash' -count=1 ok (359s); gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/call_cache.go | 42 ++++++++++--- internal/sessions/calls.go | 20 +++--- internal/sessions/calls_kimi.go | 49 ++++++--------- internal/sessions/calls_kimi_test.go | 93 +++++++++++++++++++++++++++- 4 files changed, 153 insertions(+), 51 deletions(-) diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 5f79a8b9c..d714ed1d0 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -176,7 +176,8 @@ func keepCalls(path string, st *callFile) { // wholeCallReaders read an agent's calls from one session file at a time, // rather than a line at a time: its calls are not lines, or its file cannot // be read on from the middle of one. Every agent in callSources that is not -// in callFiles needs an entry here, or its calls are never read. +// in callFiles needs an entry here or in lineCallReaders, or its calls are +// never read. var wholeCallReaders = map[string]func(file) (*callFile, bool){ "opencode": readOpenCodeCalls, "zcode": readZCodeCalls, @@ -185,12 +186,27 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){ "codebuddy": readWorkBuddyCalls, // #1779 // #1605 "minimax-code": readMiniMaxCalls, - "kimi": readKimiCalls, // #1607 - "pi": readPiCalls, // #1951 + "pi": readPiCalls, // #1951 "omp": readPiCalls, "agy": readAgyCalls, // #2097 } +// lineCallReader reads an agent's calls a line at a time, as Claude Code's +// and Codex's are: a file that only grew is read on from where the last read +// left off (prepareCalls), and only the calls it adds are written to the +// disk shard. begin starts a file read from its start; line reads one whole +// line of it. Nothing a line leaves for the next may live outside st. +type lineCallReader struct { + begin func(st *callFile, f file) + line func(st *callFile, b []byte) +} + +// lineCallReaders are the agents in callSources, beside callFiles' own, +// whose calls are each one line of a file only appended to. +var lineCallReaders = map[string]lineCallReader{ + "kimi": {kimiCallsBegin, kimiCallLine}, // #1607 +} + func readCalls(f file) *callFile { h := fnv.New32a() _, _ = h.Write([]byte(f.path)) @@ -247,18 +263,26 @@ func readCalls(f file) *callFile { if continued { start = len(old.Calls) } + line := claudeCallLine + if f.agent == "codex" { + line = codexCallLine + } else if r, ok := lineCallReaders[f.agent]; ok { + if st.Off == 0 { + r.begin(st, f) + } + line = r.line + } off, err := scanAt(f.path, st.Off, func(b []byte) bool { return callHead(st, b) }, func(b []byte, start, end int64) bool { st.At, st.End = start, end - if f.agent == "codex" { - codexCallLine(st, b) - } else { - claudeCallLine(st, b) - } + line(st, b) return true }) if err == nil { st.Off, st.Size, st.Mod = off, f.size, f.mod.UnixNano() - st.ContentHash = prefixHash(f.path, f.size) + // the bytes read, not the listed size: a listing may fold another + // file's size into this one's (Kimi's state.json), and hashing past + // the end would leave no hash to read on from + st.ContentHash = prefixHash(f.path, off) writeCalls(st, start, continued) } // Do not turn a one-time historical scan into an indefinitely retained diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 7c640bc6f..c6b1aafc4 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -306,15 +306,15 @@ func callFiles() []file { return out } -// callSources are callFiles and the agents whose calls are read whole -// rather than line by line: OpenCode's (#680) and ZCode's, whose calls are -// rows of their database or their JSON files; DeepSeek Harness's, whose -// session file is packed in frames and so cannot be read on from the middle -// of one; and WorkBuddy's, whose usage lines repeat a reply's id as it goes -// on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages -// file a later generation of its history may replace (#1605); and Kimi -// Code's, whose forks copy their parent's records (#1607). Every agent here -// needs an entry in wholeCallReaders. +// callSources are callFiles and the other agents' session files. Most are +// read whole rather than line by line: OpenCode's (#680) and ZCode's, whose +// calls are rows of their database or their JSON files; DeepSeek Harness's, +// whose session file is packed in frames and so cannot be read on from the +// middle of one; and WorkBuddy's, whose usage lines repeat a reply's id as it +// goes on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages +// file a later generation of its history may replace (#1605). Kimi Code's +// (#1607) are lines of a file only appended to, read on as callFiles' are. +// Every agent here needs an entry in wholeCallReaders or lineCallReaders. func callSources() []file { out := callFiles() out = append(out, openCodeCallFiles()...) @@ -365,7 +365,7 @@ func prepareCalls(f file, old *callFile) *callFile { head := headOf(f.path) var st *callFile - if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Size) == old.ContentHash { + if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Off) == old.ContentHash { st = old.clone() } else { st = &callFile{Agent: f.agent} diff --git a/internal/sessions/calls_kimi.go b/internal/sessions/calls_kimi.go index d0c1c45ce..a242b2f03 100644 --- a/internal/sessions/calls_kimi.go +++ b/internal/sessions/calls_kimi.go @@ -1,12 +1,9 @@ package sessions import ( - "bufio" "bytes" "cmp" "encoding/json" - "errors" - "io" "os" "path/filepath" "strconv" @@ -88,35 +85,27 @@ type kimiRecord struct { var kimiUsageRecord = []byte(`"usage.record"`) -// readKimiCalls reads one agent's wire file whole. -func readKimiCalls(f file) (*callFile, bool) { - r, err := os.Open(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: "kimi"}, false +// kimiCallsBegin starts an agent's wire file read from its start. Kimi Code +// only appends to it, each record a line of its own, so readCalls reads one +// that grew on from where it left off (lineCallReaders). +func kimiCallsBegin(st *callFile, f file) { + st.Session = strings.TrimPrefix(f.key, "kimi:") +} + +// kimiCallLine reads one line of an agent's wire file: a usage.record is a +// call. +func kimiCallLine(st *callFile, b []byte) { + b = bytes.TrimSpace(b) + if len(b) == 0 || len(b) > maxLine || !bytes.Contains(b, kimiUsageRecord) { + return } - defer r.Close() - agentDir := filepath.Base(filepath.Dir(f.path)) - st := &callFile{Agent: "kimi", Path: f.path, Session: strings.TrimPrefix(f.key, "kimi:")} - br := bufio.NewReaderSize(r, 1<<20) - for { - b, err := br.ReadBytes('\n') - if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { - break - } - b = bytes.TrimSpace(b) - if len(b) > 0 && len(b) <= maxLine && bytes.Contains(b, kimiUsageRecord) { - var rec kimiRecord - if json.Unmarshal(b, &rec) == nil { - if c, ok := kimiCall(st, agentDir, rec); ok { - st.Calls = append(st.Calls, c) - } - } - } - if err != nil { - break - } + var rec kimiRecord + if json.Unmarshal(b, &rec) != nil { + return + } + if c, ok := kimiCall(st, filepath.Base(filepath.Dir(st.Path)), rec); ok { + st.Calls = append(st.Calls, c) } - return st, true } // kimiCall is a usage.record as a call. diff --git a/internal/sessions/calls_kimi_test.go b/internal/sessions/calls_kimi_test.go index b7cd7b0bf..70cfc6e98 100644 --- a/internal/sessions/calls_kimi_test.go +++ b/internal/sessions/calls_kimi_test.go @@ -4,7 +4,10 @@ import ( "bytes" "os" "path/filepath" + "slices" + "strconv" "strings" + "sync" "testing" "time" ) @@ -175,8 +178,8 @@ func TestKimiCodeForkCountsOnce(t *testing.T) { // and two subagents of one session whose 1.5 records name themselves: // the same call in two agents' files is two calls sub := strings.Replace(kimiRecordLine, `"agentId":"main"`, `"agentId":"agent-0"`, 1) - writeKimiWire(t, home, "session_agents", "agent-0", sub) - writeKimiWire(t, home, "session_agents", "main", kimiRecordLine) + writeKimiWire(t, home, "session_agents", "agent-0", sub, "") + writeKimiWire(t, home, "session_agents", "main", kimiRecordLine, "") tot := kimiTotals(kimiCalls()) if got := tot["session_169766c9-86f5-4577-97a3-a51d402db5b9"]; got != kimiWant["session_169766c9-86f5-4577-97a3-a51d402db5b9"] { @@ -232,3 +235,89 @@ func TestKimiCodeBrokenFiles(t *testing.T) { } } } + +// A Kimi Code wire file that grew is read on from where the last read of +// its calls left off, not whole again; a half-written last line waits for +// the rest; a file cut shorter or written over is read whole again. Before +// this, every poll after an append decoded the whole file again. +func TestKimiCodeCallsReadOnlyWhatWasAppended(t *testing.T) { + home := kimiHome(t) + rec := func(i int) string { + r := strings.Replace(kimiRecordLine, `1791696952640`, strconv.FormatInt(1791696900000+int64(i)*1000, 10), 1) + return strings.Replace(r, `"inputOther":20257`, `"inputOther":`+strconv.Itoa(20000+i), 1) + } + writeKimiWire(t, home, "session_grow", "main", rec(1), rec(2), rec(3), "") + path := filepath.Join(home, "sessions", "wd_test_000000000009", "session_grow", "agents", "main", "wire.jsonl") + // the listing folds state.json's size into the main wire file's + if err := os.WriteFile(filepath.Join(home, "sessions", "wd_test_000000000009", "session_grow", "state.json"), []byte(`{"title":"Grow","cwd":"/work/grow"}`), 0o644); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + read := func(what string, from int64, want ...int) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + mu.Lock() + got := append([]int64(nil), starts...) + mu.Unlock() + if len(got) == 0 { + t.Fatalf("%s: not read", what) + } + for _, off := range got { + if off != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, off, from, got) + } + } + var in []int + for _, c := range calls { + in = append(in, c.Input-20000) + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + size := func() int64 { + t.Helper() + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return st.Size() + } + read("first read", 0, 1, 2, 3) + + end := size() + appendText(t, path, rec(4)+"\n"+rec(5)[:40]) + read("appended, half a line after", end, 1, 2, 3, 4) + + appendText(t, path, rec(5)[40:]+"\n") + read("the half line finished", end+int64(len(rec(4))+1), 1, 2, 3, 4, 5) + + // cut shorter: read whole again + writeKimiWire(t, home, "session_grow", "main", rec(7), "") + read("cut shorter", 0, 7) + + // written over, longer than it was: read whole again + writeKimiWire(t, home, "session_grow", "main", rec(8), rec(9), "") + later := time.Now().Add(time.Hour) + if err := os.Chtimes(path, later, later); err != nil { + t.Fatal(err) + } + read("written over", 0, 8, 9) +} From 1f411802b8219f56d98ce51ca5806d431c51d011 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:11:34 +0800 Subject: [PATCH 31/92] sessions: Droid's and Grok's listings open only the files that changed Droid's listing opened every transcript to read its first line, for whether it is a subagent's (callingSessionId), and Grok Build's read and decoded every session's summary.json for its session_kind and parent. The listing runs on every 15s poll of Sessions and Usage, so with thousands of sessions each poll opened thousands of files that had not changed. listMemo (listmemo.go) keeps what a listing read from each file by that file's own size and mtime, not the folded size the listing gives the session. A listing is a round: a file not seen in it (a session deleted) is dropped when it ends, so the memo never outgrows the sessions there are. A read that failed, such as a transcript whose first line is still being written, is not kept, and the next listing reads it again: a failed read means unknown, not "nobody's". Reset clears both memos. Measured (3000 sessions each, one listing after another, CPU by getrusage, the machine at load ~500): Droid before: 1103 ms CPU / 8.3 s wall per listing Droid after: 27-47 ms CPU / 0.05-1.0 s wall (first listing 1166 ms) Grok before: 649 ms CPU / 4.2 s wall per listing Grok after: 252-295 ms CPU / 1.8-2.2 s wall (first listing 707 ms) What Grok's listing still spends is its globs and two stats a session (updates.jsonl, summary.json), not reads. Tests: TestDroidListingReadsOnlyChangedTranscripts counts transcript opens (scanHook): a second listing opens only the half-written one, appending reopens only that file, a finished first line is then kept, and a transcript written over without a caller is its own session. TestGrokListingReadsOnlyChangedSummaries counts summary reads (grokSummaryHook): none when nothing changed or only the updates grew, one when the summary is written over, and the key follows it. Broken by hand: the memo never hit -> both red ("nothing changed: read map[...all...]"); failed reads kept -> Droid red ("nothing changed: read map[], want only the half-written one again"). Run: go test ./internal/sessions -run 'Listing|Droid|Grok' -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/droid.go | 16 ++- internal/sessions/grok.go | 24 ++++- internal/sessions/listmemo.go | 62 ++++++++++++ internal/sessions/listmemo_test.go | 157 +++++++++++++++++++++++++++++ internal/sessions/sessions.go | 2 + 5 files changed, 258 insertions(+), 3 deletions(-) create mode 100644 internal/sessions/listmemo.go create mode 100644 internal/sessions/listmemo_test.go diff --git a/internal/sessions/droid.go b/internal/sessions/droid.go index 885688508..3d9eb5602 100644 --- a/internal/sessions/droid.go +++ b/internal/sessions/droid.go @@ -64,10 +64,18 @@ func readDroidStart(path string) (droidStart, bool) { return s, ok } +// droidCallers is whose subagent each transcript is, as its session_start +// line said when the listing last read it: a listing runs on every poll, and +// opening every session's transcript for its first line each time cost more +// than the rest of the listing together. +var droidCallers listMemo[string] + func droidFiles() []file { root := filepath.Join(FactoryDir(), "sessions") a, _ := filepath.Glob(filepath.Join(root, "*.jsonl")) b, _ := filepath.Glob(filepath.Join(root, "*", "*.jsonl")) + callers := droidCallers.round() + defer callers.done() var out []file for _, p := range append(a, b...) { id := strings.TrimSuffix(filepath.Base(p), ".jsonl") @@ -78,6 +86,10 @@ func droidFiles() []file { if !stat(&f) { continue } + calling, _ := callers.get(p, f.size, f.mod, func() (string, bool) { + s, ok := readDroidStart(p) + return s.Calling, ok + }) // what it spent and on which model are in its settings m := file{path: strings.TrimSuffix(p, ".jsonl") + ".settings.json"} if stat(&m) { @@ -87,8 +99,8 @@ func droidFiles() []file { f.mod = m.mod } } - if s, ok := readDroidStart(p); ok && s.Calling != "" && s.Calling != id && safeID.MatchString(s.Calling) { - f.key, f.main = "droid:"+s.Calling, false + if calling != "" && calling != id && safeID.MatchString(calling) { + f.key, f.main = "droid:"+calling, false } out = append(out, f) } diff --git a/internal/sessions/grok.go b/internal/sessions/grok.go index a679067d7..ea68115a5 100644 --- a/internal/sessions/grok.go +++ b/internal/sessions/grok.go @@ -51,13 +51,31 @@ type grokSummary struct { Kind string `json:"session_kind"` } +// grokSummaryHook, when a test sets it, is told each time a summary.json +// is read. +var grokSummaryHook func(path string) + func readGrokSummary(path string) (grokSummary, bool) { + if grokSummaryHook != nil { + grokSummaryHook(path) + } var s grokSummary b, err := os.ReadFile(path) return s, err == nil && json.Unmarshal(b, &s) == nil } +// grokKind is what a listing needs of a session's summary.json: whether it +// is a subagent's, and whose. +type grokKind struct{ Kind, Parent string } + +// grokKinds keeps each summary's kind as the listing last read it: a +// listing runs on every poll, and reading and decoding every session's +// summary each time cost more than the rest of the listing together. +var grokKinds listMemo[grokKind] + func grokFiles() []file { + kinds := grokKinds.round() + defer kinds.done() root := filepath.Join(GrokDir(), "sessions") paths, _ := filepath.Glob(filepath.Join(root, "*", "*", "updates.jsonl")) // a session's subagents are named in its subagents/ folder too @@ -83,7 +101,11 @@ func grokFiles() []file { if m.mod.After(f.mod) { f.mod = m.mod } - if s, ok := readGrokSummary(m.path); ok && strings.HasPrefix(s.Kind, "subagent") { + s, ok := kinds.get(m.path, m.size, m.mod, func() (grokKind, bool) { + s, ok := readGrokSummary(m.path) + return grokKind{s.Kind, s.Parent}, ok + }) + if ok && strings.HasPrefix(s.Kind, "subagent") { parent := s.Parent if parent == "" { parent = parentOf[id] diff --git a/internal/sessions/listmemo.go b/internal/sessions/listmemo.go new file mode 100644 index 000000000..912d7935d --- /dev/null +++ b/internal/sessions/listmemo.go @@ -0,0 +1,62 @@ +package sessions + +import ( + "sync" + "time" +) + +// listMemo keeps what a listing read from each of many small files, by the +// file's own size and mtime, so a listing that runs on every poll opens only +// the files that changed since the last one rather than every session's. +// Each listing is a round: a file it did not ask about (a session deleted) +// is dropped when the round ends. A read that failed is not kept, so the +// next listing tries again: a failed read means unknown, not empty. +type listMemo[T any] struct { + sync.Mutex + m map[string]memoEntry[T] +} + +type memoEntry[T any] struct { + size, mod int64 + v T +} + +type memoRound[T any] struct { + l *listMemo[T] + old, next map[string]memoEntry[T] +} + +// round starts a listing. +func (l *listMemo[T]) round() *memoRound[T] { + l.Lock() + old := l.m + l.Unlock() + return &memoRound[T]{l: l, old: old, next: make(map[string]memoEntry[T], len(old))} +} + +// get is what read gives for the file at path, read again only when its +// size or mtime is not what it was when last read. +func (r *memoRound[T]) get(path string, size int64, mod time.Time, read func() (T, bool)) (T, bool) { + if e, ok := r.old[path]; ok && e.size == size && e.mod == mod.UnixNano() { + r.next[path] = e + return e.v, true + } + v, ok := read() + if ok { + r.next[path] = memoEntry[T]{size, mod.UnixNano(), v} + } + return v, ok +} + +// done keeps what this round read, and only that, for the next. +func (r *memoRound[T]) done() { + r.l.Lock() + r.l.m = r.next + r.l.Unlock() +} + +func (l *listMemo[T]) reset() { + l.Lock() + l.m = nil + l.Unlock() +} diff --git a/internal/sessions/listmemo_test.go b/internal/sessions/listmemo_test.go new file mode 100644 index 000000000..5648ac468 --- /dev/null +++ b/internal/sessions/listmemo_test.go @@ -0,0 +1,157 @@ +package sessions + +import ( + "os" + "path/filepath" + "sync" + "testing" +) + +// keyOf is the key a listing gives the file at path. +func keyOf(t *testing.T, fs []file, path string) string { + t.Helper() + for _, f := range fs { + if f.path == path { + return f.key + } + } + t.Fatalf("%s not listed", path) + return "" +} + +// readCounter counts reads of each file a hook is told of. +type readCounter struct { + mu sync.Mutex + n map[string]int +} + +func (c *readCounter) saw(p string) { + c.mu.Lock() + c.n[p]++ + c.mu.Unlock() +} + +func (c *readCounter) take() map[string]int { + c.mu.Lock() + defer c.mu.Unlock() + n := c.n + c.n = map[string]int{} + return n +} + +// Droid's listing, run on every poll, opens a transcript for whose +// subagent it is only when the transcript changed; a transcript it could +// not read is tried again on the next listing, not taken as nobody's. +func TestDroidListingReadsOnlyChangedTranscripts(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + putDroid(t, home) + dir := filepath.Join(home, ".factory", "sessions", "-work-droid") + sub := filepath.Join(dir, "d0000000-0000-4000-8000-0000000000aa.jsonl") + start := `{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000aa","title":"Sub","cwd":"/work","callingSessionId":"` + droidMain + `"}` + "\n" + if err := os.WriteFile(sub, []byte(start), 0o644); err != nil { + t.Fatal(err) + } + half := filepath.Join(dir, "d0000000-0000-4000-8000-0000000000bb.jsonl") + if err := os.WriteFile(half, []byte(`{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000bb","callingSessionId":"`+droidMain), 0o644); err != nil { + t.Fatal(err) + } + c := &readCounter{n: map[string]int{}} + scanHook = func(p string, _ int64) { c.saw(p) } + t.Cleanup(func() { scanHook = nil }) + + fs := droidFiles() + if n := c.take(); n[sub] != 1 || n[half] != 1 || len(n) < 3 { + t.Fatalf("first listing read %v", n) + } + if k := keyOf(t, fs, sub); k != "droid:"+droidMain { + t.Fatalf("subagent keyed %q", k) + } + fs = droidFiles() + if n := c.take(); len(n) != 1 || n[half] != 1 { + t.Fatalf("nothing changed: read %v, want only the half-written one again", n) + } + if k := keyOf(t, fs, sub); k != "droid:"+droidMain { + t.Fatalf("subagent keyed %q from what was kept", k) + } + + // appended to: read again, still the same caller + appendText(t, sub, `{"type":"message","id":"m1","timestamp":"2026-09-27T08:00:00.000Z","message":{"role":"user","content":"go"}}`+"\n") + fs = droidFiles() + if n := c.take(); n[sub] != 1 || n[half] != 1 || len(n) != 2 { + t.Fatalf("one appended to: read %v", n) + } + // the half-written line finished: read, and kept from then on + appendText(t, half, `"}`+"\n") + fs = droidFiles() + if k := keyOf(t, fs, half); k != "droid:"+droidMain { + t.Fatalf("finished line keyed %q", k) + } + c.take() + droidFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("nothing changed: read %v", n) + } + // written over without a caller: its own session now + if err := os.WriteFile(sub, []byte(`{"type":"session_start","id":"d0000000-0000-4000-8000-0000000000aa","title":"Own"}`+"\n"), 0o644); err != nil { + t.Fatal(err) + } + if k := keyOf(t, droidFiles(), sub); k != "droid:d0000000-0000-4000-8000-0000000000aa" { + t.Fatalf("written over: keyed %q", k) + } +} + +// Grok Build's listing reads a session's summary.json, for whether it is +// a subagent's, only when the summary changed. +func TestGrokListingReadsOnlyChangedSummaries(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + id := "0190aaaa-0000-7000-8000-0000000000dd" + dir := filepath.Join(home, ".grok", "sessions", "%2Fwork%2Fgrok", id) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, "updates.jsonl") + if err := os.WriteFile(p, []byte(`{"timestamp":1790496001}`+"\n"), 0o644); err != nil { + t.Fatal(err) + } + summary := filepath.Join(dir, "summary.json") + if err := os.WriteFile(summary, []byte(`{"info":{"id":"`+id+`"},"session_kind":"subagent","parent_session_id":"`+grokMain+`"}`), 0o644); err != nil { + t.Fatal(err) + } + c := &readCounter{n: map[string]int{}} + grokSummaryHook = c.saw + t.Cleanup(func() { grokSummaryHook = nil }) + + fs := grokFiles() + if n := c.take(); n[summary] != 1 || len(n) < 2 { + t.Fatalf("first listing read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+grokMain { + t.Fatalf("subagent keyed %q", k) + } + fs = grokFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("nothing changed: read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+grokMain { + t.Fatalf("subagent keyed %q from what was kept", k) + } + // the updates grew: the summary is not read for that + appendText(t, p, `{"timestamp":1790496002}`+"\n") + grokFiles() + if n := c.take(); len(n) != 0 { + t.Fatalf("updates grew: read %v", n) + } + // the summary written over, no longer a subagent's: read, its own now + if err := os.WriteFile(summary, []byte(`{"info":{"id":"`+id+`"},"session_kind":"main","generated_title":"Own"}`), 0o644); err != nil { + t.Fatal(err) + } + fs = grokFiles() + if n := c.take(); n[summary] != 1 || len(n) != 1 { + t.Fatalf("summary changed: read %v", n) + } + if k := keyOf(t, fs, p); k != "grok:"+id { + t.Fatalf("written over: keyed %q", k) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index f317bbc30..a906d0033 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -994,6 +994,8 @@ func Reset() { directoryCache.entries = map[string]directoryEntry{} directoryCache.Unlock() resetCalls() + droidCallers.reset() + grokKinds.reset() wslReset() forgetHermesPrints() mu.Lock() From da9fc17eb6c618e0dd08ac25a7d4d33e2fa31a32 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:30:28 +0800 Subject: [PATCH 32/92] sessions: a Pi or omp session file read for calls is read on, not whole Pi's and omp's calls (#1951) were read by a whole-file reader: every time a session file grew by one line, Usage's ledger decoded the whole file again, its header and every message, and rewrote its disk shard. Pi and omp only append to a session file, a line an entry, as Kimi Code's wire file is. Pi and omp are now line readers (lineCallReaders): a file that only grew is read on from the last whole line, and only the calls it adds are appended to the shard. What a later line's call is read with is carried in piCarry on the callFile: the header's cwd, a fork's start (what came before it is its parent's), and the provider and model in use for a compaction's or tool result's usage. That carry is kept in the shard's state too, flat (callDiskState.Pi*), as the in-memory read is let go after packing: a carry that lived only in memory made every append read from 0 again. A shard written before has no carry (piCallsKept false) and its file is read whole once more. Cut shorter, written over, or grown at a changed head: read whole again (prepareCalls' head and prefix hashes, as for Kimi). Measured (CPU, getrusage; one 50 MB Pi session, ~3500 calls, a call appended between reads; the old reader measured from a worktree at 432a2ba5e with the same harness; machine at load ~500): before: 112-153 ms CPU, 1.0-2.5 s wall per read after an append after: 1.1-3.1 ms CPU, 5-57 ms wall per read after an append; first read ~95 ms CPU, as before Test: TestPiCallsReadOnlyWhatWasAppended (a fork, its model set once at the top, compaction usage) checks where each read starts (scanHook) and the calls it gives: an append with a half line after reads from the old end and leaves the half line; finished, it is read; a line older than the fork's start is left out after a resume as on a whole read; the model, provider and cwd stay right on calls read on; after resetCalls() the read resumes from the disk shard; cut shorter and written over read from 0. Broken by hand: piCallsKept always false -> red ("read from 0, want 686"); the carry not written to the shard -> red (same); begin run on every read, the carry lost -> red ("calls [1 2], want [1 2 3]"). Run: go test ./internal/sessions -run 'Pi|Omp|OMP|Call|Usage' -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/call_cache.go | 35 +++++++-- internal/sessions/calls.go | 9 ++- internal/sessions/calls_pi.go | 106 ++++++++++++------------- internal/sessions/calls_pi_test.go | 119 ++++++++++++++++++++++++++++- 4 files changed, 208 insertions(+), 61 deletions(-) diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index d714ed1d0..4127f1c86 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -186,8 +186,6 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){ "codebuddy": readWorkBuddyCalls, // #1779 // #1605 "minimax-code": readMiniMaxCalls, - "pi": readPiCalls, // #1951 - "omp": readPiCalls, "agy": readAgyCalls, // #2097 } @@ -195,16 +193,22 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){ // and Codex's are: a file that only grew is read on from where the last read // left off (prepareCalls), and only the calls it adds are written to the // disk shard. begin starts a file read from its start; line reads one whole -// line of it. Nothing a line leaves for the next may live outside st. +// line of it. Nothing a line leaves for the next may live outside st. kept, +// when a reader carries something from line to line, says whether st holds +// it: a read kept on disk before it was carried there does not, and is +// read whole again. type lineCallReader struct { begin func(st *callFile, f file) line func(st *callFile, b []byte) + kept func(st *callFile) bool } // lineCallReaders are the agents in callSources, beside callFiles' own, // whose calls are each one line of a file only appended to. var lineCallReaders = map[string]lineCallReader{ - "kimi": {kimiCallsBegin, kimiCallLine}, // #1607 + "kimi": {kimiCallsBegin, kimiCallLine, nil}, // #1607 + "pi": {piCallsBegin, readPiCallLine, piCallsKept}, // #1951 + "omp": {piCallsBegin, readPiCallLine, piCallsKept}, } func readCalls(f file) *callFile { @@ -257,6 +261,9 @@ func readCalls(f file) *callFile { callsMu.Unlock() return st } + if r, ok := lineCallReaders[f.agent]; ok && r.kept != nil && old != nil && !r.kept(old) { + old = nil + } st := prepareCalls(f, old) continued := old != nil && st.Off == old.Off && st.Off > 0 start := 0 @@ -325,16 +332,30 @@ type callDiskState struct { At, End, AsstEnd int64 Session, Requested string LastUser, LastAsst time.Time + // Pi's and omp's carry (piCarry), flat: PiOn when there is one + PiOn, PiHeader bool + PiCwd string + PiSince time.Time + PiProvider, PiModel string } func diskCallState(s *callFile) callDiskState { - return callDiskState{s.ContentHash, s.Size, s.Mod, s.Off, s.Head, s.HeadSize, - s.Path, s.Agent, s.At, s.End, s.AsstEnd, s.Session, s.Requested, s.LastUser, s.LastAsst} + d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, + Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, + LastUser: s.LastUser, LastAsst: s.LastAsst} + if p := s.Pi; p != nil { + d.PiOn, d.PiHeader, d.PiCwd, d.PiSince, d.PiProvider, d.PiModel = true, p.Header, p.Cwd, p.Since, p.Provider, p.Model + } + return d } func (s callDiskState) restore() *callFile { - return &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, + st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} + if s.PiOn { + st.Pi = &piCarry{s.PiHeader, s.PiCwd, s.PiSince, s.PiProvider, s.PiModel} + } + return st } func callText(c *Call) [13]*string { diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index c6b1aafc4..87ecfbdaa 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -94,6 +94,8 @@ type callFile struct { CompactMs int64 // Codex CX *cxRun + // Pi and omp + Pi *piCarry } // cxRun is where a rollout's read stands: what its lines have said so far. @@ -313,7 +315,8 @@ func callFiles() []file { // middle of one; and WorkBuddy's, whose usage lines repeat a reply's id as it // goes on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages // file a later generation of its history may replace (#1605). Kimi Code's -// (#1607) are lines of a file only appended to, read on as callFiles' are. +// (#1607), Pi's and omp's (#1951) are lines of a file only appended to, +// read on as callFiles' are. // Every agent here needs an entry in wholeCallReaders or lineCallReaders. func callSources() []file { out := callFiles() @@ -397,6 +400,10 @@ func (st *callFile) clone() *callFile { r.Timings = append([]cxCallTiming(nil), r.Timings...) c.CX = &r } + if st.Pi != nil { + p := *st.Pi + c.Pi = &p + } return &c } diff --git a/internal/sessions/calls_pi.go b/internal/sessions/calls_pi.go index 1a462fdae..a9e161f90 100644 --- a/internal/sessions/calls_pi.go +++ b/internal/sessions/calls_pi.go @@ -1,13 +1,9 @@ package sessions import ( - "bufio" "bytes" "encoding/json" - "errors" - "io" "math" - "os" "strings" "time" ) @@ -73,59 +69,65 @@ type piCallLine struct { } `json:"message"` } -// readPiCalls reads one Pi or omp session file whole. -func readPiCalls(f file) (*callFile, bool) { - r, err := os.Open(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: f.agent}, false +// piCarry is what a Pi or omp session file's lines have said so far that a +// later line's call is read with: the header's cwd and, for a fork, when it +// began (what was written before is its parent's), and the provider and +// model in use. Pi and omp only append to the file, a line an entry, so a +// file that grew is read on from where the last read left off with it +// (lineCallReaders). +type piCarry struct { + Header bool + Cwd string + Since time.Time + Provider, Model string +} + +// piCallsBegin starts a session file read from its start. +func piCallsBegin(st *callFile, f file) { + st.Session = strings.TrimPrefix(f.key, f.agent+":") + st.Pi = &piCarry{} +} + +// piCallsKept is whether st holds what reading on needs: a disk shard +// written before the carry was kept there does not, and its file is read +// whole again once it changes. +func piCallsKept(st *callFile) bool { return st.Pi != nil } + +// readPiCallLine reads one line of a Pi or omp session file. +func readPiCallLine(st *callFile, b []byte) { + if len(b) == 0 || len(b) > maxLine || !(bytes.Contains(b, piUsed) || bytes.Contains(b, piHeader) || bytes.Contains(b, piModel)) { + return } - defer r.Close() - st := &callFile{Agent: f.agent, Path: f.path, Session: strings.TrimPrefix(f.key, f.agent+":")} - var cwd, provider, model string - var header bool - var since time.Time // a fork's: what was written before it is its parent's - br := bufio.NewReaderSize(r, 1<<20) - for { - b, err := br.ReadBytes('\n') - if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { - break - } - b = bytes.TrimSpace(b) - if len(b) > 0 && len(b) <= maxLine && (bytes.Contains(b, piUsed) || bytes.Contains(b, piHeader) || bytes.Contains(b, piModel)) { - var l piCallLine - if json.Unmarshal(b, &l) == nil { - switch l.Type { - case "session": - if !header { - header, cwd = true, l.Cwd - if l.Parent != "" { - since, _ = time.Parse(time.RFC3339Nano, l.Timestamp) - } - } - case "model_change": - p, id := l.Provider, l.ModelID - if id == "" { - p, id, _ = strings.Cut(l.Model, "/") - } - if id != "" { - provider, model = p, id - } - case "message": - if m := l.Message; m != nil && m.Role == "assistant" && m.Model != "" { - provider, model = m.Provider, m.Model - } - } - if c, ok := piCall(st, f.agent, l, provider, model); ok && !c.Time.Before(since) { - c.Cwd = st.str(cwd) - st.Calls = append(st.Calls, c) - } + var l piCallLine + if json.Unmarshal(b, &l) != nil { + return + } + p := st.Pi + switch l.Type { + case "session": + if !p.Header { + p.Header, p.Cwd = true, l.Cwd + if l.Parent != "" { + p.Since, _ = time.Parse(time.RFC3339Nano, l.Timestamp) } } - if err != nil { - break + case "model_change": + prov, id := l.Provider, l.ModelID + if id == "" { + prov, id, _ = strings.Cut(l.Model, "/") + } + if id != "" { + p.Provider, p.Model = prov, id + } + case "message": + if m := l.Message; m != nil && m.Role == "assistant" && m.Model != "" { + p.Provider, p.Model = m.Provider, m.Model } } - return st, true + if c, ok := piCall(st, st.Agent, l, p.Provider, p.Model); ok && !c.Time.Before(p.Since) { + c.Cwd = st.str(p.Cwd) + st.Calls = append(st.Calls, c) + } } // piCall is an entry as a call, on the provider and model in use for the diff --git a/internal/sessions/calls_pi_test.go b/internal/sessions/calls_pi_test.go index 7c3c17484..d1785ccc1 100644 --- a/internal/sessions/calls_pi_test.go +++ b/internal/sessions/calls_pi_test.go @@ -1,8 +1,12 @@ package sessions import ( + "os" "path/filepath" + "slices" "sort" + "strconv" + "sync" "testing" "time" ) @@ -57,7 +61,7 @@ func TestPiCalls(t *testing.T) { // first for _, f := range piFiles() { if f.key == "pi:"+fork { - if st, ok := readPiCalls(f); !ok || len(st.Calls) != 1 { + if st := readCalls(f); len(st.Calls) != 1 { t.Errorf("the fork's own calls: %+v", st.Calls) } } @@ -108,3 +112,116 @@ func TestPiCallsBesideReplies(t *testing.T) { } } } + +// A Pi session file that grew is read on from where the last read left +// off, with what its earlier lines said (its cwd, a fork's start, the +// model in use) carried on, in memory and in the disk shard; a half +// line waits for the rest, and a file cut shorter or written over is +// read whole again. +func TestPiCallsReadOnlyWhatWasAppended(t *testing.T) { + claude, _ := setup(t) + dir := filepath.Join(filepath.Dir(claude), "pi", "sessions", "--work-grow--") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "2026-10-13T08-00-00-000Z_01a1343b-0000-7000-8000-000000000077.jsonl") + t0 := time.Date(2026, 10, 13, 8, 0, 0, 0, time.UTC) + // a fork: what was written before its own time is its parent's + head := `{"type":"session","version":3,"id":"01a1343b-0000-7000-8000-000000000077","timestamp":"2026-10-13T08:00:00.000Z","cwd":"/work/grow","parentSession":"/p.jsonl"}` + "\n" + + `{"type":"model_change","id":"m0","timestamp":"2026-10-13T08:00:00.000Z","provider":"relay","modelId":"deepseek-v4"}` + "\n" + // a compaction's usage is on the provider and model in use + rec := func(i int) string { + at := t0.Add(time.Duration(i) * time.Second).Format("2006-01-02T15:04:05.000Z") + return `{"type":"compaction","id":"c` + strconv.Itoa(i+100) + `","timestamp":"` + at + `","usage":{"input":` + strconv.Itoa(20000+i) + `,"output":5,"cacheRead":0,"cacheWrite":0}}` + } + write := func(lines ...string) { + t.Helper() + b := head + for _, l := range lines { + b += l + "\n" + } + if err := os.WriteFile(path, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + } + write(rec(-5), rec(1), rec(2)) + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + read := func(what string, from int64, want ...int) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var calls []Call + for _, s := range CallSources() { + if s.Path == path { + calls = ReadCallSource(s) + } + } + mu.Lock() + got := append([]int64(nil), starts...) + mu.Unlock() + if len(got) == 0 { + t.Fatalf("%s: not read", what) + } + for _, off := range got { + if off != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, off, from, got) + } + } + var in []int + for _, c := range calls { + if c.Model != "deepseek-v4" || c.Upstream != "relay" || c.Cwd != "/work/grow" || c.Agent != "pi" { + t.Fatalf("%s: call %+v lost what the earlier lines said", what, c) + } + in = append(in, c.Input-20000) + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + size := func() int64 { + t.Helper() + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + return st.Size() + } + read("first read", 0, 1, 2) + + end := size() + appendText(t, path, rec(3)+"\n"+rec(-4)+"\n"+rec(5)[:40]) + read("appended, half a line after", end, 1, 2, 3) + + end += int64(len(rec(3)) + len(rec(-4)) + 2) + appendText(t, path, rec(5)[40:]+"\n") + read("the half line finished", end, 1, 2, 3, 5) + + // read again after the in-memory reads are gone: from the disk shard, + // with what it carried + resetCalls() + end = size() + appendText(t, path, rec(6)+"\n") + read("from the disk shard", end, 1, 2, 3, 5, 6) + + // cut shorter: read whole again + write(rec(7)) + read("cut shorter", 0, 7) + + // written over, longer than it was: read whole again + write(rec(8), rec(9), rec(10)) + later := time.Now().Add(time.Hour) + if err := os.Chtimes(path, later, later); err != nil { + t.Fatal(err) + } + read("written over", 0, 8, 9, 10) +} From ec396be60c8f3fac2f1a270bc43586fee0b0ebed Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:53:08 +0800 Subject: [PATCH 33/92] sessions: a dsh session read for calls is read on, not whole dsh's calls were read by a whole-file reader: each reply appended to a session made Usage's ledger read the whole file again and, packed, decompress every frame of it. parseDsh already reads on from the frame it left off in (frames.go, 827c304d9); the call reader now does too. readDshCalls is handed what the last read came to and reads on from its tail (scanFrames for a packed file, scanAt for a plain one), carrying dsh's header in dshCarry. It says how many of the calls it gives were kept from before, so only the new ones are appended to the disk shard (resumeCallReaders in call_cache.go). The carry is kept in the shard's state as JSON (callDiskState.Dsh), since the in-memory read is let go after packing. A fork's inherited end-seed met in a later read drops what was counted before it and rewrites the shard whole, as the whole read did by cutting at the last one. A file cut short or replaced (tail.holds) is read whole. One change from before, as for parseDsh: a last line not ended by a newline waits for it. Measured (CPU, getrusage; 50 MB of events, ~3600 calls, a reply appended between reads; packed: frames of 200 lines; the old reader measured from a worktree at 432a2ba5e with the same harness; machine at load ~500): plain before: 91-109 ms CPU, 0.5-1.3 s wall per read after an append plain after: 0.6-7.7 ms CPU, 2-129 ms wall packed before: 214-230 ms CPU, 3.5-4.8 s wall per read after an append packed after: 1.2-1.5 ms CPU, 13-46 ms wall first read unchanged (plain ~60-105 ms, packed ~195-215 ms CPU) Tests: TestDshCallsReadOnlyWhatWasAppended (packed dsh-a) checks where each read starts (scanHook) and its calls: a frame appended is read alone; half a frame waits; a frame ending inside a line is read on from that frame; after resetCalls() the read goes on from the disk shard; cut short reads from 0. TestDshCallsEndSeedAcrossReads: dsh-c's end-seed arriving in a later read drops the seeded call, its own is read on, and the shard holds only that after resetCalls(). Broken by hand: no resume -> both red ("read from 0, want 654"); the carry not written to the shard -> both red (same); the end-seed not rewriting the shard -> red ("the fork's own ...: [50 100]"). Run: go test ./internal/sessions -run 'Dsh|Call|Usage|Pi' -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. --- internal/sessions/call_cache.go | 44 +++++++- internal/sessions/calls.go | 20 +++- internal/sessions/calls_dsh.go | 132 ++++++++++++----------- internal/sessions/calls_dsh_test.go | 162 ++++++++++++++++++++++++++++ 4 files changed, 286 insertions(+), 72 deletions(-) diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 4127f1c86..04e9f759c 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -8,6 +8,7 @@ import ( "bytes" "encoding/binary" "encoding/gob" + "encoding/json" "hash/crc32" "hash/fnv" "io" @@ -176,12 +177,11 @@ func keepCalls(path string, st *callFile) { // wholeCallReaders read an agent's calls from one session file at a time, // rather than a line at a time: its calls are not lines, or its file cannot // be read on from the middle of one. Every agent in callSources that is not -// in callFiles needs an entry here or in lineCallReaders, or its calls are -// never read. +// in callFiles needs an entry here, in lineCallReaders or in +// resumeCallReaders, or its calls are never read. var wholeCallReaders = map[string]func(file) (*callFile, bool){ "opencode": readOpenCodeCalls, "zcode": readZCodeCalls, - "dsh": readDshCalls, "workbuddy": readWorkBuddyCalls, "codebuddy": readWorkBuddyCalls, // #1779 // #1605 @@ -189,6 +189,17 @@ var wholeCallReaders = map[string]func(file) (*callFile, bool){ "agy": readAgyCalls, // #2097 } +// resumeCallReaders read an agent's calls from a file only appended to that +// the line reader can't read on through, as dsh's packed file of zstd +// frames: each is handed what the last read came to and reads on from +// where it left off, or whole when it can't. It gives how many of the +// calls it hands back were in old, kept as they were (0 when it read +// whole, or what it had counted no longer stands), so only the rest are +// appended to the disk shard. +var resumeCallReaders = map[string]func(f file, old *callFile) (st *callFile, kept int, ok bool){ + "dsh": readDshCalls, +} + // lineCallReader reads an agent's calls a line at a time, as Claude Code's // and Codex's are: a file that only grew is read on from where the last read // left off (prepareCalls), and only the calls it adds are written to the @@ -245,6 +256,22 @@ func readCalls(f file) *callFile { // that changed is read again, and one that did not is kept. OpenCode's // and ZCode's are rows of a database or JSON documents; dsh's file is // packed in frames, so it cannot be read on from the middle of one. + if read, ok := resumeCallReaders[f.agent]; ok { + st, kept, readOK := read(f, old) + if !readOK && old != nil { + return old + } + if readOK { + st.Size, st.Mod = f.size, f.mod.UnixNano() + writeCalls(st, kept, kept > 0) + } + callsMu.Lock() + if readOK && generation == callGeneration { + keepCalls(f.path, st) + } + callsMu.Unlock() + return st + } if read, ok := wholeCallReaders[f.agent]; ok { st, readOK := read(f) if !readOK && old != nil { @@ -332,6 +359,8 @@ type callDiskState struct { At, End, AsstEnd int64 Session, Requested string LastUser, LastAsst time.Time + // dsh's carry (dshCarry), as JSON: nil when there is none + Dsh []byte // Pi's and omp's carry (piCarry), flat: PiOn when there is one PiOn, PiHeader bool PiCwd string @@ -343,6 +372,9 @@ func diskCallState(s *callFile) callDiskState { d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} + if s.Dsh != nil { + d.Dsh, _ = json.Marshal(s.Dsh) + } if p := s.Pi; p != nil { d.PiOn, d.PiHeader, d.PiCwd, d.PiSince, d.PiProvider, d.PiModel = true, p.Header, p.Cwd, p.Since, p.Provider, p.Model } @@ -352,6 +384,12 @@ func (s callDiskState) restore() *callFile { st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} + if len(s.Dsh) > 0 { + var c dshCarry + if json.Unmarshal(s.Dsh, &c) == nil { + st.Dsh = &c + } + } if s.PiOn { st.Pi = &piCarry{s.PiHeader, s.PiCwd, s.PiSince, s.PiProvider, s.PiModel} } diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 87ecfbdaa..ab2863655 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -96,6 +96,8 @@ type callFile struct { CX *cxRun // Pi and omp Pi *piCarry + // dsh + Dsh *dshCarry } // cxRun is where a rollout's read stands: what its lines have said so far. @@ -310,14 +312,14 @@ func callFiles() []file { // callSources are callFiles and the other agents' session files. Most are // read whole rather than line by line: OpenCode's (#680) and ZCode's, whose -// calls are rows of their database or their JSON files; DeepSeek Harness's, -// whose session file is packed in frames and so cannot be read on from the -// middle of one; and WorkBuddy's, whose usage lines repeat a reply's id as it +// calls are rows of their database or their JSON files; and WorkBuddy's, whose usage lines repeat a reply's id as it // goes on, as CodeBuddy Code's do (#1779); and MiniMax Code's, whose messages // file a later generation of its history may replace (#1605). Kimi Code's // (#1607), Pi's and omp's (#1951) are lines of a file only appended to, -// read on as callFiles' are. -// Every agent here needs an entry in wholeCallReaders or lineCallReaders. +// read on as callFiles' are; DeepSeek Harness's, a file only appended to +// that may be packed in zstd frames, is read on from the frame it was +// left in (readDshCalls). Every agent here needs an entry in +// wholeCallReaders, lineCallReaders or resumeCallReaders. func callSources() []file { out := callFiles() out = append(out, openCodeCallFiles()...) @@ -404,6 +406,14 @@ func (st *callFile) clone() *callFile { p := *st.Pi c.Pi = &p } + if st.Dsh != nil { + d := *st.Dsh + if d.Tail != nil { + t := *d.Tail + d.Tail = &t + } + c.Dsh = &d + } return &c } diff --git a/internal/sessions/calls_dsh.go b/internal/sessions/calls_dsh.go index cc8f72563..e93cf2997 100644 --- a/internal/sessions/calls_dsh.go +++ b/internal/sessions/calls_dsh.go @@ -1,11 +1,8 @@ package sessions import ( - "bufio" "bytes" "encoding/json" - "errors" - "io" "strings" ) @@ -37,82 +34,89 @@ func dshCallFiles() []file { return dshFiles() } -// readDshCalls reads a dsh session whole: packed in frames, it can't be read -// on from the middle of one (as parseDsh says). -func readDshCalls(f file) (*callFile, bool) { - r, err := dshOpen(f.path) - if err != nil { - return &callFile{Path: f.path, Agent: "dsh"}, false +// readDshCalls reads a dsh session's calls. dsh only appends to a session +// file, a line at a time or, packed, a frame of lines at a time, so a file +// read before is read on from where that read left off, a packed one from +// the frame it left off in (frames.go), as parseDsh reads it. A file cut +// short or replaced is read whole again, and a line or frame not yet +// written whole waits for the next read. kept is how many of st's calls +// were old's. +func readDshCalls(f file, old *callFile) (st *callFile, kept int, ok bool) { + var c dshCarry + var off, skip int64 + if old != nil && old.Dsh != nil && old.Dsh.Tail.holds(f.path) { + st = old.clone() + c, off, skip = *st.Dsh, st.Dsh.Tail.Off, st.Dsh.Tail.Skip + kept = len(st.Calls) + } else { + st = &callFile{Agent: "dsh", Path: f.path, Session: strings.TrimPrefix(f.key, "dsh:")} } - defer r.Close() - st := &callFile{Agent: "dsh", Path: f.path, Session: strings.TrimPrefix(f.key, "dsh:")} - br := bufio.NewReaderSize(r, 1<<20) - var h dshHead - // the events a fork was seeded with are the session it came from, not - // this one: parseDsh skips them, and counting them here would spend the - // same request once per fork (dsh-a's first reply is also dsh-c's and - // dsh-d's first lines) - var evs []dshEvent - var seeds []bool - cut := -1 - for first := true; ; first = false { - b, err := br.ReadBytes('\n') - if err != nil { - // a line still being written, or a frame cut short - if !errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0 { - break - } - } + headed := c.Head.Type == "session" + ok = true + each := func(b []byte) bool { b = bytes.TrimSpace(b) if len(b) == 0 || len(b) > maxLine { - if err != nil { - break - } - continue + return true } - if first { - if json.Unmarshal(b, &h) != nil || h.Type != "session" { - return st, false + if !headed { + headed = true + if json.Unmarshal(b, &c.Head) != nil || c.Head.Type != "session" { + ok = false + return false } if st.Session == "" { - st.Session = h.ID + st.Session = c.Head.ID } - continue + return true } // only an assistant/message carries a call, and only the ones a // seed ends: every other line is passed over undecoded - if bytes.Contains(b, []byte(`"assistant/message"`)) || bytes.Contains(b, []byte(`"session/end-seed"`)) { - var e dshEvent - if json.Unmarshal(b, &e) == nil && e.Type != "" { - evs = append(evs, e) - seeds = append(seeds, e.Type == "session/end-seed" && e.Data.Inherited) + if !bytes.Contains(b, []byte(`"assistant/message"`)) && !bytes.Contains(b, []byte(`"session/end-seed"`)) { + return true + } + var e dshEvent + if json.Unmarshal(b, &e) != nil { + return true + } + switch e.Type { + case "session/end-seed": + // the events a fork was seeded with are the session it came + // from, not this one: parseDsh skips them, and counting them + // here would spend the same request once per fork (dsh-a's + // first reply is also dsh-c's and dsh-d's first lines). From + // format 2 the seed ends with this marker: what came before + // it is not this session's. + if e.Data.Inherited && c.Head.Version >= 2 && c.Head.IsSeeded { + st.Calls, kept = nil, 0 + } + case "assistant/message": + // before format 2 the seed is counted in events + if c.Head.Version < 2 && e.Seq != nil && *e.Seq < c.Head.SeedLength { + return true + } + if call, ok := dshCall(st, e); ok { + st.Calls = append(st.Calls, call) } } - if err != nil { - break - } + return true } - if h.Version >= 2 && h.IsSeeded { - for i, seed := range seeds { - if seed { - cut = i - } - } + var next, nextSkip, end int64 + var err error + if packed(f.path) { + next, nextSkip, end, err = scanFrames(f.path, off, skip, each) + } else { + next, err = scanAt(f.path, off, nil, func(b []byte, _, _ int64) bool { return each(b) }) + end = next } - for i, e := range evs { - if e.Type != "assistant/message" { - continue - } - // before format 2 the seed is counted in events, after it by the - // marker it ends with - if i <= cut || h.Version < 2 && e.Seq != nil && *e.Seq < h.SeedLength { - continue - } - if c, ok := dshCall(st, e); ok { - st.Calls = append(st.Calls, c) - } + if !ok || err != nil && !headed { + return &callFile{Path: f.path, Agent: "dsh"}, 0, false } - return st, true + c.Tail = nil + if err == nil { + c.Tail = markTail(f.path, next, nextSkip, end) + } + st.Dsh = &c + return st, kept, true } // dshCall is an assistant/message as a call: its model, its tokens and the diff --git a/internal/sessions/calls_dsh_test.go b/internal/sessions/calls_dsh_test.go index ca5a26773..36f16cf83 100644 --- a/internal/sessions/calls_dsh_test.go +++ b/internal/sessions/calls_dsh_test.go @@ -1,8 +1,16 @@ package sessions import ( + "bytes" + "fmt" + "os" + "path/filepath" + "slices" + "sync" "testing" "time" + + "github.com/klauspost/compress/zstd" ) // dshCalls are the DeepSeek Harness calls Calls gives. @@ -129,3 +137,157 @@ func TestDshGatewayProviderTakesEveryRouteOfMagpies(t *testing.T) { } } } + +// dshCallReader reads the calls of the dsh session file at path as the +// ledger does, and says where each scan of it started. +func dshCallReader(t *testing.T, path string) func() ([]int, []int64) { + var mu sync.Mutex + var starts []int64 + scanHook = func(p string, off int64) { + if p == path { + mu.Lock() + starts = append(starts, off) + mu.Unlock() + } + } + t.Cleanup(func() { scanHook = nil }) + return func() ([]int, []int64) { + t.Helper() + mu.Lock() + starts = nil + mu.Unlock() + var in []int + found := false + for _, s := range CallSources() { + if s.Path == path { + found = true + for _, c := range ReadCallSource(s) { + in = append(in, c.Input) + } + } + } + if !found { + t.Fatalf("%s is no call source", path) + } + slices.Sort(in) + mu.Lock() + defer mu.Unlock() + return in, append([]int64(nil), starts...) + } +} + +// A dsh session read for calls before is read on from where it was left, +// packed or not: a frame appended is read alone, a frame or line not yet +// written whole waits, the read goes on from the disk shard after the +// in-memory one is let go, and a file cut short is read whole again. +func TestDshCallsReadOnlyWhatWasAppended(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + plain := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-a", "session.v3.jsonl") + b, err := os.ReadFile(plain) + if err != nil { + t.Fatal(err) + } + os.Remove(plain) + enc, _ := zstd.NewWriter(nil) + defer enc.Close() + frame := func(s string) string { return string(enc.EncodeAll([]byte(s), nil)) } + p := plain + ".zstd" + half := bytes.IndexByte(b[len(b)/2:], '\n') + len(b)/2 + 1 + orig := frame(string(b[:half])) + frame(string(b[half:])) + if err := os.WriteFile(p, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + reply := func(n int) string { + return fmt.Sprintf(`{"type":"assistant/message","seq":%d,"time":%d,"data":{"message":{"source":{"model":"deepseek-v4-flash"}},"usage":{"inputTokens":%d,"outputTokens":1,"cacheReadTokens":0}}}`+"\n", n, 1790503290000+int64(n)*1000, n) + } + size := func() int64 { + t.Helper() + fi, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + return fi.Size() + } + read := dshCallReader(t, p) + check := func(what string, from int64, want ...int) { + t.Helper() + in, starts := read() + if len(starts) == 0 { + t.Fatalf("%s: not read", what) + } + for _, at := range starts { + if at != from { + t.Fatalf("%s: read from %d, want %d (%v)", what, at, from, starts) + } + } + if !slices.Equal(in, want) { + t.Fatalf("%s: calls %v, want %v", what, in, want) + } + } + check("first read", 0, 10, 100) + + was := size() + appendText(t, p, frame(reply(6))) + check("a frame appended", was, 6, 10, 100) + + was = size() + f := frame(reply(7)) + appendText(t, p, f[:len(f)/2]) + check("half a frame", was, 6, 10, 100) + appendText(t, p, f[len(f)/2:]) + check("the half frame finished", was, 6, 7, 10, 100) + + // a frame ending inside a line: the line is read once whole, from + // the frame it starts in + was = size() + r9 := reply(9) + appendText(t, p, frame(reply(8)+r9[:20])) + check("a frame ending in a line", was, 6, 7, 8, 10, 100) + appendText(t, p, frame(r9[20:])) + check("the line finished in the next frame", was, 6, 7, 8, 9, 10, 100) + + resetCalls() + was = size() + appendText(t, p, frame(reply(11))) + check("from the disk shard", was, 6, 7, 8, 9, 10, 11, 100) + + if err := os.WriteFile(p, []byte(orig), 0o644); err != nil { + t.Fatal(err) + } + check("cut short", 0, 10, 100) +} + +// A fork's end-seed that comes in a later read still ends what it was +// seeded with: what was counted before it is its source's, in memory and +// in the disk shard. +func TestDshCallsEndSeedAcrossReads(t *testing.T) { + inZone(t, 0) + home := setupAgents(t) + p := filepath.Join(home, ".dsh", "sessions", "work-dsh-3f2a", "dsh-c", "session.v3.jsonl") + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + cut := bytes.Index(b, []byte(`{"type":"session/end-seed"`)) + rest := bytes.IndexByte(b[cut:], '\n') + cut + 1 + if err := os.WriteFile(p, b[:cut], 0o644); err != nil { + t.Fatal(err) + } + read := dshCallReader(t, p) + if in, _ := read(); !slices.Equal(in, []int{100}) { + t.Fatalf("before its end-seed: %v", in) + } + appendText(t, p, string(b[cut:rest])) + if in, starts := read(); len(in) != 0 || !slices.Equal(starts, []int64{int64(cut)}) { + t.Fatalf("its end-seed read on from %v: %v, want none", starts, in) + } + appendText(t, p, string(b[rest:])) + if in, starts := read(); !slices.Equal(in, []int{50}) || !slices.Equal(starts, []int64{int64(rest)}) { + t.Fatalf("the fork's own, read on from %v: %v", starts, in) + } + resetCalls() + if in, starts := read(); !slices.Equal(in, []int{50}) || len(starts) != 0 { + t.Fatalf("from the disk shard (read from %v): %v", starts, in) + } +} From a77f6ae168dd8d5307da6b0dd1a5ba14aa550ae1 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 09:07:06 +0800 Subject: [PATCH 34/92] sessions: a WorkBuddy reply whose first line spent nothing is one call Found in the reader audit, not a speed fix. readWorkBuddyCalls replaced the call before a line whenever the line's messageId was the one the line before it carried. A zero-token line makes no call but still set that id. So a reply opening with a zero line: - as a session's first reply, panicked: index out of range [-1] at st.Calls[len(st.Calls)-1], which took down the Usage ledger's read; - after another reply, overwrote that reply's call. m8 50/5, then m9 0/0, then m9 300/20 gave one call (m9) where the Sessions summary (workbuddyLine: unuse m9's zero, keep m8) counts both. The call before is replaced now only when it carries the same id. CodeBuddy and the other WorkBuddy builds read through the same reader. Test: TestWorkBuddyCallsReplyStartingAtZero writes both cases. - On the old code: panic, index out of range [-1]. - Broken by hand, with only a len(st.Calls) > 0 check: red, "calls [m9 300/20], want m8's and m9's". Run: go test ./internal/sessions -run 'WorkBuddy|CodeBuddy|Buddy' -count=1 ok. The full-suite record is in the report for this series. --- internal/sessions/calls_workbuddy.go | 4 ++- internal/sessions/calls_workbuddy_test.go | 40 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/internal/sessions/calls_workbuddy.go b/internal/sessions/calls_workbuddy.go index 63ae13e27..00de930e8 100644 --- a/internal/sessions/calls_workbuddy.go +++ b/internal/sessions/calls_workbuddy.go @@ -185,7 +185,9 @@ func readWorkBuddyCalls(f file) (*callFile, bool) { // it is a new one, so both readers end on the same call id := st.str(l.ProviderData.MessageID) if c, ok := workbuddyCall(st, dir, l, b); ok { - if c.Msg != "" && c.Msg == last { + // a zero-token line made no call, so the call before is + // this reply's only when it carries the same id + if n := len(st.Calls); c.Msg != "" && c.Msg == last && n > 0 && st.Calls[n-1].Msg == c.Msg { st.Calls[len(st.Calls)-1] = c // another line of the reply before it } else { st.Calls = append(st.Calls, c) diff --git a/internal/sessions/calls_workbuddy_test.go b/internal/sessions/calls_workbuddy_test.go index 73093ebab..8739ffc88 100644 --- a/internal/sessions/calls_workbuddy_test.go +++ b/internal/sessions/calls_workbuddy_test.go @@ -3,6 +3,7 @@ package sessions import ( "os" "path/filepath" + "strconv" "testing" "time" ) @@ -167,3 +168,42 @@ func TestWorkBuddyGatewayFollowsModelsJSON(t *testing.T) { t.Fatal("a routing group's name stopped being the gateway's") } } + +// A reply whose first usage line spent nothing, before any call of the +// session's, is one call when its next line spends: there is no call +// before it to stand for, and reading it must not take one that isn't +// there. +func TestWorkBuddyCallsReplyStartingAtZero(t *testing.T) { + home := setupAgents(t) + p := filepath.Join(home, ".workbuddy", "projects", "Users-me-zero", "44444444-aaaa-4bbb-8ccc-000000000009.jsonl") + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + line := func(msg string, in, out int) string { + return `{"id":"a9","timestamp":1790503210000,"type":"message","role":"assistant","providerData":{"messageId":"` + msg + `","model":"hy3","requestModelId":"hy3","usage":{"inputTokens":` + strconv.Itoa(in) + `,"outputTokens":` + strconv.Itoa(out) + `}},"sessionId":"44444444-aaaa-4bbb-8ccc-000000000009","cwd":"/work/zero"}` + "\n" + } + read := func() []Call { + resetCalls() + for _, s := range CallSources() { + if s.Path == p { + return ReadCallSource(s) + } + } + t.Fatal("no call source for the session") + return nil + } + if err := os.WriteFile(p, []byte(line("m9", 0, 0)+line("m9", 300, 20)), 0o644); err != nil { + t.Fatal(err) + } + if got := read(); len(got) != 1 || got[0].Tokens != (Tokens{Input: 300, Output: 20}) { + t.Fatalf("calls %+v, want the reply's one", got) + } + // after another reply's call: that call is not this reply's to replace + if err := os.WriteFile(p, []byte(line("m8", 50, 5)+line("m9", 0, 0)+line("m9", 300, 20)), 0o644); err != nil { + t.Fatal(err) + } + got := read() + if len(got) != 2 || got[0].Msg != "m8" || got[0].Tokens != (Tokens{Input: 50, Output: 5}) || got[1].Msg != "m9" || got[1].Tokens != (Tokens{Input: 300, Output: 20}) { + t.Fatalf("calls %+v, want m8's and m9's", got) + } +} From c381e4cd1e9ed5fb70f869ad9d841c736f985266 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:29:25 +0800 Subject: [PATCH 35/92] sessions: a read is never held by another read's refresh, only by a change to the files (#2776) A read of the sessions (List, Stats, Manage, the agents' lists, Codex's threads) took dbReadMu, a plain mutex, for the whole call, parse included. The start's warm-up reads every session file with a quarter of the cores, so the first pages and API calls after a start waited for its whole read before they could even look at the cache. - dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only the changes to the files (Delete, a Codex provider move, a Claude project relocation) take it alone. - A file another refresh is reading now is in `parsing`, with a channel closed when its parse is in the cache. A second read serves the parse it already has of such a file, and waits only for one it has never read; it never reads the same file twice at once. - Each parse is published as it finishes, not in checkpoint batches, so a waiting reader gets it at once. - The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the end of every read; with reads overlapping, one could close a handle another still used. They now live as long as their last user (useDBs). get() and the titles path closed them without the lock at all before. Tests (internal/sessions/refresh_shared_test.go), each broken by hand: - TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is held; List and Manage answer within 10s from the kept parses, each file is parsed once in all, and a later List parses none. With storeMu.Lock in List: red, "List waited for another read of the same files to end". - TestReadWaitsForAFirstReadUnderWay: a file never read is waited for, not served empty, and read once. Without the waits: red, "List answered without the files being read". Without the skip of a file being read: panic, close of nil channel. - TestStoresLiveAsLongAsTheirLastUser: with the release always closing: red, "closed while a read still used it". All three pass with -race. Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code and Codex sessions, 300 grown since the last start; 4 API calls asked 3.5s after the routes, when the warm-up starts), base 1a3b92688 against this branch, back to back. The machine's load average was 350-480 (nine agents running suites), so these timings are mostly CPU wait and vary by tens of seconds run to run: first answer (stats?days=30) base 91s / 81s new 50s / 79s manage?agent=claude base 112s / 95s new 83s / 96s The pages no longer queue behind the warm-up's lock, but at this load the answer is bound by the CPU its own parse gets, so no gain shows above the noise in the second pair. On an idle machine the held reads are what #2776 reports; the tests above show they are no longer held. Run on origin/main 2ceff7370 with all four #2776 commits' changes (this one and the three beside it), load average 291-568 (nine agents running suites), macOS: - go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok, among them agent (2310s), gateway (1707s), provider (764s), usage (83s). Red: - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept, TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each "TempDir: mkdir ...: no space left on device" (the disk filled mid-run). After space was freed, ./internal/sessions alone: ok (139s). - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow, TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and TestMainWindowCorners (86s): the real-window AppKit tests under load, already filed as #2645 and #1936. Rerun alone at load ~335: all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s). - gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and GOOS=windows all exit 0. - No internal/gui/assets file changed, so the GUI Playwright suite was not run. - At this commit alone (2ceff7370 + this change): ./internal/sessions ok (82s), and its three new tests with -race ok. --- internal/sessions/codex.go | 6 +- internal/sessions/codex_provider.go | 6 +- internal/sessions/manage.go | 30 ++-- internal/sessions/opencode.go | 19 ++- internal/sessions/refresh_shared_test.go | 171 +++++++++++++++++++++++ internal/sessions/relocate_claude.go | 4 +- internal/sessions/sessions.go | 103 ++++++++++---- internal/sessions/stats.go | 6 +- internal/sessions/traces_opencode_db.go | 2 +- internal/sessions/traces_review_test.go | 6 +- internal/sessions/transcript_opencode.go | 18 ++- 11 files changed, 312 insertions(+), 59 deletions(-) create mode 100644 internal/sessions/refresh_shared_test.go diff --git a/internal/sessions/codex.go b/internal/sessions/codex.go index 50730fc22..8d27e7bc0 100644 --- a/internal/sessions/codex.go +++ b/internal/sessions/codex.go @@ -277,12 +277,12 @@ func noteCodexIdentity(s *state, identity CodexIdentity, conflict bool) { // CodexIdentities returns an independent snapshot of the native thread identities. func CodexIdentities() map[string]CodexIdentity { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() want := append(codexFiles(), wslFiles("codex")...) refresh(want, nil) return codexIdentitySnapshot(want) diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index 6a1de69c0..52ca0e870 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -195,12 +195,12 @@ func MoveCodexProvider(id, to string) (CodexMove, error) { if !codexProviderRe.MatchString(to) { return CodexMove{}, fmt.Errorf("%q isn't a provider id", to) } - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() all := allFiles() groups := map[string][]file{} var mine []file diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index da52f5cd2..aa673df85 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -73,11 +73,11 @@ var ErrActive = errors.New("the session was written to in the last minute; it ma // Agents are the agents with sessions on this computer, by how many. func Agents() []AgentCount { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() - defer closeDBs() + defer useDBs()() return agentCounts(allFiles()) } @@ -105,12 +105,12 @@ func agentCounts(all []file) []AgentCount { // ListAgent is every session of one agent, the most recently active first, // with no limit; one nothing was said in is listed too, to be cleared away. func ListAgent(agent string) []Managed { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() return listAgent(agent, allFiles()) } @@ -120,12 +120,12 @@ func ListAgent(agent string) []Managed { // agents' files are looked at, and of those only the ones whose session id // is inside the file are read when they changed. func NativeIDs(agents map[string]bool) map[string]map[string]bool { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() return nativeIDs(agents, allFiles()) } @@ -146,12 +146,12 @@ type ManageView struct { // Only native's agents and the one picked are read: a change to another // agent's sessions waits for a page that shows it (#2776). func Manage(native map[string]bool, pick func([]AgentCount, map[string]map[string]bool) string) ManageView { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() all := allFiles() v := ManageView{Agents: agentCounts(all), Native: nativeIDs(native, all)} v.Agent = pick(v.Agents, v.Native) @@ -298,12 +298,12 @@ func Delete(agent, id string) (Trashed, error) { if !safeID.MatchString(id) { return Trashed{}, errors.New("no such session") } - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() all := allFiles() groups := map[string][]file{} var mine []file diff --git a/internal/sessions/opencode.go b/internal/sessions/opencode.go index 0e36617f0..60e1fff8c 100644 --- a/internal/sessions/opencode.go +++ b/internal/sessions/opencode.go @@ -8,6 +8,7 @@ import ( "path/filepath" "sort" "strings" + "sync" "time" "github.com/yetone/magpie/internal/appdir" @@ -170,9 +171,25 @@ func ocRoots(out []file, parent map[string]string) []file { // ---- the database ------------------------------------------------------------- // dbs are the databases open while List or Stats reads them, closed when -// they are done (closeDBs). +// the last of the reads using them is done (useDBs). var dbs = map[string]*sql.DB{} +// dbUsers is how many reads use dbs now. A read lets mu go while it parses +// with them, and another read may then start and end: it must not close +// what the first is still reading (#2776). +var dbUsers int + +// useDBs counts a read, with mu held, as a user of dbs until the release it +// returns is called, with mu held again; the last to go closes them. +func useDBs() (release func()) { + dbUsers++ + return sync.OnceFunc(func() { + if dbUsers--; dbUsers == 0 { + closeDBs() + } + }) +} + // Snapshot readers also remove their temporary database when a scan ends. var dbCleanup = map[string]func(){} diff --git a/internal/sessions/refresh_shared_test.go b/internal/sessions/refresh_shared_test.go new file mode 100644 index 000000000..57dd9d5ec --- /dev/null +++ b/internal/sessions/refresh_shared_test.go @@ -0,0 +1,171 @@ +package sessions + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +// growSessions adds a line to each of moreSessions' files, so each has to +// be read again. +func growSessions(t *testing.T, claude string, n int) { + t.Helper() + dir := filepath.Join(claude, "projects", "-work-many") + for i := range n { + p := filepath.Join(dir, fmt.Sprintf("33333333-2222-3333-4444-%012d.jsonl", i)) + f, err := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + f.WriteString(ccMsg(fmt.Sprintf("n%d", i), "2026-09-21T11:00:00.000Z", 100, 10)) + f.Close() + } +} + +// A page asked for while the start's warm-up reads the changed files is +// answered with the parses kept of them, not held until the warm-up has +// read them all (#2776: the warm-up held the page for its whole read). +func TestReadNotHeldByAnotherRead(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + if n := len(List(0)); n < 12 { + t.Fatalf("listed %d sessions", n) + } + growSessions(t, claude, 12) + + hold, started := make(chan struct{}), make(chan struct{}) + var once sync.Once + var parsed atomic.Int32 + parseHook = func() { + parsed.Add(1) + once.Do(func() { close(started) }) + <-hold + } + release := sync.OnceFunc(func() { close(hold) }) + t.Cleanup(func() { release(); parseHook = nil }) + + warm := make(chan struct{}) + go func() { defer close(warm); statsAt(0, statsNow) }() + <-started + + listed := make(chan []Session, 1) + go func() { listed <- List(0) }() + select { + case got := <-listed: + if len(got) < 12 { + t.Fatalf("listed %d sessions while another read ran", len(got)) + } + case <-time.After(10 * time.Second): + t.Fatal("List waited for another read of the same files to end") + } + managed := make(chan ManageView, 1) + go func() { + managed <- Manage(map[string]bool{"claude": true}, func([]AgentCount, map[string]map[string]bool) string { return "claude" }) + }() + select { + case v := <-managed: + if len(v.Sessions) < 12 { + t.Fatalf("managed %d sessions while another read ran", len(v.Sessions)) + } + case <-time.After(10 * time.Second): + t.Fatal("Manage waited for another read of the same files to end") + } + release() + <-warm + if n := parsed.Load(); n != 12 { + t.Fatalf("the 12 changed files were read %d times", n) + } + // and what the warm-up read is in, for the next page + parsed.Store(0) + List(0) + if n := parsed.Load(); n != 0 { + t.Fatalf("read %d files again after the warm-up had read them", n) + } +} + +// A file never read before has no parse to serve: a page waits for the +// read already under way, rather than reading it a second time. +func TestReadWaitsForAFirstReadUnderWay(t *testing.T) { + inZone(t, 0) + claude, _ := setup(t) + moreSessions(t, claude, 12) + + hold, started := make(chan struct{}), make(chan struct{}) + var once sync.Once + var parsed atomic.Int32 + parseHook = func() { + parsed.Add(1) + once.Do(func() { close(started) }) + <-hold + } + release := sync.OnceFunc(func() { close(hold) }) + t.Cleanup(func() { release(); parseHook = nil }) + + warm := make(chan struct{}) + go func() { defer close(warm); statsAt(0, statsNow) }() + <-started + before := parsed.Load() + + listed := make(chan []Session, 1) + go func() { listed <- List(0) }() + select { + case <-listed: + t.Fatal("List answered without the files being read") + case <-time.After(200 * time.Millisecond): + } + release() + var got []Session + select { + case got = <-listed: + case <-time.After(30 * time.Second): + t.Fatal("List never answered") + } + <-warm + if len(got) < 12 { + t.Fatalf("listed %d sessions", len(got)) + } + total := before + mu.Lock() + n := len(cache) + mu.Unlock() + if p := parsed.Load(); p != int32(n) { + t.Fatalf("%d files read %d times (%d before the page asked)", n, p, total) + } +} + +// The stores two reads share stay open until the last of them is done: a +// read that ends first must not close what the other still reads. +func TestStoresLiveAsLongAsTheirLastUser(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.db") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + mu.Lock() + first := useDBs() + db := openDB(path) + second := useDBs() + if openDB(path) != db { + mu.Unlock() + t.Fatal("a second read opened its own handle") + } + second() + mu.Unlock() + if db == nil { + t.Fatal("not opened") + } + if err := db.Ping(); err != nil { + t.Fatalf("closed while a read still used it: %v", err) + } + mu.Lock() + first() + open := dbs[path] != nil + mu.Unlock() + if open || db.Ping() == nil { + t.Fatal("left open after the last read") + } +} diff --git a/internal/sessions/relocate_claude.go b/internal/sessions/relocate_claude.go index 9ae12f7c1..3d4b682e4 100644 --- a/internal/sessions/relocate_claude.go +++ b/internal/sessions/relocate_claude.go @@ -39,8 +39,8 @@ type ClaudeRelocationResult struct { // session-ID-keyed files (file-history, todos and session-env). IDs stay intact. // Clients must be closed: the in-process lock cannot exclude Claude itself. func RelocateClaudeProject(in ClaudeRelocation) (ClaudeRelocationResult, error) { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.Lock() + defer storeMu.Unlock() mu.Lock() defer mu.Unlock() root, target, err := claudeRelocationRoot(in) diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index a906d0033..1807a354e 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -615,10 +615,20 @@ func rolloutTwin(p string) string { } var ( - // DB readers share connection lifetimes; call-file readers need only mu. - dbReadMu sync.Mutex - mu sync.Mutex - cache map[string]*state // path → parse + // storeMu keeps the reads of the sessions apart from the changes made + // to their files (Delete, a provider move, a project relocation): a + // read takes it shared, so reads never wait on one another, and a + // change alone. The store handles they share live as long as their last + // user (useDBs), not as long as the read that opened them. + storeMu sync.RWMutex + mu sync.Mutex + cache map[string]*state // path → parse + // parsing holds the files a refresh is reading now, each closed when + // its parse is in the cache: another reader serves the parse kept of + // such a file rather than reading it a second time, and waits only for + // one it has no parse of yet (#2776: the start's warm-up held every + // page for its whole read) + parsing = map[string]chan struct{}{} loaded bool cacheGeneration uint64 // the zone the parses in memory date their days in @@ -770,15 +780,26 @@ func writeCache(c *save) { // cached agents alone, for a Codex-only identity refresh. func refresh(want, all []file) { defer func() { trimSummaryRevisions(time.Now()) }() - var todo []file + var todo, waits []file for _, f := range want { if f.cold { continue // in a stopped WSL distro: what was read of it stands } if s := cache[f.path]; s == nil || s.Size != f.size || s.Mod != f.mod.UnixNano() || (f.agent == "hermes" && (f.hermes == nil || f.rev == "" || s.DBRevision != f.rev)) || ((f.agent == "alma" || f.agent == "cursor") && s.DBRevision != f.rev) { + if parsing[f.path] != nil { + // another refresh is reading it: its last parse stands + // until that one is in, and one never read is waited for + if s == nil { + waits = append(waits, f) + } + continue + } todo = append(todo, f) } } + if len(waits) > 0 { + defer waitParsing(waits) + } gone := false if len(cache) > 0 && all != nil { on := make(map[string]bool, len(all)) @@ -821,6 +842,7 @@ func refresh(want, all []file) { jobs := make([]job, len(todo)) for i, f := range todo { jobs[i] = job{f: f, old: cache[f.path]} + parsing[f.path] = make(chan struct{}) } generation := cacheGeneration mu.Unlock() @@ -853,15 +875,16 @@ func refresh(want, all []file) { } close(ch) }() - // publish puts the parses finished since last time in the cache. - publish := func(done []int) { - for _, i := range done { - j := &jobs[i] - // A concurrent read may already have published a newer parse. - if generation == cacheGeneration && cache[j.f.path] == j.old { - cache[j.f.path] = j.parsed - } + // publish puts a finished parse in the cache at once, for a reader + // waiting on it, and lets the file be read again. + publish := func(i int) { + j := &jobs[i] + // A concurrent read may already have published a newer parse. + if generation == cacheGeneration && cache[j.f.path] == j.old { + cache[j.f.path] = j.parsed } + close(parsing[j.f.path]) + delete(parsing, j.f.path) } // What is read is kept on disk every checkpointEvery, not only at the // end: a first read of a long history on a slow disk runs for minutes, @@ -869,33 +892,65 @@ func refresh(want, all []file) { // of it, so the next start read it all again. tick := time.NewTicker(checkpointEvery) defer tick.Stop() - var done []int + unsaved := false for n := 0; n < len(jobs); { select { case i := <-finished: - done = append(done, i) + mu.Lock() + publish(i) + mu.Unlock() + unsaved = true n++ case <-tick.C: - if len(done) == 0 { + if !unsaved { continue } mu.Lock() - publish(done) if generation == cacheGeneration { saveCache() } mu.Unlock() - done = done[:0] + unsaved = false } } mu.Lock() - publish(done) progress.finish() if generation == cacheGeneration { saveCache() } } +// waitParsing waits, with mu let go, for the files other refreshes are +// reading, and reads itself any of them that came to nothing (a Reset +// dropped its parse). +func waitParsing(fs []file) { + for { + var chans []chan struct{} + for _, f := range fs { + if ch := parsing[f.path]; ch != nil { + chans = append(chans, ch) + } + } + if len(chans) == 0 { + break + } + mu.Unlock() + for _, ch := range chans { + <-ch + } + mu.Lock() + } + var missing []file + for _, f := range fs { + if cache[f.path] == nil { + missing = append(missing, f) + } + } + if len(missing) > 0 { + refresh(missing, nil) + } +} + // checkpointEvery is how often a long read of changed files keeps what it // has read so far on disk. var checkpointEvery = 5 * time.Second @@ -1008,8 +1063,8 @@ func Reset() { // List reads the latest sessions of every agent, the most recently active // first, at most limit of them (Limit when 0). func List(limit int) []Session { - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() if limit <= 0 { limit = Limit } @@ -1017,7 +1072,7 @@ func List(limit int) []Session { defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() groups := map[string][]file{} latest := map[string]time.Time{} @@ -1627,7 +1682,7 @@ func Titles(keys []string) map[string]string { mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() groups := map[string][]file{} var fs []file @@ -1675,7 +1730,7 @@ func get(key string) (s Session, ok, found bool) { mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() var fs []file for _, f := range files { diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index c8035dc3e..67c8a10de 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -131,12 +131,12 @@ func statsIn(days int, now time.Time, native map[string]bool) Stats { } out := Stats{From: from, To: today.Format(time.DateOnly), Days: []Day{}, Sessions: []Summary{}, Keys: []string{}} - dbReadMu.Lock() - defer dbReadMu.Unlock() + storeMu.RLock() + defer storeMu.RUnlock() mu.Lock() defer mu.Unlock() loadCache() - defer closeDBs() + defer useDBs()() files := allFiles() // every changed file, whatever the range, so a wider range picked later // finds them read rather than starting another run diff --git a/internal/sessions/traces_opencode_db.go b/internal/sessions/traces_opencode_db.go index cfd386f3f..74140ee54 100644 --- a/internal/sessions/traces_opencode_db.go +++ b/internal/sessions/traces_opencode_db.go @@ -12,7 +12,7 @@ import ( // These connections belong to the trace reader, not the Sessions listing cache. // Updates are read in timestamp/ID order in bounded batches; large histories -// neither hold dbReadMu nor force the entire conversation to be re-exported. +// neither hold storeMu nor force the entire conversation to be re-exported. type ocTraceState struct { messages map[string]ocTraceMessage order []string diff --git a/internal/sessions/traces_review_test.go b/internal/sessions/traces_review_test.go index c5ab8f71f..9af8a793b 100644 --- a/internal/sessions/traces_review_test.go +++ b/internal/sessions/traces_review_test.go @@ -156,15 +156,15 @@ func TestOpenCodeTraceLargeSessionProgressAndIncrementalUpdate(t *testing.T) { for i := 0; i < 12; i++ { budget := int64(8 << 20) // Trace reading must not acquire the Sessions listing mutex. - dbReadMu.Lock() + storeMu.Lock() done := make(chan []TraceSpan, 1) go func() { done <- r.pollOpenCode(false, &budget) }() var spans []TraceSpan select { case spans = <-done: - dbReadMu.Unlock() + storeMu.Unlock() case <-time.After(10 * time.Second): - dbReadMu.Unlock() + storeMu.Unlock() <-done t.Fatal("trace reading blocked on the listing mutex") } diff --git a/internal/sessions/transcript_opencode.go b/internal/sessions/transcript_opencode.go index 833616feb..92b6d7fc4 100644 --- a/internal/sessions/transcript_opencode.go +++ b/internal/sessions/transcript_opencode.go @@ -8,10 +8,20 @@ import ( // openCodeTranscript reads the conversation in message order from the same // store the listing chose, including while a v1 to v2 migration is underway. func openCodeTranscript(s Session, add func(bool, Part) bool) error { - dbReadMu.Lock() - defer dbReadMu.Unlock() - defer closeDBs() - for _, f := range openCodeFiles() { + storeMu.RLock() + defer storeMu.RUnlock() + // the store handles are shared with the reads that hold mu: they are + // opened and given back under it, and read from without it + mu.Lock() + release := useDBs() + files := openCodeFiles() + mu.Unlock() + defer func() { + mu.Lock() + release() + mu.Unlock() + }() + for _, f := range files { if f.sid != s.ID { continue } From d7e02ae0882047ada02c9660f8ebf52b93d9acf5 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:29:39 +0800 Subject: [PATCH 36/92] sessions: a scan's read buffer is the size of what is left of the file, 1 MiB at most (#2776) scanAt gave every scan a 1 MiB bufio buffer. A start reads ~4,600 mostly small session files (and reads each again from where it was left), so those buffers were the largest single allocation of a start: 9.4 GB of the 22.4 GB a warm start allocated on the sandbox below. The buffer is now the rest of a plain file plus one byte, at least 16 KiB and at most 1 MiB; a packed (zstd) file keeps 1 MiB. A line longer than the buffer (a file grown since its size was read) is still read whole through scanAt's long-line path. Tests (internal/sessions/scan_buffer_test.go): - TestScanOfASmallFileTakesASmallBuffer: 200 scans of a two-line file allocate under 64 KiB each. With the 1 MiB buffer back: red, "a scan of a two-line file allocated 1048871 bytes". - TestScanReadsALineLongerThanItsBuffer: a line three buffers long, then a short one, are both handed over whole. Measured on a sandbox instance (600k gateway calls, ~4,600 sessions), base 1a3b92688 against this branch with every #2776 commit, back to back at a load average of 340-450 (nine agents running suites), heap profile after the four first API calls and 60s idle: allocated of it scan buffers live heap warm base 22.40 GB 9.40 GB 483 MB warm new 15.86 GB 1.98 GB 498 MB cold base 22.48 GB 9.31 GB 450 MB cold new 15.76 GB 1.98 GB 498 MB What is left in bufio.NewReaderSize is the other call readers' own 1 MiB buffers (calls_pi, calls_kimi, ...). Peak RSS did not drop at this load (base 4.38/4.41 GB, new 4.59/4.54 GB): the peak comes from the four first calls each materialising the 600k-call ledger at once (gatewayRecords appends every Record, 2.56 GB allocated; ledgerOfAt 6.2 GB for CodexModelEffort), which this commit does not change. Run on origin/main 2ceff7370 with all four #2776 commits' changes (this one and the three beside it), load average 291-568 (nine agents running suites), macOS: - go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok, among them agent (2310s), gateway (1707s), provider (764s), usage (83s). Red: - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept, TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each "TempDir: mkdir ...: no space left on device" (the disk filled mid-run). After space was freed, ./internal/sessions alone: ok (139s). - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow, TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and TestMainWindowCorners (86s): the real-window AppKit tests under load, already filed as #2645 and #1936. Rerun alone at load ~335: all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s). - gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and GOOS=windows all exit 0. - No internal/gui/assets file changed, so the GUI Playwright suite was not run. --- internal/sessions/scan_buffer_test.go | 63 +++++++++++++++++++++++++++ internal/sessions/sessions.go | 18 +++++++- 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 internal/sessions/scan_buffer_test.go diff --git a/internal/sessions/scan_buffer_test.go b/internal/sessions/scan_buffer_test.go new file mode 100644 index 000000000..8844a66f1 --- /dev/null +++ b/internal/sessions/scan_buffer_test.go @@ -0,0 +1,63 @@ +package sessions + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// A scan of a small session file takes a buffer the size of the file, not +// 1 MiB: a start reads thousands of them, and their buffers were most of +// what it allocated (#2776). +func TestScanOfASmallFileTakesASmallBuffer(t *testing.T) { + p := filepath.Join(t.TempDir(), "s.jsonl") + if err := os.WriteFile(p, []byte(`{"type":"user","n":1}`+"\n"+`{"type":"assistant","n":2}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + const scans = 200 + lines := 0 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range scans { + if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { lines++; return true }); err != nil { + t.Fatal(err) + } + } + runtime.ReadMemStats(&after) + if lines != 2*scans { + t.Fatalf("read %d lines, want %d", lines, 2*scans) + } + // 16 KiB each, with room for the file handles and anything else + if per := (after.TotalAlloc - before.TotalAlloc) / scans; per > 64<<10 { + t.Fatalf("a scan of a two-line file allocated %d bytes", per) + } +} + +// A line longer than the buffer (the file grew after its size was read) is +// still handed over whole. +func TestScanReadsALineLongerThanItsBuffer(t *testing.T) { + p := filepath.Join(t.TempDir(), "s.jsonl") + if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil { + t.Fatal(err) + } + f, err := os.Open(p) + if err != nil { + t.Fatal(err) + } + size := scanBuffer(f, 0) + f.Close() + long := `{"text":"` + strings.Repeat("x", 3*size) + `"}` + if err := os.WriteFile(p, []byte(long+"\n{}\n"), 0o600); err != nil { + t.Fatal(err) + } + var got []int + if _, err := scanAt(p, 0, nil, func(b []byte, _, _ int64) bool { got = append(got, len(b)); return true }); err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0] != len(long) || got[1] != 2 { + t.Fatalf("lines %v, want [%d 2]", got, len(long)) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 1807a354e..3fd94942b 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1371,7 +1371,7 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } return off, err } - r := bufio.NewReaderSize(f, 1<<20) + r := bufio.NewReaderSize(f, scanBuffer(f, off)) var long []byte var n int64 // bytes of the line so far skip, seen := false, false @@ -1413,6 +1413,22 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } } +// scanBuffer is the read buffer scanAt needs for what is left of f from off: +// 1 MiB at most, and no more than that rest of a plain file. Every scan +// took 1 MiB, and a start's read of ~4,600 mostly small session files +// (each read again from where it was left) allocated ~9 GB of them, which +// the GC's heap target followed up (#2776). A line longer than the buffer +// (a file grown since) is still read whole, through scanAt's long line. +func scanBuffer(f io.Reader, off int64) int { + const most, least = 1 << 20, 16 << 10 + if pf, ok := f.(*os.File); ok { + if info, err := pf.Stat(); err == nil { + return int(min(most, max(least, info.Size()-off+1))) + } + } + return most +} + // packed says whether a session file is compressed: a Codex rollout the // Codex app has packed (.zst), a dsh session (.zstd). A packed rollout is // written whole, so it is read whole again whenever it changes. From cfbd321fc47ea5ba52876f6479b8bc672f7a9649 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:29:44 +0800 Subject: [PATCH 37/92] gui: the start's warm-up reads Codex's per-thread effort when there are Codex sessions (#2776) The first Sessions page after a start that showed Codex rows read usage.CodexModelEffort cold, from the whole ledger, while the page waited. The warm-up now reads it as its last step, after the stats it already warmed, and only when those stats hold a Codex session; every later ask is answered from what CodexModelEffort keeps per period. The steps move into warmSteps() so a test can run them. TestWarmUpReadsCodexEffort: with Codex keys in the stats the step reads the effort once, with none it reads nothing. With the step removed: red, "read 0 times, want 1". Measured on the same sandbox as the commit before (600k gateway calls, ~4,600 sessions), base 1a3b92688 against this branch, back to back, at a load average of 350-480 (nine agents running suites): manage?agent=codex, asked 3.5s after the routes: base 226s / 190s / 232s (cold) new 247s / 222s / 246s (cold) It is not faster here: asked at 3.5s, the page arrives before the warm-up reaches its last step, and both read the ledger at once; the load makes every one of these numbers mostly CPU wait. The step helps a first Codex page opened after the warm-up is done, which is the case in #2776 (a page opened some time after a restart). Not measured at that point under this load. Run on origin/main 2ceff7370 with all four #2776 commits' changes (this one and the three beside it), load average 291-568 (nine agents running suites), macOS: - go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok, among them agent (2310s), gateway (1707s), provider (764s), usage (83s). Red: - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept, TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each "TempDir: mkdir ...: no space left on device" (the disk filled mid-run). After space was freed, ./internal/sessions alone: ok (139s). - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow, TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and TestMainWindowCorners (86s): the real-window AppKit tests under load, already filed as #2645 and #1936. Rerun alone at load ~335: all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s). - gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and GOOS=windows all exit 0. - No internal/gui/assets file changed, so the GUI Playwright suite was not run. --- internal/gui/sessions.go | 28 +++++++++++++++++------ internal/gui/sessions_warm_test.go | 36 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 17ce06eca..27d306bf6 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -481,16 +481,30 @@ func warmSessions() { time.Sleep(3 * time.Second) // with few readers, as nobody waits on it yet: after an update // that reads every file again, it held every core (#1665) - sessions.Warm(func() { - warmUp( - func() { statsFor(0) }, - func() { statsFor(30) }, - func() { usage.QueryPage(usage.All, usage.Filter{}, 0, 50) }, - ) - }) + sessions.Warm(func() { warmUp(warmSteps()...) }) }() } +// warmSteps are the reads the warm-up makes before any page asks for them. +// The last is Codex's per-thread effort, when there are Codex sessions: a +// first Codex page after a start read it from the whole ledger while it +// waited (#2776), and every later ask is answered from what it kept. +func warmSteps() []func() { + return []func(){ + func() { statsFor(0) }, + func() { statsFor(30) }, + func() { usage.QueryPage(usage.All, usage.Filter{}, 0, 50) }, + func() { + if slices.ContainsFunc(statsFor(0).Keys, func(k string) bool { return strings.HasPrefix(k, "codex:") }) { + warmCodexEffort() + } + }, + } +} + +// warmCodexEffort reads what the Sessions page's Codex rows ask for. +var warmCodexEffort = func() { usage.CodexModelEffort(usage.All) } + // warmUp runs the warm-up's reads, then hands what they threw away back to // the system at once. Reading a long history allocates many times what it // keeps (a 13k-session Codex and Claude Code history: ~830 MB allocated to diff --git a/internal/gui/sessions_warm_test.go b/internal/gui/sessions_warm_test.go index 97b68f1a6..ebf3464ba 100644 --- a/internal/gui/sessions_warm_test.go +++ b/internal/gui/sessions_warm_test.go @@ -3,6 +3,9 @@ package gui import ( "runtime" "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" ) // The warm-up's garbage goes back to the system when it ends, not over the @@ -26,3 +29,36 @@ func TestWarmUpReturnsItsGarbage(t *testing.T) { } runtime.KeepAlive(keep) } + +// With Codex sessions on this computer the warm-up also reads Codex's +// per-thread effort, which a first Codex page after a start otherwise read +// from the whole ledger while it waited (#2776); without any it doesn't. +func TestWarmUpReadsCodexEffort(t *testing.T) { + statsMemo.Lock() + saved := statsMemo.m + statsMemo.Unlock() + old := warmCodexEffort + t.Cleanup(func() { + statsMemo.Lock() + statsMemo.m = saved + statsMemo.Unlock() + warmCodexEffort = old + }) + for _, c := range []struct { + keys []string + want int + }{{[]string{"claude:a", "codex:b"}, 1}, {[]string{"claude:a"}, 0}} { + statsMemo.Lock() + statsMemo.m = map[int]*statsKept{} + for _, d := range []int{0, 30} { + statsMemo.m[d] = &statsKept{at: time.Now(), st: sessions.Stats{Keys: c.keys}} + } + statsMemo.Unlock() + read := 0 + warmCodexEffort = func() { read++ } + warmUp(warmSteps()...) + if read != c.want { + t.Fatalf("with sessions %v Codex's effort was read %d times, want %d", c.keys, read, c.want) + } + } +} From e7114d3882e6f6a069ed71f0d64871518d1dbc54 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:29:47 +0800 Subject: [PATCH 38/92] usage: one gateway session projection is kept, and a range of days is read out of it (#2776) The gateway's sessions were projected and kept once per `since`, up to four at once (all time, and each Sessions stats range: today, 7, 30 days...). With 600k calls the all-time projection alone is ~160 MB in use (pprof inuse_space of buildGatewaySessions on the sandbox below), and #2776 counted 148 MB for its copies. Now only the all-time projection is kept. A range that starts at a local midnight (every stats range does: combinedSessionStats parses st.From in time.Local) is derived from it: each session's days from that date on, with its tokens, models, cost and start/last summed from those days. Each kept day now carries the first and last time of its requests (unexported, two time.Time) so the derived start and last are exact. Any other start is built from the log and not kept. The cache is keyed on the zone too, since the days are local dates. TestGatewayWindowsShareOneProjection: six days of calls over three sessions, priced and unpriced models; the all-time read and five ranges (0, 1, 2, 3 and 7 days back) build one projection between them, and each range equals a direct build from its midnight (sessions, start, last, tokens, models, cost within 1e-9, unpriced, days). Broken by hand: - the midnight path turned off (a build per range, as before): red, "built 6 projections for one log and 5 ranges, want 1". - the derived start taken from the whole session: red, codex|even's Start 2026-10-15 where the build says 2026-10-19. Cost: the two times per kept day add ~13 MB to the one projection on the sandbox below (158 -> 171 MB in use), against a whole second projection (~160 MB) for each range a page asks for. Measured: the sandbox runs (see the commits before) ask only the 30-day range, so their heap shows one kept projection on both sides; the saving is per extra range asked and is shown by the test's build count, not by those runs. Run on origin/main 2ceff7370 with all four #2776 commits' changes (this one and the three beside it), load average 291-568 (nine agents running suites), macOS: - go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok, among them agent (2310s), gateway (1707s), provider (764s), usage (83s). Red: - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept, TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each "TempDir: mkdir ...: no space left on device" (the disk filled mid-run). After space was freed, ./internal/sessions alone: ok (139s). - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow, TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and TestMainWindowCorners (86s): the real-window AppKit tests under load, already filed as #2645 and #1936. Rerun alone at load ~335: all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s). - gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and GOOS=windows all exit 0. - No internal/gui/assets file changed, so the GUI Playwright suite was not run. --- internal/usage/gateway_sessions.go | 164 ++++++++++++++++++------ internal/usage/gateway_sessions_test.go | 68 ++++++++++ internal/usage/kept_strings_test.go | 2 +- 3 files changed, 196 insertions(+), 38 deletions(-) diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index 888afc7ab..8eb143629 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -4,6 +4,7 @@ import ( "slices" "sort" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/catalog" @@ -26,6 +27,10 @@ type GatewayDayUsage struct { sessions.Tokens Cost float64 Priced bool + // first and last bound the day's requests (last includes the request's + // own duration), so a session seen from a later midnight is derived + // from the one kept projection instead of a second copy (#2776). + first, last time.Time } // GatewaySession is a read-only projection of requests served by this @@ -54,14 +59,103 @@ type GatewayModel struct { // history or agent files. NativeKeys contains identities already represented // by local session files and is used to suppress the duplicate projection. func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession { - e := gatewayProjection(since) - out := make([]GatewaySession, 0, len(e.sessions)) - for _, s := range e.sessions { - if !nativeKeys[s.Agent+"|"+s.ID] { - out = append(out, cloneGatewaySession(s)) + if since.IsZero() { + e := gatewayProjection() + out := make([]GatewaySession, 0, len(e.sessions)) + for _, s := range e.sessions { + if !nativeKeys[s.Agent+"|"+s.ID] { + out = append(out, cloneGatewaySession(s)) + } + } + return out + } + if date, ok := localMidnight(since); ok { + // a range of whole days is the all-time projection's days from + // its first on: no copy of it is kept per range (#2776) + e := gatewayProjection() + out := make([]GatewaySession, 0, len(e.sessions)) + for _, s := range e.sessions { + if nativeKeys[s.Agent+"|"+s.ID] || !s.Last.After(since) { + continue + } + if w, ok := gatewaySessionFrom(s, date); ok { + out = append(out, w) + } + } + return out + } + // any other start is read from the log, and not kept + snapshot := readLogSnapshot() + out, _ := buildGatewaySessions(snapshot, since, nativeKeys) + return out +} + +// localMidnight is since's local date when since is that date's start. +func localMidnight(since time.Time) (string, bool) { + date := since.In(time.Local).Format(time.DateOnly) + start, err := time.ParseInLocation(time.DateOnly, date, time.Local) + return date, err == nil && start.Equal(since) +} + +// gatewaySessionFrom is s as it was read from the start of date on: its +// days from then, and its models, tokens, cost and times summed from them. +func gatewaySessionFrom(s GatewaySession, date string) (GatewaySession, bool) { + i := sort.Search(len(s.Daily), func(i int) bool { return s.Daily[i].Date >= date }) + if i == len(s.Daily) { + return GatewaySession{}, false + } + if i == 0 { + return cloneGatewaySession(s), true + } + w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: slices.Clone(s.Daily[i:])} + models := map[string]int{} // index in w.Models, which grows + for _, d := range w.Daily { + if w.Start.IsZero() || d.first.Before(w.Start) { + w.Start = d.first + } + if d.last.After(w.Last) { + w.Last = d.last + } + w.Input += d.Input + w.Output += d.Output + w.CacheRead += d.CacheRead + w.CacheWrite += d.CacheWrite + w.CacheWrite1h += d.CacheWrite1h + at, ok := models[d.Model] + if !ok { + at = len(w.Models) + w.Models = append(w.Models, GatewayModel{Model: d.Model, Priced: true}) + models[d.Model] = at + } + m := &w.Models[at] + m.Input += d.Input + m.Output += d.Output + m.CacheRead += d.CacheRead + m.CacheWrite += d.CacheWrite + m.CacheWrite1h += d.CacheWrite1h + m.Cost += d.Cost + m.Priced = m.Priced && d.Priced + } + finishGatewayModels(&w) + return w, true +} + +// finishGatewayModels sums s's models' cost into it, counts those not priced +// and puts the models in order, the most tokens first. +func finishGatewayModels(s *GatewaySession) { + for _, m := range s.Models { + s.Cost += m.Cost + if !m.Priced && m.Input+m.Output > 0 { + s.Unpriced++ } } - return out + sort.Slice(s.Models, func(i, j int) bool { + a, b := s.Models[i], s.Models[j] + if a.Input+a.Output != b.Input+b.Output { + return a.Input+a.Output > b.Input+b.Output + } + return a.Model < b.Model + }) } func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySession, bool) { @@ -72,7 +166,7 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySe if nativeKeys[agent+"|"+id] { return GatewaySession{}, false } - entry := gatewayProjection(time.Time{}) + entry := gatewayProjection() i, ok := entry.byID[agent+"|"+id] if !ok { return GatewaySession{}, false @@ -83,42 +177,37 @@ func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySe type gatewayProjectionEntry struct { version uint64 meta string - since time.Time + zone *time.Location // the zone its days are dates in sessions []GatewaySession byID map[string]int } +// gatewayCache keeps one projection, of all time, not one copy for every +// native exclusion set or range: a range of days is read out of it. With +// ~600k calls each range kept was another ~37 MB, four of them at once +// (#2776). The log snapshot version also detects rewrites and changes of +// config directory. var gatewayCache struct { sync.Mutex - entries []gatewayProjectionEntry + entry *gatewayProjectionEntry } -// Retain a few window projections, not one copy for every native exclusion set. -// The log snapshot version also detects rewrites and changes of config directory. -func gatewayProjection(since time.Time) gatewayProjectionEntry { +func gatewayProjection() gatewayProjectionEntry { snapshot := readLogSnapshot() meta := usagePriceCacheKey(time.Now()) gatewayCache.Lock() defer gatewayCache.Unlock() - for _, e := range gatewayCache.entries { - if e.version == snapshot.version && e.meta == meta && e.since.Equal(since) { - return e - } + if e := gatewayCache.entry; e != nil && e.version == snapshot.version && e.meta == meta && e.zone == time.Local { + return *e } - ss, _ := buildGatewaySessions(snapshot, since, nil) - e := gatewayProjectionEntry{version: snapshot.version, meta: meta, since: since, sessions: ss, byID: make(map[string]int, len(ss))} + ss, _ := buildGatewaySessions(snapshot, time.Time{}, nil) + e := gatewayProjectionEntry{version: snapshot.version, meta: meta, zone: time.Local, sessions: ss, byID: make(map[string]int, len(ss))} for i, s := range ss { e.byID[s.Agent+"|"+s.ID] = i } // A failed or partial read must be retried, not published as current. if snapshot.info != nil && snapshot.off == snapshot.info.Size() { - gatewayCache.entries = slices.DeleteFunc(gatewayCache.entries, func(old gatewayProjectionEntry) bool { - return old.version != e.version || old.meta != e.meta || old.since.Equal(since) - }) - if len(gatewayCache.entries) >= 4 { - gatewayCache.entries = gatewayCache.entries[1:] - } - gatewayCache.entries = append(gatewayCache.entries, e) + gatewayCache.entry = &e } return e } @@ -170,7 +259,11 @@ func gatewayDays(ss []GatewaySession) []GatewayDayUsage { return out } +// gatewayBuilds counts the projections built from the log, for tests. +var gatewayBuilds atomic.Int64 + func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage) { + gatewayBuilds.Add(1) priceOf := Pricer() type key struct{ agent, id string } groups := map[key]*GatewaySession{} @@ -199,7 +292,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map if s.Start.IsZero() || r.Time.Before(s.Start) { s.Start = r.Time } - if end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond); end.After(s.Last) { + end := r.Time.Add(time.Duration(max(0, r.Millis)) * time.Millisecond) + if end.After(s.Last) { s.Last = end } p := priceOf(r) @@ -226,6 +320,12 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map d.CacheWrite1h += tokens.CacheWrite1h d.Cost += cost d.Priced = d.Priced && priced + if d.first.IsZero() || r.Time.Before(d.first) { + d.first = r.Time + } + if end.After(d.last) { + d.last = end + } } s.Input += r.Input s.Output += r.Output @@ -251,18 +351,8 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map }) for _, m := range models[k] { s.Models = append(s.Models, *m) - s.Cost += m.Cost - if !m.Priced && m.Input+m.Output > 0 { - s.Unpriced++ - } } - sort.Slice(s.Models, func(i, j int) bool { - a, b := s.Models[i], s.Models[j] - if a.Input+a.Output != b.Input+b.Output { - return a.Input+a.Output > b.Input+b.Output - } - return a.Model < b.Model - }) + finishGatewayModels(s) } out := make([]GatewaySession, 0, len(groups)) for _, s := range groups { diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.go index 5158c5a76..f28dca083 100644 --- a/internal/usage/gateway_sessions_test.go +++ b/internal/usage/gateway_sessions_test.go @@ -2,6 +2,7 @@ package usage import ( "github.com/yetone/magpie/internal/settings" + "math" "os" "path/filepath" "testing" @@ -116,3 +117,70 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) { t.Fatalf("rewrite retained routing: %+v", got) } } + +// A range of whole days is read out of the one all-time projection: no +// second copy is built or kept for it, and what it reads equals a direct +// build from that midnight (#2776). +func TestGatewayWindowsShareOneProjection(t *testing.T) { + resetUsageTest(t) + price := 3.0 + cfg := settings.Load() + cfg.ModelPrices = map[string]settings.ModelPrice{"*/priced": {Input: &price, Output: &price, CacheRead: new(0.0), CacheWrite: new(0.0)}} + if err := settings.Save(cfg); err != nil { + t.Fatal(err) + } + today := time.Now() + day := func(back int) time.Time { + y, m, d := today.AddDate(0, 0, -back).Date() + return time.Date(y, m, d, 0, 0, 0, 0, time.Local) + } + for back := 5; back >= 0; back-- { + at := day(back).Add(10 * time.Hour) + Append(Record{Time: at, Agent: "pi", Session: "long", Provider: "p", Model: "priced", Input: 1000 * (back + 1), Output: 7, Millis: 1500, Status: 200}) + Append(Record{Time: at.Add(time.Minute), Agent: "pi", Session: "long", Provider: "p", Model: "free", Input: 11, Output: 3, CacheRead: 5, Status: 200}) + if back%2 == 0 { + Append(Record{Time: at.Add(2 * time.Minute), Agent: "codex", Session: "even", Provider: "p", Model: "priced", Input: 300, Output: 9, Millis: 250, Status: 200}) + } + } + Append(Record{Time: day(5).Add(time.Hour), Agent: "pi", Session: "old", Provider: "p", Model: "priced", Input: 9, Status: 200}) + + key := func(ss []GatewaySession) map[string]GatewaySession { + m := map[string]GatewaySession{} + for _, s := range ss { + m[s.Agent+"|"+s.ID] = s + } + return m + } + backs := []int{0, 1, 2, 3, 7} + base := gatewayBuilds.Load() + GatewaySessions(time.Time{}, nil) + got := map[int][]GatewaySession{} + for _, back := range backs { + got[back] = GatewaySessions(day(back), nil) + } + if built := gatewayBuilds.Load() - base; built != 1 { + t.Fatalf("built %d projections for one log and %d ranges, want 1 kept and shared by them all", built, len(backs)) + } + for _, back := range backs { + want, _ := buildGatewaySessions(readLogSnapshot(), day(back), nil) + g, w := key(got[back]), key(want) + if len(g) != len(w) { + t.Fatalf("from %d days back: %d sessions, want %d: %+v", back, len(g), len(w), got[back]) + } + for k, ws := range w { + gs, ok := g[k] + if !ok { + t.Fatalf("from %d days back: %s missing", back, k) + } + if !gs.Start.Equal(ws.Start) || !gs.Last.Equal(ws.Last) || gs.Tokens != ws.Tokens || gs.Unpriced != ws.Unpriced || math.Abs(gs.Cost-ws.Cost) > 1e-9 || len(gs.Models) != len(ws.Models) || len(gs.Daily) != len(ws.Daily) { + t.Fatalf("from %d days back, %s:\n got %+v\nwant %+v", back, k, gs, ws) + } + for i := range ws.Models { + a, b := gs.Models[i], ws.Models[i] + if a.Model != b.Model || a.Tokens != b.Tokens || a.Priced != b.Priced || math.Abs(a.Cost-b.Cost) > 1e-9 { + t.Fatalf("from %d days back, %s model %d: got %+v want %+v", back, k, i, a, b) + } + } + } + } +} diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.go index 0e03230de..4d50fe3e4 100644 --- a/internal/usage/kept_strings_test.go +++ b/internal/usage/kept_strings_test.go @@ -63,7 +63,7 @@ func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) { logIndex.Unlock() withCaches := held() gatewayCache.Lock() - gatewayCache.entries = nil + gatewayCache.entry = nil gatewayCache.Unlock() viasCache.Lock() viasCache.value = nil From f76201a84a0d3cc7473d24cdde8353f188f7a605 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:40:44 +0800 Subject: [PATCH 39/92] plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里". Grok's plugin signs in through `grok login --device-auth`, and Grok Build (1.0.50, the webbrowser crate) opens the device page itself, through NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER; the macOS binary has no "BROWSER" string. magpie then opened the same URL from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a browser tab) or `magpie plugin login`. Reproduced in a sandbox HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not involved, with and without SSH_CONNECTION. Built-in grok is retired (2927a161e), so the plugin's path is the only one. - The plugin's authorize result can say `opened: true` (not OpenCode's). host.js passes it on as Authorization.Opened, then SignInState.Opened, and the desktop handler, the CLI and app.js (both open points) open nothing then; the link is still shown. - opencode-grok-auth 0.1.17 (magpie-community/plugins 47fbf63, on npm per `npm view --prefer-online`) says opened on darwin/win32, and elsewhere gives grok BROWSER=true, a no-op, so magpie stays the one opener there. The grok mover min is raised to 0.1.17. - No other plugin's CLI opens a page: devin, cursor, kiro and qoder run status/refresh commands only. - docs/subsystems/provider-plugins.md says so. Tests: - TestPluginSignInPageOpensOnce: the fake plugin signs in through /api/plugin-signin. "cli-opened" opens 0 pages; otherwise 1. Red with the old gui/plugins.go ("opened 1 more times"). - plugin-signin-opened.test.cjs: in a browser tab, right away and after an install, 5 languages, Chromium and WebKit. Every "opened" case is red on HEAD's app.js (23 fail); 42/42 with the change. Run at the change (base origin/main 2ceff7370): - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: clean. - go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package ok except two. - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed as #2901. - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners, TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and TestCoveredWindowStaysUp, killed at their deadlines. All pass alone with TestPluginSignInPageOpensOnce; filed as #2645/#1936. - GUI, both engines, at most 2 workers: plugin-signin-opened, plugin-signin, plugin-signin-no-url, plugin-moved-signin, signin-paste-plugin, signin-browser-down, signin-link, plugin-password-prompt and plugin-replaced. The run went 126 pass, 10 fail, all launch or 5s timeouts at load ~380. Alone, plugin-signin-opened passes in both engines and password-prompt passes. signin-browser-down was red in one case per run, a different one each time. plugin-moved-signin (Chromium) is red alone at HEAD's app.js too. Both are filed as #2900. - plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its publish run is red only for middleware-think-tags's npm trust (plugins#180); grok 0.1.17 was published. --- docs/subsystems/provider-plugins.md | 2 + internal/cli/plugins_cli.go | 4 +- internal/gui/assets/app.js | 5 +- internal/gui/plugin_signin_open_test.go | 75 ++++++++++++++++ internal/gui/plugins.go | 2 +- .../gui/tests/plugin-signin-opened.test.cjs | 89 +++++++++++++++++++ internal/plugin/host.js | 5 +- internal/plugin/providers.go | 3 + internal/plugin/testdata/fake/index.js | 3 + internal/provider/migrate_side.go | 2 +- internal/provider/pluginsignin.go | 2 +- internal/provider/signin.go | 3 + 12 files changed, 188 insertions(+), 7 deletions(-) create mode 100644 internal/gui/plugin_signin_open_test.go create mode 100644 internal/gui/tests/plugin-signin-opened.test.cjs diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index f18f675f2..b6cfbf4ae 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -178,6 +178,8 @@ What a plugin writes with `console.log`, `console.warn` and the rest goes to the A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`). +A plugin sign-in's page is opened once. An `authorize` result may say `opened: true` (not OpenCode's field): the plugin's own CLI opened the page already. Grok's `grok login --device-auth` does this on macOS and Windows, where nothing turns it off, and magpie's opening it too showed two pages (andyfmyth on X; plugin 0.1.17, which on other systems gives grok a `BROWSER` that opens nothing instead). `host.js` passes it on as `Authorization.Opened`, then `SignInState.Opened`, and the desktop's `/api/plugin-signin`, `magpie plugin login` and the window in a browser tab (`startPluginSignIn`, and `followSignIn` after an install) then open nothing; the page's link is still shown (`TestPluginSignInPageOpensOnce`, `plugin-signin-opened.test.cjs`). + The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects. ## Verification diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index 64e40dfdb..af0cc8e1e 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -480,7 +480,9 @@ func pluginLogin(ctx context.Context, name, method string) error { if a.URL != "" { fmt.Println("Sign in in your browser. If it didn't open, go to:") fmt.Println(faint.Render(a.URL)) - openInBrowser(a.URL) + if !a.Opened { + openInBrowser(a.URL) + } } if a.Instructions != "" { fmt.Println(a.Instructions) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2c1386a12..68c997e1b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11842,7 +11842,7 @@ async function followSignIn(id) { if (signing?.id !== id) continue; if (st.state === "waiting" || st.state === "installing") { // the CLI it needed is in: now the vendor's page can open - if (signing.state === "installing" && st.state === "waiting" && st.url) { + if (signing.state === "installing" && st.state === "waiting" && st.url && !st.opened) { api("open", { url: st.url }).catch((e) => { if (signing?.id === id) { signing = { ...signing, openError: e.message }; renderProviders(); } }); @@ -11927,7 +11927,8 @@ async function startPluginSignIn(sub, method, inputs = {}, o = {}) { if (o.user) body.user = o.user; if (o.proxy != null) body.proxy = o.proxy; signing = { ...(await api("plugin-signin", body)), ...keep }; - if (web && signing.url) api("open", { url: signing.url }); + // opened: the plugin's own CLI opened the page already (Grok Build's) + if (web && signing.url && !signing.opened) api("open", { url: signing.url }); renderProviders(); followSignIn(signing.id); } catch (e) { diff --git a/internal/gui/plugin_signin_open_test.go b/internal/gui/plugin_signin_open_test.go new file mode 100644 index 000000000..5ae685e45 --- /dev/null +++ b/internal/gui/plugin_signin_open_test.go @@ -0,0 +1,75 @@ +package gui + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "sync" + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// openCounter is a desktop that counts the pages it was asked to open. +type openCounter struct { + webHost + mu sync.Mutex + opened []string +} + +func (w *openCounter) OpenURL(u string) error { + w.mu.Lock() + defer w.mu.Unlock() + w.opened = append(w.opened, u) + return nil +} + +// A plugin's sign-in page opens once. Grok Build's `grok login` opens its +// page in the browser itself on macOS and Windows, and magpie opened it +// again: two pages every time (andyfmyth on X). A plugin that says the page +// is open already gets none opened by magpie; one that doesn't gets one. +func TestPluginSignInPageOpensOnce(t *testing.T) { + bun := testenv.Bun(t) + dir := t.TempDir() + testenv.SetHome(t, dir) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache")) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("MAGPIE_PLUGIN_MARKET", "off") + t.Cleanup(plugin.Settle) + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(t.Context(), abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(t.Context()); err != nil { + t.Fatal(err) + } + start := func(team string) (int, provider.SignInState) { + t.Helper() + w := &openCounter{} + body, _ := json.Marshal(map[string]any{"provider": "fakeco", "method": 1, "inputs": map[string]string{"where": "work", "team": team}}) + rec := httptest.NewRecorder() + Handler(w, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/plugin-signin", bytes.NewReader(body))) + if rec.Code != http.StatusOK { + t.Fatalf("sign-in: %d %s", rec.Code, rec.Body) + } + var st provider.SignInState + if err := json.Unmarshal(rec.Body.Bytes(), &st); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { provider.CancelSignIn(st.ID) }) + w.mu.Lock() + defer w.mu.Unlock() + return len(w.opened), st + } + if n, st := start("cli-opened"); n != 0 || !st.Opened || st.URL == "" { + t.Fatalf("a page the plugin's CLI opened was opened %d more times: %+v", n, st) + } + if n, st := start("blue"); n != 1 || st.Opened { + t.Fatalf("a page nothing opened was opened %d times: %+v", n, st) + } +} diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index e4f0baaea..e10c18db6 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -717,7 +717,7 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { return } var failed string - if w != nil { + if w != nil && !st.Opened { failed = openError(w, st.URL) } writeJSON(rw, signInOpened{st, failed}) diff --git a/internal/gui/tests/plugin-signin-opened.test.cjs b/internal/gui/tests/plugin-signin-opened.test.cjs new file mode 100644 index 000000000..f11227c12 --- /dev/null +++ b/internal/gui/tests/plugin-signin-opened.test.cjs @@ -0,0 +1,89 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin's sign-in page opens once. Grok Build's `grok login` opens its +// page in the browser itself on macOS and Windows, and the window opened it +// again: two pages every time (andyfmyth on X). A sign-in that says its page +// is open already (opened) has the window ask for no /api/open, right away +// or once the CLI it needed is installed; one that doesn't still gets one. +// In every language, Chromium and WebKit; 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 assets = path.resolve(__dirname, "../assets"); + +// a plugin of its own name: the built-in Grok tile sits beside one named Grok +const plugin = { id: "fakeco", pid: "fakeco", name: "FakeCo", icon: "generic", spec: "opencode-fakeco-auth", signedIn: false, models: 3, + methods: [{ type: "oauth", label: "Sign in with Grok Build" }, { type: "api", label: "API key" }] }; + +const URL_ = "https://accounts.x.ai/oauth2/device?user_code=AB12-CD34"; + +// first is what /api/plugin-signin answers, then is what /api/signin/p1 does +function server(lang, first, then, opens) { + const payload = () => ({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [plugin] }); + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(payload()); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugin-signin/prompt") return json({ prompt: null, inputs: {} }); + if (url.pathname === "/api/plugin-signin") return json(first); + if (url.pathname === "/api/signin/p1") { then.asked = (then.asked || 0) + 1; return json(then); } + if (url.pathname === "/api/open") { opens.push(JSON.parse(route.request().postData() || "{}").url); return route.fulfill({ status: 204, body: "" }); } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const waiting = (opened) => ({ id: "p1", agent: "fakeco", state: "waiting", url: URL_, instructions: "Approve the sign-in on the page; Grok Build finishes it.", ...(opened ? { opened: true } : {}) }); +const installing = { id: "p1", agent: "fakeco", state: "installing", installing: "Grok Build" }; +const cases = [ + { name: "opened by its CLI", first: waiting(true), then: waiting(true), want: 0 }, + { name: "not opened", first: waiting(false), then: waiting(false), want: 1 }, + { name: "opened by its CLI after the install", first: installing, then: waiting(true), want: 0 }, + { name: "not opened, after the install", first: installing, then: waiting(false), want: 1 }, +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a plugin sign-in's page opens once", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const c of cases) { + await t.test(`${lang} ${c.name}`, async () => { + const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(15000); // a busy machine takes seconds over a click + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const opens = []; + const then = { ...c.then }; + await page.route("**/*", server(lang, c.first, then, opens)); + // in a browser tab the window opens a page itself + await page.exposeFunction("__opened", (u) => opens.push(u)); + await page.addInitScript(() => { window.open = (u) => { window.__opened(String(u)); return null; }; }); + await page.goto("http://magpie.test/?view=providers"); + await page.locator("#addProvider").click(); + const sheet = page.locator("#addSheet"); + await sheet.locator('.tile[data-pick="FakeCo"]').click(); + const box = sheet.locator(".signing"); + await box.locator("button", { hasText: "Sign in with Grok Build" }).press("Enter"); + // the window shows the page's words, then follows the sign-in two + // more times: past where it would have opened the page + await box.locator(".s", { hasText: "Grok Build finishes it" }).waitFor(); + const asked = then.asked || 0; + await new Promise((r) => { const tick = () => (then.asked || 0) >= asked + 2 ? r() : setTimeout(tick, 50); tick(); }); + assert.deepEqual(opens, c.want ? [URL_] : [], "pages opened"); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + } + }); +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 6badab79a..36376492b 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2061,7 +2061,10 @@ async function authorize({ provider, method, inputs, account, proxy }) { const a = await via.run(proxy ?? "", () => inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined))) const session = String(nextSession++) sessions.set(session, { provider, key, a, inputs, proxy: proxy ?? "" }) - return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method } + // opened (not OpenCode's) is a page the plugin's own CLI opened already: + // Grok Build's `grok login` opens it on macOS and Windows, and magpie's + // opening it too showed it twice (andyfmyth on X) + return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method, opened: a.opened === true } } // failed is a sign-in's failure, with why, where the plugin tells it diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 56b603a91..72bfe1f83 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -810,6 +810,9 @@ type Authorization struct { URL string `json:"url"` Instructions string `json:"instructions"` Method string `json:"method"` + // Opened is a page the plugin (its vendor's CLI) opened already, not + // to be opened again + Opened bool `json:"opened"` } // NewAccount is the account a sign-in goes to when it is a new one: the diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 7a40501e8..60ee44f81 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -132,6 +132,9 @@ export const FakePlugin = async ({ client }) => ({ url: "https://fake.invalid/auth?where=" + inputs.where, instructions: "Paste the code", method: "code", + // team "cli-opened": the page is open already, as Grok Build's + // `grok login` opens its own on macOS and Windows + opened: inputs.team === "cli-opened", callback: async (code) => (process.env.FAKE_SIGNIN && (await fetch(process.env.FAKE_SIGNIN + "/token").catch(() => {})), code === "good") ? { type: "success", refresh: "r-" + (inputs.team ?? "none"), access: "stale", expires: 0, ...fakeWho(inputs.team) } diff --git a/internal/provider/migrate_side.go b/internal/provider/migrate_side.go index e0f3d61d1..b79353b07 100644 --- a/internal/provider/migrate_side.go +++ b/internal/provider/migrate_side.go @@ -97,7 +97,7 @@ func init() { // names, as the built-in does: the homes stay where they are. movers["grok"] = &mover{ pkg: "@magpie-community/opencode-grok-auth", - min: "0.1.16", // a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked + min: "0.1.17", // the sign-in page opens once, where Grok Build opened it and magpie again (andyfmyth on X); a Go key the Provider API refuses is taken as Go's and asked at /alpha/generate (#969); a failure's status and its sign-in mark as the built-in's; grok-4.7's reasoning levels; a token Grok refuses early reads as expired; the sign-in renewed ahead of time through auth.refresh; a 429 shows a spent Rate limit window until it lifts; a login with no link says why; a tool whose parameters are a root union goes as a plain object (#1271); a plain Codex agent_message (a subagent's task or reply) goes as the user's message, not refused with 422 "unknown item type", a sealed one as it came (plugins#61); a model Grok lists at two windows is offered at each, grok-4.7@500k sent with x-grok-context-window (plugins#83); a window offered without a k (grok-4.7@131072) goes as that window, not as a model named so (#1679); a sign-in without Grok Build names GROK_BIN_DIR (#2223); a sign-in with no email (an X account) is kept by its xAI user id, GROK_AUTH_PATH no longer takes it elsewhere, and a login that leaves none says where it looked agents: []string{"grok"}, out: func() ([]Moving, error) { var out []Moving diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index 4025af0ba..cdfa75300 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -132,7 +132,7 @@ func (s *signInFlow) pluginBegin(id string, method int, inputs map[string]string return nil } s.st.State, s.st.Installing = "waiting", "" - s.st.URL, s.st.Instructions, s.st.Code = a.URL, a.Instructions, codeIn(a.Instructions) + s.st.URL, s.st.Instructions, s.st.Code, s.st.Opened = a.URL, a.Instructions, codeIn(a.Instructions), a.Opened s.stop = stop if a.Method == "code" { s.st.PasteCode, s.plugin = true, a.Session diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 4e73232c0..ac5a3292b 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -75,6 +75,9 @@ type SignInState struct { PasteKey bool `json:"pasteKey,omitempty"` KeysURL string `json:"keysURL,omitempty"` Instructions string `json:"instructions,omitempty"` // a plugin's words for its page + // Opened is a page the plugin's own CLI opened already (Grok Build's + // `grok login`), shown but not opened a second time + Opened bool `json:"opened,omitempty"` // Installing is the CLI being installed before the sign-in can start Installing string `json:"installing,omitempty"` User string `json:"user,omitempty"` // the account, once done From c483feadfd88a5b8de8541de0567f3856822bde5 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 13:33:47 +0800 Subject: [PATCH 40/92] usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示". Cause, two parts: - An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source, so KeyBalances skipped it without a word and the Usage page drew no card. OpenCode has no balance a key can read. In sst/opencode, packages/console/app/src/lib/inference-proxy.ts serves only the model routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and /zen/v1/billing all 404, and billing.mdx shows the credits only in the console (Overview -> Credits, to owners and admins). No endpoint was invented. - planQuotaSourceOf matched only /zen/go. models.dev now gives Go as opencode.ai/inference/go/openai/v1, so a Go provider saved there got no plan card at all. openCodeGateway() now tells go/zen/other (custom is the user's own) for both URL shapes, and Go at either one reads https://opencode.ai/zen/go/v1/usage. What changed: - A Zen key's card now carries errOpenCodeNoBalance and seeAt (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits", with an "Open the console ↗" button. That is one button with the needsAccessKey "Open settings" one (#1821), so the bytes stay small. - A provider with its own BalanceURL is still asked that URL. - Strings are in zh, zh-TW, ja and de. - coreScriptBudget: rebased onto f76201a84, whose 1,469,000 already holds the card (~390 bytes; the tray panel draws it too); unchanged. TestCoreScriptBudget re-run after the rebase: ok. - Plugins: there is no OpenCode built-in mover, and this is a key provider, so the change is all in magpie. Run, all on this tree (HEAD 94919109c): - Old code: TestOpenCodeZenSaysItTellsNoBalance (adapted), TestPlanQuotaSource, TestPlanQuotas and opencode-zen-balance.test.cjs all fail on a detached HEAD checkout; they pass here. - Real use, in a sandbox (go build -tags dev, sandbox HOME, ports 3486/3487, never the live config), with the owner's OpenCode key copied read-only: - /api/usage/quotas gives the Zen variant the new error and seeAt. - Both Go providers (/zen/go and /inference/go) request the usage URL and show the vendor's real 401 "This API key has expired". The owner's key is expired, so no live Go reading was seen. There's no Zen account with credit either, so the console page itself wasn't checked against a balance. - A Playwright screenshot shows the card. Clicking the button posted /api/open with the console URL. - go test -p 4 ./... -timeout 45m: every package ok except these. - internal/agent timed out at 45m under load; alone it is ok in 1184s (#2723, #2544). - gateway TestClaudeAccountsSpentFallBackToCodex and TestMaxRPMWaitsForRoomInTheMinute pass alone -count=3 (#2858/#2859, #1791). - gui TestCoreScriptBudget was mine; fixed above. - gofmt -l clean. go vet: darwin all; GOOS=windows provider and gui; GOOS=linux provider (gui needs cgo/wails for linux). - GUI, chromium + webkit, en/zh/zh-TW/ja/de at 900 and 420px, 2 workers. The full suite was stopped at ~416 tests (load 160-500). Its reds were in agent-*/account-* files, which this doesn't touch (#1544, #1949). - The targeted set passed: quota-*, balance-*, key-balance-card, opencode-*, usage-access-key-card, gui-de/ja/zh-tw, i18n-keys, panel-usage, panel-balance-order, panel-quota-refresh, tray-usages, usage-quota-head, glm/plugin-quota-error, gateway-key-quotas, usage-remote-cards, usage-card-refresh and deprecated-subscriptions. - Exceptions: gateway-key-quotas (ja launch timeout) and panel-usage (zh) were red under load and pass alone. - quota-name-translated and quota-count-wrap (webkit) are red alone here and on origin/main f76201a84, with the same asserts. That is #2228, commented. --- internal/gui/assets/app.js | 13 ++- internal/gui/assets/i18n.js | 8 ++ internal/gui/core_budget_test.go | 2 +- .../gui/tests/opencode-zen-balance.test.cjs | 101 ++++++++++++++++ internal/provider/balance.go | 44 ++++++- internal/provider/opencode_balance_test.go | 109 ++++++++++++++++++ internal/provider/opencode_endpoints.go | 26 +++++ internal/provider/planquota.go | 10 +- internal/provider/planquota_test.go | 21 +++- internal/provider/subscription_usage.go | 4 + 10 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 internal/gui/tests/opencode-zen-balance.test.cjs create mode 100644 internal/provider/opencode_balance_test.go diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 68c997e1b..3f5a534cc 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -13121,6 +13121,8 @@ function balanceError(err) { if (/takes the API key, not the access token/.test(err)) return t("The Balance URL …/api/usage/token takes the API key, not the access token — set it to …/api/user/self in the provider's settings"); if (/takes the API key, not the login token/.test(err)) return t("The Balance URL …/v1/usage takes the API key, not the login token — set it to …/api/v1/user/profile in the provider's settings"); if (/New-Api-User/i.test(err)) return t("Add the header New-Api-User = your user ID (shown in the site's personal settings) to the provider's Headers"); + // errOpenCodeNoBalance: not a reading that failed + if (/^OpenCode tells no API key its balance/.test(err)) return t("OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits"); return ""; } @@ -17794,12 +17796,13 @@ function quotaWindows(sub) { e.title = sub.error; // read again from here too: a failed reading is the one most wanted e.prepend(quotaRefresh(sub)); - // a plan that needs the access key the provider hasn't: the way to - // give it, one click away (#1821) - if (sub.needsAccessKey && sub.provider) { - const go = el("button", "quota-fix", t("Open settings")); + // one click away: the access key a plan needs (#1821), or the + // vendor's page for a balance it tells no key (seeAt, Zen's console) + const key = sub.needsAccessKey && sub.provider; + if (key || sub.seeAt) { + const go = el("button", "quota-fix", t(key ? "Open settings" : "Open the console ↗")); go.type = "button"; - go.onclick = (ev) => { ev.stopPropagation(); openProvider(sub.provider); }; + go.onclick = (ev) => { ev.stopPropagation(); key ? openProvider(sub.provider) : api("open", { url: sub.seeAt }).catch(() => {}); }; e.append(" ", go); } return e; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7d11c7fee..aae6e937a 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2721,6 +2721,8 @@ const I18N = { "MCP · Month": "MCP · 本月", "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "这个 Key 没有 OpenCode Go — 请用订阅者本人在该工作区创建的 Key", "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不认这个 Key — 请在提供商设置里换一个有效的 Key", + "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不会把余额告诉 API Key — 请在 OpenCode 控制台的 Overview → Credits 查看 Zen 的余额", + "Open the console ↗": "打开控制台 ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不认这个 Key — 它已过期、被删除或填错了;请在提供商设置里换一个有效的 Key", "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 返回的格式 magpie 读不懂 — 悬停查看它返回了什么", "7 days · Opus": "7 天 · Opus", @@ -6422,6 +6424,8 @@ const I18N = { "MCP · Month": "MCP · 本月", "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "這個 Key 沒有 OpenCode Go — 請用訂閱者本人在該工作區建立的 Key", "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不認這個 Key — 請在供應商設定裡換一個有效的 Key", + "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode 不會把餘額告訴 API Key — 請在 OpenCode 主控台的 Overview → Credits 查看 Zen 的餘額", + "Open the console ↗": "開啟主控台 ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不認這個 Key — 它已過期、被刪除或填錯了;請在供應商設定裡換一個有效的 Key", "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 回傳的格式 magpie 讀不懂 — 懸停查看它回傳了什麼", "7 days · Opus": "7 天 · Opus", @@ -10128,6 +10132,8 @@ const I18N = { "MCP · Month": "MCP · 月", "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "このキーには OpenCode Go がありません — 契約したメンバー本人がそのワークスペースで作ったキーを使ってください", "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode がこのキーを受け付けませんでした — プロバイダ設定で有効なキーを貼り付けてください", + "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode は API キーに残高を教えません — Zen のクレジットは OpenCode コンソールの Overview → Credits で確認してください", + "Open the console ↗": "コンソールを開く ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} がこのキーを受け付けませんでした — 期限切れ、削除済み、または入力ミスです。プロバイダ設定で有効なキーを貼り付けてください", "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go の応答は magpie が読めない形式です — ホバーで内容を表示", "7 days · Opus": "7 日 · Opus", @@ -13844,6 +13850,8 @@ const I18N = { "MCP · Month": "MCP · Monat", "No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "Kein OpenCode Go auf diesem Schlüssel — nimm einen Schlüssel, den das abonnierende Mitglied in diesem Workspace erstellt hat", "OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode hat diesen Schlüssel nicht angenommen — füge in den Anbieter-Einstellungen einen gültigen ein", + "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits": "OpenCode nennt einem API-Schlüssel sein Guthaben nicht — sieh Zens Guthaben in der OpenCode-Konsole unter Overview → Credits", + "Open the console ↗": "Konsole öffnen ↗", "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} hat diesen Schlüssel nicht angenommen — er ist abgelaufen, gelöscht oder vertippt; füge in den Anbieter-Einstellungen einen gültigen ein", "OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go hat in einer Form geantwortet, die magpie nicht liest — für den Inhalt darüberfahren", "7 days · Opus": "7 Tage · Opus", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index c5f936f92..26823042d 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_269_000 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397) - coreScriptBudget = 1_469_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5% + coreScriptBudget = 1_469_000 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/opencode-zen-balance.test.cjs b/internal/gui/tests/opencode-zen-balance.test.cjs new file mode 100644 index 000000000..4b7dfbba1 --- /dev/null +++ b/internal/gui/tests/opencode-zen-balance.test.cjs @@ -0,0 +1,101 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ttmrmx on X: OpenCode Zen's balance card wasn't shown at all. OpenCode +// tells no API key its balance (Zen's credits are on the console only), +// so the card now says that, in the user's language, with the reason in +// its tooltip and a button that opens the console (seeAt). The editor's +// "Check balance" says the same (balanceError). 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 assets = path.resolve(__dirname, "../assets"); +// errOpenCodeNoBalance's words (internal/provider/balance.go) +const ZEN = "OpenCode tells no API key its balance: Zen's pay-as-you-go credits are shown only in the OpenCode console (https://opencode.ai/console, Overview → Credits, to the workspace's owners and admins)"; +const CONSOLE = "https://opencode.ai/console"; + +const quotas = [ + { provider: "opencode-zen", name: "OpenCode Zen", icon: "opencode", error: ZEN, seeAt: CONSOLE, windows: [] }, + { provider: "kimi", name: "Kimi", icon: "kimi-color", error: "HTTP 503", windows: [] }, +]; + +function serve(lang, opened) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" }; + return async (route) => { + const req = route.request(); + const url = new URL(req.url()); + const json = (body) => route.fulfill({ json: body }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/usage/quotas/history") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/open") { + opened.push(JSON.parse(req.postData() || "{}").url); + return route.fulfill({ status: 204, body: "" }); + } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const said = "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits"; +const button = "Open the console ↗"; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: an OpenCode Zen key's card says OpenCode tells no balance and opens the console`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const errors = []; + const opened = []; + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => { + window.__opened = []; + window.open = (url) => { window.__opened.push(url); return null; }; + }); + await page.route("**/*", serve(lang, opened)); + // app.js is large: its first load on a busy machine takes more than 5s + await page.goto("http://magpie.test/?view=usage", { timeout: 30000 }); + + const err = page.locator(".subscription-card", { hasText: "OpenCode Zen" }).locator(".subscription-error"); + await err.waitFor(); + assert.equal(await err.getAttribute("title"), ZEN, "the reason in the tooltip"); + const [words, open, generic] = await page.evaluate(([a, b]) => [t(a), t(b), t("Allowance unavailable")], [said, button]); + if (lang !== "en") { + assert.notEqual(words, said, `${lang} has its own words for the card`); + assert.notEqual(open, button, `${lang} has its own words for the button`); + } + assert.ok((await err.textContent()).includes(words), await err.textContent()); + assert.ok(!(await err.textContent()).includes(generic)); + const go = err.locator(".quota-fix"); + assert.equal((await go.textContent()).trim(), open); + // a card that failed for another reason has no such button + assert.equal(await page.locator(".subscription-card", { hasText: "Kimi" }).locator(".quota-fix").count(), 0); + const [e, b] = [await err.boundingBox(), await go.boundingBox()]; + assert.ok(e.x + e.width <= width && b.x + b.width <= width, "the error and its button fit the page"); + + await go.click(); + // in a browser api("open") is window.open (the app posts /api/open) + await page.waitForFunction(() => window.__opened.length > 0); + assert.deepEqual(await page.evaluate(() => window.__opened), [CONSOLE]); + assert.deepEqual(opened, []); + assert.equal(new URL(page.url()).searchParams.get("view"), "usage", "the page stays where it was"); + // the editor's Check balance says the same + assert.equal(await page.evaluate((z) => balanceError(z), ZEN), words); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 98d491551..a55962093 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -1211,6 +1211,10 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ ctx = p.Via(ctx) p = keyQueryOf(p) src, ok := balanceSourceOf(p) + if !ok && p.Account == nil && p.Key != "" && openCodeZen(p) { + // a balance the vendor keeps from the key: said so, not left out + return "", nil, nil, nil, true, errOpenCodeNoBalance + } if !ok || p.Account != nil || p.Key == "" { return "", nil, nil, nil, false, nil } @@ -1309,6 +1313,35 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [ return amount, nil, split, nil, true, err } +// OpenCodeConsole is where OpenCode shows a workspace's credits: the +// Credits card on the console's Overview, to its owners and admins. +const OpenCodeConsole = "https://opencode.ai/console" + +// errOpenCodeNoBalance is a Zen key's balance, which OpenCode tells no +// key: Zen's routes (/zen/v1, the inference API's /inference/v1) have no +// usage or balance query, only Go's /zen/go/v1/usage, which tells Go's +// windows and not the credits (proxyInference's paths in sst/opencode's +// packages/console/app/src/lib/inference-proxy.ts; /zen/v1/usage and +// /inference/v1/usage answer 404), and its docs give the balance only on +// the console's Credits card (console/billing.mdx, "Check your balance"). +// The card used to be left out unsaid (ttmrmx on X). +var errOpenCodeNoBalance = errors.New("OpenCode tells no API key its balance: Zen's pay-as-you-go credits are shown only in the OpenCode console (" + OpenCodeConsole + ", Overview → Credits, to the workspace's owners and admins)") + +// openCodeZen says p is at OpenCode Zen, whose credits OpenCode keeps from +// the key, and not at Go, whose windows are its card (planQuotaSourceOf). +func openCodeZen(p Provider) bool { + zen := false + for _, b := range []string{p.Chat, p.Responses, p.Anthropic} { + switch openCodeGateway(b) { + case "go": + return false + case "zen": + zen = true + } + } + return zen +} + // balanceMethodOf is the HTTP method a Balance URL is asked with: GET // when none is named, else GET or POST in any case. Another is an error, // never a GET in its place. @@ -1409,11 +1442,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { continue } src, ok := balanceSourceOf(p) - if !ok && !clineKeyCard(p) { + zen := !ok && openCodeZen(p) + if !ok && !clineKeyCard(p) && !zen { continue } others := 0 - if src.token != "" { + if src.token != "" || zen { // the account's balance is the same whichever key asks jobs = append(jobs, job{p, ""}) continue @@ -1473,6 +1507,12 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { if errors.Is(err, errNoBalance) { return // a reply with no balance for this key: no card } + if errors.Is(err, errOpenCodeNoBalance) { + // nothing to read or keep: where the balance is shown + q.Error, q.SeeAt = err.Error(), OpenCodeConsole + out[i] = q + return + } if err != nil { q.Error = err.Error() } else { diff --git a/internal/provider/opencode_balance_test.go b/internal/provider/opencode_balance_test.go new file mode 100644 index 000000000..4558a9f02 --- /dev/null +++ b/internal/provider/opencode_balance_test.go @@ -0,0 +1,109 @@ +package provider + +import ( + "context" + "errors" + "net/http" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/agentenv" +) + +// noVendor answers no request and keeps what was asked: OpenCode tells +// a Zen key no balance, so there is nothing to ask. +type noVendor struct{ asked *[]string } + +func (n noVendor) RoundTrip(r *http.Request) (*http.Response, error) { + *n.asked = append(*n.asked, r.URL.String()) + return nil, errors.New("no network in this test") +} + +// ttmrmx on X: an OpenCode Zen key's balance card wasn't shown at all. +// OpenCode tells no key the workspace's credits, so the card says that, +// and where they are shown, on every surface that asks a key's balance: +// the Usage page's cards (KeyBalances) and the editor, TUI and CLI +// (Balance). One card a provider, however many keys: the credits are the +// workspace's. +func TestOpenCodeZenSaysItTellsNoBalance(t *testing.T) { + isolate(t) + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("PATH", h) + for _, v := range agentenv.Vars { + t.Setenv(v, "") + } + keyBalanceCache.data = nil + t.Cleanup(func() { keyBalanceCache.data = nil }) + old := http.DefaultClient.Transport + var asked []string + http.DefaultClient.Transport = noVendor{&asked} + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + zen := Provider{ID: "opencode-zen", Name: "OpenCode Zen", Chat: "https://opencode.ai/zen/v1", Responses: "https://opencode.ai/zen/v1", + Anthropic: "https://opencode.ai/zen", Key: "zen-a", Keys: []KeyAccount{{Key: "zen-a"}, {Key: "zen-b", Name: "spare"}}} + for _, p := range []Provider{ + zen, + // Zen at the inference API, models.dev's URL for it + {ID: "zen-inference", Name: "Zen", Chat: "https://opencode.ai/inference/openai/v1", Key: "zen-c"}, + // OpenCode Go: its plan windows are its card, not a balance + {ID: "opencode-go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // a provider of the user's own at the inference API: its vendor's + {ID: "custom", Name: "Custom", Chat: "https://opencode.ai/inference/custom/acme/v1", Key: "c"}, + } { + if err := Save(p); err != nil { + t.Fatal(err) + } + } + var lines []string + for _, q := range KeyBalances(context.Background()) { + lines = append(lines, q.Provider+"|"+q.User+"|"+q.Balance+"|"+q.SeeAt) + if !strings.HasPrefix(q.Error, "OpenCode tells no API key its balance") || !strings.Contains(q.Error, "Overview → Credits") { + t.Errorf("%s's card says %q", q.Provider, q.Error) + } + } + want := "opencode-zen|||https://opencode.ai/console,zen-inference|||https://opencode.ai/console" + if got := strings.Join(lines, ","); got != want { + t.Fatalf("cards:\n%s\nwant\n%s", got, want) + } + if len(asked) != 0 { + t.Fatalf("asked %v", asked) + } + amount, ok, err := Balance(context.Background(), zen) + if !ok || amount != "" || !errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("Balance = %q %v %v", amount, ok, err) + } + // a Balance URL of the user's own is still asked + zen.BalanceURL = "https://opencode.ai/somewhere" + if _, ok, err := Balance(context.Background(), zen); !ok || errors.Is(err, errOpenCodeNoBalance) { + t.Fatalf("own Balance URL: %v %v", ok, err) + } + if strings.Join(asked, ",") != "https://opencode.ai/somewhere" { + t.Fatalf("asked %v", asked) + } +} + +func TestOpenCodeGateway(t *testing.T) { + for base, want := range map[string]string{ + "https://opencode.ai/zen/v1": "zen", + "https://opencode.ai/zen": "zen", + "https://opencode.ai/inference/openai/v1": "zen", + "https://opencode.ai/inference/anthropic": "zen", + "https://opencode.ai/zen/go/v1": "go", + "https://opencode.ai/zen/go": "go", + "https://opencode.ai/inference/go/openai/v1": "go", + "https://opencode.ai/inference/go/anthropic": "go", + "https://opencode.ai/inference/custom/x/v1": "", + "https://opencode.ai/console": "", + "https://example.com/zen/go/v1": "", + "": "", + } { + if got := openCodeGateway(base); got != want { + t.Errorf("%q: %q, want %q", base, got, want) + } + } +} diff --git a/internal/provider/opencode_endpoints.go b/internal/provider/opencode_endpoints.go index e39b2d863..f49cbf7d2 100644 --- a/internal/provider/opencode_endpoints.go +++ b/internal/provider/opencode_endpoints.go @@ -29,6 +29,32 @@ func openCodeRoot(base string) (root, catalogID string) { return "", "" } +// openCodeGateway says which of OpenCode's gateways base is at: "go" for +// Go's (…/zen/go, or the inference API's …/inference/go, whatever follows: +// /v1, or /openai/v1 and /anthropic, the URLs models.dev and Go's docs +// give since October 2026), "zen" for Zen's (…/zen, …/inference: the +// workspace's pay-as-you-go credits), "" for any other, a provider of the +// user's own at …/inference/custom among them, which its vendor bills. +func openCodeGateway(base string) string { + u, err := url.Parse(strings.TrimSpace(base)) + if err != nil || !openCodeHost(u.Hostname()) { + return "" + } + seg := strings.Split(strings.Trim(u.Path, "/"), "/") + if seg[0] != "zen" && seg[0] != "inference" { + return "" + } + if len(seg) > 1 { + switch seg[1] { + case "go": + return "go" + case "custom": + return "" + } + } + return "zen" +} + // openCodeGemini is the base of Gemini's generateContent at the gateway // root is: models/{model}:streamGenerateContent is asked under it. Zen's // /zen/v1 relays it to the inference API's Google route, reading the key diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index e0defa263..476e5d6fd 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -37,6 +37,12 @@ type planQuotaSource struct { func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { for _, base := range []string{p.Chat, p.Anthropic, p.Responses} { coding := strings.Contains(base, "/api/coding/") + if openCodeGateway(base) == "go" { + // Go at Zen's gateway or at the inference API, the URL + // models.dev and Go's docs give since October 2026: the same + // key, told its windows at the same usage query + return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true + } switch hostOf(base) { case "open.bigmodel.cn": return planQuotaSource{"https://open.bigmodel.cn/api/monitor/usage/quota/limit", false, readZhipuPlan, coding}, true @@ -55,10 +61,6 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { // a Coding Plan key (sk-cp-…) is told its windows; a // pay-as-you-go key isn't, and gets no card (#387) return planQuotaSource{"https://" + hostOf(base) + "/v1/token_plan/remains", true, readMiniMaxPlan, false}, true - case "opencode.ai": - if u := strings.TrimSuffix(base, "/"); strings.HasSuffix(u, "/zen/go") || strings.Contains(u, "/zen/go/") { - return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true - } case "ollama.com": // Ollama Cloud's included allowance (#1888); a key with none // gets no card diff --git a/internal/provider/planquota_test.go b/internal/provider/planquota_test.go index 858fd102a..2ca41b1e4 100644 --- a/internal/provider/planquota_test.go +++ b/internal/provider/planquota_test.go @@ -27,6 +27,14 @@ func TestPlanQuotaSource(t *testing.T) { {Provider{Chat: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, {Provider{Chat: "https://opencode.ai/zen/v1"}, "", false, false}, // Zen is pay as you go + // Go at the inference API, as models.dev and Go's docs give it + // since October 2026 (ttmrmx on X: no card) + {Provider{Chat: "https://opencode.ai/inference/go/openai/v1"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/go/v1", Anthropic: "https://opencode.ai/inference/go"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Anthropic: "https://opencode.ai/inference/go/anthropic"}, "https://opencode.ai/zen/go/v1/usage", true, true}, + {Provider{Chat: "https://opencode.ai/inference/openai/v1"}, "", false, false}, // Zen's + {Provider{Chat: "https://opencode.ai/inference/custom/acme/v1"}, "", false, false}, // the user's own provider + {Provider{Chat: "https://example.com/zen/go/v1"}, "", false, false}, {Provider{Chat: "https://api.kimi.com/coding/v1", Anthropic: "https://api.kimi.com/coding"}, "https://api.kimi.com/coding/v1/usages", true, true}, {Provider{Anthropic: "https://api.kimi.ai/coding/"}, "https://api.kimi.ai/coding/v1/usages", true, true}, {Provider{Chat: "https://api.commandcode.ai/provider/v1", Anthropic: "https://api.commandcode.ai/provider"}, "https://api.commandcode.ai/alpha/billing/credits", true, false}, @@ -335,6 +343,8 @@ func TestPlanQuotas(t *testing.T) { Keys: []KeyAccount{{Key: "glm-a"}, {Key: "glm-b", Name: "home"}, {Key: "glm-off", Off: true}}}, {ID: "glm-api", Name: "GLM API", Chat: "https://open.bigmodel.cn/api/paas/v4", Key: "glm-payg"}, {ID: "go", Name: "OpenCode Go", Chat: "https://opencode.ai/zen/go/v1", Key: "go-k"}, + // Go at models.dev's URL for it: the same card (ttmrmx on X) + {ID: "go-inference", Name: "OpenCode Go", Chat: "https://opencode.ai/inference/go/openai/v1", Key: "go-k"}, {ID: "zen", Name: "Zen", Chat: "https://opencode.ai/zen/v1", Key: "zen-k"}, {ID: "minimax-cn", Name: "MiniMax (China)", Chat: "https://api.minimaxi.com/v1", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-cp-k"}, {ID: "minimax-payg", Name: "MiniMax API", Anthropic: "https://api.minimaxi.com/anthropic", Key: "sk-api-k"}, @@ -347,7 +357,7 @@ func TestPlanQuotas(t *testing.T) { for _, q := range PlanQuotas(context.Background()) { got[q.Provider+"/"+q.User] = q } - if len(got) != 4 { + if len(got) != 5 { t.Fatalf("cards: %+v", got) } if q := got["minimax-cn/"]; len(q.Windows) != 2 || q.Windows[0].Name != "5 hours" && q.Windows[0].Name != "Allowance" || q.Windows[0].Used != 25 || q.Windows[1].Name != "7 days" || q.Windows[1].Used != 4 { @@ -370,6 +380,9 @@ func TestPlanQuotas(t *testing.T) { if q := got["go/"]; q.Name != "OpenCode Go" || len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" { t.Errorf("go: %+v", q) } + if q := got["go-inference/"]; len(q.Windows) != 1 || q.Windows[0].Name != "5 hours" || q.Error != "" { + t.Errorf("go at the inference API: %+v", q) + } // The custom GLM provider is recognized by its endpoint, not its id // or key labels, and the provenance survives PlanQuotas' cache. reset := time.UnixMilli(4102444800000) @@ -380,7 +393,7 @@ func TestPlanQuotas(t *testing.T) { t.Errorf("%s/%s: hidden=%v", q.Provider, q.User, hidden) } } - if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 2 { + if qs := notShown(PlanQuotas(context.Background()), []SubscriptionQuota{sub}); len(qs) != 3 { t.Fatalf("cached plans after deduplication: %+v", qs) } // A restart loses the in-memory provenance; a failed read restores @@ -393,10 +406,10 @@ func TestPlanQuotas(t *testing.T) { lastQuotas.m, lastQuotas.loaded = nil, false lastQuotas.Unlock() qs := PlanQuotas(context.Background()) - if len(qs) != 4 { + if len(qs) != 5 { t.Fatalf("restored plans: %+v", qs) } - if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 2 { + if kept := notShown(qs, []SubscriptionQuota{sub}); len(kept) != 3 { t.Fatalf("restored plans after deduplication: %+v", kept) } } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 313e0a4f2..af6bbfd0e 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -135,6 +135,10 @@ type SubscriptionQuota struct { // its provider hasn't (accessKeyCard, #1821): the Usage page offers // the provider's settings to give it in. NeedsAccessKey bool `json:"needsAccessKey,omitempty"` + // SeeAt is the vendor's page that shows what its API tells no key: + // OpenCode Zen's credits, on its console (errOpenCodeNoBalance). The + // Usage page offers to open it. + SeeAt string `json:"seeAt,omitempty"` // AsOf is when an allowance shown in place of one that couldn't be // read was read (see keepLast); nil for a reading just made. AsOf *time.Time `json:"asOf,omitempty"` From baef679f2954e80d28a7f170e09c03460a67230e Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:39:12 +0800 Subject: [PATCH 41/92] sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776) d7e02ae08 sized scanAt's buffer by the rest of the file. The other line readers of a session file still took 1 MiB per file read: - readMiniMaxCalls, readAgyCalls and readWorkBuddyCalls (WorkBuddy and CodeBuddy Code), which read a changed file whole; - scanFrames, dsh's packed (.zstd) sessions, read on from a frame; - mayHold, a search's first look at each file. (calls_pi, calls_kimi, calls_dsh and dsh.go no longer hold one since the incremental readers before a77f6ae16.) Each now takes scanBuffer(f, off): the rest of a plain file plus one byte, 16 KiB to 1 MiB. ReadBytes and readFrame read a line or frame longer than the buffer whole, as before; a packed WorkBuddy file (a zstd stream, not an *os.File) keeps 1 MiB. TestReadersOfASmallFileTakeASmallBuffer reads a two-line file 50 times through each of the five and allows 256 KiB per read. With the five readers put back (the test kept): red in all five, 1,049,161 (minimax), 1,049,271 (agy), 1,049,256 (workbuddy), 1,068,296 (frames) and 1,056,984 (search) bytes per read. Not measured on the 600k sandbox: it holds no MiniMax, agy, WorkBuddy or dsh sessions, so the saving there is the test's: ~1 MiB per file each time one of these is read again. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/sessions/calls_agy.go | 2 +- internal/sessions/calls_minimax.go | 2 +- internal/sessions/calls_workbuddy.go | 2 +- internal/sessions/frames.go | 2 +- internal/sessions/scan_buffer_test.go | 51 +++++++++++++++++++++++++++ internal/sessions/search.go | 2 +- internal/sessions/sessions.go | 5 +-- 7 files changed, 59 insertions(+), 7 deletions(-) diff --git a/internal/sessions/calls_agy.go b/internal/sessions/calls_agy.go index f5d21ca80..7cd92a0b2 100644 --- a/internal/sessions/calls_agy.go +++ b/internal/sessions/calls_agy.go @@ -82,7 +82,7 @@ func readAgyCalls(f file) (*callFile, bool) { defer r.Close() st := &callFile{Agent: "agy", Path: f.path, Session: strings.TrimPrefix(f.key, "agy:")} at := map[int]int{} // a step's index → its call in st.Calls - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) for { b, err := br.ReadBytes('\n') if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { diff --git a/internal/sessions/calls_minimax.go b/internal/sessions/calls_minimax.go index 7a7061205..b48383518 100644 --- a/internal/sessions/calls_minimax.go +++ b/internal/sessions/calls_minimax.go @@ -106,7 +106,7 @@ func readMiniMaxCalls(f file) (*callFile, bool) { } defer r.Close() st := &callFile{Agent: "minimax-code", Path: f.path, Session: strings.TrimPrefix(f.key, "minimax-code:")} - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) for { b, err := br.ReadBytes('\n') if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) { diff --git a/internal/sessions/calls_workbuddy.go b/internal/sessions/calls_workbuddy.go index 00de930e8..2301eced4 100644 --- a/internal/sessions/calls_workbuddy.go +++ b/internal/sessions/calls_workbuddy.go @@ -167,7 +167,7 @@ func readWorkBuddyCalls(f file) (*callFile, bool) { defer r.Close() st := &callFile{Agent: f.agent, Path: f.path, Session: strings.TrimPrefix(f.key, f.agent+":")} dir := buddyDir(f.agent) - br := bufio.NewReaderSize(r, 1<<20) + br := bufio.NewReaderSize(r, scanBuffer(r, 0)) last := "" // the messageId the call before this line carried for { b, err := br.ReadBytes('\n') diff --git a/internal/sessions/frames.go b/internal/sessions/frames.go index 520a12674..a661e834e 100644 --- a/internal/sessions/frames.go +++ b/internal/sessions/frames.go @@ -136,7 +136,7 @@ func scanFrames(path string, off, skip int64, fn func([]byte) bool) (next, nextS return } defer dec.Close() - r := bufio.NewReaderSize(f, 1<<20) + r := bufio.NewReaderSize(f, scanBuffer(f, off)) var frame, out, pending []byte at := off first := true diff --git a/internal/sessions/scan_buffer_test.go b/internal/sessions/scan_buffer_test.go index 8844a66f1..a81278fb3 100644 --- a/internal/sessions/scan_buffer_test.go +++ b/internal/sessions/scan_buffer_test.go @@ -1,11 +1,14 @@ package sessions import ( + "context" "os" "path/filepath" "runtime" "strings" "testing" + + "github.com/klauspost/compress/zstd" ) // A scan of a small session file takes a buffer the size of the file, not @@ -61,3 +64,51 @@ func TestScanReadsALineLongerThanItsBuffer(t *testing.T) { t.Fatalf("lines %v, want [%d 2]", got, len(long)) } } + +// Every other reader of a session file sizes its buffer as scanAt does: +// the calls readers of MiniMax Code, agy and WorkBuddy, dsh's packed +// frames and a search's first look each took 1 MiB per file read (#2776). +func TestReadersOfASmallFileTakeASmallBuffer(t *testing.T) { + dir := t.TempDir() + write := func(name, body string) string { + t.Helper() + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return p + } + line := `{"type":"user","n":1}` + "\n" + plain := write("s.jsonl", line+line) + enc, err := zstd.NewWriter(nil) + if err != nil { + t.Fatal(err) + } + framed := write("s.v3.jsonl.zstd", string(enc.EncodeAll([]byte(line+line), nil))) + enc.Close() + for _, c := range []struct { + name string + read func() + }{ + {"minimax", func() { readMiniMaxCalls(file{path: plain, key: "minimax-code:s"}) }}, + {"agy", func() { readAgyCalls(file{path: plain, key: "agy:s"}) }}, + {"workbuddy", func() { readWorkBuddyCalls(file{agent: "workbuddy", path: plain, key: "workbuddy:s"}) }}, + {"frames", func() { scanFrames(framed, 0, 0, func([]byte) bool { return true }) }}, + {"search", func() { mayHold(context.Background(), plain, "absent") }}, + } { + t.Run(c.name, func(t *testing.T) { + const reads = 50 + c.read() // anything a first read sets up once + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range reads { + c.read() + } + runtime.ReadMemStats(&after) + if per := (after.TotalAlloc - before.TotalAlloc) / reads; per > 256<<10 { + t.Fatalf("a read of a two-line file allocated %d bytes", per) + } + }) + } +} diff --git a/internal/sessions/search.go b/internal/sessions/search.go index f09b87dd4..00f8d4250 100644 --- a/internal/sessions/search.go +++ b/internal/sessions/search.go @@ -157,7 +157,7 @@ func mayHold(ctx context.Context, path, needle string) bool { defer f.Close() nb := []byte(needle) keep := len(nb) - 1 - buf := make([]byte, 1<<20+keep) + buf := make([]byte, scanBuffer(f, 0)+keep) have := 0 for { if ctx.Err() != nil { diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 3fd94942b..f689dd23a 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -1413,8 +1413,9 @@ func scanAt(path string, off int64, head func([]byte) bool, fn func(b []byte, st } } -// scanBuffer is the read buffer scanAt needs for what is left of f from off: -// 1 MiB at most, and no more than that rest of a plain file. Every scan +// scanBuffer is the read buffer a reader of f needs for what is left of it +// from off: 1 MiB at most, and no more than that rest of a plain file. +// Every line reader of a session file sizes its buffer by it. Every scan // took 1 MiB, and a start's read of ~4,600 mostly small session files // (each read again from where it was left) allocated ~9 GB of them, which // the GC's heap target followed up (#2776). A line longer than the buffer From 227b864a451c15cd093a3f9a2b372ca370c112b9 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:03:35 +0800 Subject: [PATCH 42/92] usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776) CodexModelEffort built the whole ledger of the period and kept the rows that carry a Codex thread. Every gateway call became a Record (in gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and a priced Row (ledgerMatched), all held at once, though only a gateway call paired with a Codex session file's call by its response id can carry a thread. On the 720k-call sandbox this build was 7.6 GB of the start's 18 GB allocated and most of its peak. codexEffortRows visits the log once and keeps only the gateway calls with a response id, request id or session (native, else magpie's) that one of the session files' calls has, or an agy call when one is agy's. No other gateway call can change gatewayMatchesDetails' answer: the request-id match looks up only the locals' ids, the fallback groups are looked up only by the locals' sessions, and a response id's uniqueness is counted over every call that has it, all of which are kept. Only the paired calls are priced into rows, and the rows are the whole ledger's thread rows in the same order, so the sums (floats included) are the same. TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole ledger's for All, Today and 7d, with Codex's reader and every agent's: a pair by response id, an ambiguous response id, a session-and-tokens match, a call two days old, and unrelated calls around them. With the session test dropped from matchingRecords by hand it is red (all, every agent: the session-matched call shows as a row of its own). TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated gateway calls and allows a visit of the log and a half. With the old build put back (LedgerOf): red, 18,347,128 bytes against a visit's 1,198,680. With the fix: 1,321,824 against 1,321,744. 720k-call sandbox, cold start, the four first asks together, back to back (load 48.7 then 14.7, so the times are not comparable; the memory is what this measures): before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB after: peak RSS 2427 MB, heapSys 2413 MB, live 542 MB manage?agent=codex answered in 41.5 s before, 23.1 s after. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/usage/codex_effort_rows_test.go | 92 ++++++++++++++++++++++++ internal/usage/codex_identity.go | 65 ++++++++++++++++- 2 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 internal/usage/codex_effort_rows_test.go diff --git a/internal/usage/codex_effort_rows_test.go b/internal/usage/codex_effort_rows_test.go new file mode 100644 index 000000000..28db18e1c --- /dev/null +++ b/internal/usage/codex_effort_rows_test.go @@ -0,0 +1,92 @@ +package usage + +import ( + "fmt" + "path/filepath" + "reflect" + "runtime" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// threadRows are the rows of a whole ledger that carry a Codex thread. +func threadRows(l Ledgered) []Row { + return slices.DeleteFunc(slices.Clone(l.Rows), func(r Row) bool { return r.codexActor == "" }) +} + +// CodexModelEffort's rows are the whole ledger's rows that carry a thread, +// row for row, though it keeps only the gateway calls a session file's call +// can be matched to: paired by response id, an ambiguous response id, +// matched by session and tokens, and unrelated calls around them (#2776). +func TestCodexEffortRowsAreTheWholeLedgers(t *testing.T) { + now, _ := effortFixture(t) + root := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30") + at := func(d time.Duration) time.Time { return now.Add(-d) } + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-00-00-main-b.jsonl"), "main-b", "main-b", `"cli"`, "resp-b", "m", "high", at(30*time.Minute), 300, 30) + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-10-00-main-c.jsonl"), "main-c", "main-c", `"cli"`, "resp-c", "m2", "low", at(25*time.Minute), 70, 7) + writeCodexCall(t, filepath.Join(root, "rollout-2026-09-30T09-20-00-main-d.jsonl"), "main-d", "main-d", `"cli"`, "resp-d", "m", "medium", at(20*time.Minute), 50, 5) + writeCodexCall(t, filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "28", "rollout-2026-09-28T09-00-00-old-e.jsonl"), "old-e", "old-e", `"cli"`, "resp-e", "m", "low", now.Add(-50*time.Hour), 11, 1) + // paired by its response id, which the gateway's call alone has + Append(Record{Time: at(30 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Effort: "xhigh", Input: 300, Output: 30, Status: 200, ResponseID: "resp-b", Session: "main-b"}) + // two gateway calls with one response id: neither is paired + Append(Record{Time: at(25 * time.Minute), Agent: "codex", Provider: "openai", Model: "m2", Input: 70, Output: 7, Status: 200, ResponseID: "resp-c"}) + Append(Record{Time: at(25 * time.Minute), Agent: "codex", Provider: "openai", Model: "m2", Input: 70, Output: 7, Status: 200, ResponseID: "resp-c"}) + // matched by session and tokens: the session file's call is the gateway's + Append(Record{Time: at(20 * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 50, Output: 5, Status: 200, NativeSession: "main-d"}) + // paired two days ago + Append(Record{Time: now.Add(-50 * time.Hour), Agent: "codex", Provider: "openai", Model: "m", Input: 11, Output: 1, Status: 200, ResponseID: "resp-e", Session: "old-e"}) + for i := range 40 { + Append(Record{Time: at(time.Duration(i) * time.Minute), Agent: "claude-code", Provider: "anthropic", Model: "claude-opus-5-5", Input: 40 + i, Output: 4, Status: 200, RequestID: fmt.Sprintf("req_%d", i), Session: "sess1"}) + Append(Record{Time: at(time.Duration(i) * time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 9, Output: 9, Status: 200, ResponseID: fmt.Sprintf("resp-other-%d", i), Session: "elsewhere"}) + } + for _, p := range []Period{All, Today, Week} { + for name, reader := range map[string]func(time.Time) []sessions.Call{"codex": codexCalls, "every agent": sessions.Calls} { + whole := threadRows(ledgerOfAt(p, Filter{}, now, reader)) + if p == All && len(whole) < 3 { + t.Fatalf("fixture: the whole ledger has %d thread rows: %+v", len(whole), whole) + } + if got := codexEffortRows(p, now, reader); !reflect.DeepEqual(got, whole) { + t.Fatalf("%s, %s:\n got %+v\nwant %+v", p, name, got, whole) + } + } + } +} + +// A build of CodexModelEffort takes no more for a gateway call no Codex +// session file's call can be matched to than a visit of the log does: it +// made every such call a record, a packed row and a priced row, and over +// ~720k calls that was most of the start's peak (#2776). +func TestCodexModelEffortLetsUnrelatedCallsGo(t *testing.T) { + now, _ := effortFixture(t) + Append(Record{Time: now.Add(-time.Hour), Agent: "codex", Provider: "openai", Model: "m", Input: 20, Output: 3, Status: 200, ResponseID: "resp-1", Session: "main-a"}) + const calls = 3000 + for i := range calls { + Append(Record{Time: now.Add(-time.Duration(i) * time.Second), Agent: "claude-code", Provider: "anthropic", Model: "claude-opus-5-5", Input: 40 + i, Output: 4, Status: 200, RequestID: fmt.Sprintf("req_%d", i), Session: fmt.Sprintf("sess%d", i%50)}) + } + measure := func(fn func()) uint64 { + fn() // anything a first read sets up once + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + fn() + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc + } + // the session files read by a reader of their own: a build each ask + old := LogCalls + LogCalls = codexCalls + t.Cleanup(func() { LogCalls = old }) + if got := CodexModelEffort(All); len(got["main-a"]) != 1 { + t.Fatalf("main-a's consumption: %+v", got) + } + visit := measure(func() { Visit(time.Time{}, func(Record) {}) }) + build := measure(func() { CodexModelEffort(All) }) + t.Logf("a build allocated %d bytes, a visit %d", build, visit) + // the visit itself, the thread's own rows and the sets of its ids + if build > visit+visit/2+256<<10 { + t.Fatalf("a build over %d unrelated calls allocated %d bytes, a visit of the log %d", calls, build, visit) + } +} diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go index a948f80ce..046b9068c 100644 --- a/internal/usage/codex_identity.go +++ b/internal/usage/codex_identity.go @@ -329,7 +329,7 @@ var effortBuilt func() // CodexModelEffort reports each Codex thread's own priced ledger consumption. func CodexModelEffort(p Period) map[string][]sessions.ModelEffort { if LogCalls != nil { // synthetic logs carry no state to key on - return codexModelEffort(LedgerOf(p, Filter{}).Rows) + return codexModelEffort(codexEffortRows(p, Clock(), LogCalls)) } now := Clock() st := readRequestState(now) @@ -378,10 +378,71 @@ func CodexModelEffort(p Period) map[string][]sessions.ModelEffort { // Only Codex's own calls carry a Codex thread: a gateway call is told // its thread by the Codex call that has its response id, so the other // agents' session files are not read for this. - value = codexModelEffort(ledgerOfAt(p, Filter{}, now, codexCalls).Rows) + value = codexModelEffort(codexEffortRows(p, now, codexCalls)) return cloneEffort(value) } +// codexEffortRows are the rows of ledgerOfAt(p, Filter{}, now, reader) that +// carry a Codex thread, in the same order, without the rest of the ledger. +// A gateway call is told its thread only by the session file's call it is +// paired with, and a session file's call is matched (and so not a row of +// its own) only by a gateway call with its request id, its session or its +// response id: only those gateway calls are kept from the log, each read +// and let go as the log is visited. Over ~720k gateway calls a build held +// every one of them three times over (a record, a packed row and a priced +// row) at the start's peak (#2776). +func codexEffortRows(p Period, now time.Time, reader func(time.Time) []sessions.Call) []Row { + since := p.Since(now) + gatewaySince := since + if !since.IsZero() { + gatewaySince = since.Add(-24 * time.Hour) + } + logs := reader(since) + if len(logs) == 0 { + return nil + } + recs := matchingRecords(gatewaySince, logs) + matched, pairs, actors, compactions := gatewayMatchesDetails(recs, logs) + // only a gateway call paired with a session file's call has a thread + paired := make([]Record, 0, len(pairs)) + byRecord := make(map[int]int, len(pairs)) + for i, r := range recs { + if call, ok := pairs[i]; ok { + byRecord[len(paired)] = call + paired = append(paired, r) + } + } + rows, _, _, _ := ledgerMatched(since, p.Until(now), Filter{}, paired, logs, nil, matched, byRecord, actors, compactions) + return slices.DeleteFunc(rows, func(r Row) bool { return r.codexActor == "" }) +} + +// matchingRecords are the gateway's calls from since on that can be matched +// to one of logs, in the log's order: the ones with a response id, a request +// id or a session one of them has (an agy call by its agent: agy names no +// session). Any other gateway call leaves gatewayMatchesDetails' answer for +// logs as it is. +func matchingRecords(since time.Time, logs []sessions.Call) []Record { + responses, requests, sessionIDs := map[string]bool{}, map[string]bool{}, map[string]bool{} + agy := false + for _, c := range logs { + responses[c.ResponseID] = true + requests[c.RequestID] = true + sessionIDs[c.Session] = true + agy = agy || c.Agent == "agy" + } + delete(responses, "") + delete(requests, "") + delete(sessionIDs, "") + var out []Record + Visit(since, func(r Record) { + if responses[r.ResponseID] || requests[r.RequestID] || sessionIDs[r.NativeSession] || sessionIDs[r.Session] || + agy && ReportedAs(r.Agent) == "agy" { + out = append(out, r) + } + }) + return out +} + func codexCalls(since time.Time) []sessions.Call { return sessions.AgentCalls(since, "codex") } // forgetEffortPeriods drops the answers asked for longest ago, keeping p's From 6359b2c27cb765ccfbf476947148f8d920fdc9f8 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:03:49 +0800 Subject: [PATCH 43/92] usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776) Vias cloned every session's list for each ask, from a cache built for exactly this. The Sessions list, the manage pages and a session's detail each asked, and read the lists of the sessions they show, or of one. Over ~720k calls one ask was ~66 MB. Vias now answers a ViaIndex over the kept map. Of(key) is a session's list as a copy of its own, so a caller still can't change the kept one; Len is how many sessions have one. The three GUI callers and the tests read through Of. TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times, reading one list each: 2,590 bytes an ask. With the clone of every list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask. It also changes a list read through Of and checks the next ask still says 1 call. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/gateway/effort_test.go | 2 +- internal/gui/sessions.go | 4 +- internal/gui/sessions_manage.go | 4 +- internal/usage/client_agents_test.go | 2 +- internal/usage/gateway_sessions_test.go | 10 ++-- internal/usage/growing_rewrite_test.go | 2 +- internal/usage/incremental_log_test.go | 2 +- internal/usage/kept_strings_test.go | 4 +- internal/usage/plan_credits_test.go | 4 +- internal/usage/reported_test.go | 2 +- internal/usage/review_test.go | 4 +- internal/usage/usage.go | 2 +- internal/usage/vias_cache.go | 21 ++++++--- internal/usage/vias_cache_test.go | 61 +++++++++++++++++++++++++ 14 files changed, 97 insertions(+), 27 deletions(-) create mode 100644 internal/usage/vias_cache_test.go diff --git a/internal/gateway/effort_test.go b/internal/gateway/effort_test.go index 3799d112f..bf65d26a3 100644 --- a/internal/gateway/effort_test.go +++ b/internal/gateway/effort_test.go @@ -221,7 +221,7 @@ func TestTraceRecordsTheEffortSent(t *testing.T) { if strings.Join(got, ",") != "high,xhigh,high,max," { t.Errorf("usage efforts %q", got) } - vs := usage.Vias(time.Time{})[usage.AgentOf("")+"|sess-1"] + vs := usage.Vias(time.Time{}).Of(usage.AgentOf("") + "|sess-1") if len(vs) != 4 || vs[0].Model != "glm-5.3-flash" || vs[0].Effort != "high" || vs[0].Calls != 2 { t.Errorf("vias %+v", vs) } diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 27d306bf6..7f8a16d98 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -120,7 +120,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { } vias := usage.Vias(since.Add(-time.Minute)) for _, s := range list { - j := sessionJSON{Session: s, Name: s.Agent, Icon: "generic", Via: vias[s.Agent+"|"+s.ID]} + j := sessionJSON{Session: s, Name: s.Agent, Icon: "generic", Via: vias.Of(s.Agent + "|" + s.ID)} if a := agents[s.Agent]; a != nil { j.Name, j.Icon = a.SharedName(), a.Icon } @@ -226,7 +226,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { if since.IsZero() { since = s.Last } - j.Via = usage.Vias(since.Add(-time.Minute))[s.Agent+"|"+s.ID] + j.Via = usage.Vias(since.Add(-time.Minute)).Of(s.Agent + "|" + s.ID) j.Path = tilde(j.Path) writeJSON(rw, j) }) diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.go index f56017237..7ec415175 100644 --- a/internal/gui/sessions_manage.go +++ b/internal/gui/sessions_manage.go @@ -207,7 +207,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { vias := usage.Vias(since.Add(-time.Minute)) for _, s := range list { s.Path = tilde(s.Path) - out.Sessions = append(out.Sessions, managedJSON{Managed: s, Via: vias[s.Agent+"|"+s.ID]}) + out.Sessions = append(out.Sessions, managedJSON{Managed: s, Via: vias.Of(s.Agent + "|" + s.ID)}) } sizes := sessions.GatewaySizes() for _, g := range gateway { @@ -218,7 +218,7 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { addCodexModelEffort(&s, modelEffort) // its size is the conversation text magpie recorded of it m := sessions.Managed{Session: s, Deletable: true, Size: sizes(s.Agent, s.ID)} - out.Sessions = append(out.Sessions, managedJSON{Managed: m, Via: vias[s.Agent+"|"+s.ID]}) + out.Sessions = append(out.Sessions, managedJSON{Managed: m, Via: vias.Of(s.Agent + "|" + s.ID)}) } sort.SliceStable(out.Sessions, func(i, j int) bool { return out.Sessions[i].Last.After(out.Sessions[j].Last) diff --git a/internal/usage/client_agents_test.go b/internal/usage/client_agents_test.go index a8795a6e3..e13c2c34c 100644 --- a/internal/usage/client_agents_test.go +++ b/internal/usage/client_agents_test.go @@ -51,7 +51,7 @@ func TestClientCountedAsAgent(t *testing.T) { if sum.Agents[0].Calls != 3 || sum.Agents[0].Input != 22 { t.Fatalf("Codex's row doesn't hold the bridge's calls: %+v", sum.Agents[0]) } - if got := Vias(time.Time{}); len(got["codex|thread-1"]) != 1 || len(got["hermes-codex-thread-bridge|thread-1"]) != 0 { + if got := Vias(time.Time{}); len(got.Of("codex|thread-1")) != 1 || len(got.Of("hermes-codex-thread-bridge|thread-1")) != 0 { t.Fatalf("Routing's sessions: %v", got) } g, ok := GatewaySessionByID("codex", "thread-1", nil) diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.go index f28dca083..9affd4158 100644 --- a/internal/usage/gateway_sessions_test.go +++ b/internal/usage/gateway_sessions_test.go @@ -64,7 +64,7 @@ func TestClientRequestPrefixedSessionsCount(t *testing.T) { if len(summary.Sessions) != 1 || summary.Sessions[0].ID != "request-mine" { t.Fatalf("the client's session is missing from Usage: %+v", summary.Sessions) } - if got := Vias(time.Time{}); len(got["pi|request-mine"]) != 1 { + if got := Vias(time.Time{}); len(got.Of("pi|request-mine")) != 1 { t.Fatalf("the client's session is missing from Routing: %+v", got) } if _, ok := GatewaySessionByID("pi", "request-mine", nil); !ok { @@ -100,11 +100,11 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) { } } vias := Vias(time.Time{}) - vias["pi|native"][0].Calls = 999 - if got := Vias(time.Time{})["pi|native"][0].Calls; got != 2 { + vias.Of("pi|native")[0].Calls = 999 + if got := Vias(time.Time{}).Of("pi|native")[0].Calls; got != 2 { t.Fatalf("caller mutated routing cache: %d", got) } - if got := Vias(at.Add(-time.Minute))["pi|native"][0].Calls; got != 1 { + if got := Vias(at.Add(-time.Minute)).Of("pi|native")[0].Calls; got != 1 { t.Fatalf("routing window: %d", got) } if err := os.WriteFile(Path(), nil, 0600); err != nil { @@ -113,7 +113,7 @@ func TestGatewaySessionsCachePricesWindowsAndRewrite(t *testing.T) { if got := GatewaySessions(time.Time{}, nil); len(got) != 0 { t.Fatalf("rewrite retained sessions: %+v", got) } - if got := Vias(time.Time{}); len(got) != 0 { + if got := Vias(time.Time{}); got.Len() != 0 { t.Fatalf("rewrite retained routing: %+v", got) } } diff --git a/internal/usage/growing_rewrite_test.go b/internal/usage/growing_rewrite_test.go index c4937d23d..73f891665 100644 --- a/internal/usage/growing_rewrite_test.go +++ b/internal/usage/growing_rewrite_test.go @@ -76,7 +76,7 @@ func TestLogGrowingRewriteThenAppend(t *testing.T) { } vias := Vias(time.Time{}) for session, input := range map[string]int{"edited-prefix": 73, "appended-tail": 19} { - v := vias["codex|"+session] + v := vias.Of("codex|" + session) if len(v) != 1 || v[0].Calls != 1 || v[0].Tokens != input { t.Fatalf("%s vias stale: %+v", session, v) } diff --git a/internal/usage/incremental_log_test.go b/internal/usage/incremental_log_test.go index 0b1d6a739..7e50a3192 100644 --- a/internal/usage/incremental_log_test.go +++ b/internal/usage/incremental_log_test.go @@ -75,7 +75,7 @@ func TestUsageViasSkipsOldHistory(t *testing.T) { settleLogClock(t) historyLog(t, 4000) since := time.Now().Add(-time.Hour) - if v := Vias(since); len(v) != 1 || v["codex|s"][0].Calls != 1 { + if v := Vias(since); v.Len() != 1 || v.Of("codex|s")[0].Calls != 1 { t.Fatal(v) } if n := testing.AllocsPerRun(2, func() { Vias(since) }); n > 1500 { diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.go index 4d50fe3e4..2c8b24585 100644 --- a/internal/usage/kept_strings_test.go +++ b/internal/usage/kept_strings_test.go @@ -54,8 +54,8 @@ func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) { if got := GatewaySessions(time.Time{}, nil); len(got) != blocks { t.Fatalf("sessions: %d, want %d", len(got), blocks) } - if got := Vias(time.Time{}); len(got) != blocks { - t.Fatalf("vias: %d, want %d", len(got), blocks) + if got := Vias(time.Time{}); got.Len() != blocks { + t.Fatalf("vias: %d, want %d", got.Len(), blocks) } // the index is kept by design; only what the caches hold is measured logIndex.Lock() diff --git a/internal/usage/plan_credits_test.go b/internal/usage/plan_credits_test.go index f61c30390..f069c0ef4 100644 --- a/internal/usage/plan_credits_test.go +++ b/internal/usage/plan_credits_test.go @@ -49,10 +49,10 @@ func TestPlanCreditsSummed(t *testing.T) { } } vias := Vias(time.Time{}) - if v := vias["claude-code|s1"]; len(v) != 1 || !near(v[0].Credits, 0.7) || v[0].Credited != 70 { + if v := vias.Of("claude-code|s1"); len(v) != 1 || !near(v[0].Credits, 0.7) || v[0].Credited != 70 { t.Fatalf("session s1: %+v", v) } - if v := vias["codex|s2"]; len(v) != 2 || v[0].Credited+v[1].Credited != 1 { + if v := vias.Of("codex|s2"); len(v) != 2 || v[0].Credited+v[1].Credited != 1 { t.Fatalf("session s2: %+v", v) } if got := FormatCredits(page.Sum); got != "0.7 credits" { diff --git a/internal/usage/reported_test.go b/internal/usage/reported_test.go index 5a9fc5244..7fd1aac03 100644 --- a/internal/usage/reported_test.go +++ b/internal/usage/reported_test.go @@ -199,7 +199,7 @@ func TestReportedTouchesNothingLive(t *testing.T) { t.Fatalf("a reported session is a gateway session: %+v", g) } } - if v := Vias(time.Time{})["claude|s-rep"]; len(v) != 0 { + if v := Vias(time.Time{}).Of("claude|s-rep"); len(v) != 0 { t.Fatalf("a reported session was routed: %+v", v) } if !(Record{Source: SourceReported}).IsReported() || (Record{}).IsReported() { diff --git a/internal/usage/review_test.go b/internal/usage/review_test.go index bcdfe2ed9..75c5991c4 100644 --- a/internal/usage/review_test.go +++ b/internal/usage/review_test.go @@ -158,12 +158,12 @@ func TestZeroTokenFailuresDeduplicateAndRejectedStayVisible(t *testing.T) { t.Fatal("local rejection consumed a real API call") } Append(r) - if len(Vias(time.Time{})) != 0 { + if Vias(time.Time{}).Len() != 0 { t.Fatal("rejected request appears as a session provider") } Append(Record{Time: at, Agent: "claude", Provider: "relay", Model: "m", Session: "s", Status: 200}) Append(Record{Time: at, Agent: "claude", Model: "m", Session: "s", Status: 400}) // legacy rejection - if vias := Vias(time.Time{}); len(vias) != 1 || len(vias["claude|s"]) != 1 || vias["claude|s"][0].Calls != 1 { + if vias := Vias(time.Time{}); vias.Len() != 1 || len(vias.Of("claude|s")) != 1 || vias.Of("claude|s")[0].Calls != 1 { t.Fatalf("session via includes a local rejection: %+v", vias) } var out bytes.Buffer diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 684267961..116d119d0 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -999,7 +999,7 @@ type Via struct { // Vias is what the gateway sent each session's calls to since a time, by // agent id and the session's id ("codex|"), the most calls first. -func Vias(since time.Time) map[string][]Via { +func Vias(since time.Time) ViaIndex { return cachedVias(since) } diff --git a/internal/usage/vias_cache.go b/internal/usage/vias_cache.go index de63bd367..1d821fc4b 100644 --- a/internal/usage/vias_cache.go +++ b/internal/usage/vias_cache.go @@ -14,7 +14,20 @@ var viasCache struct { value map[string][]Via } -func cachedVias(since time.Time) map[string][]Via { +// ViaIndex is Vias' answer: the one copy every caller shares, handed out +// whole and read only through Of, which gives each session's list as a +// copy of its own. Each ask cloned every session's list, ~66 MB a time +// over ~720k calls, where a page reads the few sessions it lists (#2776). +type ViaIndex struct{ m map[string][]Via } + +// Of is what the gateway sent one session's calls to ("agent|id"), the +// most calls first; nil for a session it sent none of. +func (x ViaIndex) Of(key string) []Via { return slices.Clone(x.m[key]) } + +// Len is how many sessions have a list. +func (x ViaIndex) Len() int { return len(x.m) } + +func cachedVias(since time.Time) ViaIndex { snapshot := readLogSnapshot() clients := clientAgentsKey() viasCache.Lock() @@ -26,9 +39,5 @@ func cachedVias(since time.Time) map[string][]Via { viasCache.version, viasCache.since, viasCache.value, viasCache.clients = snapshot.version, since, value, clients } } - out := make(map[string][]Via, len(value)) - for k, vs := range value { - out[k] = slices.Clone(vs) - } - return out + return ViaIndex{value} } diff --git a/internal/usage/vias_cache_test.go b/internal/usage/vias_cache_test.go new file mode 100644 index 000000000..9a8f0a551 --- /dev/null +++ b/internal/usage/vias_cache_test.go @@ -0,0 +1,61 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// Vias hands every caller the one copy it keeps, not a clone of every +// session's list: a Sessions page reads the few sessions it lists, and +// each ask cloned all of them, ~66 MB a time over ~720k calls (#2776). +// A list read through Of is still the caller's own. +func TestViasHandOutTheKeptCopy(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount = 20000 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for i := range sessionCount { + if err := enc.Encode(Record{Time: now.Add(-time.Duration(i) * time.Second), Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + vias := Vias(time.Time{}) + if vias.Len() != sessionCount { + t.Fatalf("%d sessions, want %d", vias.Len(), sessionCount) + } + vias.Of("pi|s1")[0].Calls = 999 + if got := Vias(time.Time{}).Of("pi|s1")[0].Calls; got != 1 { + t.Fatalf("a caller changed the kept copy: %d calls", got) + } + const asks = 20 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range asks { + Vias(time.Time{}).Of("pi|s7") + } + runtime.ReadMemStats(&after) + // a clone of 20000 lists is a few MB; the log's check and one list + // are tens of KB + per := (after.TotalAlloc - before.TotalAlloc) / asks + t.Logf("an ask allocated %d bytes", per) + if per > 256<<10 { + t.Fatalf("an ask allocated %d bytes", per) + } +} From 43bd998b1507114e16d4a443d70e8d790149fcf6 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:18:18 +0800 Subject: [PATCH 44/92] usage: GatewaySessions hands out the kept projection's lists instead of cloning every session's days for each ask (#2776) GatewaySessions cloned every session's Models and Daily for each ask, from the projection kept for exactly these asks. The start's first asks (the Sessions list, each agent's manage page, the stats) each cloned them all. In a heap snapshot at the 720k-call sandbox's peak, cloneGatewaySession held ~447 MB live of the 1362 MB. Every caller (gatewayExternal, listedGateway) only reads the lists, and copies them again into its own ExternalSession anyway. The lists are now the kept projection's, shared and read only, which GatewaySessions' doc now says. This changes the old contract that a caller owned its copy. The kept lists are clipped, so an append by a caller makes a slice of its own and can't write into another's. gatewaySessionFrom shares the days in a window the same way. GatewaySessionByID still hands out a clone. TestGatewaySessionsHandOutTheKeptProjection writes 2000 sessions x 10 days and asks 10 times: 435,215 bytes an ask, against the 368,000-byte list itself. With the clone put back by hand: red, 3,669,150 bytes an ask. TestGatewaySessionsCacheRefreshAndOwnership now checks that two asks share the days, that two callers' appends don't alias each other or the kept list, and that the kept data is unchanged after them. With the clone put back it is red too ("each ask has a copy of the days of its own"). Run: go test -p 4 -count=1 ./internal/usage/ ./internal/gui/: ok (load ~157). Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/usage/gateway_sessions.go | 14 ++++- .../usage/gateway_sessions_shared_test.go | 60 +++++++++++++++++++ internal/usage/gateway_sessions_test.go | 15 ++++- 3 files changed, 83 insertions(+), 6 deletions(-) create mode 100644 internal/usage/gateway_sessions_shared_test.go diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index 8eb143629..db56f7f64 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -58,13 +58,19 @@ type GatewayModel struct { // GatewaySessions aggregates one usage snapshot without reading routing // history or agent files. NativeKeys contains identities already represented // by local session files and is used to suppress the duplicate projection. +// +// A session's Models and Daily are the kept projection's own, shared by +// every caller, which reads them and never changes them: each ask cloned +// every session's days, and the start's first asks together held ~450 MB +// of copies over ~720k calls (#2776). They are clipped, so an append +// makes a slice of the caller's own. func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession { if since.IsZero() { e := gatewayProjection() out := make([]GatewaySession, 0, len(e.sessions)) for _, s := range e.sessions { if !nativeKeys[s.Agent+"|"+s.ID] { - out = append(out, cloneGatewaySession(s)) + out = append(out, s) } } return out @@ -105,9 +111,9 @@ func gatewaySessionFrom(s GatewaySession, date string) (GatewaySession, bool) { return GatewaySession{}, false } if i == 0 { - return cloneGatewaySession(s), true + return s, true } - w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: slices.Clone(s.Daily[i:])} + w := GatewaySession{Agent: s.Agent, ID: s.ID, Models: []GatewayModel{}, Daily: s.Daily[i:]} models := map[string]int{} // index in w.Models, which grows for _, d := range w.Daily { if w.Start.IsZero() || d.first.Before(w.Start) { @@ -204,6 +210,8 @@ func gatewayProjection() gatewayProjectionEntry { e := gatewayProjectionEntry{version: snapshot.version, meta: meta, zone: time.Local, sessions: ss, byID: make(map[string]int, len(ss))} for i, s := range ss { e.byID[s.Agent+"|"+s.ID] = i + // handed out as they are: an append is the caller's own + ss[i].Models, ss[i].Daily = slices.Clip(s.Models), slices.Clip(s.Daily) } // A failed or partial read must be retried, not published as current. if snapshot.info != nil && snapshot.off == snapshot.info.Size() { diff --git a/internal/usage/gateway_sessions_shared_test.go b/internal/usage/gateway_sessions_shared_test.go new file mode 100644 index 000000000..0cab4790d --- /dev/null +++ b/internal/usage/gateway_sessions_shared_test.go @@ -0,0 +1,60 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" + "unsafe" +) + +// GatewaySessions hands every caller the kept projection's sessions, not a +// clone of each one's models and days: the start's first asks (the +// Sessions list, Manage for each agent, Stats) each cloned all of them, +// ~450 MB of copies at once over ~720k calls (#2776). +func TestGatewaySessionsHandOutTheKeptProjection(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount, days = 2000, 10 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for d := range days { + for i := range sessionCount { + at := now.AddDate(0, 0, -d).Add(-time.Duration(i) * time.Second) + if err := enc.Encode(Record{Time: at, Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := GatewaySessions(time.Time{}, nil); len(got) != sessionCount || len(got[0].Daily) < days { + t.Fatalf("%d sessions, the first with %d days", len(got), len(got[0].Daily)) + } + const asks = 10 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for range asks { + GatewaySessions(time.Time{}, nil) + } + runtime.ReadMemStats(&after) + per := (after.TotalAlloc - before.TotalAlloc) / asks + list := uint64(sessionCount) * uint64(unsafe.Sizeof(GatewaySession{})) + t.Logf("an ask allocated %d bytes; the list it answers is %d", per, list) + // the list itself, and the log's check + if per > list+list/2 { + t.Fatalf("an ask allocated %d bytes, its list is %d", per, list) + } +} diff --git a/internal/usage/gateway_sessions_test.go b/internal/usage/gateway_sessions_test.go index 9affd4158..61b06e89a 100644 --- a/internal/usage/gateway_sessions_test.go +++ b/internal/usage/gateway_sessions_test.go @@ -40,10 +40,19 @@ func TestGatewaySessionsCacheRefreshAndOwnership(t *testing.T) { if len(first) != 1 { t.Fatalf("first: %+v", first) } - first[0].Models[0].Model = "changed by caller" - first[0].Daily[0].Input = 999 + // the lists are the kept projection's, read only; an append is the + // caller's own (#2776) again := GatewaySessions(time.Time{}, nil) - if again[0].Models[0].Model != "m" || again[0].Daily[0].Input != 10 { + if &again[0].Daily[0] != &first[0].Daily[0] { + t.Fatal("each ask has a copy of the days of its own") + } + mine := append(first[0].Daily, GatewayDayUsage{Date: "mine"}) + theirs := append(again[0].Daily, GatewayDayUsage{Date: "theirs"}) + models := append(first[0].Models, GatewayModel{Model: "mine"}) + if mine[1].Date != "mine" || theirs[1].Date != "theirs" || &mine[0] == &first[0].Daily[0] || &models[0] == &first[0].Models[0] { + t.Fatalf("two callers' appends share the kept lists: %+v %+v", mine, theirs) + } + if again := GatewaySessions(time.Time{}, nil); len(again[0].Models) != 1 || len(again[0].Daily) != 1 || again[0].Models[0].Model != "m" || again[0].Daily[0].Input != 10 { t.Fatalf("caller changed cache: %+v", again) } if got := GatewaySessions(time.Time{}, map[string]bool{"pi|native": true}); len(got) != 0 { From 34b1757843922c7e75e64937725ac9f34b5d1fb1 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:43:26 +0800 Subject: [PATCH 45/92] usage: the kept gateway projection's days and models are lists of their own size (#2776) buildGatewaySessions grew each session's Daily and Models an item at a time from empty. The projection is kept for as long as the log is unchanged, and so was the spare room append had left each list (five days took eight). slices.Clip in gatewayProjection hides that room from callers but doesn't free it. On the 720k-call sandbox, that append was the largest single allocation of the build (319 MB of 1.14 GB), and the lists are most of what the start keeps for the Sessions page. Each list is now made at the size its map already counts. TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days with one to five models each, and measures the heap the projection keeps. The bound is its days and models x1.3, plus the sessions' list and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With the two makes taken out by hand: red, 12,754,488 bytes. 720k-call sandbox, cold start, the four first asks together, the live heap 20 s after them, back to back: 541 MB before, 479 MB after. The machine's load was ~250-290 and the answers took ~140 s in both runs, so their peak RSS (1395 and 1891 MB) measured the load, not this. Run: go test -p 4 -count=1 ./internal/usage/: ok. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/usage/gateway_sessions.go | 4 ++ internal/usage/gateway_sessions_kept_test.go | 70 ++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 internal/usage/gateway_sessions_kept_test.go diff --git a/internal/usage/gateway_sessions.go b/internal/usage/gateway_sessions.go index db56f7f64..c1fe4bcf1 100644 --- a/internal/usage/gateway_sessions.go +++ b/internal/usage/gateway_sessions.go @@ -348,6 +348,10 @@ func buildGatewaySessions(snapshot *logSnapshot, since time.Time, nativeKeys map m.addRecord(r, p) }) for k, s := range groups { + // of their own size: the projection keeps them, and grown an item + // at a time they kept append's spare room, ~40% of them (#2776) + s.Daily = make([]GatewayDayUsage, 0, len(perSession[k])) + s.Models = make([]GatewayModel, 0, len(models[k])) for _, d := range perSession[k] { s.Daily = append(s.Daily, *d) } diff --git a/internal/usage/gateway_sessions_kept_test.go b/internal/usage/gateway_sessions_kept_test.go new file mode 100644 index 000000000..0c1b3843b --- /dev/null +++ b/internal/usage/gateway_sessions_kept_test.go @@ -0,0 +1,70 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "unsafe" +) + +// The kept projection holds each session's days and models in lists of +// their own size: grown an item at a time they kept the room append had +// left them (five days took eight), which is most of what a start keeps +// for the Sessions page over ~720k calls (#2776). +func TestGatewayProjectionKeepsNoSpareRoom(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount, days = 3000, 5 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + for d := range days { + for i := range sessionCount { + at := now.AddDate(0, 0, -d) + for _, model := range []string{"m1", "m2", "m3", "m4", "m5"}[:1+i%5] { + if err := enc.Encode(Record{Time: at, Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: model, Input: 10, Status: 200}); err != nil { + t.Fatal(err) + } + } + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + readLogSnapshot() // kept whether or not a projection is + gatewayCache.Lock() + gatewayCache.entry = nil + gatewayCache.Unlock() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + e := gatewayProjection() + runtime.GC() + runtime.ReadMemStats(&after) + kept := int64(after.HeapAlloc) - int64(before.HeapAlloc) + items, models := 0, 0 + for _, s := range e.sessions { + items += len(s.Daily) + models += len(s.Models) + } + if len(e.sessions) != sessionCount || items != sessionCount*days*3 { + t.Fatalf("%d sessions, %d days", len(e.sessions), items) + } + // the lists themselves, and the sessions' list and index beside them + lists := int64(items)*int64(unsafe.Sizeof(GatewayDayUsage{})) + int64(models)*int64(unsafe.Sizeof(GatewayModel{})) + beside := int64(sessionCount) * (int64(unsafe.Sizeof(GatewaySession{})) + 64) + t.Logf("the projection keeps %d bytes; its days and models are %d, its list and index ~%d", kept, lists, beside) + if kept > lists*13/10+beside { + t.Fatalf("the projection keeps %d bytes for %d bytes of days and models", kept, lists) + } + runtime.KeepAlive(e) +} From 2fcd4b33c4c8881b478c72df1422747bbfe1f56f Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 13:30:54 +0800 Subject: [PATCH 46/92] usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776) Vias kept the lists for one since. The Sessions list asks from its oldest listed session's start, each agent's manage page from that agent's oldest, and a session's detail from that session's start, so an open page's polls almost never asked the kept since, and each ask read and grouped the whole log again. Idle with an open Sessions page on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes, 78% of everything allocated, which is most of why the idle process churned its heap and grew. The cache now keeps one index from the whole log and each session's first call. A session whose calls all came at or after the since is answered from it. A session with calls before its since is answered from one kept window for that since, built only when such a session is read. Len counts the sessions with a call since the index's time. Both are kept per log version and agent list, as before. TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks from three sinces in turn, as the three pages do: 2,677 bytes an ask. On the old cache: red, 11,580,100 bytes an ask. It also checks that a session with a call on each side of a since counts only the one after it, and what Len says for a window and for every session. TestGatewaySessionsCachePricesWindowsAndRewrite's window check and TestUsageViasSkipsOldHistory stay green. 720k-call sandbox, idle with an open page's polls every 15 s (the Sessions list, stats, Claude's manage page, Requests, state), before and after side by side for 12 minutes, load ~170-250. Allocated from minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once, before minute 4). The faster answers let the poll loop run about twice as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962 and 555-1217 MB; both swing with where a poll is when the snapshot is taken and the machine's load, and neither shows a trend in 12 minutes. Run: go test -p 4 -count=1 ./internal/usage/ -run 'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/usage/kept_strings_test.go | 2 +- internal/usage/usage.go | 8 ++- internal/usage/vias_cache.go | 93 +++++++++++++++++++++++++---- internal/usage/vias_since_test.go | 86 ++++++++++++++++++++++++++ 4 files changed, 173 insertions(+), 16 deletions(-) create mode 100644 internal/usage/vias_since_test.go diff --git a/internal/usage/kept_strings_test.go b/internal/usage/kept_strings_test.go index 2c8b24585..f2953b3a7 100644 --- a/internal/usage/kept_strings_test.go +++ b/internal/usage/kept_strings_test.go @@ -66,7 +66,7 @@ func TestSessionCachesHoldNoDecodedBlocks(t *testing.T) { gatewayCache.entry = nil gatewayCache.Unlock() viasCache.Lock() - viasCache.value = nil + viasCache.all, viasCache.window.m = nil, nil viasCache.Unlock() without := held() decoded := uint64(blocks * logBlockRows * text) diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 116d119d0..c3f26802a 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -1003,8 +1003,9 @@ func Vias(since time.Time) ViaIndex { return cachedVias(since) } -func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { +func buildVias(snapshot *logSnapshot, since time.Time) *viaLists { out := map[string][]Via{} + first := map[string]time.Time{} keep := keptStrings{} snapshot.visit(since, func(r Record) { if r.IsRejected() || r.IsReported() || r.Session == "" || r.Model == "" { @@ -1013,6 +1014,9 @@ func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { r.Provider, r.Model, r.Effort = keep.of(r.Provider), keep.of(r.Model), keep.of(r.Effort) k := ReportedAs(r.Agent) + "|" + r.Session vs := out[k] + if t, seen := first[k]; !seen || r.Time.Before(t) { + first[k] = r.Time + } i := slices.IndexFunc(vs, func(v Via) bool { return v.Provider == r.Provider && v.Model == r.Model && v.Effort == r.Effort }) if i < 0 { vs, i = append(vs, Via{Provider: r.Provider, Model: r.Model, Effort: r.Effort}), len(vs) @@ -1031,7 +1035,7 @@ func buildVias(snapshot *logSnapshot, since time.Time) map[string][]Via { for _, vs := range out { sort.SliceStable(vs, func(i, j int) bool { return vs[i].Calls > vs[j].Calls }) } - return out + return &viaLists{m: out, first: first} } // Saw notes a request from an agent arriving now. diff --git a/internal/usage/vias_cache.go b/internal/usage/vias_cache.go index 1d821fc4b..656019703 100644 --- a/internal/usage/vias_cache.go +++ b/internal/usage/vias_cache.go @@ -6,38 +6,105 @@ import ( "time" ) +// viaLists is what the gateway sent each session's calls to, and when each +// session's first call was: a list counted from any time at or before that +// first call is the same list. +type viaLists struct { + m map[string][]Via + first map[string]time.Time +} + +// viasCache keeps one index of the whole log, which answers every since a +// session's calls all came after, and one window for a session that had +// calls before its since. The Sessions list, each agent's manage page and +// a session's detail each ask from a since of their own; one kept since +// was built again from the whole log at almost every ask, ~280 MB a time +// over ~720k calls, on every poll of an open page (#2776). var viasCache struct { sync.Mutex version uint64 - since time.Time clients string // the clients counted as agents (#1958) - value map[string][]Via + all *viaLists + window struct { + version uint64 + clients string + since time.Time + m map[string][]Via + } } // ViaIndex is Vias' answer: the one copy every caller shares, handed out // whole and read only through Of, which gives each session's list as a // copy of its own. Each ask cloned every session's list, ~66 MB a time // over ~720k calls, where a page reads the few sessions it lists (#2776). -type ViaIndex struct{ m map[string][]Via } +type ViaIndex struct { + all *viaLists + since time.Time + snapshot *logSnapshot + clients string +} -// Of is what the gateway sent one session's calls to ("agent|id"), the -// most calls first; nil for a session it sent none of. -func (x ViaIndex) Of(key string) []Via { return slices.Clone(x.m[key]) } +// Of is what the gateway sent one session's calls to ("agent|id") since +// the index's time, the most calls first; nil for a session it sent none +// of. +func (x ViaIndex) Of(key string) []Via { + vs, ok := x.all.m[key] + if !ok { + return nil + } + if x.since.IsZero() || !x.all.first[key].Before(x.since) { + return slices.Clone(vs) + } + return slices.Clone(x.window()[key]) +} // Len is how many sessions have a list. -func (x ViaIndex) Len() int { return len(x.m) } +func (x ViaIndex) Len() int { + if x.since.IsZero() { + return len(x.all.m) + } + n := 0 + for _, vs := range x.all.m { + if slices.ContainsFunc(vs, func(v Via) bool { return !v.Last.Before(x.since) }) { + n++ + } + } + return n +} + +// window is the lists counted from the index's since, for a session that +// had calls before it. +func (x ViaIndex) window() map[string][]Via { + viasCache.Lock() + defer viasCache.Unlock() + w := &viasCache.window + if w.m != nil && w.version == x.snapshot.version && w.clients == x.clients && w.since.Equal(x.since) { + return w.m + } + m := buildVias(x.snapshot, x.since).m + if x.snapshot.complete() { + w.version, w.clients, w.since, w.m = x.snapshot.version, x.clients, x.since, m + } + return m +} func cachedVias(since time.Time) ViaIndex { snapshot := readLogSnapshot() clients := clientAgentsKey() viasCache.Lock() defer viasCache.Unlock() - value := viasCache.value - if value == nil || viasCache.version != snapshot.version || !viasCache.since.Equal(since) || viasCache.clients != clients { - value = buildVias(snapshot, since) - if snapshot.info != nil && snapshot.off == snapshot.info.Size() { - viasCache.version, viasCache.since, viasCache.value, viasCache.clients = snapshot.version, since, value, clients + all := viasCache.all + if all == nil || viasCache.version != snapshot.version || viasCache.clients != clients { + all = buildVias(snapshot, time.Time{}) + if snapshot.complete() { + viasCache.version, viasCache.clients, viasCache.all = snapshot.version, clients, all } } - return ViaIndex{value} + return ViaIndex{all: all, since: since, snapshot: snapshot, clients: clients} +} + +// complete is whether the snapshot reached the end of the log, so what is +// built from it can be kept for its version. +func (s *logSnapshot) complete() bool { + return s.info != nil && s.off == s.info.Size() } diff --git a/internal/usage/vias_since_test.go b/internal/usage/vias_since_test.go new file mode 100644 index 000000000..c1ad8b7ed --- /dev/null +++ b/internal/usage/vias_since_test.go @@ -0,0 +1,86 @@ +package usage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// The Sessions list, each agent's manage page and a session's detail each +// ask Vias from a since of their own. One kept since was built again from +// the whole log at almost every ask, ~280 MB a time over ~720k calls, on +// every poll of an open page (#2776). One index now answers every since a +// session's calls all came after, and a session with calls before its +// since still counts only those after it. +func TestViasAnswerEverySinceFromOneIndex(t *testing.T) { + pageHome(t) + settleLogClock(t) + const sessionCount = 20000 + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.Create(Path()) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + now := Clock() + write := func(r Record) { + if err := enc.Encode(r); err != nil { + t.Fatal(err) + } + } + for i := range sessionCount { + write(Record{Time: now.Add(-time.Duration(sessionCount-i) * time.Second), Agent: "pi", Session: fmt.Sprintf("s%d", i), Provider: "p", Model: "m", Input: 10, Status: 200}) + } + // one session with a call on each side of a since + write(Record{Time: now.Add(-time.Hour), Agent: "pi", Session: "both", Provider: "p", Model: "m", Input: 10, Status: 200}) + write(Record{Time: now, Agent: "pi", Session: "both", Provider: "p", Model: "m", Input: 10, Status: 200}) + if err := f.Close(); err != nil { + t.Fatal(err) + } + if got := Vias(now.Add(-time.Minute)).Of("pi|both"); len(got) != 1 || got[0].Calls != 1 { + t.Fatalf("since a minute ago: %+v, want the one call after it", got) + } + if got := Vias(time.Time{}).Of("pi|both"); len(got) != 1 || got[0].Calls != 2 { + t.Fatalf("since ever: %+v, want both calls", got) + } + // the last 60 sessions, a second apart up to a second ago, and "both" + if n := Vias(now.Add(-time.Minute)).Len(); n != 61 { + t.Fatalf("%d sessions with calls since a minute ago, want 61", n) + } + if n := Vias(time.Time{}).Len(); n != sessionCount+1 { + t.Fatalf("%d sessions, want %d", n, sessionCount+1) + } + // the list, a manage page and a detail, asking in turn + sinces := []time.Time{ + now.Add(-(sessionCount + 60) * time.Second), + now.Add(-(sessionCount/2 + 60) * time.Second), + now.Add(-(sessionCount - 10 + 60) * time.Second), + } + key := fmt.Sprintf("pi|s%d", sessionCount-10) + for _, since := range sinces { + if got := Vias(since).Of(key); len(got) != 1 || got[0].Calls != 1 { + t.Fatalf("since %v: %+v", since, got) + } + } + const asks = 30 + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + for i := range asks { + Vias(sinces[i%len(sinces)]).Of(key) + } + runtime.ReadMemStats(&after) + // building the lists of 20000 sessions is several MB; the log's check + // and one list are tens of KB + per := (after.TotalAlloc - before.TotalAlloc) / asks + t.Logf("an ask allocated %d bytes", per) + if per > 256<<10 { + t.Fatalf("an ask allocated %d bytes: the lists were built again", per) + } +} From 865b61808690bc9fd716257949414ec97618a5a5 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 13:49:56 +0800 Subject: [PATCH 47/92] gui: a gateway session is listed without its days, which only the stats read (#2776) gatewayExternal copied every gateway session's days into the ExternalSession it hands the Sessions list, each agent's manage page and a session's detail. MergeExternal, which all three go through, never reads them; only MergeExternalStats does. The Sessions list asks for every session, so each poll of an open page copied every gateway session's days. After the Vias fix (the commit before this one), that copy was the largest allocation an idle open page makes: 5.11 GB of 9.14 GB in 6 minutes on the 720k-call sandbox. gatewayExternal now leaves the days out, and the stats add them through gatewayDays. Each model list is made at its size. TestGatewayListCopiesNoDays lists a session with 365 days: no days in the listed copy, and gatewayDays has all of them. With the days copy put back in gatewayExternal by hand: red, "a listed session copied 365 days". TestGatewaySessionHistoryAndCalendar still sees each day's output in the stats. 720k-call sandbox, idle with an open page's polls every 15 s, this and the build before it side by side for 10 minutes, load ~190-210, 12 poll rounds each. Allocated from minute 2 to minute 8: gatewayListed 5,440 MB before and 1,000 MB after, the Sessions list handler 5,820 MB and 2,970 MB, the manage page 2,220 MB and 1,850 MB. The live heap at the snapshots ran 393-857 MB before and 389-889 MB after, and RSS 406-1176 MB and 357-934 MB, with no trend in either over the 10 minutes. Run: go test -p 4 -count=1 ./internal/gui/ ./internal/sessions/: ok. Full suite on this series' final tree (aa678b482 before this note was added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout 45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s), 41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux (-tags nogui) and windows exit 0. The GUI suite wasn't run: no file under internal/gui/assets changed. --- internal/gui/gateway_list_days_test.go | 24 ++++++++++++++++++++++++ internal/gui/sessions.go | 21 +++++++++++++++++---- 2 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 internal/gui/gateway_list_days_test.go diff --git a/internal/gui/gateway_list_days_test.go b/internal/gui/gateway_list_days_test.go new file mode 100644 index 000000000..68ab55aa9 --- /dev/null +++ b/internal/gui/gateway_list_days_test.go @@ -0,0 +1,24 @@ +package gui + +import ( + "testing" + + "github.com/yetone/magpie/internal/usage" +) + +// A list, a manage page and a detail never read a gateway session's days, +// and copying every session's days for each poll of an open Sessions page +// was ~1.8 GB in 4 minutes over ~720k calls (#2776). Only the stats copy +// them, and they still count each one (TestGatewaySessionHistoryAndCalendar). +func TestGatewayListCopiesNoDays(t *testing.T) { + g := usage.GatewaySession{Agent: "pi", ID: "s", Models: []usage.GatewayModel{{Model: "m"}}} + for range 365 { + g.Daily = append(g.Daily, usage.GatewayDayUsage{Date: "2026-10-19", Agent: "pi", Model: "m"}) + } + if e := gatewayListed(g); len(e.Daily) != 0 || len(e.Models) != 1 { + t.Fatalf("a listed session copied %d days and %d models, want 0 and 1", len(e.Daily), len(e.Models)) + } + if d := gatewayDays(g); len(d) != len(g.Daily) { + t.Fatalf("the stats' copy has %d days, want %d", len(d), len(g.Daily)) + } +} diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 7f8a16d98..545012860 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -41,17 +41,28 @@ type sessionsJSON struct { Dirs []string `json:"dirs"` // where they were read from } +// gatewayExternal is a gateway session without its days: a list, a manage +// page and a detail (MergeExternal) never read them, and copying every +// session's days for each poll of an open Sessions page was ~1.8 GB in 4 +// minutes over ~720k calls (#2776). The stats add them (gatewayDays). func gatewayExternal(g usage.GatewaySession) sessions.ExternalSession { e := sessions.ExternalSession{Agent: g.Agent, ID: g.ID, Start: g.Start, Last: g.Last, Tokens: g.Tokens, Cost: g.Cost, Unpriced: g.Unpriced} + e.Models = make([]sessions.ExternalModel, 0, len(g.Models)) for _, m := range g.Models { e.Models = append(e.Models, sessions.ExternalModel{Model: m.Model, Tokens: m.Tokens, Cost: m.Cost, Priced: m.Priced}) } - for _, d := range g.Daily { - e.Daily = append(e.Daily, sessions.ExternalDayUsage{Date: d.Date, Agent: d.Agent, Model: d.Model, Tokens: d.Tokens, Cost: d.Cost, Priced: d.Priced}) - } return e } +// gatewayDays is a gateway session's usage by day, as the stats count it. +func gatewayDays(g usage.GatewaySession) []sessions.ExternalDayUsage { + out := make([]sessions.ExternalDayUsage, 0, len(g.Daily)) + for _, d := range g.Daily { + out = append(out, sessions.ExternalDayUsage{Date: d.Date, Agent: d.Agent, Model: d.Model, Tokens: d.Tokens, Cost: d.Cost, Priced: d.Priced}) + } + return out +} + // gatewayListed is a gateway session as a list shows it: titled by what it // was first asked, when magpie recorded it, not by its ses_… id (YOU on // Discord) @@ -460,7 +471,9 @@ func combinedSessionStats(days int) sessions.Stats { gs, gd := usage.GatewaySessionWindowExcept(since, nativeKeys) ext := make([]sessions.ExternalSession, 0, len(gs)) for _, g := range gs { - ext = append(ext, gatewayListed(g)) + e := gatewayListed(g) + e.Daily = gatewayDays(g) + ext = append(ext, e) } daily := make([]sessions.ExternalDayUsage, 0, len(gd)) for _, d := range gd { From a20d86900d539a46b05c147e7ac791f4e6a7168e Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:10:34 +0800 Subject: [PATCH 48/92] provider: what answered a request is written to served.json behind it, once in a while, not on every answer NoteServed ran on every answered request (servedCandidate): it read served.json, merged, and wrote it through steady.WriteFile (a synced temp file renamed over it), all under servedAt's lock, so concurrent answers queued behind each other's fsync. Now NoteServed only notes in memory and arms one write for servedFlushAfter (2s) later; everything noted meanwhile goes in that one write, merged with what the file holds (another gateway's) and pruned past servedKeep as before. The file's format is unchanged. This process's LastServed has a note at once (it merges memory over the file, as it did); the CLI, a process of its own, sees it within 2s. FlushServed writes what is pending: the gateway calls it as Serve ends, and the CLI's signal handler before it dies of the signal. A crash loses at most the last 2s of notes. A note made under one config path (a test's HOME) is never written into another's: a path change drops the pending write. Numbers (Apple M4 Pro, machine loaded by other sessions): BenchmarkNoteServed before 5.10-5.33 ms/op 7.8 KB/op 82 allocs/op after 0.64 us/op 352 B/op 5 allocs/op Test: TestNoteServedWritesBehind notes 200 answers and checks the file is untouched, LastServed has the latest at once, FlushServed writes it once (a second flush writes nothing), merged with another gateway's entry, and that the timer writes it by itself. Broken by hand (origin/main's served.go with stubs for the new names): red, "written on a request answered", and the 200 notes took 1.04s. Run: go test ./internal/provider -run 'TestNoteServedWritesBehind|TestQuotasLastServed|TestCardsLastServed'; ./internal/gateway -run TestQuotasLastServedAt; ./internal/cli -run 'TestQuotaJSONLastServedAt|Signal'; ./internal/gui -run TestServedMovedWakesTheMenuBar: ok. The full suite run is in the last commit of this series. --- internal/cli/signals.go | 2 + internal/gateway/gateway.go | 1 + internal/provider/served.go | 52 +++++++++++++++++++- internal/provider/served_test.go | 81 ++++++++++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 2 deletions(-) diff --git a/internal/cli/signals.go b/internal/cli/signals.go index f001214d6..adf313216 100644 --- a/internal/cli/signals.go +++ b/internal/cli/signals.go @@ -9,6 +9,7 @@ import ( "syscall" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/provider" ) // endProbesOnSignal: the probes magpie asks a CLI with lead a session of @@ -39,6 +40,7 @@ func endProbesOnSignal() { handled := s == os.Interrupt && interrupts.Load() > 0 proc.EndProbes() if !handled { + provider.FlushServed() // a gateway's last answers, noted and not yet written die(s) } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 30b879463..b5ac19456 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -591,6 +591,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error { defer cancel() srv.Shutdown(c) s.subscription.abortAll() + provider.FlushServed() // what answered last, kept for the next start and the CLI }() for { err := srv.Serve(ln) diff --git a/internal/provider/served.go b/internal/provider/served.go index bc26e92da..52a9fabe1 100644 --- a/internal/provider/served.go +++ b/internal/provider/served.go @@ -66,6 +66,7 @@ func servedOf(id string) string { func ours(path string) map[string]time.Time { if servedAt.path != path { servedAt.path, servedAt.m, servedAt.by = path, map[string]time.Time{}, map[string]string{} + servedFlush.pending = false // what was noted for the other file isn't this one's } return servedAt.m } @@ -85,7 +86,24 @@ func ServedID(p Provider) string { return p.ID } -// NoteServed records that p just answered a request, at at. +// servedFlushAfter is how long NoteServed waits before it writes the file: +// what is noted meanwhile goes in the same write, so a gateway answering +// many requests a second writes it once in a while, not once a request +// (a read, a write and a rename on every answer). A crash loses what was +// noted in that last moment; FlushServed, as the gateway ends, loses +// nothing. +var servedFlushAfter = 2 * time.Second + +// servedFlush is the write NoteServed has waiting, and the one being made. +var servedFlush struct { + sync.Mutex // one write of the file at a time + pending bool // a write is waiting (servedAt held to read or set it) + writes uint64 // the writes made, for tests +} + +// NoteServed records that p just answered a request, at at. The file +// follows within servedFlushAfter (FlushServed): this process's LastServed +// has it at once. func NoteServed(p Provider, at time.Time) { id := ServedID(p) path := servedPath() @@ -108,19 +126,49 @@ func NoteServed(p Provider, at time.Time) { moved = true servedAt.by[of] = id } + if !servedFlush.pending { + servedFlush.pending = true + time.AfterFunc(servedFlushAfter, func() { flushServed(path) }) + } +} + +// FlushServed writes what NoteServed noted and hasn't written yet: the +// gateway calls it as it ends. +func FlushServed() { flushServed(servedPath()) } + +// flushServed writes what this process noted to the file at path, merged +// with what the file holds (another gateway's), when path is still the one +// noted for: what a test noted under a HOME of its own isn't written into +// the next one's. +func flushServed(path string) { + servedFlush.Lock() + defer servedFlush.Unlock() + servedAt.Lock() + if !servedFlush.pending || servedAt.path != path { + servedAt.Unlock() + return + } + servedFlush.pending = false + mine := make(map[string]time.Time, len(servedAt.m)) + for k, t := range servedAt.m { + mine[k] = t + } + servedAt.Unlock() m := readServed(path) + now := time.Now() for k, t := range mine { if t.After(m[k]) { m[k] = t } } for k, t := range m { - if at.Sub(t) > servedKeep { + if now.Sub(t) > servedKeep { delete(m, k) } } if b, err := json.Marshal(m); err == nil && os.MkdirAll(filepath.Dir(path), 0o700) == nil { writeFileAtomic(path, b) + servedFlush.writes++ } } diff --git a/internal/provider/served_test.go b/internal/provider/served_test.go index b93c12d62..0012e55de 100644 --- a/internal/provider/served_test.go +++ b/internal/provider/served_test.go @@ -3,6 +3,7 @@ package provider import ( "encoding/json" "os" + "path/filepath" "strings" "testing" "time" @@ -24,6 +25,7 @@ func TestQuotasLastServed(t *testing.T) { NoteServed(Provider{ID: "codex", Account: &Account{Agent: "codex", User: "A@x.com"}}, now.Add(-time.Hour)) NoteServed(Provider{ID: "dk", Key: "sk-other-key-0002"}, now.Add(-time.Minute)) NoteServed(Provider{ID: "solo", Key: "sk-solo"}, now.Add(-2*time.Hour)) + FlushServed() // as the gateway ending writes it // the CLI is a process of its own: what it is told is read from the file servedAt.Lock() servedAt.m = map[string]time.Time{} @@ -95,3 +97,82 @@ func TestCardsLastServed(t *testing.T) { t.Errorf("json %s", b) } } + +// A request answered isn't a read and a write of served.json: what is +// noted is written once, within servedFlushAfter, however many requests +// were answered meanwhile, or as the gateway ends (FlushServed); the file +// is as it was, merged with what another gateway wrote, and this process +// tells what it noted at once. +func TestNoteServedWritesBehind(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + now := time.Now().Truncate(time.Second) + // another gateway's, already in the file + if err := os.MkdirAll(filepath.Dir(servedPath()), 0o700); err != nil { + t.Fatal(err) + } + other, _ := json.Marshal(map[string]time.Time{"other#k1": now.Add(-time.Hour)}) + if err := os.WriteFile(servedPath(), other, 0o600); err != nil { + t.Fatal(err) + } + servedFlush.Lock() + writes := servedFlush.writes + servedFlush.Unlock() + key := "dk#" + KeyID("sk-key-0001") + for i := range 200 { + NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Duration(i)*time.Millisecond)) + } + if b, _ := os.ReadFile(servedPath()); string(b) != string(other) { + t.Fatalf("written on a request answered: %s", b) + } + if at := LastServed()[key]; !at.Equal(now.Add(199 * time.Millisecond)) { + t.Fatalf("this process isn't told at once: %v", LastServed()) + } + FlushServed() + FlushServed() // nothing new: no write + servedFlush.Lock() + n := servedFlush.writes - writes + servedFlush.Unlock() + if n != 1 { + t.Fatalf("%d writes for 200 answers", n) + } + b, err := os.ReadFile(servedPath()) + if err != nil { + t.Fatal(err) + } + var m map[string]time.Time + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err, string(b)) + } + if len(m) != 2 || !m["other#k1"].Equal(now.Add(-time.Hour)) || !m[key].Equal(now.Add(199*time.Millisecond)) { + t.Fatalf("file %s", b) + } + // and by itself, a moment later + defer func(d time.Duration) { servedFlushAfter = d }(servedFlushAfter) + servedFlushAfter = time.Millisecond + NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Second)) + for deadline := time.Now().Add(10 * time.Second); ; { + if b, _ := os.ReadFile(servedPath()); json.Unmarshal(b, &m) == nil && m[key].Equal(now.Add(time.Second)) { + break + } + if time.Now().After(deadline) { + t.Fatal("never written") + } + time.Sleep(5 * time.Millisecond) + } +} + +// BenchmarkNoteServed is what noting a request answered costs the request. +func BenchmarkNoteServed(b *testing.B) { + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + p := Provider{ID: "dk", Key: "sk-key-0001"} + for b.Loop() { + NoteServed(p, time.Now()) + } + FlushServed() +} From e1ebd173e81f2fc2a135ce154a3dff1e3c915f67 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:16:09 +0800 Subject: [PATCH 49/92] filememo: a file not there is, while a request holds what was read, not looked for again A provider with no live model list fetched has no live-models file, and each request asked after it for each of its models (Provider.Exposed -> ListedAPIs -> catalog.LiveByID -> readLive), each time an os.Stat that failed: in a CPU profile of a 30-provider, 60-model catalog, os.Stat was 32% of a request, nearly all of it this. A file found unchanged was already taken as unchanged for heldFor (1s) within a hold; a file found missing now is too, in the same generation of Forget. Forget (a write magpie makes), Look(path) (another's write), the hold's end, a second gone by, or a stat finding the file there drops it. Unheld, every read still looks. Numbers, BenchmarkGroupOverhead, 200KB body, stream=false, 100x each, binaries alternated twice (Apple M4 Pro, loaded by other sessions): before (cpu-ms/op, allocs) after 30x60 p0/m1 34.69 / 35.14 95126 32.87 / 31.84 89266 30x60 group/g4 44.33 / 43.88 115303 40.77 / 40.77 109071 12x20 p0/m1 15.75 / 16.30 42535 16.22 / 15.09 41645 12x20 group/g4 18.15 / 18.50 54138 18.16 / 17.76 53118 (about 7-8% of a request's CPU on the larger catalog; within noise on the small one, which has fewer missing files.) Test: TestHoldMissing: 100 held reads of a missing file make one stat; a file written meanwhile isn't seen until Forget, and is seen after Forget, after Look and after the release; unheld, 3 reads make 3 stats. Broken by hand (the missing check disabled): red, "100 looks at a file not there, held". Run: go test ./internal/filememo ./internal/catalog: ok. The full suite run is in the last commit of this series. --- internal/filememo/filememo.go | 29 ++++++++++++++++ internal/filememo/filememo_test.go | 55 ++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/internal/filememo/filememo.go b/internal/filememo/filememo.go index 6449e18e3..9c9a12f8d 100644 --- a/internal/filememo/filememo.go +++ b/internal/filememo/filememo.go @@ -44,8 +44,23 @@ var ( // on again (steady.Stat): one there before and not now may be being // replaced (Windows), and is gone = map[string]bool{} + // missing is the files found not there while a request held what was + // read, when, and in which of Forget's generations: taken as still + // not there as a file found unchanged is, not looked at again. A + // provider with no list fetched has no file of one, and a request + // asked after it for each of its models, each time a look at the disk + // (a third of a request's CPU with 30 providers of 60 models). + missing = map[string]missingFile{} + // stats counts the looks at the disk, for tests + stats int ) +type missingFile struct { + err error + checked time.Time + gen uint64 +} + // heldFor is how long a file found unchanged is taken as unchanged, while // a request holds what was read, before it is looked at again. const heldFor = time.Second @@ -86,6 +101,7 @@ func Look(path string) { seen[k] = e } } + delete(missing, path) } // Read is parse of the file at path, from what it gave last time when the @@ -101,10 +117,21 @@ func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) { mu.Unlock() return e.v.(T), nil } + if m, ok := missing[path]; ok && holds > 0 && m.gen == gen && time.Since(m.checked) < heldFor { + mu.Unlock() + return zero, m.err + } g := gen mu.Unlock() fi, err := statFile(path) if err != nil { + if errors.Is(err, fs.ErrNotExist) { + mu.Lock() + if holds > 0 && g == gen { + missing[path] = missingFile{err, time.Now(), g} + } + mu.Unlock() + } return zero, err } if ok && e.mod.Equal(fi.ModTime()) && e.size == fi.Size() && e.raw == nil { @@ -153,6 +180,7 @@ func Read[T any](kind, path string, parse func([]byte) (T, error)) (T, error) { func statFile(path string) (os.FileInfo, error) { mu.Lock() wasGone := gone[path] + stats++ mu.Unlock() var fi os.FileInfo var err error @@ -166,6 +194,7 @@ func statFile(path string) (os.FileInfo, error) { gone[path] = true } else { delete(gone, path) + delete(missing, path) } mu.Unlock() return fi, err diff --git a/internal/filememo/filememo_test.go b/internal/filememo/filememo_test.go index aee28c79a..f539abf41 100644 --- a/internal/filememo/filememo_test.go +++ b/internal/filememo/filememo_test.go @@ -96,3 +96,58 @@ func TestHold(t *testing.T) { t.Fatalf("a file written just now: %q", v) } } + +// A file not there is, while a request holds what was read, taken as +// still not there as a file found unchanged is: a provider with no list +// fetched was a look at the disk for each of its models, each request. A +// write magpie makes (Forget), another's (Look), or the hold's end has it +// looked at again; unheld, every read looks. +func TestHoldMissing(t *testing.T) { + p := filepath.Join(t.TempDir(), "none") + parse := func(b []byte) (string, error) { return string(b), nil } + looks := func() int { + mu.Lock() + defer mu.Unlock() + return stats + } + release := Hold() + before := looks() + for range 100 { + if _, err := Read("missing", p, parse); !os.IsNotExist(err) { + t.Fatalf("a file not there: %v", err) + } + } + if n := looks() - before; n != 1 { + t.Fatalf("%d looks at a file not there, held", n) + } + os.WriteFile(p, []byte("a"), 0o600) + if _, err := Read("missing", p, parse); !os.IsNotExist(err) { + t.Fatalf("looked at again while held: %v", err) + } + Forget() + if v, err := Read("missing", p, parse); v != "a" || err != nil { + t.Fatalf("after a write magpie made: %q %v", v, err) + } + os.Remove(p) + Read("missing", p, parse) + os.WriteFile(p, []byte("b"), 0o600) + Look(p) + if v, err := Read("missing", p, parse); v != "b" || err != nil { + t.Fatalf("after another's write: %q %v", v, err) + } + os.Remove(p) + Read("missing", p, parse) + release() + os.WriteFile(p, []byte("c"), 0o600) + if v, err := Read("missing", p, parse); v != "c" || err != nil { + t.Fatalf("released: %q %v", v, err) + } + os.Remove(p) + before = looks() + for range 3 { + Read("missing", p, parse) + } + if n := looks() - before; n != 3 { + t.Fatalf("unheld, %d looks for 3 reads", n) + } +} From 8fd74d15bfee60f1044e1aa5f505ce19875c6887 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 05:28:21 +0800 Subject: [PATCH 50/92] provider: retired.json is looked at on disk once a second, not on every request answered Every answered request asks Unretire (the gateway's servedCandidate), and each catalog built asks retiredNow; each was an os.Stat of retired.json under retired's lock. Only retired.go writes the file (writeRetired, for Retire and Unretire), and it keeps retired.at and the file's time current itself, so this process's own retirements are told at once. The file is now looked at again only after retiredLook (1s): another magpie's write is seen within it. A config path of its own (another HOME) is read at once, as before. Numbers (Apple M4 Pro, loaded by other sessions): BenchmarkUnretire before 98.8 us/op 640 B/op 5 allocs/op after 0.46 us/op 320 B/op 3 allocs/op Test: TestRetiredLooksOnceInAWhile: 200 Unretire+Retired calls look at the disk at most twice; Retire and Unretire are told at once; a write another magpie makes is seen once retiredLook passes; a new config path is read at once. Broken by hand (the throttle disabled): red, "400 looks at retired.json for 200 requests". Run: go test ./internal/provider -run TestRetiredLooksOnceInAWhile; ./internal/gateway -run 'Retired|Zen': ok. The full suite run is in the last commit of this series. --- internal/provider/retired.go | 16 +++++- internal/provider/retired_test.go | 85 +++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 internal/provider/retired_test.go diff --git a/internal/provider/retired.go b/internal/provider/retired.go index 7251aebb4..42cfe0619 100644 --- a/internal/provider/retired.go +++ b/internal/provider/retired.go @@ -33,8 +33,17 @@ var retired struct { at map[string]time.Time // "provider/model" → when the vendor said it is retired from string // the file read, and its time then mod time.Time + // checked is when the file was last looked at: within retiredLook it + // isn't looked at again. Every answered request asks Unretire, and a + // look at the disk each time was a stat per request; this process's + // own writes keep retired.at current, and another magpie's is seen + // within retiredLook. + checked time.Time + looks int // looks at the disk, for tests } +var retiredLook = time.Second + func retiredPath() string { return filepath.Join(filepath.Dir(Path()), "retired.json") } // readRetired brings retired.at up to the file, when the file changed since @@ -42,6 +51,11 @@ func retiredPath() string { return filepath.Join(filepath.Dir(Path()), "retired. // retired held. func readRetired() { path := retiredPath() + if path == retired.from && !retired.checked.IsZero() && time.Since(retired.checked) < retiredLook { + return + } + retired.looks++ + retired.checked = time.Now() fi, err := os.Stat(path) if err != nil { if path != retired.from { @@ -81,7 +95,7 @@ func writeRetired() { return } if fi, err := os.Stat(path); err == nil { - retired.from, retired.mod = path, fi.ModTime() + retired.from, retired.mod, retired.checked = path, fi.ModTime(), time.Now() } } diff --git a/internal/provider/retired_test.go b/internal/provider/retired_test.go new file mode 100644 index 000000000..363272459 --- /dev/null +++ b/internal/provider/retired_test.go @@ -0,0 +1,85 @@ +package provider + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +func retiredLooks() int { + retired.Lock() + defer retired.Unlock() + return retired.looks +} + +// Every answered request asks Unretire (the gateway's servedCandidate): +// retired.json isn't looked at on disk for each, only once in retiredLook. +// What this process retires or brings back is told at once, another +// magpie's write within retiredLook, and a config path of its own (a new +// HOME) is read at once. +func TestRetiredLooksOnceInAWhile(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + before := retiredLooks() + for range 200 { + Unretire("p", "m") + if Retired("p", "m") { + t.Fatal("retired out of nothing") + } + } + if n := retiredLooks() - before; n > 2 { + t.Fatalf("%d looks at retired.json for 200 requests", n) + } + Retire("p", "m") + if !Retired("p", "m") { + t.Fatal("this process's retirement isn't told at once") + } + Unretire("p", "m") + if Retired("p", "m") { + t.Fatal("this process's unretirement isn't told at once") + } + + // another magpie's write + defer func(d time.Duration) { retiredLook = d }(retiredLook) + retiredLook = 20 * time.Millisecond + b, _ := json.Marshal(map[string]time.Time{"p/other": time.Now()}) + if err := os.MkdirAll(filepath.Dir(retiredPath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(retiredPath(), b, 0o600); err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Minute) + os.Chtimes(retiredPath(), later, later) + for deadline := time.Now().Add(10 * time.Second); !Retired("p", "other"); time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("another magpie's write isn't seen") + } + } + + // a config of its own is read at once + home2 := t.TempDir() + t.Setenv("HOME", home2) + t.Setenv("USERPROFILE", home2) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + retiredLook = time.Hour + if Retired("p", "other") { + t.Fatal("another config's retirement told") + } +} + +// BenchmarkUnretire is what an answered request's Unretire costs it. +func BenchmarkUnretire(b *testing.B) { + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", b.TempDir()) + Retire("p", "x") + for b.Loop() { + Unretire("p", "m") + } +} From ae019defed238ab27069cd96c45fb48e4f6f8c18 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 07:40:53 +0800 Subject: [PATCH 51/92] provider: in a test binary served.json is written as an answer is noted, so no write outlives its test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 4f9e8331a wrote served.json 2s behind the answer. In a test binary that timer outlived the test that answered, and wrote into its temp HOME as testing removed it: BenchmarkGroupOverhead's first case failed 1 run in 6 with "TempDir RemoveAll cleanup: unlinkat …: directory not empty", and TestOTelSessionDedupOnlyUnkeyedLoopback failed the same way in a package run. servedFlushAfter is now 0 in a test binary (testing.Testing(), as partners.go already does), and NoteServed writes at once, after it lets go of servedAt, as it did before 4f9e8331a. TestNoteServedWritesBehind sets the 2s itself. Test: TestNoteServedInATestWritesAtOnce. Broken by hand (writeBehind returning d in a test binary too): red, "not written as the answer was noted: … served.json: no such file or directory". Run: go test ./internal/provider -run 'TestNoteServed|LastServed' -count 1: ok. BenchmarkGroupOverhead's 12x20 p0/m1 case, 6 runs of 100 requests before: 1 failed on the cleanup; see the next commits' records for the runs after. --- internal/provider/served.go | 24 ++++++++++++++++++++---- internal/provider/served_test.go | 26 +++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/internal/provider/served.go b/internal/provider/served.go index 52a9fabe1..c86700d75 100644 --- a/internal/provider/served.go +++ b/internal/provider/served.go @@ -15,6 +15,7 @@ import ( "strings" "sync" "sync/atomic" + "testing" "time" ) @@ -91,8 +92,18 @@ func ServedID(p Provider) string { // many requests a second writes it once in a while, not once a request // (a read, a write and a rename on every answer). A crash loses what was // noted in that last moment; FlushServed, as the gateway ends, loses -// nothing. -var servedFlushAfter = 2 * time.Second +// nothing. In a test binary it is 0, the file written at once, as it +// was: a write waiting outlived the test that noted it and wrote into its +// temp folder as the folder was being removed ("directory not empty"). +var servedFlushAfter = writeBehind(2 * time.Second) + +// writeBehind is d, or 0 in a test binary: no timer outlives a test. +func writeBehind(d time.Duration) time.Duration { + if testing.Testing() { + return 0 + } + return d +} // servedFlush is the write NoteServed has waiting, and the one being made. var servedFlush struct { @@ -108,9 +119,12 @@ func NoteServed(p Provider, at time.Time) { id := ServedID(p) path := servedPath() servedAt.Lock() - moved := false + moved, now := false, false defer func() { servedAt.Unlock() + if now { + flushServed(path) + } if moved { servedMoved() } @@ -128,7 +142,9 @@ func NoteServed(p Provider, at time.Time) { } if !servedFlush.pending { servedFlush.pending = true - time.AfterFunc(servedFlushAfter, func() { flushServed(path) }) + if now = servedFlushAfter <= 0; !now { + time.AfterFunc(servedFlushAfter, func() { flushServed(path) }) + } } } diff --git a/internal/provider/served_test.go b/internal/provider/served_test.go index 0012e55de..c99d15ae9 100644 --- a/internal/provider/served_test.go +++ b/internal/provider/served_test.go @@ -98,6 +98,29 @@ func TestCardsLastServed(t *testing.T) { } } +// In a test binary served.json is written as an answer is noted: a write +// left waiting outlived the test that noted it, and wrote into its temp +// folder as the folder was being removed (BenchmarkGroupOverhead failed +// "TempDir RemoveAll cleanup: … directory not empty"). +func TestNoteServedInATestWritesAtOnce(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + at := time.Now().Truncate(time.Second) + NoteServed(Provider{ID: "dk", Key: "sk-key-0002"}, at) + var m map[string]time.Time + if b, err := os.ReadFile(servedPath()); err != nil || json.Unmarshal(b, &m) != nil || !m["dk#"+KeyID("sk-key-0002")].Equal(at) { + t.Fatalf("not written as the answer was noted: %v %v", err, m) + } + servedFlush.Lock() + pending := servedFlush.pending + servedFlush.Unlock() + if pending { + t.Fatal("a write left waiting past the test") + } +} + // A request answered isn't a read and a write of served.json: what is // noted is written once, within servedFlushAfter, however many requests // were answered meanwhile, or as the gateway ends (FlushServed); the file @@ -117,6 +140,8 @@ func TestNoteServedWritesBehind(t *testing.T) { if err := os.WriteFile(servedPath(), other, 0o600); err != nil { t.Fatal(err) } + defer func(d time.Duration) { servedFlushAfter = d }(servedFlushAfter) + servedFlushAfter = 2 * time.Second // as outside a test binary servedFlush.Lock() writes := servedFlush.writes servedFlush.Unlock() @@ -150,7 +175,6 @@ func TestNoteServedWritesBehind(t *testing.T) { t.Fatalf("file %s", b) } // and by itself, a moment later - defer func(d time.Duration) { servedFlushAfter = d }(servedFlushAfter) servedFlushAfter = time.Millisecond NoteServed(Provider{ID: "dk", Key: "sk-key-0001"}, now.Add(time.Second)) for deadline := time.Now().Add(10 * time.Second); ; { From ed3a46d02b8e22358d27a4384c4b776813980c3b Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:09:31 +0800 Subject: [PATCH 52/92] provider: what a request built of the catalog stays for the next request within a second, not built again for each Hold dropped everything held when the last request let go, so one request after another built the catalog again from every provider's files and accounts (All, entries, the groups' entries, the settings): a fifth to a third of a request's CPU with 30 providers. What is built now stays until heldFor (1s) is past, as it already did for requests that overlapped. It is built again at once when anything it was built from may have moved: - Changed() and a plugin change (dropHeld), as before; - a write that only tells filememo (settings.Save, writePrivate, an agent's account file): held values carry filememo.Gen(), new here, and are dropped when it moved; - providers.json or settings.json written by another process (the CLI's "magpie group add"): the first Hold of a request stats both and drops what is held when either changed, so the next request sees it, not a second later; - the groups served or gated (GateGroups, ServeGroups): holdGate drops what is held on both changes (TestGroupsOnAndOff was red without it); - another environment (a test's HOME), by a hash of os.Environ(). Other files another process writes (an agent's own sign-in file) are seen within heldFor, as filememo already takes a file found unchanged. Tests: - TestHoldKeptForTheNextRequest: five requests one after another build once. Broken by hand (held.built = nil on the last release put back): red, "five requests one after another: built 5 times, want 1". - TestHoldKeptUntilAWrite: each of filememo.Forget, providers.json and settings.json written behind magpie's back, and GateGroups, builds again once. Broken by hand, one at a time: the Gen check off, red "filememo told: built 0 times, want 1"; the stat off, red "providers.json written by another process: built 0 times, want 1"; holdGate's dropHeld off, red "the groups gated: built 0 times, want 1". - TestRequestBuildsProvidersOnce now wants 1, 0, then 1 after Changed() (a request later than 0.9s after the first may rightly build again on a loaded machine; the test allows it). BenchmarkGroupOverhead (internal/gateway, 200KB Anthropic body, stream=false, 100x, two rounds alternating; load average ~450, so the cpu-ms/op it reports is the measure, not wall ns/op). base is 8215e8275: 12x20 p0/m1 base 25.66 / 24.36 cpu-ms/op 16.8MB 41723-41827 allocs this 22.13 / 20.67 cpu-ms/op 13.4MB 33771-33969 allocs 12x20 g4 base 30.59 / 30.68 cpu-ms/op 22.5MB 53213-53409 allocs this 25.91 / 25.60 cpu-ms/op 19.0MB 45213-45613 allocs 30x60 p0/m1 base 54.95 / 53.26 cpu-ms/op 42.5MB 89466-90023 allocs this 30.80 / 29.27 cpu-ms/op 23.0MB 45853-46928 allocs 30x60 g4 base 66.67 / 73.07 cpu-ms/op 68-70MB 112283-116845 allocs this 45.59 / 48.38 cpu-ms/op 49-52MB 68540-74905 allocs Run: go test ./internal/provider -run 'Hold|Group|Changed|Served' -count 1: ok (91s). go test ./internal/gateway -run '^(TestGroupsOnAndOff|TestRequestBuildsProvidersOnce)$' -count 1: ok. The full suite at the head of this series is in its last commit. --- internal/filememo/filememo.go | 9 ++ internal/gateway/request_builds_once_test.go | 25 ++++-- internal/provider/group_serve.go | 8 +- internal/provider/hold.go | 81 ++++++++++++++++- internal/provider/hold_test.go | 92 ++++++++++++++++++++ 5 files changed, 205 insertions(+), 10 deletions(-) diff --git a/internal/filememo/filememo.go b/internal/filememo/filememo.go index 9c9a12f8d..3623f57d3 100644 --- a/internal/filememo/filememo.go +++ b/internal/filememo/filememo.go @@ -9,6 +9,7 @@ import ( "os" "strings" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/steady" @@ -86,9 +87,17 @@ func Hold() (release func()) { func Forget() { mu.Lock() gen++ + gens.Store(gen) mu.Unlock() } +// gens is gen, read without mu. +var gens atomic.Uint64 + +// Gen is moved on by every Forget: what is built from files read here, and +// kept past one read, is built again when it moved. +func Gen() uint64 { return gens.Load() } + // Look has the file at path looked at on its next read, even while a // request holds what was read (Hold): another magpie may have written it, // which Forget, moved on by this one's writes alone, can't know of. diff --git a/internal/gateway/request_builds_once_test.go b/internal/gateway/request_builds_once_test.go index 290cd75d1..63ed12f7e 100644 --- a/internal/gateway/request_builds_once_test.go +++ b/internal/gateway/request_builds_once_test.go @@ -2,6 +2,7 @@ package gateway import ( "testing" + "time" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/provider" @@ -11,18 +12,32 @@ import ( // model up on its way: each build reads every agent's sign-in, every // plugin's and the settings, and three builds a request kept magpie at // 100–350% CPU under seven agents at once (#2502). The next request, -// nothing held between them, builds afresh. +// within a second and nothing written, builds none: one request after +// another built the providers again each time. After a write it builds +// once more. func TestRequestBuildsProvidersOnce(t *testing.T) { plugin.UseCached(nil) setup(t, provider.Chat, &fake{t: t, reply: sse(`{"choices":[{"delta":{"content":"hi"}}]}`, "[DONE]")}) - for i := range 2 { - n := provider.AllBuilt.Load() + var first time.Time + for i, want := range []int64{1, 0, 1} { + if i == 2 { + provider.Changed() // a provider saved + } + n, start := provider.AllBuilt.Load(), time.Now() + if i == 1 && start.Sub(first) > 900*time.Millisecond { + // what was built is held for a second: a request this late + // (a loaded machine) builds again, rightly + want = 1 + } + if i == 0 { + first = start + } code, body := post(t, "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`) if code != 200 { t.Fatalf("%d %s", code, body) } - if got := provider.AllBuilt.Load() - n; got != 1 { - t.Fatalf("request %d built the providers %d times, want 1", i+1, got) + if got := provider.AllBuilt.Load() - n; got != want { + t.Fatalf("request %d built the providers %d times, want %d", i+1, got, want) } } } diff --git a/internal/provider/group_serve.go b/internal/provider/group_serve.go index 60be9496a..9ae4c4ce7 100644 --- a/internal/provider/group_serve.go +++ b/internal/provider/group_serve.go @@ -55,19 +55,21 @@ func ServeGroups() (remove func()) { return holdGate(&groupGate.served) } -// holdGate holds n until the func it gives is called. Nothing built from -// the groups is kept past one call (only the file is, while a request -// holds it), so the next lookup sees the change. +// holdGate holds n until the func it gives is called. What is built from +// the groups and held across requests (heldOf) is dropped either way, so +// the next lookup sees the change. func holdGate(n *int) func() { groupGate.Lock() *n++ groupGate.Unlock() + dropHeld() var once sync.Once return func() { once.Do(func() { groupGate.Lock() *n-- groupGate.Unlock() + dropHeld() }) } } diff --git a/internal/provider/hold.go b/internal/provider/hold.go index 48b2736f7..52ced4f9e 100644 --- a/internal/provider/hold.go +++ b/internal/provider/hold.go @@ -1,6 +1,8 @@ package provider import ( + "hash/maphash" + "os" "slices" "sync" "time" @@ -22,6 +24,62 @@ var held struct { gen uint64 // what was built, and when, by what it is built map[string]heldValue + // env is the environment it was built in (environSum) + env uint64 + // fgen is filememo's generation it was built in: a write that only + // tells filememo (settings.Save, an account's file) has it built again + fgen uint64 + // roots is the providers' and the settings' files as last looked at + roots [2]rootStamp +} + +// rootStamp is a file's time and size, or that it wasn't there. +type rootStamp struct { + mod time.Time + size int64 + ok bool +} + +func stampOf(path string) rootStamp { + fi, err := os.Stat(path) + if err != nil { + return rootStamp{} + } + return rootStamp{fi.ModTime(), fi.Size(), true} +} + +// heldFreshLocked drops what is built when a file was written since, by +// this process (filememo.Gen) or, for the providers' and the settings' +// files, by another (the CLI's "magpie group add", seen by the next +// request, not a second later). Called with held held. +func heldFreshLocked(look bool) { + if g := filememo.Gen(); g != held.fgen { + held.built, held.fgen = nil, g + } + if !look { + return + } + for i, path := range [2]string{Path(), settings.Path()} { + if st := stampOf(path); st != held.roots[i] { + held.roots[i] = st + held.built = nil + filememo.Look(path) + } + } +} + +var environSeed = maphash.MakeSeed() + +// environSum is a hash of this process's environment: the folders every +// file and account is read from are named by it. +func environSum() uint64 { + var h maphash.Hash + h.SetSeed(environSeed) + for _, kv := range os.Environ() { + h.WriteString(kv) + h.WriteByte(0) + } + return h.Sum64() } type heldValue struct { @@ -47,18 +105,35 @@ func init() { // heldFor is how long a held catalog is used before it is built again, // while one request after another keeps it held. -const heldFor = time.Second +var heldFor = time.Second // Hold keeps the catalog built once until release is called, for a // request that only reads; a write meanwhile (Changed) drops it. func Hold() (release func()) { held.Lock() + if held.holds == 0 { + // what was built under another environment (a HOME or config + // folder of its own: a test's) isn't this one's + if env := environSum(); env != held.env { + held.built, held.env = nil, env + } + heldFreshLocked(true) + } held.holds++ held.Unlock() return sync.OnceFunc(func() { held.Lock() if held.holds--; held.holds == 0 { - held.built = nil + // what is built stays for the next request within heldFor, as + // it stays for one that overlaps this one: one request after + // another, each built the catalog again from every provider's + // files and accounts (a fifth of a request's CPU with 30 + // providers). Only what is past heldFor goes, for memory. + for k, h := range held.built { + if time.Since(h.at) >= heldFor { + delete(held.built, k) + } + } } held.Unlock() }) @@ -87,6 +162,7 @@ func heldOf[T any](key string, build func() T) T { held.Unlock() return build() } + heldFreshLocked(false) if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor { held.Unlock() return h.v.(T) @@ -140,6 +216,7 @@ func heldFrom[T any](key string, entries []Entry, build func([]Entry) T) T { held.Unlock() return build(entries) } + heldFreshLocked(false) if h, ok := held.built[key]; ok && time.Since(h.at) < heldFor { if f := h.v.(fromEntries[T]); f.at == at && f.n == len(entries) { held.Unlock() diff --git a/internal/provider/hold_test.go b/internal/provider/hold_test.go index a49a74824..a7124d289 100644 --- a/internal/provider/hold_test.go +++ b/internal/provider/hold_test.go @@ -7,8 +7,10 @@ import ( "slices" "strings" "testing" + "time" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/testenv" @@ -45,6 +47,96 @@ func TestHoldBuildsOnce(t *testing.T) { } } +// One request after another within heldFor builds the catalog once, as +// requests that overlap do: each built it again from every provider's +// files and accounts (a fifth of a request's CPU with 30 providers). A +// write between them (Changed), or another environment (a test's HOME), +// has it built again. +func TestHoldKeptForTheNextRequest(t *testing.T) { + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Minute // a loaded machine's pause between requests isn't the change + t.Setenv("MAGPIE_HOLD_TEST", "1") + n := 0 + build := func() int { n++; return n } + for range 5 { + release := Hold() + heldOf("t-next", build) + heldOf("t-next", build) + release() + } + if n != 1 { + t.Fatalf("five requests one after another: built %d times, want 1", n) + } + Changed() + func() { + defer Hold()() + if heldOf("t-next", build); n != 2 { + t.Fatalf("after a write: built %d times, want 2", n) + } + }() + t.Setenv("MAGPIE_HOLD_TEST", "2") + func() { + defer Hold()() + if heldOf("t-next", build); n != 3 { + t.Fatalf("in another environment: built %d times, want 3", n) + } + }() + if heldOf("t-next", build); n != 4 { + t.Fatalf("unheld: built %d times, want 4", n) + } +} + +// What is held across requests is built again when anything it was built +// from may have moved: a write that only tells filememo (settings.Save, an +// account's file), the providers' or the settings' file written by +// another process (the CLI's "magpie group add"), and the groups served +// or not (GateGroups, ServeGroups). +func TestHoldKeptUntilAWrite(t *testing.T) { + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Minute // a loaded machine's pause between requests isn't the change + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + n := 0 + build := func() int { n++; return n } + request := func() { + defer Hold()() + heldOf("t-write", build) + } + request() + request() + if n != 1 { + t.Fatalf("two requests: built %d times, want 1", n) + } + for _, c := range []struct { + what string + write func() + }{ + {"filememo told", filememo.Forget}, + {"providers.json written by another process", func() { + os.MkdirAll(filepath.Dir(Path()), 0o700) + os.WriteFile(Path(), []byte(`{"providers":[]}`), 0o600) + }}, + {"settings.json written by another process", func() { + os.MkdirAll(filepath.Dir(settings.Path()), 0o700) + os.WriteFile(settings.Path(), []byte(`{}`), 0o600) + }}, + {"the groups gated", func() { GateGroups(nil)() }}, + } { + was := n + c.write() + request() + if n != was+1 { + t.Fatalf("%s: built %d times, want 1", c.what, n-was) + } + request() + if n != was+1 { + t.Fatalf("%s, then a request: built again", c.what) + } + } +} + // A change the plugin host tells (a sign-in saved, a plugin added) drops // what a request holds before it returns: a SyncCatalog running held the // plugins as they were before `magpie plugin login` saved its account, From a1118187b5c94819775899ff0ad58833e27cc3d7 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:46:04 +0800 Subject: [PATCH 53/92] gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer answered() (and unanswered()) called saveSticks on every request answered: up to 512 conversations sorted, marshalled, written to a temp file and renamed, one answer after another under sticksSaving. Now the stick is in memory at once (stickOf reads the map first) and the file follows within sticksFlushAfter (2s): what is answered meanwhile goes in one write. The gateway's drain (ListenAndServe) and magpie ending on a signal (cli/signals.go, beside FlushServed) write what is waiting, so a restart or the magpie handed over to reads every answer. A crash loses the last 2s, as served.json does since 4f9e8331a. In a test binary the wait is 0 and the file is written at once, as it was (no timer outlives a test; 8215e8275 did the same for served.json). A write waiting for another HOME's file (a test's) is dropped, not written into this one. Test: TestSticksWrittenBehind (2s set by the test): 200 answers write no file, the last is known in memory, flushSticks writes all 200, and a short wait writes by itself. Broken by hand (noteSticks calling saveSticks always): red, "affinity.json written on a request answered". BenchmarkAnswered (512 sticks kept, 200x, 2 runs; load average ~450): old (saveSticks inline) 21.3 / 25.0 ms/op 506KB/op 2140 allocs/op new 2.5 / 5.6 us/op 392-434B/op 8 allocs/op Run: go test ./internal/gateway -run '^TestSticksWrittenBehind$' -count 1: ok. go test ./internal/gateway -run 'TestSticksWrittenBehind|Affinity| Sealed|Stick|Strict' -count 1: ok (57.8s). --- internal/cli/signals.go | 2 + internal/gateway/affinity.go | 73 ++++++++++++++++- .../gateway/affinity_write_behind_test.go | 79 +++++++++++++++++++ internal/gateway/gateway.go | 1 + 4 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/affinity_write_behind_test.go diff --git a/internal/cli/signals.go b/internal/cli/signals.go index adf313216..d27102608 100644 --- a/internal/cli/signals.go +++ b/internal/cli/signals.go @@ -8,6 +8,7 @@ import ( "sync/atomic" "syscall" + "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" ) @@ -41,6 +42,7 @@ func endProbesOnSignal() { proc.EndProbes() if !handled { provider.FlushServed() // a gateway's last answers, noted and not yet written + gateway.FlushSticks() // and who answered which conversation die(s) } } diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 2e6508318..4352c4d6f 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -36,6 +36,7 @@ import ( "slices" "strings" "sync" + "testing" "time" "github.com/yetone/magpie/internal/edit" @@ -141,6 +142,69 @@ var sticks = struct { // sticksSaving keeps one write of the file at a time, the latest last. var sticksSaving sync.Mutex +// sticksFlushAfter is how long a conversation answered waits before the +// file is written: what is answered meanwhile goes in the same write, so a +// gateway answering many requests a second writes it once in a while, not +// once a request (up to 512 conversations marshalled, written and renamed +// on every answer, each after the last). A crash loses the last moment's; +// flushSticks, as the gateway ends, loses nothing. In a test binary it is +// 0, the file written at once, as it was: a write left waiting would +// outlive the test and write into its temp folder as it is removed. +var sticksFlushAfter = func() time.Duration { + if testing.Testing() { + return 0 + } + return 2 * time.Second +}() + +// sticksFlush is the write noteSticks has waiting, for the file at path. +var sticksFlush struct { + sync.Mutex + pending bool + path string +} + +// noteSticks has the file written within sticksFlushAfter: what this +// magpie answered is in memory at once. +func noteSticks() { + if sticksFlushAfter <= 0 { + saveSticks() + return + } + path := sticksPath() + sticksFlush.Lock() + if sticksFlush.pending && sticksFlush.path == path { + sticksFlush.Unlock() + return + } + sticksFlush.pending, sticksFlush.path = true, path + sticksFlush.Unlock() + time.AfterFunc(sticksFlushAfter, func() { flushSticksAt(path) }) +} + +// flushSticks writes what noteSticks has waiting: the gateway calls it as +// it ends, so the magpie it hands over to, or the next start, reads it. +func flushSticks() { flushSticksAt(sticksPath()) } + +// FlushSticks is flushSticks, for magpie ending on a signal before the +// gateway's own end. +func FlushSticks() { flushSticks() } + +// flushSticksAt writes the file at path when a write for it is waiting: +// one waiting for another (a test's HOME before this one's) is dropped. +func flushSticksAt(path string) { + sticksFlush.Lock() + if !sticksFlush.pending || sticksFlush.path != path { + sticksFlush.Unlock() + return + } + sticksFlush.pending = false + sticksFlush.Unlock() + if path == sticksPath() { + saveSticks() + } +} + // savedStick is a stick as the file has it. type savedStick struct { Rest string `json:"rest"` @@ -201,6 +265,11 @@ func stickOf(key string) (stick, bool) { func saveSticks() { sticksSaving.Lock() defer sticksSaving.Unlock() + sticksFlush.Lock() + if sticksFlush.path == sticksPath() { + sticksFlush.pending = false // this write is the one waiting + } + sticksFlush.Unlock() now := time.Now() type kept struct { k string @@ -600,7 +669,7 @@ func answered(key string, c candidate, turn int, u Usage) { } } sticks.Unlock() - saveSticks() + noteSticks() } // unanswered forgets that c answered a conversation, when its reply to it @@ -626,7 +695,7 @@ func unanswered(key string, c candidate) { } sticks.Unlock() if ok { - saveSticks() + noteSticks() } } diff --git a/internal/gateway/affinity_write_behind_test.go b/internal/gateway/affinity_write_behind_test.go new file mode 100644 index 000000000..2ff7c90b6 --- /dev/null +++ b/internal/gateway/affinity_write_behind_test.go @@ -0,0 +1,79 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Who answered a conversation is written to affinity.json behind the +// answer, once in a while: each answer marshalled up to 512 conversations +// and wrote and renamed the file, one answer after another. +func TestSticksWrittenBehind(t *testing.T) { + fresh(t) + was := sticksFlushAfter + sticksFlushAfter = 2 * time.Second // as outside a test binary + t.Cleanup(func() { flushSticks(); sticksFlushAfter = was }) + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + os.Remove(sticksPath()) + c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"} + for i := range 200 { + answered(fmt.Sprintf("conv-%d", i), c, 1, Usage{}) + } + if _, err := os.Stat(sticksPath()); err == nil { + t.Fatal("affinity.json written on a request answered") + } + sticks.Lock() + _, ok := stickOf("conv-199") + sticks.Unlock() + if !ok { + t.Fatal("the last answer isn't known in memory") + } + flushSticks() // as the gateway ends + b, err := os.ReadFile(sticksPath()) + if err != nil { + t.Fatalf("not written as the gateway ends: %v", err) + } + var saved map[string]savedStick + if err := json.Unmarshal(b, &saved); err != nil || len(saved) != 200 { + t.Fatalf("written %d conversations (%v), want 200", len(saved), err) + } + + // and by itself, a moment later + sticksFlushAfter = 10 * time.Millisecond + os.Remove(sticksPath()) + answered("conv-late", c, 1, Usage{}) + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if b, err := os.ReadFile(sticksPath()); err == nil && json.Unmarshal(b, &saved) == nil && saved["conv-late"].Who != "" { + break + } + if time.Now().After(deadline) { + t.Fatal("an answer never written") + } + } +} + +func BenchmarkAnswered(b *testing.B) { + was := sticksFlushAfter + sticksFlushAfter = 2 * time.Second // as outside a test binary + b.Cleanup(func() { flushSticks(); sticksFlushAfter = was }) + sticks.Lock() + sticks.m = map[string]stick{} + for i := range sticksKept { + sticks.m[fmt.Sprintf("conv-%d", i)] = stick{rest: "a", who: "a#k", model: "m", turn: 3, at: time.Now()} + } + sticks.Unlock() + c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"} + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + answered(fmt.Sprintf("conv-%d", i%sticksKept), c, 3, Usage{Input: 100}) + } + b.StopTimer() + flushSticks() +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b5ac19456..a0f248abf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -592,6 +592,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error { srv.Shutdown(c) s.subscription.abortAll() provider.FlushServed() // what answered last, kept for the next start and the CLI + flushSticks() // who answered which conversation, for the next start or the magpie handed over to }() for { err := srv.Serve(ln) From 2a27fb8da8fb0d50e35a2f65effdf2330c8accdc Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 08:50:47 +0800 Subject: [PATCH 54/92] gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit attempt() asked searchAsked first, on every relayed request, and only then whether the provider searches by itself. searchAsked looked for three words with strings.Contains(string(body), …), each conversion a copy of the whole body (a 211KB body: ~640KB and ms a request), and a body offering web_search was then parsed whole: Codex offers it on every turn, so each relayed Codex turn was parsed only to be told "Codex searches by itself". searchedForIt now asks what is known of the provider and model first, and searchAsked looks with bytes.Contains. The same copy in the siblings that look at an error body (fallback.passing, patience.busy, routing.failure's insufficient_quota) goes too. lan.go's and the lower-cased look-ups in gateway.go need the string they make and are left as they are. Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the old order put back): red, "a 211KB body with no search in it: 3 allocations, want 0" and "a provider that searches by itself: 29 allocations, the body parsed". BenchmarkSearchedForIt (211KB Responses body; load average ~450): codex-asks old 2.55-5.02 ms/op 665KB/op 29-30 allocs/op new 0.1-1.9 us/op 0B/op 0 allocs/op other-plain old 1.6-4.8 ms/op 663KB/op 3 allocs/op new 0.26-1.15 ms/op 0B/op 0 allocs/op Run: go test ./internal/gateway -run 'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy| Passing|Failure|Credit|Quota' -count 1: ok (140s). --- internal/gateway/fallback.go | 2 +- internal/gateway/gateway.go | 2 +- internal/gateway/patience.go | 4 +-- internal/gateway/routing.go | 4 +-- internal/gateway/search.go | 14 +++++++++- internal/gateway/search_test.go | 46 +++++++++++++++++++++++++++++++++ 6 files changed, 65 insertions(+), 7 deletions(-) diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index c34871b28..b8e991c30 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1354,7 +1354,7 @@ func passing(status int, header http.Header, body []byte, again int) (time.Durat case wait > longestPause: return 0, false case status == 408, status == 500, status == 502, status == 503, status == 504, status == 529: - if strings.Contains(string(body), didNotStream) { + if bytes.Contains(body, []byte(didNotStream)) { return 0, false } return wait, again < lastRetries diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a0f248abf..0f7a3f52d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3539,7 +3539,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P ownAPI := false // except a subagent's task its lead sealed (#1109): only the server // that sealed it reads it, and a translation would drop it - if relay && searchAsked(from, body) && (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && !(from == provider.Responses && hasSealedAgentMessage(body)) { + if relay && searchedForIt(p, from, model, body) && !(from == provider.Responses && hasSealedAgentMessage(body)) { relay, ownAPI = false, true } // Copilot seals an argument the tools mark "encrypted" (spawn_agent's diff --git a/internal/gateway/patience.go b/internal/gateway/patience.go index b66c71281..8c5fe4394 100644 --- a/internal/gateway/patience.go +++ b/internal/gateway/patience.go @@ -1,10 +1,10 @@ package gateway import ( + "bytes" "context" "net/http" "slices" - "strings" "time" "github.com/yetone/magpie/internal/provider" @@ -59,7 +59,7 @@ func busy(status int, body []byte) bool { switch status { case 408, 500, 502, 503, 504, 529: return failure(status, body) == failOther && !protectionRefused(status, body) && - !strings.Contains(string(body), didNotStream) + !bytes.Contains(body, []byte(didNotStream)) case 429: return failure(status, body) == failRate && !creditWords.Match(wordsOf(body)) } diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 1d81d5708..04123b3c1 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -297,14 +297,14 @@ func failure(status int, body []byte) string { // Kimi's "exceeded model token limit" is the conversation's // length, not the plan's return failOther - case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !strings.Contains(string(body), "insufficient_quota"): + case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !bytes.Contains(body, []byte("insufficient_quota")): // a 402 that says a usage limit and nothing of money is out of // quota, not of credit: Factory's "You've reached your weekly // standard usage limit (resets in …). Switch to Droid Core …" is // Standard's pool, which counts some models only, and read as the // account out of credit it rested Droid Core with it (#1979) return failQuota - case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)) || strings.Contains(string(body), "insufficient_quota"): + case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)) || bytes.Contains(body, []byte("insufficient_quota")): return failCredit case status == 429 && resetsWhen.Match(body): // out until the time it names, in whichever language it said so: diff --git a/internal/gateway/search.go b/internal/gateway/search.go index c5c53389e..ce5f6d256 100644 --- a/internal/gateway/search.go +++ b/internal/gateway/search.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "cmp" "context" "encoding/json" @@ -215,13 +216,24 @@ var searchHosts = map[provider.Protocol][]string{ // searchAsked is whether a body offers the model web search, looked for // cheaply before it is parsed. func searchAsked(proto provider.Protocol, body []byte) bool { - if !strings.Contains(string(body), "web_search") && !strings.Contains(string(body), "oogle_search") && !strings.Contains(string(body), "googleSearch") { + // bytes, not string(body): each conversion copied the whole body, three + // times a request (a 200KB body: 640KB and 3ms) + if !bytes.Contains(body, []byte("web_search")) && !bytes.Contains(body, []byte("oogle_search")) && !bytes.Contains(body, []byte("googleSearch")) { return false } req, err := parse(proto, body) return err == nil && req.WebSearch } +// searchedForIt is whether a relayed request's web search is done by magpie +// for the provider, which can't be relayed: a body offering it to a model +// that doesn't search by itself. What is known of the provider is asked +// first: Codex offers web_search on every turn, and each relayed turn was +// parsed whole to learn it, for a provider that searches by itself. +func searchedForIt(p provider.Provider, from provider.Protocol, model string, body []byte) bool { + return (from == provider.Chat && !p.IsRemoteMagpie() || !searchesModel(p, from, model)) && searchAsked(from, body) +} + // searcher is the model magpie searches with: the one Settings names, while // it can (chosenSearcher), else the first of the providers that search by // themselves, with a small model of theirs, as searching needs no more. diff --git a/internal/gateway/search_test.go b/internal/gateway/search_test.go index 9057f5412..84bf1da2d 100644 --- a/internal/gateway/search_test.go +++ b/internal/gateway/search_test.go @@ -656,3 +656,49 @@ func TestPluginSaidToSearch(t *testing.T) { }) } } + +// A request's body is looked at for web search without a copy of it, and +// not parsed at all for a provider that searches by itself: Codex offers +// web_search on every turn, and each relayed turn was parsed whole. +func TestSearchAskedLooksCheaply(t *testing.T) { + long := strings.Repeat("a long prompt with words in it ", 7000) + plain := []byte(`{"model":"m","input":"` + long + `"}`) + if n := testing.AllocsPerRun(20, func() { searchAsked(provider.Responses, plain) }); n != 0 { + t.Errorf("a %dKB body with no search in it: %v allocations, want 0", len(plain)/1024, n) + } + asks := []byte(`{"model":"gpt-5","input":"` + long + `","tools":[{"type":"web_search"}]}`) + codex := provider.Provider{ID: "codex", Responses: provider.CodexBase, Account: &provider.Account{Agent: "codex"}} + if searchedForIt(codex, provider.Responses, "gpt-5", asks) { + t.Error("Codex searches by itself, and magpie searched for it") + } + if n := testing.AllocsPerRun(20, func() { searchedForIt(codex, provider.Responses, "gpt-5", asks) }); n > 20 { + t.Errorf("a provider that searches by itself: %v allocations, the body parsed", n) + } + other := provider.Provider{ID: "x", Responses: "https://example.test/v1"} + if !searchedForIt(other, provider.Responses, "gpt-5", asks) { + t.Error("a provider that doesn't search: magpie didn't search for it") + } + if searchedForIt(other, provider.Responses, "gpt-5", plain) { + t.Error("a body offering no search: magpie searched for it") + } +} + +func BenchmarkSearchedForIt(b *testing.B) { + long := strings.Repeat("a long prompt with words in it ", 7000) + asks := []byte(`{"model":"gpt-5","input":"` + long + `","tools":[{"type":"web_search"}]}`) + plain := []byte(`{"model":"gpt-5","input":"` + long + `"}`) + codex := provider.Provider{ID: "codex", Responses: provider.CodexBase, Account: &provider.Account{Agent: "codex"}} + other := provider.Provider{ID: "x", Responses: "https://example.test/v1"} + b.Run("codex-asks", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + searchedForIt(codex, provider.Responses, "gpt-5", asks) + } + }) + b.Run("other-plain", func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + searchedForIt(other, provider.Responses, "gpt-5", plain) + } + }) +} From ec6fba472050f6bf2c9c633afe28ece8534cf001 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 09:13:04 +0800 Subject: [PATCH 55/92] gateway: a long body's top level is split at its members once, not by each decode of it decodeJSON remembered that a body of 32KB or more was valid (validMemo), but each decode of it still walked every byte of the conversation to find its members: a request's readers (the model and stream flag, the metadata, max tokens, the messages, the tools...) decode the same body a dozen times, each into a few members. Where the top level's members are is now remembered with the body's validity (longBody), and fillJSON fills a struct or map at the top from those spans; a member the type doesn't want is passed over without a walk. A body under 32KB, or one not an object, is decoded as before. Test: TestDecodeJSONSplitsALongBodyOnce: 20 decodes of one long body into five types (a struct, a slice inside one, a pointer, a map of RawMessage, a nested struct) split it once, and each gets what encoding/json gives. Broken by hand (members never remembered): red, "split 21 times over 20 decodes, want 1". BenchmarkDecodeReaders (one 200KB body decoded into three small structs, as a request's readers do; -test.cpu 1, user+sys CPU of the whole binary, 3000 iterations minus a 30-iteration run, two rounds; load average ~450, so CPU time, not wall ns/op): before 1.26 / 1.25 s (0.09-0.11 s at 30) ~383 us per request's three decodes after 0.26 / 0.26 s (0.07-0.11 s at 30) ~57 us Allocations are unchanged (25 allocs, ~358B per iteration). BenchmarkGroupOverhead's 200KB request moved within its noise (12x20 p0/m1 22.16 -> 19.30/21.45 cpu-ms/op; 30x60 g4 43.22/48.49 -> 43.86/45.24). Run: go test ./internal/gateway -run 'JSON|Json|Decode|Fill|Memo' -count 1: ok (23.5s). --- internal/gateway/fastjson.go | 119 ++++++++++++++++-- internal/gateway/fastjson_memo_test.go | 58 +++++++++ internal/gateway/fastjson_split_bench_test.go | 35 ++++++ 3 files changed, 201 insertions(+), 11 deletions(-) create mode 100644 internal/gateway/fastjson_split_bench_test.go diff --git a/internal/gateway/fastjson.go b/internal/gateway/fastjson.go index f6b18fa3f..b9f4acf0a 100644 --- a/internal/gateway/fastjson.go +++ b/internal/gateway/fastjson.go @@ -38,7 +38,16 @@ import ( // of its own (a slice's old elements are decoded over, not replaced). func decodeJSON(data []byte, dst any) error { v := reflect.ValueOf(dst) - if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() || !jsonValid(data) { + if v.Kind() != reflect.Pointer || v.IsNil() || !v.Elem().IsZero() { + return json.Unmarshal(data, dst) + } + var members []memberSpan + if len(data) >= validMemoMin { + var valid bool + if valid, members = longBody(data); !valid { + return json.Unmarshal(data, dst) + } + } else if !jsonCheck(data) { return json.Unmarshal(data, dst) } start := skipJSONSpace(data, 0) @@ -49,7 +58,7 @@ func decodeJSON(data []byte, dst any) error { // of the value's opening and its close. return json.Unmarshal(append(data[:start+1:start+1], close), dst) } - if err := fillJSON(trimJSON(data), v.Elem()); err != nil { + if err := fillJSONIn(trimJSON(data), v.Elem(), members); err != nil { v.Elem().SetZero() return json.Unmarshal(data, dst) } @@ -170,7 +179,11 @@ func (f *fastFields) field(key []byte) int { // fillJSON decodes raw, a whole valid JSON value, into v; errSlowJSON or // another error leaves it to encoding/json. -func fillJSON(raw []byte, v reflect.Value) error { +func fillJSON(raw []byte, v reflect.Value) error { return fillJSONIn(raw, v, nil) } + +// fillJSONIn is fillJSON with where raw's members are, when known +// (longBody): a struct or map at raw's top is filled from them. +func fillJSONIn(raw []byte, v reflect.Value, members []memberSpan) error { t := v.Type() if t == rawMessageType { v.SetBytes(bytes.Clone(raw)) // a copy, as encoding/json makes @@ -193,7 +206,7 @@ func fillJSON(raw []byte, v reflect.Value) error { if v.IsNil() { v.Set(reflect.New(t.Elem())) } - return fillJSON(raw, v.Elem()) + return fillJSONIn(raw, v.Elem(), members) case reflect.String: if null { return nil @@ -231,7 +244,7 @@ func fillJSON(raw []byte, v reflect.Value) error { } var seen []bool var err error - eachMember(raw, func(key, val []byte) bool { + eachMemberIn(raw, members, func(key, val []byte) bool { name, ok := unquoteJSON(key) if !ok { err = errSlowJSON @@ -292,7 +305,7 @@ func fillJSON(raw []byte, v reflect.Value) error { v.Set(reflect.MakeMap(t)) } var err error - eachMember(raw, func(key, val []byte) bool { + eachMemberIn(raw, members, func(key, val []byte) bool { name, ok := unquoteJSON(key) if !ok { err = errSlowJSON @@ -353,6 +366,29 @@ func trimJSON(data []byte) []byte { // eachMember calls f with each member of obj, a valid JSON object, its key // still quoted, until f returns false. func eachMember(obj []byte, f func(key, val []byte) bool) { + eachMemberAt(obj, func(k0, k1, v0, v1 int) bool { return f(obj[k0:k1], obj[v0:v1:v1]) }) +} + +// eachMemberIn is eachMember, from where its members are when known +// (longBody), else by splitting obj. +func eachMemberIn(obj []byte, members []memberSpan, f func(key, val []byte) bool) { + if members == nil { + if h := topSplit.Load(); h != nil && len(obj) >= validMemoMin { + (*h)(obj) + } + eachMember(obj, f) + return + } + for _, m := range members { + if !f(obj[m.k0:m.k1], obj[m.v0:m.v1:m.v1]) { + return + } + } +} + +// eachMemberAt is eachMember by offsets: the key at [k0, k1), the value +// at [v0, v1). +func eachMemberAt(obj []byte, f func(k0, k1, v0, v1 int) bool) { i := skipJSONSpace(obj, 1) if obj[i] == '}' { return @@ -360,12 +396,12 @@ func eachMember(obj []byte, f func(key, val []byte) bool) { for { k := i i = skipJSONString(obj, i) - key := obj[k:i] + k1 := i i = skipJSONSpace(obj, i) i = skipJSONSpace(obj, i+1) // ':' s := i i = skipJSONValue(obj, i) - if !f(key, obj[s:i:i]) { + if !f(k, k1, s, i) { return } i = skipJSONSpace(obj, i) @@ -575,7 +611,7 @@ const validMemoMin = 32 << 10 // seed of this process's own. var validMemo struct { sync.Mutex - sums [8]validSum + sums [8]validEntry next int } @@ -584,6 +620,67 @@ type validSum struct { sum uint64 } +// validEntry is a body remembered valid, and where its top level's +// members are, once a decode has split it (nil before, and for a body not +// an object). +type validEntry struct { + validSum + members []memberSpan +} + +// memberSpan is a member of a body's top-level object: its key, quoted, +// at [k0, k1) and its value at [v0, v1), of the body trimmed (trimJSON). +type memberSpan struct{ k0, k1, v0, v1 int } + +// topSplit, when set (tests), is told of each object of validMemoMin or +// more that decodeJSON splits at its members. +var topSplit atomic.Pointer[func(data []byte)] + +// longBody is what decodeJSON knows of a body of validMemoMin or more: +// valid or not, and where its top level's members are. The members are +// remembered with the body, as its validity is: a request's body was split +// at its top level again by each of the dozen decodes it went through, +// each a walk over every byte of the conversation. +func longBody(data []byte) (valid bool, members []memberSpan) { + s := validSum{len(data), maphash.Bytes(validSeed, data)} + validMemo.Lock() + i := slices.IndexFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }) + if i >= 0 && validMemo.sums[i].members != nil { + members = validMemo.sums[i].members + validMemo.Unlock() + return true, members + } + validMemo.Unlock() + if i < 0 { + if f := validScanned.Load(); f != nil { + (*f)(data) + } + if !jsonCheck(data) { + return false, nil + } + } + raw := trimJSON(data) + if raw[0] == '{' { + if f := topSplit.Load(); f != nil { + (*f)(data) + } + members = []memberSpan{} + eachMemberAt(raw, func(k0, k1, v0, v1 int) bool { + members = append(members, memberSpan{k0, k1, v0, v1}) + return true + }) + } + validMemo.Lock() + if i = slices.IndexFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }); i >= 0 { + validMemo.sums[i].members = members + } else { + validMemo.sums[validMemo.next] = validEntry{s, members} + validMemo.next = (validMemo.next + 1) % len(validMemo.sums) + } + validMemo.Unlock() + return true, members +} + var validSeed = maphash.MakeSeed() // validScanned, when set (tests), is told of each body of validMemoMin or @@ -599,7 +696,7 @@ func jsonValid(data []byte) bool { } s := validSum{len(data), maphash.Bytes(validSeed, data)} validMemo.Lock() - known := slices.Contains(validMemo.sums[:], s) + known := slices.ContainsFunc(validMemo.sums[:], func(e validEntry) bool { return e.validSum == s }) validMemo.Unlock() if known { return true @@ -611,7 +708,7 @@ func jsonValid(data []byte) bool { return false } validMemo.Lock() - validMemo.sums[validMemo.next] = s + validMemo.sums[validMemo.next] = validEntry{validSum: s} validMemo.next = (validMemo.next + 1) % len(validMemo.sums) validMemo.Unlock() return true diff --git a/internal/gateway/fastjson_memo_test.go b/internal/gateway/fastjson_memo_test.go index 52e9189b0..4e1f8d70d 100644 --- a/internal/gateway/fastjson_memo_test.go +++ b/internal/gateway/fastjson_memo_test.go @@ -2,6 +2,7 @@ package gateway import ( "bytes" + "encoding/json" "strings" "sync/atomic" "testing" @@ -45,6 +46,63 @@ func TestDecodeJSONChecksALongBodyOnce(t *testing.T) { } } +// A long body's top level is split at its members once, not by each decode +// of it: each reader of a request (the model, the stream flag, the +// messages, the tools…) walked every byte of the conversation again to +// find its member. What each is given is what encoding/json gives it. +func TestDecodeJSONSplitsALongBodyOnce(t *testing.T) { + body := []byte(`{"model":"` + t.Name() + `","stream":true,"max_tokens":9,"messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt ", 6000) + `"}],"metadata":{"user_id":"u"}}`) + var n atomic.Int32 + f := func(data []byte) { + if bytes.Equal(data, body) { + n.Add(1) + } + } + topSplit.Store(&f) + t.Cleanup(func() { topSplit.Store(nil) }) + type msgs struct { + Messages []struct { + Role string `json:"role"` + Content string `json:"content"` + } `json:"messages"` + } + for range 4 { + var a struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + var b msgs + var c *msgs + var d map[string]json.RawMessage + var e struct { + Metadata struct { + UserID string `json:"user_id"` + } `json:"metadata"` + Max int `json:"max_tokens"` + } + for _, dst := range []any{&a, &b, &c, &d, &e} { + if err := decodeJSON(body, dst); err != nil { + t.Fatal(err) + } + } + wa, wb, we := a, msgs{}, e + wa.Model, wa.Stream, we.Metadata.UserID, we.Max = "", false, "", 0 + var wd map[string]json.RawMessage + json.Unmarshal(body, &wa) + json.Unmarshal(body, &wb) + json.Unmarshal(body, &wd) + json.Unmarshal(body, &we) + if a != wa || len(b.Messages) != 1 || b.Messages[0] != wb.Messages[0] || c == nil || len(c.Messages) != 1 || + len(d) != len(wd) || string(d["messages"]) != string(wd["messages"]) || e != we { + t.Fatalf("decoded otherwise than encoding/json: %+v %+v %d %v", a, e, len(d), c == nil) + } + } + if got := n.Load(); got != 1 { + t.Fatalf("a %d-byte body's top level was split %d times over 20 decodes, want 1", len(body), got) + } +} + // What is remembered is a valid body: an invalid one, or a valid one // changed by a byte at the same length, is checked again and refused. func TestDecodeJSONMemoKeepsRefusing(t *testing.T) { diff --git a/internal/gateway/fastjson_split_bench_test.go b/internal/gateway/fastjson_split_bench_test.go new file mode 100644 index 000000000..9f3a5ed99 --- /dev/null +++ b/internal/gateway/fastjson_split_bench_test.go @@ -0,0 +1,35 @@ +package gateway + +import ( + "strings" + "testing" +) + +// BenchmarkDecodeReaders is a request's readers decoding one 200KB body, +// each into the few members it wants: the model and stream flag, the +// metadata, the max tokens. +func BenchmarkDecodeReaders(b *testing.B) { + body := []byte(`{"model":"claude-x","stream":true,"max_tokens":9,"messages":[{"role":"user","content":"` + + strings.Repeat("a long prompt with \\\"quotes\\\" and words ", 5000) + `"}],"metadata":{"user_id":"u"}}`) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + for b.Loop() { + var a struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + var e struct { + Metadata struct { + UserID string `json:"user_id"` + } `json:"metadata"` + } + var m struct { + Max int `json:"max_tokens"` + } + for _, dst := range []any{&a, &e, &m} { + if err := decodeJSON(body, dst); err != nil { + b.Fatal(err) + } + } + } +} From 627e8e7d958af2dbc624a108559827614622ee63 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 11:31:49 +0800 Subject: [PATCH 56/92] provider: a request's groups are built once under its Hold, not again by each look-up groupsIn read providers.json's groups, matched each pattern against every model and found the automatic groups over the whole catalog, and every caller did it again: a request to a group asks FindGroup for its route, members and window, and the group list, several times each. Under a Hold the built groups are now kept (heldFrom, keyed on the catalog's entries, dropped by a write as the other held values are), and each caller gets a deep copy (cloneGroups) so a change of its own, such as the TUI's edit before a failed save, never reaches the next. Tests: - TestGroupsBuiltOnceWhileHeld: 40 look-ups under one Hold build the groups 0 more times; a change to a returned group's members isn't the next caller's; a SaveGroup under the Hold is seen. Broken by hand (groupsIn built every time): red, "the groups were built 40 times more in 40 looks under one Hold, want 0". Without the copy: red, "a change to a held group's members reached the next caller" (and TestHeldGroupsAreTheCallers red too). - TestCloneGroupsSharesNothing fills every field of a Group and its Rules by reflection and fails on any slice, map or pointer the copy shares, so a field added later is caught. Broken by hand (Weights not cloned): red, "Group.Weights is shared with the held group". BenchmarkGroupLooksHeld (30 providers x 60 models, 4 FindGroup and 1 Groups under one Hold; -benchtime 200x, two rounds; load average ~450): before 13.8 / 23.9 ms/op 26.2MB/op 41080 allocs/op after 0.18 / 0.14 ms/op 310KB/op 413 allocs/op User+sys CPU of the binary, 300 iterations minus 3: before 4.5/4.2 s (~15 ms per request's look-ups), after 0.08/0.06 s (~0.2 ms). BenchmarkGroupOverhead (200KB, not streamed, 30x): allocs of a group request fell (30x60 g4 72.9K/75.0K -> 60.5K/75.8K, g1 70.9K/73.1K -> 62.4K/68.4K; 12x20 g4 46.1K/45.8K -> 43.7K/44.7K); cpu-ms/op moved within the noise of a machine at load ~450, where a request's wall time passes heldFor and the held values are built again. Run: go vet ./internal/provider; go test ./internal/provider -run 'Group|Hold|Held|Rule|Clone' -count 1: ok (17.0s); go test ./internal/gateway -run Group -count 1: ok (53.1s). --- internal/provider/group.go | 44 +++++++ internal/provider/group_held_test.go | 167 +++++++++++++++++++++++++++ 2 files changed, 211 insertions(+) diff --git a/internal/provider/group.go b/internal/provider/group.go index feba98c31..c83c686a0 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -28,6 +28,7 @@ import ( "regexp" "slices" "strings" + "sync/atomic" "time" "github.com/yetone/magpie/internal/catalog" @@ -351,7 +352,50 @@ func Groups() []Group { return groupsIn(providerEntries()) } +// groupsIn is the groups among entries (Groups), built once while a +// request holds the catalog: a request looked its group up by building +// every group again, matching each pattern and finding the automatic +// groups over every model (FindGroup, then the groups' entries). Each +// caller gets a copy of its own to change. func groupsIn(entries []Entry) []Group { + return cloneGroups(heldFrom("groups", entries, buildGroupsIn)) +} + +// cloneGroups is gs with nothing shared with it: no slice, map or pointer +// of a group or its rules. +func cloneGroups(gs []Group) []Group { + if gs == nil { + return nil + } + out := make([]Group, len(gs)) + for i, g := range gs { + g.Members, g.Match, g.Matched = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched) + g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast) + g.Weights = maps.Clone(g.Weights) + if g.Rules != nil { + rs := make([]Rule, len(g.Rules)) + for j, r := range g.Rules { + r.Agents, r.Folders, r.ExceptFolders = slices.Clone(r.Agents), slices.Clone(r.Folders), slices.Clone(r.ExceptFolders) + if r.Time != nil { + t := *r.Time + t.Days = slices.Clone(t.Days) + r.Time = &t + } + rs[j] = r + } + g.Rules = rs + } + out[i] = g + } + return out +} + +// groupsBuilt counts buildGroupsIn, for the test that a held request +// builds the groups once. +var groupsBuilt atomic.Int64 + +func buildGroupsIn(entries []Entry) []Group { + groupsBuilt.Add(1) f := heldOf("file", load) var out []Group hidden := map[string]bool{} diff --git a/internal/provider/group_held_test.go b/internal/provider/group_held_test.go index 819447c43..88828cdf7 100644 --- a/internal/provider/group_held_test.go +++ b/internal/provider/group_held_test.go @@ -3,7 +3,9 @@ package provider import ( "fmt" "path/filepath" + "reflect" "testing" + "time" "github.com/yetone/magpie/internal/settings" ) @@ -134,3 +136,168 @@ func BenchmarkGroupEntries(b *testing.B) { buildGroupEntries(entries) } } + +// A request to a group looked its group up through FindGroup and the +// other group readers, and each built every group again: reading +// providers.json's groups, matching each pattern against every model and +// finding the automatic groups over the catalog. While a request holds the +// catalog the groups are built once, and each caller gets its own copy. +func TestGroupsBuiltOnceWhileHeld(t *testing.T) { + groupHeldFixture(t) + release := Hold() + defer release() + Groups() + before := groupsBuilt.Load() + for range 20 { + Groups() + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + t.Fatal("no group g4") + } + } + if n := groupsBuilt.Load() - before; n != 0 { + t.Fatalf("the groups were built %d times more in 40 looks under one Hold, want 0", n) + } + // a caller's change to its copy is not the next caller's + var g4 Group + for _, g := range Groups() { + if g.ID == "g4" { + g4 = g + } + } + g4.Members[0] = "changed" + for _, g := range Groups() { + if g.ID == "g4" && g.Members[0] == "changed" { + t.Fatal("a change to a held group's members reached the next caller") + } + } + // a write builds them again + if err := SaveGroup(Group{ID: "g4", Name: "Renamed", Members: []string{"p0/m1", "p1/m1"}, Routing: Ordered}); err != nil { + t.Fatal(err) + } + if g, _, ok := FindGroup(GroupPrefix + "g4"); !ok || g.Name != "Renamed" { + t.Fatalf("a group saved under the Hold kept its old self: %+v", g) + } +} + +// cloneGroups shares nothing with what it copies: every slice, map and +// pointer of a Group and of its Rules, found by reflection, so a field +// added later is copied too or this fails. +func TestCloneGroupsSharesNothing(t *testing.T) { + var g Group + fillEvery(reflect.ValueOf(&g).Elem()) + if len(g.Rules) == 0 { + t.Fatal("the fill made no rule") + } + c := cloneGroups([]Group{g})[0] + if !reflect.DeepEqual(c, g) { + t.Fatalf("the copy differs:\n%+v\n%+v", c, g) + } + if path := sharedRef(reflect.ValueOf(g), reflect.ValueOf(c), "Group"); path != "" { + t.Fatalf("%s is shared with the held group", path) + } +} + +// fillEvery gives every field of v a value, and each slice, map and pointer one +// element. +func fillEvery(v reflect.Value) { + switch v.Kind() { + case reflect.Struct: + for i := range v.NumField() { + if v.Type().Field(i).IsExported() { + fillEvery(v.Field(i)) + } + } + case reflect.Slice: + v.Set(reflect.MakeSlice(v.Type(), 1, 1)) + fillEvery(v.Index(0)) + case reflect.Map: + v.Set(reflect.MakeMap(v.Type())) + k, e := reflect.New(v.Type().Key()).Elem(), reflect.New(v.Type().Elem()).Elem() + fillEvery(k) + fillEvery(e) + v.SetMapIndex(k, e) + case reflect.Pointer: + v.Set(reflect.New(v.Type().Elem())) + fillEvery(v.Elem()) + case reflect.String: + v.SetString("x") + case reflect.Bool: + v.SetBool(true) + case reflect.Int, reflect.Int64, reflect.Int32: + v.SetInt(1) + case reflect.Float64: + v.SetFloat(1) + } +} + +// sharedRef names the first slice, map or pointer a and b hold in common. +func sharedRef(a, b reflect.Value, path string) string { + switch a.Kind() { + case reflect.Struct: + for i := range a.NumField() { + if a.Type().Field(i).IsExported() { + if p := sharedRef(a.Field(i), b.Field(i), path+"."+a.Type().Field(i).Name); p != "" { + return p + } + } + } + case reflect.Slice: + if a.Len() > 0 && a.Pointer() == b.Pointer() { + return path + } + for i := range a.Len() { + if p := sharedRef(a.Index(i), b.Index(i), fmt.Sprintf("%s[%d]", path, i)); p != "" { + return p + } + } + case reflect.Map, reflect.Pointer: + if !a.IsNil() && a.Pointer() == b.Pointer() { + return path + } + if a.Kind() == reflect.Pointer && !a.IsNil() { + return sharedRef(a.Elem(), b.Elem(), path) + } + } + return "" +} + +// BenchmarkGroupLooksHeld is the group look-ups one request to a group +// makes under its Hold (FindGroup for the route, its members and the +// window, and the group list), over 30 providers serving the same 60 +// models. +func BenchmarkGroupLooksHeld(b *testing.B) { + isolate(b) + home := b.TempDir() + b.Setenv("HOME", home) + b.Setenv("USERPROFILE", home) + b.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + b.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + b.Setenv("MAGPIE_NO_ACCOUNTS", "1") + var models []string + for i := range 60 { + models = append(models, fmt.Sprintf("m%d", i)) + } + for i := range 30 { + if err := Save(Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: models, Anthropic: "http://127.0.0.1:9"}); err != nil { + b.Fatal(err) + } + } + if err := SaveGroup(Group{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: Ordered}); err != nil { + b.Fatal(err) + } + Changed() + defer func(d time.Duration) { heldFor = d }(heldFor) + heldFor = time.Hour // the look-ups of one request, not the Hold's age on a loaded machine + release := Hold() + defer release() + providerEntries() + b.ResetTimer() + for range b.N { + for range 4 { + if _, _, ok := FindGroup(GroupPrefix + "g4"); !ok { + b.Fatal("no group g4") + } + } + Groups() + } +} From 224ea7d5bee5759e1e2bfeac8aca4a0c3d9503a5 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 12:00:12 +0800 Subject: [PATCH 57/92] catalog: a reset drops what a request built of the old catalog 5351343e7 keeps what a request built of the catalog for the next request within heldFor, dropped by every write magpie makes. A reset of models.dev's catalog (catalog.Reset) wasn't one of them: Sync tells Touched after it, but a Reset alone left the providers' entries with the old windows and output limits for up to a second, and Pi's and Crush's model lists written in that second carried them (TestPiModelsCarryMaxTokens, TestCrushModelsCarryMaxTokens red in the full run: "unknown output sent: ...maxTokens:131072"). Reset now tells Forget (provider.Changed) after it lets go of its lock. Test: TestHoldKeptUntilAWrite gains "the catalog reset". Broken by hand (Reset not telling Forget): red, "the catalog reset: built 0 times, want 1", and both agent tests red again; fixed, the agent tests pass 3 of 3. Run: go test ./internal/catalog -count 1: ok (3.4s); go test ./internal/provider -run TestHoldKeptUntilAWrite: ok; go test ./internal/agent -run 'TestPiModelsCarryMaxTokens|TestCrushModelsCarryMaxTokens' -count 3: ok; go vet ./internal/catalog ./internal/provider. --- internal/catalog/catalog.go | 10 ++++++++-- internal/provider/hold_test.go | 7 +++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 82da1d966..a410b3870 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -615,12 +615,18 @@ func load() map[string]mdProvider { return mdev } -// Reset forgets the loaded catalog so the next call re-reads the cache. +// Reset forgets the loaded catalog so the next call re-reads the cache, +// and tells Forget: what the provider package built of the old one (the +// windows and output limits of its entries) is kept between requests +// for a moment, and would answer for the old catalog meanwhile. func Reset() { loadMu.Lock() - defer loadMu.Unlock() loaded = false mdev, images, windows, outputs, efforts, thinks, names, listed, canonical = nil, nil, nil, nil, nil, nil, nil, nil, nil + loadMu.Unlock() + if Forget != nil { + Forget() + } } // Sync downloads the models.dev catalog into CachePath. It serializes with diff --git a/internal/provider/hold_test.go b/internal/provider/hold_test.go index a7124d289..6b5c415e5 100644 --- a/internal/provider/hold_test.go +++ b/internal/provider/hold_test.go @@ -89,8 +89,8 @@ func TestHoldKeptForTheNextRequest(t *testing.T) { // What is held across requests is built again when anything it was built // from may have moved: a write that only tells filememo (settings.Save, an // account's file), the providers' or the settings' file written by -// another process (the CLI's "magpie group add"), and the groups served -// or not (GateGroups, ServeGroups). +// another process (the CLI's "magpie group add"), the groups served or +// not (GateGroups, ServeGroups), and the models.dev catalog read again. func TestHoldKeptUntilAWrite(t *testing.T) { defer func(d time.Duration) { heldFor = d }(heldFor) heldFor = time.Minute // a loaded machine's pause between requests isn't the change @@ -123,6 +123,9 @@ func TestHoldKeptUntilAWrite(t *testing.T) { os.WriteFile(settings.Path(), []byte(`{}`), 0o600) }}, {"the groups gated", func() { GateGroups(nil)() }}, + // models.dev's catalog read again: the entries' windows and + // output limits come from it (Pi's maxTokens, Crush's default) + {"the catalog reset", catalog.Reset}, } { was := n c.write() From 33dbdcc529622cf0dd053c99eb34f51c06fbba77 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 16:05:09 +0800 Subject: [PATCH 58/92] plugins: Sign in on Installed takes the reader down to the plugin's sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sign in on Plugins › Installed (or a plugin card) opens the Providers add sheet with the plugin's sign-in drawn at the sheet's foot, under every tile. With many plugins the sheet is taller than the window and the reader was left at its top, the sign-in out of sight: the click seemed to do nothing (the owner, on magpie-intelligence-check). The click now passes its event, so pluginSignIn scrolls the sign-in into the middle of the view on purpose. In WebKit that alone didn't hold: the list show() loads redraws the sheet after the scroll, WebKit pulls the view to 0 while it is drawn, and inside the purpose window that 0 was taken as the reader's, then backToReader returned there. arrived(v) ends the purpose window once the scroll is done and keeps where it left the view as where the reader is, so the redraw is put back to the sign-in. Run: - plugin-signin-scrolls.test.cjs (new; 24 signed-in plugins and one signed out, 900x560, Chromium and WebKit, en and zh): 6/6 pass. On origin/main 0/6 ("the page went down to the sign-in"); with the scroll but without arrived(), Chromium passes and WebKit fails 2/2. - GUI: plugin*, *scroll*, *signin*, builtins: 1033 pass, 0 fail. - go test -tags nogui ./internal/gui: ok (script budget, guard tests). No Go changes. --- internal/gui/assets/app.js | 17 +++- internal/gui/assets/plugins.js | 4 +- .../gui/tests/plugin-signin-scrolls.test.cjs | 91 +++++++++++++++++++ 3 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 internal/gui/tests/plugin-signin-scrolls.test.cjs diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3f5a534cc..3b3d4226c 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7235,13 +7235,19 @@ async function openPlugins(q) { } // pluginSignIn: a plugin's provider signed in to as every subscription is, -// in the Providers add sheet -async function pluginSignIn(id) { +// in the Providers add sheet. Its sign-in is drawn at the sheet's foot, +// under every tile: the click that asked for it, on the Plugins page, takes +// the reader there, with room around it for what the sign-in asks next. +async function pluginSignIn(id, e) { + const go = scrollOnPurpose(e, 3000); if (!await show("providers")) return; closeModal(); adding = true; editing = null; draft = null; presetQuery = ""; renderProviders(); startSignIn(id); + if (!go) return; + $("#addSheet .signing")?.scrollIntoView({ block: "center" }); + arrived($("#view-providers")); } // openProvider: a provider opened in the Providers tab @@ -22243,6 +22249,13 @@ function scrollOnPurpose(e, ms = 1000) { readerScrolls(ms); return true; } +// arrived: a scroll asked for is done. Where it left v is where the reader +// is now, and what redraws after it (a load come in, which WebKit lets pull +// the view up while it is drawn) is put back there, not taken as theirs. +function arrived(v) { + readerLeaves(v); + purposeUntil = performance.now(); +} const SCROLL_KEYS = new Set(["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown", " "]); // Enter/Space can move focus to another field (opening a form, or validation). // Reveal that field only when the keyboard action moved it out of sight. diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index f8044d014..36f627569 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -470,7 +470,7 @@ b.classList.add("go"); b.textContent = t("Sign in"); b.title = subs.length > 1 ? t("Sign in to {name}", { name: out.name }) : ""; - b.onclick = (ev) => { ev.stopPropagation(); pluginSignIn(out.id); }; + b.onclick = (ev) => { ev.stopPropagation(); pluginSignIn(out.id, ev); }; return b; } // an update out: the one button says so in place of Signed in or @@ -1229,7 +1229,7 @@ // button names the one it signs in to and stays quiet const out = subs.find((x) => !x.signedIn), some = subs.some((x) => x.signedIn); const s = el("button", "text" + (here || some ? "" : " primary"), some ? t("Sign in to {name}", { name: out.name }) : t("Sign in")); - s.onclick = () => pluginSignIn(out.id); + s.onclick = (ev) => pluginSignIn(out.id, ev); val.append(s); } // switched on again: a built-in it can carry is offered its way, in diff --git a/internal/gui/tests/plugin-signin-scrolls.test.cjs b/internal/gui/tests/plugin-signin-scrolls.test.cjs new file mode 100644 index 000000000..9d01e50bb --- /dev/null +++ b/internal/gui/tests/plugin-signin-scrolls.test.cjs @@ -0,0 +1,91 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Sign in on Plugins › Installed opens the Providers add sheet with that +// plugin's sign-in drawn at the sheet's foot, under every tile. With enough +// plugins the sheet is taller than the window, and the click left the reader +// at the top, the sign-in out of sight: the Sign in seemed to do nothing. The +// click that asked for it now takes the reader down to it. +// In Chromium and WebKit, en and zh; 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 assets = path.resolve(__dirname, "../assets"); +const LAST = "opencode-zz-last-auth"; + +// 24 plugins signed in already, each with a tile in the sheet, and the one +// signed out last +const subs = []; +for (let i = 0; i < 24; i++) { + const n = String(i).padStart(2, "0"); + subs.push({ id: `p${n}`, pid: `p${n}`, name: `Plugin ${n}`, icon: "generic", spec: `opencode-p${n}-auth`, signedIn: true, models: 2, methods: [{ type: "api", label: "API key" }] }); +} +subs.push({ id: "zzlast", pid: "zzlast", name: "Last One", icon: "generic", spec: LAST, signedIn: false, models: 2, methods: [{ type: "api", label: "API key" }] }); + +function server(lang) { + const providers = { providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: subs }; + const plugins = { plugins: subs.map((x) => ({ spec: x.spec, providers: [x.name], named: true, version: "0.1.0", moved: [] })), bun: true, bunVersion: "1.3.0", picker: false, mirror: false }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${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: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/plugins") return json(plugins); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/plugin-signin/prompt") return json({}); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { en: { signIn: "Sign in" }, zh: { signIn: "登录" } }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Sign in on Installed takes the reader to the plugin's sign-in", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh"]) { + await t.test(lang, async () => { + const ctx = await browser.newContext({ viewport: { width: 900, height: 560 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.pluginTab", "installed"); } catch {} }); + const page = await ctx.newPage(); + t.after(() => ctx.close()); + page.setDefaultTimeout(15000); // a busy machine takes seconds over a click + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang)); + await page.goto("http://magpie.test/?view=plugins"); + const row = page.locator("#view-plugins .pm-row", { hasText: LAST }); + const button = row.locator("button", { hasText: new RegExp(`^${words[lang].signIn}$`) }); + await button.waitFor(); + // the reader scrolls down to the row: a scroll no reader made is put + // back, Playwright's own among them + await page.mouse.move(450, 300); + for (let i = 0; i < 40 && !(await button.evaluate((b) => { const r = b.getBoundingClientRect(); return r.top >= 0 && r.bottom <= innerHeight; })); i++) { + await page.mouse.wheel(0, 300); + await page.waitForTimeout(50); + } + await button.click(); + const box = page.locator("#addSheet .signing"); + await box.locator(".callback-form input").waitFor(); + const at = await page.evaluate(() => { + const v = document.querySelector("#view-providers"), b = document.querySelector("#addSheet .signing"); + const r = b.getBoundingClientRect(), w = v.getBoundingClientRect(); + return { top: v.scrollTop, height: v.scrollHeight, client: v.clientHeight, inSight: r.top >= w.top && r.top < w.bottom }; + }); + assert(at.height > 1.5 * at.client, `the sheet is taller than the window (${at.height} over ${at.client})`); + assert(at.top > 0, "the page went down to the sign-in"); + assert(at.inSight, "the sign-in is in sight"); + assert.match(await box.innerText(), /Last One/); + assert.deepEqual(errors, []); + }); + } + }); +} From 129d8b08a5e38352e5112851bd6f3b2fa42ec720 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 16:38:24 +0800 Subject: [PATCH 59/92] gateway: a schema a tool's $ref reaches goes to Kimi with a type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chaosy on Discord: Codex on Kimi Code k3 failed every request, 400 "not a valid moonshot flavored json schema … $defs.__schema20 … must be defined". Moonshot's validator expands each $ref and refuses a target with no type ("At path 'properties.b': detected infinite recursion without termination condition"), though the same schema written inline passes. Codex sends its MCP and Codex App tools as zod's $defs and types a def with properties or an enum, but leaves a oneOf or allOf def as it was, so the whole request fails. kimiToolRefTypes, scoped by isKimi and run in forwardOnce after kimiToolEnumTypes (chat, Anthropic and Codex's Responses routes all pass there), writes a type after the brace of each untyped $ref target: the one its keywords or branches say, a type array when they differ, every type when nothing does. {} targets, anyOf targets (Kimi refuses a type beside an anyOf) and pure $ref chains are left alone. kimiToolEnumTypes now also types an enum of one type plus null as [T,"null"], the one type array Kimi takes beside an enum. Kimi doesn't count as a moved subscription, so no plugin path reaches it. Measured against the real Kimi Code chat endpoint (api.kimi.com/coding/v1/chat/completions, a key without a plan, so a schema that passes validation gets 403 access_terminated_error and a refused one gets 400 first): - Codex 0.162.1's processed shapes: 400 at properties.b before, 403 after. - Raw shapes (properties-only, minLength-only, const, [1,null] enum, description-only and oneOf-of-refs defs): 400 before, 403 after. - The zod-built Codex App automation_update forms: 403 before and after. - [T,"null"] plus enum, a type array beside oneOf, and every type beside a description: 403. The Anthropic endpoint answers 403 before it validates, so it couldn't be probed; the same rewrite reaches it. Tests: TestKimiToolRefTypes posts on /v1/chat/completions, /v1/messages and /v1/responses to Kimi and to another provider, which gets the tools unchanged. With the forwardOnce line removed it fails on all three Kimi routes. TestKimiToolEnumTypes now expects [T,"null"] for ["a",null], and fails with that branch removed. Run at this head: gofmt -l (clean); go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (clean); set -o pipefail; HOME= go test -timeout 45m ./... at 33dbdcc52 plus this change: exit 0, all 64 packages ok (internal/gateway 1203.9s). --- internal/gateway/gateway.go | 1 + internal/gateway/kimi_schema.go | 315 +++++++++++++++++++++++++-- internal/gateway/kimi_schema_test.go | 95 +++++++- 3 files changed, 397 insertions(+), 14 deletions(-) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 0f7a3f52d..4e3a789e6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3754,6 +3754,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = deepseekTokenField(p, to, body) body = toolOneOfAsAnyOf(p, to, body) body = kimiToolEnumTypes(p, to, body) + body = kimiToolRefTypes(p, to, body) body = kimiLockedSampling(p, to, body) body = clinePin(p, to, body) body = codexImagesFit(p, to, body) diff --git a/internal/gateway/kimi_schema.go b/internal/gateway/kimi_schema.go index 28880dd36..8d698c323 100644 --- a/internal/gateway/kimi_schema.go +++ b/internal/gateway/kimi_schema.go @@ -2,6 +2,8 @@ package gateway import ( "bytes" + "net/url" + "sort" "strconv" "strings" @@ -16,9 +18,10 @@ import ( // defined" (#886, cua-driver's parse_visual_regions, whose kinds' items are // {"enum":["text","icon"]}), and the whole request fails though the tool is // never called. The type is the one every value has — string, integer, -// number or boolean; values of mixed types, or a null among them, are left -// as they were. It is written in place, after the schema's brace, so the -// rest of the body and a cache's prefix stay as they were. +// number or boolean, or that type and "null" when a null is among them, the +// one type array Kimi takes beside an enum; values of other mixed types are +// left as they were. It is written in place, after the schema's brace, so +// the rest of the body and a cache's prefix stay as they were. func kimiToolEnumTypes(p provider.Provider, to provider.Protocol, body []byte) []byte { if !isKimi(p, to) { return body @@ -32,19 +35,29 @@ func kimiToolEnumTypes(p provider.Provider, to provider.Protocol, body []byte) [ } var ins []typeInsert collectUntypedEnums(body, tools, false, &ins) + return withTypes(body, ins) +} + +// withTypes is body with each insert's type written after its schema's +// opening brace; a brace named twice gets it once. +func withTypes(body []byte, ins []typeInsert) []byte { if len(ins) == 0 { return body } - // the walk goes through the body in order, so the inserts ascend + sort.SliceStable(ins, func(i, j int) bool { return ins[i].at < ins[j].at }) var out bytes.Buffer - out.Grow(len(body) + len(ins)*20) - last := 0 + out.Grow(len(body) + len(ins)*24) + last := -1 for _, in := range ins { - out.Write(body[last : in.at+1]) - out.WriteString(`"type":"` + in.typ + `",`) - last = in.at + 1 + if in.at == last { + continue + } + start := last + 1 + out.Write(body[start : in.at+1]) + out.WriteString(`"type":` + in.typ + `,`) + last = in.at } - out.Write(body[last:]) + out.Write(body[last+1:]) return out.Bytes() } @@ -59,8 +72,8 @@ func isKimi(p provider.Provider, to provider.Protocol) bool { } type typeInsert struct { - at int // the schema's opening brace - typ string + at int // the schema's opening brace + typ string // the type as JSON: "string", or ["string","null"] } // collectUntypedEnums adds, for each schema under node with an enum or a @@ -80,7 +93,7 @@ func collectUntypedEnums(body []byte, node gjson.Result, inSchema bool, ins *[]t } else if c := node.Get("const"); c.Exists() { vals = []gjson.Result{c} } - if t := valuesType(vals); t != "" { + if t := enumType(vals); t != "" { *ins = append(*ins, typeInsert{node.Index, t}) } } @@ -109,6 +122,29 @@ func collectUntypedEnums(body []byte, node gjson.Result, inSchema bool, ins *[]t } } +// enumType is the type, as JSON, an enum or const of vals is written with +// for Kimi: the one all of them have, or it and "null" when a null is among +// them; "" when there are none or other types are mixed. +func enumType(vals []gjson.Result) string { + var rest []gjson.Result + null := false + for _, v := range vals { + if v.Type == gjson.Null { + null = true + continue + } + rest = append(rest, v) + } + t := valuesType(rest) + switch { + case t == "": + return "" + case null: + return `["` + t + `","null"]` + } + return `"` + t + `"` +} + // valuesType is the JSON Schema type all of vals have, "" when there are // none or they differ; whole numbers among fractions make them number. func valuesType(vals []gjson.Result) string { @@ -210,3 +246,256 @@ func leadingInt(s string) (int, string) { } return n, s[i:] } + +// kimiToolRefTypes is body with a type written into each schema its tools' +// $refs reach that has none, for Kimi and Moonshot. Their validator expands +// a $ref and refuses a target with no type — 400 "not a valid moonshot +// flavored json schema … At path 'properties.b': detected infinite +// recursion without termination condition" — and the whole request fails, +// though the same schema written inline passes. Codex sends such targets: +// its MCP and Codex App tools come as zod's $defs (__schema0, __schema1 …), +// and it types a def with properties or an enum but leaves a oneOf or an +// allOf one as it was (chaosy on Discord, Codex on k3). The type is the +// one the target's keywords or branches say, a type array when they differ, +// and every type when nothing does, which Kimi takes as "any". A target +// that is {}, an anyOf (Kimi refuses a type beside one: "type should be +// defined in anyOf items instead of the parent schema") or only another +// $ref is left as Kimi takes it, as is an enum whose values no one type +// array can hold. Written in place, like kimiToolEnumTypes', after which it +// runs. +func kimiToolRefTypes(p provider.Provider, to provider.Protocol, body []byte) []byte { + if !isKimi(p, to) || !bytes.Contains(body, []byte(`"$ref"`)) { + return body + } + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() || tools.Index <= 0 { + return body + } + var ins []typeInsert + tools.ForEach(func(_, tool gjson.Result) bool { + for _, at := range []string{"function.parameters", "parameters", "input_schema"} { + if root := tool.Get(at); root.IsObject() { + collectRefTargets(body, root, root, &ins) + } + } + return true + }) + return withTypes(body, ins) +} + +// collectRefTargets adds, for each local $ref under node (a schema of the +// tool schema root) whose target Kimi would refuse untyped, where the +// target opens and the type it is given. +func collectRefTargets(body []byte, root, node gjson.Result, ins *[]typeInsert) { + walkSchema(node, func(s gjson.Result) { + ref := s.Get(`\$ref`) + if ref.Type != gjson.String { + return + } + t, ok := refTarget(root, ref.String()) + if !ok || !t.IsObject() || t.Index <= 0 || t.Index >= len(body) || body[t.Index] != '{' || !untypedForKimi(t) { + return + } + if typ := kimiSchemaType(root, t); typ != "" { + *ins = append(*ins, typeInsert{t.Index, typ}) + } + }) +} + +// walkSchema calls f with node and every schema under it, through the +// keywords that hold schemas. +func walkSchema(node gjson.Result, f func(gjson.Result)) { + switch { + case node.IsArray(): + node.ForEach(func(_, v gjson.Result) bool { + walkSchema(v, f) + return true + }) + case node.IsObject(): + f(node) + node.ForEach(func(key, v gjson.Result) bool { + switch key.String() { + case "properties", "$defs", "definitions", "dependentSchemas", "patternProperties": + v.ForEach(func(_, s gjson.Result) bool { + walkSchema(s, f) + return true + }) + case "items", "additionalProperties", "contains", "propertyNames", "not", "if", "then", "else", "allOf", "anyOf", "oneOf", "prefixItems", "unevaluatedProperties", "unevaluatedItems", "contentSchema": + walkSchema(v, f) + } + return true + }) + } +} + +// refTarget is the schema a local $ref ("#", "#/$defs/x") names in root. +func refTarget(root gjson.Result, ref string) (gjson.Result, bool) { + if ref != "#" && !strings.HasPrefix(ref, "#/") { + return gjson.Result{}, false + } + cur := root + for _, tok := range strings.Split(ref, "/")[1:] { + tok = strings.ReplaceAll(strings.ReplaceAll(tok, "~1", "/"), "~0", "~") + if u, err := url.PathUnescape(tok); err == nil { + tok = u + } + if !cur.IsObject() && !cur.IsArray() { + return gjson.Result{}, false + } + cur = cur.Get(gjson.Escape(tok)) + if !cur.Exists() { + return gjson.Result{}, false + } + } + return cur, true +} + +// untypedForKimi is whether Kimi refuses s as a $ref's target: it has no +// type, isn't {}, an anyOf, or a $ref with nothing but notes beside it. +func untypedForKimi(s gjson.Result) bool { + if s.Get("type").Exists() || s.Get("anyOf").Exists() { + return false + } + only := true + n := 0 + s.ForEach(func(k, _ gjson.Result) bool { + n++ + switch k.String() { + case "$ref", "description", "title", "default", "examples", "$comment": + default: + only = false + } + return true + }) + if n == 0 { + return false + } + return !(only && s.Get(`\$ref`).Exists()) +} + +// allKimiTypes is every JSON Schema type, which Kimi takes for a schema +// that may be anything. +const allKimiTypes = `["string","number","integer","boolean","object","array","null"]` + +// kimiSchemaType is the type, as JSON, an untyped schema s is given: the +// one (or the ones) its keywords and branches say, every type when they +// say nothing, and "" for an enum no type Kimi takes beside one can hold. +func kimiSchemaType(root, s gjson.Result) string { + if e := s.Get("enum"); e.IsArray() { + return enumType(e.Array()) + } + if c := s.Get("const"); c.Exists() { + return enumType([]gjson.Result{c}) + } + ts := schemaTypes(root, s, 0) + if len(ts) == 0 { + return allKimiTypes + } + if ts["integer"] && ts["number"] { + delete(ts, "integer") + } + var names []string + for _, t := range []string{"string", "number", "integer", "boolean", "object", "array", "null"} { + if ts[t] { + names = append(names, `"`+t+`"`) + } + } + if len(names) == 1 { + return names[0] + } + return "[" + strings.Join(names, ",") + "]" +} + +// schemaTypes is the set of types s can have, as its type, its keywords, +// its values or its branches (through their $refs) say; nil when they +// don't say. +func schemaTypes(root, s gjson.Result, depth int) map[string]bool { + if depth > 16 || !s.IsObject() { + return nil + } + ts := map[string]bool{} + if t := s.Get("type"); t.Exists() { + for _, v := range t.Array() { + ts[v.String()] = true + } + return ts + } + if ref := s.Get(`\$ref`); ref.Type == gjson.String { + if t, ok := refTarget(root, ref.String()); ok { + return schemaTypes(root, t, depth+1) + } + return nil + } + if e := s.Get("enum"); e.IsArray() || s.Get("const").Exists() { + vals := e.Array() + if c := s.Get("const"); c.Exists() { + vals = []gjson.Result{c} + } + for _, v := range vals { + switch v.Type { + case gjson.String: + ts["string"] = true + case gjson.True, gjson.False: + ts["boolean"] = true + case gjson.Null: + ts["null"] = true + case gjson.Number: + if strings.ContainsAny(v.Raw, ".eE") { + ts["number"] = true + } else { + ts["integer"] = true + } + default: + if v.IsArray() { + ts["array"] = true + } else { + ts["object"] = true + } + } + } + return ts + } + // a branch that says nothing makes oneOf and anyOf anything; allOf + // is what its branches that do say + for _, k := range []string{"oneOf", "anyOf", "allOf"} { + bs := s.Get(k) + if !bs.IsArray() { + continue + } + known := false + for _, b := range bs.Array() { + bt := schemaTypes(root, b, depth+1) + if len(bt) == 0 && k != "allOf" { + return nil + } + for t := range bt { + ts[t] = true + known = true + } + } + if known { + return ts + } + } + has := func(keys ...string) bool { + for _, k := range keys { + if s.Get(k).Exists() { + return true + } + } + return false + } + switch { + case has("properties", "required", "additionalProperties", "patternProperties", "minProperties", "maxProperties", "propertyNames", "dependentRequired", "dependentSchemas", "unevaluatedProperties"): + ts["object"] = true + case has("items", "prefixItems", "minItems", "maxItems", "uniqueItems", "contains", "unevaluatedItems"): + ts["array"] = true + case has("minLength", "maxLength", "pattern", "format", "contentEncoding", "contentMediaType"): + ts["string"] = true + case has("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"): + ts["number"] = true + default: + return nil + } + return ts +} diff --git a/internal/gateway/kimi_schema_test.go b/internal/gateway/kimi_schema_test.go index 0eda23d58..56cb91864 100644 --- a/internal/gateway/kimi_schema_test.go +++ b/internal/gateway/kimi_schema_test.go @@ -18,7 +18,9 @@ import ( // 'properties.options.properties.kinds.anyOf.items': type is not defined" // (#886), and the whole request failed. Values of mixed types, a schema // with a type, a property called enum and the rest of the body are left as -// they were; anyone else is sent the tools unchanged. +// they were; a null among one type's values gives that type and "null", +// the type array Kimi takes beside an enum. Anyone else is sent the tools +// unchanged. func TestKimiToolEnumTypes(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) @@ -61,6 +63,7 @@ func TestKimiToolEnumTypes(t *testing.T) { `"scale":{"enum"`, `"scale":{"type":"number","enum"`, `"on":{"const"`, `"on":{"type":"boolean","const"`, `"mode":{ "enum"`, `"mode":{"type":"string", "enum"`, + `"maybe":{"enum"`, `"maybe":{"type":["string","null"],"enum"`, ).Replace(tools) b := got["api.kimi.com"] if !strings.Contains(b, want) { @@ -74,6 +77,96 @@ func TestKimiToolEnumTypes(t *testing.T) { } } +// A schema a tool's $ref reaches goes to Kimi with a type: Kimi expands +// the $ref and refuses a target with none, 400 "At path 'properties.b': +// detected infinite recursion without termination condition", and Codex on +// k3 failed outright (chaosy on Discord). Codex sends zod's $defs with a +// oneOf or allOf def untyped, as captured from Codex 0.162.1 (b, c); raw +// clients send defs typed by nothing but their keywords, or by nothing at +// all. Each goes on the chat route, the Anthropic route and from Codex's +// Responses; a {} def, an anyOf (Kimi refuses a type beside one), a typed +// def, an unreferenced one and the rest of the body are left as they were, +// and anyone else is sent the tools unchanged. +func TestKimiToolRefTypes(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + kimi, err := provider.FromPreset("kimi-code-cn") + if err != nil { + t.Fatal(err) + } + kimi.ID, kimi.Key, kimi.Models = "kimi", "k", []string{"m"} + for _, p := range []provider.Provider{kimi, + {ID: "other", Name: "Other", Key: "k", Chat: "https://other.test/v1", Anthropic: "https://other.test", Models: []string{"m"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + got := map[string]string{} + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, _ := io.ReadAll(r.Body) + got[r.URL.Host+r.URL.Path] = string(b) + return &http.Response{StatusCode: 400, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"no","type":"invalid_request_error"}}`))}, nil + })} + schema := `{"type":"object","properties":{"a":{"$ref":"#/$defs/__schema0"},"b":{"$ref":"#/$defs/__schema1"},` + + `"c":{"items":{"$ref":"#/$defs/__schema2"},"type":"array"},"d":{"anyOf":[{"$ref":"#/$defs/P"},{"type":"null"}]},` + + `"e":{"$ref":"#/$defs/M"},"f":{"$ref":"#/definitions/D"},"g":{"$ref":"#/$defs/R"},"h":{"$ref":"#/$defs/U"},"i":{"$ref":"#/$defs/S"}},` + + `"$defs":{"__schema0":{},"__schema1":{"oneOf":[{"type":"string"},{"type":"number"}]},"__schema2":{"allOf":[{"type":"string"}]},` + + `"P":{"properties":{"x":{"type":"string"}}},"M":{"minLength":1},"R":{"oneOf":[{"$ref":"#/$defs/P"},{"$ref":"#/definitions/D"}]},` + + `"U":{"anyOf":[{"type":"string"},{"$ref":"#/$defs/U"}]},"S":{"type":"string","enum":["x"]},"V":{"oneOf":[{"type":"string"}]}},` + + `"definitions":{"D":{"description":"anything"}}}` + anything := `["string","number","integer","boolean","object","array","null"]` + want := strings.NewReplacer( + `"__schema1":{`, `"__schema1":{"type":["string","number"],`, + `"__schema2":{`, `"__schema2":{"type":"string",`, + `"P":{`, `"P":{"type":"object",`, + `"M":{`, `"M":{"type":"string",`, + `"R":{`, `"R":{"type":`+anything+`,`, + `"D":{`, `"D":{"type":`+anything+`,`, + ).Replace(schema) + routes := []struct{ path, tools, upstream, otherUp string }{ + {"/v1/chat/completions", `"tools":[{"type":"function","function":{"name":"automation_update","parameters":%s}}]`, "api.kimi.com/coding/v1/chat/completions", "other.test/v1/chat/completions"}, + {"/v1/messages", `"tools":[{"name":"automation_update","input_schema":%s}]`, "api.kimi.com/coding/v1/messages", "other.test/v1/messages"}, + {"/v1/responses", `"tools":[{"type":"function","name":"automation_update","parameters":%s}]`, "api.kimi.com/coding/v1/chat/completions", "other.test/v1/chat/completions"}, + } + for _, r := range routes { + for _, id := range []string{"kimi", "other"} { + clear(got) + msgs := `"messages":[{"role":"user","content":"hi"}],"max_tokens":16,` + if r.path == "/v1/responses" { + msgs = `"input":"hi",` + } + body := `{"model":"` + id + `/m",` + msgs + strings.Replace(r.tools, "%s", schema, 1) + `}` + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", r.path, strings.NewReader(body))) + up := r.upstream + if id == "other" { + up = r.otherUp + } + b, ok := got[up] + if !ok { + t.Fatalf("%s %s: nothing sent to %s, only %v (%d %s)", r.path, id, up, got, rec.Code, rec.Body) + } + if !json.Valid([]byte(b)) { + t.Fatalf("%s %s: invalid JSON sent:\n%s", r.path, id, b) + } + sent := gjson.Get(b, "tools.0.function.parameters") + if !sent.Exists() { + sent = gjson.Get(b, "tools.0.input_schema") + } + w := schema + if id == "kimi" { + w = want + } + if sent.Raw != w { + t.Errorf("%s %s was sent:\n%s\nwant:\n%s", r.path, id, sent.Raw, w) + } + } + } +} + // A request to a model whose server locks temperature and top_p — Kimi // Code's kimi-for-coding and k3*, kimi-k2.5 and later on either Kimi // platform — goes without them: the whitelist refuses the ones clients From 65f5f0153d9d9a2e1d0515eb59469bc838ee9556 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 16:43:18 +0800 Subject: [PATCH 60/92] gui: a sign-in's field and its button are one height, 8px apart The key field in a sign-in (a plugin's key, Copilot GHE's address, a pasted callback, the proxy ask) was 30px tall with its button at the button's own ~24px and 4px beside it: a short button jammed against a tall field (the owner, on OpenCode 2 Free's key). The field is now 28px with no vertical padding, its button 28px with the same 7px corners, 8px apart. Measured (plugin key form, Chromium and WebKit): zh 1100 and en 900: field 28, button 28, gap 8, one row, button's right edge at the form's; de 420: both 44 (the narrow-width touch height), gap 8. Run: - Full GUI suite (2156 tests at ~load 100): red only in codex-predictions (10, the same 10 on origin/main 224ea7d5b, #2624) and agent-expand-steady webkit 560px (1, passes alone on 224ea7d5b and here; under-load flake, #1583). - plugin-signin-scrolls, signin-*.test.cjs within the full run: green. CSS only. --- internal/gui/assets/app.css | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index fb4c6462d..7043198dd 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2680,8 +2680,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } /* the sign-in link, one line, selected whole with a click */ .signing .signlink { display: flex; align-items: center; gap: 4px; margin: 5px 0 1px; min-width: 0; } .signing .signlink code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--code-style, normal) var(--code-weight, 400) 11px/1.3 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); padding: 4px 7px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); user-select: all; -webkit-user-select: all; cursor: text; } -.signing .callback-form { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 6px; } -.signing .callback-form input { flex: 1; min-width: 120px; width: 100%; padding: 6px 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; } +.signing .callback-form { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 6px; } +.signing .callback-form input { flex: 1; min-width: 120px; width: 100%; height: 28px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font-size: 12px; } +/* the field's button: as tall as the field, with the same corners */ +.signing .callback-form > button { height: 28px; padding: 0 12px; border-radius: 7px; } .signing .why { color: var(--red); } /* a plugin's ways to sign in: the question keeps the row, the choices wrap beneath it at whatever length the plugin names them */ From ab7ec8c657da4653d2b55c91a1cdccd9ad92b4a4 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 16:45:31 +0800 Subject: [PATCH 61/92] gui: Manage agents' names sit beside their icons, not at the row's far end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner's screenshot (zh, a wide window): each row's name was pushed to the right edge, next to 未隐藏, far from its icon. A row is a