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

fix(chat): generalize source-citation aggregation to any agentic loop

Louis Beaumont7a75e83b63c3
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 1a290f2f8..ae506a35b 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -71,7 +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,
+ computeChatCitationPlan,
formatSourceCitationsMarkdown,
sourceCitationsFromMessage,
type SourceCitation,
@@ -7287,9 +7287,24 @@ export function StandaloneChat({
}
if (m.role === "assistant") {
- const citationsMarkdown = formatSourceCitationsMarkdown(sourceCitationsFromMessage(m));
- if (citationsMarkdown) {
- body = body ? `${body}\n\n${citationsMarkdown}` : citationsMarkdown;
+ // Mirror the in-app aggregation: if this message's per-message footer
+ // was folded into a turn-level aggregate, skip its Sources block here
+ // so we don't repeat the same files across every step of an agentic
+ // loop. The aggregated Sources block is appended after the last
+ // assistant of the turn instead.
+ const isDeferred = citationPlan.deferredMessageIds.has(m.id);
+ const turnAggregate = citationPlan.aggregatedAfter.get(m.id);
+ if (!isDeferred) {
+ const citationsMarkdown = formatSourceCitationsMarkdown(sourceCitationsFromMessage(m));
+ if (citationsMarkdown) {
+ body = body ? `${body}\n\n${citationsMarkdown}` : citationsMarkdown;
+ }
+ }
+ if (turnAggregate && turnAggregate.length > 0) {
+ const aggregateMarkdown = formatSourceCitationsMarkdown(turnAggregate);
+ if (aggregateMarkdown) {
+ body = body ? `${body}\n\n${aggregateMarkdown}` : aggregateMarkdown;
+ }
}
}
@@ -7609,14 +7624,18 @@ 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.
+ // Per-turn aggregation plan. Pipe sessions (pipe-run, pipe-watch) and any
+ // chat with an agentic loop (≥2 assistant messages with citations between
+ // user turns) fold their per-message footers into one aggregated footer
+ // rendered after the last assistant of the turn. Single-step turns keep
+ // their per-message footer untouched.
const isPipeSessionChat =
currentSessionKind === "pipe-run" || currentSessionKind === "pipe-watch";
- const aggregatedPipeCitations = React.useMemo(
- () => (isPipeSessionChat ? aggregateSourceCitations(messages) : []),
+ const citationPlan = React.useMemo(
+ () =>
+ computeChatCitationPlan(messages, {
+ forceAggregate: isPipeSessionChat,
+ }),
[isPipeSessionChat, messages],
);
@@ -8013,7 +8032,8 @@ export function StandaloneChat({
!message.content &&
!message.contentBlocks?.length
);
- return (
+ const turnAggregatedCitations = citationPlan.aggregatedAfter.get(message.id);
+ return [
<motion.div
key={message.id}
initial={{ opacity: 0, y: 10 }}
@@ -8151,7 +8171,8 @@ export function StandaloneChat({
<MessageContent
message={message}
deferSourceFooter={
- isPipeSessionChat || message.id === activeSourceFooterMessageId
+ citationPlan.deferredMessageIds.has(message.id) ||
+ message.id === activeSourceFooterMessageId
}
onImageClick={(images, index) => setImageViewer({ images, index })}
onRetry={(prompt) => sendMessage(prompt)}
@@ -8273,16 +8294,24 @@ export function StandaloneChat({
</>
) : null}
</div>
- </motion.div>
- );
+ </motion.div>,
+ turnAggregatedCitations && turnAggregatedCitations.length > 0 ? (
+ <motion.div
+ key={`turn-sources-${message.id}`}
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -4 }}
+ transition={{ duration: 0.15 }}
+ className="w-full"
+ data-testid="chat-turn-sources"
+ >
+ <SourceCitationFooter citations={turnAggregatedCitations} />
+ </motion.div>
+ ) : null,
+ ];
});
})()}
</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 blocks
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts
index 14031d5dd..ff12a7362 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts
@@ -5,6 +5,7 @@
import { describe, expect, it } from "vitest";
import {
aggregateSourceCitations,
+ computeChatCitationPlan,
formatSourceCitationsMarkdown,
sourceCitationsFromMessage,
} from "../source-citations";
@@ -414,6 +415,90 @@ describe("source citations", () => {
]);
});
+ describe("computeChatCitationPlan", () => {
+ const readMsg = (id: string, path: string) => ({
+ id,
+ role: "assistant" as const,
+ contentBlocks: [
+ {
+ type: "tool",
+ toolCall: {
+ toolName: "read",
+ args: { path },
+ result: "ok",
+ isRunning: false,
+ },
+ },
+ ],
+ });
+ const userMsg = (id: string) => ({ id, role: "user" as const, contentBlocks: [] });
+
+ it("leaves single-tool turns alone", () => {
+ const plan = computeChatCitationPlan([
+ userMsg("u1"),
+ readMsg("a1", "/tmp/x.ts"),
+ ]);
+ expect(plan.deferredMessageIds.size).toBe(0);
+ expect(plan.aggregatedAfter.size).toBe(0);
+ });
+
+ it("aggregates an agentic loop turn (≥2 citation-bearing assistants)", () => {
+ const plan = computeChatCitationPlan([
+ userMsg("u1"),
+ readMsg("a1", "/tmp/state.json"),
+ readMsg("a2", "/tmp/state.json"),
+ readMsg("a3", "/tmp/script.ts"),
+ ]);
+ expect([...plan.deferredMessageIds]).toEqual(["a1", "a2", "a3"]);
+ expect(plan.aggregatedAfter.has("a3")).toBe(true);
+ expect(plan.aggregatedAfter.get("a3")?.map((c) => c.title)).toEqual([
+ "Read: state.json",
+ "Read: script.ts",
+ ]);
+ });
+
+ it("scopes aggregation per turn so separate user questions stay separate", () => {
+ const plan = computeChatCitationPlan([
+ userMsg("u1"),
+ readMsg("a1", "/tmp/a.ts"),
+ readMsg("a2", "/tmp/a.ts"),
+ userMsg("u2"),
+ readMsg("b1", "/tmp/b.ts"),
+ readMsg("b2", "/tmp/b.ts"),
+ ]);
+ expect(plan.aggregatedAfter.has("a2")).toBe(true);
+ expect(plan.aggregatedAfter.has("b2")).toBe(true);
+ expect(plan.aggregatedAfter.get("a2")?.map((c) => c.title)).toEqual(["Read: a.ts"]);
+ expect(plan.aggregatedAfter.get("b2")?.map((c) => c.title)).toEqual(["Read: b.ts"]);
+ });
+
+ it("forceAggregate folds even single-step turns (pipe sessions)", () => {
+ const plan = computeChatCitationPlan(
+ [userMsg("u1"), readMsg("a1", "/tmp/once.ts")],
+ { forceAggregate: true },
+ );
+ expect(plan.deferredMessageIds.has("a1")).toBe(true);
+ expect(plan.aggregatedAfter.get("a1")?.map((c) => c.title)).toEqual([
+ "Read: once.ts",
+ ]);
+ });
+
+ it("ignores assistant messages without citations when deciding to aggregate", () => {
+ const plain = {
+ id: "a1",
+ role: "assistant" as const,
+ contentBlocks: [{ type: "text", text: "hi" }],
+ };
+ const plan = computeChatCitationPlan([
+ userMsg("u1"),
+ plain,
+ readMsg("a2", "/tmp/x.ts"),
+ ]);
+ // Only one citation-bearing assistant — below the default threshold.
+ expect(plan.aggregatedAfter.size).toBe(0);
+ });
+ });
+
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.ts
index a6f5c771f..92bc878eb 100644
--- a/apps/screenpipe-app-tauri/lib/source-citations.ts
+++ b/apps/screenpipe-app-tauri/lib/source-citations.ts
@@ -53,6 +53,73 @@ export function aggregateSourceCitations(messages: readonly MessageLike[]): Sour
return dedupeCitations(all);
}
+export interface ChatCitationPlan {
+ // Messages whose own per-message footer should be hidden because their
+ // citations have been folded into a turn-level aggregate below.
+ deferredMessageIds: Set<string>;
+ // After this message renders, render an aggregated footer with these
+ // citations. Keyed by message id (the last assistant of the turn group).
+ aggregatedAfter: Map<string, SourceCitation[]>;
+}
+
+interface PlanMessageLike extends MessageLike {
+ id?: unknown;
+ role?: unknown;
+}
+
+interface ChatCitationPlanOptions {
+ // Always aggregate even if a turn has only one citation-bearing assistant
+ // message. Used for pipe sessions where the visual treatment should be
+ // consistent across every transcript.
+ forceAggregate?: boolean;
+ // Aggregate when a turn group has ≥ this many assistant messages bearing
+ // citations. Defaults to 2 — leaves single-tool-call turns alone.
+ minAssistantsForAggregation?: number;
+}
+
+// Walk a message list and produce an aggregation plan. A "turn" is one user
+// message plus the assistant messages that follow until the next user
+// message (or end of chat). Within each turn, if multiple assistant messages
+// carry citations, fold them into a single footer rendered after the last
+// assistant of that turn — that's the agentic-loop pattern (Pi looping
+// debug→fix→re-run, pipe-runs, multi-step research).
+export function computeChatCitationPlan(
+ messages: readonly PlanMessageLike[],
+ options: ChatCitationPlanOptions = {},
+): ChatCitationPlan {
+ const minAssistants = options.minAssistantsForAggregation ?? 2;
+ const force = options.forceAggregate ?? false;
+ const deferredMessageIds = new Set<string>();
+ const aggregatedAfter = new Map<string, SourceCitation[]>();
+
+ let turn: PlanMessageLike[] = [];
+ const flush = () => {
+ if (turn.length === 0) return;
+ const assistantsWithCitations = turn.filter(
+ (m) => m.role === "assistant" && sourceCitationsFromMessage(m).length > 0,
+ );
+ const lastAssistant = [...turn].reverse().find((m) => m.role === "assistant");
+ const shouldAggregate = force
+ ? assistantsWithCitations.length >= 1
+ : assistantsWithCitations.length >= minAssistants;
+ if (shouldAggregate && lastAssistant && typeof lastAssistant.id === "string") {
+ for (const m of assistantsWithCitations) {
+ if (typeof m.id === "string") deferredMessageIds.add(m.id);
+ }
+ aggregatedAfter.set(lastAssistant.id, aggregateSourceCitations(turn));
+ }
+ turn = [];
+ };
+
+ for (const message of messages) {
+ if (message.role === "user") flush();
+ turn.push(message);
+ }
+ flush();
+
+ return { deferredMessageIds, aggregatedAfter };
+}
+
export function sourceCitationsFromContentBlocks(contentBlocks: unknown): SourceCitation[] {
if (!Array.isArray(contentBlocks)) return [];