diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 30adf3d82..ac82e92da 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -152,7 +152,9 @@ go test -tags nogui ./internal/edit -run 'BOM|CRLF' go test -tags nogui ./internal/agent ./internal/proc -run 'ClaudeCloud|TestT3CodeSaysAClaudeCloudSwitch|TestLoginEnvClaudeProvidersNotSet' go test -tags nogui ./internal/agent -run '^TestAnte' go test -tags nogui ./internal/agent -run 'AionUi|Cindy' -go test -tags nogui ./internal/gui -run 'TestAionUiImportRow|TestImportStatusUnreadableIsUnknown|TestLodyImportHandoff' +go test -tags nogui ./internal/agent -run 'AppLink|CommandProgram|SystemLinkHandler' +go test -tags nogui ./internal/gui -run 'TestAionUiImportRow|TestImportStatusUnreadableIsUnknown|TestLodyImportHandoff|TestImportLinkNothingOpens' +go test -tags nogui ./internal/cli -run 'TestImportAddSaysNothingOpensIt' node --test internal/gui/tests/import-row.test.cjs go test -tags nogui ./internal/agent -run '^TestAstrBot' go test -tags nogui ./internal/agent -run '^TestJcode' @@ -227,6 +229,38 @@ can't be read, or a stopped WSL distro's, is unknown, never "not added" Reopening the link lets Lody handle duplicates. Bub requires its separately installed ACP plugin. +## Whether anything opens an import link + +Windows' rundll32, macOS' `open` and xdg-open are started and not waited +on, so an import link that nothing here opens (the app never registered its +scheme, or the program it registered is gone) did nothing at all, and +nothing said so (sungt, 10-29: Cindy's Add magpie on Windows "spins, no +response"). [`applink.go`](../../internal/agent/applink.go)'s +`agent.OpenAppLink` asks the system first, without opening anything: +Windows reads `HKEY_CLASSES_ROOT\\shell\open\command` (what +Electron's `setAsDefaultProtocolClient` writes) and then the user's +`UrlAssociations\\UserChoice`; macOS asks Launch Services +(`LSCopyDefaultApplicationURLForURL`, cgo builds only); Linux asks +`xdg-mime query default x-scheme-handler/`. Only "none", or a +registered program whose full path isn't there, refuses the link with +`agent.NoLinkHandlerError`; a key with no command of its own (a packaged +app's), a bare program name, KDE's empty answer, no xdg-mime, a build +without cgo or a failed read is unknown, and the link is handed over as +before. `/api/open` checks Cindy's, AionUi's and Lody's links this way +(Lody's after `agent.OpenLody`'s desktop entry), and `fail` answers +`code: "no_link_handler"` with `app`, `exe` and `said`, an i18n.js key +from `linkSaid` (the one with ` ({exe})` when a gone program is named), +which `api()` puts through `t()` with the reply's fields, as it does +`bunSaid`'s. The Agents page's import button awaits the call and says what +came of it: "Sent to {name}: confirm adding magpie there" (handed over, +not seen to open), that reason in the reader's language, or any other +error's own text. `magpie add` returns the same error instead of +"✓ opened" (`TestOpenAppLinkSaysNothingOpensIt`, +`TestSystemLinkHandlerNoSuchScheme`, `TestImportLinkNothingOpens`, +`TestLinkSaidIsTranslated`, `TestImportAddSaysNothingOpensIt`, +`import-row.test.cjs`). Whether the app +then shows its confirmation is the app's own and is not read. + ## AionUi add-provider link AionUi (`internal/agent/aionui.go`) keeps its providers in its own SQLite diff --git a/internal/agent/agentenv_test.go b/internal/agent/agentenv_test.go index 94d9ac77f..92220976b 100644 --- a/internal/agent/agentenv_test.go +++ b/internal/agent/agentenv_test.go @@ -36,9 +36,10 @@ var notAnAgent = map[string]string{ "MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally", "MAGPIE_PARTNERS": "where magpie's own partner list is read from (a URL, or off), not a folder", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder", - "GIT_SSH": "the user's own SSH program for git, which a skill fetched with their git keeps", - "GIT_SSH_COMMAND": "the same, as a command", - "TZ": "the machine's time zone, which a routing rule's hours fall back to (c888ef272), not a folder", + "GIT_SSH": "the user's own SSH program for git, which a skill fetched with their git keeps", + "GIT_SSH_COMMAND": "the same, as a command", + "XDG_CURRENT_DESKTOP": "the desktop the user runs, which says whether xdg-mime's answer about an app's links is the whole one (agent.OpenAppLink), not a folder", + "TZ": "the machine's time zone, which a routing rule's hours fall back to (c888ef272), not a folder", } // TestFolderVarsAreListed says every variable the packages that find an diff --git a/internal/agent/applink.go b/internal/agent/applink.go new file mode 100644 index 000000000..3479bbc04 --- /dev/null +++ b/internal/agent/applink.go @@ -0,0 +1,85 @@ +package agent + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" +) + +// NoLinkHandlerError says that nothing on this computer opens App's links +// (Scheme://), so handing one to the system opens nothing and says nothing: +// Windows' rundll32, macOS' open and xdg-open are started, not waited on. +// With Exe set, the scheme is registered to a program that is gone. +type NoLinkHandlerError struct { + App, Scheme, Exe string +} + +func (e *NoLinkHandlerError) Error() string { + if e.Exe != "" { + return fmt.Sprintf("%s's links (%s://) open %s, which isn't there", e.App, e.Scheme, e.Exe) + } + return fmt.Sprintf("nothing on this computer opens %s's links (%s://)", e.App, e.Scheme) +} + +// linkApps names the app behind each import link's scheme. +var linkApps = map[string]string{"cindy": "Cindy", "lody": "Lody", "aionui": "AionUi"} + +// linkHandler says which program opens scheme's links here: found false +// when none does, an error when that can't be read (unknown). Each system +// has its own; tests stand in for it. +var linkHandler = systemLinkHandler + +// OpenAppLink hands an app's import link (Cindy's, Lody's, AionUi's) to +// open, after checking that something here opens it. The system starts +// the opener and never says whether it found a program, so without the +// check a click on Add magpie does nothing at all when the app never +// registered its scheme or was moved since (sungt, 10-29). A check that +// can't be read is unknown, and the link is handed over anyway. +func OpenAppLink(link string, open func(string) error) error { + scheme, _, ok := strings.Cut(link, "://") + if !ok { + scheme, _, _ = strings.Cut(link, ":") + } + scheme = strings.ToLower(scheme) + app := linkApps[scheme] + if app == "" { + app = scheme + } + exe, found, err := linkHandler(scheme) + if err == nil && !found { + return &NoLinkHandlerError{App: app, Scheme: scheme} + } + if err == nil && exe != "" && gone(exe) { + return &NoLinkHandlerError{App: app, Scheme: scheme, Exe: exe} + } + return open(link) +} + +// commandProgram is the program a Windows shell\open\command value runs: +// the quoted path, or the first word of an unquoted one. +func commandProgram(cmd string) string { + cmd = strings.TrimSpace(cmd) + if strings.HasPrefix(cmd, `"`) { + if end := strings.Index(cmd[1:], `"`); end >= 0 { + return cmd[1 : 1+end] + } + return strings.TrimPrefix(cmd, `"`) + } + if i := strings.IndexAny(cmd, " \t"); i >= 0 { + return cmd[:i] + } + return cmd +} + +// gone says that exe, a full path, isn't there. A bare name is found on +// PATH by the system and isn't judged; a failed look is unknown, not gone. +func gone(exe string) bool { + if !filepath.IsAbs(exe) { + return false + } + _, err := os.Stat(exe) + return errors.Is(err, fs.ErrNotExist) +} diff --git a/internal/agent/applink_darwin.go b/internal/agent/applink_darwin.go new file mode 100644 index 000000000..e98f3a701 --- /dev/null +++ b/internal/agent/applink_darwin.go @@ -0,0 +1,50 @@ +//go:build darwin && cgo + +package agent + +/* +#cgo CFLAGS: -Wno-deprecated-declarations +#cgo LDFLAGS: -framework CoreServices -framework CoreFoundation +#include + +// magpie_link_handler asks Launch Services which app opens link, without +// opening it: 1 found, 0 none (kLSApplicationNotFoundErr), -1 unknown. +static int magpie_link_handler(const char *link) { + CFURLRef url = CFURLCreateWithBytes(NULL, (const UInt8 *)link, strlen(link), kCFStringEncodingUTF8, NULL); + if (url == NULL) return -1; + CFErrorRef err = NULL; + CFURLRef app = LSCopyDefaultApplicationURLForURL(url, kLSRolesAll, &err); + CFRelease(url); + if (app != NULL) { + CFRelease(app); + return 1; + } + int r = -1; + if (err != NULL) { + if (CFErrorGetCode(err) == kLSApplicationNotFoundErr) r = 0; + CFRelease(err); + } + return r; +} +*/ +import "C" + +import ( + "errors" + "unsafe" +) + +// systemLinkHandler asks Launch Services whether any app opens scheme's +// links. The app's path isn't judged: Launch Services forgets an app +// that is gone. +func systemLinkHandler(scheme string) (string, bool, error) { + link := C.CString(scheme + "://x") + defer C.free(unsafe.Pointer(link)) + switch C.magpie_link_handler(link) { + case 1: + return "", true, nil + case 0: + return "", false, nil + } + return "", false, errors.New("launch services: unknown") +} diff --git a/internal/agent/applink_other.go b/internal/agent/applink_other.go new file mode 100644 index 000000000..79f32ff76 --- /dev/null +++ b/internal/agent/applink_other.go @@ -0,0 +1,42 @@ +//go:build !windows && !(darwin && cgo) + +package agent + +import ( + "context" + "errors" + "runtime" + "strings" + "time" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/proc" +) + +// systemLinkHandler asks xdg-mime which desktop entry opens scheme's +// links, as xdg-open does. No xdg-mime, or a failed query, is unknown, +// and so is KDE's empty answer: kde-open reads KDE's own service cache, +// which can know a handler xdg-mime's lookup doesn't. +func systemLinkHandler(scheme string) (string, bool, error) { + if runtime.GOOS == "darwin" { + return "", false, errors.New("no launch services without cgo") + } + kde := strings.Contains(strings.ToUpper(appdir.Getenv("XDG_CURRENT_DESKTOP")), "KDE") + tool := proc.FindTool("xdg-mime") + if tool == "" { + return "", false, errors.New("no xdg-mime") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + out, err := proc.CommandContext(ctx, tool, "query", "default", "x-scheme-handler/"+scheme).Output() + if err != nil { + return "", false, err + } + if strings.TrimSpace(string(out)) != "" { + return "", true, nil + } + if kde { + return "", false, errors.New("xdg-mime: no answer under KDE") + } + return "", false, nil +} diff --git a/internal/agent/applink_test.go b/internal/agent/applink_test.go new file mode 100644 index 000000000..672716377 --- /dev/null +++ b/internal/agent/applink_test.go @@ -0,0 +1,100 @@ +package agent + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +func TestCommandProgram(t *testing.T) { + for in, want := range map[string]string{ + `"C:\Users\a b\AppData\Local\Programs\Cindy\Cindy.exe" "%1"`: `C:\Users\a b\AppData\Local\Programs\Cindy\Cindy.exe`, + `"C:\Program Files\Lody\Lody.exe" -- "%1"`: `C:\Program Files\Lody\Lody.exe`, + `C:\Tools\aionui.exe %1`: `C:\Tools\aionui.exe`, + ` "C:\x\y.exe"`: `C:\x\y.exe`, + `"C:\unclosed\y.exe`: `C:\unclosed\y.exe`, + ``: ``, + `rundll32.exe url.dll,FileProtocolHandler %1`: `rundll32.exe`, + } { + if got := commandProgram(in); got != want { + t.Errorf("commandProgram(%q) = %q, want %q", in, got, want) + } + } +} + +// sungt (10-29): Add magpie on Cindy did nothing, as the system starts its +// opener and never says that nothing opens the link. The link is handed +// over only when something does, and otherwise the reason is said. +func TestOpenAppLinkSaysNothingOpensIt(t *testing.T) { + there := filepath.Join(t.TempDir(), "Cindy.exe") + if err := os.WriteFile(there, nil, 0o600); err != nil { + t.Fatal(err) + } + missing := filepath.Join(t.TempDir(), "gone", "Cindy.exe") + link := CindyLink("http://127.0.0.1:3425") + cases := []struct { + name string + exe string + found bool + err error + opens bool + wantExe string + wantError bool + }{ + {name: "none", wantError: true}, + {name: "program gone", exe: missing, found: true, wantError: true, wantExe: missing}, + {name: "program there", exe: there, found: true, opens: true}, + {name: "found, no path (macOS)", found: true, opens: true}, + {name: "bare name on PATH", exe: "cindy.exe", found: true, opens: true}, + {name: "unreadable is unknown", err: errors.New("access denied"), opens: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + old := linkHandler + t.Cleanup(func() { linkHandler = old }) + var asked string + linkHandler = func(scheme string) (string, bool, error) { asked = scheme; return c.exe, c.found, c.err } + var opened string + err := OpenAppLink(link, func(u string) error { opened = u; return nil }) + if asked != "cindy" { + t.Errorf("asked about %q, want cindy", asked) + } + if c.opens != (opened == link) { + t.Errorf("opened %q", opened) + } + var nh *NoLinkHandlerError + if got := errors.As(err, &nh); got != c.wantError { + t.Fatalf("err = %v", err) + } + if nh != nil && (nh.App != "Cindy" || nh.Scheme != "cindy" || nh.Exe != c.wantExe) { + t.Errorf("error %+v", nh) + } + }) + } + // every import scheme names its app + old := linkHandler + t.Cleanup(func() { linkHandler = old }) + linkHandler = func(string) (string, bool, error) { return "", false, nil } + for link, app := range map[string]string{LodyLink("http://127.0.0.1:3425"): "Lody", AionUiScheme + "a=1": "AionUi"} { + var nh *NoLinkHandlerError + if err := OpenAppLink(link, func(string) error { return nil }); !errors.As(err, &nh) || nh.App != app { + t.Errorf("%s: %v", link, err) + } + } +} + +// The system's own answer for a scheme nothing registers: none, not an +// error, where it can be read (the registry, Launch Services, xdg-mime). +func TestSystemLinkHandlerNoSuchScheme(t *testing.T) { + scheme := fmt.Sprintf("magpie-no-such-%d", time.Now().UnixNano()) + exe, found, err := systemLinkHandler(scheme) + if err != nil { + t.Skipf("can't be read here: %v", err) + } + if found || exe != "" { + t.Fatalf("%s:// opens %q", scheme, exe) + } +} diff --git a/internal/agent/applink_windows.go b/internal/agent/applink_windows.go new file mode 100644 index 000000000..7c7d36339 --- /dev/null +++ b/internal/agent/applink_windows.go @@ -0,0 +1,69 @@ +//go:build windows + +package agent + +import ( + "errors" + + "golang.org/x/sys/windows/registry" +) + +// systemLinkHandler reads the program Windows runs for scheme's links, +// HKEY_CLASSES_ROOT\\shell\open\command, which is what Electron's +// setAsDefaultProtocolClient writes (Cindy, AionUi) for the user, and +// installers for the user or the machine. Only a scheme with no key of its +// own and no default app the user chose (UserChoice, as Settings' Default +// apps keeps one) opens nothing; a key with no command of its own is +// handed to another (a packaged app's), so it opens something unknown. +func systemLinkHandler(scheme string) (string, bool, error) { + k, err := registry.OpenKey(registry.CLASSES_ROOT, scheme, registry.QUERY_VALUE) + if errors.Is(err, registry.ErrNotExist) { + return userChoice(scheme) + } + if err != nil { + return "", false, err + } + k.Close() + k, err = registry.OpenKey(registry.CLASSES_ROOT, scheme+`\shell\open\command`, registry.QUERY_VALUE) + if errors.Is(err, registry.ErrNotExist) { + return "", true, nil + } + if err != nil { + return "", false, err + } + defer k.Close() + v, typ, err := k.GetStringValue("") + if errors.Is(err, registry.ErrNotExist) { + return "", true, nil + } + if err != nil { + return "", false, err + } + if typ == registry.EXPAND_SZ { + if x, err := registry.ExpandString(v); err == nil { + v = x + } + } + return commandProgram(v), true, nil +} + +// userChoice: the app the user picked for scheme in Default apps, which +// needs no key of the scheme's own. +func userChoice(scheme string) (string, bool, error) { + k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\Shell\Associations\UrlAssociations\`+scheme+`\UserChoice`, registry.QUERY_VALUE) + if errors.Is(err, registry.ErrNotExist) { + return "", false, nil + } + if err != nil { + return "", false, err + } + defer k.Close() + id, _, err := k.GetStringValue("ProgId") + if errors.Is(err, registry.ErrNotExist) { + return "", false, nil + } + if err != nil { + return "", false, err + } + return "", id != "", nil +} diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index b4a6cbb6f..ae818cc91 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -663,6 +663,10 @@ func importAccounts(args []string) error { // tests can have it go nowhere without starting a program (noBrowser). var openInBrowser = openURLInBrowser +// appLink hands an app's import link over once something here opens it +// (agent.OpenAppLink); tests stand in for the system's answer. +var appLink = agent.OpenAppLink + func openURLInBrowser(url string) { // the link is printed beside it, to open by hand when this fails (#2043) if err := proc.OpenBrowser(url); err != nil { diff --git a/internal/cli/applink_cli_test.go b/internal/cli/applink_cli_test.go new file mode 100644 index 000000000..c082d4d38 --- /dev/null +++ b/internal/cli/applink_cli_test.go @@ -0,0 +1,37 @@ +package cli + +import ( + "errors" + "testing" + + "github.com/yetone/magpie/internal/agent" +) + +// sungt (10-29): with nothing here to open Cindy's links, `magpie cindy +// add` said "✓ Cindy opened" while nothing opened. It says why, and hands +// nothing to the browser. +func TestImportAddSaysNothingOpensIt(t *testing.T) { + groupsHome(t) + var handed []string + old := openInBrowser + openInBrowser = func(u string) { handed = append(handed, u) } + t.Cleanup(func() { openInBrowser = old }) + oldLink := appLink + t.Cleanup(func() { appLink = oldLink }) + for _, id := range []string{"cindy", "aionui"} { + appLink = func(string, func(string) error) error { + return &agent.NoLinkHandlerError{App: id, Scheme: id} + } + var nh *agent.NoLinkHandlerError + if err := run([]string{id, "add"}); !errors.As(err, &nh) { + t.Errorf("%s add: %v", id, err) + } + appLink = func(link string, open func(string) error) error { return open(link) } + if err := run([]string{id, "add"}); err != nil { + t.Errorf("%s add with a handler: %v", id, err) + } + } + if len(handed) != 2 { + t.Fatalf("handed to the browser: %q", handed) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 29d89d1c3..a8ed5294a 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -518,11 +518,16 @@ func run(args []string) error { // 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()) } + // handed over only when something here opens it, or nothing + // opens and nothing says so (sungt, 10-29) + openApp := func(u string) error { return appLink(u, func(u string) error { openInBrowser(u); return nil }) } + handOver := openApp if a.ID == "lody" { // Lody on Linux is run with the link (agent.OpenLody) - _ = agent.OpenLody(link, func(u string) error { openInBrowser(u); return nil }) - } else { - openInBrowser(link) + handOver = func(u string) error { return agent.OpenLody(u, openApp) } + } + if err := handOver(link); err != nil { + return fmt.Errorf("%w. Open %s once or install it again, then run this again", err, a.Name) } 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/api.go b/internal/gui/api.go index 1b9f61908..e807be7ac 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2768,6 +2768,12 @@ func fail(rw http.ResponseWriter, err error) { out["code"] = "runtime_unavailable" out["offline"] = string(unavailable.Offline) } + // an app's import link that nothing here opens, or that opens a + // program which is gone, said in the reader's language + var noHandler *agent.NoLinkHandlerError + if errors.As(err, &noHandler) { + out["code"], out["app"], out["exe"], out["said"] = "no_link_handler", noHandler.App, noHandler.Exe, linkSaid[noHandler.Exe != ""] + } var noModels *agent.NoModelsError if errors.As(err, &noModels) { out["code"] = "no_models" @@ -2891,6 +2897,14 @@ var bunSaid = map[string]string{ "cpu": "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.", } +// linkSaid is what the page says for an app's import link that nothing +// here opens, by whether it names a program that is gone: an i18n.js key +// like bunSaid's, with {app} and {exe} filled from the reply +var linkSaid = map[bool]string{ + false: "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again", + true: "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again ({exe})", +} + // appOutJSON is Codex on magpie while its ChatGPT account is used up: the // account, when it has room again (zero when the reading doesn't say), and // whether a Codex app is left on the account, its app-server not diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index b4df27501..1571adcb0 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -151,7 +151,7 @@ async function api(path, body, heads, signal) { err.message = t("None of magpie's models is left in {agent}'s model list: pick one under Model list → Pick, then connect {agent}", { agent: data.agent }); } if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language - if (data?.code === "bun_unstartable") err.message = t(data.said); // bunSaid in api.go: an i18n.js key + if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go) // an account the agent is signed in to, refused removal while it has // another: said in the reader's language if (data?.code === "signed_in") { @@ -2706,7 +2706,7 @@ function importButton(a) { b.onclick = (ev) => { ev.stopPropagation(); if (web) location.href = a.import; - else api("open", { url: a.import }); + else api("open", { url: a.import }).then(() => status(t("Sent to {name}: confirm adding magpie there", a), "ok"), (e) => status(e.message, "err")); }; return b; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index b7935d554..10a5d268b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -539,6 +539,9 @@ const I18N = { "{name} has magpie as a provider · click to add it again": "{name} 已添加 magpie 供应商 · 点击可再次添加", "Opens {name} to add magpie as a provider — confirm it there": "打开 {name} 添加 magpie 供应商,在其中确认", "Add magpie": "添加 magpie", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again": "这台电脑上没有程序能打开 {app} 的链接,所以 {app} 没有打开:先打开一次 {app} 或重新安装,再点「添加 magpie」", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again ({exe})": "这台电脑上没有程序能打开 {app} 的链接,所以 {app} 没有打开:先打开一次 {app} 或重新安装,再点「添加 magpie」 ({exe})", + "Sent to {name}: confirm adding magpie there": "已交给 {name}:请在其中确认添加 magpie", "Added · magpie is a provider in {agent}": "已添加 · magpie 是 {agent} 的提供商", "Not added · {agent} asks to add magpie when its link opens": "未添加 · 打开链接后 {agent} 会询问是否添加 magpie", "{agent} hidden · find it under Hidden at the bottom": "已隐藏 {agent} · 可在列表底部「已隐藏」里找回", @@ -4610,6 +4613,9 @@ const I18N = { "{name} has magpie as a provider · click to add it again": "{name} 已新增 magpie 供應商 · 點選可再次新增", "Opens {name} to add magpie as a provider — confirm it there": "開啟 {name} 新增 magpie 供應商,在其中確認", "Add magpie": "新增 magpie", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again": "這台電腦上沒有程式能開啟 {app} 的連結,所以 {app} 沒有開啟:先開啟一次 {app} 或重新安裝,再點「新增 magpie」", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again ({exe})": "這台電腦上沒有程式能開啟 {app} 的連結,所以 {app} 沒有開啟:先開啟一次 {app} 或重新安裝,再點「新增 magpie」 ({exe})", + "Sent to {name}: confirm adding magpie there": "已交給 {name}:請在其中確認新增 magpie", "Added · magpie is a provider in {agent}": "已新增 · magpie 是 {agent} 的提供商", "Not added · {agent} asks to add magpie when its link opens": "未新增 · 開啟連結後 {agent} 會詢問是否新增 magpie", "{agent} hidden · find it under Hidden at the bottom": "已隱藏 {agent} · 可在列表底部「已隱藏」裡找回", @@ -8647,6 +8653,9 @@ const I18N = { "{name} has magpie as a provider · click to add it again": "{name} には magpie がプロバイダとして追加済み · クリックで再追加", "Opens {name} to add magpie as a provider — confirm it there": "{name} を開いて magpie をプロバイダとして追加します。そちらで確認してください", "Add magpie": "magpie を追加", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again": "このコンピュータには {app} のリンクを開くアプリがないため、{app} は開きませんでした。{app} を一度起動するか入れ直してから、もう一度「magpie を追加」を押してください", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again ({exe})": "このコンピュータには {app} のリンクを開くアプリがないため、{app} は開きませんでした。{app} を一度起動するか入れ直してから、もう一度「magpie を追加」を押してください ({exe})", + "Sent to {name}: confirm adding magpie there": "{name} に渡しました。そちらで magpie の追加を確認してください", "Added · magpie is a provider in {agent}": "追加済み · magpie は {agent} のプロバイダです", "Not added · {agent} asks to add magpie when its link opens": "未追加 · リンクを開くと {agent} が magpie の追加を確認します", "{agent} hidden · find it under Hidden at the bottom": "{agent} を非表示にしました · 一番下の「非表示」から戻せます", @@ -12701,6 +12710,9 @@ const I18N = { "{name} has magpie as a provider · click to add it again": "{name} hat magpie als Anbieter · klicken, um es erneut hinzuzufügen", "Opens {name} to add magpie as a provider — confirm it there": "Öffnet {name}, um magpie als Anbieter hinzuzufügen — dort bestätigen", "Add magpie": "magpie hinzufügen", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again": "Auf diesem Computer öffnet nichts die Links von {app}, daher wurde {app} nicht geöffnet: {app} einmal starten oder neu installieren, dann erneut auf „magpie hinzufügen“ klicken", + "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again ({exe})": "Auf diesem Computer öffnet nichts die Links von {app}, daher wurde {app} nicht geöffnet: {app} einmal starten oder neu installieren, dann erneut auf „magpie hinzufügen“ klicken ({exe})", + "Sent to {name}: confirm adding magpie there": "An {name} übergeben: dort das Hinzufügen von magpie bestätigen", "Added · magpie is a provider in {agent}": "Hinzugefügt · magpie ist ein Anbieter in {agent}", "Not added · {agent} asks to add magpie when its link opens": "Nicht hinzugefügt · {agent} fragt beim Öffnen des Links, ob magpie hinzugefügt werden soll", "{agent} hidden · find it under Hidden at the bottom": "{agent} ausgeblendet · unten unter „Ausgeblendet“ zu finden", diff --git a/internal/gui/lody_test.go b/internal/gui/lody_test.go index 10502afd8..7a37b78c8 100644 --- a/internal/gui/lody_test.go +++ b/internal/gui/lody_test.go @@ -21,6 +21,65 @@ type importWindows struct { func (w *importWindows) OpenURL(u string) error { w.opened = u; return nil } +// linksOpen has every app's import link opened here, whatever this +// machine has installed (agent.OpenAppLink asks the system). +func linksOpen(t *testing.T) { + old := appLink + t.Cleanup(func() { appLink = old }) + appLink = func(link string, open func(string) error) error { return open(link) } +} + +// sungt (10-29): Add magpie on Cindy did nothing when nothing on the +// computer opened cindy:// links. /api/open says so, by code and app, and +// hands nothing over. +func TestImportLinkNothingOpens(t *testing.T) { + sandboxHome(t) + old := appLink + t.Cleanup(func() { appLink = old }) + for _, c := range []struct{ link, app, exe string }{ + {agent.CindyLink("http://127.0.0.1:3425"), "Cindy", ""}, + {agent.CindyLink("http://127.0.0.1:3425"), "Cindy", `C:\gone\Cindy.exe`}, + {agent.AionUiScheme + "a=1", "AionUi", ""}, + {agent.LodyLink("http://127.0.0.1:3425"), "Lody", ""}, + } { + appLink = func(link string, open func(string) error) error { + return &agent.NoLinkHandlerError{App: c.app, Scheme: "x", Exe: c.exe} + } + w := &importWindows{} + mux := http.NewServeMux() + providerRoutes(mux, w) + body, _ := json.Marshal(map[string]string{"url": c.link}) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/open", strings.NewReader(string(body)))) + var out map[string]string + _ = json.Unmarshal(rec.Body.Bytes(), &out) + if rec.Code != http.StatusBadRequest || out["code"] != "no_link_handler" || out["app"] != c.app || out["exe"] != c.exe || out["said"] != linkSaid[c.exe != ""] { + t.Errorf("%s: %d %s", c.app, rec.Code, rec.Body) + } + if w.opened != "" { + t.Errorf("%s: handed over %q", c.app, w.opened) + } + } +} + +// What the page says for it is a key i18n.js has in every language, with +// the {app} and {exe} the reply fills. +func TestLinkSaidIsTranslated(t *testing.T) { + words, err := os.ReadFile("assets/i18n.js") + if err != nil { + t.Fatal(err) + } + for exe, said := range linkSaid { + key, _ := json.Marshal(said) + if n := strings.Count(string(words), string(key)+":"); n != 4 { + t.Errorf("%v: i18n.js has %q in %d languages, want zh, zh-TW, ja and de", exe, said, n) + } + if !strings.Contains(said, "{app}") || strings.Contains(said, "{exe}") != exe { + t.Errorf("%v: %q doesn't say {app}, or {exe} only when it is set", exe, said) + } + } +} + func TestLodyImportHandoff(t *testing.T) { home := sandboxHome(t) // no Lody desktop entry of the machine's is run (agent.OpenLody) @@ -67,6 +126,7 @@ func TestLodyImportHandoff(t *testing.T) { if b, _ := json.Marshal(cindy); !strings.Contains(string(b), `"added":false`) { t.Fatalf("Cindy's row leaves added out: %s", b) } + linksOpen(t) w := &importWindows{} mux := http.NewServeMux() providerRoutes(mux, w) @@ -122,6 +182,7 @@ func TestLodyImportRunsLodyOnLinux(t *testing.T) { t.Fatal(err) } link := agent.LodyLink("http://127.0.0.1:3425") + linksOpen(t) w := &importWindows{} mux := http.NewServeMux() providerRoutes(mux, w) @@ -206,6 +267,7 @@ func TestAionUiImportRow(t *testing.T) { if b, _ := json.Marshal(find()); strings.Contains(string(b), `"added"`) { t.Fatalf("an unreadable database says added: %s", b) } + linksOpen(t) w := &importWindows{} mux := http.NewServeMux() providerRoutes(mux, w) diff --git a/internal/gui/providers.go b/internal/gui/providers.go index c717ed414..4238d6319 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -999,6 +999,10 @@ func moveContext(r *http.Request) (context.Context, context.CancelFunc) { return context.WithTimeout(context.WithoutCancel(r.Context()), 10*time.Minute) } +// appLink hands an app's import link over once something here opens it +// (agent.OpenAppLink); tests stand in for the system's answer. +var appLink = agent.OpenAppLink + func providerRoutes(mux *http.ServeMux, w Windows) { importAppsRoutes(mux) pluginRoutes(mux, w) @@ -2383,10 +2387,17 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // again: that one pane, not System Settings' scheme at large if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) || strings.HasPrefix(in.URL, agent.AionUiScheme) || in.URL == autostart.LoginItemsURL { open := w.OpenURL - if strings.HasPrefix(in.URL, agent.LodyScheme) { + // an app's import link is handed over only when something + // here opens it: the system says nothing when nothing does, + // and Add magpie did nothing at all (sungt, 10-29) + app := func(u string) error { return appLink(u, w.OpenURL) } + switch { + case strings.HasPrefix(in.URL, agent.LodyScheme): // Lody on Linux is run with the link, which xdg-open // turned away (agent.OpenLody) - open = func(u string) error { return agent.OpenLody(u, w.OpenURL) } + open = func(u string) error { return agent.OpenLody(u, app) } + case strings.HasPrefix(in.URL, agent.CindyScheme), strings.HasPrefix(in.URL, agent.AionUiScheme): + open = app } // Open again on a sign-in says why it didn't open (#2043) if err := open(in.URL); err != nil { diff --git a/internal/gui/tests/import-row.test.cjs b/internal/gui/tests/import-row.test.cjs index bfcf5aca4..22874af14 100644 --- a/internal/gui/tests/import-row.test.cjs +++ b/internal/gui/tests/import-row.test.cjs @@ -22,7 +22,7 @@ const cindy = (added) => ({ id: "cindy", name: "Cindy", path: "", icon: "cindy", const AIONUI_LINK = "aionui://add-provider?api_key=magpie-aionui&base_url=http%3A%2F%2F127.0.0.1%3A3425%2Fv1&name=magpie&platform=custom"; const aionui = (added) => ({ id: "aionui", name: "AionUi", path: "", icon: "aionui", import: AIONUI_LINK, added, fields: [] }); -async function serve(route, lang, added) { +async function serve(route, lang, added, ctl = {}) { const url = new URL(route.request().url()); const json = (data) => route.fulfill({ json: data }); if (url.pathname === "/boot.js") { @@ -32,6 +32,8 @@ async function serve(route, lang, added) { if (url.pathname === "/api/state") return json({ agents: [crush(added), cindy(added), aionui(!added), { id: "lody", name: "Lody", path: "", icon: "lody", import: "lody://provider/import?v=1&data=fixture", fields: [] }], profiles: [], settings: { lang, theme: "light", textSize: 100 } }); if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); if (url.pathname === "/api/plugins") return json({ plugins: [] }); + // nothing here opens the app's links (agent.NoLinkHandlerError) + if (url.pathname === "/api/open" && ctl.noHandler) return route.fulfill({ status: 400, json: { error: "nothing on this computer opens Cindy's links (cindy://)", code: "no_link_handler", app: "Cindy", exe: ctl.exe || "", said: LINK_SAID + (ctl.exe ? " ({exe})" : "") } }); if (url.pathname.startsWith("/api/")) return json({}); const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; @@ -55,6 +57,25 @@ const UNKNOWN = { de: "Öffnet Lody, um magpie als Anbieter hinzuzufügen — dort bestätigen", }; +// what a click on Add magpie became, in the reader's language (sungt, +// 10-29: a link nothing opened did nothing, and nothing said so) +const OPENED = { + en: "Sent to Cindy: confirm adding magpie there", + zh: "已交给 Cindy:请在其中确认添加 magpie", + "zh-TW": "已交給 Cindy:請在其中確認新增 magpie", + ja: "Cindy に渡しました。そちらで magpie の追加を確認してください", + de: "An Cindy übergeben: dort das Hinzufügen von magpie bestätigen", +}; +// the i18n.js key api.go's linkSaid sends +const LINK_SAID = "Nothing on this computer opens {app}'s links, so {app} didn't open: open {app} once or install it again, then click Add magpie again"; +const NO_HANDLER = { + en: "Nothing on this computer opens Cindy's links, so Cindy didn't open: open Cindy once or install it again, then click Add magpie again", + zh: "这台电脑上没有程序能打开 Cindy 的链接,所以 Cindy 没有打开:先打开一次 Cindy 或重新安装,再点「添加 magpie」", + "zh-TW": "這台電腦上沒有程式能開啟 Cindy 的連結,所以 Cindy 沒有開啟:先開啟一次 Cindy 或重新安裝,再點「新增 magpie」", + ja: "このコンピュータには Cindy のリンクを開くアプリがないため、Cindy は開きませんでした。Cindy を一度起動するか入れ直してから、もう一度「magpie を追加」を押してください", + de: "Auf diesem Computer öffnet nichts die Links von Cindy, daher wurde Cindy nicht geöffnet: Cindy einmal starten oder neu installieren, dann erneut auf „magpie hinzufügen“ klicken", +}; + for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { for (const lang of Object.keys(SAID)) { for (const added of [false, true]) { @@ -69,7 +90,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await browser.close(); }); page.setDefaultTimeout(5000); - await page.route("**/*", (route) => serve(route, lang, added)); + const ctl = {}; + await page.route("**/*", (route) => serve(route, lang, added, ctl)); await page.goto("http://magpie.test/"); await page.waitForLoadState("networkidle"); @@ -142,6 +164,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await row.locator(".ag-start").click(); const req = await opened; assert.equal(JSON.parse(req.postData() || "{}").url, "cindy://import?x=1"); + // and says what became of it: opened, or why nothing opened + const said = async (text, kind) => { + await page.waitForFunction(([want, k]) => { const s = document.querySelector("#status"); return s && s.textContent === want && s.classList.contains(k); }, [text, kind], { timeout: 3000 }).catch(async () => { + assert.fail(`status ${JSON.stringify(await page.locator("#status").evaluate((s) => [s.textContent, s.className]))}, want ${kind} ${JSON.stringify(text)}`); + }); + }; + await said(OPENED[lang], "ok"); + ctl.noHandler = true; + await row.locator(".ag-start").click(); + await said(NO_HANDLER[lang], "err"); + ctl.exe = "C:\\gone\\Cindy.exe"; + await row.locator(".ag-start").click(); + await said(NO_HANDLER[lang] + " (C:\\gone\\Cindy.exe)", "err"); }); } }