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.223, CLI to v0.3.17

Louis Beaumontac4f66b274ba
diff --git a/Cargo.toml b/Cargo.toml
index cf0feebaf..9e030a904 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ exclude = ["screenpipe-app-tauri/src-tauri"]
resolver = "2"
[workspace.package]
-version = "0.3.16"
+version = "0.3.17"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/mediar-ai/screenpipe"
diff --git a/screenpipe-app-tauri/app/page.tsx b/screenpipe-app-tauri/app/page.tsx
index 3dbd85d03..7a41b4915 100644
--- a/screenpipe-app-tauri/app/page.tsx
+++ b/screenpipe-app-tauri/app/page.tsx
@@ -13,6 +13,7 @@ import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { commands } from "@/lib/utils/tauri";
import localforage from "localforage";
import { LoginDialog } from "../components/login-dialog";
+import { UpdateBanner } from "../components/update-banner";
import { ModelDownloadTracker } from "../components/model-download-tracker";
import Timeline from "@/components/rewind/timeline";
import { Button } from "@/components/ui/button";
@@ -175,7 +176,7 @@ export default function Home() {
{showTimeline ? (
<div className="w-full scrollbar-hide bg-background relative">
-<<<<<<< Updated upstream
+ <UpdateBanner />
{/* Subtle disconnected indicator - only show if we have data but no connection */}
{hasAnyData && !isConnected && isServerDown && (
<div className="fixed top-10 right-4 z-50 flex items-center gap-2 px-3 py-1.5 bg-muted/90 backdrop-blur-sm rounded-full text-xs text-muted-foreground border">
@@ -186,11 +187,6 @@ export default function Home() {
{/* Show connecting overlay only if NO data and still loading */}
{!hasAnyData && isHealthLoading && (
-=======
- <UpdateBanner />
- {/* Show connecting overlay while health check is loading */}
- {isHealthLoading && (
->>>>>>> Stashed changes
<div className="absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
<div className="flex flex-col items-center gap-3">
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsx
index 87006aebb..b0c068f9e 100644
--- a/screenpipe-app-tauri/components/global-chat.tsx
+++ b/screenpipe-app-tauri/components/global-chat.tsx
@@ -10,7 +10,7 @@ import { Button } from "@/components/ui/button";
import { CustomDialogContent } from "@/components/rewind/custom-dialog-content";
import { useSettings, ChatMessage, ChatConversation } from "@/lib/hooks/use-settings";
import { cn } from "@/lib/utils";
-import { Loader2, Send, Square, User, X, Settings, ExternalLink, Video, Plus, FolderOpen, Zap, History, Search, Trash2, ChevronLeft, Copy, Check } from "lucide-react";
+import { Loader2, Send, Square, User, X, Settings, ExternalLink, Video, Plus, Zap, History, Search, Trash2, ChevronLeft, Copy, Check } from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { parseInt } from "lodash";
import { motion, AnimatePresence } from "framer-motion";
@@ -23,11 +23,10 @@ import remarkGfm from "remark-gfm";
import OpenAI from "openai";
import { ChatCompletionTool } from "openai/resources/chat/completions";
import { open as openUrl } from "@tauri-apps/plugin-shell";
-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, PiInfo } from "@/lib/utils/tauri";
+import { commands } from "@/lib/utils/tauri";
import posthog from "posthog-js";
import { UpgradeDialog } from "@/components/upgrade-dialog";
@@ -565,11 +564,11 @@ export function GlobalChat() {
const [upgradeReason, setUpgradeReason] = useState<"daily_limit" | "model_not_allowed">("daily_limit");
const [upgradeResetsAt, setUpgradeResetsAt] = useState<string | undefined>();
- // Pi state
- const [piInfo, setPiInfo] = useState<PiInfo | null>(null);
+ // Pi agent state
+ const [piInfo, setPiInfo] = useState<{ running: boolean; projectDir: string | null; pid: number | null } | null>(null);
const [piProjectDir, setPiProjectDir] = useState<string>("");
const [piStarting, setPiStarting] = useState(false);
- const [piLogs, setPiLogs] = useState<string[]>([]);
+ const [piStreamingText, setPiStreamingText] = useState<string>("");
// Chat history state
const [conversationId, setConversationId] = useState<string | null>(null);
@@ -1055,79 +1054,92 @@ export function GlobalChat() {
// Check if we have valid AI setup
const hasPresets = settings.aiPresets && settings.aiPresets.length > 0;
- 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 hasValidModel = isPi || (activePreset?.model && activePreset.model.trim() !== "");
+ const needsLogin = (activePreset?.provider === "screenpipe-cloud" || isPi) && !settings.user?.token;
const needsProjectDir = isPi && !piProjectDir;
const piReady = isPi ? (piInfo?.running && !needsProjectDir) : true;
const canChat = hasPresets && hasValidModel && !needsLogin && piReady;
- // Debug: log why chat might be disabled
- useEffect(() => {
- if (open && activePreset) {
- console.log("[GlobalChat] Active preset:", {
- id: activePreset.id,
- provider: activePreset.provider,
- model: activePreset.model,
- url: activePreset.url,
- hasValidModel,
- needsLogin,
- canChat,
- });
- }
- }, [open, activePreset, hasValidModel, needsLogin, canChat]);
-
- // Load saved project directory on mount
+ // Load Pi project dir from localStorage
useEffect(() => {
const saved = localStorage.getItem("pi_project_dir");
if (saved) setPiProjectDir(saved);
}, []);
- // Save project directory when changed
+ // Save Pi project dir
useEffect(() => {
if (piProjectDir) {
localStorage.setItem("pi_project_dir", piProjectDir);
}
}, [piProjectDir]);
- // Start Pi when preset is selected, dialog is open, and project dir is set
+ // Start Pi when needed
useEffect(() => {
- if (!isPi || !open || needsLogin || !piProjectDir || piStarting) return;
+ if (!isPi || !open || needsLogin || !piProjectDir || piStarting || piInfo?.running) return;
- const initPi = async () => {
+ const startPi = async () => {
setPiStarting(true);
-
try {
- // Check current status
- const infoResult = await commands.piInfo();
- if (infoResult.status === "ok") {
- setPiInfo(infoResult.data);
-
- // Check if already running with same project
- 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.piStart(piProjectDir, settings.user?.token ?? null);
- if (startResult.status === "ok" && startResult.data.running) {
- setPiInfo(startResult.data);
- } else if (startResult.status === "error") {
- toast({
- title: "Pi failed to start",
- description: startResult.error,
- variant: "destructive",
- });
- }
- }
+ const result = await commands.piStart(piProjectDir, settings.user?.token ?? null);
+ if (result.status === "ok") {
+ setPiInfo(result.data);
+ } else {
+ toast({ title: "Failed to start Pi", description: result.error, variant: "destructive" });
}
} finally {
setPiStarting(false);
}
};
+ startPi();
+ }, [isPi, open, needsLogin, piProjectDir, piStarting, piInfo?.running, settings.user?.token]);
+
+ // Listen for Pi events
+ useEffect(() => {
+ if (!isPi) return;
- initPi();
- }, [isPi, open, needsLogin, piProjectDir, settings.user?.token]);
+ const unlistenEvent = listen<any>("pi_event", (event) => {
+ const data = event.payload;
+ console.log("[Pi Event]", data);
+
+ // Handle different event types
+ if (data.type === "message_update" && data.assistantMessageEvent) {
+ const evt = data.assistantMessageEvent;
+ if (evt.type === "text_delta" && evt.delta) {
+ setPiStreamingText(prev => prev + evt.delta);
+ }
+ } else if (data.type === "agent_end") {
+ // Agent finished
+ setPiStreamingText("");
+ }
+ });
+
+ const unlistenTerminated = listen("pi_terminated", () => {
+ setPiInfo(null);
+ });
+
+ return () => {
+ unlistenEvent.then(fn => fn());
+ unlistenTerminated.then(fn => fn());
+ };
+ }, [isPi]);
+
+ // Debug: log why chat might be disabled
+ useEffect(() => {
+ if (open && activePreset) {
+ console.log("[GlobalChat] Active preset:", {
+ id: activePreset.id,
+ provider: activePreset.provider,
+ model: activePreset.model,
+ url: activePreset.url,
+ hasValidModel,
+ needsLogin,
+ canChat,
+ isPi,
+ piReady,
+ });
+ }
+ }, [open, activePreset, hasValidModel, needsLogin, canChat, isPi, piReady]);
// Get error message for why chat is disabled
const getDisabledReason = (): string | null => {
@@ -1135,19 +1147,20 @@ 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 (isPi && needsProjectDir) return "Select a project folder";
- if (isPi && piStarting) return "Starting Pi...";
- if (isPi && !piReady) return "Connecting to Pi...";
+ if (isPi && needsProjectDir) return "Select a project folder for Pi";
+ if (isPi && piStarting) return "Starting Pi agent...";
+ if (isPi && !piReady) return "Connecting to Pi agent...";
return null;
};
const disabledReason = getDisabledReason();
- // Project directory picker for Pi
+ // Pi project folder picker
const selectPiProject = async () => {
+ const { open: openDialog } = await import("@tauri-apps/plugin-dialog");
const selected = await openDialog({
directory: true,
multiple: false,
- title: "Select Project Folder for Pi",
+ title: "Select Project Folder for Pi Agent",
});
if (selected) {
setPiProjectDir(selected as string);
@@ -1311,23 +1324,24 @@ export function GlobalChat() {
function getOpenAIClient(): OpenAI | null {
if (!activePreset) return null;
- // For screenpipe-cloud, use token if available, otherwise "anonymous" for free tier
- const apiKey =
- activePreset.provider === "screenpipe-cloud"
+ // Pi and screenpipe-cloud both use the screenpipe API
+ const isScreenpipeProvider = activePreset.provider === "screenpipe-cloud" || activePreset.provider === "pi";
+
+ // For screenpipe providers, use token if available, otherwise "anonymous" for free tier
+ const apiKey = isScreenpipeProvider
? settings.user?.token || "anonymous"
: "apiKey" in activePreset
? (activePreset.apiKey as string) || ""
: "";
- // Force correct URL for screenpipe-cloud (in case preset has wrong URL saved)
- const baseURL =
- activePreset.provider === "screenpipe-cloud"
+ // Force correct URL for screenpipe providers
+ const baseURL = isScreenpipeProvider
? "https://api.screenpi.pe/v1"
: activePreset.url;
// Add device ID header for usage tracking (free tier)
const defaultHeaders: Record<string, string> = {};
- if (activePreset.provider === "screenpipe-cloud" && settings.deviceId) {
+ if (isScreenpipeProvider && settings.deviceId) {
defaultHeaders["X-Device-Id"] = settings.deviceId;
}
@@ -1339,9 +1353,12 @@ export function GlobalChat() {
});
}
- // Send message using Pi (listen to events for streaming output)
+ // Send message using Pi agent
async function sendPiMessage(userMessage: string) {
- if (!piInfo?.running) return;
+ if (!piInfo?.running) {
+ toast({ title: "Pi not running", description: "Please wait for Pi to start", variant: "destructive" });
+ return;
+ }
const newUserMessage: Message = {
id: Date.now().toString(),
@@ -1355,15 +1372,16 @@ export function GlobalChat() {
setInput("");
setIsLoading(true);
setIsStreaming(true);
+ setPiStreamingText("");
try {
- // Add placeholder for streaming response
+ // Add placeholder for response
setMessages((prev) => [
...prev,
- { id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now() },
+ { id: assistantMessageId, role: "assistant", content: "", timestamp: Date.now() },
]);
- // Send prompt to Pi via RPC
+ // Send prompt to Pi
const result = await commands.piPrompt(userMessage);
if (result.status === "error") {
@@ -1374,17 +1392,51 @@ export function GlobalChat() {
: m
)
);
- } else {
- // Listen for output via pi_output events
- // The response will be collected from pi_output events
+ setIsLoading(false);
+ setIsStreaming(false);
+ return;
+ }
+
+ // Wait for Pi events to update the message
+ // The pi_event listener will update piStreamingText
+ // We need to watch for changes and update the message
+ const checkInterval = setInterval(() => {
setMessages((prev) =>
prev.map((m) =>
m.id === assistantMessageId
- ? { ...m, content: "Pi is processing your request. Check the terminal for full output." }
+ ? { ...m, content: piStreamingText || "Processing..." }
: m
)
);
- }
+ }, 100);
+
+ // Wait for agent_end or timeout
+ const timeout = setTimeout(() => {
+ clearInterval(checkInterval);
+ setIsLoading(false);
+ setIsStreaming(false);
+ }, 120000); // 2 minute timeout
+
+ // Listen for agent_end to stop
+ const unlistenEnd = await listen("pi_event", (event: any) => {
+ if (event.payload?.type === "agent_end") {
+ clearInterval(checkInterval);
+ clearTimeout(timeout);
+ unlistenEnd();
+
+ // Final update with accumulated text
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantMessageId
+ ? { ...m, content: piStreamingText || "Done" }
+ : m
+ )
+ );
+ setIsLoading(false);
+ setIsStreaming(false);
+ }
+ });
+
} catch (error) {
console.error("Pi error:", error);
setMessages((prev) =>
@@ -1394,7 +1446,6 @@ export function GlobalChat() {
: m
)
);
- } finally {
setIsLoading(false);
setIsStreaming(false);
}
@@ -1409,10 +1460,9 @@ export function GlobalChat() {
message_length: userMessage.length,
provider: activePreset?.provider,
model: activePreset?.model,
- is_pi: isPi,
});
- // Use Pi if that's the active provider
+ // Use Pi agent if selected
if (isPi) {
return sendPiMessage(userMessage);
}
@@ -2051,15 +2101,6 @@ export function GlobalChat() {
: "Screen Activity Assistant"}
</p>
</div>
- {isPi && piProjectDir && (
- <button
- 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"
- >
- <FolderOpen size={16} />
- </button>
- )}
<Button
variant={showHistory ? "secondary" : "ghost"}
size="sm"
@@ -2199,7 +2240,7 @@ export function GlobalChat() {
<div className="absolute bottom-0 right-0 w-4 h-4 border-r-2 border-b-2 border-current opacity-20 rounded-br" />
{needsProjectDir ? (
- <FolderOpen className="h-12 w-12 text-muted-foreground" />
+ <Settings className="h-12 w-12 text-muted-foreground" />
) : needsLogin ? (
<PipeAIIconLarge size={48} className="text-muted-foreground" />
) : piStarting ? (
@@ -2210,10 +2251,10 @@ 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" : piStarting ? "Starting Pi..." : "Login Required"}
+ {needsProjectDir ? "Select Project Folder" : !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 Pi to work with" : disabledReason}
+ {disabledReason}
</p>
</div>
{needsProjectDir && (
@@ -2222,7 +2263,7 @@ export function GlobalChat() {
onClick={selectPiProject}
className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"
>
- <FolderOpen className="h-4 w-4" />
+ <Settings className="h-4 w-4" />
Select Folder
</Button>
)}
@@ -2236,7 +2277,7 @@ export function GlobalChat() {
Login
</Button>
)}
- {!hasPresets && (
+ {!hasPresets && !needsProjectDir && (
<Button
variant="outline"
onClick={async () => {
@@ -2249,7 +2290,7 @@ export function GlobalChat() {
Go to Settings
</Button>
)}
- {hasPresets && !hasValidModel && (
+ {hasPresets && !hasValidModel && !needsProjectDir && (
<p className="text-xs text-muted-foreground font-mono">
Use the preset selector below to configure a model
</p>
diff --git a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx
index dc4e21d8c..35e5ebe27 100644
--- a/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx
+++ b/screenpipe-app-tauri/components/settings/obsidian-sync-card.tsx
@@ -109,7 +109,7 @@ const ObsidianLogo = ({ className }: { className?: string }) => (
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { open as openDialog } from "@tauri-apps/plugin-dialog";
-import { open as openUrl } from "@tauri-apps/plugin-shell";
+import { 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";
@@ -429,14 +429,20 @@ export function ObsidianSyncCard() {
const openObsidian = async () => {
if (!settings.vaultPath) return;
- // Extract vault name from path
- const vaultName = settings.vaultPath.split("/").pop() || "vault";
- const deepLink = `obsidian://open?vault=${encodeURIComponent(vaultName)}&file=screenpipe%2Flogs`;
+ // Use path-based deep link (don't encode - Obsidian expects raw path)
+ const deepLink = `obsidian://open?path=${settings.vaultPath}`;
try {
- await openUrl(deepLink);
+ // Use the 'open' command on macOS to handle custom URL schemes
+ const command = Command.create("open", [deepLink]);
+ await command.execute();
} catch (e) {
console.error("Failed to open Obsidian:", e);
+ toast({
+ variant: "destructive",
+ title: "Failed to open Obsidian",
+ description: "Make sure Obsidian is installed",
+ });
}
};
diff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.ts
index 7b4fb103f..bb5c1d833 100644
--- a/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -383,7 +383,7 @@ async piStop() : Promise<Result<PiInfo, string>> {
}
},
/**
- * Check if pi is available (either as sidecar or in PATH)
+ * Check if pi is available
*/
async piCheck() : Promise<Result<PiCheckResult, string>> {
try {
@@ -394,7 +394,7 @@ async piCheck() : Promise<Result<PiCheckResult, string>> {
}
},
/**
- * Install pi via bun (runs in background)
+ * Install pi via bun
*/
async piInstall() : Promise<Result<null, string>> {
try {
@@ -405,7 +405,7 @@ async piInstall() : Promise<Result<null, string>> {
}
},
/**
- * Send a prompt to pi via stdin (RPC mode)
+ * Send a prompt to Pi
*/
async piPrompt(message: string) : Promise<Result<null, string>> {
try {
@@ -415,6 +415,17 @@ async piPrompt(message: string) : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
+/**
+ * Abort current Pi operation
+ */
+async piAbort() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("pi_abort") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* Save obsidian settings to persistent store (called when settings change)
*/
@@ -568,8 +579,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 PiCheckResult = { available: boolean; sidecarAvailable: boolean; pathAvailable: boolean }
-export type PiInfo = { running: boolean; projectDir: string | null; pid: number | null }
+export type PiCheckResult = { available: boolean; path: string | null }
+export type PiInfo = { running: boolean; projectDir: string | null; pid: number | null; sessionId: string | 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/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 2c9a569af..cf8f205e8 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.222"
+version = "2.0.223"
dependencies = [
"anyhow",
"async-stream",
@@ -8692,7 +8692,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"anyhow",
"bytemuck",
@@ -8740,7 +8740,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -8791,7 +8791,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"anyhow",
"chrono",
@@ -8815,7 +8815,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"anyhow",
"chrono",
@@ -8831,7 +8831,7 @@ dependencies = [
[[package]]
name = "screenpipe-integrations"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"anyhow",
"image 0.25.5",
@@ -8846,7 +8846,7 @@ dependencies = [
[[package]]
name = "screenpipe-server"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"anyhow",
"async-trait",
@@ -8910,7 +8910,7 @@ dependencies = [
[[package]]
name = "screenpipe-vision"
-version = "0.3.16"
+version = "0.3.17"
dependencies = [
"accessibility-sys",
"anyhow",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index f4fe6fba4..da4f6ddfa 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.222"
+version = "2.0.223"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 0fd26c893..717b86a23 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -826,6 +826,7 @@ async fn main() {
pi::pi_check,
pi::pi_install,
pi::pi_prompt,
+ pi::pi_abort,
// Obsidian Sync commands
obsidian_sync::obsidian_save_settings,
obsidian_sync::obsidian_validate_vault,
@@ -972,6 +973,7 @@ async fn main() {
pi::pi_check,
pi::pi_install,
pi::pi_prompt,
+ pi::pi_abort,
// Obsidian Sync commands
obsidian_sync::obsidian_save_settings,
obsidian_sync::obsidian_validate_vault,
diff --git a/screenpipe-app-tauri/src-tauri/src/pi.rs b/screenpipe-app-tauri/src-tauri/src/pi.rs
index 60cbc232a..85401918b 100644
--- a/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1,17 +1,16 @@
//! Pi Coding Agent Integration
//!
-//! Manages the pi coding agent via RPC mode for AI-powered features.
-//! Uses stdin/stdout JSON protocol for communication.
+//! Manages the pi coding agent via RPC mode (stdin/stdout JSON protocol).
use serde::{Deserialize, Serialize};
-use serde_json::json;
+use serde_json::{json, Value};
use specta::Type;
+use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
+use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use tauri::Emitter;
-use tauri::{Manager, State};
-use tauri_plugin_shell::process::{CommandChild, CommandEvent};
-use tauri_plugin_shell::ShellExt;
+use tauri::{AppHandle, Manager, State};
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
@@ -27,6 +26,7 @@ pub struct PiInfo {
pub running: bool,
pub project_dir: Option<String>,
pub pid: Option<u32>,
+ pub session_id: Option<String>,
}
impl Default for PiInfo {
@@ -35,6 +35,7 @@ impl Default for PiInfo {
running: false,
project_dir: None,
pid: None,
+ session_id: None,
}
}
}
@@ -43,51 +44,92 @@ impl Default for PiInfo {
#[serde(rename_all = "camelCase")]
pub struct PiCheckResult {
pub available: bool,
- pub sidecar_available: bool,
- pub path_available: bool,
+ pub path: Option<String>,
+}
+
+/// RPC Response from Pi
+#[derive(Debug, Deserialize)]
+struct RpcResponse {
+ #[serde(rename = "type")]
+ response_type: String,
+ success: Option<bool>,
+ error: Option<String>,
+ data: Option<Value>,
+ command: Option<String>,
+ id: Option<String>,
}
pub struct PiManager {
- child: Option<CommandChild>,
+ child: Option<Child>,
+ stdin: Option<ChildStdin>,
project_dir: Option<String>,
- child_exited: bool,
+ request_id: u64,
+ app_handle: AppHandle,
}
impl PiManager {
- pub fn new() -> Self {
+ pub fn new(app_handle: AppHandle) -> Self {
Self {
child: None,
+ stdin: None,
project_dir: None,
- child_exited: false,
+ request_id: 0,
+ app_handle,
}
}
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())),
+ Some(child) => (true, Some(child.id())),
};
PiInfo {
running,
project_dir: self.project_dir.clone(),
pid,
+ session_id: None,
}
}
pub fn stop(&mut self) {
- if let Some(child) = self.child.take() {
+ if let Some(mut child) = self.child.take() {
+ // Send abort command first
+ if let Some(ref mut stdin) = self.stdin {
+ let _ = writeln!(stdin, r#"{{"type":"abort"}}"#);
+ }
+
+ // Kill the process
if let Err(e) = child.kill() {
error!("Failed to kill pi child process: {}", e);
}
+ let _ = child.wait();
}
- self.child_exited = true;
+ self.stdin = None;
self.project_dir = None;
}
pub fn is_running(&self) -> bool {
- self.child.is_some() && !self.child_exited
+ self.child.is_some()
+ }
+
+ /// Send a command to Pi via stdin and return response
+ pub fn send_command(&mut self, command: Value) -> Result<(), String> {
+ let stdin = self.stdin.as_mut().ok_or("Pi not running")?;
+
+ self.request_id += 1;
+ let mut cmd = command;
+ if let Some(obj) = cmd.as_object_mut() {
+ obj.insert("id".to_string(), json!(format!("req_{}", self.request_id)));
+ }
+
+ let cmd_str = serde_json::to_string(&cmd).map_err(|e| e.to_string())?;
+ debug!("Sending to Pi: {}", cmd_str);
+
+ writeln!(stdin, "{}", cmd_str).map_err(|e| format!("Failed to write to Pi stdin: {}", e))?;
+ stdin.flush().map_err(|e| format!("Failed to flush Pi stdin: {}", e))?;
+
+ Ok(())
}
}
@@ -98,6 +140,38 @@ fn get_pi_config_dir() -> Result<PathBuf, String> {
Ok(home_dir.join(".pi").join("agent"))
}
+/// Find pi executable
+fn find_pi_executable() -> Option<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),
+ "/opt/homebrew/bin/pi".to_string(),
+ "/usr/local/bin/pi".to_string(),
+ ];
+
+ for path in paths {
+ if std::path::Path::new(&path).exists() {
+ return Some(path);
+ }
+ }
+
+ // Try which command
+ if let Ok(output) = std::process::Command::new("which").arg("pi").output() {
+ if output.status.success() {
+ let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ if !path.is_empty() {
+ return Some(path);
+ }
+ }
+ }
+
+ None
+}
+
/// 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()?;
@@ -158,41 +232,6 @@ fn ensure_pi_config(user_token: Option<&str>) -> Result<(), String> {
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]
@@ -215,9 +254,6 @@ pub async fn pi_stop(state: State<'_, PiState>) -> Result<PiInfo, String> {
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()),
@@ -228,7 +264,7 @@ pub async fn pi_stop(state: State<'_, PiState>) -> Result<PiInfo, String> {
#[tauri::command]
#[specta::specta]
pub async fn pi_start(
- app: tauri::AppHandle,
+ app: AppHandle,
state: State<'_, PiState>,
project_dir: String,
user_token: Option<String>,
@@ -242,14 +278,14 @@ pub async fn pi_start(
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 is configured
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());
+ *manager_guard = Some(PiManager::new(app.clone()));
}
// Stop any existing instance
@@ -260,285 +296,155 @@ pub async fn pi_start(
}
}
- // 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(),
- ];
+ // Find pi executable
+ let pi_path = find_pi_executable()
+ .ok_or_else(|| format!("Pi not found. Install with: bun add -g {}", PI_PACKAGE))?;
- info!("Starting pi with args: {:?} in dir: {}", args, project_dir);
+ info!("Starting pi from {} in dir: {}", pi_path, 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
- };
+ // Build command
+ let mut cmd = Command::new(&pi_path);
+ cmd.current_dir(&project_dir)
+ .args(["--mode", "rpc", "--provider", "screenpipe", "--model", "claude-haiku-4-5@20251001"])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
- // 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);
- }
+ if let Some(ref token) = user_token {
+ cmd.env("SCREENPIPE_API_KEY", token);
+ }
- command.spawn()
- }
- }
- };
+ // Spawn process
+ let mut child = cmd.spawn()
+ .map_err(|e| format!("Failed to spawn pi: {}", e))?;
+
+ let pid = child.id();
+ info!("Pi started with PID: {}", pid);
- let (mut rx, child) = spawn_result.map_err(|e| {
- format!("Failed to start Pi: {}. Install with: bun add -g {}", e, PI_PACKAGE)
- })?;
+ // Take stdin for writing commands
+ let stdin = child.stdin.take()
+ .ok_or_else(|| "Failed to get pi stdin".to_string())?;
- let pid = child.pid();
- info!("Spawned pi with PID {}", pid);
+ // Take stdout for reading events
+ let stdout = child.stdout.take()
+ .ok_or_else(|| "Failed to get pi stdout".to_string())?;
- // Update manager state
+ // Take stderr for logging
+ let stderr = child.stderr.take();
+
+ // Update manager
if let Some(m) = manager_guard.as_mut() {
m.child = Some(child);
+ m.stdin = Some(stdin);
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);
+ // Spawn stdout reader thread
+ let app_handle = app.clone();
+ std::thread::spawn(move || {
+ let reader = BufReader::new(stdout);
+ for line in reader.lines() {
+ match line {
+ Ok(line) => {
+ debug!("Pi stdout: {}", line);
+ // Try to parse as JSON and emit event
+ if let Ok(event) = serde_json::from_str::<Value>(&line) {
+ let _ = app_handle.emit("pi_event", &event);
}
- let _ = app_handle.emit("pi_log", &line);
+ let _ = app_handle.emit("pi_output", &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);
+ Err(e) => {
+ error!("Error reading pi stdout: {}", e);
+ break;
}
- 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;
+ }
+ }
+ info!("Pi stdout reader ended");
+ let _ = app_handle.emit("pi_terminated", ());
+ });
+
+ // Spawn stderr reader thread
+ if let Some(stderr) = stderr {
+ let app_handle = app.clone();
+ std::thread::spawn(move || {
+ let reader = BufReader::new(stderr);
+ for line in reader.lines() {
+ match line {
+ Ok(line) => {
+ if line.to_lowercase().contains("error") {
+ error!("Pi stderr: {}", line);
+ } else {
+ debug!("Pi stderr: {}", line);
}
+ let _ = app_handle.emit("pi_log", &line);
}
- let _ = app_handle.emit("pi_error", &message);
+ Err(_) => break,
}
- _ => {}
}
- }
- });
+ });
+ }
- // Brief wait for process to start
+ // Wait a moment for initialization
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)
+/// Send a prompt to Pi
#[tauri::command]
#[specta::specta]
pub async fn pi_prompt(
state: State<'_, PiState>,
message: String,
) -> Result<(), String> {
- let manager = state.0.lock().await;
+ let mut manager = state.0.lock().await;
+ let m = manager.as_mut().ok_or("Pi not initialized")?;
- 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()),
+ if !m.is_running() {
+ return Err("Pi is not running".to_string());
}
+
+ let cmd = json!({
+ "type": "prompt",
+ "message": message
+ });
+
+ m.send_command(cmd)
}
-/// Cleanup function to be called on app exit
-pub async fn cleanup_pi(state: &PiState) {
- info!("Cleaning up pi on app exit");
+/// Abort current Pi operation
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_abort(state: State<'_, PiState>) -> Result<(), String> {
let mut manager = state.0.lock().await;
- if let Some(m) = manager.as_mut() {
- m.stop();
+ let m = manager.as_mut().ok_or("Pi not initialized")?;
+
+ if !m.is_running() {
+ return Err("Pi is not running".to_string());
}
- 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 path
-fn 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),
- format!("{}/.nvm/versions/node/v22.11.0/bin/pi", home),
- "/opt/homebrew/bin/pi".to_string(),
- "/usr/local/bin/pi".to_string(),
- "/usr/bin/pi".to_string(),
- "pi".to_string(),
- ];
+ m.send_command(json!({"type": "abort"}))
+}
- 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))
+/// Check if pi is available
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_check() -> Result<PiCheckResult, String> {
+ let path = find_pi_executable();
+ Ok(PiCheckResult {
+ available: path.is_some(),
+ path,
+ })
}
-/// 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...");
+/// Install pi via bun
+#[tauri::command]
+#[specta::specta]
+pub async fn pi_install(app: AppHandle) -> Result<(), String> {
+ info!("Installing pi via bun...");
let home = dirs::home_dir()
.map(|h| h.to_string_lossy().to_string())
@@ -548,143 +454,114 @@ pub async fn ensure_installed() -> Result<(), String> {
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())
+ .find(|p| 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))?;
+ let app_handle = app.clone();
+ std::thread::spawn(move || {
+ let output = std::process::Command::new(&bun)
+ .args(["add", "-g", PI_PACKAGE])
+ .output();
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- warn!("bun install warning: {}", stderr);
- } else {
- info!("pi CLI installed/updated successfully");
- }
+ match output {
+ Ok(output) => {
+ if output.status.success() {
+ info!("Pi installed successfully");
+ let _ = app_handle.emit("pi_installed", true);
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ error!("Pi installation failed: {}", stderr);
+ let _ = app_handle.emit("pi_installed", false);
+ }
+ }
+ Err(e) => {
+ error!("Failed to run bun: {}", e);
+ let _ = app_handle.emit("pi_installed", false);
+ }
+ }
+ });
Ok(())
}
-/// Run pi with a prompt (non-interactive print mode) - legacy for obsidian sync
+/// 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();
+ }
+}
+
+// ============================================================================
+// Legacy functions for obsidian sync (print mode)
+// ============================================================================
+
+/// Run pi with a prompt (non-interactive print mode)
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 configured
- ensure_installed().await?;
ensure_pi_config(user_token)?;
- let pi_cmd = find_executable()?;
- info!("Using pi at: {}", pi_cmd);
+ let pi_path = find_pi_executable()
+ .ok_or_else(|| format!("Pi not found. Install with: bun add -g {}", PI_PACKAGE))?;
- let mut cmd = tokio::process::Command::new(&pi_cmd);
+ let mut cmd = tokio::process::Command::new(&pi_path);
cmd.current_dir(working_dir);
cmd.arg("-p").arg(prompt);
cmd.arg("--provider").arg("screenpipe");
- cmd.arg("--model").arg(DEFAULT_MODEL);
+ cmd.arg("--model").arg("claude-haiku-4-5@20251001");
if let Some(token) = user_token {
- 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 requested
if let Some(tx) = pid_tx {
if let Some(pid) = child.id() {
let _ = tx.send(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);
- }
- if !stderr.is_empty() {
- debug!("pi stderr: {}", stderr);
- }
-
if output.status.success() {
- info!("Pi completed successfully");
Ok(stdout)
} else {
- let error_msg = if !stderr.is_empty() {
- stderr
- } else {
- format!("Pi exited with code {:?}", output.status.code())
- };
- error!("Pi failed: {}", error_msg);
- Err(error_msg)
+ Err(if !stderr.is_empty() { stderr } else { format!("Pi exited with code {:?}", output.status.code()) })
}
}
-/// Kill a pi process by PID (legacy)
+/// Kill a pi process by PID
pub fn kill(pid: u32) -> Result<(), String> {
- info!("Killing pi process with PID: {}", pid);
-
#[cfg(unix)]
{
- use std::process::Command;
- let _ = Command::new("kill")
- .args(["-TERM", &format!("-{}", pid)])
- .output();
- let output = Command::new("kill")
+ let _ = std::process::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(())
- } else {
- Err(format!("Failed to kill process {}", pid))
- }
+ .output();
}
-
#[cfg(windows)]
{
- use std::process::Command;
- let output = Command::new("taskkill")
+ let _ = std::process::Command::new("taskkill")
.args(["/F", "/PID", &pid.to_string()])
- .output()
- .map_err(|e| format!("Failed to kill process: {}", e))?;
-
- if output.status.success() {
- Ok(())
- } else {
- Err(format!("Failed to kill process {}", pid))
- }
+ .output();
}
+ Ok(())
}