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

events(stage 5): migrate last consumers, drop legacy pi_event/pipe_event

Louis Beaumont919de819c721
diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx
index 954c37d53..724d4f842 100644
--- a/apps/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/timeline/ai-panel.tsx
@@ -12,6 +12,10 @@ import { StreamTimeSeriesResponse } from "@/components/rewind/timeline";
import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";
import { Agent } from "./agents";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
+import {
+ mountAgentEventBus,
+ registerDefault as registerAgentDefault,
+} from "@/lib/events/bus";
import {
reducePiEvent,
createInitialState,
@@ -297,14 +301,19 @@ export function AIPanel({
const piMessageStateRef = useRef(createInitialState());
const piStreamingRef = useRef(false);
- // Listen for Pi events to stream responses in ai-panel
+ // Listen for Pi events on the agent_event bus to stream responses
+ // in ai-panel. Filters source==pi + the legacy "chat" sessionId
+ // reserved by this panel's reducer.
useEffect(() => {
- let unlisten: UnlistenFn | null = null;
- const setup = async () => {
- unlisten = await listen<any>("pi_event", (event) => {
+ let off: (() => void) | null = null;
+ let cancelled = false;
+ void mountAgentEventBus().then(() => {
+ if (cancelled) return;
+ off = registerAgentDefault((envelope) => {
if (!piStreamingRef.current) return;
- const { sessionId, event: piEvent } = event.payload;
- if (sessionId !== "chat") return;
+ if (envelope.source !== "pi") return;
+ if (envelope.sessionId !== "chat") return;
+ const piEvent = envelope.event as PiEvent;
const newState = reducePiEvent(piMessageStateRef.current, piEvent);
piMessageStateRef.current = newState;
@@ -321,9 +330,11 @@ export function AIPanel({
setIsStreaming(false);
}
});
+ });
+ return () => {
+ cancelled = true;
+ try { off?.(); } catch { /* ignore */ }
};
- setup();
- return () => { unlisten?.(); };
}, []);
const handleStopStreaming = async () => {
diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
index ff4af3a87..f7357e189 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
@@ -48,6 +48,8 @@ import {
} from "@/components/ui/select";
import { openUrl } from "@tauri-apps/plugin-opener";
import { emit, once, listen, type UnlistenFn } from "@tauri-apps/api/event";
+import { mountAgentEventBus, registerDefault } from "@/lib/events/bus";
+import { parsePipeSessionId } from "@/lib/events/types";
import { ChatPrefillData } from "@/lib/chat-utils";
import { commands } from "@/lib/utils/tauri";
import { cn } from "@/lib/utils";
@@ -1320,24 +1322,34 @@ export function PipesSection() {
};
}, [savePipeContent]);
- // Listen for pipe_event to stream live output for running executions
+ // Listen for pipe events on the unified agent_event bus to stream
+ // live output for running executions. Filters source==pipe and
+ // parses the synthetic sessionId for pipe metadata.
useEffect(() => {
- let unlisten: UnlistenFn | null = null;
let mounted = true;
+ let off: (() => void) | null = null;
- listen<any>("pipe_event", (event) => {
+ void mountAgentEventBus().then(() => {
if (!mounted) return;
- const { pipeName, executionId, event: pipeEvent } = event.payload;
- if (!pipeName || executionId == null) return;
+ off = registerDefault((envelope) => {
+ if (!mounted) return;
+ if (envelope.source !== "pipe") return;
+ const parsed = parsePipeSessionId(envelope.sessionId);
+ if (!parsed) return;
+ const { pipeName, executionId } = parsed;
+ const pipeEvent = envelope.event;
const key = `${pipeName}:${executionId}`;
let text = "";
if (pipeEvent?.type === "raw_line") {
- text = pipeEvent.text || "";
+ text = (pipeEvent as any).text || "";
} else if (pipeEvent) {
- // For structured events (Pi NDJSON), show only meaningful content
+ // For structured events (Pi NDJSON), show only meaningful content.
+ // The `assistantMessageEvent` shape in the agent-event types only
+ // declares the fields stage-1 codified; pipe stdout still carries
+ // some legacy variants (`thinking`, etc) that we read defensively.
if (pipeEvent.type === "message_update" && pipeEvent.assistantMessageEvent) {
- const evt = pipeEvent.assistantMessageEvent;
+ const evt = pipeEvent.assistantMessageEvent as any;
if (evt.type === "text_delta" && evt.delta) {
text = evt.delta;
} else if (evt.type === "thinking" && evt.thinking) {
@@ -1346,7 +1358,7 @@ export function PipesSection() {
text = `\n> running ${evt.toolName}...\n`;
}
} else if (pipeEvent.type === "tool_use") {
- text = `\n> running ${pipeEvent.name || "unknown"}...\n`;
+ text = `\n> running ${(pipeEvent as any).name || "unknown"}...\n`;
}
// Silently skip all other event types (turn_start, turn_end,
// message_start, message_end, tool_execution_start/end/update,
@@ -1360,11 +1372,12 @@ export function PipesSection() {
};
setLiveOutput({ ...liveOutputRef.current });
}
- }).then((fn) => { unlisten = fn; });
+ });
+ });
return () => {
mounted = false;
- unlisten?.();
+ try { off?.(); } catch { /* ignore */ }
};
}, []);
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-pi.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-pi.tsx
index fc84735d7..07a3438f1 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-pi.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-pi.tsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback } from "react";
import { commands, PiInfo, PiCheckResult } from "@/lib/utils/tauri";
import { listen } from "@tauri-apps/api/event";
+import { mountAgentEventBus, onTerminated as onAgentTerminated } from "@/lib/events/bus";
export interface UsePiResult {
info: PiInfo | null;
@@ -107,8 +108,14 @@ export function usePi(): UsePiResult {
setLogs((prev) => [...prev.slice(-99), event.payload]);
});
- const unlistenTerminated = listen<number | null>("pi_terminated", () => {
- refresh();
+ // Termination — bus broadcast (`agent_terminated`). This hook
+ // doesn't filter by sessionId; any pi termination triggers a
+ // status refresh regardless of which session.
+ let offTerminated: (() => void) | null = null;
+ void mountAgentEventBus().then(() => {
+ offTerminated = onAgentTerminated(() => {
+ refresh();
+ });
});
const unlistenError = listen<string>("pi_error", (event) => {
@@ -119,7 +126,7 @@ export function usePi(): UsePiResult {
return () => {
unlistenLog.then((fn) => fn());
unlistenOutput.then((fn) => fn());
- unlistenTerminated.then((fn) => fn());
+ try { offTerminated?.(); } catch { /* ignore */ }
unlistenError.then((fn) => fn());
};
}, [refresh]);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index c67ff9bce..40bc62a3b 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1557,7 +1557,9 @@ async fn main() {
let capture_arc = recording_state.capture.clone();
let is_starting_clone = recording_state.is_starting.clone();
- // Pipe output callback
+ // Pipe output callback. Stage 5: legacy `pipe_event`
+ // topic dropped — every pipe stdout line goes out on
+ // `agent_event` with sessionId `pipe:<name>:<execId>`.
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| {
@@ -1566,16 +1568,6 @@ async fn main() {
} else {
serde_json::json!({ "type": "raw_line", "text": line })
};
- // Legacy envelope — kept until Stage 5 cleanup.
- let legacy = serde_json::json!({
- "pipeName": pipe_name,
- "executionId": exec_id,
- "event": inner,
- });
- let _ = app_for_pipe.emit("pipe_event", &legacy);
- // Unified envelope (Stage 1). `sessionId` follows the
- // `pipe:<name>:<execId>` convention defined in
- // `apps/screenpipe-app-tauri/lib/events/types.ts`.
let unified = serde_json::json!({
"source": "pipe",
"sessionId": format!("pipe:{}:{}", pipe_name, exec_id),
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index e613a823b..67d881227 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1122,13 +1122,8 @@ pub async fn pi_start_inner(
if let Some(mut m) = pool.sessions.remove(&key) {
m.stop();
}
- let _ = app.emit(
- "pi_session_evicted",
- serde_json::json!({ "session": key, "reason": "pool_full" }),
- );
- // Unified envelope (Stage 1 dual-emit): consumers will move to
- // `agent_session_evicted` over the next stages; legacy topic
- // stays for now so nothing breaks during migration.
+ // Stage 5: legacy `pi_session_evicted` topic dropped.
+ // Consumers read from `agent_session_evicted` via the bus.
let _ = app.emit(
"agent_session_evicted",
serde_json::json!({
@@ -1545,13 +1540,10 @@ pub async fn pi_start_inner(
}
}
}
- // Always emit as Tauri event too (frontend may need response events)
- 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);
- }
- // Unified envelope (Stage 1 dual-emit). The shape here
- // is what stages 2+ migrate every consumer onto.
+ // Frontend subscribes via the agent-event bus
+ // (`apps/screenpipe-app-tauri/lib/events/bus.ts`).
+ // Stage 5 cleanup: legacy `pi_event` topic removed
+ // — every consumer now reads from `agent_event`.
let unified = json!({
"source": "pi",
"sessionId": sid_clone,
@@ -1584,11 +1576,8 @@ pub async fn pi_start_inner(
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
- let _ = app_handle.emit(
- "pi_terminated",
- json!({ "sessionId": sid_clone, "pid": pid }),
- );
- // Unified envelope (Stage 1 dual-emit).
+ // Stage 5 cleanup: legacy `pi_terminated` topic removed.
+ // Consumers read from `agent_terminated` via the bus.
let _ = app_handle.emit(
"agent_terminated",
json!({
@@ -1618,10 +1607,8 @@ pub async fn pi_start_inner(
"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);
- }
+ // Stage 5: stderr JSON forwarded on the unified bus
+ // (legacy `pi_event` topic dropped).
let unified = json!({
"source": "pi",
"sessionId": sid_stderr,
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index 6c2a50cdb..c3051242b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -601,7 +601,10 @@ pub async fn spawn_screenpipe(
let server_arc = state.server.clone();
let capture_arc = state.capture.clone();
- // Pipe output callback
+ // Pipe output callback. Stage 5: legacy `pipe_event` topic dropped.
+ // Every pipe stdout line is emitted on the unified `agent_event`
+ // topic with sessionId `pipe:<name>:<execId>` (see the matching
+ // helper in `apps/screenpipe-app-tauri/lib/events/types.ts`).
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| {
@@ -610,16 +613,6 @@ pub async fn spawn_screenpipe(
} else {
serde_json::json!({ "type": "raw_line", "text": line })
};
- // Legacy envelope — kept until Stage 5 cleanup.
- let legacy = serde_json::json!({
- "pipeName": pipe_name,
- "executionId": exec_id,
- "event": inner,
- });
- let _ = app_for_pipe.emit("pipe_event", &legacy);
- // Unified envelope (Stage 1). `sessionId` follows the
- // `pipe:<name>:<execId>` convention defined in
- // `apps/screenpipe-app-tauri/lib/events/types.ts`.
let unified = serde_json::json!({
"source": "pipe",
"sessionId": format!("pipe:{}:{}", pipe_name, exec_id),