plugin: the pi tests keep the pinned pi's Bun cache between runs (#2865)

installPinnedPi's `bun install --frozen-lockfile` used the install
cache bunCommand names, which lies in the test's home. testenv makes a
new home for every go test process, so every run fetched pi's 118
tarballs before the host could start, inside the test's 4 minutes.
yetone saw TestPiPackage red at 86fef947e after 226s, most of it that
install, with gateway's tests run beside it on a Mac at load 26.

Now the install gets a Bun cache that outlives the home,
magpie-test-bun-cache-<uid>-<n> in os.TempDir() (pinnedPiCache), as
the last BUN_INSTALL_CACHE_DIR in its environment. The first run fills
it, and a run after that installs pi from it and asks npm for nothing.
Bun names each entry by package, version and registry, so a new pin,
or a run through another registry, fetches only what is missing. It
holds about 155 MB here. This is the first thing the tests leave
behind between runs, on purpose: testenv's own bound is the temp
folder (checkChild), so the folder is inside it, but it is outside the
test home, which goes when the run ends. agent-wiring.md's "Tests
never touch the real machine" now says so.

Why that folder:
- It is none of the user's own folders. testenv moves HOME, the XDG
  folders, APPDATA and LOCALAPPDATA into the sandbox, not the temp
  folder, and ~/.bun, ~/.cache and ~/.config/magpie are never named.
  Only the install's own process gets the variable, so the host and
  anything else a test starts never see it. The host keeps the home's
  cache, and pruneInstallCache, which prunes the app's cache, never
  touches this one.
- It is this user's. The uid is in its name, as Linux's temp folder is
  shared (macOS' and Windows' are the user's own). It is made 0700, and
  used only when it is a folder, not a link, that no one else has any
  permission on (not checked on Windows, where Go reports no real modes)
  and that this user can make a file in. One someone else made fails
  one of those, and the install then uses the home's cache as before.
  Root always uses the home's cache: root passes those checks in a
  folder another user made, and would run what that user put there.
- Its files are never old enough for a temp folder's cleaner. macOS
  takes files under its temp folder that went unread for about 3 days,
  and Bun doesn't notice a file missing from a cached package: it
  installs the rest, and pi doesn't load (shown below). So the folder
  is a new one every two days (<n> counts two day periods), the one
  before is kept for a run still using it, and older ones are taken
  out by the next run. The first run in a new period fetches pi again.
  TestPinnedPiCacheMovesOn checks the folder moves, the one before
  stays and older ones go.
- Two go test runs can share it. Bun unpacks each tarball into a folder
  of its own and renames it into the cache. When another install got
  there first, it swaps the two or removes the old one and renames
  again (move_to_cache_directory in Bun 1.4.2's extract_tarball.rs,
  written for concurrent installs sharing one cache; on Windows it
  retries the move). Two runs started at once on an empty cache both
  passed here.
- Bun's documented default on Linux is to hardlink the installed files
  to the cache (not looked at here), so a test that wrote into pi's
  installed files in place could change the cache. None does.

No assertion in the pi tests goes red when the cache is taken out: they
pass either way while npm answers inside their 4 minutes. What
regresses is the fetches, counted below; the times move with npm.

What was run (tree 93b344b1, on origin/main acdc85ac, go1.26.8,
linux/amd64, Linux 5.15, umask 077):
- npm's registry through a local relay (BUN_CONFIG_REGISTRY, Bun 1.4.2)
  that passes every request on at once and logs it, with `go test -tags
  nogui -count=1 -v -run <tests> ./internal/plugin/`, load 16 to 26,
  the cache folders removed first:
  - TestPiPackage alone: pass, 29.38s, 118 tarballs asked (no
    manifest). Run again: pass, 1.13s, nothing asked.
  - Then TestGatewayHookMixedPiPackage and TestPiPackage: pass, 0.92s
    and 1.04s, nothing asked.
  - Two TestPiPackage runs started at once: both pass (227.40s and
    115.58s), with every tarball asked twice (236 asked, 118
    distinct). A run after them: 1.13s, nothing asked.
- Broken by hand:
  - The cache not given to the install (the home's cache, as before
    this commit), the folder left full: TestPiPackage passes in 141.92s
    with 118 tarballs asked again.
  - One file of pi-coding-agent's cached package taken out, as a temp
    cleaner would: TestPiPackage red in 0.49s, nothing asked,
    `@earendil-works/pi-coding-agent isn't installed: add it as a
    plugin's dependency, or reinstall the pi plugin`.
  - The folder's name without its period: TestPinnedPiCacheMovesOn red,
    `after two days the cache is ".../magpie-test-bun-cache-<uid>-0",
    not a folder other than ...`. Older folders kept: red, `a folder
    four days old is kept (<nil>)`.
- go test -tags nogui -count=1 -timeout 45m ./internal/plugin/ (Bun
  1.4.2, npm direct): ok, 341 PASS lines counting subtests, 2 skip
  (TestFlowBigReplyProd wants MAGPIE_FLOW_BIG, TestRenewOtherHost is
  run by TestRenewOnceAcrossHosts). TestGatewayHookMixedPiPackage
  9.88s, TestPiPackage 1.08s.
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- Not run again at this tree: -race and the full suite. This tree
  differs from tree f2b71fdd only in pi_test.go and agent-wiring.md;
  at f2b71fdd internal/plugin passed with -race, and the full suite
  had 79 packages ok, internal/plugin among them, and 7 tests red in 2
  packages, each filed: agent TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

Not tried: macOS and Windows (their checks and cleaners were only
read), a run as root, a real temp cleaner, and the pi tests under a
load like yetone's.

Reviewed and run again by the maintainer at the stack's tree 45994757c
(this commit and the six beside it, on origin/main 90518de26), go1.26.8:
- mote (macOS, arm64): gofmt -l clean; go vet and go build for darwin,
  GOOS=linux -tags nogui and GOOS=windows (library, plugin, gui): exit 0.
  go test -tags nogui -count=1 -timeout 45m ./...: every package ok but
  internal/gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  internal/proc TestNoCommandBypassesProc (#4491), both red on main
  from b09349d17 and c59c547c5, in files this stack doesn't touch.
  go test -race -run 'TestWSL|TestTagged|TestPinnedPiCache' for
  library and plugin: ok.
- magpie-desktop (Linux, wsl-run; WebKit hangs on mote), Chromium and
  WebKit: every library-*, sync-*, s3-sync, github-sync and i18n-keys
  file, 4 at a time: 1003 of 1020. The 17 reds are in 6 files no commit here
  touches: i18n-keys ("Unmarked", #4524), library-chip-fan, -items,
  -mcp-health, -mcp-hub (#4483) and -mcp-tools. Those 6 alone, one at a
  time, at load ~60: 74 of 92 here, 77 of 92 at 90518de26 itself. Red
  in both: i18n-keys, -chip-fan and -items in WebKit, -mcp-tools in
  Chromium ja 420; -mcp-health green in both; -mcp-hub's WebKit case
  red here only, the case #4483 has red on main. -chip-fan and -items
  are #3072's and #4501's kind, WebKit under load.
- On macOS (mote), the pi tests twice in a row: TestGatewayHookMixedPiPackage
  21.41s then 0.96s, TestPiPackage 1.23s then 1.24s, and
  TestPinnedPiCacheMovesOn ok: the second run installs from the kept
  cache. It sits in os.TempDir(), outside a test's HOME, by design.
- The stack rebased on origin/main e4c784177 (main's 7 commits since
  share only docs/subsystems/agent-wiring.md with it, a line apart),
  with no conflict: on mote gofmt -l, go vet (linux nogui,
  windows), go test -tags nogui -count=1 ./internal/library
  ./internal/plugin ok and internal/gui's budget tests ok; on Linux
  sync-note-show and library-wsl-asleep, both engines: 92 of 92.
This commit is contained in:
JoeyWu-tech
2026-10-31 17:03:55 +08:00
committed by yetone
parent a246ad4cfc
commit d0a61b856a
2 changed files with 93 additions and 2 deletions
+1 -1
View File
@@ -145,7 +145,7 @@ something else shows up as drift.
- Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it.
- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...; on Windows the registry's PATH plus the Node fnm's default alias names, `%APPDATA%\fnm\aliases\default` or under `FNM_DIR`, which fnm puts on a terminal's PATH from the shell profile and never in the registry, #2685), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A command another app ships under the agent's name doesn't count either: VS Code forks put a `code` launcher in their own bin folder (Cursor; Qoder IDE beside `qoder`), which their Windows installers put on PATH, so a `code`, `code-insiders` or `codium` counts as VS Code, Insiders or VSCodium only when the `product.json` beside it names that build (`applicationName`), or names none (`vscodeCodeBinary`; ggbr on Discord: Qoder IDE listed as VS Code too, `TestVSCodeDetected`, `TestVSCodeBuildLauncher`). A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).
- Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/.<editor>/extensions/<id>-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`).
- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`.
- Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`. The one thing tests keep between runs is the pi tests' Bun install cache, `magpie-test-bun-cache-<uid>-<n>` in the temp folder (`pinnedPiCache` in `internal/plugin`), outside the test home on purpose so a run doesn't fetch the pinned pi's 118 packages again (#2865): it is used only when it is this user's alone, never as root, and is a new folder every two days, so the temp folder's cleaner never takes a file out of the one in use.
- OmO and Prime Agent write a Gemini-capable model as `google-generative-ai` at the gateway's `/v1beta` (`piModelJSON` in [`agents.go`](../../internal/agent/agents.go)); each one's Google client takes the version path from `baseUrl` (senpi-ai's `apiVersion = ""`, Prime Agent's `pa-ai` `providers/google.rs`). omp does the same in `models.yml` (`ompProviderAt` in [`omp.go`](../../internal/agent/omp.go), #4277): its `google-generative-ai` posts to `baseUrl/models/<id>:streamGenerateContent?alt=sse` (pi-ai `providers/google.ts`, 16.0.0 to 18.14.0). Its Google client throws without a key, but under `auth: none` omp hands it its no-auth key `N/A`, which it sends as `x-goog-api-key` and loopback takes, so the provider stays keyless; a WSL omp under NAT sends its `apiKey` there. A Gemini 3 or later model thinks with `mode: google-level` (thinkingLevel MINIMAL to HIGH; xhigh and max go as HIGH), a Gemini 1.x or 2.x one with `budget`, which omp sends as `thinkingBudget: -1` (`ompGeminiMode`; `TestOmpGeminiModelsAskedOnGeminisAPI`). Checked with omp 18.14.0 against the gateway and a fake Gemini server. Pi and StepCode keep such a model on Chat, which the gateway translates (`piAsked`). StepCode registers no `google-generative-ai` stream, only `anthropic-messages`, `openai-completions` and `openai-responses` (Step-Code `packages/providers/src/compat.ts`), though its docs list it. Pi's own agent folder is read by apps that run Pi's SDK on it too: Raft's daemon (`@botiverse/raft-daemon`, pi-ai 0.83.0) opens `~/.pi/agent/models.json` and hands every request its own fetch, which pi-ai's Google adapter refuses before sending ("Custom fetch is not supported by the Google Generative AI adapter", in pi-ai 1.4.0 too; yunfei9958 on X, `TestPiFolderKeepsGeminiOnChatForRaft`). `magpieModels` in [`route.go`](../../internal/agent/route.go) includes Gemini and Code Assist capabilities when no native Chat, Responses or Messages API was selected; this includes a plugin model declaring `@ai-sdk/google`. Requests keep going through the gateway and the plugin's sign-in and fetch, with the gateway's usual translation where needed. A normal model sync updates existing entries. Routing groups retain their existing API choice, and Pencil remains on Chat. Pi resolves a level there to one of Gemini's four (minimal, low, medium, high) and throws on any other, so a level the model names otherwise is set to null in `thinkingLevelMap` (`TestPiGoogleThinkingLevelsAreGeminis`).
## Verification
+92 -1
View File
@@ -11,7 +11,9 @@ import (
"os/exec"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"testing"
"time"
@@ -444,7 +446,11 @@ func installPinnedPi(t *testing.T, ctx context.Context) {
if err != nil {
t.Fatal(err)
}
if out, err := bunCommand(ctx, bun, Dir(), "install", "--frozen-lockfile", "--ignore-scripts").CombinedOutput(); err != nil {
cmd := bunCommand(ctx, bun, Dir(), "install", "--frozen-lockfile", "--ignore-scripts")
if cache := pinnedPiCache(time.Now()); cache != "" {
cmd.Env = append(cmd.Env, "BUN_INSTALL_CACHE_DIR="+cache) // os/exec takes a key's last
}
if out, err := cmd.CombinedOutput(); err != nil {
t.Skipf("pi couldn't be installed: %v: %s", err, lastLines(string(out), 6))
}
if v := Version(piAgent); v != pinnedPi {
@@ -452,6 +458,91 @@ func installPinnedPi(t *testing.T, ctx context.Context) {
}
}
// pinnedPiCache is the Bun install cache installPinnedPi installs with at
// now, in the temp folder, which outlives the test's home: a run after the
// first installs pi from it, where the home's own cache started empty each
// run and every run fetched pi's 118 tarballs, most of TestPiPackage's 4
// minutes on a busy machine (#2865). It is this user's (their uid in its
// name, as the temp folder is shared on Linux; Windows' is the user's
// own), and used only when no one else can read or write it and this
// user can write in it; else "", and the home's cache is used as before.
// Never as root: root passes those checks in a folder another user made.
// It is a new folder every two days (pinnedPiCacheDays), so none of its
// files is old enough for the temp folder's cleaner to have taken it
// (macOS' takes what went unread for 3 days): Bun installs a package
// whose cached folder lost a file as it is, and pi didn't load. The
// folder before stays for a run still using it; older ones go. Bun
// unpacks a package in a folder of its own and renames it into the
// cache, so two go test runs can share it. It isn't the app's cache
// (installCacheDir), which pruneInstallCache prunes.
func pinnedPiCache(now time.Time) string {
if os.Getuid() == 0 {
return ""
}
name := "magpie-test-bun-cache-" + strconv.Itoa(os.Getuid()) + "-"
n := now.Unix() / int64(pinnedPiCacheDays*24*time.Hour/time.Second)
old, _ := filepath.Glob(filepath.Join(os.TempDir(), name+"*"))
for _, o := range old {
if k, err := strconv.ParseInt(strings.TrimPrefix(filepath.Base(o), name), 10, 64); err == nil && k < n-1 {
os.RemoveAll(o)
}
}
dir := filepath.Join(os.TempDir(), name+strconv.FormatInt(n, 10))
if err := os.MkdirAll(dir, 0o700); err != nil {
return ""
}
fi, err := os.Lstat(dir)
if err != nil || !fi.IsDir() || runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
return ""
}
f, err := os.CreateTemp(dir, "probe-")
if err != nil {
return ""
}
f.Close()
os.Remove(f.Name())
return dir
}
// pinnedPiCacheDays is how long pinnedPiCache keeps one folder.
const pinnedPiCacheDays = 2
// The pinned pi's cache moves to a new folder every two days, the one
// before kept and older ones taken out, so the temp folder's cleaner
// never takes a file from the one in use (#2865).
func TestPinnedPiCacheMovesOn(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("root gets no cache")
}
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp) // os.TempDir: TMPDIR on Unix, TMP on Windows
t.Setenv("TMP", tmp)
day := 24 * time.Hour
period := int64(pinnedPiCacheDays * 24 * 3600)
start := time.Unix(1800000000/period*period, 0) // a folder's first second
a := pinnedPiCache(start)
if a == "" || filepath.Dir(a) != tmp {
t.Fatalf("the cache is %q, not a folder in %s", a, tmp)
}
if got := pinnedPiCache(start.Add(2*day - time.Second)); got != a {
t.Fatalf("within its two days the cache moved from %s to %s", a, got)
}
b := pinnedPiCache(start.Add(2 * day))
if b == "" || b == a {
t.Fatalf("after two days the cache is %q, not a folder other than %s", b, a)
}
if _, err := os.Stat(a); err != nil {
t.Fatalf("the folder before was taken out while a run may use it: %v", err)
}
c := pinnedPiCache(start.Add(4 * day))
if _, err := os.Stat(a); !os.IsNotExist(err) {
t.Fatalf("a folder four days old is kept (%v)", err)
}
if _, err := os.Stat(b); err != nil || c == "" || c == b {
t.Fatalf("after four days: %q, and the one before %s: %v", c, b, err)
}
}
// A pi package added without pi has pi installed with it (ensurePi), once;
// with pi there already, and for an OpenCode plugin, nothing is installed.
func TestEnsurePi(t *testing.T) {