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

Bump app to v2.0.566

Louis Beaumont967deeb043d0
diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
index c8054c460..0470ee33e 100644
--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx
@@ -14,7 +14,6 @@ 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 { join, homeDir } from "@tauri-apps/api/path";
-import { ObsidianSyncCard } from "./obsidian-sync-card";
import { AppleIntelligenceCard } from "./apple-intelligence-card";
import { CalendarCard } from "./calendar-card";
import { GoogleCalendarCard } from "./google-calendar-card";
@@ -622,9 +621,6 @@ export function ConnectionsSection() {
{/* Google Calendar (cloud) */}
<GoogleCalendarCard />
- {/* Obsidian Sync */}
- <ObsidianSyncCard />
-
{/* Docs link */}
<button
onClick={() => openUrl("https://docs.screenpi.pe")}
diff --git a/apps/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx b/apps/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx
deleted file mode 100644
index 44263c870..000000000
--- a/apps/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx
+++ /dev/null
@@ -1,766 +0,0 @@
-"use client";
-
-import React, { useState, useEffect, useCallback } from "react";
-import { commands } from "@/lib/utils/tauri";
-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,
- ExternalLink,
- X,
-} from "lucide-react";
-
-// Official Obsidian logo SVG
-const ObsidianLogo = ({ className }: { className?: string }) => (
- <svg
- viewBox="0 0 65 100"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- className={className}
- >
- <path
- d="M46.3815 1.64838C45.2519 0.813498 43.7845 0.584108 42.4545 1.03483L3.24014 14.5801C1.49498 15.1697 0.326172 16.8207 0.326172 18.6635V62.5907C0.326172 63.9128 0.939877 65.1578 1.98099 65.9521L19.3133 79.1764L43.8598 98.2123C44.8174 98.9549 46.0419 99.2481 47.2303 99.0186L61.4684 96.1592C63.2723 95.7962 64.6211 94.2257 64.6738 92.3817L65.3262 28.3912C65.3519 26.2187 64.0954 24.2459 62.1038 23.3874L46.3815 1.64838Z"
- fill="url(#paint0_linear)"
- />
- <path
- d="M46.3815 1.64838C45.2519 0.813498 43.7845 0.584108 42.4545 1.03483L3.24014 14.5801C1.49498 15.1697 0.326172 16.8207 0.326172 18.6635V62.5907C0.326172 63.9128 0.939877 65.1578 1.98099 65.9521L19.3133 79.1764L43.8598 98.2123C44.8174 98.9549 46.0419 99.2481 47.2303 99.0186L61.4684 96.1592C63.2723 95.7962 64.6211 94.2257 64.6738 92.3817L65.3262 28.3912C65.3519 26.2187 64.0954 24.2459 62.1038 23.3874L46.3815 1.64838Z"
- fill="url(#paint1_radial)"
- fillOpacity="0.5"
- />
- <path
- d="M19.5464 79.4006L2.03852 65.7962C1.05533 65.0455 0.475586 63.8721 0.475586 62.6279V18.5625C0.475586 16.6254 1.74092 14.913 3.60033 14.3312L42.4771 1.03483C43.7845 0.584108 45.2519 0.813498 46.3815 1.64838L62.1038 23.3874C64.0954 24.2459 65.3519 26.2187 65.3262 28.3912L64.6738 92.3817C64.6211 94.2257 63.2723 95.7962 61.4684 96.1592L47.2303 99.0186C46.0419 99.2481 44.8174 98.9549 43.8598 98.2123L19.5464 79.4006Z"
- stroke="url(#paint2_linear)"
- strokeWidth="0.5"
- />
- <path
- d="M39.0728 36.9812L25.2818 62.8318C24.6506 63.9804 25.0839 65.4298 26.2325 66.061L43.2024 75.7139C44.3509 76.3451 45.8004 75.9118 46.4316 74.7632L60.2226 48.9126C60.8538 47.764 60.4205 46.3146 59.2719 45.6834L42.302 36.0305C41.1534 35.3993 39.704 35.8326 39.0728 36.9812Z"
- fill="#9A8AFF"
- />
- <path
- d="M19.3133 79.1764L1.98099 65.9521C0.939877 65.1578 0.326172 63.9128 0.326172 62.5907V18.6635L24.4687 63.6587L19.3133 79.1764Z"
- fill="url(#paint3_linear)"
- />
- <path
- d="M24.4687 63.6587L0.326172 18.6635C0.326172 16.8207 1.49498 15.1697 3.24014 14.5801L42.4545 1.03483L24.4687 63.6587Z"
- fill="url(#paint4_linear)"
- />
- <path
- d="M42.4545 1.03483L46.3815 1.64838L62.1038 23.3874L24.4687 63.6587L42.4545 1.03483Z"
- fill="url(#paint5_linear)"
- />
- <path
- d="M62.1038 23.3874C64.0954 24.2459 65.3519 26.2187 65.3262 28.3912L64.6738 92.3817L24.4687 63.6587L62.1038 23.3874Z"
- fill="url(#paint6_linear)"
- />
- <path
- d="M64.6738 92.3817C64.6211 94.2257 63.2723 95.7962 61.4684 96.1592L47.2303 99.0186C46.0419 99.2481 44.8174 98.9549 43.8598 98.2123L19.3133 79.1764L24.4687 63.6587L64.6738 92.3817Z"
- fill="url(#paint7_linear)"
- />
- <defs>
- <linearGradient id="paint0_linear" x1="32.8262" y1="0.695312" x2="32.8262" y2="99.1953" gradientUnits="userSpaceOnUse">
- <stop stopColor="#6C56CC"/>
- <stop offset="1" stopColor="#9785E5"/>
- </linearGradient>
- <radialGradient id="paint1_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(32.8262 49.9453) scale(49.1504 49.1504)">
- <stop stopColor="white"/>
- <stop offset="1" stopColor="white" stopOpacity="0"/>
- </radialGradient>
- <linearGradient id="paint2_linear" x1="0.225586" y1="49.9453" x2="65.5762" y2="49.9453" gradientUnits="userSpaceOnUse">
- <stop stopColor="#6C56CC"/>
- <stop offset="1" stopColor="#9785E5"/>
- </linearGradient>
- <linearGradient id="paint3_linear" x1="12.3974" y1="18.6635" x2="12.3974" y2="79.1764" gradientUnits="userSpaceOnUse">
- <stop stopColor="#6C56CC"/>
- <stop offset="1" stopColor="#4A3A9E"/>
- </linearGradient>
- <linearGradient id="paint4_linear" x1="21.3903" y1="1.03483" x2="21.3903" y2="63.6587" gradientUnits="userSpaceOnUse">
- <stop stopColor="#9785E5"/>
- <stop offset="1" stopColor="#6C56CC"/>
- </linearGradient>
- <linearGradient id="paint5_linear" x1="43.2862" y1="1.03483" x2="43.2862" y2="63.6587" gradientUnits="userSpaceOnUse">
- <stop stopColor="#6C56CC"/>
- <stop offset="1" stopColor="#4A3A9E"/>
- </linearGradient>
- <linearGradient id="paint6_linear" x1="44.8974" y1="23.3874" x2="44.8974" y2="92.3817" gradientUnits="userSpaceOnUse">
- <stop stopColor="#9785E5"/>
- <stop offset="1" stopColor="#6C56CC"/>
- </linearGradient>
- <linearGradient id="paint7_linear" x1="42.0" y1="63.6587" x2="42.0" y2="99.1953" gradientUnits="userSpaceOnUse">
- <stop stopColor="#6C56CC"/>
- <stop offset="1" stopColor="#4A3A9E"/>
- </linearGradient>
- </defs>
- </svg>
-);
-import { invoke } from "@tauri-apps/api/core";
-import { listen } from "@tauri-apps/api/event";
-import { open as openDialog } from "@tauri-apps/plugin-dialog";
-import { Command } 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;
- notesPath: string; // Subfolder within vault for notes (e.g., "screenpipe/logs" or "daily/activity")
- syncIntervalMinutes: number;
- customPrompt: string;
- lastSyncTime: string | null;
- syncHours: number;
-}
-
-interface ObsidianSyncStatus {
- isSyncing: boolean;
- lastSyncTime: string | null;
- lastError: string | null;
- notesCreatedToday: number;
- nextScheduledRun: string | null;
-}
-
-interface SyncHistoryEntry {
- timestamp: string;
- status: "success" | "error";
- error?: string;
-}
-
-const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; // e.g. "America/New_York"
-
-const DEFAULT_CUSTOM_PROMPT = `timezone: ${userTimezone}
-focus areas: work, coding, meetings
-my projects: [[Project A]], [[Project B]]
-embed video clips for meetings using absolute file paths
-tag people I talk to frequently: [[Alice]], [[Bob]]`;
-
-const DEFAULT_SETTINGS: ObsidianSyncSettings = {
- enabled: false,
- vaultPath: "",
- notesPath: "screenpipe/logs", // Default subfolder
- syncIntervalMinutes: 0, // 0 = manual only
- customPrompt: DEFAULT_CUSTOM_PROMPT,
- 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,
- nextScheduledRun: null,
- });
- const [suggestedPaths, setSuggestedPaths] = useState<string[]>([]);
- const [isValidVault, setIsValidVault] = useState<boolean | null>(null);
- const [isValidating, setIsValidating] = useState(false);
- const [isExpanded, setIsExpanded] = useState(false);
- const [settingsLoaded, setSettingsLoaded] = useState(false);
- const [syncHistory, setSyncHistory] = useState<SyncHistoryEntry[]>([]);
-
- // Load settings from localStorage on mount
- useEffect(() => {
- let saved: string | null = null;
- try { saved = localStorage?.getItem("obsidian-sync-settings"); } catch {}
- if (saved) {
- try {
- const parsed = JSON.parse(saved);
- // Preserve pre-filled custom prompt for existing users who never set one
- if (!parsed.customPrompt) {
- parsed.customPrompt = DEFAULT_CUSTOM_PROMPT;
- }
- setSettings({ ...DEFAULT_SETTINGS, ...parsed });
- } catch (e) {
- console.error("Failed to parse obsidian settings:", e);
- }
- }
- setSettingsLoaded(true);
-
- // Load sync history
- let savedHistory: string | null = null;
- try { savedHistory = localStorage?.getItem("obsidian-sync-history"); } catch {}
- if (savedHistory) {
- try {
- setSyncHistory(JSON.parse(savedHistory).slice(0, 10)); // Keep last 10
- } catch (e) {
- console.error("Failed to parse sync history:", e);
- }
- }
-
- // Fetch suggested vault paths
- fetchVaultPaths();
-
- // Get initial status
- fetchStatus();
- }, []);
-
- // Periodically refresh status to update "next run" countdown
- useEffect(() => {
- if (!settings.enabled) return;
-
- const interval = setInterval(() => {
- fetchStatus();
- }, 30000); // Refresh every 30 seconds
-
- return () => clearInterval(interval);
- }, [settings.enabled]);
-
- // Save settings to localStorage immediately
- useEffect(() => {
- if (settingsLoaded) {
- try { localStorage?.setItem("obsidian-sync-settings", JSON.stringify(settings)); } catch {}
- }
- }, [settings, settingsLoaded]);
-
- // Debounced save to Rust store (just persist, don't restart scheduler)
- useEffect(() => {
- if (!settingsLoaded) return;
-
- const timeoutId = setTimeout(() => {
- // Save to Rust store for persistence across app restarts
- invoke("obsidian_save_settings", { settings }).catch((e) => {
- console.error("Failed to save obsidian settings to store:", e);
- });
- }, 1000); // 1 second debounce
-
- return () => clearTimeout(timeoutId);
- }, [settings, settingsLoaded]);
-
- // Only restart scheduler when interval changes via user action (not on initial load)
- const prevIntervalRef = React.useRef<number | null>(null);
- const prevEnabledRef = React.useRef<boolean | null>(null);
- const isInitialLoadRef = React.useRef(true);
-
- useEffect(() => {
- if (!settingsLoaded) return;
-
- // Skip the first render after settings are loaded from localStorage
- // to avoid killing the auto-started scheduler from Rust
- if (isInitialLoadRef.current) {
- isInitialLoadRef.current = false;
- prevIntervalRef.current = settings.syncIntervalMinutes;
- prevEnabledRef.current = settings.enabled;
- return;
- }
-
- const intervalChanged = prevIntervalRef.current !== settings.syncIntervalMinutes;
- const enabledChanged = prevEnabledRef.current !== settings.enabled;
-
- prevIntervalRef.current = settings.syncIntervalMinutes;
- prevEnabledRef.current = settings.enabled;
-
- // Only restart if interval or enabled status changed by user action
- if ((intervalChanged || enabledChanged) && settings.enabled && settings.vaultPath && settings.syncIntervalMinutes > 0 && appSettings?.user?.token) {
- invoke("obsidian_start_scheduler", {
- settings,
- userToken: appSettings.user.token
- }).catch((e) => {
- console.error("Failed to restart scheduler:", e);
- });
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [settings.syncIntervalMinutes, settings.enabled, settingsLoaded, isValidVault, appSettings?.user?.token]);
-
- // Validate vault path when it changes
- useEffect(() => {
- if (settings.vaultPath) {
- validateVault(settings.vaultPath);
- } else {
- setIsValidVault(null);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [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);
- // Add to history
- const newEntry: SyncHistoryEntry = { timestamp: new Date().toISOString(), status: "success" };
- setSyncHistory(prev => {
- const updated = [newEntry, ...prev].slice(0, 10);
- try { localStorage?.setItem("obsidian-sync-history", JSON.stringify(updated)); } catch {}
- return updated;
- });
- 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,
- }));
- // Add to history
- const newEntry: SyncHistoryEntry = { timestamp: new Date().toISOString(), status: "error", error: event.payload };
- setSyncHistory(prev => {
- const updated = [newEntry, ...prev].slice(0, 10);
- try { localStorage?.setItem("obsidian-sync-history", JSON.stringify(updated)); } catch {}
- return updated;
- });
- 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 Notes Folder",
- });
- if (selected && typeof selected === "string") {
- setSettings((s) => ({ ...s, vaultPath: selected }));
- }
- } catch (e) {
- console.error("Failed to open dialog:", e);
- }
- };
-
- const handleSync = async () => {
- if (!settings.vaultPath) {
- toast({
- variant: "destructive",
- title: "No folder selected",
- description: "Please select a folder 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;
- }
-
- console.log("obsidian sync: token present, length:", appSettings.user.token.length);
-
- try {
- await invoke("obsidian_run_sync", { settings, userToken: appSettings.user.token });
- } catch (e) {
- console.error("Failed to run sync:", e);
- toast({
- variant: "destructive",
- title: "Sync failed",
- description: String(e),
- });
- }
- };
-
- const handleCancel = async () => {
- try {
- await invoke("obsidian_cancel_sync");
- } catch (e) {
- console.error("Failed to cancel sync:", e);
- }
- };
-
- const handleEnableScheduler = async () => {
- if (!settings.vaultPath || settings.syncIntervalMinutes === 0) {
- return;
- }
-
- try {
- const newSettings = { ...settings, enabled: true };
- setSettings(newSettings);
- await invoke("obsidian_start_scheduler", { settings: newSettings, userToken: appSettings?.user?.token });
- 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;
-
- try {
- // Read Obsidian's vault registry to find the correct vault name
- const { homeDir } = await import("@tauri-apps/api/path");
- const { readTextFile } = await import("@tauri-apps/plugin-fs");
-
- const home = await homeDir();
- const { platform } = await import("@tauri-apps/plugin-os");
- const os = platform();
- const obsidianConfigPath = os === "windows"
- ? `${home}AppData\\Roaming\\obsidian\\obsidian.json`
- : `${home}Library/Application Support/obsidian/obsidian.json`;
-
- let vaultName: string | null = null;
-
- try {
- const configContent = await readTextFile(obsidianConfigPath);
- const config = JSON.parse(configContent);
-
- // Find vault that matches our path
- for (const [_id, vault] of Object.entries(config.vaults || {})) {
- const v = vault as { path: string };
- if (v.path === settings.vaultPath) {
- // Extract vault name from path
- vaultName = settings.vaultPath.split("/").pop() || null;
- break;
- }
- }
- } catch (e) {
- console.warn("Could not read Obsidian config:", e);
- }
-
- // Use vault name if found, otherwise just open Obsidian app
- const deepLink = vaultName
- ? `obsidian://open?vault=${encodeURIComponent(vaultName)}`
- : "obsidian://";
-
- const command = os === "windows"
- ? Command.create("cmd", ["/c", "start", "", deepLink])
- : Command.create("open", [deepLink]);
- await command.execute();
-
- if (!vaultName) {
- toast({
- title: "Opened Obsidian",
- description: "Vault not found in Obsidian registry. You may need to open it manually.",
- });
- }
- } catch (e) {
- console.error("Failed to open Obsidian:", e);
- toast({
- variant: "destructive",
- title: "Failed to open Obsidian",
- description: "Make sure Obsidian is installed",
- });
- }
- };
-
- 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 formatNextRun = (isoTime: string | null) => {
- if (!isoTime) return null;
-
- const date = new Date(isoTime);
- const now = new Date();
- const diffMs = date.getTime() - now.getTime();
-
- if (diffMs <= 0) return "any moment";
-
- const diffMins = Math.floor(diffMs / 60000);
- if (diffMins < 1) return "< 1 min";
- if (diffMins < 60) return `${diffMins} min`;
- const diffHours = Math.floor(diffMins / 60);
- const remainingMins = diffMins % 60;
- if (diffHours < 24) {
- return remainingMins > 0 ? `${diffHours}h ${remainingMins}m` : `${diffHours}h`;
- }
- return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- };
-
- const isLoggedIn = Boolean(appSettings?.user?.token);
- const isSubscribed = Boolean(appSettings?.user?.cloud_subscribed);
-
- return (
- <Card className="border-border bg-card overflow-hidden">
- <CardContent className="p-0">
- <div className="flex items-start p-4 gap-4">
- {/* Obsidian Logo */}
- <div className="flex-shrink-0">
- <div className="w-10 h-10 rounded-xl flex items-center justify-center">
- <ObsidianLogo className="w-7 h-10" />
- </div>
- </div>
-
- {/* Content */}
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 mb-1">
- <h3 className="text-sm font-semibold text-foreground">
- Obsidian Sync
- </h3>
- {settings.enabled && (
- <span className="px-1.5 py-0.5 text-[10px] font-medium bg-foreground/10 text-foreground rounded-full">
- ● auto
- </span>
- )}
- </div>
- <p className="text-xs text-muted-foreground mb-3">
- Sync screen activity to markdown notes. Powered by Claude AI.
- </p>
-
- {!isLoggedIn && (
- <Button
- variant="outline"
- size="sm"
- className="text-xs gap-1.5 h-7 mb-2"
- onClick={() => commands.openLoginWindow()}
- >
- <AlertCircle className="h-3 w-3" />
- login to use
- </Button>
- )}
-
- <div className="flex flex-wrap gap-2">
- <Button onClick={() => setIsExpanded(!isExpanded)} variant="outline" size="sm" className="gap-1.5 h-7 text-xs">
- {isExpanded ? "Hide" : "Configure"}
- </Button>
-
- {status.isSyncing ? (
- <Button onClick={handleCancel} variant="outline" size="sm" className="gap-1.5 h-7 text-xs">
- <X className="h-3 w-3" />Cancel
- </Button>
- ) : (
- <Button onClick={handleSync} disabled={!settings.vaultPath || !isLoggedIn} size="sm" className="gap-1.5 h-7 text-xs">
- <RefreshCw className="h-3 w-3" />Sync Now
- </Button>
- )}
-
- {settings.vaultPath && isValidVault && (
- <Button variant="outline" onClick={openObsidian} size="sm" className="gap-1.5 h-7 text-xs">
- <ExternalLink className="h-3 w-3" />Open
- </Button>
- )}
- </div>
- </div>
- </div>
-
- {/* Expanded Settings */}
- {isExpanded && (
- <div className="px-4 pb-4 space-y-3 border-t border-border pt-3">
- {/* Vault Path */}
- <div className="space-y-1.5">
- <Label htmlFor="vault-path" className="text-xs font-medium">Notes folder</Label>
- <div className="flex gap-1.5">
- <div className="flex-1 relative">
- <Input id="vault-path" value={settings.vaultPath} onChange={(e) => setSettings((s) => ({ ...s, vaultPath: e.target.value }))} placeholder="/path/to/folder" className={`h-7 text-xs ${isValidVault === true ? "border-green-500" : ""}`} />
- {isValidating && <Loader2 className="absolute right-2 top-1.5 h-3 w-3 animate-spin text-muted-foreground" />}
- </div>
- <Button type="button" variant="outline" onClick={handleBrowse} size="sm" className="h-7 w-7 p-0">
- <FolderOpen className="h-3 w-3" />
- </Button>
- </div>
- {isValidVault === true && <p className="text-[11px] text-green-500"><Check className="h-2.5 w-2.5 inline mr-0.5" />Obsidian vault detected</p>}
- {isValidVault === false && settings.vaultPath && <p className="text-[11px] text-muted-foreground"><Check className="h-2.5 w-2.5 inline mr-0.5" />Folder OK (not an Obsidian vault)</p>}
- {suggestedPaths.length > 0 && (
- <div className="flex flex-wrap gap-1 mt-1">
- {suggestedPaths.map((path) => (
- <Badge key={path} variant="outline" className="cursor-pointer hover:bg-muted text-[10px] h-5" onClick={() => setSettings((s) => ({ ...s, vaultPath: path }))}>
- {path.split("/").pop()}
- </Badge>
- ))}
- </div>
- )}
- </div>
-
- {/* Notes subfolder */}
- <div className="space-y-1.5">
- <Label htmlFor="notes-path" className="text-xs font-medium">Subfolder</Label>
- <Input id="notes-path" value={settings.notesPath} onChange={(e) => setSettings((s) => ({ ...s, notesPath: e.target.value }))} placeholder="screenpipe/logs" className="h-7 text-xs" />
- </div>
-
- {/* Sync Hours + Interval in a row */}
- <div className="grid grid-cols-2 gap-2">
- <div className="space-y-1.5">
- <Label className="text-xs font-medium">Hours to sync</Label>
- <Select value={String(settings.syncHours)} onValueChange={(v) => setSettings((s) => ({ ...s, syncHours: parseInt(v) }))}>
- <SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="1">Last 1h</SelectItem>
- <SelectItem value="2">Last 2h</SelectItem>
- <SelectItem value="4">Last 4h</SelectItem>
- <SelectItem value="8">Last 8h</SelectItem>
- <SelectItem value="24">Last 24h</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <div className="space-y-1.5">
- <Label className="text-xs font-medium">Auto-sync</Label>
- <div className="flex gap-1.5">
- <Select value={String(settings.syncIntervalMinutes)} onValueChange={(v) => setSettings((s) => ({ ...s, syncIntervalMinutes: parseInt(v) }))}>
- <SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="0">Manual</SelectItem>
- <SelectItem value="15">15 min</SelectItem>
- <SelectItem value="30">30 min</SelectItem>
- <SelectItem value="60">1 hour</SelectItem>
- <SelectItem value="120">2 hours</SelectItem>
- </SelectContent>
- </Select>
- {settings.syncIntervalMinutes > 0 && (
- <Button variant={settings.enabled ? "destructive" : "default"} size="sm" className="h-7 text-xs px-2" onClick={settings.enabled ? handleDisableScheduler : handleEnableScheduler} disabled={!settings.vaultPath || !isLoggedIn}>
- {settings.enabled ? "Stop" : "Start"}
- </Button>
- )}
- </div>
- </div>
- </div>
-
- {/* Custom Prompt */}
- <div className="space-y-1.5">
- <Label htmlFor="custom-prompt" className="text-xs font-medium">Custom instructions</Label>
- <Textarea id="custom-prompt" value={settings.customPrompt} onChange={(e) => setSettings((s) => ({ ...s, customPrompt: e.target.value }))} rows={4} className="text-xs" />
- </div>
- </div>
- )}
-
- {/* Rate limit / upgrade banner */}
- {status.lastError && (status.lastError.includes("429") || status.lastError.includes("rate limit")) && (
- <div className="px-4 py-2 border-t border-border bg-muted/50">
- <div className="flex items-center justify-between gap-2">
- <p className="text-xs text-muted-foreground">
- <AlertCircle className="h-3 w-3 inline mr-1" />
- {isSubscribed
- ? "usage limit reached · retrying shortly"
- : isLoggedIn
- ? "usage limit reached · upgrade for higher limits"
- : "usage limit reached · sign in for 2x more"}
- </p>
- {!isSubscribed && (
- <Button
- variant="outline"
- size="sm"
- className="text-xs h-6 gap-1"
- onClick={async () => {
- if (isLoggedIn) {
- const { openUrl } = await import("@tauri-apps/plugin-opener");
- await openUrl("https://screenpi.pe/pricing");
- } else {
- await commands.openLoginWindow();
- }
- }}
- >
- {isLoggedIn ? "upgrade" : "sign in"}
- </Button>
- )}
- </div>
- </div>
- )}
-
- {/* Status Bar */}
- <div className="px-4 py-2 bg-muted/50 border-t border-border">
- <div className="flex items-center gap-3 text-xs text-muted-foreground flex-wrap">
- <span>Last: <span className="text-foreground">{formatLastSync(status.lastSyncTime ?? syncHistory[0]?.timestamp ?? null)}</span></span>
- {settings.enabled && status.nextScheduledRun && (
- <span className="flex items-center gap-0.5"><Clock className="h-2.5 w-2.5" />Next: <span className="text-foreground">{formatNextRun(status.nextScheduledRun)}</span></span>
- )}
- {syncHistory.length > 0 && syncHistory.slice(0, 5).map((entry, i) => {
- const d = new Date(entry.timestamp);
- const isToday = d.toDateString() === new Date().toDateString();
- const timeStr = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- const dateStr = d.toLocaleDateString([], { month: 'short', day: 'numeric' });
- const fullStr = d.toLocaleString();
- return (
- <span key={i} className="px-1 py-0.5 rounded bg-muted text-[10px] cursor-default" title={`${fullStr}${entry.error ? ` — ${entry.error}` : ""}`}>
- {isToday ? timeStr : `${dateStr} ${timeStr}`}{entry.status === "success" ? " ✓" : " ✗"}
- </span>
- );
- })}
- </div>
- </div>
- </CardContent>
- </Card>
- );
-}
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 068ea30f0..6b652ecb4 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1036,23 +1036,50 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
(async () => {
if (piInfo?.running) {
try {
+ // Abort any in-flight message, then reset session
+ if (piMessageIdRef.current) {
+ await commands.piAbort();
+ }
await commands.piNewSession();
} catch (e) {
console.warn("[Pi] Failed to reset session:", e);
}
}
+ // Clear all streaming state so sendPiMessage doesn't think a message is in-flight
+ piStreamingTextRef.current = "";
+ piMessageIdRef.current = null;
+ piContentBlocksRef.current = [];
+ setIsLoading(false);
+ setIsStreaming(false);
setMessages([]);
setConversationId(null);
setPrefillContext(null);
setPrefillFrameId(null);
// Set input as fallback in case auto-send fails (pi not ready)
setInput(fullMessage);
- // Try to auto-send after state settles
- setTimeout(() => {
- if (sendMessageRef.current) {
- sendMessageRef.current(fullMessage);
+ // Wait for Pi to be ready before sending (poll up to 10s)
+ const waitForPi = async (maxMs: number): Promise<boolean> => {
+ const start = Date.now();
+ while (Date.now() - start < maxMs) {
+ try {
+ const info = await commands.piInfo();
+ if (info.status === "ok" && info.data.running) {
+ // Update React state so canChat becomes true before we send
+ setPiInfo(info.data);
+ return true;
+ }
+ } catch {}
+ await new Promise(r => setTimeout(r, 500));
}
- }, 500);
+ return false;
+ };
+ const ready = piInfo?.running || await waitForPi(10000);
+ if (ready) {
+ // Give React one tick to re-render with updated piInfo so sendMessage's canChat is true
+ setTimeout(() => {
+ sendMessageRef.current?.(fullMessage);
+ }, 300);
+ }
})();
return;
}
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index e8e2ab68b..c4ceb5fd1 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -572,94 +572,6 @@ async piNewSession() : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
-/**
- * Save obsidian settings to persistent store (called when settings change)
- */
-async obsidianSaveSettings(settings: ObsidianSyncSettings) : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_save_settings", { settings }) };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Validate that a path is a valid Obsidian vault (has .obsidian folder)
- */
-async obsidianValidateVault(path: string) : Promise<Result<boolean, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_validate_vault", { path }) };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Get suggested Obsidian vault paths by scanning common locations
- */
-async obsidianGetVaultPaths() : Promise<Result<string[], string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_get_vault_paths") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Get current sync status
- */
-async obsidianGetSyncStatus() : Promise<Result<ObsidianSyncStatus, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_get_sync_status") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Run a sync operation (manual trigger or from scheduler)
- */
-async obsidianRunSync(settings: ObsidianSyncSettings, userToken: string | null) : Promise<Result<ObsidianSyncStatus, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_run_sync", { settings, userToken }) };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Start the background scheduler for periodic syncs
- */
-async obsidianStartScheduler(settings: ObsidianSyncSettings, userToken: string | null) : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_start_scheduler", { settings, userToken }) };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Stop the background scheduler
- */
-async obsidianStopScheduler() : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_stop_scheduler") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
-/**
- * Cancel the currently running sync
- */
-async obsidianCancelSync() : Promise<Result<null, string>> {
- try {
- return { status: "ok", data: await TAURI_INVOKE("obsidian_cancel_sync") };
-} catch (e) {
- if(e instanceof Error) throw e;
- else return { status: "error", error: e as any };
-}
-},
/**
* Check Reminders authorization + scheduler status (no popup).
*/
@@ -906,46 +818,6 @@ export type MonitorDevice = { id: number; stableId: string; name: string; isDefa
export type OSPermission = "screenRecording" | "microphone" | "accessibility" | "automation"
export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; accessibility: OSPermissionStatus }
-/**
- * Obsidian sync settings stored in the app store
- */
-export type ObsidianSyncSettings = {
-/**
- * Whether sync is enabled
- */
-enabled: boolean;
-/**
- * Path to the Obsidian vault
- */
-vaultPath: string;
-/**
- * Subfolder within vault for notes (e.g., "screenpipe/logs" or "daily/activity")
- */
-notesPath?: string;
-/**
- * Sync interval in minutes (0 = manual only)
- */
-syncIntervalMinutes: number;
-/**
- * Custom user prompt to append to system prompt
- */
-customPrompt: string;
-/**
- * Last successful sync timestamp (ISO 8601)
- */
-lastSyncTime: string | null;
-/**
- * Number of hours to sync (how far back to look)
- */
-syncHours: number }
-/**
- * Status of an ongoing or completed sync
- */
-export type ObsidianSyncStatus = { isSyncing: boolean; lastSyncTime: string | null; lastError: string | null; notesCreatedToday: number;
-/**
- * Next scheduled run time (ISO 8601) - for UI display
- */
-nextScheduledRun: string | null }
export type OnboardingStore = { isCompleted: boolean; completedAt: string | null;
/**
* Current step in onboarding flow (login, intro, usecases, status)
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index fce85fe8b..7f476b5a6 100755
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -8097,7 +8097,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.0.564"
+version = "2.0.566"
dependencies = [
"anyhow",
"arboard",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 8af56e3e0..b75896d97 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.0.565"
+version = "2.0.566"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 5fa0d33a7..0b71580d6 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -57,7 +57,6 @@ mod windows_overlay;
#[allow(deprecated)]
mod space_monitor;
mod sync;
-mod obsidian_sync;
mod reminders;
mod calendar;
mod pi;
@@ -1223,15 +1222,6 @@ async fn main() {
pi::pi_prompt,
pi::pi_abort,
pi::pi_new_session,
- // Obsidian Sync commands
- obsidian_sync::obsidian_save_settings,
- 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,
- obsidian_sync::obsidian_cancel_sync,
// Reminders commands
reminders::reminders_status,
reminders::reminders_authorize,
@@ -1261,8 +1251,6 @@ async fn main() {
.typ::<sync::SyncStatusResponse>()
.typ::<sync::SyncDeviceInfo>()
.typ::<sync::SyncConfig>()
- .typ::<obsidian_sync::ObsidianSyncSettings>()
- .typ::<obsidian_sync::ObsidianSyncStatus>()
.typ::<reminders::RemindersStatus>()
.typ::<reminders::ReminderItem>()
.typ::<reminders::ScanResult>()
@@ -1286,7 +1274,6 @@ async fn main() {
is_starting: Arc::new(AtomicBool::new(false)),
};
let pi_state = pi::PiState(Arc::new(tokio::sync::Mutex::new(None)));
- let obsidian_sync_state = obsidian_sync::ObsidianSyncState::new();
let reminders_state = reminders::RemindersState::new();
let suggestions_state = suggestions::SuggestionsState::new();
#[allow(clippy::single_match)]
@@ -1356,7 +1343,6 @@ async fn main() {
let app = app.manage(recording_state)
.manage(pi_state)
- .manage(obsidian_sync_state)
.manage(reminders_state)
.manage(suggestions_state)
.invoke_handler(tauri::generate_handler![
@@ -1437,15 +1423,6 @@ async fn main() {
pi::pi_prompt,
pi::pi_abort,
pi::pi_new_session,
- // Obsidian Sync commands
- obsidian_sync::obsidian_save_settings,
- 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,
- obsidian_sync::obsidian_cancel_sync,
// Reminders commands
reminders::reminders_status,
reminders::reminders_authorize,
@@ -2108,20 +2085,6 @@ async fn main() {
}
});
- // Auto-start obsidian sync scheduler if it was enabled
- let app_handle_clone = app_handle.clone();
- let obsidian_state = app_handle.state::<obsidian_sync::ObsidianSyncState>();
- let obsidian_state_clone = obsidian_sync::ObsidianSyncState {
- status: obsidian_state.status.clone(),
- scheduler_handle: obsidian_state.scheduler_handle.clone(),
- current_pid: obsidian_state.current_pid.clone(),
- };
- tauri::async_runtime::spawn(async move {
- // Small delay to ensure everything is ready
- tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
- obsidian_sync::auto_start_scheduler(app_handle_clone, &obsidian_state_clone).await;
- });
-
// Auto-start suggestions scheduler (always on)
let suggestions_state = app_handle.state::<suggestions::SuggestionsState>();
let suggestions_state_clone = suggestions::SuggestionsState {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs b/apps/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs
deleted file mode 100644
index 6e4b0022e..000000000
--- a/apps/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs
+++ /dev/null
@@ -1,893 +0,0 @@
-//! Obsidian Sync Module
-//!
-//! Syncs screenpipe activity data to an Obsidian vault using pi as the AI agent.
-//! The agent queries screenpipe API in chunks and generates markdown summaries.
-
-use crate::pi;
-use crate::store::{ObsidianSettingsStore, SettingsStore};
-use serde::{Deserialize, Serialize};
-use specta::Type;
-use std::path::PathBuf;
-use std::sync::Arc;
-use tauri::{AppHandle, Emitter};
-use tokio::sync::Mutex;
-use tracing::{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,
- /// Subfolder within vault for notes (e.g., "screenpipe/logs" or "daily/activity")
- #[serde(default = "default_notes_path")]
- pub notes_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,
-}
-
-fn default_notes_path() -> String {
- "screenpipe/logs".to_string()
-}
-
-/// 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,
- /// Next scheduled run time (ISO 8601) - for UI display
- pub next_scheduled_run: Option<String>,
-}
-
-impl Default for ObsidianSyncStatus {
- fn default() -> Self {
- Self {
- is_syncing: false,
- last_sync_time: None,
- last_error: None,
- notes_created_today: 0,
- next_scheduled_run: None,
- }
- }
-}
-
-/// State for managing obsidian sync
-pub struct ObsidianSyncState {
- pub status: Arc<Mutex<ObsidianSyncStatus>>,
- pub scheduler_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
- pub current_pid: Arc<Mutex<Option<u32>>>,
-}
-
-impl ObsidianSyncState {
- pub fn new() -> Self {
- Self {
- status: Arc::new(Mutex::new(ObsidianSyncStatus::default())),
- current_pid: Arc::new(Mutex::new(None)),
- scheduler_handle: Arc::new(Mutex::new(None)),
- }
- }
-}
-
-/// System prompt for the pi 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
-Full API reference (60+ endpoints): https://docs.screenpi.pe/llms-full.txt
-
-### Search Endpoint
-```
-GET /search
-```
-
-Query parameters:
-- `content_type`: "ocr" | "audio" | "input" | "accessibility" | "all" (default: all)
- - `ocr` — screen text from screenshots
- - `audio` — transcribed speech
- - `input` — user actions: clicks, keystrokes, clipboard, app switches
- - `accessibility` — accessibility tree text (richer than OCR for UI elements)
- - `all` — combines ocr + audio + accessibility
-- `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
-- `q`: text search query (optional, filters results by keyword)
-- `app_name`: filter by app (e.g., "Arc", "Slack", "zoom")
-- `min_length`: minimum content length in chars (use 50 to skip noise)
-- `speaker_name`: filter audio by speaker name
-
-Example:
-```bash
-curl "http://localhost:3030/search?content_type=ocr&start_time=2025-02-01T10:00:00Z&end_time=2025-02-01T10:30:00Z&limit=200&min_length=50"
-```
-
-### Querying Strategy
-
-For best results, query each modality separately per 30-min chunk:
-1. `content_type=ocr&min_length=50` — what was on screen (apps, documents, code)
-2. `content_type=audio` — what was said (meetings, voice notes)
-3. `content_type=input` — what the user did (typed text, clicks, app switches, clipboard)
-4. `content_type=accessibility` — UI element tree (buttons, labels, menus — richer than OCR for understanding UI interactions)
-
-This gives you richer context than a single `all` query. Use `input` data to understand workflow, `audio` for meeting summaries, and `accessibility` for precise UI context.
-
-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. Read the existing daily note file first (if it exists) — you will merge into it
-2. Query the screenpipe API for the specified time range in 30-minute chunks
-3. Use `min_length=50` to skip noisy/short OCR fragments
-4. Synthesize activities, extract action items, and write the note
-
-## Output Format
-
-Write the daily note with these sections:
-
-```markdown
-# Activity Log - YYYY-MM-DD
-
-## Timeline
-
-| 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 |
-
-## Action Items
-
-- [ ] Follow up with [[Alice]] on API design — from 10:30 meeting
-- [ ] Review deployment checklist before Friday
-- [ ] Visit https://example.com/docs for reference
-
-## Key Moments
-
-- [10:32 AM](screenpipe://timeline?timestamp=2025-02-01T10:32:00Z) — [[Bob]] mentioned Q2 deadline is March 15
-- [11:15 AM](screenpipe://timeline?timestamp=2025-02-01T11:15:00Z) — decided to use PostgreSQL for new service
-
-## Summary
-
-Brief 2-3 sentence summary of the day's main themes and accomplishments.
-```
-
-## Accumulation Rules (critical for hourly syncs)
-
-- ALWAYS read the existing note file first before writing
-- MERGE new time ranges into the existing timeline — do not overwrite earlier entries
-- DEDUPLICATE: if a time range already exists, skip or update it, don't duplicate
-- MERGE action items: keep existing TODOs, add new ones, don't remove completed items
-- REWRITE the Summary section to cover the full day so far (not just the latest chunk)
-
-## Privacy Rules
-
-- NEVER dump raw OCR text — always synthesize into activity descriptions
-- REDACT passwords, API keys, tokens, secrets, and credentials if they appear in OCR
-- SKIP banking, financial, and medical content — just note "personal/private activity"
-- MINIMIZE personally identifiable information — use [[Name]] links, don't include full emails/phone numbers
-- DO NOT include full audio transcripts — summarize conversations instead
-
-## Embedding Media & Deep Links
-
-- **Timeline links**: `[10:30 AM](screenpipe://timeline?timestamp=2025-02-01T10:30:00Z)` — opens screenpipe at that moment
-- **Frame links**: `[screenshot](screenpipe://frame/12345)` — links a specific captured frame
-- **Video files**: `![video](/path/to/file.mp4)` using the exact file_path from search results
-- **Audio files**: `![audio](/path/to/file.mp4)` using audio_file_path from search results
-
-## Best Practices
-
-- Link people names with [[Name]] (Obsidian wiki-links)
-- Link projects/concepts with [[concept-name]]
-- Extract TODOs: explicit tasks, follow-ups, URLs to visit, deadlines, purchases mentioned
-- Keep summaries concise but capture key activities
-- Group related activities together
-- Add semantic tags (#coding, #meeting, #research, etc.)
-- Include timeline deep links for key moments
-- Skip idle periods or duplicates
-
-## Important
-
-- Query in chunks to avoid context overflow
-- Use curl to fetch data from the API
-- Write files using the write tool
-- Create the subfolder structure if it doesn't exist
-- ONLY create/modify the single daily log file (YYYY-MM-DD.md) - DO NOT create any other files
-- Use the user's LOCAL timezone for all times displayed in the log (convert UTC timestamps)
-"#;
-
-/// Build the full prompt for pi
-fn build_prompt(settings: &ObsidianSyncSettings, start_time: &str, end_time: &str) -> String {
- let local_now = chrono::Local::now();
- let today = local_now.format("%Y-%m-%d").to_string();
- let timezone = local_now.format("%Z").to_string(); // e.g., "PST", "EST"
- let timezone_offset = local_now.format("%:z").to_string(); // e.g., "-08:00"
-
- let notes_path = if settings.notes_path.is_empty() {
- "screenpipe/logs".to_string()
- } else {
- settings.notes_path.trim_matches('/').to_string()
- };
- let note_path = format!(
- "{}/{}/{}.md",
- settings.vault_path.trim_end_matches('/'),
- notes_path,
- today
- );
-
- // Static system prompt first (cacheable by LLM providers), dynamic context last
- let mut prompt = SYSTEM_PROMPT.to_string();
-
- // 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.push_str(&format!(
- r#"
-
-## Current Task
-
-Sync my screenpipe activity to Obsidian.
-
-Time range: {} to {}
-Output file: {}
-User's timezone: {} (UTC{})"#,
- start_time, end_time, note_path, timezone, timezone_offset
- ));
-
- prompt
-}
-
-/// Save obsidian settings to persistent store (called when settings change)
-#[tauri::command]
-#[specta::specta]
-pub async fn obsidian_save_settings(
- app: AppHandle,
- settings: ObsidianSyncSettings,
-) -> Result<(), String> {
- // Preserve existing next_scheduled_run when saving settings from UI
- let existing_next_run = ObsidianSettingsStore::get(&app)
- .ok()
- .flatten()
- .and_then(|s| s.next_scheduled_run);
-
- let store_settings = ObsidianSettingsStore {
- enabled: settings.enabled,
- vault_path: settings.vault_path,
- notes_path: settings.notes_path,
- sync_interval_minutes: settings.sync_interval_minutes,
- custom_prompt: settings.custom_prompt,
- sync_hours: settings.sync_hours,
- next_scheduled_run: existing_next_run,
- };
- store_settings.save(&app)?;
- info!("Obsidian settings saved to store (preserved next_scheduled_run)");
- Ok(())
-}
-
-/// 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(
- app: AppHandle,
- state: tauri::State<'_, ObsidianSyncState>,
-) -> Result<ObsidianSyncStatus, String> {
- let mut status = state.status.lock().await.clone();
-
- // Load next_scheduled_run from persistent store
- if let Ok(Some(settings)) = ObsidianSettingsStore::get(&app) {
- status.next_scheduled_run = settings.next_scheduled_run;
- }
-
- Ok(status)
-}
-
-/// 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,
- user_token: Option<String>,
-) -> 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());
- }
-
- // Note: vault validation is non-blocking - any folder works, Obsidian is optional
-
- // 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);
-
- // Debug: check if token is passed
- info!("obsidian_run_sync: user_token present = {}, vault_path = {}", user_token.is_some(), settings.vault_path);
-
- // Create channel to receive PID
- let (pid_tx, pid_rx) = tokio::sync::oneshot::channel();
- let current_pid = state.current_pid.clone();
-
- // Spawn task to store PID when received
- tokio::spawn(async move {
- if let Ok(pid) = pid_rx.await {
- *current_pid.lock().await = Some(pid);
- }
- });
-
- // Run pi in the vault directory
- let result = pi::run(&prompt, user_token.as_deref(), &settings.vault_path, Some(pid_tx)).await.map(|_| ());
-
- // Clear PID when done
- *state.current_pid.lock().await = None;
-
- // 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())
-}
-
-/// 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,
- user_token: Option<String>,
-) -> 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;
-
- // Calculate next scheduled run time
- let next_run = chrono::Utc::now() + chrono::Duration::minutes(interval_mins as i64);
-
- // Save settings with next_scheduled_run to persistent store
- let store_settings = ObsidianSettingsStore {
- enabled: settings.enabled,
- vault_path: settings.vault_path.clone(),
- notes_path: settings.notes_path.clone(),
- sync_interval_minutes: settings.sync_interval_minutes,
- custom_prompt: settings.custom_prompt.clone(),
- sync_hours: settings.sync_hours,
- next_scheduled_run: Some(next_run.to_rfc3339()),
- };
- if let Err(e) = store_settings.save(&app) {
- warn!("Failed to save obsidian settings to store: {}", e);
- }
-
- let settings_clone = settings.clone();
- let status_arc = state.status.clone();
- let current_pid_arc = state.current_pid.clone();
- let app_handle = app.clone();
- let token_clone = user_token.clone();
-
- info!(
- "Starting obsidian sync scheduler with {}min interval, next run at {}",
- interval_mins, next_run
- );
-
- let handle = tokio::spawn(async move {
- info!("Obsidian scheduler task started (manual), interval: {}min", interval_mins);
-
- let interval_duration = tokio::time::Duration::from_secs(interval_mins as u64 * 60);
-
- // First sync: wait the full interval (user just started/restarted the scheduler)
- info!("Obsidian scheduler: waiting {}min for first sync...", interval_mins);
- tokio::time::sleep(interval_duration).await;
-
- loop {
- let now = chrono::Utc::now();
- info!("Obsidian scheduler: tick received at {:?}", now);
-
- // Check if we should sync
- {
- let status = status_arc.lock().await;
- if status.is_syncing {
- info!("Obsidian scheduler: skipping - already syncing");
- tokio::time::sleep(interval_duration).await;
- continue;
- }
- }
-
- info!("Running scheduled obsidian sync (manual)");
-
- let (result, retry_secs) = run_scheduled_sync_with_reschedule(
- &app_handle,
- &settings_clone,
- &status_arc,
- &current_pid_arc,
- token_clone.as_deref(),
- interval_mins,
- ).await;
-
- match &result {
- Ok(_) => info!("Scheduled obsidian sync completed successfully"),
- Err(e) => warn!("Scheduled obsidian sync failed: {}", e),
- }
-
- let wait = match retry_secs {
- Some(secs) => {
- info!("Obsidian scheduler: retrying in {}s...", secs);
- tokio::time::Duration::from_secs(secs)
- }
- None => {
- info!("Obsidian scheduler: waiting {}min for next sync...", interval_mins);
- interval_duration
- }
- };
- tokio::time::sleep(wait).await;
- }
- });
-
- // 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(())
-}
-
-/// Auto-start the scheduler on app launch if it was previously enabled
-pub async fn auto_start_scheduler(app: AppHandle, state: &ObsidianSyncState) {
- info!("Checking if obsidian scheduler should auto-start...");
-
- // Load obsidian settings from store
- let obsidian_settings = match ObsidianSettingsStore::get(&app) {
- Ok(Some(s)) => s,
- Ok(None) => {
- info!("No obsidian settings found, skipping auto-start");
- return;
- }
- Err(e) => {
- warn!("Failed to load obsidian settings: {}", e);
- return;
- }
- };
-
- if !obsidian_settings.enabled {
- info!("Obsidian scheduler is disabled, skipping auto-start");
- return;
- }
-
- if obsidian_settings.vault_path.is_empty() {
- info!("Obsidian vault path is empty, skipping auto-start");
- return;
- }
-
- if obsidian_settings.sync_interval_minutes == 0 {
- info!("Obsidian sync interval is 0, skipping auto-start");
- return;
- }
-
- // Get user token from settings store
- let user_token = match SettingsStore::get(&app) {
- Ok(Some(s)) => s.user.token,
- _ => None,
- };
-
- if user_token.is_none() {
- info!("No user token found, skipping obsidian auto-start (requires login)");
- return;
- }
-
- // Convert store settings to sync settings
- let settings = ObsidianSyncSettings {
- enabled: obsidian_settings.enabled,
- vault_path: obsidian_settings.vault_path.clone(),
- notes_path: obsidian_settings.notes_path.clone(),
- sync_interval_minutes: obsidian_settings.sync_interval_minutes,
- custom_prompt: obsidian_settings.custom_prompt.clone(),
- last_sync_time: None,
- sync_hours: obsidian_settings.sync_hours,
- };
-
- let interval_mins = settings.sync_interval_minutes;
- let settings_clone = settings.clone();
- let status_arc = state.status.clone();
- let current_pid_arc = state.current_pid.clone();
- let app_handle = app.clone();
- let token_clone = user_token.clone();
-
- // Check if we have a scheduled run time and calculate initial delay
- let now = chrono::Utc::now();
- let (initial_delay, next_run_time) = if let Some(ref next_run_str) = obsidian_settings.next_scheduled_run {
- match chrono::DateTime::parse_from_rfc3339(next_run_str) {
- Ok(next_run) => {
- let next_run_utc = next_run.with_timezone(&chrono::Utc);
- if next_run_utc <= now {
- // Missed the scheduled time - run immediately, then continue with normal interval
- info!("Obsidian scheduler: missed scheduled run at {}, will run immediately", next_run_str);
- // Next run will be now (immediate) + interval
- let next = now + chrono::Duration::minutes(interval_mins as i64);
- (tokio::time::Duration::from_secs(0), next)
- } else {
- // Wait until the scheduled time
- let delay = (next_run_utc - now).to_std().unwrap_or(tokio::time::Duration::from_secs(0));
- info!("Obsidian scheduler: resuming, next run in {:?} (at {})", delay, next_run_str);
- (delay, next_run_utc)
- }
- }
- Err(e) => {
- warn!("Failed to parse next_scheduled_run '{}': {}, using full interval", next_run_str, e);
- let next = now + chrono::Duration::minutes(interval_mins as i64);
- (tokio::time::Duration::from_secs(interval_mins as u64 * 60), next)
- }
- }
- } else {
- // No scheduled time, use full interval and save it
- info!("Obsidian scheduler: no previous schedule, waiting full interval");
- let next = now + chrono::Duration::minutes(interval_mins as i64);
- (tokio::time::Duration::from_secs(interval_mins as u64 * 60), next)
- };
-
- // Always save next_scheduled_run to store (so UI can display it)
- let updated_settings = ObsidianSettingsStore {
- enabled: obsidian_settings.enabled,
- vault_path: obsidian_settings.vault_path.clone(),
- notes_path: obsidian_settings.notes_path.clone(),
- sync_interval_minutes: obsidian_settings.sync_interval_minutes,
- custom_prompt: obsidian_settings.custom_prompt.clone(),
- sync_hours: obsidian_settings.sync_hours,
- next_scheduled_run: Some(next_run_time.to_rfc3339()),
- };
- if let Err(e) = updated_settings.save(&app) {
- warn!("Failed to save next_scheduled_run on auto-start: {}", e);
- }
-
- // Stop any existing scheduler before starting (prevents duplicate tasks)
- {
- let mut handle = state.scheduler_handle.lock().await;
- if let Some(h) = handle.take() {
- h.abort();
- info!("Stopped existing obsidian scheduler before auto-start");
- }
- }
-
- info!("Auto-starting obsidian scheduler with {}min interval, initial delay: {:?}, next run at {}", interval_mins, initial_delay, next_run_time);
-
- let handle = tokio::spawn(async move {
- info!("Obsidian scheduler task started (auto-start), interval: {}min", interval_mins);
-
- let interval_duration = tokio::time::Duration::from_secs(interval_mins as u64 * 60);
-
- // Wait for initial delay (could be 0 if we missed a sync, or remaining time until next scheduled)
- if !initial_delay.is_zero() {
- info!("Obsidian scheduler: waiting {:?} before first sync...", initial_delay);
- tokio::time::sleep(initial_delay).await;
- }
-
- loop {
- let now = chrono::Utc::now();
- info!("Obsidian scheduler: tick received at {:?}", now);
-
- // Check if we should sync
- {
- let status = status_arc.lock().await;
- if status.is_syncing {
- info!("Obsidian scheduler: skipping - already syncing");
- tokio::time::sleep(interval_duration).await;
- continue;
- }
- }
-
- info!("Running scheduled obsidian sync (auto-start)");
-
- let (result, retry_secs) = run_scheduled_sync_with_reschedule(
- &app_handle,
- &settings_clone,
- &status_arc,
- &current_pid_arc,
- token_clone.as_deref(),
- interval_mins,
- ).await;
-
- match &result {
- Ok(_) => info!("Scheduled obsidian sync completed successfully"),
- Err(e) => warn!("Scheduled obsidian sync failed: {}", e),
- }
-
- let wait = match retry_secs {
- Some(secs) => {
- info!("Obsidian scheduler: retrying in {}s...", secs);
- tokio::time::Duration::from_secs(secs)
- }
- None => {
- info!("Obsidian scheduler: waiting {}min for next sync...", interval_mins);
- interval_duration
- }
- };
- tokio::time::sleep(wait).await;
- }
- });
-
- // Store the handle
- let mut scheduler_handle = state.scheduler_handle.lock().await;
- *scheduler_handle = Some(handle);
-
- info!("Obsidian scheduler auto-started successfully");
-}
-
-/// Cancel the currently running sync
-#[tauri::command]
-#[specta::specta]
-pub async fn obsidian_cancel_sync(
- app: AppHandle,
- state: tauri::State<'_, ObsidianSyncState>,
-) -> Result<(), String> {
- let mut pid = state.current_pid.lock().await;
- if let Some(p) = pid.take() {
- crate::pi::kill(p)?;
-
- // Update status
- let mut status = state.status.lock().await;
- status.is_syncing = false;
- status.last_error = Some("Cancelled by user".to_string());
-
- let _ = app.emit("obsidian_sync_error", "Cancelled by user");
- info!("Obsidian sync cancelled");
- }
- Ok(())
-}
-
-/// Internal function to run a scheduled sync
-async fn run_scheduled_sync(
- app: &AppHandle,
- settings: &ObsidianSyncSettings,
- status: &Arc<Mutex<ObsidianSyncStatus>>,
- current_pid: &Arc<Mutex<Option<u32>>>,
- user_token: Option<&str>,
-) -> 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());
-
- // Create channel to receive PID
- let (pid_tx, pid_rx) = tokio::sync::oneshot::channel();
- let pid_clone = current_pid.clone();
- tokio::spawn(async move {
- if let Ok(pid) = pid_rx.await {
- *pid_clone.lock().await = Some(pid);
- }
- });
-
- let result = pi::run(&prompt, user_token, &settings.vault_path, Some(pid_tx)).await.map(|_| ());
-
- // Clear PID when done
- *current_pid.lock().await = None;
-
- // 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
-}
-
-/// Internal function to run a scheduled sync and update next_scheduled_run.
-/// Returns (result, retry_secs) — retry_secs is Some if should retry sooner than normal interval.
-async fn run_scheduled_sync_with_reschedule(
- app: &AppHandle,
- settings: &ObsidianSyncSettings,
- status: &Arc<Mutex<ObsidianSyncStatus>>,
- current_pid: &Arc<Mutex<Option<u32>>>,
- user_token: Option<&str>,
- interval_mins: u32,
-) -> (Result<(), String>, Option<u64>) {
- // Run the actual sync
- let result = run_scheduled_sync(app, settings, status, current_pid, user_token).await;
-
- let (next_run, retry_secs) = match &result {
- Ok(_) => {
- // Success — schedule next run at normal interval
- let next = chrono::Utc::now() + chrono::Duration::minutes(interval_mins as i64);
- (next, None)
- }
- Err(e) if e.contains("429") || e.contains("rate limit") => {
- // Rate limited — retry in 60 seconds, not the full interval
- let retry = 60u64;
- let next = chrono::Utc::now() + chrono::Duration::seconds(retry as i64);
- warn!("Obsidian sync rate limited, retrying in {}s", retry);
- (next, Some(retry))
- }
- Err(_) => {
- // Other failure — retry in 5 minutes, not the full interval
- let retry = 300u64;
- let next = chrono::Utc::now() + chrono::Duration::seconds(retry as i64);
- (next, Some(retry))
- }
- };
-
- // Save next_scheduled_run to persistent store
- // Preserve other fields from current store
- if let Ok(Some(mut store_settings)) = ObsidianSettingsStore::get(app) {
- store_settings.next_scheduled_run = Some(next_run.to_rfc3339());
- if let Err(e) = store_settings.save(app) {
- warn!("Failed to save next_scheduled_run: {}", e);
- } else {
- info!("Updated next_scheduled_run to {}", next_run);
- }
- }
-
- (result, retry_secs)
-}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
index 85f83e5d9..434e51994 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/permissions.rs
@@ -691,10 +691,12 @@ pub async fn start_permission_monitor(app: tauri::AppHandle) {
let screen_confirmed_lost = screen_fail_count == REQUIRED_CONSECUTIVE_FAILURES;
let mic_confirmed_lost = mic_fail_count == REQUIRED_CONSECUTIVE_FAILURES;
let accessibility_confirmed_lost = accessibility_fail_count == REQUIRED_CONSECUTIVE_FAILURES;
- let arc_confirmed_lost = arc_fail_count == REQUIRED_CONSECUTIVE_FAILURES;
+ // Arc automation is tracked but NOT used to trigger the recovery modal —
+ // it's optional and shouldn't block the user. The arc_automation field is
+ // still included in the payload for the banner/recovery page to display.
+ let _ = arc_fail_count; // keep tracking for payload, suppress unused warning
// Only emit permission-lost when a CORE permission is lost (screen, mic, accessibility).
- // Arc automation is optional — don't open the recovery modal just for that.
let core_lost = screen_confirmed_lost || mic_confirmed_lost || accessibility_confirmed_lost;
if core_lost && (!screen_ok || !mic_ok || !accessibility_ok) {
// Enforce cooldown to prevent modal spam from flaky checks
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index b4425c105..6cd094143 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -689,49 +689,6 @@ pub fn init_onboarding_store(app: &AppHandle) -> Result<OnboardingStore, String>
Ok(onboarding)
}
-/// Obsidian sync settings stored persistently
-#[derive(Serialize, Deserialize, Type, Clone, Default)]
-#[serde(rename_all = "camelCase")]
-pub struct ObsidianSettingsStore {
- pub enabled: bool,
- pub vault_path: String,
- #[serde(default = "default_notes_path")]
- pub notes_path: String,
- pub sync_interval_minutes: u32,
- pub custom_prompt: String,
- pub sync_hours: u32,
- /// Next scheduled run time (ISO 8601) - used to resume scheduler after app restart
- #[serde(default)]
- pub next_scheduled_run: Option<String>,
-}
-
-fn default_notes_path() -> String {
- "screenpipe/logs".to_string()
-}
-
-impl ObsidianSettingsStore {
- pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
- let store = get_store(app, None).map_err(|e| e.to_string())?;
-
- match store.is_empty() {
- true => Ok(None),
- false => {
- let settings = serde_json::from_value(store.get("obsidian").unwrap_or(Value::Null));
- match settings {
- Ok(settings) => Ok(settings),
- Err(_) => Ok(None),
- }
- }
- }
- }
-
- pub fn save(&self, app: &AppHandle) -> Result<(), String> {
- let store = get_store(app, None).map_err(|e| e.to_string())?;
- store.set("obsidian", json!(self));
- store.save().map_err(|e| e.to_string())
- }
-}
-
// ─── Reminders Settings ─────────────────────────────────────────────────────
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/screenpipe-accessibility/src/tree/macos.rs b/crates/screenpipe-accessibility/src/tree/macos.rs
index 8e9b85c86..1621d165e 100644
--- a/crates/screenpipe-accessibility/src/tree/macos.rs
+++ b/crates/screenpipe-accessibility/src/tree/macos.rs
@@ -45,6 +45,7 @@ fn extract_browser_url(
// Tier 1: AXDocument attribute on the window
if let Some(url) = get_string_attr(window, ax::attr::document()) {
if url.starts_with("http://") || url.starts_with("https://") {
+ debug!("browser_url: tier1 AXDocument hit for {}: {}", app_name, url);
return Some(url);
}
}
@@ -53,15 +54,18 @@ fn extract_browser_url(
let app_lower = app_name.to_lowercase();
if app_lower.contains("arc") {
if let Some(url) = get_arc_url(window_name) {
+ debug!("browser_url: tier2 Arc AppleScript hit: {}", url);
return Some(url);
}
}
// Tier 3: Shallow walk for AXTextField with URL-like value
if let Some(url) = find_url_in_children(window, 0, 5) {
+ debug!("browser_url: tier3 AXTextField hit for {}: {}", app_name, url);
return Some(url);
}
+ debug!("browser_url: all tiers failed for app={}, window={}", app_name, window_name);
None
}
@@ -69,38 +73,61 @@ fn extract_browser_url(
/// Cross-checks the returned title against window_name to avoid stale results.
fn get_arc_url(window_name: &str) -> Option<String> {
let script = r#"tell application "Arc"
- set currentTab to active tab of front window
- set tabURL to URL of currentTab
- set tabTitle to title of currentTab
- return tabTitle & "\n" & tabURL
+ set t to title of active tab of front window
+ set u to URL of active tab of front window
+ return t & "\n" & u
end tell"#;
- let output = Command::new("osascript")
+ let output = match Command::new("osascript")
.arg("-e")
.arg(script)
.output()
- .ok()?;
+ {
+ Ok(o) => o,
+ Err(e) => {
+ debug!("get_arc_url: osascript spawn failed: {}", e);
+ return None;
+ }
+ };
if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ debug!("get_arc_url: osascript failed (exit={}): {}", output.status, stderr.trim());
return None;
}
let result = String::from_utf8_lossy(&output.stdout).trim().to_string();
let mut lines = result.lines();
- let title = lines.next()?;
- let url = lines.next()?;
+ let title = match lines.next() {
+ Some(t) => t,
+ None => {
+ debug!("get_arc_url: no title line in output");
+ return None;
+ }
+ };
+ let url = match lines.next() {
+ Some(u) => u,
+ None => {
+ debug!("get_arc_url: no URL line in output (title={})", title);
+ return None;
+ }
+ };
// Cross-check: window title should contain the tab title (or vice versa)
let window_lower = window_name.to_lowercase();
let title_lower = title.to_lowercase();
if !window_lower.contains(&title_lower) && !title_lower.contains(&window_lower) {
- // Title mismatch — may be stale
+ debug!(
+ "get_arc_url: title mismatch — window='{}', arc_title='{}', url='{}'",
+ window_name, title, url
+ );
return None;
}
if url.starts_with("http://") || url.starts_with("https://") {
Some(url.to_string())
} else {
+ debug!("get_arc_url: URL not http(s): {}", url);
None
}
}