agent: the disconnect preview reads no sign-ins, so macOS never asks "Keychain Not Found"

jasonz3g on X (macOS, two Claude accounts): clicking Claude Code on the
Agents page made macOS ask "Keychain Not Found — A keychain cannot be
found to store …" (Cancel / Reset To Defaults), dozens of times.

The Agents page loads a disconnect preview each time an agent's box
shows: DisconnectPreview runs Disconnect on a copy, in a subprocess
whose HOME is a temporary folder. Claude Code's Disconnect builds the
model list (buildModels -> CatalogFor -> provider.All -> Accounts ->
rememberLogins -> liveLogin), which read the Claude sign-in with
`security find-generic-password`, and Cursor's too. On a Mac the
keychain is found through HOME, and the temporary one has none. With a
copy of real ~/.claude and ~/.config/magpie, the dry run ran security
three times under the temporary HOME, started Devin's CLI there, and
rewrote held/lapsed in the copy's logins.json.

previewEnv now sets MAGPIE_NO_ACCOUNTS=1, which every keychain read and
write, liveLogin and askClaudeStatus already honour. The dry run of
the same real copy then runs no security and no CLI, and the agent's
~/.claude files come out byte for byte the same as before (diff -r), so
the preview shows the same changes.

Run:
- TestDisconnectPreviewReadsNoSignIns (new), red on the old code
  (security find-generic-password -s Claude Code-credentials ... twice),
  green after; its second half checks the fixture does reach the
  keychain out of the dry run.
- go test ./internal/agent -count=1 -timeout 45m: ok on mica (macOS)
  and on WSL Ubuntu (magpie-desktop); GOOS=linux and GOOS=windows go
  vet ./internal/agent ok; gofmt -l clean.
- Real binary, dry run of `claude` on a copy of real ~/.claude and
  ~/.config/magpie with logging security/claude stubs: 3 security calls
  before, none after.

Not tried: the GUI dialog itself (no display over ssh); the
reporter's own accounts.
This commit is contained in:
yetone
2026-11-16 14:45:15 +08:00
parent 50f7a8e01f
commit b9c385286b
3 changed files with 86 additions and 2 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ something else shows up as drift.
| What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable`, `proxied` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now, and keeps the agent connected (`applied.Kept`). An agent whose magpie is a provider of its own config (`Spelled`, not `Native`) is connected only when magpie set it up (`setUp`: a record, `Kept`, or a `<id>.connect.was` stash). A provider named magpie the user wrote by hand (`handWired`) is theirs: it isn't `Wired`, has no `Drift`, and neither `SyncCatalog`, `RenameProvider` nor `Disconnect` writes it; connecting in magpie takes it on (JFunfunfun on X, Pi on `magpie/<model>`; `TestPiHandWiredMagpieProviderIsTheirs`, `TestPiConnectedBeforeStaysConnected`, `TestHandWiredMagpieProviderSiblings`). | [`applied.go`](../../internal/agent/applied.go) |
| What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) |
| Restore on quit | By default a connected agent keeps magpie as the app quits. With Settings › General › Put agents back when quitting on, `RestoreOnQuit` runs `Disconnect` on each agent that is `Wired` and not `Disconnected()`, drops the `.disconnected` mark that Disconnect left, and stashes the ids (`quit.restored`); `RewireOnStart` connects those again at the next start, once, skipping any the user disconnected or connected since. See the gui-shell page, "A Quit asks while agents go through magpie". | [`quitrestore.go`](../../internal/agent/quitrestore.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent, mu; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent, mu; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. That subprocess reads no sign-ins (`MAGPIE_NO_ACCOUNTS`): on a Mac the keychain is found through HOME, and a read under the temporary one made macOS ask "Keychain Not Found" at each preview. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) |
| Uninstall | `magpie uninstall` and Settings › About › Uninstall magpie take magpie off this computer, because deleting magpie's folders by hand left Codex's `openai_base_url` on a gateway that was gone, and every turn failed with a 502 (Jevik_AI on X). `Run` goes in this order. `System` removes the service, opening at login, the Start menu shortcut, `magpie://` links and the privacy model's helper. `Agents` ends Codex's account failover, runs each connected agent's `Disconnect`, or its offline disconnect for a closed app, so the restore keeps what the user changed by hand since. It then takes Codex's leftovers (`TakeCodexLeftovers`): an `openai_base_url` at magpie's gateway, or magpie as Codex's provider, goes by the gates a Disconnect uses even when magpie's notes are gone and Codex reads as not connected (#3866); magpie's provider table stays for the threads that name it. A table magpie writes for a provider a Codex thread names that config.toml lost (`putThreadTables`, #1372) is written only for CC Switch's ids and an id config.toml has had a table of (stash `codex.filed_tables`): another app can give Codex a provider on its command line (T3 Code's `openai_token_sharing` with `auth = {command}`), and magpie's table merged with it made Codex refuse its config ("provider auth cannot be combined with experimental_bearer_token"). One an older magpie wrote so goes at a Sync, a Disconnect and here (`tidyTables`, `TestCodexLeavesOtherAppsProviders`, `TestCodexDropsStrayThreadTables`). It then ports Codex's rollouts and restarts the Codex app's app-server. `Data` deletes magpie's folders, but keeps the Library while it holds skills, servers or hooks. The executable stays where the user put it. The CLI refuses while another magpie runs, and asks first unless given `--yes`. On Windows magpie is listed in Settings › Apps › Installed apps: `shortcut.Ensure` writes `HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\magpie` at every installed start, and `System` takes it out with the Start menu shortcut. Its Uninstall runs `magpie uninstall --window` with no console, which opens the app's window (or the running app's) on Settings › About with the question asked (`uninstallView`, `shortcut.UninstallArgs`). Deleting the app by hand still runs no code. The app runs `System` and `Agents` from `POST /api/uninstall`. If anything failed, nothing else is removed. Otherwise `POST /api/uninstall/finish` starts a detached `magpie uninstall --data-after <pid>`, which deletes the files once the app has quit, since WebView2 holds its folder open until then. magpie web refuses both routes (`TestUninstall*`, `uninstall-settings.test.cjs`). Every line magpie writes into a TOML, YAML or env config has a `# magpie:` note above it saying how to undo it, so a config left behind still names magpie (`edit.Mark`, `TestMarkedLinesEveryAgent`). | [`uninstall.go`](../../internal/uninstall/uninstall.go), [`uninstall_cli.go`](../../internal/cli/uninstall_cli.go), [`gui/uninstall.go`](../../internal/gui/uninstall.go) |
| Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. For Codex that is where its config sends it and which models its lists hold (`listedModels`, slug and visibility), not every byte of each entry: the Codex app's list carries the ChatGPT backend's entries as sent, asked for each hour, and a rewrite with the same models told the user to reopen the app several times a day (Qyburn3 on X). A digest an older magpie stashed over the same files is kept (`readsBefore`). | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Restarting a desktop app | Claude Desktop, WorkBuddy (WorkBuddy AI on macOS), OpenMausBot and ZCode (`ZCode.app`, `ZCode.exe`; `zcodePart`: magpie's provider without its key and magpie's rules in `provider_config.json`, Flandern1211 on X, #5662) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`), but a script run on the app's own executable (`runsScript`: a `.js` argument or an absolute path as its first argument), which the running check skips too. WorkBuddy starts its sidecar (`sidecar-entry.js`) and its `codebuddy` CLIs that way, detached; the sidecar outlives a quit, so counting it kept the row behind after every restart and made Restart wait it out and never open the app (Northes on Discord, 11-04, #3700). On Windows the same check reads each process's command line (`proc.CommandLine`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); one that has hidden every window and still runs after `appTrayGrace` (1s) is in the tray and has its tree ended at once (`waitClosed`, `winShown`: Claude Desktop hides its window in ~0.6s and keeps all its processes, so waiting the whole `appCloseWait` made a Restart ~12s where quitting by hand takes ~2s, CyberCaius on Discord, 10-29); one still showing a window (a question) gets `appCloseWait` before it is ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too, then ends only the app-server that app runs for itself (`provider.RestartCodexApp`: under its bundle, never a `--listen` one), as a switch does; the app starts another and keeps its window. Quitting and opening it, as before, opened a new window (yoshi037070 on Discord, 10-27). Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
+8 -1
View File
@@ -390,7 +390,14 @@ func previewEnv(home, tmp string) []string {
// The test binary recognizes this marker and keeps the fixture HOME
// instead of creating a second isolated home. Production binaries ignore
// the variable.
return append(out, "HOME="+tmp, "USERPROFILE="+tmp, "TMPDIR="+tmp, "MAGPIE_TEST_SANDBOX="+tmp)
//
// No sign-in is read: building the providers there would read the
// Claude sign-in from the keychain, found through HOME on a Mac, and
// the copy's home has none, so macOS asked the user "Keychain Not
// Found" at each preview (jasonz3g on X). It would run agents' CLIs
// under the copy's home too. The files the dry run changes are the
// agent's, and no account changes them.
return append(out, "HOME="+tmp, "USERPROFILE="+tmp, "TMPDIR="+tmp, "MAGPIE_TEST_SANDBOX="+tmp, "MAGPIE_NO_ACCOUNTS=1")
}
// diffLines is the lines that differ between two texts, in the order of the
+77
View File
@@ -0,0 +1,77 @@
package agent
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// The Agents page shows what disconnecting Claude Code would change by
// running Disconnect on a copy, in a process whose HOME is a temporary
// folder (DisconnectPreview). Claude Code's Disconnect builds magpie's
// providers there, and with them the accounts: the Claude sign-in read
// from the keychain, its account asked of Claude Code. On a Mac the
// keychain is found through HOME, and the copy's home has no login
// keychain: macOS asks "Keychain Not Found — A keychain cannot be found
// to store …" (Cancel / Reset To Defaults). jasonz3g on X, with two Claude
// accounts in magpie, cancelled it dozens of times after clicking Claude
// Code. The dry run reads no sign-ins: the files it changes are the
// agent's, and no account changes them.
func TestDisconnectPreviewReadsNoSignIns(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("no keychain")
}
home, _ := codexHome(t, "", "")
ran := filepath.Join(t.TempDir(), "ran.log")
bin := t.TempDir()
for _, name := range []string{"security", "claude"} {
testenv.Program(t, filepath.Join(bin, name), "#!/bin/sh\necho \""+name+" $*\" >> '"+ran+"'\nexit 44\n")
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
writeFile(t, filepath.Join(home, ".claude.json"), `{"oauthAccount":{"emailAddress":"jason@example.com"}}`)
auth := func(tok string) string {
return `{"claudeAiOauth":{"accessToken":"` + tok + `","refreshToken":"r-` + tok + `","expiresAt":4102444800000,"subscriptionType":"max"}}`
}
writeFile(t, filepath.Join(filepath.Dir(provider.Path()), "logins.json"), `[
{"agent":"claude","user":"jason@example.com","plan":"max","seen":"2026-11-15T00:00:00Z","auth":`+auth("a1")+`,"profile":{"emailAddress":"jason@example.com"},"held":true},
{"agent":"claude","user":"jason2@example.com","plan":"max","seen":"2026-11-15T00:00:00Z","on":true,"auth":`+auth("a2")+`,"profile":{"emailAddress":"jason2@example.com"}}
]`)
accounts := func() string {
os.Remove(ran)
provider.ForgetAccounts()
provider.Accounts()
b, _ := os.ReadFile(ran)
return strings.TrimSpace(string(b))
}
// what the dry run's process has that this one hasn't, home and its
// folders aside: those would take this test's files away. It goes
// first: the Claude sign-in read is kept for seconds, so a read out of
// the dry run before it would stand in for one in it.
moved := map[string]bool{"HOME": true, "USERPROFILE": true, "TMPDIR": true, testenv.Marker: true}
var set []string
for _, kv := range previewEnv(home, t.TempDir()) {
k, v, _ := strings.Cut(kv, "=")
if !moved[k] && !strings.HasPrefix(k, "XDG_") && os.Getenv(k) != v {
t.Setenv(k, v)
set = append(set, k)
}
}
if got := accounts(); got != "" {
t.Fatalf("the dry run read the sign-ins, under its temporary home:\n%s", got)
}
// the same accounts read out of the dry run reach the keychain on a
// Mac: the fixture is one that asks it
for _, k := range set {
os.Unsetenv(k)
}
if got := accounts(); runtime.GOOS == "darwin" && !strings.Contains(got, "security find-generic-password") {
t.Fatalf("the accounts were read without the keychain: %q", got)
}
}