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: add Obsidian sync integration (#2158)
Louis Beaumont390e76bce4da
diff --git a/screenpipe-app-tauri/components/settings/connections-section.tsx b/screenpipe-app-tauri/components/settings/connections-section.tsxindex 09e8941d7..37c0178ab 100644--- a/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -10,6 +10,7 @@ import { writeFile, readTextFile } from "@tauri-apps/plugin-fs";import { fetch as tauriFetch } from "@tauri-apps/plugin-http";import { platform } from "@tauri-apps/plugin-os";import { tempDir, join, homeDir } from "@tauri-apps/api/path";+import { ObsidianSyncCard } from "./obsidian-sync-card";const GITHUB_RELEASES_API = "https://api.github.com/repos/mediar-ai/screenpipe/releases";@@ -299,6 +300,9 @@ export function ConnectionsSection() {</CardContent></Card>+ {/* Obsidian Sync */}+ <ObsidianSyncCard />+{/* Learn & Build section */}<div className="space-y-3"><h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">diff --git a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsxnew file mode 100644index 000000000..a688261cf--- /dev/null+++ b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx@@ -0,0 +1,557 @@+"use client";++import React, { useState, useEffect, useCallback } from "react";+import { Card, CardContent } from "@/components/ui/card";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ FolderOpen,+ RefreshCw,+ Check,+ Loader2,+ AlertCircle,+ Clock,+ FileText,+ ExternalLink,+} from "lucide-react";+import { invoke } from "@tauri-apps/api/core";+import { listen } from "@tauri-apps/api/event";+import { open as openDialog } from "@tauri-apps/plugin-dialog";+import { open as openUrl } from "@tauri-apps/plugin-shell";+import { Badge } from "@/components/ui/badge";+import { useSettings } from "@/lib/hooks/use-settings";+import { useToast } from "@/components/ui/use-toast";++// Types matching Rust structs+interface ObsidianSyncSettings {+ enabled: boolean;+ vaultPath: string;+ syncIntervalMinutes: number;+ customPrompt: string;+ lastSyncTime: string | null;+ syncHours: number;+}++interface ObsidianSyncStatus {+ isSyncing: boolean;+ lastSyncTime: string | null;+ lastError: string | null;+ notesCreatedToday: number;+}++const DEFAULT_SETTINGS: ObsidianSyncSettings = {+ enabled: false,+ vaultPath: "",+ syncIntervalMinutes: 0, // 0 = manual only+ customPrompt: "",+ lastSyncTime: null,+ syncHours: 2,+};++export function ObsidianSyncCard() {+ const { settings: appSettings } = useSettings();+ const { toast } = useToast();++ const [settings, setSettings] = useState<ObsidianSyncSettings>(DEFAULT_SETTINGS);+ const [status, setStatus] = useState<ObsidianSyncStatus>({+ isSyncing: false,+ lastSyncTime: null,+ lastError: null,+ notesCreatedToday: 0,+ });+ const [suggestedPaths, setSuggestedPaths] = useState<string[]>([]);+ const [isValidVault, setIsValidVault] = useState<boolean | null>(null);+ const [isValidating, setIsValidating] = useState(false);+ const [isExpanded, setIsExpanded] = useState(false);++ // Load settings from localStorage on mount+ useEffect(() => {+ const saved = localStorage.getItem("obsidian-sync-settings");+ if (saved) {+ try {+ const parsed = JSON.parse(saved);+ setSettings({ ...DEFAULT_SETTINGS, ...parsed });+ } catch (e) {+ console.error("Failed to parse obsidian settings:", e);+ }+ }++ // Fetch suggested vault paths+ fetchVaultPaths();++ // Get initial status+ fetchStatus();+ }, []);++ // Save settings to localStorage when they change+ useEffect(() => {+ localStorage.setItem("obsidian-sync-settings", JSON.stringify(settings));+ }, [settings]);++ // Validate vault path when it changes+ useEffect(() => {+ if (settings.vaultPath) {+ validateVault(settings.vaultPath);+ } else {+ setIsValidVault(null);+ }+ }, [settings.vaultPath]);++ // Listen for sync events+ useEffect(() => {+ const unlisteners: (() => void)[] = [];++ listen<void>("obsidian_sync_started", () => {+ setStatus((s) => ({ ...s, isSyncing: true }));+ }).then((u) => unlisteners.push(u));++ listen<ObsidianSyncStatus>("obsidian_sync_completed", (event) => {+ setStatus(event.payload);+ toast({+ title: "Obsidian sync completed",+ description: "Your activity has been synced to Obsidian",+ });+ }).then((u) => unlisteners.push(u));++ listen<string>("obsidian_sync_error", (event) => {+ setStatus((s) => ({+ ...s,+ isSyncing: false,+ lastError: event.payload,+ }));+ toast({+ variant: "destructive",+ title: "Obsidian sync failed",+ description: event.payload,+ });+ }).then((u) => unlisteners.push(u));++ return () => {+ unlisteners.forEach((u) => u());+ };+ }, [toast]);++ const fetchVaultPaths = async () => {+ try {+ const paths = await invoke<string[]>("obsidian_get_vault_paths");+ setSuggestedPaths(paths);+ } catch (e) {+ console.error("Failed to fetch vault paths:", e);+ }+ };++ const fetchStatus = async () => {+ try {+ const status = await invoke<ObsidianSyncStatus>("obsidian_get_sync_status");+ setStatus(status);+ } catch (e) {+ console.error("Failed to fetch sync status:", e);+ }+ };++ const validateVault = useCallback(async (path: string) => {+ if (!path.trim()) {+ setIsValidVault(null);+ return;+ }++ setIsValidating(true);+ try {+ const isValid = await invoke<boolean>("obsidian_validate_vault", { path });+ setIsValidVault(isValid);+ } catch (e) {+ console.error("Failed to validate vault:", e);+ setIsValidVault(false);+ } finally {+ setIsValidating(false);+ }+ }, []);++ const handleBrowse = async () => {+ try {+ const selected = await openDialog({+ directory: true,+ multiple: false,+ title: "Select Obsidian Vault",+ });+ if (selected && typeof selected === "string") {+ setSettings((s) => ({ ...s, vaultPath: selected }));+ }+ } catch (e) {+ console.error("Failed to open dialog:", e);+ }+ };++ const handleSync = async () => {+ if (!isValidVault) {+ toast({+ variant: "destructive",+ title: "Invalid vault",+ description: "Please select a valid Obsidian vault first",+ });+ return;+ }++ // Check if user is logged in (required for Claude API)+ if (!appSettings?.user?.token) {+ toast({+ variant: "destructive",+ title: "Login required",+ description: "Please log in to use Obsidian sync",+ });+ return;+ }++ try {+ await invoke("obsidian_run_sync", { settings });+ } catch (e) {+ console.error("Failed to run sync:", e);+ toast({+ variant: "destructive",+ title: "Sync failed",+ description: String(e),+ });+ }+ };++ const handleEnableScheduler = async () => {+ if (!isValidVault || settings.syncIntervalMinutes === 0) {+ return;+ }++ try {+ const newSettings = { ...settings, enabled: true };+ setSettings(newSettings);+ await invoke("obsidian_start_scheduler", { settings: newSettings });+ toast({+ title: "Scheduler started",+ description: `Syncing every ${settings.syncIntervalMinutes} minutes`,+ });+ } catch (e) {+ console.error("Failed to start scheduler:", e);+ toast({+ variant: "destructive",+ title: "Failed to start scheduler",+ description: String(e),+ });+ }+ };++ const handleDisableScheduler = async () => {+ try {+ setSettings((s) => ({ ...s, enabled: false }));+ await invoke("obsidian_stop_scheduler");+ toast({+ title: "Scheduler stopped",+ });+ } catch (e) {+ console.error("Failed to stop scheduler:", e);+ }+ };++ const openObsidian = async () => {+ if (!settings.vaultPath) return;++ // Extract vault name from path+ const vaultName = settings.vaultPath.split("/").pop() || "vault";+ const deepLink = `obsidian://open?vault=${encodeURIComponent(vaultName)}&file=screenpipe%2Flogs`;++ try {+ await openUrl(deepLink);+ } catch (e) {+ console.error("Failed to open Obsidian:", e);+ }+ };++ const formatLastSync = (isoTime: string | null) => {+ if (!isoTime) return "Never";++ const date = new Date(isoTime);+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);++ if (diffMins < 1) return "Just now";+ if (diffMins < 60) return `${diffMins} min ago`;+ const diffHours = Math.floor(diffMins / 60);+ if (diffHours < 24) return `${diffHours} hours ago`;+ return date.toLocaleDateString();+ };++ const isLoggedIn = Boolean(appSettings?.user?.token);++ return (+ <Card className="border-border bg-card shadow-sm overflow-hidden">+ <CardContent className="p-0">+ <div className="flex items-start p-6 gap-6">+ {/* Obsidian Logo */}+ <div className="flex-shrink-0">+ <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-purple-600 to-purple-800 flex items-center justify-center">+ <FileText className="w-8 h-8 text-white" />+ </div>+ </div>++ {/* Content */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-2">+ <h3 className="text-xl font-semibold text-foreground">+ Obsidian Sync+ </h3>+ <span className="px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full">+ PKM+ </span>+ {settings.enabled && (+ <span className="px-2 py-0.5 text-xs font-medium bg-green-500/20 text-green-500 rounded-full">+ ● auto-sync+ </span>+ )}+ </div>+ <p className="text-muted-foreground mb-4">+ Automatically sync your screen activity to Obsidian as markdown+ notes. Powered by Claude AI.+ </p>++ {!isLoggedIn && (+ <div className="p-3 bg-yellow-500/10 border border-yellow-500/20 rounded-lg mb-4">+ <p className="text-sm text-yellow-600 dark:text-yellow-400">+ <AlertCircle className="h-4 w-4 inline mr-2" />+ Login required to use Obsidian sync (requires Claude API access)+ </p>+ </div>+ )}++ <div className="flex flex-wrap gap-3">+ <Button+ onClick={() => setIsExpanded(!isExpanded)}+ variant="outline"+ className="gap-2"+ >+ {isExpanded ? "Hide Settings" : "Configure"}+ </Button>++ <Button+ onClick={handleSync}+ disabled={!isValidVault || status.isSyncing || !isLoggedIn}+ className="gap-2"+ >+ {status.isSyncing ? (+ <>+ <Loader2 className="h-4 w-4 animate-spin" />+ Syncing...+ </>+ ) : (+ <>+ <RefreshCw className="h-4 w-4" />+ Sync Now+ </>+ )}+ </Button>++ {settings.vaultPath && (+ <Button+ variant="outline"+ onClick={openObsidian}+ className="gap-2"+ >+ <ExternalLink className="h-4 w-4" />+ Open in Obsidian+ </Button>+ )}+ </div>+ </div>+ </div>++ {/* Expanded Settings */}+ {isExpanded && (+ <div className="px-6 pb-6 space-y-4 border-t border-border pt-4">+ {/* Vault Path */}+ <div className="space-y-2">+ <Label htmlFor="vault-path" className="flex items-center gap-2">+ <FolderOpen className="h-4 w-4" />+ Obsidian Vault Path+ </Label>+ <div className="flex gap-2">+ <div className="flex-1 relative">+ <Input+ id="vault-path"+ value={settings.vaultPath}+ onChange={(e) =>+ setSettings((s) => ({ ...s, vaultPath: e.target.value }))+ }+ placeholder="/path/to/your/vault"+ className={+ isValidVault === true+ ? "border-green-500"+ : isValidVault === false+ ? "border-red-500"+ : ""+ }+ />+ {isValidating && (+ <Loader2 className="absolute right-3 top-2.5 h-4 w-4 animate-spin text-muted-foreground" />+ )}+ </div>+ <Button type="button" variant="outline" onClick={handleBrowse}>+ <FolderOpen className="h-4 w-4" />+ </Button>+ </div>+ {isValidVault === true && (+ <p className="text-sm text-green-500 flex items-center gap-1">+ <Check className="h-3 w-3" /> Valid Obsidian vault+ </p>+ )}+ {isValidVault === false && (+ <p className="text-sm text-red-500 flex items-center gap-1">+ <AlertCircle className="h-3 w-3" /> Not a valid Obsidian vault+ (no .obsidian folder)+ </p>+ )}+ {/* Suggested paths */}+ {suggestedPaths.length > 0 && (+ <div className="flex flex-wrap gap-2 mt-2">+ {suggestedPaths.map((path) => (+ <Badge+ key={path}+ variant="outline"+ className="cursor-pointer hover:bg-muted"+ onClick={() =>+ setSettings((s) => ({ ...s, vaultPath: path }))+ }+ >+ {path.split("/").pop()}+ </Badge>+ ))}+ </div>+ )}+ </div>++ {/* Sync Hours */}+ <div className="space-y-2">+ <Label className="flex items-center gap-2">+ <Clock className="h-4 w-4" />+ Hours to sync+ </Label>+ <Select+ value={String(settings.syncHours)}+ onValueChange={(v) =>+ setSettings((s) => ({ ...s, syncHours: parseInt(v) }))+ }+ >+ <SelectTrigger className="w-48">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="1">Last 1 hour</SelectItem>+ <SelectItem value="2">Last 2 hours</SelectItem>+ <SelectItem value="4">Last 4 hours</SelectItem>+ <SelectItem value="8">Last 8 hours</SelectItem>+ <SelectItem value="24">Last 24 hours</SelectItem>+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ How far back to look when syncing+ </p>+ </div>++ {/* Auto-sync Interval */}+ <div className="space-y-2">+ <Label className="flex items-center gap-2">+ <RefreshCw className="h-4 w-4" />+ Auto-sync interval+ </Label>+ <div className="flex gap-2 items-center">+ <Select+ value={String(settings.syncIntervalMinutes)}+ onValueChange={(v) =>+ setSettings((s) => ({+ ...s,+ syncIntervalMinutes: parseInt(v),+ }))+ }+ >+ <SelectTrigger className="w-48">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="0">Manual only</SelectItem>+ <SelectItem value="15">Every 15 minutes</SelectItem>+ <SelectItem value="30">Every 30 minutes</SelectItem>+ <SelectItem value="60">Every hour</SelectItem>+ <SelectItem value="120">Every 2 hours</SelectItem>+ </SelectContent>+ </Select>+ {settings.syncIntervalMinutes > 0 && (+ <Button+ variant={settings.enabled ? "destructive" : "default"}+ size="sm"+ onClick={+ settings.enabled+ ? handleDisableScheduler+ : handleEnableScheduler+ }+ disabled={!isValidVault || !isLoggedIn}+ >+ {settings.enabled ? "Stop" : "Start"}+ </Button>+ )}+ </div>+ </div>++ {/* Custom Prompt */}+ <div className="space-y-2">+ <Label htmlFor="custom-prompt">+ Custom instructions (optional)+ </Label>+ <Textarea+ id="custom-prompt"+ value={settings.customPrompt}+ onChange={(e) =>+ setSettings((s) => ({ ...s, customPrompt: e.target.value }))+ }+ placeholder="Add any custom instructions for how to structure your notes, what to focus on, naming conventions, etc."+ rows={3}+ />+ <p className="text-xs text-muted-foreground">+ These instructions will be added to the AI prompt+ </p>+ </div>+ </div>+ )}++ {/* Status Bar */}+ <div className="px-6 py-3 bg-muted/50 border-t border-border">+ <div className="flex items-center justify-between text-sm text-muted-foreground">+ <div className="flex items-center gap-4">+ <span>+ Last sync:{" "}+ <span className="text-foreground">+ {formatLastSync(status.lastSyncTime)}+ </span>+ </span>+ {status.notesCreatedToday > 0 && (+ <span>+ {status.notesCreatedToday} sync+ {status.notesCreatedToday > 1 ? "s" : ""} today+ </span>+ )}+ </div>+ {status.lastError && (+ <span className="text-red-500 text-xs truncate max-w-xs">+ Error: {status.lastError}+ </span>+ )}+ </div>+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex c55ffe8e7..352798b74 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -52,6 +52,7 @@ mod windows_overlay;#[cfg(target_os = "macos")]mod space_monitor;mod sync;+mod obsidian_sync;pub use server::*;@@ -820,12 +821,21 @@ async fn main() {opencode::opencode_stop,opencode::opencode_check,opencode::opencode_install,+ // Obsidian Sync commands+ obsidian_sync::obsidian_validate_vault,+ obsidian_sync::obsidian_get_vault_paths,+ obsidian_sync::obsidian_get_sync_status,+ obsidian_sync::obsidian_run_sync,+ obsidian_sync::obsidian_start_scheduler,+ obsidian_sync::obsidian_stop_scheduler,]).typ::<SettingsStore>().typ::<OnboardingStore>().typ::<sync::SyncStatusResponse>().typ::<sync::SyncDeviceInfo>()- .typ::<sync::SyncConfig>();+ .typ::<sync::SyncConfig>()+ .typ::<obsidian_sync::ObsidianSyncSettings>()+ .typ::<obsidian_sync::ObsidianSyncStatus>();builder.export(@@ -838,6 +848,7 @@ async fn main() {let sidecar_state = SidecarState(Arc::new(tokio::sync::Mutex::new(None)));let sidecar_state_for_init = sidecar_state.0.clone(); // Clone for initial spawnlet opencode_state = opencode::OpencodeState(Arc::new(tokio::sync::Mutex::new(None)));+ let obsidian_sync_state = obsidian_sync::ObsidianSyncState::new();#[allow(clippy::single_match)]let app = tauri::Builder::default().plugin(tauri_plugin_opener::init())@@ -890,6 +901,7 @@ async fn main() {let app = app.manage(sidecar_state).manage(opencode_state)+ .manage(obsidian_sync_state).invoke_handler(tauri::generate_handler![spawn_screenpipe,stop_screenpipe,@@ -950,7 +962,14 @@ async fn main() {opencode::opencode_start,opencode::opencode_stop,opencode::opencode_check,- opencode::opencode_install+ opencode::opencode_install,+ // Obsidian Sync commands+ obsidian_sync::obsidian_validate_vault,+ obsidian_sync::obsidian_get_vault_paths,+ obsidian_sync::obsidian_get_sync_status,+ obsidian_sync::obsidian_run_sync,+ obsidian_sync::obsidian_start_scheduler,+ obsidian_sync::obsidian_stop_scheduler]).setup(move |app| {//deep link register_alldiff --git a/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rsnew file mode 100644index 000000000..356ca5600--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs@@ -0,0 +1,517 @@+//! Obsidian Sync Module+//!+//! Syncs screenpipe activity data to an Obsidian vault using opencode as the AI agent.+//! The agent queries screenpipe API in chunks and generates markdown summaries.++use serde::{Deserialize, Serialize};+use specta::Type;+use std::path::PathBuf;+use std::sync::Arc;+use tauri::{AppHandle, Emitter, Manager};+use tauri_plugin_shell::process::CommandEvent;+use tauri_plugin_shell::ShellExt;+use tokio::sync::Mutex;+use tracing::{debug, error, info, warn};++/// Obsidian sync settings stored in the app store+#[derive(Debug, Clone, Serialize, Deserialize, Type, Default)]+#[serde(rename_all = "camelCase")]+pub struct ObsidianSyncSettings {+ /// Whether sync is enabled+ pub enabled: bool,+ /// Path to the Obsidian vault+ pub vault_path: String,+ /// Sync interval in minutes (0 = manual only)+ pub sync_interval_minutes: u32,+ /// Custom user prompt to append to system prompt+ pub custom_prompt: String,+ /// Last successful sync timestamp (ISO 8601)+ pub last_sync_time: Option<String>,+ /// Number of hours to sync (how far back to look)+ pub sync_hours: u32,+}++/// Status of an ongoing or completed sync+#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct ObsidianSyncStatus {+ pub is_syncing: bool,+ pub last_sync_time: Option<String>,+ pub last_error: Option<String>,+ pub notes_created_today: u32,+}++impl Default for ObsidianSyncStatus {+ fn default() -> Self {+ Self {+ is_syncing: false,+ last_sync_time: None,+ last_error: None,+ notes_created_today: 0,+ }+ }+}++/// State for managing obsidian sync+pub struct ObsidianSyncState {+ pub status: Arc<Mutex<ObsidianSyncStatus>>,+ pub scheduler_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,+}++impl ObsidianSyncState {+ pub fn new() -> Self {+ Self {+ status: Arc::new(Mutex::new(ObsidianSyncStatus::default())),+ scheduler_handle: Arc::new(Mutex::new(None)),+ }+ }+}++/// System prompt for the opencode agent with screenpipe API docs+const SYSTEM_PROMPT: &str = r#"You are syncing screenpipe activity data to an Obsidian vault.++## Screenpipe API Reference++Base URL: http://localhost:3030++### Search Endpoint+```+GET /search+```++Query parameters:+- `content_type`: "ocr" | "audio" | "all" (default: all)+- `start_time`: ISO 8601 timestamp (e.g., 2025-02-01T10:00:00Z)+- `end_time`: ISO 8601 timestamp+- `limit`: max results per request (default: 50, max: 1000)+- `offset`: pagination offset++Example:+```bash+curl "http://localhost:3030/search?content_type=all&start_time=2025-02-01T10:00:00Z&end_time=2025-02-01T10:30:00Z&limit=200"+```++Response format:+```json+{+ "data": [+ {+ "type": "OCR",+ "content": {+ "frame_id": 123,+ "text": "screen text content...",+ "app_name": "Arc",+ "window_name": "GitHub - Pull Request",+ "timestamp": "2025-02-01T10:05:00Z"+ }+ },+ {+ "type": "Audio",+ "content": {+ "transcription": "spoken words...",+ "timestamp": "2025-02-01T10:05:30Z"+ }+ }+ ],+ "pagination": { "total": 500, "limit": 200, "offset": 0 }+}+```++## Your Task++1. Query the screenpipe API for the specified time range+2. Process data in 30-minute chunks to manage context size+3. For each chunk, summarize the key activities+4. Append summaries to the daily markdown log file+5. Create folders/files as needed++## Output Format++Create/append to the daily log file using this markdown table format:++```markdown+# Activity Log - YYYY-MM-DD++| Time | Activity | Apps | Tags |+|------|----------|------|------|+| 10:00-10:30 | Reviewed PR #123 for auth module | GitHub, VSCode | #coding #review |+| 10:30-11:00 | Call with team about roadmap | Zoom, Notion | #meeting #planning |+```++## Best Practices++- Link people names with [[Name]] (Obsidian wiki-links)+- Link projects/concepts with [[concept-name]]+- Keep summaries concise but capture key activities+- Group related activities together+- Include apps used for context+- Add semantic tags for easy filtering+- Skip idle periods or duplicates+- If no meaningful activity in a chunk, skip it or note "idle"++## Important++- Query in chunks to avoid context overflow+- Use curl to fetch data from the API+- Write files using the write tool+- Create the screenpipe/logs/ subfolder structure+"#;++/// Build the full prompt for opencode+fn build_prompt(settings: &ObsidianSyncSettings, start_time: &str, end_time: &str) -> String {+ let today = chrono::Utc::now().format("%Y-%m-%d").to_string();+ let note_path = format!(+ "{}/screenpipe/logs/{}.md",+ settings.vault_path.trim_end_matches('/'),+ today+ );++ let mut prompt = format!(+ r#"Sync my screenpipe activity to Obsidian.++Time range: {} to {}+Output file: {}++{}"#,+ start_time, end_time, note_path, SYSTEM_PROMPT+ );++ // Append user's custom prompt if provided+ if !settings.custom_prompt.is_empty() {+ prompt.push_str("\n\n## Additional Instructions from User\n\n");+ prompt.push_str(&settings.custom_prompt);+ }++ prompt+}++/// Validate that a path is a valid Obsidian vault (has .obsidian folder)+#[tauri::command]+#[specta::specta]+pub async fn obsidian_validate_vault(path: String) -> Result<bool, String> {+ let vault_path = PathBuf::from(&path);+ let obsidian_folder = vault_path.join(".obsidian");+ Ok(obsidian_folder.exists() && obsidian_folder.is_dir())+}++/// Get suggested Obsidian vault paths by scanning common locations+#[tauri::command]+#[specta::specta]+pub async fn obsidian_get_vault_paths() -> Result<Vec<String>, String> {+ let mut paths = Vec::new();++ // Common Obsidian vault locations+ if let Some(home) = dirs::home_dir() {+ let candidates = vec![home.join("Documents"), home.join("Obsidian"), home.clone()];++ for candidate in candidates {+ if let Ok(entries) = std::fs::read_dir(&candidate) {+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ let obsidian_folder = path.join(".obsidian");+ if obsidian_folder.exists() {+ if let Some(path_str) = path.to_str() {+ paths.push(path_str.to_string());+ }+ }+ }+ }+ }+ }+ }++ // Also check iCloud on macOS+ #[cfg(target_os = "macos")]+ if let Some(home) = dirs::home_dir() {+ let icloud_obsidian = home.join("Library/Mobile Documents/iCloud~md~obsidian/Documents");+ if let Ok(entries) = std::fs::read_dir(&icloud_obsidian) {+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ let obsidian_folder = path.join(".obsidian");+ if obsidian_folder.exists() {+ if let Some(path_str) = path.to_str() {+ paths.push(path_str.to_string());+ }+ }+ }+ }+ }+ }++ Ok(paths)+}++/// Get current sync status+#[tauri::command]+#[specta::specta]+pub async fn obsidian_get_sync_status(+ state: tauri::State<'_, ObsidianSyncState>,+) -> Result<ObsidianSyncStatus, String> {+ let status = state.status.lock().await;+ Ok(status.clone())+}++/// Run a sync operation (manual trigger or from scheduler)+#[tauri::command]+#[specta::specta]+pub async fn obsidian_run_sync(+ app: AppHandle,+ state: tauri::State<'_, ObsidianSyncState>,+ settings: ObsidianSyncSettings,+) -> Result<ObsidianSyncStatus, String> {+ // Check if already syncing+ {+ let status = state.status.lock().await;+ if status.is_syncing {+ return Err("Sync already in progress".to_string());+ }+ }++ // Validate vault path+ if settings.vault_path.is_empty() {+ return Err("Vault path not configured".to_string());+ }++ if !obsidian_validate_vault(settings.vault_path.clone()).await? {+ return Err("Invalid Obsidian vault path".to_string());+ }++ // Update status to syncing+ {+ let mut status = state.status.lock().await;+ status.is_syncing = true;+ status.last_error = None;+ }++ // Emit event for UI+ let _ = app.emit("obsidian_sync_started", ());++ // Calculate time range+ let end_time = chrono::Utc::now();+ let start_time = end_time - chrono::Duration::hours(settings.sync_hours as i64);+ let start_time_str = start_time.to_rfc3339();+ let end_time_str = end_time.to_rfc3339();++ // Build prompt+ let prompt = build_prompt(&settings, &start_time_str, &end_time_str);++ // Run opencode+ let result = run_opencode_sync(&app, &prompt).await;++ // Update status based on result+ {+ let mut status = state.status.lock().await;+ status.is_syncing = false;++ match &result {+ Ok(_) => {+ status.last_sync_time = Some(chrono::Utc::now().to_rfc3339());+ status.last_error = None;+ status.notes_created_today += 1;+ let _ = app.emit("obsidian_sync_completed", status.clone());+ }+ Err(e) => {+ status.last_error = Some(e.clone());+ let _ = app.emit("obsidian_sync_error", e.clone());+ }+ }+ }++ let status = state.status.lock().await;+ result.map(|_| status.clone())+}++/// Internal function to run opencode with the sync prompt+async fn run_opencode_sync(app: &AppHandle, prompt: &str) -> Result<(), String> {+ info!("Starting obsidian sync with opencode");++ // Try sidecar first, then PATH+ let shell = app.shell();+ let cmd_result = shell.sidecar("opencode");++ let (mut rx, _child) = match cmd_result {+ Ok(cmd) => {+ // Use sidecar with prompt as argument+ cmd.args(&["-p", prompt, "--no-input"])+ .spawn()+ .map_err(|e| format!("Failed to spawn opencode: {}", e))?+ }+ Err(_) => {+ // Try PATH+ shell+ .command("opencode")+ .args(&["-p", prompt, "--no-input"])+ .spawn()+ .map_err(|e| format!("Failed to spawn opencode from PATH: {}", e))?+ }+ };++ // Collect output+ let mut stdout_lines = Vec::new();+ let mut stderr_lines = Vec::new();+ let mut exit_code = None;++ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line) => {+ let text = String::from_utf8_lossy(&line).to_string();+ debug!("opencode stdout: {}", text);+ stdout_lines.push(text);+ }+ CommandEvent::Stderr(line) => {+ let text = String::from_utf8_lossy(&line).to_string();+ debug!("opencode stderr: {}", text);+ stderr_lines.push(text);+ }+ CommandEvent::Terminated(payload) => {+ exit_code = payload.code;+ break;+ }+ CommandEvent::Error(e) => {+ error!("opencode error: {}", e);+ return Err(format!("Opencode error: {}", e));+ }+ _ => {}+ }+ }++ match exit_code {+ Some(0) => {+ info!("Obsidian sync completed successfully");+ Ok(())+ }+ Some(code) => {+ let error_msg = if !stderr_lines.is_empty() {+ stderr_lines.join("\n")+ } else {+ format!("Opencode exited with code {}", code)+ };+ error!("Obsidian sync failed: {}", error_msg);+ Err(error_msg)+ }+ None => Err("Opencode terminated without exit code".to_string()),+ }+}++/// Start the background scheduler for periodic syncs+#[tauri::command]+#[specta::specta]+pub async fn obsidian_start_scheduler(+ app: AppHandle,+ state: tauri::State<'_, ObsidianSyncState>,+ settings: ObsidianSyncSettings,+) -> Result<(), String> {+ // Stop existing scheduler if any+ obsidian_stop_scheduler(state.clone()).await?;++ if !settings.enabled || settings.sync_interval_minutes == 0 {+ info!("Obsidian sync scheduler not started (disabled or interval=0)");+ return Ok(());+ }++ let interval_mins = settings.sync_interval_minutes;+ let settings_clone = settings.clone();+ let status_arc = state.status.clone();+ let app_handle = app.clone();++ info!(+ "Starting obsidian sync scheduler with {}min interval",+ interval_mins+ );++ let handle = tokio::spawn(async move {+ let mut interval =+ tokio::time::interval(tokio::time::Duration::from_secs(interval_mins as u64 * 60));++ // Skip the first tick (immediate)+ interval.tick().await;++ loop {+ interval.tick().await;++ // Check if we should sync+ {+ let status = status_arc.lock().await;+ if status.is_syncing {+ debug!("Skipping scheduled sync - already syncing");+ continue;+ }+ }++ info!("Running scheduled obsidian sync");++ // Run sync (we can't use the command directly, so replicate the logic)+ let result = run_scheduled_sync(&app_handle, &settings_clone, &status_arc).await;++ if let Err(e) = result {+ warn!("Scheduled obsidian sync failed: {}", e);+ }+ }+ });++ // Store the handle+ let mut scheduler_handle = state.scheduler_handle.lock().await;+ *scheduler_handle = Some(handle);++ Ok(())+}++/// Stop the background scheduler+#[tauri::command]+#[specta::specta]+pub async fn obsidian_stop_scheduler(+ state: tauri::State<'_, ObsidianSyncState>,+) -> Result<(), String> {+ let mut handle = state.scheduler_handle.lock().await;+ if let Some(h) = handle.take() {+ h.abort();+ info!("Obsidian sync scheduler stopped");+ }+ Ok(())+}++/// Internal function to run a scheduled sync+async fn run_scheduled_sync(+ app: &AppHandle,+ settings: &ObsidianSyncSettings,+ status: &Arc<Mutex<ObsidianSyncStatus>>,+) -> Result<(), String> {+ // Update status+ {+ let mut s = status.lock().await;+ s.is_syncing = true;+ s.last_error = None;+ }++ let _ = app.emit("obsidian_sync_started", ());++ // Calculate time range+ let end_time = chrono::Utc::now();+ let start_time = end_time - chrono::Duration::hours(settings.sync_hours as i64);++ let prompt = build_prompt(settings, &start_time.to_rfc3339(), &end_time.to_rfc3339());+ let result = run_opencode_sync(app, &prompt).await;++ // Update status+ {+ let mut s = status.lock().await;+ s.is_syncing = false;++ match &result {+ Ok(_) => {+ s.last_sync_time = Some(chrono::Utc::now().to_rfc3339());+ s.last_error = None;+ s.notes_created_today += 1;+ let _ = app.emit("obsidian_sync_completed", s.clone());+ }+ Err(e) => {+ s.last_error = Some(e.clone());+ let _ = app.emit("obsidian_sync_error", e.clone());+ }+ }+ }++ result+}