Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gui: the Providers page draws the last list at once and the fresh one behind it

yetone92fbabb47e81
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 6904e3cc2..bf9b7cf98 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -3955,6 +3955,8 @@ async function load(again) {
paintUpdateAll(true);
loadCLIs(); // after the rows, never holding them up
loadInstalls();
+ // the Providers page made ready behind the one shown (#1519)
+ if (mode !== "panel" && !(view === "providers" || providersPage(view))) prefetchProviders();
// the panel brought up on its Allowances tab is the reader opening
// them (#1588); the page loaded while the panel is still put away is not
if (mode === "panel") { renderPanelQuota(); panelTab === "usage" && !document.hidden && (again || document.hasFocus()) ? quotasOpened() : loadQuotas(); }
@@ -5581,15 +5583,71 @@ saveCurrent.onclick = () => {
// every provider becomes "provider/model" in the agents' pickers, served by
// the local gateway in whichever API the agent speaks.
-async function loadProviders() {
+// The list read in the background once the app has started (#1519), for
+// the page's first opening: { read, got } — the read, and the list once in.
+let providersEarly = null;
+function prefetchProviders() {
+ if (providers || providersEarly) return;
+ const e = providersEarly = { read: api("providers") };
+ e.read.then((s) => { e.got = s; }, () => { if (providersEarly === e) providersEarly = null; });
+}
+
+// The page's first reading, while it is on its way, is the one every ask
+// gets (a start on the page asks from load and from show both), not
+// another read: the kept list drawn, a click on a row waits for it.
+function loadProviders() {
+ if ((!providers || providers.last) && loadProviders.first) return loadProviders.first;
+ const first = !providers, p = loadProvidersNow();
+ if (first) {
+ loadProviders.first = p;
+ p.finally(() => { if (loadProviders.first === p) loadProviders.first = null; }).catch(() => {});
+ }
+ return p;
+}
+
+async function loadProvidersNow() {
+ // The page's first opening (#1519, fatkun): a list is drawn at once, as
+ // the Agents page draws the last state, and the fresh one replaces it
+ // when it is in — the one read in the background after the start, else
+ // the one kept from the last read (this run's or the run before's). The
+ // read in the background still on its way is waited for, not asked again.
+ let fresh = null, kept = null;
+ if (!providers) {
+ const early = providersEarly;
+ providersEarly = null;
+ if (early?.got) kept = early.got;
+ else {
+ fresh = early ? early.read : api("providers");
+ if (view === "providers") {
+ kept = await Promise.race([fresh.then(() => null, () => null), api("providers?last=1").catch(() => null)]);
+ if (!kept?.providers?.length || providers) kept = null;
+ // a kept list, whatever it says of itself: a row clicked on it
+ // waits for the fresh one, never opened to be drawn again under
+ // the reader's hands when that comes in
+ else kept.last = true;
+ }
+ }
+ }
+ fresh ||= api("providers");
+ if (kept) {
+ providers = kept;
+ renderSideGw(providers.gateway);
+ if (typeof editing === "string" && !providers.providers.some((p) => p.id === editing)) editing = null;
+ if (providersPage(view)) magpie.call(view, "render", null);
+ else renderProviders();
+ }
// the skeletons only while there is nothing yet: a reload keeps what is
// drawn, and where the reader is in it, until the new one is in
- if (!providers) { if (providersPage(view)) magpie.call(view, "loading"); else renderProvidersLoading(); }
+ else if (!providers) { if (providersPage(view)) magpie.call(view, "loading"); else renderProvidersLoading(); }
// a plugin's page opened from another that had the list: drawn from it
// at once (#123)
else if (providersPage(view)) magpie.call(view, "draft");
const was = providers;
- providers = await api("providers");
+ const next = await fresh;
+ // a change saved meanwhile drew the list it was answered with, newer
+ // than this read
+ if (kept && providers !== kept) return;
+ providers = next;
renderSideGw(providers.gateway);
// a reload's provider may be gone since
if (typeof editing === "string" && !providers.providers.some((p) => p.id === editing)) editing = null;
@@ -5820,6 +5878,12 @@ function renderProviders() {
if (!p.off) row.oncontextmenu = (ev) => { ev.preventDefault(); openProviderMenu(row.querySelector(".pv-handle"), p); };
row.onclick = async () => {
if (providerDirty() && !(await confirmDiscard())) return;
+ // a list drawn before the fresh one is in (#1519) leaves out what the
+ // editor shows (headers, proxies): the row opens on the fresh one
+ if (providers.last) {
+ try { await loadProviders(); } catch (e) { status(e.message, "err"); return; }
+ if (!providers.providers.some((x) => x.id === p.id)) return;
+ }
editing = open ? null : p.id; draft = null; renderProviders();
}; // the preset sheet stays as it is under the dialog
list.append(row);
@@ -23484,7 +23548,14 @@ function renderCrumb(items) {
// the gateway at the sidebar's foot: where it listens, or that it doesn't
var sideGwAt = null;
function sideGwRead() {
- if (sideGwRead.due && sideNav() && !sideGwAt) api("providers").then((r) => renderSideGw(r?.gateway), () => {});
+ if (!(sideGwRead.due && sideNav() && !sideGwAt)) return;
+ // the list is not read yet: the read the Providers page is made ready
+ // with (#1519) serves both, one read, not two
+ if (!providers && mode !== "panel") {
+ prefetchProviders();
+ if (providersEarly) return void providersEarly.read.then((r) => renderSideGw(r?.gateway), () => {});
+ }
+ api("providers").then((r) => renderSideGw(r?.gateway), () => {});
}
function renderSideGw(g) {
const b = $("#sideGw");
diff --git a/internal/gui/lastproviders.go b/internal/gui/lastproviders.go
new file mode 100644
index 000000000..68d7e2516
--- /dev/null
+++ b/internal/gui/lastproviders.go
@@ -0,0 +1,92 @@
+package gui
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/yetone/magpie/internal/appdir"
+ "github.com/yetone/magpie/internal/edit"
+)
+
+// The last-known providers list (#1519, fatkun): the Providers page asked
+// /api/providers each time it opened, and after a start that read took
+// seconds (every account's sign-in, every agent's model), so the page
+// showed skeletons for that long. As the Agents page draws the last state
+// (laststate.go), it now draws the list built last, kept here and in the
+// cache folder for the next start, and the fresh one replaces it the
+// moment it is in.
+//
+// What is kept leaves out what the page never needs before the fresh list
+// is in and what can hold a secret: the gateway's recent calls and lanes,
+// each provider's headers, proxies and extra body. The page opens no
+// provider's editor from the kept list; it waits for the fresh one.
+
+var lastProviders struct {
+ sync.Mutex
+ kept []byte
+ read bool
+}
+
+type providersFile struct {
+ Version string `json:"version"`
+ Providers providersJSON `json:"providers"`
+}
+
+func lastProvidersPath() string { return filepath.Join(appdir.Cache(), "providers-state.json") }
+
+// keepProviders remembers s as the last-known list, written only when what
+// is kept changed.
+func keepProviders(s providersJSON) {
+ s.Gateway.Calls, s.Gateway.Lanes = nil, nil
+ s.Moved, s.Added, s.Had, s.Removed, s.Fetching = nil, 0, 0, 0, false
+ ps := make([]providerJSON, len(s.Providers))
+ for i, p := range s.Providers {
+ p.Headers, p.ExtraBody, p.Proxy, p.AccountProxies = nil, nil, "", nil
+ ps[i] = p
+ }
+ s.Providers = ps
+ b, err := json.Marshal(providersFile{Version: Version, Providers: s})
+ if err != nil {
+ return
+ }
+ lastProviders.Lock()
+ defer lastProviders.Unlock()
+ if !lastProviders.read {
+ lastProviders.kept, _ = os.ReadFile(lastProvidersPath())
+ lastProviders.read = true
+ }
+ if bytes.Equal(b, lastProviders.kept) {
+ return
+ }
+ lastProviders.kept = b
+ // only this user's to read: it names their accounts
+ if _, err := os.Stat(lastProvidersPath()); os.IsNotExist(err) {
+ os.MkdirAll(filepath.Dir(lastProvidersPath()), 0o700)
+ os.WriteFile(lastProvidersPath(), nil, 0o600)
+ }
+ _ = edit.WriteAtomic(lastProvidersPath(), b)
+}
+
+// lastKnownProviders is the last list built, by this run or the one
+// before it, as kept; false when none is kept, or another version kept it.
+func lastKnownProviders() (json.RawMessage, bool) {
+ lastProviders.Lock()
+ if !lastProviders.read {
+ lastProviders.kept, _ = os.ReadFile(lastProvidersPath())
+ lastProviders.read = true
+ }
+ b := lastProviders.kept
+ lastProviders.Unlock()
+ var f struct {
+ Version string `json:"version"`
+ Providers json.RawMessage `json:"providers"`
+ }
+ if len(b) == 0 || json.Unmarshal(b, &f) != nil || f.Version != Version || len(f.Providers) == 0 || f.Providers[0] != '{' {
+ return nil, false
+ }
+ // marked, for the page to tell it from a fresh one
+ return append(json.RawMessage(`{"last":true,`), f.Providers[1:]...), true
+}
diff --git a/internal/gui/lastproviders_test.go b/internal/gui/lastproviders_test.go
new file mode 100644
index 000000000..a0648ca09
--- /dev/null
+++ b/internal/gui/lastproviders_test.go
@@ -0,0 +1,95 @@
+package gui
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+func forgetLastProviders() {
+ lastProviders.Lock()
+ lastProviders.kept, lastProviders.read = nil, false
+ lastProviders.Unlock()
+}
+
+// #1519 (fatkun): the Providers page draws the list kept from the last
+// read at once (?last=1), this run's or the run before's, and the fresh
+// one after; none kept is null. What can hold a secret (a header's value,
+// a proxy's password, the raw key) never reaches the file.
+func TestLastKnownProviders(t *testing.T) {
+ sandboxHome(t)
+ forgetLastProviders()
+ t.Cleanup(forgetLastProviders)
+ if _, err := provider.Add(provider.Provider{ID: "own", Name: "Own", Chat: "http://127.0.0.1:1/v1", Key: "sk-raw-key-1519",
+ Models: []string{"m1"}, Headers: map[string]string{"X-Token": "hdr-secret-1519"}, Proxy: "http://u:[email protected]:2"}); err != nil {
+ t.Fatal(err)
+ }
+ srv := Handler(nil, nil)
+ get := func(path string) string {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
+ if rec.Code != 200 {
+ t.Fatalf("%s: %d %s", path, rec.Code, rec.Body)
+ }
+ return strings.TrimSpace(rec.Body.String())
+ }
+ type list struct {
+ Last bool `json:"last"`
+ Providers []struct {
+ ID string `json:"id"`
+ } `json:"providers"`
+ }
+ has := func(l list, id string) bool {
+ for _, p := range l.Providers {
+ if p.ID == id {
+ return true
+ }
+ }
+ return false
+ }
+
+ if b := get("/api/providers?last=1"); b != "null" {
+ t.Fatalf("nothing kept yet: want null, got %.200s", b)
+ }
+ var fresh list
+ json.Unmarshal([]byte(get("/api/providers")), &fresh)
+ if fresh.Last || !has(fresh, "own") {
+ t.Fatalf("fresh list: %+v", fresh)
+ }
+ file, err := os.ReadFile(lastProvidersPath())
+ if err != nil {
+ t.Fatalf("the read was not kept: %v", err)
+ }
+ for _, s := range []string{"sk-raw-key-1519", "hdr-secret-1519", "proxy-secret-1519"} {
+ if strings.Contains(string(file), s) {
+ t.Errorf("the kept list holds %s", s)
+ }
+ }
+ if fi, err := os.Stat(lastProvidersPath()); err == nil && runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
+ t.Errorf("the kept list is readable by others: %v", fi.Mode())
+ }
+
+ // magpie starts again: the list kept is served, marked as such
+ forgetLastProviders()
+ var last list
+ if err := json.Unmarshal([]byte(get("/api/providers?last=1")), &last); err != nil {
+ t.Fatal(err)
+ }
+ if !last.Last || !has(last, "own") {
+ t.Fatalf("kept list after a start: %+v", last)
+ }
+
+ // kept by another version: not drawn
+ b, _ := os.ReadFile(lastProvidersPath())
+ os.WriteFile(lastProvidersPath(), []byte(strings.Replace(string(b), `"version":"`, `"version":"other-`, 1)), 0o600)
+ forgetLastProviders()
+ if b := get("/api/providers?last=1"); b != "null" {
+ t.Fatalf("another version's list served: %.200s", b)
+ }
+}
diff --git a/internal/gui/providers.go b/internal/gui/providers.go
index 263abc938..aa40c7955 100644
--- a/internal/gui/providers.go
+++ b/internal/gui/providers.go
@@ -1030,7 +1030,20 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if r.URL.Query().Has("wait") {
provider.FetchNew(8 * time.Second)
}
- writeJSON(rw, providersState())
+ // ?last=1: the list kept from the last read, at once (#1519);
+ // null when none is kept
+ if r.URL.Query().Get("last") == "1" {
+ if b, ok := lastKnownProviders(); ok {
+ rw.Header().Set("Content-Type", "application/json")
+ rw.Write(b)
+ } else {
+ writeJSON(rw, nil)
+ }
+ return
+ }
+ s := providersState()
+ writeJSON(rw, s)
+ keepProviders(s)
})
// Recent-call bodies are read only when their row is opened, not with
// every Providers or Gateway refresh (#1521): forty calls' bodies made
diff --git a/internal/gui/tests/providers-last-known.test.cjs b/internal/gui/tests/providers-last-known.test.cjs
new file mode 100644
index 000000000..f2d4df9fd
--- /dev/null
+++ b/internal/gui/tests/providers-last-known.test.cjs
@@ -0,0 +1,120 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// #1519 (fatkun): the Providers page showed skeletons for as long as
+// /api/providers took, seconds after a start. Like the Agents page, it now
+// draws the list kept from the last read (/api/providers?last=1) at once,
+// and the fresh one replaces it when it is in; a row opens only on the
+// fresh list, since the kept one leaves out headers and proxies. Started on
+// another page, the app reads the list in the background once the state is
+// in, and the Providers page opens on it without a skeleton. With nothing
+// kept, the page shows its skeletons until the read, as before.
+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");
+const SLOW = 1500; // each fresh read of the list
+const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
+
+const provider = (name, extra) => ({
+ id: "relay", name, icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
+ models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], keyList: [],
+ key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, ...extra,
+});
+const list = (p) => ({ providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } });
+// without the server's "last": true, as most pages' fixtures answer
+// ?last=1 with the full list: the page knows it kept by where it came from
+const keptList = list(provider("Kept Relay"));
+const freshList = list(provider("Fresh Relay", { headers: { "X-Team": "t1" }, proxy: "" }));
+
+function serve(lang, kept, reads) {
+ const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
+ return async (route) => {
+ const url = new URL(route.request().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};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json(url.searchParams.get("last") === "1" ? null : state);
+ if (url.pathname === "/api/providers") {
+ if (url.searchParams.get("last") === "1") return json(kept ? keptList : null);
+ reads.asked++;
+ await new Promise((r) => setTimeout(r, SLOW));
+ reads.done++;
+ return json(freshList);
+ }
+ if (url.pathname === "/api/groups") return json({ groups: [] });
+ 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 route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+async function open(engine, t, lang, kept, view, width = 900) {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ const reads = { asked: 0, done: 0 };
+ await page.route("**/*", serve(lang, kept, reads));
+ await page.goto("http://magpie.test/?view=" + view);
+ return { page, errors, reads };
+}
+
+const row = (page) => page.locator("#providers .row.provider:not(.pv-sk-row)");
+const skeletons = (page) => page.locator("#providers .pv-sk-row");
+const name = (page) => row(page).first().locator(".name").evaluate((e) => e.firstChild.textContent);
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of LANGS) {
+ test(`${engine} ${lang}: the Providers page draws the kept list at once, then the fresh one`, async (t) => {
+ const { page, errors, reads } = await open(engine, t, lang, true, "providers", 420);
+ await row(page).first().waitFor();
+ assert.equal(reads.done, 0, "the rows came only with the fresh read");
+ assert.equal(await name(page), "Kept Relay");
+ assert.equal(await page.evaluate(() => document.querySelector("#view-providers").classList.contains("loading")), false);
+ await page.waitForFunction(() => document.querySelector("#providers .row.provider .name")?.firstChild.textContent === "Fresh Relay", null, { timeout: SLOW + 4000 });
+ assert.equal(reads.asked, 1, "one fresh read");
+ assert.equal(await row(page).count(), 1);
+ assert.equal(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), true, "no sideways scroll at narrow width");
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine} ${lang}: a row clicked on the kept list opens on the fresh one`, async (t) => {
+ const { page, errors, reads } = await open(engine, t, lang, true, "providers");
+ await row(page).first().waitFor();
+ const top = await page.evaluate(() => document.querySelector("#view-providers").scrollTop);
+ await row(page).first().click();
+ await page.locator(".editor").waitFor({ timeout: SLOW + 4000 });
+ assert(reads.done >= 1, "the editor opened before the fresh list was in");
+ assert.equal(await name(page), "Fresh Relay");
+ assert.equal(await page.evaluate(() => document.querySelector("#view-providers").scrollTop), top, "the click moved the page");
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine} ${lang}: started on Agents, the Providers page is read behind it`, async (t) => {
+ const { page, errors, reads } = await open(engine, t, lang, false, "agents");
+ await page.waitForFunction(() => document.querySelector("#view-agents") && !document.querySelector("#view-agents").classList.contains("loading"));
+ for (let i = 0; i < 100 && reads.done < 1; i++) await page.waitForTimeout(50);
+ assert.equal(reads.done, 1, "the list was not read in the background");
+ await page.locator('#nav button[data-view="providers"]').click();
+ await row(page).first().waitFor({ timeout: 1000 });
+ assert.equal(await skeletons(page).count(), 0, "skeletons drawn over a list read in the background");
+ assert.equal(await name(page), "Fresh Relay");
+ assert.deepEqual(errors, []);
+ });
+
+ test(`${engine} ${lang}: with nothing kept, skeletons until the read`, async (t) => {
+ const { page, errors, reads } = await open(engine, t, lang, false, "providers");
+ await skeletons(page).first().waitFor();
+ assert.equal(await row(page).count(), 0);
+ await row(page).first().waitFor({ timeout: SLOW + 4000 });
+ assert.equal(reads.asked, 1);
+ assert.equal(await name(page), "Fresh Relay");
+ assert.deepEqual(errors, []);
+ });
+ }
+}
diff --git a/internal/gui/tests/sidebar.test.cjs b/internal/gui/tests/sidebar.test.cjs
index 71253892a..8f2da1208 100644
--- a/internal/gui/tests/sidebar.test.cjs
+++ b/internal/gui/tests/sidebar.test.cjs
@@ -151,7 +151,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await context.close();
});
- await t.test("narrow from the start: the gateway is not read for a sidebar", async () => {
+ await t.test("narrow from the start: the gateway is not read again for a sidebar", async () => {
const reads = [];
const context = await browser.newContext({ viewport: { width: 900, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
@@ -159,11 +159,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.goto("http://magpie.test/");
await page.waitForSelector("#nav button.on");
await page.waitForTimeout(2000);
- assert.equal(reads.length, 0, "no read with no sidebar to show it");
- // and read when the window is made wide
+ // the providers list is read once after the start, for the
+ // Providers page to open on it (#1519), and nothing more with no
+ // sidebar to show its gateway
+ assert.equal(reads.length, 1, "read once, for the Providers page");
+ // made wide, the sidebar shows the gateway from that read
await page.setViewportSize({ width: 1200, height: 700 });
await page.locator("#sideGw").waitFor();
- assert.equal(reads.length, 1);
+ await page.waitForTimeout(500);
+ assert.equal(reads.length, 1, "the sidebar reads nothing more");
await context.close();
});