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.324, CLI to v0.3.118 release-app

Louis Beaumont306b4f611f29
diff --git a/.claude/agents/posthog.md b/.claude/agents/posthog.md
index f85906295..778aa9890 100644
--- a/.claude/agents/posthog.md
+++ b/.claude/agents/posthog.md
@@ -1,6 +1,6 @@
---
name: posthog
-description: Query PostHog for product analytics, create insights, dashboards, and track user behavior. Auto-activates when user asks about analytics, user behavior, funnels, retention, or dashboards. Trigger words: "check posthog", "create insight", "analytics", "user behavior", "dashboard", "funnel", "retention", "user metrics", "usage stats"
+description: 'Query PostHog for product analytics, create insights, dashboards, and track user behavior. Auto-activates when user asks about analytics, user behavior, funnels, retention, or dashboards. Trigger words: "check posthog", "create insight", "analytics", "user behavior", "dashboard", "funnel", "retention", "user metrics", "usage stats"'
allowed-tools: Bash, Read
---
diff --git a/Cargo.toml b/Cargo.toml
index 4ae98bf20..f76567ef7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ exclude = ["apps/screenpipe-app-tauri/src-tauri"]
resolver = "2"
[workspace.package]
-version = "0.3.117"
+version = "0.3.118"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/screenpipe/screenpipe"
diff --git a/apps/screenpipe-app-tauri/components/update-banner.tsx b/apps/screenpipe-app-tauri/components/update-banner.tsx
index 82efdb6dd..80d5b1d95 100644
--- a/apps/screenpipe-app-tauri/components/update-banner.tsx
+++ b/apps/screenpipe-app-tauri/components/update-banner.tsx
@@ -6,6 +6,9 @@ import { create } from "zustand";
import { useEffect } from "react";
import { listen } from "@tauri-apps/api/event";
import { relaunch } from "@tauri-apps/plugin-process";
+import { invoke } from "@tauri-apps/api/core";
+import { check, type Update } from "@tauri-apps/plugin-updater";
+import { platform, arch } from "@tauri-apps/plugin-os";
import { useToast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
@@ -18,18 +21,22 @@ interface UpdateBannerState {
isVisible: boolean;
updateInfo: UpdateInfo | null;
isInstalling: boolean;
+ pendingUpdate: Update | null;
setIsVisible: (visible: boolean) => void;
setUpdateInfo: (info: UpdateInfo | null) => void;
setIsInstalling: (installing: boolean) => void;
+ setPendingUpdate: (update: Update | null) => void;
}
export const useUpdateBanner = create<UpdateBannerState>((set) => ({
isVisible: false,
updateInfo: null,
isInstalling: false,
+ pendingUpdate: null,
setIsVisible: (visible) => set({ isVisible: visible }),
setUpdateInfo: (info) => set({ updateInfo: info }),
setIsInstalling: (installing) => set({ isInstalling: installing }),
+ setPendingUpdate: (update) => set({ pendingUpdate: update }),
}));
interface UpdateBannerProps {
@@ -38,21 +45,66 @@ interface UpdateBannerProps {
}
export function UpdateBanner({ className, compact = false }: UpdateBannerProps) {
- const { isVisible, updateInfo, isInstalling, setIsVisible, setIsInstalling } = useUpdateBanner();
+ const { isVisible, updateInfo, isInstalling, setIsVisible, setIsInstalling, pendingUpdate } = useUpdateBanner();
const { toast } = useToast();
const handleUpdate = async () => {
setIsInstalling(true);
- toast({
- title: "installing update...",
- description: "screenpipe will restart automatically",
- duration: 10000,
- });
-
+ const os = platform();
+
try {
+ // On Windows, the update is not pre-downloaded by the backend (unlike macOS/Linux)
+ // We need to check for update, download, and install it before relaunching
+ if (os === "windows") {
+ toast({
+ title: "downloading update...",
+ description: "please wait while the update is downloaded",
+ duration: Infinity,
+ });
+
+ // Stop screenpipe before update on Windows
+ try {
+ await invoke("stop_screenpipe");
+ } catch (e) {
+ console.warn("failed to stop screenpipe:", e);
+ }
+
+ // Get or check for the update
+ let update = pendingUpdate;
+ if (!update) {
+ const cpuArch = arch();
+ const endpoint = `https://cdn.crabnebula.app/update/mediar/screenpipe/windows-${cpuArch}/{{current_version}}`;
+ update = await check({ endpoints: [endpoint] } as any);
+ }
+
+ if (update?.available) {
+ // Backup before installing
+ try {
+ await invoke("backup_current_app");
+ } catch (e) {
+ console.warn("rollback backup failed, continuing with update:", e);
+ }
+
+ await update.downloadAndInstall();
+
+ toast({
+ title: "update complete",
+ description: "relaunching application",
+ duration: 3000,
+ });
+ }
+ } else {
+ // On macOS/Linux, the update was already downloaded by the backend
+ toast({
+ title: "installing update...",
+ description: "screenpipe will restart automatically",
+ duration: 10000,
+ });
+ }
+
await relaunch();
} catch (error) {
- console.error("failed to relaunch:", error);
+ console.error("failed to update:", error);
setIsInstalling(false);
toast({
title: "update failed",
@@ -79,7 +131,7 @@ export function UpdateBanner({ className, compact = false }: UpdateBannerProps)
onClick={handleUpdate}
disabled={isInstalling}
>
- {isInstalling ? "..." : "update"}
+ {isInstalling ? "downloading..." : "update"}
</Button>
</div>
);
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-handler.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-handler.test.ts
new file mode 100644
index 000000000..10faa37d3
--- /dev/null
+++ b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-handler.test.ts
@@ -0,0 +1,533 @@
+import { describe, it, expect } from "vitest";
+import {
+ createInitialState,
+ reducePiEvent,
+ formatPiMessage,
+ validateProjectDir,
+ shouldPiStart,
+ shouldIgnoreTermination,
+ formatToolArgs,
+ PiEvent,
+ PiMessageState,
+} from "../pi-event-handler";
+
+// ============================================================================
+// reducePiEvent
+// ============================================================================
+
+describe("reducePiEvent", () => {
+ it("returns initial state for unknown event types", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, { type: "turn_start" } as PiEvent);
+ expect(result).toEqual(state);
+ });
+
+ // --- text_delta ---
+
+ it("appends text_delta to text", () => {
+ const state = createInitialState();
+ const event: PiEvent = {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "Hello" },
+ };
+ const result = reducePiEvent(state, event);
+ expect(result.text).toBe("Hello");
+ });
+
+ it("appends multiple text deltas", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "Hello" },
+ });
+ state = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: " world" },
+ });
+ expect(state.text).toBe("Hello world");
+ });
+
+ it("ignores message_update with no assistantMessageEvent", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, { type: "message_update" });
+ expect(result).toEqual(state);
+ });
+
+ it("ignores non-text_delta assistant events", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_start" },
+ });
+ expect(result.text).toBe("");
+ });
+
+ it("ignores text_delta with no delta", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta" },
+ });
+ expect(result.text).toBe("");
+ });
+
+ // --- tool_execution_start ---
+
+ it("adds tool call on tool_execution_start", () => {
+ const state = createInitialState();
+ const event: PiEvent = {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "read",
+ args: { path: "sample.txt" },
+ };
+ const result = reducePiEvent(state, event);
+ expect(result.toolCalls).toHaveLength(1);
+ expect(result.toolCalls[0]).toMatchObject({
+ id: "call_1",
+ name: "read",
+ args: { path: "sample.txt" },
+ status: "running",
+ });
+ });
+
+ it("handles tool_execution_start with missing fields", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, { type: "tool_execution_start" });
+ expect(result.toolCalls).toHaveLength(1);
+ expect(result.toolCalls[0].name).toBe("unknown");
+ expect(result.toolCalls[0].id).toBe("");
+ });
+
+ // --- tool_execution_update ---
+
+ it("updates tool result on tool_execution_update", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "bash",
+ args: { command: "ls" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_update",
+ toolCallId: "call_1",
+ toolName: "bash",
+ partialResult: { content: [{ type: "text", text: "file1.txt\nfile2.txt" }] },
+ });
+ expect(state.toolCalls[0].result).toBe("file1.txt\nfile2.txt");
+ expect(state.toolCalls[0].status).toBe("running");
+ });
+
+ it("ignores tool_execution_update for unknown toolCallId", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "bash",
+ args: {},
+ });
+ const result = reducePiEvent(state, {
+ type: "tool_execution_update",
+ toolCallId: "call_999",
+ partialResult: { content: [{ type: "text", text: "stuff" }] },
+ });
+ expect(result.toolCalls[0].result).toBeUndefined();
+ });
+
+ it("ignores tool_execution_update with no content", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "bash",
+ args: {},
+ });
+ const result = reducePiEvent(state, {
+ type: "tool_execution_update",
+ toolCallId: "call_1",
+ });
+ expect(result.toolCalls[0].result).toBeUndefined();
+ });
+
+ // --- tool_execution_end ---
+
+ it("marks tool as done on tool_execution_end", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "read",
+ args: { path: "test.txt" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_end",
+ toolCallId: "call_1",
+ toolName: "read",
+ result: { content: [{ type: "text", text: "file contents" }] },
+ isError: false,
+ });
+ expect(state.toolCalls[0].status).toBe("done");
+ expect(state.toolCalls[0].result).toBe("file contents");
+ });
+
+ it("marks tool as error on tool_execution_end with isError", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "bash",
+ args: { command: "bad-cmd" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_end",
+ toolCallId: "call_1",
+ toolName: "bash",
+ result: { content: [{ type: "text", text: "command not found" }] },
+ isError: true,
+ });
+ expect(state.toolCalls[0].status).toBe("error");
+ expect(state.toolCalls[0].result).toBe("command not found");
+ });
+
+ it("ignores tool_execution_end with no toolCallId", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "call_1",
+ toolName: "read",
+ args: {},
+ });
+ const result = reducePiEvent(state, {
+ type: "tool_execution_end",
+ isError: false,
+ });
+ // Tool unchanged
+ expect(result.toolCalls[0].status).toBe("running");
+ });
+
+ // --- agent_end ---
+
+ it("sets done on agent_end", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, { type: "agent_end" });
+ expect(result.done).toBe(true);
+ });
+
+ it("preserves text and toolCalls on agent_end", () => {
+ let state = createInitialState();
+ state = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "result" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "c1",
+ toolName: "bash",
+ args: {},
+ });
+ state = reducePiEvent(state, { type: "agent_end" });
+ expect(state.text).toBe("result");
+ expect(state.toolCalls).toHaveLength(1);
+ expect(state.done).toBe(true);
+ });
+
+ // --- response errors ---
+
+ it("appends error on response success=false", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, {
+ type: "response",
+ success: false,
+ error: "Model not found",
+ });
+ expect(result.text).toContain("Error: Model not found");
+ expect(result.done).toBe(true);
+ });
+
+ it("ignores successful response events", () => {
+ const state = createInitialState();
+ const result = reducePiEvent(state, {
+ type: "response",
+ success: true,
+ command: "prompt",
+ });
+ expect(result).toEqual(state);
+ });
+
+ // --- full scenario ---
+
+ it("handles a full read + write scenario end to end", () => {
+ let state = createInitialState();
+
+ // Text before tool
+ state = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "I'll read the file.\n\n" },
+ });
+
+ // Read tool
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "t1",
+ toolName: "read",
+ args: { path: "sample.txt" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_end",
+ toolCallId: "t1",
+ toolName: "read",
+ result: { content: [{ type: "text", text: "hello" }] },
+ isError: false,
+ });
+
+ // More text
+ state = reducePiEvent(state, {
+ type: "message_update",
+ assistantMessageEvent: { type: "text_delta", delta: "Now writing." },
+ });
+
+ // Write tool
+ state = reducePiEvent(state, {
+ type: "tool_execution_start",
+ toolCallId: "t2",
+ toolName: "write",
+ args: { path: "result.txt", content: "olleh" },
+ });
+ state = reducePiEvent(state, {
+ type: "tool_execution_end",
+ toolCallId: "t2",
+ toolName: "write",
+ result: { content: [{ type: "text", text: "Wrote 5 bytes to result.txt" }] },
+ isError: false,
+ });
+
+ // Agent done
+ state = reducePiEvent(state, { type: "agent_end" });
+
+ expect(state.text).toBe("I'll read the file.\n\nNow writing.");
+ expect(state.toolCalls).toHaveLength(2);
+ expect(state.toolCalls[0].status).toBe("done");
+ expect(state.toolCalls[0].result).toBe("hello");
+ expect(state.toolCalls[1].status).toBe("done");
+ expect(state.toolCalls[1].result).toBe("Wrote 5 bytes to result.txt");
+ expect(state.done).toBe(true);
+ });
+});
+
+// ============================================================================
+// formatPiMessage
+// ============================================================================
+
+describe("formatPiMessage", () => {
+ it("returns 'Processing...' when empty and not done", () => {
+ const state = createInitialState();
+ expect(formatPiMessage(state)).toBe("Processing...");
+ });
+
+ it("returns text when present and no tools", () => {
+ const state: PiMessageState = { text: "Hello world", toolCalls: [], done: false };
+ expect(formatPiMessage(state)).toBe("Hello world");
+ });
+
+ it("includes running tool with spinner icon", () => {
+ const state: PiMessageState = {
+ text: "Reading...",
+ toolCalls: [
+ { id: "t1", name: "read", args: { path: "file.txt" }, status: "running" },
+ ],
+ done: false,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("⏳");
+ expect(formatted).toContain("**read**");
+ expect(formatted).toContain("`file.txt`");
+ });
+
+ it("includes done tool with check icon", () => {
+ const state: PiMessageState = {
+ text: "Done",
+ toolCalls: [
+ { id: "t1", name: "read", args: { path: "file.txt" }, status: "done", result: "contents" },
+ ],
+ done: true,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("✅");
+ expect(formatted).toContain("```\ncontents\n```");
+ });
+
+ it("includes error tool with X icon", () => {
+ const state: PiMessageState = {
+ text: "",
+ toolCalls: [
+ { id: "t1", name: "bash", args: { command: "bad" }, status: "error", result: "not found" },
+ ],
+ done: true,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("❌");
+ expect(formatted).toContain("`bad`");
+ expect(formatted).toContain("not found");
+ });
+
+ it("truncates long tool results", () => {
+ const longResult = "x".repeat(600);
+ const state: PiMessageState = {
+ text: "",
+ toolCalls: [
+ { id: "t1", name: "read", args: { path: "big.txt" }, status: "done", result: longResult },
+ ],
+ done: true,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("... (truncated)");
+ expect(formatted.length).toBeLessThan(longResult.length);
+ });
+
+ it("formats bash tool args as command", () => {
+ const state: PiMessageState = {
+ text: "",
+ toolCalls: [
+ { id: "t1", name: "bash", args: { command: "ls -la" }, status: "done", result: "files" },
+ ],
+ done: true,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("`ls -la`");
+ });
+
+ it("formats write tool args as path", () => {
+ const state: PiMessageState = {
+ text: "",
+ toolCalls: [
+ { id: "t1", name: "write", args: { path: "out.txt", content: "data" }, status: "done", result: "ok" },
+ ],
+ done: true,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("`out.txt`");
+ });
+
+ it("handles multiple tool calls in sequence", () => {
+ const state: PiMessageState = {
+ text: "Working...",
+ toolCalls: [
+ { id: "t1", name: "read", args: { path: "a.txt" }, status: "done", result: "A" },
+ { id: "t2", name: "write", args: { path: "b.txt" }, status: "done", result: "wrote B" },
+ { id: "t3", name: "bash", args: { command: "echo hi" }, status: "running" },
+ ],
+ done: false,
+ };
+ const formatted = formatPiMessage(state);
+ expect(formatted).toContain("✅ **read**");
+ expect(formatted).toContain("✅ **write**");
+ expect(formatted).toContain("⏳ **bash**");
+ });
+});
+
+// ============================================================================
+// validateProjectDir
+// ============================================================================
+
+describe("validateProjectDir", () => {
+ it("returns error for empty string", () => {
+ expect(validateProjectDir("")).not.toBeNull();
+ });
+
+ it("returns error for whitespace only", () => {
+ expect(validateProjectDir(" ")).not.toBeNull();
+ });
+
+ it("returns error for relative path", () => {
+ expect(validateProjectDir("relative/path")).not.toBeNull();
+ });
+
+ it("returns null for valid unix absolute path", () => {
+ expect(validateProjectDir("/home/user/project")).toBeNull();
+ });
+
+ it("returns null for valid windows absolute path", () => {
+ expect(validateProjectDir("C:\\Users\\project")).toBeNull();
+ });
+
+ it("returns null for /tmp path", () => {
+ expect(validateProjectDir("/tmp/test")).toBeNull();
+ });
+});
+
+// ============================================================================
+// shouldPiStart
+// ============================================================================
+
+describe("shouldPiStart", () => {
+ const defaults = {
+ isPi: true,
+ open: true,
+ needsLogin: false,
+ projectDir: "/tmp/test",
+ starting: false,
+ running: false,
+ generation: 0,
+ };
+
+ it("returns true when all conditions met", () => {
+ const { shouldStart } = shouldPiStart(defaults);
+ expect(shouldStart).toBe(true);
+ });
+
+ it("returns false when not pi", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, isPi: false });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("not pi preset");
+ });
+
+ it("returns false when chat closed", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, open: false });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("chat not open");
+ });
+
+ it("returns false when needs login", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, needsLogin: true });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("needs login");
+ });
+
+ it("returns false when no project dir", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, projectDir: "" });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("no project dir");
+ });
+
+ it("returns false when already starting", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, starting: true });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("already starting");
+ });
+
+ it("returns false when already running", () => {
+ const { shouldStart, reason } = shouldPiStart({ ...defaults, running: true });
+ expect(shouldStart).toBe(false);
+ expect(reason).toBe("already running");
+ });
+});
+
+// ============================================================================
+// shouldIgnoreTermination
+// ============================================================================
+
+describe("shouldIgnoreTermination", () => {
+ it("ignores stale generation", () => {
+ expect(shouldIgnoreTermination(0, 1)).toBe(true);
+ expect(shouldIgnoreTermination(5, 10)).toBe(true);
+ });
+
+ it("does not ignore current generation", () => {
+ expect(shouldIgnoreTermination(5, 5)).toBe(false);
+ });
+
+ it("does not ignore future generation (edge case)", () => {
+ expect(shouldIgnoreTermination(6, 5)).toBe(false);
+ });
+});
diff --git a/apps/screenpipe-app-tauri/lib/pi-event-handler.ts b/apps/screenpipe-app-tauri/lib/pi-event-handler.ts
new file mode 100644
index 000000000..62471779a
--- /dev/null
+++ b/apps/screenpipe-app-tauri/lib/pi-event-handler.ts
@@ -0,0 +1,277 @@
+/**
+ * Pi RPC event handler - pure functions for processing Pi sidecar events.
+ * Extracted from global-chat.tsx for testability.
+ */
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export interface PiToolCall {
+ id: string;
+ name: string;
+ args: Record<string, unknown>;
+ status: "running" | "done" | "error";
+ result?: string;
+}
+
+export interface PiMessageState {
+ text: string;
+ toolCalls: PiToolCall[];
+ done: boolean;
+}
+
+export type PiEventType =
+ | "message_update"
+ | "tool_execution_start"
+ | "tool_execution_update"
+ | "tool_execution_end"
+ | "agent_end"
+ | "agent_start"
+ | "turn_start"
+ | "turn_end"
+ | "message_start"
+ | "message_end"
+ | "response";
+
+export interface PiEvent {
+ type: PiEventType;
+ // message_update
+ assistantMessageEvent?: {
+ type: string;
+ delta?: string;
+ contentIndex?: number;
+ content?: string;
+ };
+ // tool events
+ toolCallId?: string;
+ toolName?: string;
+ args?: Record<string, unknown>;
+ partialResult?: {
+ content?: Array<{ type: string; text?: string }>;
+ };
+ result?: {
+ content?: Array<{ type: string; text?: string }>;
+ };
+ isError?: boolean;
+ // response
+ success?: boolean;
+ error?: string;
+ command?: string;
+ // agent_end
+ messages?: unknown[];
+}
+
+// ============================================================================
+// State reducer - processes Pi events into message state
+// ============================================================================
+
+export function createInitialState(): PiMessageState {
+ return { text: "", toolCalls: [], done: false };
+}
+
+/**
+ * Pure reducer: takes current state + event, returns new state.
+ * No side effects, fully testable.
+ */
+export function reducePiEvent(
+ state: PiMessageState,
+ event: PiEvent
+): PiMessageState {
+ switch (event.type) {
+ case "message_update": {
+ const evt = event.assistantMessageEvent;
+ if (!evt) return state;
+ if (evt.type === "text_delta" && evt.delta) {
+ return { ...state, text: state.text + evt.delta };
+ }
+ return state;
+ }
+
+ case "tool_execution_start": {
+ const toolCall: PiToolCall = {
+ id: event.toolCallId ?? "",
+ name: event.toolName ?? "unknown",
+ args: event.args ?? {},
+ status: "running",
+ };
+ return { ...state, toolCalls: [...state.toolCalls, toolCall] };
+ }
+
+ case "tool_execution_update": {
+ const content = event.partialResult?.content
+ ?.map((c) => c.text)
+ .filter(Boolean)
+ .join("\n");
+ if (!content || !event.toolCallId) return state;
+ return {
+ ...state,
+ toolCalls: state.toolCalls.map((tc) =>
+ tc.id === event.toolCallId ? { ...tc, result: content } : tc
+ ),
+ };
+ }
+
+ case "tool_execution_end": {
+ const resultText = event.result?.content
+ ?.map((c) => c.text)
+ .filter(Boolean)
+ .join("\n");
+ if (!event.toolCallId) return state;
+ return {
+ ...state,
+ toolCalls: state.toolCalls.map((tc) =>
+ tc.id === event.toolCallId
+ ? {
+ ...tc,
+ status: event.isError ? "error" : "done",
+ result: resultText ?? tc.result,
+ }
+ : tc
+ ),
+ };
+ }
+
+ case "agent_end": {
+ return { ...state, done: true };
+ }
+
+ case "response": {
+ if (event.success === false) {
+ return {
+ ...state,
+ text: state.text + `\n\nError: ${event.error ?? "Unknown error"}`,
+ done: true,
+ };
+ }
+ return state;
+ }
+
+ default:
+ return state;
+ }
+}
+
+// ============================================================================
+// Format message content with tool call details for display
+// ============================================================================
+
+/**
+ * Renders Pi message state into markdown string for the chat UI.
+ * Shows text + collapsible tool call details.
+ */
+export function formatPiMessage(state: PiMessageState): string {
+ let content = state.text;
+
+ for (const tc of state.toolCalls) {
+ const statusIcon =
+ tc.status === "running" ? "⏳" : tc.status === "error" ? "❌" : "✅";
+
+ const argsStr = formatToolArgs(tc.name, tc.args);
+
+ content += `\n\n${statusIcon} **${tc.name}** ${argsStr}`;
+
+ if (tc.result) {
+ // Truncate long results
+ const result =
+ tc.result.length > 500
+ ? tc.result.slice(0, 500) + "\n... (truncated)"
+ : tc.result;
+ content += `\n\`\`\`\n${result}\n\`\`\``;
+ }
+ }
+
+ if (!content && !state.done) {
+ content = "Processing...";
+ }
+
+ return content;
+}
+
+function formatToolArgs(
+ toolName: string,
+ args: Record<string, unknown>
+): string {
+ switch (toolName) {
+ case "read":
+ return `\`${args.path ?? ""}\``;
+ case "write":
+ return `\`${args.path ?? ""}\``;
+ case "edit":
+ return `\`${args.path ?? ""}\``;
+ case "bash":
+ return `\`${args.command ?? ""}\``;
+ default:
+ return JSON.stringify(args);
+ }
+}
+
+// ============================================================================
+// Pi process lifecycle helpers
+// ============================================================================
+
+export interface PiStartConfig {
+ projectDir: string;
+ userToken: string | null;
+}
+
+/**
+ * Validates a project directory path.
+ * Returns null if valid, error string if not.
+ */
+export function validateProjectDir(dir: string): string | null {
+ if (!dir || !dir.trim()) {
+ return "Project directory is required";
+ }
+ // Must be absolute
+ if (!dir.startsWith("/") && !dir.match(/^[A-Z]:\\/)) {
+ return "Project directory must be an absolute path";
+ }
+ return null;
+}
+
+/**
+ * Determines if Pi should start based on current state.
+ * Returns { shouldStart, reason }.
+ */
+export function shouldPiStart(params: {
+ isPi: boolean;
+ open: boolean;
+ needsLogin: boolean;
+ projectDir: string;
+ starting: boolean;
+ running: boolean;
+ generation: number;
+}): { shouldStart: boolean; reason: string } {
+ if (!params.isPi) return { shouldStart: false, reason: "not pi preset" };
+ if (!params.open) return { shouldStart: false, reason: "chat not open" };
+ if (params.needsLogin) return { shouldStart: false, reason: "needs login" };
+ if (!params.projectDir)
+ return { shouldStart: false, reason: "no project dir" };
+ if (params.starting) return { shouldStart: false, reason: "already starting" };
+ if (params.running) return { shouldStart: false, reason: "already running" };
+ return { shouldStart: true, reason: "ready" };
+}
+
+/**
+ * Checks if a pi_terminated event should be ignored
+ * (e.g., it's from a stale process generation).
+ */
+export function shouldIgnoreTermination(
+ eventGeneration: number,
+ currentGeneration: number
+): boolean {
+ return eventGeneration < currentGeneration;
+}
+
+// ============================================================================
+// Default project directory
+// ============================================================================
+
+export function getDefaultProjectDir(): string {
+ // Use user's home directory as a sensible default
+ if (typeof process !== "undefined" && process.env?.HOME) {
+ return `${process.env.HOME}/screenpipe-workspace`;
+ }
+ return "/tmp/screenpipe-pi-chat";
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 9110404fd..5b90e5978 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.0.323"
+version = "2.0.324"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""