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

chore: make pipes merge pipe configs (useful for dev, sqaving time)

Louis Beaumontf263db3a14c3
diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.json b/examples/typescript/pipe-twitter-autopilot/pipe.json
index 5c04ba44c..797664008 100644
--- a/examples/typescript/pipe-twitter-autopilot/pipe.json
+++ b/examples/typescript/pipe-twitter-autopilot/pipe.json
@@ -28,6 +28,39 @@
"type": "string",
"default": "you generate comments to tweets and optimise for the twitter algorithm to get maximum score\n\nrules:\n- be controversial but not offensive\n- use lowercase\n- be concise\n- sound like a real person, not a brand, nor an ai\n- optimize for engagement\n- don't use hashtags\n- don't be cringe\n- don't be fucking woke",
"description": "custom prompt for generating tweets"
+ },
+ {
+ "name": "aiProvider",
+ "type": "string",
+ "default": "ollama",
+ "description": "ai provider to use (ollama or openai)"
+ },
+ {
+ "name": "openaiApiKey",
+ "type": "string",
+ "description": "openai api key (required if using openai provider)",
+ "optional": true
+ },
+ {
+ "name": "openaiModel",
+ "type": "string",
+ "default": "gpt-4o",
+ "description": "openai model to use (if using openai provider)",
+ "optional": true
+ },
+ {
+ "name": "keywords",
+ "type": "string",
+ "default": "",
+ "description": "comma-separated list of keywords to search for (if empty, keywords will be extracted from screen data)",
+ "optional": true
+ },
+ {
+ "name": "targetUsers",
+ "type": "string",
+ "default": "",
+ "description": "comma-separated list of twitter usernames to search within their network (if empty, searches globally)",
+ "optional": true
}
]
}
diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.ts b/examples/typescript/pipe-twitter-autopilot/pipe.ts
index 82a3b6ef6..0e81401ff 100644
--- a/examples/typescript/pipe-twitter-autopilot/pipe.ts
+++ b/examples/typescript/pipe-twitter-autopilot/pipe.ts
@@ -4,32 +4,52 @@ import { z } from "zod";
import { generateObject } from "ai";
import { createOllama } from "ollama-ai-provider";
import { pipe } from "screenpipe";
+import { createOpenAI } from "npm:@ai-sdk/openai";
const twitterSuggestionLog = z.object({
- tweetId: z.string(),
- comment: z.string(),
+ suggestions: z.array(
+ z.object({
+ tweetId: z.string(),
+ comment: z.string(),
+ })
+ ),
});
type TwitterSuggestionLog = z.infer<typeof twitterSuggestionLog>;
+function createAIProvider(config: any) {
+ if (config.aiProvider === "openai") {
+ if (!config.openaiApiKey) {
+ throw new Error("openai api key required when using openai provider");
+ }
+ return createOpenAI({
+ apiKey: config.openaiApiKey,
+ })(config.openaiModel || "gpt-4o");
+ } else {
+ return createOllama({ baseURL: config.aiApiUrl })(config.aiModel);
+ }
+}
+
async function extractKeywords(
screenData: ContentItem[],
- ollamaModel: string,
- ollamaApiUrl: string
+ config: any
): Promise<string[]> {
- const prompt = `Extract 5 relevant keywords from the following screen data:
+ if (config.keywords?.trim()) {
+ const keywords = config.keywords.split(",").map((k: string) => k.trim());
+ console.log("using hardcoded keywords:", keywords);
+ return keywords;
+ }
+ const prompt = `Extract 5 relevant keywords from the following screen data:
${JSON.stringify(screenData)}
-
Return a JSON object with a single array of strings, here are a few examples:
- { "keywords": ["screen", "software", "developer", "product", "design"] }
-
`;
- const provider = createOllama({ baseURL: ollamaApiUrl });
+ const provider = createAIProvider(config);
const response = await generateObject({
- model: provider(ollamaModel),
+ model: provider,
messages: [{ role: "user", content: prompt }],
schema: z.object({ keywords: z.array(z.string()) }),
});
@@ -38,67 +58,217 @@ async function extractKeywords(
return response.object.keywords;
}
-async function fetchRelevantTweets(
- keywords: string[],
- twitterClient: TwitterApi
+async function filterTweetsWithAI(
+ tweets: TweetV2[],
+ customPrompt: string,
+ config: any
): Promise<TweetV2[]> {
- const query = `${keywords.join(" OR ")} lang:en`;
- const tweets = await twitterClient.v2.search(query, {
- max_results: 10,
- "tweet.fields": ["id", "text", "author_id"],
- "user.fields": ["id", "username", "location"],
- expansions: ["author_id"],
+ const provider = createAIProvider(config);
+
+ const filterPrompt = `you are a tweet filter. evaluate if these tweets are relevant based on these criteria:
+${customPrompt}
+
+additional rules:
+- tweets should be engaging and worth responding to
+- tweets should be from real users (not bots/spam)
+- tweets should be relevant to screen recording, productivity, or software
+- tweets should have potential for meaningful interaction
+
+rate each tweet as either KEEP or SKIP. return a JSON array of booleans where true means KEEP.
+
+example format:
+{
+ "keep": [true, false, true]
+}`;
+
+ const response = await generateObject({
+ model: provider,
+ messages: [
+ { role: "system", content: filterPrompt },
+ { role: "user", content: JSON.stringify(tweets.map((t) => t.text)) },
+ ],
+ schema: z.object({ keep: z.array(z.boolean()) }),
});
- return tweets.data.data;
+ return tweets.filter((_, i) => response.object.keep[i]);
}
-async function generateTwitterSuggestions(
- tweets: TweetV2[],
+async function fetchRelevantTweets(
+ keywords: string[],
+ twitterClient: TwitterApi,
customPrompt: string,
- ollamaModel: string,
- ollamaApiUrl: string
-): Promise<TwitterSuggestionLog[]> {
- const hardcodedPrompt = `you generate 3 tweet comments to these tweets: ${tweets
- .map((tweet) => tweet.text)
- .join(", ")}
+ config: any,
+ desiredCount: number = 3,
+ attempt: number = 1,
+ maxAttempts: number = 3
+): Promise<TweetV2[]> {
+ // Expand search window based on attempt number
+ const hoursAgo = attempt * 24; // Increase time window with each attempt
+ const startTime = new Date(
+ Date.now() - hoursAgo * 60 * 60 * 1000
+ ).toISOString();
+
+ // Decrease engagement thresholds with each attempt
+ const minLikes = Math.max(1, 4 - attempt);
+ const minReplies = Math.max(1, 3 - attempt);
+ const minRetweets = Math.max(1, 3 - attempt);
+
+ // Create search query with expanded criteria on later attempts
+ const baseTerms = [
+ "screen recording",
+ "screencasting",
+ "screen capture",
+ "screenpipe",
+ "recording software",
+ ];
+
+ // Add more general terms in later attempts
+ if (attempt > 1) {
+ baseTerms.push("productivity", "software", "tech");
+ }
- respect these rules: ${customPrompt}
+ const relevantKeywords = [...baseTerms, ...keywords]
+ .filter((k) => k.length > 0)
+ .map((k) => `"${k}"`)
+ .join(" OR ");
- your goal is to help the user grow their twitter account by generating comments that are engaging and help the user get more likes, replies and followers.
+ const query = `(${relevantKeywords}) lang:en -is:retweet -is:reply has:mentions`;
- TLDR of twitter algorithm:
+ try {
+ console.log(
+ `attempt ${attempt}: fetching tweets from last ${hoursAgo} hours`
+ );
+
+ const tweets = await twitterClient.v2.search(query, {
+ max_results: 25 * attempt, // Fetch more tweets with each attempt
+ start_time: startTime,
+ "tweet.fields": [
+ "id",
+ "text",
+ "author_id",
+ "public_metrics",
+ "created_at",
+ ],
+ "user.fields": ["id", "username", "public_metrics"],
+ expansions: ["author_id"],
+ sort_order: "relevancy",
+ });
+
+ // Pre-filter for engagement with reduced thresholds
+ const engagementFiltered = tweets.data.data.filter((tweet) => {
+ const metrics = tweet.public_metrics;
+ return (
+ metrics &&
+ (metrics.like_count >= minLikes ||
+ metrics.reply_count >= minReplies ||
+ metrics.retweet_count >= minRetweets)
+ );
+ });
- optimize for these engagement metrics (higher is better):
- - probability the user replies to the tweet: 13.5
- - probability the user opens the tweet author profile and likes or replies to a tweet: 12.0
- - probability the user replies to the tweet and this reply is engaged by the tweet author: 75.0
- - probability the user will click into the conversation of this tweet and reply or like a tweet: 11.0
- - probability the user will click into the conversation and stay there for at least 2 minutes: 10.0
+ // AI filter
+ const aiFiltered = await filterTweetsWithAI(
+ engagementFiltered,
+ customPrompt,
+ config
+ );
+
+ console.log(
+ `attempt ${attempt} results: ${engagementFiltered.length} -> ${aiFiltered.length}`
+ );
+
+ // If we don't have enough relevant tweets and haven't hit max attempts, try again
+ if (aiFiltered.length < desiredCount && attempt < maxAttempts) {
+ console.log(
+ `not enough relevant tweets, trying again with expanded criteria`
+ );
+ const nextAttemptTweets = await fetchRelevantTweets(
+ keywords,
+ twitterClient,
+ customPrompt,
+ config,
+ desiredCount,
+ attempt + 1,
+ maxAttempts
+ );
+ return [...aiFiltered, ...nextAttemptTweets].slice(0, desiredCount);
+ }
+
+ return aiFiltered.slice(0, desiredCount);
+ } catch (error) {
+ console.log(`error in attempt ${attempt}:`, error);
+ if (attempt < maxAttempts) {
+ console.log("retrying with expanded criteria");
+ return fetchRelevantTweets(
+ keywords,
+ twitterClient,
+ customPrompt,
+ config,
+ desiredCount,
+ attempt + 1,
+ maxAttempts
+ );
+ }
+ return [];
+ }
+}
- avoid these negative outcomes:
- - probability the user will react negatively (requesting "show less often" on the tweet or author, block or mute the tweet author): -74.0
- - probability the user will click report tweet: -369.0
+async function generateTwitterSuggestions(
+ tweets: TweetV2[],
+ customPrompt: string,
+ config: any
+): Promise<TwitterSuggestionLog["suggestions"]> {
+ // Only process the filtered tweets
+ const tweetTexts = tweets.map((t) => t.text);
+
+ const hardcodedPrompt = `you are a tweet comment generator. your task is to generate engaging replies to tweets.
+
+rules for comments:
+${customPrompt}
+
+format rules:
+- you MUST return a valid JSON object containing a "comments" array
+- each comment in the array MUST be a string
+- generate exactly ${tweetTexts.length} comments, one for each tweet provided
+- comments should be in the same order as the tweets provided
+- do NOT include any explanation or other text, ONLY the JSON object
+
+here's a valid example:
+{
+ "comments": [
+ "what do you think is the reason why this happen?",
+ "been there, totally get it. the struggle is real",
+ "hot take but you're absolutely right"
+ ]
+}
- for each tweet, return a json object:
- {
- "tweetId": "the id of the tweet",
- "comment": "the tweet comment"
- }`;
+twitter algorithm optimization:
+- aim for replies that get 13.5+ engagement score
+- aim for profile visits that convert (12.0+ score)
+- aim for author engagement on your reply (75.0+ score)
+- avoid content that gets reported (-369.0 penalty)
+- avoid content that gets muted/blocked (-74.0 penalty)`;
- const provider = createOllama({ baseURL: ollamaApiUrl });
+ const provider = createAIProvider(config);
const response = await generateObject({
- model: provider(ollamaModel),
- messages: [{ role: "user", content: hardcodedPrompt }],
- schema: z.array(twitterSuggestionLog),
+ model: provider,
+ messages: [
+ { role: "system", content: hardcodedPrompt },
+ { role: "user", content: `tweets: ${tweetTexts.join("\n")}` },
+ ],
+ schema: z.object({ comments: z.array(z.string()) }),
});
- console.log("ai suggestions:", response.object);
- return response.object;
+ // Map AI comments back to tweets with correct IDs
+ return response.object.comments.map((comment, index) => ({
+ tweetId: tweets[index].id,
+ comment,
+ }));
}
-function generateTwitterLinks(suggestions: TwitterSuggestionLog[]): string {
+function generateTwitterLinks(
+ suggestions: TwitterSuggestionLog["suggestions"]
+): string {
return suggestions
.map((suggestion, index) => {
const encodedComment = encodeURIComponent(suggestion.comment);
@@ -117,7 +287,7 @@ Comment: ${suggestion.comment}
}
async function syncSuggestionsToInbox(
- suggestions: TwitterSuggestionLog[]
+ suggestions: TwitterSuggestionLog["suggestions"]
): Promise<void> {
try {
console.log("syncSuggestionsToInbox", suggestions);
@@ -144,8 +314,6 @@ async function streamTwitterSuggestions(): Promise<void> {
console.log("loaded config:", JSON.stringify(config, null, 2));
const interval = config.interval * 1000;
- const ollamaApiUrl = config.aiApiUrl;
- const ollamaModel = config.aiModel;
const twitterBearerToken = config.twitterBearerToken;
const twitterClient = new TwitterApi(twitterBearerToken);
@@ -157,9 +325,7 @@ async function streamTwitterSuggestions(): Promise<void> {
pipe.scheduler
.task("generateTwitterSuggestions")
- // .every(interval)
-
- .every("1 minutes")
+ .every(`${config.interval} seconds`)
.do(async () => {
try {
const now = new Date();
@@ -170,25 +336,26 @@ async function streamTwitterSuggestions(): Promise<void> {
endTime: now.toISOString(),
limit: 50,
contentType: "ocr",
+ minLength: 50,
});
+ console.log("fetched screen data:", screenData?.pagination.total);
+
if (screenData && screenData.data.length > 0) {
- const keywords = await extractKeywords(
- screenData.data,
- ollamaModel,
- ollamaApiUrl
- );
+ const keywords = await extractKeywords(screenData.data, config);
+ console.log("extracted keywords:", keywords);
const relevantTweets = await fetchRelevantTweets(
keywords,
- twitterClient
+ twitterClient,
+ config.customPrompt,
+ config
);
if (relevantTweets.length > 0) {
const suggestions = await generateTwitterSuggestions(
relevantTweets,
config.customPrompt,
- ollamaModel,
- ollamaApiUrl
+ config
);
await syncSuggestionsToInbox(suggestions);
} else {
@@ -206,10 +373,10 @@ async function streamTwitterSuggestions(): Promise<void> {
}
});
- await pipe.scheduler.start();
+ pipe.scheduler.start();
}
-streamTwitterSuggestions();
+// streamTwitterSuggestions();
/**
@@ -221,3 +388,70 @@ export PIPE_DIR="$SCREENPIPE_DIR/pipes/pipe-twitter-autopilot"
deno run --allow-read --allow-write --allow-env --allow-net --allow-run --allow-sys examples/typescript/pipe-twitter-autopilot/pipe.ts
*/
+
+// ... existing code ...
+
+async function testTwitterSuggestionsOnce(): Promise<void> {
+ console.log("testing twitter suggestions with last 60 min data");
+
+ const config = pipe.loadPipeConfig();
+ console.log("loaded config:", JSON.stringify(config, null, 2));
+
+ const twitterClient = new TwitterApi(config.twitterBearerToken);
+
+ try {
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ const screenData = await pipe.queryScreenpipe({
+ startTime: oneHourAgo.toISOString(),
+ endTime: now.toISOString(),
+ limit: 50,
+ contentType: "ocr",
+ minLength: 50,
+ });
+
+ console.log("fetched screen data:", screenData?.pagination.total);
+
+ if (screenData && screenData.data.length > 0) {
+ const keywords = await extractKeywords(screenData.data, config);
+ console.log("extracted keywords:", keywords);
+ const relevantTweets = await fetchRelevantTweets(
+ keywords,
+ twitterClient,
+ config.customPrompt,
+ config
+ );
+
+ if (relevantTweets.length > 0) {
+ const suggestions = await generateTwitterSuggestions(
+ relevantTweets,
+ config.customPrompt,
+ config
+ );
+ await syncSuggestionsToInbox(suggestions);
+ } else {
+ console.log("no relevant tweets found");
+ }
+ } else {
+ console.log("no relevant screen data detected in the last hour");
+ }
+ } catch (error) {
+ console.error("error in twitter suggestions test:", error);
+ await pipe.inbox.send({
+ title: "twitter suggestions test error",
+ body: `error in twitter suggestions test: ${error}`,
+ });
+ }
+}
+
+// Comment out or remove the streamTwitterSuggestions() call
+// streamTwitterSuggestions();
+
+// Add this line to run the test function
+testTwitterSuggestionsOnce();
+
+// fetchRelevantTweets(
+// ["screen", "recording", "software"],
+// new TwitterApi(pipe.loadPipeConfig().twitterBearerToken)
+// ).then(console.log);
diff --git a/screenpipe-app-tauri/components/inbox-messages.tsx b/screenpipe-app-tauri/components/inbox-messages.tsx
index 502d10f30..9a640fd90 100644
--- a/screenpipe-app-tauri/components/inbox-messages.tsx
+++ b/screenpipe-app-tauri/components/inbox-messages.tsx
@@ -26,6 +26,7 @@ import { MemoizedReactMarkdown } from "./markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { format } from "date-fns";
+import posthog from "posthog-js";
export interface Message {
id: string;
@@ -106,6 +107,9 @@ export function InboxMessages({
};
useEffect(() => {
+ // Trigger PostHog event when the inbox is opened
+ posthog.capture("inbox opened");
+
function handleClickOutside(event: MouseEvent) {
if (
inboxRef.current &&
@@ -180,12 +184,18 @@ export function InboxMessages({
<p className="mb-2 last:mb-0">{children}</p>
),
a: ({ node, href, children, ...props }) => {
- const isExternal = href?.startsWith('http') || href?.startsWith('https');
+ const isExternal =
+ href?.startsWith("http") ||
+ href?.startsWith("https");
return (
<a
href={href}
target={isExternal ? "_blank" : undefined}
- rel={isExternal ? "noopener noreferrer" : undefined}
+ rel={
+ isExternal
+ ? "noopener noreferrer"
+ : undefined
+ }
className="break-all text-blue-500 hover:underline"
{...props}
>
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index e6b6c2ee7..6b442b525 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -232,43 +232,97 @@ mod pipes {
debug!("Destination directory: {:?}", dest_dir);
+ // Save existing pipe.json content before downloading
let pipe_json_path = dest_dir.join("pipe.json");
- let existing_pipe_json = if pipe_json_path.exists() {
+ let existing_config = if pipe_json_path.exists() {
debug!("Existing pipe.json found");
- Some(tokio::fs::read_to_string(&pipe_json_path).await?)
+ let content = tokio::fs::read_to_string(&pipe_json_path).await?;
+ Some(serde_json::from_str::<Value>(&content)?)
} else {
debug!("No existing pipe.json found");
None
};
- tokio::fs::create_dir_all(&dest_dir).await?;
- debug!("Created destination directory");
+ // Create temp directory for download
+ let temp_dir = dest_dir.with_extension("_temp");
+ tokio::fs::create_dir_all(&temp_dir).await?;
+ // Download to temp directory first
if let Ok(parsed_url) = Url::parse(source) {
debug!("Source is a URL: {}", parsed_url);
if parsed_url.host_str() == Some("github.com") {
- download_github_folder(&parsed_url, &dest_dir).await?;
+ download_github_folder(&parsed_url, &temp_dir).await?;
} else {
anyhow::bail!("Unsupported URL format");
}
} else {
debug!("Source is a local path");
let source_path = Path::new(source);
- if !source_path.exists() {
- error!("Local source path does not exist: {:?}", source_path);
- anyhow::bail!("Local source path does not exist");
- }
- if !source_path.is_dir() {
- error!("Local source is not a directory: {:?}", source_path);
- anyhow::bail!("Local source is not a directory");
+ if !source_path.exists() || !source_path.is_dir() {
+ anyhow::bail!("Invalid local source path");
}
+ copy_dir_all(source_path, &temp_dir).await?;
+ }
+
+ // If download successful, move temp dir to final location
+ if dest_dir.exists() {
+ tokio::fs::remove_dir_all(&dest_dir).await?;
+ }
+ tokio::fs::rename(&temp_dir, &dest_dir).await?;
+
+ // Restore or merge pipe.json if needed
+ if let Some(ref existing_config) = existing_config {
+ let new_config_path = dest_dir.join("pipe.json");
+ if new_config_path.exists() {
+ let content = tokio::fs::read_to_string(&new_config_path).await?;
+ let new_json: Value = serde_json::from_str(&content)?;
+
+ // Create merged config
+ let mut merged_config = new_json.clone(); // Start with new schema
+
+ // If both configs have fields array, preserve user values
+ if let (Some(existing_obj), Some(new_obj)) =
+ (existing_config.as_object(), merged_config.as_object_mut())
+ {
+ // Copy over non-fields properties from existing config
+ for (key, value) in existing_obj {
+ if key != "fields" {
+ new_obj.insert(key.clone(), value.clone());
+ }
+ }
- debug!(
- "Copying local folder from {:?} to {:?}",
- source_path, dest_dir
- );
- copy_dir_all(source_path, &dest_dir).await?;
- info!("Copied local folder: {:?} to {:?}", source_path, dest_dir);
+ // For fields array, preserve user values while keeping new schema
+ if let (Some(existing_fields), Some(new_fields)) = (
+ existing_config["fields"].as_array(),
+ new_obj.get_mut("fields").and_then(|f| f.as_array_mut()),
+ ) {
+ // For each field in the new schema
+ for new_field in new_fields {
+ if let Some(name) = new_field.get("name").and_then(Value::as_str) {
+ // If this field existed in the old config, preserve its value
+ if let Some(existing_field) = existing_fields
+ .iter()
+ .find(|f| f.get("name").and_then(Value::as_str) == Some(name))
+ {
+ if let Some(user_value) = existing_field.get("value") {
+ if let Some(new_field_obj) = new_field.as_object_mut() {
+ new_field_obj
+ .insert("value".to_string(), user_value.clone());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let config_str = serde_json::to_string_pretty(&merged_config)?;
+ tokio::fs::write(&new_config_path, config_str).await?;
+ } else {
+ // If no new config exists, keep the existing one
+ let config_str = serde_json::to_string_pretty(&existing_config)?;
+ tokio::fs::write(&new_config_path, config_str).await?;
+ }
}
// After downloading/copying the pipe, check if it's a Next.js project
@@ -309,8 +363,8 @@ mod pipes {
// stream_logs("next build", &mut build_child).await?;
// Update pipe.json to indicate it's a Next.js project
- let mut pipe_config = if let Some(existing_json) = existing_pipe_json {
- serde_json::from_str(&existing_json)?
+ let mut pipe_config = if let Some(existing_json) = &existing_config {
+ serde_json::from_str(&existing_json.as_str().unwrap())?
} else if pipe_json_path.exists() {
let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
serde_json::from_str(&pipe_json)?