YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: send email from pipes, daily log email pipe
Louis Beaumont1b7a29d1a926
diff --git a/examples/typescript/pipe-email-daily-log/README.md b/examples/typescript/pipe-email-daily-log/README.mdnew file mode 100644index 000000000..841154094--- /dev/null+++ b/examples/typescript/pipe-email-daily-log/README.md@@ -0,0 +1,28 @@+### phi3.5 engineering team logs+++++automates logging of engineering work to notion using screenpipe and phi3.5 ai.++#### quick setup++1. run ollama:+ ```+ ollama run phi3.5:3.8b-mini-instruct-q4_K_M+ ```++2. set up notion:+ - create integration: https://www.notion.so/my-integrations (copy api key)+ - make database with: Title, Description (rich text), Tags (multi-select), Date+ - share database with your integration (click three dots, connections, your integration), open database in full screen mode, copy the database id e.g. https://www.notion.so/some-database-id?v=some-database-version-id++3. configure pipe in the app ui, save, enable, restart screenpipe recording++<img width="1312" alt="Screenshot 2024-09-25 at 10 28 38" src="https://github.com/user-attachments/assets/08c79b70-dc85-45e8-bc59-eec6c7d58422">++boom! it'll log your work to notion every minute.++wanna tweak it? check `pipe.ts` to change frequency or adjust the ai prompt.++(can be used through CLI also)diff --git a/examples/typescript/pipe-email-daily-log/pipe.json b/examples/typescript/pipe-email-daily-log/pipe.jsonnew file mode 100644index 000000000..6318b38fa--- /dev/null+++ b/examples/typescript/pipe-email-daily-log/pipe.json@@ -0,0 +1,64 @@+{+ "fields": [+ {+ "name": "interval",+ "type": "number",+ "default": 60,+ "description": "Interval in seconds to read your screen data"+ },+ {+ "name": "emailTime",+ "type": "time",+ "default": "11:00",+ "description": "Time to send daily summary email"+ },+ {+ "name": "emailAddress",+ "type": "string",+ "default": "<fill your email address here>",+ "description": "Email Address"+ },+ {+ "name": "emailPassword",+ "type": "string",+ "default": "<fill your email password here>",+ "description": "Email Password https://support.google.com/accounts/answer/185833?hl=en"+ },+ {+ "name": "ollamaApiUrl",+ "type": "string",+ "default": "http://localhost:11434/api",+ "description": "Ollama API URL"+ },+ {+ "name": "ollamaModel",+ "type": "string",+ "default": "llama3.2:3b-instruct-q4_K_M",+ "description": "Ollama Model"+ },+ {+ "name": "pageSize",+ "type": "number",+ "default": 100,+ "description": "Number of records to retrieve from screenpipe per page, keep in mind LLMs have a context window limit"+ },+ {+ "name": "customPrompt",+ "type": "string",+ "default": "You are an AI assistant tasked with extracting structured information from screen data (OCR). Analyze the following screen data and extract relevant information about my daily activity.",+ "description": "Custom prompt for the AI assistant"+ },+ {+ "name": "summaryPrompt",+ "type": "string",+ "default": "You are an AI assistant tasked with summarizing information that has previously been extracted from screen data (OCR) by another AI assistant. Analyze the following structured data extracted from my screen data and summarize my daily activity, this will be send as a mail to my email address.",+ "description": "Summary prompt for the AI assistant"+ },+ {+ "name": "windowName",+ "type": "window",+ "default": "",+ "description": "Specific window name to filter the screen data, for example 'gmail', 'john', 'slack', 'myCodeFile.tsx', etc."+ }+ ]+}\ No newline at end of filediff --git a/examples/typescript/pipe-email-daily-log/pipe.ts b/examples/typescript/pipe-email-daily-log/pipe.tsnew file mode 100644index 000000000..ed130d3a0--- /dev/null+++ b/examples/typescript/pipe-email-daily-log/pipe.ts@@ -0,0 +1,323 @@+interface ScreenData {+ data: {+ content: {+ timestamp: string;+ text: string;+ };+ }[];+}++interface DailyLog {+ activity: string;+ category: string;+ tags: string[];+ timestamp: string;+}++function encodeQueryData(data: Record<string, string>): string {+ return Object.keys(data)+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)+ .join("&");+}++async function queryScreenpipe(+ startTime: string,+ endTime: string,+ windowName: string,+ pageSize: number+): Promise<ScreenData> {+ try {+ const params: Record<string, string> = {+ content_type: "ocr",+ limit: pageSize.toString(),+ offset: "0",+ start_time: startTime,+ end_time: endTime,+ };++ if (windowName) {+ params.window_name = windowName;+ }++ const queryString = encodeQueryData(params);+ const url = `http://localhost:3030/search?${queryString}`;+ console.log("query url:", url);++ const response = await fetch(url);+ if (!response.ok) {+ throw new Error(`http error! status: ${response.status}`);+ }+ return await response.json();+ } catch (error) {+ console.error("error querying screenpipe:", error);+ return { data: [] };+ }+}++async function generateDailyLog(+ screenData: ScreenData,+ customPrompt: string,+ ollamaModel: string,+ ollamaApiUrl: string+): Promise<DailyLog> {+ const prompt = `${customPrompt}++ Based on the following screen data, generate a concise daily log entry:++ ${JSON.stringify(screenData)}++ Return a JSON object with the following structure:+ {+ "activity": "Brief description of the activity",+ "category": "Category of the activity like work, email, slack, etc"+ "tags": ["productivity", "work", "email", "john", "salesforce", "etc"]+ }+++ Rules:+ - Do not add backticks to the JSON eg \`\`\`json\`\`\` is WRONG+ - DO NOT RETURN ANYTHING BUT JSON. NO COMMENTS BELOW THE JSON.++ `;++ const response = await fetch(ollamaApiUrl + "/chat", {+ method: "POST",+ body: JSON.stringify({+ model: ollamaModel,+ messages: [{ role: "user", content: prompt }],+ stream: false,+ response_format: { type: "json_object" },+ }),+ });++ if (!response.ok) {+ console.log("ollama response:", await response.text());+ throw new Error(`http error! status: ${response.status}`);+ }++ const result = await response.json();++ console.log("ai answer:", result);+ // clean up the result+ const cleanedResult = result.message.content+ .trim()+ .replace(/^```(?:json)?\s*|\s*```$/g, "") // remove start and end code block markers+ .replace(/\n/g, "") // remove newlines+ .replace(/\\n/g, "") // remove escaped newlines+ .trim(); // trim any remaining whitespace++ let content;+ try {+ content = JSON.parse(cleanedResult);+ } catch (error) {+ console.error("failed to parse ai response:", error);+ console.error("cleaned result:", cleanedResult);+ throw new Error("invalid ai response format");+ }++ return content;+}++async function saveDailyLog(logEntry: DailyLog): Promise<void> {+ const logsDir = `${process.env.PIPE_DIR}/logs`;+ fs.mkdirSync(logsDir);+ const timestamp = new Date()+ .toISOString()+ .replace(/:/g, "-")+ .replace(/\..+/, "");+ const filename = `${timestamp}-${logEntry.category.replace("/", "-")}.json`;+ fs.writeFileSync(`${logsDir}/${filename}`, JSON.stringify(logEntry, null, 2));+}++async function generateDailySummary(+ logs: DailyLog[],+ customPrompt: string,+ ollamaModel: string,+ ollamaApiUrl: string+): Promise<string> {+ const prompt = `${customPrompt}++ Based on the following daily logs, generate a concise summary of the day's activities:++ ${JSON.stringify(logs)}++ Provide a human-readable summary that highlights key activities and insights.`;++ console.log("daily summary prompt:", prompt);+ const response = await fetch(ollamaApiUrl + "/chat", {+ method: "POST",+ body: JSON.stringify({+ model: ollamaModel,+ messages: [{ role: "user", content: prompt }],+ stream: false,+ }),+ });+ console.log("daily summary ollama response:", response);++ if (!response.ok) {+ console.log("ollama response:", await response.text());+ throw new Error(`http error! status: ${response.status}`);+ }++ const result = await response.json();++ console.log("ai summary:", result);++ return result.message.content;+}++async function retry<T>(+ fn: () => Promise<T>,+ maxAttempts: number = 3,+ delay: number = 1000+): Promise<T> {+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ try {+ return await fn();+ } catch (error) {+ if (attempt === maxAttempts) {+ throw error;+ }+ console.log(`attempt ${attempt} failed, retrying in ${delay}ms...`);+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }+ throw new Error("this should never happen");+}++async function sendEmail(+ to: string,+ password: string,+ subject: string,+ body: string+): Promise<void> {+ const from = to; // assuming the sender is the same as the recipient+ await retry(async () => {+ const result = await pipe.sendEmail({+ to,+ from,+ password,+ subject,+ body,+ });+ if (!result) {+ throw new Error("failed to send email");+ }+ console.log(`email sent to ${to} with subject: ${subject}`);+ });+}++async function dailyLogPipeline(): Promise<void> {+ console.log("starting daily log pipeline");++ const config = await pipe.loadConfig();+ console.log("loaded config:", JSON.stringify(config, null, 2));++ const interval = config.interval * 1000;+ const emailTime = config.emailTime;+ const emailAddress = config.emailAddress;+ const emailPassword = config.emailPassword;+ const customPrompt = config.customPrompt!;+ const summaryPrompt = config.summaryPrompt!;+ const ollamaModel = config.ollamaModel;+ const ollamaApiUrl = config.ollamaApiUrl;+ const windowName = config.windowName || "";+ const pageSize = config.pageSize;++ let lastEmailSent = new Date(0); // Initialize to a past date+ let logEntries: DailyLog[] = []; // Store log entries in memory++ // send a welcome email to announce what will happen, when it will happen, and what it will do+ const welcomeEmail = `+ Welcome to the daily log pipeline!++ This pipe will send you a daily summary of your activities.+ It will run at ${emailTime} every day.++ `;+ await sendEmail(+ emailAddress,+ emailPassword,+ "daily activity summary",+ welcomeEmail+ );++ while (true) {+ try {+ const now = new Date();+ const oneMinuteAgo = new Date(now.getTime() - interval);++ const screenData = await queryScreenpipe(+ oneMinuteAgo.toISOString(),+ now.toISOString(),+ windowName,+ pageSize+ );++ if (screenData.data && screenData.data.length > 0) {+ const logEntry = await generateDailyLog(+ screenData,+ customPrompt,+ ollamaModel,+ ollamaApiUrl+ );+ console.log("log entry:", logEntry);+ await saveDailyLog(logEntry);+ logEntries.push(logEntry); // Store the log entry in memory+ }++ const [emailHour, emailMinute] = emailTime.split(":").map(Number);+ const emailTimeToday = new Date(+ now.getFullYear(),+ now.getMonth(),+ now.getDate(),+ emailHour,+ emailMinute+ );++ if (+ now >= emailTimeToday &&+ now.getTime() - lastEmailSent.getTime() > 24 * 60 * 60 * 1000+ ) {+ const todayStart = new Date(+ now.getFullYear(),+ now.getMonth(),+ now.getDate()+ );++ // Filter log entries for today+ // const todayLogs = logEntries.filter(+ // (log) => new Date(log.timestamp) >= todayStart+ // );++ // console.log("today's logs:", todayLogs);++ // if (todayLogs.length > 0) {+ await retry(async () => {+ const summary = await generateDailySummary(+ logEntries,+ summaryPrompt,+ ollamaModel,+ ollamaApiUrl+ );+ console.log("summary:", summary);+ await sendEmail(+ emailAddress,+ emailPassword,+ "daily activity summary",+ summary+ );+ });++ lastEmailSent = now;+ logEntries = [];+ // }+ }+ } catch (error) {+ console.error("error in daily log pipeline:", error);+ }+ await new Promise((resolve) => setTimeout(resolve, interval));+ }+}++dailyLogPipeline();diff --git a/examples/typescript/pipe-email-daily-log/screenpipe.d.ts b/examples/typescript/pipe-email-daily-log/screenpipe.d.tsnew file mode 100644index 000000000..024826813--- /dev/null+++ b/examples/typescript/pipe-email-daily-log/screenpipe.d.ts@@ -0,0 +1,53 @@+declare global {+ const pipe: {+ readFile: (path: string) => Promise<string>;+ writeFile: (path: string, contents: string) => Promise<void>;+ removeFile: (path: string) => Promise<void>;+ get: (url: string) => Promise<any>;+ post: (url: string, body: string) => Promise<any>;+ fetch: (url: string, options?: RequestInit) => Promise<Response>;+ sendNotification: (options: {+ title: string;+ body: string;+ }) => Promise<any>;+ loadConfig: () => Promise<Record<string, any>>;+ config: Record<string, any>;+ metadata: {+ id: string;+ };+ sendEmail: (options: {+ to: string;+ from: string;+ password: string;+ subject: string;+ body: string;+ }) => Promise<boolean>;+ };++ const fs: {+ readFileSync: (path: string) => string;+ writeFileSync: (path: string, contents: string) => void;+ readdirSync: (path: string) => string[];+ mkdirSync: (path: string) => void;+ };++ const path: {+ join: (...paths: string[]) => string;+ };++ namespace NodeJS {+ interface ProcessEnv {+ SCREENPIPE_DIR: string;+ SCREENPIPE_LOG_API_URL?: string;+ SCREENPIPE_SERVER_URL?: string;+ PIPE_DIR: string;+ NOTION_DATABASE_ID: string;+ NOTION_API_KEY: string;+ }+ }+ const process: {+ env: NodeJS.ProcessEnv;+ };+}++export {};diff --git a/examples/typescript/pipe-email-daily-log/tsconfig.json b/examples/typescript/pipe-email-daily-log/tsconfig.jsonnew file mode 100644index 000000000..c4e6dfdd7--- /dev/null+++ b/examples/typescript/pipe-email-daily-log/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "es2018",+ "module": "esnext",+ "moduleResolution": "node",+ "outDir": "./",+ "rootDir": "./",+ "strict": true,+ "esModuleInterop": true+ },+ "include": [+ "./**/*.ts"+ ],+ "exclude": [+ "node_modules"+ ]+}\ No newline at end of filediff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.jsonindex 4fc31a3fc..23a65c9a5 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.json@@ -27,7 +27,7 @@{"name": "ollamaModel","type": "string",- "default": "phi3.5:3.8b-mini-instruct-q4_K_M",+ "default": "llama3.2:3b-instruct-q4_K_M","description": "Ollama Model"},{diff --git a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.tsindex 807af5b3e..2f76d21e1 100644--- a/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts+++ b/examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts@@ -1,9 +1,4 @@-const DEFAULT_INTERVAL = 60 * 60 * 1000; // 1 hour in milliseconds-const DEFAULT_OLLAMA_API_URL = "http://localhost:11434/api/chat";-const DEFAULT_OLLAMA_MODEL = "phi3.5:3.8b-mini-instruct-q4_K_M";const NOTION_API_URL = "https://api.notion.com/v1/pages";-const DEFAULT_NOTION_DATABASE_ID = process.env.NOTION_DATABASE_ID;-const DEFAULT_NOTION_API_KEY = process.env.NOTION_API_KEY;interface ScreenData {data: {@@ -38,7 +33,9 @@ async function queryScreenpipe(}async function generateEngineeringLog(- screenData: ScreenData+ screenData: ScreenData,+ ollamaApiUrl: string,+ ollamaModel: string): Promise<EngineeringLog> {const prompt = `Based on the following screen data, generate a concise engineering log entry:@@ -53,14 +50,23 @@ async function generateEngineeringLog(}Provide 1-3 relevant tags related to the engineering work.`;- const result = await pipe.post(- "http://localhost:11434/api/chat",- JSON.stringify({- model: "phi3.5",+ const response = await fetch(ollamaApiUrl + "/chat", {+ method: "POST",+ body: JSON.stringify({+ model: ollamaModel,messages: [{ role: "user", content: prompt }],stream: false,- })- );+ }),+ });+ if (!response.ok) {+ const errorBody = await response.text();+ console.error("Error generating engineering log:", errorBody);+ throw new Error(+ `HTTP error! status: ${response.status}, body: ${errorBody}`+ );+ }++ const result = await response.json();console.log("AI answer:", result);@@ -114,11 +120,11 @@ async function streamEngineeringLogsToNotion(): Promise<void> {const config = await pipe.loadConfig();console.log("loaded config:", JSON.stringify(config, null, 2));- const interval = config.interval || DEFAULT_INTERVAL;- const databaseId = config.notionDatabaseId || DEFAULT_NOTION_DATABASE_ID;- const apiKey = config.notionApiKey || DEFAULT_NOTION_API_KEY;- const ollamaApiUrl = config.ollamaApiUrl || DEFAULT_OLLAMA_API_URL;- const ollamaModel = config.ollamaModel || DEFAULT_OLLAMA_MODEL;+ const interval = config.interval * 1000;+ const databaseId = config.notionDatabaseId;+ const apiKey = config.notionApiKey;+ const ollamaApiUrl = config.ollamaApiUrl;+ const ollamaModel = config.ollamaModel;while (true) {try {@@ -131,7 +137,11 @@ async function streamEngineeringLogsToNotion(): Promise<void> {);if (screenData.data && screenData.data.length > 0) {- const logEntry = await generateEngineeringLog(screenData);+ const logEntry = await generateEngineeringLog(+ screenData,+ ollamaApiUrl,+ ollamaModel+ );await syncLogToNotion(logEntry, apiKey, databaseId);} else {console.log("No relevant engineering work detected in the last hour");diff --git a/screenpipe-app-tauri/components/pipe-config-form.tsx b/screenpipe-app-tauri/components/pipe-config-form.tsxindex d4676b100..24e6bf19c 100644--- a/screenpipe-app-tauri/components/pipe-config-form.tsx+++ b/screenpipe-app-tauri/components/pipe-config-form.tsx@@ -10,9 +10,10 @@ import {TooltipProvider,TooltipTrigger,} from "./ui/tooltip";-import { RefreshCw } from "lucide-react";+import { Layout, RefreshCw } from "lucide-react";import { toast } from "./ui/use-toast";import { Pipe } from "./pipe-store";+import { SqlAutocompleteInput } from "./sql-autocomplete-input";type PipeConfigFormProps = {pipe: Pipe;@@ -138,6 +139,65 @@ export const PipeConfigForm: React.FC<PipeConfigFormProps> = ({</TooltipProvider></div>);+ case "time":+ return (+ <div className="flex items-center space-x-2">+ <Input+ id={field.name}+ type="time"+ value={value}+ onChange={(e) => handleInputChange(field.name, e.target.value)}+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ size="icon"+ variant="ghost"+ onClick={resetToDefault}+ className="h-8 w-8"+ >+ <RefreshCw className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Reset to default</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ );+ case "window":+ return (+ <div className="flex items-center space-x-2 w-full">+ <SqlAutocompleteInput+ className="w-full"+ id={field.name}+ placeholder={`Enter ${field.name}`}+ value={value}+ onChange={(newValue) => handleInputChange(field.name, newValue)}+ type="window"+ icon={<Layout className="h-4 w-4" />}+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ size="icon"+ variant="ghost"+ onClick={resetToDefault}+ className="h-8 w-8"+ >+ <RefreshCw className="h-4 w-4" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Reset to default</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ );default:return (<div className="flex items-center space-x-2">diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsxindex 26a70c1a2..8b5eb12ed 100644--- a/screenpipe-app-tauri/components/pipe-store.tsx+++ b/screenpipe-app-tauri/components/pipe-store.tsx@@ -19,18 +19,21 @@ import { useSettings } from "@/lib/hooks/use-settings";import { invoke } from "@tauri-apps/api/core";import { toast } from "./ui/use-toast";import { Input } from "./ui/input";-import { Download, Plus, Trash2, ExternalLink } from "lucide-react";+import {+ Download,+ Plus,+ Trash2,+ ExternalLink,+ FolderOpen,+ RefreshCw,+ Power,+ Link,+ Heart,+} from "lucide-react";import { PipeConfigForm } from "./pipe-config-form";import { useHealthCheck } from "@/lib/hooks/use-health-check";import posthog from "posthog-js";-const formatDate = (dateString: string) => {- const date = new Date(dateString);- return date.toLocaleDateString("en-US", {- year: "numeric",- month: "long",- day: "numeric",- });-};+import { open } from "@tauri-apps/plugin-dialog";import {Tooltip,@@ -41,6 +44,12 @@ import {import { readFile } from "@tauri-apps/plugin-fs";import { homeDir, join } from "@tauri-apps/api/path";import { convertHtmlToMarkdown } from "@/lib/utils";+import LogViewer from "./log-viewer-v2";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";export interface Pipe {enabled: boolean;@@ -59,7 +68,8 @@ interface CorePipe {const corePipes: CorePipe[] = [{id: "pipe-phi3.5-engineering-team-logs",- description: "continuously write logs of your days in a notion table using ollama+phi3.5",+ description:+ "continuously write logs of your days in a notion table using ollama+phi3.5",url: "https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs",},// {@@ -75,6 +85,8 @@ const PipeDialog: React.FC = () => {const [pipes, setPipes] = useState<Pipe[]>([]);const { settings, updateSettings } = useSettings();const { health } = useHealthCheck();+ const [isLogOpen, setIsLogOpen] = useState(false);+useEffect(() => {fetchInstalledPipes();}, [health?.status]);@@ -111,7 +123,7 @@ const PipeDialog: React.FC = () => {}}};- console.log("pipes", pipes);+ // console.log("pipes", pipes);const fetchInstalledPipes = async () => {if (!health || health?.status === "error") {return;@@ -290,6 +302,27 @@ const PipeDialog: React.FC = () => {}};+ const handleLoadFromLocalFolder = async () => {+ try {+ const selectedFolder = await open({+ directory: true,+ multiple: false,+ });++ if (selectedFolder) {+ // set in the bar+ setNewRepoUrl(selectedFolder);+ }+ } catch (error) {+ console.error("failed to load pipe from local folder:", error);+ toast({+ title: "error loading pipe",+ description: "please try again or check the logs for more information.",+ variant: "destructive",+ });+ }+ };+const handleConfigSave = async (config: Record<string, any>) => {if (selectedPipe) {fetch(`http://localhost:3030/pipes/update`, {@@ -354,16 +387,38 @@ const PipeDialog: React.FC = () => {variant={selectedPipe.enabled ? "default" : "outline"}disabled={health?.status === "error"}>+ <Power className="mr-2 h-4 w-4" />{selectedPipe.enabled ? "disable" : "enable"}</Button>+ {!selectedPipe.source.startsWith("https://") && (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={() => handleRefreshFromDisk(selectedPipe)}+ variant="outline"+ >+ <RefreshCw className="mr-2 h-4 w-4" />+ refresh+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>refresh the code from your local disk</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ )}+<Button disabled variant="outline">+ <Link className="mr-2 h-4 w-4" />copy share link<Badge variant="secondary" className="ml-2">soon</Badge></Button><Button disabled variant="outline">+ <Heart className="mr-2 h-4 w-4" />donate<Badge variant="secondary" className="ml-2">soon@@ -374,11 +429,27 @@ const PipeDialog: React.FC = () => {{selectedPipe.enabled && (<>+ <Collapsible+ open={isLogOpen}+ onOpenChange={setIsLogOpen}+ className="w-full mt-4"+ >+ <div className="flex items-center justify-between w-full">+ <CollapsibleTrigger className="flex items-center justify-between p-2 flex-grow border-b border-gray-200">+ screenpipe logs+ <span>{isLogOpen ? "▲" : "▼"}</span>+ </CollapsibleTrigger>+ </div>+ <CollapsibleContent>+ <LogViewer className="mt-2" />+ </CollapsibleContent>+ </Collapsible>+ <Separator className="my-4" />+<PipeConfigFormpipe={selectedPipe}onConfigSave={handleConfigSave}/>- <Separator className="my-4" /></>)}@@ -440,6 +511,43 @@ const PipeDialog: React.FC = () => {);};+ // Add this function to handle refreshing from disk+ const handleRefreshFromDisk = async (pipe: Pipe) => {+ try {+ posthog.capture("refresh_pipe_from_disk", {+ pipe_id: pipe.id,+ });+ toast({+ title: "refreshing pipe",+ description: "please wait...",+ });+ const response = await fetch(`http://localhost:3030/pipes/download`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ url: pipe.source }),+ });+ if (!response.ok) {+ throw new Error("failed to refresh pipe");+ }+ await fetchInstalledPipes();+ toast({+ title: "pipe refreshed",+ description: "the pipe has been successfully refreshed from disk.",+ });+ } catch (error) {+ console.error("failed to refresh pipe from disk:", error);+ toast({+ title: "error refreshing pipe",+ description: "please try again or check the logs for more information.",+ variant: "destructive",+ });+ } finally {+ setSelectedPipe(null);+ }+ };+const renderCorePipes = () => (<div className="mb-3"><h3 className="text-lg font-semibold mb-2">try these pipes</h3>@@ -509,6 +617,14 @@ const PipeDialog: React.FC = () => {<Plus className="mr-2" size={16} />add your own pipe</Button>+ <Button+ className="mt-2 w-full"+ onClick={handleLoadFromLocalFolder}+ variant="outline"+ >+ <FolderOpen className="mr-2" size={16} />+ load from local folder+ </Button></Card></div><div className="w-full pl-4 border-l overflow-y-auto">diff --git a/screenpipe-app-tauri/components/sql-autocomplete-input.tsx b/screenpipe-app-tauri/components/sql-autocomplete-input.tsxindex 9164256ef..dbed0f9e7 100644--- a/screenpipe-app-tauri/components/sql-autocomplete-input.tsx+++ b/screenpipe-app-tauri/components/sql-autocomplete-input.tsx@@ -3,6 +3,7 @@ import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";import { Command } from "cmdk";import { Input } from "@/components/ui/input";import { Loader2, Search, X } from "lucide-react";+import { cn } from "@/lib/utils";interface SqlAutocompleteInputProps {id: string;@@ -11,6 +12,7 @@ interface SqlAutocompleteInputProps {onChange: (value: string) => void;type: "app" | "window";icon: React.ReactNode;+ className?: string;}export function SqlAutocompleteInput({@@ -20,6 +22,7 @@ export function SqlAutocompleteInput({onChange,type,icon,+ className,}: SqlAutocompleteInputProps) {const { items, isLoading } = useSqlAutocomplete(type);const [open, setOpen] = useState(false);@@ -71,7 +74,7 @@ export function SqlAutocompleteInput({}, []);return (- <div className="relative" ref={commandRef}>+ <div className={cn("relative", className)} ref={commandRef}><div className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400 z-10 flex items-center">{icon}<span className="w-2" />diff --git a/screenpipe-core/Cargo.toml b/screenpipe-core/Cargo.tomlindex dbae32292..c84ce6f63 100644--- a/screenpipe-core/Cargo.toml+++ b/screenpipe-core/Cargo.toml@@ -34,7 +34,7 @@ tracing = { workspace = true }tracing-subscriber = { workspace = true }dirs = "5.0.0"-+lettre = "0.11.0"[features]default = ["pipes", "security"]llm = ["candle", "candle-nn", "candle-transformers", "tokenizers", "hf-hub"]diff --git a/screenpipe-core/src/deno/runtime.js b/screenpipe-core/src/deno/runtime.jsindex 1fde05b41..768eb63da 100644--- a/screenpipe-core/src/deno/runtime.js+++ b/screenpipe-core/src/deno/runtime.js@@ -142,6 +142,15 @@ const pipe = {return {};}},+ sendEmail: async ({ to, from, password, subject, body }) => {+ try {+ await ops.op_send_email(to, from, password, subject, body);+ return true;+ } catch (error) {+ console.error("Error sending email:", error);+ return false;+ }+ },// isEnabled: async () => {// return ops.op_is_enabled();// }@@ -164,6 +173,29 @@ const fs = { // TODO does not work?.then(resolve).catch(reject);});+ },+ readdirSync: (path) => {+ return new Promise((resolve, reject) => {+ ops.op_readdir(path)+ .then(resolve)+ .catch(reject);+ });+ },+ mkdirSync: (path) => {+ // This is a synchronous wrapper around the async operation+ return new Promise((resolve, reject) => {+ ops.op_create_dir(path)+ .then(resolve)+ .catch(reject);+ });+ },+ statSync: (path) => {+ // This is a synchronous wrapper around the async operation+ return new Promise((resolve, reject) => {+ ops.op_stat(path)+ .then(resolve)+ .catch(reject);+ });}};@@ -185,4 +217,3 @@ globalThis.pipe = pipe;globalThis.pipe.metadata = globalThis.metadata;globalThis.fetch = pipe.fetch;globalThis.loadConfig = pipe.loadConfig;-diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 4f7f0cdff..95a7da3d6 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -22,6 +22,8 @@ mod pipes {use reqwest::Client;use serde_json::Value;+ use lettre::transport::smtp::authentication::Credentials;+ use lettre::{Message, SmtpTransport, Transport};use reqwest;use std::path::Path;use tracing::{error, info};@@ -127,6 +129,20 @@ mod pipes {})}+ #[op2(async)]+ #[serde]+ async fn op_readdir(#[string] path: String) -> anyhow::Result<Vec<String>, AnyError> {+ let mut entries = tokio::fs::read_dir(&path).await?;+ let mut file_names = Vec::new();+ while let Some(entry) = entries.next_entry().await? {+ let path = entry.path();+ if let Some(file_name) = path.file_name().and_then(|os_str| os_str.to_str()) {+ file_names.push(file_name.to_string());+ }+ }+ Ok(file_names)+ }+#[op2(async)]#[string]async fn op_fetch_get(#[string] url: String) -> anyhow::Result<String, AnyError> {@@ -185,6 +201,42 @@ mod pipes {Ok(())}+ #[op2(async)]+ #[string]+ async fn op_send_email(+ #[string] to: String,+ #[string] from: String,+ #[string] password: String,+ #[string] subject: String,+ #[string] body: String,+ ) -> anyhow::Result<String, AnyError> {+ let email = Message::builder()+ .from(from.parse()?)+ .to(to.parse()?)+ .subject(subject)+ .body(body)?;++ let creds = Credentials::new(from.clone(), password);++ let mailer = SmtpTransport::relay("smtp.gmail.com")?+ .credentials(creds)+ .build();++ match mailer.send(&email) {+ Ok(_) => Ok("Email sent successfully".to_string()),+ Err(e) => Err(anyhow::anyhow!("Could not send email: {:?}", e)),+ }+ }++ // Add this new operation+ #[op2(async)]+ async fn op_create_dir(#[string] path: String) -> anyhow::Result<(), AnyError> {+ tokio::fs::create_dir_all(&path).await.map_err(|e| {+ error!("Failed to create directory '{}': {}", path, e);+ AnyError::from(e)+ })+ }+struct TsModuleLoader;impl deno_core::ModuleLoader for TsModuleLoader {@@ -270,6 +322,9 @@ mod pipes {op_set_timeout,op_fetch,op_get_env,+ op_readdir,+ op_send_email,+ op_create_dir,]}@@ -542,7 +597,11 @@ mod pipes {let file_name = item["name"].as_str().unwrap();let download_url = item["download_url"].as_str().unwrap();- if file_name == "pipe.js" || file_name == "pipe.ts" || file_name == "pipe.json" || file_name == "README.md" {+ if file_name == "pipe.js"+ || file_name == "pipe.ts"+ || file_name == "pipe.json"+ || file_name == "README.md"+ {let file_content = client.get(download_url).send().await?.bytes().await?;let file_path = pipe_dir.join(file_name);tokio::fs::write(&file_path, &file_content).await?;diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rsindex fd655aae5..85e72d7d3 100644--- a/screenpipe-core/tests/pipes_test.rs+++ b/screenpipe-core/tests/pipes_test.rs@@ -232,4 +232,44 @@ mod tests {assert!(result.is_err(), "Expected an error for invalid URL");}++ #[tokio::test]+ #[ignore]+ async fn test_send_email() {+ let temp_dir = TempDir::new().unwrap();+ let screenpipe_dir = temp_dir.path().to_path_buf();+ let to = std::env::var("EMAIL_TO").expect("EMAIL_TO not set");+ let from = std::env::var("EMAIL_TO").expect("EMAIL_TO not set");+ let password = std::env::var("EMAIL_PASSWORD").expect("EMAIL_PASSWORD not set");++ println!("to: {}", to);+ println!("from: {}", from);+ println!("password: {}", password);+ let code = format!(+ r#"+ (async () => {{+ const result = await pipe.sendEmail({{+ to: "{to}",+ from: "{from}",+ password: "{password}",+ subject: "Test Email from Screenpipe",+ body: "This is a test email sent from the Screenpipe unit test."+ }});+ console.log("Email sent:", result);+ if (!result) {{+ throw new Error("Failed to send email");+ }}+ }})();+ "#+ );+ println!("code: {}", code);++ let pipe_dir = setup_test_pipe(&temp_dir, "email_test_pipe", &code).await;++ // Change the working directory to the pipe directory+ std::env::set_current_dir(&pipe_dir).unwrap();++ let result = run_pipe(pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;+ assert!(result.is_ok(), "Pipe execution failed: {:?}", result);+ }}