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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Pipe execution chat display fixes (#4509)
Harsh Kumar4f58c5122322
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsxindex bcadcc360..0192f67a2 100644--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx@@ -116,6 +116,7 @@ import {applySidebarRecentsCap,buildSidebarRecentsSections,recurringPipeGroupKeys,+ sessionGroupKey,type SidebarItem,validateSidebarGroupName,} from "@/lib/utils/chat-sidebar-grouping";@@ -232,6 +233,15 @@ function useQueueDepths(): Map<string, number> {*/export function ChatSidebar({ className, onViewAll }: ChatSidebarProps) {const currentId = useChatStore((s) => s.currentId);+ // Reactive group key for the current session — re-evaluates when the+ // session appears in the store (handles the race where currentId is set+ // before the session record lands).+ const currentSessionGroupKey = useChatStore((s) => {+ if (!s.currentId) return null;+ const session = s.sessions[s.currentId];+ if (!session || (session.kind === "pipe-watch" && session.isLoading)) return null;+ return sessionGroupKey(session);+ });const diskHydrated = useChatStore((s) => s.diskHydrated);const actions = useChatActions();const queueDepths = useQueueDepths();@@ -506,6 +516,22 @@ export function ChatSidebar({ className, onViewAll }: ChatSidebarProps) {});};+ // Auto-expand the pipe group containing the current session so the+ // highlighted row is visible (e.g. after "open in chat" from Pipes).+ // Uses a reactive store selector so it also fires when the session+ // record lands after currentId was set (race on new conversations).+ // In-memory only — doesn't persist to localStorage since this is a+ // transient convenience, not a user preference.+ useEffect(() => {+ if (!currentSessionGroupKey) return;+ setExpandedGroups((prev) => {+ if (prev.has(currentSessionGroupKey)) return prev;+ const next = new Set(prev);+ next.add(currentSessionGroupKey);+ return next;+ });+ }, [currentSessionGroupKey, setExpandedGroups]);+// GC stale expand-state keys on mount — compare against the full// (pre-cap) recents list so we don't accidentally prune keys for// real groups that are past the 15-row cap.diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pipe-watch-session.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pipe-watch-session.tsindex be89b842b..d0d919c23 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pipe-watch-session.ts+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pipe-watch-session.ts@@ -46,7 +46,7 @@ export function usePipeWatchSession({"@/lib/pipe-ndjson-to-chat");let messagesFromStdout = execution.stdout- ? parsePipeNdjsonToMessages(execution.stdout)+ ? parsePipeNdjsonToMessages(execution.stdout, pipeName): [];if (messagesFromStdout.length === 0) {const fallback =@@ -89,7 +89,7 @@ export function usePipeWatchSession({if (!storeNow.sessions[pipeSid]) {storeNow.actions.upsert({id: pipeSid,- title: pipeName,+ title: `${pipeName} #${executionId}`,preview: "",status: "streaming",messageCount: 0,@@ -106,7 +106,7 @@ export function usePipeWatchSession({const pipeConversation: ChatConversation = {id: pipeSid,- title: pipeName,+ title: `${pipeName} #${executionId}`,messages: [],createdAt: Date.now(),updatedAt: Date.now(),diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsxindex c5412db67..daad46cf8 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx@@ -1071,6 +1071,81 @@ export function MessageContent({</div>) : null;+ // Attachment cards — computed early so the displayContent path below+ // can include them when the message carries docs/images.+ const hasDocs = isUser && (message.attachments?.length ?? 0) > 0;+ const hasImages = isUser && (message.images?.length ?? 0) > 0;+ const attachmentsRow = (hasDocs || hasImages) ? (+ <div className="flex gap-2 flex-wrap items-stretch">+ {hasDocs && message.attachments!.map((doc, i) => {+ const badge = attachmentBadge(doc.ext);+ return (+ <div+ key={`doc-${doc.name}-${i}`}+ title={`${doc.name} — ${doc.charCount.toLocaleString()} chars${doc.truncated ? " (truncated)" : ""}`}+ className="flex items-center gap-2.5 h-20 max-w-[260px] rounded-xl border border-border/50 bg-muted/40 px-3 shadow-sm"+ >+ <div className={`shrink-0 w-11 h-11 rounded-lg flex items-center justify-center text-[10px] font-semibold tracking-tight ${badge.tint}`}>+ {badge.label}+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate text-xs font-medium text-foreground">{doc.name}</div>+ <div className="truncate text-[10px] text-muted-foreground">+ {doc.charCount.toLocaleString()} chars{doc.truncated ? " • truncated" : ""}+ </div>+ </div>+ </div>+ );+ })}+ {hasImages && message.images!.map((img, i) => (+ <button+ key={`img-${i}`}+ type="button"+ onClick={() => onImageClick?.(message.images ?? [], i)}+ className="rounded-xl border border-border/50 shadow-sm overflow-hidden p-0 block text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={img} alt={`Attached ${i + 1}`} className="h-20 w-20 min-h-20 min-w-20 object-cover cursor-pointer" />+ </button>+ ))}+ </div>+ ) : null;++ // User messages with a display label — checked before contentBlocks so+ // pipe messages with both fields render the collapsible label, not raw+ // prompt text. Also handles connection chip messages and doc-attached+ // messages that carry displayContent.+ if (isUser && message.displayContent) {+ const chipMatch = message.displayContent.match(/^\[chip:([^|]+)\|([^\]]+)\] ([\s\S]*)/);+ if (chipMatch) {+ const [, chipId, chipName, chipText] = chipMatch;+ return (+ <div className="space-y-2">+ {attachmentsRow}+ <div className="flex flex-wrap gap-x-1.5 gap-y-0.5">+ <span className="inline-flex h-5 items-center gap-1 shrink-0 align-top">+ <IntegrationIcon+ icon={chipId}+ className="w-4 h-4 flex items-center justify-center overflow-hidden shrink-0"+ fallbackClassName="h-3 w-3 text-muted-foreground"+ />+ <span className="text-sm font-mono font-semibold text-foreground/80 leading-5">{chipName}</span>+ </span>+ <span className="text-sm leading-5 break-words min-w-0">{chipText}</span>+ </div>+ </div>+ );+ }+ return (+ <div className="space-y-2">+ {attachmentsRow}+ {hasDocs+ ? <div className="text-sm font-medium">{message.displayContent}</div>+ : <CollapsibleUserMessage label={message.displayContent} fullContent={message.content} />}+ </div>+ );+ }+// If we have content blocks (Pi messages with tool calls), render them in order// Group consecutive tool blocks into collapsible containersif (message.contentBlocks && message.contentBlocks.length > 0) {@@ -1141,88 +1216,9 @@ export function MessageContent({);}- // Unified attachment row — docs (PDF/DOCX/…) + image thumbnails share- // ONE flex container so the strip reads as a single row regardless of- // attachment mix. The previous design rendered docs and images as two- // sibling <div>s, which produced a fragmented two-row strip whenever- // a user attached one of each kind. Both card types are 80px tall so- // the row baselines line up cleanly.- const hasDocs = isUser && (message.attachments?.length ?? 0) > 0;- const hasImages = isUser && (message.images?.length ?? 0) > 0;- const attachmentsRow = (hasDocs || hasImages) ? (- <div className="flex gap-2 flex-wrap items-stretch">- {hasDocs && message.attachments!.map((doc, i) => {- const badge = attachmentBadge(doc.ext);- return (- <div- key={`doc-${doc.name}-${i}`}- title={`${doc.name} — ${doc.charCount.toLocaleString()} chars${doc.truncated ? " (truncated)" : ""}`}- className="flex items-center gap-2.5 h-20 max-w-[260px] rounded-xl border border-border/50 bg-muted/40 px-3 shadow-sm"- >- <div className={`shrink-0 w-11 h-11 rounded-lg flex items-center justify-center text-[10px] font-semibold tracking-tight ${badge.tint}`}>- {badge.label}- </div>- <div className="min-w-0 flex-1">- <div className="truncate text-xs font-medium text-foreground">{doc.name}</div>- <div className="truncate text-[10px] text-muted-foreground">- {doc.charCount.toLocaleString()} chars{doc.truncated ? " • truncated" : ""}- </div>- </div>- </div>- );- })}- {hasImages && message.images!.map((img, i) => (- <button- key={`img-${i}`}- type="button"- onClick={() => onImageClick?.(message.images ?? [], i)}- className="rounded-xl border border-border/50 shadow-sm overflow-hidden p-0 block text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src={img} alt={`Attached ${i + 1}`} className="h-20 w-20 min-h-20 min-w-20 object-cover cursor-pointer" />- </button>- ))}- </div>- ) : null;-- // Fallback: plain text message (user messages, non-Pi assistant messages)- // For user messages with a display label, show the short label with expand toggle.- //- // When the message has document attachments, the "fullContent" we'd- // expand to contains the raw `<attached file: ...>` payload — that's- // a model-input artifact, not something the user wants to read. The- // attachment cards above already disclose what was attached, so we- // suppress the expansion chevron in that case (label-only bubble).- if (isUser && message.displayContent) {- const chipMatch = message.displayContent.match(/^\[chip:([^|]+)\|([^\]]+)\] ([\s\S]*)/);- if (chipMatch) {- const [, chipId, chipName, chipText] = chipMatch;- return (- <div className="space-y-2">- {attachmentsRow}- <div className="flex flex-wrap gap-x-1.5 gap-y-0.5">- <span className="inline-flex h-5 items-center gap-1 shrink-0 align-top">- <IntegrationIcon- icon={chipId}- className="w-4 h-4 flex items-center justify-center overflow-hidden shrink-0"- fallbackClassName="h-3 w-3 text-muted-foreground"- />- <span className="text-sm font-mono font-semibold text-foreground/80 leading-5">{chipName}</span>- </span>- <span className="text-sm leading-5 break-words min-w-0">{chipText}</span>- </div>- </div>- );- }- return (- <div className="space-y-2">- {attachmentsRow}- {hasDocs- ? <div className="text-sm font-medium">{message.displayContent}</div>- : <CollapsibleUserMessage label={message.displayContent} fullContent={message.content} />}- </div>- );- }+ // Fallback: plain text message (non-Pi assistant messages, or user messages+ // without displayContent — the displayContent case is handled above before+ // the contentBlocks path).// Strip raw "Error:" prefix that leaks from backend — show only the human partconst displayText = !isUser && message.content.startsWith("Error: ")? message.content.slice("Error: ".length)@@ -1267,6 +1263,11 @@ export function attachmentBadge(ext: string): { label: string; tint: string } {function CollapsibleUserMessage({ label, fullContent }: { label: string; fullContent: string }) {const [expanded, setExpanded] = useState(false);+ const prevLabelRef = useRef(label);+ if (prevLabelRef.current !== label) {+ prevLabelRef.current = label;+ setExpanded(false);+ }return (<div><div className="flex items-center gap-1.5">diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/standalone-chat-header.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/standalone-chat-header.tsxindex 79a015ddf..add34837c 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/standalone-chat-header.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/standalone-chat-header.tsx@@ -10,6 +10,7 @@ import { ChatTitleMenu } from "@/components/chat/standalone/chat-title-menu";import { formatShortcutDisplay } from "@/lib/chat-utils";import { cn } from "@/lib/utils";import type { Message } from "@/lib/chat/types";+import { useChatStore } from "@/lib/stores/chat-store";interface StandaloneChatHeaderProps {className?: string;@@ -49,12 +50,18 @@ export function StandaloneChatHeader({startNewConversation,onNewChat,}: StandaloneChatHeaderProps) {+ const hasChatTitle = useChatStore((s) => {+ if (!conversationId) return false;+ const session = s.sessions[conversationId];+ return !!(session?.streamingTitle || session?.title);+ }) || messages.length > 0;+return (<divclassName={cn("relative flex items-center gap-3 px-4 py-3.5 border-b border-border/50 bg-gradient-to-r from-background to-muted/30",!className && "cursor-grab active:cursor-grabbing",- (!className || (conversationId && messages.length > 0)) && "py-0.5",+ (!className || (conversationId && hasChatTitle)) && "py-0.5",sidebarCollapsed && conversationId && messages.length > 0 && "!pl-[58px]",sidebarCollapsed && isMac && !isFullscreen && "!pl-[128px]",!className && isMac && !isFullscreen && "!pl-[78px]"diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.tsindex 2d2e23108..0d005357d 100644--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts@@ -530,8 +530,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {// Opt-out: when the user disables auto title generation (to save tokens),// skip the extra LLM call entirely — chats keep the fallback title.const autoTitleEnabled = settings?.autoGenerateChatTitles !== false;+ // Skip AI titling for pipe executions — their title is always+ // `pipeName #executionId`, set by the recorder / watch session.+ // Only allow AI titles when the user manually renames (titleSource+ // would be "user" at that point, so this gate is a no-op for renames).+ const isPipeChat = existing?.kind === "pipe-run" || existing?.kind === "pipe-watch";if (autoTitleEnabled &&+ !isPipeChat &&titleSource === "fallback" &&rawContent &&hasValidPreset &&diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsxindex 1728cc8c1..3e67aaac4 100644--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx@@ -111,7 +111,8 @@ import { useToast } from "@/components/ui/use-toast";import { useQueryState } from "nuqs";import { HelpTooltip } from "@/components/ui/help-tooltip";import { pipeExecutionToConversation } from "@/lib/pipe-ndjson-to-chat";-import { saveConversationFile } from "@/lib/chat-storage";+import { loadConversationFile, saveConversationFile } from "@/lib/chat-storage";+import { pipeSessionId } from "@/lib/events/types";import { PublishDialog } from "@/components/pipe-store";import {Dialog,@@ -987,6 +988,7 @@ export function PipesSection() {// Favorites — per-machine preference persisted via /pipes/favorites.// `showOnly` toggles a filter that hides non-starred pipes.const pipeFavorites = usePipeFavorites();+ const [copiedExecId, setCopiedExecId] = useState<number | null>(null);const [availableConnections, setAvailableConnections] = useState<AvailableConnection[]>([]);const [connectionModal, setConnectionModal] = useState<{ pipeName: string; connections: string[] } | null>(null);const [availableUpdates, setAvailableUpdates] = useState<Record<string, { latest_version: number; installed_version: number; locally_modified: boolean }>>({});@@ -2724,16 +2726,26 @@ export function PipesSection() {{exec.model && <span className="text-muted-foreground/60 truncate max-w-[100px]">{exec.model}</span>}{exec.status === "completed" && exec.stdout && cleanPipeStdout(exec.stdout) && (<div className="ml-auto flex items-center gap-1">- <button className="text-muted-foreground hover:text-foreground p-0.5" title="copy" onClick={() => commands.copyTextToClipboard(cleanPipeStdout(exec.stdout))}>- <Copy className="w-3.5 h-3.5" />+ <button className="text-muted-foreground hover:text-foreground p-0.5" title="copy" onClick={() => {+ commands.copyTextToClipboard(cleanPipeStdout(exec.stdout));+ setCopiedExecId(exec.id);+ setTimeout(() => setCopiedExecId((prev) => prev === exec.id ? null : prev), 1500);+ }}>+ {copiedExecId === exec.id ? <Check className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}</button><button className="text-muted-foreground hover:text-foreground p-0.5" title="open in chat" onClick={async () => {- const conv = pipeExecutionToConversation(exec.pipe_name, exec.id, exec.stdout, exec.started_at);- await saveConversationFile(conv);- localStorage.setItem("pending-chat-conversation", conv.id);- const url = new URL(window.location.href);- url.searchParams.set("section", "home");- window.location.href = url.toString();+ // Check if the recorder already saved this execution+ const recorderSid = pipeSessionId(exec.pipe_name, exec.id);+ const existing = await loadConversationFile(recorderSid);+ if (!existing) {+ const conv = pipeExecutionToConversation(exec.pipe_name, exec.id, exec.stdout, exec.started_at);+ conv.id = recorderSid;+ conv.kind = "pipe-run";+ conv.titleSource = "user";+ conv.pipeContext = { pipeName: exec.pipe_name, executionId: exec.id, startedAt: exec.started_at || new Date().toISOString() };+ await saveConversationFile(conv);+ }+ await emit("chat-load-conversation", { conversationId: recorderSid });}}><MessageSquare className="w-3.5 h-3.5" /></button>@@ -2778,10 +2790,14 @@ export function PipesSection() {<div className="relative group"><buttonclassName="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-muted"- onClick={() => commands.copyTextToClipboard(cleanPipeStdout(log.stdout))}+ onClick={() => {+ commands.copyTextToClipboard(cleanPipeStdout(log.stdout));+ setCopiedExecId(-(i + 1));+ setTimeout(() => setCopiedExecId((prev) => prev === -(i + 1) ? null : prev), 1500);+ }}title="copy">- <Copy className="h-3 w-3 text-muted-foreground" />+ {copiedExecId === -(i + 1) ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3 text-muted-foreground" />}</button><div className="text-xs text-muted-foreground max-h-96 overflow-y-auto scrollbar-hide"><MemoizedReactMarkdown className="prose prose-xs dark:prose-invert max-w-none break-words text-xs [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_h1]:text-sm [&_h2]:text-xs [&_h3]:text-xs [&_p]:text-xs [&_li]:text-xs [&_code]:text-[10px]">{cleanPipeStdout(log.stdout)}</MemoizedReactMarkdown></div></div>diff --git a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.tsindex 61a7747aa..de16ad418 100644--- a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts+++ b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-run-recorder.test.ts@@ -115,7 +115,7 @@ describe("pipe-run-recorder: finalize on terminal event", () => {expect(saveSpy).not.toHaveBeenCalled();});- it("treats turn_end as a terminal event", async () => {+ it("does not finalize on turn_end (only agent_end / pipe_done)", async () => {await __testing.inject(env({ type: "message_start", message: { role: "assistant" } }));await __testing.inject(env({@@ -124,7 +124,10 @@ describe("pipe-run-recorder: finalize on terminal event", () => {}),);await __testing.inject(env({ type: "turn_end" }));- expect(saveSpy).toHaveBeenCalledTimes(1);+ // turn_end fires between LLM turns in multi-turn pipes — finalizing+ // here would drop the user message from subsequent saves.+ expect(saveSpy).not.toHaveBeenCalled();+ expect(__testing.peek(SID)).toBeDefined();});it("treats pipe_done as a terminal event", async () => {diff --git a/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts b/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.tsindex 98bdc9028..33d8d5b2a 100644--- a/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts+++ b/apps/screenpipe-app-tauri/lib/events/pipe-run-recorder.ts@@ -69,7 +69,6 @@ let unregister: Unregister | null = null;const TERMINAL_EVENT_TYPES = new Set(["agent_end",- "turn_end","pipe_done",]);@@ -191,7 +190,7 @@ async function finalizeBuffer(sid: string, buf: PipeRunBuffer): Promise<void> {}const ndjson = buf.lines.join("\n");- const messages: ChatMessage[] = parsePipeNdjsonToMessages(ndjson);+ const messages: ChatMessage[] = parsePipeNdjsonToMessages(ndjson, buf.pipeName);// Skip empty conversations — pipes that emitted no parseable// assistant content (e.g. raw_line-only streams that the parser@@ -205,6 +204,7 @@ async function finalizeBuffer(sid: string, buf: PipeRunBuffer): Promise<void> {const conv: ChatConversation = {id: sid,title: `${buf.pipeName} #${buf.executionId}`,+ titleSource: "user",messages,createdAt: buf.firstEventAt,updatedAt: buf.lastEventAt,diff --git a/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts b/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.tsindex dec99e8c0..3aadb3fbc 100644--- a/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts+++ b/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts@@ -43,6 +43,11 @@ let mounted = false;let mountPromise: Promise<() => void> | null = null;let unregister: Unregister | null = null;+/** Per-session user prompt captured from streaming events. Used as a+ * fallback when agent_end.messages omits the user message (common for+ * single-turn, no-tool-use pipes). */+const streamingUserPrompts = new Map<string, string>();+export async function mountPipeWatchWriter(): Promise<() => void> {if (mounted) return unmountPipeWatchWriter;if (mountPromise) return mountPromise;@@ -62,6 +67,7 @@ function unmountPipeWatchWriter(): void {// ignore — tearing down}unregister = null;+ streamingUserPrompts.clear();mounted = false;mountPromise = null;}@@ -124,6 +130,19 @@ function apply(sid: string, payload: AgentInnerEvent): void {return;}+ // ── capture user prompt from streaming events ──────────────────────+ // The Pi agent emits message_start/message_end with role "user" for the+ // prompt. We stash it so we can inject it when agent_end.messages+ // omits the user message (single-turn, no-tool-use pipes).+ if (+ (t === "message_start" || t === "message_end") &&+ (payload as any).message?.role === "user"+ ) {+ const text = extractText((payload as any).message?.content);+ if (text.trim()) streamingUserPrompts.set(sid, text.trim());+ return;+ }+// ── text_delta (flat) and message_update wrapping text_delta ────────const isTextDelta =(t === "text_delta" ||@@ -320,7 +339,26 @@ function apply(sid: string, payload: AgentInnerEvent): void {if (t === "agent_end" || t === "pipe_done") {const messages = (payload as any).messages;if (Array.isArray(messages) && messages.length > 0) {- const reconstructed = reconstructFromAgentEnd(messages);+ const sessionPipeName = useChatStore.getState().sessions[sid]?.pipeContext?.pipeName || "pipe";+ const reconstructed = reconstructFromAgentEnd(messages, sessionPipeName);++ // If agent_end.messages didn't include the user prompt (common+ // for single-turn pipes), inject it from the streaming events we+ // captured earlier.+ if (!reconstructed.some((m: any) => m.role === "user")) {+ const cachedPrompt = streamingUserPrompts.get(sid);+ if (cachedPrompt) {+ const label = pipePromptLabel(sessionPipeName, cachedPrompt);+ reconstructed.unshift({+ id: `pipe-user-${Date.now()}`,+ role: "user",+ content: cachedPrompt,+ timestamp: Date.now(),+ displayContent: label,+ });+ }+ }+const notificationMarkers = ((useChatStore.getState().sessions[sid]?.messages as any[]) ?? []).filter(isNotificationMessage);const merged = appendUniqueNotificationMessages(reconstructed, notificationMarkers);@@ -328,6 +366,8 @@ function apply(sid: string, payload: AgentInnerEvent): void {store.actions.setMessages(sid, merged as any);}}+ // Clean up the cached prompt — this session is done.+ streamingUserPrompts.delete(sid);store.actions.endTurn(sid);return;}@@ -378,7 +418,7 @@ function appendUniqueNotificationMessages(messages: any[], notifications: any[])** Mirrors the logic in `parsePipeNdjsonToMessages` so live and* post-hoc views render the same shape. */-function reconstructFromAgentEnd(agentMessages: any[]): any[] {+function reconstructFromAgentEnd(agentMessages: any[], pipeName: string): any[] {const out: any[] = [];for (let i = 0; i < agentMessages.length; i++) {const m = agentMessages[i];@@ -403,17 +443,36 @@ function reconstructFromAgentEnd(agentMessages: any[]): any[] {// Skip empty-and-blockless messages — usually pipe scaffolding.if (!text.trim() && blocks.length === 0) continue;+ // Every user message in a pipe session is the system-injected+ // prompt. Show a clean label; full prompt available via dropdown.+ const displayContent = m.role === "user"+ ? pipePromptLabel(pipeName, text)+ : undefined;+out.push({id: typeof m.id === "string" ? m.id : `pipe-agent-${i}`,role: m.role,content: text,timestamp: Date.now(),+ ...(displayContent ? { displayContent } : {}),...(blocks.length ? { contentBlocks: blocks } : {}),});}return out;}+/** Build a clean display label for pipe prompt user messages. */+function pipePromptLabel(pipeName: string, text: string): string {+ const match = text.match(/Time range: (\S+) to (\S+)/);+ if (match) {+ const start = new Date(match[1]);+ const end = new Date(match[2]);+ const fmt = (d: Date) => d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+ return `pipe executed: ${pipeName} (${fmt(start)} – ${fmt(end)})`;+ }+ return `pipe executed: ${pipeName}`;+}+function extractText(content: any): string {if (typeof content === "string") return content;if (!Array.isArray(content)) return "";diff --git a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.tsindex a03cfe7da..a7f56e0ca 100644--- a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts+++ b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts@@ -49,12 +49,29 @@ function extractToolCalls(content: any[], msgIndex: number): any[] {* calls into one "Worked for X min" rail instead of stacking a tower of* single-tool headers.*/-export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {+/** Build a clean display label for pipe prompt user messages. */+function pipePromptLabel(pipeName: string, text: string): string {+ const match = text.match(/Time range: (\S+) to (\S+)/);+ if (match) {+ const start = new Date(match[1]);+ const end = new Date(match[2]);+ const fmt = (d: Date) => d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+ return `pipe executed: ${pipeName} (${fmt(start)} – ${fmt(end)})`;+ }+ return `pipe executed: ${pipeName}`;+}++export function parsePipeNdjsonToMessages(raw: string, pipeName?: string): ChatMessage[] {let agentEndMessages: any[] | null = null;const notificationMessages: ChatMessage[] = [];let messageCounter = 0;const ts = Date.now();+ // User prompt captured from streaming events — used as a fallback when+ // agent_end.messages omits the user message (common for single-turn,+ // no-tool-use pipes).+ let streamingUserPrompt: string | null = null;+// First pass: find agent_end event (has the complete conversation)for (const line of raw.split("\n")) {const trimmed = line.trim();@@ -67,6 +84,15 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {if (evt.type === "notification_sent") {notificationMessages.push(notificationEventToMessage(evt, notificationMessages.length, ts));}+ // Capture user prompt from streaming events as fallback+ if (+ !streamingUserPrompt &&+ (evt.type === "message_start" || evt.type === "message_end") &&+ evt.message?.role === "user"+ ) {+ const text = extractText(evt.message.content);+ if (text.trim()) streamingUserPrompt = text.trim();+ }} catch {continue;}@@ -126,27 +152,21 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {continue;}+ // Every user message in pipe NDJSON is the system-injected prompt.+ // Show a clean label; the full prompt is available via the+ // CollapsibleUserMessage dropdown.if (role === "user") {flushPendingAssistant();if (!text.trim()) continue;- const isPipePrompt = text.includes("Time range:") && text.includes("Execute the pipe now.");+ const name = pipeName || "pipe";+ const label = pipePromptLabel(name, text);const chatMsg: any = {id: `pipe-msg-${messageCounter++}`,role: "user",content: text.trim(),timestamp: ts,+ displayContent: label,};- if (isPipePrompt) {- const match = text.match(/Time range: (\S+) to (\S+)/);- if (match) {- const start = new Date(match[1]);- const end = new Date(match[2]);- const fmt = (d: Date) => d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });- chatMsg.displayContent = `pipe executed (${fmt(start)} – ${fmt(end)})`;- } else {- chatMsg.displayContent = "pipe executed";- }- }messages.push(chatMsg);continue;}@@ -187,6 +207,21 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {flushPendingAssistant();+ // If agent_end.messages didn't include the user prompt (common for+ // single-turn pipes without tool use), inject it from the streaming+ // events we captured during the first pass.+ if (!messages.some((m) => m.role === "user") && streamingUserPrompt) {+ const name = pipeName || "pipe";+ const label = pipePromptLabel(name, streamingUserPrompt);+ messages.unshift({+ id: `pipe-msg-${messageCounter++}`,+ role: "user",+ content: streamingUserPrompt,+ timestamp: ts,+ displayContent: label,+ } as any);+ }+if (messages.some((m) => m.role === "assistant" && (m.content?.trim() || (m.contentBlocks?.length ?? 0) > 0))) {return appendUniqueNotificationMessages(messages, notificationMessages);}@@ -270,19 +305,14 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {flushAssistant();const text = extractText(evt.message.content);if (text.trim()) {- const isPipePrompt = text.includes("Time range:") && text.includes("Execute the pipe now.");- const msg: any = { id: `pipe-msg-${messageCounter++}`, role: "user", content: text.trim(), timestamp: ts };- if (isPipePrompt) {- const match = text.match(/Time range: (\S+) to (\S+)/);- if (match) {- const start = new Date(match[1]);- const end = new Date(match[2]);- const fmt = (d: Date) => d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });- msg.displayContent = `pipe executed (${fmt(start)} – ${fmt(end)})`;- } else {- msg.displayContent = "pipe executed";- }- }+ const name = pipeName || "pipe";+ const msg: any = {+ id: `pipe-msg-${messageCounter++}`,+ role: "user",+ content: text.trim(),+ timestamp: ts,+ displayContent: pipePromptLabel(name, text),+ };messages.push(msg);}continue;@@ -437,7 +467,7 @@ export function pipeExecutionToConversation(stdout: string,startedAt: string | null,): ChatConversation {- const messages = parsePipeNdjsonToMessages(stdout);+ const messages = parsePipeNdjsonToMessages(stdout, pipeName);const ts = startedAt ? new Date(startedAt).getTime() : Date.now();return {