search: a search API's keys are a list, each switched off, moved and removed on its own
Web search took one key per API in one field (辰林鸭~ on Discord: only one
Tavily key). Settings › Models › Web search now lists an API's keys under
it as a provider's accounts are: each masked on its own row with a tick
(off / on), Show, Copy and Remove; several pasted at once (commas,
semicolons, lines), the reply saying how many were new and how many it
had; the order changed by dragging or Alt+↑/↓. A resting key says why and
until when on its row ("asked last until 14:05: rate limited"), from the
gateway's rest (SearchKeyRest, SearchQuota.Ref); rotation on 401/403,
402/432/433 and 429 (#1477) is unchanged.
provider.SearchAPI keeps Key as the keys on, comma-joined, so the gateway
and an older magpie never ask one switched off; keyList is written only
while a key is off. A Key that differs from the list (an older magpie, a
sync) wins, its keys on in its order, the list's off keys after. The last
key on can't be switched off or removed. The GUI names a key by
SearchKeyRef (a hash): POST /api/settings/search-keys (add, ref+on,
ref+remove, arrange) and /api/settings/search-key with ref. Saving an API
with no key keeps its keys, off ones too. Backup and WebDAV sync carry
the off keys, or leave them out with the rest. `magpie search` says
"+N off". docs/subsystems/gateway-routing.md has "The keys as a list".
Run (mote, at this tree, base 3441035a2):
- go test -count=1 ./internal/gui ./internal/provider ./internal/backup
./internal/davsync ./internal/cli: ok but gui's
TestPanelHiddenByWailsMarksPageOutOfSight (#5322, mote, untouched) and
cli's TestEveryRouteHasACommandOrIsNamed, then fixed (search-keys named
S2) and run again: ok. ./internal/gateway search tests ok earlier.
- node --test search-key-list, search-keys, search-api, search-signs-in,
search-order: 84/84, Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and
420px (search-api/order at their own widths). i18n-keys: only "a
plugin's words are its own" red, as on main (#5332, #5426, #5482).
- go build ./..., go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: ok. gofmt -l: clean.
Broken by hand, each red then restored:
- SetSearchAPI drops KeyList: provider and gui tests red.
- backup clears Key only / davsync merges Key only: their tests red.
- off keys still put in Key: provider, gui, backup and gateway red.
- the whole key in /api/state: TestSearchKeyListFromSettings red.
- no last-key-on check: TestSearchKeyList red.
- settings.js at HEAD: search-key-list.test.cjs red.
Not tried: a real Tavily account with several keys (the vendor is faked;
no test reaches the network); the real app window (the GUI ran in
Playwright only); Windows and Linux runs of the tests (vet only). The
full Go and GUI suites run after the push, under mote's suite lock.
Reported-by: 辰林鸭~ (Discord)
This commit is contained in:
@@ -1785,15 +1785,45 @@ or a reply missing those fields is unknown, with why, never 0 used. A read
|
||||
is kept two minutes (Tavily allows /usage 10 times in 10 minutes) unless
|
||||
asked fresh. A key at its limit with no pay-as-you-go credit left rests an
|
||||
hour as "used up"; a later read that finds credit wakes a key resting for
|
||||
that or for being out of credit. Settings › Models › Web search shows a row
|
||||
of the keys under an API with several or with Tavily's (In turn / In order,
|
||||
each key masked with what it has used, Check again), and `magpie search`
|
||||
lists the same, read fresh.
|
||||
that or for being out of credit. `magpie search` lists each key's use,
|
||||
read fresh.
|
||||
|
||||
### The keys as a list
|
||||
|
||||
Settings › Models › Web search shows an API's keys as a list under it
|
||||
(辰林鸭~ on Discord), as a provider's accounts are: each key masked on a
|
||||
row of its own with a tick that switches it off or on, Show, Copy and
|
||||
Remove, one or several added at once (split by commas, semicolons or
|
||||
lines; the reply says how many were new and how many it had), and the
|
||||
order changed by dragging or Alt+↑/↓. A key resting says why and until
|
||||
when on its row ("asked last until 14:05: rate limited"), from
|
||||
`SearchKeyRest` and `SearchQuota.Ref`; with Tavily's quota, what it has
|
||||
used is beside it, and In turn / In order and Check again sit on the row.
|
||||
|
||||
The list is `provider.SearchAPI.SearchKeys()`
|
||||
([`search_api.go`](../../internal/provider/search_api.go)). `Key` stays
|
||||
the keys that are on, comma-joined, so the gateway (`a.Keys()`) and an
|
||||
older magpie never ask one switched off; `keyList` is written only while
|
||||
a key is off, and with every key on the file is as before. A `Key` that
|
||||
differs from the list (written by a magpie that knows no list, or synced
|
||||
from one) wins: its keys are on in its order, a key the list had off and
|
||||
it doesn't name stays off after them. The last key on can't be switched
|
||||
off or removed from the list. The GUI names a key by `SearchKeyRef` (a
|
||||
hash), never by its value: `POST /api/settings/search-keys` takes `add`,
|
||||
`ref` with `on` or `remove`, or `arrange`, and `/api/settings/search-key`
|
||||
reads one key by its ref for Show and Copy. Saving an API with no key (a
|
||||
new base URL) keeps its keys, off ones too; a key typed in the API's own
|
||||
field replaces the list, every key on. Backup and sync carry the keys
|
||||
switched off with the rest, or drop them with the rest when keys are left
|
||||
out.
|
||||
|
||||
Covered by `TestReadTavilyUsage`, `TestSearchKeysTakeTurnsRoundRobin`,
|
||||
`TestSearchKeyRefusedRests`, `TestSearchRestFor`, `TestSearchQuotas`,
|
||||
`TestSearchKeyNeverInFull`, `TestSearchAPIKeysTakeTurns` and
|
||||
`search-keys.test.cjs`.
|
||||
`TestSearchKeyNeverInFull`, `TestSearchAPIKeysTakeTurns`,
|
||||
`TestSearchKeyOffAndWhyItRests`, `TestSearchKeyList`,
|
||||
`TestSearchKeysKeyWins`, `TestSearchKeyListFromSettings`,
|
||||
`TestBackupSearchKeysOff`, `TestSyncSearchKeysOff`,
|
||||
`search-keys.test.cjs` and `search-key-list.test.cjs`.
|
||||
|
||||
## A search API's asks in the request log
|
||||
|
||||
|
||||
@@ -219,7 +219,7 @@ func Collect(keys bool, app string) (Bundle, error) {
|
||||
searches := []provider.SearchAPI{}
|
||||
for _, a := range provider.StoredSearchAPIs() {
|
||||
if !keys {
|
||||
a.Key = ""
|
||||
a = a.WithoutKeys() // those switched off too
|
||||
}
|
||||
searches = append(searches, a)
|
||||
}
|
||||
|
||||
@@ -111,3 +111,49 @@ func TestBackupSearchAPIsOrderAndOff(t *testing.T) {
|
||||
t.Fatalf("stored %v, asked %v", stored, asked)
|
||||
}
|
||||
}
|
||||
|
||||
// A key switched off in a search API's list (辰林鸭~ on Discord) goes in a
|
||||
// backup with its keys and comes back off; one without keys carries none
|
||||
// of them, on or off, and the list here stays whole.
|
||||
func TestBackupSearchKeysOff(t *testing.T) {
|
||||
home(t)
|
||||
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: "tvly-a,tvly-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SwitchSearchKey("tavily", provider.SearchKeyRef("tvly-a"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []provider.SearchKey{{Key: "tvly-a", Off: true}, {Key: "tvly-b"}}
|
||||
with, err := Collect(true, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
without, err := Collect(false, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := *without.Searches; len(s) != 1 || s[0].HasKeys() {
|
||||
t.Fatalf("a backup without keys holds %+v", s)
|
||||
}
|
||||
data, err := Seal(with, "pass")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
home(t) // another machine
|
||||
got, err := Open(data, "pass")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Restore(got, All); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if as := provider.StoredSearchAPIs(); len(as) != 1 || !slices.Equal(as[0].SearchKeys(), want) || as[0].Key != "tvly-b" {
|
||||
t.Fatalf("restored %+v", as)
|
||||
}
|
||||
if _, err := Restore(without, Parts{Providers: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if as := provider.StoredSearchAPIs(); len(as) != 1 || !slices.Equal(as[0].SearchKeys(), want) {
|
||||
t.Fatalf("a backup without keys took keys here away: %+v", as)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,10 @@ func searchCmd(args []string) error {
|
||||
if a.Key == "" {
|
||||
what = "no key"
|
||||
}
|
||||
// keys switched off in Settings stay in its list, never asked
|
||||
if off := len(a.SearchKeys()) - len(a.Keys()); off > 0 {
|
||||
what += fmt.Sprintf(" +%d off", off)
|
||||
}
|
||||
if a.URL != "" {
|
||||
what += " " + a.URL
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
@@ -33,8 +34,8 @@ func TestSearchCLI(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
as := provider.SearchAPIs()
|
||||
if len(as) != 3 || as[0] != (provider.SearchAPI{Vendor: "tavily", Key: "tvly-1"}) || as[1].URL != "https://sx.example.com" ||
|
||||
as[2] != (provider.SearchAPI{Vendor: "brave", Key: "b-1", URL: "https://brave2.example.com"}) {
|
||||
if len(as) != 3 || !reflect.DeepEqual(as[0], provider.SearchAPI{Vendor: "tavily", Key: "tvly-1"}) || as[1].URL != "https://sx.example.com" ||
|
||||
!reflect.DeepEqual(as[2], provider.SearchAPI{Vendor: "brave", Key: "b-1", URL: "https://brave2.example.com"}) {
|
||||
t.Fatalf("%+v", as)
|
||||
}
|
||||
// a new key alone keeps the base URL the user set (#1580); url= with
|
||||
@@ -42,13 +43,13 @@ func TestSearchCLI(t *testing.T) {
|
||||
if err := searchCmd([]string{"add", "brave", "b-2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if as := provider.SearchAPIs(); as[2] != (provider.SearchAPI{Vendor: "brave", Key: "b-2", URL: "https://brave2.example.com"}) {
|
||||
if as := provider.SearchAPIs(); !reflect.DeepEqual(as[2], provider.SearchAPI{Vendor: "brave", Key: "b-2", URL: "https://brave2.example.com"}) {
|
||||
t.Fatalf("a new key took the base URL away: %+v", as[2])
|
||||
}
|
||||
if err := searchCmd([]string{"add", "brave", "url="}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if as := provider.SearchAPIs(); as[2] != (provider.SearchAPI{Vendor: "brave", Key: "b-2"}) || as[2].Base() != "https://api.search.brave.com" {
|
||||
if as := provider.SearchAPIs(); !reflect.DeepEqual(as[2], provider.SearchAPI{Vendor: "brave", Key: "b-2"}) || as[2].Base() != "https://api.search.brave.com" {
|
||||
t.Fatalf("url= kept the base URL: %+v", as[2])
|
||||
}
|
||||
for _, bad := range []string{"url=ftp://x.example.com", "url=https://x.example.com/?k=1", "url=https://x.example.com/#a", "url=x.example.com"} {
|
||||
@@ -78,7 +79,7 @@ func TestSearchCLIYouWithoutKey(t *testing.T) {
|
||||
if err := searchCmd([]string{"add", "you"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if as := provider.SearchAPIs(); len(as) != 1 || as[0] != (provider.SearchAPI{Vendor: "you"}) {
|
||||
if as := provider.SearchAPIs(); len(as) != 1 || !reflect.DeepEqual(as[0], provider.SearchAPI{Vendor: "you"}) {
|
||||
t.Fatalf("%+v", as)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,6 +231,7 @@ var notYet = map[string]string{
|
||||
"POST /api/settings/redact-rules": S2, // api.go
|
||||
"POST /api/settings/reveal": W, // api.go
|
||||
"POST /api/settings/search-all": S2, // api.go
|
||||
"POST /api/settings/search-keys": S2, // api.go
|
||||
"POST /api/settings/search-quota": S2, // api.go
|
||||
"POST /api/settings/text-size": W, // api.go
|
||||
"POST /api/settings/trae-checkin": S2, // api.go
|
||||
|
||||
@@ -931,15 +931,13 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
|
||||
}
|
||||
searches := from.Searches
|
||||
if searches != nil && !keys && (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) && to.Searches != nil { // the same for the search APIs
|
||||
keys := map[string]string{}
|
||||
keys := map[string]provider.SearchAPI{}
|
||||
for _, a := range *to.Searches {
|
||||
keys[a.Vendor] = a.Key
|
||||
keys[a.Vendor] = a
|
||||
}
|
||||
ss := slices.Clone(*searches)
|
||||
for i, a := range ss {
|
||||
if a.Key == "" {
|
||||
ss[i].Key = keys[a.Vendor]
|
||||
}
|
||||
ss[i].KeepKeysOf(keys[a.Vendor]) // those switched off too
|
||||
}
|
||||
searches = &ss
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/backup"
|
||||
@@ -48,3 +49,14 @@ func TestSyncSearchAPIs(t *testing.T) {
|
||||
t.Fatal("removed elsewhere, kept here")
|
||||
}
|
||||
}
|
||||
|
||||
// Sent without keys, a search API keeps the server's keys switched off
|
||||
// too (辰林鸭~ on Discord), not only the ones on.
|
||||
func TestSyncSearchKeysOff(t *testing.T) {
|
||||
list := []provider.SearchKey{{Key: "tvly-a", Off: true}, {Key: "tvly-b"}}
|
||||
server := backup.Bundle{Keys: true, Searches: &[]provider.SearchAPI{{Vendor: "tavily", Key: "tvly-b", KeyList: list}}}
|
||||
take(&server, backup.Bundle{Searches: &[]provider.SearchAPI{{Vendor: "tavily", Pick: provider.SearchPickOrder}}}, "providers")
|
||||
if s := *server.Searches; len(s) != 1 || s[0].Pick != provider.SearchPickOrder || !slices.Equal(s[0].SearchKeys(), list) {
|
||||
t.Fatalf("taken %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
@@ -87,3 +88,61 @@ func TestSearchAPIKeysTakeTurns(t *testing.T) {
|
||||
t.Errorf("stored %+v, shown %q", as, as[0].MaskedKey())
|
||||
}
|
||||
}
|
||||
|
||||
// A key switched off in its list (辰林鸭~ on Discord) is never asked, and
|
||||
// each key refused says why it rests, as the list shows it: Tavily's 433
|
||||
// out of credit, a 429 rate limited for as long as its Retry-After, a 401
|
||||
// turned away. The key that answered rests not at all.
|
||||
func TestSearchKeyOffAndWhyItRests(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
mu.Lock()
|
||||
asked = append(asked, key)
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch key {
|
||||
case "tvly-limited":
|
||||
w.Header().Set("Retry-After", "120")
|
||||
w.WriteHeader(429)
|
||||
io.WriteString(w, `{"detail":{"error":"Your request has been blocked due to excessive requests."}}`)
|
||||
case "tvly-paygo":
|
||||
w.WriteHeader(433)
|
||||
io.WriteString(w, `{"detail":{"error":"This request exceeds the pay-as-you-go limit."}}`)
|
||||
case "tvly-good":
|
||||
io.WriteString(w, `{"query":"x","results":[{"title":"Go","url":"https://go.dev/dl/","content":"go1.27.1","score":0.9}]}`)
|
||||
default:
|
||||
w.WriteHeader(401)
|
||||
io.WriteString(w, `{"detail":{"error":"Unauthorized: missing or invalid API key."}}`)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
forgetSearchKeys()
|
||||
if err := provider.SetSearchAPI(provider.SearchAPI{Vendor: "tavily", Key: "tvly-off,tvly-limited,tvly-paygo,tvly-bad,tvly-good", URL: srv.URL, Pick: provider.SearchPickOrder}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SwitchSearchKey("tavily", provider.SearchKeyRef("tvly-off"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
said, _, err := New().apiSearch(context.Background(), "latest go")
|
||||
if err != nil || !strings.Contains(said, "go1.27.1") {
|
||||
t.Fatalf("%q, %v", said, err)
|
||||
}
|
||||
mu.Lock()
|
||||
got := slices.Clone(asked)
|
||||
mu.Unlock()
|
||||
if !slices.Equal(got, []string{"tvly-limited", "tvly-paygo", "tvly-bad", "tvly-good"}) {
|
||||
t.Fatalf("asked with %v", got)
|
||||
}
|
||||
for key, want := range map[string]string{"tvly-limited": "rate limited", "tvly-paygo": "out of credit", "tvly-bad": "turned away", "tvly-good": "", "tvly-off": ""} {
|
||||
why, until := SearchKeyRest("tavily", key)
|
||||
if why != want || (want == "") != until.IsZero() {
|
||||
t.Errorf("%s rests %q until %v, want %q", key, why, until, want)
|
||||
}
|
||||
}
|
||||
if _, until := SearchKeyRest("tavily", "tvly-limited"); time.Until(until) < 90*time.Second || time.Until(until) > 125*time.Second {
|
||||
t.Errorf("a 429 with Retry-After 120 rests until %v", until)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,6 +102,15 @@ func searchKeyRest(vendor, key string, now time.Time) (keyRest, bool) {
|
||||
return r, true
|
||||
}
|
||||
|
||||
// SearchKeyRest is why a search API's key rests now (searchKeyOrder asks
|
||||
// it last), and until when; "" when it doesn't.
|
||||
func SearchKeyRest(vendor, key string) (string, time.Time) {
|
||||
if r, ok := searchKeyRest(vendor, key, time.Now()); ok {
|
||||
return r.Why, r.Until
|
||||
}
|
||||
return "", time.Time{}
|
||||
}
|
||||
|
||||
// searchKeyOrder is the order a search asks a's keys in, by their index:
|
||||
// from the key whose turn it is (the first, for SearchPickOrder), each
|
||||
// key resting put after those that aren't, the soonest awake first.
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
// SearchKeyQuota is what one key of a search API has used of its limit.
|
||||
type SearchKeyQuota struct {
|
||||
Key string `json:"key"` // masked (provider.MaskSearchKey)
|
||||
Ref string `json:"ref"` // provider.SearchKeyRef, its row's in the list
|
||||
// Known: Used and Limit were read. Unlimited: read, and the key and
|
||||
// its plan have no limit (Used is what the key has used).
|
||||
Known bool `json:"known"`
|
||||
@@ -171,7 +172,7 @@ func searchQuota(ctx context.Context, a provider.SearchAPI, key string, fresh bo
|
||||
msg := strings.ReplaceAll(err.Error(), key, provider.MaskSearchKey(key))
|
||||
q = SearchKeyQuota{Err: msg}
|
||||
}
|
||||
q.Key = provider.MaskSearchKey(key)
|
||||
q.Key, q.Ref = provider.MaskSearchKey(key), provider.SearchKeyRef(key)
|
||||
searchQuotas.Store(id, keptQuota{time.Now(), q})
|
||||
switch {
|
||||
case q.UsedUp:
|
||||
|
||||
+74
-1
@@ -592,6 +592,21 @@ type searchAPIJSON struct {
|
||||
Quota bool `json:"quota,omitempty"`
|
||||
// Off: switched off, kept but never asked (#2286)
|
||||
Off bool `json:"off,omitempty"`
|
||||
// KeyList is each key in its order, masked, on or off, and resting
|
||||
// (辰林鸭~ on Discord)
|
||||
KeyList []searchKeyJSON `json:"keyList"`
|
||||
}
|
||||
|
||||
// searchKeyJSON is one key of a search API as its list shows it: never
|
||||
// the key itself, which only Copy and Show ask for.
|
||||
type searchKeyJSON struct {
|
||||
Ref string `json:"ref"` // provider.SearchKeyRef
|
||||
Masked string `json:"masked"`
|
||||
Off bool `json:"off,omitempty"`
|
||||
// Rest is why the gateway asks it last now, RestUntil until when
|
||||
// (gateway.SearchKeyRest)
|
||||
Rest string `json:"rest,omitempty"`
|
||||
RestUntil time.Time `json:"restUntil,omitzero"`
|
||||
}
|
||||
|
||||
// searchChoiceJSON is a provider that can search for a model that can't,
|
||||
@@ -647,6 +662,14 @@ func searchState(s *settingsJSON) {
|
||||
if a.Key != "" {
|
||||
j.Key = a.MaskedKey()
|
||||
}
|
||||
j.KeyList = []searchKeyJSON{}
|
||||
for _, k := range a.SearchKeys() {
|
||||
kj := searchKeyJSON{Ref: provider.SearchKeyRef(k.Key), Masked: provider.MaskSearchKey(k.Key), Off: k.Off}
|
||||
if !k.Off {
|
||||
kj.Rest, kj.RestUntil = gateway.SearchKeyRest(a.Vendor, k.Key)
|
||||
}
|
||||
j.KeyList = append(j.KeyList, kj)
|
||||
}
|
||||
s.SearchAPIs = append(s.SearchAPIs, j)
|
||||
}
|
||||
for _, v := range provider.AllSearchVendors() {
|
||||
@@ -2553,6 +2576,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
Remove bool
|
||||
On *bool
|
||||
Arrange []string
|
||||
// Append: the keys typed for an API added before go after its
|
||||
// own, which stay, rather than in their place
|
||||
Append bool
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
@@ -2566,6 +2592,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
err = provider.RemoveSearchAPI(in.Vendor)
|
||||
case in.On != nil:
|
||||
err = provider.SwitchSearchAPI(in.Vendor, *in.On)
|
||||
case in.Append && in.Key != "" && slices.ContainsFunc(provider.StoredSearchAPIs(), func(a provider.SearchAPI) bool { return a.Vendor == in.Vendor }):
|
||||
if err = provider.SetSearchAPI(provider.SearchAPI{Vendor: in.Vendor, URL: in.URL, Pick: in.Pick}); err == nil {
|
||||
_, _, err = provider.AddSearchKeys(in.Vendor, in.Key)
|
||||
}
|
||||
default:
|
||||
err = provider.SetSearchAPI(provider.SearchAPI{Vendor: in.Vendor, Key: in.Key, URL: in.URL, Pick: in.Pick})
|
||||
}
|
||||
@@ -2575,14 +2605,57 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// one search API's list of keys (辰林鸭~ on Discord): keys added, one
|
||||
// removed or switched on or off, or the list put in a new order, each
|
||||
// key named by its ref (provider.SearchKeyRef), never by itself
|
||||
mux.HandleFunc("POST /api/settings/search-keys", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Vendor, Add, Ref string
|
||||
Remove bool
|
||||
On *bool
|
||||
Arrange []string
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
var err error
|
||||
added, had := 0, 0
|
||||
switch {
|
||||
case in.Arrange != nil:
|
||||
err = provider.ArrangeSearchKeys(in.Vendor, in.Arrange)
|
||||
case in.Add != "":
|
||||
added, had, err = provider.AddSearchKeys(in.Vendor, in.Add)
|
||||
case in.Remove:
|
||||
err = provider.RemoveSearchKey(in.Vendor, in.Ref)
|
||||
case in.On != nil:
|
||||
err = provider.SwitchSearchKey(in.Vendor, in.Ref, *in.On)
|
||||
default:
|
||||
err = fmt.Errorf("nothing to change")
|
||||
}
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]any{"settings": settingsState(), "added": added, "had": had})
|
||||
})
|
||||
// a search API's saved key, for its row's Show button (OnurBen on
|
||||
// Discord); like a provider's, it never leaves this machine
|
||||
mux.HandleFunc("POST /api/settings/search-key", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Vendor string }
|
||||
var in struct{ Vendor, Ref string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if in.Ref != "" { // one key of its list
|
||||
k, err := provider.SearchKeyOf(in.Vendor, in.Ref)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, map[string]string{"key": k})
|
||||
return
|
||||
}
|
||||
for _, a := range provider.StoredSearchAPIs() {
|
||||
if a.Vendor == in.Vendor {
|
||||
writeJSON(rw, map[string]string{"key": a.Key})
|
||||
|
||||
+25
-12
@@ -3889,19 +3889,32 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
|
||||
/* 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%; }
|
||||
/* a search API's key, shown: selectable, and broken anywhere rather than widening the row */
|
||||
.search-api .sub.revealed { font-family: var(--code-font, var(--code)); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; }
|
||||
:where(html[data-fonts]) .search-api .sub.revealed { font-style: var(--code-style, inherit); font-weight: var(--code-weight, inherit); font-stretch: var(--code-stretch, 100%); }
|
||||
/* a search API's keys and what each has used of its limit */
|
||||
/* how its searches pick a key, and Check again: wrapped, right-aligned, on a
|
||||
narrow window in a long language rather than past its edge */
|
||||
/* a search API's keys (辰林鸭~ on Discord), listed as a provider's are:
|
||||
how its searches pick one and Check again wrapped and right-aligned on a
|
||||
narrow window in a long language rather than past its edge; each key's
|
||||
rest and what it has used on a line under it */
|
||||
.row.pref.search-keys .val { flex-wrap: wrap; justify-content: flex-end; gap: 4px; }
|
||||
.search-quota { display: flex; flex-direction: column; gap: 3px; margin-top: 6px; font-size: 12px; min-width: 0; }
|
||||
.search-quota .quota-key { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; min-width: 0; }
|
||||
.search-quota code { font-family: var(--code-font, var(--code)); color: var(--muted); }
|
||||
.search-quota .faint { color: var(--muted); overflow-wrap: anywhere; }
|
||||
.search-quota .err { color: var(--red); overflow-wrap: anywhere; }
|
||||
.search-quota .warn { color: var(--amber); }
|
||||
.row.pref.search-keys .who { min-width: 0; }
|
||||
.search-key-list { margin-top: 8px; }
|
||||
.search-key-list > .acc { position: relative; flex-wrap: wrap; row-gap: 2px; cursor: default; }
|
||||
.search-key-list > .acc code.n { font-family: var(--code-font, var(--code)); font-weight: 400; color: var(--fg-2); }
|
||||
.search-key-list > .acc code.revealed { white-space: normal; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; cursor: text; }
|
||||
.search-key-list > .acc.off code.n { opacity: .55; }
|
||||
.search-key-list > .acc .key-state { flex-basis: 100%; display: flex; flex-wrap: wrap; gap: 2px 10px; padding-left: 25px; font-size: 11.5px; color: var(--muted); min-width: 0; overflow-wrap: anywhere; }
|
||||
.search-key-list .key-state .warn { color: var(--amber); }
|
||||
.search-key-list .key-state .err { color: var(--red); }
|
||||
.search-key-list .key-quota { display: contents; }
|
||||
.search-key-list > .acc.adding { display: flex; align-items: center; gap: 6px; }
|
||||
.search-key-list > .acc.adding input { flex: 1 1 12em; min-width: 0; }
|
||||
.search-key-list.reorderable > .acc:not(.add, .adding) { cursor: grab; touch-action: pan-y; }
|
||||
.search-key-list.reorderable > .acc:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.search-key-list > .acc > .grip { position: absolute; left: 2px; top: 19px; translate: 0 -50%; width: 6px; height: 11px; background: radial-gradient(circle, var(--muted) .9px, transparent 1.2px) 0 0 / 3px 3.75px; opacity: 0; transition: opacity .15s; pointer-events: none; }
|
||||
.search-key-list > .acc:is(:hover, .dragging) > .grip { opacity: 1; }
|
||||
.search-key-list > .acc:focus-visible > .grip { opacity: 1; }
|
||||
@media (hover: none) { .search-key-list > .acc > .grip { opacity: 1; } }
|
||||
.search-key-list.sorting { user-select: none; -webkit-user-select: none; }
|
||||
.search-key-list.sorting > .acc { transition: transform .16s cubic-bezier(.22, 1, .36, 1); cursor: grabbing; }
|
||||
.search-key-list.sorting > .acc.dragging { z-index: 2; background: var(--card-2); box-shadow: 0 0 0 1px var(--line); transition: none; }
|
||||
.prefs .val.rule-add .segs { margin-left: 0; }
|
||||
/* a search API and its keys' row, dragged as one into the order they are
|
||||
asked in (#2286); its grip shows only under the pointer, and one
|
||||
|
||||
@@ -1524,7 +1524,10 @@ const I18N = {
|
||||
"API key, or several split by commas": "API 密钥,多个用逗号分隔",
|
||||
"Base URL": "API 地址",
|
||||
"Base URL, empty for {url}": "API 地址,留空则用 {url}",
|
||||
"A new key, or empty to keep {key}": "新的密钥,留空则保留 {key}",
|
||||
"Another key for {name}, or empty to keep its keys": "{name} 的另一个密钥,留空则保留它的密钥",
|
||||
"Paste a key, or several split by commas or lines": "粘贴一个密钥,或用逗号、换行分隔的多个",
|
||||
"Key added": "已添加密钥",
|
||||
"{n} keys added": "已添加 {n} 个密钥",
|
||||
"Reading what each key has used…": "正在读取每个密钥的用量…",
|
||||
"Unknown: {why}": "未知:{why}",
|
||||
"{used} used, no limit": "已用 {used},无上限",
|
||||
@@ -2025,6 +2028,7 @@ const I18N = {
|
||||
"The first is tried first; the other {n} are added to its accounts": "第一个优先使用,其余 {n} 个加为它的账号",
|
||||
"Add many keys at once, one a line or separated by commas": "一次添加多个密钥,每行一个或用逗号分隔",
|
||||
"Add another key": "添加另一个密钥",
|
||||
"Add a key": "添加密钥",
|
||||
"Name (optional), e.g. Team": "名称(可选),例如 团队",
|
||||
"Name, e.g. Personal or Team": "名称,例如 个人 或 团队",
|
||||
"Name this account": "给此账号起名",
|
||||
@@ -6197,7 +6201,10 @@ const I18N = {
|
||||
"API key, or several split by commas": "API 金鑰,多個用逗號分隔",
|
||||
"Base URL": "API 位址",
|
||||
"Base URL, empty for {url}": "API 位址,留空則用 {url}",
|
||||
"A new key, or empty to keep {key}": "新的金鑰,留空則保留 {key}",
|
||||
"Another key for {name}, or empty to keep its keys": "{name} 的另一個金鑰,留空則保留它的金鑰",
|
||||
"Paste a key, or several split by commas or lines": "貼上一個金鑰,或用逗號、換行分隔的多個",
|
||||
"Key added": "已新增金鑰",
|
||||
"{n} keys added": "已新增 {n} 個金鑰",
|
||||
"Reading what each key has used…": "正在讀取每個金鑰的用量…",
|
||||
"Unknown: {why}": "未知:{why}",
|
||||
"{used} used, no limit": "已用 {used},無上限",
|
||||
@@ -6692,6 +6699,7 @@ const I18N = {
|
||||
"The first is tried first; the other {n} are added to its accounts": "第一個優先使用,其餘 {n} 個加為它的帳號",
|
||||
"Add many keys at once, one a line or separated by commas": "一次新增多個金鑰,每行一個或用逗號分隔",
|
||||
"Add another key": "新增另一個金鑰",
|
||||
"Add a key": "新增金鑰",
|
||||
"Name (optional), e.g. Team": "名稱(可選),例如 團隊",
|
||||
"Name, e.g. Personal or Team": "名稱,例如 個人 或 團隊",
|
||||
"Name this account": "為此帳號命名",
|
||||
@@ -10840,7 +10848,10 @@ const I18N = {
|
||||
"API key, or several split by commas": "APIキー(複数はカンマ区切り)",
|
||||
"Base URL": "ベース URL",
|
||||
"Base URL, empty for {url}": "ベース URL(空なら {url})",
|
||||
"A new key, or empty to keep {key}": "新しいキー(空なら {key} のまま)",
|
||||
"Another key for {name}, or empty to keep its keys": "{name} の別のキー(空なら今のキーのまま)",
|
||||
"Paste a key, or several split by commas or lines": "キーを貼り付け(複数はカンマか改行で区切る)",
|
||||
"Key added": "キーを追加しました",
|
||||
"{n} keys added": "{n} 個のキーを追加しました",
|
||||
"Reading what each key has used…": "各キーの使用量を読み込み中…",
|
||||
"Unknown: {why}": "不明:{why}",
|
||||
"{used} used, no limit": "{used} 使用、上限なし",
|
||||
@@ -11335,6 +11346,7 @@ const I18N = {
|
||||
"The first is tried first; the other {n} are added to its accounts": "最初のキーを優先し、残りの {n} 個はアカウントとして追加します",
|
||||
"Add many keys at once, one a line or separated by commas": "複数のキーを一度に追加(1 行に 1 つ、またはカンマ区切り)",
|
||||
"Add another key": "別のキーを追加",
|
||||
"Add a key": "キーを追加",
|
||||
"Name (optional), e.g. Team": "名前(任意)、例:チーム",
|
||||
"Name, e.g. Personal or Team": "名前、例:個人 または チーム",
|
||||
"Name this account": "このアカウントに名前を付ける",
|
||||
@@ -15514,7 +15526,10 @@ const I18N = {
|
||||
"API key, or several split by commas": "API-Schlüssel, mehrere durch Kommas getrennt",
|
||||
"Base URL": "Basis-URL",
|
||||
"Base URL, empty for {url}": "Basis-URL, leer für {url}",
|
||||
"A new key, or empty to keep {key}": "Neuer Schlüssel, leer lässt {key}",
|
||||
"Another key for {name}, or empty to keep its keys": "Weiterer Schlüssel für {name}, leer lässt seine Schlüssel",
|
||||
"Paste a key, or several split by commas or lines": "Einen Schlüssel einfügen, oder mehrere, durch Kommas oder Zeilen getrennt",
|
||||
"Key added": "Schlüssel hinzugefügt",
|
||||
"{n} keys added": "{n} Schlüssel hinzugefügt",
|
||||
"Reading what each key has used…": "Lese, was jeder Schlüssel verbraucht hat…",
|
||||
"Unknown: {why}": "Unbekannt: {why}",
|
||||
"{used} used, no limit": "{used} verbraucht, kein Limit",
|
||||
@@ -16009,6 +16024,7 @@ const I18N = {
|
||||
"The first is tried first; the other {n} are added to its accounts": "Der erste wird zuerst versucht; die anderen {n} kommen als seine Konten dazu",
|
||||
"Add many keys at once, one a line or separated by commas": "Viele Schlüssel auf einmal hinzufügen, einer pro Zeile oder durch Kommas getrennt",
|
||||
"Add another key": "Weiteren Schlüssel hinzufügen",
|
||||
"Add a key": "Schlüssel hinzufügen",
|
||||
"Name (optional), e.g. Team": "Name (optional), z. B. Team",
|
||||
"Name, e.g. Personal or Team": "Name, z. B. Privat oder Team",
|
||||
"Name this account": "Diesem Konto einen Namen geben",
|
||||
|
||||
@@ -63,7 +63,7 @@ function renderSearch(s, keep) {
|
||||
url.placeholder = v.needURL ? "https://searx.example.com" : t("Base URL, empty for {url}", { url: v.base || "" });
|
||||
url.setAttribute("aria-label", v.needURL ? t("Address") : t("Base URL"));
|
||||
key.placeholder = v.needURL ? t("API key, if it needs one")
|
||||
: saved()?.key ? t("A new key, or empty to keep {key}", { key: saved().key })
|
||||
: saved()?.keyList?.length ? t("Another key for {name}, or empty to keep its keys", { name: v.name || "" })
|
||||
: v.keyOptional ? t("API key, or empty for its free search")
|
||||
: t("API key, or several split by commas");
|
||||
get.hidden = !v.keysURL || !!v.auth;
|
||||
@@ -83,7 +83,8 @@ function renderSearch(s, keep) {
|
||||
// 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 && !vendor().auth) return (vendor().needURL ? url : key).focus();
|
||||
set({ vendor: d.vendor, key: d.key, url: d.url },
|
||||
// a key typed for one added before joins its keys, never replaces them
|
||||
set({ vendor: d.vendor, key: d.key, url: d.url, ...(saved() && d.key ? { append: true } : {}) },
|
||||
() => { searchDraft = { vendor: d.vendor, key: "", url: "", err: "" }; });
|
||||
};
|
||||
for (const i of [key, url]) {
|
||||
@@ -118,30 +119,9 @@ function renderSearch(s, keep) {
|
||||
: !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(" · ");
|
||||
// its keys are listed under it, each with its own Show and Copy
|
||||
const what = [signedIn || (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
|
||||
// editor does (OnurBen on Discord)
|
||||
const eye = el("button", "text search-eye", t("Show"));
|
||||
eye.onclick = async () => {
|
||||
const sub = r.querySelector(".sub");
|
||||
if (eye.textContent === t("Show")) {
|
||||
try { sub.textContent = [(await api("settings/search-key", { vendor: a.vendor })).key, a.url].filter(Boolean).join(" · "); } catch (e) { status(e.message, "err"); return; }
|
||||
sub.classList.add("revealed");
|
||||
eye.textContent = t("Hide");
|
||||
} else {
|
||||
sub.textContent = what;
|
||||
sub.classList.remove("revealed");
|
||||
eye.textContent = t("Show");
|
||||
}
|
||||
};
|
||||
const cp = el("button", "text search-copy", t("Copy"));
|
||||
cp.onclick = async () => {
|
||||
try { copy((await api("settings/search-key", { vendor: a.vendor })).key, t("API key"), cp); } catch (e) { status(e.message, "err"); }
|
||||
};
|
||||
tools.unshift(eye, cp);
|
||||
}
|
||||
// switched off it stays, key and all, and no search asks it (#2286)
|
||||
const sw = el("button", "lib-switch use-credits search-on" + (a.off ? "" : " on"));
|
||||
sw.type = "button";
|
||||
@@ -160,7 +140,7 @@ function renderSearch(s, keep) {
|
||||
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); }
|
||||
if (!auth && (a.keyList?.length || !vendors.find((v) => v.id === a.vendor)?.needURL)) { unit.classList.add("with-keys"); searchKeysRow(s, a, row, set); }
|
||||
into = box;
|
||||
});
|
||||
searchArrange(box, units, set);
|
||||
@@ -262,25 +242,33 @@ function searchArrange(box, units, set) {
|
||||
move(unit, units.indexOf(unit) + (e.key === "ArrowUp" ? -1 : 1));
|
||||
};
|
||||
unit.onpointerdown = (e) => {
|
||||
if (searchArranging || e.target.closest("input, textarea, select, a, button, code, .segs, .sub.revealed")) return;
|
||||
if (searchArranging || e.target.closest("input, textarea, select, a, button, code, .segs, .sub.revealed, .search-key-list")) return;
|
||||
searchArranging = dragRows(e, unit, unit, box, units, (to) => move(unit, to), () => {},
|
||||
() => { searchArranging = false; });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// searchKeysRow: under a search API with several keys, or one whose keys
|
||||
// quota magpie can read (Tavily's), a row of its keys (SlouchyQuill on
|
||||
// Discord): how a search picks among them, in turn (the default) or in
|
||||
// order, and what each has used of its limit, read once as the page is
|
||||
// drawn and again on Check again. A read that fails says unknown and why,
|
||||
// never 0; a key a search set aside lately says why and until when.
|
||||
// searchKeysRow: under a search API that takes keys, its list of them
|
||||
// (辰林鸭~ on Discord), as a provider's keys are listed: each masked, on or
|
||||
// off by its dot, shown, copied or removed, dragged into another order or
|
||||
// moved with Alt+↑/↓, and one or several added at its foot. How a search
|
||||
// picks among those on, in turn (the default) or in order (SlouchyQuill on
|
||||
// Discord), and why a key is asked last now and until when, show beside
|
||||
// them; what each has used of its limit (Tavily's) is read once as the page
|
||||
// is drawn and again on Check again. A read that fails says unknown and
|
||||
// why, never 0.
|
||||
const searchQuotaSeen = {};
|
||||
let searchKeyAdding = null, searchKeyShown = {};
|
||||
function searchKeysRow(s, a, row, set) {
|
||||
const list0 = a.keyList || [], on = list0.filter((k) => !k.off).length;
|
||||
const tools = [];
|
||||
if (a.keys > 1) tools.push(segs([["", t("In turn")], ["order", t("In order")]], a.pick || "",
|
||||
if (on > 1) tools.push(segs([["", t("In turn")], ["order", t("In order")]], a.pick || "",
|
||||
(v) => set({ vendor: a.vendor, pick: v || "turns" })));
|
||||
const mine = el("div", "search-quota");
|
||||
const keys = (body, said) => writingPrefs(api("settings/search-keys", { vendor: a.vendor, ...body }))
|
||||
.then((r) => { prefs = r.settings; searchKeyAdding = null; renderSettings(); status(said?.(r) || t("Saved"), "ok", 1500); })
|
||||
.catch((e) => { status(e.message, "err"); renderSettings(); });
|
||||
const list = el("div", "accts keys search-key-list");
|
||||
const seenAs = [a.key, a.url].join(" ");
|
||||
const ask = (fresh) => {
|
||||
searchQuotaSeen[a.vendor] = { as: seenAs, loading: true };
|
||||
@@ -290,49 +278,159 @@ function searchKeysRow(s, a, row, set) {
|
||||
.catch((e) => { searchQuotaSeen[a.vendor] = { as: seenAs, err: e.message }; })
|
||||
.finally(draw);
|
||||
};
|
||||
// the list in the page now: Settings may have been drawn again while
|
||||
// the read was out
|
||||
const num = (n) => Number(n).toLocaleString(intlLang());
|
||||
const whyOf = (w) => ({ "turned away": t("turned away"), "out of credit": t("out of credit"), "rate limited": t("rate limited"), "used up": t("used up") })[w] || w;
|
||||
// each key's quota, in the rows in the page now: Settings may have been
|
||||
// drawn again while the read was out
|
||||
const draw = () => {
|
||||
const list = document.querySelector(`.search-keys[data-vendor="${a.vendor}"] .search-quota`) || mine;
|
||||
const box = document.querySelector(`.search-keys[data-vendor="${CSS.escape(a.vendor)}"] .search-key-list`) || list;
|
||||
const seen = searchQuotaSeen[a.vendor];
|
||||
list.replaceChildren();
|
||||
if (!seen || seen.loading) return list.append(el("div", "faint", t("Reading what each key has used…")));
|
||||
if (seen.err) return list.append(el("div", "err", t("Unknown: {why}", { why: seen.err })));
|
||||
const num = (n) => Number(n).toLocaleString(intlLang());
|
||||
for (const q of seen.keys) {
|
||||
const line = el("div", "quota-key");
|
||||
for (const line of box.querySelectorAll(".acc[data-ref]")) {
|
||||
const at = line.querySelector(".key-quota");
|
||||
if (!at) continue;
|
||||
at.replaceChildren();
|
||||
if (!seen || seen.loading) { at.append(el("span", "faint", t("Reading what each key has used…"))); continue; }
|
||||
if (seen.err) { at.append(el("span", "err", t("Unknown: {why}", { why: seen.err }))); continue; }
|
||||
const q = seen.keys.find((x) => x.ref === line.dataset.ref);
|
||||
if (!q) continue;
|
||||
const said = !q.known ? t("Unknown: {why}", { why: q.err || "" })
|
||||
: q.unlimited ? t("{used} used, no limit", { used: num(q.used) })
|
||||
: t("{used} of {limit} used", { used: num(q.used), limit: num(q.limit) });
|
||||
const notes = [];
|
||||
if (q.known && q.of === "plan") notes.push(q.plan ? t("{plan} plan, shared by its account's keys", { plan: q.plan }) : t("the plan's, shared by its account's keys"));
|
||||
if (q.paygoLeft > 0) notes.push(t("{n} pay-as-you-go left", { n: num(q.paygoLeft) }));
|
||||
if (q.resting) notes.push(t("asked last until {time}: {why}", { time: hhmm(q.restUntil),
|
||||
why: { "turned away": t("turned away"), "out of credit": t("out of credit"), "rate limited": t("rate limited"), "used up": t("used up") }[q.resting] || q.resting }));
|
||||
const used = el("span", q.known ? (q.usedUp ? "used warn" : "used") : "used err", said);
|
||||
line.append(el("code", "", q.key), used);
|
||||
if (q.usedUp) line.append(el("span", "warn", t("used up")));
|
||||
if (notes.length) line.append(el("span", "faint", notes.join(" · ")));
|
||||
list.append(line);
|
||||
at.append(el("span", q.known ? (q.usedUp ? "used warn" : "used") : "used err", said));
|
||||
if (q.usedUp) at.append(el("span", "warn", t("used up")));
|
||||
if (notes.length) at.append(el("span", "faint", notes.join(" · ")));
|
||||
}
|
||||
};
|
||||
if (a.quota) {
|
||||
const rows = [];
|
||||
for (const k of list0) {
|
||||
const r = el("div", "acc" + (k.off ? " off" : " in-use"));
|
||||
r.dataset.ref = k.ref;
|
||||
const dot = el("button", "dot tick");
|
||||
dot.type = "button";
|
||||
if (!k.off) dot.append(svg(CHECK, 10, 2.2));
|
||||
dot.title = k.off ? t("Use this key too") : t("Stop using this key");
|
||||
dot.setAttribute("aria-label", dot.title);
|
||||
dot.setAttribute("aria-pressed", String(!k.off));
|
||||
dot.onclick = () => keys({ ref: k.ref, on: !!k.off });
|
||||
const shown = searchKeyShown[a.vendor + " " + k.ref];
|
||||
const code = el("code", "n" + (shown ? " revealed" : ""), shown || k.masked);
|
||||
const eye = el("button", "text search-eye", shown ? t("Hide") : t("Show"));
|
||||
eye.onclick = async () => {
|
||||
const id = a.vendor + " " + k.ref;
|
||||
if (searchKeyShown[id]) delete searchKeyShown[id];
|
||||
else try { searchKeyShown[id] = (await api("settings/search-key", { vendor: a.vendor, ref: k.ref })).key; } catch (e) { return status(e.message, "err"); }
|
||||
code.textContent = searchKeyShown[id] || k.masked;
|
||||
code.classList.toggle("revealed", !!searchKeyShown[id]);
|
||||
eye.textContent = searchKeyShown[id] ? t("Hide") : t("Show");
|
||||
};
|
||||
const cp = el("button", "copy search-copy");
|
||||
cp.type = "button";
|
||||
cp.title = t("Copy");
|
||||
cp.setAttribute("aria-label", t("Copy"));
|
||||
cp.append(svg(COPY_ICON, 12, 1.5));
|
||||
cp.onclick = async () => {
|
||||
try { copy((await api("settings/search-key", { vendor: a.vendor, ref: k.ref })).key, t("API key"), cp); } catch (e) { status(e.message, "err"); }
|
||||
};
|
||||
const x = el("button", "text search-key-remove", t("Remove"));
|
||||
x.onclick = () => keys({ ref: k.ref, remove: true });
|
||||
r.append(dot, code, el("span", "grow"), eye, cp, x);
|
||||
// why it is asked last now, and until when: on a line of its own
|
||||
const state = el("div", "key-state");
|
||||
if (k.off) state.append(el("span", "faint", t("Off")));
|
||||
else if (k.rest && new Date(k.restUntil) > Date.now()) {
|
||||
r.classList.add("resting");
|
||||
state.append(el("span", "warn key-rest", t("asked last until {time}: {why}", { time: hhmm(k.restUntil), why: whyOf(k.rest) })));
|
||||
}
|
||||
if (a.quota && !k.off) state.append(el("span", "key-quota"));
|
||||
if (state.childNodes.length) r.append(state);
|
||||
rows.push(r);
|
||||
list.append(r);
|
||||
}
|
||||
if (searchKeyAdding === a.vendor) {
|
||||
// one key, or several pasted at once, split as a provider's are
|
||||
const box = el("div", "acc adding");
|
||||
const i = input("", t("Paste a key, or several split by commas or lines"), "password");
|
||||
i.className = "words search-key-new";
|
||||
i.setAttribute("aria-label", t("API key"));
|
||||
const go = () => {
|
||||
const n = splitKeys(i.value).length;
|
||||
if (!n) return i.focus(NO_SCROLL);
|
||||
keys({ add: i.value }, (r) => r.had ? t("{n} keys added, {m} already there", { n: r.added, m: r.had })
|
||||
: r.added === 1 ? t("Key added") : t("{n} keys added", { n: r.added }));
|
||||
};
|
||||
const add = el("button", "text primary", t("Add"));
|
||||
add.onclick = go;
|
||||
const no = el("button", "text", t("Cancel"));
|
||||
no.onclick = () => { searchKeyAdding = null; renderSettings(); };
|
||||
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") go(); else if (e.key === "Escape") no.onclick(); };
|
||||
box.append(i, no, add);
|
||||
list.append(box);
|
||||
queueMicrotask(() => i.focus(NO_SCROLL));
|
||||
} else list.append(addRow(list0.length ? t("Add another key") : t("Add a key"), () => { searchKeyAdding = a.vendor; renderSettings(); }));
|
||||
searchKeyArrange(a, list, rows, keys);
|
||||
if (a.quota && on) {
|
||||
const again = el("button", "text search-quota-again", t("Check again"));
|
||||
again.onclick = () => ask(true);
|
||||
tools.push(again);
|
||||
}
|
||||
const r = row(t("Keys of {name}", { name: a.name }),
|
||||
a.keys > 1 ? t("In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.") : t("What the key has used of its limit"),
|
||||
on > 1 ? t("In turn spreads searches over the keys; in order uses the first until it is refused. A key refused lately is asked last.") : "",
|
||||
...tools);
|
||||
r.classList.add("search-keys");
|
||||
r.dataset.vendor = a.vendor;
|
||||
if (a.quota) {
|
||||
r.querySelector(".who").append(mine);
|
||||
r.querySelector(".who").append(list);
|
||||
if (a.quota && on) {
|
||||
if (searchQuotaSeen[a.vendor]?.as !== seenAs) ask(false);
|
||||
else draw();
|
||||
}
|
||||
}
|
||||
|
||||
// searchKeyArrange: a search API's keys are asked in their list's order
|
||||
// (in order, or from the first in turn), put in another by dragging a key
|
||||
// or with Alt+↑/↓ on it; the order shows at once and the page is drawn
|
||||
// again from what is saved.
|
||||
function searchKeyArrange(a, list, rows, keys) {
|
||||
if (rows.length < 2) return;
|
||||
list.classList.add("reorderable");
|
||||
let busy = false;
|
||||
const move = (r, to) => {
|
||||
const from = rows.indexOf(r);
|
||||
to = Math.max(0, Math.min(rows.length - 1, to));
|
||||
if (to === from || busy) return;
|
||||
busy = true;
|
||||
const order = rows.map((x) => x.dataset.ref);
|
||||
order.splice(to, 0, ...order.splice(from, 1));
|
||||
const focus = document.activeElement === r;
|
||||
list.insertBefore(r, to > from ? rows[to].nextSibling : rows[to]);
|
||||
rows.splice(to, 0, ...rows.splice(from, 1));
|
||||
if (focus) r.focus(NO_SCROLL);
|
||||
keys({ arrange: order }).then(() => {
|
||||
if (focus) document.querySelector(`.search-keys[data-vendor="${CSS.escape(a.vendor)}"] .acc[data-ref="${CSS.escape(r.dataset.ref)}"]`)?.focus(NO_SCROLL);
|
||||
});
|
||||
};
|
||||
for (const r of rows) {
|
||||
r.tabIndex = 0;
|
||||
r.title = t("Drag to reorder · Alt+↑/↓ to move");
|
||||
r.prepend(el("span", "grip"));
|
||||
r.addEventListener("click", (e) => {
|
||||
if (r.dataset.dragged) { e.preventDefault(); e.stopImmediatePropagation(); }
|
||||
}, true);
|
||||
r.onkeydown = (e) => {
|
||||
if (e.target !== r || !e.altKey || !["ArrowUp", "ArrowDown"].includes(e.key)) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
move(r, rows.indexOf(r) + (e.key === "ArrowUp" ? -1 : 1));
|
||||
};
|
||||
r.onpointerdown = (e) => {
|
||||
if (busy || e.target.closest("input, button, code.revealed")) return;
|
||||
e.stopPropagation();
|
||||
dragRows(e, r, r, list, rows, (to) => move(r, to));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// renderSearcher: the provider that searches the web for a model that
|
||||
// can't — the one magpie picks, or one named, by itself (its small model)
|
||||
// or with a model of it. One named that is gone, off or can't search gives
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -67,7 +68,7 @@ func TestSearchAPIBaseURLFromSettings(t *testing.T) {
|
||||
if rec := post(`{"vendor":"tavily","key":"","url":"https://other.example.com"}`); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if as := provider.SearchAPIs(); len(as) != 1 || as[0] != (provider.SearchAPI{Vendor: "tavily", Key: "tvly-1", URL: "https://other.example.com"}) {
|
||||
if as := provider.SearchAPIs(); len(as) != 1 || !reflect.DeepEqual(as[0], provider.SearchAPI{Vendor: "tavily", Key: "tvly-1", URL: "https://other.example.com"}) {
|
||||
t.Fatalf("%+v", as)
|
||||
}
|
||||
for _, bad := range []string{"ftp://x.example.com", "search.example.com", "https://x.example.com/?key=1"} {
|
||||
@@ -130,3 +131,98 @@ func TestSearchAPIOrderAndOffFromSettings(t *testing.T) {
|
||||
t.Fatalf("switched on %+v", as)
|
||||
}
|
||||
}
|
||||
|
||||
// A search API's keys are a list in Settings (辰林鸭~ on Discord): each
|
||||
// listed masked by its ref, never whole; added (several at once, one
|
||||
// already there counted), switched off, put in order and removed by
|
||||
// ref; a key typed in Add for an API already set goes after its keys;
|
||||
// and Show reads the one key its ref names.
|
||||
func TestSearchKeyListFromSettings(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
keys := []string{"tvly-dev-aaaaaaaaaaaa1111", "tvly-dev-bbbbbbbbbbbb2222", "tvly-dev-cccccccccccc3333", "tvly-dev-dddddddddddd4444"}
|
||||
ref := provider.SearchKeyRef
|
||||
post := func(path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
list := func() []searchKeyJSON {
|
||||
t.Helper()
|
||||
var s settingsJSON
|
||||
searchState(&s)
|
||||
b, _ := json.Marshal(s)
|
||||
for _, k := range keys {
|
||||
if strings.Contains(string(b), k) {
|
||||
t.Fatalf("the settings hold a whole key: %s", b)
|
||||
}
|
||||
}
|
||||
if len(s.SearchAPIs) != 1 {
|
||||
t.Fatalf("%+v", s.SearchAPIs)
|
||||
}
|
||||
return s.SearchAPIs[0].KeyList
|
||||
}
|
||||
order := func(l []searchKeyJSON) (out []string) {
|
||||
for _, k := range l {
|
||||
s := k.Ref
|
||||
if k.Off {
|
||||
s += " off"
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if rec := post("/api/settings/search-api", `{"vendor":"tavily","key":"`+keys[0]+`"}`); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
// a key added in Add once the API is set goes after its key
|
||||
if rec := post("/api/settings/search-api", `{"vendor":"tavily","key":"`+keys[1]+`","append":true}`); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
rec := post("/api/settings/search-keys", `{"vendor":"tavily","add":"`+keys[1]+`\n`+keys[2]+`, `+keys[3]+`"}`)
|
||||
var added struct{ Added, Had int }
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &added) != nil || added.Added != 2 || added.Had != 1 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
l := list()
|
||||
if !reflect.DeepEqual(order(l), []string{ref(keys[0]), ref(keys[1]), ref(keys[2]), ref(keys[3])}) || l[0].Masked != provider.MaskSearchKey(keys[0]) {
|
||||
t.Fatalf("%+v", l)
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"vendor":"tavily","ref":"` + ref(keys[1]) + `","on":false}`,
|
||||
`{"vendor":"tavily","arrange":["` + ref(keys[3]) + `","` + ref(keys[1]) + `"]}`,
|
||||
`{"vendor":"tavily","ref":"` + ref(keys[0]) + `","remove":true}`,
|
||||
} {
|
||||
if rec := post("/api/settings/search-keys", body); rec.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", body, rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
if got := order(list()); !reflect.DeepEqual(got, []string{ref(keys[3]), ref(keys[1]) + " off", ref(keys[2])}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"vendor":"tavily","ref":"` + ref(keys[0]) + `","remove":true}`, // gone already
|
||||
`{"vendor":"tavily","arrange":["` + ref(keys[0]) + `"]}`, // a key not here
|
||||
`{"vendor":"exa","add":"` + keys[0] + `"}`, // an API not set
|
||||
`{"vendor":"tavily"}`, // nothing asked
|
||||
} {
|
||||
if rec := post("/api/settings/search-keys", body); rec.Code < 400 {
|
||||
t.Errorf("%s: %d", body, rec.Code)
|
||||
}
|
||||
}
|
||||
var got struct{ Key string }
|
||||
if rec := post("/api/settings/search-key", `{"vendor":"tavily","ref":"`+ref(keys[1])+`"}`); rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &got) != nil || got.Key != keys[1] {
|
||||
t.Fatalf("an off key's Show: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
// a new address keeps every key, those off too
|
||||
if rec := post("/api/settings/search-api", `{"vendor":"tavily","url":"https://t.example.com"}`); rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := order(list()); len(got) != 3 {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
// to when no provider can search, in their order, and a row to add one. A
|
||||
// SearXNG picked asks for its address; Add sends the API, its key and its
|
||||
// address; Remove takes one away; a key magpie refuses is said in the row,
|
||||
// what was typed kept. A saved key is shown in its row and hidden again, or
|
||||
// copied, as a provider's is (OnurBen on Discord). Every API takes a base URL
|
||||
// what was typed kept. A saved key is shown in its row of the API's keys
|
||||
// and hidden again, or copied, as a provider's is (OnurBen on Discord); a
|
||||
// key typed for an API added before joins its keys (辰林鸭~ on Discord). Every API takes a base URL
|
||||
// of the user's own (#1580), on a line under the key: empty is the vendor's,
|
||||
// and one set shows in the field when its API is picked again, so a new key
|
||||
// alone keeps it. You.com is added with no key, for its free search
|
||||
@@ -28,13 +29,13 @@ const vendors = [
|
||||
];
|
||||
const words = {
|
||||
en: { head: "Web search", name: "Search APIs", none: "No provider can search", add: "Add", remove: "Remove", refused: "Brave Search: 401 bad key", show: "Show", hide: "Hide", copy: "Copy",
|
||||
base: "Base URL, empty for https://api.tavily.com", exaBase: "Base URL, empty for https://api.exa.ai", keep: "A new key, or empty to keep tvly…abcd", youKey: "API key, or empty for its free search" },
|
||||
base: "Base URL, empty for https://api.tavily.com", exaBase: "Base URL, empty for https://api.exa.ai", keep: "Another key for Tavily, or empty to keep its keys", youKey: "API key, or empty for its free search" },
|
||||
zh: { head: "联网搜索", name: "搜索 API", none: "没有能搜索的供应商", add: "添加", remove: "移除", refused: "Brave Search: 401 bad key", show: "显示", hide: "隐藏", copy: "复制",
|
||||
base: "API 地址,留空则用 https://api.tavily.com", exaBase: "API 地址,留空则用 https://api.exa.ai", keep: "新的密钥,留空则保留 tvly…abcd", youKey: "API 密钥,留空则用其免费搜索" },
|
||||
base: "API 地址,留空则用 https://api.tavily.com", exaBase: "API 地址,留空则用 https://api.exa.ai", keep: "Tavily 的另一个密钥,留空则保留它的密钥", youKey: "API 密钥,留空则用其免费搜索" },
|
||||
};
|
||||
|
||||
function serve(lang, posted) {
|
||||
let apis = [{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true }];
|
||||
let apis = [{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true, keyList: [{ ref: "r-abcd", masked: "tvly…abcd" }] }];
|
||||
const settings = () => ({ lang, theme: "light", searchVendors: vendors, searchAPIs: apis });
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
@@ -51,14 +52,18 @@ function serve(lang, posted) {
|
||||
else {
|
||||
// as SetSearchAPI: one of a vendor added before is changed where it
|
||||
// is, keeping its key when none is sent
|
||||
// its keys when none is sent, and a key sent with append after them
|
||||
const was = apis.find((a) => a.vendor === b.vendor);
|
||||
const now = { vendor: b.vendor, name: vendors.find((v) => v.id === b.vendor).name, url: b.url || undefined, key: b.key ? "••••" : was?.key || "", ready: true };
|
||||
const typed = b.key ? [{ ref: "r-" + b.key, masked: "••••" + b.key.slice(-1) }] : [];
|
||||
const keyList = b.append ? [...(was?.keyList || []), ...typed] : b.key ? typed : was?.keyList || [];
|
||||
const now = { vendor: b.vendor, name: vendors.find((v) => v.id === b.vendor).name, url: b.url || undefined, key: keyList.map((k) => k.masked).join(", "), keyList, ready: true };
|
||||
apis = was ? apis.map((a) => (a === was ? now : a)) : [...apis, now];
|
||||
}
|
||||
return json(settings());
|
||||
}
|
||||
if (url.pathname === "/api/settings/search-key") {
|
||||
posted.push({ asked: JSON.parse(r.request().postData()).vendor });
|
||||
const b = JSON.parse(r.request().postData());
|
||||
posted.push({ asked: b.vendor, ref: b.ref });
|
||||
return json({ key: "tvly-dev-0123456789abcd" });
|
||||
}
|
||||
if (url.pathname === "/api/copy") { posted.push({ copied: JSON.parse(r.request().postData()).text }); return json({}); }
|
||||
@@ -180,19 +185,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await head.locator("input.search-key").fill("exa-2");
|
||||
await click(head.locator("button.text", { hasText: w.add }));
|
||||
await page.waitForFunction((n) => document.querySelector("#searchList .search-add input.search-key")?.value === "", null);
|
||||
assert.deepEqual(posted.at(-1), { vendor: "exa", key: "exa-2", url: "https://search.example.com/exa" });
|
||||
assert.deepEqual(posted.at(-1), { vendor: "exa", key: "exa-2", url: "https://search.example.com/exa", append: true });
|
||||
// and with no key typed, the address alone changes, the key kept
|
||||
await url.fill("https://search2.example.com/exa");
|
||||
await click(head.locator("button.text", { hasText: w.add }));
|
||||
await page.waitForFunction(() => [...document.querySelectorAll("#searchList .row.search-api .sub")].at(-1)?.innerText.includes("search2.example.com"));
|
||||
assert.deepEqual(posted.at(-1), { vendor: "exa", key: "", url: "https://search2.example.com/exa" });
|
||||
assert.deepEqual(await list.locator(".row.search-api .name").allInnerTexts(), ["1. Tavily", "2. SearXNG", "3. Exa"]);
|
||||
assert((await list.locator(".row.search-api").nth(2).locator(".sub").innerText()).startsWith("••••"), "Exa's key kept");
|
||||
assert.deepEqual(await list.locator('.row.search-keys[data-vendor="exa"] .acc[data-ref] code').allInnerTexts(), ["••••k", "••••2"], "Exa's keys kept, the second after the first");
|
||||
|
||||
// the saved key: shown, hidden, copied; SearXNG's row has none to show
|
||||
const tavily = list.locator(".row.search-api").first();
|
||||
assert.equal(await list.locator(".row.search-api").nth(1).locator("button.search-eye").count(), 0);
|
||||
assert.equal(await tavily.locator(".sub").innerText(), "tvly…abcd");
|
||||
const tavily = list.locator('.row.search-keys[data-vendor="tavily"] .acc[data-ref="r-abcd"]');
|
||||
const code = tavily.locator("code");
|
||||
assert.equal(await list.locator(".search-unit").nth(1).locator("button.search-eye").count(), 0);
|
||||
assert.equal(await list.locator(".row.search-api").first().locator(".sub").innerText(), "", "the key is in its own row, not the API's");
|
||||
assert.equal(await code.innerText(), "tvly…abcd");
|
||||
const sent = posted.length;
|
||||
// the clicks so far moved nothing; Image generation timeout, drawn
|
||||
// above, puts the saved keys past the window's foot at 420, so the
|
||||
@@ -201,19 +208,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await reach(page, tavily.locator("button.search-eye"));
|
||||
before = await where();
|
||||
await click(tavily.locator("button.search-eye"));
|
||||
await page.waitForFunction(() => document.querySelector("#searchList .row.search-api .sub.revealed"));
|
||||
assert.equal(await tavily.locator(".sub").innerText(), "tvly-dev-0123456789abcd");
|
||||
await page.waitForFunction(() => document.querySelector("#searchList .search-key-list code.revealed"));
|
||||
assert.equal(await code.innerText(), "tvly-dev-0123456789abcd");
|
||||
assert.equal(await tavily.locator("button.search-eye").innerText(), w.hide);
|
||||
assert.equal(await tavily.locator(".sub").evaluate((e) => getComputedStyle(e).webkitUserSelect || getComputedStyle(e).userSelect), "text", "the key shown can be selected");
|
||||
assert.equal(await code.evaluate((e) => getComputedStyle(e).webkitUserSelect || getComputedStyle(e).userSelect), "text", "the key shown can be selected");
|
||||
await click(tavily.locator("button.search-eye"));
|
||||
assert.equal(await tavily.locator(".sub").innerText(), "tvly…abcd");
|
||||
assert.equal(await code.innerText(), "tvly…abcd");
|
||||
assert.equal(await tavily.locator("button.search-eye").innerText(), w.show);
|
||||
await click(tavily.locator("button.search-copy", { hasText: w.copy }));
|
||||
await page.waitForFunction(() => document.querySelector("#searchList .row.search-api .sub")?.innerText === "tvly…abcd");
|
||||
assert.equal(await tavily.locator("button.search-copy").getAttribute("aria-label"), w.copy);
|
||||
await click(tavily.locator("button.search-copy"));
|
||||
// #status may still hold Brave's refusal, so wait for the copy itself
|
||||
for (let i = 0; i < 100 && !posted.some((p) => p.copied); i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posted.slice(sent), [{ asked: "tavily" }, { asked: "tavily" }, { copied: "tvly-dev-0123456789abcd" }]);
|
||||
assert.equal(await tavily.locator(".sub").innerText(), "tvly…abcd", "copying shows nothing");
|
||||
assert.deepEqual(posted.slice(sent), [{ asked: "tavily", ref: "r-abcd" }, { asked: "tavily", ref: "r-abcd" }, { copied: "tvly-dev-0123456789abcd" }]);
|
||||
assert.equal(await code.innerText(), "tvly…abcd", "copying shows nothing");
|
||||
posted.splice(sent);
|
||||
|
||||
// Remove
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings' Web search section, a search API's keys as a list (辰林鸭~ on
|
||||
// Discord: "only one Tavily key can be entered"): each key on a row of its
|
||||
// own, masked, with its tick, Show, Copy and Remove; a key switched off
|
||||
// stays, dimmed, and says so; a key refused lately says why and until when
|
||||
// it is asked last. Several are added at once, pasted split by commas or
|
||||
// lines, and the list is put in order with Alt+↑/↓. Every change is sent
|
||||
// by the key's ref, never the key. In five languages, Chromium and WebKit,
|
||||
// 1100px 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, reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
const I18N = (() => {
|
||||
const src = require("node:fs").readFileSync(path.join(assets, "i18n.js"), "utf8");
|
||||
return new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")();
|
||||
})();
|
||||
const tr = (lang, s, vars = {}) => {
|
||||
const got = lang === "en" ? s : I18N[lang][s];
|
||||
assert(got, `"${s}" has no ${lang} translation`);
|
||||
return got.replace(/\{(\w+)\}/g, (_, k) => String(vars[k]));
|
||||
};
|
||||
|
||||
const vendors = [{ id: "tavily", name: "Tavily", keysURL: "https://app.tavily.com/home", base: "https://api.tavily.com" }];
|
||||
const restUntil = new Date(Date.now() + 40 * 60 * 1000).toISOString();
|
||||
const mask = (k) => "tvly-…" + k.slice(-4);
|
||||
const refOf = (k) => "ref-" + k.slice(-4);
|
||||
|
||||
function serve(lang, posted) {
|
||||
// as the real list: keys in order, each on or off; the rest is the
|
||||
// gateway's, for a key on
|
||||
let list = [
|
||||
{ key: "tvly-dev-first-1111" },
|
||||
{ key: "tvly-dev-limit-2222", rest: "rate limited" },
|
||||
{ key: "tvly-dev-spare-3333", off: true },
|
||||
];
|
||||
const settings = () => ({
|
||||
lang, theme: "light", searchVendors: vendors,
|
||||
searchAPIs: [{
|
||||
vendor: "tavily", name: "Tavily", ready: true, keys: list.filter((k) => !k.off).length,
|
||||
key: list.filter((k) => !k.off).map((k) => mask(k.key)).join(", "),
|
||||
keyList: list.map((k) => ({ ref: refOf(k.key), masked: mask(k.key), off: k.off || undefined, ...(k.rest && !k.off ? { rest: k.rest, restUntil } : {}) })),
|
||||
}],
|
||||
});
|
||||
const at = (ref) => list.findIndex((k) => refOf(k.key) === ref);
|
||||
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-keys") {
|
||||
const b = JSON.parse(r.request().postData());
|
||||
posted.push(b);
|
||||
let added = 0, had = 0;
|
||||
if (b.arrange) list = b.arrange.map((ref) => list[at(ref)]);
|
||||
else if (b.add) {
|
||||
for (const k of b.add.split(/[\s,;]+/).filter(Boolean)) {
|
||||
if (list.some((x) => x.key === k)) had++;
|
||||
else { list.push({ key: k }); added++; }
|
||||
}
|
||||
} else if (b.remove) list.splice(at(b.ref), 1);
|
||||
else if ("on" in b) list[at(b.ref)] = { ...list[at(b.ref)], off: !b.on };
|
||||
return json({ settings: settings(), added, had });
|
||||
}
|
||||
if (url.pathname === "/api/settings/search-key") {
|
||||
const b = JSON.parse(r.request().postData());
|
||||
posted.push({ asked: b });
|
||||
return json({ key: list[at(b.ref)].key });
|
||||
}
|
||||
if (url.pathname === "/api/copy") { posted.push({ copied: JSON.parse(r.request().postData()).text }); return json({}); }
|
||||
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 LANGS) for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: a search API's keys are a list, each switched, shown, removed and moved`, 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 }, reducedMotion: "reduce" })).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 keys = page.locator('#searchList .row.search-keys[data-vendor="tavily"]');
|
||||
await keys.waitFor();
|
||||
const rows = keys.locator(".search-key-list .acc[data-ref]");
|
||||
const codes = () => rows.locator("code").allInnerTexts();
|
||||
assert.deepEqual(await codes(), ["tvly-…1111", "tvly-…2222", "tvly-…3333"]);
|
||||
// nothing in the page holds a whole key
|
||||
assert.equal(await page.evaluate(() => document.body.innerHTML.includes("tvly-dev-")), false);
|
||||
assert.deepEqual(await rows.evaluateAll((rs) => rs.map((r) => r.className.includes("off") ? "off" : "on")), ["on", "on", "off"]);
|
||||
assert.deepEqual(await rows.locator("button.tick").evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-pressed"))), ["true", "true", "false"]);
|
||||
assert.equal(await rows.nth(0).locator("button.tick").getAttribute("aria-label"), tr(lang, "Stop using this key"));
|
||||
assert.equal(await rows.nth(2).locator("button.tick").getAttribute("aria-label"), tr(lang, "Use this key too"));
|
||||
// why a key is asked last, and until when; one off says Off
|
||||
const until = await page.evaluate((u) => hhmm(u), restUntil);
|
||||
assert.equal(await rows.nth(1).locator(".key-rest").innerText(), tr(lang, "asked last until {time}: {why}", { time: until, why: tr(lang, "rate limited") }));
|
||||
assert.equal(await rows.locator(".key-rest").count(), 1);
|
||||
assert.equal(await rows.nth(2).locator(".key-state").innerText(), tr(lang, "Off"));
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
const past = await keys.evaluate((r) => [...r.querySelectorAll("button, code, .key-rest")]
|
||||
.filter((e) => e.getBoundingClientRect().right > innerWidth + 0.5).map((e) => e.className + " " + e.textContent));
|
||||
assert.deepEqual(past, [], "nothing past the window's edge");
|
||||
|
||||
const where = () => page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop, document.querySelector("#view-settings")?.scrollTop]);
|
||||
// reached as a reader does (the wheel), then clicked where it is:
|
||||
// the click itself never moves the page. Settings is drawn again
|
||||
// after each change, so the box is taken from the row that stays.
|
||||
const stays = [];
|
||||
const click = async (loc) => {
|
||||
await reach(page, loc);
|
||||
const b = await loc.boundingBox();
|
||||
assert(b, "the button is in the page");
|
||||
const at = await where();
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
stays.push(async () => assert.deepEqual(await where(), at, "a click doesn't scroll"));
|
||||
};
|
||||
const drawn = (want) => page.waitForFunction((w) => [...document.querySelectorAll('#searchList .search-keys[data-vendor="tavily"] .acc[data-ref] code')].map((c) => c.textContent).join() === w, want.join());
|
||||
const settle = async () => { for (const f of stays.splice(0)) await f(); };
|
||||
|
||||
// Show reads that one key, by its ref; Hide masks it again
|
||||
await click(rows.nth(2).locator("button.search-eye"));
|
||||
await page.waitForFunction(() => document.querySelector("#searchList .search-key-list code.revealed"));
|
||||
assert.equal(await rows.nth(2).locator("code").innerText(), "tvly-dev-spare-3333");
|
||||
assert.equal(await rows.nth(2).locator("button.search-eye").innerText(), tr(lang, "Hide"));
|
||||
await click(rows.nth(2).locator("button.search-eye"));
|
||||
assert.equal(await rows.nth(2).locator("code").innerText(), "tvly-…3333");
|
||||
await settle();
|
||||
await click(rows.nth(0).locator("button.search-copy"));
|
||||
for (let i = 0; i < 100 && !posted.some((p) => p.copied); i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posted.splice(0), [{ asked: { vendor: "tavily", ref: "ref-3333" } }, { asked: { vendor: "tavily", ref: "ref-1111" } }, { copied: "tvly-dev-first-1111" }]);
|
||||
|
||||
// switched on, then the first off
|
||||
await click(rows.nth(2).locator("button.tick"));
|
||||
await page.waitForFunction(() => !document.querySelector('#searchList .search-keys[data-vendor="tavily"] .acc.off'));
|
||||
await click(rows.nth(0).locator("button.tick"));
|
||||
await page.waitForFunction(() => document.querySelector('#searchList .search-keys[data-vendor="tavily"] .acc[data-ref="ref-1111"]')?.classList.contains("off"));
|
||||
assert.deepEqual(posted.splice(0), [{ vendor: "tavily", ref: "ref-3333", on: true }, { vendor: "tavily", ref: "ref-1111", on: false }]);
|
||||
await settle();
|
||||
|
||||
// several pasted at once, one already there: said how many
|
||||
await click(keys.locator(".search-key-list .acc.add"));
|
||||
const field = keys.locator("input.search-key-new");
|
||||
await field.waitFor();
|
||||
await settle();
|
||||
assert.equal(await field.getAttribute("type"), "password", "a key typed is masked");
|
||||
assert.equal(await field.getAttribute("placeholder"), tr(lang, "Paste a key, or several split by commas or lines"));
|
||||
await field.fill("tvly-dev-new-4444, tvly-dev-first-1111, tvly-dev-more-5555");
|
||||
await field.press("Enter");
|
||||
await drawn(["tvly-…1111", "tvly-…2222", "tvly-…3333", "tvly-…4444", "tvly-…5555"]);
|
||||
assert.deepEqual(posted.splice(0), [{ vendor: "tavily", add: "tvly-dev-new-4444, tvly-dev-first-1111, tvly-dev-more-5555" }]);
|
||||
await page.waitForFunction((w) => document.querySelector("#status")?.textContent === w, tr(lang, "{n} keys added, {m} already there", { n: 2, m: 1 }));
|
||||
|
||||
// Alt+↓ on the second puts it third: the order is sent as refs
|
||||
await rows.nth(1).focus();
|
||||
await page.keyboard.press("Alt+ArrowDown");
|
||||
await drawn(["tvly-…1111", "tvly-…3333", "tvly-…2222", "tvly-…4444", "tvly-…5555"]);
|
||||
assert.deepEqual(posted.splice(0), [{ vendor: "tavily", arrange: ["ref-1111", "ref-3333", "ref-2222", "ref-4444", "ref-5555"] }]);
|
||||
await page.waitForFunction(() => document.activeElement?.dataset?.ref === "ref-2222");
|
||||
|
||||
// Remove
|
||||
await click(rows.nth(3).locator("button.search-key-remove"));
|
||||
await drawn(["tvly-…1111", "tvly-…3333", "tvly-…2222", "tvly-…5555"]);
|
||||
assert.deepEqual(posted.splice(0), [{ vendor: "tavily", ref: "ref-4444", remove: true }]);
|
||||
assert.equal(await rows.nth(0).locator("button.search-key-remove").innerText(), tr(lang, "Remove"));
|
||||
|
||||
await settle();
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
assert.equal(await page.evaluate(() => document.body.innerHTML.includes("tvly-dev-")), false, "no key left in the page");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,12 @@
|
||||
// (SlouchyQuill on Discord, after dsh-tavily-pool): under it a row of its
|
||||
// keys, In turn (the default) or In order, sent as pick "turns" or "order";
|
||||
// for Tavily, what each key has used of its limit, read once as the page
|
||||
// is drawn and again, fresh, on Check again. Each key is shown masked; a
|
||||
// read that failed says Unknown and why, never 0; a key used up says so,
|
||||
// and one asked last says until when and why. An API with one key that
|
||||
// magpie can't read gets no row. In five languages, Chromium and WebKit,
|
||||
// 1100px and 420px wide, with the API faked.
|
||||
// is drawn and again, fresh, on Check again, each on its key's line of the
|
||||
// list (辰林鸭~ on Discord). Each key is shown masked; a read that failed
|
||||
// says Unknown and why, never 0; a key used up says so, and one asked last
|
||||
// says until when and why. An API with one key that magpie can't read
|
||||
// lists it with no choice of order and no Check again. In five languages,
|
||||
// Chromium and WebKit, 1100px and 420px wide, with the API faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -34,9 +35,14 @@ const vendors = [
|
||||
];
|
||||
const restUntil = new Date(Date.now() + 50 * 60 * 1000).toISOString();
|
||||
const quotas = (used) => [
|
||||
{ key: "tvly-…aaaa", known: true, used, limit: 1000, of: "key" },
|
||||
{ key: "tvly-…bbbb", known: true, used: 1000, limit: 1000, of: "plan", plan: "Researcher", usedUp: true, resting: "used up", restUntil },
|
||||
{ key: "tvly-…cccc", known: false, used: 0, limit: 0, err: "401 Unauthorized" },
|
||||
{ key: "tvly-…aaaa", ref: "ra", known: true, used, limit: 1000, of: "key" },
|
||||
{ key: "tvly-…bbbb", ref: "rb", known: true, used: 1000, limit: 1000, of: "plan", plan: "Researcher", usedUp: true, resting: "used up", restUntil },
|
||||
{ key: "tvly-…cccc", ref: "rc", known: false, used: 0, limit: 0, err: "401 Unauthorized" },
|
||||
];
|
||||
const keyList = [
|
||||
{ ref: "ra", masked: "tvly-…aaaa" },
|
||||
{ ref: "rb", masked: "tvly-…bbbb", rest: "used up", restUntil },
|
||||
{ ref: "rc", masked: "tvly-…cccc" },
|
||||
];
|
||||
|
||||
function serve(lang, posted) {
|
||||
@@ -45,8 +51,8 @@ function serve(lang, posted) {
|
||||
const settings = () => ({
|
||||
lang, theme: "light", searchVendors: vendors,
|
||||
searchAPIs: [
|
||||
{ vendor: "tavily", name: "Tavily", key: "tvly-…aaaa, tvly-…bbbb, tvly-…cccc", keys: 3, quota: true, pick, ready: true },
|
||||
{ vendor: "brave", name: "Brave Search", key: "BSA…wxyz", keys: 1, ready: true },
|
||||
{ vendor: "tavily", name: "Tavily", key: "tvly-…aaaa, tvly-…bbbb, tvly-…cccc", keys: 3, quota: true, pick, ready: true, keyList },
|
||||
{ vendor: "brave", name: "Brave Search", key: "BSA…wxyz", keys: 1, ready: true, keyList: [{ ref: "rw", masked: "BSA…wxyz" }] },
|
||||
],
|
||||
});
|
||||
return async (r) => {
|
||||
@@ -93,23 +99,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=settings&tab=models");
|
||||
await settingsDrawn(page);
|
||||
const keys = page.locator("#searchList .row.search-keys");
|
||||
await keys.first().waitFor();
|
||||
// Tavily's only: Brave has one key and no quota magpie can read
|
||||
assert.equal(await keys.count(), 1);
|
||||
assert.equal(await keys.getAttribute("data-vendor"), "tavily");
|
||||
const keys = page.locator('#searchList .row.search-keys[data-vendor="tavily"]');
|
||||
await keys.waitFor();
|
||||
assert.equal(await keys.locator(".name").innerText(), tr(lang, "Keys of {name}", { name: "Tavily" }));
|
||||
// Brave's one key is listed, with no order to pick and nothing to read
|
||||
const brave = page.locator('#searchList .row.search-keys[data-vendor="brave"]');
|
||||
assert.deepEqual(await brave.locator(".acc[data-ref] code").allInnerTexts(), ["BSA…wxyz"]);
|
||||
assert.equal(await brave.locator(".segs, button.search-quota-again, .key-quota").count(), 0);
|
||||
|
||||
const lines = keys.locator(".search-quota .quota-key");
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .quota-key").length === 3);
|
||||
const lines = keys.locator(".search-key-list .acc[data-ref]");
|
||||
await page.waitForFunction(() => document.querySelectorAll('#searchList .search-keys[data-vendor="tavily"] .key-quota .used').length === 3);
|
||||
assert.deepEqual(await lines.locator("code").allInnerTexts(), ["tvly-…aaaa", "tvly-…bbbb", "tvly-…cccc"]);
|
||||
assert.equal(await lines.nth(0).locator(".used").innerText(), tr(lang, "{used} of {limit} used", { used: "812", limit: await page.evaluate(() => (1000).toLocaleString(intlLang())) }));
|
||||
// used up: said, with the plan it is of and why it is asked last
|
||||
assert.equal(await lines.nth(1).locator(".warn").last().innerText(), tr(lang, "used up"));
|
||||
const note = await lines.nth(1).locator(".faint").innerText();
|
||||
assert.equal(await lines.nth(1).locator(".key-quota .warn").last().innerText(), tr(lang, "used up"));
|
||||
const note = await lines.nth(1).locator(".key-quota .faint").innerText();
|
||||
assert(note.includes(tr(lang, "{plan} plan, shared by its account's keys", { plan: "Researcher" })), note);
|
||||
const until = await page.evaluate((u) => new Date(u).toLocaleTimeString(intlLang(), { hour: "2-digit", minute: "2-digit" }), restUntil);
|
||||
assert(note.includes(tr(lang, "asked last until {time}: {why}", { time: until, why: tr(lang, "used up") })), note);
|
||||
assert.equal(await lines.nth(1).locator(".key-rest").innerText(), tr(lang, "asked last until {time}: {why}", { time: until, why: tr(lang, "used up") }));
|
||||
assert.equal(await lines.locator(".key-rest").count(), 1, "only the key resting says so");
|
||||
// a failed read: unknown and why, never 0
|
||||
const unknown = await lines.nth(2).locator(".used").innerText();
|
||||
assert.equal(unknown, tr(lang, "Unknown: {why}", { why: "401 Unauthorized" }));
|
||||
@@ -118,7 +126,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.deepEqual(posted, [{ quota: { vendor: "tavily", fresh: false } }]);
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
// the page clips what is past its edge, so each control is measured
|
||||
const past = await keys.evaluate((r) => [...r.querySelectorAll("button, code, .used")]
|
||||
const past = await keys.evaluate((r) => [...r.querySelectorAll("button, code, .used, .key-rest")]
|
||||
.filter((e) => e.getBoundingClientRect().right > innerWidth + 0.5).map((e) => e.textContent));
|
||||
assert.deepEqual(past, [], "nothing past the window's edge");
|
||||
|
||||
@@ -137,21 +145,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const before = await where();
|
||||
// Check again: read fresh
|
||||
await click(keys.locator("button.search-quota-again", { hasText: tr(lang, "Check again") }));
|
||||
await page.waitForFunction(() => /813/.test(document.querySelector("#searchList .search-keys .quota-key .used")?.innerText || ""));
|
||||
await page.waitForFunction(() => /813/.test(document.querySelector('#searchList .search-keys[data-vendor="tavily"] .key-quota .used')?.innerText || ""));
|
||||
assert.deepEqual(posted.at(-1), { quota: { vendor: "tavily", fresh: true } });
|
||||
// In order, then In turn again
|
||||
const segs = keys.locator(".segs .opt");
|
||||
assert.deepEqual(await segs.allInnerTexts(), [tr(lang, "In turn"), tr(lang, "In order")]);
|
||||
assert.equal(await segs.nth(0).getAttribute("aria-pressed"), "true");
|
||||
await click(segs.nth(1));
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .segs .opt")[1]?.getAttribute("aria-pressed") === "true");
|
||||
await page.waitForFunction(() => document.querySelectorAll('#searchList .search-keys[data-vendor="tavily"] .segs .opt')[1]?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(posted.filter((p) => p.pick), [{ vendor: "tavily", pick: "order" }]);
|
||||
await click(keys.locator(".segs .opt").nth(0));
|
||||
await page.waitForFunction(() => document.querySelectorAll("#searchList .search-keys .segs .opt")[0]?.getAttribute("aria-pressed") === "true");
|
||||
await page.waitForFunction(() => document.querySelectorAll('#searchList .search-keys[data-vendor="tavily"] .segs .opt')[0]?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(posted.filter((p) => p.pick), [{ vendor: "tavily", pick: "order" }, { vendor: "tavily", pick: "turns" }]);
|
||||
// redrawn with the same keys, it isn't read again
|
||||
assert.equal(posted.filter((p) => p.quota).length, 2);
|
||||
assert.equal(await keys.locator(".quota-key").count(), 3);
|
||||
assert.equal(await keys.locator(".key-quota .used").count(), 3);
|
||||
assert.deepEqual(await where(), before, "a click doesn't scroll");
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
@@ -24,9 +24,9 @@ const off = { en: "Off", zh: "关闭", ja: "オフ", de: "Aus" };
|
||||
|
||||
function serve(lang, posted, opts) {
|
||||
let apis = [
|
||||
{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true },
|
||||
{ vendor: "exa", name: "Exa", key: "exa…1234", ready: true, off: true },
|
||||
{ vendor: "brave", name: "Brave Search", key: "bsa…9876", ready: true, keys: 2 },
|
||||
{ vendor: "tavily", name: "Tavily", key: "tvly…abcd", ready: true, keyList: [{ ref: "t1", masked: "tvly…abcd" }] },
|
||||
{ vendor: "exa", name: "Exa", key: "exa…1234", ready: true, off: true, keyList: [{ ref: "e1", masked: "exa…1234" }] },
|
||||
{ vendor: "brave", name: "Brave Search", key: "bsa…9876", ready: true, keys: 2, keyList: [{ ref: "b1", masked: "bsa…9876" }, { ref: "b2", masked: "bsa…5432" }] },
|
||||
];
|
||||
const settings = () => ({ lang, theme: "light", searchVendors: vendors, searchAPIs: apis, searchProvider: "OpenAI" });
|
||||
return async (r) => {
|
||||
@@ -86,9 +86,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
// Exa is off: dimmed, says so, its switch unchecked; the others on
|
||||
const exa = units.nth(1);
|
||||
assert.equal(await exa.evaluate((u) => u.classList.contains("off")), true);
|
||||
assert((await exa.locator(".row.search-api .sub").innerText()).startsWith(off[lang]), await exa.locator(".sub").innerText());
|
||||
assert((await exa.locator(".row.search-api .sub").innerText()).startsWith(off[lang]), await exa.locator(".row.search-api .sub").innerText());
|
||||
assert.deepEqual(await list.locator("button.search-on").evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-checked"))), ["true", "false", "true"]);
|
||||
assert(Number(await exa.locator(".row .who").evaluate((e) => getComputedStyle(e).opacity)) < 1, "an API off is dimmed");
|
||||
assert(Number(await exa.locator(".row.search-api .who").evaluate((e) => getComputedStyle(e).opacity)) < 1, "an API off is dimmed");
|
||||
assert.equal(await exa.locator("button.search-on").evaluate((e) => getComputedStyle(e).opacity), "1", "its switch isn't");
|
||||
assert.equal(await page.locator("#searchFirstRow").count(), 1);
|
||||
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "nothing wider than the window");
|
||||
|
||||
@@ -89,6 +89,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
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");
|
||||
assert.equal(await list.locator(".row.search-keys").count(), 0, "no keys to list");
|
||||
|
||||
// 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());
|
||||
|
||||
@@ -6,6 +6,8 @@ package provider
|
||||
// kept in providers.json beside the providers, their keys with theirs.
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"slices"
|
||||
@@ -18,8 +20,14 @@ import (
|
||||
type SearchAPI struct {
|
||||
Vendor string `json:"vendor"` // one of SearchVendors
|
||||
// Key is its key, or several separated by commas (Keys), each tried
|
||||
// when the one before is refused (#1477).
|
||||
// when the one before is refused (#1477): the keys that are on, so a
|
||||
// magpie that knows no KeyList asks just those.
|
||||
Key string `json:"key,omitempty"`
|
||||
// KeyList is every key in the list's order, those switched off too
|
||||
// (辰林鸭~ on Discord: keys added, removed, put in order and switched
|
||||
// off one by one). It is kept only while a key is off; Key alone is
|
||||
// the list when every key is on (SearchKeys).
|
||||
KeyList []SearchKey `json:"keyList,omitempty"`
|
||||
// Pick is how a search picks among several keys: "" takes them in
|
||||
// turn (SearchPickTurns), each search the next one; SearchPickOrder
|
||||
// asks the first until it is refused, then the next (SlouchyQuill on
|
||||
@@ -138,6 +146,88 @@ func (a SearchAPI) Keys() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// SearchKey is one key in a search API's list: off, it is kept and never
|
||||
// asked.
|
||||
type SearchKey struct {
|
||||
Key string `json:"key"`
|
||||
Off bool `json:"off,omitempty"`
|
||||
}
|
||||
|
||||
// SearchKeyRef is how a page names one key without holding it: a hash
|
||||
// of it, the same on every computer.
|
||||
func SearchKeyRef(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
// SearchKeys is every key of the API in its list's order, each on or
|
||||
// off. KeyList is the list while its keys that are on are Key's; a Key
|
||||
// written by something that knows no KeyList (an older magpie, or one
|
||||
// it syncs with) wins: its keys are the ones on, in its order, and a
|
||||
// key the list has off that Key doesn't name stays, off, after them.
|
||||
func (a SearchAPI) SearchKeys() []SearchKey {
|
||||
on := a.Keys()
|
||||
var listOn []string
|
||||
for _, k := range a.KeyList {
|
||||
if !k.Off {
|
||||
listOn = append(listOn, k.Key)
|
||||
}
|
||||
}
|
||||
out := []SearchKey{}
|
||||
if len(a.KeyList) > 0 && slices.Equal(listOn, on) {
|
||||
for _, k := range a.KeyList {
|
||||
if k.Key != "" && !slices.ContainsFunc(out, func(x SearchKey) bool { return x.Key == k.Key }) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
for _, k := range on {
|
||||
out = append(out, SearchKey{Key: k})
|
||||
}
|
||||
for _, k := range a.KeyList {
|
||||
if k.Off && k.Key != "" && !slices.ContainsFunc(out, func(x SearchKey) bool { return x.Key == k.Key }) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// putKeys makes list the API's keys: Key the ones on, KeyList the whole
|
||||
// list while one is off.
|
||||
func (a *SearchAPI) putKeys(list []SearchKey) {
|
||||
var on []string
|
||||
off := false
|
||||
for _, k := range list {
|
||||
if k.Off {
|
||||
off = true
|
||||
} else {
|
||||
on = append(on, k.Key)
|
||||
}
|
||||
}
|
||||
a.Key, a.KeyList = strings.Join(on, ","), nil
|
||||
if off {
|
||||
a.KeyList = slices.Clone(list)
|
||||
}
|
||||
}
|
||||
|
||||
// WithoutKeys is the API with no key, on or off: as a backup or a sync
|
||||
// that leaves keys out carries it.
|
||||
func (a SearchAPI) WithoutKeys() SearchAPI {
|
||||
a.Key, a.KeyList = "", nil
|
||||
return a
|
||||
}
|
||||
|
||||
// HasKeys is whether it holds a key, on or off.
|
||||
func (a SearchAPI) HasKeys() bool { return a.Key != "" || len(a.KeyList) > 0 }
|
||||
|
||||
// KeepKeysOf gives a, which came with no key (WithoutKeys), b's keys.
|
||||
func (a *SearchAPI) KeepKeysOf(b SearchAPI) {
|
||||
if !a.HasKeys() {
|
||||
a.Key, a.KeyList = b.Key, slices.Clone(b.KeyList)
|
||||
}
|
||||
}
|
||||
|
||||
// MaskedKey is Key as shown: each of its keys masked (MaskSearchKey), so a
|
||||
// list of them shows no more of any one than a single key does.
|
||||
func (a SearchAPI) MaskedKey() string {
|
||||
@@ -274,7 +364,9 @@ func SetSearchAPI(a SearchAPI) error {
|
||||
}
|
||||
i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor })
|
||||
if i >= 0 && a.Key == "" {
|
||||
a.Key = f.Searches[i].Key
|
||||
a.Key, a.KeyList = f.Searches[i].Key, f.Searches[i].KeyList
|
||||
} else {
|
||||
a.KeyList = nil // keys given are the list, every one on
|
||||
}
|
||||
if i >= 0 {
|
||||
a.Off, a.Mix = f.Searches[i].Off, f.Searches[i].Mix
|
||||
@@ -405,8 +497,8 @@ func RestoreSearchAPIs(as []SearchAPI) error {
|
||||
if _, ok := SearchVendorOf(a.Vendor); !ok || slices.ContainsFunc(out, func(x SearchAPI) bool { return x.Vendor == a.Vendor }) {
|
||||
continue
|
||||
}
|
||||
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 && a.Key == "" {
|
||||
a.Key = f.Searches[i].Key
|
||||
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 {
|
||||
a.KeepKeysOf(f.Searches[i])
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
@@ -431,8 +523,8 @@ func MirrorSearchAPIs(as []SearchAPI) error {
|
||||
if _, ok := SearchVendorOf(a.Vendor); !ok {
|
||||
continue
|
||||
}
|
||||
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 && a.Key == "" {
|
||||
a.Key = f.Searches[i].Key
|
||||
if i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == a.Vendor }); i >= 0 {
|
||||
a.KeepKeysOf(f.Searches[i])
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
@@ -442,3 +534,125 @@ func MirrorSearchAPIs(as []SearchAPI) error {
|
||||
f.Searches = out
|
||||
return store(f)
|
||||
}
|
||||
|
||||
// editSearchKeys changes the vendor's list of keys with edit and saves
|
||||
// it. A list left with no key on, for an API that needs one, is refused:
|
||||
// the API's own switch or Remove is for that.
|
||||
func editSearchKeys(vendor string, edit func([]SearchKey) ([]SearchKey, error)) error {
|
||||
f, err := read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(f.Searches, func(x SearchAPI) bool { return x.Vendor == vendor })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("no %s search API is set up", vendor)
|
||||
}
|
||||
a := f.Searches[i]
|
||||
list, err := edit(a.SearchKeys())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, _ := SearchVendorOf(vendor)
|
||||
if !v.KeyOptional && v.Auth == "" && !slices.ContainsFunc(list, func(k SearchKey) bool { return !k.Off }) {
|
||||
return fmt.Errorf("%s needs a key on: switch the API off, or remove it, instead", a.Name())
|
||||
}
|
||||
a.putKeys(list)
|
||||
f.Searches[i] = a
|
||||
return store(f)
|
||||
}
|
||||
|
||||
// searchKeyAt is the index in list of the key ref names.
|
||||
func searchKeyAt(list []SearchKey, ref string) (int, error) {
|
||||
i := slices.IndexFunc(list, func(k SearchKey) bool { return SearchKeyRef(k.Key) == ref })
|
||||
if i < 0 {
|
||||
return 0, fmt.Errorf("no such key: it was removed or changed")
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// AddSearchKeys puts the keys in text (one, or several separated by
|
||||
// commas, spaces or lines) after the vendor's, on; one it has already
|
||||
// is counted in had and left as it is.
|
||||
func AddSearchKeys(vendor, text string) (added, had int, err error) {
|
||||
keys := SearchAPI{Key: text}.Keys()
|
||||
if len(keys) == 0 {
|
||||
return 0, 0, fmt.Errorf("no key given")
|
||||
}
|
||||
err = editSearchKeys(vendor, func(list []SearchKey) ([]SearchKey, error) {
|
||||
added, had = 0, 0
|
||||
for _, k := range keys {
|
||||
if slices.ContainsFunc(list, func(x SearchKey) bool { return x.Key == k }) {
|
||||
had++
|
||||
continue
|
||||
}
|
||||
list = append(list, SearchKey{Key: k})
|
||||
added++
|
||||
}
|
||||
return list, nil
|
||||
})
|
||||
return added, had, err
|
||||
}
|
||||
|
||||
// RemoveSearchKey takes one key out of the vendor's list.
|
||||
func RemoveSearchKey(vendor, ref string) error {
|
||||
return editSearchKeys(vendor, func(list []SearchKey) ([]SearchKey, error) {
|
||||
i, err := searchKeyAt(list, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return slices.Delete(list, i, i+1), nil
|
||||
})
|
||||
}
|
||||
|
||||
// SwitchSearchKey switches one key on or off, keeping its place.
|
||||
func SwitchSearchKey(vendor, ref string, on bool) error {
|
||||
return editSearchKeys(vendor, func(list []SearchKey) ([]SearchKey, error) {
|
||||
i, err := searchKeyAt(list, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list[i].Off = !on
|
||||
return list, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ArrangeSearchKeys puts the vendor's keys in the order of refs; one not
|
||||
// named keeps its place after them, and a ref of no key is refused, so an
|
||||
// order sent from a page drawn before a key was removed changes nothing.
|
||||
func ArrangeSearchKeys(vendor string, refs []string) error {
|
||||
return editSearchKeys(vendor, func(list []SearchKey) ([]SearchKey, error) {
|
||||
out := make([]SearchKey, 0, len(list))
|
||||
for _, ref := range refs {
|
||||
i, err := searchKeyAt(list, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if slices.ContainsFunc(out, func(k SearchKey) bool { return k.Key == list[i].Key }) {
|
||||
return nil, fmt.Errorf("a key is named twice")
|
||||
}
|
||||
out = append(out, list[i])
|
||||
}
|
||||
for _, k := range list {
|
||||
if !slices.ContainsFunc(out, func(x SearchKey) bool { return x.Key == k.Key }) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
|
||||
// SearchKeyOf is the vendor's key that ref names, on or off.
|
||||
func SearchKeyOf(vendor, ref string) (string, error) {
|
||||
for _, a := range load().Searches {
|
||||
if a.Vendor != vendor {
|
||||
continue
|
||||
}
|
||||
list := a.SearchKeys()
|
||||
i, err := searchKeyAt(list, ref)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return list[i].Key, nil
|
||||
}
|
||||
return "", fmt.Errorf("no %s search API is set up", vendor)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func storedTavily(t *testing.T) SearchAPI {
|
||||
t.Helper()
|
||||
for _, a := range StoredSearchAPIs() {
|
||||
if a.Vendor == "tavily" {
|
||||
return a
|
||||
}
|
||||
}
|
||||
t.Fatal("no tavily")
|
||||
return SearchAPI{}
|
||||
}
|
||||
|
||||
// A search API's keys are a list (辰林鸭~ on Discord): added one or several
|
||||
// at once, switched off one by one and kept, put in order and removed,
|
||||
// each named by its ref. Key stays the keys that are on, so the gateway
|
||||
// and an older magpie never ask one switched off; the list is written
|
||||
// only while a key is off.
|
||||
func TestSearchKeyList(t *testing.T) {
|
||||
claudeHome(t)
|
||||
if err := SetSearchAPI(SearchAPI{Vendor: "tavily", Key: "tvly-a, tvly-b"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a key or a list saved before carries over as it was, every key on
|
||||
a := storedTavily(t)
|
||||
if want := []SearchKey{{Key: "tvly-a"}, {Key: "tvly-b"}}; !reflect.DeepEqual(a.SearchKeys(), want) || a.KeyList != nil {
|
||||
t.Fatalf("old keys: %+v, list %+v", a.SearchKeys(), a.KeyList)
|
||||
}
|
||||
added, had, err := AddSearchKeys("tavily", "tvly-b\ntvly-c;tvly-d")
|
||||
if err != nil || added != 2 || had != 1 {
|
||||
t.Fatalf("added %d, had %d, %v", added, had, err)
|
||||
}
|
||||
ref := SearchKeyRef
|
||||
if err := SwitchSearchKey("tavily", ref("tvly-b"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a = storedTavily(t)
|
||||
if a.Key != "tvly-a,tvly-c,tvly-d" || !reflect.DeepEqual(a.Keys(), []string{"tvly-a", "tvly-c", "tvly-d"}) {
|
||||
t.Fatalf("a key switched off is still asked: %q", a.Key)
|
||||
}
|
||||
if want := []SearchKey{{Key: "tvly-a"}, {Key: "tvly-b", Off: true}, {Key: "tvly-c"}, {Key: "tvly-d"}}; !reflect.DeepEqual(a.SearchKeys(), want) {
|
||||
t.Fatalf("list %+v", a.SearchKeys())
|
||||
}
|
||||
if k, err := SearchKeyOf("tavily", ref("tvly-b")); err != nil || k != "tvly-b" {
|
||||
t.Fatalf("an off key's value: %q %v", k, err)
|
||||
}
|
||||
// put in order: those named first, the rest after in their places
|
||||
if err := ArrangeSearchKeys("tavily", []string{ref("tvly-d"), ref("tvly-b")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a = storedTavily(t)
|
||||
if want := []SearchKey{{Key: "tvly-d"}, {Key: "tvly-b", Off: true}, {Key: "tvly-a"}, {Key: "tvly-c"}}; !reflect.DeepEqual(a.SearchKeys(), want) || a.Key != "tvly-d,tvly-a,tvly-c" {
|
||||
t.Fatalf("arranged %+v, %q", a.SearchKeys(), a.Key)
|
||||
}
|
||||
for _, bad := range [][]string{{ref("tvly-a"), ref("tvly-a")}, {ref("tvly-zz")}} {
|
||||
if err := ArrangeSearchKeys("tavily", bad); err == nil {
|
||||
t.Errorf("order %v taken", bad)
|
||||
}
|
||||
}
|
||||
if err := RemoveSearchKey("tavily", ref("tvly-a")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := RemoveSearchKey("tavily", ref("tvly-a")); err == nil {
|
||||
t.Error("a key removed twice")
|
||||
}
|
||||
// the last key on can't be switched off or removed: the API's own
|
||||
// switch, or Remove, is for that
|
||||
if err := SwitchSearchKey("tavily", ref("tvly-d"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SwitchSearchKey("tavily", ref("tvly-c"), false); err == nil || !strings.Contains(err.Error(), "needs a key on") {
|
||||
t.Fatalf("every key off: %v", err)
|
||||
}
|
||||
if err := RemoveSearchKey("tavily", ref("tvly-c")); err == nil {
|
||||
t.Fatal("the last key on removed")
|
||||
}
|
||||
if a := storedTavily(t); a.Key != "tvly-c" || len(a.SearchKeys()) != 3 {
|
||||
t.Fatalf("a refused change was saved: %+v", a)
|
||||
}
|
||||
// a change of address with no key keeps every key, those off too
|
||||
if err := SetSearchAPI(SearchAPI{Vendor: "tavily", URL: "https://t.example.com"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := storedTavily(t); a.URL != "https://t.example.com" || len(a.SearchKeys()) != 3 || a.Key != "tvly-c" {
|
||||
t.Fatalf("an address took keys away: %+v", a)
|
||||
}
|
||||
// every key on again: the file is as an older magpie writes it
|
||||
for _, k := range []string{"tvly-b", "tvly-d"} {
|
||||
if err := SwitchSearchKey("tavily", ref(k), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if a := storedTavily(t); a.KeyList != nil || a.Key != "tvly-d,tvly-b,tvly-c" {
|
||||
t.Fatalf("all on: %+v", a)
|
||||
}
|
||||
b, err := os.ReadFile(Path())
|
||||
if err == nil && strings.Contains(string(b), "keyList") {
|
||||
t.Errorf("a list with every key on is written: %s", b)
|
||||
}
|
||||
// a key typed in place of the list is the list, every one on
|
||||
if err := SetSearchAPI(SearchAPI{Vendor: "tavily", Key: "tvly-new"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := storedTavily(t); !reflect.DeepEqual(a.SearchKeys(), []SearchKey{{Key: "tvly-new"}}) {
|
||||
t.Fatalf("replaced %+v", a.SearchKeys())
|
||||
}
|
||||
}
|
||||
|
||||
// A Key written by a magpie that knows no list (an older one, or one this
|
||||
// one syncs with) is the keys on, in its order; a key the list had off
|
||||
// that it doesn't name stays, off, after them.
|
||||
func TestSearchKeysKeyWins(t *testing.T) {
|
||||
a := SearchAPI{Vendor: "tavily", Key: "tvly-x,tvly-c", KeyList: []SearchKey{{Key: "tvly-c"}, {Key: "tvly-b", Off: true}}}
|
||||
want := []SearchKey{{Key: "tvly-x"}, {Key: "tvly-c"}, {Key: "tvly-b", Off: true}}
|
||||
if got := a.SearchKeys(); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
// and one it switched on again is on, once
|
||||
a = SearchAPI{Vendor: "tavily", Key: "tvly-c,tvly-b", KeyList: []SearchKey{{Key: "tvly-c"}, {Key: "tvly-b", Off: true}}}
|
||||
if got := a.SearchKeys(); !reflect.DeepEqual(got, []SearchKey{{Key: "tvly-c"}, {Key: "tvly-b"}}) {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if !a.HasKeys() || a.WithoutKeys().HasKeys() {
|
||||
t.Fatal("WithoutKeys")
|
||||
}
|
||||
var c SearchAPI
|
||||
c.KeepKeysOf(a)
|
||||
if c.Key != a.Key || !reflect.DeepEqual(c.KeyList, a.KeyList) {
|
||||
t.Fatalf("kept %+v", c)
|
||||
}
|
||||
if SearchKeyRef("tvly-c") == SearchKeyRef("tvly-b") || strings.Contains(SearchKeyRef("tvly-c"), "tvly") {
|
||||
t.Fatal("ref")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user