From efe11df3a062c84da4b203722975bbbd5deaa934 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 4 Nov 2026 13:21:50 +0800 Subject: [PATCH] gui: a press and release on a button with no click after it is clicked once (refeccd, Tap to click) refeccd (Discord) reports, a third time, that with macOS Tap to click the first tap on a magpie button only shows the pressed state and does nothing; the second tap works, a physical press works first time. Fixes 4c0cfafcf (v0.1.2868, tap with a few px of movement is not a drag) and c360d9d30 (v0.1.2877, a tap sliding off a segmented option counts) did not help him. Cause: NOT proven. No physical trackpad was used, so I could not see which events the engine delivers. Checked and ruled out: Wails drag.ts only suppresses click while dragging/resizing; mainwindow.go sets no InvisibleTitleBarHeight, so the native first-press window drag does not reach mid-window controls like the Form/JSON switch. The symptom (pressed state, mouseup, no click) is what a lost click looks like. Change: a capture-phase net in app.js. A trusted left mousedown on a button-like control, released on the same control within 300ms and 12px and not on a --wails-draggable element, that is followed by no click within 30ms gets one el.click(). A real click sets the flag first, so a working engine is never double-clicked. Applies to every button-like control (button, a[href], summary, label, .opt, role button/tab/switch/checkbox/ radio/menuitem/option), not one page. Comments in the tapLike/segs blocks were shortened so the app.js budget (1,316,874) needs no raise. Test: tap-lost-click.test.cjs emulates "mouseup arrives, click does not" (a capture listener swallows the first trusted click after a mouseup), then taps JSON, Form and the editor's Cancel in Library > MCP > Edit. Both engines, en/zh/zh-TW/ja/de, 1100 and 390 wide. Red on the old app.js (0/22 per engine), green with the change (22/22 per engine). The lost click is emulated, not captured from a Mac. Run on mote: tap-lost-click plus 8 neighbouring files (168/168, both engines); a 33-file mouse/tap/segs subset before the comment trims; core script budget test passes. Reds in the subset (segs-press-redraw, routing-rule-drag, 21 failures) are identical on unmodified app.js and already filed (#4566, #3922, #4932). The whole GUI suite was started and killed at file ~57/1185 (about 6h on a loaded mote), so it was NOT run in full. go test ./internal/gui: TestMainWindowCorners red, same on origin/main 40cfd32b0 (#3949). Not tried: a real trackpad with Tap to click, the real Wails app, Linux and Windows webviews. If refeccd still sees it, the next step is a log of the mousedown/mouseup/click sequence from his machine. --- internal/gui/assets/app.js | 52 +++++---- internal/gui/tests/tap-lost-click.test.cjs | 118 +++++++++++++++++++++ 2 files changed, 147 insertions(+), 23 deletions(-) create mode 100644 internal/gui/tests/tap-lost-click.test.cjs diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 5bb91e844..6fbe84f05 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -3128,9 +3128,7 @@ function dragListen(handle, move, finish) { return () => { for (const [t, n, f, o] of on) t.removeEventListener(n, f, o); }; } -// A tap-to-click on a trackpad can slide a few pixels between the press and -// the lift. A press let go within 300ms and under 12px from where it came down -// is a click, not a drag, though it crossed the 4px that lifts a row. +// A trackpad tap can slide a few px: a press let go within 300ms and 12px is a click, not a drag. const tapLike = (t0, x0, y0, ev) => ev?.type === "pointerup" && performance.now() - t0 < 300 && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 12; // Shared pointer sorter: transforms each frame, one commit on release. Rows are @@ -6834,26 +6832,20 @@ function segs(items, current, onPick) { }); return box; } -// where a control is in the page: the nearest element with an id, and which -// of the same options it is there; "" for one not in the page +// where a control is: the nearest id, and which of its kind there; "" if not in the page function segsPlace(box) { const home = box.isConnected && box.parentElement.closest("[id]"); return home ? box.dataset.kind + "@" + home.id + ":" + [...home.querySelectorAll(".segs")].filter((x) => x.dataset.kind === box.dataset.kind).indexOf(box) : ""; } -// A press on an option still picks it when the control is drawn again -// before the button is let go: a save's answer redraws Settings, and a -// second option pressed while the first one's save came back was let go -// on a new button. Down and up were on two buttons, so the browser sent the -// click to neither and nothing was picked. Let go on the same option of the -// same control, the new one is clicked; let go anywhere else (dragged off -// to another option), nothing is, as for any button. A touch tap is left to -// the browser, which clicks what is under the finger as it lifts; a mouse or -// trackpad tap that slid off its option within tapLike's bounds still picks it. +// A press on an option still picks it when the control is drawn again before +// the button is let go (a save's answer redraws Settings): down and up were on +// two buttons, so no click came. Let go on the same option of the same +// control, the new one is clicked; anywhere else, nothing is. A touch tap is +// the browser's; a mouse tap that slid off its option within tapLike's bounds +// still picks it. let segsPress = null; const optAt = (b) => [...b.parentElement.querySelectorAll(":scope > .opt")].indexOf(b); -// the same control is at the same place, among as many of its kind, in rows -// that are the same by their data-* (an agent's, a provider's): a list drawn -// again with a row gone, come in or moved above it is another control there +// the same control: same place, as many of its kind, rows the same by data-* function segsWho(box) { const place = segsPlace(box); if (!place) return ""; @@ -6872,27 +6864,41 @@ addEventListener("pointerup", (e) => { if (!p?.who || !e.isPrimary) return; let b; if (p.b.isConnected) { - // a tap that slid off its option (a trackpad's tap lifts a few pixels - // from where it came down, refeccd's first press of Form | JSON): the - // browser clicks neither, or their common holder. A tap is the press - // let go soon and near, as tapLike has it; a drag off it is not. + // a tap that slid off its option: the browser clicks neither if (p.b.contains(e.target) || !tapLike(p.t, p.x, p.y, e)) return; b = p.b; } else { b = document.elementFromPoint(e.clientX, e.clientY)?.closest(".segs > .opt"); if (!b || segsWho(b.parentElement) !== p.who || optAt(b) !== p.i) return; } - // after the browser's own click, should one come to it after all let clicked = false; const seen = (c) => { if (b.contains(c.target)) clicked = true; }; addEventListener("click", seen, true); setTimeout(() => { removeEventListener("click", seen, true); - // its newest self: b, or what a draw since put there (#3922) + // its newest self (#3922) if (!clicked) [...document.querySelectorAll(".segs")].find((x) => segsWho(x) === p.who)?.querySelectorAll(":scope > .opt")[p.i]?.click(); }); }, true); +// A tap whose mouseup comes and no click (refeccd, Tap to click on a Mac): the +// control pressed and let go is clicked once; a click comes with the mouseup. +{ + let d, clicked; + addEventListener("mousedown", (e) => { + const el = e.isTrusted && !e.button && e.target.closest?.('button, a[href], summary, label, .opt, [role="button"], [role="tab"], [role="switch"], [role="checkbox"], [role="radio"], [role="menuitem"], [role="option"]'); + d = el && { el, t: performance.now(), x: e.clientX, y: e.clientY }; + }, true); + addEventListener("click", () => { clicked = true; }, true); + addEventListener("mouseup", (e) => { + const p = d; + d = null; + if (!p || !e.isTrusted || e.button || !p.el.contains(e.target) || performance.now() - p.t >= 300 || Math.hypot(e.clientX - p.x, e.clientY - p.y) >= 12 || getComputedStyle(p.el).getPropertyValue("--wails-draggable").trim() === "drag") return; + clicked = false; + setTimeout(() => { if (!clicked && p.el.isConnected && !p.el.disabled && !p.el.closest('[inert], [aria-disabled="true"]')) p.el.click(); }, 30); + }, true); +} + // An installed list's order, the reader's pick, remembered for each list // (#481): its names A→Z or Z→A, and for a list that has one, a view of its // own first (the skills by where they came from). sortOf(list) is the pick, diff --git a/internal/gui/tests/tap-lost-click.test.cjs b/internal/gui/tests/tap-lost-click.test.cjs new file mode 100644 index 000000000..8fa168cda --- /dev/null +++ b/internal/gui/tests/tap-lost-click.test.cjs @@ -0,0 +1,118 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// refeccd on Discord: Library > MCP servers > magpie-web-search > Edit, the +// Form | JSON switch: the first click changed the text size but not the +// view; it took a second click. A trackpad's tap lifts a few pixels from +// where it came down: here a press near the top of the option that slides 8px +// up, off the switch, in under 300ms. The view must change on the first one, +// both ways, in every language, in Chromium and WebKit, at 1100 and 390 +// wide. No backend: the API is faked. +// refeccd on Discord (third report): Library > MCP servers > magpie-web-search > +// Edit, the Form | JSON switch: on a Mac with Tap to click the first tap only +// shrinks the button (:active) and does nothing; a second tap works. A +// physical press works. No physical trackpad has been used for this test, and +// the engine-level cause is not proven. What is common to the reports is a +// press whose mouseup the page sees and whose click it never does. This test +// makes the engine lose the click of the first tap (a capture listener, +// installed before the page's, swallows the first trusted click that follows +// a mouseup) and holds the page to a click on the control, for the switch and +// for a plain button, with a tap that has no hold at all. 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 { I18N } = require("./strings.cjs").strings(); +const tr = (lang, s) => (lang === "en" ? s : I18N[lang][s]) || s; +const HOME = "/Users/rf"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); + +function server(lang, web) { + const lib = { + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: ["claude:Claude Code","codex:Codex","gemini:Gemini CLI","cursor:Cursor","opencode:OpenCode","kimi:Kimi Code","droid:Droid","amp:Amp","qwen:Qwen Code","crush:Crush","pi:Pi","zed:Zed","trae:Trae","iflow:iFlow","goose:Goose","cline:Cline","roo:Roo","kilo:Kilo","aider:Aider","warp:Warp"].map((x) => agent(...x.split(":"))), mcpHub: true, hubPath: "/mcp", + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], + servers: [{ name: "magpie-web-search", transport: "stdio", command: "/Applications/magpie.app/Contents/MacOS/magpie", args: ["mcp", "search"], env: {}, icon: "https://usemagpie.ai/favicon.png", agents: ["claude", "codex", "gemini"] }], + }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib }); + if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + if (url.hostname === "usemagpie.ai") { + return route.fulfill({ body: await fs.readFile(path.join(assets, "favicon.png")).catch(() => Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64")), contentType: "image/png" }); + } + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a tap whose click the engine loses still presses the control", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 390]) { + await t.test(`${lang} ${width}`, async () => { + const w = (s) => tr(lang, s); + const ctx = await browser.newContext({ viewport: { width, height: 800 } }); + await ctx.addInitScript(() => { + try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} + // the engine that sends the mouseup and no click: the next + // trusted click after a mouseup is lost, once per arming + let up = false; + window.__lose = 0; + addEventListener("mouseup", (e) => { if (e.isTrusted && window.__lose > 0) up = true; }, true); + addEventListener("click", (e) => { + if (!e.isTrusted || !up) return; + up = false; + window.__lose--; + e.stopImmediatePropagation(); + }, true); + }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + await page.route("**/*", server(lang, width < 600)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const ed = page.locator("#modal .lib-editor"); + await page.locator("#view-library .lib-server .name", { hasText: "magpie-web-search" }).click(); + await ed.waitFor(); + await page.waitForTimeout(600); // the dialog has stopped growing in + const pick = (name) => ed.locator(".lib-viewpick .opt", { hasText: new RegExp("^" + name + "$") }); + // a trackpad's tap: down and up with no hold, the pointer already there + const tap = async (loc) => { + const b = await loc.boundingBox(); + await page.mouse.move(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForTimeout(100); + await page.evaluate(() => { window.__lose = 1; }); + await page.mouse.down(); + await page.mouse.up(); + }; + await tap(pick("JSON")); + await ed.locator("textarea.lib-json").waitFor({ timeout: 1500 }); + assert.equal(await pick("JSON").getAttribute("aria-pressed"), "true", "JSON is picked by the first tap"); + await tap(pick(w("Form"))); + await ed.locator("textarea.lib-json").waitFor({ state: "detached", timeout: 1500 }); + assert.equal(await pick(w("Form")).getAttribute("aria-pressed"), "true", "Form is picked by the first tap"); + // a plain button too: the Cancel at the dialog's foot closes it + await tap(ed.locator("button", { hasText: new RegExp("^" + w("Cancel") + "$") }).first()); + await page.locator("#modal").waitFor({ state: "hidden", timeout: 1500 }); + await ctx.close(); + }); + } + } + }); +}