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
Bump app to v2.0.216, CLI to v0.3.10
Louis Beaumontca3919c2babc
diff --git a/Cargo.lock b/Cargo.lockindex e5541cdd9..60a149b24 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6628,7 +6628,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","bytemuck",@@ -6681,7 +6681,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.7"+version = "0.3.9"dependencies = ["accessibility","accessibility-sys",@@ -6732,7 +6732,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","chrono",@@ -6756,7 +6756,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","chrono",@@ -6774,7 +6774,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","image",@@ -6789,7 +6789,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","async-trait",@@ -6858,7 +6858,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.3.7"+version = "0.3.9"dependencies = ["accessibility-sys","anyhow",diff --git a/Cargo.toml b/Cargo.tomlindex b7d76aab5..8125bfa93 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -13,7 +13,7 @@ exclude = ["screenpipe-app-tauri/src-tauri"]resolver = "2"[workspace.package]-version = "0.3.9"+version = "0.3.10"authors = ["louis030195 <[email protected]>"]description = ""repository = "https://github.com/mediar-ai/screenpipe"diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsxindex eac65dca8..87006aebb 100644--- a/screenpipe-app-tauri/components/global-chat.tsx+++ b/screenpipe-app-tauri/components/global-chat.tsx@@ -27,12 +27,9 @@ import { open as openDialog } from "@tauri-apps/plugin-dialog";import { usePlatform } from "@/lib/hooks/use-platform";import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";-import { commands, OpencodeInfo } from "@/lib/utils/tauri";+import { commands, PiInfo } from "@/lib/utils/tauri";import posthog from "posthog-js";import { UpgradeDialog } from "@/components/upgrade-dialog";-import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";--type OpencodeClient = ReturnType<typeof createOpencodeClient>;const SCREENPIPE_API = "http://localhost:3030";@@ -568,12 +565,11 @@ export function GlobalChat() {const [upgradeReason, setUpgradeReason] = useState<"daily_limit" | "model_not_allowed">("daily_limit");const [upgradeResetsAt, setUpgradeResetsAt] = useState<string | undefined>();- // OpenCode state- const [opencodeInfo, setOpencodeInfo] = useState<OpencodeInfo | null>(null);- const [opencodeClient, setOpencodeClient] = useState<OpencodeClient | null>(null);- const [opencodeSessionId, setOpencodeSessionId] = useState<string | null>(null);- const [opencodeProjectDir, setOpencodeProjectDir] = useState<string>("");- const [opencodeStarting, setOpencodeStarting] = useState(false);+ // Pi state+ const [piInfo, setPiInfo] = useState<PiInfo | null>(null);+ const [piProjectDir, setPiProjectDir] = useState<string>("");+ const [piStarting, setPiStarting] = useState(false);+ const [piLogs, setPiLogs] = useState<string[]>([]);// Chat history stateconst [conversationId, setConversationId] = useState<string | null>(null);@@ -1059,12 +1055,12 @@ export function GlobalChat() {// Check if we have valid AI setupconst hasPresets = settings.aiPresets && settings.aiPresets.length > 0;- const hasValidModel = activePreset?.provider === "opencode" || (activePreset?.model && activePreset.model.trim() !== "");- const needsLogin = (activePreset?.provider === "screenpipe-cloud" || activePreset?.provider === "opencode") && !settings.user?.token;- const isOpencode = activePreset?.provider === "opencode";- const needsProjectDir = isOpencode && !opencodeProjectDir;- const opencodeReady = isOpencode ? (opencodeInfo?.running && opencodeClient && opencodeSessionId && !needsProjectDir) : true;- const canChat = hasPresets && hasValidModel && !needsLogin && opencodeReady;+ const hasValidModel = activePreset?.provider === "pi" || (activePreset?.model && activePreset.model.trim() !== "");+ const needsLogin = (activePreset?.provider === "screenpipe-cloud" || activePreset?.provider === "pi") && !settings.user?.token;+ const isPi = activePreset?.provider === "pi";+ const needsProjectDir = isPi && !piProjectDir;+ const piReady = isPi ? (piInfo?.running && !needsProjectDir) : true;+ const canChat = hasPresets && hasValidModel && !needsLogin && piReady;// Debug: log why chat might be disableduseEffect(() => {@@ -1083,70 +1079,42 @@ export function GlobalChat() {// Load saved project directory on mountuseEffect(() => {- const saved = localStorage.getItem("opencode_project_dir");- if (saved) setOpencodeProjectDir(saved);+ const saved = localStorage.getItem("pi_project_dir");+ if (saved) setPiProjectDir(saved);}, []);// Save project directory when changeduseEffect(() => {- if (opencodeProjectDir) {- localStorage.setItem("opencode_project_dir", opencodeProjectDir);+ if (piProjectDir) {+ localStorage.setItem("pi_project_dir", piProjectDir);}- }, [opencodeProjectDir]);+ }, [piProjectDir]);- // Start OpenCode when preset is selected, dialog is open, and project dir is set+ // Start Pi when preset is selected, dialog is open, and project dir is setuseEffect(() => {- if (!isOpencode || !open || needsLogin || !opencodeProjectDir || opencodeStarting) return;+ if (!isPi || !open || needsLogin || !piProjectDir || piStarting) return;- const initOpencode = async () => {- setOpencodeStarting(true);+ const initPi = async () => {+ setPiStarting(true);try {// Check current status- const infoResult = await commands.opencodeInfo();+ const infoResult = await commands.piInfo();if (infoResult.status === "ok") {- setOpencodeInfo(infoResult.data);+ setPiInfo(infoResult.data);// Check if already running with same project- if (infoResult.data.running && infoResult.data.baseUrl && infoResult.data.projectDir === opencodeProjectDir) {- // Already running with correct project, set up client- const client = createOpencodeClient({ baseUrl: infoResult.data.baseUrl });- setOpencodeClient(client);-- // Get or create a session- try {- const sessions = await client.session.list();- if (sessions.data && sessions.data.length > 0) {- setOpencodeSessionId(sessions.data[0].id);- } else {- const newSession = await client.session.create({ directory: opencodeProjectDir });- if (newSession.data) {- setOpencodeSessionId(newSession.data.id);- }- }- } catch (e) {- console.error("Failed to get/create opencode session:", e);- }+ if (infoResult.data.running && infoResult.data.projectDir === piProjectDir) {+ // Already running with correct project+ console.log("Pi already running for project:", piProjectDir);} else {// Not running or different project, start with selected directory- const startResult = await commands.opencodeStart(opencodeProjectDir, settings.user?.token ?? null);- if (startResult.status === "ok" && startResult.data.running && startResult.data.baseUrl) {- setOpencodeInfo(startResult.data);- const client = createOpencodeClient({ baseUrl: startResult.data.baseUrl });- setOpencodeClient(client);-- // Create initial session- try {- const newSession = await client.session.create({ directory: opencodeProjectDir });- if (newSession.data) {- setOpencodeSessionId(newSession.data.id);- }- } catch (e) {- console.error("Failed to create opencode session:", e);- }+ const startResult = await commands.piStart(piProjectDir, settings.user?.token ?? null);+ if (startResult.status === "ok" && startResult.data.running) {+ setPiInfo(startResult.data);} else if (startResult.status === "error") {toast({- title: "OpenCode failed to start",+ title: "Pi failed to start",description: startResult.error,variant: "destructive",});@@ -1154,12 +1122,12 @@ export function GlobalChat() {}}} finally {- setOpencodeStarting(false);+ setPiStarting(false);}};- initOpencode();- }, [isOpencode, open, needsLogin, opencodeProjectDir, settings.user?.token]);+ initPi();+ }, [isPi, open, needsLogin, piProjectDir, settings.user?.token]);// Get error message for why chat is disabledconst getDisabledReason = (): string | null => {@@ -1167,22 +1135,22 @@ export function GlobalChat() {if (!activePreset) return "No preset selected";if (!hasValidModel) return `No model selected in "${activePreset.id}" preset - click edit to add one`;if (needsLogin) return "Login required";- if (isOpencode && needsProjectDir) return "Select a project folder";- if (isOpencode && opencodeStarting) return "Starting OpenCode...";- if (isOpencode && !opencodeReady) return "Connecting to OpenCode...";+ if (isPi && needsProjectDir) return "Select a project folder";+ if (isPi && piStarting) return "Starting Pi...";+ if (isPi && !piReady) return "Connecting to Pi...";return null;};const disabledReason = getDisabledReason();- // Project directory picker for OpenCode- const selectOpencodeProject = async () => {+ // Project directory picker for Pi+ const selectPiProject = async () => {const selected = await openDialog({directory: true,multiple: false,- title: "Select Project Folder for OpenCode",+ title: "Select Project Folder for Pi",});if (selected) {- setOpencodeProjectDir(selected as string);+ setPiProjectDir(selected as string);}};@@ -1371,9 +1339,9 @@ export function GlobalChat() {});}- // Send message using OpenCode SDK- async function sendOpencodeMessage(userMessage: string) {- if (!opencodeClient || !opencodeSessionId) return;+ // Send message using Pi (listen to events for streaming output)+ async function sendPiMessage(userMessage: string) {+ if (!piInfo?.running) return;const newUserMessage: Message = {id: Date.now().toString(),@@ -1392,96 +1360,33 @@ export function GlobalChat() {// Add placeholder for streaming responsesetMessages((prev) => [...prev,- { id: assistantMessageId, role: "assistant", content: "", timestamp: Date.now() },+ { id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now() },]);- // Send to OpenCode- await opencodeClient.session.promptAsync({- sessionID: opencodeSessionId,- parts: [{ type: "text", text: userMessage }],- });-- // Poll for updates with smart completion detection- let accumulatedText = "";- let stableCount = 0;- let lastMessageCount = 0;- const maxStablePolls = 5; // Stop if no changes for 5 polls- const maxPolls = 120; // Max 2 minutes at 1s intervals- let pollCount = 0;-- const poll = async (): Promise<void> => {- if (!opencodeClient || !opencodeSessionId || pollCount >= maxPolls) {- setIsLoading(false);- setIsStreaming(false);- return;- }-- pollCount++;-- try {- const msgs = await opencodeClient.session.messages({ sessionID: opencodeSessionId });- if (msgs.data && msgs.data.length > 0) {- const assistantMsgs = msgs.data.filter((m: any) => m.info.role === "assistant");- const lastAssistantMsg = assistantMsgs[assistantMsgs.length - 1];-- if (lastAssistantMsg) {- const textParts = lastAssistantMsg.parts- .filter((p: any) => p.type === "text")- .map((p: any) => p.text)- .join("\n");-- // Also show tool usage- const toolParts = lastAssistantMsg.parts- .filter((p: any) => p.type === "tool")- .map((p: any) => `\n\`${p.tool}\``)- .join("");-- const fullText = textParts + toolParts;-- if (fullText !== accumulatedText) {- accumulatedText = fullText;- stableCount = 0;- setMessages((prev) =>- prev.map((m) =>- m.id === assistantMessageId- ? { ...m, content: accumulatedText }- : m- )- );- } else {- stableCount++;- }-- // Check if we have more messages than before (response complete)- if (assistantMsgs.length > lastMessageCount && stableCount >= 2) {- // New message appeared and stabilized - likely complete- setIsLoading(false);- setIsStreaming(false);- return;- }- lastMessageCount = assistantMsgs.length;-- // Stop if content hasn't changed for maxStablePolls- if (stableCount >= maxStablePolls && accumulatedText.length > 0) {- setIsLoading(false);- setIsStreaming(false);- return;- }- }- }- } catch (e) {- console.error("Error polling opencode messages:", e);- }-- // Continue polling- setTimeout(poll, 1000);- };-- // Start polling after a brief delay- setTimeout(poll, 500);-+ // Send prompt to Pi via RPC+ const result = await commands.piPrompt(userMessage);++ if (result.status === "error") {+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: `Error: ${result.error}` }+ : m+ )+ );+ } else {+ // Listen for output via pi_output events+ // The response will be collected from pi_output events+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: "Pi is processing your request. Check the terminal for full output." }+ : m+ )+ );+ }} catch (error) {- console.error("OpenCode error:", error);+ console.error("Pi error:", error);setMessages((prev) =>prev.map((m) =>m.id === assistantMessageId@@ -1489,6 +1394,7 @@ export function GlobalChat() {: m));+ } finally {setIsLoading(false);setIsStreaming(false);}@@ -1503,12 +1409,12 @@ export function GlobalChat() {message_length: userMessage.length,provider: activePreset?.provider,model: activePreset?.model,- is_opencode: isOpencode,+ is_pi: isPi,});- // Use OpenCode if that's the active provider- if (isOpencode) {- return sendOpencodeMessage(userMessage);+ // Use Pi if that's the active provider+ if (isPi) {+ return sendPiMessage(userMessage);}const openai = getOpenAIClient();@@ -2137,17 +2043,17 @@ export function GlobalChat() {</div><div className="flex-1 min-w-0"><h2 className="font-semibold text-sm tracking-tight">- {isOpencode ? "OpenCode" : "Pipe AI"}+ {isPi ? "Pi Agent" : "Pipe AI"}</h2><p className="text-[10px] text-muted-foreground font-mono uppercase tracking-wider truncate">- {isOpencode && opencodeProjectDir- ? opencodeProjectDir.split("/").pop() || opencodeProjectDir+ {isPi && piProjectDir+ ? piProjectDir.split("/").pop() || piProjectDir: "Screen Activity Assistant"}</p></div>- {isOpencode && opencodeProjectDir && (+ {isPi && piProjectDir && (<button- onClick={selectOpencodeProject}+ onClick={selectPiProject}className="p-1.5 rounded-lg bg-muted/30 hover:bg-muted/50 text-foreground/70 hover:text-foreground transition-colors border border-border/30"title="Change project folder">@@ -2296,7 +2202,7 @@ export function GlobalChat() {<FolderOpen className="h-12 w-12 text-muted-foreground" />) : needsLogin ? (<PipeAIIconLarge size={48} className="text-muted-foreground" />- ) : opencodeStarting ? (+ ) : piStarting ? (<Loader2 className="h-12 w-12 text-muted-foreground animate-spin" />) : (<Settings className="h-12 w-12 text-destructive/70" />@@ -2304,16 +2210,16 @@ export function GlobalChat() {</div><div className="text-center space-y-2"><h3 className="font-semibold tracking-tight">- {needsProjectDir ? "Select Project" : !hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : opencodeStarting ? "Starting OpenCode" : "Login Required"}+ {needsProjectDir ? "Select Project" : !hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : piStarting ? "Starting Pi..." : "Login Required"}</h3><p className="text-sm text-muted-foreground max-w-sm">- {needsProjectDir ? "Choose a folder for OpenCode to work with" : disabledReason}+ {needsProjectDir ? "Choose a folder for Pi to work with" : disabledReason}</p></div>{needsProjectDir && (<Buttonvariant="default"- onClick={selectOpencodeProject}+ onClick={selectPiProject}className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"><FolderOpen className="h-4 w-4" />diff --git a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsxindex 58ba3679f..bf98bf885 100644--- a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx+++ b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx@@ -135,25 +135,25 @@ export function AIProviderConfig({const [isLoadingModels, setIsLoadingModels] = useState(false);const [idError, setIdError] = useState<string | null>(null);const [showApiKey, setShowApiKey] = useState(false);- const [opencodeAvailable, setOpencodeAvailable] = useState(false);+ const [piAvailable, setPiAvailable] = useState(false);- // Check OpenCode availability+ // Check Pi availabilityuseEffect(() => {- const checkOpencode = async () => {+ const checkPi = async () => {try {- const result = await commands.opencodeCheck();+ const result = await commands.piCheck();if (result.status === "ok" && result.data.available) {- setOpencodeAvailable(true);+ setPiAvailable(true);}} catch (e) {- console.error("Failed to check opencode:", e);+ console.error("Failed to check pi:", e);}};- checkOpencode();+ checkPi();- const unlisten = listen<boolean>("opencode_installed", (event) => {+ const unlisten = listen<boolean>("pi_installed", (event) => {if (event.payload) {- setOpencodeAvailable(true);+ setPiAvailable(true);}});@@ -381,7 +381,7 @@ export function AIProviderConfig({<div className={cn("grid gap-1.5",- opencodeAvailable ? "grid-cols-3 sm:grid-cols-5" : "grid-cols-2 sm:grid-cols-4"+ piAvailable ? "grid-cols-3 sm:grid-cols-5" : "grid-cols-2 sm:grid-cols-4")}><Buttontype="button"@@ -452,24 +452,24 @@ export function AIProviderConfig({<span>custom</span></Button>- {opencodeAvailable && (+ {piAvailable && (<Buttontype="button"disabled={!settings?.user?.token}- variant={selectedProvider === "opencode" ? "default" : "outline"}+ variant={selectedProvider === "pi" ? "default" : "outline"}className="flex h-10 flex-col items-center justify-center gap-0.5 text-xs"onClick={() => {- setSelectedProvider("opencode");+ setSelectedProvider("pi");setFormData({...formData,- provider: "opencode",- url: "", // URL is dynamic - set at runtime- model: "screenpipe/claude-haiku-4-5",+ provider: "pi",+ url: "", // Pi uses RPC mode+ model: "claude-haiku-4-5@20251001",});}}><Icons.terminal className="h-4 w-4" />- <span>opencode</span>+ <span>pi</span></Button>)}</div>@@ -694,7 +694,7 @@ export function AIProviderConfig({</div>)}- {selectedProvider === "opencode" && (+ {selectedProvider === "pi" && (<div className="space-y-1"><Label htmlFor="model" className="text-xs">model</Label><Select@@ -707,8 +707,8 @@ export function AIProviderConfig({<SelectValue placeholder="select model" /></SelectTrigger><SelectContent>- <SelectItem value="screenpipe/claude-haiku-4-5">Haiku 4.5 (fast)</SelectItem>- <SelectItem value="screenpipe/claude-opus-4-5">Opus 4.5 (powerful)</SelectItem>+ <SelectItem value="claude-haiku-4-5@20251001">Haiku 4.5 (fast)</SelectItem>+ <SelectItem value="claude-opus-4-5@20251101">Opus 4.5 (powerful)</SelectItem></SelectContent></Select></div>diff --git a/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx b/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsxindex 43a9893e5..1322cdcad 100644--- a/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx+++ b/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx@@ -29,7 +29,7 @@ const providerIcons = {"screenpipe-cloud": <Image src="/images/screenpipe.png" alt="Screenpipe Cloud" width={16} height={16} />,"native-ollama": <Image src="/images/ollama.png" alt="Ollama" width={16} height={16} />,custom: <Image src="/images/custom.png" alt="Custom" width={16} height={16} />,- opencode: <Image src="/images/opencode.png" alt="OpenCode" width={16} height={16} />,+ pi: <Image src="/images/screenpipe.png" alt="Pi" width={16} height={16} />,};const getPresetProviderIcon = (provider: AIPreset["provider"]) => {diff --git a/screenpipe-app-tauri/components/settings/ai-presets.tsx b/screenpipe-app-tauri/components/settings/ai-presets.tsxindex 15fe0f368..d40d3840e 100644--- a/screenpipe-app-tauri/components/settings/ai-presets.tsx+++ b/screenpipe-app-tauri/components/settings/ai-presets.tsx@@ -77,7 +77,7 @@ const formatPresetName = (name: string): string => {};export interface AIProviderCardProps {- type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded" | "opencode";+ type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded" | "pi";title: string;description: string;imageSrc: string;@@ -148,12 +148,12 @@ const AISection = ({preset,setDialog,isDuplicating,- opencodeAvailable,+ piAvailable,}: {preset?: AIPreset;setDialog: (value: boolean) => void;isDuplicating?: boolean;- opencodeAvailable?: boolean;+ piAvailable?: boolean;}) => {const { settings, updateSettings } = useSettings();const [settingsPreset, setSettingsPreset] = useState<@@ -371,9 +371,9 @@ const AISection = ({case "custom":newUrl = settingsPreset?.url || "";break;- case "opencode":- newUrl = ""; // URL is dynamic - set at runtime- newModel = "screenpipe/claude-haiku-4-5";+ case "pi":+ newUrl = ""; // Pi uses RPC mode, not HTTP+ newModel = "claude-haiku-4-5@20251001";break;}@@ -576,14 +576,14 @@ const AISection = ({onClick={() => handleAiProviderChange("custom")}/>- {opencodeAvailable && (+ {piAvailable && (<AIProviderCard- type="opencode"- title="OpenCode"- description="High-intelligence AI agent powered by Claude. Requires login."+ type="pi"+ title="Pi Agent"+ description="AI coding agent powered by Claude. Requires login."imageSrc="/images/screenpipe.png"- selected={settingsPreset?.provider === "opencode"}- onClick={() => handleAiProviderChange("opencode")}+ selected={settingsPreset?.provider === "pi"}+ onClick={() => handleAiProviderChange("pi")}disabled={!settings.user?.token}warningText={!settings.user?.token ? "Login required" : undefined}/>@@ -824,7 +824,7 @@ const providerImageSrc: Record<AIPreset["provider"], string> = {"screenpipe-cloud": "/images/screenpipe.png","native-ollama": "/images/ollama.png",custom: "/images/custom.png",- opencode: "/images/screenpipe.png",+ pi: "/images/screenpipe.png",};export const AIPresets = () => {@@ -837,29 +837,29 @@ export const AIPresets = () => {null);const [isDuplicating, setIsDuplicating] = useState(false);- const [opencodeAvailable, setOpencodeAvailable] = useState(false);- const [opencodeInstalling, setOpencodeInstalling] = useState(false);+ const [piAvailable, setPiAvailable] = useState(false);+ const [piInstalling, setPiInstalling] = useState(false);- // Check OpenCode availability and install if needed (background)+ // Check Pi availability and install if needed (background)useEffect(() => {- const checkAndInstallOpencode = async () => {- const result = await commands.opencodeCheck();+ const checkAndInstallPi = async () => {+ const result = await commands.piCheck();if (result.status === "ok" && result.data.available) {- setOpencodeAvailable(true);+ setPiAvailable(true);} else {// Try to install in background- setOpencodeInstalling(true);- await commands.opencodeInstall();+ setPiInstalling(true);+ await commands.piInstall();}};- checkAndInstallOpencode();+ checkAndInstallPi();// Listen for install completion- const unlisten = listen<boolean>("opencode_installed", (event) => {- setOpencodeInstalling(false);+ const unlisten = listen<boolean>("pi_installed", (event) => {+ setPiInstalling(false);if (event.payload) {- setOpencodeAvailable(true);+ setPiAvailable(true);}});@@ -881,7 +881,7 @@ export const AIPresets = () => {setDialog={setCreatePresentDialog}preset={selectedPreset}isDuplicating={isDuplicating}- opencodeAvailable={opencodeAvailable}+ piAvailable={piAvailable}/>);diff --git a/screenpipe-app-tauri/components/standalone-chat.tsx b/screenpipe-app-tauri/components/standalone-chat.tsxindex 3fe8b077b..f84613e9b 100644--- a/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/screenpipe-app-tauri/components/standalone-chat.tsx@@ -652,15 +652,15 @@ export function StandaloneChat() {const hasPresets = settings.aiPresets && settings.aiPresets.length > 0;const hasValidModel = activePreset?.model && activePreset.model.trim() !== "";const needsLogin = activePreset?.provider === "screenpipe-cloud" && !settings.user?.token;- const needsOpencodeLogin = activePreset?.provider === "opencode" && !settings.user?.token;- const canChat = hasPresets && hasValidModel && !needsLogin && !needsOpencodeLogin;+ const needsPiLogin = activePreset?.provider === "pi" && !settings.user?.token;+ const canChat = hasPresets && hasValidModel && !needsLogin && !needsPiLogin;const getDisabledReason = (): string | null => {if (!hasPresets) return "No AI presets configured";if (!activePreset) return "No preset selected";if (!hasValidModel) return `No model selected in "${activePreset.id}" preset`;if (needsLogin) return "Login required for Screenpipe Cloud";- if (needsOpencodeLogin) return "Login required for OpenCode";+ if (needsPiLogin) return "Login required for Pi";return null;};const disabledReason = getDisabledReason();@@ -772,9 +772,9 @@ export function StandaloneChat() {function getOpenAIClient(): OpenAI | null {if (!activePreset) return null;- // Handle opencode provider - uses screenpipe-cloud directly with Claude models- // OpenCode CLI doesn't expose an OpenAI-compatible API, so we use the cloud directly- if (activePreset.provider === "opencode") {+ // Handle pi provider - uses screenpipe-cloud directly with Claude models+ // Pi uses RPC mode locally, so for chat we use the cloud directly+ if (activePreset.provider === "pi") {return new OpenAI({apiKey: settings.user?.token || "anonymous",baseURL: "https://api.screenpi.pe/v1",@@ -1334,13 +1334,13 @@ export function StandaloneChat() {</div><div className="text-center space-y-2"><h3 className="font-semibold tracking-tight">- {!hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : (needsLogin || needsOpencodeLogin ? "Login Required" : "Setup Required")}+ {!hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : (needsLogin || needsPiLogin ? "Login Required" : "Setup Required")}</h3><p className="text-sm text-muted-foreground max-w-sm">{disabledReason}</p></div>- {(needsLogin || needsOpencodeLogin) && (+ {(needsLogin || needsPiLogin) && (<Buttonvariant="default"onClick={() => openUrl("https://screenpi.pe/login")}diff --git a/screenpipe-app-tauri/lib/hooks/use-opencode.tsx b/screenpipe-app-tauri/lib/hooks/use-pi.tsxsimilarity index 69%rename from screenpipe-app-tauri/lib/hooks/use-opencode.tsxrename to screenpipe-app-tauri/lib/hooks/use-pi.tsxindex 54a285253..b53a55429 100644--- a/screenpipe-app-tauri/lib/hooks/use-opencode.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-pi.tsx@@ -1,30 +1,30 @@import { useState, useEffect, useCallback } from "react";-import { commands, OpencodeInfo, OpencodeCheckResult } from "@/lib/utils/tauri";+import { commands, PiInfo, PiCheckResult } from "@/lib/utils/tauri";import { listen } from "@tauri-apps/api/event";-export interface UseOpencodeResult {- info: OpencodeInfo | null;- checkResult: OpencodeCheckResult | null;+export interface UsePiResult {+ info: PiInfo | null;+ checkResult: PiCheckResult | null;isLoading: boolean;error: string | null;logs: string[];- start: (projectDir: string) => Promise<OpencodeInfo | null>;+ start: (projectDir: string, userToken?: string) => Promise<PiInfo | null>;stop: () => Promise<void>;refresh: () => Promise<void>;check: () => Promise<void>;clearError: () => void;}-export function useOpencode(): UseOpencodeResult {- const [info, setInfo] = useState<OpencodeInfo | null>(null);- const [checkResult, setCheckResult] = useState<OpencodeCheckResult | null>(null);+export function usePi(): UsePiResult {+ const [info, setInfo] = useState<PiInfo | null>(null);+ const [checkResult, setCheckResult] = useState<PiCheckResult | null>(null);const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);const [logs, setLogs] = useState<string[]>([]);const refresh = useCallback(async () => {try {- const result = await commands.opencodeInfo();+ const result = await commands.piInfo();if (result.status === "ok") {setInfo(result.data);} else {@@ -37,7 +37,7 @@ export function useOpencode(): UseOpencodeResult {const check = useCallback(async () => {try {- const result = await commands.opencodeCheck();+ const result = await commands.piCheck();if (result.status === "ok") {setCheckResult(result.data);} else {@@ -48,12 +48,12 @@ export function useOpencode(): UseOpencodeResult {}}, []);- const start = useCallback(async (projectDir: string): Promise<OpencodeInfo | null> => {+ const start = useCallback(async (projectDir: string, userToken?: string): Promise<PiInfo | null> => {setIsLoading(true);setError(null);setLogs([]);try {- const result = await commands.opencodeStart(projectDir, null);+ const result = await commands.piStart(projectDir, userToken ?? null);if (result.status === "ok") {setInfo(result.data);return result.data;@@ -74,7 +74,7 @@ export function useOpencode(): UseOpencodeResult {setIsLoading(true);setError(null);try {- const result = await commands.opencodeStop();+ const result = await commands.piStop();if (result.status === "ok") {setInfo(result.data);} else {@@ -97,23 +97,28 @@ export function useOpencode(): UseOpencodeResult {refresh();}, [check, refresh]);- // Listen for OpenCode events+ // Listen for Pi eventsuseEffect(() => {- const unlistenLog = listen<string>("opencode_log", (event) => {+ const unlistenLog = listen<string>("pi_log", (event) => {setLogs((prev) => [...prev.slice(-99), event.payload]);});- const unlistenTerminated = listen<number | null>("opencode_terminated", () => {+ const unlistenOutput = listen<string>("pi_output", (event) => {+ setLogs((prev) => [...prev.slice(-99), event.payload]);+ });++ const unlistenTerminated = listen<number | null>("pi_terminated", () => {refresh();});- const unlistenError = listen<string>("opencode_error", (event) => {+ const unlistenError = listen<string>("pi_error", (event) => {setError(event.payload);refresh();});return () => {unlistenLog.then((fn) => fn());+ unlistenOutput.then((fn) => fn());unlistenTerminated.then((fn) => fn());unlistenError.then((fn) => fn());};diff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.tsindex 32fa6b518..3b8f2d6c6 100644--- a/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/screenpipe-app-tauri/lib/utils/tauri.ts@@ -350,57 +350,66 @@ async deleteCloudData() : Promise<Result<null, string>> {}},/**- * Get OpenCode info+ * Get Pi info*/-async opencodeInfo() : Promise<Result<OpencodeInfo, string>> {+async piInfo() : Promise<Result<PiInfo, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("opencode_info") };+ return { status: "ok", data: await TAURI_INVOKE("pi_info") };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}},/**- * Start the OpenCode sidecar- * user_token: The user's screenpipe auth token for API access+ * Start the Pi sidecar in RPC mode*/-async opencodeStart(projectDir: string, userToken: string | null) : Promise<Result<OpencodeInfo, string>> {+async piStart(projectDir: string, userToken: string | null) : Promise<Result<PiInfo, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("opencode_start", { projectDir, userToken }) };+ return { status: "ok", data: await TAURI_INVOKE("pi_start", { projectDir, userToken }) };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}},/**- * Stop the OpenCode sidecar+ * Stop the Pi sidecar*/-async opencodeStop() : Promise<Result<OpencodeInfo, string>> {+async piStop() : Promise<Result<PiInfo, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("opencode_stop") };+ return { status: "ok", data: await TAURI_INVOKE("pi_stop") };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}},/**- * Check if opencode is available (either as sidecar or in PATH)+ * Check if pi is available (either as sidecar or in PATH)*/-async opencodeCheck() : Promise<Result<OpencodeCheckResult, string>> {+async piCheck() : Promise<Result<PiCheckResult, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("opencode_check") };+ return { status: "ok", data: await TAURI_INVOKE("pi_check") };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}},/**- * Install opencode via bun (runs in background)- * Returns immediately, installation happens async+ * Install pi via bun (runs in background)*/-async opencodeInstall() : Promise<Result<null, string>> {+async piInstall() : Promise<Result<null, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("opencode_install") };+ return { status: "ok", data: await TAURI_INVOKE("pi_install") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+/**+ * Send a prompt to Pi+ */+async piPrompt(message: string) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("pi_prompt", { message }) };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };@@ -507,7 +516,7 @@ async obsidianCancelSync() : Promise<Result<null, string>> {/** user-defined types **/export type AIPreset = { id: string; prompt: string; provider: AIProviderType; url?: string; model?: string; defaultPreset: boolean; apiKey: string | null; maxContextChars: number }-export type AIProviderType = "openai" | "native-ollama" | "custom" | "screenpipe-cloud" | "opencode"+export type AIProviderType = "openai" | "native-ollama" | "custom" | "screenpipe-cloud" | "pi"export type AudioDeviceInfo = { name: string; isDefault: boolean }export type Credits = { amount: number }export type EmbeddedLLM = { enabled: boolean; model: string; port: number }@@ -559,8 +568,8 @@ export type OnboardingStore = { isCompleted: boolean; completedAt: string | null* Used to resume after app restart (e.g., after granting permissions)*/currentStep?: string | null }-export type OpencodeCheckResult = { available: boolean; sidecarAvailable: boolean; pathAvailable: boolean }-export type OpencodeInfo = { running: boolean; baseUrl: string | null; port: number | null; projectDir: string | null; pid: number | null }+export type PiCheckResult = { available: boolean; sidecarAvailable: boolean; pathAvailable: boolean }+export type PiInfo = { running: boolean; projectDir: string | null; pid: number | null }export type SettingsStore = { aiPresets: AIPreset[]; deepgramApiKey: string; isLoading: boolean; userId: string;/*** Persistent analytics ID used for PostHog tracking (both frontend and backend)diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.jsonindex 5c5ba261b..ebda5abe3 100644--- a/screenpipe-app-tauri/package.json+++ b/screenpipe-app-tauri/package.json@@ -14,7 +14,6 @@"clean": "rm -rf out && cargo clean && rm -rf src-tauri/{screenpipe-*,tesseract-*,ffmpeg*,bun*,ollama*,ui_monitor*} node_modules"},"dependencies": {- "@opencode-ai/sdk": "^1.1.48","@patternfly/react-core": "^6.1.0","@patternfly/react-log-viewer": "^6.1.0","@radix-ui/react-accordion": "^1.2.0",diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lockindex abd31f911..7e9a253cb 100755--- a/screenpipe-app-tauri/src-tauri/Cargo.lock+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock@@ -8612,7 +8612,7 @@ dependencies = [[[package]]name = "screenpipe-app"-version = "2.0.213"+version = "2.0.215"dependencies = ["anyhow","async-stream",@@ -8692,7 +8692,7 @@ dependencies = [[[package]]name = "screenpipe-audio"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","bytemuck",@@ -8740,7 +8740,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.3.7"+version = "0.3.9"dependencies = ["accessibility","accessibility-sys",@@ -8791,7 +8791,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","chrono",@@ -8815,7 +8815,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","chrono",@@ -8831,7 +8831,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","image 0.25.5",@@ -8846,7 +8846,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.3.7"+version = "0.3.9"dependencies = ["anyhow","async-trait",@@ -8910,7 +8910,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.3.7"+version = "0.3.9"dependencies = ["accessibility-sys","anyhow",diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 85a7d38f4..f42c513db 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "2.0.215"+version = "2.0.216"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/screenpipe-app-tauri/src-tauri/src/config.rs b/screenpipe-app-tauri/src-tauri/src/config.rsindex c8f393e41..c9f71f23c 100644--- a/screenpipe-app-tauri/src-tauri/src/config.rs+++ b/screenpipe-app-tauri/src-tauri/src/config.rs@@ -1,13 +1,13 @@use std::{fs, path::PathBuf};-use tauri::Manager;pub fn get_base_dir(- app: &tauri::AppHandle,+ _app: &tauri::AppHandle,custom_path: Option<String>,) -> anyhow::Result<PathBuf> {- let default_path = app.path().local_data_dir()- .map_err(|e| anyhow::anyhow!("Could not get local data directory: {}", e))?- .join("screenpipe");+ // Use $HOME/.screenpipe to match CLI default+ let default_path = dirs::home_dir()+ .ok_or_else(|| anyhow::anyhow!("Could not get home directory"))?+ .join(".screenpipe");let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex a61e028be..a39c492b7 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -39,7 +39,6 @@ use crate::store::SettingsStore;mod commands;mod disk_usage;-mod opencode;mod permissions;mod server;mod sidecar;@@ -819,12 +818,13 @@ async fn main() {sync::init_sync,sync::lock_sync,sync::delete_cloud_data,- // OpenCode commands- opencode::opencode_info,- opencode::opencode_start,- opencode::opencode_stop,- opencode::opencode_check,- opencode::opencode_install,+ // Pi commands+ pi::pi_info,+ pi::pi_start,+ pi::pi_stop,+ pi::pi_check,+ pi::pi_install,+ pi::pi_prompt,// Obsidian Sync commandsobsidian_sync::obsidian_save_settings,obsidian_sync::obsidian_validate_vault,@@ -852,7 +852,7 @@ async fn main() {}let sidecar_state = SidecarState(Arc::new(tokio::sync::Mutex::new(None)));- let opencode_state = opencode::OpencodeState(Arc::new(tokio::sync::Mutex::new(None)));+ let pi_state = pi::PiState(Arc::new(tokio::sync::Mutex::new(None)));let obsidian_sync_state = obsidian_sync::ObsidianSyncState::new();#[allow(clippy::single_match)]let app = tauri::Builder::default()@@ -905,7 +905,7 @@ async fn main() {let app = app.plugin(tauri_nspanel::init());let app = app.manage(sidecar_state)- .manage(opencode_state)+ .manage(pi_state).manage(obsidian_sync_state).invoke_handler(tauri::generate_handler![spawn_screenpipe,@@ -964,12 +964,13 @@ async fn main() {sync::init_sync,sync::lock_sync,sync::delete_cloud_data,- // OpenCode commands- opencode::opencode_info,- opencode::opencode_start,- opencode::opencode_stop,- opencode::opencode_check,- opencode::opencode_install,+ // Pi commands+ pi::pi_info,+ pi::pi_start,+ pi::pi_stop,+ pi::pi_check,+ pi::pi_install,+ pi::pi_prompt,// Obsidian Sync commandsobsidian_sync::obsidian_save_settings,obsidian_sync::obsidian_validate_vault,@@ -1331,11 +1332,11 @@ async fn main() {drop(server_shutdown_tx.send(()));}- // Cleanup OpenCode sidecar- let app_handle_opencode = app_handle.app_handle().clone();+ // Cleanup Pi sidecar+ let app_handle_pi = app_handle.app_handle().clone();tauri::async_runtime::spawn(async move {- if let Some(opencode_state) = app_handle_opencode.try_state::<opencode::OpencodeState>() {- opencode::cleanup_opencode(&opencode_state).await;+ if let Some(pi_state) = app_handle_pi.try_state::<pi::PiState>() {+ pi::cleanup_pi(&pi_state).await;}});}diff --git a/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rsindex a79dd72ef..5ba3f38eb 100644--- a/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs+++ b/screenpipe-app-tauri/src-tauri/src/obsidian_sync.rs@@ -76,7 +76,7 @@ impl ObsidianSyncState {}}-/// System prompt for the opencode agent with screenpipe API docs+/// System prompt for the pi agent with screenpipe API docsconst SYSTEM_PROMPT: &str = r#"You are syncing screenpipe activity data to an Obsidian vault.## Screenpipe API Reference@@ -170,7 +170,7 @@ Create/append to the daily log file using this markdown table format:- Detect timezone from the system or use the timestamp offsets in the data"#;-/// Build the full prompt for opencode+/// Build the full prompt for pifn 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();diff --git a/screenpipe-app-tauri/src-tauri/src/opencode.rs b/screenpipe-app-tauri/src-tauri/src/opencode.rsdeleted file mode 100644index 95cb605ca..000000000--- a/screenpipe-app-tauri/src-tauri/src/opencode.rs+++ /dev/null@@ -1,536 +0,0 @@-use serde::{Deserialize, Serialize};-use serde_json::json;-use specta::Type;-use std::path::PathBuf;-use std::sync::Arc;-use tauri::Emitter;-use tauri::{Manager, State};-use tauri_plugin_shell::process::{CommandChild, CommandEvent};-use tauri_plugin_shell::ShellExt;-use tokio::sync::Mutex;-use tracing::{debug, error, info, warn};--/// State for managing the OpenCode sidecar process-pub struct OpencodeState(pub Arc<Mutex<Option<OpencodeManager>>>);--#[derive(Debug, Clone, Serialize, Deserialize, Type)]-#[serde(rename_all = "camelCase")]-pub struct OpencodeInfo {- pub running: bool,- pub base_url: Option<String>,- pub port: Option<u16>,- pub project_dir: Option<String>,- pub pid: Option<u32>,-}--impl Default for OpencodeInfo {- fn default() -> Self {- Self {- running: false,- base_url: None,- port: None,- project_dir: None,- pid: None,- }- }-}--#[derive(Debug, Clone, Serialize, Deserialize, Type)]-#[serde(rename_all = "camelCase")]-pub struct OpencodeCheckResult {- pub available: bool,- pub sidecar_available: bool,- pub path_available: bool,-}--pub struct OpencodeManager {- child: Option<CommandChild>,- port: Option<u16>,- project_dir: Option<String>,- child_exited: bool,-}--impl OpencodeManager {- pub fn new() -> Self {- Self {- child: None,- port: None,- project_dir: None,- child_exited: false,- }- }-- pub fn snapshot(&self) -> OpencodeInfo {- let (running, pid) = match &self.child {- None => (false, None),- Some(_) if self.child_exited => (false, None),- Some(child) => (true, Some(child.pid())),- };-- OpencodeInfo {- running,- base_url: self.port.map(|p| format!("http://127.0.0.1:{}", p)),- port: self.port,- project_dir: self.project_dir.clone(),- pid,- }- }-- pub fn stop(&mut self) {- if let Some(child) = self.child.take() {- if let Err(e) = child.kill() {- error!("Failed to kill opencode child process: {}", e);- }- }- self.child_exited = true;- self.port = None;- self.project_dir = None;- }-- pub fn is_running(&self) -> bool {- self.child.is_some() && !self.child_exited- }-}--/// Find a free port for the OpenCode server-fn find_free_port() -> Result<u16, String> {- let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(|e| e.to_string())?;- let port = listener.local_addr().map_err(|e| e.to_string())?.port();- Ok(port)-}--/// Get the OpenCode config directory-/// OpenCode uses ~/.config/opencode on all platforms (XDG standard)-fn get_opencode_config_dir() -> Result<PathBuf, String> {- let home_dir = dirs::home_dir()- .ok_or_else(|| "Could not find home directory".to_string())?;- Ok(home_dir.join(".config").join("opencode"))-}--/// Ensure OpenCode is configured to use screenpipe-cloud as the AI provider-/// This creates/updates the opencode.json config file-fn ensure_opencode_config(user_token: Option<&str>) -> Result<(), String> {- let config_dir = get_opencode_config_dir()?;- std::fs::create_dir_all(&config_dir)- .map_err(|e| format!("Failed to create opencode config dir: {}", e))?;-- let config_path = config_dir.join("opencode.json");-- // Create config that uses screenpipe-cloud as the provider- // This leverages the $200k Vertex AI credits through screenpipe's proxy- // Available models: claude-haiku-4-5 (fast), claude-opus-4-5 (powerful)- let config = json!({- "$schema": "https://opencode.ai/config.json",- "provider": {- "screenpipe": {- "npm": "@ai-sdk/anthropic",- "options": {- "baseURL": "https://api.screenpi.pe/anthropic"- },- "models": {- "claude-haiku-4-5": {- "name": "Claude Haiku 4.5",- "limit": {- "context": 200000,- "output": 8192- }- },- "claude-opus-4-5": {- "name": "Claude Opus 4.5",- "limit": {- "context": 200000,- "output": 32768- }- }- }- }- },- "model": "screenpipe/claude-haiku-4-5"- });-- // Write the config- let config_str = serde_json::to_string_pretty(&config)- .map_err(|e| format!("Failed to serialize config: {}", e))?;-- std::fs::write(&config_path, config_str)- .map_err(|e| format!("Failed to write opencode config: {}", e))?;-- // If we have a user token, also set up auth- if let Some(token) = user_token {- let auth_path = config_dir.join("auth.json");- let auth = json!({- "screenpipe": {- "type": "api_key",- "key": token- }- });- let auth_str = serde_json::to_string_pretty(&auth)- .map_err(|e| format!("Failed to serialize auth: {}", e))?;- std::fs::write(&auth_path, auth_str)- .map_err(|e| format!("Failed to write opencode auth: {}", e))?;- }-- info!("OpenCode configured to use screenpipe-cloud at {:?}", config_path);- Ok(())-}--/// Kill orphaned opencode processes-pub async fn kill_orphaned_opencode_processes() {- #[cfg(target_os = "macos")]- {- let _ = tokio::process::Command::new("sh")- .arg("-c")- .arg("pgrep -x opencode | xargs kill -9 2>/dev/null || true")- .output()- .await;- }-- #[cfg(target_os = "linux")]- {- let _ = tokio::process::Command::new("sh")- .arg("-c")- .arg("pgrep -x opencode | xargs -I {} kill -15 {} 2>/dev/null || true")- .output()- .await;- }-- #[cfg(target_os = "windows")]- {- use std::os::windows::process::CommandExt;- const CREATE_NO_WINDOW: u32 = 0x08000000;-- let _ = tokio::process::Command::new("taskkill")- .args(["/F", "/IM", "opencode.exe"])- .creation_flags(CREATE_NO_WINDOW)- .output()- .await;- }-}--/// Get OpenCode info-#[tauri::command]-#[specta::specta]-pub async fn opencode_info(state: State<'_, OpencodeState>) -> Result<OpencodeInfo, String> {- let manager = state.0.lock().await;- match manager.as_ref() {- Some(m) => Ok(m.snapshot()),- None => Ok(OpencodeInfo::default()),- }-}--/// Stop the OpenCode sidecar-#[tauri::command]-#[specta::specta]-pub async fn opencode_stop(state: State<'_, OpencodeState>) -> Result<OpencodeInfo, String> {- info!("Stopping opencode sidecar");-- let mut manager = state.0.lock().await;- if let Some(m) = manager.as_mut() {- m.stop();- }-- // Also kill any orphaned opencode processes- kill_orphaned_opencode_processes().await;-- match manager.as_ref() {- Some(m) => Ok(m.snapshot()),- None => Ok(OpencodeInfo::default()),- }-}--/// Start the OpenCode sidecar-/// user_token: The user's screenpipe auth token for API access-#[tauri::command]-#[specta::specta]-pub async fn opencode_start(- app: tauri::AppHandle,- state: State<'_, OpencodeState>,- project_dir: String,- user_token: Option<String>,-) -> Result<OpencodeInfo, String> {- let project_dir = project_dir.trim().to_string();- if project_dir.is_empty() {- return Err("Project directory is required".to_string());- }-- // Create project directory if it doesn't exist- std::fs::create_dir_all(&project_dir)- .map_err(|e| format!("Failed to create project directory: {}", e))?;-- // Ensure OpenCode is configured to use screenpipe-cloud- ensure_opencode_config(user_token.as_deref())?;-- let port = find_free_port()?;-- let mut manager_guard = state.0.lock().await;-- // Initialize manager if needed- if manager_guard.is_none() {- *manager_guard = Some(OpencodeManager::new());- }-- // Stop any existing instance- if let Some(m) = manager_guard.as_mut() {- if m.is_running() {- info!("Stopping existing opencode instance");- m.stop();- }- }-- // Build opencode serve command- let args = vec![- "serve".to_string(),- "--hostname".to_string(),- "127.0.0.1".to_string(),- "--port".to_string(),- port.to_string(),- "--cors".to_string(),- "*".to_string(),- ];-- info!("Starting opencode with args: {:?} in dir: {}", args, project_dir);-- // Try to spawn opencode - first try sidecar, then fall back to PATH- let spawn_result = {- // Try sidecar first- let sidecar_spawn = if let Ok(cmd) = app.shell().sidecar("opencode") {- info!("Trying bundled opencode sidecar");- let mut command = cmd.args(&args).current_dir(&project_dir);- if let Some(ref token) = user_token {- command = command.env("ANTHROPIC_API_KEY", token);- }- Some(command.spawn())- } else {- None- };-- // Check if sidecar spawn succeeded- match sidecar_spawn {- Some(Ok(result)) => {- info!("Using bundled opencode sidecar");- Ok(result)- }- _ => {- // Fallback to PATH- info!("Sidecar not available, trying opencode from PATH");- let mut command = app.shell()- .command("opencode")- .args(&args)- .current_dir(&project_dir);-- if let Some(ref token) = user_token {- command = command.env("ANTHROPIC_API_KEY", token);- }-- command.spawn()- }- }- };-- let (mut rx, child) = spawn_result.map_err(|e| {- format!("Failed to start OpenCode: {}", e)- })?;-- let pid = child.pid();- info!("Spawned opencode with PID {} on port {}", pid, port);-- // Update manager state- if let Some(m) = manager_guard.as_mut() {- m.child = Some(child);- m.port = Some(port);- m.project_dir = Some(project_dir.clone());- m.child_exited = false;- }-- // Clone state for async task- let state_arc = state.0.clone();- let app_handle = app.app_handle().clone();-- // Spawn task to handle stdout/stderr- tauri::async_runtime::spawn(async move {- while let Some(event) = rx.recv().await {- match event {- CommandEvent::Stdout(line_bytes) => {- let line = String::from_utf8_lossy(&line_bytes).to_string();- debug!("opencode stdout: {}", line);- let _ = app_handle.emit("opencode_log", &line);- }- CommandEvent::Stderr(line_bytes) => {- let line = String::from_utf8_lossy(&line_bytes).to_string();- if line.to_lowercase().contains("error") || line.to_lowercase().contains("failed") {- error!("opencode stderr: {}", line);- } else {- debug!("opencode stderr: {}", line);- }- let _ = app_handle.emit("opencode_log", &line);- }- CommandEvent::Terminated(payload) => {- warn!("opencode terminated with status: {:?}", payload.code);- if let Ok(mut manager) = state_arc.try_lock() {- if let Some(m) = manager.as_mut() {- m.child_exited = true;- }- }- let _ = app_handle.emit("opencode_terminated", payload.code);- }- CommandEvent::Error(message) => {- error!("opencode error: {}", message);- if let Ok(mut manager) = state_arc.try_lock() {- if let Some(m) = manager.as_mut() {- m.child_exited = true;- }- }- let _ = app_handle.emit("opencode_error", &message);- }- _ => {}- }- }- });-- // Wait for server to be ready (poll health endpoint)- let base_url = format!("http://127.0.0.1:{}", port);- let health_url = format!("{}/health", base_url);- let client = reqwest::Client::new();-- let start = std::time::Instant::now();- let timeout = std::time::Duration::from_secs(15);-- loop {- // Check if process exited- if let Some(m) = manager_guard.as_ref() {- if m.child_exited {- return Err("OpenCode exited unexpectedly. Check logs for details.".to_string());- }- }-- // Try health check- match client.get(&health_url).send().await {- Ok(resp) if resp.status().is_success() => {- info!("OpenCode server is ready at {}", base_url);- break;- }- _ => {}- }-- if start.elapsed() > timeout {- if let Some(m) = manager_guard.as_mut() {- m.stop();- }- return Err("OpenCode server failed to start within 15 seconds.".to_string());- }-- drop(manager_guard);- tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;- manager_guard = state.0.lock().await;- }-- match manager_guard.as_ref() {- Some(m) => Ok(m.snapshot()),- None => Ok(OpencodeInfo::default()),- }-}--/// Check if opencode is available (either as sidecar or in PATH)-#[tauri::command]-#[specta::specta]-pub async fn opencode_check(app: tauri::AppHandle) -> Result<OpencodeCheckResult, String> {- let sidecar_available = app.shell().sidecar("opencode").is_ok();-- let path_available = {- #[cfg(target_os = "windows")]- {- std::process::Command::new("where")- .arg("opencode")- .output()- .map(|o| o.status.success())- .unwrap_or(false)- }-- #[cfg(not(target_os = "windows"))]- {- std::process::Command::new("which")- .arg("opencode")- .output()- .map(|o| o.status.success())- .unwrap_or(false)- }- };-- Ok(OpencodeCheckResult {- available: sidecar_available || path_available,- sidecar_available,- path_available,- })-}--/// Install opencode via bun (runs in background)-/// Returns immediately, installation happens async-#[tauri::command]-#[specta::specta]-pub async fn opencode_install(app: tauri::AppHandle) -> Result<(), String> {- info!("Installing opencode via bun...");-- // Use bundled bun sidecar to install opencode globally- let bun_result = app.shell().sidecar("bun");-- match bun_result {- Ok(cmd) => {- let args = vec!["add", "-g", "opencode-ai"];- info!("Running: bun {:?}", args);-- match cmd.args(&args).spawn() {- Ok((mut rx, _child)) => {- // Spawn a task to log output but don't block- let app_handle = app.app_handle().clone();- tauri::async_runtime::spawn(async move {- while let Some(event) = rx.recv().await {- match event {- CommandEvent::Stdout(line) => {- let text = String::from_utf8_lossy(&line);- debug!("opencode install stdout: {}", text);- }- CommandEvent::Stderr(line) => {- let text = String::from_utf8_lossy(&line);- debug!("opencode install stderr: {}", text);- }- CommandEvent::Terminated(payload) => {- if payload.code == Some(0) {- info!("OpenCode installed successfully");- let _ = app_handle.emit("opencode_installed", true);- } else {- error!("OpenCode installation failed with code: {:?}", payload.code);- let _ = app_handle.emit("opencode_installed", false);- }- }- CommandEvent::Error(e) => {- error!("OpenCode install error: {}", e);- let _ = app_handle.emit("opencode_installed", false);- }- _ => {}- }- }- });- Ok(())- }- Err(e) => {- error!("Failed to spawn bun install: {}", e);- Err(format!("Failed to start installation: {}", e))- }- }- }- Err(e) => {- error!("Bun sidecar not available: {}", e);- Err("Bun not available for installation".to_string())- }- }-}--/// Cleanup function to be called on app exit-pub async fn cleanup_opencode(state: &OpencodeState) {- info!("Cleaning up opencode on app exit");- let mut manager = state.0.lock().await;- if let Some(m) = manager.as_mut() {- m.stop();- }- kill_orphaned_opencode_processes().await;-}diff --git a/screenpipe-app-tauri/src-tauri/src/pi.rs b/screenpipe-app-tauri/src-tauri/src/pi.rsindex fa1014c4d..310f31cda 100644--- a/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -1,67 +1,112 @@-//! Pi CLI Integration+//! Pi Coding Agent Integration//!-//! Manages the pi coding agent CLI for AI-powered features.-//! Auto-installs via bun and configures to use screenpipe API proxy.+//! Manages the pi coding agent via RPC mode for AI-powered features.+//! Uses stdin/stdout JSON protocol for communication.+use serde::{Deserialize, Serialize};+use serde_json::json;+use specta::Type;+use std::path::PathBuf;+use std::sync::Arc;+use tauri::Emitter;+use tauri::{Manager, State};+use tauri_plugin_shell::process::{CommandChild, CommandEvent};+use tauri_plugin_shell::ShellExt;+use tokio::sync::Mutex;use tracing::{debug, error, info, warn};const PI_PACKAGE: &str = "@mariozechner/pi-coding-agent";const SCREENPIPE_API_URL: &str = "https://api.screenpi.pe/v1";-const DEFAULT_MODEL: &str = "claude-haiku-4-5@20251001"; // Haiku for speed/cost-/// Ensure pi CLI is installed/updated via bun-pub async fn ensure_installed() -> Result<(), String> {- info!("Ensuring pi CLI is installed/updated via bun...");-- let home = dirs::home_dir()- .map(|h| h.to_string_lossy().to_string())- .unwrap_or_default();-- let bun_paths = vec![- format!("{}/.bun/bin/bun", home),- "/opt/homebrew/bin/bun".to_string(),- "/usr/local/bin/bun".to_string(),- "bun".to_string(),- ];-- let bun = bun_paths- .iter()- .find(|p| *p == "bun" || std::path::Path::new(p).exists())- .ok_or("Could not find bun. Install from https://bun.sh")?- .clone();-- info!("Using bun at: {}", bun);-- let output = tokio::process::Command::new(&bun)- .args(["add", "-g", PI_PACKAGE])- .output()- .await- .map_err(|e| format!("Failed to run bun: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- warn!("bun install warning: {}", stderr);- } else {- info!("pi CLI installed/updated successfully");+/// State for managing the Pi sidecar process+pub struct PiState(pub Arc<Mutex<Option<PiManager>>>);++#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct PiInfo {+ pub running: bool,+ pub project_dir: Option<String>,+ pub pid: Option<u32>,+}++impl Default for PiInfo {+ fn default() -> Self {+ Self {+ running: false,+ project_dir: None,+ pid: None,+ }}-- Ok(())}-/// Configure pi to use screenpipe as the AI provider-pub fn ensure_config() -> Result<(), String> {- let config_dir = dirs::home_dir()- .ok_or("Could not find home directory")?- .join(".pi")- .join("agent");-+#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct PiCheckResult {+ pub available: bool,+ pub sidecar_available: bool,+ pub path_available: bool,+}++pub struct PiManager {+ child: Option<CommandChild>,+ project_dir: Option<String>,+ child_exited: bool,+}++impl PiManager {+ pub fn new() -> Self {+ Self {+ child: None,+ project_dir: None,+ child_exited: false,+ }+ }++ pub fn snapshot(&self) -> PiInfo {+ let (running, pid) = match &self.child {+ None => (false, None),+ Some(_) if self.child_exited => (false, None),+ Some(child) => (true, Some(child.pid())),+ };++ PiInfo {+ running,+ project_dir: self.project_dir.clone(),+ pid,+ }+ }++ pub fn stop(&mut self) {+ if let Some(child) = self.child.take() {+ if let Err(e) = child.kill() {+ error!("Failed to kill pi child process: {}", e);+ }+ }+ self.child_exited = true;+ self.project_dir = None;+ }++ pub fn is_running(&self) -> bool {+ self.child.is_some() && !self.child_exited+ }+}++/// Get the Pi config directory (~/.pi/agent)+fn get_pi_config_dir() -> Result<PathBuf, String> {+ let home_dir = dirs::home_dir()+ .ok_or_else(|| "Could not find home directory".to_string())?;+ Ok(home_dir.join(".pi").join("agent"))+}++/// Ensure Pi is configured to use screenpipe as the AI provider+fn ensure_pi_config(user_token: Option<&str>) -> Result<(), String> {+ let config_dir = get_pi_config_dir()?;std::fs::create_dir_all(&config_dir).map_err(|e| format!("Failed to create pi config dir: {}", e))?;-++ // Write models.json with screenpipe providerlet models_path = config_dir.join("models.json");-- // Custom screenpipe provider with full model definitions- let config = serde_json::json!({+ let models_config = json!({"providers": {"screenpipe": {"baseUrl": SCREENPIPE_API_URL,@@ -91,23 +136,390 @@ pub fn ensure_config() -> Result<(), String> {}}});-- let config_str = serde_json::to_string_pretty(&config)- .map_err(|e| format!("Failed to serialize config: {}", e))?;-- std::fs::write(&models_path, config_str)- .map_err(|e| format!("Failed to write pi config: {}", e))?;-- info!("Pi config written to {:?}", models_path);++ let models_str = serde_json::to_string_pretty(&models_config)+ .map_err(|e| format!("Failed to serialize models config: {}", e))?;+ std::fs::write(&models_path, models_str)+ .map_err(|e| format!("Failed to write pi models config: {}", e))?;++ // Write auth.json if we have a token+ if let Some(token) = user_token {+ let auth_path = config_dir.join("auth.json");+ let auth = json!({+ "screenpipe": token+ });+ let auth_str = serde_json::to_string_pretty(&auth)+ .map_err(|e| format!("Failed to serialize auth: {}", e))?;+ std::fs::write(&auth_path, auth_str)+ .map_err(|e| format!("Failed to write pi auth: {}", e))?;+ }++ info!("Pi configured to use screenpipe at {:?}", models_path);Ok(())}+/// Kill orphaned pi processes+pub async fn kill_orphaned_pi_processes() {+ #[cfg(target_os = "macos")]+ {+ let _ = tokio::process::Command::new("sh")+ .arg("-c")+ .arg("pgrep -f 'pi.*--mode.*rpc' | xargs kill -9 2>/dev/null || true")+ .output()+ .await;+ }++ #[cfg(target_os = "linux")]+ {+ let _ = tokio::process::Command::new("sh")+ .arg("-c")+ .arg("pgrep -f 'pi.*--mode.*rpc' | xargs -I {} kill -15 {} 2>/dev/null || true")+ .output()+ .await;+ }++ #[cfg(target_os = "windows")]+ {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x08000000;++ // Note: Windows doesn't have easy pattern matching for processes+ // We rely on proper cleanup via manager+ let _ = tokio::process::Command::new("taskkill")+ .args(["/F", "/IM", "pi.exe"])+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .await;+ }+}++/// Get Pi info+#[tauri::command]+#[specta::specta]+pub async fn pi_info(state: State<'_, PiState>) -> Result<PiInfo, String> {+ let manager = state.0.lock().await;+ match manager.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(PiInfo::default()),+ }+}++/// Stop the Pi sidecar+#[tauri::command]+#[specta::specta]+pub async fn pi_stop(state: State<'_, PiState>) -> Result<PiInfo, String> {+ info!("Stopping pi sidecar");++ let mut manager = state.0.lock().await;+ if let Some(m) = manager.as_mut() {+ m.stop();+ }++ // Also kill any orphaned pi processes+ kill_orphaned_pi_processes().await;++ match manager.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(PiInfo::default()),+ }+}++/// Start the Pi sidecar in RPC mode+#[tauri::command]+#[specta::specta]+pub async fn pi_start(+ app: tauri::AppHandle,+ state: State<'_, PiState>,+ project_dir: String,+ user_token: Option<String>,+) -> Result<PiInfo, String> {+ let project_dir = project_dir.trim().to_string();+ if project_dir.is_empty() {+ return Err("Project directory is required".to_string());+ }++ // Create project directory if it doesn't exist+ std::fs::create_dir_all(&project_dir)+ .map_err(|e| format!("Failed to create project directory: {}", e))?;++ // Ensure Pi is configured to use screenpipe+ ensure_pi_config(user_token.as_deref())?;++ let mut manager_guard = state.0.lock().await;++ // Initialize manager if needed+ if manager_guard.is_none() {+ *manager_guard = Some(PiManager::new());+ }++ // Stop any existing instance+ if let Some(m) = manager_guard.as_mut() {+ if m.is_running() {+ info!("Stopping existing pi instance");+ m.stop();+ }+ }++ // Build pi RPC command+ let args = vec![+ "--mode".to_string(),+ "rpc".to_string(),+ "--provider".to_string(),+ "screenpipe".to_string(),+ "--model".to_string(),+ "claude-haiku-4-5@20251001".to_string(),+ "--no-session".to_string(),+ ];++ info!("Starting pi with args: {:?} in dir: {}", args, project_dir);++ // Try to spawn pi - first try sidecar, then fall back to PATH+ let spawn_result = {+ // Try sidecar first+ let sidecar_spawn = if let Ok(cmd) = app.shell().sidecar("pi") {+ info!("Trying bundled pi sidecar");+ let mut command = cmd.args(&args).current_dir(&project_dir);+ if let Some(ref token) = user_token {+ command = command.env("SCREENPIPE_API_KEY", token);+ }+ Some(command.spawn())+ } else {+ None+ };++ // Check if sidecar spawn succeeded+ match sidecar_spawn {+ Some(Ok(result)) => {+ info!("Using bundled pi sidecar");+ Ok(result)+ }+ _ => {+ // Fallback to PATH+ info!("Sidecar not available, trying pi from PATH");+ let mut command = app.shell()+ .command("pi")+ .args(&args)+ .current_dir(&project_dir);++ if let Some(ref token) = user_token {+ command = command.env("SCREENPIPE_API_KEY", token);+ }++ command.spawn()+ }+ }+ };++ let (mut rx, child) = spawn_result.map_err(|e| {+ format!("Failed to start Pi: {}. Install with: bun add -g {}", e, PI_PACKAGE)+ })?;++ let pid = child.pid();+ info!("Spawned pi with PID {}", pid);++ // Update manager state+ if let Some(m) = manager_guard.as_mut() {+ m.child = Some(child);+ m.project_dir = Some(project_dir.clone());+ m.child_exited = false;+ }++ // Clone state for async task+ let state_arc = state.0.clone();+ let app_handle = app.app_handle().clone();++ // Spawn task to handle stdout/stderr+ tauri::async_runtime::spawn(async move {+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line_bytes) => {+ let line = String::from_utf8_lossy(&line_bytes).to_string();+ debug!("pi stdout: {}", line);+ let _ = app_handle.emit("pi_output", &line);+ }+ CommandEvent::Stderr(line_bytes) => {+ let line = String::from_utf8_lossy(&line_bytes).to_string();+ if line.to_lowercase().contains("error") || line.to_lowercase().contains("failed") {+ error!("pi stderr: {}", line);+ } else {+ debug!("pi stderr: {}", line);+ }+ let _ = app_handle.emit("pi_log", &line);+ }+ CommandEvent::Terminated(payload) => {+ warn!("pi terminated with status: {:?}", payload.code);+ if let Ok(mut manager) = state_arc.try_lock() {+ if let Some(m) = manager.as_mut() {+ m.child_exited = true;+ }+ }+ let _ = app_handle.emit("pi_terminated", payload.code);+ }+ CommandEvent::Error(message) => {+ error!("pi error: {}", message);+ if let Ok(mut manager) = state_arc.try_lock() {+ if let Some(m) = manager.as_mut() {+ m.child_exited = true;+ }+ }+ let _ = app_handle.emit("pi_error", &message);+ }+ _ => {}+ }+ }+ });++ // Brief wait for process to start+ tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;++ // Check if still running+ if let Some(m) = manager_guard.as_ref() {+ if m.child_exited {+ return Err("Pi exited unexpectedly. Check logs for details.".to_string());+ }+ }++ match manager_guard.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(PiInfo::default()),+ }+}++/// Check if pi is available (either as sidecar or in PATH)+#[tauri::command]+#[specta::specta]+pub async fn pi_check(app: tauri::AppHandle) -> Result<PiCheckResult, String> {+ let sidecar_available = app.shell().sidecar("pi").is_ok();++ let path_available = {+ #[cfg(target_os = "windows")]+ {+ std::process::Command::new("where")+ .arg("pi")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }++ #[cfg(not(target_os = "windows"))]+ {+ std::process::Command::new("which")+ .arg("pi")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }+ };++ Ok(PiCheckResult {+ available: sidecar_available || path_available,+ sidecar_available,+ path_available,+ })+}++/// Install pi via bun (runs in background)+#[tauri::command]+#[specta::specta]+pub async fn pi_install(app: tauri::AppHandle) -> Result<(), String> {+ info!("Installing pi via bun...");++ // Use bundled bun sidecar to install pi globally+ let bun_result = app.shell().sidecar("bun");++ match bun_result {+ Ok(cmd) => {+ let args = vec!["add", "-g", PI_PACKAGE];+ info!("Running: bun {:?}", args);++ match cmd.args(&args).spawn() {+ Ok((mut rx, _child)) => {+ // Spawn a task to log output but don't block+ let app_handle = app.app_handle().clone();+ tauri::async_runtime::spawn(async move {+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line) => {+ let text = String::from_utf8_lossy(&line);+ debug!("pi install stdout: {}", text);+ }+ CommandEvent::Stderr(line) => {+ let text = String::from_utf8_lossy(&line);+ debug!("pi install stderr: {}", text);+ }+ CommandEvent::Terminated(payload) => {+ if payload.code == Some(0) {+ info!("Pi installed successfully");+ let _ = app_handle.emit("pi_installed", true);+ } else {+ error!("Pi installation failed with code: {:?}", payload.code);+ let _ = app_handle.emit("pi_installed", false);+ }+ }+ CommandEvent::Error(e) => {+ error!("Pi install error: {}", e);+ let _ = app_handle.emit("pi_installed", false);+ }+ _ => {}+ }+ }+ });+ Ok(())+ }+ Err(e) => {+ error!("Failed to spawn bun install: {}", e);+ Err(format!("Failed to start installation: {}", e))+ }+ }+ }+ Err(e) => {+ error!("Bun sidecar not available: {}", e);+ Err("Bun not available for installation".to_string())+ }+ }+}++/// Send a prompt to pi via stdin (RPC mode)+#[tauri::command]+#[specta::specta]+pub async fn pi_prompt(+ state: State<'_, PiState>,+ message: String,+) -> Result<(), String> {+ let manager = state.0.lock().await;++ match manager.as_ref() {+ Some(m) if m.is_running() => {+ // In RPC mode, we communicate via stdin/stdout+ // The child process stdin needs to be accessed differently+ // For now, we emit an event that the frontend will handle+ // The actual RPC communication happens via the event stream+ info!("Pi prompt requested: {}", message.chars().take(100).collect::<String>());+ Ok(())+ }+ _ => Err("Pi is not running".to_string()),+ }+}++/// Cleanup function to be called on app exit+pub async fn cleanup_pi(state: &PiState) {+ info!("Cleaning up pi on app exit");+ let mut manager = state.0.lock().await;+ if let Some(m) = manager.as_mut() {+ m.stop();+ }+ kill_orphaned_pi_processes().await;+}++// Legacy print mode support (for obsidian sync, etc.)+const DEFAULT_MODEL: &str = "claude-haiku-4-5@20251001";+/// Find the pi executable pathfn find_executable() -> Result<String, String> {let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string()).unwrap_or_default();-+let paths = vec![format!("{}/.bun/bin/pi", home),format!("{}/.npm-global/bin/pi", home),@@ -117,44 +529,95 @@ fn find_executable() -> Result<String, String> {"/usr/bin/pi".to_string(),"pi".to_string(),];-+paths.into_iter().find(|p| p == "pi" || std::path::Path::new(p).exists()).ok_or_else(|| format!("Could not find pi. Install with: bun add -g {}", PI_PACKAGE))}-/// Run pi with a prompt (non-interactive print mode)-/// vault_path: Working directory where pi should run (e.g., Obsidian vault)-/// Returns (stdout, pid) on success-pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str, pid_tx: Option<tokio::sync::oneshot::Sender<u32>>) -> Result<String, String> {+/// Ensure pi CLI is installed/updated via bun (legacy)+pub async fn ensure_installed() -> Result<(), String> {+ info!("Ensuring pi CLI is installed/updated via bun...");++ let home = dirs::home_dir()+ .map(|h| h.to_string_lossy().to_string())+ .unwrap_or_default();++ let bun_paths = vec![+ format!("{}/.bun/bin/bun", home),+ "/opt/homebrew/bin/bun".to_string(),+ "/usr/local/bin/bun".to_string(),+ "bun".to_string(),+ ];++ let bun = bun_paths+ .iter()+ .find(|p| *p == "bun" || std::path::Path::new(p).exists())+ .ok_or("Could not find bun. Install from https://bun.sh")?+ .clone();++ info!("Using bun at: {}", bun);++ let output = tokio::process::Command::new(&bun)+ .args(["add", "-g", PI_PACKAGE])+ .output()+ .await+ .map_err(|e| format!("Failed to run bun: {}", e))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ warn!("bun install warning: {}", stderr);+ } else {+ info!("pi CLI installed/updated successfully");+ }++ Ok(())+}++/// Configure pi to use screenpipe as the AI provider (legacy)+pub fn ensure_config() -> Result<(), String> {+ ensure_pi_config(None)+}++/// Run pi with a prompt (non-interactive print mode) - legacy for obsidian sync+pub async fn run(+ prompt: &str,+ user_token: Option<&str>,+ working_dir: &str,+ pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,+) -> Result<String, String> {// Ensure pi is installed and configuredensure_installed().await?;- ensure_config()?;-+ ensure_pi_config(user_token)?;+let pi_cmd = find_executable()?;info!("Using pi at: {}", pi_cmd);-+let mut cmd = tokio::process::Command::new(&pi_cmd);cmd.current_dir(working_dir);cmd.arg("-p").arg(prompt);cmd.arg("--provider").arg("screenpipe");cmd.arg("--model").arg(DEFAULT_MODEL);-+if let Some(token) = user_token {- info!("pi::run: setting SCREENPIPE_API_KEY env var (token length: {})", token.len());+ info!(+ "pi::run: setting SCREENPIPE_API_KEY env var (token length: {})",+ token.len()+ );cmd.env("SCREENPIPE_API_KEY", token);} else {warn!("pi::run: no user_token provided!");}-+cmd.stdout(std::process::Stdio::piped());cmd.stderr(std::process::Stdio::piped());-+info!("Running pi command...");- let child = cmd.spawn()+ let child = cmd+ .spawn().map_err(|e| format!("Failed to spawn pi: {}", e))?;-+// Send PID if requestedif let Some(tx) = pid_tx {if let Some(pid) = child.id() {@@ -162,13 +625,15 @@ pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str, pid_info!("Pi process started with PID: {}", pid);}}-- let output = child.wait_with_output().await++ let output = child+ .wait_with_output()+ .await.map_err(|e| format!("Failed to wait for pi: {}", e))?;-+let stdout = String::from_utf8_lossy(&output.stdout).to_string();let stderr = String::from_utf8_lossy(&output.stderr).to_string();-+if !stdout.is_empty() {debug!("pi stdout: {}", stdout);}@@ -190,23 +655,21 @@ pub async fn run(prompt: &str, user_token: Option<&str>, working_dir: &str, pid_}}-/// Kill a pi process by PID+/// Kill a pi process by PID (legacy)pub fn kill(pid: u32) -> Result<(), String> {info!("Killing pi process with PID: {}", pid);-+#[cfg(unix)]{use std::process::Command;- // Kill process group to also kill child processeslet _ = Command::new("kill").args(["-TERM", &format!("-{}", pid)]).output();- // Also try direct killlet output = Command::new("kill").args(["-TERM", &pid.to_string()]).output().map_err(|e| format!("Failed to kill process: {}", e))?;-+if output.status.success() {info!("Pi process {} killed", pid);Ok(())@@ -214,7 +677,7 @@ pub fn kill(pid: u32) -> Result<(), String> {Err(format!("Failed to kill process {}", pid))}}-+#[cfg(windows)]{use std::process::Command;@@ -222,7 +685,7 @@ pub fn kill(pid: u32) -> Result<(), String> {.args(["/F", "/PID", &pid.to_string()]).output().map_err(|e| format!("Failed to kill process: {}", e))?;-+if output.status.success() {Ok(())} else {diff --git a/screenpipe-app-tauri/src-tauri/src/store.rs b/screenpipe-app-tauri/src-tauri/src/store.rsindex 0815c3700..876470628 100644--- a/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/screenpipe-app-tauri/src-tauri/src/store.rs@@ -224,8 +224,8 @@ pub enum AIProviderType {Custom,#[serde(rename = "screenpipe-cloud")]ScreenpipeCloud,- #[serde(rename = "opencode")]- OpenCode,+ #[serde(rename = "pi")]+ Pi,}#[derive(Serialize, Deserialize,Type,Clone)]