// magpie — one state object per view, rendered into a list. No framework. const $ = (s) => document.querySelector(s); const $$ = (s) => document.querySelectorAll(s); const params = new URLSearchParams(location.search); const mode = params.get("mode") || "window"; // The panel loads Wails for ExecJS readiness, but stays attached to the tray. // On Linux it is dragged by its header like the window: a Wayland window // can't be put by the icon, so KWin places it, and since it has no KWin // title bar (#1283) the header is the only handle it has (#1430). if (mode === "panel" && !document.body.classList.contains("linux")) $("header.top").style.setProperty("--wails-draggable", "no-drag"); // `magpie web`: the page in a browser tab, with no window of the app's // around it — it opens links itself, and what is the desktop's is left out const web = !!window.bootPrefs?.web; // layout.js applies the mode and platform before the header can paint. // Gateway mode (gatewaymode.go): magpie web on a server that is only the // gateway for other computers' agents leaves out this computer's agents' // pages — Agents, Sessions, Library — and their settings; Settings › // General turns it off, and they are back. let gatewayMode = web && !!window.bootPrefs?.gateway; const GATEWAY_HIDES = ["agents", "library"]; // Plugins › Built-in (builtins.go; Lxxyx on X: too much to look through): // the optional parts of the window switched off, by id. Whatever is marked // data-feature="" leaves the page while its feature is off — by a // style, so what a page draws later goes too — a page's tab leaves the nav // (navHides), a link to the page opens Agents (show), and Settings and its // search pass over its rows. boot.js says which before the first paint, // each read of the settings after (applyFeatures). The gateway is the // same either way. let featuresOff = new Set(window.bootPrefs?.featuresOff || []); const featureSel = () => [...featuresOff].map((id) => `[data-feature~="${id}"]`).join(","); const featureHides = (n) => { const sel = featureSel(); return !!sel && !!n?.closest(sel); }; function featureStyle() { let st = document.getElementById("featureStyle"); if (!st) { st = document.createElement("style"); st.id = "featureStyle"; document.head.append(st); } const sel = featureSel(); st.textContent = sel ? sel + "{display:none!important}" : ""; } featureStyle(); // a page a plugin adds (kernel.js) that draws from /api/providers, as the // Gateway page does: read with Providers and Routing, and drawn through its // hooks const providersPage = (v) => magpie.page(v)?.loads === "providers"; // The window is dragged by its header, and only where the header says so // (--wails-draggable), so the tabs and buttons in it stay plain clicks. // Outside the app — a browser on the gateway's page, or on `magpie web` — // there is no runtime, and it isn't asked for (a 404 in the browser's // console, Jorben on Discord). // The panel also needs runtime readiness to drain Go's queued ExecJS calls. const winRuntime = !web ? import("/wails/runtime.js").catch(() => null) : Promise.resolve(null); // theme.js already applied the theme and text size before the first paint. if (window.bootPrefs) setLocale(window.bootPrefs.lang); let state = { agents: [], profiles: [], catalog: "", settings: {} }; let prefs = null; // the settings page: theme, lang, version, dir, gateway let providers = null; // { providers, presets, gateway } let view = "agents"; let showAllAgents = false; // the agents no one has set anything on, folded away let showHiddenAgents = false; // under them, the ones hidden by hand: a fold of their own, shut until asked let period = "today"; // usage window let usage = null; // last usage summary let usageHidOpen = false; // the Usage page's hidden agents shown under their line let pick = null; // { agent, field, options, items, cursor, anchor } let editing = null; // provider id being edited; { preset } or { custom: true } for a new one let draft = null; // the editor's working copy let naming = null; // the provider whose models' names and levels are open in its editor let adding = false; // the preset sheet is open // the partners counted as shown since the sheet opened: once an opening, // however often it is drawn (countPartner) let partnersCounted = null; let importing = null; // a magpie://import link waiting for a yes: { provider, error, replaces } let importingApps = null; // the Import from other apps dialog: { sources, picks } let providerDiscovery = []; // only opaque fingerprints and app names, never credentials let discoveryAt = 0, discoveryRun = 0, discoveryPending = false; let discoveryIgnored = new Set(); try { discoveryIgnored = new Set(JSON.parse(localStorage.getItem("magpie.discoveryIgnored") || "[]")); } catch {} // a streamed reply's body is read as its reply, its events or as it came; // the pick is one for every call and kept, the events drawn per call let sseView = "events"; try { sseView = localStorage.getItem("magpie.sseView") || "events"; } catch {} const sseShown = new Map(); // call id → how many events are drawn let savedModelFavorites = []; try { savedModelFavorites = JSON.parse(localStorage.getItem("magpie.modelFavorites") || "[]"); } catch {} const modelFavorites = new Set(Array.isArray(savedModelFavorites) ? savedModelFavorites : []); // A model through magpie is starred as its catalog id, which is the same in // every agent; the agent's own models by their value. Stars kept by value // before still count. const favoriteKey = (o) => o.ref || o.value; const isFavorite = (o) => modelFavorites.has(favoriteKey(o)) || modelFavorites.has(o.value); // heads, when given, is shown the answer's headers (loadQuotas' X-Magpie-Reading); // signal, when given, cancels the request (a read the reader moved on from) async function api(path, body, heads, signal) { if (web && path === "open") { window.open(body.url, "_blank", "noopener"); return null; } // a segment may be an agent id, and omp's named profiles are omp#: // left raw, the browser reads #work as the fragment and the request // reaches the default omp row (#1187). Only # is encoded: ? = & stay a // query string, which encodeURIComponent would turn into a 404. path = path.replace(/#/g, "%23"); const res = await fetch("/api/" + path, { method: body === undefined ? "GET" : "POST", headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal, }); heads?.(res.headers); if (res.status === 204) return null; // a body that isn't JSON (a proxy's or a plain http.Error) is the error // itself, not WebKit's "did not match the expected pattern" const text = await res.text(); let data; try { data = text ? JSON.parse(text) : null; } catch { throw new Error(notJSON(res, text)); } if (!res.ok) { const err = new Error(data?.error || `${res.status} ${res.statusText}`); if (data?.code === "runtime_unavailable") { err.code = data.code; if (data.offline === "stage" || data.offline === "disconnect") err.offline = data.offline; } // magpie has no models to connect an agent to yet: said in the // reader's language if (data?.code === "no_models") err.message = t("Add a provider or subscription in magpie first, then connect {agent}", { agent: data.agent }); // magpie has models, and none is left in the agent's model list (#1989) if (data?.code === "all_hidden") err.message = t("None of magpie's models is left in {agent}'s model list: pick one under Model list → Pick, then connect {agent}", { agent: data.agent }); if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language // an account the agent is signed in to, refused removal while it has // another: said in the reader's language if (data?.code === "signed_in") { err.code = data.code; err.message = t("{agent} is signed in to {user} now: sign it in to another of its accounts first (Use on that account), then remove this one", { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user }); } // a text Import can't add as a routing group (laincatx on X) if (data?.code === "share") { err.code = data.code; err.message = { newer: t("This group was shared from a newer magpie (format {n}): update magpie to import it", { n: data.format }), no_format: t("This shared group says no format it is in: copy it again with Copy to share"), unreadable: t("This shared group can't be read: copy it again with Copy to share"), none_here: t("None of the group's models is in your magpie: {models}", { models: data.models }), }[data.share] || t("This is not a routing group shared from magpie: copy one with Copy to share in a group's menu"); } // an agent's npm update whose global folder (Program Files) needs an // administrator, or RTK's winget for every user, the prompt declined or // not to be had (新v学员 on Discord): what to do, in the reader's language if (data?.code === "needs_admin") { err.code = data.code; const v = { agent: data.agent, prefix: data.prefix, cmd: data.command, why: data.reason || "" }; const where = data.prefix ? (data.canceled ? t("{agent} is installed in {prefix}, which only an administrator can change, and the administrator prompt was declined.", v) : t("{agent} is installed in {prefix}, which only an administrator can change, and magpie couldn't ask Windows for one ({why}).", v)) : (data.canceled ? t("{agent} needs an administrator here, and the administrator prompt was declined.", v) : t("{agent} needs an administrator here, and magpie couldn't ask Windows for one ({why}).", v)); err.message = where + " " + (data.via === "winget" ? t("Try again and allow it, or run {cmd} in a terminal opened as administrator.", v) : t("Update again and allow it, run {cmd} in a terminal opened as administrator, or move npm's global folder to one of your own (npm config set prefix \"%APPDATA%\\npm\") and install {agent} again.", v)); } throw err; } // the accounts it names, for Hide accounts to know them (#568); a // session's or a library's words aren't looked through if (data && typeof data === "object" && !/^(sessions|library|skills|plugins|market)/.test(path)) noteAccounts(data); return data; } // notJSON is what an answer that isn't magpie's JSON says. A web page is // a proxy's or a tunnel's own, not magpie's: magpie web behind Cloudflare // got its 524 page when an install outlasted Cloudflare's 100 seconds, // shown as "