diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 50743e7b5..57d006bdc 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2083,6 +2083,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .copy:hover { background: var(--pill-hover); color: var(--fg); } .copy.done { color: var(--green); background: var(--green-soft); animation: copy-pop .36s var(--ease); } @keyframes copy-pop { 0% { transform: scale(.55); } 55% { transform: scale(1.16); } 100% { transform: scale(1); } } +/* the snippet's language, and beside it the shell it is for (#1514); + a narrow window puts the shell on a row of its own */ +.snip-tabs { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; } .snip-wrap { position: relative; min-width: 0; } .snip { margin: 0; padding: 10px 40px 10px 12px; border-radius: 9px; background: var(--card); border: 1px solid var(--line); overflow-x: auto; line-height: 1.55; } .snip code { font-size: 11.5px; color: var(--fg); white-space: pre; user-select: text; -webkit-user-select: text; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 721aec276..a556c7d5e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -54,6 +54,7 @@ try { discoveryIgnored = new Set(JSON.parse(localStorage.getItem("magpie.discove // the gateway tab's choices, kept per machine let flavor = params.get("flavor") || localStorage.getItem("magpie.flavor") || "openai"; // which API the snippets speak let lang = params.get("lang") || localStorage.getItem("magpie.lang") || "shell"; // which snippet +let snipOS = localStorage.getItem("magpie.snipOS") || ""; // the shell the Shell and curl snippets are for (#1514) let exampleModel = localStorage.getItem("magpie.model") || ""; // the model in the snippets let decideModel = localStorage.getItem("magpie.decideModel") || ""; // the System One snippets' decision model let connectFolded = false; // Connect folded away under its heading @@ -6255,20 +6256,49 @@ const a = (await r.json()).answers.team; console.log(a.choice, a.confidence);`, }, }; -// Windows gets PowerShell: $env: in place of export, and the curl.exe that -// ships with it (plain curl there is Invoke-WebRequest). The body goes in -// on stdin, since Windows PowerShell drops the quotes inside an argument. +// The Shell and curl snippets are written for one shell: PowerShell on +// Windows ($env: in place of export, and the curl.exe that ships with it, +// as plain curl there is Invoke-WebRequest; the body goes in on stdin, +// since Windows PowerShell drops the quotes inside an argument), or a POSIX +// shell (bash, zsh) on macOS and Linux. They start as the shell of the +// machine magpie runs on, and can be switched to the other: a Windows +// desktop's user often runs them on a Linux server over ssh (FourLeafTec, +// #1514). The choice is kept with the snippet language. const WIN = /^Win/.test(navigator.platform); -const LANGS = [["shell", WIN ? "PowerShell" : "Shell"], ["curl", "curl"], ["python", "Python"], ["node", "Node"]]; +const SNIP_OSES = [["windows", "Windows"], ["unix", "macOS · Linux"]]; +const snipWin = () => (SNIP_OSES.some(([id]) => id === snipOS) ? snipOS : WIN ? "windows" : "unix") === "windows"; +const langs4 = () => [["shell", snipWin() ? "PowerShell" : "Shell"], ["curl", "curl"], ["python", "Python"], ["node", "Node"]]; + +// A word each shell takes as it is, quoted only where it has to be: a key +// of the user's own can hold any ASCII symbol (", $, `, ', !), and a model +// id brackets ([1m]) that zsh would glob; a comma would make PowerShell +// pass a list. +const plainWord = /^[\w%+=:./-]+$/; +const shQuote = (s) => (plainWord.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`); +// in "…" for a header's spaces, unless it holds what bash expands there +const shHeader = (s) => (/[$`"\\!]/.test(s) ? `'${s.replaceAll("'", `'\\''`)}'` : `"${s}"`); +const psQuote = (s) => (plainWord.test(s) ? s : `'${s.replace(/['‘’‚‛]/g, "$&$&")}'`); +// "…" as the C runtime splits a command line: \" for a quote, and the +// backslashes before one doubled +const winArg = (s) => (plainWord.test(s) ? s : `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`); +const psHeader = (s) => (/[$`"“”„]/.test(s) ? `'${s.replace(/['‘’‚‛]/g, "$&$&")}'` : `"${s}"`); function curlSnippet({ url, headers, body }) { headers = [...headers, "Content-Type: application/json"]; - if (WIN) return `@'\n${body}\n'@ | curl.exe ${url} \`\n${headers.map((h) => ` -H "${h}" \``).join("\n")}\n --data-binary "@-"`; - return `curl ${url} \\\n${headers.map((h) => ` -H "${h}" \\`).join("\n")}\n -d '${body.replaceAll("\n", "\n ")}'`; + // curl reads [ ] { } in a URL as a range unless told not to + const g = /[[\]{}]/.test(url) ? " -g" : ""; + // A " inside an argument reaches curl.exe differently from Windows + // PowerShell 5.1 and from PowerShell 7, and whole from neither as + // written; after --% the line goes to curl.exe as it stands, on one line, + // quoted as the C runtime reads a command line. (A %NAME% of a variable + // the shell has is still put in there; a key would have to hold both.) + if (snipWin() && headers.some((h) => h.includes('"'))) return `@'\n${body}\n'@ | curl.exe --%${g} ${winArg(url)} ${headers.map((h) => `-H ${winArg(h)}`).join(" ")} --data-binary "@-"`; + if (snipWin()) return `@'\n${body}\n'@ | curl.exe${g} ${psQuote(url)} \`\n${headers.map((h) => ` -H ${psHeader(h)} \``).join("\n")}\n --data-binary "@-"`; + return `curl${g} ${shQuote(url)} \\\n${headers.map((h) => ` -H ${shHeader(h)} \\`).join("\n")}\n -d '${body.replaceAll("'", `'\\''`).replaceAll("\n", "\n ")}'`; } function envSnippet(vars) { - return vars.map(([k, v]) => (WIN ? `$env:${k}="${v}"` : `export ${k}=${v}`)).join("\n"); + return vars.map(([k, v]) => (snipWin() ? `$env:${k}=${psHeader(v)}` : `export ${k}=${shQuote(v)}`)).join("\n"); } // a decision model on the list: one only System One asks, never an agent @@ -6424,7 +6454,7 @@ function renderConnect() { model = exampleModel || "provider/model"; } // no SDK speaks System One, so it has no shell variables to set - const langs = f.baseEnv ? LANGS : LANGS.filter(([id]) => id !== "shell"); + const langs = f.baseEnv ? langs4() : langs4().filter(([id]) => id !== "shell"); const snipLang = langs.some(([id]) => id === lang) ? lang : "curl"; const urls = [g.url, ...(g.lanURLs || [])]; // the address picked is kept (coeo91): an address not offered right now @@ -6493,7 +6523,22 @@ function renderConnect() { : t(models.length ? "provider/model, as listed below. Click a model there to put it in the snippets." : "No models yet. Add a provider, or sign in to Codex or Copilot."))); const ex = el("div", "stack"); - ex.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); })); + const tabs = el("div", "snip-tabs"); + tabs.append(segs(langs, snipLang, (id) => { lang = id; localStorage.setItem("magpie.lang", id); renderConnect(); })); + // the shell the Shell and curl snippets are for; Python and Node read the same everywhere + if (snipLang === "shell" || snipLang === "curl") { + const os = segs(SNIP_OSES.map(([id, name]) => [id, t(name)]), snipWin() ? "windows" : "unix", (id) => { + snipOS = id; + try { localStorage.setItem("magpie.snipOS", id); } catch {} + renderConnect(); + }); + os.classList.add("snip-os"); + os.setAttribute("role", "group"); + os.setAttribute("aria-label", t("Where the snippet runs")); + os.title = t("Where the snippet runs"); + tabs.append(os); + } + ex.append(tabs); const code = !secret ? t(key ? "Loading gateway key…" : "Create a gateway key above to connect") : snipLang === "shell" ? envSnippet([[f.baseEnv, base], [f.keyEnv, secret]]) : snipLang === "curl" ? curlSnippet(f.curl(base, model, secret)) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d184d2255..1ba127fc2 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2283,6 +2283,9 @@ const I18N = { "Example": "示例", "Snippet": "代码片段", "Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.": "将这些写入 shell(或工具设置),工具即改连 magpie,而非直连供应商。", + "Windows": "Windows", + "macOS · Linux": "macOS · Linux", + "Where the snippet runs": "在哪里运行这段代码", "Copy all ids": "复制全部 ID", "No models exposed yet": "尚未暴露任何模型", "All models": "全部模型", @@ -6800,6 +6803,9 @@ const I18N = { "Example": "範例", "Snippet": "程式碼片段", "Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.": "將這些寫入 shell(或工具設定),工具即改連 magpie,而非直連供應商。", + "Windows": "Windows", + "macOS · Linux": "macOS · Linux", + "Where the snippet runs": "在哪裡執行這段程式碼", "Copy all ids": "複製全部 ID", "No models exposed yet": "尚未暴露任何模型", "All models": "全部模型", @@ -11314,6 +11320,9 @@ const I18N = { "Example": "例", "Snippet": "スニペット", "Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.": "これらをシェル(またはツールの設定)に入れると、ツールはベンダーではなく magpie と通信します。", + "Windows": "Windows", + "macOS · Linux": "macOS · Linux", + "Where the snippet runs": "スニペットを実行する場所", "Copy all ids": "すべての ID をコピー", "No models exposed yet": "公開されているモデルはまだありません", "All models": "すべてのモデル", @@ -15827,6 +15836,9 @@ const I18N = { "Example": "Beispiel", "Snippet": "Snippet", "Put these in the shell (or the tool's settings) and the tool talks to magpie instead of the vendor.": "Tragen Sie diese in der Shell (oder in den Einstellungen des Tools) ein, dann spricht das Tool mit magpie statt mit dem Anbieter.", + "Windows": "Windows", + "macOS · Linux": "macOS · Linux", + "Where the snippet runs": "Wo das Snippet läuft", "Copy all ids": "Alle IDs kopieren", "No models exposed yet": "Noch keine Modelle freigegeben", "All models": "Alle Modelle", diff --git a/internal/gui/tests/connect-snippet-shell.test.cjs b/internal/gui/tests/connect-snippet-shell.test.cjs new file mode 100644 index 000000000..1ea06783b --- /dev/null +++ b/internal/gui/tests/connect-snippet-shell.test.cjs @@ -0,0 +1,134 @@ +const assert = require("node:assert/strict"); +const http = require("node:http"); +const { execFile, execFileSync } = require("node:child_process"); +const run = require("node:util").promisify(execFile); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +// FourLeafTec on #1514: at home on Windows, but mostly running things on a +// Linux server over ssh. Connect's Shell and curl snippets start as the +// shell of the machine magpie runs on and can be switched to the other: +// PowerShell ($env:, curl.exe, the body in a here-string) or a POSIX shell +// (export, curl, the body in '…'). The pick is kept, a click on it doesn't +// move the page, and the POSIX snippets run in bash and zsh as written, with +// a key of the user's own that holds quotes, $, ! and a backtick. +const SECRET = "k'ey\"$HOME!`x\\y"; + +// a stand-in for the gateway: answers with what it was sent +async function echoServer(t) { + const got = []; + const server = http.createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + got.push({ url: req.url, headers: req.headers, body }); + res.setHeader("Content-Type", "application/json"); + res.end("{}"); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + t.after(() => new Promise((r) => server.close(r))); + return { base: `http://127.0.0.1:${server.address().port}`, got }; +} +const shells = ["bash", "zsh"].filter((sh) => { try { execFileSync("which", [sh]); return true; } catch { return false; } }); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 390]) { + test(`${engine} ${lang} ${width}: the Shell and curl snippets are for Windows or macOS · Linux, as picked`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const open = async (platform) => { + const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" }); + await context.addInitScript((p) => Object.defineProperty(Navigator.prototype, "platform", { get: () => p }), platform); + const page = await context.newPage(); + page.setDefaultTimeout(6000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const serve = fixture(lang, "light", [], { lan: true }); + // the gateway key picked is one of the user's own, quotes and all + await page.route("**/*", (route) => serve(new Proxy(route, { get: (r, k) => k !== "fulfill" ? r[k].bind?.(r) ?? r[k] + : (o) => r.fulfill(new URL(r.request().url()).pathname.endsWith("/copy-key") ? { ...o, json: { ...o.json, secret: SECRET } } : o) }))); + return { page, errors }; + }; + const snip = (page) => page.locator("#connect pre.snip").textContent(); + const tab = (page, name) => page.locator("#connect .segs:not(.snip-os) .opt", { hasText: new RegExp(`^${name}$`) }); + const os = (page, name) => page.locator("#connect .snip-os .opt", { hasText: name }); + const until = (page, fn, arg) => page.waitForFunction(fn, arg); + const snipIs = (page, re) => until(page, (src) => new RegExp(src).test(document.querySelector("#connect pre.snip")?.textContent || ""), re.source); + + // on Windows, with the address another machine uses: PowerShell still + const { page, errors } = await open("Win32"); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#connectAddress").click(); + await page.locator(".proto-menu .pm-item", { hasText: "192.168.1.10" }).click(); + await page.locator(".proto-menu").waitFor({ state: "detached" }); + await tab(page, "PowerShell").click(); + await snipIs(page, /OPENAI_API_KEY=.*k/); + assert.equal(await snip(page), `$env:OPENAI_BASE_URL="http://192.168.1.10:3999/v1"\n$env:OPENAI_API_KEY='k''ey"$HOME!\`x\\y'`); + assert.equal(await os(page, "Windows").getAttribute("aria-pressed"), "true"); + + // picked macOS · Linux: export, and nothing moves under the click + const at = async () => page.evaluate(() => [document.querySelector("#connect .snip-os").getBoundingClientRect().top, + document.scrollingElement.scrollTop, document.querySelector("#view-gateway").scrollTop]); + const before = await at(); + await os(page, "macOS · Linux").click(); + await snipIs(page, /^export /); + assert.deepEqual(await at(), before, "the click moved the page"); + assert.equal(await tab(page, "Shell").count(), 1); + const env = await snip(page); + assert.equal(env, `export OPENAI_BASE_URL=http://192.168.1.10:3999/v1\nexport OPENAI_API_KEY='k'\\''ey"$HOME!\`x\\y'`); + for (const sh of shells) { + const { stdout: out } = await run(sh, ["-c", `${env}\nprintf '%s\\n' "$OPENAI_BASE_URL" "$OPENAI_API_KEY"`]); + assert.equal(out, `http://192.168.1.10:3999/v1\n${SECRET}\n`, sh); + } + + // curl, as a POSIX shell runs it: the key and the body arrive whole + await tab(page, "curl").click(); + await snipIs(page, /^curl http:\/\/192\.168\.1\.10:3999\/v1\/chat\/completions /); + const curl = await snip(page); + assert.doesNotMatch(curl, /curl\.exe|@'/); + for (const sh of shells) { + const srv = await echoServer(t); + // async: the stand-in answers on this process's own loop + await run(sh, ["-c", curl.replace("http://192.168.1.10:3999", srv.base) + " -sS -o /dev/null --max-time 10"]); + assert.equal(srv.got.length, 1, sh); + assert.equal(srv.got[0].url, "/v1/chat/completions"); + assert.equal(srv.got[0].headers.authorization, `Bearer ${SECRET}`, sh); + assert.equal(JSON.parse(srv.got[0].body).messages[0].content, "hi", sh); + } + + // kept across a reload; then back to Windows: curl.exe, the body on stdin + await page.reload(); + await snipIs(page, /^curl http/); + assert.equal(await os(page, "macOS · Linux").getAttribute("aria-pressed"), "true"); + await os(page, "Windows").click(); + await snipIs(page, /^@'\n/); + const ps = await snip(page); + // a " in the key: the line goes to curl.exe as written, after --% + assert.equal(ps.split("\n").at(-1), `'@ | curl.exe --% http://192.168.1.10:3999/v1/chat/completions -H "Authorization: Bearer k'ey\\"$HOME!\`x\\y" -H "Content-Type: application/json" --data-binary "@-"`); + + // Python and Node read the same everywhere: no shell to pick + await tab(page, "Python").click(); + await snipIs(page, /from openai import OpenAI/); + assert.equal(await page.locator("#connect .snip-os").count(), 0); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.deepEqual(errors, []); + + // on a Mac nothing was picked yet: macOS · Linux + const mac = await open("MacIntel"); + await mac.page.goto("http://magpie.test/?view=gateway"); + await tab(mac.page, "curl").click(); + await snipIs(mac.page, /^curl http/); + assert.equal(await os(mac.page, "macOS · Linux").getAttribute("aria-pressed"), "true"); + // this computer's key, with nothing to quote: one -H a line + await os(mac.page, "Windows").click(); + await snipIs(mac.page, /^@'\n/); + assert.match(await snip(mac.page), /\n'@ \| curl\.exe http:\/\/127\.0\.0\.1:3999\/v1\/chat\/completions `\n {2}-H "Authorization: Bearer magpie" `\n {2}-H "Content-Type: application\/json" `\n {2}--data-binary "@-"$/); + assert.equal(await mac.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.deepEqual(mac.errors, []); + }); + } + } +}