gui: a copy nothing could make says so, with the text to copy by hand (#1881, BabyLy233)
copy() tried /api/copy, then navigator.clipboard.writeText, then the copy command, and when all three failed it put the bare text in the footer with no word that nothing was copied. Now that magpie refuses a copy it can't read back (the commit before), that last case is reachable in the app on Linux, so it reads "Couldn't copy. Select it here and copy it yourself: <text>" as an error (role=alert, 8s) and the button isn't flashed as copied. Translated in zh, zh-TW, ja and de. The order of the tries and the success path are unchanged, on macOS and Windows too. docs/subsystems/gui-shell.md: the host's copy row says how a Linux copy is made and checked, and where the page takes over. Run: - tests/copy-fallback.test.cjs (new): /api/copy 204 (no page copy), 501 + clipboard API, 501 + API refused + copy command, all refused; en, zh, zh-TW, ja, de; Chromium and WebKit: 40 pass. With the failure line put back to status(text), the 10 "nothing copies" cases go red. - copy-command, key-copy, model-copy-id, library-mcp-copy-config, i18n-keys: pass. - go test -tags nogui ./internal/gui: pass. Not tried: WebKitGTK's own clipboard API and copy command inside the real Linux app window when /api/copy refuses (the container run drove the host's copy directly).
This commit is contained in:
@@ -11,7 +11,7 @@ three.
|
||||
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. | [`app.go`](../../internal/gui/app.go), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) |
|
||||
| Native host | `Run` starts the Wails v3 app: the tray icon, the panel, the main window, single-instance handover, `magpie://` import links and open at login. `host` implements `Windows` for the API: show and hide, open URLs and folders, copy to the clipboard, fit and tint the panel, and set the text size. A copy on Linux sets PRIMARY before CLIPBOARD, since GTK 3 serves CLIPBOARD empty when PRIMARY is set after it on a compositor with no primary selection (KDE Plasma with middle-click paste off, #1881); on Wayland the copy is read back through the compositor, and one that doesn't read back whole answers `/api/copy` with 501, so the page tries its clipboard API, then the copy command, then says the copy failed with the text to copy by hand (`copy-fallback.test.cjs`). | [`app.go`](../../internal/gui/app.go), [`clipboard_gtk3.go`](../../internal/gui/clipboard_gtk3.go), [`clipboard_gtk3.h`](../../internal/gui/clipboard_gtk3.h), [`mainwindow.go`](../../internal/gui/mainwindow.go), [`traymenu.go`](../../internal/gui/traymenu.go) |
|
||||
| Backend | `startBackend` starts the gateway this process serves, unless another magpie already serves it. In that case this process only shows the other one's status (`gw` is nil). `stopServing` drains requests in flight. | [`backend.go`](../../internal/gui/backend.go) |
|
||||
| API and assets | `Handler` serves `assets/` (embedded with `//go:embed assets`) and the `/api/*` routes, such as `/api/state`, `/api/set` and `/api/agents/{action}/{id}`. `held` lets one API request's reads share one catalog build (`provider.Hold`), and drops it after any write. `revalidated` and `versionedPage` name each script by its content hash, so a cache never serves an old `app.js` under a new page; a file asked for under its current hash (`?v=`) is cached for good (`immutable`), anything else is revalidated by its ETag. | [`api.go`](../../internal/gui/api.go) |
|
||||
| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) |
|
||||
|
||||
@@ -6074,14 +6074,17 @@ function accountPlan(a) {
|
||||
// clipboard API is refused inside the app's window; a browser tab on the
|
||||
// dev UI falls back to it. A tab on `magpie web` reached over plain http
|
||||
// from another computer (a NAS's) has no clipboard API at all, so the
|
||||
// older copy command is the last try there.
|
||||
// older copy command is the last try there. magpie refuses a copy it
|
||||
// couldn't read back (#1881: GTK 3 on KDE Plasma without middle-click
|
||||
// paste served it empty), and the page's ways are tried then too. When
|
||||
// none copies, the page says so and shows the text to copy by hand.
|
||||
async function copy(text, what, btn, message) {
|
||||
const done = () => { status(message || t("{what} copied", { what }), "ok"); flashCopied(btn); };
|
||||
const res = await fetch("/api/copy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) }).catch(() => null);
|
||||
if (res && res.ok) return done();
|
||||
try { await navigator.clipboard.writeText(text); return done(); } catch {}
|
||||
if (copyByCommand(text)) return done();
|
||||
status(text);
|
||||
status(t("Couldn't copy. Select it here and copy it yourself: {text}", { text }), "err");
|
||||
}
|
||||
|
||||
// copyByCommand copies text with the page's copy command, through a
|
||||
|
||||
@@ -2288,6 +2288,7 @@ const I18N = {
|
||||
"Plan · Europe": "套餐 · 欧洲",
|
||||
"which endpoint {p} is reached through": "通过哪个入口访问 {p}",
|
||||
"{what} copied": "已复制{what}",
|
||||
"Couldn't copy. Select it here and copy it yourself: {text}": "复制失败,请在这里选中后自行复制:{text}",
|
||||
"Connect": "接入",
|
||||
"Loopback only · the key can be anything": "仅限本机回环 · 密钥可以随意填",
|
||||
"Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.": "Chat Completions,多数工具使用的 API。任何可设置 OpenAI base URL 的工具都能用。",
|
||||
@@ -6867,6 +6868,7 @@ const I18N = {
|
||||
"Plan · Europe": "套餐 · 歐洲",
|
||||
"which endpoint {p} is reached through": "透過哪個入口存取 {p}",
|
||||
"{what} copied": "已複製{what}",
|
||||
"Couldn't copy. Select it here and copy it yourself: {text}": "複製失敗,請在這裡選取後自行複製:{text}",
|
||||
"Connect": "接入",
|
||||
"Loopback only · the key can be anything": "僅限本機迴環 · 金鑰可以隨意填",
|
||||
"Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.": "Chat Completions,多數工具使用的 API。任何可設定 OpenAI base URL 的工具都能用。",
|
||||
@@ -11441,6 +11443,7 @@ const I18N = {
|
||||
"Plan · Europe": "プラン · ヨーロッパ",
|
||||
"which endpoint {p} is reached through": "{p} に接続するエンドポイント",
|
||||
"{what} copied": "{what}をコピーしました",
|
||||
"Couldn't copy. Select it here and copy it yourself: {text}": "コピーできませんでした。ここで選択してコピーしてください:{text}",
|
||||
"Connect": "接続",
|
||||
"Loopback only · the key can be anything": "ループバックのみ · キーは何でも構いません",
|
||||
"Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.": "Chat Completions。多くのツールが使う API です。OpenAI のベース URL を設定できるものなら何でも使えます。",
|
||||
@@ -16015,6 +16018,7 @@ const I18N = {
|
||||
"Plan · Europe": "Tarif · Europa",
|
||||
"which endpoint {p} is reached through": "über welchen Endpunkt {p} erreicht wird",
|
||||
"{what} copied": "{what} kopiert",
|
||||
"Couldn't copy. Select it here and copy it yourself: {text}": "Kopieren fehlgeschlagen. Hier markieren und selbst kopieren: {text}",
|
||||
"Connect": "Verbinden",
|
||||
"Loopback only · the key can be anything": "Nur Loopback · der Schlüssel ist beliebig",
|
||||
"Chat Completions, the API most tools speak. Anything with an OpenAI base-URL setting works.": "Chat Completions, die API, die die meisten Tools sprechen. Alles mit einer Einstellung für die OpenAI-Basis-URL funktioniert.",
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A copy magpie couldn't make (#1881, BabyLy233: on KDE Plasma Wayland the
|
||||
// app said "copied" and the clipboard stayed empty). magpie now refuses a
|
||||
// copy it couldn't read back (/api/copy answers 501), and the page tries the
|
||||
// clipboard API, then the copy command, and says it failed only when none
|
||||
// copied, with the text to copy by hand. A copy magpie made is not copied
|
||||
// again. Every language, Chromium and WebKit; no backend, the API is faked.
|
||||
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 LINK = "https://factory.example/device?code=WDJB-MJHT&state=" + "x".repeat(40);
|
||||
|
||||
function server(lang, magpieCopies) {
|
||||
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:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname === "/api/gateway/trace") return json({ routes: [] });
|
||||
const signing = { id: "s1", agent: "factory", state: "waiting", url: LINK, code: "WDJB-MJHT" };
|
||||
if (url.pathname === "/api/signin" || url.pathname.startsWith("/api/signin/")) return json(signing);
|
||||
if (url.pathname === "/api/copy") return route.fulfill({ status: magpieCopies ? 204 : 501, 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 W = {
|
||||
en: { anyway: "Sign in anyway", copied: "Sign-in link copied", failed: "Couldn't copy. Select it here and copy it yourself: " + LINK },
|
||||
zh: { anyway: "仍然登录", copied: "已复制登录链接", failed: "复制失败,请在这里选中后自行复制:" + LINK },
|
||||
"zh-TW": { anyway: "仍然登入", copied: "已複製登入連結", failed: "複製失敗,請在這裡選取後自行複製:" + LINK },
|
||||
ja: { anyway: "それでもサインイン", copied: "サインインリンクをコピーしました", failed: "コピーできませんでした。ここで選択してコピーしてください:" + LINK },
|
||||
de: { anyway: "Trotzdem anmelden", copied: "Anmeldelink kopiert", failed: "Kopieren fehlgeschlagen. Hier markieren und selbst kopieren: " + LINK },
|
||||
};
|
||||
|
||||
// magpie: /api/copy copies; api: the clipboard API copies; command: the
|
||||
// copy command copies; none: nothing does
|
||||
const CASES = [
|
||||
{ name: "magpie copies", magpie: true, api: true, command: true, want: "copied", writes: [], commands: [] },
|
||||
{ name: "magpie refuses, the clipboard API copies", magpie: false, api: true, command: true, want: "copied", writes: [LINK], commands: [] },
|
||||
{ name: "magpie and the clipboard API refuse, the copy command copies", magpie: false, api: false, command: true, want: "copied", writes: [LINK], commands: [LINK] },
|
||||
{ name: "nothing copies", magpie: false, api: false, command: false, want: "failed", writes: [LINK], commands: [LINK] },
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(W)) {
|
||||
for (const c of CASES) {
|
||||
test(`${engine} ${lang}: ${c.name}`, async (t) => {
|
||||
const w = W[lang];
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 800 }, reducedMotion: "reduce" })).newPage();
|
||||
t.after(() => browser.close());
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.addInitScript(({ api, command }) => {
|
||||
window.__writes = [];
|
||||
window.__commands = [];
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: { writeText: (s) => { window.__writes.push(s); return api ? Promise.resolve() : Promise.reject(new DOMException("refused", "NotAllowedError")); } },
|
||||
});
|
||||
document.execCommand = (cmd) => {
|
||||
if (cmd !== "copy") return false;
|
||||
const a = document.activeElement;
|
||||
window.__commands.push(a && a.tagName === "TEXTAREA" ? a.value.slice(a.selectionStart, a.selectionEnd) : String(getSelection()));
|
||||
return command;
|
||||
};
|
||||
}, { api: c.api, command: c.command });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, c.magpie));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator("#addProvider").click();
|
||||
const sheet = page.locator("#addSheet");
|
||||
await sheet.locator('.tile[data-pick="Factory"]').click();
|
||||
const box = sheet.locator(".signing");
|
||||
await box.locator("button", { hasText: w.anyway }).click();
|
||||
const cp = box.locator(".signlink button.copy");
|
||||
await cp.waitFor();
|
||||
|
||||
await cp.click();
|
||||
const want = w[c.want];
|
||||
await page.waitForFunction((s) => document.querySelector("#status").textContent === s, want);
|
||||
const st = page.locator("#status");
|
||||
if (c.want === "failed") {
|
||||
assert.ok(await st.evaluate((e) => e.classList.contains("err")), "the failure reads as an error");
|
||||
assert.equal(await st.getAttribute("role"), "alert");
|
||||
assert.ok(await st.isVisible(), "the failure is shown");
|
||||
assert.equal(await cp.evaluate((b) => b.classList.contains("done")), false, "the button doesn't say it copied");
|
||||
} else {
|
||||
assert.ok(await st.evaluate((e) => e.classList.contains("ok")));
|
||||
assert.ok(await cp.evaluate((b) => b.classList.contains("done")), "the button says it copied");
|
||||
}
|
||||
assert.deepEqual(await page.evaluate(() => window.__writes), c.writes, "clipboard API calls");
|
||||
assert.deepEqual(await page.evaluate(() => window.__commands), c.commands, "copy command calls");
|
||||
assert.equal(await page.locator("textarea[readonly]").count(), 0, "the textarea is gone");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user