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.2.92: token counter, fix ShowRewindWindow type, remove duplicate pipe suggestions

Louis Beaumont2f75e90bf357
diff --git a/Cargo.lock b/Cargo.lock
index bc76a39c3..c09bcd5bf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6476,7 +6476,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"audiopipe",
@@ -6533,7 +6533,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"async-trait",
@@ -6559,7 +6559,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -6602,7 +6602,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"chrono",
@@ -6627,7 +6627,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"async-trait",
@@ -6694,7 +6694,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"chrono",
@@ -6712,7 +6712,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -6752,7 +6752,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"argon2",
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
index 8b96d224b..7724822a5 100644
--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
@@ -1163,7 +1163,7 @@ export const AIPresetsSelector = ({
size="sm"
className="shrink-0 h-7 text-xs border-amber-500/30 hover:bg-amber-500/10"
onClick={async () => {
- await commands.showWindow({ Settings: { page: "account" } });
+ await commands.showWindow({ Home: { page: "account" } });
}}
>
<LogIn className="h-3 w-3 mr-1" />
diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
index 32758c8a8..b8f5c8c36 100644
--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
@@ -979,7 +979,7 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {
</p>
<button
- onClick={() => commands.showWindow({ Settings: { page: null } })}
+ onClick={() => commands.showWindow({ Home: { page: null } })}
className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-full text-sm font-medium hover:bg-primary/90 transition-colors"
>
<Settings className="w-4 h-4" />
diff --git a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
index e728a4a69..142d890b3 100644
--- a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
@@ -369,6 +369,42 @@ const AISection = ({
updateSettingsPreset({ apiKey: value });
}, [updateSettingsPreset]);
+ // Auto-set max output tokens based on model name
+ const getDefaultMaxTokens = useCallback((model: string): number | null => {
+ const m = model.toLowerCase();
+ // Claude models
+ if (m.includes("opus")) return 64000;
+ if (m.includes("sonnet-4") || m.includes("sonnet-3.7")) return 64000;
+ if (m.includes("haiku")) return 8192;
+ // OpenAI models
+ if (m.includes("gpt-5")) return 128000;
+ if (m.includes("o3") || m.includes("o4") || m.includes("o1")) return 100000;
+ if (m.includes("gpt-4.1")) return 32768;
+ if (m.includes("gpt-oss")) return 8192;
+ // Google models
+ if (m.includes("gemini-3") || m.includes("gemini-2.5-pro")) return 65536;
+ if (m.includes("gemini")) return 8192;
+ // DeepSeek
+ if (m.includes("deepseek")) return 8192;
+ // Qwen
+ if (m.includes("qwen")) return 8192;
+ // Mistral
+ if (m.includes("mistral")) return 4096;
+ // Local/OSS models
+ if (m.includes("llama")) return 4096;
+ if (m.includes("phi")) return 16384;
+ return null; // unknown model, don't change
+ }, []);
+
+ useEffect(() => {
+ const model = settingsPreset?.model;
+ if (!model) return;
+ const tokens = getDefaultMaxTokens(model);
+ if (tokens && (settingsPreset as any)?.maxTokens !== tokens) {
+ updateSettingsPreset({ maxTokens: tokens } as any);
+ }
+ }, [settingsPreset?.model]);
+
const handleCustomPromptChange = useCallback((value: string, isValid: boolean) => {
updateSettingsPreset({ prompt: value });
}, [updateSettingsPreset]);
@@ -1256,7 +1292,7 @@ const AISection = ({
Max Output Tokens
</Label>
<p className="text-xs text-muted-foreground mb-2">
- Maximum tokens the model can generate per response. Lower values work better with providers like Groq.
+ Maximum tokens the model can generate per response.
</p>
<Input
id="maxTokens"
@@ -1268,6 +1304,30 @@ const AISection = ({
onChange={(e) => updateSettingsPreset({ maxTokens: parseInt(e.target.value) || 4096 } as any)}
className="w-full"
/>
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ {[
+ { label: "8k", value: 8192, hint: "haiku / qwen / deepseek" },
+ { label: "32k", value: 32768, hint: "gpt-4.1" },
+ { label: "64k", value: 64000, hint: "opus / sonnet" },
+ { label: "65k", value: 65536, hint: "gemini 3 pro" },
+ { label: "100k", value: 100000, hint: "o3 / o4" },
+ { label: "128k", value: 128000, hint: "gpt-5" },
+ ].map((preset) => (
+ <button
+ key={preset.value}
+ type="button"
+ className={`px-2 py-1 text-xs rounded-md border transition-colors ${
+ (settingsPreset as any)?.maxTokens === preset.value
+ ? "bg-primary text-primary-foreground border-primary"
+ : "bg-muted/50 hover:bg-muted border-border"
+ }`}
+ onClick={() => updateSettingsPreset({ maxTokens: preset.value } as any)}
+ >
+ {preset.label}
+ <span className="text-[10px] ml-1 opacity-60">{preset.hint}</span>
+ </button>
+ ))}
+ </div>
</div>
)}
diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
index 1244c972d..10ea12b4b 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
@@ -32,6 +32,13 @@ import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { homeDir, join } from "@tauri-apps/api/path";
import { revealItemInDir, openUrl } from "@tauri-apps/plugin-opener";
import { emit, once } from "@tauri-apps/api/event";
@@ -1173,6 +1180,23 @@ export function PipesSection() {
}
/>
+ {/* Optimize with AI */}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0"
+ title="optimize with ai"
+ onClick={() => {
+ navigateHomeAndPrefill({
+ context: "the user wants to optimize their pipe",
+ prompt: buildOptimizePrompt(pipe.config.name),
+ autoSend: true,
+ });
+ }}
+ >
+ <Sparkles className="h-3.5 w-3.5" />
+ </Button>
+
{/* Overflow menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -1207,18 +1231,6 @@ export function PipesSection() {
</DropdownMenuItem>
</>
)}
- <DropdownMenuItem
- onClick={async () => {
- navigateHomeAndPrefill({
- context: "the user wants to optimize their pipe",
- prompt: buildOptimizePrompt(pipe.config.name),
- autoSend: true,
- });
- }}
- >
- <Sparkles className="h-3.5 w-3.5 mr-2" />
- optimize
- </DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive"
@@ -1371,6 +1383,69 @@ export function PipesSection() {
</p>
</div>
+ <div>
+ <Label className="text-xs">schedule</Label>
+ <Select
+ value={pipe.config.schedule || "manual"}
+ onValueChange={(value) => {
+ const pipeName = pipe.config.name;
+ setPipes((prev) =>
+ prev.map((p) =>
+ p.config.name === pipeName
+ ? { ...p, config: { ...p.config, schedule: value } }
+ : p
+ )
+ );
+ const savePromise = fetch(`http://localhost:3030/pipes/${pipeName}/config`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ schedule: value }),
+ }).then(() => {
+ delete pendingConfigSaves.current[pipeName];
+ fetchPipes();
+ }).catch(() => {
+ delete pendingConfigSaves.current[pipeName];
+ });
+ pendingConfigSaves.current[pipeName] = savePromise;
+ }}
+ >
+ <SelectTrigger className="mt-1 h-8 text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {(() => {
+ const presets = [
+ { value: "manual", label: "manual" },
+ { value: "every 5m", label: "every 5 minutes" },
+ { value: "every 15m", label: "every 15 minutes" },
+ { value: "every 30m", label: "every 30 minutes" },
+ { value: "every 1h", label: "every hour" },
+ { value: "every 3h", label: "every 3 hours" },
+ { value: "every day at 9am", label: "every morning (9 AM)" },
+ { value: "every day at 12pm", label: "every noon (12 PM)" },
+ { value: "every day at 6pm", label: "every evening (6 PM)" },
+ { value: "every monday at 9am", label: "every monday (9 AM)" },
+ ];
+ const current = pipe.config.schedule || "manual";
+ const isCustom = !presets.some((p) => p.value === current);
+ return (
+ <>
+ {isCustom && (
+ <SelectItem value={current}>{current} (custom)</SelectItem>
+ )}
+ {presets.map((p) => (
+ <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>
+ ))}
+ </>
+ );
+ })()}
+ </SelectContent>
+ </Select>
+ <p className="text-[11px] text-muted-foreground mt-1">
+ how often this pipe runs automatically
+ </p>
+ </div>
+
<div className="flex items-center gap-3">
<div className="flex items-center gap-1.5">
<Label className="text-xs">history</Label>
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 9ee55988b..1ac1861fd 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -208,11 +208,13 @@ function GridDissolveLoader({
label,
toolName,
thinkingSecs,
+ tokenCount,
}: {
phase?: LoaderPhase;
label?: string;
toolName?: string;
thinkingSecs?: number;
+ tokenCount?: number;
}) {
const ROWS = 3;
const COLS = 5;
@@ -262,6 +264,12 @@ function GridDissolveLoader({
"analyzing..."
);
+ const tokenLabel = tokenCount != null && tokenCount > 0
+ ? tokenCount >= 1000
+ ? `${(tokenCount / 1000).toFixed(1)}k tokens`
+ : `${tokenCount} tokens`
+ : null;
+
return (
<div className="flex items-center gap-2">
<div
@@ -288,7 +296,7 @@ function GridDissolveLoader({
))}
</div>
<span className="text-[11px] font-mono text-muted-foreground tracking-wide">
- {displayLabel}
+ {displayLabel}{tokenLabel && <span className="ml-1.5 opacity-60">· {tokenLabel}</span>}
</span>
</div>
);
@@ -713,6 +721,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const [messages, setMessages] = useState<Message[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isStreaming, setIsStreaming] = useState(false);
+ const [streamedCharCount, setStreamedCharCount] = useState(0);
const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);
const [activePreset, setActivePreset] = useState<AIPreset | undefined>();
const [showMentionDropdown, setShowMentionDropdown] = useState(false);
@@ -1427,6 +1436,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const evt = data.assistantMessageEvent;
if (evt.type === "text_delta" && evt.delta) {
piStreamingTextRef.current += evt.delta;
+ setStreamedCharCount(piStreamingTextRef.current.length);
// Append to last text block or create new one
const blocks = piContentBlocksRef.current;
@@ -2301,6 +2311,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
piStreamingTextRef.current = "";
piMessageIdRef.current = assistantMessageId;
piContentBlocksRef.current = [];
+ setStreamedCharCount(0);
// Clear follow-ups for new message
setFollowUpSuggestions([]);
@@ -2872,7 +2883,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
<Button
variant="outline"
onClick={async () => {
- await commands.showWindow({ Settings: { page: null } });
+ await commands.showWindow({ Home: { page: null } });
}}
className="gap-2"
>
@@ -3032,6 +3043,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
phase={loaderPhase}
toolName={toolName}
thinkingSecs={thinkingSecs}
+ tokenCount={Math.round(streamedCharCount / 4)}
/>
</motion.div>
);
diff --git a/apps/screenpipe-app-tauri/lib/utils/window.ts b/apps/screenpipe-app-tauri/lib/utils/window.ts
index ad86978bb..8353b1ccb 100644
--- a/apps/screenpipe-app-tauri/lib/utils/window.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/window.ts
@@ -2,7 +2,7 @@ import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
import { commands } from "./tauri";
export async function openSettingsWindow(section?: string) {
- await commands.showWindow({ Settings: { page: section ?? null } });
+ await commands.showWindow({ Home: { page: section ?? null } });
}
export async function openMainWindow() {
await commands.showWindow("Main");
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 419717d27..7a47e43cc 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9172,7 +9172,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.2.90"
+version = "2.2.92"
dependencies = [
"anyhow",
"arboard",
@@ -9273,7 +9273,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"audiopipe",
@@ -9325,7 +9325,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"async-trait",
@@ -9351,7 +9351,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -9393,7 +9393,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"chrono",
@@ -9418,7 +9418,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"async-trait",
@@ -9480,7 +9480,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"chrono",
@@ -9496,7 +9496,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -9532,7 +9532,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.3.180"
+version = "0.3.181"
dependencies = [
"anyhow",
"argon2",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 72cac0d74..b4d66d327 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.2.91"
+version = "2.2.92"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 9b4e1ea0b..3ea21e199 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -12,6 +12,30 @@ use serde_json::{json, Value};
use specta::Type;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
+
+/// Read lines from a byte stream using lossy UTF-8 conversion.
+/// Unlike `BufReader::lines()`, this never fails on invalid UTF-8 —
+/// invalid bytes are replaced with U+FFFD instead of crashing the reader.
+fn read_lines_lossy(reader: &mut BufReader<impl std::io::Read>) -> Option<String> {
+ let mut buf = Vec::new();
+ match reader.read_until(b'\n', &mut buf) {
+ Ok(0) => None, // EOF
+ Ok(_) => {
+ // Strip trailing newline
+ if buf.last() == Some(&b'\n') {
+ buf.pop();
+ if buf.last() == Some(&b'\r') {
+ buf.pop();
+ }
+ }
+ Some(String::from_utf8_lossy(&buf).into_owned())
+ }
+ Err(e) => {
+ error!("I/O error reading pi output: {}", e);
+ None
+ }
+ }
+}
use std::path::PathBuf;
#[cfg(windows)]
use std::path::Path;
@@ -709,7 +733,7 @@ fn ensure_pi_config(
let wire_api = if config.provider == "openai-chatgpt" {
"openai-codex-responses"
} else if config.provider == "anthropic" {
- "anthropic"
+ "anthropic-messages"
} else {
"openai-completions"
};
@@ -1240,61 +1264,53 @@ pub async fn pi_start_inner(
let terminated_guard = terminated_emitted.clone();
let sid_clone = sid.clone();
std::thread::spawn(move || {
- let reader = BufReader::new(stdout);
+ let mut reader = BufReader::new(stdout);
info!(
"Pi stdout reader started (pid: {}, session: {})",
pid, sid_clone
);
let mut line_count = 0u64;
let mut ready_signalled = false;
- for line in reader.lines() {
- match line {
- Ok(line) => {
- line_count += 1;
- let event_type = serde_json::from_str::<Value>(&line).ok().and_then(|v| {
- v.get("type")
- .and_then(|t| t.as_str())
- .map(|s| s.to_string())
- });
- debug!(
- "Pi stdout #{} (pid {}, session {}): type={}",
- line_count,
- pid,
- sid_clone,
- event_type.as_deref().unwrap_or("non-json")
- );
+ while let Some(line) = read_lines_lossy(&mut reader) {
+ line_count += 1;
+ let event_type = serde_json::from_str::<Value>(&line).ok().and_then(|v| {
+ v.get("type")
+ .and_then(|t| t.as_str())
+ .map(|s| s.to_string())
+ });
+ debug!(
+ "Pi stdout #{} (pid {}, session {}): type={}",
+ line_count,
+ pid,
+ sid_clone,
+ event_type.as_deref().unwrap_or("non-json")
+ );
- // Signal readiness on first successful JSON line
- if !ready_signalled {
- if serde_json::from_str::<Value>(&line).is_ok() {
- ready_notify_reader.notify_one();
- ready_signalled = true;
- }
- }
+ // Signal readiness on first successful JSON line
+ if !ready_signalled {
+ if serde_json::from_str::<Value>(&line).is_ok() {
+ ready_notify_reader.notify_one();
+ ready_signalled = true;
+ }
+ }
- // Try to parse as JSON and emit event tagged with sessionId
- match serde_json::from_str::<Value>(&line) {
- Ok(event) => {
- let tagged = json!({ "sessionId": sid_clone, "event": event });
- if let Err(e) = app_handle.emit("pi_event", &tagged) {
- error!("Failed to emit pi_event: {}", e);
- }
- }
- Err(e) => {
- let end = line.len().min(100);
- let end = line.floor_char_boundary(end);
- warn!("Pi stdout not JSON: {} (line: {})", e, &line[..end]);
- }
- }
- if let Err(e) = app_handle.emit("pi_output", &line) {
- error!("Failed to emit pi_output: {}", e);
+ // Try to parse as JSON and emit event tagged with sessionId
+ match serde_json::from_str::<Value>(&line) {
+ Ok(event) => {
+ let tagged = json!({ "sessionId": sid_clone, "event": event });
+ if let Err(e) = app_handle.emit("pi_event", &tagged) {
+ error!("Failed to emit pi_event: {}", e);
}
}
Err(e) => {
- error!("Error reading pi stdout: {}", e);
- break;
+ let end = line.len().min(100);
+ let end = line.floor_char_boundary(end);
+ warn!("Pi stdout not JSON: {} (line: {})", e, &line[..end]);
}
}
+ if let Err(e) = app_handle.emit("pi_output", &line) {
+ error!("Failed to emit pi_output: {}", e);
+ }
}
info!(
"Pi stdout reader ended (pid: {}, session: {}), processed {} lines",
@@ -1320,37 +1336,29 @@ pub async fn pi_start_inner(
let app_handle = app.clone();
let sid_stderr = sid.clone();
std::thread::spawn(move || {
- let reader = BufReader::new(stderr);
+ let mut reader = BufReader::new(stderr);
info!("Pi stderr reader started (session: {})", sid_stderr);
- for line in reader.lines() {
- match line {
- Ok(line) => {
- // Try to parse as JSON RPC event and forward like stdout
- if let Ok(event) = serde_json::from_str::<Value>(&line) {
- let event_type =
- event.get("type").and_then(|t| t.as_str()).unwrap_or("?");
- debug!(
- "Pi stderr JSON (session {}): type={}",
- sid_stderr, event_type
- );
- let tagged = json!({ "sessionId": sid_stderr, "event": event });
- if let Err(e) = app_handle.emit("pi_event", &tagged) {
- error!("Failed to emit pi_event from stderr: {}", e);
- }
- if let Err(e) = app_handle.emit("pi_output", &line) {
- error!("Failed to emit pi_output from stderr: {}", e);
- }
- } else {
- // Not JSON — log as warn so Pi startup errors are visible
- warn!("Pi stderr: {}", &line[..line.len().min(500)]);
- }
- let _ = app_handle.emit("pi_log", &line);
+ while let Some(line) = read_lines_lossy(&mut reader) {
+ // Try to parse as JSON RPC event and forward like stdout
+ if let Ok(event) = serde_json::from_str::<Value>(&line) {
+ let event_type =
+ event.get("type").and_then(|t| t.as_str()).unwrap_or("?");
+ debug!(
+ "Pi stderr JSON (session {}): type={}",
+ sid_stderr, event_type
+ );
+ let tagged = json!({ "sessionId": sid_stderr, "event": event });
+ if let Err(e) = app_handle.emit("pi_event", &tagged) {
+ error!("Failed to emit pi_event from stderr: {}", e);
}
- Err(e) => {
- error!("Error reading pi stderr: {}", e);
- break;
+ if let Err(e) = app_handle.emit("pi_output", &line) {
+ error!("Failed to emit pi_output from stderr: {}", e);
}
+ } else {
+ // Not JSON — log as warn so Pi startup errors are visible
+ warn!("Pi stderr: {}", &line[..line.len().min(500)]);
}
+ let _ = app_handle.emit("pi_log", &line);
}
info!("Pi stderr reader ended (session: {})", sid_stderr);
});
@@ -2397,4 +2405,109 @@ mod tests {
fn test_ready_timeout_constant() {
assert_eq!(super::PI_READY_TIMEOUT.as_secs(), 2);
}
+
+ // -- read_lines_lossy unit tests --
+
+ /// Valid UTF-8 line is returned as-is
+ #[test]
+ fn test_read_lines_lossy_valid_utf8() {
+ let data = b"hello world\n";
+ let mut reader = BufReader::new(&data[..]);
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("hello world".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), None); // EOF
+ }
+
+ /// Multiple lines are read sequentially
+ #[test]
+ fn test_read_lines_lossy_multiple_lines() {
+ let data = b"line one\nline two\nline three\n";
+ let mut reader = BufReader::new(&data[..]);
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("line one".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("line two".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("line three".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), None);
+ }
+
+ /// Invalid UTF-8 bytes are replaced with U+FFFD instead of erroring
+ #[test]
+ fn test_read_lines_lossy_invalid_utf8() {
+ // 0xFF 0xFE are not valid UTF-8
+ let data: &[u8] = &[b'h', b'i', 0xFF, 0xFE, b'\n'];
+ let mut reader = BufReader::new(data);
+ let line = super::read_lines_lossy(&mut reader).unwrap();
+ assert!(line.contains('\u{FFFD}'), "should contain replacement char, got: {}", line);
+ assert!(line.starts_with("hi"), "should preserve valid prefix");
+ }
+
+ /// CRLF line endings are stripped
+ #[test]
+ fn test_read_lines_lossy_crlf() {
+ let data = b"windows line\r\n";
+ let mut reader = BufReader::new(&data[..]);
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("windows line".into()));
+ }
+
+ /// Last line without trailing newline is still returned
+ #[test]
+ fn test_read_lines_lossy_no_trailing_newline() {
+ let data = b"no newline at end";
+ let mut reader = BufReader::new(&data[..]);
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("no newline at end".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), None);
+ }
+
+ /// Empty input returns None immediately
+ #[test]
+ fn test_read_lines_lossy_empty() {
+ let data: &[u8] = b"";
+ let mut reader = BufReader::new(data);
+ assert_eq!(super::read_lines_lossy(&mut reader), None);
+ }
+
+ /// Empty line (just a newline) returns empty string
+ #[test]
+ fn test_read_lines_lossy_empty_line() {
+ let data = b"\n";
+ let mut reader = BufReader::new(&data[..]);
+ assert_eq!(super::read_lines_lossy(&mut reader), Some("".into()));
+ assert_eq!(super::read_lines_lossy(&mut reader), None);
+ }
+
+ /// Large JSON line (simulating Pi's big outputs) is read completely
+ #[test]
+ fn test_read_lines_lossy_large_json() {
+ let big_value = "x".repeat(100_000);
+ let json_line = format!("{{\"type\":\"data\",\"content\":\"{}\"}}\n", big_value);
+ let mut reader = BufReader::new(json_line.as_bytes());
+ let line = super::read_lines_lossy(&mut reader).unwrap();
+ assert_eq!(line.len(), json_line.len() - 1); // minus the \n
+ // Verify it's valid JSON
+ assert!(serde_json::from_str::<Value>(&line).is_ok());
+ }
+
+ /// Mixed valid and invalid UTF-8 lines — valid lines unaffected
+ #[test]
+ fn test_read_lines_lossy_mixed_valid_invalid() {
+ let mut data: Vec<u8> = Vec::new();
+ data.extend_from_slice(b"{\"type\":\"ok\"}\n");
+ data.extend_from_slice(&[0x80, 0x81, b'\n']); // invalid UTF-8 line
+ data.extend_from_slice(b"{\"type\":\"still_ok\"}\n");
+
+ let mut reader = BufReader::new(&data[..]);
+
+ // First line: valid JSON
+ let line1 = super::read_lines_lossy(&mut reader).unwrap();
+ assert!(serde_json::from_str::<Value>(&line1).is_ok());
+
+ // Second line: lossy conversion, not valid JSON but reader survives
+ let line2 = super::read_lines_lossy(&mut reader).unwrap();
+ assert!(line2.contains('\u{FFFD}'));
+
+ // Third line: valid JSON — reader recovered
+ let line3 = super::read_lines_lossy(&mut reader).unwrap();
+ let v: Value = serde_json::from_str(&line3).unwrap();
+ assert_eq!(v["type"], "still_ok");
+
+ assert_eq!(super::read_lines_lossy(&mut reader), None);
+ }
}
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index 4afb5b3e9..f76646b6d 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -342,7 +342,7 @@ impl PiExecutor {
let wire_api = if prov == "openai-chatgpt" {
"openai-codex-responses"
} else if prov == "anthropic" {
- "anthropic"
+ "anthropic-messages"
} else {
"openai-completions"
};