claude: a switch waits for another magpie's runs in the account's directory (#4532)
StringKe's audit, item 2. claudeDirRun is an in-process RWMutex, so
`magpie accounts switch` from the CLI never waited for the app's /usage,
warm-up or keep-alive run in the saved account's directory: it handed
Claude Code the refresh token that run could still spend, and removed
the directory under it. And the gateway's hand-over let go only of idle
runs; a run in a turn when the switch came was kept for its next turn,
waiting up to idleLongest in the removed directory with the same token.
- inSavedClaudeDir also holds a lock file of its own beside the
account's directory (markClaudeRun, <dir>.run-<pid>-<n>.lock,
filelock), removed as it ends.
- switchSavedLogin waits on every such file (waitClaudeRuns) up to
claudeRunWait (90s), then fails with errClaudeRunning and leaves the
sign-in as it was. A file whose run ended without removing it is free
and taken out.
- handedOver marks the account's runs in a turn (subscriptionRun.handed);
keepIdle ends such a run instead of keeping it.
Shelved (parked) sessions hold no process or token; a later turn starts
a new run under the account the gateway picks then, so nothing changes
there.
Run (mote, nogui):
- new tests TestClaudeSwitchWaitsForAnotherMagpiesRun,
TestClaudeSwitchRunHeldAndLeft, TestSavedClaudeRunHoldsItsLock,
TestClaudeHandOverEndsTheAccountsBusyRuns, plus TestClaudeSwitch*,
TestSavedClaude*, TestClaudeHandOver*: ok.
- Broken by hand (wait call, run mark and the handed check taken out,
helpers kept): all four new tests red ("switched while another magpie
ran Claude Code…", "got <nil>", "a left lock file kept", "run locks []",
"a run of the handed-over account was kept for its next turn").
- go vet darwin/linux/windows for provider and gateway: ok.
- Windows (win-run): the three provider tests and
TestSavedClaudeUsageKeepsRotatedSignIn: ok.
Not tried: two real magpie processes with a real Claude Code (the other
process is a second open of the lock file, which flock and LockFileEx
treat as another holder; filelock's own test covers a real second
process). Not covered, filed as #4750: a run queued behind the switch
makes the handed-over account's directory again, and a run in a turn
can still refresh during that turn.
This commit is contained in:
@@ -292,7 +292,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. `savedTokenMu` stops two requests refreshing one saved account at once.
|
||||
- A Claude subscription account is used only for Claude Code, through the genuine Claude Code binary (see [Claude subscription bridge](claude-subscription-bridge.md)).
|
||||
- Claude usage asks are ordered by `claudeAskGeneration`, not wall-clock timestamps. `AskClaudeUsage` and a Claude card's `RefreshUsage` advance it while holding the subscription cache then the login cache lock (`markClaudeUsageAsked`). Each cache captures it under its own lock before launching a read and checks it under that lock when publishing: a newer ask prevents `LoginUsage` from keeping the older reading and leaves `SubscriptionUsage` due to read again. Each `claudeWindows` entry records the generation its run answered. The timestamp's zero sentinel, `tried`/`wait`, the 30-second floor, idle behavior and saved-account scope remain unchanged. [`login_usage.go`](../../internal/provider/login_usage.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go).
|
||||
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, `magpie quota` and `magpie accounts` ask every card and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first, and after the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run goes through the account's reading as a card refresh's does (`keepingAlive` has `claudeWindows` run it, past the 30-second floor; `loginReading` keeps it beside the account and on disk, `keepCardRead` on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits `keepAliveRetry` (6 hours, `renewWaiting`) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it; `magpie accounts refresh` tries it at once (`TestRenewLoginsKeepsSavedClaudeSignedIn`, `TestRenewLoginsKeepsClaudeReading`, `TestRenewLoginsFailedWaitsItsTurn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
|
||||
- A saved Claude account's allowance is read only when its own card is refreshed (#1630; `savedRefresh`: `RefreshUsage` for that account, so `cardRefresh.wants` it and the read is asked). The real Claude Code runs `/usage` with `CLAUDE_CONFIG_DIR` set to the account's `claudeSavedDir` (`readSavedClaudeUsage`, through the gateway's `claudeUsage`), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, `magpie quota` and `magpie accounts` ask every card and so start no saved account's Claude Code: they keep its last reading, or `errClaudeSaved` before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So `inSavedClaudeDir` holds `claudeDirRun(user)` for reading while it runs, which `switchSavedLogin` takes for writing first. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (`markClaudeRun`, `<dir>.run-<pid>-<n>.lock`), and the switch waits on every one there first (`waitClaudeRuns`, up to `claudeRunWait`, 90s, then `errClaudeRunning` with the sign-in left as it was): before, `magpie accounts switch` didn't wait for the app's run (#4532; `TestClaudeSwitchWaitsForAnotherMagpiesRun`, `TestClaudeSwitchRunHeldAndLeft`). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (`handedOver`, `subscriptionRun.handed`, `TestClaudeHandOverEndsTheAccountsBusyRuns`). After the run `syncSavedClaude` copies a rotated sign-in back into `logins.json` under `savedTokenMu` and `loginsMu`. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (`keepAliveEvery`, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's, `RenewLogins` runs that `/usage` once for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (`claudeKeptAlive`, `renewClaude`), so Claude Code refreshes the sign-in if it is due and `syncSavedClaude` keeps it. The run goes through the account's reading as a card refresh's does (`keepingAlive` has `claudeWindows` run it, past the 30-second floor; `loginReading` keeps it beside the account and on disk, `keepCardRead` on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks `Renewed`, refreshed or not. A refusal is kept as a request's is (`NoteClaudeSignInFailure`, or the emptied sign-in `syncClaudeDir` reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits `keepAliveRetry` (6 hours, `renewWaiting`) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it; `magpie accounts refresh` tries it at once (`TestRenewLoginsKeepsSavedClaudeSignedIn`, `TestRenewLoginsKeepsClaudeReading`, `TestRenewLoginsFailedWaitsItsTurn`). [`claude_usage_saved_test.go`](../../internal/provider/claude_usage_saved_test.go) covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; `TestClaudeUsageRunsInSavedAccountDirectory` checks the directory the command runs in.
|
||||
- Claude Code's `/usage` prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). `claudeResetTime` reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and `claudeResetSlack`: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
|
||||
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
|
||||
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
|
||||
|
||||
@@ -43,3 +43,36 @@ func TestClaudeHandOverLetsGoOfTheAccountsRuns(t *testing.T) {
|
||||
t.Fatalf("idle runs after the hand-over: %d, moved kept %v", n, kept)
|
||||
}
|
||||
}
|
||||
|
||||
// #4532: a run in a turn as its account is handed over isn't kept for the
|
||||
// next turn when this one ends: kept, it waited up to idleLongest in the
|
||||
// removed directory with the refresh token that is Claude Code's now.
|
||||
// Another account's run in a turn is kept as before.
|
||||
func TestClaudeHandOverEndsTheAccountsBusyRuns(t *testing.T) {
|
||||
b := newSubscriptionBridge()
|
||||
run := func(owner string) *subscriptionRun {
|
||||
r := &subscriptionRun{bridge: b, token: owner, pending: map[string]chan mcpToolResult{}}
|
||||
r.owner.Store(&owner)
|
||||
b.mu.Lock()
|
||||
b.runs[owner] = r // in a turn: a run, not waiting
|
||||
b.mu.Unlock()
|
||||
return r
|
||||
}
|
||||
moved := run("claude\x00b@example.com")
|
||||
other := run("claude\x00a@example.com")
|
||||
|
||||
provider.ClaudeHandedOver("b@example.com")
|
||||
|
||||
if b.keepIdle(moved, "next", "") || !moved.closed {
|
||||
t.Fatal("a run of the handed-over account was kept for its next turn")
|
||||
}
|
||||
if !b.keepIdle(other, "other", "") || other.closed {
|
||||
t.Fatal("another account's run in a turn was let go")
|
||||
}
|
||||
b.mu.Lock()
|
||||
_, kept := b.idle["next"]
|
||||
b.mu.Unlock()
|
||||
if kept {
|
||||
t.Fatal("the handed-over account's run waits for a next turn")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,6 +191,10 @@ type subscriptionRun struct {
|
||||
idleKey string
|
||||
idleAt time.Time
|
||||
convKey string
|
||||
// handed is set (b.mu held) when its account was handed over to
|
||||
// Claude Code itself during a turn (handedOver): it isn't kept for
|
||||
// the next one
|
||||
handed bool
|
||||
// loose is the conversation it waits at as a client may send it back
|
||||
// rewritten (looseTurn)
|
||||
loose *looseTurn
|
||||
@@ -519,7 +523,9 @@ func init() {
|
||||
// directory of the saved Claude account user, now Claude Code's own sign-in
|
||||
// (provider.ClaudeHandedOver): each holds its refresh token, which a
|
||||
// refresh there would rotate under Claude Code's copy. Their conversations
|
||||
// go on in a new run, on the account the gateway picks then.
|
||||
// go on in a new run, on the account the gateway picks then. A run in a
|
||||
// turn ends as the turn does, not kept for the next (keepIdle): it went
|
||||
// on waiting there, with the same token, for up to idleLongest (#4532).
|
||||
func (b *subscriptionBridge) handedOver(user string) {
|
||||
var drop []*subscriptionRun
|
||||
b.mu.Lock()
|
||||
@@ -530,6 +536,11 @@ func (b *subscriptionBridge) handedOver(user string) {
|
||||
drop = append(drop, run)
|
||||
}
|
||||
}
|
||||
for _, run := range b.runs {
|
||||
if u, own := ownerAccount(run.owned()); !own && strings.EqualFold(u, user) {
|
||||
run.handed = true
|
||||
}
|
||||
}
|
||||
b.mu.Unlock()
|
||||
for _, run := range drop {
|
||||
run.abort()
|
||||
@@ -1836,6 +1847,11 @@ func (b *subscriptionBridge) keepIdle(r *subscriptionRun, key, conv string) bool
|
||||
b.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
if r.handed {
|
||||
b.mu.Unlock()
|
||||
r.abortFor("its account was handed over to Claude Code itself")
|
||||
return false
|
||||
}
|
||||
// a run waits at one point of its conversation: kept again, it leaves
|
||||
// the key it waited at, unless another run waits there now (#1596:
|
||||
// which caller kept one run twice isn't known; ended and letGo of one
|
||||
|
||||
@@ -19,8 +19,10 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
@@ -129,6 +131,61 @@ func claudeDirRun(user string) *sync.RWMutex {
|
||||
return mu
|
||||
}
|
||||
|
||||
// claudeDirRun is this magpie's own runs only: a switch from another
|
||||
// magpie process (`magpie accounts switch` while the app reads a card)
|
||||
// didn't wait for them, and handed Claude Code the refresh token a run of
|
||||
// the app's could still spend (#4532). So each run also holds a lock file
|
||||
// of its own beside the account's directory, for as long as it runs, and
|
||||
// a switch waits on every one of them (waitClaudeRuns). A file whose
|
||||
// holder ended without removing it is free, and taken out.
|
||||
|
||||
// claudeRunWait is how long a switch waits for runs in the account's
|
||||
// directory: a /usage or a warm-up takes seconds.
|
||||
var claudeRunWait = 90 * time.Second
|
||||
|
||||
var claudeRunSeq atomic.Int64
|
||||
|
||||
// claudeRunMarks matches the lock files of the runs in user's directory.
|
||||
func claudeRunMarks(user string) string { return claudeAccountDir(user) + ".run-*.lock" }
|
||||
|
||||
// markClaudeRun holds a lock file of this run's own, released as it ends.
|
||||
func markClaudeRun(user string) (release func()) {
|
||||
path := fmt.Sprintf("%s.run-%d-%d.lock", claudeAccountDir(user), os.Getpid(), claudeRunSeq.Add(1))
|
||||
unlock, held := filelock.Lock(path, 0)
|
||||
if !held {
|
||||
_ = os.Remove(path)
|
||||
return func() {}
|
||||
}
|
||||
return func() {
|
||||
unlock()
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
}
|
||||
|
||||
// errClaudeRunning is a run in the account's directory past claudeRunWait.
|
||||
var errClaudeRunning = errors.New("Claude Code is still running on this account for magpie (its usage or a warm-up): try again in a moment")
|
||||
|
||||
// waitClaudeRuns waits until no process runs Claude Code in user's
|
||||
// directory for magpie.
|
||||
func waitClaudeRuns(user string) error {
|
||||
marks, _ := filepath.Glob(claudeRunMarks(user))
|
||||
deadline := time.Now().Add(claudeRunWait)
|
||||
for _, m := range marks {
|
||||
start := time.Now()
|
||||
wait := max(time.Until(deadline), 0)
|
||||
unlock, held := filelock.Lock(m, wait)
|
||||
if !held {
|
||||
if time.Since(start) >= wait {
|
||||
return errClaudeRunning
|
||||
}
|
||||
continue // a file system without locks: nothing to wait on
|
||||
}
|
||||
unlock()
|
||||
_ = os.Remove(m) // its run has ended
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// inSavedClaudeDir runs f with the config directory of the saved Claude
|
||||
// account user (claudeSavedDir), and keeps what Claude Code made of the
|
||||
// sign-in there in logins.json once it is done: a refreshed one is the
|
||||
@@ -137,6 +194,7 @@ func inSavedClaudeDir(user string, f func(dir string) error) error {
|
||||
mu := claudeDirRun(user)
|
||||
mu.RLock()
|
||||
defer mu.RUnlock()
|
||||
defer markClaudeRun(user)()
|
||||
dir, err := claudeSavedDir(user)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
)
|
||||
|
||||
// claudeLockAccounts signs Claude Code in to b, with a saved beside it,
|
||||
@@ -152,3 +154,117 @@ func TestClaudeSwitchStaleAndHeldLocks(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// #4532: a switch from one magpie process waits for Claude Code another
|
||||
// runs in the account's own directory (the app reading its /usage while
|
||||
// `magpie accounts switch` runs), and hands Claude Code the sign-in that
|
||||
// run refreshed. Before, the wait was in-process only: the switch handed
|
||||
// over the refresh token the run then spent.
|
||||
func TestClaudeSwitchWaitsForAnotherMagpiesRun(t *testing.T) {
|
||||
claudeThree(t)
|
||||
home := os.Getenv("HOME")
|
||||
old := ClaudeHandedOver
|
||||
t.Cleanup(func() { ClaudeHandedOver = old })
|
||||
ClaudeHandedOver = func(string) {}
|
||||
dir, err := claudeSavedDir("max@x.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the other magpie's run, as markClaudeRun holds it there
|
||||
mark := claudeAccountDir("max@x.com") + ".run-99999-1.lock"
|
||||
unlock, held := filelock.Lock(mark, time.Second)
|
||||
if !held {
|
||||
t.Fatal("the run's lock wasn't to be had")
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- SwitchLogin("claude", "max@x.com") }()
|
||||
select {
|
||||
case err := <-done:
|
||||
unlock()
|
||||
t.Fatalf("switched while another magpie ran Claude Code in the account's directory (%v)", err)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
// its Claude Code refreshes the sign-in there, and ends
|
||||
writeFile(t, filepath.Join(dir, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{
|
||||
"accessToken": "tok-rotated", "refreshToken": "r-rotated",
|
||||
"expiresAt": time.Now().Add(8 * time.Hour).UnixMilli(), "subscriptionType": "max"}})
|
||||
unlock()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the switch never went on after the run ended")
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(home, ".claude", ".credentials.json"))
|
||||
if err != nil || !strings.Contains(string(b), "r-rotated") {
|
||||
t.Fatalf("Claude Code was handed the spent sign-in: %s %v", b, err)
|
||||
}
|
||||
if m, _ := filepath.Glob(claudeRunMarks("max@x.com")); len(m) != 0 {
|
||||
t.Fatalf("run locks left behind: %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// A run that outlasts the wait leaves Claude Code signed in as it was, and
|
||||
// says why; a lock file whose run ended without removing it holds nothing.
|
||||
func TestClaudeSwitchRunHeldAndLeft(t *testing.T) {
|
||||
t.Run("held", func(t *testing.T) {
|
||||
claudeThree(t)
|
||||
home := os.Getenv("HOME")
|
||||
w := claudeRunWait
|
||||
claudeRunWait = 300 * time.Millisecond
|
||||
t.Cleanup(func() { claudeRunWait = w })
|
||||
unlock, held := filelock.Lock(claudeAccountDir("max@x.com")+".run-99999-1.lock", time.Second)
|
||||
if !held {
|
||||
t.Fatal("not held")
|
||||
}
|
||||
defer unlock()
|
||||
if err := SwitchLogin("claude", "max@x.com"); !errors.Is(err, errClaudeRunning) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(home, ".claude", ".credentials.json"))
|
||||
if !strings.Contains(string(b), "r-pro@x.com") {
|
||||
t.Fatalf("Claude Code's sign-in written over while a run held the account: %s", b)
|
||||
}
|
||||
})
|
||||
t.Run("left", func(t *testing.T) {
|
||||
claudeThree(t)
|
||||
mark := claudeAccountDir("max@x.com") + ".run-99999-1.lock"
|
||||
if err := os.MkdirAll(filepath.Dir(mark), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(mark, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SwitchLogin("claude", "max@x.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(mark); !os.IsNotExist(err) {
|
||||
t.Fatalf("a left lock file kept: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A run in a saved account's directory holds its lock file while it runs,
|
||||
// and removes it as it ends.
|
||||
func TestSavedClaudeRunHoldsItsLock(t *testing.T) {
|
||||
claudeThree(t)
|
||||
var seen []string
|
||||
err := inSavedClaudeDir("max@x.com", func(string) error {
|
||||
seen, _ = filepath.Glob(claudeRunMarks("max@x.com"))
|
||||
if len(seen) == 1 {
|
||||
if unlock, held := filelock.Lock(seen[0], 50*time.Millisecond); held {
|
||||
unlock()
|
||||
t.Error("the run's lock was free while it ran")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || len(seen) != 1 {
|
||||
t.Fatalf("%v, run locks %v", err, seen)
|
||||
}
|
||||
if m, _ := filepath.Glob(claudeRunMarks("max@x.com")); len(m) != 0 {
|
||||
t.Fatalf("run locks left behind: %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1228,6 +1228,10 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
|
||||
mu := claudeDirRun(user)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
// nor while another magpie process runs it there (#4532)
|
||||
if err := waitClaudeRuns(user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
// not while a saved account is being refreshed: the agent would be
|
||||
// given the refresh token that refresh is spending
|
||||
|
||||
Reference in New Issue
Block a user