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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix: preserve symlinks during MCP setup and removal (#6977)
Ezra Ellettefa7ce9ab5fa8
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/ai-tools-mcp.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/ai-tools-mcp.test.tsindex 462368f4b..eee76d918 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/ai-tools-mcp.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/ai-tools-mcp.test.ts@@ -20,6 +20,9 @@ const skillsMock = vi.hoisted(() => ({}));const tauriMock = vi.hoisted(() => ({+ resolveAiToolConfigPath: vi.fn<[string], Promise<+ { status: "ok"; data: string } | { status: "error"; error: string }+ >>(),grokbotConnection: vi.fn(),setAiToolAutoConnectOptOut: vi.fn(async () => ({ status: "ok", data: null })),}));@@ -65,6 +68,7 @@ vi.mock("@tauri-apps/plugin-fs", () => ({vi.mock("@/lib/utils/tauri", () => ({commands: {+ resolveAiToolConfigPath: tauriMock.resolveAiToolConfigPath,getLocalApiConfig: vi.fn(async () => ({ key: "sp-test", port: 3030, auth_enabled: true })),bunCheck: vi.fn(async () => ({status: "ok",@@ -84,6 +88,8 @@ vi.mock("@/lib/hooks/use-hardcoded-tiles", () => ({vi.mock("@/lib/external-agent-skills", () => skillsMock);import {+ installCodexMcp,+ uninstallCodexMcp,installCursorMcp,uninstallCursorMcp,installHermesMcp,@@ -114,6 +120,8 @@ const tmpsOf = (path: string) =>Array.from(fsMock.files.keys()).filter((p) => p.startsWith(`${path}.`) && p.endsWith(".tmp"));beforeEach(() => {+ tauriMock.resolveAiToolConfigPath.mockReset();+ tauriMock.resolveAiToolConfigPath.mockImplementation(async (path) => ({ status: "ok", data: path }));fsMock.files.clear();fsMock.unreadable.clear();skillsMock.installExternalAgentSkills.mockClear();@@ -122,6 +130,36 @@ beforeEach(() => {});describe("safe config IO", () => {+ it.each([+ ["/Users/test/.codex/config.toml", 'model = "test"\n', installCodexMcp, uninstallCodexMcp],+ [CURSOR, '{"theme":"dark"}', installCursorMcp, uninstallCursorMcp],+ ] as const)("backs up and replaces the resolved target of %s on connect and disconnect", async (path, seeded, install, uninstall) => {+ const target = `/Users/test/dotfiles/${path.split("/").pop()}`;+ fsMock.files.set(target, seeded);+ tauriMock.resolveAiToolConfigPath.mockImplementation(async (requested) => ({+ status: "ok", data: requested === path ? target : requested,+ }));++ await install();+ expect(fsMock.files.get(target)).toContain("screenpipe");+ expect(fsMock.files.get(backupsOf(target)[0])).toBe(seeded);+ expect(fsMock.files.has(path)).toBe(false);+ expect(backupsOf(path)).toHaveLength(0);+ expect(tmpsOf(target)).toHaveLength(0);++ await uninstall();+ expect(fsMock.files.get(target)).not.toContain("screenpipe");+ expect(fsMock.files.get(target)).toContain(path.endsWith("toml") ? 'model = "test"' : '"theme": "dark"');+ expect(fsMock.files.has(path)).toBe(false);+ });++ it("refuses connect and disconnect when config resolution fails", async () => {+ tauriMock.resolveAiToolConfigPath.mockResolvedValue({ status: "error", error: "could not resolve config: symlink loop" });+ await expect(installCodexMcp()).rejects.toThrow(/could not resolve config/);+ await expect(uninstallCodexMcp()).rejects.toThrow(/could not resolve config/);+ expect(fsMock.files.size).toBe(0);+ });+it("preserves unrelated servers and settings, and takes a backup", async () => {const seeded = JSON.stringify({ mcpServers: { other: { command: "x" } }, theme: "dark" });fsMock.files.set(CURSOR, seeded);diff --git a/apps/screenpipe-app-tauri/lib/ai-tools-mcp.ts b/apps/screenpipe-app-tauri/lib/ai-tools-mcp.tsindex dd07171f3..68c147512 100644--- a/apps/screenpipe-app-tauri/lib/ai-tools-mcp.ts+++ b/apps/screenpipe-app-tauri/lib/ai-tools-mcp.ts@@ -175,12 +175,19 @@ export async function buildMcpConfig(opts?: {/** How many `.screenpipe-backup-*` siblings to keep per config file. */const MAX_CONFIG_BACKUPS = 2;+async function resolveConfigPath(configPath: string): Promise<string> {+ const result = await commands.resolveAiToolConfigPath(configPath);+ if (result.status === "error") throw new Error(result.error);+ return result.data;+}+/*** Read a config as text. Missing file → null (caller starts fresh). A file* that exists but cannot be read (permissions, IO) throws a clear error —* never treated as empty, which is how configs get silently wiped.*/async function readConfigText(configPath: string): Promise<string | null> {+ configPath = await resolveConfigPath(configPath);if (!(await exists(configPath))) return null;try {return await readTextFile(configPath);@@ -254,6 +261,7 @@ async function writeConfigAtomic(configPath: string, text: string): Promise<void/** Backup (if existing) + atomic write, the standard mutation path. */async function replaceConfig(configPath: string, text: string): Promise<void> {+ configPath = await resolveConfigPath(configPath);await backupConfigIfExists(configPath);await writeConfigAtomic(configPath, text);}diff --git a/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts b/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.tsindex 5f5d5c466..a7311f9f0 100644--- a/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts+++ b/apps/screenpipe-app-tauri/lib/dev/browser-tauri-mock.ts@@ -731,6 +731,8 @@ export function createBrowserIpcMock(options: BrowserIpcMockOptions) {: [];case "plugin:fs|exists":return String(input.path) === chatsDir || chatFixtures.has(String(input.path)) || String(input.path).endsWith("/.grokbot/settings.json");+ case "resolve_ai_tool_config_path":+ return String(input.path);case "plugin:fs|stat":case "plugin:fs|lstat":return {diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 31e310a7e..5457641e9 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -2245,6 +2245,17 @@ async resizeSearchWindow(width: number, height: number) : Promise<Result<null, selse return { status: "error", error: e as any };}},+/**+ * Resolve a local AI tool config without replacing a symlink during setup.+ */+async resolveAiToolConfigPath(path: string) : Promise<Result<string, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("resolve_ai_tool_config_path", { path }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Restart only after the user explicitly clicks the in-app action. macOS's* native Screen Recording sheet includes a "Later" choice; closing that sheetdiff --git a/apps/screenpipe-app-tauri/src-tauri/src/skills.rs b/apps/screenpipe-app-tauri/src-tauri/src/skills.rsindex 00f8e243e..7d9ca4d94 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/skills.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/skills.rs@@ -778,6 +778,15 @@ fn write_managed_team_skill_package(Ok(())}+/// Resolve a local AI tool config without replacing a symlink during setup.+#[tauri::command]+#[specta::specta]+pub fn resolve_ai_tool_config_path(path: String) -> Result<String, String> {+ screenpipe_engine::cli::agent::resolve_config_path(std::path::Path::new(&path))+ .map(|resolved| resolved.to_string_lossy().into_owned())+ .map_err(|error| format!("{error:#}"))+}+/// Install the two built-in screenpipe skills into a supported external agent./// Explicit Settings actions still call this narrow command; native launch/// reconciliation shares the same engine skill installer directly.diff --git a/crates/screenpipe-engine/src/cli/agent.rs b/crates/screenpipe-engine/src/cli/agent.rsindex 6e1e42a1a..787adc285 100644--- a/crates/screenpipe-engine/src/cli/agent.rs+++ b/crates/screenpipe-engine/src/cli/agent.rs@@ -789,6 +789,8 @@ fn claude_desktop_config(home: &Path) -> Result<PathBuf> {/// unreadable (permissions, IO) → error — never treated as empty, which is/// how a subsequent write would wipe the user's config (issue #5291).fn read_config_text(path: &Path) -> Result<Option<String>> {+ let resolved = resolve_config_path(path)?;+ let path = resolved.as_path();match std::fs::read_to_string(path) {Ok(s) => Ok(Some(s)),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),@@ -799,6 +801,23 @@ fn read_config_text(path: &Path) -> Result<Option<String>> {}}+/// Resolve existing config symlink chains before reading or replacing them.+/// Only a genuinely missing path starts fresh: dangling links, loops and+/// permission errors must never fall back to replacing the link itself.+pub fn resolve_config_path(path: &Path) -> Result<PathBuf> {+ match std::fs::canonicalize(path) {+ Ok(resolved) => Ok(resolved),+ Err(error) => {+ if error.kind() == std::io::ErrorKind::NotFound+ && matches!(std::fs::symlink_metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound)+ {+ return Ok(path.to_path_buf());+ }+ Err(error).with_context(|| format!("could not resolve config {}", path.display()))+ }+ }+}+/// How many `.screenpipe-backup-*` siblings to keep per config file.const MAX_CONFIG_BACKUPS: usize = 2;@@ -814,6 +833,8 @@ fn config_lock_path(path: &Path) -> PathBuf {/// owner-only files on Unix so the embedded local API key is never widened to/// a default `0644` mode.fn replace_config(path: &Path, expected: Option<&str>, contents: &str) -> Result<()> {+ let resolved = resolve_config_path(path)?;+ let path = resolved.as_path();let _lock = crate::atomic_file::lock(&config_lock_path(path)).with_context(|| format!("lock {} before changing it", path.display()))?;let current = read_config_text(path)?;@@ -1605,6 +1626,69 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ #[cfg(unix)]+ #[test]+ fn test_config_symlink_connect_and_disconnect_preserve_chain_and_target_settings() {+ use std::os::unix::fs::symlink;++ let dir = tempfile::tempdir().unwrap();+ let dotfiles = dir.path().join("dotfiles");+ let codex = dir.path().join(".codex");+ std::fs::create_dir(&dotfiles).unwrap();+ std::fs::create_dir(&codex).unwrap();+ let target = dotfiles.join("config.toml");+ let intermediate = dir.path().join("config-link");+ let link = codex.join("config.toml");+ let original = "model = \"test\"\n";+ std::fs::write(&target, original).unwrap();+ symlink(&target, &intermediate).unwrap();+ symlink("../config-link", &link).unwrap();++ merge_mcp_toml(&link, true, "http://localhost:3030").unwrap();+ let connected = std::fs::read_to_string(&target).unwrap();+ assert!(connected.contains("mcp_servers.screenpipe"));+ assert!(connected.contains(original.trim()));+ let backup = std::fs::read_dir(&dotfiles)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .find(|path| {+ path.file_name()+ .unwrap()+ .to_string_lossy()+ .contains(".screenpipe-backup-")+ })+ .unwrap();+ assert_eq!(std::fs::read_to_string(backup).unwrap(), original);++ remove_mcp_toml(&link).unwrap();+ let disconnected = std::fs::read_to_string(&target).unwrap();+ assert!(!disconnected.contains("mcp_servers.screenpipe"));+ assert!(disconnected.contains(original.trim()));+ assert_eq!(+ std::fs::read_link(&link).unwrap(),+ Path::new("../config-link")+ );+ assert_eq!(std::fs::read_link(&intermediate).unwrap(), target);+ assert_eq!(std::fs::read_dir(&codex).unwrap().count(), 1);+ }++ #[cfg(unix)]+ #[test]+ fn test_config_symlink_resolution_errors_leave_links_untouched() {+ use std::os::unix::fs::symlink;++ for destination in ["missing.toml", "config.toml"] {+ let dir = tempfile::tempdir().unwrap();+ let link = dir.path().join("config.toml");+ symlink(destination, &link).unwrap();++ assert!(read_config_text(&link).is_err());+ assert!(replace_config(&link, None, "replacement").is_err());+ assert_eq!(std::fs::read_link(&link).unwrap(), Path::new(destination));+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);+ }+ }+#[test]fn test_replace_config_rejects_a_concurrent_edit() {let dir = tempfile::tempdir().unwrap();