From 7d1f2ecba35bdaee25ea1b131a7f294900c4dcd8 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 19:00:47 +0800 Subject: [PATCH] claudecode: magpie keeps the Claude Code it downloaded at the newest release alextjy on Discord runs magpie in Docker with Claude Code from `magpie claude-code install`, and asked whether a magpie update touches it and how it updates. The download lives in /claude-code (/config/cache, on the volume), so a new image keeps it. But nothing ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it stayed at the version first installed until the user ran install again. claudecode.KeepCurrent now runs while magpie serves (a WhileServing loop): a minute after start and every six hours it asks downloads.claude.ai for the latest release and downloads a newer one, checked against the manifest's SHA-256 and size as install does. The version it replaced is removed on the next look rather than at once, since a run being started may hold its path (Install, the CLI's, still removes it at once; a folder with a .part download in it is left alone). It does nothing when magpie downloaded none, when the machine has its own `claude` (that one is run and updates itself), or when DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a version. A failed look keeps the download and is logged. It never downgrades. The status line of `magpie claude-code`, the Docker docs (en, zh, ja) and the bridge's subsystem page say so. Run: - wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v ./internal/claudecode/ -run 'Keep|Install|Find': all pass. - Broken by hand on WSL, each red: no newer() check (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own() check (the_machine's_own), pruning at install (UpdatesMagpiesDownload), no prune on the next look (UpdatesMagpiesDownload). - Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program with a fake 2.1.1 download ran KeepCurrent against the real downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to 2.1.316", the kept binary's --version said "2.1.316 (Claude Code)", 2.1.1 was still there for the next look, and the loop ended with its context. - mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of both packages, go vet ./internal/claudecode/, go build ., then go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m: VET-OK; claudecode ok 0.680s, cli ok 56.673s. - gofmt -l clean. Not tried: the Docker image itself (no docker on the test boxes), and a Windows run whose replaced binary is still in use (prune leaves what it can't remove for the next look). Full suite not run: the change is the claudecode package, one WhileServing line and one CLI status line. A WSL run of ./internal/cli/ at the default 10m timeout timed out while the box ran other sessions' full suites; the 45m run above replaces it. --- docs/subsystems/claude-subscription-bridge.md | 15 +- internal/claudecode/claudecode.go | 33 +++- internal/claudecode/keep.go | 81 +++++++++ internal/claudecode/keep_test.go | 169 ++++++++++++++++++ internal/cli/claude_code_cli.go | 2 +- internal/cli/main.go | 5 + site/public/docs/docker.html | 2 +- site/public/docs/ja/docker.html | 2 +- site/public/docs/zh/docker.html | 2 +- 9 files changed, 299 insertions(+), 12 deletions(-) create mode 100644 internal/claudecode/keep.go create mode 100644 internal/claudecode/keep_test.go diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 58e234990..ad5ec95ba 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -20,9 +20,17 @@ platform's SHA-256 and size, and a build that doesn't match both is not kept. It is only made when the user asks (`magpie claude-code install`, or yes to `magpie accounts add claude`'s offer on a machine without one), for a server or a container (Jorben on Discord). It is not on PATH and stands -in for no agent. It doesn't update itself (the bridge sets -`DISABLE_AUTOUPDATER`); installing again takes the newest and removes the -older one. +in for no agent. It doesn't update itself (every run magpie starts sets +`DISABLE_AUTOUPDATER`), so the serving magpie keeps it current +(`claudecode.KeepCurrent`, a `WhileServing` loop): a minute after it +starts and every six hours it asks for the latest release and downloads a +newer one, checked the same way. The version it replaced is removed on the +next look, not at once, as a run being started may hold its path; +`magpie claude-code install` removes it at once. It does nothing when +magpie downloaded none, when the machine has its own `claude`, or when +`DISABLE_AUTOUPDATER` is set for magpie (alextjy on Discord: a container's +download stayed at its first version across image updates). A failed look +keeps the download as it is and is logged. A run is started with `--dangerously-skip-permissions` (`claudeCLIArgs`): its only tools are magpie's MCP ones, answered by the client, and @@ -1161,6 +1169,7 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeLeanPrompt' -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeTUIChosen$' -count=1 go test ./internal/claudetui/ -count=1 go test -tags nogui ./internal/claudecode/ -count=1 +go test -tags nogui ./internal/claudecode/ -run TestKeepCurrent -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForASOCKSProxy$' -count=1 go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1 go test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1 diff --git a/internal/claudecode/claudecode.go b/internal/claudecode/claudecode.go index e41a0c507..262f9008d 100644 --- a/internal/claudecode/claudecode.go +++ b/internal/claudecode/claudecode.go @@ -6,7 +6,9 @@ // takes it: the release's manifest.json names each platform's SHA-256 and // size, and the binary is checked against both before it is kept. It is // kept in magpie's cache folder, not on PATH, so it stands in for no agent: -// it is only what the bridge and the sign-in run. +// it is only what the bridge and the sign-in run. While magpie serves, it +// keeps that download at the newest release (KeepCurrent), as Claude +// Code's own updater would, which magpie's runs turn off. package claudecode import ( @@ -215,6 +217,15 @@ func get(ctx context.Context, url string, limit int64) ([]byte, error) { // has none of its own; the versions downloaded before are removed. progress, // when set, is told the bytes so far. It returns the binary's path. func Install(ctx context.Context, r Release, progress func(done int64)) (string, error) { + exe, err := install(ctx, r, progress) + if err == nil { + prune(r.Version) + } + return exe, err +} + +// install is Install without removing the versions before it. +func install(ctx context.Context, r Release, progress func(done int64)) (string, error) { dir := filepath.Join(Root(), r.Version) if !versionRe.MatchString(r.Version) { return "", fmt.Errorf("not a version: %q", r.Version) @@ -232,14 +243,26 @@ func Install(ctx context.Context, r Release, progress func(done int64)) (string, os.Remove(tmp) return "", err } - // one version kept: what a run takes is the newest, and each is ~240 MB + return exe, nil +} + +// prune removes every version but kept: what a run takes is the newest, and +// each is ~240 MB. A folder with a download under way (a .part) stays. +// Removing the binary of a Claude Code still running is fine on Linux and +// macOS (the run keeps its file); on Windows that one stays, for the next +// prune. +func prune(kept string) { ents, _ := os.ReadDir(Root()) for _, e := range ents { - if e.IsDir() && e.Name() != r.Version && versionRe.MatchString(e.Name()) { - _ = os.RemoveAll(filepath.Join(Root(), e.Name())) + if !e.IsDir() || e.Name() == kept || !versionRe.MatchString(e.Name()) { + continue } + dir := filepath.Join(Root(), e.Name()) + if _, err := os.Stat(filepath.Join(dir, exeName(runtime.GOOS)+".part")); err == nil { + continue + } + _ = os.RemoveAll(dir) } - return exe, nil } func download(ctx context.Context, r Release, to string, progress func(int64)) error { diff --git a/internal/claudecode/keep.go b/internal/claudecode/keep.go new file mode 100644 index 000000000..2be75f9cf --- /dev/null +++ b/internal/claudecode/keep.go @@ -0,0 +1,81 @@ +package claudecode + +import ( + "context" + "fmt" + "log" + "os" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// When KeepCurrent first looks, and how often after that; vars for tests. +var ( + keepFirst = time.Minute + keepEvery = 6 * time.Hour +) + +// keep is what KeepCurrent reads of the machine; tests stand in for it. +var keep = struct { + own func() string + latest func(context.Context) (Release, error) +}{ + own: func() string { return proc.FindTool("claude") }, + latest: Latest, +} + +// KeepCurrent keeps the Claude Code magpie downloaded at Claude Code's +// newest release while magpie serves: a minute after it starts and every six +// hours after. Every run magpie starts sets DISABLE_AUTOUPDATER, so nothing +// else updates it, and a container's download (in /config/cache, on the +// volume) would otherwise stay at the version first installed, image +// update after image update (alextjy on Discord). It does nothing when +// magpie downloaded none, when the machine has a Claude Code of its own +// (that one is run, and updates itself), or when DISABLE_AUTOUPDATER is set +// for magpie: Claude Code's own way of holding a version. +func KeepCurrent(ctx context.Context) { + t := time.NewTimer(keepFirst) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + if said, err := keepOnce(ctx); err != nil { + log.Printf("Claude Code: keeping magpie's download current: %v", err) + } else if said != "" { + log.Print(said) + } + t.Reset(keepEvery) + } +} + +// keepOnce updates magpie's download when a newer release is out, and says +// what it did ("" for nothing). The version an earlier look replaced goes +// first: no run has been started on it since then. +func keepOnce(ctx context.Context) (string, error) { + path, v := Downloaded() + if path == "" || keep.own() != "" || os.Getenv("DISABLE_AUTOUPDATER") != "" { + return "", nil + } + prune(v) + lctx, cancel := context.WithTimeout(ctx, 30*time.Second) + r, err := keep.latest(lctx) + cancel() + if err != nil { + return "", err + } + if !newer(r.Version, v) { + return "", nil + } + dctx, cancel := context.WithTimeout(ctx, 30*time.Minute) + defer cancel() + // the old version stays until the next look: a run being started now + // may have been handed its path + if _, err := install(dctx, r, nil); err != nil { + return "", fmt.Errorf("Claude Code %s: %w", r.Version, err) + } + return fmt.Sprintf("Claude Code: magpie's download updated from %s to %s", v, r.Version), nil +} diff --git a/internal/claudecode/keep_test.go b/internal/claudecode/keep_test.go new file mode 100644 index 000000000..4748f3095 --- /dev/null +++ b/internal/claudecode/keep_test.go @@ -0,0 +1,169 @@ +package claudecode + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +// keepRelease serves 2.1.287 as downloads.claude.ai does and counts what is +// asked: the latest version, and the build's download. +func keepRelease(t *testing.T, latestV string) (asked, downloads *atomic.Int32) { + t.Helper() + const body = "#!/bin/sh\necho 2.1.287 '(Claude Code)'\n" + platform := thisPlatform(t) + asked, downloads = new(atomic.Int32), new(atomic.Int32) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/latest": + asked.Add(1) + fmt.Fprint(w, latestV) + case "/2.1.287/manifest.json": + fmt.Fprint(w, manifest(platform, body)) + case "/2.1.287/" + platform + "/" + exeName(runtime.GOOS): + downloads.Add(1) + fmt.Fprint(w, body) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + oldBase, oldKeep := Base, keep + Base = srv.URL + keep.own = func() string { return "" } + keep.latest = func(ctx context.Context) (Release, error) { + return latest(ctx, runtime.GOOS, runtime.GOARCH, false) + } + t.Cleanup(func() { Base, keep = oldBase, oldKeep }) + t.Cleanup(func() { _ = Remove() }) + t.Setenv("DISABLE_AUTOUPDATER", "") + return asked, downloads +} + +// downloaded puts a Claude Code of version v where magpie keeps its own. +func downloaded(t *testing.T, v string) string { + t.Helper() + dir := filepath.Join(Root(), v) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, exeName(runtime.GOOS)) + if err := os.WriteFile(p, []byte("old"), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func TestKeepCurrentUpdatesMagpiesDownload(t *testing.T) { + asked, downloads := keepRelease(t, "2.1.287\n") + old := downloaded(t, "2.1.200") + + said, err := keepOnce(context.Background()) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(said, "2.1.200 to 2.1.287") { + t.Errorf("said %q", said) + } + if p, v := Downloaded(); v != "2.1.287" || p == old { + t.Fatalf("Downloaded() = %q, %q; want 2.1.287", p, v) + } + // a run started a moment ago may hold the old path: it stays for now + if _, err := os.Stat(old); err != nil { + t.Errorf("the replaced version went at once: %v", err) + } + + // the next look removes it, and downloads nothing again + if said, err := keepOnce(context.Background()); err != nil || said != "" { + t.Fatalf("second look: %q, %v", said, err) + } + if _, err := os.Stat(filepath.Dir(old)); !os.IsNotExist(err) { + t.Errorf("the replaced version is still there on the next look: %v", err) + } + if asked.Load() != 2 || downloads.Load() != 1 { + t.Errorf("asked %d times, downloaded %d; want 2 and 1", asked.Load(), downloads.Load()) + } +} + +func TestKeepCurrentLeavesWhatIsntMagpiesToUpdate(t *testing.T) { + for name, set := range map[string]func(t *testing.T){ + "nothing downloaded": func(t *testing.T) {}, + "the machine's own": func(t *testing.T) { + downloaded(t, "2.1.200") + keep.own = func() string { return "/usr/local/bin/claude" } + }, + "held by the user": func(t *testing.T) { downloaded(t, "2.1.200"); t.Setenv("DISABLE_AUTOUPDATER", "1") }, + "already the newest": func(t *testing.T) { downloaded(t, "2.1.287") }, + "newer than the latest": func(t *testing.T) { downloaded(t, "2.1.300") }, + } { + t.Run(name, func(t *testing.T) { + _, downloads := keepRelease(t, "2.1.287") + set(t) + _, before := Downloaded() + if said, err := keepOnce(context.Background()); err != nil || said != "" { + t.Fatalf("keepOnce = %q, %v", said, err) + } + if downloads.Load() != 0 { + t.Errorf("downloaded %d times", downloads.Load()) + } + if _, v := Downloaded(); v != before { + t.Errorf("Downloaded() is %q, was %q", v, before) + } + }) + } +} + +func TestKeepCurrentKeepsTheDownloadWhenTheReleaseCantBeRead(t *testing.T) { + keepRelease(t, "Unavailable") + old := downloaded(t, "2.1.200") + if _, err := keepOnce(context.Background()); err == nil { + t.Fatal("no error for a release that couldn't be read") + } + if p, v := Downloaded(); p != old || v != "2.1.200" { + t.Errorf("Downloaded() = %q, %q; want the old one kept", p, v) + } + + keep.latest = func(context.Context) (Release, error) { return Release{}, errors.New("offline") } + if _, err := keepOnce(context.Background()); err == nil { + t.Fatal("no error when offline") + } + if p, _ := Downloaded(); p != old { + t.Errorf("Downloaded() = %q; want the old one kept", p) + } +} + +func TestKeepCurrentLooksWhileServingAndEndsWithIt(t *testing.T) { + keepRelease(t, "2.1.287") + downloaded(t, "2.1.200") + oldFirst, oldEvery := keepFirst, keepEvery + keepFirst, keepEvery = 0, time.Hour + t.Cleanup(func() { keepFirst, keepEvery = oldFirst, oldEvery }) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { KeepCurrent(ctx); close(done) }() + defer func() { cancel(); <-done }() + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if _, v := Downloaded(); v == "2.1.287" { + break + } + if time.Now().After(deadline) { + t.Fatal("KeepCurrent never updated the download") + } + } + cancel() + select { + case <-done: + case <-time.After(20 * time.Second): + t.Fatal("KeepCurrent didn't end with its context") + } +} diff --git a/internal/cli/claude_code_cli.go b/internal/cli/claude_code_cli.go index a79d5c7a6..312df7a19 100644 --- a/internal/cli/claude_code_cli.go +++ b/internal/cli/claude_code_cli.go @@ -232,7 +232,7 @@ func claudeCodeStatus() error { } case path != "": fmt.Println(green.Render("●"), "Claude Code", v, muted.Render(path), muted.Render("· downloaded by magpie")) - fmt.Println(muted.Render(" magpie claude-code install gets the newest · magpie claude-code remove deletes it")) + fmt.Println(muted.Render(" magpie keeps it at the newest release while it runs (DISABLE_AUTOUPDATER=1 holds it) · magpie claude-code remove deletes it")) default: fmt.Println(amber.Render("○"), "no Claude Code here: a Claude subscription can't be signed in to or answered") fmt.Println(muted.Render(" install it (https://code.claude.com/docs), or magpie claude-code install downloads Anthropic's own build for magpie")) diff --git a/internal/cli/main.go b/internal/cli/main.go index 31abae908..08ed3e8d7 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -18,6 +18,7 @@ import ( "github.com/yetone/magpie/internal/browsermcp" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/claudebridge" + "github.com/yetone/magpie/internal/claudecode" "github.com/yetone/magpie/internal/claudetui" "github.com/yetone/magpie/internal/codexrelay" "github.com/yetone/magpie/internal/davsync" @@ -408,6 +409,10 @@ func run(args []string) error { // and Claude Science's daemon, which a restart of the computer ends, // started on the gateway again while it is connected gateway.WhileServing = append(gateway.WhileServing, agent.KeepClaudeScience) + // and the Claude Code magpie downloaded for a machine with none (a + // server's, a container's), at Claude Code's newest release: its runs + // turn its own updater off + gateway.WhileServing = append(gateway.WhileServing, claudecode.KeepCurrent) // and the request archive, when it is on, goes to the bucket sync is to gateway.ArchiveBucket = func() (gateway.Putter, bool) { if b, ok := davsync.S3Bucket(); ok { diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index a1ca1d5e6..cab4c6892 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -137,7 +137,7 @@ docker logs magpie
docker exec -it magpie magpie accounts add codex

Open the link it prints, sign in, then paste the address the browser ended on. The browser UI can also import sign-ins from a file.

-

A Claude subscription is signed in to and answered through Claude Code, which the image doesn’t have. Have magpie download Anthropic’s own build first: it says the version, where it comes from and where it goes, asks, and checks the download’s SHA-256 against Anthropic’s manifest. It is kept in /config/cache; run it again for a newer one. magpie accounts add claude offers it too when Claude Code is missing.

+

A Claude subscription is signed in to and answered through Claude Code, which the image doesn’t have. Have magpie download Anthropic’s own build first: it says the version, where it comes from and where it goes, asks, and checks the download’s SHA-256 against Anthropic’s manifest. It is kept in /config/cache, on the volume, so a new image keeps it, and magpie keeps it at Claude Code’s newest release by itself: it looks a minute after it starts and every six hours, and downloads a newer one the same way. Nothing needs installing again after an update. To hold a version, set -e DISABLE_AUTOUPDATER=1. magpie accounts add claude offers it too when Claude Code is missing.

Shell diff --git a/site/public/docs/ja/docker.html b/site/public/docs/ja/docker.html index 3fe04e155..e9c4cc7f5 100644 --- a/site/public/docs/ja/docker.html +++ b/site/public/docs/ja/docker.html @@ -137,7 +137,7 @@ docker logs magpie
docker exec -it magpie magpie accounts add codex

表示されたリンクを開いてサインインし、ブラウザが最後に表示したアドレスを貼り付けます。ブラウザ UI からはファイルからサインインを取り込むこともできます。

-

Claude サブスクリプションのサインインとリクエストは Claude Code を通りますが、イメージには入っていません。先に magpie に Anthropic 公式のビルドをダウンロードさせます。バージョン、ダウンロード元、保存先を示して確認してからダウンロードし、Anthropic のマニフェストにある SHA-256 で検証します。/config/cache に保存され、もう一度実行すると新しいバージョンになります。Claude Code がないときは magpie accounts add claude もダウンロードを提案します。

+

Claude サブスクリプションのサインインとリクエストは Claude Code を通りますが、イメージには入っていません。先に magpie に Anthropic 公式のビルドをダウンロードさせます。バージョン、ダウンロード元、保存先を示して確認してからダウンロードし、Anthropic のマニフェストにある SHA-256 で検証します。ボリューム上の /config/cache に保存されるので新しいイメージでも残り、magpie が Claude Code の最新リリースに自動で保ちます。起動の 1 分後と、その後 6 時間ごとに確認し、新しいバージョンがあれば同じように検証してダウンロードします。更新のたびに入れ直す必要はありません。バージョンを固定するには -e DISABLE_AUTOUPDATER=1 を設定します。Claude Code がないときは magpie accounts add claude もダウンロードを提案します。

Shell diff --git a/site/public/docs/zh/docker.html b/site/public/docs/zh/docker.html index 04b624308..8b754bbb9 100644 --- a/site/public/docs/zh/docker.html +++ b/site/public/docs/zh/docker.html @@ -137,7 +137,7 @@ docker logs magpie
docker exec -it magpie magpie accounts add codex

打开它打印的链接并登录,再把浏览器最后停在的地址粘贴回去。Web 界面也能从文件导入登录。

-

Claude 订阅的登录和请求都经过 Claude Code,而镜像里没有它。先让 magpie 下载 Anthropic 官方的构建:它会说明版本、下载来源和保存位置,问过你再下载,并用 Anthropic 清单里的 SHA-256 校验。它保存在 /config/cache 里;再运行一次可以更新到新版本。缺少 Claude Code 时,magpie accounts add claude 也会提出下载。

+

Claude 订阅的登录和请求都经过 Claude Code,而镜像里没有它。先让 magpie 下载 Anthropic 官方的构建:它会说明版本、下载来源和保存位置,问过你再下载,并用 Anthropic 清单里的 SHA-256 校验。它保存在卷里的 /config/cache,换新镜像也还在;magpie 会自己让它保持在 Claude Code 的最新版本:启动一分钟后检查一次,之后每六小时一次,有新版本就同样校验后下载。更新 magpie 后不用重新安装。想固定某个版本,设置 -e DISABLE_AUTOUPDATER=1。缺少 Claude Code 时,magpie accounts add claude 也会提出下载。

Shell