From 2e2c890304eb849fcf1b5267654bddd505bbe283 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 20:58:43 +0800 Subject: [PATCH] agent: Lody is detected by what Lody makes, its link only on loopback is guarded, and its row is tested in every language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of Leon Zhao's Lody import (the two commits before this): - Detection: a bare ~/.lody or ~/.lody-oss another tool made counted as Lody. Now the home folder counts only with an entry Lody makes there (workspace-catalog.json, loro-repo, agent-binaries, code-collab-v2, all in the owner's real ~/.lody). A Lody.app counts only with an ai.lody. bundle id (the real /Applications/Lody.app is ai.lody.desktop, and registers the lody scheme) or a plist that isn't XML. Electron's data folder under os.UserConfigDir (Application Support / %APPDATA% / ~/.config, "Lody", "Lody OSS", "Lody Nightly") still counts as before. A never-opened install on Windows or Linux has no folder and isn't shown; said in agent-wiring.md. - Security: TestLodyLinkCarriesNoSecret turns LAN sharing on and checks the link holds magpie-lody and never the LAN key, every endpoint is loopback http, and MAGPIE_ADDR pinned beyond loopback gives no link at all (0.0.0.0, 127.0.0.1 and [::1] still give one). - `magpie lody add` with no link (a LAN-pinned gateway) said it opened Lody and opened ""; it now says why and opens nothing. - Added *bool: every consumer re-read. The CLI and TUI use agent.Agent's func (nil-safe), the GUI reads a.added == null, and Cindy's false is now sent as "added":false. TestLodyImportHandoff also checks Cindy's row says false and Lody's leaves added out; the handoff test's ~/.lody holds a catalog file now and checks it is left byte for byte. - The hint "Opens {name} to add magpie as a provider — confirm it there" was already translated in zh, zh-TW, ja and de (the import button's tooltip). import-row now runs in all five languages, asserts Lody's exact translated line and that no added/not-added wording shows, and checks both import rows fit a 420px window with no sideways scroll (waiting for the header's segments to settle after the resize, which overflow for ~300ms in WebKit en on main too). Run (on origin/main 4a6bf80f4 + Leon's two; after rebasing onto dcf292cc8, a routing-only CSS change, import-row, agent-layout, group-editor-align and i18n-keys were run again in both engines, 47/47, with the Lody/Cindy/Import Go tests in agent and gui, ok): - go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME (scratchpad dir, XDG_* there too, Go caches pinned): 64 packages ok, exit 0 (agent 607s, gateway 674s, gui 130s, provider 219s). - gofmt -l .: clean. go vet: darwin ./..., GOOS=linux -tags nogui ./..., GOOS=windows ./...: clean. - GUI, playwright 1.62.0, Chromium and WebKit: import-row 20/20 (5 languages x added/not x 2 engines, 960/700/420px); i18n-keys, gui-de, gui-ja, gui-zh-tw, agent-layout, agent-connect, plugin-agent, agent-cli-missing, agent-connected-unfolded, agent-bulk-visibility, agents-hidden-last: 116/116. Broken by hand, each went red, then restored: - a bare ~/.lody counting again: TestLodyDetectionAndRegistration; - any Lody.app counting: TestLodyBundle (com.example.lody, ai.lodyx.); - the loopback switch removed: TestLodyLinkCarriesNoSecret (LAN-pinned addresses got a link); - the key taken from agentKeyAt at a LAN address: the LAN key showed in the link, red; - Cindy's false left out of state(): TestLodyImportHandoff; - app.js's unknown-status branch taken out: import-row red in every language; the de translation removed: import-row de red. Not tried: Lody opening the link for real (Leon ran Lody's parser), and Windows or Linux Lody installs. --- docs/subsystems/agent-wiring.md | 16 ++- internal/agent/lody.go | 52 ++++++--- internal/agent/lody_test.go | 148 ++++++++++++++++++++++++- internal/cli/main.go | 4 + internal/gui/lody_test.go | 35 +++++- internal/gui/tests/import-row.test.cjs | 34 +++++- 6 files changed, 264 insertions(+), 25 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index ccccd9ff6..65a3983f4 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -126,13 +126,21 @@ node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-d ## Lody import handoff -[`lody.go`](../../internal/agent/lody.go) detects Lody's standard data folders -(`~/.lody`, `~/.lody-oss`, or the platform configuration folders for Lody, -Lody OSS and Lody Nightly), or its macOS application bundle. Its row opens +[`lody.go`](../../internal/agent/lody.go) detects Lody by its home folder +(`~/.lody`, `~/.lody-oss`) only when it holds an entry Lody makes there +(`workspace-catalog.json`, `loro-repo`, `agent-binaries` or +`code-collab-v2`), so a bare folder of that name another tool made isn't +Lody; by its Electron data folder under the OS's config folder (Lody, Lody +OSS, Lody Nightly: `~/Library/Application Support`, `%APPDATA%`, +`~/.config`); or by a macOS bundle whose id starts `ai.lody.` (the real app +is `ai.lody.desktop`). A Windows or Linux install that has never been +opened has no data folder yet and isn't shown. Its row opens `lody://provider/import?v=1&data=` with the Magpie envelope and seven runtime targets. Only loopback HTTP gateways are offered; the key is always the public attribution token `magpie-lody`, never a LAN secret. -The OS chooses the installed Lody handler. A compatible Lody build must +With `MAGPIE_ADDR` pinned beyond loopback there is no link: the row has no +button, and `magpie lody add` says why and opens nothing +(`TestLodyLinkCarriesNoSecret`). The OS chooses the installed Lody handler. A compatible Lody build must implement this import route. Lody asks which Providers to add, names them with `-magpie`, and writes only diff --git a/internal/agent/lody.go b/internal/agent/lody.go index c143fbbc0..6470ac91a 100644 --- a/internal/agent/lody.go +++ b/internal/agent/lody.go @@ -70,32 +70,58 @@ func LodyLink(base string) string { return LodyScheme + "v=1&data=" + base64.RawURLEncoding.EncodeToString(b) } +// lodyMarks are entries Lody makes in its home folder (~/.lody, or +// ~/.lody-oss for its OSS build) once it has run: a folder of that name +// another tool made, with none of them in it, isn't Lody. +var lodyMarks = []string{"workspace-catalog.json", "loro-repo", "agent-binaries", "code-collab-v2"} + +// lodyNames are the names Lody's builds go by: its app bundle on a Mac and +// its data folder under the OS's config folder (Electron's userData: +// ~/Library/Application Support/Lody, %APPDATA%\Lody, ~/.config/Lody). +var lodyNames = []string{"Lody", "Lody OSS", "Lody Nightly"} + +// lodyBundle reports whether an app bundle in folders is one of Lody's: +// ai.lody.desktop (or another ai.lody. build), or a plist that isn't XML, +// which says nothing either way. A Lody.app of another vendor's isn't. +func lodyBundle(folders []string) bool { + for _, dir := range folders { + for _, name := range lodyNames { + b, err := os.ReadFile(filepath.Join(dir, name+".app", "Contents", "Info.plist")) + if err != nil { + continue + } + if id := plistIDRe.FindSubmatch(b); id == nil || strings.HasPrefix(strings.TrimSpace(string(id[1])), "ai.lody.") { + return true + } + } + } + return false +} + func lody(home string) *Agent { - dirs := []string{filepath.Join(home, ".lody"), filepath.Join(home, ".lody-oss")} - names := []string{"Lody", "Lody OSS", "Lody Nightly"} + homes := []string{filepath.Join(home, ".lody"), filepath.Join(home, ".lody-oss")} + var dirs []string if cfg, err := os.UserConfigDir(); err == nil { - for _, name := range names { + for _, name := range lodyNames { dirs = append(dirs, filepath.Join(cfg, name)) } } return &Agent{ ID: "lody", Name: "Lody", Icon: "lody", UA: []string{"lody"}, detect: func() bool { + for _, dir := range homes { + for _, m := range lodyMarks { + if _, err := os.Stat(filepath.Join(dir, m)); err == nil { + return true + } + } + } for _, dir := range dirs { if isDir(dir) { return true } } - if runtime.GOOS == "darwin" { - for _, dir := range macAppFolders(home) { - for _, name := range names { - if isDir(filepath.Join(dir, name+".app")) { - return true - } - } - } - } - return false + return runtime.GOOS == "darwin" && lodyBundle(macAppFolders(home)) }, Import: func() string { return LodyLink(gateway.URL()) }, // There is no public status API. Never infer import success from a diff --git a/internal/agent/lody_test.go b/internal/agent/lody_test.go index d109c91a0..ec0eb3808 100644 --- a/internal/agent/lody_test.go +++ b/internal/agent/lody_test.go @@ -3,11 +3,16 @@ package agent import ( "encoding/base64" "encoding/json" + "net" "net/url" "os" "path/filepath" "reflect" + "strings" "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/gateway" ) func TestLodyLink(t *testing.T) { @@ -69,16 +74,47 @@ func TestLodyDetectionAndRegistration(t *testing.T) { } for _, name := range []string{".lody", ".lody-oss"} { dir := filepath.Join(home, name) + // a bare folder of that name another tool made isn't Lody + if err := os.MkdirAll(filepath.Join(dir, "bin"), 0700); err != nil { + t.Fatal(err) + } + if a.Detected() { + t.Fatalf("a %s without Lody's own entries counted as Lody", name) + } + for _, m := range lodyMarks { + if err := os.WriteFile(filepath.Join(dir, m), nil, 0600); err != nil { + t.Fatal(err) + } + if !a.Detected() { + t.Fatalf("missed %s with %s", name, m) + } + if err := os.Remove(filepath.Join(dir, m)); err != nil { + t.Fatal(err) + } + } + if err := os.RemoveAll(dir); err != nil { + t.Fatal(err) + } + } + cfg, err := os.UserConfigDir() + if err != nil { + t.Fatal(err) + } + for _, name := range lodyNames { + dir := filepath.Join(cfg, name) if err := os.MkdirAll(dir, 0700); err != nil { t.Fatal(err) } if !a.Detected() { - t.Fatalf("missed %s", name) + t.Fatalf("missed Lody's data folder %s", dir) } if err := os.Remove(dir); err != nil { t.Fatal(err) } } + if a.Detected() { + t.Fatal("still detected after its folders went") + } if a.Added != nil || len(a.Fields) != 0 || a.Sync != nil || a.Unwire != nil { t.Fatal("import adapter must not infer status or edit Lody settings") } @@ -92,3 +128,113 @@ func TestLodyDetectionAndRegistration(t *testing.T) { } t.Fatal("Lody missing from Agents") } + +// A Lody.app is Lody's only with its bundle id (ai.lody.desktop on the +// real app) or a plist that says nothing; another vendor's Lody.app isn't. +func TestLodyBundle(t *testing.T) { + plist := func(id string) string { + return `CFBundleIdentifier` + id + `` + } + for _, c := range []struct { + name, plist string + want bool + }{ + {"Lody", plist("ai.lody.desktop"), true}, + {"Lody Nightly", plist("ai.lody.desktop.nightly"), true}, + {"Lody", "bplist00", true}, + {"Lody", plist("com.example.lody"), false}, + {"Lody", plist("ai.lodyx.desktop"), false}, + {"Lodyssey", plist("ai.lody.desktop"), false}, + } { + dir := t.TempDir() + contents := filepath.Join(dir, c.name+".app", "Contents") + if err := os.MkdirAll(contents, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(contents, "Info.plist"), []byte(c.plist), 0600); err != nil { + t.Fatal(err) + } + if got := lodyBundle([]string{dir}); got != c.want { + t.Errorf("%s.app with %q: %v, want %v", c.name, c.plist, got, c.want) + } + } + if lodyBundle([]string{t.TempDir()}) { + t.Error("no bundle counted as Lody") + } +} + +// Lody's link carries only the public magpie-lody token and a loopback +// gateway, with LAN sharing on too; with MAGPIE_ADDR pinned beyond +// loopback, where that token is turned away, there is no link at all +// rather than one carrying the LAN key. +func TestLodyLinkCarriesNoSecret(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("MAGPIE_ADDR", "") + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { access.ConfigureLAN(false, false) }) + lan := access.LANSecret() + if !strings.HasPrefix(lan, access.Prefix) { + t.Fatalf("LAN key %q", lan) + } + link := LodyLink(gateway.URL()) + if link == "" { + t.Fatalf("no link for the loopback gateway %s", gateway.URL()) + } + u, err := url.Parse(link) + if err != nil { + t.Fatal(err) + } + data, err := base64.RawURLEncoding.DecodeString(u.Query().Get("data")) + if err != nil { + t.Fatal(err) + } + if strings.Contains(link, lan) || strings.Contains(string(data), lan) { + t.Fatalf("the LAN key went into Lody's link: %s", data) + } + var got struct { + Auth struct { + APIKey string `json:"apiKey"` + } `json:"auth"` + Endpoints []struct { + BaseURL string `json:"baseUrl"` + ModelsURL string `json:"modelsUrl"` + } `json:"endpoints"` + } + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if got.Auth.APIKey != gateway.TokenFor("lody") || got.Auth.APIKey != "magpie-lody" { + t.Fatalf("key %q, want magpie-lody", got.Auth.APIKey) + } + if len(got.Endpoints) == 0 { + t.Fatal("no endpoints") + } + for _, e := range got.Endpoints { + for _, s := range []string{e.BaseURL, e.ModelsURL} { + p, err := url.Parse(s) + if err != nil || p.Scheme != "http" || !loopbackHost(p.Hostname()) { + t.Fatalf("endpoint %q is not loopback", s) + } + } + } + for addr, want := range map[string]bool{"172.23.80.1:3425": false, "192.168.1.2:3425": false, "0.0.0.0:3425": true, "127.0.0.1:4567": true, "[::1]:4567": true} { + t.Setenv("MAGPIE_ADDR", addr) + gw := gateway.URL() + if got := LodyLink(gw) != ""; got != want { + t.Errorf("MAGPIE_ADDR %s (%s): link %v, want %v", addr, gw, got, want) + } + } +} + +func loopbackHost(h string) bool { + if h == "localhost" { + return true + } + ip := net.ParseIP(h) + return ip != nil && ip.IsLoopback() +} diff --git a/internal/cli/main.go b/internal/cli/main.go index d01da65fc..794168cbf 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -412,6 +412,10 @@ func run(args []string) error { // `magpie cindy`: it takes magpie through its own link, confirmed there if len(args) > 1 { link := a.Import() + if link == "" { + // Lody takes only a gateway on this computer's loopback + return fmt.Errorf("%s takes magpie only at a loopback address, and the gateway is at %s: nothing was opened", a.Name, gateway.URL()) + } openInBrowser(link) fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render("opened to add magpie — confirm it there")) fmt.Println(muted.Render(" " + link)) diff --git a/internal/gui/lody_test.go b/internal/gui/lody_test.go index a2bc50b1f..c1e6082c7 100644 --- a/internal/gui/lody_test.go +++ b/internal/gui/lody_test.go @@ -24,12 +24,27 @@ func TestLodyImportHandoff(t *testing.T) { if err := os.MkdirAll(filepath.Join(home, ".lody"), 0700); err != nil { t.Fatal(err) } - var row *agentJSON + catalog := filepath.Join(home, ".lody", "workspace-catalog.json") + if err := os.WriteFile(catalog, []byte(`{"workspaces":[]}`), 0600); err != nil { + t.Fatal(err) + } + // Cindy, beside it, still says whether it has magpie: false is said, + // not left out as unknown + cfg, err := os.UserConfigDir() + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(cfg, "Cindy"), 0700); err != nil { + t.Fatal(err) + } + var row, cindy *agentJSON s := state() for i := range s.Agents { - if s.Agents[i].ID == "lody" { + switch s.Agents[i].ID { + case "lody": row = &s.Agents[i] - break + case "cindy": + cindy = &s.Agents[i] } } if row == nil || !strings.HasPrefix(row.Import, agent.LodyScheme) { @@ -38,6 +53,15 @@ func TestLodyImportHandoff(t *testing.T) { if row.Added != nil { t.Fatal("unknown import status must not be reported as not added") } + if b, _ := json.Marshal(row); strings.Contains(string(b), `"added"`) { + t.Fatalf("Lody's row says added: %s", b) + } + if cindy == nil || cindy.Added == nil || *cindy.Added { + t.Fatalf("Cindy without magpie: %+v, want added false", cindy) + } + if b, _ := json.Marshal(cindy); !strings.Contains(string(b), `"added":false`) { + t.Fatalf("Cindy's row leaves added out: %s", b) + } w := &importWindows{} mux := http.NewServeMux() providerRoutes(mux, w) @@ -55,7 +79,10 @@ func TestLodyImportHandoff(t *testing.T) { } } entries, err := os.ReadDir(filepath.Join(home, ".lody")) - if err != nil || len(entries) != 0 { + if err != nil || len(entries) != 1 { t.Fatalf("handoff modified Lody data: %v %v", entries, err) } + if b, err := os.ReadFile(catalog); err != nil || string(b) != `{"workspaces":[]}` { + t.Fatalf("handoff modified Lody's catalog: %q %v", b, err) + } } diff --git a/internal/gui/tests/import-row.test.cjs b/internal/gui/tests/import-row.test.cjs index 671de25c5..e99b5a726 100644 --- a/internal/gui/tests/import-row.test.cjs +++ b/internal/gui/tests/import-row.test.cjs @@ -37,10 +37,22 @@ async function serve(route, lang, added) { const SAID = { en: [/^Not added · Cindy asks to add magpie/, /^Added · magpie is a provider in Cindy/], zh: [/^未添加 · /, /^已添加 · /], + "zh-TW": [/^未新增 · /, /^已新增 · /], + ja: [/^未追加 · /, /^追加済み · /], + de: [/^Nicht hinzugefügt · /, /^Hinzugefügt · /], +}; +// Lody has no status magpie can read: its line asks to confirm in Lody, in +// the reader's language, and never says added or not +const UNKNOWN = { + en: "Opens Lody to add magpie as a provider — confirm it there", + zh: "打开 Lody 添加 magpie 供应商,在其中确认", + "zh-TW": "開啟 Lody 新增 magpie 供應商,在其中確認", + ja: "Lody を開いて magpie をプロバイダとして追加します。そちらで確認してください", + de: "Öffnet Lody, um magpie als Anbieter hinzuzufügen — dort bestätigen", }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - for (const lang of ["en", "zh"]) { + for (const lang of Object.keys(SAID)) { for (const added of [false, true]) { test(`${engine} ${lang} ${added ? "added" : "not added"}: import rows show known or unknown status and open their app`, async (t) => { const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); @@ -63,8 +75,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await lody.scrollIntoViewIfNeeded(); await lody.locator(".ag-st-t").waitFor(); const hint = await lody.locator(".ag-st-t").innerText(); - assert.match(hint, /Lody/); - assert.doesNotMatch(hint, /Not added|未添加|Added ·|已添加/); + assert.equal(hint, UNKNOWN[lang]); + for (const said of Object.values(SAID).flat()) assert.doesNotMatch(hint, said); assert.equal(await lody.locator(".ag-st").evaluate((e) => e.classList.contains("on")), false); const lodyOpened = page.waitForRequest((r) => r.url().includes("/api/open")); await lody.locator(".ag-start").click(); @@ -83,6 +95,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const who = await box('.row.agent[data-id="cindy"] > .who'); assert(link.x >= who.right, `the button stays clear of the name at ${width}px`); } + // narrow: no page scroll sideways, and both import rows keep their + // line and button inside the window + await page.setViewportSize({ width: 420, height: 700 }); + // the header's segments settle a moment after a resize, so wait for + // the state rather than reading it at once + await page.waitForFunction(() => document.documentElement.scrollWidth <= window.innerWidth, null, { timeout: 3000 }).catch(async () => { + assert.fail(`sideways scroll at 420px: ${await page.evaluate(() => document.documentElement.scrollWidth)}`); + }); + for (const id of ["lody", "cindy"]) { + const r = page.locator(`.row.agent[data-id="${id}"]`); + for (const sel of [".ag-start", ".ag-st-t"]) { + const b = await r.locator(sel).evaluate((e) => { const x = e.getBoundingClientRect(); return { left: x.left, right: x.right, width: x.width }; }); + assert(b.width > 0 && b.left >= 0 && b.right <= 420 + 0.5, `${id} ${sel} inside the window at 420px: ${JSON.stringify(b)}`); + } + } + await page.setViewportSize({ width: 960, height: 600 }); // a click opens the app's link, the row's one control const opened = page.waitForRequest((r) => r.url().includes("/api/open")); await row.locator(".ag-start").click();