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): paste into COSMIC terminals with Ctrl+Shift+V (#2519)

voidce42fea5c538
diff --git a/CLAUDE.md b/CLAUDE.md
index 6afa270e2..6c3050367 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -63,6 +63,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- macOS: AppleScript-based paste with accessibility permission check
- Windows: PowerShell SendKeys with nircmd.exe fallback
- Linux: compositor-aware Wayland paste (Hyprland sendshortcut, wlroots wtype, GNOME/KDE portal keysyms) with native uinput/XTest and system-tool fallbacks
+ - Linux COSMIC: paste reads the focused app from cosmic-comp's `zcosmic_toplevel_info_v1` (`cosmicToplevel.js`, a minimal Wayland wire client, bound at version 1, which still sends app_id and state), never from xdotool, whose XWayland answer goes stale while a native Wayland window has focus. A known terminal is pasted through wtype (Ctrl+Shift+V; Shift+Insert for Konsole); everything else keeps uinput Shift+Insert, since COSMIC gives no PID to spot Electron apps hosting TUIs. Short terminal names (`st`) match whole words only, or every `com.system76.*` app id would read as a terminal
- Linux: before any paste or selection-copy chord, `linux-fast-paste --capabilities --await-modifier-release <ms>` waits for physically held modifiers to be released (XKB state on X11, `EVIOCGKEY` on Wayland; `unknown` without `/dev/input` access pastes as before). A chord injected into held keys arrives as a different shortcut, and a virtual device cannot release another device's key (#2113). Still held after 1.5 s → not pasted, `reason: "modifiers-held"`, and the renderer shows the dictation-error pill with the transcript on the clipboard; a selection edit blocked the same way reports `code: "modifiers_held"` and gets the same pill (the assistant caret paste reports the same code, for logs only). `ydotoold`'s virtual keyboard is ignored, since an interrupted chord can leave its modifier down, and an unreadable key state is logged once per session. The wait runs before `pasteLinux` detects the target window, and a selection copy that had to wait looks the target up again, since focus can move while a key is held: a fresh capture then runs the command on its own (`focus_moved`), and a revalidated session declines as `target_changed`. Retry on a modifiers-held pill pastes the kept transcript again rather than recording again (the macOS/Windows push force-stop pill keeps its record-again Retry, since neither platform waits for held keys), ignores clicks while its paste is pending, and never dismisses a newer pill. `useAudioRecording` keeps the pill in processing until the paste attempt settles (the audio manager settles before the paste starts), but never reports that to main, which drops dictation hotkeys while processing; a paste held back after the next dictation started leaves the transcript on the clipboard without a pill. The helper measures its wait on `CLOCK_MONOTONIC`, since the JS watchdog kills it at timeout + 1 s
- **database.js**: SQLite operations for transcription history
- **debugLogger.js**: Debug logging system with file output
@@ -877,6 +878,7 @@ UI icons come from `src/components/icons/` (vendored Nucleo core outline compone
- X11: xdotool fallback if native binary unavailable
- Hyprland Wayland: wtype → sendshortcut → uinput/ydotool
- Sway/wlroots Wayland: wtype → uinput/ydotool
+ - COSMIC Wayland: wtype for a detected terminal → uinput/ydotool
- GNOME/KDE Wayland: portal keysyms → uinput/ydotool
- Physical Wayland fallbacks use Shift+Insert to avoid layout-sensitive KEY_V
- Windows: PowerShell SendKeys (built-in) or nircmd.exe (bundled)
@@ -960,6 +962,7 @@ UI icons come from `src/components/icons/` (vendored Nucleo core outline compone
- **X11**: `xdotool` (recommended)
- **Hyprland Wayland**: `wtype`, then `hyprctl` sendshortcut (avoids the sendshortcut stuck-modifier bug when wtype is installed)
- **Sway/wlroots Wayland**: `wtype` (requires the virtual keyboard protocol)
+ - **COSMIC Wayland**: `wtype` for terminals (Warp has no Shift+Insert paste); other windows paste with uinput Shift+Insert. Settings and onboarding ask for `wtype` there once something else pastes (`needsWtype` in `src/utils/linuxPasteTools.ts`), but `checkPasteTools` never reports it as the method
- **GNOME/KDE Wayland**: RemoteDesktop portal keysyms, then uinput/ydotool
- **Wayland physical fallback**: Shift+Insert avoids layout-sensitive KEY_V; `ydotool` requires the `ydotoold` daemon
- Terminal detection: Auto-detects terminal emulators and uses Ctrl+Shift+V
diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.c
index e8d6180ad..1d8a9f840 100644
--- a/resources/linux-fast-paste.c
+++ b/resources/linux-fast-paste.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -367,13 +368,25 @@ static const char *terminal_classes[] = {
"terminator", "xterm", "urxvt", "rxvt", "tilix", "terminology",
"wezterm", "foot", "st", "yakuake", "ghostty", "guake", "tilda",
"hyper", "tabby", "sakura", "warp", "termius", "waveterm",
- "ptyxis", "kgx", "org.gnome.console", NULL
+ "ptyxis", "kgx", "org.gnome.console", "cosmicterm", "xst", "stterm", NULL
};
+/* A short name like "st" would match inside unrelated names
+ * ("com.system76.CosmicEdit"), so it must be a whole word. */
+static int contains_terminal_name(const char *wm_class, const char *name) {
+ size_t len = strlen(name);
+ if (len > 2) return strcasestr(wm_class, name) != NULL;
+ for (const char *p = wm_class; (p = strcasestr(p, name)); p++) {
+ if ((p == wm_class || !isalnum((unsigned char)p[-1])) && !isalnum((unsigned char)p[len]))
+ return 1;
+ }
+ return 0;
+}
+
static int is_terminal(const char *wm_class) {
if (!wm_class) return 0;
for (int i = 0; terminal_classes[i]; i++) {
- if (strcasestr(wm_class, terminal_classes[i]))
+ if (contains_terminal_name(wm_class, terminal_classes[i]))
return 1;
}
return 0;
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 6f431cf2a..90d1d819d 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -1407,6 +1407,7 @@ export default function SettingsPage({
hasGroup: boolean;
isKde: boolean;
isWlroots: boolean;
+ isCosmic: boolean;
hasXclip: boolean;
hasXsel: boolean;
isNixOS: boolean;
@@ -3494,7 +3495,7 @@ export default function SettingsPage({
key: "hasWtype",
label: "wtype",
ok: ydotoolStatus.hasWtype,
- required: ydotoolStatus.isWlroots,
+ required: ydotoolStatus.isWlroots || ydotoolStatus.isCosmic,
desc: t("settingsPage.general.waylandPaste.wtypeDesc"),
steps: [
{
diff --git a/src/components/ui/PasteToolsInfo.tsx b/src/components/ui/PasteToolsInfo.tsx
index 3bcea064a..568e9c39d 100644
--- a/src/components/ui/PasteToolsInfo.tsx
+++ b/src/components/ui/PasteToolsInfo.tsx
@@ -6,6 +6,7 @@ import type { PasteToolsResult } from "../../types/electron";
import {
getLinuxPasteInstallCommands,
needsLinuxPasteToolGuidance,
+ needsWtype,
} from "../../utils/linuxPasteTools";
interface PasteToolsInfoProps {
@@ -99,8 +100,9 @@ export default function PasteToolsInfo({
if (needsLinuxPasteToolGuidance(pasteToolsInfo)) {
const isWayland = pasteToolsInfo.isWayland;
- const needsWtype = pasteToolsInfo.isWlroots && !pasteToolsInfo.hasWtype;
- const recommendedTool = needsWtype
+ const wtypeMissing = needsWtype(pasteToolsInfo);
+ const cosmicTerminalsOnly = wtypeMissing && !!pasteToolsInfo.isCosmic;
+ const recommendedTool = wtypeMissing
? "wtype"
: pasteToolsInfo.recommendedInstall === "wtype"
? "wtype"
@@ -123,7 +125,9 @@ export default function PasteToolsInfo({
{showInstall ? (
<>
<p className="text-sm text-warning dark:text-warning mt-1">
- {needsWtype ? (
+ {cosmicTerminalsOnly ? (
+ t("pasteToolsInfo.wtypeCosmicTerminalsDescription")
+ ) : wtypeMissing ? (
t("pasteToolsInfo.wtypeFallbackDescription")
) : (
<>
@@ -169,7 +173,7 @@ export default function PasteToolsInfo({
</p>
)}
- {showInstall && (
+ {showInstall && !cosmicTerminalsOnly && (
<p className="text-sm text-warning dark:text-warning mt-3">
{t("pasteToolsInfo.withoutToolPrefix")}{" "}
<kbd dir="ltr" className="bg-warning/20 px-1 rounded text-xs">
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 71d576abc..b7ad6bb69 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -6,6 +6,7 @@ const fs = require("fs");
const os = require("os");
const debugLogger = require("./debugLogger");
const { getLinuxSessionInfo } = require("./linuxSession");
+const { getCosmicActiveAppId } = require("./cosmicToplevel");
const CACHE_TTL_MS = 30000;
@@ -66,6 +67,9 @@ const LINUX_TERMINAL_CLASSES = [
"ptyxis",
"kgx",
"org.gnome.console",
+ "cosmicterm",
+ "xst",
+ "stterm",
];
// macOS reports localized app names rather than window classes, and iTerm2 has
@@ -245,11 +249,15 @@ class ClipboardManager {
return null;
}
- // Accepts a Linux window class or a macOS app name.
+ // Accepts a Linux window class or a macOS app name. A short name like "st" would
+ // match inside unrelated names ("com.system76.CosmicEdit"), so it must be a whole word.
isTerminalSignature(signature) {
if (!signature) return false;
const normalized = String(signature).toLowerCase();
- return TERMINAL_SIGNATURES.some((term) => normalized.includes(term));
+ const words = normalized.split(/[^a-z0-9]+/);
+ return TERMINAL_SIGNATURES.some((term) =>
+ term.length > 2 ? normalized.includes(term) : words.includes(term)
+ );
}
isLinuxTerminalWindowClass(windowClass) {
@@ -1468,7 +1476,7 @@ class ClipboardManager {
}
async pasteLinux(originalClipboard, options = {}) {
- const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots, isHyprland } =
+ const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots, isHyprland, isCosmic } =
getLinuxSessionInfo();
const webContents = options.webContents;
const originalPrimary = options.originalPrimary ?? null;
@@ -1534,8 +1542,11 @@ class ClipboardManager {
// Pre-detect the target window BEFORE our window takes focus or blurs,
// so the fast-paste binary and fallback tools know where to send keystrokes.
+ // COSMIC's XWayland keeps naming the last X11 window while a native Wayland
+ // window has focus, so xdotool would name the wrong target there.
+ const xdotoolSeesTarget = xdotoolExists && !(isWayland && (!xwaylandAvailable || isCosmic));
const preDetectTargetWindow = () => {
- if (!xdotoolExists || (isWayland && !xwaylandAvailable)) return null;
+ if (!xdotoolSeesTarget) return null;
try {
const result = spawnSync("xdotool", ["getactivewindow"]);
return result.status === 0 ? result.stdout.toString().trim() || null : null;
@@ -1545,7 +1556,7 @@ class ClipboardManager {
};
const preDetectWindowClass = (windowId) => {
- if (!xdotoolExists || (isWayland && !xwaylandAvailable)) return null;
+ if (!xdotoolSeesTarget) return null;
try {
const args = windowId
? ["getwindowclassname", windowId]
@@ -1561,7 +1572,7 @@ class ClipboardManager {
// xdotool, leaving WM_CLASS detection blind. Fall back to the owning process
// name from /proc/<pid>/comm so terminal-aware paste keys still get chosen.
const preDetectWindowPid = (windowId) => {
- if (!xdotoolExists || (isWayland && !xwaylandAvailable)) return null;
+ if (!xdotoolSeesTarget) return null;
try {
const args = windowId ? ["getwindowpid", windowId] : ["getactivewindow", "getwindowpid"];
const result = spawnSync("xdotool", args, { timeout: 1000 });
@@ -1626,6 +1637,13 @@ class ClipboardManager {
}
}
+ if (!detectedWindowClass && isCosmic) {
+ detectedWindowClass = await getCosmicActiveAppId();
+ if (detectedWindowClass) {
+ debugLogger.debug("COSMIC window class detected", { detectedWindowClass }, "clipboard");
+ }
+ }
+
const detectedWindowPid = preDetectWindowPid(targetWindowId);
const detectedWindowComm = preDetectWindowComm(detectedWindowPid);
const detectedIsElectron = preDetectIsElectron(detectedWindowPid);
@@ -1638,6 +1656,9 @@ class ClipboardManager {
const windowSignals = [detectedWindowClass, detectedWindowComm].filter(Boolean);
const signalsMatch = (needle) => windowSignals.some((signal) => signal.includes(needle));
const detectedIsKonsole = signalsMatch("konsole");
+ const isTerminalTarget = windowSignals.some((signal) =>
+ this.isLinuxTerminalWindowClass(signal)
+ );
// Shift+Insert is the universal Linux paste shortcut — works in terminals and
// GUI apps, and (unlike Ctrl+V) is not intercepted by TUI agents like Codex,
@@ -1645,10 +1666,12 @@ class ClipboardManager {
// can't be classified, or for Konsole which silently drops simulated Ctrl+Shift+V.
// Electron apps (VS Code, Cursor) host TUI terminals too, so route them to
// Shift+Insert on any desktop environment, even when their class is detected.
+ // COSMIC names the focused app but not its process, so Electron apps look like any
+ // other window there: only a known terminal leaves Shift+Insert.
const useShiftInsert =
- detectedIsKonsole || detectedIsElectron || (isWayland && windowSignals.length === 0);
- const isTerminalTarget =
- windowSignals.length > 0 && LINUX_TERMINAL_CLASSES.some((term) => signalsMatch(term));
+ detectedIsKonsole ||
+ detectedIsElectron ||
+ (isWayland && (windowSignals.length === 0 || (isCosmic && !isTerminalTarget)));
const hyprlandShortcut = useShiftInsert
? { modifiers: "SHIFT", key: "Insert" }
: isTerminalTarget
@@ -1687,7 +1710,9 @@ class ClipboardManager {
else if (isTerminalTarget) args.push("--terminal");
};
- if (isWayland && isWlroots && wtypeExists) {
+ // cosmic-comp has the virtual keyboard too, and wtype is the only way to give a
+ // terminal there its Ctrl+Shift+V: the uinput fallback below is always Shift+Insert.
+ if (isWayland && wtypeExists && (isWlroots || (isCosmic && isTerminalTarget))) {
try {
await this._runLinuxPasteCommand("wtype", wtypeArgs, "wtype");
this.safeLog("✅ Paste successful using wtype");
@@ -2348,7 +2373,7 @@ Would you like to open System Settings now?`;
};
}
- const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots, isHyprland } =
+ const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots, isHyprland, isCosmic } =
getLinuxSessionInfo();
const linuxFastPaste = this.resolveLinuxFastPasteBinary();
const hasNativeBinary = !!linuxFastPaste;
@@ -2369,7 +2394,9 @@ Would you like to open System Settings now?`;
const tools = [];
const hasHyprlandShortcut = isWayland && isHyprland && this.commandExists("hyprctl");
- const hasWtype = isWayland && isWlroots && this.commandExists("wtype");
+ // On COSMIC wtype only pastes into terminals, so it is reported for the setup
+ // guidance but never listed as a paste tool or method there.
+ const hasWtype = isWayland && (isWlroots || isCosmic) && this.commandExists("wtype");
const canUseYdotool = this.commandExists("ydotool") && this._isYdotoolDaemonRunning();
const canUseXdotool = !isWayland || xwaylandAvailable;
@@ -2404,7 +2431,7 @@ Would you like to open System Settings now?`;
let method = null;
if (!isWayland) {
method = nativeBinaryUsable ? "xtest" : tools[0] || null;
- } else if (hasWtype) {
+ } else if (hasWtype && isWlroots) {
method = "wtype";
} else if (hasHyprlandShortcut) {
method = "hyprland-sendshortcut";
@@ -2427,6 +2454,7 @@ Would you like to open System Settings now?`;
hasUinput,
hasWtype,
isWlroots,
+ isCosmic,
tools,
recommendedInstall,
};
diff --git a/src/helpers/cosmicToplevel.js b/src/helpers/cosmicToplevel.js
new file mode 100644
index 000000000..a41be81da
--- /dev/null
+++ b/src/helpers/cosmicToplevel.js
@@ -0,0 +1,142 @@
+const net = require("net");
+const path = require("path");
+
+// The app id of the focused window on cosmic-comp, lowercased, or null. COSMIC has no
+// command or D-Bus call for it and xdotool only sees X11 windows, so this speaks the
+// Wayland wire protocol to zcosmic_toplevel_info_v1. Version 1 of that global sends
+// every toplevel's app_id and state as soon as it is bound (version 2 moved app_id to
+// ext_foreign_toplevel_list_v1), so two roundtrips answer the question.
+
+const TOPLEVEL_INFO = "zcosmic_toplevel_info_v1";
+const STATE_ACTIVATED = 2;
+const TIMEOUT_MS = 300;
+
+// Client object ids, allocated in the order the requests create them.
+const DISPLAY = 1;
+const REGISTRY = 2;
+const GLOBALS_LISTED = 3;
+const TOPLEVEL_INFO_ID = 4;
+const TOPLEVELS_LISTED = 5;
+
+// Wayland messages use host byte order, little-endian on every platform OpenWhispr ships.
+function message(objectId, opcode, ...args) {
+ const body = Buffer.concat(args);
+ const header = Buffer.alloc(8);
+ header.writeUInt32LE(objectId, 0);
+ header.writeUInt32LE((8 + body.length) * 0x10000 + opcode, 4);
+ return Buffer.concat([header, body]);
+}
+
+function uint(value) {
+ const buffer = Buffer.alloc(4);
+ buffer.writeUInt32LE(value);
+ return buffer;
+}
+
+function string(value) {
+ const bytes = Buffer.from(`${value}\0`);
+ return Buffer.concat([uint(bytes.length), bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]);
+}
+
+// A string or array argument: its byte length, then the bytes.
+function readBytes(body, offset) {
+ return body.subarray(offset + 4, offset + 4 + body.readUInt32LE(offset));
+}
+
+function readString(body, offset) {
+ const bytes = readBytes(body, offset);
+ return bytes.toString("utf8", 0, Math.max(bytes.length - 1, 0));
+}
+
+function getCosmicActiveAppId(env = process.env) {
+ const display = env.WAYLAND_DISPLAY || "wayland-0";
+ const socketPath = path.isAbsolute(display)
+ ? display
+ : path.join(env.XDG_RUNTIME_DIR || "", display);
+
+ return new Promise((resolve) => {
+ const socket = net.connect(socketPath);
+ const toplevels = new Map();
+ let toplevelInfoName = null;
+ let pending = Buffer.alloc(0);
+
+ const finish = (appId) => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(appId);
+ };
+ const timer = setTimeout(() => finish(null), TIMEOUT_MS);
+
+ const handleEvent = (objectId, opcode, body) => {
+ if (objectId === REGISTRY && opcode === 0) {
+ // wl_registry.global: name, interface, version
+ if (readString(body, 4) === TOPLEVEL_INFO) toplevelInfoName = body.readUInt32LE(0);
+ } else if (objectId === GLOBALS_LISTED && toplevelInfoName === null) {
+ finish(null);
+ } else if (objectId === GLOBALS_LISTED) {
+ socket.write(
+ Buffer.concat([
+ // wl_registry.bind, then wl_display.sync
+ message(
+ REGISTRY,
+ 0,
+ uint(toplevelInfoName),
+ string(TOPLEVEL_INFO),
+ uint(1),
+ uint(TOPLEVEL_INFO_ID)
+ ),
+ message(DISPLAY, 0, uint(TOPLEVELS_LISTED)),
+ ])
+ );
+ } else if (objectId === TOPLEVEL_INFO_ID && opcode === 0) {
+ // zcosmic_toplevel_info_v1.toplevel: the new handle's id
+ toplevels.set(body.readUInt32LE(0), { appId: null, activated: false });
+ } else if (toplevels.has(objectId) && opcode === 3) {
+ // zcosmic_toplevel_handle_v1.app_id
+ toplevels.get(objectId).appId = readString(body, 0);
+ } else if (toplevels.has(objectId) && opcode === 8) {
+ // zcosmic_toplevel_handle_v1.state: an array of uint32 states
+ const states = readBytes(body, 0);
+ for (let offset = 0; offset + 4 <= states.length; offset += 4) {
+ if (states.readUInt32LE(offset) === STATE_ACTIVATED) {
+ toplevels.get(objectId).activated = true;
+ }
+ }
+ } else if (objectId === TOPLEVELS_LISTED) {
+ const active = [...toplevels.values()].find((toplevel) => toplevel.activated);
+ finish(active?.appId?.toLowerCase() || null);
+ }
+ };
+
+ socket.on("connect", () => {
+ // wl_display.get_registry, then wl_display.sync
+ socket.write(
+ Buffer.concat([
+ message(DISPLAY, 1, uint(REGISTRY)),
+ message(DISPLAY, 0, uint(GLOBALS_LISTED)),
+ ])
+ );
+ });
+ socket.on("data", (chunk) => {
+ pending = Buffer.concat([pending, chunk]);
+ try {
+ while (pending.length >= 8) {
+ const size = pending.readUInt32LE(4) >>> 16;
+ if (size < 8 || pending.length < size) break;
+ handleEvent(
+ pending.readUInt32LE(0),
+ pending.readUInt32LE(4) & 0xffff,
+ pending.subarray(8, size)
+ );
+ pending = pending.subarray(size);
+ }
+ } catch {
+ finish(null);
+ }
+ });
+ socket.on("error", () => finish(null));
+ socket.on("close", () => finish(null));
+ });
+}
+
+module.exports = { getCosmicActiveAppId };
diff --git a/src/helpers/ensureYdotool.js b/src/helpers/ensureYdotool.js
index 447398b89..aaacd3c51 100644
--- a/src/helpers/ensureYdotool.js
+++ b/src/helpers/ensureYdotool.js
@@ -193,13 +193,14 @@ function getYdotoolStatus() {
const hasUinput = isUinputAccessible();
const hasUdevRule = udevRuleExists();
const hasGroup = userInInputGroup();
- const { isWayland, isKde, isWlroots } = getLinuxSessionInfo();
+ const { isWayland, isKde, isWlroots, isCosmic } = getLinuxSessionInfo();
return {
isLinux: process.platform === "linux",
isWayland,
isKde,
isWlroots,
+ isCosmic,
hasYdotool,
hasYdotoold,
hasWtype,
diff --git a/src/helpers/linuxSession.js b/src/helpers/linuxSession.js
index bbb645b8b..073de5517 100644
--- a/src/helpers/linuxSession.js
+++ b/src/helpers/linuxSession.js
@@ -15,6 +15,7 @@ function getLinuxSessionInfo(environment = process.env) {
const isGnome = isWayland && desktopEnv.includes("gnome");
const isKde = isWayland && desktopEnv.includes("kde");
const isHyprland = isWayland && !!environment.HYPRLAND_INSTANCE_SIGNATURE;
+ const isCosmic = isWayland && desktopEnv.includes("cosmic");
// SWAYSOCK can survive a compositor switch, so trust it only when no desktop
// metadata identifies the current session.
const isSway =
@@ -38,6 +39,7 @@ function getLinuxSessionInfo(environment = process.env) {
isWlroots,
isHyprland,
isSway,
+ isCosmic,
};
}
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index e2b366fac..98fe144c7 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -567,9 +567,7 @@ class SelectionManager {
if (target.kind === "atspi-pid" && (await this._isTerminalPid(target.id))) return capture;
// macOS targets normally carry the copier's NSWorkspace app name, already
// matched above; only an unnamed target needs its executable resolved so a
- // terminal cannot become a caret destination. Never resolve a
- // named one — `ps` reports bundle paths like "Visual Studio Code" whose
- // "st" substring would misread editors as terminals.
+ // terminal cannot become a caret destination.
if (
target.kind === "mac-pid" &&
!this._targetSignature(target) &&
@@ -608,8 +606,8 @@ class SelectionManager {
async _readTargetNames(pid) {
const executablePath = await this._readExecutablePath(pid);
if (!executablePath) return "";
- // Match the bundle and executable names, not the whole path — segments
- // like "/System/" would collide with short signatures such as "st".
+ // Match the bundle and executable names, not the whole path, so a directory
+ // name can't read as a terminal signature.
const bundleName = executablePath.match(/\/([^/]+)\.app\//)?.[1] ?? "";
const executableName = executablePath.split("/").pop() ?? "";
return `${bundleName} ${executableName}`.trim();
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index 51eebeeb4..2881aee62 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -3631,7 +3631,7 @@
"recheck": "إعادة الفحص",
"copy": "نسخ",
"ydotoolDesc": "أداة أتمتة الإدخال لـ Wayland",
- "wtypeDesc": "أداة أتمتة الإدخال المفضلة على مُركِّبات wlroots",
+ "wtypeDesc": "أداة أتمتة الإدخال المفضلة على مُركِّبات wlroots؛ وفي COSMIC تُستخدم للّصق في الطرفيات",
"ydotooldDesc": "خدمة ydotool الخلفية (حزمة منفصلة على Ubuntu/Pop!_OS)",
"uinputDesc": "الوصول إلى جهاز إدخال النواة",
"uinputRuleFound": "القاعدة موجودة ولكنها غير نشطة. من المفترض أن تصلحها إعادة التشغيل.",
@@ -4447,6 +4447,7 @@
"waylandClipboardTitle": "وضع الحافظة في Wayland",
"windowsReady": "نظام Windows يدعم اللصق التلقائي بشكل افتراضي. لا يتطلب أي إعداد!",
"withoutToolPrefix": "بدون هذه الأداة، سيقوم OpenWhispr بنسخ النص إلى الحافظة الخاصة بك. يمكنك بعد ذلك اللصق يدويًا باستخدام Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "على COSMIC، لا تستقبل الطرفيات مثل Warp النص الملصق إلا عبر wtype. أما التطبيقات الأخرى فيعمل فيها اللصق بدونه.",
"wtypeFallbackDescription": "يُعد wtype الطريقة المفضلة للصق التلقائي في مركب wlroots هذا. يتوفر بديل آخر، ولكنه قد يكون أقل موثوقية.",
"xwaylandAppsOnly": "اللصق التلقائي يعمل مع تطبيقات XWayland فقط"
},
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index fbe174ba7..3d1334b62 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1510,6 +1510,7 @@
"waylandClipboardTitle": "Zwischenablage-Modus unter Wayland",
"windowsReady": "Windows unterstützt automatisches Einfügen direkt. Keine Einrichtung erforderlich!",
"withoutToolPrefix": "Ohne dieses Tool kopiert OpenWhispr den Text in Ihre Zwischenablage. Sie können ihn dann manuell mit Ctrl+V einfügen.",
+ "wtypeCosmicTerminalsDescription": "Unter COSMIC empfangen Terminals wie Warp eingefügten Text nur über wtype. In andere Apps wird bereits ohne wtype eingefügt.",
"wtypeFallbackDescription": "wtype ist die bevorzugte Methode für automatisches Einfügen auf diesem wlroots-Compositor. Eine Alternative ist verfügbar, kann aber weniger zuverlässig sein.",
"xwaylandAppsOnly": "Automatisches Einfügen funktioniert nur für XWayland-Apps"
},
@@ -2296,7 +2297,7 @@
"recheck": "Erneut prüfen",
"copy": "Kopieren",
"ydotoolDesc": "Eingabeautomatisierung für Wayland",
- "wtypeDesc": "Bevorzugte Eingabeautomatisierung für wlroots-Compositoren",
+ "wtypeDesc": "Bevorzugte Eingabeautomatisierung für wlroots-Compositoren; unter COSMIC zum Einfügen in Terminals genutzt",
"ydotooldDesc": "Daemon für ydotool (separates Paket unter Ubuntu/Pop!_OS)",
"uinputDesc": "Zugriff auf das Kernel-Eingabegerät",
"uinputRuleFound": "Regel vorhanden, aber nicht aktiv. Ein Neustart sollte das beheben.",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 0956d90d0..eba84257c 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1510,6 +1510,7 @@
"waylandClipboardTitle": "Clipboard Mode on Wayland",
"windowsReady": "Windows supports automatic pasting out of the box. No setup required!",
"withoutToolPrefix": "Without this tool, OpenWhispr will copy text to your clipboard. You can then paste manually with Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "On COSMIC, terminals such as Warp only receive pasted text through wtype. Other apps already paste without it.",
"wtypeFallbackDescription": "wtype is the preferred auto-paste method for this wlroots compositor. A fallback is available, but may be less reliable.",
"xwaylandAppsOnly": "automatic pasting works for XWayland apps only"
},
@@ -2296,7 +2297,7 @@
"recheck": "Re-check",
"copy": "Copy",
"ydotoolDesc": "Input automation tool for Wayland",
- "wtypeDesc": "Preferred input automation tool on wlroots compositors",
+ "wtypeDesc": "Preferred input automation tool on wlroots compositors; on COSMIC, used to paste into terminals",
"ydotooldDesc": "Daemon for ydotool (separate package on Ubuntu/Pop!_OS)",
"uinputDesc": "Kernel input device access",
"uinputRuleFound": "Rule present but not active. A reboot should fix it.",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index bd12226ee..d39f8c21a 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1468,6 +1468,7 @@
"waylandClipboardTitle": "Modo portapapeles en Wayland",
"windowsReady": "Windows es compatible con el pegado automático de forma nativa. ¡No se requiere configuración!",
"withoutToolPrefix": "Sin esta herramienta, OpenWhispr copiará el texto al portapapeles. Luego puedes pegarlo manualmente con Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "En COSMIC, las terminales como Warp solo reciben el texto pegado mediante wtype. En las demás aplicaciones ya se pega sin él.",
"wtypeFallbackDescription": "wtype es el método de pegado automático preferido para este compositor wlroots. Hay una alternativa disponible, pero puede ser menos fiable.",
"xwaylandAppsOnly": "el pegado automático funciona solo en apps XWayland"
},
@@ -2054,7 +2055,7 @@
"recheck": "Volver a comprobar",
"copy": "Copiar",
"ydotoolDesc": "Herramienta de automatización de entrada para Wayland",
- "wtypeDesc": "Herramienta de automatización de entrada preferida en compositores wlroots",
+ "wtypeDesc": "Herramienta de automatización de entrada preferida en compositores wlroots; en COSMIC, se usa para pegar en terminales",
"ydotooldDesc": "Daemon de ydotool (paquete separado en Ubuntu/Pop!_OS)",
"uinputDesc": "Acceso al dispositivo de entrada del kernel",
"uinputRuleFound": "Regla presente pero no activa. Un reinicio debería solucionarlo.",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 548468a17..e8fd6a8f7 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1510,6 +1510,7 @@
"waylandClipboardTitle": "Mode presse-papiers sur Wayland",
"windowsReady": "Windows prend en charge le collage automatique nativement. Aucune configuration requise !",
"withoutToolPrefix": "Sans cet outil, OpenWhispr copiera le texte dans le presse-papiers. Vous pourrez ensuite coller manuellement avec Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "Sous COSMIC, les terminaux comme Warp ne reçoivent le texte collé que via wtype. Les autres applications collent déjà sans lui.",
"wtypeFallbackDescription": "wtype est la méthode de collage automatique recommandée pour ce compositeur wlroots. Une solution de repli est disponible, mais elle peut être moins fiable.",
"xwaylandAppsOnly": "le collage automatique fonctionne uniquement pour les apps XWayland"
},
@@ -2296,7 +2297,7 @@
"recheck": "Revérifier",
"copy": "Copier",
"ydotoolDesc": "Outil d'automatisation de saisie pour Wayland",
- "wtypeDesc": "Outil d'automatisation de saisie recommandé sur les compositeurs wlroots",
+ "wtypeDesc": "Outil d'automatisation de saisie recommandé sur les compositeurs wlroots ; sous COSMIC, sert à coller dans les terminaux",
"ydotooldDesc": "Daemon pour ydotool (paquet séparé sur Ubuntu/Pop!_OS)",
"uinputDesc": "Accès au périphérique d'entrée du noyau",
"uinputRuleFound": "Règle présente mais inactive. Un redémarrage devrait résoudre le problème.",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 3bc108a7e..185ca2e41 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1415,6 +1415,7 @@
"waylandClipboardTitle": "Modalità appunti su Wayland",
"windowsReady": "Windows supporta l'incollaggio automatico senza configurazione aggiuntiva!",
"withoutToolPrefix": "Senza questo strumento, OpenWhispr copierà il testo negli appunti. Potrai poi incollare manualmente con Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "Su COSMIC, i terminali come Warp ricevono il testo incollato solo tramite wtype. Nelle altre app l'incollaggio funziona già senza.",
"wtypeFallbackDescription": "wtype è il metodo di incollaggio automatico preferito per questo compositor wlroots. È disponibile un'alternativa, ma potrebbe essere meno affidabile.",
"xwaylandAppsOnly": "l'incollaggio automatico funziona solo per le app XWayland"
},
@@ -2001,7 +2002,7 @@
"recheck": "Ricontrolla",
"copy": "Copia",
"ydotoolDesc": "Strumento di automazione input per Wayland",
- "wtypeDesc": "Strumento di automazione input preferito sui compositor wlroots",
+ "wtypeDesc": "Strumento di automazione input preferito sui compositor wlroots; su COSMIC, usato per incollare nei terminali",
"ydotooldDesc": "Daemon per ydotool (pacchetto separato su Ubuntu/Pop!_OS)",
"uinputDesc": "Accesso al dispositivo di input del kernel",
"uinputRuleFound": "Regola presente ma non attiva. Un riavvio dovrebbe risolvere.",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 1ac96940c..9eeae436f 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1415,6 +1415,7 @@
"waylandClipboardTitle": "Wayland でのクリップボードモード",
"windowsReady": "Windows は自動貼り付けに標準対応しています。設定は不要です!",
"withoutToolPrefix": "このツールがない場合、OpenWhispr はテキストをクリップボードにコピーします。Ctrl+V で手動で貼り付けてください。",
+ "wtypeCosmicTerminalsDescription": "COSMIC では、Warp などのターミナルは wtype 経由でのみ貼り付けを受け取ります。その他のアプリには wtype なしで貼り付けられます。",
"wtypeFallbackDescription": "この wlroots 系コンポジターでは wtype が推奨される自動貼り付け方法です。代替手段も利用できますが、信頼性が低い場合があります。",
"xwaylandAppsOnly": "自動貼り付けは XWayland アプリのみで動作します"
},
@@ -2001,7 +2002,7 @@
"recheck": "再確認",
"copy": "コピー",
"ydotoolDesc": "Wayland 用入力自動化ツール",
- "wtypeDesc": "wlroots 系コンポジターで推奨される入力自動化ツール",
+ "wtypeDesc": "wlroots 系コンポジターで推奨される入力自動化ツール。COSMIC ではターミナルへの貼り付けに使用",
"ydotooldDesc": "ydotool デーモン(Ubuntu/Pop!_OS では別パッケージ)",
"uinputDesc": "カーネル入力デバイスへのアクセス",
"uinputRuleFound": "ルールは存在しますが未適用です。再起動で解決するはずです。",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 417459b95..aeab8e421 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1394,6 +1394,7 @@
"waylandClipboardTitle": "Modo área de transferência no Wayland",
"windowsReady": "O Windows suporta colagem automática nativamente. Nenhuma configuração necessária!",
"withoutToolPrefix": "Sem essa ferramenta, o OpenWhispr copiará o texto para a área de transferência. Você poderá colar manualmente com Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "No COSMIC, terminais como o Warp só recebem texto colado pelo wtype. Nos outros apps, a colagem já funciona sem ele.",
"wtypeFallbackDescription": "O wtype é o método de colagem automática preferido para este compositor wlroots. Há uma alternativa disponível, mas ela pode ser menos confiável.",
"xwaylandAppsOnly": "a colagem automática funciona apenas para apps XWayland"
},
@@ -1980,7 +1981,7 @@
"recheck": "Verificar novamente",
"copy": "Copiar",
"ydotoolDesc": "Ferramenta de automação de entrada para Wayland",
- "wtypeDesc": "Ferramenta de automação de entrada preferida em compositores wlroots",
+ "wtypeDesc": "Ferramenta de automação de entrada preferida em compositores wlroots; no COSMIC, usada para colar em terminais",
"ydotooldDesc": "Daemon do ydotool (pacote separado no Ubuntu/Pop!_OS)",
"uinputDesc": "Acesso ao dispositivo de entrada do kernel",
"uinputRuleFound": "Regra presente mas não ativa. Uma reinicialização deve resolver.",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index b0fe0e4b7..1bf15801e 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1415,6 +1415,7 @@
"waylandClipboardTitle": "Режим буфера обмена в Wayland",
"windowsReady": "Windows поддерживает автоматическую вставку из коробки. Настройка не требуется!",
"withoutToolPrefix": "Без этого инструмента OpenWhispr скопирует текст в буфер обмена. Вы сможете вставить его вручную с помощью Ctrl+V.",
+ "wtypeCosmicTerminalsDescription": "В COSMIC терминалы, такие как Warp, получают вставляемый текст только через wtype. В остальные приложения вставка уже работает без него.",
"wtypeFallbackDescription": "wtype — предпочтительный способ автоматической вставки для этого композитора wlroots. Доступен резервный вариант, но он может быть менее надёжным.",
"xwaylandAppsOnly": "автоматическая вставка работает только для приложений XWayland"
},
@@ -2005,7 +2006,7 @@
"recheck": "Проверить снова",
"copy": "Копировать",
"ydotoolDesc": "Инструмент автоматизации ввода для Wayland",
- "wtypeDesc": "Предпочтительный инструмент автоматизации ввода для композиторов wlroots",
+ "wtypeDesc": "Предпочтительный инструмент автоматизации ввода для композиторов wlroots; в COSMIC используется для вставки в терминалы",
"ydotooldDesc": "Демон ydotool (отдельный пакет в Ubuntu/Pop!_OS)",
"uinputDesc": "Доступ к устройству ввода ядра",
"uinputRuleFound": "Правило найдено, но не активно. Перезагрузка должна помочь.",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index df5b032c4..48bdb296f 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1415,6 +1415,7 @@
"waylandClipboardTitle": "Wayland 上的剪贴板模式",
"windowsReady": "Windows 原生支持自动粘贴,无需额外设置!",
"withoutToolPrefix": "如果不安装此工具,OpenWhispr 会将文本复制到剪贴板,你可以使用 Ctrl+V 手动粘贴。",
+ "wtypeCosmicTerminalsDescription": "在 COSMIC 上,Warp 等终端只能通过 wtype 接收粘贴的文本。其他应用无需 wtype 即可粘贴。",
"wtypeFallbackDescription": "wtype 是此 wlroots 合成器上的首选自动粘贴方式。有备用方案可用,但可能不太可靠。",
"xwaylandAppsOnly": "自动粘贴仅适用于 XWayland 应用"
},
@@ -2001,7 +2002,7 @@
"recheck": "重新检查",
"copy": "复制",
"ydotoolDesc": "Wayland 输入自动化工具",
- "wtypeDesc": "wlroots 合成器上的首选输入自动化工具",
+ "wtypeDesc": "wlroots 合成器上的首选输入自动化工具;在 COSMIC 上用于向终端粘贴",
"ydotooldDesc": "ydotool 守护进程(Ubuntu/Pop!_OS 上为独立包)",
"uinputDesc": "内核输入设备访问",
"uinputRuleFound": "规则已存在但未生效,重启应可解决。",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 01b01f155..7c3e6441c 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1415,6 +1415,7 @@
"waylandClipboardTitle": "Wayland 剪貼簿模式",
"windowsReady": "Windows 內建支援自動貼上。不需要額外設定!",
"withoutToolPrefix": "若未安裝此工具,OpenWhispr 會將文字複製到剪貼簿。你可以使用 Ctrl+V 手動貼上。",
+ "wtypeCosmicTerminalsDescription": "在 COSMIC 上,Warp 等終端機只能透過 wtype 接收貼上的文字。其他應用程式不需要 wtype 即可貼上。",
"wtypeFallbackDescription": "wtype 是此 wlroots 合成器上的首選自動貼上方式。有備用方案可用,但可能較不可靠。",
"xwaylandAppsOnly": "自動貼上僅適用於 XWayland 應用程式"
},
@@ -2001,7 +2002,7 @@
"recheck": "重新檢查",
"copy": "複製",
"ydotoolDesc": "Wayland 輸入自動化工具",
- "wtypeDesc": "wlroots 合成器上的首選輸入自動化工具",
+ "wtypeDesc": "wlroots 合成器上的首選輸入自動化工具;在 COSMIC 上用於向終端機貼上",
"ydotooldDesc": "ydotool 常駐程式(Ubuntu/Pop!_OS 上為獨立套件)",
"uinputDesc": "核心輸入裝置存取",
"uinputRuleFound": "規則已存在但未生效,重新開機應可解決。",
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 66751ec7d..2dc5439d5 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1099,6 +1099,7 @@ export interface PasteToolsResult {
hasUinput?: boolean;
hasWtype?: boolean;
isWlroots?: boolean;
+ isCosmic?: boolean;
tools?: string[];
recommendedInstall?: string;
}
@@ -2213,6 +2214,7 @@ declare global {
isNixOS: boolean;
isKde: boolean;
isWlroots: boolean;
+ isCosmic: boolean;
hasXclip: boolean;
hasXsel: boolean;
}>;
diff --git a/src/utils/linuxPasteTools.ts b/src/utils/linuxPasteTools.ts
index e237041f8..eafdbc950 100644
--- a/src/utils/linuxPasteTools.ts
+++ b/src/utils/linuxPasteTools.ts
@@ -35,10 +35,16 @@ export function getLinuxPasteInstallCommands(
];
}
-export function needsLinuxPasteToolGuidance(pasteTools: PasteToolsResult) {
+// wtype is the paste tool on wlroots. On COSMIC other apps paste without it, but
+// terminals only receive Ctrl+Shift+V through wtype.
+export function needsWtype(pasteTools: PasteToolsResult) {
return (
- pasteTools.platform === "linux" &&
- (!pasteTools.available || (pasteTools.isWlroots && !pasteTools.hasWtype))
+ !pasteTools.hasWtype &&
+ (!!pasteTools.isWlroots || (!!pasteTools.isCosmic && pasteTools.available))
);
}
+
+export function needsLinuxPasteToolGuidance(pasteTools: PasteToolsResult) {
+ return pasteTools.platform === "linux" && (!pasteTools.available || needsWtype(pasteTools));
+}
import type { PasteToolsResult } from "../types/electron";
diff --git a/test/components/onboardingCompatibility.test.js b/test/components/onboardingCompatibility.test.js
index 6708680a8..6851982af 100644
--- a/test/components/onboardingCompatibility.test.js
+++ b/test/components/onboardingCompatibility.test.js
@@ -162,6 +162,49 @@ test("Linux onboarding shows paste-tool installation and recheck guidance", asyn
assertGuidancePrecedesActions(markup, "sudo apt install xdotool");
});
+// COSMIC pastes into other apps without wtype, but terminals like Warp only take
+// the Ctrl+Shift+V that wtype sends there.
+test("COSMIC onboarding recommends wtype for terminals until it is installed", async (t) => {
+ const vite = await createOnboardingRenderer(t);
+ const { default: CompactPermissionsStep } = await vite.ssrLoadModule(
+ "/components/onboarding/CompactPermissionsStep.tsx"
+ );
+
+ const render = (hasWtype, available = true) =>
+ renderToStaticMarkup(
+ React.createElement(CompactPermissionsStep, {
+ permissions: permissions({
+ pasteToolsInfo: {
+ platform: "linux",
+ available,
+ method: available ? "uinput" : null,
+ requiresPermission: false,
+ isWayland: true,
+ isWlroots: false,
+ isCosmic: true,
+ hasWtype,
+ recommendedInstall: available ? undefined : "xdotool",
+ },
+ }),
+ systemAudio,
+ onContinue: noop,
+ })
+ );
+
+ const missing = render(false);
+ assert.match(missing, /pasteToolsInfo\.wtypeCosmicTerminalsDescription/);
+ assert.match(missing, /sudo apt install wtype/);
+ assert.doesNotMatch(missing, /pasteToolsInfo\.withoutToolPrefix/);
+ assertGuidancePrecedesActions(missing, "sudo apt install wtype");
+
+ assert.doesNotMatch(render(true), /sudo apt install wtype/);
+
+ // With nothing pasting at all, wtype alone would only fix terminals.
+ const unavailable = render(false, false);
+ assert.match(unavailable, /sudo apt install xdotool/);
+ assert.doesNotMatch(unavailable, /wtypeCosmicTerminalsDescription/);
+});
+
test("permissions offers Back ahead of Continue and gates Continue on microphone access", async (t) => {
const vite = await createOnboardingRenderer(t, "darwin");
const { default: CompactPermissionsStep } = await vite.ssrLoadModule(
diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.js
index 3f73a79ed..001980a4e 100644
--- a/test/helpers/clipboardRestore.test.js
+++ b/test/helpers/clipboardRestore.test.js
@@ -66,7 +66,13 @@ const originalLoad = Module._load;
// The held-modifier wait spawns the fast-paste binary ahead of every Linux paste.
// Tests that pin the paste chain's spawn sequence see it as already released;
// the wait itself is covered by tests that load with `realModifierWait`.
-function loadClipboardManager({ spawn, accessibility = true, realModifierWait = false } = {}) {
+function loadClipboardManager({
+ spawn,
+ spawnSync,
+ cosmicAppId,
+ accessibility = true,
+ realModifierWait = false,
+} = {}) {
delete require.cache[clipboardModulePath];
Module._load = function loadWithMocks(request, parent, isMain) {
@@ -78,8 +84,11 @@ function loadClipboardManager({ spawn, accessibility = true, realModifierWait =
},
};
}
- if (request === "child_process" && spawn) {
- return { ...childProcess, spawn };
+ if (request === "./cosmicToplevel" && cosmicAppId !== undefined) {
+ return { getCosmicActiveAppId: async () => cosmicAppId };
+ }
+ if (request === "child_process" && (spawn || spawnSync)) {
+ return { ...childProcess, ...(spawn && { spawn }), ...(spawnSync && { spawnSync }) };
}
return originalLoad.call(this, request, parent, isMain);
};
@@ -417,6 +426,83 @@ test("failed wtype continues to native Shift+Insert uinput", async () => {
assert.deepEqual(spawnCalls[1].args, ["--uinput", "--shift-insert"]);
});
+// Warp binds paste to Ctrl+Shift+V only, and COSMIC's own app ids must not read as the
+// "st" terminal ("system76").
+for (const [appId, expected] of [
+ [
+ "dev.warp.warp",
+ {
+ command: "wtype",
+ args: ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"],
+ },
+ ],
+ [
+ "com.system76.cosmicedit",
+ { command: "/tmp/linux-fast-paste", args: ["--uinput", "--shift-insert"] },
+ ],
+ [null, { command: "/tmp/linux-fast-paste", args: ["--uinput", "--shift-insert"] }],
+]) {
+ test(`COSMIC pastes into ${appId ?? "an undetected window"} with ${expected.command}`, async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ cosmicAppId: appId,
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("COSMIC", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [expected]);
+ });
+}
+
+// COSMIC's XWayland keeps naming the last X11 window while a native Wayland window has
+// focus, and COSMIC gives no PID to spot an Electron app hosting a TUI.
+test("COSMIC ignores xdotool and keeps Shift+Insert for a window that is not a terminal", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0]),
+ spawnSync: () => ({ status: 0, stdout: Buffer.from("4194322\n") }),
+ cosmicAppId: "code",
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "xdotool";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("COSMIC", async () => {
+ process.env.DISPLAY = ":0";
+ await manager.pasteLinux(null);
+ });
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.args),
+ [["--uinput", "--shift-insert"], ["--shift-insert"]]
+ );
+});
+
+// On COSMIC wtype only pastes into terminals, so it is reported for the guidance
+// without becoming the paste method.
+test("COSMIC reports wtype without making it the paste method", async (t) => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "linux" });
+ t.after(() => Object.defineProperty(process, "platform", platform));
+ const TestClipboardManager = loadClipboardManager();
+ const manager = new TestClipboardManager();
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._canAccessUinput = () => true;
+
+ for (const hasWtype of [true, false]) {
+ manager.commandExists = (command) => hasWtype && command === "wtype";
+ const status = await withWaylandEnvironment("COSMIC", () => manager.checkPasteTools());
+ assert.equal(status.isCosmic, true);
+ assert.equal(status.hasWtype, hasWtype);
+ assert.equal(status.method, "uinput");
+ assert.deepEqual(status.tools, []);
+ }
+});
+
test("GNOME tries uinput before a tokenless portal", async () => {
const spawnCalls = [];
const TestClipboardManager = loadClipboardManager({
diff --git a/test/helpers/cosmicToplevel.test.js b/test/helpers/cosmicToplevel.test.js
new file mode 100644
index 000000000..03c99924d
--- /dev/null
+++ b/test/helpers/cosmicToplevel.test.js
@@ -0,0 +1,124 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const net = require("node:net");
+const os = require("node:os");
+const path = require("node:path");
+
+const { getCosmicActiveAppId } = require("../../src/helpers/cosmicToplevel");
+
+function message(objectId, opcode, ...args) {
+ const body = Buffer.concat(args);
+ const header = Buffer.alloc(8);
+ header.writeUInt32LE(objectId, 0);
+ header.writeUInt32LE((8 + body.length) * 0x10000 + opcode, 4);
+ return Buffer.concat([header, body]);
+}
+
+function uint(value) {
+ const buffer = Buffer.alloc(4);
+ buffer.writeUInt32LE(value);
+ return buffer;
+}
+
+function bytes(buffer) {
+ return Buffer.concat([uint(buffer.length), buffer, Buffer.alloc((4 - (buffer.length % 4)) % 4)]);
+}
+
+const string = (value) => bytes(Buffer.from(`${value}\0`));
+const states = (values) => bytes(Buffer.concat(values.map(uint)));
+
+function readString(body, offset) {
+ return body.toString("utf8", offset + 4, offset + 3 + body.readUInt32LE(offset));
+}
+
+// A compositor that lists `globals` and, once zcosmic_toplevel_info_v1 is bound, sends
+// `toplevels` the way cosmic-comp does for a version 1 client. Records every bind.
+function startCompositor(t, { globals, toplevels }) {
+ const runtimeDir = fs.mkdtempSync(path.join(os.tmpdir(), "ow-cosmic-"));
+ const binds = [];
+ const server = net.createServer((socket) => {
+ let registry = null;
+ let pending = Buffer.alloc(0);
+ socket.on("data", (chunk) => {
+ pending = Buffer.concat([pending, chunk]);
+ while (pending.length >= 8 && pending.length >= pending.readUInt32LE(4) >>> 16) {
+ const size = pending.readUInt32LE(4) >>> 16;
+ const objectId = pending.readUInt32LE(0);
+ const opcode = pending.readUInt32LE(4) & 0xffff;
+ const body = pending.subarray(8, size);
+ pending = pending.subarray(size);
+
+ if (objectId === 1 && opcode === 1) {
+ registry = body.readUInt32LE(0);
+ globals.forEach((name, index) =>
+ socket.write(message(registry, 0, uint(index + 1), string(name), uint(3)))
+ );
+ } else if (objectId === 1 && opcode === 0) {
+ socket.write(message(body.readUInt32LE(0), 0, uint(0)));
+ } else if (objectId === registry && opcode === 0) {
+ const interfaceName = readString(body, 4);
+ const info = body.readUInt32LE(body.length - 4);
+ binds.push({ interfaceName, version: body.readUInt32LE(body.length - 8) });
+ toplevels.forEach((toplevel, index) => {
+ const handle = 0xff000000 + index;
+ socket.write(
+ Buffer.concat([
+ message(info, 0, uint(handle)),
+ message(handle, 2, string(`${toplevel.appId} window`)),
+ message(handle, 3, string(toplevel.appId)),
+ message(handle, 8, states(toplevel.states)),
+ message(handle, 1),
+ ])
+ );
+ });
+ }
+ }
+ });
+ });
+ const socketPath = path.join(runtimeDir, "wayland-test");
+ t.after(() => {
+ server.close();
+ fs.rmSync(runtimeDir, { recursive: true, force: true });
+ });
+ return new Promise((resolve) =>
+ server.listen(socketPath, () =>
+ resolve({ env: { XDG_RUNTIME_DIR: runtimeDir, WAYLAND_DISPLAY: "wayland-test" }, binds })
+ )
+ );
+}
+
+test("returns the activated toplevel's app id from a version 1 bind", async (t) => {
+ const { env, binds } = await startCompositor(t, {
+ globals: ["wl_seat", "zcosmic_toplevel_info_v1"],
+ toplevels: [
+ { appId: "com.system76.CosmicEdit", states: [0] },
+ { appId: "dev.warp.Warp", states: [0, 2] },
+ ],
+ });
+
+ assert.equal(await getCosmicActiveAppId(env), "dev.warp.warp");
+ assert.deepEqual(binds, [{ interfaceName: "zcosmic_toplevel_info_v1", version: 1 }]);
+});
+
+test("returns null when the compositor has no COSMIC toplevel info", async (t) => {
+ const { env, binds } = await startCompositor(t, {
+ globals: ["wl_seat"],
+ toplevels: [{ appId: "dev.warp.Warp", states: [2] }],
+ });
+
+ assert.equal(await getCosmicActiveAppId(env), null);
+ assert.deepEqual(binds, []);
+});
+
+test("returns null without a Wayland socket", async () => {
+ const runtimeDir = fs.mkdtempSync(path.join(os.tmpdir(), "ow-cosmic-"));
+ try {
+ assert.equal(
+ await getCosmicActiveAppId({ XDG_RUNTIME_DIR: runtimeDir, WAYLAND_DISPLAY: "wayland-9" }),
+ null
+ );
+ } finally {
+ fs.rmSync(runtimeDir, { recursive: true, force: true });
+ }
+});
diff --git a/test/helpers/linuxSession.test.js b/test/helpers/linuxSession.test.js
index de06b16cb..066b84475 100644
--- a/test/helpers/linuxSession.test.js
+++ b/test/helpers/linuxSession.test.js
@@ -73,3 +73,15 @@ test("does not let a stale SWAYSOCK override a named compositor", () => {
assert.equal(session[expectedFlag], true, name);
}
});
+
+test("detects COSMIC without treating it as wlroots", () => {
+ const session = getLinuxSessionInfo({
+ XDG_SESSION_TYPE: "wayland",
+ XDG_CURRENT_DESKTOP: "COSMIC",
+ WAYLAND_DISPLAY: "wayland-1",
+ DISPLAY: ":0",
+ });
+
+ assert.equal(session.isCosmic, true);
+ assert.equal(session.isWlroots, false);
+});
diff --git a/test/helpers/linuxTerminalClasses.test.js b/test/helpers/linuxTerminalClasses.test.js
index e78467c50..e7b4d1fb3 100644
--- a/test/helpers/linuxTerminalClasses.test.js
+++ b/test/helpers/linuxTerminalClasses.test.js
@@ -45,6 +45,17 @@ test("existing terminals still match", () => {
assert.equal(clipboard.isLinuxTerminalWindowClass("gnome-terminal"), true);
});
+test("short names match whole words only", () => {
+ const clipboard = new ClipboardManager();
+ assert.equal(clipboard.isLinuxTerminalWindowClass("st-256color"), true);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("st"), true);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("stterm"), true);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("xst-256color"), true);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("com.system76.CosmicTerm"), true);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("com.system76.CosmicEdit"), false);
+ assert.equal(clipboard.isLinuxTerminalWindowClass("com.system76.CosmicFiles"), false);
+});
+
test("ordinary GUI apps are not terminals", () => {
const clipboard = new ClipboardManager();
assert.equal(clipboard.isLinuxTerminalWindowClass("Code"), false);