Files
tobitege 21702d01ff Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars

Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows.

* Makefile: know magpie's folder by its go.mod, so paths with spaces work

The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs.

* i18n: German for the strings main added since, with a parity test

75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system.

* appdir: ignore relative folder variables when reading, keep them for children

CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder.

* Sandbox the tests main added since

internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE.

* agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose

omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over.

* i18n: German for the Library's multi-select and System One's decision API

The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes.

* appdir: tidy the import into magpie's group; say what Go makes of /c/x

The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x.
2026-10-04 23:30:56 +08:00

311 lines
9.7 KiB
Go

package plugin
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/testenv"
)
// storeSandbox gives the test its own magpie folders, without the Bun the
// other tests need: these only read and write plugins.json.
func storeSandbox(t testing.TB) string {
t.Helper()
dir := t.TempDir()
testenv.SetHome(t, dir)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
if err := os.MkdirAll(settings.Dir(), 0o700); err != nil {
t.Fatal(err)
}
return dir
}
// writeList puts plugins.json where magpie keeps it.
func writeList(t testing.TB, body string) {
t.Helper()
if err := os.WriteFile(listPath(), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
func TestLoadMissingIsEmptyNotGrown(t *testing.T) {
storeSandbox(t)
l := Load()
if l.Plugins != nil || l.Config != nil {
t.Fatalf("a missing plugins.json gave %+v, want the zero List", l)
}
}
// TestLoadKeepsWhatAPartialFileGave: what a file that doesn't parse whole
// gives is what Load gives, as it always was — the error is no more read
// than it was, so a half-written file can't empty a list a magpie is using.
func TestLoadKeepsWhatAPartialFileGave(t *testing.T) {
for _, tc := range []struct{ name, body string }{
{"truncated", `{"plugins":[{"spec":"a"},{"spec":"b"`},
{"a field of the wrong type", `{"plugins":[{"spec":"a"},{"spec":"b","off":"yes"}],"config":{"k":1}}`},
{"empty", `{"plugins":[]}`},
{"whole", `{"plugins":[{"spec":"a","options":{"k":1}}],"config":{"p":{"q":["x"]}}}`},
} {
t.Run(tc.name, func(t *testing.T) {
storeSandbox(t)
writeList(t, tc.body)
// what a plain parse of those bytes gives is what Load gives:
// the error was never read, and a partly filled list stayed
var want List
_ = json.Unmarshal([]byte(tc.body), &want)
if got := Load(); !reflect.DeepEqual(got, want) {
t.Fatalf("Load = %+v, want the plain parse %+v", got, want)
}
})
}
t.Run("a plugin edited after a wrong type isn't saved away", func(t *testing.T) {
storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"a"},{"spec":"b","off":"yes"}],"config":{"k":1}}`)
if l := Load(); len(l.Plugins) != 2 || l.Plugins[0].Spec != "a" || l.Plugins[1].Spec != "b" || l.Plugins[1].Off {
t.Fatalf("a wrong type gave %+v, want both plugins", l.Plugins)
}
if err := SetOff("a", true); err != nil {
t.Fatal(err)
}
if l := Load(); len(l.Plugins) != 2 || !l.Plugins[0].Off || l.Plugins[1].Spec != "b" || l.Config["k"] != float64(1) {
t.Fatalf("after turning one off: %+v", l)
}
})
}
// TestLoadCopyIsIndependent: what Load gives may be changed anywhere in it,
// and what magpie keeps is not.
func TestLoadCopyIsIndependent(t *testing.T) {
storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"a","options":{"k":{"n":[1]}}}],"config":{"p":{"q":["x"]}}}`)
l := Load()
l.Plugins[0].Spec = "changed"
l.Plugins[0].Off = true
l.Plugins[0].Options["k"].(map[string]any)["n"].([]any)[0] = 2
l.Plugins = append(l.Plugins, Entry{Spec: "added"})
l.Config["p"].(map[string]any)["q"].([]any)[0] = "changed"
l.Config["new"] = 1
again := Load()
if len(again.Plugins) != 1 || again.Plugins[0].Spec != "a" || again.Plugins[0].Off {
t.Fatalf("the entries changed with a copy: %+v", again.Plugins)
}
if n := again.Plugins[0].Options["k"].(map[string]any)["n"].([]any)[0]; n != float64(1) {
t.Fatalf("a nested option changed with a copy: %v", n)
}
if q := again.Config["p"].(map[string]any)["q"].([]any)[0]; q != "x" {
t.Fatalf("a nested config value changed with a copy: %v", q)
}
if _, ok := again.Config["new"]; ok {
t.Fatal("a new config key reached what magpie keeps")
}
}
// TestListReusesTheParse: while the bytes are the same the parse is reused.
func TestListReusesTheParse(t *testing.T) {
storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"a"},{"spec":"b"}]}`)
a := list()
b := list()
if len(a.Plugins) == 0 || &a.Plugins[0] != &b.Plugins[0] {
t.Fatal("the same bytes were parsed again")
}
}
// TestLoadSeesAnEditThatKeepsSizeAndTime: an old file edited in place, or
// replaced by a rename, with its size and time put back, is read as it is
// now — a stamp would serve the parse before it.
func TestLoadSeesAnEditThatKeepsSizeAndTime(t *testing.T) {
old := time.Now().Add(-time.Hour)
edit := func(t *testing.T, was, now string) {
t.Helper()
writeList(t, was)
if err := os.Chtimes(listPath(), old, old); err != nil {
t.Fatal(err)
}
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != specOf(was) {
t.Fatalf("first read: %+v", l.Plugins)
}
writeList(t, now)
if err := os.Chtimes(listPath(), old, old); err != nil {
t.Fatal(err)
}
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != specOf(now) {
t.Fatalf("an edit of one size kept the parse before it: %+v", l.Plugins)
}
}
t.Run("in place", func(t *testing.T) {
storeSandbox(t)
edit(t, `{"plugins":[{"spec":"aaa"}]}`, `{"plugins":[{"spec":"bbb"}]}`)
})
t.Run("replaced by a rename", func(t *testing.T) {
storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"aaa"}]}`)
if err := os.Chtimes(listPath(), old, old); err != nil {
t.Fatal(err)
}
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "aaa" {
t.Fatalf("first read: %+v", l.Plugins)
}
tmp := filepath.Join(filepath.Dir(listPath()), "plugins.json.tmp")
if err := os.WriteFile(tmp, []byte(`{"plugins":[{"spec":"bbb"}]}`), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(tmp, old, old); err != nil {
t.Fatal(err)
}
if err := os.Rename(tmp, listPath()); err != nil {
t.Fatal(err)
}
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "bbb" {
t.Fatalf("a replaced file kept the parse before it: %+v", l.Plugins)
}
})
}
// specOf is the one plugin spec a test's list holds.
func specOf(body string) string {
var l List
_ = json.Unmarshal([]byte(body), &l)
if len(l.Plugins) == 0 {
return ""
}
return l.Plugins[0].Spec
}
// TestLoadDeleteRecreateAndReadError: gone, unreadable and back again.
func TestLoadDeleteRecreateAndReadError(t *testing.T) {
storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"a"}]}`)
if l := Load(); len(l.Plugins) != 1 {
t.Fatalf("first read: %+v", l.Plugins)
}
if err := os.Remove(listPath()); err != nil {
t.Fatal(err)
}
if l := Load(); l.Plugins != nil {
t.Fatalf("a deleted file gave %+v, want the zero List", l.Plugins)
}
// a folder where the file goes: reading it fails
if err := os.Mkdir(listPath(), 0o700); err != nil {
t.Fatal(err)
}
if l := Load(); l.Plugins != nil {
t.Fatalf("an unreadable file gave %+v, want the zero List", l.Plugins)
}
if err := os.Remove(listPath()); err != nil {
t.Fatal(err)
}
writeList(t, `{"plugins":[{"spec":"back"}]}`)
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "back" {
t.Fatalf("after it came back: %+v", l.Plugins)
}
}
// TestLoadPerConfigDir: what one magpie folder keeps is not another's.
func TestLoadPerConfigDir(t *testing.T) {
dir := storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"one"}]}`)
if l := Load(); l.Plugins[0].Spec != "one" {
t.Fatalf("first dir: %+v", l.Plugins)
}
other := filepath.Join(dir, "elsewhere")
t.Setenv("XDG_CONFIG_HOME", other)
if err := os.MkdirAll(settings.Dir(), 0o700); err != nil {
t.Fatal(err)
}
writeList(t, `{"plugins":[{"spec":"two"}]}`)
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "two" {
t.Fatalf("second dir: %+v", l.Plugins)
}
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
if l := Load(); len(l.Plugins) != 1 || l.Plugins[0].Spec != "one" {
t.Fatalf("back to the first dir: %+v", l.Plugins)
}
}
// TestLoadConcurrentWithSavesAndEdits: reading the list while another
// magpie's writes land (each of them a rename) never gives half a file, and
// add, off and remove work under it.
func TestLoadConcurrentWithSavesAndEdits(t *testing.T) {
dir := storeSandbox(t)
writeList(t, `{"plugins":[{"spec":"p0"}]}`)
plug := filepath.Join(dir, "plug.mjs")
if err := os.WriteFile(plug, []byte("// a plugin\n"), 0o600); err != nil {
t.Fatal(err)
}
stop := make(chan struct{})
var wg sync.WaitGroup
for range 4 {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-stop:
return
default:
}
plugins := Load().Plugins
if len(plugins) < 1 || len(plugins) > 2 {
t.Errorf("a read gave %d plugins", len(plugins))
return
}
for _, e := range plugins {
if e.Spec == "" {
t.Errorf("a read gave an entry with no spec")
return
}
}
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
defer close(stop)
for i := range 60 {
_ = save(List{Plugins: []Entry{{Spec: fmt.Sprintf("p%d", i%2)}}})
if _, err := Add(context.Background(), plug); err != nil {
t.Errorf("add: %v", err)
return
}
if err := SetOff(Name(plug), true); err != nil {
t.Errorf("off: %v", err)
return
}
if err := Remove(context.Background(), Name(plug)); err != nil {
t.Errorf("remove: %v", err)
return
}
}
}()
wg.Wait()
if l := Load(); len(l.Plugins) != 1 || !strings.HasPrefix(l.Plugins[0].Spec, "p") {
t.Fatalf("after the writers: %+v", l.Plugins)
}
}
// BenchmarkCachedWarm is Cached with the providers already good, so nothing
// is refreshed in the background: what is measured is the per-call read.
func BenchmarkCachedWarm(b *testing.B) {
storeSandbox(b)
writeList(b, `{"plugins":[{"spec":"@magpie-community/opencode-zed-auth@latest","options":{"a":1}},{"spec":"@magpie-community/opencode-qoder-auth@latest","off":true}],"config":{"provider":{"zed":{"options":{"projectId":"p"}}}}}`)
UseCached([]Provider{{ID: "zed", Spec: "@magpie-community/opencode-zed-auth@latest", Name: "Zed", SignedIn: true}})
b.ReportAllocs()
for b.Loop() {
Cached()
}
}