// 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"; // focus without a scroll, as every focus call here asks const NO_SCROLL = { preventScroll: true }; // a Mac window hidden by orderOut leaves its page drawing: the app says so (#4293) let outOfSight = false, asleep; for (const [k, off] of [["hidden", true], ["visibilityState", "hidden"]]) { const own = Object.getOwnPropertyDescriptor(Document.prototype, k)?.get; try { own && Object.defineProperty(Document.prototype, k, { configurable: true, get() { return outOfSight ? off : own.call(this); } }); } catch {} } window.magpieWindowVisibility = (v) => { if (outOfSight !== v) return; outOfSight = !v; const c = document.documentElement.classList; c.toggle("magpie-out-of-sight", outOfSight); // out of sight 30s: let go of layers, laid out now since a hidden page // never draws (#5530) clearTimeout(asleep); c.remove("magpie-asleep"); if (outOfSight && mode == "window") asleep = setTimeout(() => { c.add("magpie-asleep"); document.body.offsetWidth; }, 3e4); document.dispatchEvent(new Event("visibilitychange")); }; addEventListener("focus", () => magpieWindowVisibility(true)); // focused is on screen // kept: magpie. in localStorage as JSON; d when none, not d's kind or // unreadable. keep writes one, for this time only if it can't be kept function kept(k, d) { try { const v = JSON.parse(localStorage.getItem("magpie." + k)); return v && typeof v == typeof d && Array.isArray(v) == Array.isArray(d) ? v : d; } catch { return d; } } function keep(k, v) { try { localStorage.setItem("magpie." + k, JSON.stringify(v)); } catch {} } // The panel stays attached to the tray; on Linux it is dragged by its // header, as KWin places a Wayland window with no title bar (#1283, #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; // the version that served this page, for servedAnew const pageVersion = window.bootPrefs?.version || ""; // magpie web seen from another computer: localhost is the viewer's (curtinp118) const remotePage = web && !/^(localhost|127(\.\d+){3}|\[::1\]|::1)$/i.test(location.hostname); // layout.js applies the mode and platform before the header can paint. // Gateway mode (gatewaymode.go): magpie web serving only other computers' // agents leaves out this one's agents' pages (Agents, the Library but MCP) // and settings, until Settings › General turns it off. let gatewayMode = web && !!window.bootPrefs?.gateway; const GATEWAY_HIDES = ["agents"]; // Plugins › Built-in (builtins.go, Lxxyx): the window's parts switched off, // by id. data-feature="" leaves by a style while off; its tab leaves the // nav (navHides), a link opens Agents (show), Settings skips its rows. // boot.js says which before paint, applyFeatures after. data-feature-off is // there only while off: where a page says what went (bigbenniu). 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(), off = [...featuresOff].map((id) => `[data-feature-off~="${id}"]`).join(","); st.textContent = (sel ? sel + "{display:none!important}" : "") + (off ? `[data-feature-off]:not(${off})` : "[data-feature-off]") + "{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 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 advanced = null; // { of, open }: the editor's Advanced as it was opened or closed by hand, kept by // what the editor edits (editing), not its draft: a move to the plugin or a // refresh made under it starts a new draft, and the fold stays as left 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; // the Partners heading's light has run since the sheet opened (shinePartners) let partnersShone = false; 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(kept("discoveryIgnored", [])); const modelFavorites = new Set(kept("modelFavorites", [])); // 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); // The reads the page asks for again and again and mostly finds the same // (writeJSONSame in api.go): the tag of the answer last read goes with the // next ask, and an answer that is the same comes back with no body and is // the object read before. The Sessions tab's ~8 MB list was read, parsed and // compared every 15 s over a long history. const sameReads = new Map(); const readsSame = (path) => /^sessions(\?|$)|^sessions\/stats\?/.test(path); // each such answer's tag: two answers with tags are the same only when they // are one object, so the Sessions tab needn't compare ~8 MB to know const readTags = new WeakMap(); // 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 same = body === undefined && readsSame(path); const had = same ? sameReads.get(path) : undefined; const res = await fetch("/api/" + path, { method: body === undefined ? "GET" : "POST", headers: had ? { "Content-Type": "application/json", "X-Magpie-Had": had.tag } : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), signal, }); if (body === undefined) await skelHold(); heads?.(res.headers); if (had && res.ok && res.headers.get("X-Magpie-Same")) return had.data; 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.code = data.code; 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?.code === "config_blocked") { // a folder magpie can't write: Repair offered err.code = data.code; err.message = t("magpie can't save into {path}: it belongs to another user", { path: data.blocked }); setTimeout(() => configBlockedAsk(data.blocked), 0); } if (data?.why) err.why = data.why; // a failed move's reason, said in the reader's language if (data?.said) err.message = t(data.said, data); // an i18n.js key (api.go) // 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" || data?.code === "signed_in_only") { err.code = data.code; const v = { agent: { codex: "Codex", claude: "Claude Code" }[data.agent] || data.agent, user: data.user }; err.message = data.code === "signed_in_only" ? t("{agent} is signed in to {user}, the only account in magpie it can be signed in to, and magpie doesn't sign it out: add another account first, or sign out in {agent} itself, then remove this one", v) : 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", v); } // 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); // a list changed since the one the page has (writeJSONRows in api.go): // only its new rows are sent, and [from, count] for each run of the old const delta = had && res.headers.get("X-Magpie-Delta"); const was = delta && had.data?.[delta]; if (Array.isArray(was) && Array.isArray(data?.[delta])) data[delta] = data[delta].flatMap((r) => Array.isArray(r) ? was.slice(r[0], r[0] + r[1]) : [r]); const tag = same && res.headers.get("X-Magpie-Tag"); if (tag) { sameReads.set(path, { tag, data }); if (data && typeof data === "object") readTags.set(data, tag); } 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 "