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

feat(pipes): run tasks in an existing chat (#6853)

Louis Beaumontcf124e55806d
diff --git a/apps/screenpipe-app-tauri/components/__tests__/chat-sidebar-grouping.test.ts b/apps/screenpipe-app-tauri/components/__tests__/chat-sidebar-grouping.test.ts
index eeb28d507..7e9849531 100644
--- a/apps/screenpipe-app-tauri/components/__tests__/chat-sidebar-grouping.test.ts
+++ b/apps/screenpipe-app-tauri/components/__tests__/chat-sidebar-grouping.test.ts
@@ -24,6 +24,7 @@ import {
isTerminalPipeExecutionStatus,
pipeExecutionConversationId,
pipeExecutionDeletionKey,
+ pipeExecutionUsesExistingChat,
shouldReloadPipeExecutionHistory,
uniquePipeExecutionConversations,
} from "@/lib/pipe-execution-status";
@@ -72,6 +73,23 @@ describe("buildPipeExecutionHistoryPage", () => {
});
describe("continued pipe chat inventory", () => {
+ it("distinguishes user-selected chats from Pipe-owned chats", () => {
+ expect(
+ pipeExecutionUsesExistingChat({
+ id: 12,
+ pipe_name: "daily-brief",
+ conversation_id: "chat-42",
+ }),
+ ).toBe(true);
+ expect(
+ pipeExecutionUsesExistingChat({
+ id: 12,
+ pipe_name: "daily-brief",
+ conversation_id: "pipe:daily-brief:continuous",
+ }),
+ ).toBe(false);
+ });
+
it("collapses multiple runs onto their newest stable conversation", () => {
const executions = [
{
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index 482ef438b..a2cb0ae2e 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -138,6 +138,7 @@ import {
pipeConversationDeletionKey,
pipeExecutionConversationId,
pipeExecutionDeletionKey,
+ pipeExecutionUsesExistingChat,
shouldReloadPipeExecutionHistory,
uniquePipeExecutionConversations,
} from "@/lib/pipe-execution-status";
@@ -974,12 +975,14 @@ export function ChatSidebar({
const visibleExecutions = uniquePipeExecutionConversations(
terminalExecutions,
alreadyLoadedIds,
- ).filter(
- (execution) => !isPipeExecutionDeleted(
- execution,
- deletedPipeExecutionIdsRef.current,
- ),
- );
+ )
+ .filter((execution) => !pipeExecutionUsesExistingChat(execution))
+ .filter(
+ (execution) => !isPipeExecutionDeleted(
+ execution,
+ deletedPipeExecutionIdsRef.current,
+ ),
+ );
const candidates = await Promise.all(visibleExecutions.map(async (execution) => {
const sessionId = pipeExecutionConversationId(execution);
executionMetadataRef.current.set(sessionId, execution);
diff --git a/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.test.tsx b/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.test.tsx
new file mode 100644
index 000000000..8b57e4535
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.test.tsx
@@ -0,0 +1,151 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { PipeChatDestinationPicker } from "./pipe-chat-destination-picker";
+import type { ConversationMeta } from "@/lib/chat-storage";
+
+const { listConversations, loadConversationFile, searchConversations } = vi.hoisted(() => ({
+ listConversations: vi.fn(),
+ loadConversationFile: vi.fn(),
+ searchConversations: vi.fn(),
+}));
+
+vi.mock("@/lib/chat-storage", () => ({
+ listConversations,
+ loadConversationFile,
+ searchConversations,
+}));
+
+function chat(id: string, title: string, pinned = false): ConversationMeta {
+ return {
+ id,
+ title,
+ createdAt: 1,
+ updatedAt: pinned ? 1 : 2,
+ messageCount: 2,
+ pinned,
+ hidden: false,
+ kind: "chat",
+ };
+}
+
+beforeAll(() => {
+ globalThis.PointerEvent ||= MouseEvent as unknown as typeof PointerEvent;
+ Element.prototype.scrollIntoView = vi.fn();
+});
+
+describe("PipeChatDestinationPicker", () => {
+ beforeEach(() => {
+ listConversations.mockReset();
+ loadConversationFile.mockReset();
+ searchConversations.mockReset();
+ listConversations.mockResolvedValue([
+ chat("recent-chat", "recent work"),
+ chat("pinned-chat", "pinned strategy", true),
+ ]);
+ searchConversations.mockResolvedValue([]);
+ loadConversationFile.mockResolvedValue(null);
+ });
+
+ it("groups pinned chats first and selects the immutable id", async () => {
+ const onSelect = vi.fn();
+ render(
+ <PipeChatDestinationPicker
+ open
+ onOpenChange={vi.fn()}
+ onSelect={onSelect}
+ />,
+ );
+
+ await screen.findByText("pinned strategy");
+ expect(listConversations).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: "chat", includeHidden: false }),
+ );
+ const options = screen.getAllByRole("option");
+ expect(options[0]).toHaveTextContent("pinned strategy");
+ fireEvent.keyDown(screen.getByRole("textbox", { name: "search chats" }), {
+ key: "ArrowDown",
+ });
+ expect(options[0]).toHaveFocus();
+ fireEvent.keyDown(options[0], { key: "ArrowDown" });
+ expect(options[1]).toHaveFocus();
+ fireEvent.click(screen.getByRole("option", { name: /recent work/i }));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: "recent-chat" }));
+ });
+
+ it("searches chat content without replacing a selected id", async () => {
+ searchConversations.mockResolvedValue([chat("match-id", "customer follow-up")]);
+ render(
+ <PipeChatDestinationPicker
+ value="kept-id"
+ open
+ onOpenChange={vi.fn()}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ fireEvent.change(screen.getByRole("textbox", { name: "search chats" }), {
+ target: { value: "customer" },
+ });
+ await waitFor(() => expect(searchConversations).toHaveBeenCalledWith(
+ "customer",
+ expect.objectContaining({ kind: "chat", includeHidden: false }),
+ ));
+ expect(await screen.findByText("customer follow-up")).toBeInTheDocument();
+ });
+
+ it("makes a deleted target explicit instead of choosing a replacement", async () => {
+ render(
+ <PipeChatDestinationPicker
+ value="deleted-chat"
+ open={false}
+ onOpenChange={vi.fn()}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ expect(await screen.findByText("chat unavailable")).toBeInTheDocument();
+ expect(listConversations).not.toHaveBeenCalled();
+ });
+
+ it("shows the saved title while closed without loading the whole list", async () => {
+ loadConversationFile.mockResolvedValue({
+ id: "kept-chat",
+ title: "customer strategy",
+ createdAt: 1,
+ updatedAt: 2,
+ messages: [],
+ kind: "chat",
+ });
+ render(
+ <PipeChatDestinationPicker
+ value="kept-chat"
+ open={false}
+ onOpenChange={vi.fn()}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ expect(await screen.findByText("customer strategy")).toBeInTheDocument();
+ expect(listConversations).not.toHaveBeenCalled();
+ });
+
+ it("offers retry when the local chat index cannot be read", async () => {
+ listConversations
+ .mockRejectedValueOnce(new Error("index unavailable"))
+ .mockResolvedValueOnce([chat("recovered-chat", "recovered chat")]);
+ render(
+ <PipeChatDestinationPicker
+ open
+ onOpenChange={vi.fn()}
+ onSelect={vi.fn()}
+ />,
+ );
+
+ expect(await screen.findByText("couldn't load chats")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "retry" }));
+ expect(await screen.findByText("recovered chat")).toBeInTheDocument();
+ });
+});
diff --git a/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.tsx b/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.tsx
new file mode 100644
index 000000000..6bd901e44
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/settings/pipe-chat-destination-picker.tsx
@@ -0,0 +1,296 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+"use client";
+
+import React from "react";
+import { Check, Loader2, MessageSquare, Pin, Search } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ listConversations,
+ loadConversationFile,
+ searchConversations,
+ type ConversationMeta,
+} from "@/lib/chat-storage";
+import { cn } from "@/lib/utils";
+
+const CHAT_PICKER_LIMIT = 50;
+
+function chatDate(timestamp: number): string {
+ const date = new Date(timestamp);
+ if (!Number.isFinite(date.getTime())) return "";
+ const now = new Date();
+ if (date.toDateString() === now.toDateString()) {
+ return date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+ }
+ return date.toLocaleDateString([], { month: "short", day: "numeric" });
+}
+
+function conversationToMeta(
+ conversation: Awaited<ReturnType<typeof loadConversationFile>>,
+): ConversationMeta | null {
+ if (!conversation || (conversation.kind ?? "chat") !== "chat") return null;
+ return {
+ id: conversation.id,
+ title: conversation.title || "untitled chat",
+ createdAt: conversation.createdAt,
+ updatedAt: conversation.updatedAt,
+ messageCount: conversation.messages.length,
+ pinned: conversation.pinned === true,
+ hidden: conversation.hidden === true,
+ lastUserMessageAt: conversation.lastUserMessageAt,
+ lastContentAt: conversation.lastContentAt,
+ lastViewedAt: conversation.lastViewedAt,
+ kind: "chat",
+ presetId: conversation.presetId,
+ };
+}
+
+interface PipeChatDestinationPickerProps {
+ value?: string;
+ disabled?: boolean;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSelect: (chat: ConversationMeta) => void;
+}
+
+export function PipeChatDestinationPicker({
+ value,
+ disabled,
+ open,
+ onOpenChange,
+ onSelect,
+}: PipeChatDestinationPickerProps) {
+ const [query, setQuery] = React.useState("");
+ const [results, setResults] = React.useState<ConversationMeta[]>([]);
+ const [selected, setSelected] = React.useState<ConversationMeta | null>(null);
+ const [selectedLoading, setSelectedLoading] = React.useState(Boolean(value));
+ const [loading, setLoading] = React.useState(false);
+ const [loadError, setLoadError] = React.useState(false);
+ const requestId = React.useRef(0);
+ const searchInput = React.useRef<HTMLInputElement>(null);
+
+ const loadChats = React.useCallback(async (nextQuery: string) => {
+ const id = ++requestId.current;
+ setLoading(true);
+ setLoadError(false);
+ try {
+ const chats = nextQuery.trim()
+ ? await searchConversations(nextQuery, {
+ limit: CHAT_PICKER_LIMIT,
+ includeHidden: false,
+ kind: "chat",
+ })
+ : await listConversations({
+ limit: CHAT_PICKER_LIMIT,
+ includeHidden: false,
+ kind: "chat",
+ });
+ if (requestId.current === id) setResults(chats);
+ } catch {
+ if (requestId.current === id) setLoadError(true);
+ } finally {
+ if (requestId.current === id) setLoading(false);
+ }
+ }, []);
+
+ React.useEffect(() => {
+ if (!value) {
+ setSelected(null);
+ setSelectedLoading(false);
+ return;
+ }
+ let cancelled = false;
+ setSelectedLoading(true);
+ void loadConversationFile(value)
+ .then((conversation) => {
+ if (!cancelled) setSelected(conversationToMeta(conversation));
+ })
+ .catch(() => {
+ if (!cancelled) setSelected(null);
+ })
+ .finally(() => {
+ if (!cancelled) setSelectedLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [value]);
+
+ React.useEffect(() => {
+ if (!open) return;
+ const timeout = window.setTimeout(() => void loadChats(query), query ? 150 : 0);
+ return () => window.clearTimeout(timeout);
+ }, [loadChats, open, query]);
+
+ React.useEffect(() => {
+ if (!open) setQuery("");
+ }, [open]);
+
+ const pinned = results.filter((chat) => chat.pinned);
+ const recent = results.filter((chat) => !chat.pinned);
+ const unavailable = Boolean(value && !selected && !selectedLoading);
+
+ const renderRows = (chats: ConversationMeta[]) =>
+ chats.map((chat) => (
+ <button
+ key={chat.id}
+ type="button"
+ role="option"
+ aria-selected={chat.id === value}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm outline-none transition-colors",
+ "hover:bg-muted focus-visible:bg-muted focus-visible:ring-1 focus-visible:ring-ring",
+ chat.id === value && "bg-muted/70",
+ )}
+ onClick={() => {
+ setSelected(chat);
+ onSelect(chat);
+ onOpenChange(false);
+ }}
+ onKeyDown={(event) => {
+ if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
+ const listbox = event.currentTarget.closest('[role="listbox"]');
+ const options = Array.from(
+ listbox?.querySelectorAll<HTMLButtonElement>('[role="option"]') ?? [],
+ );
+ if (options.length === 0) return;
+ event.preventDefault();
+ const current = options.indexOf(event.currentTarget);
+ const next = event.key === "Home"
+ ? 0
+ : event.key === "End"
+ ? options.length - 1
+ : (current + (event.key === "ArrowDown" ? 1 : -1) + options.length) % options.length;
+ options[next]?.focus();
+ }}
+ >
+ {chat.pinned ? (
+ <Pin className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ ) : (
+ <MessageSquare className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ )}
+ <span className="min-w-0 flex-1 truncate">{chat.title || "untitled chat"}</span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {chatDate(chat.updatedAt)}
+ </span>
+ <Check
+ className={cn(
+ "h-4 w-4 shrink-0",
+ chat.id === value ? "opacity-100" : "opacity-0",
+ )}
+ aria-hidden="true"
+ />
+ </button>
+ ));
+
+ return (
+ <Popover open={open} onOpenChange={onOpenChange}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="secondary"
+ disabled={disabled}
+ className={cn(
+ "h-8 min-w-0 max-w-full justify-between gap-2 rounded-md px-3 text-xs font-normal sm:w-64",
+ unavailable && "text-destructive",
+ )}
+ aria-label="choose an existing chat"
+ data-testid="pipe-chat-destination-trigger"
+ >
+ <span className="truncate">
+ {selected?.title ||
+ (selectedLoading
+ ? "loading chat…"
+ : unavailable
+ ? "chat unavailable"
+ : "choose chat")}
+ </span>
+ <Search className="h-3.5 w-3.5 shrink-0 opacity-60" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ className="w-[min(28rem,calc(100vw-2rem))] rounded-lg p-0"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ searchInput.current?.focus();
+ }}
+ >
+ <div className="border-b border-border p-2">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ ref={searchInput}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "ArrowDown") return;
+ const first = document.querySelector<HTMLButtonElement>(
+ '[role="listbox"] [role="option"]',
+ );
+ if (!first) return;
+ event.preventDefault();
+ first.focus();
+ }}
+ placeholder="search chats"
+ aria-label="search chats"
+ className="h-8 rounded-md pl-8 text-xs"
+ />
+ </div>
+ </div>
+
+ <div className="max-h-80 overflow-y-auto p-1.5" role="listbox" aria-label="chats">
+ {loading && results.length === 0 ? (
+ <div className="flex items-center justify-center gap-2 px-3 py-8 text-xs text-muted-foreground" role="status">
+ <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
+ loading chats
+ </div>
+ ) : loadError ? (
+ <div className="space-y-2 px-3 py-6 text-center text-xs text-muted-foreground" role="alert">
+ <p>couldn&apos;t load chats</p>
+ <Button type="button" size="sm" variant="outline" className="h-7 text-xs" onClick={() => void loadChats(query)}>
+ retry
+ </Button>
+ </div>
+ ) : results.length === 0 ? (
+ <div className="px-4 py-8 text-center text-xs text-muted-foreground">
+ {query ? "no matching chats" : "no chats yet — start a chat, then return here"}
+ </div>
+ ) : (
+ query ? (
+ <>{renderRows(results)}</>
+ ) : (
+ <>
+ {pinned.length > 0 && (
+ <div>
+ <p className="px-2.5 pb-1 pt-1 text-[11px] font-medium text-muted-foreground">pinned</p>
+ {renderRows(pinned)}
+ </div>
+ )}
+ {recent.length > 0 && (
+ <div>
+ <p className="px-2.5 pb-1 pt-2 text-[11px] font-medium text-muted-foreground">
+ recent
+ </p>
+ {renderRows(recent)}
+ </div>
+ )}
+ </>
+ )
+ )}
+ </div>
+
+ <p className="border-t border-border px-3 py-2 text-[11px] text-muted-foreground">
+ the task queues behind any reply already running in this chat
+ </p>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
index f5da77a71..0af1d4edc 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
@@ -141,7 +141,10 @@ import {
materializePipeExecutionConversation,
pipeConversationNeedsRefresh,
} from "@/lib/pipe-conversation";
-import { pipeConversationDeletionKey } from "@/lib/pipe-execution-status";
+import {
+ pipeConversationDeletionKey,
+ pipeExecutionUsesExistingChat,
+} from "@/lib/pipe-execution-status";
import { PipeStoreSubmissionDialog } from "@/components/pipe-store-submission";
import {
Dialog,
@@ -157,6 +160,7 @@ import { MarkdownBlock } from "@/components/chat/markdown-block";
import { useDeviceMonitor } from "@/lib/hooks/use-device-monitor";
import { Monitor, Wifi, WifiOff, ScanSearch, Lock } from "lucide-react";
import { requestPipeStop } from "@/lib/pipe-stop";
+import { PipeChatDestinationPicker } from "./pipe-chat-destination-picker";
const PIPE_EXECUTIONS_PAGE_LIMIT = 10;
@@ -488,6 +492,10 @@ interface PipeConfig {
preset?: string | string[];
enterprise_managed?: boolean;
history?: boolean;
+ run_in?: {
+ mode: "existing_chat";
+ chat_id: string;
+ } | null;
connections?: string[];
trigger?: {
events?: string[];
@@ -504,6 +512,13 @@ interface PipeConfig {
[key: string]: unknown;
}
+type PipeRunDestinationMode = "per_run" | "task_chat" | "existing_chat";
+
+function pipeRunDestinationMode(config: PipeConfig): PipeRunDestinationMode {
+ if (config.run_in?.mode === "existing_chat") return "existing_chat";
+ return config.history ? "task_chat" : "per_run";
+}
+
interface PipeConnectionOption {
key: string;
label: string;
@@ -1138,6 +1153,10 @@ export function PipesSection() {
Record<string, "saving" | "saved" | "error">
>({});
const [historySaveErrors, setHistorySaveErrors] = useState<Record<string, string>>({});
+ const [runDestinationDrafts, setRunDestinationDrafts] = useState<
+ Record<string, PipeRunDestinationMode>
+ >({});
+ const [chatPickerOpen, setChatPickerOpen] = useState<Record<string, boolean>>({});
const [historyResetPipe, setHistoryResetPipe] = useState<PipeStatus | null>(null);
const [historyResetStatus, setHistoryResetStatus] = useState<
Record<string, "clearing" | "cleared" | "error">
@@ -1503,9 +1522,21 @@ export function PipesSection() {
const isReadOnlyPipe = (pipe: PipeStatus) =>
isReceivedTeamPipe(pipe) || isEnterpriseManagedPipe(pipe);
- const savePipeHistoryMode = async (pipe: PipeStatus, history: boolean) => {
+ const savePipeRunDestination = async (
+ pipe: PipeStatus,
+ mode: PipeRunDestinationMode,
+ chatId?: string,
+ ) => {
const pipeName = pipe.config.name;
const previousHistory = Boolean(pipe.config.history);
+ const previousRunIn = pipe.config.run_in ?? null;
+ if (mode === "existing_chat" && !chatId?.trim()) {
+ throw new Error("choose a chat before saving this destination");
+ }
+ const history = mode === "task_chat";
+ const run_in = mode === "existing_chat"
+ ? { mode: "existing_chat" as const, chat_id: chatId!.trim() }
+ : null;
setHistorySaveStatus((previous) => ({ ...previous, [pipeName]: "saving" }));
setHistorySaveErrors((previous) => {
const next = { ...previous };
@@ -1515,7 +1546,7 @@ export function PipesSection() {
setPipes((previous) =>
previous.map((candidate) =>
candidate.config.name === pipeName
- ? { ...candidate, config: { ...candidate.config, history } }
+ ? { ...candidate, config: { ...candidate.config, history, run_in } }
: candidate
)
);
@@ -1526,7 +1557,7 @@ export function PipesSection() {
{
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ history }),
+ body: JSON.stringify({ history, run_in }),
},
);
let data: { error?: string; success?: boolean } | undefined;
@@ -1543,7 +1574,7 @@ export function PipesSection() {
try {
await savePromise;
- void emit("pipe-config-updated", { pipeName, history }).catch(() => undefined);
+ void emit("pipe-config-updated", { pipeName, history, run_in }).catch(() => undefined);
setHistorySaveStatus((previous) => ({ ...previous, [pipeName]: "saved" }));
window.setTimeout(() => {
setHistorySaveStatus((previous) => {
@@ -1560,7 +1591,11 @@ export function PipesSection() {
candidate.config.name === pipeName
? {
...candidate,
- config: { ...candidate.config, history: previousHistory },
+ config: {
+ ...candidate.config,
+ history: previousHistory,
+ run_in: previousRunIn,
+ },
}
: candidate
)
@@ -1569,6 +1604,11 @@ export function PipesSection() {
setHistorySaveErrors((previous) => ({ ...previous, [pipeName]: message }));
throw error;
} finally {
+ setRunDestinationDrafts((previous) => {
+ const next = { ...previous };
+ delete next[pipeName];
+ return next;
+ });
if (pendingConfigSaves.current[pipeName] === savePromise) {
delete pendingConfigSaves.current[pipeName];
}
@@ -3604,7 +3644,15 @@ export function PipesSection() {
<button className="text-muted-foreground hover:text-foreground p-0.5" title="open in chat" onClick={async () => {
const recorderSid = exec.conversation_id || `pipe:${exec.pipe_name}:${exec.id}`;
const existing = await loadConversationFile(recorderSid);
- if (pipeConversationNeedsRefresh(existing, exec)) {
+ if (pipeExecutionUsesExistingChat(exec) && !existing) {
+ toast({
+ title: "chat unavailable",
+ description: "this run's destination was deleted or cannot be read",
+ variant: "destructive",
+ });
+ return;
+ }
+ if (!pipeExecutionUsesExistingChat(exec) && pipeConversationNeedsRefresh(existing, exec)) {
await saveConversationFile(
materializePipeExecutionConversation(exec, existing),
);
@@ -3703,10 +3751,10 @@ export function PipesSection() {
</TabsContent>
{/* ═══ ADVANCED TAB ═══ */}
- <TabsContent value="advanced" className="mt-4 space-y-4">
+ <TabsContent value="advanced" className="mt-4 flex flex-col gap-4">
{!enterpriseManaged && (
<>
- <section className="divide-y divide-border border border-border">
+ <section className="order-2 divide-y divide-border border border-border">
<div className="px-4 py-3">
<p className="text-sm font-medium">runtime</p>
<p className="mt-0.5 text-[11px] text-muted-foreground">
@@ -3829,108 +3877,185 @@ export function PipesSection() {
</div>
</section>
- <section className="flex items-start justify-between gap-4 border border-border p-4">
- <div className="min-w-0">
- <Label
- htmlFor={`pipe-history-switch-${pipe.config.name}`}
- className="text-xs font-medium"
- >
- continue in one chat
- </Label>
- <div
- id={`pipe-history-description-${pipe.config.name}`}
- className="text-[11px] text-muted-foreground"
- >
- {pipe.config.history
- ? "new runs and your replies share this chat. turning this off pauses memory; it does not delete saved context."
- : "runs start in separate chats. any previous one-chat context stays saved and resumes if you turn this on."}
- </div>
- {historySaveStatus[pipe.config.name] === "saving" && (
- <div className="mt-1 flex items-center gap-1 text-[11px] text-muted-foreground" role="status">
- <Loader2 className="h-3 w-3 animate-spin" /> saving
- </div>
- )}
- {historySaveStatus[pipe.config.name] === "saved" && (
- <div className="mt-1 flex items-center gap-1 text-[11px] text-muted-foreground" role="status">
- <Check className="h-3 w-3" /> saved
- </div>
- )}
- {historySaveStatus[pipe.config.name] === "error" && (
- <div
- className="mt-1 text-[11px] text-destructive"
- role="alert"
- data-testid={`pipe-history-error-${pipe.config.name}`}
- >
- save failed — previous setting restored
- {historySaveErrors[pipe.config.name]
- ? `: ${historySaveErrors[pipe.config.name]}`
- : ""}
- </div>
- )}
- {(pipe.has_saved_context ||
- historyResetStatus[pipe.config.name]) && (
- <div className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1">
- {pipe.has_saved_context && (
- <Button
- type="button"
- variant="link"
- size="sm"
- className="h-auto p-0 text-[11px] text-muted-foreground underline-offset-2"
- data-testid={`pipe-history-reset-${pipe.config.name}`}
- disabled={
- isRunning ||
- historyResetStatus[pipe.config.name] === "clearing"
+ {(() => {
+ const savedMode = pipeRunDestinationMode(pipe.config);
+ const mode = runDestinationDrafts[pipe.config.name] ?? savedMode;
+ const destinationDisabled =
+ isReadOnlyPipe(pipe) ||
+ isRunning ||
+ historySaveStatus[pipe.config.name] === "saving";
+ return (
+ <section className="order-1 overflow-hidden rounded-lg border border-border">
+ <div className="grid gap-3 p-4 sm:grid-cols-[minmax(0,1fr)_16rem] sm:items-center">
+ <div>
+ <Label className="text-xs font-medium">runs in</Label>
+ <p
+ id={`pipe-run-destination-description-${pipe.config.name}`}
+ className="mt-0.5 text-[11px] text-muted-foreground"
+ >
+ {mode === "per_run" && "a new chat with fresh context for every run."}
+ {mode === "task_chat" && "this task's own chat, shared across runs and your replies."}
+ {mode === "existing_chat" && "the selected chat on this device, using that chat's AI settings and approval prompts."}
+ </p>
+ </div>
+ <Select
+ value={mode}
+ disabled={destinationDisabled}
+ onValueChange={(value: PipeRunDestinationMode) => {
+ setRunDestinationDrafts((previous) => ({
+ ...previous,
+ [pipe.config.name]: value,
+ }));
+ if (value === "existing_chat") {
+ // Let the Select portal finish closing before opening the
+ // chat Popover. Opening both in the same Radix event causes
+ // the Select's outside-click cleanup to immediately dismiss
+ // the picker and makes the choice appear to do nothing.
+ window.setTimeout(() => {
+ setChatPickerOpen((previous) => ({
+ ...previous,
+ [pipe.config.name]: true,
+ }));
+ }, 0);
+ return;
}
- onClick={() => setHistoryResetPipe(pipe)}
+ void savePipeRunDestination(pipe, value).catch(() => undefined);
+ }}
+ >
+ <SelectTrigger
+ className="h-8 w-full rounded-md text-xs"
+ aria-describedby={`pipe-run-destination-description-${pipe.config.name}`}
+ data-testid={`pipe-run-destination-${pipe.config.name}`}
>
- {pipe.config.history
- ? "start next run fresh"
- : "clear saved one-chat context"}
- </Button>
- )}
- {isRunning && (
- <span className="text-[11px] text-muted-foreground">
- available after this run
- </span>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="per_run">new chat each run</SelectItem>
+ <SelectItem value="task_chat">this task&apos;s chat</SelectItem>
+ <SelectItem value="existing_chat" disabled={Boolean(selectedDevice)}>
+ existing chat{selectedDevice ? " (choose on that device)" : ""}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ {mode === "existing_chat" && (
+ <div className="grid gap-3 border-t border-border p-4 sm:grid-cols-[minmax(0,1fr)_16rem] sm:items-center">
+ <div>
+ <Label className="text-xs font-medium">chat</Label>
+ <p className="mt-0.5 text-[11px] text-muted-foreground">
+ {selectedDevice
+ ? "open this task on that device to view or change its chat."
+ : "renaming or unpinning is safe. deleting this chat makes future runs fail until you choose another."}
+ </p>
+ </div>
+ {selectedDevice ? (
+ <Button
+ type="button"
+ variant="secondary"
+ disabled
+ className="h-8 justify-start rounded-md text-xs font-normal"
+ >
+ configured on selected device
+ </Button>
+ ) : (
+ <PipeChatDestinationPicker
+ value={pipe.config.run_in?.chat_id}
+ disabled={destinationDisabled}
+ open={Boolean(chatPickerOpen[pipe.config.name])}
+ onOpenChange={(open) => {
+ setChatPickerOpen((previous) => ({
+ ...previous,
+ [pipe.config.name]: open,
+ }));
+ if (!open && savedMode !== "existing_chat") {
+ setRunDestinationDrafts((previous) => {
+ const next = { ...previous };
+ delete next[pipe.config.name];
+ return next;
+ });
+ }
+ }}
+ onSelect={(chat) => {
+ void savePipeRunDestination(pipe, "existing_chat", chat.id).catch(
+ () => undefined,
+ );
+ }}
+ />
+ )}
+ </div>
+ )}
+
+ <div className="border-t border-border px-4 py-2.5">
+ {historySaveStatus[pipe.config.name] === "saving" && (
+ <div className="flex items-center gap-1 text-[11px] text-muted-foreground" role="status">
+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" /> saving destination
+ </div>
)}
- {historyResetStatus[pipe.config.name] === "cleared" && (
- <span
- className="text-[11px] text-muted-foreground"
- role="status"
- >
- context cleared
- </span>
+ {historySaveStatus[pipe.config.name] === "saved" && (
+ <div className="flex items-center gap-1 text-[11px] text-muted-foreground" role="status">
+ <Check className="h-3 w-3" /> destination saved on {selectedDevice ? "selected device" : "this device"}
+ </div>
)}
- {historyResetStatus[pipe.config.name] === "error" && (
- <span
+ {historySaveStatus[pipe.config.name] === "error" && (
+ <div
className="text-[11px] text-destructive"
role="alert"
+ data-testid={`pipe-history-error-${pipe.config.name}`}
>
- context was not cleared
- </span>
+ save failed — previous destination restored
+ {historySaveErrors[pipe.config.name]
+ ? `: ${historySaveErrors[pipe.config.name]}`
+ : ""}
+ </div>
)}
+ {mode !== "existing_chat" &&
+ (pipe.has_saved_context || historyResetStatus[pipe.config.name]) && (
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ {pipe.has_saved_context && (
+ <Button
+ type="button"
+ variant="link"
+ size="sm"
+ className="h-auto p-0 text-[11px] text-muted-foreground underline-offset-2"
+ data-testid={`pipe-history-reset-${pipe.config.name}`}
+ disabled={
+ isRunning ||
+ historyResetStatus[pipe.config.name] === "clearing"
+ }
+ onClick={() => setHistoryResetPipe(pipe)}
+ >
+ {mode === "task_chat"
+ ? "start next run fresh"
+ : "clear saved task-chat context"}
+ </Button>
+ )}
+ {isRunning && (
+ <span className="text-[11px] text-muted-foreground">available after this run</span>
+ )}
+ {historyResetStatus[pipe.config.name] === "cleared" && (
+ <span className="text-[11px] text-muted-foreground" role="status">context cleared</span>
+ )}
+ {historyResetStatus[pipe.config.name] === "error" && (
+ <span className="text-[11px] text-destructive" role="alert">context was not cleared</span>
+ )}
+ </div>
+ )}
+ {!pipe.has_saved_context &&
+ !historyResetStatus[pipe.config.name] &&
+ !historySaveStatus[pipe.config.name] && (
+ <p className="text-[11px] text-muted-foreground">
+ destination changes apply to the next run and never delete a chat.
+ </p>
+ )}
</div>
- )}
- </div>
- <Switch
- id={`pipe-history-switch-${pipe.config.name}`}
- checked={!!pipe.config.history}
- disabled={
- isReadOnlyPipe(pipe) ||
- historySaveStatus[pipe.config.name] === "saving"
- }
- aria-label={`continue ${pipe.config.name} in one chat`}
- aria-describedby={`pipe-history-description-${pipe.config.name}`}
- data-testid={`pipe-history-switch-${pipe.config.name}`}
- onCheckedChange={(checked) => {
- void savePipeHistoryMode(pipe, checked).catch(() => undefined);
- }}
- />
- </section>
+ </section>
+ );
+ })()}
</>
)}
- <section className="border border-border">
+ <section className="order-3 border border-border">
<div className="flex items-center gap-2 border-b border-border px-4 py-3">
<Label className="text-sm font-medium">task definition</Label>
<span className="text-[11px] text-muted-foreground">task configuration</span>
@@ -4024,7 +4149,15 @@ export function PipesSection() {
const conversationId =
exec.conversation_id || `pipe:${exec.pipe_name}:${exec.id}`;
const existing = await loadConversationFile(conversationId);
- if (pipeConversationNeedsRefresh(existing, exec)) {
+ if (pipeExecutionUsesExistingChat(exec) && !existing) {
+ toast({
+ title: "chat unavailable",
+ description: "this run's destination was deleted or cannot be read",
+ variant: "destructive",
+ });
+ return;
+ }
+ if (!pipeExecutionUsesExistingChat(exec) && pipeConversationNeedsRefresh(existing, exec)) {
await saveConversationFile(
materializePipeExecutionConversation(exec, existing),
);
diff --git a/apps/screenpipe-app-tauri/lib/dev/browser-engine-mock.ts b/apps/screenpipe-app-tauri/lib/dev/browser-engine-mock.ts
index 7aebd10c5..373f79e89 100644
--- a/apps/screenpipe-app-tauri/lib/dev/browser-engine-mock.ts
+++ b/apps/screenpipe-app-tauri/lib/dev/browser-engine-mock.ts
@@ -49,6 +49,8 @@ let mockCloudAgentConfig: MockCloudAgentConfig = {
context_max_items: 80,
};
let mockPipeAgent = "cloud-agent";
+let mockPipeHistory = false;
+let mockPipeRunIn: { mode: "existing_chat"; chat_id: string } | null = null;
function mockCloudProviderStatuses() {
return (["codex", "claude", "cursor"] as const).map((provider) => ({
@@ -82,6 +84,8 @@ function mockDailyRecapPipe() {
cloud_agent:
mockPipeAgent === "cloud-agent" ? mockCloudAgentConfig : null,
connections: [],
+ history: mockPipeHistory,
+ run_in: mockPipeRunIn,
},
last_run: null,
last_success: null,
@@ -388,6 +392,11 @@ export function mockLocalApiResponse(
if (body.cloud_agent && typeof body.cloud_agent === "object") {
mockCloudAgentConfig = body.cloud_agent as MockCloudAgentConfig;
}
+ if (typeof body.history === "boolean") mockPipeHistory = body.history;
+ if (body.run_in === null) mockPipeRunIn = null;
+ if (body.run_in && typeof body.run_in === "object") {
+ mockPipeRunIn = body.run_in as { mode: "existing_chat"; chat_id: string };
+ }
return Response.json({ success: true });
}
if (url.pathname === "/pipes/favorites") {
diff --git a/apps/screenpipe-app-tauri/lib/pipe-execution-status.ts b/apps/screenpipe-app-tauri/lib/pipe-execution-status.ts
index c1355aefe..53f035014 100644
--- a/apps/screenpipe-app-tauri/lib/pipe-execution-status.ts
+++ b/apps/screenpipe-app-tauri/lib/pipe-execution-status.ts
@@ -16,6 +16,20 @@ export function pipeExecutionConversationId(
return execution.conversation_id || `pipe:${execution.pipe_name}:${execution.id}`;
}
+/**
+ * Pipe-owned chats always use the `pipe:<name>:` namespace. Any other saved
+ * conversation id points at a real user chat selected as the run destination;
+ * it must be opened as-is and never materialized from execution stdout.
+ */
+export function pipeExecutionUsesExistingChat(
+ execution: PipeExecutionChatIdentity,
+): boolean {
+ const conversationId = execution.conversation_id;
+ return Boolean(
+ conversationId && !conversationId.startsWith(`pipe:${execution.pipe_name}:`),
+ );
+}
+
/**
* Deleting a per-run chat can tombstone its stable id forever because that id
* belongs to only one execution. A continued chat needs an execution-scoped
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/chat_control.rs b/apps/screenpipe-app-tauri/src-tauri/src/chat_control.rs
index 64798ab29..3fbc36170 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/chat_control.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/chat_control.rs
@@ -11,13 +11,16 @@
use crate::pi::{self, AcpAgentConfig, PiBackend, PiProviderConfig, PiState};
use crate::store::{AIPreset, AIProviderType, SettingsStore};
use async_trait::async_trait;
+use screenpipe_core::agents::chat_destination::ChatDestinationRequest;
use screenpipe_core::agents::chat_control::{
self, ChatControlEndpoint, ChatSendRequest, DeliveryMode, ScreenpipeChat, ScreenpipeChatHost,
ScreenpipeDelivery, WorktreeStartRequest,
};
+use screenpipe_core::agents::STOP_REQUESTED_PID;
use serde_json::Value;
use std::collections::HashSet;
use std::sync::Arc;
+use std::sync::atomic::Ordering;
use tauri::Manager;
use tokio::sync::OnceCell;
@@ -238,6 +241,120 @@ impl ScreenpipeChatHost for DesktopChatHost {
}
}
+struct ScheduledChatTurnGuard {
+ state: PiState,
+ chat_id: String,
+ queue_id: String,
+ armed: bool,
+}
+
+impl ScheduledChatTurnGuard {
+ fn disarm(&mut self) {
+ self.armed = false;
+ }
+}
+
+impl Drop for ScheduledChatTurnGuard {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let state = self.state.clone();
+ let chat_id = self.chat_id.clone();
+ let queue_id = self.queue_id.clone();
+ tokio::spawn(async move {
+ match pi::pi_cancel_queued_inner(&state, &chat_id, queue_id).await {
+ Ok(true) => {}
+ // Once the prompt has entered the in-flight slot, cancel only
+ // that active turn. Other user follow-ups remain queued.
+ Ok(false) | Err(_) => {
+ let _ = pi::pi_abort_active_inner(&state, &chat_id).await;
+ }
+ }
+ });
+ }
+}
+
+/// Run one Pipe prompt in the exact existing chat selected in its config.
+/// Completion is receipt-based: returning Ok means the target turn reached a
+/// terminal idle state, not merely that it was accepted into Rust's queue.
+pub(crate) async fn run_pipe_in_existing_chat(
+ app: &tauri::AppHandle,
+ request: ChatDestinationRequest,
+) -> Result<(), String> {
+ let chat = chat_control::load_screenpipe_chat(&request.chat_id).map_err(|error| {
+ format!(
+ "selected chat is unavailable; choose another chat in scheduled task settings: {error}"
+ )
+ })?;
+ let state = app.state::<PiState>();
+ let running = {
+ let mut pool = state.0.lock().await;
+ pool.sessions
+ .get_mut(&request.chat_id)
+ .is_some_and(|manager| manager.is_running())
+ };
+
+ let message = if running {
+ request.message
+ } else {
+ let (provider_config, token) = provider_config_for_chat(app, &chat.conversation)?;
+ let project_dir = screenpipe_core::paths::default_screenpipe_data_dir()
+ .join("pi-chat")
+ .to_string_lossy()
+ .to_string();
+ let coding_workspace = crate::coding_workspace::launch_for_session(&request.chat_id)?;
+ let started = pi::pi_start_inner(
+ app.clone(),
+ state.inner(),
+ &request.chat_id,
+ project_dir,
+ token,
+ Some(provider_config),
+ coding_workspace,
+ )
+ .await?;
+ if !started.running {
+ return Err(started
+ .startup_error
+ .unwrap_or_else(|| "selected chat's AI agent did not start".to_string()));
+ }
+ chat_control::conversation_history_prompt(&chat.conversation, &request.message)
+ };
+
+ let (queue_id, mut completion_rx) = pi::pi_queue_prompt_tracked_inner(
+ app,
+ state.inner(),
+ &request.chat_id,
+ message,
+ Some(request.display_preview),
+ )
+ .await?;
+ let mut guard = ScheduledChatTurnGuard {
+ state: state.inner().clone(),
+ chat_id: request.chat_id,
+ queue_id,
+ armed: true,
+ };
+
+ loop {
+ tokio::select! {
+ completion = &mut completion_rx => {
+ guard.disarm();
+ return completion
+ .map_err(|_| "selected chat closed before the scheduled turn finished".to_string())?;
+ }
+ _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
+ if request.shared_pid.as_ref().is_some_and(|pid| {
+ pid.load(Ordering::SeqCst) == STOP_REQUESTED_PID
+ }) {
+ return Err("scheduled chat turn was cancelled".to_string());
+ }
+ }
+ }
+ }
+}
+
pub async fn ensure_broker(app: &tauri::AppHandle) -> Result<ChatControlEndpoint, String> {
CHAT_CONTROL_ENDPOINT
.get_or_try_init(|| async {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 1b2763026..466993252 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1929,6 +1929,7 @@ async fn main() {
// topic dropped — every pipe stdout line goes out on
// `agent_event` with a per-run or stable continued session id.
let app_for_pipe = app_handle.clone();
+ let app_for_chat_destination = app_handle.clone();
// Separate clone for the owned-browser install path — the
// on_pipe_output closure below captures app_for_pipe by
// move, so we need a distinct handle that survives into
@@ -1941,6 +1942,14 @@ async fn main() {
pipe_agent_events.emit_line(pipe_name, exec_id, continues_chat, line);
}),
);
+ let chat_destination: Option<
+ screenpipe_core::agents::chat_destination::ChatDestinationDispatch,
+ > = Some(std::sync::Arc::new(move |request| {
+ let app = app_for_chat_destination.clone();
+ Box::pin(async move {
+ crate::chat_control::run_pipe_in_existing_chat(&app, request).await
+ })
+ }));
let is_starting_after_spawn_error = is_starting_clone.clone();
let server_thread = std::thread::Builder::new()
@@ -2080,6 +2089,7 @@ async fn main() {
let server = match server_core::ServerCore::start(
&config,
on_pipe_output,
+ chat_destination,
Some(owned_browser),
cloud_token_arc.clone(),
history_access.clone(),
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 3f3319d24..27e2534d9 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -4470,6 +4470,68 @@ pub(crate) async fn pi_queue_prompt_inner(
Ok(queue_id)
}
+/// Queue a prompt and expose a terminal receipt for backend workflows that
+/// must distinguish "accepted" from "finished". The normal composer keeps
+/// using `pi_queue_prompt_inner`, which intentionally returns immediately.
+pub(crate) async fn pi_queue_prompt_tracked_inner(
+ app: &AppHandle,
+ state: &PiState,
+ sid: &str,
+ message: String,
+ display_preview: Option<String>,
+) -> Result<
+ (
+ String,
+ oneshot::Receiver<Result<(), String>>,
+ ),
+ String,
+> {
+ let mut conversation = acquire_pi_conversation_lease(state, sid).await?;
+ let message = conversation.prepare_prompt(message);
+ let preview = display_preview.unwrap_or_else(|| message.clone());
+ let message = attach_foreground_connections_context(app, sid, message).await;
+ #[cfg(feature = "e2e")]
+ emit_e2e_pi_wire_prompt(app, sid, "queue", &message);
+ let cmd = build_prompt_command(message, None, &preview)?;
+ let (queue_id, acceptance_rx, completion_rx) = conversation
+ .queue
+ .send_prompt_tracked(
+ cmd,
+ crate::pi_command_queue::WaitMode::Prompt,
+ preview,
+ true,
+ )
+ .await?;
+
+ let state_for_watchdog = state.clone();
+ let sid_for_watchdog = sid.to_string();
+ if conversation.is_synced() {
+ drop(conversation);
+ tokio::spawn(async move {
+ if let Err(error) =
+ await_prompt_start(&state_for_watchdog, &sid_for_watchdog, acceptance_rx).await
+ {
+ warn!(
+ "tracked Pi prompt failed before it started for session {}: {}",
+ sid_for_watchdog, error
+ );
+ }
+ });
+ } else {
+ tokio::spawn(async move {
+ match await_prompt_start(&state_for_watchdog, &sid_for_watchdog, acceptance_rx).await {
+ Ok(()) => conversation.mark_synced(),
+ Err(error) => warn!(
+ "tracked Pi prompt failed before it started for session {}: {}",
+ sid_for_watchdog, error
+ ),
+ }
+ });
+ }
+
+ Ok((queue_id, completion_rx))
+}
+
/// Steer the active Pi reply using Pi's native steering command.
/// Unlike `pi_prompt`, this is intentionally not added to the follow-up queue:
/// Pi interrupts the current stream and resumes with the steering instruction.
@@ -4561,11 +4623,19 @@ pub async fn pi_cancel_queued(
prompt_id: String,
) -> Result<bool, String> {
let sid = session_id.unwrap_or_else(|| "chat".to_string());
+ pi_cancel_queued_inner(state.inner(), &sid, prompt_id).await
+}
+
+pub(crate) async fn pi_cancel_queued_inner(
+ state: &PiState,
+ sid: &str,
+ prompt_id: String,
+) -> Result<bool, String> {
let queue = {
let pool = state.0.lock().await;
let m = pool
.sessions
- .get(&sid)
+ .get(sid)
.ok_or("session not found".to_string())?;
m.queue_handle
.clone()
@@ -4659,9 +4729,13 @@ pub async fn pi_abort_active(
session_id: Option<String>,
) -> Result<(), String> {
let sid = session_id.unwrap_or_else(|| "chat".to_string());
+ pi_abort_active_inner(state.inner(), &sid).await
+}
+
+pub(crate) async fn pi_abort_active_inner(state: &PiState, sid: &str) -> Result<(), String> {
let queue = {
let mut pool = state.0.lock().await;
- let m = pool.sessions.get_mut(&sid).ok_or("Pi not initialized")?;
+ let m = pool.sessions.get_mut(sid).ok_or("Pi not initialized")?;
if !m.is_running() {
return Err("Pi is not running".to_string());
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
index 09da98db1..d3b410a74 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi_command_queue.rs
@@ -82,6 +82,9 @@ pub struct PiCommand {
/// Channel to notify the caller when the command has been written to stdin
/// (for fire-and-forget prompts) or when `done` is received (for blocking commands).
pub reply: oneshot::Sender<Result<(), String>>,
+ /// Optional second receipt for callers that must know the whole turn
+ /// finished, not merely that Pi accepted the prompt.
+ pub completion: Option<oneshot::Sender<Result<(), String>>>,
/// Set on user-prompt commands so the queue can publish "what's pending"
/// to subscribers. None for new_session / abort / internal commands.
pub prompt_meta: Option<PiQueuedPrompt>,
@@ -538,6 +541,7 @@ impl PiQueueHandle {
payload,
wait_mode,
reply: tx,
+ completion: None,
prompt_meta: None,
}))
.await
@@ -555,6 +559,54 @@ impl PiQueueHandle {
wait_mode: WaitMode,
preview: String,
force_visible_queue: bool,
+ ) -> Result<(String, oneshot::Receiver<Result<(), String>>), String> {
+ self.send_prompt_with_completion(
+ payload,
+ wait_mode,
+ preview,
+ force_visible_queue,
+ None,
+ )
+ .await
+ }
+
+ /// Enqueue a prompt and return both its acceptance receipt and its terminal
+ /// turn receipt. Scheduled chat destinations use the latter so a Pipe is
+ /// never marked successful just because its message entered the queue.
+ pub async fn send_prompt_tracked(
+ &self,
+ payload: Value,
+ wait_mode: WaitMode,
+ preview: String,
+ force_visible_queue: bool,
+ ) -> Result<
+ (
+ String,
+ oneshot::Receiver<Result<(), String>>,
+ oneshot::Receiver<Result<(), String>>,
+ ),
+ String,
+ > {
+ let (completion_tx, completion_rx) = oneshot::channel();
+ let (id, acceptance_rx) = self
+ .send_prompt_with_completion(
+ payload,
+ wait_mode,
+ preview,
+ force_visible_queue,
+ Some(completion_tx),
+ )
+ .await?;
+ Ok((id, acceptance_rx, completion_rx))
+ }
+
+ async fn send_prompt_with_completion(
+ &self,
+ payload: Value,
+ wait_mode: WaitMode,
+ preview: String,
+ force_visible_queue: bool,
+ completion: Option<oneshot::Sender<Result<(), String>>>,
) -> Result<(String, oneshot::Receiver<Result<(), String>>), String> {
let id = format!("q_{}", uuid::Uuid::new_v4().simple());
let queued_at_ms = std::time::SystemTime::now()
@@ -584,6 +636,7 @@ impl PiQueueHandle {
payload,
wait_mode,
reply: tx,
+ completion,
prompt_meta: Some(meta),
}))
.await
@@ -892,7 +945,7 @@ fn spawn_queue_with_prompt_start_timeouts(
}
match msg {
- QueueMessage::Command(cmd) => {
+ QueueMessage::Command(mut cmd) => {
let prompt_id = cmd.prompt_meta.as_ref().map(|m| m.id.clone());
let is_prompt = prompt_id.is_some();
@@ -1115,6 +1168,11 @@ fn spawn_queue_with_prompt_start_timeouts(
// plain rejection (process still alive) just skips
// this one prompt and drains the next.
let wedged = matches!(&accepted, Err(error) if error == PROMPT_START_TIMEOUT_ERROR);
+ if let Err(error) = &accepted {
+ if let Some(completion) = cmd.completion.take() {
+ let _ = completion.send(Err(error.clone()));
+ }
+ }
let _ = cmd.reply.send(accepted);
if rejected {
state.cancel_response(&req_id);
@@ -1130,11 +1188,24 @@ fn spawn_queue_with_prompt_start_timeouts(
std::time::Duration::from_secs(300),
)
.await;
- if let PromptWait::Rejected(error) = wait {
- warn!(
- "pi_command_queue: {} was rejected after starting: {}",
- cmd_type, error
- );
+ let completion = match wait {
+ PromptWait::Idle => Ok(()),
+ PromptWait::Terminated => {
+ Err(format!("Pi process died during {cmd_type}"))
+ }
+ PromptWait::TimedOut => Err(format!(
+ "AI agent did not finish {cmd_type} within its idle timeout"
+ )),
+ PromptWait::Rejected(error) => {
+ warn!(
+ "pi_command_queue: {} was rejected after starting: {}",
+ cmd_type, error
+ );
+ Err(error)
+ }
+ };
+ if let Some(receipt) = cmd.completion.take() {
+ let _ = receipt.send(completion);
}
state.cancel_response(&req_id);
}
@@ -1676,6 +1747,92 @@ mod tests {
assert!(result.is_ok());
}
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn tracked_prompt_receipt_waits_for_terminal_idle() {
+ use std::process::{Command as StdCommand, Stdio};
+
+ let mut child = StdCommand::new("cat")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn fake pi");
+ let stdin = Arc::new(Mutex::new(child.stdin.take().expect("fake pi stdin")));
+ let state = PiQueueState::new();
+ let (handle, join) = spawn_queue(stdin, state.clone(), 0);
+
+ let (_, acceptance, mut completion) = handle
+ .send_prompt_tracked(
+ json!({ "type": "prompt", "message": "scheduled work" }),
+ WaitMode::Prompt,
+ "scheduled work".into(),
+ true,
+ )
+ .await
+ .expect("enqueue tracked prompt");
+ let request_id = wait_for_response_id(&state).await;
+ state.mark_agent_active();
+ state.signal_response(&request_id, Ok(()));
+ assert_eq!(acceptance.await.expect("acceptance receipt"), Ok(()));
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(25), &mut completion)
+ .await
+ .is_err(),
+ "terminal receipt must not resolve while the turn is active"
+ );
+
+ state.mark_agent_idle();
+ state.signal_done();
+ assert_eq!(completion.await.expect("completion receipt"), Ok(()));
+
+ state.signal_terminated();
+ drop(handle);
+ join.await.expect("queue join");
+ let _ = child.wait();
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn tracked_prompt_receipt_reports_process_death() {
+ use std::process::{Command as StdCommand, Stdio};
+
+ let mut child = StdCommand::new("cat")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .expect("spawn fake pi");
+ let stdin = Arc::new(Mutex::new(child.stdin.take().expect("fake pi stdin")));
+ let state = PiQueueState::new();
+ let (handle, join) = spawn_queue(stdin, state.clone(), 0);
+
+ let (_, acceptance, completion) = handle
+ .send_prompt_tracked(
+ json!({ "type": "prompt", "message": "scheduled work" }),
+ WaitMode::Prompt,
+ "scheduled work".into(),
+ true,
+ )
+ .await
+ .expect("enqueue tracked prompt");
+ let request_id = wait_for_response_id(&state).await;
+ state.mark_agent_active();
+ state.signal_response(&request_id, Ok(()));
+ assert_eq!(acceptance.await.expect("acceptance receipt"), Ok(()));
+
+ state.signal_terminated();
+ let terminal = completion
+ .await
+ .expect("terminal receipt")
+ .expect_err("process death must fail the tracked turn");
+ assert!(terminal.contains("process died"));
+
+ drop(handle);
+ join.await.expect("queue join");
+ let _ = child.wait();
+ }
+
#[cfg(unix)]
#[tokio::test]
async fn test_priority_abort_interrupts_active_prompt_and_drops_follow_up() {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index f162e2aa1..5df244372 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -1384,6 +1384,7 @@ async fn spawn_screenpipe_inner(
// topic with either a per-run or stable continued session id (see the matching
// helper in `apps/screenpipe-app-tauri/lib/events/types.ts`).
let app_for_pipe = app.clone();
+ let app_for_chat_destination = app.clone();
let app_for_owned = app.clone();
let app_for_port_conflict = app.clone();
@@ -1405,6 +1406,12 @@ async fn spawn_screenpipe_inner(
pipe_agent_events.emit_line(pipe_name, exec_id, continues_chat, line);
}),
);
+ let chat_destination: Option<
+ screenpipe_core::agents::chat_destination::ChatDestinationDispatch,
+ > = Some(std::sync::Arc::new(move |request| {
+ let app = app_for_chat_destination.clone();
+ Box::pin(async move { crate::chat_control::run_pipe_in_existing_chat(&app, request).await })
+ }));
// Oneshot for result
let (result_tx, result_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
@@ -1433,6 +1440,7 @@ async fn spawn_screenpipe_inner(
let server = match ServerCore::start(
&recording_config,
on_pipe_output,
+ chat_destination,
Some(owned_browser),
cloud_token_arc.clone(),
history_access.clone(),
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index 52f62c037..7a8c52453 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -292,6 +292,9 @@ impl ServerCore {
pub async fn start(
config: &RecordingConfig,
on_pipe_output: Option<screenpipe_core::pipes::OnPipeOutputLine>,
+ chat_destination: Option<
+ screenpipe_core::agents::chat_destination::ChatDestinationDispatch,
+ >,
owned_browser: Option<
std::sync::Arc<screenpipe_connect::connections::browser::OwnedBrowser>,
>,
@@ -739,6 +742,9 @@ impl ServerCore {
if let Some(cb) = on_pipe_output {
pipe_manager.set_on_output_line(cb);
}
+ if let Some(dispatch) = chat_destination {
+ pipe_manager.set_chat_destination_dispatch(dispatch);
+ }
// Give scheduled runs the same Live View target authority the foreground
// refresh button sends, so a Pipe feeding several dashboards refreshes
// all of them instead of leaving the ones it skipped stale until a
diff --git a/crates/screenpipe-core/src/agents/chat_control.rs b/crates/screenpipe-core/src/agents/chat_control.rs
index 06408a8bb..8480bc06c 100644
--- a/crates/screenpipe-core/src/agents/chat_control.rs
+++ b/crates/screenpipe-core/src/agents/chat_control.rs
@@ -1510,6 +1510,24 @@ pub struct ScreenpipeChat {
pub conversation: Value,
}
+/// Resolve one exact local chat by immutable id. This deliberately does not
+/// search by title or create a replacement: callers that hold a saved target
+/// must fail visibly when that file was deleted or became unreadable.
+pub fn load_screenpipe_chat(id: &str) -> Result<ScreenpipeChat, String> {
+ if id.trim().is_empty() || id.len() > 200 {
+ return Err("invalid chat id".to_string());
+ }
+ let path = screenpipe_chat_path(id)?;
+ let (summary, conversation, _) = parse_screenpipe_chat(&path)?;
+ if summary.id != id {
+ return Err("screenpipe chat id did not match its conversation file".to_string());
+ }
+ Ok(ScreenpipeChat {
+ summary,
+ conversation,
+ })
+}
+
#[derive(Clone, Debug)]
pub struct ScreenpipeDelivery {
pub status: String,
@@ -1551,18 +1569,10 @@ pub async fn send<H: ScreenpipeChatHost + ?Sized>(
}
let response = if request.source == ChatSource::Screenpipe {
- let path = screenpipe_chat_path(&request.id)?;
- let (summary, conversation, _) = parse_screenpipe_chat(&path)?;
- if summary.id != request.id {
- return Err("screenpipe chat id did not match its conversation file".to_string());
- }
+ let chat = load_screenpipe_chat(&request.id)?;
if request.origin_session_id.as_deref() == Some(request.id.as_str()) {
return Err("refused to send a chat to itself".to_string());
}
- let chat = ScreenpipeChat {
- summary,
- conversation,
- };
let delivery = host.send_to_screenpipe_chat(&request, &chat).await?;
ChatSendResponse {
status: delivery.status,
diff --git a/crates/screenpipe-core/src/agents/chat_destination.rs b/crates/screenpipe-core/src/agents/chat_destination.rs
new file mode 100644
index 000000000..f89a45b78
--- /dev/null
+++ b/crates/screenpipe-core/src/agents/chat_destination.rs
@@ -0,0 +1,184 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+//! Adapter that lets the Pipe runtime execute in an existing screenpipe chat.
+
+use super::{AgentExecutor, AgentOutput, ExecutionHandle, SharedPid};
+use anyhow::{anyhow, Result};
+use serde_json::Value;
+use std::future::Future;
+use std::path::Path;
+use std::pin::Pin;
+use std::sync::Arc;
+
+pub const CHAT_DESTINATION_EXECUTOR: &str = "screenpipe-chat";
+
+#[derive(Clone)]
+pub struct ChatDestinationRequest {
+ pub chat_id: String,
+ pub message: String,
+ pub display_preview: String,
+ pub shared_pid: Option<SharedPid>,
+}
+
+pub type ChatDestinationDispatch = Arc<
+ dyn Fn(
+ ChatDestinationRequest,
+ ) -> Pin<Box<dyn Future<Output = std::result::Result<(), String>> + Send>>
+ + Send
+ + Sync,
+>;
+
+pub struct ChatDestinationExecutor {
+ dispatch: ChatDestinationDispatch,
+}
+
+impl ChatDestinationExecutor {
+ pub fn new(dispatch: ChatDestinationDispatch) -> Self {
+ Self { dispatch }
+ }
+
+ fn chat_id(config: Option<&Value>) -> Result<String> {
+ let chat_id = config
+ .and_then(|value| value.get("chat_id"))
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| anyhow!("existing chat destination is missing its chat id"))?;
+ if chat_id.len() > 200 {
+ return Err(anyhow!("existing chat destination has an invalid chat id"));
+ }
+ Ok(chat_id.to_string())
+ }
+
+ fn execution_message(
+ prompt: &str,
+ pipe_system_prompt: Option<&str>,
+ working_dir: &Path,
+ ) -> String {
+ let output_dir = working_dir.join("output");
+ let directory_note = format!(
+ "Scheduled task directory: {}\nResolve relative task paths against this directory and write declared outputs under {}.",
+ working_dir.display(),
+ output_dir.display(),
+ );
+ match pipe_system_prompt
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ {
+ Some(instructions) => {
+ let instructions = instructions.replace(
+ "Output directory: ./output/",
+ &format!("Output directory: {}/", output_dir.display()),
+ );
+ format!("{directory_note}\n\n{instructions}\n\n{prompt}")
+ }
+ None => format!("{directory_note}\n\n{prompt}"),
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl AgentExecutor for ChatDestinationExecutor {
+ async fn run(
+ &self,
+ _prompt: &str,
+ _model: &str,
+ _working_dir: &Path,
+ _provider: Option<&str>,
+ _provider_url: Option<&str>,
+ _provider_api_key: Option<&str>,
+ _shared_pid: Option<SharedPid>,
+ _continue_session: bool,
+ ) -> Result<AgentOutput> {
+ Err(anyhow!(
+ "existing chat destinations require the streaming Pipe runtime"
+ ))
+ }
+
+ async fn run_streaming(
+ &self,
+ prompt: &str,
+ _model: &str,
+ working_dir: &Path,
+ _provider: Option<&str>,
+ _provider_url: Option<&str>,
+ _provider_api_key: Option<&str>,
+ shared_pid: Option<SharedPid>,
+ _line_tx: tokio::sync::mpsc::UnboundedSender<String>,
+ _continue_session: bool,
+ _thinking_level: Option<&str>,
+ pipe_system_prompt: Option<&str>,
+ _mcp_server_allowlist: Option<&[String]>,
+ _session_owner: Option<&str>,
+ executor_config: Option<&Value>,
+ ) -> Result<AgentOutput> {
+ let chat_id = Self::chat_id(executor_config)?;
+ let pipe_name = working_dir
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or("scheduled task");
+ (self.dispatch)(ChatDestinationRequest {
+ chat_id,
+ message: Self::execution_message(prompt, pipe_system_prompt, working_dir),
+ display_preview: format!("Scheduled task: {pipe_name}"),
+ shared_pid,
+ })
+ .await
+ .map_err(anyhow::Error::msg)?;
+
+ Ok(AgentOutput {
+ stdout: String::new(),
+ stderr: String::new(),
+ success: true,
+ pid: None,
+ })
+ }
+
+ fn kill(&self, _handle: &ExecutionHandle) -> Result<()> {
+ // The dispatch future owns an async cancellation guard. Pipe stop and
+ // timeout drop that future, which removes a queued prompt or aborts the
+ // active turn in the exact target chat.
+ Ok(())
+ }
+
+ fn is_available(&self) -> bool {
+ true
+ }
+
+ async fn ensure_installed(&self) -> Result<()> {
+ Ok(())
+ }
+
+ fn name(&self) -> &str {
+ CHAT_DESTINATION_EXECUTOR
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ChatDestinationExecutor;
+ use serde_json::json;
+
+ #[test]
+ fn exact_chat_id_is_required() {
+ assert!(ChatDestinationExecutor::chat_id(None).is_err());
+ assert!(ChatDestinationExecutor::chat_id(Some(&json!({ "chat_id": " " }))).is_err());
+ assert_eq!(
+ ChatDestinationExecutor::chat_id(Some(&json!({ "chat_id": " chat-42 " }))).unwrap(),
+ "chat-42"
+ );
+ }
+
+ #[test]
+ fn execution_message_includes_pipe_instructions_and_run_context() {
+ let message = ChatDestinationExecutor::execution_message(
+ "Run date: 2026-09-02",
+ Some("Summarize the customer's open issues."),
+ std::path::Path::new("/tmp/daily-recap"),
+ );
+ assert!(message.contains("Summarize the customer's open issues."));
+ assert!(message.contains("Run date: 2026-09-02"));
+ assert!(message.contains("/tmp/daily-recap/output"));
+ }
+}
diff --git a/crates/screenpipe-core/src/agents/mod.rs b/crates/screenpipe-core/src/agents/mod.rs
index 260d075d7..6dfc2b565 100644
--- a/crates/screenpipe-core/src/agents/mod.rs
+++ b/crates/screenpipe-core/src/agents/mod.rs
@@ -13,6 +13,7 @@
pub mod acp;
pub mod bash_env;
pub mod chat_control;
+pub mod chat_destination;
pub mod cli_runtime;
pub mod cloud;
mod cloud_context;
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 032a0d1d2..798893706 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -21,6 +21,9 @@ pub mod sync;
pub(crate) mod trajectory;
use crate::agents::{
+ chat_destination::{
+ ChatDestinationDispatch, ChatDestinationExecutor, CHAT_DESTINATION_EXECUTOR,
+ },
cloud::CloudAgentConfig,
pi::{pi_event_protocol_error, pi_package_enabled, PiExecutor},
AgentExecutor, ExecutionHandle, SharedPid, STOP_REQUESTED_PID,
@@ -385,6 +388,12 @@ pub struct PipeConfig {
#[serde(default, skip_serializing_if = "is_false")]
pub history: bool,
+ /// Route every run into one exact existing screenpipe chat. When omitted,
+ /// `history` keeps its legacy meaning: false creates one chat per run and
+ /// true continues the Pipe's own stable chat.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub run_in: Option<PipeRunIn>,
+
/// When true, the pipe's agent has `SCREENPIPE_FILTER_PII=1` in its
/// env so the BASH_ENV shim rewrites every `curl .../search` call to
/// append `filter_pii=1` — PII is redacted server-side before the
@@ -423,6 +432,41 @@ pub struct PipeConfig {
pub config: HashMap<String, serde_json::Value>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct PipeRunIn {
+ /// V1 intentionally supports only local screenpipe chats. The explicit
+ /// discriminator leaves the frontmatter forward-compatible with other
+ /// destination types without guessing from an id.
+ pub mode: PipeRunInMode,
+ pub chat_id: String,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum PipeRunInMode {
+ ExistingChat,
+}
+
+impl PipeConfig {
+ pub fn existing_chat_id(&self) -> Result<Option<&str>> {
+ let Some(run_in) = self.run_in.as_ref() else {
+ return Ok(None);
+ };
+ let chat_id = run_in.chat_id.trim();
+ if chat_id.is_empty() || chat_id.len() > 200 {
+ return Err(anyhow!("existing chat destination has an invalid chat id"));
+ }
+ Ok(Some(chat_id))
+ }
+}
+
+fn existing_chat_executor_config(config: &PipeConfig) -> Option<serde_json::Value> {
+ config
+ .run_in
+ .as_ref()
+ .map(|destination| serde_json::json!({ "chat_id": destination.chat_id }))
+}
+
struct CloudAgentRunSettings {
model: String,
provider: String,
@@ -736,6 +780,7 @@ const KNOWN_CONFIG_UPDATE_KEYS: &[&str] = &[
"connections",
"timeout",
"history",
+ "run_in",
"trigger",
"schedule_config",
];
@@ -888,6 +933,7 @@ fn remove_tombstone(pipes_dir: &Path, name: &str) -> Result<()> {
/// File name for the local overrides registry inside the pipes directory.
const LOCAL_OVERRIDES_FILE: &str = ".local-overrides.json";
+const LOCAL_RUN_DESTINATIONS_FILE: &str = ".local-run-destinations.json";
/// Read local enabled overrides from the pipes directory.
/// Returns an empty map on any error (missing file, corrupt JSON).
@@ -931,6 +977,41 @@ fn remove_local_override(pipes_dir: &Path, pipe_name: &str) -> Result<()> {
Ok(())
}
+/// Per-device chat destinations. Values are optional on purpose: an explicit
+/// null locally overrides a `run_in` block authored in synced pipe.md content.
+fn load_local_run_destinations(pipes_dir: &Path) -> HashMap<String, Option<PipeRunIn>> {
+ let path = pipes_dir.join(LOCAL_RUN_DESTINATIONS_FILE);
+ match std::fs::read_to_string(&path) {
+ Ok(content) => serde_json::from_str(&content).unwrap_or_else(|error| {
+ warn!("local run destinations file corrupt, ignoring: {}", error);
+ HashMap::new()
+ }),
+ Err(_) => HashMap::new(),
+ }
+}
+
+fn set_local_run_destination(
+ pipes_dir: &Path,
+ pipe_name: &str,
+ destination: Option<PipeRunIn>,
+) -> Result<()> {
+ let mut destinations = load_local_run_destinations(pipes_dir);
+ destinations.insert(pipe_name.to_string(), destination);
+ let path = pipes_dir.join(LOCAL_RUN_DESTINATIONS_FILE);
+ let json = serde_json::to_string_pretty(&destinations)?;
+ atomic_write(&path, &json)
+}
+
+fn remove_local_run_destination(pipes_dir: &Path, pipe_name: &str) -> Result<()> {
+ let mut destinations = load_local_run_destinations(pipes_dir);
+ if destinations.remove(pipe_name).is_some() {
+ let path = pipes_dir.join(LOCAL_RUN_DESTINATIONS_FILE);
+ let json = serde_json::to_string_pretty(&destinations)?;
+ atomic_write(&path, &json)?;
+ }
+ Ok(())
+}
+
// ---------------------------------------------------------------------------
// PID file helpers — defense-in-depth against duplicate pipe spawns.
// The PID file is the OS-level truth for "is this pipe running?"
@@ -3009,6 +3090,16 @@ impl PipeManager {
self.on_output_line = Some(cb);
}
+ /// Register the desktop-owned dispatcher for Pipes that run in an exact
+ /// existing chat. CLI/server builds omit this adapter and return a clear
+ /// "agent not available" error instead of falling back to another chat.
+ pub fn set_chat_destination_dispatch(&mut self, dispatch: ChatDestinationDispatch) {
+ self.executors.insert(
+ CHAT_DESTINATION_EXECUTOR.to_string(),
+ Arc::new(ChatDestinationExecutor::new(dispatch)),
+ );
+ }
+
/// Add an output consumer without replacing an existing desktop or stream
/// listener. Both callbacks receive every line in registration order.
pub fn add_on_output_line(&mut self, cb: OnPipeOutputLine) {
@@ -3091,6 +3182,7 @@ impl PipeManager {
paths.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
let local_overrides = load_local_overrides(&self.pipes_dir);
+ let local_run_destinations = load_local_run_destinations(&self.pipes_dir);
let mut selected = HashMap::new();
let mut all_names = HashSet::new();
let mut suppressed = Vec::new();
@@ -3135,6 +3227,9 @@ impl PipeManager {
if let Some(&enabled) = local_overrides.get(&dir_name) {
config.enabled = enabled;
}
+ if let Some(destination) = local_run_destinations.get(&dir_name) {
+ config.run_in = destination.clone();
+ }
selected.insert(dir_name, (config, body, content));
}
@@ -3857,7 +3952,17 @@ impl PipeManager {
preset_prompt,
run_agent,
run_executor_config,
- ) = if config.agent == "cloud-agent" {
+ ) = if let Some(chat_config) = existing_chat_executor_config(&config) {
+ (
+ "existing chat".to_string(),
+ None,
+ None,
+ None,
+ None,
+ CHAT_DESTINATION_EXECUTOR.to_string(),
+ Some(chat_config),
+ )
+ } else if config.agent == "cloud-agent" {
let cloud = cloud_agent_run_settings(&config, &body)
.map_err(|error| anyhow!("pipe '{}': {error}", name))?;
(
@@ -3980,7 +4085,11 @@ impl PipeManager {
};
match created {
Ok(id) => {
- if history_enabled {
+ if let Some(conversation_id) = config.existing_chat_id().ok().flatten() {
+ let _ = store
+ .set_execution_conversation_id(id, conversation_id)
+ .await;
+ } else if history_enabled {
let conversation_id = pipe_conversation_id(name, id, true);
let _ = store
.set_execution_conversation_id(id, &conversation_id)
@@ -4028,7 +4137,11 @@ impl PipeManager {
let _ = store.set_execution_running(id, None).await;
}
emit_pipe_start(
- self.on_output_line.as_ref(),
+ if config.run_in.is_none() {
+ self.on_output_line.as_ref()
+ } else {
+ None
+ },
&pipe_name,
exec_id.unwrap_or(0),
history_enabled,
@@ -4080,7 +4193,11 @@ impl PipeManager {
let store_ref = self.store.clone();
let on_complete = self.on_run_complete.clone();
let trigger_for_cb = trigger.to_string();
- let on_output = self.on_output_line.clone();
+ let on_output = if config.run_in.is_none() {
+ self.on_output_line.clone()
+ } else {
+ None
+ };
let pipes_dir_for_log = self.pipes_dir.clone();
let pipe_timeout = config.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS);
let mcp_session_access = self.mcp_session_access.clone();
@@ -4462,7 +4579,19 @@ impl PipeManager {
active_preset_idx,
run_agent,
run_executor_config,
- ) = if config.agent == "cloud-agent" {
+ ) = if let Some(chat_config) = existing_chat_executor_config(&config) {
+ (
+ "existing chat".to_string(),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ CHAT_DESTINATION_EXECUTOR.to_string(),
+ Some(chat_config),
+ )
+ } else if config.agent == "cloud-agent" {
let cloud = match cloud_agent_run_settings(&config, &body) {
Ok(cloud) => cloud,
Err(error) => {
@@ -4637,7 +4766,11 @@ impl PipeManager {
};
match created {
Ok(id) => {
- if history_enabled {
+ if let Some(conversation_id) = config.existing_chat_id().ok().flatten() {
+ let _ = store
+ .set_execution_conversation_id(id, conversation_id)
+ .await;
+ } else if history_enabled {
let conversation_id = pipe_conversation_id(name, id, true);
let _ = store
.set_execution_conversation_id(id, &conversation_id)
@@ -4686,7 +4819,11 @@ impl PipeManager {
let _ = store.set_execution_running(id, None).await;
}
emit_pipe_start(
- self.on_output_line.as_ref(),
+ if config.run_in.is_none() {
+ self.on_output_line.as_ref()
+ } else {
+ None
+ },
name,
exec_id.unwrap_or(0),
history_enabled,
@@ -4736,7 +4873,11 @@ impl PipeManager {
let (line_tx, mut line_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
let drain_pipe_name = name.to_string();
let drain_exec_id = exec_id.unwrap_or(0);
- let drain_on_output = self.on_output_line.clone();
+ let drain_on_output = if config.run_in.is_none() {
+ self.on_output_line.clone()
+ } else {
+ None
+ };
// Tee the full agent event stream to a per-run trajectory file
// (model-training/eval export). Best-effort: None on IO failure.
let mut drain_trajectory = trajectory::TrajectoryWriter::create(
@@ -5142,6 +5283,10 @@ impl PipeManager {
config.name = name.to_string(); // preserve directory name
atomic_write(&pipe_md, raw)?;
+ if let Some(destination) = load_local_run_destinations(&self.pipes_dir).get(name) {
+ config.run_in = destination.clone();
+ }
+
// Update in-memory
let mut pipes = self.pipes.lock().await;
if let Some(entry) = pipes.get_mut(name) {
@@ -5154,6 +5299,8 @@ impl PipeManager {
let (mut config, body) = parse_frontmatter(&content)?;
config.name = name.to_string(); // preserve directory name
+ let frontmatter_run_in = config.run_in.clone();
+ let mut local_run_destination_update: Option<Option<PipeRunIn>> = None;
let mut new_body = body.clone();
for (k, v) in &updates {
@@ -5234,6 +5381,32 @@ impl PipeManager {
config.history = value;
}
}
+ "run_in" => {
+ let destination =
+ if v.is_null() {
+ None
+ } else {
+ Some(serde_json::from_value::<PipeRunIn>(v.clone()).map_err(
+ |error| anyhow!("invalid run_in config for '{}': {}", name, error),
+ )?)
+ };
+ if let Some(ref destination) = destination {
+ let chat_id = destination.chat_id.trim();
+ if chat_id.is_empty() || chat_id.len() > 200 {
+ return Err(anyhow!(
+ "invalid run_in config for '{}': invalid chat id",
+ name
+ ));
+ }
+ }
+ local_run_destination_update = Some(destination.clone());
+ config.run_in = destination;
+ // An existing chat is already a continuing context. Do not
+ // also materialize the legacy Pipe-owned chat.
+ if config.run_in.is_some() {
+ config.history = false;
+ }
+ }
"trigger" => {
if v.is_null() {
config.trigger = None;
@@ -5268,9 +5441,19 @@ impl PipeManager {
}
}
+ // Chat ids belong to this device. Persist the source file exactly as it
+ // was authored and keep UI-selected destinations in the local registry.
+ config.run_in = frontmatter_run_in;
let new_content = serialize_pipe(&config, &new_body)?;
atomic_write(&pipe_md, &new_content)?;
+ if let Some(destination) = local_run_destination_update {
+ set_local_run_destination(&self.pipes_dir, name, destination)?;
+ }
+ if let Some(destination) = load_local_run_destinations(&self.pipes_dir).get(name) {
+ config.run_in = destination.clone();
+ }
+
// Update in-memory
let mut pipes = self.pipes.lock().await;
if let Some(entry) = pipes.get_mut(name) {
@@ -5578,6 +5761,12 @@ impl PipeManager {
if let Err(e) = remove_local_override(&self.pipes_dir, name) {
warn!("failed to remove local override for '{}': {}", name, e);
}
+ if let Err(e) = remove_local_run_destination(&self.pipes_dir, name) {
+ warn!(
+ "failed to remove local run destination for '{}': {}",
+ name, e
+ );
+ }
let mut pipes = self.pipes.lock().await;
pipes.remove(name);
@@ -6198,7 +6387,19 @@ impl PipeManager {
executor_config,
active_preset_id,
active_preset_idx,
- ) = if config.agent == "cloud-agent" {
+ ) = if let Some(chat_config) = existing_chat_executor_config(config) {
+ (
+ "existing chat".to_string(),
+ None,
+ None,
+ None,
+ None,
+ CHAT_DESTINATION_EXECUTOR.to_string(),
+ Some(chat_config),
+ None,
+ None,
+ )
+ } else if config.agent == "cloud-agent" {
let cloud = match cloud_agent_run_settings(config, body) {
Ok(cloud) => cloud,
Err(error) => {
@@ -6462,6 +6663,9 @@ impl PipeManager {
combined_context.as_deref(),
);
let pipe_name = name.clone();
+ let has_chat_destination = config.run_in.is_some();
+ let existing_chat_id =
+ config.existing_chat_id().ok().flatten().map(str::to_string);
let is_event_triggered = triggered_by_event;
let trigger = trigger.to_string();
let logs_ref = logs.clone();
@@ -6469,7 +6673,11 @@ impl PipeManager {
let running_exec_ids_ref = running_execution_ids.clone();
let pipes_dir_for_log = pipes_dir.clone();
let on_complete = on_run_complete.clone();
- let on_output = on_output_line.clone();
+ let on_output = if has_chat_destination {
+ None
+ } else {
+ on_output_line.clone()
+ };
let store_ref = store.clone();
let token_registry_ref = token_registry.clone();
let mcp_session_access_ref = mcp_session_access.clone();
@@ -6504,7 +6712,9 @@ impl PipeManager {
let fallback_event_context = event_triggered.get(name).cloned();
let fallback_runner = fallback_runner.clone();
let fallback_registry = fallback_registry.clone();
- let max_fallback_attempts = if is_enterprise_managed(config) {
+ let max_fallback_attempts = if run_agent == CHAT_DESTINATION_EXECUTOR
+ || is_enterprise_managed(config)
+ {
1
} else {
preset_ids.len().min(preset_fallback::MAX_FALLBACK_DEPTH)
@@ -6564,7 +6774,11 @@ impl PipeManager {
.await
{
Ok(id) => {
- if history_enabled {
+ if let Some(conversation_id) = existing_chat_id.as_deref() {
+ let _ = store
+ .set_execution_conversation_id(id, conversation_id)
+ .await;
+ } else if history_enabled {
let conversation_id =
pipe_conversation_id(&pipe_name, id, true);
let _ = store
@@ -7315,6 +7529,7 @@ pub fn parse_frontmatter(content: &str) -> Result<(PipeConfig, String)> {
let body = rest[end + 4..].trim().to_string();
let config: PipeConfig = serde_yaml::from_str(yaml_str)?;
+ config.existing_chat_id()?;
Ok((config, body))
}
@@ -7358,6 +7573,8 @@ pub fn serialize_pipe(config: &PipeConfig, body: &str) -> Result<String> {
"connections",
"permissions",
"timeout",
+ "history",
+ "run_in",
"trigger",
"source_slug",
"installed_version",
@@ -10832,6 +11049,55 @@ Run the scheduled task.
);
}
+ #[tokio::test]
+ async fn chat_destination_update_stays_local_and_can_be_cleared() {
+ let installed = tempfile::tempdir().unwrap();
+ let pipes_dir = installed.path().join("pipes");
+ std::fs::create_dir_all(&pipes_dir).unwrap();
+
+ let manager = PipeManager::new(pipes_dir.clone(), HashMap::new(), None, 0);
+ manager.install_builtin_pipes().unwrap();
+ manager.load_pipes().await.unwrap();
+ manager
+ .update_config(
+ "day-recap",
+ HashMap::from([(
+ "run_in".to_string(),
+ serde_json::json!({
+ "mode": "existing_chat",
+ "chat_id": "chat-on-this-device"
+ }),
+ )]),
+ )
+ .await
+ .unwrap();
+
+ let selected = manager.get_pipe("day-recap").await.unwrap();
+ assert_eq!(
+ selected.config.existing_chat_id().unwrap(),
+ Some("chat-on-this-device")
+ );
+ assert!(!selected.config.history);
+ let synced_source = std::fs::read_to_string(pipes_dir.join("day-recap/pipe.md")).unwrap();
+ assert!(!synced_source.contains("chat-on-this-device"));
+
+ manager
+ .update_config(
+ "day-recap",
+ HashMap::from([("run_in".to_string(), serde_json::Value::Null)]),
+ )
+ .await
+ .unwrap();
+ assert!(manager
+ .get_pipe("day-recap")
+ .await
+ .unwrap()
+ .config
+ .run_in
+ .is_none());
+ assert_eq!(load_local_run_destinations(&pipes_dir)["day-recap"], None);
+ }
+
#[test]
fn test_parse_frontmatter_trims_preset_ids() {
let content = "---\nschedule: every 1h\nenabled: true\npreset:\n - \" primary \"\n - \" \"\n - \"fallback \"\n---\n\nBody";
@@ -10921,6 +11187,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -11658,6 +11925,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -11819,6 +12087,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -11859,6 +12128,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -11889,6 +12159,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -11928,6 +12199,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -12055,6 +12327,7 @@ Run the scheduled task.
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -12223,6 +12496,45 @@ Run the scheduled task.
assert!(!config.history, "history should default to false");
}
+ #[test]
+ fn test_parse_frontmatter_existing_chat_destination() {
+ let content = "---\nschedule: every 4h\nrun_in:\n mode: existing_chat\n chat_id: chat-42\n---\n\nPrompt";
+ let (config, _) = parse_frontmatter(content).unwrap();
+ assert_eq!(config.existing_chat_id().unwrap(), Some("chat-42"));
+ assert!(existing_chat_executor_config(&config).is_some());
+ }
+
+ #[test]
+ fn test_parse_frontmatter_rejects_empty_existing_chat_id() {
+ let content =
+ "---\nschedule: every 4h\nrun_in:\n mode: existing_chat\n chat_id: ''\n---\n\nPrompt";
+ assert!(parse_frontmatter(content).is_err());
+ }
+
+ #[test]
+ fn local_chat_destination_can_override_and_clear_synced_config() {
+ let dir = tempfile::tempdir().unwrap();
+ set_local_run_destination(
+ dir.path(),
+ "daily-recap",
+ Some(PipeRunIn {
+ mode: PipeRunInMode::ExistingChat,
+ chat_id: "chat-on-this-device".to_string(),
+ }),
+ )
+ .unwrap();
+ assert_eq!(
+ load_local_run_destinations(dir.path())["daily-recap"]
+ .as_ref()
+ .unwrap()
+ .chat_id,
+ "chat-on-this-device"
+ );
+
+ set_local_run_destination(dir.path(), "daily-recap", None).unwrap();
+ assert_eq!(load_local_run_destinations(dir.path())["daily-recap"], None);
+ }
+
#[test]
fn test_pipe_conversation_id_reuses_only_continued_chat() {
assert_eq!(
diff --git a/crates/screenpipe-core/src/pipes/permissions.rs b/crates/screenpipe-core/src/pipes/permissions.rs
index 3bd70737a..e67b2874b 100644
--- a/crates/screenpipe-core/src/pipes/permissions.rs
+++ b/crates/screenpipe-core/src/pipes/permissions.rs
@@ -963,6 +963,7 @@ mod tests {
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -995,6 +996,7 @@ mod tests {
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,
@@ -1039,6 +1041,7 @@ mod tests {
source_hash: None,
subagent: false,
history: false,
+ run_in: None,
privacy_filter: false,
artifacts: vec![],
trigger: None,