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

Polish chat suggestions and sources UI

Louis Beaumont0183d9b222a9
diff --git a/apps/screenpipe-app-tauri/components/chat/source-citation-footer.test.tsx b/apps/screenpipe-app-tauri/components/chat/source-citation-footer.test.tsx
index f288836d4..6f31d5e0e 100644
--- a/apps/screenpipe-app-tauri/components/chat/source-citation-footer.test.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/source-citation-footer.test.tsx
@@ -44,4 +44,48 @@ describe("SourceCitationFooter", () => {
);
expect(duplicateKeyErrors).toEqual([]);
});
+
+ it("uses the Perplexity icon for Perplexity connector sources", () => {
+ const { container } = render(
+ <SourceCitationFooter
+ citations={[
+ {
+ id: "screenpipe-connections-perplexity-proxy-chat-completions",
+ kind: "connector",
+ title: "Perplexity search",
+ subtitle: "external web context via Screenpipe connection",
+ },
+ ]}
+ />
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /1 source/i }));
+
+ expect(container.querySelector('img[src="/images/perplexity.svg"]')).toBeTruthy();
+ });
+
+ it("uses branded icons for other connector and screenpipe sources", () => {
+ const { container } = render(
+ <SourceCitationFooter
+ citations={[
+ {
+ id: "screenpipe-connections-google-calendar-events",
+ kind: "connector",
+ title: "Google Calendar events",
+ },
+ {
+ id: "screenpipe-memories-jill-benaglio",
+ kind: "screenpipe",
+ title: "Screenpipe memories",
+ subtitle: "memory query: Jill Benaglio",
+ },
+ ]}
+ />
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: /2 sources/i }));
+
+ expect(container.querySelector('img[src="/images/google-calendar.svg"]')).toBeTruthy();
+ expect(container.querySelector('img[src="/images/screenpipe.png"]')).toBeTruthy();
+ });
});
diff --git a/apps/screenpipe-app-tauri/components/chat/source-citation-footer.tsx b/apps/screenpipe-app-tauri/components/chat/source-citation-footer.tsx
index dce62d7d0..fcadcb708 100644
--- a/apps/screenpipe-app-tauri/components/chat/source-citation-footer.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/source-citation-footer.tsx
@@ -14,6 +14,7 @@ import {
FileText,
Globe,
HardDrive,
+ Plug,
Search,
TerminalSquare,
} from "lucide-react";
@@ -28,6 +29,7 @@ interface SourceCitationFooterProps {
const KIND_ICON: Record<SourceCitationKind, React.ComponentType<{ className?: string }>> = {
screenpipe: Search,
database: Database,
+ connector: Plug,
web: Globe,
file: FileText,
memory: HardDrive,
@@ -35,6 +37,59 @@ const KIND_ICON: Record<SourceCitationKind, React.ComponentType<{ className?: st
command: TerminalSquare,
};
+const KIND_LABEL: Record<SourceCitationKind, string> = {
+ screenpipe: "screen",
+ database: "db",
+ connector: "app",
+ web: "web",
+ file: "file",
+ memory: "memory",
+ pipe: "pipe",
+ command: "cmd",
+};
+
+const CONNECTION_SOURCE_ICON_PATHS: Array<[string, string]> = [
+ ["apple-calendar", "/images/apple.svg"],
+ ["apple calendar", "/images/apple.svg"],
+ ["asana", "/images/asana.svg"],
+ ["airtable", "/images/airtable.png"],
+ ["bitrix24", "/images/bitrix24.png"],
+ ["browser-url", "/images/browser-url.svg"],
+ ["browser url", "/images/browser-url.svg"],
+ ["fireflies", "/images/fireflies.png"],
+ ["github-issues", "/images/github.png"],
+ ["github issues", "/images/github.png"],
+ ["github", "/images/github.png"],
+ ["glean", "/images/glean.svg"],
+ ["google-calendar", "/images/google-calendar.svg"],
+ ["google calendar", "/images/google-calendar.svg"],
+ ["google-docs", "/images/google-docs.svg"],
+ ["google docs", "/images/google-docs.svg"],
+ ["google-sheets", "/images/google-sheets.svg"],
+ ["google sheets", "/images/google-sheets.svg"],
+ ["granola", "/images/granola.png"],
+ ["hubspot", "/images/hubspot.png"],
+ ["jira", "/images/jira.png"],
+ ["limitless", "/images/limitless.svg"],
+ ["linear", "/images/linear.svg"],
+ ["logseq", "/images/logseq.png"],
+ ["loops", "/images/loops.svg"],
+ ["make", "/images/make.png"],
+ ["monday", "/images/monday.png"],
+ ["n8n", "/images/n8n.png"],
+ ["notion", "/images/notion.svg"],
+ ["otter", "/images/otter.png"],
+ ["perplexity", "/images/perplexity.svg"],
+ ["pocket", "/images/pocket.png"],
+ ["posthog", "/images/posthog.svg"],
+ ["quickbooks", "/images/quickbooks.svg"],
+ ["resend", "/images/resend.svg"],
+ ["voice-memos", "/images/voice-memos.svg"],
+ ["voice memos", "/images/voice-memos.svg"],
+ ["whatsapp", "/images/whatsapp.svg"],
+ ["zapier", "/images/zapier.png"],
+];
+
export function SourceCitationFooter({ citations, className }: SourceCitationFooterProps) {
const [expanded, setExpanded] = React.useState(false);
@@ -89,16 +144,20 @@ function citationRowKey(citation: SourceCitation, index: number): string {
function SourceCitationRow({ citation }: { citation: SourceCitation }) {
const Icon = KIND_ICON[citation.kind] ?? FileText;
+ const kindLabel = KIND_LABEL[citation.kind] ?? citation.kind;
const canOpen = Boolean(citation.href);
const inner = (
<>
<span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border border-border/60 bg-background/60 text-muted-foreground">
- <Icon className="h-3 w-3" />
+ <SourceCitationIcon citation={citation} fallback={Icon} />
</span>
<span className="min-w-0 flex-1">
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate font-medium text-foreground/80">{citation.title}</span>
+ <span className="shrink-0 rounded border border-border/50 px-1 py-0.5 text-[10px] font-medium uppercase leading-none text-muted-foreground/75">
+ {kindLabel}
+ </span>
{canOpen && <ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground/70" />}
</span>
{citation.subtitle && (
@@ -128,3 +187,51 @@ function SourceCitationRow({ citation }: { citation: SourceCitation }) {
</button>
);
}
+
+function SourceCitationIcon({
+ citation,
+ fallback: FallbackIcon,
+}: {
+ citation: SourceCitation;
+ fallback: React.ComponentType<{ className?: string }>;
+}) {
+ const iconSrc = sourceIconSrc(citation);
+ if (iconSrc) {
+ return <img src={iconSrc} alt="" aria-hidden="true" className="h-3.5 w-3.5 rounded-sm" />;
+ }
+
+ if (sourceUsesObsidianIcon(citation)) {
+ return (
+ <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 text-[#7C3AED]" fill="currentColor" aria-hidden="true">
+ <path d="M19.355 18.538a68.967 68.959 0 0 0 1.858-2.954.81.81 0 0 0-.062-.9c-.516-.685-1.504-2.075-2.042-3.362-.553-1.321-.636-3.375-.64-4.377a1.707 1.707 0 0 0-.358-1.05l-3.198-4.064a3.744 3.744 0 0 1-.076.543c-.106.503-.307 1.004-.536 1.5-.134.29-.29.6-.446.914l-.31.626c-.516 1.068-.997 2.227-1.132 3.59-.124 1.26.046 2.73.815 4.481.128.011.257.025.386.044a6.363 6.363 0 0 1 3.326 1.505c.916.79 1.744 1.922 2.415 3.5zM8.199 22.569c.073.012.146.02.22.02.78.024 2.095.092 3.16.29.87.16 2.593.64 4.01 1.055 1.083.316 2.198-.548 2.355-1.664.114-.814.33-1.735.725-2.58l-.01.005c-.67-1.87-1.522-3.078-2.416-3.849a5.295 5.295 0 0 0-2.778-1.257c-1.54-.216-2.952.19-3.84.45.532 2.218.368 4.829-1.425 7.531zM5.533 9.938c-.023.1-.056.197-.098.29L2.82 16.059a1.602 1.602 0 0 0 .313 1.772l4.116 4.24c2.103-3.101 1.796-6.02.836-8.3-.728-1.73-1.832-3.081-2.55-3.831zM9.32 14.01c.615-.183 1.606-.465 2.745-.534-.683-1.725-.848-3.233-.716-4.577.154-1.552.7-2.847 1.235-3.95.113-.235.223-.454.328-.664.149-.297.288-.577.419-.86.217-.47.379-.885.46-1.27.08-.38.08-.72-.014-1.043-.095-.325-.297-.675-.68-1.06a1.6 1.6 0 0 0-1.475.36l-4.95 4.452a1.602 1.602 0 0 0-.513.952l-.427 2.83c.672.59 2.328 2.316 3.335 4.711.09.21.175.43.253.653z" />
+ </svg>
+ );
+ }
+
+ return <FallbackIcon className="h-3 w-3" />;
+}
+
+function sourceIconSrc(citation: SourceCitation): string | undefined {
+ if (citation.kind === "screenpipe") {
+ return "/images/screenpipe.png";
+ }
+
+ if (citation.kind === "connector") {
+ const fingerprint = sourceFingerprint(citation);
+ for (const [key, path] of CONNECTION_SOURCE_ICON_PATHS) {
+ if (fingerprint.includes(key.replace(/[_-]+/g, " "))) return path;
+ }
+ }
+
+ return undefined;
+}
+
+function sourceUsesObsidianIcon(citation: SourceCitation): boolean {
+ return citation.kind === "connector" && sourceFingerprint(citation).includes("obsidian");
+}
+
+function sourceFingerprint(citation: SourceCitation): string {
+ return `${citation.id} ${citation.title} ${citation.subtitle ?? ""}`
+ .toLowerCase()
+ .replace(/[_-]+/g, " ");
+}
diff --git a/apps/screenpipe-app-tauri/components/chat/summary-cards.tsx b/apps/screenpipe-app-tauri/components/chat/summary-cards.tsx
index 7a7775ad1..9a8c55d7d 100644
--- a/apps/screenpipe-app-tauri/components/chat/summary-cards.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/summary-cards.tsx
@@ -25,10 +25,8 @@ interface SummaryCardsProps {
pipesLoading?: boolean;
}
-// ─── Grid scan refresh animation ──────────────────────────────────────────────
-// Brand-aligned: 3x2 card skeleton with micro-grid scan inside each card.
-// A diagonal scan line sweeps across all 6 cards simultaneously — cells flip
-// on/off as it passes, like screenpipe scanning your screen for new context.
+// ─── Suggestion refresh animation ─────────────────────────────────────────────
+// Two quiet rows matching the persistent suggestion layout.
function SuggestionSkeleton() {
const GRID_COLS = 8;
@@ -46,34 +44,28 @@ function SuggestionSkeleton() {
}, []);
return (
- <div className="grid grid-cols-3 gap-1.5">
- {[0, 1, 2, 3, 4, 5].map((cardIdx) => {
- const cardRow = Math.floor(cardIdx / 3);
- const cardCol = cardIdx % 3;
- // Offset each card's scan phase so the line travels across all 6
- const cardOffset = cardRow * 4 + cardCol * 3;
+ <div className="divide-y divide-border/35 border-y border-border/25">
+ {[0, 1].map((rowIdx) => {
+ const rowOffset = rowIdx * 4;
return (
<div
- key={cardIdx}
- className="border border-border/20 p-2"
- style={{ minHeight: 52 }}
+ key={rowIdx}
+ className="flex min-h-[44px] items-center gap-2 px-2 py-2"
>
- {/* Micro grid — scan line sweeps diagonally */}
<div
- className="grid gap-px mb-2"
+ className="grid shrink-0 gap-px"
style={{
- gridTemplateColumns: `repeat(${GRID_COLS}, 4px)`,
- gridTemplateRows: `repeat(${GRID_ROWS}, 4px)`,
+ gridTemplateColumns: `repeat(${GRID_COLS}, 3px)`,
+ gridTemplateRows: `repeat(${GRID_ROWS}, 3px)`,
}}
>
{Array.from({ length: CARD_CELLS }, (_, i) => {
const r = Math.floor(i / GRID_COLS);
const c = i % GRID_COLS;
- const diag = r + c + cardOffset;
+ const diag = r + c + rowOffset;
const scanPos = tick % (GRID_ROWS + GRID_COLS + 10);
const dist = Math.abs(diag - scanPos);
- // On the scan line = bright, trailing = dimmer, rest = faint flicker
const on = dist === 0 || (dist < 3 && ((tick + i) % 3 === 0));
return (
<div
@@ -81,20 +73,21 @@ function SuggestionSkeleton() {
className={`transition-colors duration-75 ${
on ? "bg-foreground" : dist < 5 ? "bg-foreground/10" : "bg-foreground/[0.03]"
}`}
- style={{ width: 4, height: 4 }}
+ style={{ width: 3, height: 3 }}
/>
);
})}
</div>
- {/* Text placeholder bars that pulse with the scan */}
- <div
- className="h-[7px] bg-foreground/[0.08] transition-all duration-100"
- style={{ width: `${55 + Math.sin(tick * 0.15 + cardIdx) * 25}%` }}
- />
- <div
- className="h-[5px] bg-foreground/[0.04] mt-1 transition-all duration-100"
- style={{ width: `${35 + Math.sin(tick * 0.15 + cardIdx + 2) * 20}%` }}
- />
+ <div className="min-w-0 flex-1 space-y-1">
+ <div
+ className="h-[7px] bg-foreground/[0.08] transition-all duration-100"
+ style={{ width: `${55 + Math.sin(tick * 0.15 + rowIdx) * 25}%` }}
+ />
+ <div
+ className="h-[5px] bg-foreground/[0.04] transition-all duration-100"
+ style={{ width: `${35 + Math.sin(tick * 0.15 + rowIdx + 2) * 20}%` }}
+ />
+ </div>
</div>
);
})}
@@ -186,7 +179,6 @@ export function SummaryCards({
const templates = templatePipes.length > 0 ? templatePipes : FALLBACK_TEMPLATES;
const featured = templates.filter((t) => t.featured);
const discover = templates.filter((t) => !t.featured);
- const hasConnectionSuggestions = autoSuggestions.some((s) => s.connectionIcon);
const handleCardClick = (pipe: TemplatePipe) => {
onSendMessage(pipe.prompt, `${pipe.icon} ${pipe.title}`);
@@ -330,10 +322,7 @@ export function SummaryCards({
{/* ─── Dynamic AI suggestions ─────────────────────────────────────────── */}
<div className="w-full max-w-lg">
- <div className="flex items-center gap-1.5 mb-1.5 px-1">
- <div className="text-[10px] text-muted-foreground/60 uppercase tracking-wider font-medium font-mono">
- {hasConnectionSuggestions ? "based on activity + connections" : "based on your activity"}
- </div>
+ <div className="mb-1 flex justify-end px-1">
{onRefreshSuggestions && (
<button
onClick={onRefreshSuggestions}
@@ -346,7 +335,7 @@ export function SummaryCards({
)}
</div>
- {/* Grid scan skeleton while refreshing / suggestion cards */}
+ {/* Persistent suggestions */}
<AnimatePresence mode="wait">
{suggestionsRefreshing ? (
<motion.div
@@ -360,15 +349,14 @@ export function SummaryCards({
</motion.div>
) : (
<motion.div
- key="cards"
+ key="suggestions"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
- className="grid grid-cols-3 gap-1.5"
+ className="divide-y divide-border/35 border-y border-border/25"
>
- {autoSuggestions.slice(0, 6).map((s, i) => {
- const isHero = (s.priority ?? 2) === 1 && i === 0;
+ {autoSuggestions.slice(0, 2).map((s, i) => {
return (
<motion.button
key={s.text}
@@ -377,28 +365,15 @@ export function SummaryCards({
transition={{ duration: 0.15, delay: i * 0.05 }}
type="button"
onClick={() => onSendMessage(s.text)}
- className={`group text-left p-2 font-mono bg-muted/20 hover:bg-foreground hover:text-background border hover:border-foreground text-muted-foreground transition-all duration-150 cursor-pointer ${
- isHero
- ? "border-border/40 bg-muted/30"
- : "border-border/20"
- }`}
+ className="group flex min-h-[44px] w-full items-center gap-2 px-2 py-2 text-left font-mono text-muted-foreground transition-colors duration-150 hover:bg-muted/25 hover:text-foreground"
title={s.text}
>
- <div className="flex items-start gap-1.5 min-w-0">
- {s.connectionIcon && (
- <span className="mt-px">
- <ConnectionSuggestionIcon name={s.connectionIcon} />
- </span>
- )}
- <div className={`min-w-0 text-[11px] leading-tight ${isHero ? "font-medium" : ""} line-clamp-2`}>
- {s.text}
- </div>
- </div>
- {s.preview && (
- <div className="text-[10px] text-muted-foreground/50 group-hover:text-background/50 leading-tight mt-0.5 truncate">
- {s.preview}
- </div>
- )}
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center">
+ {s.connectionIcon && <ConnectionSuggestionIcon name={s.connectionIcon} />}
+ </span>
+ <span className="min-w-0 flex-1 text-sm leading-snug line-clamp-2">
+ {s.text}
+ </span>
</motion.button>
);
})}
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 65d0b866f..81d227628 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -114,6 +114,7 @@ const FOLLOW_UP_GENERATION_DELAY_MS = 10_000;
const POST_STREAM_SIDE_EFFECT_DELAY_MS = 1_500;
const CHAT_RAIL_CLASS = "max-w-4xl mx-auto w-full";
const CONNECTION_SUGGESTION_LIMIT = 3;
+const VISIBLE_SUGGESTION_LIMIT = 2;
type ConnectedIntegration = {
id: string;
@@ -348,8 +349,19 @@ function suggestionForConnection(connection: ConnectedIntegration): Suggestion |
function mergeConnectionSuggestions(
autoSuggestions: Suggestion[],
connections: ConnectedIntegration[],
- previewSuggestions: Suggestion[] = []
+ previewSuggestions: Suggestion[] = [],
+ rotationSeed = 0
): Suggestion[] {
+ const rotateVisible = (suggestions: Suggestion[]) => {
+ if (suggestions.length <= VISIBLE_SUGGESTION_LIMIT || rotationSeed <= 0) {
+ return suggestions.slice(0, VISIBLE_SUGGESTION_LIMIT);
+ }
+
+ const offset = rotationSeed % suggestions.length;
+ const rotated = [...suggestions.slice(offset), ...suggestions.slice(0, offset)];
+ return rotated.slice(0, VISIBLE_SUGGESTION_LIMIT);
+ };
+
const previewIcons = new Set(previewSuggestions.map((s) => s.connectionIcon).filter(Boolean));
const connectionSuggestions = connections
.filter((connection) => !previewIcons.has(connection.icon || connection.id))
@@ -358,19 +370,21 @@ function mergeConnectionSuggestions(
.slice(0, CONNECTION_SUGGESTION_LIMIT);
const combinedConnectionSuggestions = [...previewSuggestions, ...connectionSuggestions].slice(0, CONNECTION_SUGGESTION_LIMIT);
- if (combinedConnectionSuggestions.length === 0) return autoSuggestions;
+ if (combinedConnectionSuggestions.length === 0) return rotateVisible(autoSuggestions);
const [first, ...rest] = autoSuggestions;
const merged = first
? [first, ...combinedConnectionSuggestions, ...rest]
: combinedConnectionSuggestions;
const seen = new Set<string>();
- return merged.filter((suggestion) => {
+ const deduped = merged.filter((suggestion) => {
const key = suggestion.text.toLowerCase().replace(/\s+/g, " ").trim();
if (seen.has(key)) return false;
seen.add(key);
return true;
- }).slice(0, 6);
+ });
+
+ return rotateVisible(deduped);
}
interface Speaker {
@@ -1083,6 +1097,253 @@ function friendlyToolLabel(toolCall: ToolCall): string {
}
}
+interface ToolDetailField {
+ label: string;
+ value: string;
+}
+
+interface BashToolDetailsPresentation {
+ title: string;
+ eyebrow: string;
+ fields: ToolDetailField[];
+ resultSummary?: string;
+ rawCommand: string;
+ rawResult?: string;
+}
+
+function bashToolDetailsPresentation(toolCall: ToolCall): BashToolDetailsPresentation | null {
+ const command = String(toolCall.args.command ?? "");
+ if (!command) return null;
+
+ const classified = classifyCurl(command);
+ const method = curlMethod(command);
+ const localUrl = urlsInCommand(command).find(isLocalScreenpipeUrl);
+ const fields: ToolDetailField[] = [];
+
+ if (!localUrl) {
+ const target = firstExternalWebTarget(command, "fetch");
+ if (!target || !classified) return null;
+ fields.push({ label: "domain", value: target.domain });
+ fields.push({ label: "method", value: method });
+ return {
+ title: classified.label,
+ eyebrow: "Web request",
+ fields,
+ resultSummary: summarizeToolResult(toolCall.result, "web"),
+ rawCommand: command,
+ rawResult: toolCall.result,
+ };
+ }
+
+ const path = localUrl.pathname.replace(/\/$/, "") || "/";
+ fields.push({ label: "endpoint", value: path });
+ fields.push({ label: "method", value: method });
+
+ const sp = localUrl.searchParams;
+ const addParam = (label: string, key: string) => {
+ const value = sp.get(key);
+ if (value) fields.push({ label, value: trunc(value, 80) });
+ };
+
+ addParam("query", "q");
+ addParam("content", "content_type");
+ addParam("app", "app_name");
+ addParam("window", "window_name");
+ addParam("limit", "limit");
+
+ const body = curlBodyJson(command);
+ if (path === "/raw_sql" && body && typeof body.query === "string") {
+ const tables = sqlTables(body.query);
+ if (tables.length > 0) fields.push({ label: "tables", value: tables.join(", ") });
+ }
+
+ if (path.startsWith("/connections/")) {
+ const connection = path.split("/")[2];
+ if (connection) fields.push({ label: "connection", value: connection });
+ }
+
+ return {
+ title: classified?.label ?? `${method} ${path}`,
+ eyebrow: endpointFamily(path),
+ fields,
+ resultSummary: summarizeToolResult(toolCall.result, path),
+ rawCommand: command,
+ rawResult: toolCall.result,
+ };
+}
+
+function endpointFamily(path: string): string {
+ if (path === "/memories" || path.startsWith("/memories/")) return "Memory";
+ if (path === "/search") return "Screen search";
+ if (path === "/activity-summary") return "Activity";
+ if (path === "/raw_sql") return "Database";
+ if (path.startsWith("/connections/")) return "Connection";
+ if (path.startsWith("/meetings")) return "Meetings";
+ if (path.startsWith("/speakers")) return "Speakers";
+ if (path.startsWith("/pipes")) return "Pipes";
+ return "Screenpipe";
+}
+
+function parseToolResultJson(result: string | undefined): any | null {
+ if (!result?.trim()) return null;
+ try {
+ return JSON.parse(result);
+ } catch {
+ return null;
+ }
+}
+
+function summarizeToolResult(result: string | undefined, family: string): string | undefined {
+ const json = parseToolResultJson(result);
+ if (!json) return result?.trim() ? trunc(result.trim().replace(/\s+/g, " "), 120) : undefined;
+
+ const noun = family === "/memories" ? "memories"
+ : family === "/search" ? "results"
+ : family.startsWith("/meetings") ? "meetings"
+ : family.startsWith("/connections") ? "items"
+ : "items";
+
+ if (Array.isArray(json)) return json.length === 0 ? `No ${noun} returned` : `${json.length} ${noun} returned`;
+ if (Array.isArray(json.data)) {
+ const total = typeof json.pagination?.total === "number" ? json.pagination.total : json.data.length;
+ return total === 0 ? `No ${noun} found` : `${total} ${noun} found`;
+ }
+ if (Array.isArray(json.search_results)) {
+ return json.search_results.length === 0 ? "No web sources returned" : `${json.search_results.length} web sources returned`;
+ }
+ if (Array.isArray(json.choices)) return `${json.choices.length} response${json.choices.length === 1 ? "" : "s"} returned`;
+ if (typeof json.success === "boolean") return json.success ? "Request succeeded" : "Request did not succeed";
+ if (typeof json.status === "string") return `Status: ${json.status}`;
+ return "JSON response returned";
+}
+
+function formatToolResult(result: string | undefined): string | undefined {
+ if (!result) return undefined;
+ const json = parseToolResultJson(result);
+ if (!json) return result;
+ return JSON.stringify(json, null, 2);
+}
+
+function sanitizeCommand(command: string): string {
+ return command
+ .replace(/\s-H\s+['"]Authorization:\s*Bearer\s+[^'"]+['"]/g, " -H \"Authorization: Bearer …\"")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+function BashToolDetails({ toolCall }: { toolCall: ToolCall }) {
+ const details = bashToolDetailsPresentation(toolCall);
+ if (!details) {
+ return (
+ <div className="py-1.5">
+ <ToolCodeBlock code={sanitizeCommand(String(toolCall.args.command ?? ""))} language="shell" />
+ </div>
+ );
+ }
+
+ const formattedResult = formatToolResult(details.rawResult);
+
+ return (
+ <div className="py-1.5 space-y-2">
+ <div className="rounded-md border border-border/50 bg-muted/20 px-2.5 py-2">
+ <div className="mb-1 flex min-w-0 items-center gap-1.5">
+ <span className="shrink-0 rounded border border-border/50 px-1.5 py-0.5 text-[10px] font-mono uppercase leading-none text-muted-foreground">
+ {details.eyebrow}
+ </span>
+ {details.resultSummary && (
+ <span className="min-w-0 truncate text-[11px] text-muted-foreground">
+ {details.resultSummary}
+ </span>
+ )}
+ </div>
+ <div className="text-sm font-medium text-foreground/85">{details.title}</div>
+ {details.fields.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-1">
+ {details.fields.map((field) => (
+ <span
+ key={`${field.label}:${field.value}`}
+ className="max-w-full rounded border border-border/40 bg-background/60 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground"
+ >
+ <span className="text-muted-foreground/60">{field.label}</span>{" "}
+ <span className="text-foreground/70">{field.value}</span>
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <details className="group rounded-md border border-border/30 bg-background/40 px-2 py-1.5">
+ <summary className="cursor-pointer select-none text-[10px] font-mono uppercase tracking-wide text-muted-foreground/70 transition-colors hover:text-foreground/70">
+ technical details
+ </summary>
+ <div className="mt-2 space-y-2">
+ <ToolCodeBlock label="command" code={sanitizeCommand(details.rawCommand)} language="shell" />
+ {formattedResult && <ToolCodeBlock label="response" code={formattedResult} language="json" />}
+ </div>
+ </details>
+ </div>
+ );
+}
+
+function ToolCodeBlock({
+ code,
+ language,
+ label,
+}: {
+ code: string;
+ language: "shell" | "json";
+ label?: string;
+}) {
+ return (
+ <div className="min-w-0">
+ {label && <div className="mb-1 text-[10px] font-mono uppercase text-muted-foreground/50">{label}</div>}
+ <pre className="max-h-[220px] max-w-full overflow-auto rounded border border-border/30 bg-muted/20 p-2 text-xs leading-relaxed">
+ <code className="font-mono">
+ {language === "json" ? <HighlightedJson code={code} /> : <HighlightedShell code={code} />}
+ </code>
+ </pre>
+ </div>
+ );
+}
+
+function HighlightedShell({ code }: { code: string }) {
+ const parts = code.split(/(\s+|https?:\/\/[^\s"']+|-[A-Za-z-]+|\$[A-Z0-9_]+)/g).filter(Boolean);
+ return (
+ <>
+ {parts.map((part, index) => {
+ const className = /^https?:\/\//.test(part)
+ ? "text-cyan-700 dark:text-cyan-300"
+ : /^-[A-Za-z-]+$/.test(part)
+ ? "text-purple-700 dark:text-purple-300"
+ : /^\$[A-Z0-9_]+$/.test(part)
+ ? "text-amber-700 dark:text-amber-300"
+ : part === "curl"
+ ? "text-foreground"
+ : "text-muted-foreground";
+ return <span key={`${part}-${index}`} className={className}>{part}</span>;
+ })}
+ </>
+ );
+}
+
+function HighlightedJson({ code }: { code: string }) {
+ const parts = code.split(/("(?:\\.|[^"\\])*"\s*:|"(?:\\.|[^"\\])*"|true|false|null|-?\d+(?:\.\d+)?)/g).filter(Boolean);
+ return (
+ <>
+ {parts.map((part, index) => {
+ const className = /^".*"\s*:$/s.test(part)
+ ? "text-purple-700 dark:text-purple-300"
+ : /^"/s.test(part)
+ ? "text-emerald-700 dark:text-emerald-300"
+ : /^(true|false|null|-?\d)/.test(part)
+ ? "text-amber-700 dark:text-amber-300"
+ : "text-muted-foreground";
+ return <span key={`${part}-${index}`} className={className}>{part}</span>;
+ })}
+ </>
+ );
+}
+
// Render friendly expanded details instead of raw JSON
function FriendlyToolDetails({ toolCall }: { toolCall: ToolCall }) {
if (toolCall.toolName === "edit" && toolCall.args.old_string && toolCall.args.new_string) {
@@ -1098,13 +1359,7 @@ function FriendlyToolDetails({ toolCall }: { toolCall: ToolCall }) {
);
}
if (toolCall.toolName === "bash" && toolCall.args.command) {
- return (
- <div className="py-1.5">
- <pre className="whitespace-pre-wrap break-words text-foreground/70 text-xs font-mono max-h-[200px] overflow-y-auto overflow-x-hidden max-w-full">
- {toolCall.args.command}
- </pre>
- </div>
- );
+ return <BashToolDetails toolCall={toolCall} />;
}
const entries = Object.entries(toolCall.args).filter(([k]) => k !== "path" && k !== "command");
if (entries.length === 0) return null;
@@ -1191,7 +1446,7 @@ function ToolCallRailItem({ toolCall, isLast }: { toolCall: ToolCall; isLast: bo
>
<div className="border-l border-border ml-0 pl-3 mt-1 mb-1">
<FriendlyToolDetails toolCall={toolCall} />
- {toolCall.result !== undefined && (
+ {toolCall.result !== undefined && toolCall.toolName !== "bash" && (
<div className="mt-1 pt-1 border-t border-border/50">
<pre className={cn(
"whitespace-pre-wrap break-words max-h-[300px] overflow-y-auto overflow-x-hidden max-w-full text-xs font-mono",
@@ -1652,7 +1907,8 @@ function MarkdownBlock({ text, isUser }: { text: string; isUser: boolean }) {
type GroupedBlock =
| { type: "text"; text: string; key: number }
| { type: "thinking"; text: string; isThinking: boolean; durationMs?: number; key: number }
- | { type: "tool-group"; toolCalls: ToolCall[]; key: number };
+ | { type: "tool-group"; toolCalls: ToolCall[]; key: number }
+ | { type: "work-group"; toolCalls: ToolCall[]; durationMs: number; key: number };
function groupContentBlocks(blocks: ContentBlock[]): GroupedBlock[] {
const result: GroupedBlock[] = [];
@@ -1680,6 +1936,63 @@ function groupContentBlocks(blocks: ContentBlock[]): GroupedBlock[] {
return result;
}
+function collapseHiddenWorkGroups(grouped: GroupedBlock[], hideThinkingBlocks: boolean): GroupedBlock[] {
+ if (!hideThinkingBlocks) return grouped;
+
+ const out: GroupedBlock[] = [];
+ let pendingToolCalls: ToolCall[] = [];
+ let pendingDurationMs = 0;
+ let pendingToolGroupCount = 0;
+ let pendingKey: number | null = null;
+
+ const flushPending = () => {
+ if (pendingToolCalls.length === 0) {
+ pendingDurationMs = 0;
+ pendingToolGroupCount = 0;
+ pendingKey = null;
+ return;
+ }
+
+ const key = pendingKey ?? out.length;
+ if (pendingToolGroupCount > 1 || pendingToolCalls.length >= 3) {
+ out.push({
+ type: "work-group",
+ toolCalls: [...pendingToolCalls],
+ durationMs: pendingDurationMs,
+ key,
+ });
+ } else {
+ out.push({ type: "tool-group", toolCalls: [...pendingToolCalls], key });
+ }
+
+ pendingToolCalls = [];
+ pendingDurationMs = 0;
+ pendingToolGroupCount = 0;
+ pendingKey = null;
+ };
+
+ for (const group of grouped) {
+ if (group.type === "tool-group") {
+ pendingKey ??= group.key;
+ pendingToolCalls.push(...group.toolCalls);
+ pendingToolGroupCount++;
+ continue;
+ }
+
+ if (group.type === "thinking") {
+ pendingDurationMs += group.durationMs ?? 0;
+ pendingKey ??= group.key;
+ continue;
+ }
+
+ flushPending();
+ out.push(group);
+ }
+
+ flushPending();
+ return out;
+}
+
// Build natural-language summary of completed tool calls
function buildToolSummary(toolCalls: ToolCall[]): string {
const counts: Record<string, number> = {};
@@ -1698,11 +2011,29 @@ function buildToolSummary(toolCalls: ToolCall[]): string {
return parts.join(", ");
}
+function formatWorkDuration(durationMs: number): string {
+ if (!durationMs || durationMs <= 0) return "Worked";
+ const seconds = Math.max(1, Math.round(durationMs / 1000));
+ if (seconds < 60) return "Worked for <1 min";
+ const minutes = Math.max(1, Math.round(seconds / 60));
+ return `Worked for ${minutes} min${minutes === 1 ? "" : "s"}`;
+}
+
function toolCallRenderKey(toolCall: ToolCall, index: number): string {
return `${toolCall.id || toolCall.toolName || "tool"}:${index}`;
}
-function ToolCallGroup({ toolCalls, defaultExpanded = false }: { toolCalls: ToolCall[]; defaultExpanded?: boolean }) {
+function ToolCallGroup({
+ toolCalls,
+ defaultExpanded = false,
+ summaryOverride,
+ hideCount = false,
+}: {
+ toolCalls: ToolCall[];
+ defaultExpanded?: boolean;
+ summaryOverride?: string;
+ hideCount?: boolean;
+}) {
const [manualExpand, setManualExpand] = useState<boolean | null>(null);
const hasRunning = toolCalls.some((tc) => tc.isRunning);
@@ -1710,7 +2041,7 @@ function ToolCallGroup({ toolCalls, defaultExpanded = false }: { toolCalls: Tool
const allDone = !hasRunning;
const doneCount = toolCalls.filter((tc) => !tc.isRunning).length;
const total = toolCalls.length;
- const summary = allDone ? buildToolSummary(toolCalls) : "";
+ const summary = allDone ? (summaryOverride || buildToolSummary(toolCalls)) : "";
// Auto-expand while running, auto-collapse when done (user can override).
// `defaultExpanded` keeps the group open even when done — used for
@@ -1726,19 +2057,21 @@ function ToolCallGroup({ toolCalls, defaultExpanded = false }: { toolCalls: Tool
className="w-full flex items-center gap-2 py-1 text-left min-w-0 group"
>
{/* Status indicator */}
- <span className="flex-shrink-0 text-xs font-mono text-foreground/40">
- {hasRunning ? (
- <motion.span
- className="inline-block"
- animate={{ opacity: [1, 1, 0.3, 0.3, 1] }}
- transition={{ duration: 1, repeat: Infinity, times: [0, 0.25, 0.25, 0.75, 0.75], ease: "linear" }}
- >
- [{doneCount}/{total}]
- </motion.span>
- ) : (
- <span>[{total}]</span>
- )}
- </span>
+ {!hideCount && (
+ <span className="flex-shrink-0 text-xs font-mono text-foreground/40">
+ {hasRunning ? (
+ <motion.span
+ className="inline-block"
+ animate={{ opacity: [1, 1, 0.3, 0.3, 1] }}
+ transition={{ duration: 1, repeat: Infinity, times: [0, 0.25, 0.25, 0.75, 0.75], ease: "linear" }}
+ >
+ [{doneCount}/{total}]
+ </motion.span>
+ ) : (
+ <span>[{total}]</span>
+ )}
+ </span>
+ )}
{/* Summary text */}
<span className="truncate flex-1 text-xs font-mono text-foreground/50 group-hover:text-foreground/80 transition-colors duration-150">
@@ -1826,6 +2159,7 @@ function MessageContent({
// Group consecutive tool blocks into collapsible containers
if (message.contentBlocks && message.contentBlocks.length > 0) {
const grouped = groupContentBlocks(message.contentBlocks);
+ const displayGroups = collapseHiddenWorkGroups(grouped, hideThinkingBlocks);
// When the message has no rendered prose (no text block — common for
// pipe-run executions whose entire output is thinking + tool calls),
// expand thinking blocks by default. Otherwise the collapsed
@@ -1835,7 +2169,7 @@ function MessageContent({
const hasText = grouped.some((g) => g.type === "text");
return (
<div className="space-y-2 min-w-0 w-full overflow-hidden">
- {grouped.map((group) => {
+ {displayGroups.map((group) => {
if (group.type === "text") {
return <MarkdownBlock key={`text-${group.key}`} text={group.text} isUser={isUser} />;
}
@@ -1851,6 +2185,17 @@ function MessageContent({
if (group.type === "tool-group") {
return <ToolCallGroup key={`tools-${group.key}`} toolCalls={group.toolCalls} defaultExpanded={!hasText} />;
}
+ if (group.type === "work-group") {
+ return (
+ <ToolCallGroup
+ key={`work-${group.key}`}
+ toolCalls={group.toolCalls}
+ defaultExpanded={!hasText}
+ summaryOverride={formatWorkDuration(group.durationMs)}
+ hideCount={hasText}
+ />
+ );
+ }
return null;
})}
{sourceFooter}
@@ -2139,10 +2484,22 @@ export function StandaloneChat({
// agent pick the right connection for a query instead of having to guess.
const [connections, setConnections] = useState<ConnectedIntegration[]>([]);
const [connectionPreviewSuggestions, setConnectionPreviewSuggestions] = useState<Suggestion[]>([]);
+ const [suggestionRefreshSeed, setSuggestionRefreshSeed] = useState(0);
+ const visibleSuggestionSignature = React.useMemo(
+ () =>
+ [...autoSuggestions, ...connectionPreviewSuggestions]
+ .map((s) => `${s.text}|${s.preview ?? ""}|${s.connectionIcon ?? ""}|${s.priority ?? ""}`)
+ .join("\n"),
+ [autoSuggestions, connectionPreviewSuggestions]
+ );
const connectionAwareSuggestions = React.useMemo(
- () => mergeConnectionSuggestions(autoSuggestions, connections, connectionPreviewSuggestions),
- [autoSuggestions, connections, connectionPreviewSuggestions]
+ () => mergeConnectionSuggestions(autoSuggestions, connections, connectionPreviewSuggestions, suggestionRefreshSeed),
+ [autoSuggestions, connections, connectionPreviewSuggestions, suggestionRefreshSeed]
);
+
+ useEffect(() => {
+ setSuggestionRefreshSeed(0);
+ }, [visibleSuggestionSignature]);
// Watch the input section's width so suggestion chips can collapse into
// a popover on narrow chat columns.
useEffect(() => {
@@ -2218,6 +2575,16 @@ export function StandaloneChat({
};
}, [connections]);
+ const refreshVisibleSuggestions = useCallback(() => {
+ setSuggestionRefreshSeed((seed) => seed + 1);
+ void refreshSuggestions();
+
+ if (connections.length === 0) return;
+ void fetchConnectionPreviewSuggestions(connections).then((suggestions) => {
+ setConnectionPreviewSuggestions(suggestions);
+ });
+ }, [connections, refreshSuggestions]);
+
// Custom summary templates (persisted in settings)
const [customTemplates, setCustomTemplates] = useState<CustomTemplate[]>([]);
@@ -6342,7 +6709,7 @@ export function StandaloneChat({
onSendMessage={sendMessage}
autoSuggestions={connectionAwareSuggestions}
suggestionsRefreshing={suggestionsRefreshing}
- onRefreshSuggestions={refreshSuggestions}
+ onRefreshSuggestions={refreshVisibleSuggestions}
customTemplates={customTemplates}
onSaveCustomTemplate={saveCustomTemplate}
onDeleteCustomTemplate={deleteCustomTemplate}
@@ -6724,7 +7091,7 @@ export function StandaloneChat({
</button>
))}
<button
- onClick={refreshSuggestions}
+ onClick={refreshVisibleSuggestions}
disabled={suggestionsRefreshing}
className="p-0.5 text-muted-foreground/30 hover:text-foreground transition-colors duration-150 disabled:opacity-30 cursor-pointer"
title="refresh suggestions"
@@ -6769,7 +7136,7 @@ export function StandaloneChat({
</PopoverContent>
</Popover>
<button
- onClick={refreshSuggestions}
+ onClick={refreshVisibleSuggestions}
disabled={suggestionsRefreshing}
className="p-0.5 text-muted-foreground/30 hover:text-foreground transition-colors duration-150 disabled:opacity-30 cursor-pointer"
title="refresh suggestions"
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 143b2415d..5ffedc357 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/source-citations.test.ts
@@ -68,6 +68,92 @@ describe("source citations", () => {
expect(citations[0].subtitle).toContain("query: pricing");
});
+ it("names connector calls instead of collapsing them to generic screenpipe api", () => {
+ const citations = sourceCitationsFromMessage({
+ contentBlocks: [
+ {
+ type: "tool",
+ toolCall: {
+ toolName: "bash",
+ args: {
+ command:
+ 'curl -s -X POST "http://localhost:3030/connections/perplexity/proxy/chat/completions"',
+ },
+ result: '{"choices":[]}',
+ isRunning: false,
+ },
+ },
+ ],
+ });
+
+ expect(citations).toHaveLength(1);
+ expect(citations[0]).toMatchObject({
+ kind: "connector",
+ title: "Perplexity search",
+ subtitle: "external web context via Screenpipe connection",
+ });
+ });
+
+ it("labels screenpipe memory endpoint citations as memory", () => {
+ const citations = sourceCitationsFromMessage({
+ contentBlocks: [
+ {
+ type: "tool",
+ toolCall: {
+ toolName: "bash",
+ args: {
+ command:
+ 'curl -s "http://localhost:3030/memories?q=Jill%20Benaglio&limit=5"',
+ },
+ result: '{"data":[]}',
+ isRunning: false,
+ },
+ },
+ ],
+ });
+
+ expect(citations).toHaveLength(1);
+ expect(citations[0]).toMatchObject({
+ kind: "memory",
+ title: "Screenpipe memories",
+ subtitle: "memory query: Jill Benaglio",
+ });
+ });
+
+ it("pulls structured result links out of bash tool output", () => {
+ const citations = sourceCitationsFromMessage({
+ contentBlocks: [
+ {
+ type: "tool",
+ toolCall: {
+ toolName: "bash",
+ args: {
+ command:
+ 'curl -s "http://localhost:3030/connections/perplexity/proxy/chat/completions"',
+ },
+ result: JSON.stringify({
+ search_results: [
+ { title: "Screenpipe docs", url: "https://docs.screenpi.pe/chat" },
+ ],
+ }),
+ isRunning: false,
+ },
+ },
+ ],
+ });
+
+ expect(citations).toHaveLength(2);
+ expect(citations[0]).toMatchObject({
+ kind: "connector",
+ title: "Perplexity search",
+ });
+ expect(citations[1]).toMatchObject({
+ kind: "web",
+ title: "Screenpipe docs",
+ href: "https://docs.screenpi.pe/chat",
+ });
+ });
+
it("derives file and memory citations from read calls", () => {
const citations = sourceCitationsFromMessage({
contentBlocks: [
@@ -97,6 +183,28 @@ describe("source citations", () => {
expect(citations[1].title).toBe("Read: standalone-chat.tsx");
});
+ it("normalizes pi tool namespaces before deriving citations", () => {
+ const citations = sourceCitationsFromMessage({
+ contentBlocks: [
+ {
+ type: "tool",
+ toolCall: {
+ toolName: "tool_functions.read",
+ args: { path: "/Users/louisbeaumont/.screenpipe/pipes/lead-radar/pipe.ts" },
+ result: "code",
+ isRunning: false,
+ },
+ },
+ ],
+ });
+
+ expect(citations).toHaveLength(1);
+ expect(citations[0]).toMatchObject({
+ kind: "pipe",
+ title: "Read: pipe.ts",
+ });
+ });
+
it("does not treat sed ranges as file citations", () => {
const citations = sourceCitationsFromMessage({
contentBlocks: [
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts b/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts
index bcd05b403..515c7a860 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-auto-suggestions.ts
@@ -32,14 +32,17 @@ export function useAutoSuggestions() {
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const prevTextsRef = useRef<string>("");
+ const prevSignatureRef = useRef<string>("");
const applySuggestions = useCallback(
- (data: { suggestions: Suggestion[]; mode: string; tags?: string[] }) => {
- const newTexts = data.suggestions.map((s) => s.text).join("|");
- // Only update state if suggestions actually changed (avoids re-render flicker)
- if (newTexts !== prevTextsRef.current) {
- prevTextsRef.current = newTexts;
+ (data: { suggestions: Suggestion[]; mode: string; tags?: string[] }, options?: { force?: boolean }) => {
+ const newSignature = JSON.stringify(
+ data.suggestions.map((s) => [s.text, s.preview ?? "", s.priority ?? "", s.connectionIcon ?? ""])
+ );
+ // Only update state if suggestions actually changed (avoids re-render flicker),
+ // except for a manual refresh where the user expects visible feedback.
+ if (options?.force || newSignature !== prevSignatureRef.current) {
+ prevSignatureRef.current = newSignature;
setSuggestions(data.suggestions);
}
setMode(data.mode as ActivityMode);
@@ -80,7 +83,7 @@ export function useAutoSuggestions() {
try {
const result = await commands.forceRegenerateSuggestions();
if (result.status === "ok") {
- applySuggestions(result.data);
+ applySuggestions(result.data, { force: true });
}
} catch (err) {
console.error("force refresh failed:", err);
diff --git a/apps/screenpipe-app-tauri/lib/source-citations.ts b/apps/screenpipe-app-tauri/lib/source-citations.ts
index 8a16d1e9c..6d8509a22 100644
--- a/apps/screenpipe-app-tauri/lib/source-citations.ts
+++ b/apps/screenpipe-app-tauri/lib/source-citations.ts
@@ -5,6 +5,7 @@
export type SourceCitationKind =
| "screenpipe"
| "database"
+ | "connector"
| "web"
| "file"
| "memory"
@@ -71,7 +72,9 @@ export function formatSourceCitationsMarkdown(citations: SourceCitation[]): stri
function sourceCitationsFromToolCall(toolCall: ToolCallLike | undefined): SourceCitation[] {
if (!toolCall || toolCall.isError === true || toolCall.isRunning === true) return [];
- const toolName = typeof toolCall.toolName === "string" ? toolCall.toolName : "unknown";
+ const toolName = normalizeToolName(
+ typeof toolCall.toolName === "string" ? toolCall.toolName : "unknown"
+ );
const args = isObject(toolCall.args) ? toolCall.args : {};
const resultText = resultToText(toolCall.result);
@@ -88,6 +91,12 @@ function sourceCitationsFromToolCall(toolCall: ToolCallLike | undefined): Source
return path ? [fileCitation(path, "Read")] : [];
}
+ if (toolName === "write" || toolName === "edit") {
+ const path = stringArg(args, "path") ?? stringArg(args, "file_path") ?? stringArg(args, "filePath");
+ const verb = toolName === "write" ? "Wrote" : "Edited";
+ return path ? [fileCitation(path, verb)] : [];
+ }
+
if (toolName === "grep" || toolName === "rg") {
const pattern = stringArg(args, "pattern");
const path = stringArg(args, "path") || stringArg(args, "glob");
@@ -115,7 +124,7 @@ function webSearchCitations(
resultText: string
): SourceCitation[] {
const query = stringArg(args, "query");
- const urls = [...extractStructuredSources(result), ...extractWebLinks(resultText)];
+ const urls = resultLinks(result, resultText);
if (urls.length > 0) {
return dedupeLinks(urls).slice(0, 6).map((link) => ({
id: stableId(["web", link.url]),
@@ -177,6 +186,17 @@ function bashCitations(command: string, resultText: string): SourceCitation[] {
});
}
+ for (const link of extractStructuredSourcesFromText(resultText).slice(0, 6)) {
+ if (isLocalScreenpipeUrl(link.url)) continue;
+ citations.push({
+ id: stableId(["web-result", link.url]),
+ kind: "web",
+ title: link.title || hostname(link.url) || "Web source",
+ subtitle: "tool result",
+ href: link.url,
+ });
+ }
+
const filePaths = extractFilePathsFromCommand(command);
for (const path of filePaths) {
citations.push(fileCitation(path, "Local file"));
@@ -198,7 +218,7 @@ function screenpipeApiCitation(call: string): SourceCitation {
const path = extractPath(call);
const query = extractQuery(call);
const title = screenpipeTitle(path);
- const kind: SourceCitationKind = path === "/raw_sql" ? "database" : "screenpipe";
+ const kind = screenpipeKind(path);
return {
id: stableId(["screenpipe", path, query]),
@@ -208,14 +228,29 @@ function screenpipeApiCitation(call: string): SourceCitation {
};
}
+function screenpipeKind(path: string): SourceCitationKind {
+ if (path === "/raw_sql") return "database";
+ if (path === "/memories") return "memory";
+ if (path.startsWith("/connections/")) return "connector";
+ return "screenpipe";
+}
+
function screenpipeTitle(path: string): string {
if (path === "/search") return "Screenpipe search";
if (path === "/activity-summary") return "Activity summary";
if (path === "/raw_sql") return "Local database query";
+ if (path === "/memories") return "Screenpipe memories";
+ if (path.startsWith("/connections/perplexity/")) return "Perplexity search";
+ if (path.startsWith("/connections/google-calendar/") || path.startsWith("/connections/calendar/")) {
+ return "Google Calendar events";
+ }
+ if (path.startsWith("/connections/notion")) return "Notion connection";
+ if (path.startsWith("/connections/obsidian")) return "Obsidian connection";
if (path.startsWith("/meetings")) return "Meeting data";
if (path.startsWith("/frames")) return "Frame data";
if (path.startsWith("/speakers")) return "Speaker data";
if (path === "/health") return "Screenpipe health";
+ if (path.startsWith("/connections/")) return `${titleCase(path.split("/")[2] ?? "connector")} connection`;
return "Screenpipe API";
}
@@ -239,8 +274,24 @@ function screenpipeSubtitle(path: string, query: string): string | undefined {
return "local screenpipe data";
}
+ if (path === "/memories") {
+ return params.q ? `memory query: ${truncate(params.q, 60)}` : limitSubtitle(params.limit);
+ }
+
+ if (path.startsWith("/connections/perplexity/")) {
+ return "external web context via Screenpipe connection";
+ }
+
+ if (path.startsWith("/connections/google-calendar/") || path.startsWith("/connections/calendar/")) {
+ return timeRange(params.start_time ?? params.start, params.end_time ?? params.end) ?? limitSubtitle(params.limit);
+ }
+
+ if (path.startsWith("/connections/")) {
+ return "external app connection";
+ }
+
if (params.limit) {
- return `limit ${params.limit}`;
+ return limitSubtitle(params.limit);
}
return undefined;
@@ -291,6 +342,12 @@ function normalizeExplicitCitations(value: unknown): SourceCitation[] {
return dedupeCitations(citations);
}
+function normalizeToolName(toolName: string): string {
+ return toolName
+ .replace(/^tool_functions[._-]?/, "")
+ .replace(/^toolfunctions[._-]?/, "");
+}
+
function extractScreenpipeApiCalls(command: string): string[] {
const matches = command.match(
/(?:https?:\/\/)?(?:localhost|127\.0\.0\.1):3030\/[^\s"'`)<]+/g
@@ -321,22 +378,45 @@ function extractWebLinks(text: string): Array<{ title?: string; url: string }> {
function extractStructuredSources(result: unknown): Array<{ title?: string; url: string }> {
if (!isObject(result)) return [];
const details = isObject(result.details) ? result.details : undefined;
- const sources = Array.isArray(details?.sources) ? details.sources : undefined;
- if (!sources) return [];
+ const sourceArrays = [
+ Array.isArray(details?.sources) ? details.sources : undefined,
+ Array.isArray(result.sources) ? result.sources : undefined,
+ Array.isArray(result.search_results) ? result.search_results : undefined,
+ Array.isArray(result.citations) ? result.citations : undefined,
+ ].filter((sources): sources is unknown[] => Array.isArray(sources));
const links: Array<{ title?: string; url: string }> = [];
- for (const source of sources) {
- if (!isObject(source) || typeof source.url !== "string") continue;
- const url = cleanUrl(source.url);
- if (!url) continue;
- links.push({
- title: typeof source.title === "string" ? source.title.trim() : undefined,
- url,
- });
+ for (const sources of sourceArrays) {
+ for (const source of sources) {
+ if (!isObject(source) || typeof source.url !== "string") continue;
+ const url = cleanUrl(source.url);
+ if (!url) continue;
+ links.push({
+ title: typeof source.title === "string" ? source.title.trim() : undefined,
+ url,
+ });
+ }
}
return links;
}
+function resultLinks(result: unknown, resultText: string): Array<{ title?: string; url: string }> {
+ return dedupeLinks([
+ ...extractStructuredSources(result),
+ ...extractStructuredSourcesFromText(resultText),
+ ...extractWebLinks(resultText),
+ ]);
+}
+
+function extractStructuredSourcesFromText(text: string): Array<{ title?: string; url: string }> {
+ if (!text.trim()) return [];
+ try {
+ return extractStructuredSources(JSON.parse(text));
+ } catch {
+ return [];
+ }
+}
+
function dedupeLinks(links: Array<{ title?: string; url: string }>): Array<{ title?: string; url: string }> {
const seen = new Set<string>();
const out: Array<{ title?: string; url: string }> = [];
@@ -468,7 +548,7 @@ function stableId(parts: Array<string | undefined>): string {
}
function isSourceKind(kind: string): kind is SourceCitationKind {
- return ["screenpipe", "database", "web", "file", "memory", "pipe", "command"].includes(kind);
+ return ["screenpipe", "database", "connector", "web", "file", "memory", "pipe", "command"].includes(kind);
}
function isObject(value: unknown): value is Record<string, unknown> {
@@ -538,6 +618,18 @@ function truncate(text: string, max: number): string {
return text.length > max ? `${text.slice(0, Math.max(0, max - 1))}...` : text;
}
+function limitSubtitle(limit: string | undefined): string | undefined {
+ return limit ? `limit ${limit}` : undefined;
+}
+
+function titleCase(value: string): string {
+ return value
+ .split(/[-_]+/)
+ .filter(Boolean)
+ .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)
+ .join(" ");
+}
+
function safeDecode(value: string): string {
try {
return decodeURIComponent(value);