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

eat(notifications): add copy and source links for pipe alerts (#4222)

Ansh Groverb507838066d4
diff --git a/apps/screenpipe-app-tauri/app/notification-panel/page.tsx b/apps/screenpipe-app-tauri/app/notification-panel/page.tsx
index 428ef3f4e..d42f4a95d 100644
--- a/apps/screenpipe-app-tauri/app/notification-panel/page.tsx
+++ b/apps/screenpipe-app-tauri/app/notification-panel/page.tsx
@@ -17,6 +17,7 @@ import {
import { showChatWithPrefill } from "@/lib/chat-utils";
import localforage from "localforage";
import { localFetch } from "@/lib/api";
+import { Bell, Check, Copy, ExternalLink } from "lucide-react";
interface NotificationAction {
label: string;
@@ -44,6 +45,9 @@ interface NotificationPayload {
actions: NotificationAction[];
autoDismissMs?: number;
pipe_name?: string;
+ source_session_id?: string;
+ source_message_id?: string;
+ source_url?: string;
}
function windowForDeeplink(url: string) {
@@ -78,6 +82,10 @@ async function openNotificationLink(href: string) {
await open(raw);
}
+function notificationClipboardText(payload: NotificationPayload): string {
+ return `${payload.title}\n\n${payload.body}`.trim();
+}
+
export default function NotificationPanelPage() {
const [payload, setPayload] = useState<NotificationPayload | null>(null);
const [visible, setVisible] = useState(false);
@@ -89,9 +97,11 @@ export default function NotificationPanelPage() {
>("idle");
const [restartError, setRestartError] = useState<string | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const autoDismissMsRef = useRef(20000);
const hoveredRef = useRef(false);
const pausedProgressRef = useRef<number | null>(null);
+ const [copied, setCopied] = useState(false);
const hide = useCallback(
async (auto: boolean) => {
@@ -313,6 +323,48 @@ export default function NotificationPanelPage() {
[payload?.type, payload?.id, payload?.pipe_name, hide]
);
+ const openSource = useCallback(async () => {
+ if (!payload?.source_url) return;
+ const url = payload.source_url;
+ if (url.startsWith("screenpipe://")) {
+ await commands.showWindowActivated(windowForDeeplink(url));
+ await new Promise((r) => setTimeout(r, 150));
+ await emit("deep-link-received", url);
+ await hide(false);
+ return;
+ }
+ try {
+ const { open } = await import("@tauri-apps/plugin-shell");
+ await open(url);
+ await hide(false);
+ } catch (e) {
+ console.error("notification source open failed:", e);
+ }
+ }, [payload?.source_url, hide]);
+
+ const copyNotification = useCallback(async () => {
+ if (!payload) return;
+ try {
+ await commands.copyTextToClipboard(notificationClipboardText(payload));
+ if (copyResetRef.current) clearTimeout(copyResetRef.current);
+ setCopied(true);
+ copyResetRef.current = setTimeout(() => setCopied(false), 1400);
+ posthog.capture("notification_copied", {
+ type: payload.type,
+ id: payload.id,
+ });
+ } catch (e) {
+ console.error("notification copy failed:", e);
+ }
+ }, [payload]);
+
+ useEffect(() => {
+ setCopied(false);
+ return () => {
+ if (copyResetRef.current) clearTimeout(copyResetRef.current);
+ };
+ }, [payload?.id]);
+
// Listen for notification payloads from Rust
useEffect(() => {
const unlisten = listen<string>("notification-panel-update", (event) => {
@@ -536,11 +588,14 @@ export default function NotificationPanelPage() {
{/* Body */}
<div className="notif-body" style={{ padding: "8px 14px", flex: 1, overflow: "auto", minHeight: 0 }}>
<div
+ onClick={payload.source_url ? openSource : undefined}
+ title={payload.source_url ? "open source chat" : undefined}
style={{
fontSize: "12px",
fontWeight: 500,
marginBottom: "4px",
color: "rgba(0, 0, 0, 0.9)",
+ cursor: payload.source_url ? "pointer" : "default",
}}
>
{payload.title}
@@ -551,6 +606,7 @@ export default function NotificationPanelPage() {
fontSize: "11px",
lineHeight: "1.4",
color: "rgba(0, 0, 0, 0.5)",
+ userSelect: "text",
}}
>
<ReactMarkdown
@@ -698,66 +754,95 @@ export default function NotificationPanelPage() {
</div>
)}
- {/* Manage / Mute footer */}
+ {/* Popup utility footer */}
<div
style={{
display: "flex",
alignItems: "center",
padding: "4px 14px 8px 14px",
- gap: "8px",
+ gap: "12px",
borderTop: "1px solid rgba(0, 0, 0, 0.06)",
}}
>
- <span
+ <button
+ onClick={copyNotification}
+ title="copy notification"
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: 0,
+ border: "none",
+ background: "none",
+ flexShrink: 0,
+ fontSize: "9px",
+ lineHeight: 1,
+ color: "rgba(0, 0, 0, 0.3)",
+ cursor: "pointer",
+ fontFamily: '"IBM Plex Mono", monospace',
+ whiteSpace: "nowrap",
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.6)")}
+ onMouseLeave={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.3)")}
+ >
+ {copied ? <Check size={12} strokeWidth={1.8} /> : <Copy size={12} strokeWidth={1.8} />}
+ {copied ? "copied" : "copy"}
+ </button>
+ {payload.source_url && (
+ <button
+ onClick={openSource}
+ title="open source chat"
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "4px",
+ padding: 0,
+ border: "none",
+ background: "none",
+ flexShrink: 0,
+ fontSize: "9px",
+ lineHeight: 1,
+ color: "rgba(0, 0, 0, 0.3)",
+ cursor: "pointer",
+ fontFamily: '"IBM Plex Mono", monospace',
+ whiteSpace: "nowrap",
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.6)")}
+ onMouseLeave={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.3)")}
+ >
+ <ExternalLink size={12} strokeWidth={1.8} />
+ source
+ </button>
+ )}
+ <button
onClick={async () => {
await hide(false);
await emit("navigate", { url: "/home?section=notifications" });
try { await commands.showWindow({ Home: { page: null } }); } catch {}
}}
+ title="manage notification settings"
style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "4px",
+ marginLeft: "auto",
+ padding: 0,
+ border: "none",
+ background: "none",
+ flexShrink: 0,
fontSize: "9px",
+ lineHeight: 1,
color: "rgba(0, 0, 0, 0.3)",
cursor: "pointer",
fontFamily: '"IBM Plex Mono", monospace',
+ whiteSpace: "nowrap",
}}
onMouseEnter={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.6)")}
onMouseLeave={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.3)")}
>
- ⚙ manage
- </span>
- {payload.pipe_name && (
- <>
- <span style={{ fontSize: "9px", color: "rgba(0, 0, 0, 0.15)" }}>·</span>
- <span
- onClick={async () => {
- try {
- const raw = await localforage.getItem<string>("screenpipe-settings");
- const settings = raw ? JSON.parse(raw) : {};
- const prefs = settings.notificationPrefs || {
- captureStalls: true, appUpdates: true,
- pipeSuggestions: true, pipeNotifications: true, mutedPipes: [],
- };
- if (!prefs.mutedPipes.includes(payload.pipe_name!)) {
- prefs.mutedPipes.push(payload.pipe_name!);
- }
- settings.notificationPrefs = prefs;
- await localforage.setItem("screenpipe-settings", JSON.stringify(settings));
- } catch {}
- await hide(false);
- }}
- style={{
- fontSize: "9px",
- color: "rgba(0, 0, 0, 0.3)",
- cursor: "pointer",
- fontFamily: '"IBM Plex Mono", monospace',
- }}
- onMouseEnter={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.6)")}
- onMouseLeave={(e) => (e.currentTarget.style.color = "rgba(0, 0, 0, 0.3)")}
- >
- mute {payload.pipe_name}
- </span>
- </>
- )}
+ <Bell size={12} strokeWidth={1.8} />
+ manage
+ </button>
</div>
{/* Progress bar */}
diff --git a/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts b/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
index 13fcedc8f..0697fddeb 100644
--- a/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
+++ b/apps/screenpipe-app-tauri/components/__tests__/pipe-ndjson-to-chat.test.ts
@@ -35,6 +35,21 @@ describe("parsePipeNdjsonToMessages", () => {
expect(msgs[1].content).toBe("I'll help you sync screenpipe");
});
+ it("preserves notification source markers alongside agent_end messages", () => {
+ const stdout = [
+ '{"type":"message_start","message":{"role":"assistant","content":[]}}',
+ '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"draft"}}',
+ '{"type":"notification_sent","id":"notification-abc","title":"Report ready","body":"open the report","timestamp":1772387604000}',
+ '{"type":"agent_end","messages":[{"role":"user","content":[{"type":"text","text":"run pipe"}]},{"role":"assistant","content":[{"type":"text","text":"final answer"}]}]}',
+ ].join("\n");
+
+ const msgs = parsePipeNdjsonToMessages(stdout);
+ expect(msgs.map((m) => m.id)).toContain("notification-abc");
+ const marker = msgs.find((m) => m.id === "notification-abc");
+ expect(marker?.content).toContain("Report ready");
+ expect(marker?.content).toContain("open the report");
+ });
+
// ─── user message extraction ──────────────────────────────────────
it("extracts user message content from message_start", () => {
diff --git a/apps/screenpipe-app-tauri/components/deeplink-handler.tsx b/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
index 6a87c7c10..4cd3f1a9e 100644
--- a/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
+++ b/apps/screenpipe-app-tauri/components/deeplink-handler.tsx
@@ -193,6 +193,28 @@ export function DeeplinkHandler() {
}
}
+ // Handle chat deep links:
+ // screenpipe://chat/<conversationId>?message=<messageId>
+ // screenpipe://chat?conversation=<conversationId>&message=<messageId>
+ if (parsedUrl.host === "chat" || parsedUrl.pathname?.startsWith("/chat/")) {
+ const pathId =
+ parsedUrl.host === "chat"
+ ? parsedUrl.pathname.replace(/^\/+/, "").split("/")[0]
+ : parsedUrl.pathname.replace(/^\/chat\/?/, "").split("/")[0];
+ const conversationId = parsedUrl.searchParams.get("conversation") || pathId;
+ if (conversationId) {
+ const decodedConversationId = decodeURIComponent(conversationId);
+ const messageId = parsedUrl.searchParams.get("message") || undefined;
+ await commands.showWindowActivated({ Home: { page: "home" } });
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ await emit("chat-load-conversation", {
+ conversationId: decodedConversationId,
+ targetWindow: "home",
+ ...(messageId ? { focusMessageId: decodeURIComponent(messageId) } : {}),
+ });
+ }
+ }
+
// Handle in-app file viewer: screenpipe://view?path=<encoded-path>
// Notification bodies with markdown links to local files are rewritten
// to this scheme by the /notify route in src-tauri/src/notifications/rewrite.rs
diff --git a/apps/screenpipe-app-tauri/components/notification-bell.tsx b/apps/screenpipe-app-tauri/components/notification-bell.tsx
index fe0b904c6..340dd4187 100644
--- a/apps/screenpipe-app-tauri/components/notification-bell.tsx
+++ b/apps/screenpipe-app-tauri/components/notification-bell.tsx
@@ -4,8 +4,8 @@
"use client";
-import { useState, useEffect, useCallback } from "react";
-import { Bell, ChevronRight, ChevronDown, MessageSquare, X } from "lucide-react";
+import { useState, useEffect, useCallback, useRef } from "react";
+import { Bell, Check, ChevronRight, ChevronDown, Copy, ExternalLink, MessageSquare, X } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { notificationUrlTransform, openScreenpipeViewerLink } from "@/components/markdown";
import remarkGfm from "remark-gfm";
@@ -19,6 +19,7 @@ import {
import { useRouter } from "next/navigation";
import { showChatWithPrefill } from "@/lib/chat-utils";
import { invoke } from "@tauri-apps/api/core";
+import { emit } from "@tauri-apps/api/event";
interface NotificationEntry {
id: string;
@@ -26,6 +27,9 @@ interface NotificationEntry {
title: string;
body: string;
pipe_name?: string;
+ source_session_id?: string;
+ source_message_id?: string;
+ source_url?: string;
timestamp: string;
read: boolean;
}
@@ -87,6 +91,20 @@ async function openNotificationLink(href: string) {
await open(raw);
}
+async function openNotificationSource(url: string) {
+ if (!url.trim()) return;
+ if (url.startsWith("screenpipe://")) {
+ await emit("deep-link-received", url);
+ return;
+ }
+ const { open } = await import("@tauri-apps/plugin-shell");
+ await open(url);
+}
+
+function notificationClipboardText(entry: NotificationEntry): string {
+ return `${entry.title}\n\n${entry.body}`.trim();
+}
+
function buildNotificationDisplayLabel(title: string): string {
const normalized = title.replace(/\s+/g, " ").trim();
if (!normalized) return "Ask AI about notification";
@@ -98,8 +116,16 @@ export function NotificationBell() {
const [history, setHistory] = useState<NotificationEntry[]>([]);
const [open, setOpen] = useState(false);
const [expandedId, setExpandedId] = useState<string | null>(null);
+ const [copiedId, setCopiedId] = useState<string | null>(null);
+ const copiedResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const router = useRouter();
+ useEffect(() => {
+ return () => {
+ if (copiedResetRef.current) clearTimeout(copiedResetRef.current);
+ };
+ }, []);
+
const loadHistory = useCallback(async () => {
try {
const res = await notificationFetch("/notifications");
@@ -270,7 +296,7 @@ export function NotificationBell() {
</span>
</div>
{!isExpanded && entry.body && (
- <div className="text-[10px] text-muted-foreground mt-0.5 line-clamp-2 pl-4 [&_p]:inline [&_strong]:text-foreground [&_a]:underline">
+ <div className="select-text text-[10px] text-muted-foreground mt-0.5 line-clamp-2 pl-4 [&_p]:inline [&_strong]:text-foreground [&_a]:underline">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
urlTransform={notificationUrlTransform}
@@ -324,7 +350,7 @@ export function NotificationBell() {
className="px-3 pb-2 pl-7"
>
{entry.body && (
- <div className="text-[10px] text-muted-foreground leading-relaxed mb-2 [&_p]:mb-1 [&_p:last-child]:mb-0 [&_strong]:text-foreground [&_code]:bg-muted [&_code]:px-1 [&_code]:text-[9px] [&_ul]:pl-4 [&_ul]:my-0.5 [&_li]:my-0">
+ <div className="select-text text-[10px] text-muted-foreground leading-relaxed mb-2 [&_p]:mb-1 [&_p:last-child]:mb-0 [&_strong]:text-foreground [&_code]:bg-muted [&_code]:px-1 [&_code]:text-[9px] [&_ul]:pl-4 [&_ul]:my-0.5 [&_li]:my-0">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
urlTransform={notificationUrlTransform}
@@ -356,29 +382,67 @@ export function NotificationBell() {
{entry.pipe_name}
</span>
)}
- <button
- data-testid={`notification-bell-ask-ai-${entry.id}`}
- onClick={(e) => {
- e.stopPropagation();
- posthog.capture("notification_bell_ask_ai", {
- notification_type: entry.type,
- pipe_name: entry.pipe_name,
- title: entry.title,
- });
- setOpen(false);
- showChatWithPrefill({
- context: `notification from ${entry.pipe_name || "screenpipe"}:\n\n**${entry.title}**\n${entry.body}`,
- prompt: `tell me more about this: "${entry.title}"`,
- displayLabel: buildNotificationDisplayLabel(entry.title),
- autoSend: true,
- source: `notification-bell-${entry.id}`,
- });
- }}
- className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
- >
- <MessageSquare className="w-3 h-3" />
- ask ai about this
- </button>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <button
+ data-testid={`notification-bell-copy-${entry.id}`}
+ onClick={async (e) => {
+ e.stopPropagation();
+ await commands.copyTextToClipboard(notificationClipboardText(entry));
+ if (copiedResetRef.current) clearTimeout(copiedResetRef.current);
+ setCopiedId(entry.id);
+ copiedResetRef.current = setTimeout(() => setCopiedId(null), 1400);
+ posthog.capture("notification_bell_copy", {
+ notification_type: entry.type,
+ pipe_name: entry.pipe_name,
+ });
+ }}
+ className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ {copiedId === entry.id ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
+ {copiedId === entry.id ? "copied" : "copy"}
+ </button>
+ {entry.source_url && (
+ <button
+ data-testid={`notification-bell-source-${entry.id}`}
+ onClick={async (e) => {
+ e.stopPropagation();
+ setOpen(false);
+ posthog.capture("notification_bell_open_source", {
+ notification_type: entry.type,
+ pipe_name: entry.pipe_name,
+ });
+ await openNotificationSource(entry.source_url!);
+ }}
+ className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ <ExternalLink className="w-3 h-3" />
+ source
+ </button>
+ )}
+ <button
+ data-testid={`notification-bell-ask-ai-${entry.id}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ posthog.capture("notification_bell_ask_ai", {
+ notification_type: entry.type,
+ pipe_name: entry.pipe_name,
+ title: entry.title,
+ });
+ setOpen(false);
+ showChatWithPrefill({
+ context: `notification from ${entry.pipe_name || "screenpipe"}:\n\n**${entry.title}**\n${entry.body}`,
+ prompt: `tell me more about this: "${entry.title}"`,
+ displayLabel: buildNotificationDisplayLabel(entry.title),
+ autoSend: true,
+ source: `notification-bell-${entry.id}`,
+ });
+ }}
+ className="flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ <MessageSquare className="w-3 h-3" />
+ ask ai
+ </button>
+ </div>
</div>
)}
</div>
diff --git a/apps/screenpipe-app-tauri/components/notification-handler.tsx b/apps/screenpipe-app-tauri/components/notification-handler.tsx
index 539f1ea72..244daa4de 100644
--- a/apps/screenpipe-app-tauri/components/notification-handler.tsx
+++ b/apps/screenpipe-app-tauri/components/notification-handler.tsx
@@ -105,6 +105,9 @@ const NotificationHandler: React.FC = () => {
title: data.title,
body: data.body,
pipe_name: data.pipe_name,
+ source_session_id: data.source_session_id,
+ source_message_id: data.source_message_id,
+ source_url: data.source_url,
timestamp: new Date().toISOString(),
read: false,
};
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index b31954666..0d50e60d4 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -2739,6 +2739,7 @@ export function StandaloneChat({
const [queuedActionPromptId, setQueuedActionPromptId] = useState<string | null>(null);
const queuedScrollRef = useRef<HTMLDivElement | null>(null);
const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);
+ const [highlightedMessageId, setHighlightedMessageId] = useState<string | null>(null);
const [openMessageMenuId, setOpenMessageMenuId] = useState<string | null>(null);
// Cursor-style inline edit: click a sent user message to tweak and resend
const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
@@ -2867,6 +2868,35 @@ export function StandaloneChat({
// (e.g. a meeting note) that would otherwise also stage into the composer.
const dropRootRef = useRef<HTMLDivElement>(null);
+ const focusMessageById = useCallback((messageId: string) => {
+ let attempts = 0;
+ const findAndFocus = () => {
+ const container = scrollContainerRef.current;
+ const target = container
+ ? Array.from(container.querySelectorAll<HTMLElement>("[data-message-id]"))
+ .find((el) => el.dataset.messageId === messageId)
+ : null;
+
+ if (target) {
+ stickToBottomRef.current = false;
+ setIsUserScrolledUp(true);
+ target.scrollIntoView({ behavior: attempts > 1 ? "smooth" : "auto", block: "center" });
+ setHighlightedMessageId(messageId);
+ window.setTimeout(() => {
+ setHighlightedMessageId((current) => (current === messageId ? null : current));
+ }, 2400);
+ return;
+ }
+
+ attempts += 1;
+ if (attempts <= 24) {
+ window.requestAnimationFrame(findAndFocus);
+ }
+ };
+
+ window.requestAnimationFrame(findAndFocus);
+ }, []);
+
const [scheduleDialogMessage, setScheduleDialogMessage] = useState<{ prompt: string; response: string } | null>(null);
const [prefillContext, setPrefillContext] = useState<string | null>(null);
const [prefillSource, setPrefillSource] = useState<string>("search");
@@ -3851,7 +3881,7 @@ export function StandaloneChat({
useEffect(() => {
const unlisten = listen<ChatLoadConversationPayload>("chat-load-conversation", async (event) => {
- const { conversationId: convId, targetWindow } = event.payload;
+ const { conversationId: convId, targetWindow, focusMessageId } = event.payload;
const windowLabel = getCurrentWindow().label;
if (!shouldHandleChatLoadConversationForWindow(
{ conversationId: convId, targetWindow },
@@ -3860,10 +3890,13 @@ export function StandaloneChat({
return;
}
await openConversationLocally(convId);
+ if (focusMessageId) {
+ focusMessageById(focusMessageId);
+ }
});
return () => { unlisten.then((fn) => fn()); };
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [openConversationLocally]);
+ }, [openConversationLocally, focusMessageById]);
// Cmd+N / Ctrl+N from home/page emits this so the user can immediately type
// after a new chat is created without having to click into the textarea.
@@ -9007,8 +9040,9 @@ export function StandaloneChat({
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.2 }}
className={cn(
- "relative flex min-w-0",
- message.role === "user" ? "justify-end" : "justify-start"
+ "relative flex min-w-0 transition-[background-color,box-shadow] duration-150",
+ message.role === "user" ? "justify-end" : "justify-start",
+ message.id === highlightedMessageId && "bg-muted/30 ring-1 ring-foreground/30"
)}
data-testid={`chat-message-${message.role}`}
data-message-id={message.id}
diff --git a/apps/screenpipe-app-tauri/lib/chat-utils.ts b/apps/screenpipe-app-tauri/lib/chat-utils.ts
index 944131374..948dfec5c 100644
--- a/apps/screenpipe-app-tauri/lib/chat-utils.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-utils.ts
@@ -86,6 +86,7 @@ export type ChatTargetWindow = "home" | "chat";
export interface ChatLoadConversationPayload {
conversationId: string;
targetWindow?: ChatTargetWindow;
+ focusMessageId?: string;
}
export const RECENT_CHAT_SEARCH_HANDOFF_EVENT = "recent-chat-search-handoff";
diff --git a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-watch-writer.test.ts b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-watch-writer.test.ts
index 0352bd96f..bed52be1b 100644
--- a/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-watch-writer.test.ts
+++ b/apps/screenpipe-app-tauri/lib/events/__tests__/pipe-watch-writer.test.ts
@@ -204,6 +204,33 @@ describe("pipe-watch-writer: agent_end takes precedence", () => {
expect(session.isLoading).toBe(false);
});
+ it("keeps notification markers when agent_end replaces streamed messages", () => {
+ seedPipeWatchSession();
+ __testing.inject(
+ env({
+ type: "notification_sent",
+ id: "notification-abc",
+ title: "Report ready",
+ body: "open the report",
+ }),
+ );
+ __testing.inject(
+ env({
+ type: "agent_end",
+ messages: [
+ { role: "user", content: [{ type: "text", text: "run pipe" }] },
+ { role: "assistant", content: [{ type: "text", text: "final answer" }] },
+ ],
+ }),
+ );
+
+ const messages = useChatStore.getState().sessions[SID]!.messages! as any[];
+ expect(messages.map((m) => m.id)).toContain("notification-abc");
+ const marker = messages.find((m) => m.id === "notification-abc");
+ expect(marker.content).toContain("Report ready");
+ expect(marker.content).toContain("open the report");
+ });
+
it("does not render Codex-style function returns as chat messages", () => {
seedPipeWatchSession();
__testing.inject(
diff --git a/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts b/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts
index e5e9d2da1..dec99e8c0 100644
--- a/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts
+++ b/apps/screenpipe-app-tauri/lib/events/pipe-watch-writer.ts
@@ -115,6 +115,15 @@ function apply(sid: string, payload: AgentInnerEvent): void {
| { type?: string; delta?: string; content?: string }
| undefined;
+ if (t === "notification_sent") {
+ store.actions.appendMessage(sid, notificationEventToMessage(payload));
+ store.actions.patch(sid, {
+ draft: false,
+ updatedAt: Date.now(),
+ });
+ return;
+ }
+
// ── text_delta (flat) and message_update wrapping text_delta ────────
const isTextDelta =
(t === "text_delta" ||
@@ -312,8 +321,11 @@ function apply(sid: string, payload: AgentInnerEvent): void {
const messages = (payload as any).messages;
if (Array.isArray(messages) && messages.length > 0) {
const reconstructed = reconstructFromAgentEnd(messages);
- if (reconstructed.length > 0) {
- store.actions.setMessages(sid, reconstructed as any);
+ const notificationMarkers = ((useChatStore.getState().sessions[sid]?.messages as any[]) ?? [])
+ .filter(isNotificationMessage);
+ const merged = appendUniqueNotificationMessages(reconstructed, notificationMarkers);
+ if (merged.length > 0) {
+ store.actions.setMessages(sid, merged as any);
}
}
store.actions.endTurn(sid);
@@ -325,6 +337,39 @@ function apply(sid: string, payload: AgentInnerEvent): void {
// don't duplicate that here.
}
+function notificationEventToMessage(payload: AgentInnerEvent): any {
+ const evt = payload as any;
+ const title = typeof evt.title === "string" ? evt.title.trim() : "notification";
+ const body = typeof evt.body === "string" ? evt.body.trim() : "";
+ const timestamp =
+ typeof evt.timestamp === "number"
+ ? evt.timestamp
+ : typeof evt.timestamp === "string"
+ ? new Date(evt.timestamp).getTime()
+ : Date.now();
+ const content = [`notification sent`, title ? `**${title}**` : "", body]
+ .filter(Boolean)
+ .join("\n\n");
+ return {
+ id: typeof evt.id === "string" && evt.id ? evt.id : `notification-${Date.now()}`,
+ role: "assistant",
+ content,
+ timestamp: Number.isFinite(timestamp) ? timestamp : Date.now(),
+ contentBlocks: [{ type: "text", text: content }],
+ };
+}
+
+function isNotificationMessage(message: any): boolean {
+ return typeof message?.id === "string" && message.id.startsWith("notification-");
+}
+
+function appendUniqueNotificationMessages(messages: any[], notifications: any[]): any[] {
+ if (notifications.length === 0) return messages;
+ const seen = new Set(messages.map((m) => m.id));
+ const unique = notifications.filter((m) => !seen.has(m.id));
+ return unique.length > 0 ? [...messages, ...unique] : messages;
+}
+
/** Reconstruct ChatMessage[] from an `agent_end` event's `messages`
* payload — the pipe agent's complete view of the conversation. We
* prefer this over the streaming reconstruction because it carries
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-notification-panel.ts b/apps/screenpipe-app-tauri/lib/hooks/use-notification-panel.ts
index cfd656c67..a42d9777b 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-notification-panel.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-notification-panel.ts
@@ -28,6 +28,9 @@ export interface NotificationPayload {
actions: NotificationAction[];
autoDismissMs?: number;
pipe_name?: string;
+ source_session_id?: string;
+ source_message_id?: string;
+ source_url?: string;
}
export async function showNotificationPanel(
diff --git a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
index 45068c131..a03cfe7da 100644
--- a/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
+++ b/apps/screenpipe-app-tauri/lib/pipe-ndjson-to-chat.ts
@@ -51,6 +51,7 @@ function extractToolCalls(content: any[], msgIndex: number): any[] {
*/
export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
let agentEndMessages: any[] | null = null;
+ const notificationMessages: ChatMessage[] = [];
let messageCounter = 0;
const ts = Date.now();
@@ -63,6 +64,9 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
if (evt.type === "agent_end" && Array.isArray(evt.messages)) {
agentEndMessages = evt.messages;
}
+ if (evt.type === "notification_sent") {
+ notificationMessages.push(notificationEventToMessage(evt, notificationMessages.length, ts));
+ }
} catch {
continue;
}
@@ -184,7 +188,7 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
flushPendingAssistant();
if (messages.some((m) => m.role === "assistant" && (m.content?.trim() || (m.contentBlocks?.length ?? 0) > 0))) {
- return messages;
+ return appendUniqueNotificationMessages(messages, notificationMessages);
}
}
@@ -256,6 +260,12 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
try { evt = JSON.parse(trimmed); } catch { continue; }
const evtType = evt.type;
+ if (evtType === "notification_sent") {
+ flushAssistant();
+ messages.push(notificationEventToMessage(evt, messageCounter++, ts));
+ continue;
+ }
+
if (evtType === "message_start" && evt.message?.role === "user") {
flushAssistant();
const text = extractText(evt.message.content);
@@ -374,6 +384,37 @@ export function parsePipeNdjsonToMessages(raw: string): ChatMessage[] {
return messages;
}
+function appendUniqueNotificationMessages(
+ messages: ChatMessage[],
+ notifications: ChatMessage[],
+): ChatMessage[] {
+ if (notifications.length === 0) return messages;
+ const seen = new Set(messages.map((m) => m.id));
+ const unique = notifications.filter((m) => !seen.has(m.id));
+ return unique.length > 0 ? [...messages, ...unique] : messages;
+}
+
+function notificationEventToMessage(evt: any, idx: number, fallbackTs: number): ChatMessage {
+ const title = typeof evt.title === "string" ? evt.title.trim() : "notification";
+ const body = typeof evt.body === "string" ? evt.body.trim() : "";
+ const timestamp =
+ typeof evt.timestamp === "number"
+ ? evt.timestamp
+ : typeof evt.timestamp === "string"
+ ? new Date(evt.timestamp).getTime()
+ : fallbackTs;
+ const content = [`notification sent`, title ? `**${title}**` : "", body]
+ .filter(Boolean)
+ .join("\n\n");
+ return {
+ id: typeof evt.id === "string" && evt.id ? evt.id : `notification-${idx}`,
+ role: "assistant",
+ content,
+ timestamp: Number.isFinite(timestamp) ? timestamp : fallbackTs,
+ contentBlocks: [{ type: "text", text: content }],
+ };
+}
+
function isToolReturnMessage(message: any, text: string): boolean {
const role = message?.role;
if (role === "tool" || role === "toolResult") return true;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs b/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs
index 2e8ff7cd4..86fc6d06d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/notifications/routes.rs
@@ -9,9 +9,10 @@ use super::store::{self, NotificationHistoryEntry};
use crate::server::{ApiResponse, ServerState};
use crate::store::SettingsStore;
use axum::extract::{Path, State};
-use axum::http::StatusCode;
+use axum::http::{HeaderMap, StatusCode};
use axum::Json;
use tauri::AppHandle;
+use tauri::Emitter;
use tracing::{debug, error, info};
/// Read `notificationPrefs.pipeNotifications` from the settings store.
@@ -46,18 +47,21 @@ fn pipe_notifications_enabled_from_extra(
/// `POST /notify` — show a notification panel and persist to disk.
pub async fn send_notification(
State(state): State<ServerState>,
+ headers: HeaderMap,
Json(payload): Json<NotifyPayload>,
) -> Result<Json<ApiResponse>, (StatusCode, String)> {
info!("Received notification request: {:?}", payload);
let panel_id = payload
.id
+ .clone()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let dismiss_ms = payload.auto_dismiss_ms.or(payload.timeout).unwrap_or(20000);
let resolved_type = payload
.notification_type
.clone()
.unwrap_or_else(|| "pipe".to_string());
+ let source = resolve_notification_source_metadata(&payload, &headers, &panel_id);
// Gate pipe-typed alerts behind the `Pipe notifications` toggle.
// Other types (`system`, `captureStalls`, …) self-gate upstream
@@ -85,6 +89,10 @@ pub async fn send_notification(
"body": body,
"actions": payload.actions,
"autoDismissMs": dismiss_ms,
+ "pipe_name": source.pipe_name.clone(),
+ "source_session_id": source.source_session_id.clone(),
+ "source_message_id": source.source_message_id.clone(),
+ "source_url": source.source_url.clone(),
});
// Persist to disk before attempting to show — survives crashes/restarts
@@ -93,10 +101,22 @@ pub async fn send_notification(
notification_type: panel_payload["type"].as_str().unwrap_or("pipe").to_string(),
title: payload.title.clone(),
body: body.clone(),
- pipe_name: None,
+ pipe_name: source.pipe_name.clone(),
+ source_session_id: source.source_session_id.clone(),
+ source_message_id: source.source_message_id.clone(),
+ source_url: source.source_url.clone(),
timestamp: chrono::Utc::now().to_rfc3339(),
read: false,
});
+ emit_notification_source_marker(
+ &state.app_handle,
+ source.source_session_id.as_deref(),
+ source.source_message_id.as_deref(),
+ &panel_id,
+ &payload.title,
+ &body,
+ source.source_url.as_deref(),
+ );
let panel_json = panel_payload.to_string();
@@ -118,6 +138,111 @@ pub async fn send_notification(
}
}
+fn notification_source_session_from_headers(headers: &HeaderMap) -> Option<String> {
+ headers
+ .get("x-screenpipe-session")
+ .and_then(|v| v.to_str().ok())
+ .map(str::trim)
+ .filter(|v| !v.is_empty())
+ .map(ToOwned::to_owned)
+}
+
+#[derive(Debug, PartialEq, Eq)]
+struct NotificationSourceMetadata {
+ source_session_id: Option<String>,
+ source_message_id: Option<String>,
+ source_url: Option<String>,
+ pipe_name: Option<String>,
+}
+
+fn resolve_notification_source_metadata(
+ payload: &NotifyPayload,
+ headers: &HeaderMap,
+ panel_id: &str,
+) -> NotificationSourceMetadata {
+ let source_session_id = payload
+ .source_session_id
+ .clone()
+ .or_else(|| notification_source_session_from_headers(headers));
+ let source_message_id = payload.source_message_id.clone().or_else(|| {
+ source_session_id
+ .as_ref()
+ .map(|_| format!("notification-{panel_id}"))
+ });
+ let source_url = payload.source_url.clone().or_else(|| {
+ source_session_id.as_ref().map(|session_id| {
+ let encoded_session = urlencoding::encode(session_id);
+ if let Some(message_id) = &source_message_id {
+ format!(
+ "screenpipe://chat/{}?message={}",
+ encoded_session,
+ urlencoding::encode(message_id)
+ )
+ } else {
+ format!("screenpipe://chat/{}", encoded_session)
+ }
+ })
+ });
+ let pipe_name = payload.pipe_name.clone().or_else(|| {
+ source_session_id
+ .as_deref()
+ .and_then(pipe_name_from_session_id)
+ });
+
+ NotificationSourceMetadata {
+ source_session_id,
+ source_message_id,
+ source_url,
+ pipe_name,
+ }
+}
+
+fn pipe_name_from_session_id(session_id: &str) -> Option<String> {
+ let rest = session_id.strip_prefix("pipe:")?;
+ let (pipe_name, _) = rest.rsplit_once(':')?;
+ if pipe_name.trim().is_empty() {
+ None
+ } else {
+ Some(pipe_name.to_string())
+ }
+}
+
+fn emit_notification_source_marker(
+ app: &AppHandle,
+ source_session_id: Option<&str>,
+ source_message_id: Option<&str>,
+ notification_id: &str,
+ title: &str,
+ body: &str,
+ source_url: Option<&str>,
+) {
+ let Some(session_id) = source_session_id else {
+ return;
+ };
+ if !session_id.starts_with("pipe:") {
+ return;
+ }
+ let message_id = source_message_id
+ .map(ToOwned::to_owned)
+ .unwrap_or_else(|| format!("notification-{notification_id}"));
+ let event = serde_json::json!({
+ "source": "pipe",
+ "sessionId": session_id,
+ "event": {
+ "type": "notification_sent",
+ "id": message_id,
+ "notification_id": notification_id,
+ "title": title,
+ "body": body,
+ "source_url": source_url,
+ "timestamp": chrono::Utc::now().timestamp_millis(),
+ },
+ });
+ if let Err(e) = app.emit("agent_event", event) {
+ debug!("notify: failed to emit notification source marker: {}", e);
+ }
+}
+
/// `GET /notifications` — list notification history from disk.
pub async fn list() -> Json<Vec<NotificationHistoryEntry>> {
Json(store::read_all())
@@ -169,6 +294,8 @@ pub struct NotifyPayload {
pub title: String,
pub body: String,
pub id: Option<String>,
+ #[serde(default, alias = "pipeName")]
+ pub pipe_name: Option<String>,
#[serde(rename = "type")]
pub notification_type: Option<String>,
#[serde(rename = "autoDismissMs")]
@@ -176,6 +303,12 @@ pub struct NotifyPayload {
pub timeout: Option<u64>,
#[serde(default)]
pub actions: Vec<serde_json::Value>,
+ #[serde(default, alias = "sourceSessionId")]
+ pub source_session_id: Option<String>,
+ #[serde(default, alias = "sourceMessageId")]
+ pub source_message_id: Option<String>,
+ #[serde(default, alias = "sourceUrl")]
+ pub source_url: Option<String>,
}
#[cfg(test)]
@@ -231,4 +364,51 @@ mod tests {
}));
assert!(pipe_notifications_enabled_from_extra(&extra));
}
+
+ #[test]
+ fn parses_pipe_name_from_session_id_with_colons() {
+ assert_eq!(
+ pipe_name_from_session_id("pipe:daily:research:42"),
+ Some("daily:research".to_string())
+ );
+ assert_eq!(pipe_name_from_session_id("chat-123"), None);
+ assert_eq!(pipe_name_from_session_id("pipe:no-exec"), None);
+ }
+
+ #[test]
+ fn derives_source_metadata_from_pipe_session_header() {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "x-screenpipe-session",
+ "pipe:long-notification-source-test:389".parse().unwrap(),
+ );
+ let payload = NotifyPayload {
+ title: "Research Rabbit".to_string(),
+ body: "long notification body".to_string(),
+ id: None,
+ pipe_name: None,
+ notification_type: None,
+ auto_dismiss_ms: None,
+ timeout: None,
+ actions: vec![],
+ source_session_id: None,
+ source_message_id: None,
+ source_url: None,
+ };
+
+ let source = resolve_notification_source_metadata(&payload, &headers, "abc123");
+
+ assert_eq!(
+ source,
+ NotificationSourceMetadata {
+ source_session_id: Some("pipe:long-notification-source-test:389".to_string()),
+ source_message_id: Some("notification-abc123".to_string()),
+ source_url: Some(
+ "screenpipe://chat/pipe%3Along-notification-source-test%3A389?message=notification-abc123"
+ .to_string()
+ ),
+ pipe_name: Some("long-notification-source-test".to_string()),
+ }
+ );
+ }
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/notifications/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/notifications/store.rs
index 9ac52ccd8..750fac68d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/notifications/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/notifications/store.rs
@@ -17,6 +17,12 @@ pub struct NotificationHistoryEntry {
pub title: String,
pub body: String,
pub pipe_name: Option<String>,
+ #[serde(default)]
+ pub source_session_id: Option<String>,
+ #[serde(default)]
+ pub source_message_id: Option<String>,
+ #[serde(default)]
+ pub source_url: Option<String>,
pub timestamp: String,
pub read: bool,
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/swift/notification_panel.swift b/apps/screenpipe-app-tauri/src-tauri/swift/notification_panel.swift
index 6f532b7ef..5daf005f1 100644
--- a/apps/screenpipe-app-tauri/src-tauri/swift/notification_panel.swift
+++ b/apps/screenpipe-app-tauri/src-tauri/swift/notification_panel.swift
@@ -37,6 +37,9 @@ struct NotificationPayload: Codable {
let actions: [NotificationAction]
var autoDismissMs: Int?
var pipe_name: String?
+ var source_session_id: String?
+ var source_message_id: String?
+ var source_url: String?
}
// Minimal AnyCodable for JSON round-trip
@@ -180,6 +183,35 @@ struct BrandTextButton: View {
}
}
+@available(macOS 13.0, *)
+struct BrandIconTextButton: View {
+ let systemName: String
+ let label: String
+ let help: String
+ let action: () -> Void
+ @State private var isHovered = false
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 4) {
+ Image(systemName: systemName)
+ .font(.system(size: 11, weight: .regular))
+ Text(label)
+ .font(Brand.swiftUIMonoFont(size: 9, weight: .regular))
+ }
+ .foregroundColor(isHovered ? .primary.opacity(0.75) : .primary.opacity(0.34))
+ }
+ .buttonStyle(.plain)
+ .contentShape(Rectangle())
+ .help(help)
+ .onHover { hovering in
+ withAnimation(.linear(duration: Brand.animDuration)) {
+ isHovered = hovering
+ }
+ }
+ }
+}
+
@available(macOS 13.0, *)
struct NotificationContentView: View {
let payload: NotificationPayload
@@ -187,8 +219,10 @@ struct NotificationContentView: View {
let isHovered: Bool
let onDismiss: () -> Void
let onAction: (NotificationAction) -> Void
+ let onOpenSource: () -> Void
@State private var closeHovered = false
+ @State private var copied = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
@@ -220,12 +254,27 @@ struct NotificationContentView: View {
.padding(.top, 12)
// Title
- Text(payload.title)
- .font(Brand.swiftUIMonoFont(size: 12, weight: .medium))
- .foregroundColor(.primary.opacity(0.9))
- .lineLimit(2)
+ if payload.source_url != nil {
+ Button(action: onOpenSource) {
+ Text(payload.title)
+ .font(Brand.swiftUIMonoFont(size: 12, weight: .medium))
+ .foregroundColor(.primary.opacity(0.9))
+ .lineLimit(2)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .buttonStyle(.plain)
+ .contentShape(Rectangle())
.padding(.horizontal, 14)
.padding(.top, 8)
+ .help("open source chat")
+ } else {
+ Text(payload.title)
+ .font(Brand.swiftUIMonoFont(size: 12, weight: .medium))
+ .foregroundColor(.primary.opacity(0.9))
+ .lineLimit(2)
+ .padding(.horizontal, 14)
+ .padding(.top, 8)
+ }
// Body — render basic markdown inline, scrollable when long
ScrollView(.vertical, showsIndicators: true) {
@@ -255,29 +304,35 @@ struct NotificationContentView: View {
.padding(.bottom, 6)
}
- // Footer: manage + mute
- HStack(spacing: 6) {
- BrandTextButton(label: "⚙ manage", fontSize: 9) {
- onDismiss()
- // Small delay so the panel hides before the window appears
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
- sendActionJson("{\"type\":\"manage\"}")
+ // Footer: compact notification actions
+ HStack(spacing: 12) {
+ BrandIconTextButton(
+ systemName: copied ? "checkmark" : "doc.on.doc",
+ label: copied ? "copied" : "copy",
+ help: "copy notification"
+ ) {
+ copyNotificationText()
+ copied = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) {
+ copied = false
}
}
- if let pipeName = payload.pipe_name {
- Text("·")
- .font(Brand.swiftUIMonoFont(size: 9))
- .foregroundColor(.primary.opacity(0.15))
- BrandTextButton(label: "mute \(pipeName)", fontSize: 9) {
- onDismiss()
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
- sendActionJson("{\"type\":\"mute\",\"pipe_name\":\"\(pipeName)\"}")
- }
+ if payload.source_url != nil {
+ BrandIconTextButton(systemName: "arrow.up.right.square", label: "source", help: "open source chat") {
+ onOpenSource()
}
}
- Spacer()
+ Spacer(minLength: 0)
+
+ BrandIconTextButton(systemName: "bell", label: "manage", help: "manage notification settings") {
+ onDismiss()
+ // Small delay so the panel hides before the window appears
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
+ sendActionJson("{\"type\":\"manage\"}")
+ }
+ }
}
.padding(.horizontal, 14)
.padding(.vertical, 6)
@@ -329,6 +384,13 @@ struct NotificationContentView: View {
json.withCString { cb($0) }
}
}
+
+ private func copyNotificationText() {
+ let text = "\(payload.title)\n\n\(payload.body)".trimmingCharacters(in: .whitespacesAndNewlines)
+ let pasteboard = NSPasteboard.general
+ pasteboard.clearContents()
+ pasteboard.setString(text, forType: .string)
+ }
}
// MARK: - Basic Markdown text renderer
@@ -796,6 +858,13 @@ class NotificationPanelController: NSObject {
let json = String(data: data, encoding: .utf8) {
self?.sendAction(json)
}
+ },
+ onOpenSource: { [weak self] in
+ guard let self = self, let url = payload.source_url else { return }
+ self.hide()
+ let escaped = url.replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ self.sendAction("{\"type\":\"deeplink\",\"url\":\"\(escaped)\"}")
}
)
// Fixed width, height determined by content
diff --git a/crates/screenpipe-core/src/agents/bash_env.rs b/crates/screenpipe-core/src/agents/bash_env.rs
index 540153f4d..59ad8be4e 100644
--- a/crates/screenpipe-core/src/agents/bash_env.rs
+++ b/crates/screenpipe-core/src/agents/bash_env.rs
@@ -11,8 +11,8 @@
//!
//! Fix: ship a tiny bash shim that defines a `curl` shell function which
//! auto-injects the Bearer header **only** when the target URL is the local
-//! screenpipe API (localhost:3030). Non-screenpipe calls pass through
-//! untouched — the token never leaks.
+//! screenpipe API (localhost:3030) or local app server (localhost:11435).
+//! Non-screenpipe calls pass through untouched — the token never leaks.
//!
//! The shim is sourced automatically by every `bash -c` subshell via the
//! `BASH_ENV` env var, which spawning code sets on the child `Command`.
@@ -37,13 +37,13 @@ pub const WRAPPER_RELATIVE_PATH: &str = "pi-agent/bash-env.sh";
/// Bash shell-init content sourced by every `bash -c` subshell.
///
-/// Only matches literal `localhost:3030`, `127.0.0.1:3030`, `[::1]:3030`
+/// Only matches literal localhost/loopback screenpipe API or app-server
/// substrings in command arguments. If none match, `curl` runs unchanged.
pub const WRAPPER_SCRIPT: &str = r#"# screenpipe — auto-injected by pi-agent bash subshells (do not edit by hand)
# Transparently adds Authorization: Bearer to curl calls that target the
-# local screenpipe API, tags them with x-screenpipe-session (the chat/pipe
-# that owns this agent, from SCREENPIPE_SESSION_ID) so the owned-browser
-# sidebar can route navigations to the right chat, and — when
+# local screenpipe API/app server, tags them with x-screenpipe-session
+# (the chat/pipe that owns this agent, from SCREENPIPE_SESSION_ID) so
+# owned-browser and notification source links route to the right chat, and — when
# SCREENPIPE_FILTER_PII=1 — rewrites any /search URL to include filter_pii=1
# so responses are PII-redacted before Pi sees them. Other curl calls pass
# through unchanged — the token never leaks to third-party hosts.
@@ -82,7 +82,7 @@ curl() {
for arg in "$@"; do
case "$arg" in
- *localhost:3030*|*127.0.0.1:3030*|*'[::1]:3030'*)
+ *localhost:3030*|*127.0.0.1:3030*|*'[::1]:3030'*|*localhost:11435*|*127.0.0.1:11435*|*'[::1]:11435'*)
has_local=1
if [ "$add_filter" = "1" ]; then
# Only /search responses contain user-visible text we want to redact.
@@ -226,8 +226,15 @@ mod tests {
#[test]
fn wrapper_script_injects_only_for_localhost_3030() {
- // Smoke check the three matched forms; any new alias needs a line here.
- for needle in ["localhost:3030", "127.0.0.1:3030", "[::1]:3030"] {
+ // Smoke check matched forms; any new alias needs a line here.
+ for needle in [
+ "localhost:3030",
+ "127.0.0.1:3030",
+ "[::1]:3030",
+ "localhost:11435",
+ "127.0.0.1:11435",
+ "[::1]:11435",
+ ] {
assert!(
WRAPPER_SCRIPT.contains(needle),
"wrapper should match {} in curl URL args",
@@ -304,6 +311,24 @@ mod tests {
"local API call must carry the session owner header; got: {local}"
);
+ let argv_notify = tmp.path().join("notify.argv");
+ let status = Command::new("bash")
+ .env("PATH", format!("{}:/usr/bin:/bin", fake_curl_dir.display()))
+ .env("BASH_ENV", &wrapper)
+ .env("CURL_ARGV_FILE", &argv_notify)
+ .env("SCREENPIPE_LOCAL_API_KEY", "sp-test")
+ .env("SCREENPIPE_SESSION_ID", "pipe:daily:7")
+ .arg("-c")
+ .arg("curl -X POST http://localhost:11435/notify")
+ .status()
+ .unwrap();
+ assert!(status.success());
+ let notify = std::fs::read_to_string(&argv_notify).unwrap();
+ assert!(
+ notify.contains("x-screenpipe-session: pipe:daily:7"),
+ "local notification call must carry the session owner header; got: {notify}"
+ );
+
// Third-party host → owner header must NOT leak.
let argv_ext = tmp.path().join("ext.argv");
let status = Command::new("bash")