diff --git a/internal/agent/alma.go b/internal/agent/alma.go index df7cd6dc5..8bc4669da 100644 --- a/internal/agent/alma.go +++ b/internal/agent/alma.go @@ -38,6 +38,7 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/proc" ) // almaAPI is where Alma's API answers. Under test it is nothing, so no test @@ -56,6 +57,37 @@ var almaClient = &http.Client{Timeout: 1500 * time.Millisecond} // errAlmaDown is Alma not answering. var errAlmaDown = errors.New("Alma isn't running — open Alma and try again") +// almaApp is Alma's desktop app as its packages install it +// (electron-builder.yml and desktop-native/PACKAGING.md in Alma's repo): +// Alma.app (com.yetone.alma) on a Mac; Alma\Alma.exe under +// %LOCALAPPDATA%\Programs on Windows, or the folder its installer +// registered under the guid electron-builder makes of the appId; on +// Linux /opt/alma (the native deb and rpm) or /opt/Alma (the Electron +// ones), or a desktop entry named Alma for alma:// links (an AppImage's). +var almaApp = desktopApp{id: "com.yetone.alma", names: []string{"Alma.app"}, + win: filepath.Join("Alma", "Alma.exe"), guid: "53efb302-dbc3-52a1-8bb5-041beae96976", + onLinux: &linuxApp{dirs: []string{"/opt/alma", "/opt/Alma"}, exe: "alma", name: "Alma", scheme: "alma"}} + +// almaInstalled reports whether Alma is installed here: its desktop app, +// or on Linux alma-server, Alma without a desktop, on PATH. A var so a +// test can say. +var almaInstalled = func() bool { + if almaApp.installed() { + return true + } + if almaOS == "darwin" || almaOS == "windows" { + return false + } + _, err := proc.LookPath("alma-server") + return err == nil +} + +// almaTakeOut, in the stash, is magpie's provider left in an Alma that was +// gone when it was turned off (almaSet): Alma uninstalled keeps its data, +// and only Alma itself can change it. It is taken out once Alma answers +// again (Sync), installed again with that data. +const almaTakeOut = "alma.takeout" + // almaProvider is what magpie reads of one of Alma's providers. type almaProvider struct { ID string `json:"id"` @@ -604,6 +636,9 @@ func almaPutImage(s map[string]any, v string) error { func almaGet() string { s, err := almaSettingsSeen() if err != nil { + if stashShared()[almaTakeOut] != "" { + return "" + } return appliedOf("alma").Fields["model"] } v := almaDefault(s) @@ -621,11 +656,25 @@ func almaGet() string { return v } -func almaSet(v string) error { +func almaSet(v string) (err error) { + defer func() { + // put on magpie again: nothing is left to take out + if v != "" && err == nil && stashShared()[almaTakeOut] != "" { + forget(almaTakeOut) + } + }() if v == "" { // back to Alma's own: its default model is its to pick, and // magpie's provider comes out s, err := almaSettings() + if errors.Is(err, errAlmaDown) && !almaInstalled() { + // Alma uninstalled: nothing of it to change, and opening it + // to turn magpie off can't be done (aooo_han on X: "得先运行 + // 起来"). Its data, which only it changes, loses magpie's + // provider if it is installed again (Sync). + stash(map[string]string{almaTakeOut: "1"}) + return nil + } if err != nil { return err } @@ -772,6 +821,14 @@ func alma() *Agent { if err != nil { return nil // not running: nothing to keep current } + if stashShared()[almaTakeOut] != "" { + // turned off while Alma was gone, and here again + if err := almaSet(""); err != nil { + return err + } + forget(almaTakeOut) + return nil + } p := almaMagpie(ps) if p == nil { return nil diff --git a/internal/agent/alma_test.go b/internal/agent/alma_test.go index 44ba63039..c14d9a789 100644 --- a/internal/agent/alma_test.go +++ b/internal/agent/alma_test.go @@ -626,3 +626,124 @@ func TestAlmaKey(t *testing.T) { t.Fatalf("encrypted key replaced: %v", f.keys) } } + +// aooo_han on X: Alma connected, then uninstalled, couldn't be turned off +// in magpie: it said to open Alma first. Uninstalled, turning it off +// forgets magpie's own record; installed and closed it still says to open +// it. Alma installed again with its data has magpie's provider taken out +// once it answers. +func TestAlmaOffUninstalled(t *testing.T) { + syncHome(t) + f := startAlma(t) + a := alma() + os.MkdirAll(a.Dir, 0o755) + var ref string + for _, o := range a.Field("model").Options(nil) { + if o.Ref != "" { + ref = o.Ref + break + } + } + if err := a.Apply("model", "magpie/"+ref); err != nil { + t.Fatal(err) + } + if !a.Wired() { + t.Fatal("not connected") + } + srv := almaAPI + almaAPI = "http://127.0.0.1:1" + defer func() { almaAPI = srv }() + was := almaInstalled + defer func() { almaInstalled = was }() + + // installed, only closed: it is opened to take magpie out + almaInstalled = func() bool { return true } + if err := a.Disconnect(); err == nil || !strings.Contains(err.Error(), "isn't running") { + t.Fatalf("installed: %v", err) + } + + almaInstalled = func() bool { return false } + if err := a.Disconnect(); err != nil { + t.Fatalf("uninstalled: %v", err) + } + if a.Wired() { + t.Fatal("still connected after turning it off") + } + if got := a.Field("model").Get(); got != "" { + t.Fatalf("model after turning it off: %q", got) + } + if d := a.Drift(); d != nil { + t.Fatalf("drift: %+v", d) + } + + // installed again, its data kept: magpie comes out at the next sync + almaAPI = srv + if err := a.Sync(); err != nil { + t.Fatal(err) + } + f.mu.Lock() + for _, p := range f.providers { + if p["name"] == magpieID { + t.Errorf("magpie's provider left in Alma: %v", p) + } + } + def := f.settings["chat"].(map[string]any)["defaultModel"] + f.mu.Unlock() + if def != "" { + t.Fatalf("default model left on magpie: %v", def) + } + if stashShared()[almaTakeOut] != "" { + t.Fatal("take-out still pending") + } + if a.Wired() { + t.Fatal("connected after Alma came back") + } + // and a sync after that leaves Alma alone + f.mu.Lock() + n := len(f.writes) + f.mu.Unlock() + if err := a.Sync(); err != nil { + t.Fatal(err) + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.writes) != n { + t.Fatalf("second sync wrote: %v", f.writes[n:]) + } +} + +// Alma is installed where its packages put it: Alma.app on a Mac. +func TestAlmaInstalledApp(t *testing.T) { + apps := t.TempDir() + wasF, wasS, wasOS := appFolders, spotlightApps, linuxAppOS + appFolders = func() []string { return []string{apps} } + spotlightApps = func(string) []string { return nil } + linuxAppOS = "darwin" + t.Cleanup(func() { appFolders, spotlightApps, linuxAppOS = wasF, wasS, wasOS }) + if almaApp.installed() { + t.Fatal("installed with no Alma.app") + } + plist := filepath.Join(apps, "Alma.app", "Contents", "Info.plist") + os.MkdirAll(filepath.Dir(plist), 0o755) + os.WriteFile(plist, []byte(`CFBundleIdentifiercom.yetone.alma`+ + `CFBundleShortVersionString0.4.554`), 0o644) + if !almaApp.installed() { + t.Fatal("Alma.app not found") + } +} + +// An app dragged to the Trash, as a Mac app is uninstalled, is still in +// Spotlight: it doesn't count as installed (aooo_han on X). +func TestInTrash(t *testing.T) { + for p, want := range map[string]bool{ + "/Users/a/.Trash/Alma.app": true, + "/Volumes/X/.Trashes/501/Alma.app": true, + "/Applications/Alma.app": false, + "/Users/a/Applications/Alma.app": false, + "/Users/a/Trash notes/Alma.app": false, + } { + if got := inTrash(p); got != want { + t.Errorf("inTrash(%q) = %v, want %v", p, got, want) + } + } +} diff --git a/internal/agent/desktopapp.go b/internal/agent/desktopapp.go index 39c58738b..ccd6c7c4e 100644 --- a/internal/agent/desktopapp.go +++ b/internal/agent/desktopapp.go @@ -423,7 +423,9 @@ func spotlightBundles(id string) []string { out, err := proc.CommandContext(ctx, "mdfind", "kMDItemCFBundleIdentifier == '"+id+"'").Output() if err == nil { for _, p := range strings.Split(strings.TrimSpace(string(out)), "\n") { - if p = strings.TrimSpace(p); p != "" { + // an app dragged to the Trash, as a Mac app is uninstalled, + // is still in Spotlight: it isn't installed + if p = strings.TrimSpace(p); p != "" && !inTrash(p) { paths = append(paths, p) } } @@ -435,6 +437,12 @@ func spotlightBundles(id string) []string { return paths } +// inTrash reports whether p is in a Mac's Trash: the user's ~/.Trash, or +// a volume's .Trashes. +func inTrash(p string) bool { + return strings.Contains(p, "/.Trash/") || strings.Contains(p, "/.Trashes/") +} + // AppVersion is the version of the agent's desktop app installed here, "" // for an agent without one magpie knows, one not installed, or an Info.plist // that doesn't say (a binary one isn't read). diff --git a/internal/agent/hanako.go b/internal/agent/hanako.go index d3950fce0..1d6692772 100644 --- a/internal/agent/hanako.go +++ b/internal/agent/hanako.go @@ -136,9 +136,18 @@ func hanako(home string) *Agent { Set: func(v string) error { agent := hanakoAgent(dir) if v == "" { - // nothing changes rather than half of it + // nothing changes rather than half of it, while + // OpenHanako can be opened to do it all. Uninstalled, + // it can't: its agent's model goes back in its plain + // config, and magpie's provider stays in the sealed + // catalog, which only OpenHanako can change (aooo_han + // on X: Alma uninstalled said to open it first). + gone := false if _, there := hanakoCurrent(dir); there && hanakoSealed(path) && hanakoLive(dir) == nil { - return errSealed("take magpie out of") + if hanakoInstalled() { + return errSealed("take magpie out of") + } + gone = true } if onMagpie() { // the stash goes only once the model is back @@ -147,6 +156,9 @@ func hanako(home string) *Agent { } forget(key()) } + if gone { + return nil + } return hanakoRemove(dir) } if agent == "" { @@ -361,6 +373,19 @@ func hanakoRemove(dir string) error { return os.RemoveAll(hanakoPlugin(dir)) } +// hanakoApp is OpenHanako's desktop app as its package.json builds it: +// HanaAgent.app (com.hanako.app) on a Mac; HanaAgent\HanaAgent.exe under +// %LOCALAPPDATA%\Programs on Windows, or where its installer registered it +// under the guid electron-builder makes of the appId; its deb's +// /opt/HanaAgent on Linux. An AppImage of it isn't found. +var hanakoApp = desktopApp{id: "com.hanako.app", names: []string{"HanaAgent.app"}, + win: filepath.Join("HanaAgent", "HanaAgent.exe"), guid: "3802e236-0c74-5d5f-a339-e8fa54299135", + onLinux: &linuxApp{dirs: []string{"/opt/HanaAgent"}, exe: "hanako", name: "HanaAgent"}} + +// hanakoInstalled reports whether OpenHanako's app is installed here; a +// var so a test can say. +var hanakoInstalled = hanakoApp.installed + // errSealed says why magpie can't do what it was asked to with OpenHanako // closed, and what will. func errSealed(what string) error { diff --git a/internal/agent/hanako_test.go b/internal/agent/hanako_test.go index f69248c57..74b556a7d 100644 --- a/internal/agent/hanako_test.go +++ b/internal/agent/hanako_test.go @@ -578,6 +578,9 @@ func TestHanakoSealed(t *testing.T) { } // taking magpie out needs OpenHanako: nothing changes meanwhile + wasInstalled := hanakoInstalled + hanakoInstalled = func() bool { return true } + t.Cleanup(func() { hanakoInstalled = wasInstalled }) f := a.Field("model") if err := f.Set(""); err == nil || !strings.Contains(err.Error(), "open OpenHanako") { t.Fatalf("reset: %v", err) @@ -725,3 +728,37 @@ func TestHanakoLiveBackNeedsProviderID(t *testing.T) { }) } } + +// OpenHanako uninstalled with its catalog sealed can't be opened to take +// magpie out (aooo_han on X, of Alma): turning it off puts its agent's +// model back in its plain config and leaves the sealed catalog as it is. +func TestHanakoSealedUninstalled(t *testing.T) { + home, dir := hanakoTestHome(t) + catalogPath := filepath.Join(dir, "provider-catalog.json") + sealed := hanakoSeal(t, `{"catalogVersion":2,"providers":{"openai":{"api_key":"sk-x"},"magpie":{"api_key":"magpie-hanako"}}}`) + hanakoWrite(t, catalogPath, sealed, 0o600) + plugin := filepath.Join(dir, "provider-plugins", "magpie", "providers", "magpie.json") + hanakoWrite(t, plugin, `{"id":"magpie","displayName":"magpie","authType":"api-key","defaultBaseUrl":"`+gatewayV1()+`",`+ + `"defaultApi":"openai-completions","models":[{"id":"relay/glm-4.6"}]}`, 0o600) + cfg := filepath.Join(dir, "agents", "hana", "config.yaml") + hanakoWrite(t, cfg, "models:\n chat:\n id: relay/glm-4.6\n provider: magpie\n", 0o644) + a := hanako(home) + // what it was on before magpie + stash(map[string]string{"hanako:" + dir + ":hana:chat": "openai/gpt-5"}) + was := hanakoInstalled + hanakoInstalled = func() bool { return false } + t.Cleanup(func() { hanakoInstalled = was }) + + if err := a.Field("model").Set(""); err != nil { + t.Fatalf("turn off: %v", err) + } + if chat, _ := hanakoChatOf(t, cfg); chat["provider"] != "openai" || chat["id"] != "gpt-5" { + t.Fatalf("model not put back: %v", chat) + } + if b, _ := os.ReadFile(catalogPath); string(b) != sealed { + t.Fatalf("the sealed catalog was written:\n%s", b) + } + if a.Wired() { + t.Fatal("still connected") + } +}