claude: a saved account's .claude.json says magpie's work folder is trusted (#4830)

mydosu (#4830, Windows, v0.1.2679, Claude Code 2.1.316): since
d39358f1b the /usage reads and the "hi" test of a saved account run in
<tmp>/magpie-claude-work, and the account's config directory never got
a trusted entry for it. Every read waited out its 16.8s on the trust
question.

magpie now writes the entry itself, before each run there, into a saved
account's .claude.json (provider.ClaudeTrustFolder, gateway trustWork).
This covers every place Claude Code runs in that folder with a
non-default config dir: askClaudeTUI, claudeUsageTUI, and the bridge's
startRun when the caller's folder isn't used. The key is the one Claude
Code 2.1.316 looks a folder up by (its trust check, read from the
binary): the path in NFC, with forward slashes on Windows
("C:/Users/<me>/AppData/Local/Temp/magpie-claude-work"), and also with
its links resolved (/private/var/... on a Mac). For a Claude Code in WSL
it is the mount path. Only a direct child of claude-accounts is written,
never ~/.claude.json or the account Claude Code is signed in to. Other
keys and the project's own fields are kept, numbers go back as written
(UseNumber), a file that can't be parsed is left alone, and nothing is
written once the entry is there. A run's own fallback temp folder isn't
recorded. The helper's yes answer stays as it was.

I could not reproduce the missing entry itself. On xiaomi-gpu, Claude
Code 2.1.316 with a fake sign-in and the helper's yes recorded the key.
This fix does not depend on why it wasn't recorded on mydosu's machine.

Run at this head:
- mote: gofmt -l internal (empty); GOOS=linux and GOOS=windows go vet
  ./internal/gateway ./internal/provider; go test ./internal/provider
  ./internal/claudetui ok; go test -run
  'Claude|TUI|Usage|Warm|Ask|Trust|Subscription|Bridge'
  ./internal/gateway ok. The full gateway package was not run: two
  other sessions' full gateway suites were running on mote.
- xiaomi-gpu (win-run): go test -run
  'TestClaudeTrust|TestClaudeOneOffTrusts|TestClaudeBridgeTrusts'
  ./internal/provider ./internal/gateway ok (the shell-script ones
  skip there).
- xiaomi-gpu, real Claude Code 2.1.316 in a sandbox HOME/TEMP, helper
  told not to answer the question (MAGPIE_CLAUDE_TUI_TRUST=0). A saved
  account dir under a sandbox claude-accounts, with the entry written by
  trustWork (key "C:/Users/yeton/trust4830-sb/tmp/magpie-claude-work"):
  /usage drew its panel in 5.6s, exit 0. The same dir without the entry:
  "Claude Code asks whether to trust the folder" in 0.9s.

Broken by hand, each red:
- trustWork returning at once: TestClaudeOneOffTrustsMagpiesFolder,
  TestClaudeTrustWorkOnlyMagpiesFolderInSavedAccounts,
  TestClaudeBridgeTrustsMagpiesFolderForSavedAccount.
- the bridge's call dropped: TestClaudeBridgeTrustsMagpiesFolderForSavedAccount.
- no "/" for "\" on Windows: TestClaudeTrustKeysAsClaudeCodeKeys on
  mote, plus TestClaudeTrustWorkOnlyMagpiesFolderInSavedAccounts on
  Windows.
- no claude-accounts guard: TestClaudeTrustFolderOnlyMagpiesAccounts.

Not tried: a real signed-in saved account (the reporter's), and Claude
Code in WSL (the key is the mount path, by unit test only).
This commit is contained in:
yetone
2026-11-02 14:51:16 +08:00
parent f20e174aed
commit aab48dea94
6 changed files with 458 additions and 1 deletions
+13 -1
View File
@@ -362,7 +362,19 @@ folder only when it can't be made), where the helper may answer the trust
question, so a config directory holds one trusted entry for it instead of
a new `magpie-claude-<n>` entry each read (#4830, mydosu): 67 had piled up
in one `~/.claude.json`. Entries left by older magpies stay; magpie
doesn't write that file. The run's own session file in that folder is
doesn't write that file. In a saved account's config directory, magpie
writes the folder's entry itself before each run there (`trustWork`,
`provider.ClaudeTrustFolder`), and so before a bridge run of that
account in magpie's folder: on mydosu's Windows (#4830) the helper's
answer was never recorded there, and every read of the account waited
out its time on the question. The entry is keyed as Claude Code 2.1.316
looks a folder up (`claudeTrustKeys`): the path in NFC, with forward
slashes on Windows (`C:/Users/<me>/AppData/Local/Temp/magpie-claude-work`),
also with its links resolved (`/private/var/…` on a Mac), and the WSL
mount path for a Claude Code in WSL. Only a direct child of
`claude-accounts` is written, never `~/.claude.json`; every other key
is kept, a file that can't be parsed is left alone, and a run's own
fallback folder isn't recorded. The run's own session file in that folder is
removed by the `session_id` the helper's init line names (`dropOneOff`),
so the folder's project doesn't fill with "hi"s. The helper is told when
its caller stops waiting (`claudetui.DeadlineEnv`, the context's deadline
+4
View File
@@ -1059,6 +1059,10 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
// (startTrusted)
env = append(env, claudetui.TrustEnv+"=1")
}
if tui && !client {
// a saved account's run in magpie's folder is never asked (#4830)
trustWork(binary, configDir, work)
}
cmd.Env = binary.env(binary.asRoot(env), configDir)
if tui {
cmd.Env = binary.tuiEnv(cmd.Env, configDir)
+219
View File
@@ -0,0 +1,219 @@
package gateway
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/claudetui"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
"github.com/yetone/magpie/internal/wslrun"
)
// savedClaudeDir is a saved Claude account's config directory, as
// magpie keeps one (provider's claudeAccountDir), in a home of the
// test's own.
func savedClaudeDir(t *testing.T) string {
t.Helper()
home := t.TempDir()
testenv.SetHome(t, home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
dir := filepath.Join(filepath.Dir(provider.Path()), "claude-accounts", "0123456789abcdef")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
// a saved account as magpie writes it: onboarded, no projects
if err := os.WriteFile(filepath.Join(dir, ".claude.json"), []byte(`{"hasCompletedOnboarding": true}`), 0o600); err != nil {
t.Fatal(err)
}
return dir
}
// trustedIn is the projects .claude.json b records as trusted.
func trustedIn(t *testing.T, b []byte) []string {
t.Helper()
var m struct {
Projects map[string]struct {
Trusted bool `json:"hasTrustDialogAccepted"`
} `json:"projects"`
}
if err := json.Unmarshal(b, &m); err != nil {
t.Fatalf("%v: %s", err, b)
}
var out []string
for k, p := range m.Projects {
if p.Trusted {
out = append(out, k)
}
}
slices.Sort(out)
return out
}
// claudeKey is the key Claude Code 2.1.316 looks folder work up by: the
// path its links lead to, with forward slashes on Windows.
func claudeKey(work string) string { return filepath.ToSlash(evalSymlinks(work)) }
// mydosu's saved account (#4830, Windows, Claude Code 2.1.316) was asked
// whether to trust magpie's folder on every /usage read and every test,
// and each waited out its caller's time on the question. Before either
// runs, the account's .claude.json says the folder is trusted, under the
// path Claude Code runs in, which a Mac's getcwd gives with its links
// resolved (/private/var/… for /var/…).
func TestClaudeOneOffTrustsMagpiesFolder(t *testing.T) {
for _, c := range []struct {
name string
run func(ctx context.Context, cfg string) error
say string
}{
{"usage", func(ctx context.Context, cfg string) error { _, err := claudeUsage(ctx, cfg); return err }, `"local_command":"usage","result":"Current session: 1% used"`},
{"test", func(ctx context.Context, cfg string) error { return askClaude(ctx, cfg, "haiku") }, `"result":"Hi!"`},
} {
t.Run(c.name, func(t *testing.T) {
fakeWarmClaude(t, `{}`, 0)
claudeTUIRuns = true
t.Cleanup(func() { claudeTUIRuns = false })
t.Setenv("TMPDIR", t.TempDir())
cfg := savedClaudeDir(t)
seen := filepath.Join(t.TempDir(), "seen")
helper := filepath.Join(t.TempDir(), "magpie")
// what the account's file says as Claude Code starts
testenv.Program(t, helper, `#!/bin/sh
[ "$1" = "`+claudetui.Command+`" ] || exit 9
cat "$CLAUDE_CONFIG_DIR/.claude.json" > '`+seen+`'
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,`+c.say+`}'
cat > /dev/null
`)
claudeTUIHelper = helper
t.Cleanup(func() { claudeTUIHelper = "" })
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := c.run(ctx, cfg); err != nil {
t.Fatal(err)
}
work, err := claudeWorkDir()
if err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(seen)
if err != nil {
t.Fatal(err)
}
got := trustedIn(t, b)
if !slices.Contains(got, claudeKey(work)) {
t.Fatalf("Claude Code started with %v trusted, not magpie's folder %s: %s", got, claudeKey(work), b)
}
if !strings.Contains(string(b), `"hasCompletedOnboarding": true`) {
t.Fatalf("the account's other keys went: %s", b)
}
})
}
}
// The account Claude Code is signed in to (configDir "") keeps its own
// ~/.claude.json, which magpie never writes, and a folder of the run's
// own, made when magpie's can't be used, isn't recorded: each would
// leave one more trusted project behind.
func TestClaudeTrustWorkOnlyMagpiesFolderInSavedAccounts(t *testing.T) {
tmp := t.TempDir()
for _, v := range []string{"TMPDIR", "TMP", "TEMP"} {
t.Setenv(v, tmp)
}
cfg := savedClaudeDir(t)
home, _ := os.UserHomeDir()
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
work, err := claudeWorkDir()
if err != nil {
t.Fatal(err)
}
trustWork(claudeCLI{}, "", work)
for _, f := range []string{filepath.Join(home, ".claude.json"), filepath.Join(home, ".claude", ".claude.json")} {
if _, err := os.Stat(f); !os.IsNotExist(err) {
t.Errorf("%s was written", f)
}
}
own := t.TempDir()
trustWork(claudeCLI{}, cfg, own)
b, _ := os.ReadFile(filepath.Join(cfg, ".claude.json"))
if got := trustedIn(t, b); len(got) != 0 {
t.Errorf("a folder of the run's own was recorded: %v", got)
}
trustWork(claudeCLI{}, cfg, work)
b, _ = os.ReadFile(filepath.Join(cfg, ".claude.json"))
if got := trustedIn(t, b); !slices.Contains(got, claudeKey(work)) {
t.Errorf("magpie's folder wasn't recorded: %v", got)
}
}
// Claude Code 2.1.316 keys a project on Windows by its path with forward
// slashes (C:/Users/<me>/AppData/Local/Temp/magpie-claude-work): an entry
// under the backslashed path is never found, and the question is asked.
func TestClaudeTrustKeysAsClaudeCodeKeys(t *testing.T) {
old := trustGOOS
t.Cleanup(func() { trustGOOS = old })
trustGOOS = "windows"
// mydosu's folder, a name in NFD as a file system may give it
got := claudeTrustKeys(claudeCLI{}, "C:\\Users\\Me\u0301\\AppData\\Local\\Temp\\magpie-claude-work")
if want := "C:/Users/M\u00e9/AppData/Local/Temp/magpie-claude-work"; !slices.Contains(got, want) {
t.Errorf("keys %q, want %q among them", got, want)
}
for _, k := range got {
if strings.Contains(k, `\`) {
t.Errorf("key %q has a backslash", k)
}
}
trustGOOS = "linux"
if runtime.GOOS != "windows" {
if got := claudeTrustKeys(claudeCLI{}, `/tmp/a\b`); !slices.Contains(got, `/tmp/a\b`) {
t.Errorf("a backslash in a Unix name was changed: %v", got)
}
}
got = claudeTrustKeys(claudeCLI{wsl: &wslrun.Tool{Mount: "/mnt/"}}, `C:\Users\me\AppData\Local\Temp\magpie-claude-work`)
if len(got) != 1 || got[0] != "/mnt/c/Users/me/AppData/Local/Temp/magpie-claude-work" {
t.Errorf("Claude Code in WSL runs in its mount of the folder, keys %v", got)
}
}
// A saved account's bridge run in magpie's folder starts with the folder
// trusted too: the bridge's runs work there whenever the caller's own
// folder isn't one here.
func TestClaudeBridgeTrustsMagpiesFolderForSavedAccount(t *testing.T) {
h := tuiScriptHarness(t, `cat "$CLAUDE_CONFIG_DIR/.claude.json" > $log.seen`)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(os.Getenv("HOME"), ".config"))
cfg := filepath.Join(filepath.Dir(provider.Path()), "claude-accounts", "0123456789abcdef")
if err := os.MkdirAll(cfg, 0o700); err != nil {
t.Fatal(err)
}
req := &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hello"}}}}}
run, _, err := h.s.subscription.start(context.Background(), req, "claude-sonnet-5", cfg, "", nil)
if err != nil {
t.Fatal(err)
}
if !run.tui {
t.Fatal("the run wasn't interactive")
}
var b []byte
eventually(t, "the run read its account's file", func() bool {
entries, _ := os.ReadDir(h.logs)
for _, e := range entries {
if strings.HasSuffix(e.Name(), ".seen") {
b, _ = os.ReadFile(filepath.Join(h.logs, e.Name()))
}
}
return len(b) > 0
})
work, err := claudeWorkDir()
if err != nil {
t.Fatal(err)
}
if got := trustedIn(t, b); !slices.Contains(got, claudeKey(work)) {
t.Fatalf("the run started with %v trusted, not magpie's folder %s", got, claudeKey(work))
}
}
+51
View File
@@ -7,8 +7,11 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
@@ -18,6 +21,7 @@ import (
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
"golang.org/x/text/unicode/norm"
)
// claudeProxy is the proxy a Claude Code run on an account's behalf goes
@@ -95,6 +99,7 @@ func askClaudeTUI(ctx context.Context, binary claudeCLI, configDir, model string
return err
}
defer done()
trustWork(binary, configDir, work)
cmd, err := binary.tuiCommand(ctx, claudeTUIWarmArgs(model)...)
if err != nil {
return err
@@ -246,6 +251,7 @@ func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (st
return "", err
}
defer done()
trustWork(binary, configDir, work)
cmd, err := binary.tuiCommand(ctx, claudeTUIUsageArgs()...)
if err != nil {
return "", err
@@ -301,6 +307,51 @@ func oneOffDir() (dir string, done func(), err error) {
return tmp, func() { _ = os.RemoveAll(tmp) }, nil
}
// trustWork records, in a saved account's config directory (configDir,
// "" for the account Claude Code is signed in to, whose ~/.claude.json
// magpie never writes), that Claude Code may work in magpie's own folder
// work, before a run there: asked whether to trust it, a run of that
// account waited out its caller's time on the question (#4830, mydosu).
// A folder of the run's own (oneOffDir's fallback) is not recorded, so
// entries don't pile up.
func trustWork(binary claudeCLI, configDir, work string) {
if configDir == "" {
return
}
if filepath.Clean(work) != filepath.Join(os.TempDir(), claudeWorkName()) {
return
}
if err := provider.ClaudeTrustFolder(configDir, claudeTrustKeys(binary, work)...); err != nil {
log.Printf("claude: magpie's work folder not recorded as trusted for %s: %v", configDir, err)
}
}
// trustGOOS is the system claudeTrustKeys keys for; a var for tests.
var trustGOOS = runtime.GOOS
// claudeTrustKeys are the projects keys Claude Code looks a trusted folder
// up by when it runs in work (2.1.316, its trust check): the folder's path
// in NFC, on Windows with forward slashes ("C:/Users/<me>/AppData/Local/
// Temp/magpie-claude-work"), and the path its links lead to, which is the
// one a Mac's getcwd says (/private/var/… for /var/…). One in WSL runs in
// the distro's mount of it.
func claudeTrustKeys(binary claudeCLI, work string) []string {
if binary.wsl != nil {
return []string{binary.file(work)}
}
var keys []string
for _, w := range []string{work, evalSymlinks(work)} {
k := norm.NFC.String(filepath.Clean(w))
if trustGOOS == "windows" {
k = strings.ReplaceAll(k, `\`, "/")
}
if !slices.Contains(keys, k) {
keys = append(keys, k)
}
}
return keys
}
// dropOneOff removes the session a one-off interactive run left in
// magpie's folder, by its id (sid, "" when it told none): a test's "hi"
// keeps its transcript there. A folder of the run's own goes whole.
+72
View File
@@ -348,6 +348,78 @@ func claudeOnboarded(dir string, acct map[string]any) {
_ = writePrivate(profile, append(pb, '\n'))
}
// claudeTrustMu keeps two runs' ClaudeTrustFolder from writing one
// .claude.json at once.
var claudeTrustMu sync.Mutex
// ClaudeTrustFolder records, in saved account config directory dir, that
// Claude Code may work in magpie's own folder, which keys names as Claude
// Code keys its projects (2.1.316: the folder's path, on Windows with
// forward slashes, "C:/Users/<me>/AppData/Local/Temp/magpie-claude-work"),
// as Claude Code itself records it once the trust question is answered
// yes. On mydosu's Windows (#4830) a saved account's directory had no
// such entry, and every /usage read of that account waited out its time
// on the question.
// Only a directory of magpie's saved accounts is written, never the
// user's own ~/.claude.json; every other key is kept, and a file that
// can't be read or parsed, which Claude Code may be writing, is left as it
// is.
func ClaudeTrustFolder(dir string, keys ...string) error {
root := filepath.Clean(claudeDirsRoot())
dir = filepath.Clean(dir)
if rel, err := filepath.Rel(root, dir); err != nil || rel == "." || strings.HasPrefix(rel, "..") || strings.ContainsAny(rel, `/\`) {
return fmt.Errorf("%s is not a saved Claude account's folder", dir)
}
claudeTrustMu.Lock()
defer claudeTrustMu.Unlock()
profile := filepath.Join(dir, ".claude.json")
m := map[string]any{}
b, err := os.ReadFile(profile)
switch {
case os.IsNotExist(err):
case err != nil:
return err
default:
d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber() // Claude Code's numbers go back as they were written
if err := d.Decode(&m); err != nil || m == nil {
return fmt.Errorf("%s can't be read: %v", profile, err)
}
}
projects, ok := m["projects"].(map[string]any)
if !ok {
if _, there := m["projects"]; there {
return fmt.Errorf("%s has projects that aren't an object", profile)
}
projects = map[string]any{}
}
changed := false
for _, k := range keys {
if k == "" {
continue
}
p, ok := projects[k].(map[string]any)
if !ok {
p = map[string]any{}
}
if t, _ := p["hasTrustDialogAccepted"].(bool); t {
continue
}
p["hasTrustDialogAccepted"] = true
projects[k] = p
changed = true
}
if !changed {
return nil
}
m["projects"] = projects
pb, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
return writePrivate(profile, append(pb, '\n'))
}
// syncClaudeDir brings the saved Claude login l up to what Claude Code
// keeps in the account's config directory: the sign-in it refreshed to
// there, or, when it emptied that sign-in, Anthropic's refusal of the one
+99
View File
@@ -0,0 +1,99 @@
package provider
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"
)
// mydosu's saved account (#4830, Windows, Claude Code 2.1.316) had a
// .claude.json with no projects at all, so Claude Code asked whether to
// trust magpie's work folder on every /usage read. ClaudeTrustFolder puts
// the entry there as Claude Code keeps it, every other key and the
// project's own fields kept, and writes nothing once it is there.
func TestClaudeTrustFolderRecordsMagpiesFolder(t *testing.T) {
claudeHome(t)
dir := claudeAccountDir("someone@example.com")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
profile := filepath.Join(dir, ".claude.json")
key := "C:/Users/me/AppData/Local/Temp/magpie-claude-work"
// onboarding done, magpie's folder there untrusted; a big number as
// Claude Code writes them
stale := `{"hasCompletedOnboarding": true, "numStartups": 3, "big": 12345678901234567890,
"projects": {"C:/elsewhere": {"allowedTools": [], "hasTrustDialogAccepted": false},
"` + key + `": {"lastCost": 0.5, "hasTrustDialogAccepted": false}}}`
if err := os.WriteFile(profile, []byte(stale), 0o600); err != nil {
t.Fatal(err)
}
if err := ClaudeTrustFolder(dir, key, "/private/"+key); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(profile)
var m map[string]any
d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber()
if err := d.Decode(&m); err != nil {
t.Fatalf("%v: %s", err, b)
}
if m["hasCompletedOnboarding"] != true || m["numStartups"] != json.Number("3") || m["big"] != json.Number("12345678901234567890") {
t.Fatalf("other keys changed: %s", b)
}
ps := m["projects"].(map[string]any)
for _, k := range []string{key, "/private/" + key} {
if p, _ := ps[k].(map[string]any); p["hasTrustDialogAccepted"] != true {
t.Errorf("%s is %v, want trusted: %s", k, ps[k], b)
}
}
if p := ps[key].(map[string]any); p["lastCost"] != json.Number("0.5") {
t.Errorf("the project's own fields went: %v", p)
}
if p := ps["C:/elsewhere"].(map[string]any); p["hasTrustDialogAccepted"] != false {
t.Errorf("another folder was trusted: %v", p)
}
// there already: nothing is written
if err := os.WriteFile(profile, append(b, ' '), 0o600); err != nil {
t.Fatal(err)
}
if err := ClaudeTrustFolder(dir, key); err != nil {
t.Fatal(err)
}
if again, _ := os.ReadFile(profile); !bytes.Equal(again, append(b, ' ')) {
t.Errorf("a trusted folder was written again")
}
}
// Only a saved account's directory is written: never the user's own
// ~/.claude.json, nor a file Claude Code may be half way through writing.
func TestClaudeTrustFolderOnlyMagpiesAccounts(t *testing.T) {
home := claudeHome(t)
key := "/tmp/magpie-claude-work-501"
for _, dir := range []string{home, filepath.Join(home, ".claude"), claudeDirsRoot(), filepath.Join(claudeAccountDir("a"), "x")} {
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := ClaudeTrustFolder(dir, key); err == nil {
t.Errorf("%s was written", dir)
}
if _, err := os.Stat(filepath.Join(dir, ".claude.json")); !os.IsNotExist(err) {
t.Errorf("%s has a .claude.json", dir)
}
}
dir := claudeAccountDir("b")
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
half := []byte(`{"numStartups": 3, "proj`)
if err := os.WriteFile(filepath.Join(dir, ".claude.json"), half, 0o600); err != nil {
t.Fatal(err)
}
if err := ClaudeTrustFolder(dir, key); err == nil {
t.Errorf("a half-written file was taken")
}
if b, _ := os.ReadFile(filepath.Join(dir, ".claude.json")); !bytes.Equal(b, half) {
t.Errorf("a half-written file was changed: %s", b)
}
}