diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 681aa6d29..26e9d73ab 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8281,6 +8281,7 @@ function iconPicker(ed) { for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); const data = await api("icons", { data: btoa(bin) }); draft.icon = data.icon; + draft.iconFrom = ""; editorError(""); draw(); syncHead(); @@ -8297,15 +8298,18 @@ function iconPicker(ed) { site.setAttribute("aria-haspopup", "menu"); site.setAttribute("aria-expanded", "false"); site.append(svg(CHEV, 11, 1.7)); + // true when the picture is the icon now (hoobnn) const get = async (path, body) => { site.disabled = true; site.textContent = t("Looking…"); - let note = "", kind = "warn"; + let note = "", kind = "warn", ok = false; try { const data = await api(path, { name: draft.name || "", ...body }); draft.icon = data.icon; + draft.iconFrom = body.url && !data.failed ? body.url : ""; if (data.failed) note = t("That picture couldn't be used, so the icon is the name's letters: {why}", { why: data.failed }); - asking = !!data.failed; + asking = !!body.url; + ok = !data.failed; } catch (e) { note = e.message; kind = "err"; @@ -8313,6 +8317,13 @@ function iconPicker(ed) { draw(); syncHead(); editorError(note, kind); + return ok; + }; + // an address typed is fetched by Enter, Use, leaving the box or Save, + // not Enter alone (hoobnn) + const fetchTyped = ed.iconFlush = () => { + const v = (typed = (box.querySelector(".icon-url")?.value ?? typed).trim()); + return pending || (!asking || !v || v === draft.iconFrom ? null : (pending = get("icons/url", { url: v, base: base() }).finally(() => pending = null))); }; site.onclick = (e) => { e.stopPropagation(); @@ -8330,7 +8341,7 @@ function iconPicker(ed) { box.append(file, choose, site, builtin); if (draft.icon && draft.icon !== "generic") { const reset = el("button", "text", t("Default")); - reset.onclick = () => { draft.icon = ""; draw(); syncHead(); }; + reset.onclick = () => { draft.icon = ""; draft.iconFrom = ""; typed = ""; asking = false; draw(); syncHead(); }; box.append(reset); } if (asking) { @@ -8339,10 +8350,13 @@ function iconPicker(ed) { u.setAttribute("aria-label", t("Image URL")); u.onkeydown = (e) => { e.stopPropagation(); - if (e.key === "Escape") { asking = false; draw(); box.querySelector("[aria-haspopup]").focus({ preventScroll: true }); } - else if (e.key === "Enter" && (typed = u.value.trim()) && !site.disabled) get("icons/url", { url: typed, base: base() }); + if (e.key === "Escape") { typed = draft.iconFrom || ""; asking = false; draw(); box.querySelector("[aria-haspopup]").focus({ preventScroll: true }); } + else if (e.key === "Enter") fetchTyped(); }; - box.append(u); + u.oninput = () => typed = u.value; + const use = el("button", "text", t("Use")); + u.onchange = use.onclick = fetchTyped; + box.append(u, use); } if (open) { const grid = el("div", "icon-grid"); @@ -8360,14 +8374,14 @@ function iconPicker(ed) { const b = el("button", n === draft.icon ? "on" : ""); b.title = n.replace(/-color$/, ""); b.append(icon(n)); - b.onclick = () => { draft.icon = n; open = false; draw(); syncHead(); }; + b.onclick = () => { draft.icon = n; draft.iconFrom = ""; open = false; draw(); syncHead(); }; grid.append(b); } box.append(find, grid); find.oninput(); } }; - let open = false, seek = "", asking = false, typed = ""; + let open = false, seek = "", asking = !!draft.iconFrom, typed = draft.iconFrom || "", pending = null; // the dialog's title shows the icon too const syncHead = () => { const old = ed.querySelector(".ehead .ic"); @@ -8527,12 +8541,8 @@ document.addEventListener("pointerdown", (e) => { const find = at.dataset.pick ? `[data-pick="${CSS.escape(at.dataset.pick)}"]` : at.matches(".row.provider") ? `.row.provider[data-id="${CSS.escape(at.dataset.id)}"]` : null; pressed = { el: at, find, time: performance.now(), x: e.clientX }; }, true); -// Text cut short with an ellipsis says its whole self on hover (#721): an -// agent's status line, a long model name. Which lines are cut depends on the -// window's width, so it is measured when the pointer comes over one, and the -// title follows: set while the text is cut, gone again once it fits. A title -// the app wrote itself is never touched: data-full-tip keeps the text put here, -// and a title that no longer reads the same was written by the app since. +// Text cut short says its whole self on hover (#721), measured then; a +// title the app wrote itself is never touched (data-full-tip). document.addEventListener("mouseover", (e) => { let el = e.target instanceof Element ? e.target : null; for (let i = 0; el && i < 4 && getComputedStyle(el).textOverflow !== "ellipsis"; i++) el = el.parentElement; @@ -8556,12 +8566,8 @@ function originRect(o) { const r = at.matches(".row.provider") ? rowOwnRect(at, o.x) : at.getBoundingClientRect(); return r.width && r.height && r.bottom > 0 && r.top < innerHeight ? r : null; } -// rowOwnRect: a provider row as a tile in the add sheet is, its icon and -// name. The whole row is wider than the dialog, so the dialog couldn't -// shrink into it and opened as a full-size strip widening (the owner: "太 -// 生硬", the add sheet's tiles "特别完美"); out of this it zooms as they do. -// Pressed past them, it grows from where it was pressed (the owner: 应该从 -// 点击处放大): that much of the row, around the press. +// rowOwnRect: a provider row's icon and name, or that much of it round the +// press, for the dialog to grow out of as the add sheet's tiles do (the owner). function rowOwnRect(row, x) { const r = row.getBoundingClientRect(), who = row.querySelector(".who"); if (!who) return r; @@ -8642,21 +8648,11 @@ $("#modal").addEventListener("keydown", (e) => { e.preventDefault(); (e.shiftKey ? last : first).focus(); }); -// A dialog opens centred and stays centred while it fills in, until the -// reader's first press or key in it (the owner 10-24). From then it holds -// the place of what the reader last pressed or focused, growing and -// shrinking round it down to the window's foot, where its fields scroll. -// With no room left, its fields shorten over a pressed button below them, -// so an error line over Remove doesn't push Remove down. Centred all along, -// the line just clicked slid from under the pointer. Its place is a -// relative top and a cap on its height. A change made in the page is held -// before it is drawn (a mutation's microtask); a resize a frame later. +// A dialog stays centred while it fills in, until the reader's first press +// or key (the owner 10-24); then it holds what was last pressed in place. const modalHold = { off: 0, at: null, y: 0, cap: null, capSet: "", touched: false }; -// how far down the dialog an element sits, its animation (a row coming -// in) left out. One that scales (a Copy pop, a pressed segment) counts by -// its own unscaled top: by its holder's, a pressed segment read 2px high -// and the dialog crept down at each click (the owner, 10-23). One that -// turns or skews counts by its holder. +// how far down the dialog an element sits, its animation left out: one +// that scales by its own top (the owner, 10-23), one that turns by its holder. function modalDepth(a, d) { if (!a?.isConnected || !d.contains(a) || a === d || !a.offsetParent) return null; if (getComputedStyle(d).transform === "none") { @@ -9031,7 +9027,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p (#268): its URLs, @@ -9966,6 +9962,9 @@ function drawEditor(p, presetID) { cancel.onclick = cancelEdit; const saveBtn = el("button", "text primary", t(isNew ? "Add" : "Save")); const save = () => { + // a typed icon address first; one that fails stays (hoobnn) + const waiting = custom && ed.iconFlush?.(); + if (waiting) return waiting.then((ok) => ok && save()); // new: an Add never replaces a provider that has the id already const body = { id: p ? slug(draft.id) || p.id : draft.id, from: p?.id, name: draft.name, preset: draft.preset, key: draft.key || "", chat: draft.chat, responses: draft.responses, anthropic: draft.anthropic, gemini: (draft.gemini || "").trim(), catalog: draft.catalog, models: p ? chosenIds() : draft.extra, headers: headersOf(draft.headers), new: isNew }; if (isNew && draft.copyOf) body.copyOf = draft.copyOf; @@ -9986,7 +9985,7 @@ function drawEditor(p, presetID) { } body.baseAPI = draft.api === "openai" ? "chat" : draft.api; } - if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.balanceMethod = draft.balanceMethod || ""; body.modelsURL = (draft.modelsURL || "").trim(); } + if (custom) { body.icon = draft.icon || "generic"; body.iconFrom = draft.iconFrom || ""; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.balanceMethod = draft.balanceMethod || ""; body.modelsURL = (draft.modelsURL || "").trim(); } if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.hiddenDrawers = draft.hiddenDrawers; body.noModels = noneChosen(); body.bestInFamily = bestChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); } body.searches = !!draft.searches && searchable(); body.pinUpstream = !!draft.pinUpstream; diff --git a/internal/gui/icon_from_test.go b/internal/gui/icon_from_test.go new file mode 100644 index 000000000..f5e843d88 --- /dev/null +++ b/internal/gui/icon_from_test.go @@ -0,0 +1,52 @@ +package gui + +import ( + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// hoobnn on Discord: a custom provider's icon fetched from an image URL +// had its address gone when the editor was opened again. The address is +// saved with the picture, given back by /api/providers, kept by a save +// that doesn't name the icon, and dropped with a picture that came from +// elsewhere. +func TestProviderSaveKeepsIconFrom(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + providerRoutes(mux, nil) + do := func(method, path, body string) string { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + return w.Body.String() + } + const from = "https://cdn.example.com/logo.png" + do("POST", "/api/provider/save", `{"id":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":"k","icon":"file:00000000000000bb.png","iconFrom":"`+from+`","new":true}`) + if p, err := provider.Find("box"); err != nil || p.Icon != "file:00000000000000bb.png" || p.IconFrom != from { + t.Fatalf("the icon's address wasn't kept: %+v %v", p, err) + } + if !strings.Contains(do("GET", "/api/providers", ""), `"iconFrom":"`+from+`"`) { + t.Fatal("/api/providers doesn't give the address back") + } + // a save that doesn't name the icon (the CLI's, the TUI's) keeps both + do("POST", "/api/provider/save", `{"id":"box","from":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":""}`) + if p, err := provider.Find("box"); err != nil || p.Icon != "file:00000000000000bb.png" || p.IconFrom != from { + t.Fatalf("a save without the icon lost it: %+v %v", p, err) + } + // a built-in icon picked after: the address isn't that picture's + do("POST", "/api/provider/save", `{"id":"box","from":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":"","icon":"openai","iconFrom":"`+from+`"}`) + if p, err := provider.Find("box"); err != nil || p.Icon != "openai" || p.IconFrom != "" { + t.Fatalf("the address outlived its picture: %+v %v", p, err) + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 5d62321bf..ebe5407fd 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -85,6 +85,7 @@ type providerJSON struct { ID string `json:"id"` Name string `json:"name"` Icon string `json:"icon"` + IconFrom string `json:"iconFrom,omitempty"` // the address Icon was fetched from (provider.IconFrom) Preset string `json:"preset"` Host string `json:"host"` Chat string `json:"chat"` @@ -673,7 +674,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON { func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUse, desktop map[string]string) providerJSON { avail := ls.Available out := providerJSON{ - ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(), + ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, @@ -1917,8 +1918,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if in.BaseAPI == "" && old != nil { in.BaseAPI = old.BaseAPI } + // a save that doesn't say keeps the icon, and where it came from if in.Icon == "" && old != nil && in.Preset == "" { - in.Icon = old.Icon + in.Icon, in.IconFrom = old.Icon, old.IconFrom } // native compaction only where the wire carries it: a // signed-in account is told by the one saved diff --git a/internal/gui/tests/icon-url-saved.test.cjs b/internal/gui/tests/icon-url-saved.test.cjs new file mode 100644 index 000000000..b30688969 --- /dev/null +++ b/internal/gui/tests/icon-url-saved.test.cjs @@ -0,0 +1,155 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// hoobnn on Discord: a custom provider's icon given by an image URL wasn't +// fetched or applied, and on editing it again the URL was gone. The address +// was sent with Enter only, so one typed and saved was dropped, and nothing +// kept it. Now an address typed in the box is fetched by Save (or by Use, or +// by leaving the box), the picture and its address are saved, and the editor +// opened again shows both. One that can't be used keeps the editor open with +// the note why, and nothing is saved. In Chromium and WebKit, at 420 and +// 1100 wide, in every language. +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 ICON = { url: "file:00000000000000bb.png", other: "file:00000000000000dd.png", letter: "file:00000000000000cc.svg" }; +const GOOD = "https://cdn.example.com/logo.png", OTHER = "https://cdn.example.com/other.png", GONE = "https://cdn.example.com/gone.png"; +const FAILED = "the icon URL answered 404 Not Found"; + +function serve(lang, posts) { + const relay = { + id: "relay", name: "My Relay", icon: "generic", host: "relay.example.com", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-5", name: "gpt-5", on: true }], chosen: ["gpt-5"], + fetched: new Date(Date.now() - 3600e3).toISOString(), agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", + }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + 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};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + const body = req.method() === "POST" ? req.postDataJSON() || {} : null; + if (body && url.pathname.startsWith("/api/")) posts.push({ path: url.pathname, body }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + const list = () => ({ providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/providers") return json(list()); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/icons/url") { + if (body.url === GONE) return json({ icon: ICON.letter, failed: FAILED }); + return json({ icon: body.url === OTHER ? ICON.other : body.url ? ICON.url : ICON.letter, failed: "" }); + } + // the save is kept as the backend keeps it, for the editor's next opening + if (url.pathname === "/api/provider/save") { + relay.icon = body.icon; + if (body.iconFrom) relay.iconFrom = body.iconFrom; else delete relay.iconFrom; + return json(list()); + } + if (url.pathname.startsWith("/api/icons/")) return route.fulfill({ contentType: "image/svg+xml", body: '' }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const KEYS = ["Get icon", "Image URL…", "Image URL", "Use", "Save", "That picture couldn't be used, so the icon is the name's letters: {why}"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [420, 1100]) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${width} ${lang}: an icon's image URL typed and saved is fetched, kept and shown again`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-icon-url-saved.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + + const w = await page.evaluate(([lang, keys]) => Object.fromEntries(keys.map((k) => [k, lang === "en" ? k : I18N[lang]?.[k]])), [lang, KEYS]); + assert.deepEqual(KEYS.filter((k) => !w[k]), [], `${lang} lacks these`); + + const editor = page.locator("#modal:not([hidden]) .editor"); + const row = page.locator(".row.provider", { hasText: "My Relay" }); + const pick = editor.locator(".icon-pick"); + const box = pick.getByRole("textbox", { name: w["Image URL"] }); + const saveBtn = editor.locator(".bar").getByRole("button", { name: w.Save, exact: true }); + const open = async () => { + await row.click(); + await pick.waitFor(); + await pick.evaluate((p) => p.scrollIntoView({ block: "start" })); + }; + const posted = (p) => posts.filter((x) => x.path === p).map((x) => x.body); + const srcEnds = (sel, icon) => page.waitForFunction(([sel, src]) => document.querySelector(sel)?.getAttribute("src")?.endsWith(src), [sel, icon.slice(5)]); + const choose = async () => { + await pick.getByRole("button", { name: w["Get icon"] }).click(); + await page.locator(".proto-menu").getByRole("menuitemradio", { name: new RegExp("^" + w["Image URL…"].replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }).click(); + await box.waitFor(); + }; + + // an address typed, never Entered, then Save: fetched, then saved with it + await open(); + await choose(); + await box.fill(GOOD); + await saveBtn.click(); + await editor.waitFor({ state: "detached" }); + assert.deepEqual(posted("/api/icons/url").map((b) => b.url), [GOOD], "Save didn't fetch the typed address"); + const saves = posted("/api/provider/save"); + assert.equal(saves.length, 1); + assert.equal(saves[0].icon, ICON.url, "Save didn't send the fetched picture"); + assert.equal(saves[0].iconFrom, GOOD, "Save didn't send the address"); + await srcEnds(".row.provider img", ICON.url); + + // opened again: the picture, and its address in its box + await open(); + await srcEnds(".editor .icon-now img", ICON.url); + await box.waitFor(); + assert.equal(await box.inputValue(), GOOD, "the address wasn't shown again"); + const over = await pick.evaluate((p) => [...p.children].filter((c) => c.getBoundingClientRect().right > p.getBoundingClientRect().right + 1).map((c) => c.className || c.textContent)); + assert.deepEqual(over, [], "the icon row spills out"); + // nothing changed: Save fetches nothing again + await saveBtn.click(); + await editor.waitFor({ state: "detached" }); + assert.equal(posted("/api/icons/url").length, 1, "an unchanged address was fetched again"); + assert.equal(posted("/api/provider/save")[1].iconFrom, GOOD); + + // another address with Use, then Save + await open(); + await box.waitFor(); + await box.fill(OTHER); + await pick.getByRole("button", { name: w.Use, exact: true }).click(); + await srcEnds(".editor .icon-now img", ICON.other); + await saveBtn.click(); + await editor.waitFor({ state: "detached" }); + assert.deepEqual(posted("/api/icons/url").map((b) => b.url), [GOOD, OTHER], "Use and Save fetched it twice, or not at all"); + assert.deepEqual([posted("/api/provider/save")[2].icon, posted("/api/provider/save")[2].iconFrom], [ICON.other, OTHER]); + + // one that can't be used: the note, the editor open, nothing saved + await open(); + await box.waitFor(); + await box.fill(GONE); + await saveBtn.click(); + const note = editor.locator(".editor-error"); + await note.waitFor(); + assert.equal(await note.textContent(), w["That picture couldn't be used, so the icon is the name's letters: {why}"].replace("{why}", FAILED)); + assert(await editor.isVisible(), "the editor closed on a picture that couldn't be used"); + assert.equal(posted("/api/provider/save").length, 3, "a picture that couldn't be used was saved"); + assert.equal(await box.inputValue(), GONE); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/icon-url.test.cjs b/internal/gui/tests/icon-url.test.cjs index fec957266..7cd393d82 100644 --- a/internal/gui/tests/icon-url.test.cjs +++ b/internal/gui/tests/icon-url.test.cjs @@ -4,7 +4,8 @@ // app's own menu (never a native select) with Automatic (the site's icon, as // before), Image URL… and Letter icon. A typed address is sent with Enter; one // the backend couldn't use comes back as the letter tile with a note saying -// why, and the box stays for another try. Escape puts the box away. What is +// why, and the box stays for another try, as does one that worked (hoobnn). +// Escape puts the box away. What is // picked is what Save sends. No click scrolls the page. In Chromium and // WebKit, at 420 and 1100 wide, in every language. const assert = require("node:assert/strict"); @@ -136,7 +137,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await box.fill("https://cdn.example.com/logo.png"); await box.press("Enter"); assert.equal((await posted("/api/icons/url")).url, "https://cdn.example.com/logo.png"); - await box.waitFor({ state: "detached" }); + // the address it came from stays in its box (hoobnn) + await page.waitForFunction((src) => document.querySelector(".editor .icon-now img")?.getAttribute("src")?.endsWith(src), ICON.url.slice(5)); + assert.equal(await box.inputValue(), "https://cdn.example.com/logo.png"); assert.equal(await note.count(), 0, "the note outlived a picture that worked"); assert((await now()).endsWith(ICON.url.slice(5))); diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4dbe47302..eb68dbca5 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -56,10 +56,14 @@ type Provider struct { // Gave are ids it had that another provider took after it (a rename // onto one, a provider added under one), each with when: the calls // recorded under such an id before then were this one's (Renames). - Gave []Gave `json:"gave,omitempty"` - Icon string `json:"icon,omitempty"` - Preset string `json:"preset,omitempty"` // preset this was created from, if any - Key string `json:"key"` // API key, as typed by the user + Gave []Gave `json:"gave,omitempty"` + Icon string `json:"icon,omitempty"` + // IconFrom is the picture's address a custom provider's Icon was + // fetched from in its editor, shown there again (hoobnn): only a + // record, never fetched again + IconFrom string `json:"iconFrom,omitempty"` + Preset string `json:"preset,omitempty"` // preset this was created from, if any + Key string `json:"key"` // API key, as typed by the user // AccessKeyID and SecretAccessKey are a Volcengine account's access // key (TakesVolcAccessKey), what Ark tells its Coding or Agent Plan's @@ -962,6 +966,10 @@ func Save(p Provider) error { } p = normalize(p) p.IconURL = "" // import-only: never stored + // where a picture came from goes only with that picture + if p.IconFrom = strings.TrimSpace(p.IconFrom); !strings.HasPrefix(p.Icon, iconPrefix) { + p.IconFrom = "" + } if p.ID == "" { p.ID = Slug(p.Name) }