gui: a key combination opens the quick panel from any app (ben hanks)

ben hanks on Discord asked for a global shortcut that opens the menu bar
or tray panel. Settings › General has a new row, Quick panel shortcut,
with none set by default. Clicking its field records the next combination:
a letter, a digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Win, or an
F key on its own. Esc or a click elsewhere stops recording, and the cross
clears the shortcut. It is shown the system's way (⇧⌘K on a Mac,
Ctrl+Alt+K elsewhere).

POST /api/settings/panel-shortcut checks the combination, has the running
app bind it through Wails' GlobalShortcut (Carbon hot keys on the Mac,
RegisterHotKey on Windows, XGrabKey on X11), and saves it only once it is
bound. One the system refuses is not saved, the old one stays bound, and
the status line says why. A pressed shortcut toggles the panel as a tray
click does. The shortcut belongs to each computer (KeepOwn), the Settings
page's own save leaves it alone, and the old Mac process lets go of it as
it hands over. On Wayland no app may grab keys, so the field is turned off
and the row names the command (`magpie panel`) to bind in the desktop's
own keyboard settings.

Every string is in en, zh, zh-TW, ja and de. No size budget was raised:
app.js is 1,315,252 of its 1,315,316 after older comments were cut.

Run at this head (rebased on origin/main 1534474c8):
- mote (macOS 27): gofmt; go vet for darwin, GOOS=linux -tags nogui and
  GOOS=windows on internal/gui and internal/settings; go build ./...:
  ok. go test: settings ok; gui ok except TestMainWindowCorners/
  macOS_26_SDK, red on macOS 27 already (#3949).
- Windows (xiaomi-gpu, win-run): go test internal/gui internal/settings.
  settings ok; gui has 5 reds, the same 5 on origin/main d19afb4c9
  (TestGatewayHeldByAContainer #2107/#3649; TestLodyImportHandoff,
  TestImportStatusUnreadableIsUnknown, TestAionUiImportRow and
  TestUpdateThatWontStart #4115).
- Linux (WSL magpie-desktop, wsl-run -tags nogui): internal/gui (the
  Wayland branch included) and internal/settings: ok.
- GUI: panel-shortcut.test.cjs (new) in Chromium and WebKit, in all 5
  languages, faking both a Mac and Windows: ok. Whole suite (make test-ui)
  on mote: unfinished at the push. Three other sessions' suites were on
  the same box (load 130 to 250), and after 1605 tests it was still in
  the "c" files. Its reds so far are agent-panel-name-width and
  connect-snippet-shell and context-map (each on #4304), and allow-ips
  zh, which is red alone on origin/main too (#4357).

Broken by hand, each red:
- leaving the shortcut out of the general Settings save:
  TestPanelShortcutSetting "the Settings page's save changed the
  shortcut";
- dropping KeepOwn's line: "a synced setup took this computer's shortcut";
- dropping the recorder's stopImmediatePropagation: panel-shortcut.test.cjs
  "a key typing needs was sent, or a window key ran".
TestSettingsSaveKeepsWhatItDoesNotSend now sets the new field.

Real build on mote: a dev build in a sandbox HOME bound a saved
Ctrl+Option+Shift+Cmd+F18 as it started, and a POST of F16 saved it and
bound it.

Not tried:
- a real key press on any system: mote gives ssh no Accessibility access
  to post events, and Windows' ssh session has no desktop;
- the Windows and X11 refusal of a combination another app holds (only
  the fake). On the Mac, Carbon takes a combination a second app
  registered too, so both apps get it and magpie can't say so. This was
  checked on mote with a helper holding F17;
- Wails' GlobalShortcuts portal on Wayland, which isn't used;
- a Linux GUI-tag build (WSL has no gtk4/webkitgtk-6.0).
This commit is contained in:
yetone
2026-10-30 12:06:33 +08:00
parent 1534474c8e
commit 3bebc38393
13 changed files with 714 additions and 64 deletions
+1
View File
@@ -33,6 +33,7 @@ three.
6. The window opens as it was last left. Its settled size and whether it was maximised are kept in `settings.Window` and `settings.WindowMaximised` (`settle`; per machine, see `KeepOwn`). A maximised window keeps the size it restores to. `makeMain` opens it at that size (`openSize`). On its first show, `placeMain` maximises it again on the Mac and Windows (on Windows once the page has come). On Linux, `makeMain` makes it maximised with `StartState`. On Windows a size larger than the screen's work area is fitted and centred (`fitRoom`), and the larger size stays kept. The window's position is not kept.
7. The page's header is the window's title bar. `plainTitlebar` sets it up once the app has started, and again on a window lightweight mode made again (`madeAgain`). On Linux it hides GTK's title bar and keeps the shadow and the resize edges; GTK 3 leaves the corners square. On the Mac the traffic lights are inset into the header (`MacTitleBarHiddenInset`). In the design of macOS 26 a window with a toolbar has larger corners than one with a plain title bar, so `insetLights` ([`titlebar_darwin.go`](../../internal/gui/titlebar_darwin.go)) takes the toolbar off, and `MagpieLights` keeps the lights and the title bar's height where the toolbar had them: after a resize, a new title, light or dark, more contrast or less transparency, and leaving full screen. A sheet, such as the folder chooser, still begins below the title bar. A first press while another app is in front still moves the window from anywhere in that title bar (`firstPress`), as AppKit moved it with the toolbar; AppKit itself now does so only in a plain title bar's top 32pt. AppKit gives a program that design from macOS 26 when the program is linked against the macOS 26 SDK or a later one and its Info.plist doesn't ask for the earlier design (`UIDesignRequiresCompatibility`); `designOf26` reads each at run time, as the SDK depends on the toolchain that built magpie. The toolbar stays in the earlier design, where it doesn't change the corners, with the lights on the right (a right-to-left language), or when the title bar isn't laid out as expected; this is decided once, when the window is set up. In full screen the title bar is AppKit's own. Windows keeps its own title bar.
8. On the Mac, Settings › Show in Dock puts magpie in the Dock never (`DockNever`), while the window is open (the default; `DockWindow` records it chosen, for an older magpie that took none for never) or always (`Dock`, which wins). The default was never until ShouguangCao on X found the open window out of Command-Tab, so going back to it to paste a key copied elsewhere took the menu bar; a new install (no settings.json) reads With window, and Hide is a choice of its own (`inDock`, `dockChoice` in app.js, `TestDockFollowsWindowByDefault`, `dock-choice.test.cjs`). A file written before that has no `dockSettled`, and stored Hide as nothing, so a user who chose Hide can't be told from one who never chose: such a file with no Dock choice reads as Hide, and the first save writes it so with `dockSettled` (`settleDock`, `TestOlderSettingsKeepHide`, `TestNewInstallFollowsWindow`). A file nobody can read reads the same way. The page never sends `dockSettled`; the save keeps the file's (`TestSettingsSaveKeepsDockReading`). It is this computer's own, as the Dock choice is (`KeepOwn`). A full-screen window joins it whatever the setting (`inDock`, `dockOnFullscreen`). `openMain` joins before it shows the window (`setDock` runs on the main thread at once). An app activated out of the Dock (the quick panel's focus) that then joins it stays last in Command-Tab's order though it is in front, so joining to the front activates magpie by way of the Dock (`dockStep`, `activateAgain`; #1381, `TestDockStep`, `TestDockJoinLeadsCommandTab`). It does so without asking NSApp whether magpie is active: the Mac makes it the front app at once, and NSApp says so only once the main thread has taken that in, after the join on a busy Mac (#1651).
9. Settings › General › Quick panel shortcut binds a key combination that opens the tray's panel from any app (ben hanks on Discord); none is set by default. The page records the keys and posts them to `POST /api/settings/panel-shortcut`, which checks them (`panelShortcut`: a letter, digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Super, or an F key alone, written as Wails' accelerator), has the running app bind them (`onPanelShortcut`, `bindPanelKey` through Wails' `GlobalShortcut`: Carbon's hot keys on the Mac, `RegisterHotKey` on Windows, `XGrabKey` on X11) and saves them only once bound. One the system refuses (on Windows and X11, another app holding it) is not saved and the old one stays bound; one saved but refused as magpie starts is retried after a handed-over magpie exits and else said in the row (`panelKeysJSON.Taken`). A pressed shortcut toggles the panel as a tray click does (`togglePanel`). The Mac's Carbon hot keys don't refuse a combination another app registered too, so there both are taken and magpie can't tell the user. The shortcut is per computer (`KeepOwn`), and the Mac's old process lets go of it as it hands over (`leaveMenuBar`). On Wayland no app may grab keys itself, so the field is off and the row says the command to bind in the desktop's own keyboard settings (`magpie panel`); Wails' GlobalShortcuts portal is not used, since the compositor decides its keys and Hyprland binds none unless configured.
## Constraints and failure behavior
+41
View File
@@ -373,6 +373,9 @@ type settingsJSON struct {
// Builtins are the built-in plugins: each one's switch, whether it
// runs and what of it is in use (builtins.go)
Builtins []builtinJSON `json:"builtins"`
// PanelKeys is whether the quick panel's shortcut can be set here
// (panelkey.go)
PanelKeys panelKeysJSON `json:"panelKeys"`
// JSRoutings are the routings JS gateway plugins serve now
// ("<plugin>/<name>"), for the routing pickers
JSRoutings []middleware.Routing `json:"jsRoutings"`
@@ -640,6 +643,7 @@ func settingsState() settingsJSON {
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
s.Builtins = builtinsState()
s.PanelKeys = panelKeysState()
s.JSRoutings = middleware.Routings()
s.OnNetwork = gateway.OnNetwork()
if list, env := gateway.AllowIPs(); env {
@@ -1445,6 +1449,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.CodexWarmAtOf = cur.CodexWarmAtOf
// and the text size, which the keyboard changes too (text-size below)
in.TextSize = cur.TextSize
// and the quick panel's shortcut, set on its own (panel-shortcut below)
in.PanelShortcut = cur.PanelShortcut
// the Dock choice's reading, which the page never sets: the file's
// as read (settings.DockSettled), so a save from the page doesn't
// read its With window as an older file's Hide
@@ -2116,6 +2122,41 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// the quick panel's shortcut (panelkey.go): bound in the app first, so
// one the system refuses is said and not saved, the one before kept
mux.HandleFunc("POST /api/settings/panel-shortcut", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Shortcut string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
key, err := panelShortcut(in.Shortcut, runtime.GOOS)
if err != nil {
fail(rw, err)
return
}
s := settings.Load()
if key != "" && !panelKeysState().Can {
fail(rw, errors.New("This desktop doesn't let apps take a shortcut"))
return
}
if onPanelShortcut != nil {
if err := onPanelShortcut(key); err != nil {
fail(rw, err)
return
}
}
was := s.PanelShortcut
s.PanelShortcut = key
if err := settings.Save(s); err != nil {
if onPanelShortcut != nil {
_ = onPanelShortcut(was) // the saved one bound again
}
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// the Agents page's order and what it folds away, in magpie's settings
mux.HandleFunc("POST /api/agents/arrange", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Order, Hidden, Shown []string }
+7
View File
@@ -107,6 +107,10 @@ type host struct {
loading map[*application.WebviewWindow]bool
// the main window placed as it was last left (placeMain), and so shown
placed atomic.Pointer[application.WebviewWindow]
// the quick panel's shortcut bound now, "" for none (panelkey_app.go)
keyMu sync.Mutex
panelKey string
}
// whenReady runs fn once the main window can be shown safely.
@@ -576,6 +580,7 @@ func Run(version string, showMain bool, link string) error {
}
}
h.watchTrayUsage()
h.startPanelKey(before)
// Omarchy's bar shows magpie once: as its widget (Settings → Bar
// icon) or as the tray's item, not both
onBarIcon = h.setTrayInBar
@@ -815,6 +820,8 @@ func (h *host) leaveMenuBar() {
h.main.Hide()
}
setDock(false, false)
// and its shortcut, for the new version to bind
go h.dropPanelKey()
})
}
+9
View File
@@ -3507,6 +3507,15 @@ body:not(.side-nav) #view-settings .set-head.stuck::before { box-shadow: 0 1px 0
.row.pref .set-field { flex: none; width: 120px; height: 24px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); }
.row.pref .set-field[type=number] { width: 72px; text-align: right; }
.row.pref .set-field[aria-invalid=true] { border-color: var(--red); }
/* the quick panel's shortcut: a field that listens for keys, and its clear */
#panelKey { flex: none; margin-left: auto; display: flex; align-items: center; gap: 4px; }
#panelKey .key-rec { min-width: 120px; height: 24px; padding: 0 8px; font: inherit; font-size: 12px; color: var(--fg); border: 1px solid var(--line); border-radius: 7px; background: var(--card); white-space: nowrap; cursor: default; }
#panelKey .key-rec.on { color: var(--fg-2); border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
#panelKey .key-rec:disabled { opacity: .5; }
#panelKey .key-clear { display: grid; place-items: center; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; color: var(--fg-2); background: none; }
#panelKey .key-clear:hover { color: var(--fg); background: var(--pill); }
#panelKey .key-clear[hidden] { display: none; }
#panelKeyRow .sub { user-select: text; -webkit-user-select: text; }
/* a plugin's page that broke (kernel.js): what broke, and Try again */
.slot-error .row { gap: 14px; padding: 12px 14px; }
.slot-error .sub { margin-top: 2px; color: var(--fg-2); overflow-wrap: anywhere; }
+71 -62
View File
@@ -2777,10 +2777,8 @@ let panelOpenAgent = null; // the one agent row the panel has opened
// How the agent's own model is run (ultracode, an effort) is not: turning
// Claude Code's ultracode on folded every other agent away under Show more.
// One with 「接入」's switch is set up when it is connected, and only then
// (#726): its fields are read from its own files, so one not connected kept
// its row up for a model of its own (Antigravity, DeepSeek Harness), and a
// connected Codex starting on its last choice, no model set, went under
// Not set up. One magpie connected that has come apart (drift) stays up
// (#726): its fields are read from its own files. One magpie connected
// that has come apart (drift) stays up
// too, to be put right. One with no switch (Cursor, an app's own models)
// goes by what is set on it, as before, though while an agent can be
// connected it doesn't start the folding (arrangeAgents): its values are
@@ -5438,13 +5436,11 @@ function rateTag(rate = 0, was = 0) {
}
// modelTells: what tells apart the models of one list that would show the
// same label (sunset on Discord: the Our Free Model plugin's several
// "DeepSeek-V4.1-Flash · x0.1", told apart only by the buddy/… of their
// ids, in the tooltip). items are the list's entries, label(x) what each
// shows, id(x) its id, and key(x) the part of the list it is shown in (a
// picker's provider): labels are compared within a key. Returns a Map of
// id → tell for the entries whose label another of the same key shares; an
// entry whose label is its own gets none, and is drawn as it was.
// same label (sunset on Discord). items are the list's entries, label(x)
// what each shows, id(x) its id, and key(x) the part of the list it is
// shown in (a picker's provider): labels are compared within a key.
// Returns a Map of id → tell for the entries whose label another of the
// same key shares; one whose label is its own gets none.
//
// A tell is the part of its id the others' don't share: the path segments
// every id of the label begins with and ends with are dropped, so buddy/x
@@ -8788,22 +8784,15 @@ $("#modal").addEventListener("keydown", (e) => {
e.preventDefault();
(e.shiftKey ? last : first).focus();
});
// A dialog opens centred, and stays centred while what it holds fills in
// before the reader has done anything in it (a plugin's README loading
// under a dialog opened short read as a dialog sat low, the owner 10-24).
// From the reader's first press or key in it, it stays put while what it
// holds grows or shrinks (a fold opening, an error line, a list filling): it holds the
// place of whatever the reader last pressed or focused in it, and grows
// and shrinks round that, down to the window's foot, where it stays and
// its fields scroll as a full-height dialog's do. Where there is no
// room left to move, its fields shorten over a pressed button below them,
// so an error line over Remove doesn't push Remove down; a pressed field
// goes with what grows above it, as nothing a click does scrolls. Centred all along, a dialog
// shorter than the window moved by half of every change, the line just
// clicked sliding from under the pointer. Its place is a relative top and
// a cap on its height. A change made in the page is held before it is
// drawn (a mutation's microtask); one that only resizes (an animation, the
// window) a frame later, as an observer can't resize what it observes.
// A dialog opens centred and stays centred while it fills in, until the
// reader's first press or key in it (the owner 10-24). From then it holds
// the place of what the reader last pressed or focused, growing and
// shrinking round it down to the window's foot, where its fields scroll.
// With no room left, its fields shorten over a pressed button below them,
// so an error line over Remove doesn't push Remove down. Centred all along,
// the line just clicked slid from under the pointer. Its place is a
// relative top and a cap on its height. A change made in the page is held
// before it is drawn (a mutation's microtask); a resize a frame later.
const modalHold = { off: 0, at: null, y: 0, cap: null, capSet: "", touched: false };
// how far down the dialog an element sits, to the fraction of a pixel,
// what moves it in an animation (a row coming in) left out. An element
@@ -9041,11 +9030,7 @@ $("#modal").onclick = (e) => { if (modalBackdrop(e)) cancelEdit(); };
// is another (a save refused puts one back), and otherwise is left as it
// is. A thumb is placed only where the control is laid out: one drawn
// hidden (Settings at start, a tab not shown) is put under its option,
// still, when it is shown or sized again (thumbFit). Before, a redrawn
// control made a new thumb and replayed what was remembered of the old
// one's glide from its start (a click's thumb jumped back and slid again),
// and positions taken while Settings was hidden, 0 wide, made every thumb
// on the page grow in from the left on the first save.
// still, when it is shown or sized again (thumbFit).
const thumbs = new Map(); // control position → { th, pick, to }: its thumb, the option it is under or going to, and where that is
const THUMB_MS = 280, THUMB_EASE = "cubic-bezier(.2, .8, .2, 1)"; // --ease
const thumbKeys = new WeakMap(); // box → its key, for thumbFit
@@ -10843,7 +10828,7 @@ function showRest(n, open) {
const DETECT_MAX = 30;
// addFormModels: the add form's models, typed in (ex) or picked from the
// vendor's list, asked with the form as it stands before anything is saved
// (#578: 添加供应商的时候,希望添加可以获取全模型的按钮或者下拉框). A chip
// (#578). A chip
// ticked or unticked is in draft.extra, which the Save sends as the models.
function addFormModels(ex) {
const box = el("div", "stack add-models");
@@ -16174,24 +16159,15 @@ function keyCards(list) {
return gone.size ? list.filter((q) => !gone.has(q)).map((q) => merged.get(q) || q) : list;
}
// packUsage lays the Usage page's cards out in columns, each card as tall
// as itself, the next in the order going to the column that ends highest
// (huoranxuanyuan, #860: a tall Codex card beside Antigravity and a
// DeepSeek balance left the short two mostly empty; 把 antigravity 和
// deepseek 两个上下堆叠和 Codex 对齐). The order still reads left to right,
// row by row as near as the heights allow, and the cards stay in it on the
// page, for dragging, Alt+arrows and a screen reader alike. As many columns
// as 260px each fit, unless one fewer leaves much less empty beside the
// short cards for a page not much taller. Decided again when the cards
// change or the width fits another number of columns; a card growing (a
// fold opened) only packs them again, so what was clicked stays where it
// was, even as the view's scrollbar comes in and takes some of the width
// (in WebKit a card turned to every model went to one column under its
// neighbour, the page following it). The last card in each column reaches
// down to where the tallest column ends, so the bottoms line up: a row of
// cards side by side is as tall as its tallest, and a short card stacked
// under another ends with the tall one beside them (ikunbots on X: 卡片可以
// 对齐吗). Each card is measured as tall as itself before that.
// packUsage lays the Usage page's cards out in columns, each as tall as
// itself, the next going to the column that ends highest (#860). The order
// reads left to right and stays the page's, for dragging, Alt+arrows and a
// screen reader. As many 260px columns as fit, unless one fewer leaves much
// less empty for a page not much taller; decided again when the cards
// change or the width fits another count. A card growing only packs them
// again, so what was clicked stays put as the scrollbar comes and goes.
// Each column's last card reaches down to the tallest column's end, so the
// bottoms line up (ikunbots on X).
const USAGE_MIN = 260, USAGE_GAP = 7;
let usagePacked = null, usagePackFrame = 0;
function packUsage() {
@@ -19191,6 +19167,43 @@ async function setTextSize(n) {
status(e.message, "err");
}
}
// The quick panel's own shortcut from any app (ben hanks): while its field
// listens, a letter, digit, Space or F key with Ctrl, Alt or Cmd/Win (an F
// key alone too) is sent as Wails names it (panelkey.go), ahead of the
// keys below; Esc or leaving the field stops it. Wayland's desktop binds
// it itself, to the command the row shows.
let keyRec = false;
const MAC = /^Mac/.test(navigator.platform);
const keyName = (a) => MAC ? a.replace("Ctrl+", "⌃").replace("Option+", "⌥").replace("Shift+", "⇧").replace("Cmd+", "⌘")
: a.replace("Super", /^Win/.test(navigator.platform) ? "Win" : "Super");
function renderPanelKey(s) {
const k = s.panelKeys || {}, box = $("#panelKey"), sub = $("#panelKeyRow .sub"), cur = s.panelShortcut || "";
$("#panelKeyRow").hidden = web;
sub.hidden = k.can && !(cur && k.taken === cur);
sub.textContent = k.can ? t("Another app already uses this shortcut") : t("Set it in your desktop's keyboard settings, to run {command}", { command: k.command });
const b = el("button", "key-rec" + (keyRec ? " on" : ""), keyRec ? t("Type shortcut") : cur ? keyName(cur) : t("Record shortcut"));
b.type = "button";
b.disabled = !k.can;
b.onclick = () => { keyRec = !keyRec; renderSettings(); };
b.onblur = () => setTimeout(() => { if (keyRec && !box.contains(document.activeElement)) { keyRec = false; renderSettings(); } });
const x = el("button", "key-clear", svg(CROSS, 10, 2));
x.type = "button";
x.setAttribute("aria-label", x.title = t("Clear"));
x.hidden = !cur;
x.onclick = () => { keyRec = false; prefWrite(api("settings/panel-shortcut", { shortcut: "" })); };
box.replaceChildren(b, x);
if (keyRec) b.focus({ preventScroll: true });
}
if (!web) addEventListener("keydown", (e) => {
if (!keyRec) return;
e.preventDefault();
e.stopImmediatePropagation();
if (e.key === "Escape") return void ((keyRec = false), renderSettings());
const c = e.code, f = /^F([1-9]|1\d|20)$/.test(c), k = /^(?:Key|Digit)(.)$/.exec(c)?.[1] || (f || c === "Space" ? c : "");
if (!k || !(f || e.ctrlKey || e.altKey || e.metaKey)) return;
keyRec = false;
prefWrite(api("settings/panel-shortcut", { shortcut: [e.ctrlKey && "Ctrl", e.altKey && (MAC ? "Option" : "Alt"), e.shiftKey && "Shift", e.metaKey && (MAC ? "Cmd" : "Super"), k].filter(Boolean).join("+") }));
}, true);
// Ctrl/Cmd + = and − step through the sizes, 0 goes back to 100%, in the
// window and the panel alike; in a browser tab they are the browser's.
if (!web) addEventListener("keydown", (e) => {
@@ -19801,6 +19814,7 @@ function renderSettings() {
$("#textSizeSegs").title = t("Everything in magpie's windows, larger; {keys} too", { keys: textSizeKeys() });
$("#textSizeSegs").replaceChildren(segs(TEXT_SIZES.map((n) => [n, n + "%"]), s.textSize || 100, (n) => setTextSize(n)));
$("#traySegs").replaceChildren(segs(TRAYS.map(([id, name]) => [id, t(name)]), s.tray || "panel", (tray) => savePrefs({ ...keep, tray })));
renderPanelKey(s);
// the Dock is the Mac's; the tray and the login item the app's
$("#dockRow").hidden = !document.body.classList.contains("mac");
$("#traySegs").parentElement.hidden = $("#loginSegs").parentElement.hidden = web;
@@ -20519,17 +20533,12 @@ const IN_USE = "|*";
// the tray icon, side by side. The cards are the Usage page's, asked for
// when the menu opens; any number are ticked in it.
// suffixSegs: how the agents' lists name a model — with its provider's
// (or "routing group") after it, all but the names the user gave models
// and the groups they made (#92), or none (#335). Set on its own, so the
// agents are told. Offered on Settings and where names are given, the
// provider's Names & levels and over Routing's groups (#868: an agent's
// narrow menu cut "· routing group" short, and the setting wasn't found;
// in one group's editor it read as that group's, PAMI on Discord);
// drawn(mode) redraws the place it was picked in.
// The mode is read from the state's settings, which startup reads before
// any page is drawn, not from Settings' own read, which only opening
// Settings makes: Routing and the provider editor said On over a saved Off
// until Settings had been opened (#1433, ObsidianArch02).
// (or "routing group") after it, all but the user's own names (#92), or
// none (#335). Set on its own, so the agents are told. Offered on Settings,
// the provider's Names & levels and over Routing's groups (#868);
// drawn(mode) redraws the place it was picked in. The mode is read from
// the state's settings, read before any page is drawn, not Settings' own
// read (#1433).
function suffixMode(s = state.settings || {}) { return s.plainNames ? "off" : s.plainOwnNames ? "own" : "on"; }
function suffixSegs(drawn) {
const mode = suffixMode();
+32
View File
@@ -789,6 +789,14 @@ const I18N = {
"Click the tray icon to": "点击托盘图标",
"Open the quick panel": "打开快捷面板",
"Open the main window": "打开主窗口",
"Quick panel shortcut": "快捷面板快捷键",
"Record shortcut": "录制快捷键",
"Type shortcut": "请按下快捷键",
"Another app already uses this shortcut": "其他应用已占用这个快捷键",
"Set it in your desktop's keyboard settings, to run {command}": "请在桌面环境的键盘设置里添加,运行 {command}",
"magpie couldn't take this shortcut": "magpie 无法使用这个快捷键",
"Not a shortcut magpie can use": "magpie 不能使用这个快捷键",
"This desktop doesn't let apps take a shortcut": "这个桌面环境不允许应用占用快捷键",
"Bar icon": "状态栏图标",
"magpie’s icon beside Omarchy’s own in the bar; right-click opens the window": "把 magpie 图标放进 Omarchy 状态栏,与系统图标并排;右键打开窗口",
"Show in Dock": "显示程序坞",
@@ -4929,6 +4937,14 @@ const I18N = {
"Click the tray icon to": "點選托盤圖示",
"Open the quick panel": "開啟快捷面板",
"Open the main window": "開啟主視窗",
"Quick panel shortcut": "快捷面板快速鍵",
"Record shortcut": "錄製快速鍵",
"Type shortcut": "請按下快速鍵",
"Another app already uses this shortcut": "其他應用程式已占用這個快速鍵",
"Set it in your desktop's keyboard settings, to run {command}": "請在桌面環境的鍵盤設定裡新增,執行 {command}",
"magpie couldn't take this shortcut": "magpie 無法使用這個快速鍵",
"Not a shortcut magpie can use": "magpie 不能使用這個快速鍵",
"This desktop doesn't let apps take a shortcut": "這個桌面環境不允許應用程式占用快速鍵",
"Bar icon": "狀態列圖示",
"magpie’s icon beside Omarchy’s own in the bar; right-click opens the window": "把 magpie 圖示放進 Omarchy 狀態列,與系統圖示並排;右鍵開啟視窗",
"Show in Dock": "顯示程式塢",
@@ -9041,6 +9057,14 @@ const I18N = {
"Click the tray icon to": "トレイアイコンのクリックで",
"Open the quick panel": "クイックパネルを開く",
"Open the main window": "メインウィンドウを開く",
"Quick panel shortcut": "クイックパネルのショートカット",
"Record shortcut": "ショートカットを記録",
"Type shortcut": "キーを押してください",
"Another app already uses this shortcut": "このショートカットは他のアプリが使用中です",
"Set it in your desktop's keyboard settings, to run {command}": "デスクトップのキーボード設定で、{command} を実行するよう設定してください",
"magpie couldn't take this shortcut": "magpie はこのショートカットを使えませんでした",
"Not a shortcut magpie can use": "magpie が使えるショートカットではありません",
"This desktop doesn't let apps take a shortcut": "このデスクトップではアプリがショートカットを登録できません",
"Bar icon": "バーアイコン",
"magpie’s icon beside Omarchy’s own in the bar; right-click opens the window": "Omarchy のバーで、Omarchy 自身のアイコンの横に magpie のアイコンを表示します。右クリックでウィンドウを開きます",
"Show in Dock": "Dock に表示",
@@ -13167,6 +13191,14 @@ const I18N = {
"Click the tray icon to": "Klick auf das Tray-Symbol",
"Open the quick panel": "Schnell-Panel öffnen",
"Open the main window": "Hauptfenster öffnen",
"Quick panel shortcut": "Tastenkürzel für das Schnellpanel",
"Record shortcut": "Kürzel aufnehmen",
"Type shortcut": "Kürzel drücken",
"Another app already uses this shortcut": "Eine andere App nutzt dieses Kürzel bereits",
"Set it in your desktop's keyboard settings, to run {command}": "In den Tastatureinstellungen des Desktops festlegen, um {command} auszuführen",
"magpie couldn't take this shortcut": "magpie konnte dieses Kürzel nicht belegen",
"Not a shortcut magpie can use": "Kein Kürzel, das magpie nutzen kann",
"This desktop doesn't let apps take a shortcut": "Dieser Desktop lässt Apps keine Kürzel belegen",
"Bar icon": "Leistensymbol",
"magpie’s icon beside Omarchy’s own in the bar; right-click opens the window": "magpie-Symbol neben den Omarchy-Symbolen in der Leiste; Rechtsklick öffnet das Fenster",
"Show in Dock": "Im Dock zeigen",
+4
View File
@@ -214,6 +214,10 @@
<div class="who"><div class="name" data-t>Click the tray icon to</div></div>
<div id="traySegs"></div>
</div>
<div class="row pref app-only" id="panelKeyRow">
<div class="who"><div class="name" data-t>Quick panel shortcut</div><div class="sub" hidden></div></div>
<div id="panelKey"></div>
</div>
<div class="row pref" id="barIconRow" hidden>
<div class="who"><div class="name" data-t>Bar icon</div><div class="sub" data-t>magpie’s icon beside Omarchy’s own in the bar; right-click opens the window</div></div>
<div id="barIconSegs"></div>
+146
View File
@@ -0,0 +1,146 @@
package gui
import (
"errors"
"os"
"runtime"
"slices"
"strings"
"sync/atomic"
)
// The quick panel's global shortcut (Settings › General): a key
// combination the user records, which opens the tray's panel from any app
// (ben hanks on Discord). There is none by default, so nothing magpie
// takes clashes with another app's until the user picks it.
// onPanelShortcut binds the shortcut s ("" for none) in the running app in
// place of the one before, and says why it couldn't; the app sets it
// (app.go). Off the app (magpie web, tests) it is nil and the choice is
// only saved.
var onPanelShortcut func(s string) error
// panelKeyTaken is the shortcut the app couldn't bind as it started,
// another app holding it; "" once one is bound or none is set.
var panelKeyTaken atomic.Value // string
// errPanelKeyTaken is what the page is told when the system refuses the
// combination, as Windows and X11 do for one another app holds (the Mac's
// Carbon hot keys take it twice, so there it isn't said).
var errPanelKeyTaken = errors.New("Another app already uses this shortcut")
// panelKeysJSON is what Settings' row needs beside the saved shortcut.
type panelKeysJSON struct {
// Can is whether this system lets magpie take a global shortcut at all
Can bool `json:"can"`
// Command opens the panel from a shortcut the desktop binds itself,
// where magpie can't (Wayland)
Command string `json:"command,omitempty"`
// Taken is the saved shortcut the system refused as magpie started
Taken string `json:"taken,omitempty"`
}
func panelKeysState() panelKeysJSON {
st := panelKeysJSON{Can: !waylandSession(runtime.GOOS, os.Getenv)}
if !st.Can {
exe, err := os.Executable()
if err != nil || exe == "" {
exe = "magpie"
}
st.Command = shellWord(exe) + " panel"
}
st.Taken, _ = panelKeyTaken.Load().(string)
return st
}
// waylandSession says the desktop is a Wayland session, where no app may
// grab a key for itself: only the desktop's own settings (or its
// GlobalShortcuts portal, which leaves the keys to the compositor and on
// Hyprland binds none until the user writes one) can. It reads the session
// as Wails does in choosing its backend.
func waylandSession(goos string, getenv func(string) string) bool {
if goos != "linux" {
return false
}
switch strings.ToLower(getenv("XDG_SESSION_TYPE")) {
case "wayland":
return true
case "x11":
return false
}
return getenv("WAYLAND_DISPLAY") != ""
}
// shellWord quotes a path with a space or a quote for a POSIX shell.
func shellWord(s string) string {
if !strings.ContainsAny(s, " '\"\\$`!&;()|<>*?[]#~") {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// panelShortcut checks a shortcut the page recorded and writes it as
// Wails' accelerator, its modifiers in the Mac's order (Ctrl, Option,
// Shift, Cmd) and the key last: "Ctrl+Option+K", "Cmd+Shift+Space". The
// Command key is "Cmd" on the Mac and the Windows or Super key "Super" off
// it, as Wails reads them (its "Cmd" off the Mac is Ctrl). A key is a
// letter, a digit, Space or F1–F20, the keys every system's hot key table
// has; one with no modifier but Shift is refused, since it would take a
// key from typing everywhere, but an F key may stand alone. "" is none.
func panelShortcut(s, goos string) (string, error) {
s = strings.TrimSpace(s)
if s == "" {
return "", nil
}
var ctrl, alt, shift, meta bool
parts := strings.Split(s, "+")
key := strings.ToLower(strings.TrimSpace(parts[len(parts)-1]))
for _, part := range parts[:len(parts)-1] {
switch strings.ToLower(strings.TrimSpace(part)) {
case "ctrl", "control":
ctrl = true
case "alt", "option":
alt = true
case "shift":
shift = true
case "cmd", "command", "super", "win", "meta":
meta = true
default:
return "", errNotShortcut
}
}
fkey := len(key) >= 2 && key[0] == 'f' && slices.Contains(fKeys, key[1:])
switch {
case len(key) == 1 && (key[0] >= 'a' && key[0] <= 'z' || key[0] >= '0' && key[0] <= '9'):
key = strings.ToUpper(key)
case key == "space":
key = "Space"
case fkey:
key = strings.ToUpper(key)
default:
return "", errNotShortcut
}
if !ctrl && !alt && !meta && !fkey {
return "", errNotShortcut
}
var out []string
if ctrl {
out = append(out, "Ctrl")
}
if alt {
out = append(out, map[bool]string{true: "Option", false: "Alt"}[goos == "darwin"])
}
if shift {
out = append(out, "Shift")
}
if meta {
out = append(out, map[bool]string{true: "Cmd", false: "Super"}[goos == "darwin"])
}
return strings.Join(append(out, key), "+"), nil
}
// errNotShortcut is what the page is told of a combination it shouldn't
// have sent: the page checks each press itself first.
var errNotShortcut = errors.New("Not a shortcut magpie can use")
var fKeys = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"}
+89
View File
@@ -0,0 +1,89 @@
//go:build !nogui
package gui
import (
"errors"
"log"
"strings"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/yetone/magpie/internal/settings"
)
// errPanelKeyFailed is a refusal that isn't another app's hold: a key
// this keyboard has no code for, or no display to bind on.
var errPanelKeyFailed = errors.New("magpie couldn't take this shortcut")
// startPanelKey binds the saved shortcut once the app has started, and
// has Settings bind each one recorded after. A magpie this one took over
// from (before, its pid) may hold it until it has quit: refused, it is
// tried again then.
func (h *host) startPanelKey(before int) {
onPanelShortcut = h.bindPanelKey
go func() {
<-h.ready
s := settings.Load().PanelShortcut
if s == "" || !panelKeysState().Can {
return
}
if h.bindPanelKey(s) != nil && before != 0 {
awaitExit(before, handedOffWait)
if settings.Load().PanelShortcut == s {
_ = h.bindPanelKey(s)
}
}
}()
}
// bindPanelKey binds s ("" for none) in place of the shortcut bound now.
// Refused, the one before is bound again, and a saved one refused is
// said in Settings (panelKeyTaken) until one is bound.
func (h *host) bindPanelKey(s string) error {
h.keyMu.Lock()
defer h.keyMu.Unlock()
gs := h.app.GlobalShortcut
old := h.panelKey
if old != "" && old != s {
if err := gs.Unregister(old); err != nil {
log.Println("panel shortcut:", err)
}
h.panelKey = ""
}
if s != "" && h.panelKey != s {
if err := gs.Register(s, h.panelKeyPressed); err != nil {
log.Println("panel shortcut:", err)
if old != "" && old != s && gs.Register(old, h.panelKeyPressed) == nil {
h.panelKey = old
}
if s == settings.Load().PanelShortcut {
panelKeyTaken.Store(s)
}
if strings.Contains(err.Error(), "already registered") {
return errPanelKeyTaken
}
return errPanelKeyFailed
}
h.panelKey = s
}
panelKeyTaken.Store("")
return nil
}
// dropPanelKey lets the shortcut go, for a Mac's magpie leaving the menu
// bar to the version it handed over to.
func (h *host) dropPanelKey() {
h.keyMu.Lock()
defer h.keyMu.Unlock()
if h.panelKey != "" {
_ = h.app.GlobalShortcut.Unregister(h.panelKey)
h.panelKey = ""
}
}
// panelKeyPressed opens the quick panel, or closes it, as a click on the
// tray icon does when it opens the panel. Wails calls it on a goroutine
// of its own; togglePanel goes to the main thread.
func (h *host) panelKeyPressed() {
h.whenReady(func() { application.InvokeAsync(h.togglePanel) })
}
+133
View File
@@ -0,0 +1,133 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
func TestPanelShortcutNames(t *testing.T) {
for _, c := range []struct{ in, goos, want string }{
{"", "darwin", ""},
{"Cmd+Shift+m", "darwin", "Shift+Cmd+M"},
{"Option+Ctrl+Space", "darwin", "Ctrl+Option+Space"},
{"Super+Alt+k", "linux", "Alt+Super+K"},
{"Cmd+K", "windows", "Super+K"},
{"Option+1", "windows", "Alt+1"},
{"F5", "windows", "F5"},
{"Shift+F20", "linux", "Shift+F20"},
} {
got, err := panelShortcut(c.in, c.goos)
if err != nil || got != c.want {
t.Errorf("panelShortcut(%q, %s) = %q, %v; want %q", c.in, c.goos, got, err, c.want)
}
}
// a key typing needs, a key no system's table has, a made-up modifier
for _, in := range []string{"K", "Shift+K", "Ctrl+Tab", "Ctrl+F21", "Ctrl+", "Hyper+K", "Ctrl+KK", "Cmd+;"} {
if got, err := panelShortcut(in, "darwin"); err == nil {
t.Errorf("panelShortcut(%q) = %q, want refused", in, got)
}
}
}
func TestWaylandSession(t *testing.T) {
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
for _, c := range []struct {
goos string
env map[string]string
want bool
}{
{"linux", map[string]string{"XDG_SESSION_TYPE": "wayland"}, true},
{"linux", map[string]string{"XDG_SESSION_TYPE": "x11", "WAYLAND_DISPLAY": "wayland-1"}, false},
{"linux", map[string]string{"WAYLAND_DISPLAY": "wayland-1"}, true},
{"linux", map[string]string{}, false},
{"darwin", map[string]string{"XDG_SESSION_TYPE": "wayland"}, false},
} {
if got := waylandSession(c.goos, env(c.env)); got != c.want {
t.Errorf("waylandSession(%s, %v) = %v", c.goos, c.env, got)
}
}
if got := shellWord("/opt/My Apps/magpie"); got != `'/opt/My Apps/magpie'` {
t.Errorf("shellWord: %s", got)
}
}
// The shortcut is saved only once the app has it; one the system refuses
// is not saved and the old one stays bound; the Settings page's own save
// and a sync's leave it as it was.
func TestPanelShortcutSetting(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("XDG_SESSION_TYPE", "x11")
var bound []string
refuse := ""
was := onPanelShortcut
onPanelShortcut = func(s string) error {
if s != "" && s == refuse {
return errPanelKeyTaken
}
bound = append(bound, s)
return nil
}
t.Cleanup(func() { onPanelShortcut = was })
srv := Handler(&zoomWindows{}, nil)
post := func(path, body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec
}
rec := post("/api/settings/panel-shortcut", `{"shortcut":"Ctrl+Alt+Shift+K"}`)
if rec.Code != http.StatusOK {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
key, _ := panelShortcut("Ctrl+Alt+Shift+K", runtime.GOOS)
var got struct {
PanelShortcut string
PanelKeys panelKeysJSON
}
if json.Unmarshal(rec.Body.Bytes(), &got); got.PanelShortcut != key || settings.Load().PanelShortcut != key || !got.PanelKeys.Can {
t.Fatalf("answered %+v, saved %q", got, settings.Load().PanelShortcut)
}
if len(bound) != 1 || bound[0] != key {
t.Fatalf("bound %v", bound)
}
refuse = "Ctrl+J"
if rec := post("/api/settings/panel-shortcut", `{"shortcut":"Ctrl+J"}`); rec.Code == http.StatusOK || !strings.Contains(rec.Body.String(), errPanelKeyTaken.Error()) || settings.Load().PanelShortcut != key {
t.Fatalf("a refused shortcut: %d %s, saved %q", rec.Code, rec.Body, settings.Load().PanelShortcut)
}
if rec := post("/api/settings/panel-shortcut", `{"shortcut":"Shift+K"}`); rec.Code == http.StatusOK || settings.Load().PanelShortcut != key || len(bound) != 1 {
t.Fatalf("a key typing needs was taken: %d", rec.Code)
}
if rec := post("/api/settings", `{"theme":"dark","lang":"en"}`); rec.Code != http.StatusOK || settings.Load().PanelShortcut != key {
t.Fatalf("the Settings page's save changed the shortcut: %d %q", rec.Code, settings.Load().PanelShortcut)
}
in := settings.Settings{}
in.KeepOwn(settings.Load())
if in.PanelShortcut != key {
t.Fatalf("a synced setup took this computer's shortcut: %q", in.PanelShortcut)
}
if rec := post("/api/settings/panel-shortcut", `{"shortcut":""}`); rec.Code != http.StatusOK || settings.Load().PanelShortcut != "" || bound[len(bound)-1] != "" {
t.Fatalf("clearing: %d, saved %q, bound %v", rec.Code, settings.Load().PanelShortcut, bound)
}
// a Wayland desktop binds it itself: nothing is taken, and the row is
// told the command
if runtime.GOOS != "linux" {
return
}
t.Setenv("XDG_SESSION_TYPE", "wayland")
if rec := post("/api/settings/panel-shortcut", `{"shortcut":"Ctrl+K"}`); rec.Code == http.StatusOK || settings.Load().PanelShortcut != "" || len(bound) != 2 {
t.Fatalf("taken on Wayland: %d, bound %v", rec.Code, bound)
}
if st := panelKeysState(); st.Can || !strings.HasSuffix(st.Command, " panel") {
t.Fatalf("Wayland's state: %+v", st)
}
}
+1
View File
@@ -193,6 +193,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
was.ClaudeRunsMost = 3
was.RequestArchiveLocal, was.RequestArchiveLocalMB = true, 256
was.ProxyCustom = "http://me:secret@proxy.example:8080"
was.PanelShortcut = "Ctrl+Alt+K"
if err := settings.Save(was); err != nil {
t.Fatal(err)
}
+171
View File
@@ -0,0 +1,171 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// ben hanks on Discord: a key combination that opens the tray's quick panel
// from any app. Settings › General has one row for it, none set by default,
// in both engines and every language, on a Mac and off it, with the API
// faked:
// - the field listens once clicked; a key with no Ctrl, Alt or Cmd/Win is
// not taken, and the window's own keys (text size) don't fire meanwhile;
// - a combination is sent as Wails names it, and shown in the system's way
// (⇧⌘K on a Mac, Ctrl+Alt+K elsewhere); Esc stops listening, sending none;
// - one the system refuses says so in the status line, the saved one kept;
// - the clear button takes it away; nothing the row does scrolls the page;
// - on Wayland the field is off and the row says the command to bind;
// - a browser tab (magpie web) has no row; a narrow window keeps it inside.
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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const words = {
en: { name: "Quick panel shortcut", record: "Record shortcut", type: "Type shortcut", taken: "Another app already uses this shortcut" },
zh: { name: "快捷面板快捷键", record: "录制快捷键", type: "请按下快捷键", taken: "其他应用已占用这个快捷键" },
"zh-TW": { name: "快捷面板快速鍵", record: "錄製快速鍵", type: "請按下快速鍵", taken: "其他應用程式已占用這個快速鍵" },
ja: { name: "クイックパネルのショートカット", record: "ショートカットを記録", type: "キーを押してください", taken: "このショートカットは他のアプリが使用中です" },
de: { name: "Tastenkürzel für das Schnellpanel", record: "Kürzel aufnehmen", type: "Kürzel drücken", taken: "Eine andere App nutzt dieses Kürzel bereits" },
};
function serve(lang, web, posted, st) {
const settings = () => ({ lang, theme: "light", tray: "panel", searchVendors: [], searchAPIs: [], panelKeys: { can: true }, ...st });
return async (r) => {
const url = new URL(r.request().url());
const json = (data, status = 200) => r.fulfill({ status, json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() });
if (url.pathname === "/api/settings/panel-shortcut") {
const { shortcut } = JSON.parse(r.request().postData());
posted.push(shortcut);
// the fake system holds Ctrl+Alt+J / ⌃⌥J for another app
if (/^Ctrl\+(Alt|Option)\+J$/.test(shortcut)) return json({ error: "Another app already uses this shortcut" }, 400);
st.panelShortcut = shortcut;
return json(settings());
}
if (url.pathname.startsWith("/api/settings/")) { posted.push(url.pathname); return json(settings()); }
if (url.pathname === "/api/settings") return json(settings());
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
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 r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
};
}
const langs = Object.keys(words);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
langs.forEach((lang) => {
for (const platform of ["MacIntel", "Win32"]) {
const mac = platform === "MacIntel";
test(`${engine} ${lang} ${mac ? "mac" : "windows"}: the quick panel's shortcut is recorded, refused, cleared`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const w = words[lang];
const open = async (st, { web = false, width = 1000 } = {}) => {
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.addInitScript((p) => Object.defineProperty(navigator, "platform", { get: () => p }), platform);
const posted = [];
await page.route("**/*", serve(lang, web, posted, st));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=general");
await settingsDrawn(page);
return { page, posted, errors };
};
const { page, posted, errors } = await open({});
const rec = page.locator("#panelKey .key-rec"), clear = page.locator("#panelKey .key-clear");
assert.equal(await page.locator("#panelKeyRow .name").textContent(), w.name);
assert.equal(await rec.textContent(), w.record, "none is set by default");
assert.equal(await clear.isHidden(), true);
assert.equal(await page.locator("#panelKeyRow .sub").isHidden(), true);
await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {}))));
await page.locator("#panelKeyRow").hover();
await page.mouse.wheel(0, 120);
await page.waitForTimeout(300);
// where the row is on the screen: nothing the row does moves it
const top = () => page.evaluate(() => { const v = document.querySelector("#view-settings"); return `${Math.round(document.querySelector("#panelKeyRow").getBoundingClientRect().top)} (${v.scrollTop}/${v.scrollHeight - v.clientHeight})`; });
const at = await top();
// listening: a key with no Ctrl, Alt or Cmd isn't taken, nor are
// the window's text size keys run
await rec.click();
assert.equal(await rec.textContent(), w.type);
await page.keyboard.press("Shift+K");
await page.keyboard.press((mac ? "Meta" : "Control") + "+Equal");
await page.keyboard.press("Digit5");
await page.waitForTimeout(100);
assert.deepEqual(posted, [], "a key typing needs was sent, or a window key ran");
assert.equal(await rec.textContent(), w.type);
// Esc stops it, sending none
await page.keyboard.press("Escape");
assert.equal(await rec.textContent(), w.record);
assert.equal(await page.locator("#view-settings").isVisible(), true, "Esc left Settings");
assert.deepEqual(posted, []);
// a combination, sent as Wails names it and shown the system's way
await rec.click();
await page.keyboard.press(mac ? "Meta+Shift+KeyK" : "Control+Alt+KeyK");
const want = mac ? "Shift+Cmd+K" : "Ctrl+Alt+K";
for (let i = 0; i < 50 && posted.length < 1; i++) await page.waitForTimeout(50);
assert.deepEqual(posted, [want]);
await page.waitForFunction((s) => document.querySelector("#panelKey .key-rec").textContent === s, mac ? "⇧⌘K" : "Ctrl+Alt+K");
assert.equal(await clear.isVisible(), true);
// one the system refuses: said, the saved one kept
await page.waitForFunction(() => prefsBusy === 0);
await rec.click();
await page.keyboard.press("Control+Alt+KeyJ");
for (let i = 0; i < 50 && posted.length < 2; i++) await page.waitForTimeout(50);
assert.deepEqual(posted, [want, mac ? "Ctrl+Option+J" : "Ctrl+Alt+J"]);
await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), w.taken);
await page.waitForFunction((s) => document.querySelector("#panelKey .key-rec").textContent === s, mac ? "⇧⌘K" : "Ctrl+Alt+K");
// clicking away stops listening
await rec.click();
await page.locator("#panelKeyRow .name").click();
await page.waitForFunction((s) => document.querySelector("#panelKey .key-rec").textContent === s, mac ? "⇧⌘K" : "Ctrl+Alt+K");
// cleared
await page.waitForFunction(() => prefsBusy === 0);
await clear.click();
for (let i = 0; i < 50 && posted.length < 3; i++) await page.waitForTimeout(50);
assert.equal(posted[2], "");
await page.waitForFunction((s) => document.querySelector("#panelKey .key-rec").textContent === s, w.record);
assert.equal(await clear.isHidden(), true);
assert.equal(await top(), at, "the row moved on the screen");
assert.deepEqual(errors, []);
// the saved one the system refused as magpie started is said
const taken = await open({ panelShortcut: "Ctrl+Alt+K", panelKeys: { can: true, taken: "Ctrl+Alt+K" } });
assert.equal(await taken.page.locator("#panelKeyRow .sub").textContent(), w.taken);
// Wayland: off, with the command to bind
const way = await open({ panelKeys: { can: false, command: "/usr/bin/magpie panel" } });
assert.equal(await way.page.locator("#panelKey .key-rec").isDisabled(), true);
const sub = way.page.locator("#panelKeyRow .sub");
assert.equal(await sub.isVisible(), true);
assert.ok((await sub.textContent()).includes("/usr/bin/magpie panel"), await sub.textContent());
assert.ok(lang === "en" || !(await sub.textContent()).includes("keyboard settings"), "the Wayland line isn't translated");
assert.deepEqual(way.errors, []);
// a browser tab has no row
const tab = await open({}, { web: true });
assert.equal(await tab.page.locator("#panelKeyRow").isHidden(), true);
// a narrow window keeps the field inside its row
const narrow = await open({ panelShortcut: mac ? "Ctrl+Option+Shift+Cmd+K" : "Ctrl+Alt+Shift+Super+K" }, { width: 420 });
const [row, field, x] = await narrow.page.evaluate(() => ["#panelKeyRow", "#panelKey .key-rec", "#panelKey .key-clear"]
.map((s) => { const b = document.querySelector(s).getBoundingClientRect(); return { l: b.left, r: b.right }; }));
assert.ok(field.l >= row.l && x.r <= row.r + 0.5, `${JSON.stringify({ row, field, x })}`);
assert.equal(await narrow.page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "the page scrolls sideways");
assert.deepEqual(narrow.errors, []);
});
}
});
}
+9 -2
View File
@@ -56,6 +56,12 @@ type Settings struct {
NoBird bool `json:"noBird,omitempty"`
Lang string `json:"lang,omitempty"` // system | en | zh
Tray string `json:"tray,omitempty"` // what clicking the tray icon opens: panel | window
// PanelShortcut is the key combination that opens the tray's quick
// panel from any app (ben hanks on Discord), as Wails names it
// ("Cmd+Shift+M"); "" is none, the default, so nothing clashes until
// the user records one. This computer's own (KeepOwn): a Mac's Cmd is
// another keyboard's Win key, and what is free differs per computer.
PanelShortcut string `json:"panelShortcut,omitempty"`
// SessionTerminal is the Mac app that opens a resumed session, by bundle
// id. "" and "system" follow the .command file association. This
// computer's own (KeepOwn): another Mac may not have that app.
@@ -1171,8 +1177,8 @@ func (s Settings) Compact() int {
// is shared on the local network and the addresses let in to it, the
// Dock, gateway mode, whether WSL is looked in, whether agents' sign-ins
// are read, when allowances are read, the terminal app a session resumes
// in, whether the local masking model is on (it is downloaded on this
// computer alone), how many Claude Code processes may run (its memory),
// in, the quick panel's shortcut, whether the local masking model is on
// (it is downloaded on this computer alone), how many Claude Code processes may run (its memory),
// and what the menu bar or tray shows beside magpie's icon (yoooo on
// Discord: usage turned off on a Mac came back from a Windows box that
// shows it; Lullaby: sharing turned on at home came on at work).
@@ -1192,6 +1198,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.LAN, s.AllowIPs = cur.LAN, cur.AllowIPs
s.FetchPrivate = cur.FetchPrivate
s.SessionTerminal = cur.SessionTerminal
s.PanelShortcut = cur.PanelShortcut
s.RedactModel, s.RedactModelName, s.RedactModelScore = cur.RedactModel, cur.RedactModelName, cur.RedactModelScore
s.RedactModelOff, s.RedactModelAuto = cur.RedactModelOff, cur.RedactModelAuto
s.ClaudeRunsMost = cur.ClaudeRunsMost