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

Push all local changes from parallel agents

Louis Beaumont11cbcf6e5012
diff --git a/apps/screenpipe-app-tauri/app/settings/page.tsx b/apps/screenpipe-app-tauri/app/settings/page.tsx
index 1eb3deb6e..f9170702b 100644
--- a/apps/screenpipe-app-tauri/app/settings/page.tsx
+++ b/apps/screenpipe-app-tauri/app/settings/page.tsx
@@ -172,6 +172,15 @@ function SettingsPageContent() {
return () => { cancelled = true; clearInterval(interval); };
}, []);
+ // Watch pipe: navigate to chat when user clicks "watch" on a running pipe
+ useEffect(() => {
+ let unlisten: (() => void) | null = null;
+ listen<{ pipeName: string; executionId: number }>("watch_pipe", () => {
+ setActiveSection("home");
+ }).then((fn) => { unlisten = fn; });
+ return () => { unlisten?.(); };
+ }, [setActiveSection]);
+
// Settings modal state
const [settingsModalOpen, setSettingsModalOpen] = useState(false);
const [modalSection, setModalSection] = useState<SettingsModalSection>("general");
diff --git a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
index 34750e3ae..426471d22 100644
--- a/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/current-frame-timeline.tsx
@@ -67,9 +67,6 @@ const FRAME_LOAD_DEBOUNCE_ARROW_MS = 0;
// Number of adjacent frames to preload in each direction
const PRELOAD_ADJACENT = 3;
-// Crossfade duration (ms)
-const CROSSFADE_MS = 120;
-
// Track which chunks have failed with TTL — entries expire so finished chunks can be retried
const FAILED_CHUNK_TTL_MS = 30_000;
const failedChunks = new Map<string, number>();
@@ -896,18 +893,14 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
</div>
)}
- {/* Video element — crossfades in when frame is ready */}
+ {/* Video element — always visible, retains last seeked frame during loading */}
<video
ref={videoRef}
muted
playsInline
preload="auto"
className="absolute inset-0 w-full h-full object-contain"
- style={{
- zIndex: 1,
- opacity: !isLoading && useVideoMode && !isSnapshotFrame && !searchNavFrame ? 1 : 0,
- transition: `opacity ${CROSSFADE_MS}ms ease-out`,
- }}
+ style={{ zIndex: 1 }}
onError={() => {
const err = videoRef.current?.error;
console.warn("Video error:", err?.code, err?.message);
@@ -920,33 +913,25 @@ export const CurrentFrameTimeline: FC<CurrentFrameTimelineProps> = ({
}}
/>
- {/* Snapshot frame: direct local file via asset protocol — crossfades in */}
+ {/* Snapshot frame: direct local file via asset protocol — no HTTP/DB needed */}
{snapshotAssetUrl && isSnapshotFrame && !snapshotFailed && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={snapshotAssetUrl}
className="absolute inset-0 w-full h-full object-contain"
- style={{
- zIndex: 2,
- opacity: !isLoading ? 1 : 0,
- transition: `opacity ${CROSSFADE_MS}ms ease-out`,
- }}
+ style={{ zIndex: 2 }}
alt="Current frame"
draggable={false}
/>
)}
- {/* Fallback mode: preloaded <img> via HTTP server — crossfades in */}
+ {/* Fallback mode: preloaded <img> via HTTP server (also used for search nav) */}
{displayedFallbackUrl && (!useVideoMode || searchNavFrame) && !(snapshotAssetUrl && isSnapshotFrame && !snapshotFailed) && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={displayedFallbackUrl}
className="absolute inset-0 w-full h-full object-contain"
- style={{
- zIndex: 2,
- opacity: !isLoading ? 1 : 0,
- transition: `opacity ${CROSSFADE_MS}ms ease-out`,
- }}
+ style={{ zIndex: 2 }}
alt="Current frame"
draggable={false}
/>
diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
index f85879a23..3c2003644 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
@@ -877,7 +877,22 @@ export function PipesSection() {
</td>
<td className="py-0.5 pr-2 text-muted-foreground whitespace-nowrap">
{exec.status === "running" && exec.started_at ? (
- <ElapsedTimer startedAt={exec.started_at} />
+ <span className="flex items-center gap-1">
+ <ElapsedTimer startedAt={exec.started_at} />
+ <button
+ className="text-[10px] text-primary underline hover:no-underline ml-1"
+ onClick={(e) => {
+ e.stopPropagation();
+ emit("watch_pipe", {
+ pipeName: pipe.config.name,
+ executionId: exec.id,
+ });
+ }}
+ title="watch live output"
+ >
+ watch
+ </button>
+ </span>
) : exec.duration_ms != null ? (
formatDuration(exec.duration_ms)
) : null}
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 59dd6f796..13de5ce3a 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -662,6 +662,13 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const piRestartCountRef = useRef(0);
const piStoppedIntentionallyRef = useRef(false);
const piThinkingStartRef = useRef<number | null>(null);
+ const piSessionSyncedRef = useRef(false);
+
+ // Active pipe execution (when watching a running pipe)
+ const [activePipeExecution, setActivePipeExecution] = useState<{
+ name: string;
+ executionId: number;
+ } | null>(null);
// Follow-up suggestions state (TikTok-style)
const [followUpSuggestions, setFollowUpSuggestions] = useState<string[]>([]);
@@ -842,6 +849,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
})));
setConversationId(conv.id);
setShowHistory(false);
+ piSessionSyncedRef.current = false;
// Update activeConversationId directly in the store (read fresh to avoid
// overwriting conversations with stale React state)
@@ -887,6 +895,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setInput("");
setShowHistory(false);
setPastedImage(null);
+ piSessionSyncedRef.current = true;
};
// Filter conversations by search
@@ -1390,6 +1399,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const result = await commands.piStart(dir, settings.user?.token ?? null, providerConfig);
if (result.status === "ok") {
setPiInfo(result.data);
+ piSessionSyncedRef.current = false;
} else {
console.error("[Pi] Restart failed:", result.error);
toast({ title: "Failed to restart Pi", description: result.error, variant: "destructive" });
@@ -1397,27 +1407,26 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
} catch (e) {
console.error("[Pi] Restart exception:", e);
} finally {
- piStartInFlightRef.current = false;
setPiStarting(false);
+ // Keep the guard active for 2s to absorb delayed re-triggers from
+ // settings/loadUser cascades during boot (prevents double-start race)
+ setTimeout(() => { piStartInFlightRef.current = false; }, 2000);
}
};
restartPi();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activePreset?.provider, activePreset?.model, settings.user?.token]);
- // Listen for Pi events (all providers route through Pi)
+ // Listen for Pi events (all providers route through Pi) and pipe events
useEffect(() => {
let unlistenEvent: UnlistenFn | null = null;
+ let unlistenPipeEvent: UnlistenFn | null = null;
let unlistenTerminated: UnlistenFn | null = null;
let unlistenLog: UnlistenFn | null = null;
let mounted = true;
- const setup = async () => {
- unlistenEvent = await listen<any>("pi_event", (event) => {
- if (!mounted) return;
- // Pi sent an event — it's running stably, reset restart counter
- piRestartCountRef.current = 0;
- const data = event.payload;
+ // Shared handler for Pi event data — used by both pi_event and pipe_event
+ const handlePiEventData = (data: any) => {
if (data.type === "message_update" && data.assistantMessageEvent) {
const evt = data.assistantMessageEvent;
@@ -1739,6 +1748,54 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setIsLoading(false);
setIsStreaming(false);
}
+ };
+
+ const setup = async () => {
+ unlistenEvent = await listen<any>("pi_event", (event) => {
+ if (!mounted) return;
+ // Pi sent an event — it's running stably, reset restart counter
+ piRestartCountRef.current = 0;
+ handlePiEventData(event.payload);
+ });
+
+ // Listen for pipe execution events (same format as pi_event, wrapped with pipe metadata)
+ unlistenPipeEvent = await listen<any>("pipe_event", (event) => {
+ if (!mounted) return;
+ const payload = event.payload;
+ const pipeName = payload?.pipeName;
+ const execId = payload?.executionId;
+ const piEvent = payload?.event;
+ if (!piEvent) return;
+
+ // If no pipe is being watched yet and we see an event, auto-attach
+ // (the Watch button also sets activePipeExecution explicitly)
+ if (!piMessageIdRef.current || piMessageIdRef.current?.startsWith("pipe-")) {
+ // Create or reuse a message for this pipe execution
+ const msgId = `pipe-${pipeName}-${execId}`;
+ if (!piMessageIdRef.current || piMessageIdRef.current !== msgId) {
+ piStreamingTextRef.current = "";
+ piContentBlocksRef.current = [];
+ piThinkingStartRef.current = null;
+ piMessageIdRef.current = msgId;
+ setMessages((prev) => {
+ // Don't add duplicate
+ if (prev.some((m) => m.id === msgId)) return prev;
+ return [
+ ...prev,
+ {
+ id: msgId,
+ role: "assistant" as const,
+ content: "",
+ timestamp: Date.now(),
+ contentBlocks: [],
+ },
+ ];
+ });
+ setIsStreaming(true);
+ }
+ }
+
+ handlePiEventData(piEvent);
});
unlistenTerminated = await listen<number>("pi_terminated", (event) => {
@@ -1799,6 +1856,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const result = await commands.piStart(dir, settings.user?.token ?? null, providerConfig);
if (result.status === "ok") {
setPiInfo(result.data);
+ piSessionSyncedRef.current = false;
if (result.data.running) piRestartCountRef.current = 0;
} else {
console.error("[Pi] Auto-restart failed:", result.error);
@@ -1857,12 +1915,49 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
return () => {
mounted = false;
unlistenEvent?.();
+ unlistenPipeEvent?.();
unlistenTerminated?.();
unlistenLog?.();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ // Listen for "watch_pipe" events from pipes-section to start watching a running pipe
+ useEffect(() => {
+ let unlisten: (() => void) | null = null;
+ listen<{ pipeName: string; executionId: number }>("watch_pipe", (event) => {
+ const { pipeName, executionId } = event.payload;
+ setActivePipeExecution({ name: pipeName, executionId });
+ // Create a placeholder assistant message for the pipe output
+ const msgId = `pipe-${pipeName}-${executionId}`;
+ piStreamingTextRef.current = "";
+ piContentBlocksRef.current = [];
+ piThinkingStartRef.current = null;
+ piMessageIdRef.current = msgId;
+ setMessages((prev) => {
+ if (prev.some((m) => m.id === msgId)) return prev;
+ return [
+ ...prev,
+ {
+ id: `pipe-user-${executionId}`,
+ role: "user" as const,
+ content: `Watching pipe: ${pipeName}`,
+ timestamp: Date.now(),
+ },
+ {
+ id: msgId,
+ role: "assistant" as const,
+ content: "",
+ timestamp: Date.now(),
+ contentBlocks: [],
+ },
+ ];
+ });
+ setIsStreaming(true);
+ }).then((fn) => { unlisten = fn; });
+ return () => { unlisten?.(); };
+ }, []);
+
// Generate follow-up suggestions using Apple Intelligence
async function generateFollowUps(userMsg: string, partialResponse: string) {
try {
@@ -2033,8 +2128,21 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
{ id: assistantMessageId, role: "assistant", content: "Processing...", timestamp: Date.now() },
]);
+ // If Pi's session is out of sync (restart, conversation load), inject history
+ let promptMessage = userMessage;
+ if (!piSessionSyncedRef.current && messages.length > 0) {
+ const historyLines = messages
+ .slice(-40)
+ .map(m => `${m.role}: ${m.content}`)
+ .join("\n");
+ promptMessage = `<conversation_history>\n${historyLines}\n</conversation_history>\n\n${userMessage}`;
+ piSessionSyncedRef.current = true;
+ } else {
+ piSessionSyncedRef.current = true;
+ }
+
const result = await commands.piPrompt(
- userMessage,
+ promptMessage,
piImages.length > 0 ? piImages : null,
);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
index 1061f7b9a..e759b43bb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/embedded_server.rs
@@ -42,6 +42,7 @@ impl EmbeddedServerHandle {
/// Start the embedded screenpipe server
pub async fn start_embedded_server(
config: RecordingConfig,
+ on_pipe_output: Option<screenpipe_core::pipes::OnPipeOutputLine>,
) -> Result<EmbeddedServerHandle, String> {
info!("Starting embedded screenpipe server on port {}", config.port);
@@ -353,6 +354,9 @@ pub async fn start_embedded_server(
"duration_secs": duration_secs,
}));
}));
+ if let Some(cb) = on_pipe_output {
+ pipe_manager.set_on_output_line(cb);
+ }
pipe_manager.install_builtin_pipes().ok();
if let Err(e) = pipe_manager.load_pipes().await {
tracing::warn!("failed to load pipes: {}", e);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 55a4a590c..5fa0d33a7 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1905,6 +1905,27 @@ async fn main() {
let recording_state_inner = recording_state.handle.clone();
let is_starting_clone = recording_state.is_starting.clone();
+ // Create pipe output callback that emits Tauri events to the frontend
+ let app_for_pipe = app_handle.clone();
+ let on_pipe_output: Option<screenpipe_core::pipes::OnPipeOutputLine> = Some(
+ std::sync::Arc::new(move |pipe_name: &str, exec_id: i64, line: &str| {
+ let payload = if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(line) {
+ serde_json::json!({
+ "pipeName": pipe_name,
+ "executionId": exec_id,
+ "event": parsed,
+ })
+ } else {
+ serde_json::json!({
+ "pipeName": pipe_name,
+ "executionId": exec_id,
+ "event": { "type": "raw_line", "text": line },
+ })
+ };
+ let _ = app_for_pipe.emit("pipe_event", &payload);
+ }),
+ );
+
// Spawn a dedicated thread for the server with its own runtime
// This prevents CPU contention between UI and recording workloads
std::thread::Builder::new()
@@ -1957,7 +1978,7 @@ async fn main() {
info!("Starting embedded screenpipe server on dedicated runtime...");
let config = store_clone.to_recording_config(data_dir_clone);
- match embedded_server::start_embedded_server(config).await {
+ match embedded_server::start_embedded_server(config, on_pipe_output).await {
Ok(handle) => {
info!("Embedded screenpipe server started successfully on dedicated runtime");
// Store handle in state so it can be stopped/restarted later
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index 1bdb983e0..fc05a331a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -9,7 +9,7 @@ use crate::store::SettingsStore;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
-use tauri::State;
+use tauri::{Emitter, State};
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
@@ -278,6 +278,28 @@ pub async fn spawn_screenpipe(
let config = store.to_recording_config(data_dir);
let recording_state_inner = state.handle.clone();
+ // Create pipe output callback that emits Tauri events to the frontend
+ let app_for_pipe = app.clone();
+ let on_pipe_output: Option<screenpipe_core::pipes::OnPipeOutputLine> = Some(
+ std::sync::Arc::new(move |pipe_name: &str, exec_id: i64, line: &str| {
+ // Try to parse each line as JSON (Pi events are JSON objects)
+ let payload = if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(line) {
+ serde_json::json!({
+ "pipeName": pipe_name,
+ "executionId": exec_id,
+ "event": parsed,
+ })
+ } else {
+ serde_json::json!({
+ "pipeName": pipe_name,
+ "executionId": exec_id,
+ "event": { "type": "raw_line", "text": line },
+ })
+ };
+ let _ = app_for_pipe.emit("pipe_event", &payload);
+ }),
+ );
+
// Use a oneshot channel to report success/failure from the dedicated runtime
let (result_tx, result_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
@@ -300,7 +322,7 @@ pub async fn spawn_screenpipe(
};
server_runtime.block_on(async move {
- match start_embedded_server(config).await {
+ match start_embedded_server(config, on_pipe_output).await {
Ok(handle) => {
info!("Embedded screenpipe server started successfully on dedicated runtime");
{
diff --git a/crates/screenpipe-core/src/agents/mod.rs b/crates/screenpipe-core/src/agents/mod.rs
index d14f96bed..2d0ca8990 100644
--- a/crates/screenpipe-core/src/agents/mod.rs
+++ b/crates/screenpipe-core/src/agents/mod.rs
@@ -53,6 +53,31 @@ pub trait AgentExecutor: Send + Sync {
pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,
) -> Result<AgentOutput>;
+ /// Execute the prompt with line-by-line streaming of stdout.
+ ///
+ /// Each stdout line is sent via `line_tx` as it arrives, AND collected
+ /// into `AgentOutput.stdout` for the final result. The default
+ /// implementation falls back to [`run()`] and sends all lines at once.
+ async fn run_streaming(
+ &self,
+ prompt: &str,
+ model: &str,
+ working_dir: &Path,
+ provider: Option<&str>,
+ provider_url: Option<&str>,
+ provider_api_key: Option<&str>,
+ pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,
+ line_tx: tokio::sync::mpsc::UnboundedSender<String>,
+ ) -> Result<AgentOutput> {
+ let output = self
+ .run(prompt, model, working_dir, provider, provider_url, provider_api_key, pid_tx)
+ .await?;
+ for line in output.stdout.lines() {
+ let _ = line_tx.send(line.to_string());
+ }
+ Ok(output)
+ }
+
/// Kill a running agent process.
fn kill(&self, handle: &ExecutionHandle) -> Result<()>;
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index abc18c6ce..92720ef2f 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -11,6 +11,7 @@ use super::{AgentExecutor, AgentOutput, ExecutionHandle};
use anyhow::{anyhow, Result};
use serde_json::json;
use std::path::{Path, PathBuf};
+use tokio::io::AsyncBufReadExt;
use tracing::{debug, error, info, warn};
const PI_PACKAGE: &str = "@mariozechner/[email protected]";
@@ -236,6 +237,39 @@ impl PiExecutor {
Ok(())
}
+ /// Resolve a model name for the screenpipe provider by stripping date suffixes
+ /// (e.g. "claude-haiku-4-5@20251001" → "claude-haiku-4-5") to match the cloud
+ /// model list. Passthrough for non-screenpipe providers.
+ fn resolve_model(requested: &str, provider: &str) -> String {
+ if provider != "screenpipe" {
+ return requested.to_string();
+ }
+ let models = screenpipe_cloud_models();
+ // Exact match → use as-is
+ if models
+ .as_array()
+ .map(|arr| arr.iter().any(|m| m["id"].as_str() == Some(requested)))
+ .unwrap_or(false)
+ {
+ return requested.to_string();
+ }
+ // Strip @date suffix and try again
+ if let Some(base) = requested.split('@').next() {
+ if models
+ .as_array()
+ .map(|arr| arr.iter().any(|m| m["id"].as_str() == Some(base)))
+ .unwrap_or(false)
+ {
+ warn!(
+ "model '{}' not in cloud list, resolved to '{}'",
+ requested, base
+ );
+ return base.to_string();
+ }
+ }
+ requested.to_string()
+ }
+
/// Spawn the pi subprocess and wait for its output.
#[allow(clippy::too_many_arguments)]
async fn spawn_pi(
@@ -313,6 +347,108 @@ impl PiExecutor {
pid,
})
}
+
+ /// Spawn the pi subprocess with line-by-line stdout streaming.
+ ///
+ /// Same as `spawn_pi` but reads stdout incrementally via `BufReader`
+ /// and sends each line to `line_tx`. Lines are also collected into
+ /// `AgentOutput.stdout` for the final result.
+ #[allow(clippy::too_many_arguments)]
+ async fn spawn_pi_streaming(
+ &self,
+ pi_path: &str,
+ prompt: &str,
+ model: &str,
+ working_dir: &Path,
+ resolved_provider: &str,
+ provider_api_key: Option<&str>,
+ pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,
+ line_tx: tokio::sync::mpsc::UnboundedSender<String>,
+ ) -> Result<AgentOutput> {
+ let mut cmd = build_async_command(pi_path);
+ cmd.current_dir(working_dir);
+ cmd.arg("-p").arg(prompt);
+ cmd.arg("--provider").arg(resolved_provider);
+ cmd.arg("--model").arg(model);
+
+ if let Some(ref token) = self.user_token {
+ cmd.env("SCREENPIPE_API_KEY", token);
+ }
+
+ if let Some(key) = provider_api_key {
+ if !key.is_empty() {
+ match resolved_provider {
+ "openai" | "openai-byok" => {
+ cmd.env("OPENAI_API_KEY", key);
+ }
+ "custom" => {
+ cmd.env("CUSTOM_API_KEY", key);
+ }
+ _ => {}
+ }
+ }
+ }
+
+ cmd.stdout(std::process::Stdio::piped());
+ cmd.stderr(std::process::Stdio::piped());
+
+ #[cfg(unix)]
+ unsafe {
+ cmd.pre_exec(|| {
+ libc::setsid();
+ Ok(())
+ });
+ }
+
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+
+ let mut child = cmd.spawn()?;
+ let pid = child.id();
+
+ if let Some(tx) = pid_tx {
+ if let Some(p) = pid {
+ let _ = tx.send(p);
+ }
+ }
+
+ // Take stdout for streaming reads; stderr will be read after exit
+ let child_stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| anyhow!("failed to capture pi stdout"))?;
+
+ let mut reader = tokio::io::BufReader::new(child_stdout).lines();
+ let mut stdout_buf = String::new();
+
+ while let Some(line) = reader.next_line().await? {
+ let _ = line_tx.send(line.clone());
+ stdout_buf.push_str(&line);
+ stdout_buf.push('\n');
+ }
+
+ let status = child.wait().await?;
+
+ // Read remaining stderr
+ let stderr = if let Some(mut stderr_handle) = child.stderr.take() {
+ let mut buf = String::new();
+ tokio::io::AsyncReadExt::read_to_string(&mut stderr_handle, &mut buf).await?;
+ buf
+ } else {
+ String::new()
+ };
+
+ Ok(AgentOutput {
+ stdout: stdout_buf,
+ stderr,
+ success: status.success(),
+ pid,
+ })
+ }
}
#[async_trait::async_trait]
@@ -344,17 +480,18 @@ impl AgentExecutor for PiExecutor {
// 1. Explicit provider from pipe frontmatter → use it
// 2. No provider specified → screenpipe cloud (default)
let resolved_provider = provider.unwrap_or("screenpipe").to_string();
+ let resolved_model = Self::resolve_model(model, &resolved_provider);
info!(
"pipe using provider: {}, model: {}",
- resolved_provider, model
+ resolved_provider, resolved_model
);
let output = self
.spawn_pi(
&pi_path,
prompt,
- model,
+ &resolved_model,
working_dir,
&resolved_provider,
provider_api_key,
@@ -376,18 +513,96 @@ impl AgentExecutor for PiExecutor {
self.user_token.as_deref(),
&self.api_url,
provider,
- Some(model),
+ Some(&resolved_model),
provider_url,
)?;
return self
.spawn_pi(
&pi_path,
prompt,
- model,
+ &resolved_model,
+ working_dir,
+ &resolved_provider,
+ provider_api_key,
+ None,
+ )
+ .await;
+ }
+
+ Ok(output)
+ }
+
+ async fn run_streaming(
+ &self,
+ prompt: &str,
+ model: &str,
+ working_dir: &Path,
+ provider: Option<&str>,
+ provider_url: Option<&str>,
+ provider_api_key: Option<&str>,
+ pid_tx: Option<tokio::sync::oneshot::Sender<u32>>,
+ line_tx: tokio::sync::mpsc::UnboundedSender<String>,
+ ) -> Result<AgentOutput> {
+ let resolved_provider = provider.unwrap_or("screenpipe").to_string();
+ let resolved_model = Self::resolve_model(model, &resolved_provider);
+
+ Self::ensure_pi_config(
+ self.user_token.as_deref(),
+ &self.api_url,
+ provider,
+ Some(&resolved_model),
+ provider_url,
+ )?;
+ Self::ensure_screenpipe_skill(working_dir)?;
+ Self::ensure_web_search_extension(working_dir)?;
+
+ let pi_path = find_pi_executable()
+ .ok_or_else(|| anyhow!("pi not found. install with: bun add -g {}", PI_PACKAGE))?;
+
+ info!(
+ "pipe streaming using provider: {}, model: {}",
+ resolved_provider, resolved_model
+ );
+
+ let output = self
+ .spawn_pi_streaming(
+ &pi_path,
+ prompt,
+ &resolved_model,
+ working_dir,
+ &resolved_provider,
+ provider_api_key,
+ pid_tx,
+ line_tx.clone(),
+ )
+ .await?;
+
+ // Retry once on "model not found"
+ if !output.success && output.stderr.to_lowercase().contains("not found") {
+ warn!(
+ "pi model not found, retrying with fresh models.json (stderr: {})",
+ output.stderr.trim()
+ );
+ let config_dir = get_pi_config_dir()?;
+ let models_path = config_dir.join("models.json");
+ let _ = std::fs::remove_file(&models_path);
+ Self::ensure_pi_config(
+ self.user_token.as_deref(),
+ &self.api_url,
+ provider,
+ Some(&resolved_model),
+ provider_url,
+ )?;
+ return self
+ .spawn_pi_streaming(
+ &pi_path,
+ prompt,
+ &resolved_model,
working_dir,
&resolved_provider,
provider_api_key,
None,
+ line_tx,
)
.await;
}
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index e5d288caa..3267a9240 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -73,13 +73,13 @@ fn default_agent() -> String {
"pi".into()
}
fn default_model() -> String {
- "claude-haiku-4-5@20251001".into()
+ "claude-haiku-4-5".into()
}
fn is_default_agent(s: &String) -> bool {
s == "pi"
}
fn is_default_model(s: &String) -> bool {
- s == "claude-haiku-4-5@20251001"
+ s == "claude-haiku-4-5" || s == "claude-haiku-4-5@20251001"
}
/// Result of a single pipe run.
@@ -329,6 +329,10 @@ fn parse_error_type(stderr: &str) -> (Option<String>, Option<String>) {
/// Args: (pipe_name, success, duration_secs)
pub type OnPipeRunComplete = Arc<dyn Fn(&str, bool, f64) + Send + Sync>;
+/// Callback fired for each stdout line from a running pipe.
+/// Args: (pipe_name, execution_id, line)
+pub type OnPipeOutputLine = Arc<dyn Fn(&str, i64, &str) + Send + Sync>;
+
/// Default execution timeout: 5 minutes.
const DEFAULT_TIMEOUT_SECS: u64 = 300;
@@ -351,6 +355,8 @@ pub struct PipeManager {
shutdown_tx: Option<tokio::sync::watch::Sender<bool>>,
/// Optional callback fired after each scheduled pipe run.
on_run_complete: Option<OnPipeRunComplete>,
+ /// Optional callback fired for each stdout line from a running pipe.
+ on_output_line: Option<OnPipeOutputLine>,
/// Optional persistence store (None in CLI mode).
store: Option<Arc<dyn PipeStore>>,
/// API port for prompt rendering (default 3030).
@@ -376,6 +382,7 @@ impl PipeManager {
semaphore: Arc::new(Semaphore::new(1)),
shutdown_tx: None,
on_run_complete: None,
+ on_output_line: None,
store,
api_port,
last_reload: Arc::new(Mutex::new(Instant::now() - std::time::Duration::from_secs(10))),
@@ -387,6 +394,11 @@ impl PipeManager {
self.on_run_complete = Some(cb);
}
+ /// Set a callback to be invoked for each stdout line from a running pipe.
+ pub fn set_on_output_line(&mut self, cb: OnPipeOutputLine) {
+ self.on_output_line = Some(cb);
+ }
+
/// Mark orphaned 'running' executions as failed on startup.
pub async fn startup_recovery(&self) {
if let Some(ref store) = self.store {
@@ -752,6 +764,7 @@ impl PipeManager {
let semaphore = self.semaphore.clone();
let store_ref = self.store.clone();
let on_complete = self.on_run_complete.clone();
+ let on_output = self.on_output_line.clone();
let pipes_dir_for_log = self.pipes_dir.clone();
let executors = self.executors.clone();
let agent = config.agent.clone();
@@ -762,9 +775,23 @@ impl PipeManager {
let started_at = Utc::now();
let timeout_duration = std::time::Duration::from_secs(DEFAULT_TIMEOUT_SECS);
+ // Create streaming channel and drainer task
+ let (line_tx, mut line_rx) =
+ tokio::sync::mpsc::unbounded_channel::<String>();
+ let drain_pipe_name = pipe_name.clone();
+ let drain_exec_id = exec_id.unwrap_or(0);
+ let drain_on_output = on_output.clone();
+ tokio::spawn(async move {
+ while let Some(line) = line_rx.recv().await {
+ if let Some(ref cb) = drain_on_output {
+ cb(&drain_pipe_name, drain_exec_id, &line);
+ }
+ }
+ });
+
let run_result = tokio::time::timeout(
timeout_duration,
- executor.run(
+ executor.run_streaming(
&prompt,
&run_model,
&pipe_dir,
@@ -772,6 +799,7 @@ impl PipeManager {
run_provider_url.as_deref(),
run_api_key.as_deref(),
Some(pid_tx),
+ line_tx,
),
)
.await;
@@ -975,9 +1003,12 @@ impl PipeManager {
)
}
None => {
- warn!("pipe '{}': preset '{}' not found in store.bin, falling back to pipe config",
- name, preset_id);
- (config.model.clone(), config.provider.clone(), None, None)
+ return Err(anyhow!(
+ "pipe '{}': preset '{}' not found in settings — \
+ create the preset in Settings → AI or remove the \
+ 'preset: {}' line from the pipe config",
+ name, preset_id, preset_id
+ ));
}
}
} else {
@@ -1054,11 +1085,25 @@ impl PipeManager {
}
}
- // Run with timeout
+ // Run with timeout + streaming
let timeout_duration = std::time::Duration::from_secs(DEFAULT_TIMEOUT_SECS);
+
+ let (line_tx, mut line_rx) =
+ tokio::sync::mpsc::unbounded_channel::<String>();
+ let drain_pipe_name = name.to_string();
+ let drain_exec_id = exec_id.unwrap_or(0);
+ let drain_on_output = self.on_output_line.clone();
+ tokio::spawn(async move {
+ while let Some(line) = line_rx.recv().await {
+ if let Some(ref cb) = drain_on_output {
+ cb(&drain_pipe_name, drain_exec_id, &line);
+ }
+ }
+ });
+
let run_result = tokio::time::timeout(
timeout_duration,
- executor.run(
+ executor.run_streaming(
&prompt,
&run_model,
&pipe_dir,
@@ -1066,6 +1111,7 @@ impl PipeManager {
run_provider_url.as_deref(),
run_api_key.as_deref(),
Some(pid_tx),
+ line_tx,
),
)
.await;
@@ -1478,6 +1524,7 @@ impl PipeManager {
let executors = self.executors.clone();
let pipes_dir = self.pipes_dir.clone();
let on_run_complete = self.on_run_complete.clone();
+ let on_output_line = self.on_output_line.clone();
let store = self.store.clone();
let api_port = self.api_port;
@@ -1601,6 +1648,7 @@ impl PipeManager {
let sem = semaphore.clone();
let pipes_dir_for_log = pipes_dir.clone();
let on_complete = on_run_complete.clone();
+ let on_output = on_output_line.clone();
let store_ref = store.clone();
tokio::spawn(async move {
@@ -1662,9 +1710,24 @@ impl PipeManager {
let started_at = Utc::now();
let timeout_duration = std::time::Duration::from_secs(DEFAULT_TIMEOUT_SECS);
+
+ // Create streaming channel and drainer for scheduler
+ let (line_tx, mut line_rx) =
+ tokio::sync::mpsc::unbounded_channel::<String>();
+ let sched_pipe_name = pipe_name.clone();
+ let sched_exec_id = exec_id.unwrap_or(0);
+ let sched_on_output = on_output.clone();
+ tokio::spawn(async move {
+ while let Some(line) = line_rx.recv().await {
+ if let Some(ref cb) = sched_on_output {
+ cb(&sched_pipe_name, sched_exec_id, &line);
+ }
+ }
+ });
+
let run_result = tokio::time::timeout(
timeout_duration,
- executor.run(
+ executor.run_streaming(
&prompt,
&model,
&pipe_dir,
@@ -1672,6 +1735,7 @@ impl PipeManager {
provider_url.as_deref(),
api_key.as_deref(),
Some(pid_tx),
+ line_tx,
),
)
.await;