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
feat(connections): connect multiple Obsidian vaults from the UI
Louis Beaumontf7ce28117459
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex 5cca7c6db..cb554d132 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -1951,28 +1951,56 @@ async function discoverObsidianVaults(): Promise<Array<{ id: string; name: strin} catch { return []; }}+// A connected vault. `instance === null` is the default connection (stored+// under the bare `obsidian` key, what single-vault users + the ai-prompt-journal+// pipe read). Additional vaults are named instances (`obsidian:<slug>`).+interface ConnectedVault {+ instance: string | null;+ path: string;+}++const vaultFolderName = (p: string): string => p.split(/[\\/]/).filter(Boolean).pop() ?? p;++// Turn a vault folder name into a URL-safe instance slug (it becomes a path param).+const vaultSlug = (p: string): string =>+ vaultFolderName(p).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "vault";+function ObsidianPanel({ onConnected, onDisconnected }: { onConnected?: () => void; onDisconnected?: () => void }) {const sessionKey = "disconnected:obsidian";- const [vaults, setVaults] = useState<Array<{ id: string; name: string; path: string }>>([]);- const [connectedPath, setConnectedPath] = useState<string | null>(null);- const [status, setStatus] = useState<"idle" | "connecting" | "error">("idle");+ const [discovered, setDiscovered] = useState<Array<{ id: string; name: string; path: string }>>([]);+ const [connected, setConnected] = useState<ConnectedVault[]>([]);+ const [busyPath, setBusyPath] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [manualPath, setManualPath] = useState("");- useEffect(() => {- const wasDisconnected = typeof window !== "undefined" && !!sessionStorage.getItem(sessionKey);- if (!wasDisconnected) {- localFetch("/connections/obsidian")- .then(r => r.json())- .then(data => { if (data.credentials?.vault_path) setConnectedPath(data.credentials.vault_path); })- .catch(() => {});+ // Load every connected vault (default + named instances) from the backend.+ const loadConnected = useCallback(async () => {+ try {+ const r = await localFetch("/connections/obsidian/instances");+ if (!r.ok) throw new Error("instances unavailable");+ const data = await r.json();+ const list = data.instances || data.data || data || [];+ const mapped: ConnectedVault[] = (Array.isArray(list) ? list : [])+ .map((i: any) => ({ instance: i.instance ?? null, path: i.credentials?.vault_path as string }))+ .filter((v: ConnectedVault) => !!v.path);+ setConnected(mapped);+ } catch {+ /* leave as-is — server may still be starting */}- discoverObsidianVaults().then(setVaults).catch(() => {});}, []);- const handleConnect = async (vaultPath: string) => {- if (!vaultPath.trim()) return;- setStatus("connecting");+ useEffect(() => {+ loadConnected();+ discoverObsidianVaults().then(setDiscovered).catch(() => {});+ }, [loadConnected]);++ const connectedPaths = new Set(connected.map(v => v.path));++ const handleConnect = async (rawPath: string) => {+ const vaultPath = rawPath.trim();+ if (!vaultPath || busyPath) return;+ if (connectedPaths.has(vaultPath)) { setManualPath(""); return; }+ setBusyPath(vaultPath);setError(null);try {const testRes = await localFetch("/connections/obsidian/test", {@@ -1982,89 +2010,139 @@ function ObsidianPanel({ onConnected, onDisconnected }: { onConnected?: () => vo});const testData = await testRes.json();if (!testRes.ok || testData.error) throw new Error(testData.error || "test failed");- const saveRes = await localFetch("/connections/obsidian", {++ // First vault → default connection (backward compatible). Additional+ // vaults → a named instance keyed by a unique slug of the folder name.+ const hasDefault = connected.some(v => v.instance === null);+ let endpoint = "/connections/obsidian";+ if (hasDefault) {+ const taken = new Set(connected.map(v => v.instance).filter(Boolean) as string[]);+ const base = vaultSlug(vaultPath);+ let slug = base;+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`;+ endpoint = `/connections/obsidian/instances/${encodeURIComponent(slug)}`;+ }+ const saveRes = await localFetch(endpoint, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ credentials: { vault_path: vaultPath } }),});const saveData = await saveRes.json();if (!saveRes.ok || saveData.error) throw new Error(saveData.error || "save failed");+sessionStorage.removeItem(sessionKey);- setConnectedPath(vaultPath);setManualPath("");- setStatus("idle");+ await loadConnected();notifyConnectionsUpdated();posthog.capture("connection_saved", { integration: "obsidian" });onConnected?.();} catch (e: any) {setError(e?.message || "connection failed");- setStatus("idle");+ } finally {+ setBusyPath(null);}};- const handleDisconnect = async () => {+ const handleDisconnect = async (vault: ConnectedVault) => {try {- const res = await localFetch("/connections/obsidian", { method: "DELETE" });+ const endpoint = vault.instance === null+ ? "/connections/obsidian"+ : `/connections/obsidian/instances/${encodeURIComponent(vault.instance)}`;+ const res = await localFetch(endpoint, { method: "DELETE" });if (!res.ok && res.status !== 404) throw new Error("disconnect failed");- sessionStorage.setItem(sessionKey, "1");- setConnectedPath(null);- setManualPath("");- setStatus("idle");++ const remaining = connected.filter(v => v.instance !== vault.instance);+ // Keep the default `obsidian` slot filled so single-vault consumers (the+ // ai-prompt-journal pipe, onboarding's connected check) keep resolving a+ // vault. If we just removed the default but named vaults remain, promote+ // one of them into the default slot.+ const promote = vault.instance === null ? remaining.find(v => v.instance !== null) : undefined;+ if (promote && promote.instance !== null) {+ await localFetch("/connections/obsidian", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ credentials: { vault_path: promote.path } }),+ });+ await localFetch(`/connections/obsidian/instances/${encodeURIComponent(promote.instance)}`, { method: "DELETE" });+ }+setError(null);+ // Only suppress auto-reconnect hints once the last vault is gone.+ if (remaining.length === 0) sessionStorage.setItem(sessionKey, "1");+ await loadConnected();notifyConnectionsUpdated();onDisconnected?.();} catch (e: any) {setError(e?.message || "disconnect failed");+ loadConnected();}};- if (connectedPath) {- return (- <div className="space-y-3">- <div className="p-3 bg-muted border border-border rounded-lg space-y-0.5">- <p className="text-xs font-medium text-foreground">connected vault</p>- <p className="text-xs text-muted-foreground font-mono break-all">{connectedPath}</p>- </div>- {error && <p className="text-xs text-destructive">{error}</p>}- <Button onClick={handleDisconnect} variant="ghost" size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal text-destructive">- <X className="h-3 w-3" />disconnect- </Button>- </div>- );- }+ // Auto-discovered vaults the user hasn't connected yet.+ const suggestions = discovered.filter(v => !connectedPaths.has(v.path));+ const isWindows = typeof window !== "undefined" && platform() === "windows";return (<div className="space-y-4">- {vaults.length > 0 && (+ {connected.length > 0 && (<div className="space-y-1.5">- <p className="text-xs text-muted-foreground">detected vaults</p>+ <p className="text-xs text-muted-foreground">connected {connected.length === 1 ? "vault" : "vaults"}</p><div className="space-y-1">- {vaults.map(v => (+ {connected.map(v => (+ <div+ key={v.instance ?? "__default__"}+ className="p-2.5 rounded-lg border border-border bg-muted flex items-center gap-2.5"+ >+ <div className="flex-1 min-w-0">+ <p className="text-xs font-medium truncate">{vaultFolderName(v.path)}</p>+ <p className="text-xs text-muted-foreground truncate font-mono">{v.path}</p>+ </div>+ <button+ type="button"+ onClick={() => handleDisconnect(v)}+ title="disconnect vault"+ className="text-muted-foreground hover:text-destructive shrink-0"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ ))}+ </div>+ </div>+ )}++ {suggestions.length > 0 && (+ <div className="space-y-1.5">+ <p className="text-xs text-muted-foreground">{connected.length > 0 ? "add another vault" : "detected vaults"}</p>+ <div className="space-y-1">+ {suggestions.map(v => (<buttonkey={v.id}onClick={() => handleConnect(v.path)}- disabled={status === "connecting"}+ disabled={!!busyPath}className="w-full text-left p-2.5 rounded-lg border border-border bg-card hover:bg-muted transition-colors flex items-center gap-2.5 disabled:opacity-50"><div className="flex-1 min-w-0"><p className="text-xs font-medium truncate">{v.name}</p><p className="text-xs text-muted-foreground truncate font-mono">{v.path}</p></div>- {status === "connecting" ? <Loader2 className="h-3 w-3 animate-spin shrink-0 text-muted-foreground" /> : <Check className="h-3 w-3 shrink-0 text-muted-foreground opacity-0 group-hover:opacity-100" />}+ {busyPath === v.path ? <Loader2 className="h-3 w-3 animate-spin shrink-0 text-muted-foreground" /> : <Plus className="h-3 w-3 shrink-0 text-muted-foreground" />}</button>))}</div></div>)}+<div className="space-y-1.5">- {vaults.length > 0 && <p className="text-xs text-muted-foreground">or enter path manually</p>}- {vaults.length === 0 && <p className="text-xs text-muted-foreground">select your vault folder</p>}+ <p className="text-xs text-muted-foreground">+ {connected.length > 0 || suggestions.length > 0 ? "or enter a vault path manually" : "select your vault folder"}+ </p><div className="flex gap-2"><div className="relative flex-1"><Inputvalue={manualPath}onChange={e => setManualPath(e.target.value)}- placeholder={typeof window !== "undefined" && platform() === "windows" ? "C:\\Users\\you\\Documents\\MyVault" : "/Users/you/Documents/MyVault"}+ placeholder={isWindows ? "C:\\Users\\you\\Documents\\MyVault" : "/Users/you/Documents/MyVault"}className="h-8 text-xs font-mono pr-8"onKeyDown={e => { if (e.key === "Enter") handleConnect(manualPath); }}/>@@ -2082,15 +2160,16 @@ function ObsidianPanel({ onConnected, onDisconnected }: { onConnected?: () => vo</div><ButtononClick={() => handleConnect(manualPath)}- disabled={!manualPath.trim() || status === "connecting"}+ disabled={!manualPath.trim() || !!busyPath}size="sm"className="gap-1.5 h-8 text-xs normal-case font-sans tracking-normal shrink-0">- {status === "connecting" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}- connect+ {busyPath && busyPath === manualPath.trim() ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plus className="h-3 w-3" />}+ add vault</Button></div></div>+{error && <p className="text-xs text-destructive">{error}</p>}</div>);@@ -2782,7 +2861,9 @@ export function ConnectionsSection({case "obsidian": return <ObsidianPanelonConnected={() => { notifyConnectionsUpdated(); fetchIntegrations(); }}onDisconnected={() => {- setIntegrations(prev => prev.map(i => i.id === "obsidian" ? { ...i, connected: false } : i));+ // Don't optimistically flip the tile off — with multiple vaults the+ // connection stays active until the last one is removed. The panel+ // invalidated the cache, so this refetch reflects the true state.notifyConnectionsUpdated();fetchIntegrations();}}