diff --git a/docs/reference.md b/docs/reference.md index eb64e29f0..8f088c976 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1195,6 +1195,45 @@ treated as a built-in's 401/402/403/429 is; any other throw is a failure and the next search API is asked. It has the time a search API has (a quarter of a search's limit); `ctx.abort` fires then. +A search API can use a sign-in instead of a key: `auth` names a provider +this plugin's `auth` hook signs in to (one with models, or an auth hook +with none). It is added with no key, and its row in Settings says whose +sign-in it uses and how many of that provider's accounts are on. A search +asks one account at a time: the accounts that are on (Providers' switches), +in the order the provider's model requests take them, one resting from a +search refusal last. For each, +`ctx.getAuth()` returns a copy of that one account's sign-in, renewed first +when it is due; the renewal counts within the search's time, and the plugin +never reads `plugin-auth.json`. A token the hook saves with +`client.auth.set({path: {id: ""}, body})` goes to that same +account. A throw with `status` 429 (or 401, 402, 403) +rests that account for search only, never for the provider's models, and +the next account is asked. Not signed in, or no account on, is said in the +row and in the request log, and the next search API is asked. A plugin with +several providers adds one search entry per provider. + +```js +export const SeekCo = async () => ({ + auth: { provider: "seekco", methods: [/* … */], async loader(getAuth) { /* … */ } }, + search: { + seek: { + name: "SeekCo", + auth: "seekco", // the provider whose sign-in it uses; no key + async execute({ query, count }, ctx) { + const a = await ctx.getAuth() // { type: "oauth", access, refresh, expires, accountId, … } + const r = await fetch(`https://api.seek.example/search?q=${encodeURIComponent(query)}&n=${count}`, + { headers: { authorization: `Bearer ${a.access}` }, signal: ctx.abort }) + if (!r.ok) throw Object.assign(new Error(await r.text()), { status: r.status }) + return (await r.json()).results + }, + }, + }, +}) +``` + +An `auth` naming a provider this plugin doesn't sign in to is ignored: the +entry is an ordinary keyed one, and its `ctx` has no `getAuth`. + #### Gateway middleware A plugin can also be gateway middleware: `onRequest(body, ctx)` sees each diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 15d2577cf..287e42a98 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -270,6 +270,7 @@ still means off; a page is its own plugin's to turn on and off. | --- | --- | --- | --- | | Router strategy | A module's `export const strategies = {name: (pool, seats, options) => order}` (or `{order}` objects) are routings `/`, registered with `routes.Register` while the gateway serves `middleware.Points()` and the plugin is on and loaded; off or reloaded, they are removed. 20ms each, fail open: an error, a timeout or what isn't an order of the seats is the listed order, counted on the Plugins page. The routing pickers offer the served ones (`jsRoutings` in the settings state); a routing saved whose plugin is gone shows as it is and is the listed order. providers.json keeps such a routing as saved (`provider.PluginRouting`), so a plugin turned off and on again routes its groups again. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go), [`app.js`](../../internal/gui/assets/app.js), [`client.js`](../../internal/gui/assets/plugins/routing/client.js), [`groups_cli.go`](../../internal/cli/groups_cli.go), [`routing.go`](../../internal/provider/routing.go) | | Usage observer | `export function onUsage(row, options)` gets each usage row of an allow-list (no bodies, prompts or ids), from a bounded queue off the request path: a full queue drops and counts, and a request never waits. 250ms each, fail open. | `plugins/middleware` ("JS gateway plugins", from the same module as its [middleware](gateway-middleware.md)) | [`points.go`](../../internal/middleware/points.go) | +| Search API | Its `search` hook's entries, each a web search API in Settings › Web search (`:`), asked in the search APIs' order with a quarter of a search's time. An entry with a key, none (`keyOptional`) or the user's address (`url`), or one with `auth` naming a provider the plugin's own `auth` hook signs in to: it takes no key, asks that provider's accounts that are on in the order its model requests take them, and its `ctx.getAuth()` is the one account chosen, renewed first within the search's time; a refusal rests the account for search only. Off, no search asks it. | `plugins/search` (Web search, Essential) | [Plugin tools](plugin-tools.md) ("Search APIs from a plugin"), [provider plugins](provider-plugins.md) | | Tool | Its OpenCode `tool` hook's tools, offered to every agent by magpie's MCP server at `/mcp/magpie/tools`, each named `_`, each call held to the calling key's limit and run in the host within 55s. Off, no tool is listed and a call says the plugin is off. | `plugins/tools` ("Plugin tools", Essential; `InUse` counts the plugins on that give tools, from `plugin-tools.json`), `gwtool.PluginTools` | [Plugin tools](plugin-tools.md) | | A page in the window | `magpie.page {title, file, icon}` and `magpie.permissions` in package.json, installed from npm, GitHub or a folder like any plugin (`plugin.WindowPage`: `file` an .html inside the plugin, the icon in the page's folder, reads kept to `plugin.PageReads`). An on plugin's page gets a tab in the sidebar's Plugins group, after the built-in pages (`pluginpages.js`, a kernel `page` part). It runs in an iframe sandboxed to `allow-scripts`, its files served from `/_magpie/plugin//` (an HMAC of the spec with a secret of this run) under a policy of `sandbox allow-scripts`, its own folder only, `connect-src 'none'`. The frame talks to the window by `postMessage`: the window answers only its own frame (`ev.source`), with the theme, its own options (`/api/plugin-pages/options`, at most once a second, saved without restarting the host for a page-only plugin) and the reads it declared (`/api/plugin-pages/read`, checked again by the server): `usage:summary` (totals and the top 20 models) and `providers:list` (ids and names). Nothing secret is readable, since a page can still send its frame to another site. `noFramedAPI` turns away every `/api/` request a sandboxed frame or another site can send (`Origin: null`, `Sec-Fetch-Dest` a frame, a cross-site subresource), since the desktop window's API has no key; `webGuard` lets the prefix through without the cookie the frame never sends, and the token is the key. A page that throws, or doesn't say hello in 10s, is broken through the kernel (`ctx.broke`), with Try again. The frame is made the first time the page is opened. When the reader goes to another page it is told (`{event: "visibility", data: {visible: false}}`, the bridge's `magpie.visible` and `magpie.onVisibility(fn)`), since a frame in a hidden view isn't hidden to itself, and told again on coming back. A page left 10 minutes (`IDLE_MS`) has its frame let go, with its scripts, timers and connections, and loads again when it is next opened; `magpie.page.keepAlive: true` (`plugin.PageSpec.KeepAlive`, anything but `true` is false) keeps it however long, for a page that works while no one looks at it. Tests: `TestWindowPanels` (keepAlive), `plugin-page-idle.test.cjs`. The Plugins page shows the page and its reads on the row before the plugin is on. A plugin that is only a page is in-magpie-only: no Bun host starts for it. A page whose plugin also has a part for the host (a local service its page goes to, as Magiczerowxy/magpie-chat's does) starts the host when its HTML is served, if none is up (`pageHost`, `plugin.Warm`), waiting up to 7s: the host otherwise starts only on a call, so after a Restart (a plugin installed, updated or set, a Bun update) or a crash the page's service was down, and WebKit leaves a frame that navigates to a refused address on its old document with no error. A page reaches its service through magpie too, when the plugin declares it (`magpie.page.service {port, option}`, `plugin.ServiceSpec`: the port, or the plugin option named, from its plugins.json `options`): in `magpie web`, where 127.0.0.1 is the viewer's own computer, not the server (aigcfree on Discord: a server behind nginx, a Windows PC's browser, "127.0.0.1 refused to connect"), `/api/plugin-pages` gives the page a `service` under its token, `_magpie/service/`, and the bridge hands it to the frame as `magpie.service`, an absolute address (the desktop window gets none, and the page goes to 127.0.0.1 as before; a slot page gets none). `servePageService` reverse-proxies it to 127.0.0.1:: Host set to the service's own (its rebinding check), the window's cookie taken off, Origin only absent or `null` (403 otherwise), Set-Cookie dropped, everything it sends sandboxed (`sandbox allow-scripts; frame-ancestors 'self'`, `Referrer-Policy: no-referrer`), streamed as it comes (`FlushInterval -1`, `X-Accel-Buffering: no` on an event stream, which `webCompressed` never gzips), a redirect to its own address made relative, and the gateway's port never served (a request from this server is loopback, which the gateway takes without a key). The way in is the page's: the token, which only a signed-in `/api` hands out, behind `AllowGuard`; the service stays on loopback. Its entry starts the host as the page's HTML does, and a service not up yet answers its frame with a 502 page that tries again in 2s. The chat page (`@magpie-community/page-chat` 0.1.1) goes to `magpie.service` when given one, else 127.0.0.1, and asks its `api/…` by relative address. Tests: `TestPluginPageServiceListedToBrowserOnly`, `TestPluginPageServiceSpec`, `TestPluginPageServiceProxied`, `TestPluginPageServiceDown`, `TestServiceLocation`, `plugin-page.test.cjs` (`magpie.service`). Discover lists a market entry of `kind: "page"` under Pages with the Page chip, and a GitHub repository tagged `magpie-plugin` whose package.json has `magpie.page.file` as a Page (`TaggedRepos`, which then checks that file is committed, as it does a provider's entry; `TestTaggedRepos`, `plugin-kinds-discover.test.cjs`). Tests: `TestWindowPageStaysInside`, `TestPluginPageServedShutIn`, `TestPluginPageReadsWhatItDeclared`, `TestPluginPageNoAPI`, `TestPluginPageWebGuard`, `TestPluginPageStartsItsHost`, `plugin-page.test.cjs`. Example: `internal/gui/testdata/page-plugin`. A magpie that serves no pages (a command such as `magpie plugin update`, `servesPages` in `internal/cli`) starts its host with each service its plugin's option moves on a free port of its own (`plugin.ServePages`, `hostOptions`): a plugin that waits on its port, as page-chat does, loads at once beside the app's host holding it, and doesn't go on trying for it to take it when the app's host restarts (#5187). A service no option moves is started as before. Tests: `TestHostServingNoPagesLeavesHeldPort`, `TestHostOptionsMoveOnlyTheService`, `TestServesPages`. | the window, no built-in plugin: the page is the plugin's own on/off | [`page.go`](../../internal/plugin/page.go), [`pluginpage.go`](../../internal/gui/pluginpage.go), [`pagebridge.js`](../../internal/gui/pagebridge.js), [`pluginpages.js`](../../internal/gui/assets/pluginpages.js) | diff --git a/docs/subsystems/plugin-tools.md b/docs/subsystems/plugin-tools.md index 512bc62ed..26f119e80 100644 --- a/docs/subsystems/plugin-tools.md +++ b/docs/subsystems/plugin-tools.md @@ -54,13 +54,14 @@ The example plugin the tests load is [`internal/plugin/testdata/tools`](../../in ## Search APIs from a plugin -The same host and `Loaded` list carry a second hook, `search`: `{search: {: {name, keysURL?, keyOptional?, url?, execute({query, count, key, url}, ctx)}}}`, which adds a web search API to magpie's own ([`provider.SearchVendors`](../../internal/provider/search_api.go)). It is not part of the tools MCP server; it belongs to the search path ([Gateway routing](gateway-routing.md), "A search API's base URL"). +The same host and `Loaded` list carry a second hook, `search`: `{search: {: {name, keysURL?, keyOptional?, url?, auth?, execute({query, count, key, url}, ctx)}}}`, which adds a web search API to magpie's own ([`provider.SearchVendors`](../../internal/provider/search_api.go)). It is not part of the tools MCP server; it belongs to the search path ([Gateway routing](gateway-routing.md), "A search API's base URL"). | Part | Responsibility | Source | | --- | --- | --- | -| Collect | `searchesOf` keeps the ids that match `^[a-z0-9][a-z0-9-]{0,31}$` and have an `execute`; `searchList` returns `{id, name, keysURL, keyOptional, needURL}` with the plugin (`Loaded.Searches`). | `searchesOf`, `searchList` in [`host.js`](../../internal/plugin/host.js); [`search.go`](../../internal/plugin/search.go) | +| Collect | `searchesOf` keeps the ids that match `^[a-z0-9][a-z0-9-]{0,31}$` and have an `execute`; `searchList` returns `{id, name, keysURL, keyOptional, needURL, auth}` with the plugin (`auth` only when it names a provider this plugin's auth hook signs in to, `searchAuthOf`) (`Loaded.Searches`). | `searchesOf`, `searchList` in [`host.js`](../../internal/plugin/host.js); [`search.go`](../../internal/plugin/search.go) | | Note | After every load the host notes them in `plugin-searches.json` (whole, only when changed). `NotedSearches` reads it without starting the host (`filememo`), for plugins that are on in plugins.json; a note that can't be parsed is an error, and `AllSearchVendors` then adds none. The API's vendor id is `:` (`PluginSearch.VendorID`), so it can't take a built-in's id. | `noteSearches`, `NotedSearches` in `search.go` | | List | `provider.AllSearchVendors` is `SearchVendors` plus the noted ones; `SearchVendorOf`, `Ready`, `check` and the GUI's `searchVendors` use it. A user's saved key and order stay in providers.json under that id; with the plugin off or removed the API is not ready, so never asked, and comes back with the plugin. | `search_api.go` in `internal/provider`, `searchVendorJSON` in [`api.go`](../../internal/gui/api.go) | | Ask | `askSearchAPI` hands a plugin's vendor to `askPluginSearch`, below `askSearchAPIKeys`: the same keys, rest, timeout (a quarter of `searchTimeout`) and request-log row as a built-in, with the query `apiSearch` already masked. `plugin.RunSearch` runs the host's `search` call; a throw with a numeric `status` comes back as `SearchRefused`, which becomes `searchRefused`. Pages are cleaned with `searchPlain` and `clipText`, six at most. | `askPluginSearch` in [`search_api.go`](../../internal/gateway/search_api.go) | +| Sign in | An entry with `auth` (`SearchVendor.Auth`) is ready with no key. `askSearchAPIKeys` hands it to `askSearchSignedIn`: `provider.SearchSignIn` finds the plugin's provider (`plugin:` of the same plugin) and its name; none is "not signed in to X: sign in to it on Providers", and the next search API is asked. Its accounts are the ones a model request takes (`accountsOn`: own unless paused, then `AlsoOn`, by `LoginRanks`), in `searchKeyOrder`'s order, each with a quarter of the search's limit, a request-log row named by the account's user and its own search rest (`searchKeyID` of `account `); a refusal rests it for search only (`restSearchKey`), never `restingUntil`, and the next account is asked. `plugin.RunSearchAs` sends the account's key and its proxy; the host's `runSearch` checks the key is this provider's and signed in, renews it under `fresh` (its wait counts within the call's time, `late`; an account signed out mid-renewal stays out and the search fails), runs the hook inside `inScope`, so a token it saves with `client.auth.set` goes to that account, and gives `ctx.getAuth()` a copy of that account alone. The GUI's `searchVendorJSON.auth` says the provider's name, whether it is signed in and how many accounts are on (`gateway.SearchAccountsOn`); `settings.js` shows that in the key's place. | [`search_signin.go`](../../internal/gateway/search_signin.go), [`search_signin.go`](../../internal/provider/search_signin.go), `runSearch` in `host.js`, `RunSearchAs` in `search.go` | -Constraints: the plugin runs with the user's rights and sees the key and the (masked) query, as a built-in's vendor does. A backup or sync that restores search APIs on a computer without the plugin drops the plugin's entry there (`RestoreSearchAPIs` keeps only vendors it knows). The vendor list is read from the last load's note, so a plugin just added is listed after the host has loaded it. Tests: `TestPluginSearch` (host, `testdata/search`), `TestPluginSearchAPI` and `TestPluginSearchAPISeesMaskedQuery` (gateway). +Constraints: the plugin runs with the user's rights and sees the key and the (masked) query, as a built-in's vendor does. A backup or sync that restores search APIs on a computer without the plugin drops the plugin's entry there (`RestoreSearchAPIs` keeps only vendors it knows). The vendor list is read from the last load's note, so a plugin just added is listed after the host has loaded it. Tests: `TestPluginSearch` (host, `testdata/search`), `TestPluginSearchSignsIn` (host, `testdata/searchauth`: the chosen account's sign-in only, renewed when due within the timeout, an unknown or other provider's account refused, unbound entries unchanged), `TestPluginSearchAPI`, `TestPluginSearchAPISeesMaskedQuery` and `TestPluginSearchSignsIn` (gateway: signed out falls through to the next API, accounts off are skipped, a 429 rests the account for search and not for models), and `search-signs-in.test.cjs` (GUI). diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 8ccb59310..c851ed08e 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -92,6 +92,10 @@ A plugin can say how busy each model is (axelburks on Discord: an in-house vendo The provider editor shows it by the model as a grey badge (`/api/providers`' `models[].load`, `loadTag` in app.js). Routing reads it only when the user sets *Busy models last* (`settings.BusyLoad`, `POST /api/settings/busy-load {at}`, off by default): see `restLast` and `busyBehind` in [gateway routing](gateway-routing.md). +## A search API that uses a plugin's sign-in + +A plugin's `search` entry can name one of its own sign-ins with `auth: ""` (axelburks on Discord: a search plugin reusing a vendor's sign-in had to read plugin-auth.json itself). The provider is one the plugin's `auth` hook signs in to, with models or an auth hook with none. magpie then manages the accounts as it does for that provider's models: it asks the accounts that are on, in the order its model requests take them (a search-rested one last), and the hook's `ctx.getAuth()` returns a copy of the one account chosen, renewed first under `fresh` (the shared de-dup), with the wait counted within the search's time. An account signed out while it is renewed stays signed out, and the search does not go out as it. The hook runs in `inScope`, so a token it saves with `client.auth.set` goes to the account it searched as. A refusal rests that account for search only; the provider's model routing never sees it. Not signed in, or none on, is an error in the request log and in the row in Settings, and the next search API is asked. A plugin with several providers adds an entry per provider. An entry with no `auth`, or one naming a provider the plugin doesn't sign in to, is a keyed search API as before. The search side is in [plugin tools](plugin-tools.md) ("Sign in"); `TestPluginSearchSignsIn` covers it in [`search_test.go`](../../internal/plugin/search_test.go) and [`search_signin_test.go`](../../internal/gateway/search_signin_test.go). + ## A plugin whose upstream searches A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, say) can say its upstream answers a web search tool by itself (#2027). Its `config` hook sets `searches: true` on the provider; the host passes it through (`plugin.Provider.Searches`), and [`pluginProvider`](../../internal/provider/plugins.go) sets the provider's `Searches`, as a custom provider's "Searches the web by itself" does (#359). [`searchesItself`](../../internal/gateway/search.go) honours it for a plugin's provider only, on Anthropic's or Responses' API, and only for one the plugin has a model on: a client's `web_search` then goes to the plugin's `fetch` as sent, not through magpie's search. Another sign-in's `Searches` is never read, and Codex's and Grok's stay as they were. As with a relay, `searchRank` leaves it out, so magpie never picks it to search for other models; Settings can name it by hand (`namedSearcherRank`). diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index bb038a17e..c14ba4af4 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -335,6 +335,36 @@ func keepAtOnce(n int, out, aside []candidate) ([]candidate, []candidate) { return keptOf(out, 0), append(keptOf(aside, len(out)), reserves...) } +// accountsOn are the accounts of p (signed in: p.Account) a request may +// take, in the user's order: the one signed in to, unless the user paused +// it for the others on (#263), then the others on; kept signed in to an +// account of the user's choosing, the one signed in to stands at its own +// place in the order, not first (#524). A search API that signs in as a +// plugin's provider takes its accounts so too (search_signin.go). +func accountsOn(p provider.Provider, model string) []candidate { + also := p.AlsoOn() + var all []candidate + if len(also) == 0 || !p.OwnPaused() { + all = append(all, candidate{p: p, model: model, rest: p.ID}) + } + for i, q := range also { + all = append(all, candidate{p: q, model: model, rest: p.ID + "@" + q.Account.User, rank: i + 1}) + } + if ranks := p.LoginRanks(); ranks != nil { + at := func(c candidate) int { + if r, ok := ranks[strings.ToLower(c.p.Account.User)]; ok { + return r + } + return len(ranks) + } + slices.SortStableFunc(all, func(a, b candidate) int { return at(a) - at(b) }) + for i := range all { + all[i].rank = i + } + } + return all +} + // perKeyEvery is perKeyBarred with every account or key routed over, the // provider's AtOnce aside. func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out, aside, left, barred []candidate) { @@ -342,31 +372,7 @@ func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out return nil, nil, nil, nil // the user disabled it (#1867): never planned, a fallback no more than the model asked } if p.Account != nil { - also := p.AlsoOn() - var all []candidate - // the account the agent is signed in to, unless the user paused - // it for the others on (#263) - if len(also) == 0 || !p.OwnPaused() { - all = append(all, candidate{p: p, model: model, rest: p.ID}) - } - for i, q := range also { - all = append(all, candidate{p: q, model: model, rest: p.ID + "@" + q.Account.User, rank: i + 1}) - } - // kept signed in to an account of the user's choosing, the one - // signed in to stands at its own place in the order, not first - // (#524) - if ranks := p.LoginRanks(); ranks != nil { - at := func(c candidate) int { - if r, ok := ranks[strings.ToLower(c.p.Account.User)]; ok { - return r - } - return len(ranks) - } - slices.SortStableFunc(all, func(a, b candidate) int { return at(a) - at(b) }) - for i := range all { - all[i].rank = i - } - } + all := accountsOn(p, model) all = slices.DeleteFunc(all, func(c candidate) bool { if p.AccountServes(c.p.Account.User, model) { return false diff --git a/internal/gateway/search_api.go b/internal/gateway/search_api.go index 599c6c829..df3f37254 100644 --- a/internal/gateway/search_api.go +++ b/internal/gateway/search_api.go @@ -137,6 +137,9 @@ func (s *Server) apiSearch(ctx context.Context, query string) (string, []Hit, er // turned away; #1477), which then rests (searchRestFor). Anything else, such as // no answer in time, isn't about the key, and the next isn't tried. func (s *Server) askSearchAPIKeys(ctx context.Context, a provider.SearchAPI, query string) ([]foundPage, error) { + if v, ok := provider.SearchVendorOf(a.Vendor); ok && v.Plugin != "" && v.Auth != "" { + return s.askSearchSignedIn(ctx, a, v, query) + } keys := a.Keys() if len(keys) == 0 { keys = []string{""} @@ -441,6 +444,12 @@ func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v pr } return nil, err } + return pluginPages(got), nil +} + +// pluginPages are the pages a plugin's search found, cut and cleaned as a +// built-in's are. +func pluginPages(got []plugin.SearchPage) []foundPage { var pages []foundPage for _, r := range got { if r.URL == "" { @@ -455,7 +464,7 @@ func (s *Server) askPluginSearch(ctx context.Context, a provider.SearchAPI, v pr break } } - return pages, nil + return pages } // readSearchAPI reads the pages out of a search API's reply. diff --git a/internal/gateway/search_signin.go b/internal/gateway/search_signin.go new file mode 100644 index 000000000..e884c6a41 --- /dev/null +++ b/internal/gateway/search_signin.go @@ -0,0 +1,105 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// A plugin's search API may sign in as the same plugin's provider +// (provider.SearchVendor.Auth) rather than take a key: a search is then +// one of that provider's accounts, those on in the order its requests take +// them (accountsOn), each asked as a key is (askSearchAPIKeys). An account +// the API refuses (429, out of credit, turned away) rests for search alone +// (restSearchKey, by the account's id, never its token): the provider's +// own rests, which its models' requests read, are never touched, so a +// search's rate limit leaves the account's models as they were. + +// runPluginSearchAs asks a plugin's search API as one account in the host +// (a test's has no host). +var runPluginSearchAs = plugin.RunSearchAs + +// searchAccountID is how an account is known among a search API's rests: +// beside its keys, by its key in the plugin host's sign-ins. +func searchAccountID(p provider.Provider) string { return "account " + p.PluginAccountKey() } + +func (s *Server) askSearchSignedIn(ctx context.Context, a provider.SearchAPI, v provider.SearchVendor, query string) ([]foundPage, error) { + name, p := provider.SearchSignIn(v) + var cs []candidate + if p != nil { + cs = accountsOn(*p, "") + } + if len(cs) == 0 { + err := fmt.Errorf("not signed in to %s: sign in to it on Providers", name) + if p != nil { + err = fmt.Errorf("no account of %s is on", name) + } + logSearch(ctx, usage.Record{Requested: a.Name()}, query, time.Now(), 0, err) + return nil, err + } + ids := make([]string, len(cs)) + for i, c := range cs { + ids[i] = searchAccountID(c.p) + } + // the accounts in the provider's own order, one refused lately last + inOrder := provider.SearchAPI{Vendor: a.Vendor, Pick: provider.SearchPickOrder} + var errs []error + for _, i := range searchKeyOrder(inOrder, ids, time.Now()) { + q := cs[i].p + ctx, cancel := context.WithTimeout(q.Via(ctx), searchTimeout/4) + start := time.Now() + pages, err := s.askPluginSearchAs(ctx, v, q, query) + cancel() + rec := usage.Record{Requested: a.Name(), ProviderKeyID: searchKeyID(a.Vendor, ids[i]), ProviderKeyName: q.Account.User} + logSearch(ctx, rec, query, start, len(pages), err) + if err == nil { + wakeSearchKey(a.Vendor, ids[i]) + return pages, nil + } + var r searchRefused + refused := errors.As(err, &r) + if refused { + d, why := searchRestFor(a.Vendor, r.status, r.retryAfter, time.Now()) + restSearchKey(a.Vendor, ids[i], d, why, time.Now()) + } + if len(cs) > 1 { + err = fmt.Errorf("account %s: %w", q.Account.User, err) + } + errs = append(errs, err) + // signed out since it was listed: the next account may still be in + if !refused && !strings.Contains(err.Error(), "not signed in") { + break + } + } + return nil, errors.Join(errs...) +} + +// SearchAccountsOn is how many of p's accounts a search that signs in as +// it may take (accountsOn), for the GUI's row. +func SearchAccountsOn(p provider.Provider) int { return len(accountsOn(p, "")) } + +// askPluginSearchAs is askPluginSearch as one account of the provider the +// API signs in to. +func (s *Server) askPluginSearchAs(ctx context.Context, v provider.SearchVendor, p provider.Provider, query string) ([]foundPage, error) { + got, err := runPluginSearchAs(ctx, v.Plugin, v.PluginID, query, searchHits, p.PluginAccountKey()) + if err != nil { + var r plugin.SearchRefused + if errors.As(err, &r) { + if keyRefusal(r.Status) { + return nil, searchRefused{r.Status, r.Msg, r.RetryAfter} + } + return nil, errors.New(r.Msg) + } + if ctx.Err() != nil { + return nil, errors.New("no answer in time") + } + return nil, err + } + return pluginPages(got), nil +} diff --git a/internal/gateway/search_signin_test.go b/internal/gateway/search_signin_test.go new file mode 100644 index 000000000..bfdd6637f --- /dev/null +++ b/internal/gateway/search_signin_test.go @@ -0,0 +1,150 @@ +package gateway + +import ( + "context" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// A plugin's search API that signs in as the plugin's own provider +// (../plugin/testdata/searchauth, axelburks on Discord), end to end +// through the plugin host: saved with no key; while the provider isn't +// signed in, a search says so and the next search API answers; signed +// in, each search is one account that is on, in the provider's order, the +// hook seeing that account alone; an account the API rate limits rests +// for search only, the next account answering, and the provider's own +// rests (which its models' requests read) are untouched; and the plugin's +// entry without auth still takes its key as before. +func TestPluginSearchSignsIn(t *testing.T) { + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/searchauth") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + vendor := func(id string) provider.SearchVendor { + t.Helper() + for _, v := range provider.AllSearchVendors() { + if v.Plugin == abs && v.PluginID == id { + return v + } + } + t.Fatalf("no vendor %s in %+v", id, provider.AllSearchVendors()) + return provider.SearchVendor{} + } + seek, keyed := vendor("seek"), vendor("keyed") + if seek.Auth != "seekco" || keyed.Auth != "" { + t.Fatalf("seek %+v keyed %+v", seek, keyed) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: seek.ID}); err != nil { + t.Fatalf("a search API that signs in, saved with no key: %v", err) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: keyed.ID}); err == nil || !strings.Contains(err.Error(), "needs its API key") { + t.Errorf("a key's search API with no key: %v", err) + } + if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: keyed.ID, Key: "k9"}); err != nil { + t.Fatal(err) + } + if as := provider.SearchAPIs(); len(as) != 2 || as[0].Vendor != seek.ID { + t.Fatalf("search APIs %+v", as) + } + + s := New() + // not signed in: said, and the next API answers + if _, p := provider.SearchSignIn(seek); p != nil { + t.Fatalf("signed in with no account: %+v", p) + } + said, hits, err := s.apiSearch(ctx, "go") + if err != nil || len(hits) != 1 || hits[0].Title != "k9 undefined" { + t.Fatalf("signed out: %q %+v %v", said, hits, err) + } + if _, err := s.askSearchAPIKeys(ctx, provider.SearchAPI{Vendor: seek.ID}, "go"); err == nil || !strings.Contains(err.Error(), "not signed in to seekco") { + t.Errorf("signed out, the error: %v", err) + } + + later := time.Now().Add(time.Hour).UnixMilli() + for _, who := range []string{"a@seek", "b@seek", "c@seek"} { + access := "acc-" + who[:1] + if who == "a@seek" { + access = "spent" // the search API rate limits it + } + if _, err := plugin.Import(ctx, "seekco", map[string]any{"type": "oauth", "access": access, "refresh": "r-" + who, "expires": later, "accountId": who}); err != nil { + t.Fatal(err) + } + } + // c signed in but switched off + if err := provider.SetLoginOn("plugin:seekco", "c@seek", false); err != nil { + t.Fatal(err) + } + name, p := provider.SearchSignIn(seek) + if p == nil || name == "" { + t.Fatalf("signed in, no provider: %q", name) + } + cs := accountsOn(*p, "") + var users []string + for _, c := range cs { + users = append(users, c.p.Account.User) + } + if strings.Join(users, " ") != "a@seek b@seek" { + t.Fatalf("accounts on: %v", users) + } + + said, hits, err = s.apiSearch(ctx, "go") + if err != nil || len(hits) != 1 || hits[0].Title != "b@seek acc-b" { + t.Fatalf("signed in: %q %+v %v", said, hits, err) + } + // the rate limit rested a for search alone + if r, ok := searchKeyRest(seek.ID, searchAccountID(cs[0].p), time.Now()); !ok || r.Why != "rate limited" { + t.Errorf("a's search rest: %+v %v", r, ok) + } + if _, ok := searchKeyRest(seek.ID, searchAccountID(cs[1].p), time.Now()); ok { + t.Error("b rests, having answered") + } + for _, c := range accountsOn(*p, "") { + if r, resting := restingOf(c); resting { + t.Errorf("a search's rate limit rested %s for its models: %+v", c.p.Account.User, r) + } + } + // the next search starts from b, a resting + if _, hits, err := s.apiSearch(ctx, "go"); err != nil || len(hits) != 1 || hits[0].Title != "b@seek acc-b" { + t.Fatalf("after a's rest: %+v %v", hits, err) + } + rows, _ := searchRows(t) + n429 := 0 + for _, r := range rows { + if r.Status == 429 { + n429++ + if r.ProviderKeyName != "a@seek" { + t.Errorf("the refusal's row names %q", r.ProviderKeyName) + } + } + if strings.Contains(r.ProviderKeyName, "spent") || strings.Contains(r.ProviderKeyID, "seekco") { + t.Errorf("a row shows the account's token or key: %+v", r) + } + } + if n429 != 1 { + t.Errorf("%d refusals logged: %+v", n429, rows) + } + + // every account rate limited: the error says so, and the next API answers + if err := provider.SetLoginOn("plugin:seekco", "b@seek", false); err != nil { + t.Fatal(err) + } + forgetSearchKeys() + if _, hits, err := s.apiSearch(ctx, "go"); err != nil || len(hits) != 1 || hits[0].Title != "k9 undefined" { + t.Fatalf("a alone, rate limited: %+v %v", hits, err) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 6df49e571..622e880d9 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -611,6 +611,17 @@ type searchVendorJSON struct { KeyOptional bool `json:"keyOptional,omitempty"` // its own address, the one used while no base URL is set (#1580) Base string `json:"base,omitempty"` + // Auth: a plugin's API that signs in as the plugin's provider, taking + // no key (provider.SearchVendor.Auth) + Auth *searchAuthJSON `json:"auth,omitempty"` +} + +// searchAuthJSON is the provider a search API signs in as: its name, and +// how many of its accounts are on (0 with none signed in). +type searchAuthJSON struct { + Name string `json:"name"` + SignedIn bool `json:"signedIn"` + On int `json:"on"` } func searchState(s *settingsJSON) { @@ -627,7 +638,16 @@ func searchState(s *settingsJSON) { s.SearchAPIs = append(s.SearchAPIs, j) } for _, v := range provider.AllSearchVendors() { - s.SearchVendors = append(s.SearchVendors, searchVendorJSON{ID: v.ID, Name: v.Name, KeysURL: v.KeysURL, NeedURL: v.WantsURL(), KeyOptional: v.KeyOptional, Base: v.Base}) + j := searchVendorJSON{ID: v.ID, Name: v.Name, KeysURL: v.KeysURL, NeedURL: v.WantsURL(), KeyOptional: v.KeyOptional, Base: v.Base} + if v.Auth != "" { + name, p := provider.SearchSignIn(v) + j.Auth = &searchAuthJSON{Name: name} + if p != nil { + j.Auth.SignedIn = true + j.Auth.On = gateway.SearchAccountsOn(*p) + } + } + s.SearchVendors = append(s.SearchVendors, j) } s.SearchProvider = gateway.Searcher() s.SearchAuto, s.SearchUnused = gateway.AutoSearcher(), gateway.SearcherUnused() diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 5aa2c88b6..b21d3c0bc 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3859,6 +3859,8 @@ input.words.compact-num { flex: none; width: 76px; font-variant-numeric: tabular input.words.rule-kind { flex: none; width: 110px; } input.words.gateway-port { flex: none; width: 110px; font-variant-numeric: tabular-nums; }input.words.rule-match { flex: 1 1 auto; width: auto; min-width: 0; } input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; min-width: 0; } +/* a search API that signs in as a plugin's provider, in the key's place */ +.search-signs { flex: 1 1 120px; min-width: 0; font-size: 12px; color: var(--fg-2); overflow-wrap: anywhere; } /* a search API's base URL (#1580): on a line of its own under the key */ .prefs .row.search-add .val.rule-add { flex-wrap: wrap; row-gap: 6px; } .prefs .row.search-add input.words.search-url { flex: 1 1 100%; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 0052fc5a2..6333d062c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1505,6 +1505,10 @@ const I18N = { "What the key has used of its limit": "该密钥已用了多少额度", "your own": "自建", "needs its key": "缺少密钥", + "Signs in with {name}": "以 {name} 登录", + "Not signed in to {name}: sign in to it on Providers": "未登录 {name}:请在“供应商”中登录", + "No account of {name} is on": "{name} 没有开启的账号", + "Signed in to {name} · accounts on: {n}": "已登录 {name} · 开启的账号:{n}", "{name} added back": "已加回 {name}", "its accounts and model picks as they were": "账号和选好的模型都照旧", "Sign out…": "退出登录…", @@ -6092,6 +6096,10 @@ const I18N = { "What the key has used of its limit": "該金鑰已用了多少額度", "your own": "自建", "needs its key": "缺少金鑰", + "Signs in with {name}": "以 {name} 登入", + "Not signed in to {name}: sign in to it on Providers": "未登入 {name}:請在「供應商」中登入", + "No account of {name} is on": "{name} 沒有開啟的帳號", + "Signed in to {name} · accounts on: {n}": "已登入 {name} · 開啟的帳號:{n}", "{name} added back": "已加回 {name}", "its accounts and model picks as they were": "帳號和選好的模型都照舊", "Sign out…": "退出登入…", @@ -10649,6 +10657,10 @@ const I18N = { "What the key has used of its limit": "このキーが上限のうちどれだけ使ったか", "your own": "独自", "needs its key": "キーが必要", + "Signs in with {name}": "{name} でサインイン", + "Not signed in to {name}: sign in to it on Providers": "{name} にサインインしていません:「プロバイダ」でサインインしてください", + "No account of {name} is on": "{name} のオンのアカウントがありません", + "Signed in to {name} · accounts on: {n}": "{name} にサインイン済み · オンのアカウント:{n}", "{name} added back": "{name} を再追加しました", "its accounts and model picks as they were": "アカウントと選んだモデルは以前のままです", "Sign out…": "サインアウト…", @@ -15237,6 +15249,10 @@ const I18N = { "What the key has used of its limit": "Was der Schlüssel von seinem Limit verbraucht hat", "your own": "eigener", "needs its key": "Schlüssel fehlt", + "Signs in with {name}": "Meldet sich mit {name} an", + "Not signed in to {name}: sign in to it on Providers": "Nicht bei {name} angemeldet: unter Anbieter anmelden", + "No account of {name} is on": "Kein Konto von {name} ist an", + "Signed in to {name} · accounts on: {n}": "Bei {name} angemeldet · Konten an: {n}", "{name} added back": "{name} wieder hinzugefügt", "its accounts and model picks as they were": "Konten und Modellauswahl wie zuvor", "Sign out…": "Abmelden…", diff --git a/internal/gui/assets/plugins/search/settings.js b/internal/gui/assets/plugins/search/settings.js index 6f4b03234..68f60e830 100644 --- a/internal/gui/assets/plugins/search/settings.js +++ b/internal/gui/assets/plugins/search/settings.js @@ -50,6 +50,9 @@ function renderSearch(s, keep) { key.setAttribute("aria-label", t("API key")); const get = el("button", "link", t("Get a key ↗")); get.onclick = () => vendor().keysURL && api("open", { url: vendor().keysURL }); + // a plugin's API that signs in as the plugin's provider takes no key: its + // accounts are the provider's, on Providers + const signs = el("span", "search-signs"); const draw = () => { const v = vendor(); pick.replaceChildren(el("span", "", v.name || ""), svg(CHEV, 11, 1.6)); @@ -63,7 +66,10 @@ function renderSearch(s, keep) { : saved()?.key ? t("A new key, or empty to keep {key}", { key: saved().key }) : v.keyOptional ? t("API key, or empty for its free search") : t("API key, or several split by commas"); - get.hidden = !v.keysURL; + get.hidden = !v.keysURL || !!v.auth; + key.hidden = !!v.auth; + signs.hidden = !v.auth; + signs.textContent = v.auth ? t("Signs in with {name}", { name: v.auth.name }) : ""; }; pick.onclick = (e) => { e.stopPropagation(); @@ -76,7 +82,7 @@ function renderSearch(s, keep) { d.key = key.value.trim(); d.url = url.value.trim(); // one added before keeps its key when none is typed // You.com is asked at its free search with none (#1626) - if (vendor().needURL ? !d.url : !d.key && !saved()?.key && !vendor().keyOptional) return (vendor().needURL ? url : key).focus(); + if (vendor().needURL ? !d.url : !d.key && !saved()?.key && !vendor().keyOptional && !vendor().auth) return (vendor().needURL ? url : key).focus(); set({ vendor: d.vendor, key: d.key, url: d.url }, () => { searchDraft = { vendor: d.vendor, key: "", url: "", err: "" }; }); }; @@ -93,7 +99,7 @@ function renderSearch(s, keep) { : apiFirst ? t("Asked before {who}, which searches when these fail", { who: s.searchProvider }) : t("Now done by {who}; these come after it", { who: s.searchProvider }); const head = row(t("Search APIs"), d.err || t("When a model can't search the web, magpie searches for it with these, in this order, and gives it what they found") + " · " + by, - pick, key, get, add, url); + pick, key, signs, get, add, url); head.classList.add("rule-row", "search-add"); head.querySelector(".val").classList.add("rule-add"); if (d.err) head.querySelector(".sub").classList.add("err"); @@ -106,7 +112,13 @@ function renderSearch(s, keep) { units.push(unit); const x = el("button", "text", t("Remove")); x.onclick = () => set({ vendor: a.vendor, remove: true }); - const what = [a.key || (a.ready ? "" : t("needs its key")), a.url].filter(Boolean).join(" · "); + // one that signs in says whose accounts it uses, or why it has none + const auth = vendors.find((v) => v.id === a.vendor)?.auth; + const signedIn = !auth ? "" + : !auth.signedIn ? t("Not signed in to {name}: sign in to it on Providers", { name: auth.name }) + : !auth.on ? t("No account of {name} is on", { name: auth.name }) + : t("Signed in to {name} · accounts on: {n}", { name: auth.name, n: auth.on }); + const what = [signedIn || a.key || (a.ready ? "" : t("needs its key")), a.url].filter(Boolean).join(" · "); const tools = [x]; if (a.key) { // its saved key shown in its row and hidden again, as a provider's @@ -146,6 +158,7 @@ function renderSearch(s, keep) { tools.push(sw); const r = row(`${n + 1}. ${a.name}`, a.off ? [t("Off"), what].filter(Boolean).join(" · ") : what, ...tools); r.classList.add("search-api"); + if (auth && !a.off && !(auth.signedIn && auth.on)) r.querySelector(".sub").classList.add("err"); // with-keys, not :has(), which Safari before 15.4 can't parse if (a.keys > 1 || a.quota) { unit.classList.add("with-keys"); searchKeysRow(s, a, row, set); } into = box; diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index fbbaca50c..a6e6ccf77 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -2045,6 +2045,13 @@ and what was typed kept, and Remove posts `{vendor, remove: true}`. No click moves the page. English and Chinese, Chromium and WebKit, with `/api/plugins` faked. +`search-signs-in.test.cjs` checks a plugin's search API that signs in as the +plugin's provider (axelburks on Discord): the add row says "Signs in with +{provider}" where the key field and Get a key were, Add posts it with no key, +and each added one's row says how many of the provider's accounts are on, or, +as an error, that none is signed in or none is on. All five languages, 980px +and 420px, Chromium and WebKit, the API faked. + `searcher-pick.test.cjs` checks the Web search section's "Searches for other models" row (01huadalang on Discord: pick which provider searches for a model that can't). With none named it shows Automatic and magpie's own pick; its diff --git a/internal/gui/tests/search-signs-in.test.cjs b/internal/gui/tests/search-signs-in.test.cjs new file mode 100644 index 000000000..53c5f066e --- /dev/null +++ b/internal/gui/tests/search-signs-in.test.cjs @@ -0,0 +1,103 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin's search API that signs in as the plugin's provider (axelburks on +// Discord) takes no key: Settings' add row says whose sign-in it uses in +// place of the key field, Add sends it with none, and each added one's row +// says how many of the provider's accounts are on, or, as an error, that +// none is signed in or none is on. In all five languages, Chromium and +// WebKit, 980px and 420px wide, with the API faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const vendors = [ + { id: "seek-web", name: "Seek", auth: { name: "SeekCo", signedIn: true, on: 2 } }, + { id: "out-web", name: "Out", auth: { name: "OutCo", signedIn: false, on: 0 } }, + { id: "none-web", name: "None On", auth: { name: "NoneCo", signedIn: true, on: 0 } }, +]; +const words = { + en: { add: "Add", signs: "Signs in with SeekCo", on: "Signed in to SeekCo · accounts on: 2", out: "Not signed in to OutCo: sign in to it on Providers", none: "No account of NoneCo is on" }, + zh: { add: "添加", signs: "以 SeekCo 登录", on: "已登录 SeekCo · 开启的账号:2", out: "未登录 OutCo:请在“供应商”中登录", none: "NoneCo 没有开启的账号" }, + "zh-TW": { add: "新增", signs: "以 SeekCo 登入", on: "已登入 SeekCo · 開啟的帳號:2", out: "未登入 OutCo:請在「供應商」中登入", none: "NoneCo 沒有開啟的帳號" }, + ja: { add: "追加", signs: "SeekCo でサインイン", on: "SeekCo にサインイン済み · オンのアカウント:2", out: "OutCo にサインインしていません:「プロバイダ」でサインインしてください", none: "NoneCo のオンのアカウントがありません" }, + de: { add: "Hinzufügen", signs: "Meldet sich mit SeekCo an", on: "Bei SeekCo angemeldet · Konten an: 2", out: "Nicht bei OutCo angemeldet: unter Anbieter anmelden", none: "Kein Konto von NoneCo ist an" }, +}; + +function serve(lang, posted) { + let apis = [ + { vendor: "out-web", name: "Out", ready: true }, + { vendor: "none-web", name: "None On", ready: true }, + ]; + const settings = () => ({ lang, theme: "light", searchVendors: vendors, searchAPIs: apis }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data, status = 200) => r.fulfill({ status, json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/settings/search-api") { + const b = JSON.parse(r.request().postData()); + posted.push(b); + apis = [...apis, { vendor: b.vendor, name: vendors.find((v) => v.id === b.vendor).name, ready: true }]; + return json(settings()); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) for (const width of [980, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: a search API that signs in shows its sign-in, not a key`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 1400 } })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posted = []; + await page.route("**/*", serve(lang, posted)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=models"); + await settingsDrawn(page); + const list = page.locator("#searchList"); + const head = list.locator(".row.search-add"); + await head.waitFor(); + + // the first vendor is picked: Seek, which signs in as SeekCo + assert.equal(await head.locator("button.search-vendor").innerText(), "Seek"); + assert.equal(await head.locator("input.search-key").isVisible(), false, "no key field"); + assert.equal(await head.locator("button.link").isVisible(), false, "no Get a key"); + assert.equal(await head.locator(".search-signs").isVisible(), true); + assert.equal(await head.locator(".search-signs").innerText(), w.signs); + + // the stored ones: not signed in, and none on, are errors + const rows = list.locator(".row.search-api"); + assert.equal(await rows.nth(0).locator(".sub").innerText(), w.out); + assert.equal(await rows.nth(0).locator(".sub").evaluate((e) => e.classList.contains("err")), true); + assert.equal(await rows.nth(1).locator(".sub").innerText(), w.none); + assert.equal(await rows.nth(1).locator(".sub").evaluate((e) => e.classList.contains("err")), true); + assert.equal(await rows.nth(0).locator("button.search-eye").count(), 0, "nothing to show"); + + // Add sends it with no key, and its row says how many accounts are on + await head.locator("button.text", { hasText: w.add }).evaluate((b) => b.click()); + await page.waitForFunction(() => document.querySelectorAll("#searchList .row.search-api").length === 3); + assert.deepEqual(posted, [{ vendor: "seek-web", key: "", url: "" }]); + assert.equal(await rows.nth(2).locator(".sub").innerText(), w.on); + assert.equal(await rows.nth(2).locator(".sub").evaluate((e) => e.classList.contains("err")), false); + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 1f54881f2..d8bc25a76 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1744,6 +1744,14 @@ async function runTool({ spec, name, args, ms, agent }) { // status (401, 402, 403, 429…) is the API refusing the key, which magpie // rests as it does a built-in's; retryAfter is its Retry-After. // magpie keeps the keys, order and limits, and masks the query before it. +// +// An entry may name auth: "", one this plugin's auth hook +// signs in to (a model provider, or an auth hook with no models of its +// own). It then takes no key: magpie tries the provider's accounts that +// are on, in their order, one per call, and the hook reads the one chosen +// through ctx.getAuth(), renewed first if due (the wait counts within the +// search's time). A refusal rests the account for search only, never for +// its models. const SEARCH_ID = /^[a-z0-9][a-z0-9-]{0,31}$/ @@ -1769,22 +1777,48 @@ function searchList(spec) { ...(typeof def.keysURL === "string" && /^https?:\/\//.test(def.keysURL) ? { keysURL: def.keysURL } : {}), ...(def.keyOptional === true ? { keyOptional: true } : {}), ...(def.url === true ? { needURL: true } : {}), + ...(searchAuthOf(spec, def) ? { auth: def.auth } : {}), }) } return out } -async function runSearch({ spec, id, query, count, key, url, ms }) { +// searchAuthOf is the provider a search entry signs in as: one the same +// plugin's auth hooks name, "" for none (an id it doesn't sign in to is +// none, so the entry stays a key's). +function searchAuthOf(spec, def) { + return typeof def.auth === "string" && def.auth && signsIn(spec).includes(def.auth) ? def.auth : "" +} + +async function runSearch({ spec, id, query, count, key, url, ms, account, proxy }) { const def = searchesOf(spec).get(id) if (!def) throw new Error(`${spec} has no search API ${id}`) const abort = AbortSignal.timeout(ms > 0 ? ms : 60_000) + const late = new Promise((_, reject) => abort.addEventListener("abort", () => reject(new Error("no answer in time")), { once: true })) + late.catch(() => {}) const ctx = { directory, worktree: directory, abort } + const provider = searchAuthOf(spec, def) + let run = () => def.execute({ query, count, key: key ?? "", url: url ?? "" }, ctx) + if (provider) { + // the account magpie chose, and that one only: never the provider's + // first in its place, nor one of another provider + if (auths().get(provider)?.spec !== spec) throw new Error(`another plugin signs in to ${provider}`) + const k = typeof account === "string" && account && providerOf(account) === provider ? account : "" + if (!k || !(k in readAuth())) throw new Error(`not signed in to ${provider}`) + ctx.getAuth = async () => authCopy(k) + const execute = run + run = () => + via.run(proxy ?? "", () => + inScope(provider, k, async () => { + await Promise.race([fresh(provider, k), late]) + if (!(k in readAuth())) throw new Error(`not signed in to ${provider}`) + return execute() + }), + ) + } let out try { - out = await Promise.race([ - Promise.resolve().then(() => def.execute({ query, count, key: key ?? "", url: url ?? "" }, ctx)), - new Promise((_, reject) => abort.addEventListener("abort", () => reject(new Error("no answer in time")), { once: true })), - ]) + out = await Promise.race([Promise.resolve().then(run), late]) } catch (e) { const status = Number(e?.status) if (Number.isInteger(status) && status >= 300 && status < 600) { diff --git a/internal/plugin/search.go b/internal/plugin/search.go index 857ecb84a..183abb48e 100644 --- a/internal/plugin/search.go +++ b/internal/plugin/search.go @@ -30,6 +30,10 @@ type SearchDef struct { // NeedURL: the user gives an address (a SearXNG's), passed to the // plugin as url NeedURL bool `json:"needURL,omitempty"` + // Auth is the provider id the API signs in as, one the same plugin's + // auth hook signs in to: it takes no key, and each call is one of that + // provider's accounts (RunSearchAs) + Auth string `json:"auth,omitempty"` } // PluginSearch is a search API with the plugin that gives it. @@ -76,6 +80,22 @@ const searchSlack = 5 * time.Second // time ctx has (60s with none), starting the host if need be. A refusal of // the key is a SearchRefused. func RunSearch(ctx context.Context, spec, id, query string, count int, key, url string) ([]SearchPage, error) { + return runSearch(ctx, map[string]any{"spec": spec, "id": id, "query": query, "count": count, "key": key, "url": url}) +} + +// RunSearchAs asks a search API that signs in (SearchDef.Auth) as the +// account at its host key (provider or provider#slot), through the +// account's proxy in ctx. The host renews the sign-in first if due, within +// the time ctx has, and the hook reads that account alone (ctx.getAuth). +// One signed out is an error, never a sign-in to another account. +func RunSearchAs(ctx context.Context, spec, id, query string, count int, account string) ([]SearchPage, error) { + if account == "" { + return nil, errors.New("no account to search as") + } + return runSearch(ctx, map[string]any{"spec": spec, "id": id, "query": query, "count": count, "account": account, "proxy": proxyOf(ctx)}) +} + +func runSearch(ctx context.Context, params map[string]any) ([]SearchPage, error) { ms := int64(60_000) if d, ok := ctx.Deadline(); ok { ms = max(time.Until(d).Milliseconds(), 1) @@ -86,9 +106,8 @@ func RunSearch(ctx context.Context, spec, id, query string, count int, key, url Error string `json:"error"` RetryAfter string `json:"retryAfter"` } - err := callWithTimeout(ctx, "search", map[string]any{ - "spec": spec, "id": id, "query": query, "count": count, "key": key, "url": url, "ms": ms, - }, &out, time.Duration(ms)*time.Millisecond+searchSlack) + params["ms"] = ms + err := callWithTimeout(ctx, "search", params, &out, time.Duration(ms)*time.Millisecond+searchSlack) if err != nil { return nil, err } diff --git a/internal/plugin/search_test.go b/internal/plugin/search_test.go index abc4d2b2c..6dc03aa70 100644 --- a/internal/plugin/search_test.go +++ b/internal/plugin/search_test.go @@ -93,3 +93,149 @@ func TestPluginSearch(t *testing.T) { t.Error("a corrupt note counted as no searches") } } + +// A search entry with auth (testdata/searchauth) signs in as the plugin's +// own provider: it is listed with that provider and no key, an id the +// plugin doesn't sign in to leaves the entry a key's, and one without auth +// is as before (a key, no getAuth). A search runs as the one account Go +// names, ctx.getAuth() giving that account alone, renewed first when due; +// the renewal's wait counts within the search's time; and an account that +// isn't signed in, or is another provider's, is an error, never the +// provider's first account in its place. +func TestPluginSearchSignsIn(t *testing.T) { + sandbox(t) + hold := filepath.Join(t.TempDir(), "hold") + t.Setenv("SEARCHAUTH_HOLD", hold) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/searchauth") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + loaded, err := Plugins(ctx) + if err != nil || len(loaded) != 1 { + t.Fatalf("%v %v", loaded, err) + } + got := map[string]SearchDef{} + for _, d := range loaded[0].Searches { + got[d.ID] = d + } + if got["seek"].Auth != "seekco" || got["stray"].Auth != "" || got["keyed"].Auth != "" || len(got) != 3 { + t.Fatalf("searches = %+v", loaded[0].Searches) + } + if ns, err := NotedSearches(); err != nil || len(ns) != 3 || ns[0].Auth != "seekco" { + t.Fatalf("noted = %+v, %v", ns, err) + } + + later := time.Now().Add(time.Hour).UnixMilli() + soon := time.Now().Add(time.Minute).UnixMilli() + account := func(who, access, refresh string, expires int64) string { + t.Helper() + k, err := Import(ctx, "seekco", map[string]any{"type": "oauth", "access": access, "refresh": refresh, "expires": expires, "accountId": who}) + if err != nil { + t.Fatal(err) + } + return k + } + a := account("a@seek", "acc-a", "r-a", later) + b := account("b@seek", "acc-b", "r-b", later) + due := account("due@seek", "acc-due", "r-due", soon) + slow := account("slow@seek", "acc-slow", "r-slow", soon) + if a == b { + t.Fatalf("two accounts at one key %q", a) + } + + title := func(account string) string { + t.Helper() + pages, err := RunSearchAs(ctx, abs, "seek", "go", 5, account) + if err != nil || len(pages) != 1 { + t.Fatalf("as %s: %+v, %v", account, pages, err) + } + if pages[0].Text != "key= fields=access,accountId,expires,refresh,type" { + t.Errorf("as %s the hook saw %q", account, pages[0].Text) + } + return pages[0].Title + } + if s := title(b); s != "b@seek acc-b" { + t.Errorf("as the second account: %q", s) + } + if s := title(a); s != "a@seek acc-a" { + t.Errorf("as the first account: %q", s) + } + // a token the hook saves (client.auth.set) goes to the account it + // searched as, never the provider's first (inScope) + if _, err := RunSearchAs(ctx, abs, "seek", "rotate", 5, b); err != nil { + t.Fatal(err) + } + if got := Auths("seekco"); got[b]["access"] != "rotated-b@seek" || got[a]["access"] != "acc-a" { + t.Errorf("a token saved while searching as b: a %v, b %v", got[a]["access"], got[b]["access"]) + } + // due: renewed before the search, which sees the new sign-in + if s := title(due); s != "due@seek renewed-r-due" { + t.Errorf("a sign-in due for renewal searched as %q", s) + } + + for _, bad := range []string{"seekco#nobody", "elsewhere", "elsewhere#x"} { + if _, err := RunSearchAs(ctx, abs, "seek", "go", 5, bad); err == nil || !strings.Contains(err.Error(), "not signed in") { + t.Errorf("as %s: %v", bad, err) + } + } + if _, err := RunSearchAs(ctx, abs, "seek", "go", 5, ""); err == nil { + t.Error("a search that signs in ran with no account") + } + + // the renewal (3s) counts within the search's time (1s) + short, stop := context.WithTimeout(ctx, time.Second) + t0 := time.Now() + _, err = RunSearchAs(short, abs, "seek", "go", 5, slow) + stop() + if err == nil || time.Since(t0) > 2500*time.Millisecond { + t.Errorf("a renewal past the search's time: %v after %s", err, time.Since(t0)) + } + + // a refused search is a SearchRefused, as a key's + spent := account("spent@seek", "spent", "r-spent", later) + var r SearchRefused + if _, err := RunSearchAs(ctx, abs, "seek", "go", 5, spent); !errors.As(err, &r) || r.Status != 429 || r.RetryAfter != "60" { + t.Errorf("a refused search: %#v", err) + } + + // signed out while its renewal runs: the search doesn't go out as it, + // and the renewal doesn't sign it in again (renew's own guard, cd83c3147) + gone := account("gone@seek", "acc-gone", "r-hold", soon) + ran := make(chan error, 1) + go func() { + _, err := RunSearchAs(ctx, abs, "seek", "go", 5, gone) + ran <- err + }() + for { + if _, err := os.Stat(hold + ".in"); err == nil { + break + } + select { + case <-ctx.Done(): + t.Fatal("the renewal never began") + case <-time.After(10 * time.Millisecond): + } + } + if err := SignOut(ctx, "seekco", gone); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(hold, nil, 0o600); err != nil { + t.Fatal(err) + } + if err := <-ran; err == nil || !strings.Contains(err.Error(), "not signed in") { + t.Errorf("a search as an account signed out mid-renewal: %v", err) + } + if _, ok := Auths("seekco")[gone]; ok { + t.Error("the renewal signed the account in again") + } + + // entries without auth: a key, as before, and no getAuth + for _, id := range []string{"keyed", "stray"} { + pages, err := RunSearch(ctx, abs, id, "go", 5, "k9", "") + if err != nil || len(pages) != 1 || pages[0].Title != "k9 undefined" { + t.Errorf("%s: %+v, %v", id, pages, err) + } + } +} diff --git a/internal/plugin/testdata/searchauth/index.js b/internal/plugin/testdata/searchauth/index.js new file mode 100644 index 000000000..43106cb5b --- /dev/null +++ b/internal/plugin/testdata/searchauth/index.js @@ -0,0 +1,38 @@ +// A plugin whose web search signs in as its own provider (search entries +// with auth): "seekco" is an auth hook with no models, renewed through +// magpie (auth.refresh: "r-slow…" takes 3 seconds). No network: the +// search answers with what ctx.getAuth() gave it; the query "rotate" saves +// a new token through client.auth.set, as a vendor that rotates it would. +export default async ({ client }) => ({ + auth: { + provider: "seekco", + methods: [{ type: "api", label: "API key" }], + async refresh(auth) { + // "r-hold": says it began (SEARCHAUTH_HOLD.in) and waits for the test + // to let it go (SEARCHAUTH_HOLD) + const hold = process.env.SEARCHAUTH_HOLD + if (hold && auth.refresh.startsWith("r-hold")) { + const fs = await import("node:fs") + fs.writeFileSync(hold + ".in", "") + while (!fs.existsSync(hold)) await new Promise((ok) => setTimeout(ok, 20)) + } + await new Promise((ok) => setTimeout(ok, auth.refresh.startsWith("r-slow") ? 3000 : 100)) + return { access: "renewed-" + auth.refresh, refresh: auth.refresh + "+", expires: Date.now() + 3600e3 } + }, + }, + search: { + seek: { + name: "Seek", + auth: "seekco", + async execute({ query, key }, ctx) { + const a = await ctx.getAuth() + if (query === "rotate") await client.auth.set({ path: { id: "seekco" }, body: { ...a, access: "rotated-" + a.accountId } }) + if (a.access === "spent") throw Object.assign(new Error("Seek: rate limited"), { status: 429, retryAfter: 60 }) + return [{ title: a.accountId + " " + a.access, url: "https://seek.invalid/" + query, text: "key=" + key + " fields=" + Object.keys(a).sort().join(",") }] + }, + }, + // an id the plugin doesn't sign in to: a key's entry, as before + stray: { name: "Stray", auth: "elsewhere", execute: async ({ key }, ctx) => [{ title: key + " " + typeof ctx.getAuth, url: "https://x.invalid/" }] }, + keyed: { name: "Keyed", execute: async ({ key }, ctx) => [{ title: key + " " + typeof ctx.getAuth, url: "https://x.invalid/" }] }, + }, +}) diff --git a/internal/provider/search_api.go b/internal/provider/search_api.go index e151609d2..15f778dbb 100644 --- a/internal/provider/search_api.go +++ b/internal/provider/search_api.go @@ -58,6 +58,10 @@ type SearchVendor struct { Plugin, PluginID string // NeedURL: a plugin's API the user gives an address for, as a SearXNG NeedURL bool + // Auth: a plugin's API that signs in as the same plugin's provider of + // this id (plugin.SearchDef.Auth), taking no key: each search is one + // of that provider's accounts that are on (SearchSignIn) + Auth string } // WantsURL is whether the user must give its address (a SearXNG's, or a @@ -95,7 +99,7 @@ func AllSearchVendors() []SearchVendor { ps, _ := plugin.NotedSearches() for _, p := range ps { out = append(out, SearchVendor{ID: p.VendorID(), Name: p.Name, KeysURL: p.KeysURL, KeyOptional: p.KeyOptional, - Plugin: p.Spec, PluginID: p.ID, NeedURL: p.NeedURL}) + Plugin: p.Spec, PluginID: p.ID, NeedURL: p.NeedURL, Auth: p.Auth}) } return out } @@ -181,10 +185,12 @@ func (a SearchAPI) ownBase() string { } // Ready is whether it can be asked: a vendor magpie knows, at an address, -// with a key where it needs one (a SearXNG, You.com, may not). +// with a key where it needs one (a SearXNG, You.com, may not; one that +// signs in never does: signed out, a search says so and the next API is +// asked). func (a SearchAPI) Ready() bool { v, known := SearchVendorOf(a.Vendor) - return known && (a.Base() != "" || (v.Plugin != "" && !v.NeedURL)) && (a.Key != "" || v.KeyOptional) + return known && (a.Base() != "" || (v.Plugin != "" && !v.NeedURL)) && (a.Key != "" || v.KeyOptional || v.Auth != "") } // check says what is wrong with a search API the user gives. @@ -217,7 +223,7 @@ func (a SearchAPI) check() error { if v.Plugin != "" && v.NeedURL && a.URL == "" { return fmt.Errorf("%s needs its address, as url=https://…", a.Name()) } - if a.Key == "" && !v.KeyOptional { + if a.Key == "" && !v.KeyOptional && v.Auth == "" { return fmt.Errorf("%s needs its API key", a.Name()) } return nil diff --git a/internal/provider/search_signin.go b/internal/provider/search_signin.go new file mode 100644 index 000000000..bd8f20d5b --- /dev/null +++ b/internal/provider/search_signin.go @@ -0,0 +1,44 @@ +package provider + +// A plugin's search API that signs in (SearchVendor.Auth) searches as the +// same plugin's provider: its accounts, as the user switched them on and +// ordered them for the provider's requests. + +// SearchSignIn is what a search API that signs in searches as: the name +// of the provider it signs in to, and that provider as All lists it (its +// first account; AlsoOn the others on), nil while it isn't signed in or +// another plugin serves the id (the user picked another plugin for it). +func SearchSignIn(v SearchVendor) (name string, p *Provider) { + if v.Auth == "" || v.Plugin == "" { + return v.Auth, nil + } + name = v.Auth + found := false + for _, pp := range heldPlugins() { + if pp.ID == v.Auth && pp.Spec == v.Plugin { + found = true + if pp.Name != "" { + name = pp.Name + } + } + } + if !found { + return name, nil + } + id := PluginID(v.Auth) + for _, q := range All() { + if q.ID == id && q.PluginProvider() == v.Auth && q.Account.plugin.Spec == v.Plugin { + return name, &q + } + } + return name, nil +} + +// PluginAccountKey is the account's key in the plugin host's sign-ins +// (provider or provider#slot), "" for a provider not a plugin's. +func (p Provider) PluginAccountKey() string { + if !p.IsPlugin() { + return "" + } + return p.Account.pluginKey +}