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: AI inbox human in the loop

Louis Beaumont71e6924a03b6
diff --git a/content/docs/pages/docs/plugins.mdx b/content/docs/pages/docs/plugins.mdx
index a9d3078d9..03eb6d8aa 100644
--- a/content/docs/pages/docs/plugins.mdx
+++ b/content/docs/pages/docs/plugins.mdx
@@ -3,179 +3,111 @@ import MotionDiv from '@/components/motion-div';
# plugins (pipes)
<MotionDiv>
- an essential part of screenpipe is that it is extensible, providing powerful extensibility through custom workflows that interact with captured screen and audio data. whether you need to tag activities, generate summaries, or send data to third-party services, plugins allow you to tailor screenpipe to your specific needs.
+ screenpipe is built for extensibility through plugins that interact with captured screen and audio data. whether you need to tag activities, generate summaries, or send data to third-party services, plugins let you build powerful workflows.
- plugins in screenpipe are categorized into 2 types:
-
- - **pipes**: these are plugins with native integration with screenpipe. they can run within the cli/lib/app without the need for manual execution. they run in a sandboxed environment, and can be written in Typescript or Javascript.
- - **standalone scripts**: these are independent scripts that need to be run separately and may require additional setup.
+ plugins come in two flavors:
+ - **pipes**: native plugins that run within screenpipe's sandboxed environment. written in typescript/javascript.
+ - **standalone scripts or apps**: independent scripts or apps that run separately and use screenpipe APIs.
</MotionDiv>
----
-
-# 1. pipes
-## overview of pipes
+### why build pipes? 🚀
<MotionDiv delay={0.3}>
- pipes in screenpipe are plugins designed to process data captured from your screen and audio feeds. they automate workflows such as tagging, summarizing, and integrating data with external platforms like notion, salesforce, or slack.
-
- **pipe workflow examples**:
- - **pipe example**: screenpipe | ai tag | notion update
- - **pipe example**: screenpipe | ai tag | slack report
- - **pipe example**: screenpipe | log daily activities
-
- **key features of pipes**:
- - **custom workflows**: automate repetitive tasks such as tagging screen activity or summarizing audio transcriptions.
- - **real-time processing**: pipes can process captured data in real-time.
- - **integration capabilities**: extend the functionality by sending processed data to third-party apps.
-
- **example use cases**:
- - **ai activity tagging**: automatically tag screen or audio activities based on ai models.
- - **meeting summaries**: generate summaries of meeting discussions using combined screen and audio data.
- - **crm integration**: automatically log interactions or captured data into a crm like salesforce.
+think of pipes like a local Zapier which costs 10x & 10x less friction - no auth needed, with full context of your screen and audio data.
+
+#### for developers
+- **zero infrastructure**: run locally, no servers or complex setups
+- **typescript + bun**: blazing fast development
+- **full context**: rich OCR & audio transcription APIs
+- **monetization ready**: early access to pipe store with Stripe integration
+- **bounty program**: earn $100+ for building pipes or promoting screenpipe
+- **open source**: contribute to augmenting collective human intelligence
+
+#### killer features
+- **ai flexibility**: OpenAI, local LLMs (ollama), or any provider
+- **rich APIs**:
+ - `pipe.inbox` for AI/human-in-the-loop messaging
+ - `pipe.scheduler` for cron jobs
+ - `pipe.input` for keyboard/mouse control
+ - `pipe.queryScreenpipe` for context
+- **sandboxed & cross-platform**: safe execution on all OS
+- **real-time**: process screen & audio as it happens
</MotionDiv>
----
-
-## available pipes
+### quick start
<MotionDiv delay={0.5}>
- screenpipe provides a variety of pipes and standalone scripts that allow users to extend the platform's functionality with minimal effort. below is a table summarizing the available examples:
-| **example** | **description** | **link** |
-| ------------------------------------ | ------------------------------------------------ | --------------------------------- |
-| **pipe phi3.5 engineering team logs**| generate engineering team work logs | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs) |
-| **pipe post questions on reddit** | post questions on reddit based on screen activity | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-post-questions-on-reddit) |
-| **pipe email daily log** | send daily activity logs via email | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-email-daily-log) |
-| **pipe llama32 comment linear while you work** | comment on linear tasks while you work using llama32 | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-llama32-comment-linear-while-you-work) |
-| **pipe meeting summary by email** | send meeting summaries via email | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-meeting-summary-by-email) |
-
-</MotionDiv>
+```bash
+# clone & setup
+git clone https://github.com/mediar-ai/screenpipe
+cp -r screenpipe/examples/typescript/pipe-phi3.5-engineering-team-logs my-pipe
+cd my-pipe
+bun install
----
-
-## quick tour - developing pipes in screenpipe
-<MotionDiv delay={0.7}>
+# test locally
+bun run pipe.ts
-screenpipe's plugin system, referred to as **pipes**, allows you to create customized pipes that automate workflows. these pipes can process, annotate, analyze, summarize, or integrate your screen and audio data with other tools.
-
-users can begin by cloning an existing pipe, such as [pipe-phi3.5-engineering-team-logs](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs). you can use any javascript/typescript to build your use case, from simple to highly advanced. the primary requirement is that the pipe folder must contain a file named `pipe.js` or `pipe.ts`.
-
-```bash copy
-git clone https://github.com/mediar-ai/screenpipe.git
-cp -r screenpipe/examples/typescript/pipe-phi3.5-engineering-team-logs screenpipe/examples/typescript/my-pipe
+# ship it
+screenpipe pipe enable my-pipe
```
-we use Bun to run the pipe within the Rust codebase.
-
-check official [bun docs](https://bun.sh/docs) for more details on installing and running Bun.
+### available pipes
+| **pipe** | **description** | **link** |
+| ------------------------------------ | ------------------------------------------------ | --------------------------------- |
+| **phi3.5 engineering logs**| generate team work logs | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-phi3.5-engineering-team-logs) |
+| **reddit questions** | post questions based on screen activity | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-post-questions-on-reddit) |
+| **llama32 linear comments** | comment on tasks while you work | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-llama32-comment-linear-while-you-work) |
+| **meeting summary email** | send meeting summaries via email | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-meeting-summary-by-email) |
+| **obsidian time logs** | log work activities to obsidian | [link](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-obsidian-time-logs) |
-> **note**: you can also use nextjs to build your pipe, we will render the page in the pipe store. check [pipe-simple-nextjs](https://github.com/mediar-ai/screenpipe/tree/main/examples/typescript/pipe-simple-nextjs) for an example.
-
-### configuring pipes
+</MotionDiv>
-we use `pipe.json` to let others pass configuration options to your pipe through the UI or CLI.
+### pipe configuration
-we parse your `pipe.json` file to render in the UI the input fields for your pipe so you need to follow the format.
+<MotionDiv delay={0.7}>
-here's a snippet of a `pipe.json` for the pipe-post-questions-on-reddit:
+we use `pipe.json` to configure your pipe through UI/CLI:
-```json copy
+```json
{
"fields": [
{
"default": 60,
- "description": "Interval in seconds to read your screen data and extract structured logs (will be used to summarize and send an email). Increase this value if using audio.",
+ "description": "Interval in seconds to process screen data",
"name": "interval",
"type": "number"
},
{
"default": "daily",
- "description": "Frequency of summary emails: 'daily' for once a day at emailTime, or 'hourly:X' for every X hours (e.g., 'hourly:4' for every 4 hours)",
+ "description": "Summary frequency: 'daily' or 'hourly:X'",
"name": "summaryFrequency",
- "type": "string",
- "value": "hourly:1"
- },
+ "type": "string"
+ }
]
}
```
+this will render in the screenpipe UI.
-### running pipes
-
-you can run your pipe manually with bun, for example:
-
-```bash copy
-# these are mandatory env variables
-export SCREENPIPE_DIR="$HOME/.screenpipe"
-export PIPE_ID="pipe-phi3.5-engineering-team-logs"
-export PIPE_FILE="pipe.ts"
-export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-phi3.5-engineering-team-logs"
-
-bun run examples/typescript/pipe-phi3.5-engineering-team-logs/pipe.ts
-```
-
-make sure to configure your pipe.json first
-
-once the pipe is ready, follow these steps to make it work with `screenpipe`:
-
-- **download the pipe** (from local or github url):
- ```bash copy
- screenpipe pipe download path/to/pipe-name
- ```
-
-- **enable the pipe** (enabling will activate the pipe, similar to installing it in screenpipe):
- ```bash copy
- screenpipe pipe enable pipe-name
- ```
-
-- **run the pipe** (restart screenpipe):
- ```bash copy
- screenpipe
- ```
-
-you can also use the UI to download and enable your pipe (add the path or URL, click the button, enable, config, restart screenpipe).
-
-### screenpipe-js SDK
-
-cool stuff:
-- `pipe.inbox.send` to send AI messages to the user and ask for confirmation before any dangerous actions.
-- `pipe.sendDesktopNotification` to send a desktop notification to the user.
-- `pipe.queryScreenpipe` to query the screenpipe data.
-
-etc.
-
-[checkout the special api for interacting with screenpipe.](https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-js/main.ts)
-
-
-### closing thoughts
-
-think of pipes like a local Zapier which costs 10x less, 10x less friction because you don't need to authenticate etc.
-and with the full context of your screen and audio data.
-
-please send a PR with your pipe to the repo, we will review and merge it!
-
-we also do bounties for new pipes, or if you talk about screenpipe on social media, we give $100+!
-
-we're working on integration with Stripe, to allow you to monetize your pipes, feel free to reach out for early access.
-
-
-### outro
+### screenpipe-js SDK
-- we use bun to run the pipe within the Rust codebase.
-- you can use `pipe.json` to let others pass configuration options to your pipe through the UI or CLI.
-- pipes have access to a special API that allows you to interact with your computer or special features like sending notifications, sending emails, etc.
-- check this [file](https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-core/src/pipes.rs) for more details on impl.
-- in general we recommend using local LLMs like ollama as the data can be large and sensitive and JSON outputs.
-- we recommend using [vercel ai sdk](https://github.com/vercel/ai) for faster dev.
+key features:
+- `pipe.inbox.send`: AI messages with user confirmation
+- `pipe.sendDesktopNotification`: system notifications
+- `pipe.queryScreenpipe`: query screen/audio data
+- `pipe.scheduler`: cron-like scheduling
+- `pipe.input`: programmatic UI control
-### known limitations
+[full API reference](https://github.com/mediar-ai/screenpipe/blob/main/screenpipe-js/main.ts)
-- you can only use JS/TS to build your pipes.
-- you usually need to run the pipe in an infinite loop for example if it's something that process your data continuously, of course if this is for example an agent that summarize your day one shot it does not have to be infinite loop.
+### bounties & monetization
+- send PRs with your pipes, we'll review and merge!
+- earn $100+ for new pipes or social media promotion
+- early access to pipe store with Stripe integration
</MotionDiv>
diff --git a/examples/typescript/pipe-email-daily-log/README.md b/examples/typescript/archive/pipe-email-daily-log/README.md
similarity index 100%
rename from examples/typescript/pipe-email-daily-log/README.md
rename to examples/typescript/archive/pipe-email-daily-log/README.md
diff --git a/examples/typescript/pipe-email-daily-log/pipe.json b/examples/typescript/archive/pipe-email-daily-log/pipe.json
similarity index 100%
rename from examples/typescript/pipe-email-daily-log/pipe.json
rename to examples/typescript/archive/pipe-email-daily-log/pipe.json
diff --git a/examples/typescript/pipe-email-daily-log/pipe.ts b/examples/typescript/archive/pipe-email-daily-log/pipe.ts
similarity index 100%
rename from examples/typescript/pipe-email-daily-log/pipe.ts
rename to examples/typescript/archive/pipe-email-daily-log/pipe.ts
diff --git a/examples/typescript/pipe-twitter-autopilot/README.md b/examples/typescript/archive/pipe-twitter-autopilot/README.md
similarity index 100%
rename from examples/typescript/pipe-twitter-autopilot/README.md
rename to examples/typescript/archive/pipe-twitter-autopilot/README.md
diff --git a/examples/typescript/pipe-twitter-autopilot/deno.json b/examples/typescript/archive/pipe-twitter-autopilot/deno.json
similarity index 100%
rename from examples/typescript/pipe-twitter-autopilot/deno.json
rename to examples/typescript/archive/pipe-twitter-autopilot/deno.json
diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.json b/examples/typescript/archive/pipe-twitter-autopilot/pipe.json
similarity index 100%
rename from examples/typescript/pipe-twitter-autopilot/pipe.json
rename to examples/typescript/archive/pipe-twitter-autopilot/pipe.json
diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.ts b/examples/typescript/archive/pipe-twitter-autopilot/pipe.ts
similarity index 100%
rename from examples/typescript/pipe-twitter-autopilot/pipe.ts
rename to examples/typescript/archive/pipe-twitter-autopilot/pipe.ts
diff --git a/examples/typescript/pipe-keyword-notification/pipe.json b/examples/typescript/pipe-keyword-notification/pipe.json
new file mode 100644
index 000000000..9e26dfeeb
--- /dev/null
+++ b/examples/typescript/pipe-keyword-notification/pipe.json
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/examples/typescript/pipe-keyword-notification/pipe.ts b/examples/typescript/pipe-keyword-notification/pipe.ts
new file mode 100644
index 000000000..9273d2164
--- /dev/null
+++ b/examples/typescript/pipe-keyword-notification/pipe.ts
@@ -0,0 +1,111 @@
+// import { pipe, ContentItem } from "@screenpipe/js";
+import { pipe, ContentItem } from "/Users/louisbeaumont/Documents/screen-pipe/screenpipe-js/main.ts";
+
+async function monitorScreenAndNotify(): Promise<void> {
+ console.log("starting screen monitor");
+
+ pipe.scheduler
+ .task("screenMonitor")
+ .every("30 seconds")
+ .do(async () => {
+ try {
+ console.log("checking for new screen content...");
+
+ const now = new Date();
+ const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
+
+ console.log(
+ `querying from ${fiveMinutesAgo.toISOString()} to ${now.toISOString()}`
+ );
+
+ const screenData = await pipe.queryScreenpipe({
+ startTime: fiveMinutesAgo.toISOString(),
+ endTime: now.toISOString(),
+ limit: 10,
+ contentType: "ocr",
+ });
+
+ console.log(`found ${screenData?.data.length || 0} items to analyze`);
+
+ if (screenData && screenData.data.length > 0) {
+ // Look for interesting keywords in the screen data
+ const keywords = [
+ "error",
+ "warning",
+ "failed",
+ "completed",
+ "success",
+ ];
+
+ for (const item of screenData.data) {
+ if (item.type === "OCR") {
+ const text = item.content.text.toLowerCase();
+
+ for (const keyword of keywords) {
+ if (text.includes(keyword)) {
+ console.log(`found keyword "${keyword}" in screen content`);
+ // Send notification with action
+ await pipe.inbox.send({
+ title: `detected "${keyword}"`,
+ body: `context: ${item.content.text.slice(0, 100)}...`,
+ actions: [
+ {
+ action: "view-details",
+ label: "view details",
+ callback: async () => {
+ console.log("full text:", item.content.text);
+ // You could open this in a viewer or send to inbox
+ await pipe.inbox.send({
+ title: `full context for "${keyword}"`,
+ body: item.content.text,
+ });
+ },
+ },
+ ],
+ });
+
+ break; // Skip other keywords for this item
+ }
+ }
+ }
+ }
+ }
+ } catch (error) {
+ console.error("error monitoring screen:", error);
+ }
+ });
+
+ pipe.scheduler.start();
+}
+
+// Start monitoring
+monitorScreenAndNotify();
+
+/*
+Instructions:
+
+1. Save this as pipe.ts in your screenpipe pipes directory
+
+2. Run with:
+ ```
+ screenpipe pipe enable simple-notification
+ screenpipe
+ ```
+
+For development, you can run:
+```
+# these are mandatory env variables
+export SCREENPIPE_DIR="$HOME/.screenpipe"
+export PIPE_ID="pipe-keyword-notification"
+export PIPE_FILE="pipe.ts"
+export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-keyword-notification"
+
+bun run examples/typescript/pipe-keyword-notification/pipe.ts
+```
+
+This pipe will:
+- Monitor your screen every 30 seconds
+- Look for keywords like "error", "warning", etc
+- Send desktop notifications when found
+- Allow you to click to see full context
+*/
diff --git a/examples/typescript/pipe-obsidian-time-logs/pipe.ts b/examples/typescript/pipe-obsidian-time-logs/pipe.ts
index 0601d1056..b235fb364 100644
--- a/examples/typescript/pipe-obsidian-time-logs/pipe.ts
+++ b/examples/typescript/pipe-obsidian-time-logs/pipe.ts
@@ -6,52 +6,50 @@ import { pipe, ContentItem } from "@screenpipe/js";
import * as fs from "fs/promises";
import * as path from "path";
-const engineeringLog = z.object({
+const workLog = z.object({
title: z.string(),
description: z.string(),
tags: z.array(z.string()),
timeSpent: z.number(), // in seconds
});
-type EngineeringLog = z.infer<typeof engineeringLog>;
+type WorkLog = z.infer<typeof workLog>;
function getAIProvider(config: any) {
if (config.openaiApiKey.length > 0 && config.gptModel.length > 0) {
return createOpenAI({
- apiKey: config.openaiApiKey
+ apiKey: config.openaiApiKey,
});
}
return createOllama({ baseURL: config.ollamaApiUrl });
}
-async function generateEngineeringLog(
+async function generateWorkLog(
screenData: ContentItem[],
- interval: number,
provider: any,
model: string,
customPrompt?: string
-): Promise<EngineeringLog> {
- const defaultPrompt = `Based on the following screen data, generate a concise engineering log entry:
+): Promise<WorkLog> {
+ const defaultPrompt = `Based on the following screen data, generate a concise work activity log entry:
${JSON.stringify(screenData)}
- Focus only on engineering work. Ignore non-work related activities.
Return a JSON object with the following structure:
{
- "title": "Brief title of the engineering task",
- "description": "Concise description of the engineering work done",
- "tags": ["tag1", "tag2", "tag3"],
- "timeSpent": ${interval / 1000 / 60} // interval in minutes
+ "title": "Brief title of the activity",
+ "description": "Concise description of what was done",
+ "tags": ["#tag1", "#tag2", "#tag3"],
+ "timeSpent": "5" // actual time spent in minutes
}
- Provide 1-3 relevant tags related to the engineering work.
- Estimate time spent in minutes based on the activity.`;
+ Provide 1-3 relevant tags related to the work. Each tag MUST start with #.
+ Estimate time spent in minutes based on the activities timestamps.`;
const prompt = customPrompt || defaultPrompt;
const response = await generateObject({
model: provider(model),
messages: [{ role: "user", content: prompt }],
- schema: engineeringLog,
+ schema: workLog,
});
console.log("ai answer:", response);
@@ -60,52 +58,59 @@ async function generateEngineeringLog(
}
async function syncLogToObsidian(
- logEntry: EngineeringLog,
+ logEntry: WorkLog,
obsidianPath: string
): Promise<void> {
try {
console.log("syncLogToObsidian", logEntry);
-
+
// Create the daily note filename in format YYYY-MM-DD.md
const today = new Date();
- const filename = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}.md`;
+ const filename = `${today.getFullYear()}-${String(
+ today.getMonth() + 1
+ ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}.md`;
const filePath = path.join(obsidianPath, filename);
// Create markdown table row for the entry
- const tableRow = `| ${logEntry.title} | ${logEntry.description} | ${logEntry.tags.join(", ")} | ${logEntry.timeSpent} min |\n`;
+ const tableRow = `| ${logEntry.title} | ${
+ logEntry.description
+ } | ${logEntry.tags.join(", ")} | ${logEntry.timeSpent} min |\n`;
try {
// Try to read existing file
await fs.access(filePath);
// File exists, append to it
- await fs.appendFile(filePath, tableRow, 'utf8');
+ await fs.appendFile(filePath, tableRow, "utf8");
} catch {
// File doesn't exist, create it with header and first row
const content = `| Title | Description | Tags | Time Spent |\n|-------|-------------|------|------------|\n${tableRow}`;
- await fs.writeFile(filePath, content, 'utf8');
+ await fs.writeFile(filePath, content, "utf8");
}
- console.log("engineering log synced to obsidian successfully");
+ console.log("work log synced to obsidian successfully");
await pipe.inbox.send({
- title: "engineering log synced",
- body: `new engineering log entry synced to Obsidian: ${filename}`,
+ title: "work log synced",
+ body: `new work log entry synced to Obsidian: ${filename}`,
});
} catch (error) {
- console.error("error syncing engineering log to obsidian:", error);
+ console.error("error syncing work log to obsidian:", error);
await pipe.inbox.send({
- title: "engineering log error",
- body: `error syncing engineering log to obsidian: ${error}`,
+ title: "work log error",
+ body: `error syncing work log to obsidian: ${error}`,
});
}
}
-function streamEngineeringLogs(): void {
- console.log("starting engineering logs stream");
+function streamWorkLogs(): void {
+ console.log("starting work logs stream");
const config = pipe.loadPipeConfig();
console.log("loaded config:", JSON.stringify(config, null, 2));
+ let successfulLogsCount = 0;
+ const NOTIFICATION_THRESHOLD = 5; // Send notification every 5 successful logs
+
const interval = config.interval * 1000;
const obsidianPath = config.obsidianPath;
const customPrompt = config.customPrompt;
@@ -113,14 +118,12 @@ function streamEngineeringLogs(): void {
const model = config.gptModel || config.ollamaModel;
const provider = getAIProvider(config);
-
pipe.inbox.send({
- title: "engineering log stream started",
- body: `monitoring engineering work every ${config.interval/1000} seconds`,
+ title: "obsidian time logs stream started",
+ body: `monitoring work activity every ${config.interval / 1000} seconds`,
});
-
pipe.scheduler
- .task("generateEngineeringLog")
+ .task("generateWorkLog")
.every(interval)
.do(async () => {
try {
@@ -135,30 +138,45 @@ function streamEngineeringLogs(): void {
});
if (screenData && screenData.data.length > 0) {
- const logEntry = await generateEngineeringLog(
+ const logEntry = await generateWorkLog(
screenData.data,
- interval,
provider,
model,
customPrompt
);
await syncLogToObsidian(logEntry, obsidianPath);
+
+ successfulLogsCount++;
+ if (successfulLogsCount >= NOTIFICATION_THRESHOLD) {
+ await pipe.inbox.send({
+ title: "work logs batch synced",
+ body: `synced ${NOTIFICATION_THRESHOLD} work log entries to obsidian`,
+ });
+ successfulLogsCount = 0; // Reset counter
+ }
} else {
- console.log("no relevant engineering work detected in the last interval");
+ console.log("no relevant activity detected in the last interval");
}
} catch (error) {
- console.error("error in engineering log pipeline:", error);
+ console.error("error in work log pipeline:", error);
await pipe.inbox.send({
- title: "engineering log error",
- body: `error in engineering log pipeline: ${error}`,
+ title: "work log error",
+ body: `error in work log pipeline: ${error}`,
});
}
});
+ pipe.inbox.send({
+ title: "work log stream started",
+ body: `monitoring work activity every ${
+ config.interval / 1000
+ } seconds. notifications will be batched every ${NOTIFICATION_THRESHOLD} successful logs.`,
+ });
+
pipe.scheduler.start();
}
-streamEngineeringLogs();
+streamWorkLogs();
/*
@@ -197,7 +215,7 @@ Instructions to run this pipe:
The pipe will:
- Monitor your screen activity at the configured interval
-- Generate engineering log entries using OpenAI or Ollama
+- Generate work activity log entries using OpenAI or Ollama
- Save entries to daily markdown files in your obsidian vault
- Each day's entries will be saved in YYYY-MM-DD.md format
- Entries are formatted as markdown tables with Title, Description, Tags, and Time Spent
diff --git a/screenpipe-app-tauri/components/header.tsx b/screenpipe-app-tauri/components/header.tsx
index 2d9169882..410577665 100644
--- a/screenpipe-app-tauri/components/header.tsx
+++ b/screenpipe-app-tauri/components/header.tsx
@@ -16,7 +16,11 @@ import {
} from "@/components/ui/dropdown-menu";
import { MessageSquare, Heart, Menu, Bell, Play, Folder } from "lucide-react";
import { open } from "@tauri-apps/plugin-shell";
-import { InboxMessages, Message } from "@/components/inbox-messages";
+import {
+ InboxMessageAction,
+ InboxMessages,
+ Message,
+} from "@/components/inbox-messages";
import { useState, useRef, useEffect } from "react";
import Onboarding from "@/components/onboarding";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
@@ -55,24 +59,26 @@ export default function Header() {
loadMessages();
- const unlisten = listen<Message>(
- "inbox-message-received",
- async (event) => {
- console.log("inbox-message-received", event);
- const newMessage: Message = {
- id: Date.now().toString(),
- title: event.payload.title,
- body: event.payload.body,
- date: new Date().toISOString(),
- read: false,
- };
- setMessages((prevMessages) => {
- const updatedMessages = [newMessage, ...prevMessages];
- localforage.setItem("inboxMessages", updatedMessages);
- return updatedMessages;
- });
- }
- );
+ const unlisten = listen<{
+ title: string;
+ body: string;
+ actions?: InboxMessageAction[];
+ }>("inbox-message-received", async (event) => {
+ console.log("inbox-message-received", event);
+ const newMessage: Message = {
+ id: Date.now().toString(),
+ title: event.payload.title,
+ body: event.payload.body,
+ date: new Date().toISOString(),
+ read: false,
+ actions: event.payload.actions,
+ };
+ setMessages((prevMessages) => {
+ const updatedMessages = [newMessage, ...prevMessages];
+ localforage.setItem("inboxMessages", updatedMessages);
+ return updatedMessages;
+ });
+ });
return () => {
unlisten.then((unlistenFn) => unlistenFn());
diff --git a/screenpipe-app-tauri/components/inbox-messages.tsx b/screenpipe-app-tauri/components/inbox-messages.tsx
index 9a640fd90..aa6bbb8af 100644
--- a/screenpipe-app-tauri/components/inbox-messages.tsx
+++ b/screenpipe-app-tauri/components/inbox-messages.tsx
@@ -28,12 +28,19 @@ import remarkMath from "remark-math";
import { format } from "date-fns";
import posthog from "posthog-js";
+export interface InboxMessageAction {
+ label: string;
+ action: string;
+ port: number;
+}
+
export interface Message {
id: string;
title: string;
body: string;
date: string;
read: boolean;
+ actions?: InboxMessageAction[];
}
interface InboxMessagesProps {
@@ -56,6 +63,8 @@ export function InboxMessages({
const [dialogOpen, setDialogOpen] = useState(false);
const inboxRef = useRef<HTMLDivElement>(null);
+ console.log("messages", messages);
+
const handleMarkAllAsRead = () => {
messages.forEach((msg) => {
if (!msg.read) {
@@ -106,6 +115,22 @@ export function InboxMessages({
}
};
+ const handleAction = async (actionId: string, port: number) => {
+ try {
+ const response = await fetch(`http://localhost:${port}/action`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ action: actionId }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ } catch (error) {
+ console.error("failed to send action callback:", error);
+ }
+ };
+
useEffect(() => {
// Trigger PostHog event when the inbox is opened
posthog.capture("inbox opened");
@@ -232,6 +257,19 @@ export function InboxMessages({
)}
</CardContent>
<CardFooter className="flex justify-end space-x-2 py-2">
+ {message.actions?.map((action) => (
+ <Button
+ key={`${message.id}-${action.action}`}
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ handleAction(action.action, action.port);
+ }}
+ className="text-xs"
+ >
+ {action.label}
+ </Button>
+ ))}
<Button
variant="ghost"
size="sm"
@@ -297,6 +335,17 @@ export function InboxMessages({
</MemoizedReactMarkdown>
</div>
<div className="flex justify-end space-x-2 mt-4">
+ {dialogMessage?.actions?.map((action) => (
+ <Button
+ key={`dialog-${dialogMessage.id}-${action.action}`}
+ variant="outline"
+ onClick={() => {
+ console.log(`Dialog action clicked: ${action.label}`);
+ }}
+ >
+ {action.label}
+ </Button>
+ ))}
<DialogClose asChild>
<Button variant="outline" onClick={closeDialog}>
close
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index f4fa27fef..9efcc33d3 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -4170,7 +4170,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "screenpipe-app"
-version = "0.11.3"
+version = "0.12.0"
dependencies = [
"anyhow",
"axum",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index bd0075885..447022aaf 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.12.0"
+version = "0.12.1"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/src/server.rs b/screenpipe-app-tauri/src-tauri/src/server.rs
index 724600384..febaa6717 100644
--- a/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -46,12 +46,14 @@ struct InboxMessagePayload {
#[serde(rename = "type")]
message_type: String,
actions: Option<Vec<InboxMessageAction>>,
+ action_server_port: Option<u16>,
}
#[derive(Serialize, Deserialize, Debug)]
struct InboxMessageAction {
label: String,
action: String,
+ port: u16,
}
pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
diff --git a/screenpipe-app-tauri/src-tauri/tauri.conf.json b/screenpipe-app-tauri/src-tauri/tauri.conf.json
index b84deeb0a..2c2acfdb9 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.conf.json
@@ -107,7 +107,7 @@
},
"csp": {
"default-src": "'self' customprotocol: asset:",
- "connect-src": "ipc: http://ipc.localhost https://youtube.com https://api.openai.com http://localhost:3030 https://web.crabnebula.cloud https://api.github.com https://eu.i.posthog.com https://github.com https://*.githubusercontent.com https://*.github.com http://*:11434 http://*:9000 https://ai-proxy.i-f9f.workers.dev *",
+ "connect-src": "ipc: http://ipc.localhost https://youtube.com https://api.openai.com http://localhost:3030 http://localhost:* https://web.crabnebula.cloud https://api.github.com https://eu.i.posthog.com https://github.com https://*.githubusercontent.com https://*.github.com http://*:11434 http://*:9000 https://ai-proxy.i-f9f.workers.dev *",
"font-src": [
"https://fonts.gstatic.com",
"tauri://localhost",
diff --git a/screenpipe-js/bun.lockb b/screenpipe-js/bun.lockb
index 08233e40f..d140cd868 100755
Binary files a/screenpipe-js/bun.lockb and b/screenpipe-js/bun.lockb differ
diff --git a/screenpipe-js/main.ts b/screenpipe-js/main.ts
index b78d433e3..4026a0937 100644
--- a/screenpipe-js/main.ts
+++ b/screenpipe-js/main.ts
@@ -1,7 +1,6 @@
import * as fs from "node:fs";
-import * as path from "node:path";
-import cronParser from "cron-parser";
import cron, { type ScheduledTask } from "node-cron";
+import express, { Request, Response, NextFunction } from "express";
// Type definitions
export interface PipeConfig {
@@ -11,6 +10,9 @@ export interface PipeConfig {
export interface NotificationOptions {
title: string;
body: string;
+ actions?: NotificationAction[];
+ timeout?: number; // in milliseconds
+ persistent?: boolean;
}
/**
@@ -250,6 +252,7 @@ export interface InboxMessage {
export interface InboxMessageAction {
label: string;
action: string;
+ callback: () => Promise<void>;
}
class Task {
@@ -350,10 +353,115 @@ interface InputControlResponse {
success: boolean;
}
-/**
- * The pipe object is used to interact with the screenpipe higher level functions.
- *
- */
+// Add this type for action responses
+interface ActionResponse {
+ action: string;
+}
+
+// Keep track of action callbacks
+const actionCallbacks = new Map<string, () => Promise<void>>();
+
+// Add this function to find an available port
+async function getAvailablePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = require("net").createServer();
+ server.unref();
+ server.on("error", reject);
+ server.listen(0, () => {
+ const port = server.address().port;
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+export class InboxManager {
+ private actionServerPort?: number;
+ private actionServer?: express.Express;
+
+ async send(message: InboxMessage): Promise<boolean> {
+ // Ensure action server is running and we have a port
+ if (!this.actionServerPort) {
+ this.actionServerPort = await getAvailablePort();
+ this.actionServer = await this.startActionServer();
+ }
+
+ // Generate unique IDs for actions and store their callbacks
+ if (message.actions) {
+ message.actions = message.actions.map((action) => {
+ const actionId = crypto.randomUUID();
+ actionCallbacks.set(actionId, action.callback);
+ return {
+ label: action.label,
+ action: actionId,
+ port: this.actionServerPort,
+ callback: action.callback,
+ };
+ });
+ }
+
+ try {
+ const response = await fetch("http://localhost:11435/inbox", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...message,
+ type: "inbox",
+ actionServerPort: this.actionServerPort,
+ }),
+ });
+
+ return response.ok;
+ } catch (error) {
+ console.error("failed to send inbox message:", error);
+ return false;
+ }
+ }
+
+ private async startActionServer(): Promise<express.Express> {
+ const app = express();
+ app.use(express.json());
+
+ // Add CORS middleware
+ app.use((req: Request, res: Response, next: NextFunction): void => {
+ res.header("Access-Control-Allow-Origin", "*");
+ res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
+ res.header("Access-Control-Allow-Headers", "Content-Type");
+
+ if (req.method === "OPTIONS") {
+ res.sendStatus(200);
+ return;
+ }
+ next();
+ });
+
+ app.post("/action", (req, res) => {
+ const { action } = req.body as ActionResponse;
+ const callback = actionCallbacks.get(action);
+ if (callback) {
+ callback()
+ .then(() => {
+ res.json({ success: true });
+ actionCallbacks.delete(action);
+ })
+ .catch((error) => {
+ console.error("action callback failed:", error);
+ res.status(500).json({ success: false, error: error.message });
+ });
+ } else {
+ res.status(404).json({ success: false, error: "action not found" });
+ }
+ });
+
+ return new Promise((resolve) => {
+ app.listen(this.actionServerPort, () => {
+ console.log(`action server listening on port ${this.actionServerPort}`);
+ resolve(app);
+ });
+ });
+ }
+}
+
+// Remove the startActionServer from pipe object since it's now handled by InboxManager
export const pipe = {
/**
* Send a desktop notification to the user.
@@ -389,24 +497,13 @@ export const pipe = {
* ```typescript
* pipe.inbox.send({ title: "Task Completed", body: "Your task has been completed." });
* ```
+ *
+ * or with actions:
+ * ```typescript
+ * pipe.inbox.send({ title: "Task Completed", body: "Your task has been completed.", actions: [{ id: "view", label: "view details", callback: async () => { console.log("viewing details"); } }] });
+ * ```
*/
- inbox: {
- send: async (message: InboxMessage): Promise<boolean> => {
- const notificationApiUrl =
- process.env.SCREENPIPE_SERVER_URL || "http://localhost:11435";
- try {
- const response = await fetch(`${notificationApiUrl}/inbox`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ...message, type: "inbox" }),
- });
- return response.ok;
- } catch (error) {
- console.error("failed to send inbox message:", error);
- return false;
- }
- },
- },
+ inbox: new InboxManager(),
/**
* Scheduler for running tasks at specific times or intervals.
*
@@ -490,3 +587,9 @@ async function sendInputControl(action: InputAction): Promise<boolean> {
return false;
}
}
+
+export interface NotificationAction {
+ id: string;
+ label: string;
+ callback?: () => Promise<void>;
+}
diff --git a/screenpipe-js/package.json b/screenpipe-js/package.json
index 1c56c11bb..c8d406667 100644
--- a/screenpipe-js/package.json
+++ b/screenpipe-js/package.json
@@ -24,8 +24,10 @@
"@types/node": "^22.8.4"
},
"dependencies": {
+ "@types/express": "^5.0.0",
"@types/node-cron": "^3.0.11",
"cron-parser": "^4.9.0",
+ "express": "^4.21.1",
"node-cron": "^3.0.3"
},
"peerDependencies": {