diff --git a/internal/gateway/pipeline_check.go b/internal/gateway/pipeline_check.go new file mode 100644 index 000000000..9c4bad60b --- /dev/null +++ b/internal/gateway/pipeline_check.go @@ -0,0 +1,197 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "mime/multipart" + "net/http" + "net/http/httptest" + "slices" + "strings" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// Pipelines magpie serves besides chat, each of which Settings › Models +// can check with one real call (EV_John_Liu on X). +const ( + PipelineImage = "image" + PipelineTranscription = "transcription" + PipelineSpeech = "speech" + PipelineSearch = "search" +) + +// Pipelines lists them in the order Settings shows them. +var Pipelines = []string{PipelineImage, PipelineTranscription, PipelineSpeech, PipelineSearch} + +// CheckAgent is the agent a check's calls are counted for, so Usage and +// Routing name them apart from an agent's own. +const CheckAgent = "check" + +// PipelineCheck is what one check found. Unset is that nothing is set up +// to serve the pipeline, which isn't a failure of anything set up. +type PipelineCheck struct { + Kind string `json:"kind"` + OK bool `json:"ok"` + Unset bool `json:"unset,omitempty"` + Model string `json:"model,omitempty"` + Status int `json:"status,omitempty"` + Millis int64 `json:"ms"` + Error string `json:"error,omitempty"` +} + +// FirstServing is the first model of kind's API (catalog.ServesSpeech, +// catalog.ServesTranscription) a provider that is on lists, in the +// Providers order, as provider/model, which the gateway resolves to that +// provider; "" when none does. Neither API has a default in Settings, so +// a check takes this one. A model the user disabled is passed over. +func FirstServing(kind string) string { + off := provider.DisabledModels() + for _, p := range provider.All() { + if !p.On() || p.DecideOnly() || p.ServesNone() { + continue + } + var ids []string + for _, id := range p.Models { + if catalog.ServesOf(id) == kind { + ids = append(ids, id) + } + } + for _, m := range catalog.LiveServing(p.ID, kind) { + ids = append(ids, m.ID) + } + for _, m := range provider.KeptListing(p).Available { + if catalog.ServesOf(m.ID) == kind { + ids = append(ids, m.ID) + } + } + for _, m := range p.PlanRetrieval(kind) { + ids = append(ids, m.ID) + } + for _, id := range ids { + if !slices.ContainsFunc(off, func(pat string) bool { return provider.DisabledBy(pat, p.ID, id) }) { + return p.ID + "/" + id + } + } + } + return "" +} + +// CheckPipeline makes the smallest real call kind's pipeline serves, as an +// agent would through this gateway: a one-dot drawing, a second of silence +// to transcribe, a word to speak, one web search. It costs the user what +// that call costs, so it is made only when they ask. +func (s *Server) CheckPipeline(ctx context.Context, kind string) PipelineCheck { + c := PipelineCheck{Kind: kind} + start := time.Now() + switch kind { + case PipelineImage: + m, ok := drawer() + if !ok { + c.Unset, c.Error = true, "No model draws images" + return c + } + c.Model = m + body := map[string]any{"prompt": "a dot", "n": 1} + if strings.Contains(m, "gpt-image") { + body["quality"] = "low" + } + b, _ := json.Marshal(body) + s.checkCall(ctx, &c, "/v1/images/generations", "application/json", b) + case PipelineTranscription, PipelineSpeech: + api := catalog.ServesTranscription + if kind == PipelineSpeech { + api = catalog.ServesSpeech + } + ref := FirstServing(api) + if ref == "" { + c.Unset = true + c.Error = "No provider lists a speech-to-text model" + if kind == PipelineSpeech { + c.Error = "No provider lists a text-to-speech model" + } + return c + } + c.Model = ref + model := ref + if kind == PipelineSpeech { + b, _ := json.Marshal(map[string]any{"model": model, "input": "Hi.", "voice": "alloy"}) + s.checkCall(ctx, &c, "/v1/audio/speech", "application/json", b) + break + } + var form bytes.Buffer + w := multipart.NewWriter(&form) + _ = w.WriteField("model", model) + f, _ := w.CreateFormFile("file", "silence.wav") + _, _ = f.Write(silentWAV(time.Second)) + _ = w.Close() + s.checkCall(ctx, &c, "/v1/audio/transcriptions", w.FormDataContentType(), form.Bytes()) + case PipelineSearch: + ctx = context.WithValue(ctx, searchForKey{}, &CallFor{Agent: CheckAgent}) + _, _, err := s.webSearch(withSearchCount(ctx, 1), "magpie") + switch { + case errors.Is(err, errNoSearcher) || errors.Is(err, errSearchOff): + c.Unset, c.Error = true, err.Error() + return c + case err != nil: + c.Error = err.Error() + default: + c.OK = true + } + default: + c.Error = "no such pipeline: " + kind + return c + } + c.Millis = time.Since(start).Milliseconds() + return c +} + +// checkCall posts body to the gateway's own route, as CheckAgent, and +// reads the answer into c: ok on a 200 with a body, else the vendor's +// error in its words. +func (s *Server) checkCall(ctx context.Context, c *PipelineCheck, path, ctype string, body []byte) { + req := httptest.NewRequestWithContext(ctx, http.MethodPost, URL()+path, bytes.NewReader(body)) + req.RemoteAddr = "127.0.0.1:0" + req.Header.Set("Content-Type", ctype) + req.Header.Set("Authorization", "Bearer "+TokenFor(CheckAgent)) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + c.Status = rec.Code + b := rec.Body.Bytes() + if rec.Code == http.StatusOK && len(b) > 0 { + c.OK = true + return + } + if rec.Code == http.StatusOK { + c.Error = "the answer was empty" + return + } + c.Error = provider.APIError(b, http.StatusText(rec.Code)) +} + +// silentWAV is d of silence as a 16 kHz mono 16-bit WAV file. +func silentWAV(d time.Duration) []byte { + const rate = 16000 + n := int(d.Seconds()*rate) * 2 + var b bytes.Buffer + w := func(v any) { _ = binary.Write(&b, binary.LittleEndian, v) } + b.WriteString("RIFF") + w(uint32(36 + n)) + b.WriteString("WAVEfmt ") + w(uint32(16)) + w(uint16(1)) // PCM + w(uint16(1)) // mono + w(uint32(rate)) + w(uint32(rate * 2)) + w(uint16(2)) + w(uint16(16)) + b.WriteString("data") + w(uint32(n)) + b.Write(make([]byte, n)) + return b.Bytes() +} diff --git a/internal/gateway/pipeline_check_test.go b/internal/gateway/pipeline_check_test.go new file mode 100644 index 000000000..a0ae8451e --- /dev/null +++ b/internal/gateway/pipeline_check_test.go @@ -0,0 +1,143 @@ +package gateway + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// Settings › Models' check of each pipeline (EV_John_Liu on X) makes one +// real call through the provider set up for it, and says ok, or what the +// vendor said. + +func TestCheckImageDrawsOneDot(t *testing.T) { + s, e := easeled(t) + st := settings.Load() + st.ImageGen = "art/gpt-image-1" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + c := s.CheckPipeline(context.Background(), PipelineImage) + if !c.OK || c.Model != "art/gpt-image-1" || c.Status != 200 || c.Error != "" { + t.Fatalf("%+v", c) + } + sent := e.got("/v1/images/generations") + if len(sent) != 1 || !strings.Contains(sent[0], `"prompt":"a dot"`) || !strings.Contains(sent[0], `"n":1`) || !strings.Contains(sent[0], `"quality":"low"`) { + t.Fatalf("vendor was sent %v", sent) + } + st.ImageGen = "off" + settings.Save(st) + if c := s.CheckPipeline(context.Background(), PipelineImage); c.OK || !c.Unset || len(e.got("/v1/images/generations")) != 1 { + t.Fatalf("off: %+v", c) + } +} + +func TestCheckSpeechSaysAWord(t *testing.T) { + s, sp := speakerUp(t) + c := s.CheckPipeline(context.Background(), PipelineSpeech) + if !c.OK || c.Model != "voice/gpt-4o-mini-tts" || c.Status != 200 { + t.Fatalf("%+v", c) + } + sent, _ := sp.got() + if len(sent) != 1 || !bytes.Contains(sent[0], []byte(`"model":"gpt-4o-mini-tts"`)) || !bytes.Contains(sent[0], []byte(`"input":"Hi."`)) { + t.Fatalf("vendor was sent %q", sent) + } +} + +// The vendor's refusal comes back in its own words. +func TestCheckSpeechSaysTheVendorsError(t *testing.T) { + fresh(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"voice alloy isn't one of this model's"}}`) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "voice", Name: "Voice", Chat: up.URL + "/v1", Key: "key", Models: []string{"tts-1"}}); err != nil { + t.Fatal(err) + } + c := New().CheckPipeline(context.Background(), PipelineSpeech) + if c.OK || c.Unset || c.Status != 400 || !strings.Contains(c.Error, "voice alloy isn't one of this model's") { + t.Fatalf("%+v", c) + } +} + +func TestCheckTranscriptionSendsASecondOfSilence(t *testing.T) { + s, sc := scribed(t) + c := s.CheckPipeline(context.Background(), PipelineTranscription) + if !c.OK || c.Model != "ears/whisper-1" || c.Status != 200 { + t.Fatalf("%+v", c) + } + sent, types := sc.got("/v1/audio/transcriptions") + if len(sent) != 1 || !strings.HasPrefix(types[0], "multipart/form-data") || !bytes.Contains(sent[0], []byte("RIFF")) || !bytes.Contains(sent[0], []byte("whisper-1")) { + t.Fatalf("vendor was sent %d %v", len(sent), types) + } + if n := len(silentWAV(1e9)); n != 44+32000 { + t.Errorf("a second of 16 kHz 16-bit mono is %d bytes", n) + } +} + +// With no provider for a pipeline the check says so, as unset, and calls +// nothing. +func TestCheckUnsetPipelines(t *testing.T) { + fresh(t) + if err := provider.Save(provider.Provider{ID: "chat", Name: "Chat", Chat: "http://127.0.0.1:1/v1", Key: "key", Models: []string{"gpt-5"}}); err != nil { + t.Fatal(err) + } + s := New() + for _, k := range []string{PipelineTranscription, PipelineSpeech} { + if c := s.CheckPipeline(context.Background(), k); c.OK || !c.Unset || c.Error == "" || c.Status != 0 { + t.Errorf("%s: %+v", k, c) + } + } +} + +// A disabled model is none a check takes. +func TestCheckSkipsADisabledModel(t *testing.T) { + speakerUp(t) + if err := provider.SetDisabledModels([]string{"voice/gpt-4o-mini-tts"}); err != nil { + t.Fatal(err) + } + if got := FirstServing("speech"); got != "" { + t.Fatalf("a disabled model was taken: %q", got) + } +} + +func TestCheckSearchAsksOnce(t *testing.T) { + fresh(t) + st := settings.Load() + st.Searcher = "off" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + s := New() + if c := s.CheckPipeline(context.Background(), PipelineSearch); c.OK || !c.Unset { + t.Fatalf("no search API: %+v", c) + } + f := newSearchAPIs(t) + if err := provider.SetSearchAPI(f.api("tavily", "tvly-k")); err != nil { + t.Fatal(err) + } + if c := s.CheckPipeline(context.Background(), PipelineSearch); !c.OK || c.Error != "" { + t.Fatalf("%+v", c) + } + f.mu.Lock() + asked := f.asked + f.mu.Unlock() + if len(asked) != 1 || asked[0] != "tavily: magpie" { + t.Fatalf("asked %v", asked) + } + f.mu.Lock() + f.broken = true + f.mu.Unlock() + if c := s.CheckPipeline(context.Background(), PipelineSearch); c.OK || c.Unset || c.Error == "" { + t.Fatalf("broken: %+v", c) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 33f02eeed..2136cab04 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2054,6 +2054,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { // from through the proxy in force, and without it mux.HandleFunc("POST /api/proxy/check", handleProxyCheck) proxyRoutes(mux) + mux.HandleFunc("POST /api/pipelines/check", handlePipelineCheck) mux.HandleFunc("POST /api/settings/codex-titles", func(rw http.ResponseWriter, r *http.Request) { var in struct{ Model string } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c1593cde6..8423482bb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20077,6 +20077,7 @@ function renderSettings() { renderGitHubToken(s); renderImages(s, keep); renderSearch(s, keep); + window.pipeCheckFill ? pipeCheckFill() : import("./pipecheck.js").then(() => pipeCheckFill(), () => {}); renderReplies(s, keep); renderDisabledModels(s); renderRedact(s, keep); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 19fbefe16..24732b950 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,17 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "Quick check": "快速检测", + "Test all": "全部测试", + "One real call each, at the provider's price": "每项真实调用一次,按服务商的价格计费", + "Speech to text": "语音转文字", + "Text to speech": "文字转语音", + "No model draws images": "没有能生成图片的模型", + "No provider lists a speech-to-text model": "没有供应商列出语音转文字模型", + "No provider lists a text-to-speech model": "没有供应商列出文字转语音模型", + "no provider that can search the web, nor a search API, is set up in magpie": "magpie 里没有设置能联网搜索的供应商,也没有搜索 API", + "magpie's web search is off: turn the Web search plugin on in magpie's Settings → Plugins": "magpie 的联网搜索已关闭:在 magpie 的设置 → 插件里打开“联网搜索”插件", + "Another magpie serves the gateway: check there": "另一个 magpie 在提供网关:请在那边检测", "paused": "已暂停", "Resume gateway": "恢复网关", "Paused, agents are disconnected and use their own settings": "暂停时各 agent 断开连接,用回它们自己的配置", @@ -5052,6 +5063,17 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { + "Quick check": "快速檢測", + "Test all": "全部測試", + "One real call each, at the provider's price": "每項真實呼叫一次,按服務商的價格計費", + "Speech to text": "語音轉文字", + "Text to speech": "文字轉語音", + "No model draws images": "沒有能生成圖片的模型", + "No provider lists a speech-to-text model": "沒有供應商列出語音轉文字模型", + "No provider lists a text-to-speech model": "沒有供應商列出文字轉語音模型", + "no provider that can search the web, nor a search API, is set up in magpie": "magpie 裡沒有設定能聯網搜尋的供應商,也沒有搜尋 API", + "magpie's web search is off: turn the Web search plugin on in magpie's Settings → Plugins": "magpie 的聯網搜尋已關閉:在 magpie 的設定 → 外掛裡開啟「聯網搜尋」外掛", + "Another magpie serves the gateway: check there": "另一個 magpie 在提供閘道:請在那邊檢測", "paused": "已暫停", "Resume gateway": "恢復閘道", "Paused, agents are disconnected and use their own settings": "暫停時各 agent 中斷連線,改用它們自己的設定", @@ -10085,6 +10107,17 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { + "Quick check": "クイックチェック", + "Test all": "すべてテスト", + "One real call each, at the provider's price": "それぞれ実際に 1 回呼び出し、プロバイダの料金がかかります", + "Speech to text": "音声からテキスト", + "Text to speech": "テキストから音声", + "No model draws images": "画像を生成できるモデルがありません", + "No provider lists a speech-to-text model": "音声認識モデルを載せているプロバイダがありません", + "No provider lists a text-to-speech model": "音声合成モデルを載せているプロバイダがありません", + "no provider that can search the web, nor a search API, is set up in magpie": "ウェブ検索できるプロバイダも検索 API も magpie に設定されていません", + "magpie's web search is off: turn the Web search plugin on in magpie's Settings → Plugins": "magpie のウェブ検索はオフです:magpie の設定 → プラグインでウェブ検索プラグインをオンにしてください", + "Another magpie serves the gateway: check there": "別の magpie がゲートウェイを提供しています:そちらでチェックしてください", "paused": "一時停止中", "Resume gateway": "ゲートウェイを再開", "Paused, agents are disconnected and use their own settings": "一時停止中はエージェントの接続を解除し、それぞれ元の設定を使います", @@ -15120,6 +15153,17 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { + "Quick check": "Schnelltest", + "Test all": "Alle testen", + "One real call each, at the provider's price": "Je ein echter Aufruf, zum Preis des Anbieters", + "Speech to text": "Sprache zu Text", + "Text to speech": "Text zu Sprache", + "No model draws images": "Kein Modell erzeugt Bilder", + "No provider lists a speech-to-text model": "Kein Anbieter führt ein Spracherkennungsmodell", + "No provider lists a text-to-speech model": "Kein Anbieter führt ein Sprachausgabemodell", + "no provider that can search the web, nor a search API, is set up in magpie": "In magpie ist weder ein Anbieter, der im Web sucht, noch eine Such-API eingerichtet", + "magpie's web search is off: turn the Web search plugin on in magpie's Settings → Plugins": "magpies Websuche ist aus: Schalte das Websuche-Erweiterung in magpies Einstellungen → Erweiterungen ein", + "Another magpie serves the gateway: check there": "Ein anderes magpie stellt das Gateway bereit: Teste dort", "paused": "pausiert", "Resume gateway": "Zugangspunkt fortsetzen", "Paused, agents are disconnected and use their own settings": "Pausiert werden Agenten getrennt und nutzen ihre eigenen Einstellungen", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 33722fd1f..c64336bd8 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -385,6 +385,8 @@
Web search
+
Quick check
+
Replies
Routing
diff --git a/internal/gui/assets/pipecheck.js b/internal/gui/assets/pipecheck.js new file mode 100644 index 000000000..d244cdf78 --- /dev/null +++ b/internal/gui/assets/pipecheck.js @@ -0,0 +1,60 @@ +// Settings › Models' Quick check (EV_John_Liu on X): each pipeline besides +// chat checked with one real call through the gateway (/api/pipelines/ +// check): a one-dot drawing, a second of silence to transcribe, a word to +// speak, one web search. Each costs what the call costs, so only a press +// runs one, never a draw. app.js imports this when Settings draws Models. + +const pipes = [["image", "Image generation"], ["transcription", "Speech to text"], ["speech", "Text to speech"], ["search", "Web search"]]; +const pipeChecks = {}; // kind → { busy } or what the check found + +function pipeRun(kind) { + if (pipeChecks[kind]?.busy) return; + pipeChecks[kind] = { busy: true }; + pipeCheckFill(); + api("pipelines/check", { kind }) + .then((r) => { pipeChecks[kind] = r; }, (e) => { pipeChecks[kind] = { error: t(e.message) }; }) + .finally(pipeCheckFill); +} + +// pipeSaid: what a check found, and whether it is a failure +function pipeSaid(c) { + if (!c || c.busy) return ["", false]; + if (c.ok) return [(c.model ? c.model + " · " : "") + ledTook(c.ms), false]; + if (c.unset) return [t(c.error), false]; + return [(c.model ? c.model + " · " : "") + (c.status ? c.status + " · " : "") + t(c.error || ""), true]; +} + +// pipeCheckFill draws the rows into #pipeCheckList, once, and then each +// row's state in place, so a press keeps its focus +window.pipeCheckFill = function () { + const box = document.getElementById("pipeCheckList"); + if (!box) return; + const all = document.getElementById("pipeCheckAll"); + all.onclick = () => pipes.forEach(([k]) => pipeRun(k)); + all.disabled = pipes.every(([k]) => pipeChecks[k]?.busy); + if (!box.children.length) { + for (const [kind, name] of pipes) { + const row = el("div", "row pref pipe-check"); + row.dataset.pipe = kind; + const who = el("div", "who"); + const line = el("div", "sub say pipe-said"); + line.setAttribute("role", "status"); + who.append(el("div", "name", t(name)), line); + const b = el("button", "text pipe-test"); + b.type = "button"; + b.onclick = () => pipeRun(kind); + row.append(who, b); + box.append(row); + } + } + for (const row of box.children) { + const c = pipeChecks[row.dataset.pipe]; + const b = row.querySelector(".pipe-test"), line = row.querySelector(".pipe-said"); + b.textContent = c?.busy ? t("Testing…") : t("Test"); + b.disabled = !!c?.busy; + const [text, bad] = pipeSaid(c); + line.hidden = !text; + line.textContent = line.title = text; + line.classList.toggle("err", bad); + } +}; diff --git a/internal/gui/pipecheck.go b/internal/gui/pipecheck.go new file mode 100644 index 000000000..a22428162 --- /dev/null +++ b/internal/gui/pipecheck.go @@ -0,0 +1,32 @@ +package gui + +import ( + "encoding/json" + "errors" + "net/http" + "slices" + + "github.com/yetone/magpie/internal/gateway" +) + +// Settings › Models' Check (EV_John_Liu on X): each pipeline besides chat +// (image generation, speech-to-text, text-to-speech, web search) checked +// with one real call through the gateway, as an agent's would go. Each +// costs the user what the call costs, so only a press runs one. +func handlePipelineCheck(rw http.ResponseWriter, r *http.Request) { + var in struct{ Kind string } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if !slices.Contains(gateway.Pipelines, in.Kind) { + fail(rw, errors.New("no such pipeline: "+in.Kind)) + return + } + gw := served.Load() + if gw == nil { + fail(rw, errors.New("Another magpie serves the gateway: check there")) + return + } + writeJSON(rw, gw.CheckPipeline(r.Context(), in.Kind)) +} diff --git a/internal/gui/pipecheck_test.go b/internal/gui/pipecheck_test.go new file mode 100644 index 000000000..a45183760 --- /dev/null +++ b/internal/gui/pipecheck_test.go @@ -0,0 +1,35 @@ +package gui + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" +) + +// POST /api/pipelines/check takes only a pipeline magpie serves, and with +// no gateway of its own (another magpie serves it) says where to check. +func TestPipelineCheckRoute(t *testing.T) { + onePortHome(t) + prev := served.Swap(nil) + t.Cleanup(func() { served.Store(prev) }) + post := func(body string) (int, string) { + w := httptest.NewRecorder() + handlePipelineCheck(w, httptest.NewRequest("POST", "/api/pipelines/check", strings.NewReader(body))) + return w.Code, w.Body.String() + } + if code, body := post(`{"kind":"chat"}`); code < 400 || !strings.Contains(body, "no such pipeline") { + t.Fatalf("an unknown kind: %d %s", code, body) + } + if code, body := post(`{"kind":"speech"}`); code < 400 || !strings.Contains(body, "Another magpie serves the gateway") { + t.Fatalf("no gateway here: %d %s", code, body) + } + served.Store(gateway.New()) + code, body := post(`{"kind":"speech"}`) + var c gateway.PipelineCheck + if err := json.Unmarshal([]byte(body), &c); err != nil || code != 200 || c.Kind != "speech" || !c.Unset { + t.Fatalf("a fresh home has no speech model: %d %s", code, body) + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 44fea2c05..c3da9cf36 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -174,9 +174,10 @@ test("compat.js is the first of the page's own scripts", async () => { // navicons.js (the sidebar lists' marks) with the first list drawn; // autoswitchtip.js when a provider's accounts draw their switch; // codexprojects.js when the open Codex app shows fewer projects; + // pipecheck.js when Settings draws Models; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/pipeline-check.test.cjs b/internal/gui/tests/pipeline-check.test.cjs new file mode 100644 index 000000000..be665a64c --- /dev/null +++ b/internal/gui/tests/pipeline-check.test.cjs @@ -0,0 +1,193 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// EV_John_Liu on X: "现在不是有图片生成、asr、tts管线和网络搜索。能不能做个快速 +// 检测。可用". Settings › Models › Quick check has a row per pipeline (image +// generation, speech to text, text to speech, web search), each with Test, +// and Test all. A check is one real call the user pays for, so drawing the +// page calls nothing; a row's Test checks that pipeline alone, and Test all +// each of them. A row then says ok with the model and how long it took, the +// vendor's error with its status, or that nothing is set up. Every +// language; wide and at a phone's width; no backend, the API is faked here. +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 assets = path.resolve(__dirname, "../assets"); + +function settingsPayload(lang) { + return { + theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd", textSize: 100, + dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [], + codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false, + trayUsage: "", trayUsageEvery: 3, vision: "", imageGen: "", + version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", + proxyNow: "none", proxySource: "none", login: false, + visionModels: [], workbuddyCheckins: [], lanURLs: [], + imageGenAuto: "openai/gpt-image-2", + imageGenModels: [{ id: "openai/gpt-image-2", name: "gpt-image-2", provider: "openai", providerName: "OpenAI", icon: "openai" }], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; +} + +const answers = { + image: { kind: "image", ok: true, model: "openai/gpt-image-2", status: 200, ms: 840 }, + transcription: { kind: "transcription", ok: false, model: "ears/whisper-1", status: 400, ms: 120, error: "Invalid file format." }, + speech: { kind: "speech", ok: false, unset: true, ms: 0, error: "No provider lists a text-to-speech model" }, + search: { kind: "search", ok: true, ms: 1500 }, +}; + +// server answers a check only once the test lets it, so a row's busy state +// can be seen +function server(lang, checks) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true,textSize:100};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", textSize: 100 } }); + if (url.pathname === "/api/settings") return json(settingsPayload(lang)); + if (url.pathname === "/api/pipelines/check") { + const { kind } = JSON.parse(req.postData() || "{}"); + let go; + const held = new Promise((r) => (go = r)); + checks.push({ kind, go }); + await held; + return json(answers[kind]); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/window/fit") return route.fulfill({ status: 204 }); + 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)]; + const body = await fs.readFile(file).catch(() => null); + await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" })); + }; +} + +const want = { + en: { head: "Quick check", all: "Test all", test: "Test", testing: "Testing…", names: ["Image generation", "Speech to text", "Text to speech", "Web search"], ms: "840 ms", s: "1.5 s", unset: "No provider lists a text-to-speech model" }, + zh: { head: "快速检测", all: "全部测试", test: "测试", testing: "测试中…", names: ["生图模型", "语音转文字", "文字转语音", "联网搜索"], ms: "840 毫秒", s: "1.5 秒", unset: "没有供应商列出文字转语音模型" }, + "zh-TW": { head: "快速檢測", all: "全部測試", test: "測試", testing: "測試中…", names: ["生圖模型", "語音轉文字", "文字轉語音", "聯網搜尋"], ms: "840 毫秒", s: "1.5 秒", unset: "沒有供應商列出文字轉語音模型" }, + ja: { head: "クイックチェック", all: "すべてテスト", test: "テスト", testing: "テスト中…", names: ["画像生成", "音声からテキスト", "テキストから音声", "ウェブ検索"], ms: "840 ミリ秒", s: "1.5 秒", unset: "音声合成モデルを載せているプロバイダがありません" }, + de: { head: "Schnelltest", all: "Alle testen", test: "Testen", testing: "Wird getestet…", names: ["Bilderzeugung", "Sprache zu Text", "Text zu Sprache", "Websuche"], ms: "840 ms", s: "1.5 s", unset: "Kein Anbieter führt ein Sprachausgabemodell" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Settings checks each pipeline with one call, only when asked", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const shots = []; + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + for (const [name, buf] of shots) await fs.writeFile(path.join(process.env.ARTIFACT_DIR, `${engine}-pipeline-check-${name}.png`), buf); + } + await browser.close(); + }); + const fits = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + for (const lang of Object.keys(want)) { + const w = want[lang]; + for (const width of lang === "en" || lang === "zh" ? [1100, 400] : [1100]) { + await t.test(`${lang} at ${width}px: Test checks one pipeline, Test all each, and each row says what it found`, async () => { + const checks = []; + const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, checks)); + await page.goto("http://magpie.test/?view=settings&tab=models"); + const rows = page.locator("#pipeCheckList .pipe-check"); + await rows.nth(3).waitFor(); + const head = page.locator(".row-head", { has: page.locator("#pipeCheckAll") }); + assert.equal((await head.locator(".label").textContent()).trim(), w.head); + const all = page.locator("#pipeCheckAll"); + assert.equal((await all.textContent()).trim(), w.all); + assert.deepEqual((await rows.locator(".name").allTextContents()).map((x) => x.trim()), w.names); + assert.deepEqual((await rows.locator(".pipe-test").allTextContents()).map((x) => x.trim()), Array(4).fill(w.test)); + assert.equal(await rows.locator(".pipe-said:visible").count(), 0, "nothing found yet"); + // drawing the page, and drawing it again, checks nothing + await page.evaluate(() => window.pipeCheckFill()); + await page.waitForTimeout(50); + assert.deepEqual(checks, [], "a check costs money: none without a press"); + assert.equal(await fits(page), 0, "no sideways scroll"); + + // a row's Test checks that pipeline only + // pressed where it is, as a pointer does (Playwright's click + // scrolls its target into view first, which isn't the page's doing) + const press = async (loc) => { + const r = await loc.boundingBox(); + await page.mouse.click(r.x + r.width / 2, r.y + r.height / 2); + }; + const speech = rows.nth(2); + // brought into view with the wheel, as a user scrolls to it + // (WebKit's wheel scroll runs on after the event, so wait till it rests) + const settle = async () => { + let last = null; + for (let i = 0; i < 50; i++) { + const now = await page.evaluate(() => document.getElementById("view-settings").scrollTop); + if (now === last) return; + last = now; + await page.waitForTimeout(100); + } + }; + const bring = async (loc) => { + for (let i = 0; i < 40; i++) { + await settle(); + const b = await loc.boundingBox(); + if (b && b.y > 80 && b.y + b.height < 700) return; + await page.mouse.move(width / 2, 380); + await page.mouse.wheel(0, b && b.y < 80 ? -150 : 150); + await page.waitForTimeout(30); + } + assert.fail("never came into view"); + }; + const scrolled = () => page.evaluate(() => [document.scrollingElement.scrollTop, document.getElementById("view-settings").scrollTop]); + await bring(speech); + const scrollBefore = await scrolled(); + const atBefore = (await speech.locator(".pipe-test").boundingBox()).y; + await press(speech.locator(".pipe-test")); + await page.waitForFunction(() => document.querySelector('[data-pipe="speech"] .pipe-test').disabled); + assert.equal((await speech.locator(".pipe-test").textContent()).trim(), w.testing); + assert.deepEqual(checks.map((c) => c.kind), ["speech"]); + checks[0].go(); + await page.waitForFunction(() => !document.querySelector('[data-pipe="speech"] .pipe-test').disabled); + const said = speech.locator(".pipe-said"); + assert.equal((await said.textContent()).trim(), w.unset); + assert.equal(await said.evaluate((e) => e.classList.contains("err")), false, "nothing set up isn't a failure"); + // what was pressed stays where it was (app.js holds the clicked + // element while what is around it draws), and the window never scrolls + const at = (await speech.locator(".pipe-test").boundingBox()).y; + assert.equal((await scrolled())[0], scrollBefore[0], "the window never scrolls"); + assert(Math.abs(at - atBefore) <= 1, `the pressed Test stays put: moved ${at - atBefore}px`); + + // Test all checks each, at once + await bring(all); + const allAt = (await all.boundingBox()).y; + await press(all); + await page.waitForFunction(() => document.querySelectorAll("#pipeCheckList .pipe-test:disabled").length === 4); + assert.deepEqual(checks.slice(1).map((c) => c.kind).sort(), ["image", "search", "speech", "transcription"]); + for (const c of checks.slice(1)) c.go(); + await page.waitForFunction(() => document.querySelectorAll("#pipeCheckList .pipe-test:disabled").length === 0); + assert(Math.abs((await all.boundingBox()).y - allAt) <= 1, "Test all stays put"); + const line = (i) => rows.nth(i).locator(".pipe-said"); + assert.equal((await line(0).textContent()).trim(), `openai/gpt-image-2 · ${w.ms}`); + assert.equal(await line(0).evaluate((e) => e.classList.contains("err")), false); + assert.equal((await line(1).textContent()).trim(), "ears/whisper-1 · 400 · Invalid file format."); + assert.equal(await line(1).evaluate((e) => e.classList.contains("err")), true, "the vendor's error reads as one"); + assert.equal(await line(1).isVisible(), true, "the error is in sight"); + assert.equal((await line(3).textContent()).trim(), w.s); + assert.equal(checks.length, 5, "one call per press, no more"); + assert.equal(await fits(page), 0, "no sideways scroll"); + shots.push([`${lang}-${width}`, await page.screenshot({ fullPage: true })]); + assert.deepEqual(errors, []); + await context.close(); + }); + } + } + }); +}