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): restore the text monitor probe and stop shipping a stale binary (#2717)

Chad Piha8263f28cd18d
diff --git a/.github/workflows/build-linux-text-monitor.yml b/.github/workflows/build-linux-text-monitor.yml
index f54b6e4ce..15bab8be1 100644
--- a/.github/workflows/build-linux-text-monitor.yml
+++ b/.github/workflows/build-linux-text-monitor.yml
@@ -7,12 +7,18 @@ on:
- '.github/workflows/build-linux-text-monitor.yml'
branches:
- main
+ # Compile-only on PRs, so a source that doesn't build fails before merge
+ # instead of leaving the last release in place.
+ pull_request:
+ paths:
+ - 'resources/linux-text-monitor.c'
+ - '.github/workflows/build-linux-text-monitor.yml'
workflow_dispatch:
inputs:
version:
description: 'Version tag (e.g., 1.0.0)'
required: false
- default: '1.0.0'
+ default: '1.1.0'
type: string
permissions:
@@ -39,6 +45,7 @@ jobs:
ldd linux-text-monitor
ldd linux-text-monitor | grep -q "not found" && { echo "Unresolved shared library dependency"; exit 1; }
ldd linux-text-monitor | grep -q libgobject-2.0.so || { echo "libgobject-2.0 not linked - explicit -lgobject-2.0 flag may have regressed"; exit 1; }
+ grep -q -- --probe-editable linux-text-monitor || { echo "--probe-editable missing - textEditMonitor.js would get monitor output instead of a verdict"; exit 1; }
exit 0
- name: Create tar.gz archive
@@ -51,11 +58,14 @@ jobs:
name: linux-text-monitor
path: linux-text-monitor-linux-x64.tar.gz
+ # 1.1.0 is the first release with --probe-editable; bump this default
+ # whenever the binary's command-line protocol changes.
- name: Create or update release
+ if: github.event_name != 'pull_request'
uses: softprops/action-gh-release@v3
with:
- tag_name: linux-text-monitor-v${{ inputs.version || '1.0.0' }}
- name: Linux Text Monitor v${{ inputs.version || '1.0.0' }}
+ tag_name: linux-text-monitor-v${{ inputs.version || '1.1.0' }}
+ name: Linux Text Monitor v${{ inputs.version || '1.1.0' }}
body: |
Prebuilt Linux text monitor binary for auto-learn correction monitoring.
diff --git a/CLAUDE.md b/CLAUDE.md
index bc2d1a0e9..707af8152 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -719,7 +719,7 @@ Detects meetings via three independent sources, orchestrated by `MeetingDetectio
### 17. Voice Assistant Hotkey
-A dedicated global hotkey that starts a dictation whose transcript is sent straight to the voice assistant as a command — no wake word ("Hey [AgentName]") needed — and that always bypasses the cleanup model. With auto-paste enabled, a caret verified as writable at capture time (an opaque `caret` session in `selectionManager.js`, revalidated before pasting) receives the completed answer and the pill returns to idle. A dormant macOS accessibility tree reports "unknown": synthetic copy can still recover selected text, but cannot establish a safe caret destination. Unknown targets therefore stay on the panel route, since they can also be integrated terminals, pages without inputs, or fields with selections hidden by clipboard capture. A verified caret whose accessibility becomes unknown before delivery falls back the same way. Terminal and secure-field checks still apply to verified targets. Otherwise the answer streams into a floating assistant panel attached to the dictation pill (there is no separate assistant window) and, with auto-paste enabled, is also copied to the clipboard for manual paste (the Copy button confirms for six seconds). The pill window is content-protected while the panel is open (the panel never appears in screen shares).
+A dedicated global hotkey that starts a dictation whose transcript is sent straight to the voice assistant as a command — no wake word ("Hey [AgentName]") needed — and that always bypasses the cleanup model. With auto-paste enabled, a caret verified as writable at capture time (an opaque `caret` session in `selectionManager.js`, revalidated before pasting) receives the completed answer and the pill returns to idle. A dormant macOS accessibility tree reports "unknown": synthetic copy can still recover selected text, but cannot establish a safe caret destination. Unknown targets therefore stay on the panel route, since they can also be integrated terminals, pages without inputs, or fields with selections hidden by clipboard capture. A verified caret whose accessibility becomes unknown before delivery falls back the same way. Terminal and secure-field checks still apply to verified targets. On Linux the caret is verified by `linux-text-monitor --probe-editable <pid>`, which answers only for the focused field in that process's active window; the pid comes from the target (its AT-SPI pid, `xdotool`/`kdotool getwindowpid`, or `hyprctl activewindow`), and a target whose pid can't be read stays on the panel route. Otherwise the answer streams into a floating assistant panel attached to the dictation pill (there is no separate assistant window) and, with auto-paste enabled, is also copied to the clipboard for manual paste (the Copy button confirms for six seconds). The pill window is content-protected while the panel is open (the panel never appears in screen shares).
**Flow**:
diff --git a/resources/linux-text-monitor.c b/resources/linux-text-monitor.c
index 472e874d5..68406c5ac 100644
--- a/resources/linux-text-monitor.c
+++ b/resources/linux-text-monitor.c
@@ -10,9 +10,11 @@
* INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)
* CHANGED:<text> - Text field value after a change
* CHANGED_B64:<base64> - Text field value after a change (multiline)
- * EDITABLE - Focused element is writable with no live selection (--probe-editable)
+ * EDITABLE - Focused element in the active window of <pid> is
+ * writable with no live selection (--probe-editable <pid>)
* NOT_EDITABLE - Focused element is not safely writable
- * NO_ELEMENT - Could not get focused element
+ * NO_ELEMENT - Could not get focused element (with --probe-editable,
+ * also a missing or invalid pid, or no accessible app for it)
* NO_VALUE - Focused element has no text value
*
* Input (stdin):
@@ -38,6 +40,10 @@
#define TIMEOUT_SECONDS 30
#define POLL_INTERVAL_MS 500
#define MAX_OUTPUT_CHARS 10240
+/* libatspi gives every application it hasn't seen yet 15s to answer, so one
+ * peer that stops answering (#1944) would hold the probe past the caller's
+ * 1.6s kill. linux-fast-paste bounds its calls the same way. */
+#define PROBE_ATSPI_CALL_TIMEOUT_MS 500
static volatile sig_atomic_t running = 1;
static const char BASE64_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -130,6 +136,45 @@ static AtspiAccessible *find_focused(AtspiAccessible *accessible) {
return NULL;
}
+/* The editable probe vouches for the app a paste will reach, so it looks only
+ * inside that process's first ACTIVE window. A FOCUSED state left behind in
+ * another app must not count, even when the target window has nothing focused
+ * or exposes no accessibility at all. */
+static AtspiAccessible *find_focused_in_active_window(AtspiAccessible *desktop, gint target_pid) {
+ int app_count = atspi_accessible_get_child_count(desktop, NULL);
+ for (int i = 0; i < app_count; i++) {
+ AtspiAccessible *app = atspi_accessible_get_child_at_index(desktop, i, NULL);
+ if (!app) continue;
+ GError *pid_error = NULL;
+ gint pid = atspi_accessible_get_process_id(app, &pid_error);
+ if (pid_error) {
+ g_error_free(pid_error);
+ pid = 0;
+ }
+ if (pid != target_pid) {
+ g_object_unref(app);
+ continue;
+ }
+ int window_count = atspi_accessible_get_child_count(app, NULL);
+ for (int j = 0; j < window_count; j++) {
+ AtspiAccessible *win = atspi_accessible_get_child_at_index(app, j, NULL);
+ if (!win) continue;
+ AtspiStateSet *states = atspi_accessible_get_state_set(win);
+ int active = states && atspi_state_set_contains(states, ATSPI_STATE_ACTIVE);
+ if (states) g_object_unref(states);
+ if (active) {
+ AtspiAccessible *focused = find_focused(win);
+ g_object_unref(win);
+ g_object_unref(app);
+ return focused;
+ }
+ g_object_unref(win);
+ }
+ g_object_unref(app);
+ }
+ return NULL;
+}
+
static char *read_text_value(AtspiText *text_iface) {
GError *error = NULL;
@@ -151,10 +196,26 @@ static char *read_text_value(AtspiText *text_iface) {
}
int main(int argc, char **argv) {
- signal(SIGTERM, signal_handler);
- signal(SIGINT, signal_handler);
-
int probe_editable = argc >= 2 && strcmp(argv[1], "--probe-editable") == 0;
+ /* The probe never reads `running`, so it keeps the default action and the
+ * caller's kill at its give-up stops a slow walk. */
+ if (!probe_editable) {
+ signal(SIGTERM, signal_handler);
+ signal(SIGINT, signal_handler);
+ }
+ gint target_pid = 0;
+ if (probe_editable && argc >= 3) {
+ char *end = NULL;
+ long parsed = strtol(argv[2], &end, 10);
+ if (end != argv[2] && *end == '\0' && parsed > 0 && parsed <= G_MAXINT) {
+ target_pid = (gint)parsed;
+ }
+ }
+ if (probe_editable && !target_pid) {
+ printf("NO_ELEMENT\n");
+ fflush(stdout);
+ return 1;
+ }
/* Read original text from stdin (consume but don't use) */
char stdin_buf[4096];
@@ -168,6 +229,7 @@ int main(int argc, char **argv) {
fflush(stdout);
return 1;
}
+ if (probe_editable) atspi_set_timeout(PROBE_ATSPI_CALL_TIMEOUT_MS, -1);
GError *error = NULL;
AtspiAccessible *desktop = atspi_get_desktop(0);
@@ -177,26 +239,30 @@ int main(int argc, char **argv) {
return 1;
}
- /* Search for focused element across all applications */
AtspiAccessible *focused = NULL;
- int app_count = atspi_accessible_get_child_count(desktop, &error);
- if (error) {
- g_error_free(error);
- error = NULL;
- app_count = 0;
- }
-
- for (int i = 0; i < app_count && !focused; i++) {
- AtspiAccessible *app = atspi_accessible_get_child_at_index(desktop, i, &error);
+ if (probe_editable) {
+ focused = find_focused_in_active_window(desktop, target_pid);
+ } else {
+ /* Search for focused element across all applications */
+ int app_count = atspi_accessible_get_child_count(desktop, &error);
if (error) {
g_error_free(error);
error = NULL;
- continue;
+ app_count = 0;
}
- if (!app) continue;
- focused = find_focused(app);
- g_object_unref(app);
+ for (int i = 0; i < app_count && !focused; i++) {
+ AtspiAccessible *app = atspi_accessible_get_child_at_index(desktop, i, &error);
+ if (error) {
+ g_error_free(error);
+ error = NULL;
+ continue;
+ }
+ if (!app) continue;
+
+ focused = find_focused(app);
+ g_object_unref(app);
+ }
}
g_object_unref(desktop);
@@ -208,36 +274,64 @@ int main(int argc, char **argv) {
}
if (probe_editable) {
+ /* GTK4 reports a usable field as SENSITIVE without ENABLED; a
+ * disabled one has neither. */
AtspiStateSet *states = atspi_accessible_get_state_set(focused);
int editable = states &&
atspi_state_set_contains(states, ATSPI_STATE_EDITABLE) &&
- atspi_state_set_contains(states, ATSPI_STATE_ENABLED) &&
- atspi_state_set_contains(states, ATSPI_STATE_FOCUSABLE) &&
- !atspi_state_set_contains(states, ATSPI_STATE_PROTECTED);
+ (atspi_state_set_contains(states, ATSPI_STATE_ENABLED) ||
+ atspi_state_set_contains(states, ATSPI_STATE_SENSITIVE)) &&
+ atspi_state_set_contains(states, ATSPI_STATE_FOCUSABLE);
if (states) g_object_unref(states);
- /* A shell prompt must never read as a writable caret: pasted newlines
- * execute. VTE and Qt terminals expose ATSPI_ROLE_TERMINAL; the caller
- * separately refuses terminals by executable name. */
- if (editable &&
- atspi_accessible_get_role(focused, NULL) == ATSPI_ROLE_TERMINAL) {
- editable = 0;
+ /* AT-SPI has no "protected" state; a secure field is known only by
+ * its role (GTK, Qt, Chromium and Firefox all report PASSWORD_TEXT),
+ * and generated text must never be pasted into one. A shell prompt
+ * must never read as a writable caret either: pasted newlines
+ * execute. VTE and Qt terminals expose ATSPI_ROLE_TERMINAL; the
+ * caller separately refuses terminals by executable name. A role
+ * that cannot be read could be either, so it is not editable. */
+ if (editable) {
+ GError *role_error = NULL;
+ AtspiRole role = atspi_accessible_get_role(focused, &role_error);
+ if (role_error) {
+ g_error_free(role_error);
+ editable = 0;
+ } else if (role == ATSPI_ROLE_PASSWORD_TEXT || role == ATSPI_ROLE_TERMINAL) {
+ editable = 0;
+ }
}
/* A live selection means an EDITABLE verdict would let generated text
* paste over the user's highlighted text. This is the authoritative
* check: the caller's clipboard-based capture cannot see a selection
* whose text already matches the clipboard. */
if (editable) {
+ /* A selection that cannot be read could be live, so it is not
+ * editable. That includes a Text interface that cannot be read:
+ * libatspi returns none when its GetInterfaces call fails. */
AtspiText *probe_text = atspi_accessible_get_text_iface(focused);
if (probe_text) {
- gint n_selections = atspi_text_get_n_selections(probe_text, NULL);
+ GError *selection_error = NULL;
+ gint n_selections = atspi_text_get_n_selections(probe_text, &selection_error);
+ if (selection_error) {
+ g_error_free(selection_error);
+ selection_error = NULL;
+ editable = 0;
+ }
for (gint i = 0; i < n_selections && editable; i++) {
- AtspiRange *selection = atspi_text_get_selection(probe_text, i, NULL);
- if (selection) {
- if (selection->end_offset > selection->start_offset) editable = 0;
- g_free(selection);
+ AtspiRange *selection =
+ atspi_text_get_selection(probe_text, i, &selection_error);
+ if (selection_error) {
+ g_error_free(selection_error);
+ selection_error = NULL;
+ editable = 0;
+ } else if (selection && selection->end_offset > selection->start_offset) {
+ editable = 0;
}
+ if (selection) g_free(selection);
}
g_object_unref(probe_text);
+ } else {
+ editable = 0;
}
}
printf("%s\n", editable ? "EDITABLE" : "NOT_EDITABLE");
diff --git a/resources/linux-text-monitor.py b/resources/linux-text-monitor.py
index 2cfc1680f..372290df0 100644
--- a/resources/linux-text-monitor.py
+++ b/resources/linux-text-monitor.py
@@ -11,7 +11,11 @@ Protocol (stdout):
INITIAL_VALUE_B64:<base64> - Initial text field value (multiline)
CHANGED:<text> - Text field value after a change
CHANGED_B64:<base64> - Text field value after a change (multiline)
- NO_ELEMENT - Could not get focused element
+ EDITABLE - Focused element in the active window of <pid> is
+ writable with no live selection (--probe-editable <pid>)
+ NOT_EDITABLE - Focused element is not safely writable
+ NO_ELEMENT - Could not get focused element (with --probe-editable,
+ also a missing or invalid pid, or no accessible app for it)
NO_VALUE - Focused element has no text value
Input (stdin):
@@ -27,6 +31,10 @@ import base64
TIMEOUT_SECONDS = 30
MAX_OUTPUT_CHARS = 10240
+# libatspi gives every application it hasn't seen yet 15s to answer, so one
+# peer that stops answering (#1944) would hold the probe past the caller's
+# 1.6s kill. linux-fast-paste bounds its calls the same way.
+PROBE_ATSPI_CALL_TIMEOUT_MS = 500
try:
import gi
@@ -55,6 +63,32 @@ def _find_focused(accessible):
return None
+# The editable probe vouches for the app a paste will reach, so it looks only
+# inside that process's first ACTIVE window. A FOCUSED state left behind in
+# another app must not count, even when the target window has nothing focused
+# or exposes no accessibility at all.
+def _find_focused_in_active_window(desktop, target_pid):
+ for i in range(desktop.get_child_count()):
+ try:
+ app = desktop.get_child_at_index(i)
+ if app is None or app.get_process_id() != target_pid:
+ continue
+ window_count = app.get_child_count()
+ except Exception:
+ continue
+ for j in range(window_count):
+ try:
+ window = app.get_child_at_index(j)
+ active = window is not None and window.get_state_set().contains(
+ Atspi.StateType.ACTIVE
+ )
+ except Exception:
+ continue
+ if active:
+ return _find_focused(window)
+ return None
+
+
def _emit_text(prefix, value):
truncated = value[:MAX_OUTPUT_CHARS]
if "\n" in truncated or "\r" in truncated:
@@ -64,8 +98,20 @@ def _emit_text(prefix, value):
print(f"{prefix}:{truncated}", flush=True)
+def _parse_pid(value):
+ try:
+ pid = int(value)
+ except ValueError:
+ return 0
+ return pid if 0 < pid <= 2**31 - 1 else 0
+
+
def main():
probe_editable = len(sys.argv) >= 2 and sys.argv[1] == "--probe-editable"
+ target_pid = _parse_pid(sys.argv[2]) if probe_editable and len(sys.argv) >= 3 else 0
+ if probe_editable and not target_pid:
+ print("NO_ELEMENT", flush=True)
+ sys.exit(1)
# Read original text from stdin (consume but don't use in this binary)
if not probe_editable:
@@ -79,22 +125,27 @@ def main():
sys.exit(1)
Atspi.init()
+ if probe_editable:
+ Atspi.set_timeout(PROBE_ATSPI_CALL_TIMEOUT_MS, -1)
# Get the focused accessible element
desktop = Atspi.get_desktop(0)
focused = None
- # Search for the focused element across all applications
- for i in range(desktop.get_child_count()):
- try:
- app = desktop.get_child_at_index(i)
- if app is None:
+ if probe_editable:
+ focused = _find_focused_in_active_window(desktop, target_pid)
+ else:
+ # Search for the focused element across all applications
+ for i in range(desktop.get_child_count()):
+ try:
+ app = desktop.get_child_at_index(i)
+ if app is None:
+ continue
+ focused = _find_focused(app)
+ if focused is not None:
+ break
+ except Exception:
continue
- focused = _find_focused(app)
- if focused is not None:
- break
- except Exception:
- continue
if focused is None:
print("NO_ELEMENT", flush=True)
@@ -103,38 +154,54 @@ def main():
if probe_editable:
try:
states = focused.get_state_set()
+ # GTK4 reports a usable field as SENSITIVE without ENABLED; a
+ # disabled one has neither.
editable = (
states.contains(Atspi.StateType.EDITABLE)
- and states.contains(Atspi.StateType.ENABLED)
+ and (
+ states.contains(Atspi.StateType.ENABLED)
+ or states.contains(Atspi.StateType.SENSITIVE)
+ )
and states.contains(Atspi.StateType.FOCUSABLE)
- and not states.contains(Atspi.StateType.PROTECTED)
)
except Exception:
editable = False
- # A shell prompt must never read as a writable caret: pasted newlines
- # execute. VTE and Qt terminals expose the TERMINAL role; the caller
- # separately refuses terminals by executable name.
+ # AT-SPI has no "protected" state; a secure field is known only by its
+ # role (GTK, Qt, Chromium and Firefox all report PASSWORD_TEXT), and
+ # generated text must never be pasted into one. A shell prompt must
+ # never read as a writable caret either: pasted newlines execute. VTE
+ # and Qt terminals expose the TERMINAL role; the caller separately
+ # refuses terminals by executable name. A role that cannot be read
+ # could be either, so it is not editable.
if editable:
try:
- if focused.get_role() == Atspi.Role.TERMINAL:
+ if focused.get_role() in (Atspi.Role.PASSWORD_TEXT, Atspi.Role.TERMINAL):
editable = False
except Exception:
- pass
+ editable = False
# A live selection means an EDITABLE verdict would let generated text
# paste over the user's highlighted text. This is the authoritative
# check: the caller's clipboard-based capture cannot see a selection
# whose text already matches the clipboard.
+ # GI returns the text interface as an Atspi.Accessible, whose own
+ # get_selection() is the unrelated Selection interface, so the Text
+ # methods are called unbound. A selection that cannot be read could
+ # be live, so it is not editable. That includes a Text interface that
+ # cannot be read: libatspi returns none when its GetInterfaces call
+ # fails.
if editable:
try:
text_iface = focused.get_text_iface()
if text_iface:
- for i in range(text_iface.get_n_selections()):
- selection = text_iface.get_selection(i)
+ for i in range(Atspi.Text.get_n_selections(text_iface)):
+ selection = Atspi.Text.get_selection(text_iface, i)
if selection and selection.end_offset > selection.start_offset:
editable = False
break
+ else:
+ editable = False
except Exception:
- pass
+ editable = False
print("EDITABLE" if editable else "NOT_EDITABLE", flush=True)
sys.exit(0)
diff --git a/scripts/build-linux-text-monitor.js b/scripts/build-linux-text-monitor.js
index 24cd9ad2a..76993fcbe 100644
--- a/scripts/build-linux-text-monitor.js
+++ b/scripts/build-linux-text-monitor.js
@@ -4,10 +4,13 @@
*
* Strategy:
* 1. If binary exists and is up-to-date, do nothing
- * 2. Try to download prebuilt binary from GitHub releases
- * 3. Fall back to local compilation if download fails
+ * 2. Compile locally when the AT-SPI2 dev headers are installed
+ * 3. Otherwise download the prebuilt binary from GitHub releases
*
- * This allows developers without AT-SPI2 dev headers to still build the app.
+ * Compiling comes first because a release carries no source hash: it can
+ * predate resources/linux-text-monitor.c, as linux-text-monitor-v1.0.0 did
+ * once --probe-editable was added. The download lets developers without
+ * AT-SPI2 dev headers still build the app.
*/
const { spawnSync } = require("child_process");
@@ -15,11 +18,6 @@ const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
-const isLinux = process.platform === "linux";
-if (!isLinux) {
- process.exit(0);
-}
-
const projectRoot = path.resolve(__dirname, "..");
const cSource = path.join(projectRoot, "resources", "linux-text-monitor.c");
const outputDir = path.join(projectRoot, "resources", "bin");
@@ -36,53 +34,62 @@ function ensureDir(dirPath) {
}
}
-function isBinaryUpToDate() {
- if (!fs.existsSync(outputBinary)) {
- return false;
- }
+function sourceHash(pkgFlags) {
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const flagStr = pkgFlags ? pkgFlags.join(" ") : "";
+ return crypto
+ .createHash("sha256")
+ .update(sourceContent + flagStr)
+ .digest("hex");
+}
- if (!fs.existsSync(cSource)) {
- return true;
- }
+// A download is recorded against the source it was fetched for, so a source
+// change fetches again and picks up a newer release.
+function downloadedHash(hash) {
+ return `downloaded:${hash}`;
+}
- try {
- const binaryStat = fs.statSync(outputBinary);
- const sourceStat = fs.statSync(cSource);
- if (binaryStat.mtimeMs < sourceStat.mtimeMs) {
- return false;
- }
- } catch {
- return false;
- }
+/**
+ * A downloaded binary stands only while there is no way to compile. A binary
+ * with no recorded hash is of unknown origin and is rebuilt.
+ */
+function isBinaryUpToDate({ binaryExists, sourceExists, savedHash, currentHash, canCompile }) {
+ if (!binaryExists) return false;
+ if (!sourceExists) return true;
+ if (!currentHash) return false;
+ if (savedHash === downloadedHash(currentHash)) return !canCompile;
+ return savedHash === currentHash;
+}
- // Check source + build flags hash
+/**
+ * With headers installed, a failed compile is a broken source, which CI must
+ * not paper over with a release.
+ */
+function obtainSteps({ canCompile, inCI }) {
+ if (!canCompile) return ["download"];
+ return inCI ? ["compile"] : ["compile", "download"];
+}
+
+function readBuildState(pkgFlags) {
+ const sourceExists = fs.existsSync(cSource);
+ let savedHash = null;
+ let currentHash = null;
try {
- const pkgFlags = getPkgConfigFlags();
- const flagStr = pkgFlags ? pkgFlags.join(" ") : "";
- const sourceContent = fs.readFileSync(cSource, "utf8");
- const currentHash = crypto
- .createHash("sha256")
- .update(sourceContent + flagStr)
- .digest("hex");
-
- if (fs.existsSync(hashFile)) {
- const savedHash = fs.readFileSync(hashFile, "utf8").trim();
- if (savedHash !== currentHash) {
- log("Source or build flags changed, rebuild needed");
- return false;
- }
- } else {
- fs.writeFileSync(hashFile, currentHash);
- }
+ if (fs.existsSync(hashFile)) savedHash = fs.readFileSync(hashFile, "utf8").trim();
+ if (sourceExists) currentHash = sourceHash(pkgFlags);
} catch (err) {
log(`Hash check failed: ${err.message}, forcing rebuild`);
- return false;
}
-
- return true;
+ return {
+ binaryExists: fs.existsSync(outputBinary),
+ sourceExists,
+ savedHash,
+ currentHash,
+ canCompile: Boolean(pkgFlags),
+ };
}
-async function tryDownload() {
+async function tryDownload(pkgFlags) {
log("Attempting to download prebuilt binary...");
const downloadScript = path.join(__dirname, "download-text-monitor.js");
@@ -97,6 +104,11 @@ async function tryDownload() {
});
if (result.status === 0 && fs.existsSync(outputBinary)) {
+ try {
+ fs.writeFileSync(hashFile, downloadedHash(sourceHash(pkgFlags)));
+ } catch (err) {
+ log(`Warning: Could not record download: ${err.message}`);
+ }
log("Successfully downloaded prebuilt binary");
return true;
}
@@ -135,18 +147,12 @@ function attemptCompile(command, args) {
});
}
-function tryCompile() {
+function tryCompile(pkgFlags) {
if (!fs.existsSync(cSource)) {
log("C source not found, cannot compile locally");
return false;
}
- const pkgFlags = getPkgConfigFlags();
- if (!pkgFlags) {
- log("AT-SPI2 development headers not found, cannot compile locally");
- return false;
- }
-
log("Attempting local compilation...");
const compileArgs = ["-O2", cSource, "-o", outputBinary, ...pkgFlags];
@@ -167,13 +173,7 @@ function tryCompile() {
}
try {
- const sourceContent = fs.readFileSync(cSource, "utf8");
- const flagStr = pkgFlags.join(" ");
- const hash = crypto
- .createHash("sha256")
- .update(sourceContent + flagStr)
- .digest("hex");
- fs.writeFileSync(hashFile, hash);
+ fs.writeFileSync(hashFile, sourceHash(pkgFlags));
} catch (err) {
log(`Warning: Could not save source hash: ${err.message}`);
}
@@ -185,18 +185,32 @@ function tryCompile() {
async function main() {
ensureDir(outputDir);
- if (isBinaryUpToDate()) {
+ const pkgFlags = getPkgConfigFlags();
+ if (isBinaryUpToDate(readBuildState(pkgFlags))) {
log("Binary is up to date, skipping build");
return;
}
- const downloaded = await tryDownload();
- if (downloaded) {
- return;
+ if (!pkgFlags) {
+ log("AT-SPI2 development headers not found, cannot compile locally");
}
- const compiled = tryCompile();
- if (compiled) {
+ const steps = obtainSteps({ canCompile: Boolean(pkgFlags), inCI: Boolean(process.env.CI) });
+ for (const step of steps) {
+ if (step === "compile" && tryCompile(pkgFlags)) return;
+ if (step === "download") {
+ if (pkgFlags) {
+ console.warn(
+ "[linux-text-monitor] Compilation failed; the prebuilt release may predate resources/linux-text-monitor.c."
+ );
+ }
+ if (await tryDownload(pkgFlags)) return;
+ }
+ }
+
+ if (!steps.includes("download")) {
+ console.error("[linux-text-monitor] Compilation failed; refusing a prebuilt fallback in CI.");
+ process.exitCode = 1;
return;
}
@@ -207,6 +221,10 @@ async function main() {
);
}
-main().catch((error) => {
- console.error("[linux-text-monitor] Unexpected error:", error);
-});
+if (require.main === module && process.platform === "linux") {
+ main().catch((error) => {
+ console.error("[linux-text-monitor] Unexpected error:", error);
+ });
+}
+
+module.exports = { downloadedHash, isBinaryUpToDate, obtainSteps };
diff --git a/scripts/download-text-monitor.js b/scripts/download-text-monitor.js
index 6ebed7533..c9dab59d8 100644
--- a/scripts/download-text-monitor.js
+++ b/scripts/download-text-monitor.js
@@ -67,6 +67,7 @@ async function main() {
if (!release) {
console.error(`[${label}] Could not find a release matching prefix:`, tagPrefix);
console.log(`[${label}] Auto-learn correction monitoring will be disabled`);
+ process.exitCode = 1;
return;
}
@@ -74,6 +75,7 @@ async function main() {
if (!asset) {
console.error(`[${label}] Release ${release.tag} does not contain ${archiveName}`);
console.log(`[${label}] Available assets:`, release.assets.map((a) => a.name).join(", "));
+ process.exitCode = 1;
return;
}
@@ -120,9 +122,11 @@ async function main() {
console.log(`[${label}] Auto-learn correction monitoring will be disabled`);
console.log(`[${label}] To compile locally, ${compileHint}`);
+ process.exitCode = 1;
}
}
main().catch((error) => {
console.error("[text-monitor] Unexpected error:", error);
+ process.exitCode = 1;
});
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index f925dc4a2..09b9f56bf 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -582,7 +582,15 @@ class SelectionManager {
) {
return capture;
}
- const verdict = await this.textEditMonitor?.isFocusedEditable?.(target);
+ const pid = await this._linuxTargetPid(target);
+ const verdict = await this.textEditMonitor?.isFocusedEditable?.(
+ pid ? { ...target, pid } : target
+ );
+ debugLogger.debug(
+ "Editable caret probe",
+ { kind: target.kind, pid: target.pid ?? pid, verdict },
+ "clipboard"
+ );
if (verdict === "editable") return { status: "editable", target };
// An empty copy cannot distinguish a caret from an integrated terminal or
// a page without an input; it can also hide a selection matching the clipboard.
@@ -590,6 +598,23 @@ class SelectionManager {
return capture;
}
+ // The Linux editable probe answers only for a focused field in this process's
+ // active window, so a focus left behind in another app can't vouch for the
+ // target. null for other target kinds, or when the process can't be read.
+ async _linuxTargetPid(target) {
+ if (target.kind === "atspi-pid") return target.id;
+ if (target.kind === "hyprland-window") return target.pid;
+ if (target.kind === "x11-window") return this._readWindowPid("xdotool", target.id);
+ if (target.kind === "kde-window") return this._readWindowPid("kdotool", target.id);
+ return null;
+ }
+
+ async _readWindowPid(tool, windowId) {
+ const result = await runFile(tool, ["getwindowpid", windowId], { timeout: 500 });
+ const pid = result.success ? result.stdout.trim() : "";
+ return /^[1-9]\d*$/.test(pid) ? pid : null;
+ }
+
_isTerminalTarget(...targets) {
return targets.some(
(target) =>
@@ -722,6 +747,7 @@ class SelectionManager {
kind: "hyprland-window",
id: active.address,
windowClass: typeof active.class === "string" ? active.class.toLowerCase() : null,
+ pid: Number.isInteger(active.pid) && active.pid > 0 ? active.pid : null,
};
}
} catch {}
diff --git a/src/helpers/textEditMonitor.js b/src/helpers/textEditMonitor.js
index d92c9e317..dc30b5bc5 100644
--- a/src/helpers/textEditMonitor.js
+++ b/src/helpers/textEditMonitor.js
@@ -317,6 +317,11 @@ class TextEditMonitor extends EventEmitter {
const pid = target?.kind === "mac-pid" ? target.pid : this.lastTargetPid;
if (!pid) return "not_editable";
args = [...resolved.args, "--editable-target", String(pid)];
+ } else if (process.platform === "linux") {
+ // The probe answers only for the target process's active window, so a
+ // target whose process can't be resolved is never a caret.
+ if (!target?.pid) return "not_editable";
+ args = [...resolved.args, "--probe-editable", String(target.pid)];
} else {
args = [...resolved.args, "--probe-editable"];
}
diff --git a/test/helpers/selectionManager.test.js b/test/helpers/selectionManager.test.js
index 7c54b2d31..1d0cf0320 100644
--- a/test/helpers/selectionManager.test.js
+++ b/test/helpers/selectionManager.test.js
@@ -21,7 +21,7 @@ const declines = () =>
const originalLoad = Module._load;
-function loadSelectionManager({ spawn } = {}) {
+function loadSelectionManager({ spawn, execFile } = {}) {
delete require.cache[selectionManagerPath];
Module._load = function loadWithElectronMock(request, parent, isMain) {
if (request === "electron") {
@@ -30,8 +30,8 @@ function loadSelectionManager({ spawn } = {}) {
if (request === "./debugLogger") {
return debugLoggerStub;
}
- if (request === "child_process" && spawn) {
- return { ...childProcess, spawn };
+ if (request === "child_process" && (spawn || execFile)) {
+ return { ...childProcess, ...(spawn && { spawn }), ...(execFile && { execFile }) };
}
return originalLoad.call(this, request, parent, isMain);
};
@@ -221,6 +221,91 @@ test("a Linux AT-SPI terminal pid never becomes a caret delivery target", async
assert.equal(probes.length, 1);
});
+test("a Linux caret probe is bound to the target's process", async () => {
+ const probes = [];
+ const manager = new SelectionManager({
+ clipboardManager: {},
+ textEditMonitor: {
+ isFocusedEditable: async (target) => {
+ probes.push(target);
+ return target.pid ? "editable" : "not_editable";
+ },
+ },
+ platform: "linux",
+ now: () => 1000,
+ });
+ const windowPids = { "xdotool 7": "111", "kdotool {kde}": "222" };
+ manager._readWindowPid = async (tool, id) => windowPids[`${tool} ${id}`] ?? null;
+ const mark = (target) => manager._markEditableCaret({ status: "none", target }, target, true);
+
+ const cases = [
+ [{ kind: "atspi-pid", id: "333" }, "333"],
+ [{ kind: "x11-window", id: "7", windowClass: "gedit" }, "111"],
+ [{ kind: "kde-window", id: "{kde}", windowClass: "kate" }, "222"],
+ [{ kind: "hyprland-window", id: "0xabc", windowClass: "gedit", pid: 444 }, 444],
+ ];
+ for (const [target, pid] of cases) {
+ const result = await mark(target);
+ assert.equal(result.status, "editable", target.kind);
+ assert.deepEqual(result.target, target, "the stored target is unchanged");
+ assert.equal(probes.at(-1).pid, pid, target.kind);
+ }
+
+ // A window whose process can't be read is never a caret.
+ for (const target of [
+ { kind: "x11-window", id: "8", windowClass: "gedit" },
+ { kind: "hyprland-window", id: "0xdef", windowClass: "gedit", pid: null },
+ ]) {
+ assert.equal((await mark(target)).status, "none", target.kind);
+ assert.ok(!probes.at(-1).pid, target.kind);
+ }
+});
+
+// Answers keyed by the command line; anything else fails like a missing tool.
+function loadWithExecFile(outputs) {
+ return loadSelectionManager({
+ execFile: (command, args, options, callback) => {
+ const stdout = outputs[[command, ...args].join(" ")];
+ callback(stdout === undefined ? new Error("failed") : null, stdout ?? "", "");
+ },
+ });
+}
+
+test("a Linux window's pid is read by its window id", async () => {
+ const Manager = loadWithExecFile({
+ "xdotool getwindowpid 7": "111\n",
+ "kdotool getwindowpid {kde}": "222\n",
+ "xdotool getwindowpid 9": "0\n",
+ });
+ const manager = new Manager({ clipboardManager: {}, platform: "linux", now: () => 1000 });
+
+ assert.equal(await manager._readWindowPid("xdotool", "7"), "111");
+ assert.equal(await manager._readWindowPid("kdotool", "{kde}"), "222");
+ assert.equal(await manager._readWindowPid("xdotool", "9"), null);
+ assert.equal(await manager._readWindowPid("xdotool", "8"), null);
+});
+
+test("a Hyprland target carries the pid hyprctl reports", async () => {
+ const activeWindow = (fields) => ({
+ "hyprctl activewindow -j": JSON.stringify({ address: "0xabc", class: "Gedit", ...fields }),
+ });
+ const read = (outputs) =>
+ new (loadWithExecFile(outputs))({
+ clipboardManager: { commandExists: (command) => command === "hyprctl" },
+ platform: "linux",
+ now: () => 1000,
+ })._getLinuxTarget();
+
+ assert.deepEqual(await read(activeWindow({ pid: 444 })), {
+ kind: "hyprland-window",
+ id: "0xabc",
+ windowClass: "gedit",
+ pid: 444,
+ });
+ assert.equal((await read(activeWindow({}))).pid, null);
+ assert.equal((await read(activeWindow({ pid: -1 }))).pid, null);
+});
+
test("treats a clipboard-only fallback as a failed targeted paste", async () => {
const { manager, pastes } = makeHarness({
selections: [
diff --git a/test/helpers/textEditMonitorSelection.test.js b/test/helpers/textEditMonitorSelection.test.js
index 449a7cb36..f2f1485e2 100644
--- a/test/helpers/textEditMonitorSelection.test.js
+++ b/test/helpers/textEditMonitorSelection.test.js
@@ -135,6 +135,61 @@ test("isFocusedEditable answers from a stale binary's first monitor line", darwi
assert.ok(Date.now() - startedAt < 900, "must resolve on the first output line");
});
+async function withLinuxPlatform(run) {
+ const original = Object.getOwnPropertyDescriptor(process, "platform");
+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });
+ try {
+ return await run();
+ } finally {
+ Object.defineProperty(process, "platform", original);
+ }
+}
+
+// The -c script sees the appended --probe-editable as $0 and the pid as $1.
+const linuxProbe = (script) => {
+ const m = new TextEditMonitor();
+ m.resolveBinary = () => ({ command: "/bin/sh", args: ["-c", script] });
+ return m;
+};
+const posixOnly = { skip: process.platform === "win32" };
+
+const LINUX_TARGET = { kind: "x11-window", id: "7", pid: "4242" };
+
+test("isFocusedEditable passes the target pid to the Linux probe", posixOnly, async () => {
+ const m = linuxProbe(
+ '[ "$0" = "--probe-editable" ] && [ "$1" = "4242" ] && echo EDITABLE || echo NOT_EDITABLE'
+ );
+ assert.equal(await withLinuxPlatform(() => m.isFocusedEditable(LINUX_TARGET)), "editable");
+});
+
+// The probe answers only for the target process's active window; without a
+// pid it would have nothing to tie the focused field to.
+test("isFocusedEditable never probes a Linux target without a pid", posixOnly, async () => {
+ const m = linuxProbe("echo EDITABLE");
+ const withoutPid = { kind: "x11-window", id: "7" };
+ assert.equal(await withLinuxPlatform(() => m.isFocusedEditable(withoutPid)), "not_editable");
+ assert.equal(await withLinuxPlatform(() => m.isFocusedEditable(null)), "not_editable");
+});
+
+// linux-text-monitor-v1.0.0 predates --probe-editable and shipped in every
+// Linux build until the probe compiled. It ignores its arguments and runs
+// monitor mode, so a field whose text is literally "EDITABLE" must still not
+// read as a writable caret.
+test("isFocusedEditable fails closed on a pre-probe Linux binary", posixOnly, async () => {
+ const m = linuxProbe('echo "INITIAL_VALUE:EDITABLE"; sleep 2');
+ const startedAt = Date.now();
+ assert.equal(await withLinuxPlatform(() => m.isFocusedEditable(LINUX_TARGET)), "not_editable");
+ assert.ok(Date.now() - startedAt < 900, "must resolve on the first output line");
+
+ for (const line of ["NO_ELEMENT", "NO_VALUE"]) {
+ const exiting = linuxProbe(`echo ${line}; exit 1`);
+ assert.equal(
+ await withLinuxPlatform(() => exiting.isFocusedEditable(LINUX_TARGET)),
+ "not_editable"
+ );
+ }
+});
+
// The bare window as the focused element is the dormant-Chromium signature —
// the selection state is unreadable, not empty, so the caller must fall to the
// synthetic-copy read instead of treating it as "no selection".
diff --git a/test/scripts/buildLinuxTextMonitor.test.js b/test/scripts/buildLinuxTextMonitor.test.js
new file mode 100644
index 000000000..3c8aa9cb9
--- /dev/null
+++ b/test/scripts/buildLinuxTextMonitor.test.js
@@ -0,0 +1,62 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ downloadedHash,
+ isBinaryUpToDate,
+ obtainSteps,
+} = require("../../scripts/build-linux-text-monitor");
+
+const state = (overrides) => ({
+ binaryExists: true,
+ sourceExists: true,
+ savedHash: "abc",
+ currentHash: "abc",
+ canCompile: true,
+ ...overrides,
+});
+
+test("a compiled binary is current only while its source hash matches", () => {
+ assert.equal(isBinaryUpToDate(state()), true);
+ assert.equal(isBinaryUpToDate(state({ currentHash: "def" })), false);
+ assert.equal(isBinaryUpToDate(state({ binaryExists: false })), false);
+});
+
+// linux-text-monitor-v1.0.0 predated --probe-editable, yet every Linux build
+// shipped it: the download ran first and was never checked against the source.
+test("a downloaded binary is replaced as soon as the source can be compiled", () => {
+ const downloaded = downloadedHash("abc");
+ assert.equal(isBinaryUpToDate(state({ savedHash: downloaded })), false);
+ assert.equal(isBinaryUpToDate(state({ savedHash: downloaded, canCompile: false })), true);
+});
+
+// Without headers the download is the only source, so a source change must
+// fetch again: the newer release is the only way to pick up the change.
+test("a downloaded binary is fetched again when the source changes", () => {
+ assert.equal(
+ isBinaryUpToDate(
+ state({ savedHash: downloadedHash("abc"), currentHash: "def", canCompile: false })
+ ),
+ false
+ );
+});
+
+test("compiling comes first, and CI never falls back to a release", () => {
+ assert.deepEqual(obtainSteps({ canCompile: true, inCI: false }), ["compile", "download"]);
+ assert.deepEqual(obtainSteps({ canCompile: true, inCI: true }), ["compile"]);
+ assert.deepEqual(obtainSteps({ canCompile: false, inCI: true }), ["download"]);
+ assert.deepEqual(obtainSteps({ canCompile: false, inCI: false }), ["download"]);
+});
+
+// The old check stamped the current hash onto a binary with none, so a stale
+// download read as freshly built from then on.
+test("a binary with no recorded hash is rebuilt", () => {
+ assert.equal(isBinaryUpToDate(state({ savedHash: null })), false);
+ assert.equal(isBinaryUpToDate(state({ savedHash: null, canCompile: false })), false);
+ // A source that could not be hashed must not match a missing hash.
+ assert.equal(isBinaryUpToDate(state({ savedHash: null, currentHash: null })), false);
+});
+
+test("a binary with no source beside it is kept", () => {
+ assert.equal(isBinaryUpToDate(state({ sourceExists: false, savedHash: null })), true);
+});