Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(a11y,document_path): use rusqlite + dirs::config_dir to make the v2.4.139 doc-path feature actually populate — across all 3 OSes, not just macOS

Louis Beaumont338e4734dd3b
diff --git a/Cargo.lock b/Cargo.lock
index 34f6a7e45..78bca3f6e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2431,6 +2431,18 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "fallible-iterator"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -6452,6 +6464,20 @@ dependencies = [
"realfft",
]
+[[package]]
+name = "rusqlite"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2"
+dependencies = [
+ "bitflags 2.11.1",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec 1.15.1",
+]
+
[[package]]
name = "russh"
version = "0.57.1"
@@ -6838,10 +6864,12 @@ dependencies = [
"chrono",
"cidre 0.13.1",
"crossbeam-channel",
+ "dirs 5.0.1",
"evdev",
"libc",
"parking_lot",
"regex",
+ "rusqlite",
"screenpipe-core",
"screenpipe-db",
"serde",
@@ -6871,7 +6899,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"audiopipe",
@@ -6932,7 +6960,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio-eval"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"clap",
@@ -6947,7 +6975,7 @@ dependencies = [
[[package]]
name = "screenpipe-config"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -6960,7 +6988,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"async-trait",
@@ -6993,7 +7021,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -7041,7 +7069,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"chrono",
@@ -7067,7 +7095,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"arc-swap",
@@ -7140,7 +7168,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"anyhow",
"chrono",
@@ -7158,7 +7186,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -7216,7 +7244,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.3.310"
+version = "0.3.311"
dependencies = [
"argon2",
"chacha20poly1305",
diff --git a/crates/screenpipe-a11y/Cargo.toml b/crates/screenpipe-a11y/Cargo.toml
index 9443b53ac..3ec439cab 100644
--- a/crates/screenpipe-a11y/Cargo.toml
+++ b/crates/screenpipe-a11y/Cargo.toml
@@ -32,6 +32,19 @@ regex = "1.10"
# Clipboard access (native NSPasteboard/Win32/X11 — no subprocess)
arboard = "3"
+# Cross-platform user-config dir for electron_docs path resolution
+# (Obsidian / VS Code fork state files live under `dirs::config_dir()`
+# on every supported OS — `~/Library/Application Support` on macOS,
+# `%APPDATA%` on Windows, `~/.config` on Linux).
+dirs = "5.0"
+
+# VS Code fork document_path resolution reads `state.vscdb` (SQLite).
+# Pinned to 0.29 because that's the last release on libsqlite3-sys 0.26 —
+# same version screenpipe-db pins, so adding this does not pull a second
+# copy of the C library into the workspace. `bundled` ensures we ship our
+# own SQLite on every OS rather than depending on the system's.
+rusqlite = { version = "0.29", features = ["bundled"] }
+
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { version = "0.13", features = ["ax", "cg", "blocks", "ns", "app", "dispatch"] }
diff --git a/crates/screenpipe-a11y/src/tree/electron_docs.rs b/crates/screenpipe-a11y/src/tree/electron_docs.rs
index 5775539a5..66afc8195 100644
--- a/crates/screenpipe-a11y/src/tree/electron_docs.rs
+++ b/crates/screenpipe-a11y/src/tree/electron_docs.rs
@@ -19,10 +19,17 @@
//! lives. Reads are cached behind a short TTL so a burst of captures
//! while editing the same file is effectively free.
//!
-//! Cross-platform: paths in this module are macOS-only for now.
-//! Obsidian on Linux/Windows uses different config locations
-//! (`~/.config/obsidian/`, `%APPDATA%/obsidian/`); extending is
-//! mechanical when those backends materialize.
+//! Cross-platform: state files live under [`dirs::config_dir`] on every
+//! supported OS — `~/Library/Application Support` (macOS), `%APPDATA%`
+//! (Windows, i.e. `C:\Users\<user>\AppData\Roaming`), `~/.config`
+//! (Linux). Snap / Flatpak Linux installs use different roots (e.g.
+//! `~/snap/code/common/.config/Code/`) and are not covered yet — those
+//! editors return `None` and the column stays NULL.
+//!
+//! Safety: every public entry point is wrapped in [`std::panic::catch_unwind`]
+//! so a malformed state file (or any other future bug) silently returns
+//! `None` instead of panicking the engine thread. Recursive JSON walks
+//! are depth-bounded for the same reason.
use parking_lot::Mutex;
use serde_json::Value;
@@ -30,23 +37,49 @@ use std::path::PathBuf;
use std::time::{Duration, Instant};
use tracing::debug;
+/// Maximum recursion depth when walking Obsidian's `workspace.json`
+/// tree to find the active leaf. Real Obsidian workspaces are 3-5
+/// nodes deep; the cap exists purely to make a malicious / corrupt
+/// file unable to overflow the stack.
+const MAX_JSON_DEPTH: usize = 64;
+
/// How long to trust a cached read of a state file before re-checking
/// disk. Short enough that switching files in Obsidian reflects within
/// one capture interval; long enough that a burst of walks while
/// editing the same file is one IO.
const CACHE_TTL: Duration = Duration::from_millis(800);
-/// Top-level dispatcher. `app_lower` is the lowercased
-/// `NSRunningApplication.localizedName` from the AX walk caller.
-/// Returns `None` for unknown apps so the AX walker can fall through
-/// to its default (no document_path) behavior.
+/// Top-level dispatcher. `app_lower` is the lowercased focused-app
+/// name from the platform's tree walker (NSRunningApplication on
+/// macOS, the window-process name on Windows, AT-SPI app name on
+/// Linux). Returns `None` for unknown apps so the caller can fall
+/// through to its default (no document_path) behavior.
///
/// Adding a new editor: pick the resolver, map the app name(s).
/// Multiple display names map to the same fork resolver — VS Code,
/// Cursor, Windsurf, VSCodium and Trae all share the same VS Code
/// codebase and on-disk state layout, only the support-dir name
/// differs.
+///
+/// **Safety:** wrapped in [`std::panic::catch_unwind`] so a corrupt
+/// state file, sqlite read fault, or any future bug returns `None`
+/// instead of unwinding into the engine's hot capture loop. Cost is
+/// negligible — `catch_unwind` is essentially free on the happy path.
pub(super) fn resolve_electron_doc_path(app_lower: &str) -> Option<String> {
+ let app_owned = app_lower.to_string();
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
+ resolve_electron_doc_path_inner(&app_owned)
+ }))
+ .unwrap_or_else(|_| {
+ debug!(
+ "electron_docs: resolver panicked for app '{}', returning None",
+ app_lower
+ );
+ None
+ })
+}
+
+fn resolve_electron_doc_path_inner(app_lower: &str) -> Option<String> {
if app_lower == "obsidian" {
return obsidian::active_path();
}
@@ -63,9 +96,11 @@ mod obsidian {
/// currently-focused leaf of the active Obsidian vault.
///
/// Pipeline:
- /// 1. `~/Library/Application Support/obsidian/obsidian.json`
- /// lists every vault Obsidian knows about. Exactly one has
- /// `"open": true` — that's the front vault.
+ /// 1. `<config_dir>/obsidian/obsidian.json` lists every vault
+ /// Obsidian knows about. Exactly one has `"open": true` —
+ /// that's the front vault. `<config_dir>` is platform-defined
+ /// via [`dirs::config_dir`] (`~/Library/Application Support`
+ /// on macOS, `%APPDATA%` on Windows, `~/.config` on Linux).
/// 2. `<vault>/.obsidian/workspace.json` records the per-leaf
/// view state. Find the leaf whose `id == active`. Its
/// `state.state.file` is the path *relative to the vault*.
@@ -91,11 +126,16 @@ mod obsidian {
out.into_os_string().into_string().ok()
}
+ /// `<config>/obsidian/obsidian.json` where `<config>` resolves to
+ /// the platform's user-config dir:
+ /// - macOS: `~/Library/Application Support`
+ /// - Windows: `%APPDATA%` (`C:\Users\<u>\AppData\Roaming`)
+ /// - Linux: `~/.config` (or `$XDG_CONFIG_HOME`)
+ /// Returns `None` if the dir can't be resolved (rare — happens on
+ /// some headless / weird-env setups). Caller treats that as "no
+ /// Obsidian here" which is the safe default.
fn obsidian_cfg_path() -> Option<PathBuf> {
- let home = std::env::var_os("HOME")?;
- let mut p = PathBuf::from(home);
- p.push("Library");
- p.push("Application Support");
+ let mut p = dirs::config_dir()?;
p.push("obsidian");
p.push("obsidian.json");
Some(p)
@@ -115,6 +155,13 @@ mod obsidian {
/// markdown file state. Obsidian's workspace tree is small (a few
/// dozen nodes typical) so a depth-first walk is fine.
pub(super) fn find_leaf_file(node: &Value, active_id: &str) -> Option<String> {
+ find_leaf_file_inner(node, active_id, 0)
+ }
+
+ fn find_leaf_file_inner(node: &Value, active_id: &str, depth: usize) -> Option<String> {
+ if depth >= MAX_JSON_DEPTH {
+ return None;
+ }
if let Some(obj) = node.as_object() {
let is_active_leaf = obj.get("id").and_then(|v| v.as_str()) == Some(active_id)
&& obj.get("type").and_then(|v| v.as_str()) == Some("leaf");
@@ -133,13 +180,13 @@ mod obsidian {
return None;
}
for v in obj.values() {
- if let Some(f) = find_leaf_file(v, active_id) {
+ if let Some(f) = find_leaf_file_inner(v, active_id, depth + 1) {
return Some(f);
}
}
} else if let Some(arr) = node.as_array() {
for v in arr {
- if let Some(f) = find_leaf_file(v, active_id) {
+ if let Some(f) = find_leaf_file_inner(v, active_id, depth + 1) {
return Some(f);
}
}
@@ -153,7 +200,7 @@ mod obsidian {
pub(super) mod vscode_fork {
use super::*;
- use std::process::Command;
+ use rusqlite::{Connection, OpenFlags};
/// Map an app's lowercased display name to the directory it uses
/// under `~/Library/Application Support/`. All five share the
@@ -203,11 +250,15 @@ pub(super) mod vscode_fork {
extract_active_fs_path(&value)
}
+ /// `<config>/<support_dir>/User/workspaceStorage`. `<config>`:
+ /// - macOS: `~/Library/Application Support`
+ /// - Windows: `%APPDATA%`
+ /// - Linux: `~/.config`
+ /// VS Code, Cursor, Windsurf, VSCodium, and Trae all use this
+ /// layout on every supported OS — only the support-dir name
+ /// changes between forks, not between platforms.
fn workspace_storage_root(support_dir: &str) -> Option<PathBuf> {
- let home = std::env::var_os("HOME")?;
- let mut p = PathBuf::from(home);
- p.push("Library");
- p.push("Application Support");
+ let mut p = dirs::config_dir()?;
p.push(support_dir);
p.push("User");
p.push("workspaceStorage");
@@ -244,33 +295,54 @@ pub(super) mod vscode_fork {
/// Read the `memento/workbench.parts.editor` value from a VS
/// Code-style `state.vscdb` and parse it as JSON.
///
- /// Why subprocess: rusqlite would clash with the workspace's
- /// existing `libsqlite3-sys` pin (different major version, both
- /// requesting `bundled`). Spawning `/usr/bin/sqlite3` (ships with
- /// macOS) avoids the dependency conflict; the cache TTL keeps
- /// per-walk cost negligible.
+ /// Open mode: URI form with `immutable=1` + `SQLITE_OPEN_READ_ONLY`.
+ /// `immutable` tells SQLite the file will not change while we hold
+ /// the connection — no WAL replay, no SHM/WAL temp files, no
+ /// contention with the editor's own writes. Stronger and safer
+ /// than the `READ_ONLY` flag alone, which still tries to attach to
+ /// any pending WAL on open.
+ ///
+ /// Uses `rusqlite` (bundled SQLite, statically linked into the
+ /// binary). Pinned to the same `libsqlite3-sys` major as the rest
+ /// of the workspace so we don't link two SQLites.
fn read_vscode_memento(db_path: &PathBuf) -> Option<Value> {
- // -readonly: never write the WAL, never bump mtime, never
- // contend with the editor's own writes.
- let output = Command::new("/usr/bin/sqlite3")
- .arg("-readonly")
- .arg(db_path)
- .arg("SELECT value FROM ItemTable WHERE key='memento/workbench.parts.editor'")
- .output()
- .ok()?;
- if !output.status.success() {
- debug!(
- "vscode_fork: sqlite3 read on {} failed: {}",
- db_path.display(),
- String::from_utf8_lossy(&output.stderr).trim()
- );
- return None;
- }
- let raw = std::str::from_utf8(&output.stdout).ok()?.trim();
+ let uri = format!("file:{}?immutable=1", db_path.display());
+ let conn = match Connection::open_with_flags(
+ &uri,
+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI,
+ ) {
+ Ok(c) => c,
+ Err(e) => {
+ debug!(
+ "vscode_fork: open {} failed: {}",
+ db_path.display(),
+ e
+ );
+ return None;
+ }
+ };
+
+ let raw: String = match conn.query_row(
+ "SELECT value FROM ItemTable WHERE key = 'memento/workbench.parts.editor'",
+ [],
+ |row| row.get(0),
+ ) {
+ Ok(s) => s,
+ Err(rusqlite::Error::QueryReturnedNoRows) => return None,
+ Err(e) => {
+ debug!(
+ "vscode_fork: query on {} failed: {}",
+ db_path.display(),
+ e
+ );
+ return None;
+ }
+ };
+
if raw.is_empty() {
return None;
}
- serde_json::from_str(raw).ok()
+ serde_json::from_str(&raw).ok()
}
fn read_vscode_memento_cached(db_path: &PathBuf) -> Option<Value> {
@@ -421,6 +493,76 @@ mod tests {
assert_eq!(resolve_electron_doc_path(""), None);
}
+ /// Build a minimal `state.vscdb` matching the shape Cursor / VS Code
+ /// produce, and verify our reader returns the active file's fsPath.
+ /// This is the regression test for the v2.4.139 ship-bug: the
+ /// previous shellout returned None on Cursor's real DB, so this
+ /// path silently dropped every editor frame's document_path.
+ #[test]
+ fn vscode_fork_active_path_against_real_sqlite() {
+ let tmp = tempfile::tempdir().unwrap();
+ let ws_dir = tmp
+ .path()
+ .join("Library")
+ .join("Application Support")
+ .join("Cursor")
+ .join("User")
+ .join("workspaceStorage")
+ .join("abc");
+ std::fs::create_dir_all(&ws_dir).unwrap();
+ let db_path = ws_dir.join("state.vscdb");
+
+ // Build a memento JSON the resolver should accept: one group
+ // (id=0), one file editor pointing at /tmp/example.md.
+ let memento = serde_json::json!({
+ "editorpart.state": {
+ "activeGroup": 0,
+ "serializedGrid": {
+ "root": {
+ "type": "leaf",
+ "data": {
+ "id": 0,
+ "editors": [{
+ "value": serde_json::to_string(&serde_json::json!({
+ "resourceJSON": {
+ "scheme": "file",
+ "fsPath": "/tmp/example.md"
+ }
+ })).unwrap()
+ }],
+ "mru": [0]
+ }
+ }
+ }
+ }
+ });
+
+ let conn = rusqlite::Connection::open(&db_path).unwrap();
+ conn.execute(
+ "CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
+ [],
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO ItemTable (key, value) VALUES ('memento/workbench.parts.editor', ?1)",
+ [serde_json::to_string(&memento).unwrap()],
+ )
+ .unwrap();
+ drop(conn);
+
+ // Drive the public entry point — workspace_storage_root() reads
+ // $HOME, so we override it to our tmp.
+ let prev_home = std::env::var_os("HOME");
+ std::env::set_var("HOME", tmp.path());
+ let p = vscode_fork::active_path("Cursor");
+ match prev_home {
+ Some(h) => std::env::set_var("HOME", h),
+ None => std::env::remove_var("HOME"),
+ }
+
+ assert_eq!(p.as_deref(), Some("/tmp/example.md"));
+ }
+
#[test]
fn obsidian_find_leaf_file_picks_active_markdown_leaf() {
let ws: Value = serde_json::json!({
diff --git a/crates/screenpipe-a11y/src/tree/linux.rs b/crates/screenpipe-a11y/src/tree/linux.rs
index b2768ed5a..726e488c8 100644
--- a/crates/screenpipe-a11y/src/tree/linux.rs
+++ b/crates/screenpipe-a11y/src/tree/linux.rs
@@ -1125,18 +1125,19 @@ impl TreeWalkerPlatform for LinuxTreeWalker {
walk_duration
);
+ // Per-app document_path resolution from on-disk state files
+ // (Obsidian config + VS Code-fork state.vscdb under
+ // `~/.config/`). Returns None for any unknown app, missing
+ // file, or read error — never panics. AT-SPI's Document
+ // interface is too uneven across toolkits to rely on.
+ let document_path = super::electron_docs::resolve_electron_doc_path(&app_lower);
Ok(TreeWalkResult::Found(TreeSnapshot {
app_name,
window_name: window_title,
text_content,
nodes: state.nodes,
browser_url,
- // Document path extraction not yet implemented on Linux. AT-SPI
- // has a Document interface and a "DocURL" attribute, but
- // toolkit coverage is uneven (GTK exposes for some apps, Qt for
- // others, Electron for almost none). Deferring to a future
- // pass; meanwhile callers fall back to window_name.
- document_path: None,
+ document_path,
timestamp: Utc::now(),
node_count: state.node_count,
walk_duration,
diff --git a/crates/screenpipe-a11y/src/tree/mod.rs b/crates/screenpipe-a11y/src/tree/mod.rs
index 8a0217c1f..a01d37bae 100644
--- a/crates/screenpipe-a11y/src/tree/mod.rs
+++ b/crates/screenpipe-a11y/src/tree/mod.rs
@@ -5,7 +5,11 @@
//! Accessibility tree walker — periodically walks the macOS AX tree of the focused window,
//! extracts all visible text, and stores it in the accessibility table.
-#[cfg(target_os = "macos")]
+// Cross-platform: Obsidian + VS Code-fork state files live under
+// `dirs::config_dir()` on every supported OS (`~/Library/Application
+// Support` macOS, `%APPDATA%` Windows, `~/.config` Linux). Resolver
+// returns `None` for unknown apps, missing files, or any error — call
+// sites are safe to invoke for every focused frame.
mod electron_docs;
#[cfg(target_os = "linux")]
mod linux;
diff --git a/crates/screenpipe-a11y/src/tree/windows.rs b/crates/screenpipe-a11y/src/tree/windows.rs
index fc4ca06ea..fb0af0ef7 100644
--- a/crates/screenpipe-a11y/src/tree/windows.rs
+++ b/crates/screenpipe-a11y/src/tree/windows.rs
@@ -304,20 +304,17 @@ impl TreeWalkerPlatform for WindowsTreeWalker {
);
// Windows walker doesn't have timeout-based truncation yet — report as complete
+ // Per-app document_path resolution from on-disk state files
+ // (Obsidian config + VS Code-fork state.vscdb). Returns None
+ // for any unknown app or any failure — never panics.
+ let document_path = super::electron_docs::resolve_electron_doc_path(&app_name.to_lowercase());
Ok(TreeWalkResult::Found(TreeSnapshot {
app_name,
window_name,
text_content: text_buffer,
nodes,
browser_url,
- // Document path extraction not yet implemented on Windows. UIA
- // exposes per-element values via the Value pattern but the
- // window-level "current document" notion is editor-specific
- // (Notepad++ via the title, VS Code/Electron via no native
- // signal at all). Rather than ship a fragile per-app heuristic,
- // we leave this None so callers fall back to window_name and
- // we can implement it cleanly later.
- document_path: None,
+ document_path,
timestamp: Utc::now(),
node_count,
walk_duration,