Files
magpie/internal/agent/apprestart.go
T
yetone 634cbf587b agent: Claude Desktop on an imported profile for magpie's gateway is connected, and Reconnect keeps it
aa86222 on Discord: Claude Desktop's configuration (magpie's profile, with
the connectors added in it) exported on one computer and imported on
another becomes a new configLibrary entry under a random id Desktop makes
(createConfig in Desktop 2.7032's main process), applied beside magpie's
own. It points at this magpie's gateway, yet the Agents row said
"已不经过 magpie:配置已变更", since desktopCheck took any appliedId but
magpie's own as another gateway. Reconnect then applied magpie's own
profile, dropping the imported one with its managedMcpServers, and on the
old code a later switch-off applied the first entry left (CC Switch's).

Now an applied gateway profile whose inferenceGatewayBaseUrl is this
gateway (desktopIsOurGateway) counts as on magpie (desktopAppliedGateway).
Check reads its URL and key; Reconnect (desktopOn, when magpie's entry is
already listed) keeps it applied and leaves every setting in it as it is;
only a key this gateway would refuse (another magpie's named key) is set
to magpie's Desktop key, by Reconnect or by Sync at magpie's start
(desktopKeyApplied). magpie's own keys (gateway.Token, magpie-<agent>)
count as taken. A profile for another gateway (CC Switch) is still drift
and Reconnect still applies magpie's. The first switch-on still seeds
magpie's profile from an applied one (#2035, unchanged). appReads includes
the applied profile, so a key fix asks for Desktop's restart.

Run (macOS, sandbox HOME only, at 27ca0bef5 + this change):
- go test ./internal/agent -timeout 45m -count=1: ok (205s)
- gofmt -l internal/agent: clean; GOOS=linux and GOOS=windows go vet
  ./internal/agent: ok
- TestClaudeDesktopImportedProfileIsOnMagpie: fixture is _meta.json with
  CC Switch's entry (127.0.0.1:15721), magpie's, and the imported one
  applied, the imported profile carrying managedMcpServers.

Broken by hand: with claudedesktop.go put back to origin/main (and a stub
desktopAppliedGateway returning ""), the new test fails in 3 of 4
subtests: check says "uses another gateway configuration now", Reconnect
applies 00000000-…-6d6167706965, off applies CC Switch's entry, and the
other-magpie key is never fixed.

Not tried: a real Desktop export/import across two computers (the format
is from Desktop 2.7032's app.asar: configLibrary createConfig + writeConfig,
exportConfig); the GUI (no GUI file changed). Not changed: a machine
where magpie never connected Desktop and an imported profile is applied
still reads as not connected; connecting there seeds magpie's profile
from it (#2035).
2026-10-26 17:00:46 +08:00

386 lines
12 KiB
Go

package agent
import (
"context"
"errors"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/desktopdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// Claude Desktop and WorkBuddy read what magpie writes for them as they
// start (微雨南山 and stones on Discord, 10-24: a provider added showed up
// there only after a restart). Claude Desktop asks the gateway for its
// models once, at start. WorkBuddy 5.6's app.asar watches models.json only
// when the file was there at start, and the watch is on the file itself,
// so a rewrite by rename leaves it watching the old one. While such an app
// runs on what it read before magpie's last change, its Agents row offers
// a Restart. magpie never restarts one unasked: the button asks first, in
// magpie's own dialog, and only then quits the app as its own Quit does
// and opens it again. The Codex app on macOS has its own Restart on its
// stale-copy line (codex_app.go), behind the same question.
// restartable is how one such app is found running: its macOS bundle (an
// id and the names it is installed under), and on Windows its executable's
// name with a test of a process's image path that says it is the app's.
type restartable struct {
mac desktopApp
winExe string
win func(image string) bool
}
// claudeDesktopApp is Claude Desktop's bundle (Claude 2.7032's Info.plist:
// com.anthropic.claudefordesktop, executable Claude).
var claudeDesktopApp = desktopApp{id: "com.anthropic.claudefordesktop", names: []string{"Claude.app"}}
// restartApps are the agents whose desktop app the Agents row restarts.
// macOS: Claude.app, WorkBuddy.app and WorkBuddy AI.app (both run an
// executable named Electron). Windows: Claude Desktop is claude.exe, from
// Squirrel's %LOCALAPPDATA%\AnthropicClaude (a claude.exe stub beside
// app-<version>\claude.exe) or its MSIX (desktopdir's Claude_… and
// AnthropicPBC.Claude_…), never Claude Code's claude.exe elsewhere;
// WorkBuddy is C:\Program Files\WorkBuddy\WorkBuddy.exe (5.6.2, seen on
// the Windows box). WorkBuddy AI's Windows build wasn't to hand, so it has
// no Restart there. None of them ships a Linux app.
var restartApps = map[string]restartable{
"claude-desktop": {mac: claudeDesktopApp, winExe: "claude.exe", win: func(image string) bool {
return winBase(image, "claude.exe") && (winHas(image, `\AnthropicClaude\`) || winHas(image, `\WindowsApps\Claude_`) || winHas(image, `\WindowsApps\AnthropicPBC.Claude_`))
}},
"workbuddy": {mac: workbuddyApp, winExe: "WorkBuddy.exe", win: func(image string) bool {
return winBase(image, "WorkBuddy.exe") && !winHas(image, `WorkBuddy AI`) && !winHas(image, `WorkBuddy-AI`)
}},
"workbuddy-ai": {mac: workbuddyAIApp},
}
func winBase(image, name string) bool {
i := strings.LastIndexAny(image, `\/`)
return strings.EqualFold(image[i+1:], name)
}
func winHas(image, part string) bool {
return strings.Contains(strings.ToLower(image), strings.ToLower(part))
}
// restartOnWindows and restartOnMac say which system this is; vars so a
// test runs either.
var (
restartOnWindows = runtime.GOOS == "windows"
restartOnMac = runtime.GOOS == "darwin"
)
// winProc is a process running on Windows: its id, its parent's, its
// image's full path, when it started, and its AppUserModelID when it is a
// packaged (Store or MSIX) app's.
type winProc struct {
pid, parent int
image string
start time.Time
aumid string
}
// The Windows part of a restart, vars so tests stand in for each:
// winProcs lists the running processes named exe, winClose asks pids to close as
// their windows' close does, winEnd ends pid with its tree, and winLaunch
// opens what a restart opens again.
var (
winProcs = listWinProcs
winClose = closeWinProcs
winEnd = endWinTree
winLaunch = launchWin
// appCloseWait is how long a Windows app has to close by itself
// before it is ended, and appBackWait how long it has to come back
appCloseWait = 10 * time.Second
appBackWait = 20 * time.Second
appPoll = 200 * time.Millisecond
)
// appRunning is r's app as it runs here: when it started, and on macOS its
// bundle, on Windows its processes and the one the rest hang off.
type appRunning struct {
since time.Time
bundle string
procs []winProc
main winProc
}
// findRestartable is r's app running here, if it is.
func findRestartable(r restartable) (appRunning, bool) {
if restartOnWindows {
if r.win == nil {
return appRunning{}, false
}
var ps []winProc
for _, p := range winProcs(r.winExe) {
if r.win(p.image) {
ps = append(ps, p)
}
}
if len(ps) == 0 {
return appRunning{}, false
}
mine := map[int]bool{}
for _, p := range ps {
mine[p.pid] = true
}
// the main process is the one whose parent isn't the app's:
// Electron's helpers hang off it
c := appRunning{procs: ps, main: ps[0], since: ps[0].start}
top := false
for _, p := range ps {
if p.start.Before(c.since) {
c.since = p.start
}
if !mine[p.parent] && (!top || p.start.Before(c.main.start)) {
c.main, top = p, true
}
}
return c, true
}
if !restartOnMac || r.mac.id == "" {
return appRunning{}, false
}
for _, b := range macBundles(r.mac) {
exe := bundleExecutable(b, r.mac.id)
if exe == "" {
continue
}
ps := running("^" + regexp.QuoteMeta(filepath.Join(b, "Contents", "MacOS", exe)) + "( |$)")
if len(ps) == 0 {
continue
}
up := ps[0].up
for _, p := range ps[1:] {
up = max(up, p.up)
}
return appRunning{since: time.Now().Add(-up), bundle: b}, true
}
return appRunning{}, false
}
// bundleExecutable is the CFBundleExecutable of the bundle at b when its
// Info.plist says it is id's, "" otherwise.
func bundleExecutable(b, id string) string {
info, err := os.ReadFile(filepath.Join(b, "Contents", "Info.plist"))
if err != nil {
return ""
}
got := plistIDRe.FindSubmatch(info)
exe := plistExeRe.FindSubmatch(info)
if got == nil || exe == nil || strings.TrimSpace(string(got[1])) != id {
return ""
}
return strings.TrimSpace(string(exe[1]))
}
// AppRun is a desktop app running on what it read before magpie's last
// change to it: when it started, for the row to offer a Restart.
type AppRun struct {
Since time.Time `json:"since"`
}
// AppBehind is the agent's desktop app when it runs here and started
// before magpie last changed what it reads at start; nil when it isn't
// running, has started since, or magpie doesn't restart it here. Only for
// an agent connected to magpie, or one disconnected from it in magpie:
// those are the changes magpie made.
func (a *Agent) AppBehind() *AppRun {
r, ok := restartApps[a.ID]
if !ok || a.WSL != "" {
return nil
}
if !a.Wired() && !a.Disconnected() {
return nil
}
files, reads := a.appReads()
if len(files) == 0 {
return nil
}
c, ok := findRestartable(r)
if !ok {
return nil
}
changed := a.changedAt(files, reads)
if changed.IsZero() || !c.since.Before(changed.Add(-time.Second)) {
return nil
}
return &AppRun{Since: c.since}
}
// appReads are the files the agent's desktop app reads magpie's part from
// at start, and that part. Claude Desktop: deploymentMode, the profile
// applied and magpie's profile (or the user's for magpie's gateway), with the models the gateway lists it.
// WorkBuddy: magpie's models in its models.json (workbuddyPart).
func (a *Agent) appReads() (files []string, reads func() string) {
switch a.ID {
case "claude-desktop":
ps := desktopSetsHere()
for _, p := range ps {
files = append(files, p.config, p.config3p, p.meta, p.prof)
if f := desktopAppliedGateway(p); f != "" {
files = append(files, f)
}
}
return files, func() string {
var b strings.Builder
for _, p := range ps {
m, _ := edit.GetJSON(p.config, "deploymentMode")
m3, _ := edit.GetJSON(p.config3p, "deploymentMode")
id, _ := edit.GetJSON(p.meta, "appliedId")
prof, _ := edit.Read(p.prof)
b.WriteString(m + "\n" + m3 + "\n" + id + "\n")
b.Write(prof)
b.WriteString("\n")
// a profile of the user's for magpie's gateway, applied
// instead of magpie's (desktopKeyApplied)
if f := desktopAppliedGateway(p); f != "" {
theirs, _ := edit.Read(f)
b.Write(theirs)
b.WriteString("\n")
}
}
shown, _ := provider.CatalogFor(a.ListsFor())
for _, e := range shown {
b.WriteString(e.ID + "\n")
}
return b.String()
}
case "workbuddy", "workbuddy-ai":
return []string{a.Path}, func() string { return workbuddyPart(a.Path) }
}
return nil, nil
}
// desktopSetsHere are Claude Desktop's folders on this computer.
var desktopSetsHere = func() []desktopPaths {
home, _ := os.UserHomeDir()
return desktopSets(desktopdir.OS, home, os.Getenv)
}
// restarting holds one restart per agent at a time, so a second click
// waits for the first instead of quitting the app it just opened.
var restarting sync.Map
// What a Restart that didn't go through says, in the reader's language
// (tNotice): an app not on the old settings any more was quit or
// restarted meanwhile.
var (
noticeRestartNotHere = newNotice("magpie doesn't restart {agent} on this computer.")
noticeRestartCurrent = newNotice("{agent} isn't running on the old settings any more.")
noticeRestartAsk = newNotice("magpie couldn't ask {agent} to quit. Quit it yourself, then open it again.")
noticeRestartStillOpen = newNotice("{agent} is still open; it may be asking something in its window. Answer it there, or quit it, then open it again.")
noticeRestartStillThere = newNotice("{agent} is still running. Quit it, then open it again.")
noticeRestartNoOpen = newNotice("{agent} quit, but didn't open again. Open it yourself.")
)
func restartErr(n notice, a *Agent) error { return errors.New(n.say("agent", a.Name)) }
// RestartApp quits the agent's desktop app and opens it again, so it reads
// what magpie wrote. Only the Agents row's Restart calls it, after the
// user confirmed, and only an app AppBehind lists is quit. macOS: asked to
// quit as ⌘Q does, every process of its bundle waited for; one still open
// then (it may be asking something) is left, never forced, and not opened
// a second time. Windows: its windows are asked to close; an app still
// running then (Electron apps stay in the tray) is ended with its tree.
func (a *Agent) RestartApp(ctx context.Context) error {
r, ok := restartApps[a.ID]
if !ok || a.WSL != "" {
return restartErr(noticeRestartNotHere, a)
}
mu, _ := restarting.LoadOrStore(a.ID, &sync.Mutex{})
mu.(*sync.Mutex).Lock()
defer mu.(*sync.Mutex).Unlock()
if a.AppBehind() == nil {
return restartErr(noticeRestartCurrent, a)
}
c, ok := findRestartable(r)
if !ok {
return restartErr(noticeRestartCurrent, a)
}
if c.bundle != "" {
return reopenBundle(ctx, a, c.bundle)
}
pids := make([]int, len(c.procs))
for i, p := range c.procs {
pids[i] = p.pid
}
_ = winClose(pids)
if !waitGone(ctx, r, appCloseWait) {
if ctx.Err() != nil {
return ctx.Err()
}
if err := winEnd(c.main.pid); err != nil || !waitGone(ctx, r, appCloseWait) {
if ctx.Err() != nil {
return ctx.Err()
}
return restartErr(noticeRestartStillThere, a)
}
}
if err := winLaunch(c.main); err != nil {
return restartErr(noticeRestartNoOpen, a)
}
end := time.Now().Add(appBackWait)
for {
if _, ok := findRestartable(r); ok {
return nil
}
if !time.Now().Before(end) {
return restartErr(noticeRestartNoOpen, a)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(appPoll):
}
}
}
// waitGone waits until r's app no longer runs, for at most limit.
func waitGone(ctx context.Context, r restartable, limit time.Duration) bool {
end := time.Now().Add(limit)
for {
if _, ok := findRestartable(r); !ok {
return true
}
if !time.Now().Before(end) {
return false
}
select {
case <-ctx.Done():
return false
case <-time.After(appPoll):
}
}
}
// reopenBundle quits the app at bundle, as ⌘Q does, waits for every
// process under it to end and opens it again (codex_app.go's way).
func reopenBundle(ctx context.Context, a *Agent, bundle string) error {
if err := appQuit(ctx, bundle); err != nil {
return restartErr(noticeRestartAsk, a)
}
pat := regexp.QuoteMeta(bundle + "/Contents/")
end := time.Now().Add(appQuitWait)
for len(running(pat)) > 0 {
if time.Now().After(end) {
return restartErr(noticeRestartStillOpen, a)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(appPoll):
}
}
if err := appOpen(ctx, bundle); err != nil {
return restartErr(noticeRestartNoOpen, a)
}
return nil
}