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
fix(chat): collapse source-citation noise in pipe-run transcripts
Louis Beaumontf6c2bc91c531
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex bff348ce7..1a290f2f8 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -71,6 +71,7 @@ import { usePipes } from "@/lib/hooks/use-pipes";import { localFetch, getApiBaseUrl } from "@/lib/api";import { CONNECTIONS_UPDATED_EVENT } from "@/lib/connections-events";import {+ aggregateSourceCitations,formatSourceCitationsMarkdown,sourceCitationsFromMessage,type SourceCitation,@@ -7608,6 +7609,17 @@ export function StandaloneChat({? piMessageIdRef.current ?? currentStreamingMessageId ?? null: null;+ // Pipe sessions (pipe-run, pipe-watch) are one agentic loop, not a back-and-+ // forth conversation. Per-message footers spam the same file across every+ // step. Defer every message's footer and render a single aggregated footer+ // at the bottom of the transcript instead.+ const isPipeSessionChat =+ currentSessionKind === "pipe-run" || currentSessionKind === "pipe-watch";+ const aggregatedPipeCitations = React.useMemo(+ () => (isPipeSessionChat ? aggregateSourceCitations(messages) : []),+ [isPipeSessionChat, messages],+ );+return (<div className={cn("flex flex-col bg-background", className ?? "h-screen")} data-testid="section-home">{/* Header - draggable only in standalone mode */}@@ -8138,7 +8150,9 @@ export function StandaloneChat({) : (<MessageContentmessage={message}- deferSourceFooter={message.id === activeSourceFooterMessageId}+ deferSourceFooter={+ isPipeSessionChat || message.id === activeSourceFooterMessageId+ }onImageClick={(images, index) => setImageViewer({ images, index })}onRetry={(prompt) => sendMessage(prompt)}/>@@ -8264,6 +8278,11 @@ export function StandaloneChat({});})()}</AnimatePresence>+ {isPipeSessionChat && aggregatedPipeCitations.length > 0 && (+ <div className="mt-2 w-full">+ <SourceCitationFooter citations={aggregatedPipeCitations} />+ </div>+ )}<AnimatePresence>{isLoading && (() => {// Derive loader phase from the last assistant message's content blocksdiff --git a/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.tsindex 5ffedc357..14031d5dd 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts@@ -4,6 +4,7 @@import { describe, expect, it } from "vitest";import {+ aggregateSourceCitations,formatSourceCitationsMarkdown,sourceCitationsFromMessage,} from "../source-citations";@@ -335,6 +336,84 @@ describe("source citations", () => {expect(citations).toEqual([]);});+ it("does not leak file paths from heredoc script bodies", () => {+ // Common pipe pattern: write a script via heredoc then run it. Without+ // stripping the heredoc body, every quoted "/Users/..." string literal+ // and `process.platform`-style token inside the embedded source gets+ // tokenized as a path and pollutes the footer.+ const citations = sourceCitationsFromMessage({+ contentBlocks: [+ {+ type: "tool",+ toolCall: {+ toolName: "bash",+ args: {+ command:+ "cat > /tmp/sync.ts << 'SCRIPT_EOF'\n" ++ 'const IMESSAGE_DB = "/Users/me/Library/Messages/chat.db";\n' ++ 'const HINT = ".clawdbot/credentials/telegram-pairing.json";\n' ++ 'if (process.platform !== "darwin") return null;\n' ++ "SCRIPT_EOF\n" ++ "bun run /tmp/sync.ts",+ },+ result: "Done\n",+ isRunning: false,+ },+ },+ ],+ });++ const titles = citations.map((c) => c.title);+ expect(titles).toContain("Local file: sync.ts");+ expect(titles).not.toContain("Local file: chat.db");+ expect(titles).not.toContain("Local file: telegram-pairing.json");+ expect(titles).not.toContain("Local file: null");+ expect(titles).not.toContain("Local file: undefined");+ });++ it("aggregates citations across pipe-run messages and dedupes repeats", () => {+ // Real pipe-run pattern from chat-memory-sync_2341.json: the agent reads+ // the same state file across multiple debug steps. Per-message footers+ // would render N "Read: state.json" rows; the aggregator emits one.+ const readState = {+ contentBlocks: [+ {+ type: "tool",+ toolCall: {+ toolName: "read",+ args: { path: "/Users/me/.screenpipe/pipes/sync/state.json" },+ result: "{}",+ isRunning: false,+ },+ },+ ],+ };+ const writeScript = {+ contentBlocks: [+ {+ type: "tool",+ toolCall: {+ toolName: "write",+ args: { path: "/tmp/sync.ts" },+ result: "ok",+ isRunning: false,+ },+ },+ ],+ };++ const aggregated = aggregateSourceCitations([+ readState,+ writeScript,+ readState, // repeated step in the agentic loop+ ]);++ expect(aggregated.map((c) => c.title)).toEqual([+ "Read: state.json",+ "Wrote: sync.ts",+ ]);+ });+it("formats citations for chat markdown exports", () => {const markdown = formatSourceCitationsMarkdown([{diff --git a/apps/screenpipe-app-tauri/lib/source-citations.ts b/apps/screenpipe-app-tauri/lib/source-citations.tsindex 6d8509a22..a6f5c771f 100644--- a/apps/screenpipe-app-tauri/lib/source-citations.ts+++ b/apps/screenpipe-app-tauri/lib/source-citations.ts@@ -42,6 +42,17 @@ export function sourceCitationsFromMessage(message: MessageLike): SourceCitationreturn sourceCitationsFromContentBlocks(message.contentBlocks);}+// Aggregate citations across a sequence of messages, deduped. Used for+// pipe-run chats where the whole transcript is one agentic loop and showing+// per-message footers spams the same file across every step.+export function aggregateSourceCitations(messages: readonly MessageLike[]): SourceCitation[] {+ const all: SourceCitation[] = [];+ for (const message of messages) {+ all.push(...sourceCitationsFromMessage(message));+ }+ return dedupeCitations(all);+}+export function sourceCitationsFromContentBlocks(contentBlocks: unknown): SourceCitation[] {if (!Array.isArray(contentBlocks)) return [];@@ -308,6 +319,17 @@ function fileCitation(path: string, verb: string): SourceCitation {};}+// Tokens that look path-like by accident (basename of a bare word, JS keywords+// leaking out of heredocs) but aren't real files. Guards against rendering+// "Local file: null" / "Local file: undefined" footers.+function isUsablePath(path: string): boolean {+ const trimmed = path.trim();+ if (!trimmed) return false;+ const base = basename(trimmed);+ if (!base) return false;+ return base !== "null" && base !== "undefined" && base !== "true" && base !== "false";+}+function fileKind(path: string): SourceCitationKind {if (path.includes("/.codex/memories/") || /(^|\/)MEMORY\.md$/.test(path)) {return "memory";@@ -430,8 +452,9 @@ function dedupeLinks(links: Array<{ title?: string; url: string }>): Array<{ titfunction extractFilePathsFromCommand(command: string): string[] {const paths = new Set<string>();+ const stripped = stripHeredocs(command);const readCommand = /\b(cat|less|more|head|tail|sed|awk|jq|wc|stat)\b([^|;&`]*)/g;- for (const match of command.matchAll(readCommand)) {+ for (const match of stripped.matchAll(readCommand)) {const tool = match[1] ?? "";const tokens = shellWords(match[2] ?? "");let sawOperand = false;@@ -444,12 +467,43 @@ function extractFilePathsFromCommand(command: string): string[] {}sawOperand = true;- if (isPathLike(token)) paths.add(token);+ if (isPathLike(token) && isUsablePath(token)) paths.add(token);}}return Array.from(paths).slice(0, 4);}+// Remove heredoc bodies (`<< 'EOF' ... EOF`, `<<EOF ... EOF`, etc.) so the+// embedded program source isn't tokenized as filesystem paths. Common pattern:+// `cat > /tmp/x.ts << 'SCRIPT_EOF'\n...JS source...\nSCRIPT_EOF\nbun run /tmp/x.ts`+// — without this, every quoted string literal inside the JS that contains a+// "/" or ".ext" leaks into the source citation footer.+function stripHeredocs(command: string): string {+ const heredocStart = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/g;+ let result = "";+ let cursor = 0;+ let match: RegExpExecArray | null;+ while ((match = heredocStart.exec(command)) !== null) {+ const startIdx = match.index;+ const tag = match[2];+ if (!tag) continue;+ const afterTag = heredocStart.lastIndex;+ // Find the line where the body begins (skip to the end of the start line).+ const bodyStart = command.indexOf("\n", afterTag);+ if (bodyStart === -1) break;+ const closeRegex = new RegExp(`\\n\\s*${tag}\\s*(?:\\n|$)`);+ const tail = command.slice(bodyStart);+ const closeMatch = closeRegex.exec(tail);+ if (!closeMatch) break;+ const endIdx = bodyStart + closeMatch.index + closeMatch[0].length;+ result += command.slice(cursor, startIdx);+ cursor = endIdx;+ heredocStart.lastIndex = endIdx;+ }+ result += command.slice(cursor);+ return result;+}+function shellWords(value: string): string[] {const words: string[] = [];const tokenPattern = /"([^"]*)"|'([^']*)'|([^\s]+)/g;