Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(linux): keep the dictation pill above each monitor's own KDE panel (#2624)

voidf2d99b1f0f0b
diff --git a/CLAUDE.md b/CLAUDE.md
index d9723e742..299a690ec 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -173,6 +173,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **localEmbeddings.js**: Local text embedding via ONNX Runtime + all-MiniLM-L6-v2 (384-dim vectors)
- **vectorIndex.js**: Qdrant collection management — upsert, delete, search
- **windowConfig.js**: Centralized window configuration
+- **plasmaWorkAreas.js**: Per-monitor work areas on KDE Plasma. On X11 and XWayland, Chromium clips only the primary display with the single root `_NET_WORKAREA`, which KWin builds from every monitor's panels at once (#1110). This asks plasmashell over D-Bus (`evaluateScript`) for each screen's always-visible panels and rebuilds each display's `workArea` for the dictation pill, its companion windows and dragging. On X11, Qt reports a screen's origin in device pixels and only its size scaled, so those origins are divided by the display scale before matching. It refreshes on display events and each time a dictation shows the pill, retrying after 1, 5 and 15 s when plasmashell isn't ready; a display event starts those retries over. An auto-placed pill re-anchors when the result changes; a dragged one stays put. With a single display, or outside Linux + KDE, Chromium's work area is used as is
- **windowManager.js**: Window creation and lifecycle management
- **cliBridge.js**: Loopback HTTP server on ports 8200–8219, bearer-token auth (token at `~/.openwhispr/cli-bridge.json`), 127.0.0.1-only. Used by the unified CLI to talk to a running desktop app. `POST /v1/transcribe` takes a file **path** (never audio) and runs the user's downloaded local model through `IPCHandlers.transcribeLocalFile`, approving the path with `approveAudioPath` first; `GET /v1/transcribe/models` lists local models with download state and the app's default (`localTranscriptionModels.js`, read from the `.env` pre-warm values).
- **connectors/**: Agent connectors
diff --git a/src/helpers/dragManager.js b/src/helpers/dragManager.js
index 11a8286bc..4f32293be 100644
--- a/src/helpers/dragManager.js
+++ b/src/helpers/dragManager.js
@@ -1,5 +1,6 @@
const { screen } = require("electron");
const { WindowPositionUtil } = require("./windowConfig");
+const { plasmaWorkAreas } = require("./plasmaWorkAreas");
const debugLogger = require("./debugLogger");
class DragManager {
@@ -85,10 +86,12 @@ class DragManager {
// Constrain against the display the window lands on, not the one under the
// cursor: near a boundary between differently sized displays, the cursor's
// work area permits positions that leave the window in dead space.
- const display = screen.getDisplayNearestPoint({
- x: x + width / 2,
- y: y + height / 2,
- });
+ const display = plasmaWorkAreas.resolve(
+ screen.getDisplayNearestPoint({
+ x: x + width / 2,
+ y: y + height / 2,
+ })
+ );
const clamped = WindowPositionUtil.clampToWorkArea({ x, y, width, height }, display);
this.activeWindow.setPosition(clamped.x, clamped.y);
diff --git a/src/helpers/mainWindowPlacementCoordinator.js b/src/helpers/mainWindowPlacementCoordinator.js
index 1e44d8f8f..cc38b980b 100644
--- a/src/helpers/mainWindowPlacementCoordinator.js
+++ b/src/helpers/mainWindowPlacementCoordinator.js
@@ -13,6 +13,10 @@ class MainWindowPlacementCoordinator {
this.cancelPending();
}
+ hasManualPosition() {
+ return this._hasManualPosition;
+ }
+
resetManualPosition() {
this._hasManualPosition = false;
this.cancelPending();
diff --git a/src/helpers/plasmaWorkAreas.js b/src/helpers/plasmaWorkAreas.js
new file mode 100644
index 000000000..ea4ad35db
--- /dev/null
+++ b/src/helpers/plasmaWorkAreas.js
@@ -0,0 +1,283 @@
+const { screen } = require("electron");
+const debugLogger = require("./debugLogger");
+const KDEShortcutManager = require("./kdeShortcut");
+const { getLinuxSessionInfo } = require("./linuxSession");
+
+// On X11, and on XWayland where the app runs in a KDE Wayland session, Chromium
+// builds every display's workArea from the single root _NET_WORKAREA: only the
+// primary display gets clipped, and KWin computes that one rectangle from every
+// monitor's panels at once. So one monitor's panel is ignored while another's
+// cuts into the primary (#1110). Plasma knows each screen's panels, so the
+// work areas the pill is placed against are rebuilt from what it reports.
+
+const SNAPSHOT_TIMEOUT_MS = 400;
+// plasmashell can still be starting at login, or answer a display change with
+// its previous layout.
+const RETRY_DELAYS_MS = [1000, 5000, 15000];
+// Plasma reports logical pixels and Electron DIPs, which round differently.
+const GEOMETRY_TOLERANCE = 0.02;
+const EDGES = ["top", "right", "bottom", "left"];
+
+// Runs in plasmashell's script engine. A panel's height is its thickness on
+// every edge, and only an always-visible panel reserves space.
+const SNAPSHOT_SCRIPT = [
+ "var screens = [];",
+ "for (var i = 0; i < screenCount; i++) {",
+ " var g = screenGeometry(i);",
+ " screens.push({ x: g.x, y: g.y, width: g.width, height: g.height });",
+ "}",
+ "print(JSON.stringify({ screens: screens, panels: panels().map(function (p) {",
+ " return { screen: p.screen, location: p.location, thickness: p.height, hiding: p.hiding };",
+ "}) }));",
+].join("\n");
+
+function unionOf(rects) {
+ const left = Math.min(...rects.map((rect) => rect.x));
+ const top = Math.min(...rects.map((rect) => rect.y));
+ return { x: left, y: top, width: Math.max(...rects.map((rect) => rect.x + rect.width)) - left };
+}
+
+function withinTolerance(value, expected, size) {
+ return Math.abs(value - expected) <= size * GEOMETRY_TOLERANCE;
+}
+
+// Plasma's logical layout and Electron's DIP layout differ by one factor:
+// XWayland scales every output alike and Chromium uses one scale on X11. Each
+// display is matched to the Plasma screen at the same scaled place and size;
+// anything that doesn't match one-to-one yields no corrections at all.
+function computeWorkAreas(snapshot, displays, { x11 = false } = {}) {
+ const workAreas = new Map();
+ if (
+ !Array.isArray(snapshot?.screens) ||
+ !snapshot.screens.length ||
+ snapshot.screens.length !== displays.length
+ ) {
+ return workAreas;
+ }
+ // On X11, Qt keeps each screen's origin in device pixels and scales only its
+ // size (QHighDpi::fromNativeScreenGeometry), while Chromium scales both.
+ const originScale = x11 ? displays[0].scaleFactor : 1;
+ const screens = snapshot.screens.map((rect) => ({
+ ...rect,
+ x: rect.x / originScale,
+ y: rect.y / originScale,
+ }));
+
+ const insets = screens.map(() => ({ top: 0, right: 0, bottom: 0, left: 0 }));
+ for (const panel of Array.isArray(snapshot.panels) ? snapshot.panels : []) {
+ const screenInsets = insets[panel?.screen];
+ if (!screenInsets || panel.hiding !== "none" || !EDGES.includes(panel.location)) continue;
+ screenInsets[panel.location] = Math.max(screenInsets[panel.location], panel.thickness);
+ }
+
+ const displayUnion = unionOf(displays.map((display) => display.bounds));
+ const screenUnion = unionOf(screens);
+ const scale = displayUnion.width / screenUnion.width;
+ const matched = new Set();
+ for (const { id, bounds } of displays) {
+ const index = screens.findIndex(
+ (rect, i) =>
+ !matched.has(i) &&
+ withinTolerance(
+ (rect.x - screenUnion.x) * scale + displayUnion.x,
+ bounds.x,
+ bounds.width
+ ) &&
+ withinTolerance(
+ (rect.y - screenUnion.y) * scale + displayUnion.y,
+ bounds.y,
+ bounds.height
+ ) &&
+ withinTolerance(rect.width * scale, bounds.width, bounds.width) &&
+ withinTolerance(rect.height * scale, bounds.height, bounds.height)
+ );
+ if (index === -1) return new Map();
+ matched.add(index);
+ const [top, right, bottom, left] = EDGES.map((edge) => Math.round(insets[index][edge] * scale));
+ const workArea = {
+ x: bounds.x + left,
+ y: bounds.y + top,
+ width: bounds.width - left - right,
+ height: bounds.height - top - bottom,
+ };
+ if (!(workArea.width > 0 && workArea.height > 0)) return new Map();
+ workAreas.set(id, workArea);
+ }
+ return workAreas;
+}
+
+function sameBounds(a, b) {
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
+}
+
+function createPlasmaWorkAreas({ screen, fetchSnapshot, isActive, isX11 = () => false }) {
+ let corrections = new Map();
+ let onChange = null;
+ let started = false;
+ let inFlight = null;
+ let rerun = false;
+ let retryTimer = null;
+ let retries = 0;
+
+ function resetRetries() {
+ clearTimeout(retryTimer);
+ retryTimer = null;
+ retries = 0;
+ }
+
+ function retryLater() {
+ if (retryTimer || retries >= RETRY_DELAYS_MS.length) return;
+ retryTimer = setTimeout(() => {
+ retryTimer = null;
+ void refresh();
+ }, RETRY_DELAYS_MS[retries++]);
+ retryTimer.unref?.();
+ }
+
+ function apply(next) {
+ if (JSON.stringify([...next]) === JSON.stringify([...corrections])) return;
+ corrections = next;
+ debugLogger.debug(
+ "[PlasmaWorkAreas] Work areas changed",
+ { workAreas: Object.fromEntries([...next].map(([id, { workArea }]) => [id, workArea])) },
+ "window"
+ );
+ onChange?.();
+ }
+
+ async function load() {
+ // With one display Chromium's work area is already right: the root work
+ // area lies inside it, and it also counts docks Plasma doesn't know about.
+ if (screen.getAllDisplays().length < 2) {
+ apply(new Map());
+ return;
+ }
+ // A failed or mismatched snapshot keeps the last good corrections:
+ // plasmashell restarting, busy or answering with its previous layout says
+ // nothing about the panels having changed.
+ let snapshot;
+ try {
+ snapshot = await fetchSnapshot();
+ } catch (error) {
+ debugLogger.debug(
+ "[PlasmaWorkAreas] plasmashell unavailable",
+ { error: error?.message || String(error) },
+ "window"
+ );
+ retryLater();
+ return;
+ }
+ const displays = screen.getAllDisplays();
+ const workAreas = computeWorkAreas(snapshot, displays, { x11: isX11() });
+ if (!workAreas.size) {
+ debugLogger.debug(
+ "[PlasmaWorkAreas] Plasma's answer doesn't fit the displays",
+ { screens: snapshot?.screens, displays: displays.map((display) => display.bounds) },
+ "window"
+ );
+ retryLater();
+ return;
+ }
+ resetRetries();
+ apply(
+ new Map(
+ displays
+ .filter((display) => workAreas.has(display.id))
+ .map((display) => [
+ display.id,
+ { bounds: display.bounds, workArea: workAreas.get(display.id) },
+ ])
+ )
+ );
+ }
+
+ // A display event can land while a snapshot is in flight; that snapshot may
+ // predate it, so one more runs afterwards.
+ function refresh() {
+ if (!started) return Promise.resolve();
+ if (inFlight) {
+ rerun = true;
+ return inFlight;
+ }
+ inFlight = load().finally(() => {
+ inFlight = null;
+ if (rerun) {
+ rerun = false;
+ void refresh();
+ }
+ });
+ return inFlight;
+ }
+
+ function start(handleChange) {
+ if (started || !isActive()) return Promise.resolve();
+ started = true;
+ onChange = handleChange;
+ // A display change is a new layout to retry for, even after an earlier
+ // layout used up its retries. Shows don't reset them, so a plasmashell
+ // that never answers isn't asked three more times per dictation.
+ for (const event of ["display-added", "display-removed", "display-metrics-changed"]) {
+ screen.on(event, () => {
+ resetRetries();
+ void refresh();
+ });
+ }
+ return refresh();
+ }
+
+ function resolve(display) {
+ const correction = corrections.get(display.id);
+ if (!correction || !sameBounds(correction.bounds, display.bounds)) return display;
+ return { ...display, workArea: { ...correction.workArea } };
+ }
+
+ return { start, refresh, resolve };
+}
+
+function fetchPlasmaSnapshot() {
+ let bus;
+ try {
+ bus = require("@homebridge/dbus-native").sessionBus();
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const finish = (error, reply) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeoutId);
+ bus.connection.end();
+ if (error) reject(error);
+ else resolve(reply);
+ };
+ const timeoutId = setTimeout(
+ () => finish(new Error("plasmashell did not answer")),
+ SNAPSHOT_TIMEOUT_MS
+ );
+ timeoutId.unref?.();
+ // sessionBus() returns before connecting, so a stale bus address only
+ // surfaces as an "error" event, which would otherwise crash the process.
+ bus.connection.on("error", finish);
+ bus.invoke(
+ {
+ destination: "org.kde.plasmashell",
+ path: "/PlasmaShell",
+ interface: "org.kde.PlasmaShell",
+ member: "evaluateScript",
+ signature: "s",
+ body: [SNAPSHOT_SCRIPT],
+ },
+ finish
+ );
+ }).then((reply) => JSON.parse(reply));
+}
+
+const plasmaWorkAreas = createPlasmaWorkAreas({
+ screen,
+ fetchSnapshot: fetchPlasmaSnapshot,
+ isActive: () => process.platform === "linux" && KDEShortcutManager.isKDE(),
+ isX11: () => !getLinuxSessionInfo().isWayland,
+});
+
+module.exports = { computeWorkAreas, createPlasmaWorkAreas, fetchPlasmaSnapshot, plasmaWorkAreas };
diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.js
index b95f46aba..98cea1b30 100644
--- a/src/helpers/windowManager.js
+++ b/src/helpers/windowManager.js
@@ -13,6 +13,7 @@ const HotkeyManager = require("./hotkeyManager");
const { isGlobeLikeHotkey } = HotkeyManager;
const DragManager = require("./dragManager");
const MainWindowPlacementCoordinator = require("./mainWindowPlacementCoordinator");
+const { plasmaWorkAreas } = require("./plasmaWorkAreas");
const MenuManager = require("./menuManager");
const DevServerManager = require("./devServerManager");
const {
@@ -131,8 +132,12 @@ class WindowManager {
}
async createMainWindow() {
+ void plasmaWorkAreas.start(() => {
+ this.positionAgentDictationPill();
+ return this._reanchorMainWindow();
+ });
const cursorPos = screen.getCursorScreenPoint();
- const display = screen.getDisplayNearestPoint(cursorPos);
+ const display = plasmaWorkAreas.resolve(screen.getDisplayNearestPoint(cursorPos));
const position = WindowPositionUtil.getMainWindowPosition(
display,
null,
@@ -574,10 +579,12 @@ class WindowManager {
// The pill is bottom-anchored, so the display that owns its bottom-center
// point is the one that must keep it through resizes and repositions.
_getMainWindowDisplayFor(bounds) {
- return screen.getDisplayNearestPoint({
- x: bounds.x + bounds.width / 2,
- y: bounds.y + bounds.height,
- });
+ return plasmaWorkAreas.resolve(
+ screen.getDisplayNearestPoint({
+ x: bounds.x + bounds.width / 2,
+ y: bounds.y + bounds.height,
+ })
+ );
}
_resolveMainWindowSize(sizeKey, workArea, request) {
@@ -1672,12 +1679,17 @@ class WindowManager {
}
}
const bounds = pid ? await this.textEditMonitor.getTargetWindowBounds(pid) : null;
- return bounds
- ? screen.getDisplayMatching(bounds)
- : screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
+ return plasmaWorkAreas.resolve(
+ bounds
+ ? screen.getDisplayMatching(bounds)
+ : screen.getDisplayNearestPoint(screen.getCursorScreenPoint())
+ );
}
_repositionToActiveDisplay(targetPidPromise) {
+ // A panel edit that leaves the root work area unchanged raises no display
+ // event, so look again on every show; a change re-anchors the pill.
+ void plasmaWorkAreas.refresh();
return this._mainWindowPlacementCoordinator.request(
() => this._resolveActiveDisplay(targetPidPromise),
(activeDisplay, isCurrent) =>
@@ -1727,6 +1739,10 @@ class WindowManager {
{ from: currentBounds, to: newPos, displayId: activeDisplay.id },
"window"
);
+ return this._moveMainWindowTo(newPos);
+ }
+
+ _moveMainWindowTo(newPos) {
this._clearRendererResizeMask();
this.mainWindow.setBounds(newPos);
// This is an intentional native move, not a drag. Keep resize restoration
@@ -1738,6 +1754,35 @@ class WindowManager {
return { applied: true, bounds: newPos };
}
+ // Corrected work areas can arrive after the pill was placed: plasmashell
+ // answers after startup, or a panel changed. An auto-placed pill moves to its
+ // display's anchor; one the user dragged stays where they put it.
+ _reanchorMainWindow() {
+ return this._enqueueMainWindowMutation(() => {
+ if (
+ !this.mainWindow ||
+ this.mainWindow.isDestroyed() ||
+ this.dragManager.isDragActive() ||
+ this._mainWindowPlacementCoordinator.hasManualPosition()
+ ) {
+ return;
+ }
+ const currentBounds = this.mainWindow.getBounds();
+ const newPos = WindowPositionUtil.getMainWindowPosition(
+ this._getMainWindowDisplayFor(currentBounds),
+ { width: currentBounds.width, height: currentBounds.height },
+ this._panelStartPosition
+ );
+ if (newPos.x === currentBounds.x && newPos.y === currentBounds.y) return;
+ debugLogger.debug(
+ "[WindowManager] Re-anchoring dictation panel to the corrected work area",
+ { from: currentBounds, to: newPos },
+ "window"
+ );
+ this._moveMainWindowTo(newPos);
+ });
+ }
+
showDictationPanel(options = {}) {
if (this._onboardingActive) return;
const { focus = false, reposition = false, targetPidPromise } = options;
@@ -2014,7 +2059,7 @@ class WindowManager {
}
const mainBounds = this.mainWindow.getBounds();
- const display = screen.getDisplayMatching(mainBounds);
+ const display = plasmaWorkAreas.resolve(screen.getDisplayMatching(mainBounds));
const mainSide = resolveHorizontalWindowDirection(
mainBounds,
display,
@@ -2042,7 +2087,7 @@ class WindowManager {
}
const mainBounds = this.mainWindow.getBounds();
- const display = screen.getDisplayMatching(mainBounds);
+ const display = plasmaWorkAreas.resolve(screen.getDisplayMatching(mainBounds));
const nextSize =
surfaceHeight === null
? AGENT_DICTATION_PILL_SIZE
diff --git a/test/helpers/plasmaWorkAreas.test.js b/test/helpers/plasmaWorkAreas.test.js
new file mode 100644
index 000000000..2b4672143
--- /dev/null
+++ b/test/helpers/plasmaWorkAreas.test.js
@@ -0,0 +1,391 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { EventEmitter } = require("node:events");
+const Module = require("node:module");
+
+const {
+ computeWorkAreas,
+ createPlasmaWorkAreas,
+ fetchPlasmaSnapshot,
+} = require("../../src/helpers/plasmaWorkAreas");
+const { WindowPositionUtil } = require("../../src/helpers/windowConfig");
+
+// #1110, measured on KWin 6.7.5 + Xwayland: a 1080p at 100% on the left and a 4K
+// at 170% (primary) on the right, each with a 46 px bottom panel. Chromium clips
+// only the primary with the single _NET_WORKAREA, and KWin built that rectangle
+// from the 1080p's panel, so the 4K lost 236 DIP and the 1080p none.
+const ELECTRON_DISPLAYS = [
+ {
+ id: 33,
+ bounds: { x: -1, y: 0, width: 1918, height: 1079 },
+ workArea: { x: -1, y: 0, width: 1918, height: 1079 },
+ },
+ {
+ id: 35,
+ bounds: { x: 1916, y: 0, width: 2256, height: 1269 },
+ workArea: { x: 1916, y: 0, width: 2256, height: 1033 },
+ },
+];
+const PLASMA_SNAPSHOT = {
+ screens: [
+ { x: 1920, y: 0, width: 2259, height: 1271 },
+ { x: 0, y: 0, width: 1920, height: 1080 },
+ ],
+ panels: [
+ { screen: 0, location: "bottom", thickness: 46, hiding: "none" },
+ { screen: 1, location: "bottom", thickness: 46, hiding: "none" },
+ ],
+};
+const PILL = { width: 211, height: 123 };
+
+function singleScreen(panels) {
+ return {
+ snapshot: { screens: [{ x: 0, y: 0, width: 1920, height: 1080 }], panels },
+ displays: [{ id: 1, bounds: { x: 0, y: 0, width: 1920, height: 1080 } }],
+ };
+}
+
+test("each monitor's work area excludes its own panel, so the pill rests above it (#1110)", () => {
+ const workAreas = computeWorkAreas(PLASMA_SNAPSHOT, ELECTRON_DISPLAYS);
+
+ assert.deepEqual(workAreas.get(33), { x: -1, y: 0, width: 1918, height: 1033 });
+ assert.deepEqual(workAreas.get(35), { x: 1916, y: 0, width: 2256, height: 1223 });
+ for (const display of ELECTRON_DISPLAYS) {
+ const pill = WindowPositionUtil.getMainWindowPosition(
+ { ...display, workArea: workAreas.get(display.id) },
+ PILL,
+ "bottom-right"
+ );
+ const gapToScreenBottom = display.bounds.y + display.bounds.height - (pill.y + pill.height);
+ assert.equal(gapToScreenBottom, 46 + 4, `display ${display.id}`);
+ }
+});
+
+test("only always-visible panels reserve space, and panels sharing an edge take the thickest", () => {
+ const { snapshot, displays } = singleScreen([
+ { screen: 0, location: "bottom", thickness: 30, hiding: "none" },
+ { screen: 0, location: "bottom", thickness: 46, hiding: "none" },
+ { screen: 0, location: "left", thickness: 60, hiding: "none" },
+ { screen: 0, location: "top", thickness: 24, hiding: "none" },
+ { screen: 0, location: "top", thickness: 30, hiding: "autohide" },
+ { screen: 0, location: "right", thickness: 40, hiding: "dodgewindows" },
+ ]);
+
+ assert.deepEqual(computeWorkAreas(snapshot, displays).get(1), {
+ x: 60,
+ y: 24,
+ width: 1860,
+ height: 1010,
+ });
+});
+
+// A Plasma X11 session at 200% with two 4K monitors: Qt keeps each screen's
+// origin in device pixels and scales only its size, while Chromium scales both.
+const X11_DISPLAYS = [
+ { id: 1, scaleFactor: 2, bounds: { x: 0, y: 0, width: 1920, height: 1080 } },
+ { id: 2, scaleFactor: 2, bounds: { x: 1920, y: 0, width: 1920, height: 1080 } },
+];
+const X11_SNAPSHOT = {
+ screens: [
+ { x: 0, y: 0, width: 1920, height: 1080 },
+ { x: 3840, y: 0, width: 1920, height: 1080 },
+ ],
+ panels: [{ screen: 1, location: "bottom", thickness: 44, hiding: "none" }],
+};
+
+test("on X11, Plasma's pixel origins are scaled like Chromium's before matching", () => {
+ assert.equal(computeWorkAreas(X11_SNAPSHOT, X11_DISPLAYS).size, 0, "read as logical");
+
+ const workAreas = computeWorkAreas(X11_SNAPSHOT, X11_DISPLAYS, { x11: true });
+
+ assert.deepEqual(workAreas.get(1), { x: 0, y: 0, width: 1920, height: 1080 });
+ assert.deepEqual(workAreas.get(2), { x: 1920, y: 0, width: 1920, height: 1036 });
+});
+
+test("layouts that don't line up yield no corrections", () => {
+ const { snapshot, displays } = singleScreen([]);
+ const cases = {
+ "a display Plasma doesn't list": [snapshot, ELECTRON_DISPLAYS],
+ "a screen of another size": [
+ { screens: [{ x: 0, y: 0, width: 1920, height: 1200 }], panels: [] },
+ displays,
+ ],
+ "no screens": [{ panels: [] }, displays],
+ "a panel without a usable thickness": [
+ {
+ ...snapshot,
+ panels: [{ screen: 0, location: "bottom", thickness: "tall", hiding: "none" }],
+ },
+ displays,
+ ],
+ };
+ for (const [name, [input, layout]] of Object.entries(cases)) {
+ assert.equal(computeWorkAreas(input, layout).size, 0, name);
+ }
+});
+
+function fakeScreen(displays) {
+ const screen = new EventEmitter();
+ screen.getAllDisplays = () => displays;
+ return screen;
+}
+
+test("corrections apply once Plasma answers, and only to displays that kept their bounds", async () => {
+ const screen = fakeScreen(ELECTRON_DISPLAYS);
+ let changes = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen,
+ fetchSnapshot: async () => PLASMA_SNAPSHOT,
+ isActive: () => true,
+ });
+
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[1]), ELECTRON_DISPLAYS[1]);
+ await workAreas.start(() => (changes += 1));
+
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[1]).workArea.height, 1223);
+ assert.equal(changes, 1);
+ await workAreas.refresh();
+ assert.equal(changes, 1, "an unchanged snapshot is not a change");
+
+ const resized = { ...ELECTRON_DISPLAYS[1], bounds: { x: 1916, y: 0, width: 1920, height: 1080 } };
+ assert.equal(workAreas.resolve(resized), resized);
+});
+
+test("an X11 session matches Plasma's screens by their pixel origins", async () => {
+ const workAreas = createPlasmaWorkAreas({
+ screen: fakeScreen(X11_DISPLAYS),
+ fetchSnapshot: async () => X11_SNAPSHOT,
+ isActive: () => true,
+ isX11: () => true,
+ });
+
+ await workAreas.start(() => undefined);
+
+ assert.equal(workAreas.resolve(X11_DISPLAYS[1]).workArea.height, 1036);
+});
+
+test("display events refresh, and a failed or mismatched snapshot keeps the last good corrections", async () => {
+ const screen = fakeScreen(ELECTRON_DISPLAYS);
+ let snapshots = 0;
+ let changes = 0;
+ let answer = PLASMA_SNAPSHOT;
+ const workAreas = createPlasmaWorkAreas({
+ screen,
+ fetchSnapshot: async () => {
+ snapshots += 1;
+ if (answer instanceof Error) throw answer;
+ return answer;
+ },
+ isActive: () => true,
+ });
+ await workAreas.start(() => (changes += 1));
+ assert.equal(snapshots, 1);
+
+ answer = new Error("plasmashell did not answer");
+ screen.emit("display-metrics-changed");
+ await workAreas.refresh();
+ assert.equal(snapshots, 3, "the event's snapshot plus one rerun for the overlapping refresh");
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[0]).workArea.height, 1033);
+
+ // plasmashell answering a display change with its previous layout.
+ answer = { screens: PLASMA_SNAPSHOT.screens.slice(0, 1), panels: [] };
+ await workAreas.refresh();
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[0]).workArea.height, 1033);
+ assert.equal(changes, 1, "the pill isn't moved off the corrected work area");
+});
+
+const settle = () => new Promise((resolve) => setImmediate(resolve));
+
+test("a snapshot that fails or doesn't match is retried", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const answers = [new Error("plasmashell did not answer"), { screens: [], panels: [] }];
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen: fakeScreen(ELECTRON_DISPLAYS),
+ fetchSnapshot: async () => {
+ const answer = answers[snapshots++] ?? PLASMA_SNAPSHOT;
+ if (answer instanceof Error) throw answer;
+ return answer;
+ },
+ isActive: () => true,
+ });
+
+ await workAreas.start(() => undefined);
+ t.mock.timers.tick(1000);
+ await settle();
+ assert.equal(snapshots, 2);
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[1]), ELECTRON_DISPLAYS[1]);
+ t.mock.timers.tick(5000);
+ await settle();
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[1]).workArea.height, 1223);
+});
+
+test("retries stop after three attempts", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen: fakeScreen(ELECTRON_DISPLAYS),
+ fetchSnapshot: async () => {
+ snapshots += 1;
+ throw new Error("plasmashell did not answer");
+ },
+ isActive: () => true,
+ });
+
+ await workAreas.start(() => undefined);
+ for (const delay of [1000, 5000, 15000, 60000]) {
+ t.mock.timers.tick(delay);
+ await settle();
+ }
+
+ assert.equal(snapshots, 4);
+});
+
+// plasmashell can still be starting long after login, then answer a later
+// hotplug with its previous layout.
+test("a display event restarts retries that ran out", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const screen = fakeScreen(ELECTRON_DISPLAYS);
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen,
+ fetchSnapshot: async () => {
+ snapshots += 1;
+ throw new Error("plasmashell did not answer");
+ },
+ isActive: () => true,
+ });
+ await workAreas.start(() => undefined);
+ for (const delay of [1000, 5000, 15000]) {
+ t.mock.timers.tick(delay);
+ await settle();
+ }
+ assert.equal(snapshots, 4);
+
+ screen.emit("display-added");
+ await settle();
+ t.mock.timers.tick(1000);
+ await settle();
+
+ assert.equal(snapshots, 6, "the event's snapshot and its first retry");
+});
+
+test("a snapshot that succeeds cancels the pending retry", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen: fakeScreen(ELECTRON_DISPLAYS),
+ fetchSnapshot: async () => {
+ if (snapshots++ === 0) throw new Error("plasmashell did not answer");
+ return PLASMA_SNAPSHOT;
+ },
+ isActive: () => true,
+ });
+ await workAreas.start(() => undefined);
+ await workAreas.refresh();
+ assert.equal(snapshots, 2);
+
+ t.mock.timers.tick(1000);
+ await settle();
+
+ assert.equal(snapshots, 2);
+});
+
+test("a single display keeps Chromium's work area and asks Plasma nothing", async () => {
+ const display = ELECTRON_DISPLAYS[1];
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen: fakeScreen([display]),
+ fetchSnapshot: async () => {
+ snapshots += 1;
+ return PLASMA_SNAPSHOT;
+ },
+ isActive: () => true,
+ });
+
+ await workAreas.start(() => undefined);
+
+ assert.equal(snapshots, 0);
+ assert.equal(workAreas.resolve(display), display);
+});
+
+test("outside KDE nothing is fetched and displays pass through untouched", async () => {
+ const screen = fakeScreen(ELECTRON_DISPLAYS);
+ let snapshots = 0;
+ const workAreas = createPlasmaWorkAreas({
+ screen,
+ fetchSnapshot: async () => {
+ snapshots += 1;
+ return PLASMA_SNAPSHOT;
+ },
+ isActive: () => false,
+ });
+
+ await workAreas.start(() => undefined);
+ await workAreas.refresh();
+
+ assert.equal(snapshots, 0);
+ assert.equal(screen.listenerCount("display-metrics-changed"), 0);
+ assert.equal(workAreas.resolve(ELECTRON_DISPLAYS[1]), ELECTRON_DISPLAYS[1]);
+});
+
+function fakeBus(answer) {
+ const connection = Object.assign(new EventEmitter(), {
+ ended: false,
+ end() {
+ this.ended = true;
+ },
+ });
+ return {
+ connection,
+ messages: [],
+ invoke(message, callback) {
+ this.messages.push(message);
+ answer?.(callback, connection);
+ },
+ };
+}
+
+function withDBus(bus, run) {
+ const originalLoad = Module._load;
+ Module._load = function loadWithFakeDBus(request, ...rest) {
+ if (request === "@homebridge/dbus-native") return { sessionBus: () => bus };
+ return originalLoad.call(this, request, ...rest);
+ };
+ try {
+ return run();
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+test("the snapshot is one evaluateScript call to plasmashell on the session bus", async () => {
+ const bus = fakeBus((callback) => callback(null, JSON.stringify(PLASMA_SNAPSHOT)));
+
+ assert.deepEqual(await withDBus(bus, fetchPlasmaSnapshot), PLASMA_SNAPSHOT);
+ const [{ body, ...message }] = bus.messages;
+ assert.deepEqual(message, {
+ destination: "org.kde.plasmashell",
+ path: "/PlasmaShell",
+ interface: "org.kde.PlasmaShell",
+ member: "evaluateScript",
+ signature: "s",
+ });
+ assert.match(body[0], /screenGeometry\(i\)[\s\S]*panels\(\)/);
+ assert.equal(bus.connection.ended, true);
+});
+
+test("a silent plasmashell or a broken bus fails the snapshot and closes the bus", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const silent = fakeBus();
+ const pending = withDBus(silent, fetchPlasmaSnapshot);
+ t.mock.timers.tick(400);
+ await assert.rejects(pending, /did not answer/);
+ assert.equal(silent.connection.ended, true);
+
+ const broken = fakeBus((_callback, connection) =>
+ connection.emit("error", new Error("connect ECONNREFUSED"))
+ );
+ await assert.rejects(withDBus(broken, fetchPlasmaSnapshot), /ECONNREFUSED/);
+ assert.equal(broken.connection.ended, true);
+});
diff --git a/test/helpers/windowManagerWorkAreaCorrection.test.js b/test/helpers/windowManagerWorkAreaCorrection.test.js
new file mode 100644
index 000000000..4a96b742a
--- /dev/null
+++ b/test/helpers/windowManagerWorkAreaCorrection.test.js
@@ -0,0 +1,215 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+// #1110's desk as Electron reports it under KDE: the 1080p (left) keeps
+// workArea == bounds and the primary 4K (right) lost 236 DIP to the other
+// monitor's panel. Plasma's answer gives each monitor its own 46 DIP panel.
+const DISPLAYS = [
+ {
+ id: 33,
+ bounds: { x: -1, y: 0, width: 1918, height: 1079 },
+ workArea: { x: -1, y: 0, width: 1918, height: 1079 },
+ },
+ {
+ id: 35,
+ bounds: { x: 1916, y: 0, width: 2256, height: 1269 },
+ workArea: { x: 1916, y: 0, width: 2256, height: 1033 },
+ },
+];
+const PLASMA_WORK_AREAS = {
+ 33: { x: -1, y: 0, width: 1918, height: 1033 },
+ 35: { x: 1916, y: 0, width: 2256, height: 1223 },
+};
+const PILL = { width: 211, height: 123 };
+
+let cursor = { x: 0, y: 0 };
+let plasmaAnswered = true;
+let refreshes = 0;
+let workAreasChanged = null;
+
+function distanceTo(rect, point) {
+ const dx = Math.max(rect.x - point.x, 0, point.x - (rect.x + rect.width));
+ const dy = Math.max(rect.y - point.y, 0, point.y - (rect.y + rect.height));
+ return Math.hypot(dx, dy);
+}
+
+function nearestDisplay(point) {
+ return DISPLAYS.reduce((best, display) =>
+ distanceTo(display.bounds, point) < distanceTo(best.bounds, point) ? display : best
+ );
+}
+
+const originalLoad = Module._load;
+Module._load = function loadWithStubs(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: { on: () => undefined },
+ screen: {
+ getCursorScreenPoint: () => cursor,
+ getDisplayNearestPoint: nearestDisplay,
+ getDisplayMatching: (rect) =>
+ nearestDisplay({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }),
+ getPrimaryDisplay: () => DISPLAYS[1],
+ on: () => undefined,
+ },
+ BrowserWindow: class {
+ constructor({ x, y, width, height }) {
+ this.bounds = { x, y, width, height };
+ this.webContents = { on: () => undefined, send: () => undefined };
+ }
+ isDestroyed() {
+ return false;
+ }
+ getBounds() {
+ return this.bounds;
+ }
+ setBounds(next) {
+ this.bounds = next;
+ }
+ },
+ Menu: {},
+ shell: {},
+ dialog: {},
+ };
+ }
+ if (request === "./plasmaWorkAreas") {
+ return {
+ plasmaWorkAreas: {
+ start: async (onChange) => {
+ workAreasChanged = onChange;
+ },
+ refresh: async () => {
+ refreshes += 1;
+ },
+ resolve: (display) =>
+ plasmaAnswered ? { ...display, workArea: PLASMA_WORK_AREAS[display.id] } : display,
+ },
+ };
+ }
+ if (request === "./debugLogger")
+ return { warn: () => undefined, debug: () => undefined, log: () => undefined };
+ if (request === "./hotkeyManager") {
+ const FakeHotkeyManager = class {
+ unregisterAll() {}
+ };
+ FakeHotkeyManager.isGlobeLikeHotkey = () => false;
+ return FakeHotkeyManager;
+ }
+ if (request === "./menuManager") return { setupMainMenu: () => undefined };
+ if (request === "./devServerManager") return {};
+ if (request === "./dockManager") return {};
+ if (request === "./i18nMain") return { i18nMain: { t: (key) => key } };
+ return originalLoad.call(this, request, parent, isMain);
+};
+const WindowManager = require("../../src/helpers/windowManager");
+const DragManager = require("../../src/helpers/dragManager");
+const { WindowPositionUtil } = require("../../src/helpers/windowConfig");
+Module._load = originalLoad;
+
+function makeManager(bounds) {
+ const manager = new WindowManager();
+ const window = {
+ bounds,
+ setBoundsCalls: 0,
+ isDestroyed: () => false,
+ getBounds() {
+ return this.bounds;
+ },
+ setBounds(next) {
+ this.bounds = next;
+ this.setBoundsCalls += 1;
+ },
+ webContents: { send: () => undefined },
+ };
+ manager.mainWindow = window;
+ manager._notifyMainWindowHorizontalDirection = () => undefined;
+ return { manager, window };
+}
+
+// Bottom-right anchor: 4 DIP inside the work area's right and bottom edges.
+function anchoredOn(workArea) {
+ return {
+ x: workArea.x + workArea.width - PILL.width - 4,
+ y: workArea.y + workArea.height - PILL.height - 4,
+ ...PILL,
+ };
+}
+
+test("showing the pill on another monitor anchors it above that monitor's panel", async () => {
+ plasmaAnswered = true;
+ refreshes = 0;
+ const { manager, window } = makeManager(anchoredOn(DISPLAYS[0].workArea));
+ cursor = { x: 3000, y: 600 };
+
+ await manager._repositionToActiveDisplay();
+
+ assert.deepEqual(window.bounds, anchoredOn(PLASMA_WORK_AREAS[35]));
+ assert.equal(refreshes, 1, "each show asks Plasma again");
+});
+
+test("creating the pill starts watching Plasma, and a change re-anchors it", async () => {
+ plasmaAnswered = false;
+ cursor = { x: 3000, y: 600 };
+ const manager = new WindowManager();
+ for (const step of [
+ "setMainWindowInteractivity",
+ "registerMainWindowEvents",
+ "registerAssistantSelectionContextMenu",
+ "registerExternalLinkHandlers",
+ "loadMainWindow",
+ "initializeHotkey",
+ ]) {
+ manager[step] = async () => undefined;
+ }
+ manager._notifyMainWindowHorizontalDirection = () => undefined;
+ const bottomOf = (bounds) => bounds.y + bounds.height;
+
+ await manager.createMainWindow();
+ assert.equal(bottomOf(manager.mainWindow.bounds), DISPLAYS[1].workArea.height - 4);
+
+ plasmaAnswered = true;
+ await workAreasChanged();
+ assert.equal(bottomOf(manager.mainWindow.bounds), PLASMA_WORK_AREAS[35].height - 4);
+});
+
+test("work areas that arrive after placement re-anchor an auto-placed pill", async () => {
+ plasmaAnswered = false;
+ const placed = WindowPositionUtil.getMainWindowPosition(DISPLAYS[1], PILL, "bottom-right");
+ const { manager, window } = makeManager(placed);
+
+ plasmaAnswered = true;
+ await manager._reanchorMainWindow();
+
+ assert.deepEqual(window.bounds, anchoredOn(PLASMA_WORK_AREAS[35]));
+ await manager._reanchorMainWindow();
+ assert.equal(window.setBoundsCalls, 1, "a pill already at its anchor isn't moved again");
+});
+
+test("a pill the user dragged keeps its spot when work areas change", async () => {
+ plasmaAnswered = true;
+ const dragged = { x: 2400, y: 500, ...PILL };
+ const { manager, window } = makeManager(dragged);
+ manager._mainWindowPlacementCoordinator.markManuallyPositioned();
+
+ await manager._reanchorMainWindow();
+
+ assert.deepEqual(window.bounds, dragged);
+ assert.equal(window.setBoundsCalls, 0);
+});
+
+test("dragging stops at the monitor's own panel, not at the root work area", () => {
+ plasmaAnswered = true;
+ const drag = new DragManager();
+ const positions = [];
+ drag.activeWindow = {
+ getBounds: () => anchoredOn(PLASMA_WORK_AREAS[35]),
+ setPosition: (x, y) => positions.push({ x, y }),
+ };
+ drag.dragOffset = { x: 100, y: 60 };
+ cursor = { x: 4050, y: 1260 };
+
+ drag.updateWindowPosition();
+
+ assert.deepEqual(positions, [{ x: 3950, y: 1223 - PILL.height }]);
+});