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
bump ollama embedded version, improve UX, new WIP pipe, other stuff
Louis Beaumont85a60f648621
diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex 35740c480..d02fc8fc4 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -37,7 +37,7 @@ jobs:fi- name: create draft release- uses: crabnebula-dev/cloud-release@v0+ uses: crabnebula-dev/[email protected]with:command: release draft ${{ secrets.CN_APP_SLUG }} --framework tauriapi-key: ${{ secrets.CN_API_KEY }}@@ -235,7 +235,7 @@ jobs:tauriScript: bunx tauri -v- name: Upload Assets to CrabNebula Cloud- uses: crabnebula-dev/cloud-release@v0+ uses: crabnebula-dev/[email protected]with:command: release upload ${{ secrets.CN_APP_SLUG }} --framework tauriapi-key: ${{ secrets.CN_API_KEY }}diff --git a/examples/typescript/pipe-twitter-autopilot/README.md b/examples/typescript/pipe-twitter-autopilot/README.mdnew file mode 100644index 000000000..6d3f66599--- /dev/null+++ b/examples/typescript/pipe-twitter-autopilot/README.md@@ -0,0 +1 @@+WIP\ No newline at end of filediff --git a/examples/typescript/pipe-twitter-autopilot/deno.json b/examples/typescript/pipe-twitter-autopilot/deno.jsonnew file mode 100644index 000000000..ce0f24167--- /dev/null+++ b/examples/typescript/pipe-twitter-autopilot/deno.json@@ -0,0 +1,10 @@+{+ "imports": {+ "fs": "node:fs",+ "screenpipe": "https://raw.githubusercontent.com/mediar-ai/screenpipe/main/screenpipe-js/main.ts",+ "ai": "npm:ai",+ "ollama-ai-provider": "npm:ollama-ai-provider",+ "zod": "npm:zod",+ "twitter-api-v2": "npm:twitter-api-v2"+ }+}diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.json b/examples/typescript/pipe-twitter-autopilot/pipe.jsonnew file mode 100644index 000000000..5c04ba44c--- /dev/null+++ b/examples/typescript/pipe-twitter-autopilot/pipe.json@@ -0,0 +1,33 @@+{+ "fields": [+ {+ "name": "interval",+ "type": "number",+ "default": 60,+ "description": "interval in seconds to read your screen data and extract structured logs"+ },+ {+ "name": "aiApiUrl",+ "type": "string",+ "default": "http://localhost:11434/api",+ "description": "ollama api url"+ },+ {+ "name": "aiModel",+ "type": "string",+ "default": "llama3.2:3b-instruct-q4_K_M",+ "description": "ai model name"+ },+ {+ "name": "twitterBearerToken",+ "type": "string",+ "description": "twitter bearer token, find it here: https://developer.x.com/en/portal/apps"+ },+ {+ "name": "customPrompt",+ "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"+ }+ ]+}diff --git a/examples/typescript/pipe-twitter-autopilot/pipe.ts b/examples/typescript/pipe-twitter-autopilot/pipe.tsnew file mode 100644index 000000000..397a81770--- /dev/null+++ b/examples/typescript/pipe-twitter-autopilot/pipe.ts@@ -0,0 +1,234 @@+import { ContentItem } from "screenpipe";+import { TwitterApi, type TweetV2 } from "twitter-api-v2";+import { z } from "zod";+import { generateObject } from "ai";+import { createOllama } from "ollama-ai-provider";+import { pipe } from "screenpipe";++const twitterSuggestionLog = z.object({+ tweetId: z.string(),+ comment: z.string(),+});++type TwitterSuggestionLog = z.infer<typeof twitterSuggestionLog>;++async function extractKeywords(+ screenData: ContentItem[],+ ollamaModel: string,+ ollamaApiUrl: string+): Promise<string[]> {+ 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 response = await generateObject({+ model: provider(ollamaModel),+ messages: [{ role: "user", content: prompt }],+ schema: z.object({ keywords: z.array(z.string()) }),+ });++ console.log("extracted keywords:", response.object);+ return response.object.keywords;+}++async function fetchRelevantTweets(+ keywords: string[],+ twitterClient: TwitterApi+): Promise<TweetV2[]> {+ const query = `(${keywords.join(" OR ")}) (lang:en OR from:louis030195 OR to:louis030195)`;+ const tweets = await twitterClient.v2.search(query, {+ max_results: 10,+ "tweet.fields": ["id", "text", "author_id"],+ "user.fields": ["id", "username", "location"],+ expansions: ["author_id"],+ });++ // Filter tweets based on US location or related to your account+ const filteredTweets = tweets.data.data.filter(tweet => {+ const author = tweets.includes?.users?.find(user => user.id === tweet.author_id);+ return (+ author?.location?.toLowerCase().includes("united states") ||+ author?.location?.toLowerCase().includes("usa") ||+ author?.username === "louis030195" ||+ tweet.text.toLowerCase().includes("@louis030195")+ );+ });++ return filteredTweets;+}++async function generateTwitterSuggestions(+ tweets: TweetV2[],+ customPrompt: string,+ ollamaModel: string,+ ollamaApiUrl: string+): Promise<TwitterSuggestionLog[]> {+ const hardcodedPrompt = `you generate 3 tweet comments to these tweets: ${tweets+ .map((tweet) => tweet.text)+ .join(", ")}++ respect these rules: ${customPrompt}++ 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.++ TLDR of twitter algorithm:++ 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++ 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++ for each tweet, return a json object:+ {+ "tweetId": "the id of the tweet",+ "comment": "the tweet comment"+ }`;++ const provider = createOllama({ baseURL: ollamaApiUrl });++ const response = await generateObject({+ model: provider(ollamaModel),+ messages: [{ role: "user", content: hardcodedPrompt }],+ schema: z.array(twitterSuggestionLog),+ });++ console.log("ai suggestions:", response.object);+ return response.object;+}++function generateTwitterLinks(suggestions: TwitterSuggestionLog[]): string {+ return suggestions+ .map((suggestion, index) => {+ const encodedComment = encodeURIComponent(suggestion.comment);++ const twitterLink = `https://twitter.com/intent/tweet?in_reply_to=${suggestion.tweetId}&text=${encodedComment}`;++ return `+### ${index + 1}. Tweet: ${suggestion.tweetId}++Comment: ${suggestion.comment}++[Comment on Twitter](${twitterLink})+ `.trim();+ })+ .join("\n\n");+}++async function syncSuggestionsToInbox(+ suggestions: TwitterSuggestionLog[]+): Promise<void> {+ try {+ console.log("syncSuggestionsToInbox", suggestions);++ const markdownContent = generateTwitterLinks(suggestions);++ await pipe.inbox.send({+ title: "twitter suggestions",+ body: `new twitter suggestions:\n\n${markdownContent}`,+ });+ } catch (error) {+ console.error("error syncing twitter suggestions to inbox:", error);+ await pipe.inbox.send({+ title: "twitter suggestions error",+ body: `error syncing twitter suggestions to inbox: ${error}`,+ });+ }+}++async function streamTwitterSuggestions(): Promise<void> {+ console.log("starting twitter suggestions stream");++ const config = pipe.loadPipeConfig();+ 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);++ await pipe.inbox.send({+ title: "twitter suggestions stream started",+ body: `monitoring tweets every ${config.interval} seconds`,+ });++ pipe.scheduler+ .task("generateTwitterSuggestions")+ // .every(interval)++ .every("1 minutes")+ .do(async () => {+ try {+ const now = new Date();+ const oneHourAgo = new Date(now.getTime() - interval);++ const screenData = await pipe.queryScreenpipe({+ startTime: oneHourAgo.toISOString(),+ endTime: now.toISOString(),+ limit: 50,+ contentType: "ocr",+ });++ if (screenData && screenData.data.length > 0) {+ const keywords = await extractKeywords(+ screenData.data,+ ollamaModel,+ ollamaApiUrl+ );+ const relevantTweets = await fetchRelevantTweets(+ keywords,+ twitterClient+ );++ if (relevantTweets.length > 0) {+ const suggestions = await generateTwitterSuggestions(+ relevantTweets,+ config.customPrompt,+ ollamaModel,+ ollamaApiUrl+ );+ 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 pipeline:", error);+ await pipe.inbox.send({+ title: "twitter suggestions error",+ body: `error in twitter suggestions pipeline: ${error}`,+ });+ }+ });++ await pipe.scheduler.start();+}++streamTwitterSuggestions();++/**++# these are mandatory env variables+export SCREENPIPE_DIR="$HOME/.screenpipe"+export PIPE_ID="pipe-twitter-autopilot"+export PIPE_FILE="pipe.ts"+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+ */diff --git a/screenpipe-app-tauri/components/log-file-button.tsx b/screenpipe-app-tauri/components/log-file-button.tsxindex f8972a02e..8b0c0e719 100644--- a/screenpipe-app-tauri/components/log-file-button.tsx+++ b/screenpipe-app-tauri/components/log-file-button.tsx@@ -14,17 +14,24 @@ import { readTextFile } from "@tauri-apps/plugin-fs";import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";import { cn } from "@/lib/utils";-export const LogFileButton = ({ className }: { className?: string }) => {+export const LogFileButton = ({+ className,+ isAppLog = false,+}: {+ className?: string;+ isAppLog?: boolean;+}) => {const { toast } = useToast();const { copyToClipboard } = useCopyToClipboard({ timeout: 3000 });const getLogFilePath = async () => {const homeDirPath = await homeDir();+ const logFileName = isAppLog ? "screenpipe-app" : "screenpipe";return platform() === "windows"- ? `${homeDirPath}\\.screenpipe\\screenpipe.${+ ? `${homeDirPath}\\.screenpipe\\${logFileName}.${new Date().toISOString().split("T")[0]}.log`- : `${homeDirPath}/.screenpipe/screenpipe.${+ : `${homeDirPath}/.screenpipe/${logFileName}.${new Date().toISOString().split("T")[0]}.log`;};@@ -32,6 +39,7 @@ export const LogFileButton = ({ className }: { className?: string }) => {const handleOpenLogFile = async () => {try {const logPath = await getLogFilePath();+ console.log("opening log file:", logPath);await open(logPath);} catch (error) {console.error("failed to open log file:", error);@@ -80,7 +88,7 @@ export const LogFileButton = ({ className }: { className?: string }) => {</Button></TooltipTrigger><TooltipContent>- <p>open log file</p>+ <p>open {isAppLog ? "app " : ""}log file</p></TooltipContent></Tooltip></TooltipProvider>diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsxindex d90fefccc..29566a55b 100644--- a/screenpipe-app-tauri/components/settings.tsx+++ b/screenpipe-app-tauri/components/settings.tsx@@ -212,10 +212,15 @@ export function Settings({ className }: { className?: string }) {setOllamaStatus("running");toast({title: "starting ai",- description: "initializing the embedded ai...",+ description:+ "downloading and initializing the embedded ai, may take a while (check $HOME/.ollama/models)...",});try {+ console.log(+ "starting ollama sidecar with settings:",+ localSettings.embeddedLLM+ );const result = await invoke<string>("start_ollama_sidecar", {settings: {enabled: localSettings.embeddedLLM.enabled,@@ -812,7 +817,7 @@ export function Settings({ className }: { className?: string }) {<X className="h-4 w-4 mr-2" />stop ai</Button>- <LogFileButton />+ <LogFileButton isAppLog={true} /><Badge>{embeddedAIStatus}</Badge></>)}diff --git a/screenpipe-app-tauri/scripts/pre_build.js b/screenpipe-app-tauri/scripts/pre_build.jsindex d92890350..4f4846615 100644--- a/screenpipe-app-tauri/scripts/pre_build.js+++ b/screenpipe-app-tauri/scripts/pre_build.js@@ -505,7 +505,7 @@ if (process.env.GITHUB_ENV) {// Modify the installOllamaSidecar functionasync function installOllamaSidecar() {const ollamaDir = path.join(__dirname, '..', 'src-tauri');- const ollamaVersion = 'v0.3.13';+ const ollamaVersion = 'v0.3.14';let ollamaExe, ollamaUrl;diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex ccffc279d..ecf123550 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.6.8"+version = "0.6.9"description = ""authors = ["you"]license = ""diff --git a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rsindex 9499b2bc0..ed7fe51a7 100644--- a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs+++ b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs@@ -2,8 +2,10 @@ use anyhow::{anyhow, Result};use serde::{Deserialize, Serialize};use std::env;use std::time::Duration;+use tauri::async_runtime::Receiver;use tauri::Emitter;use tauri::Manager;+use tauri_plugin_shell::process::CommandEvent;use tauri_plugin_shell::ShellExt;use tokio::time::sleep;use tracing::{error, info};@@ -56,36 +58,34 @@ impl LLMSidecar {.env("CUDA_PATH", &new_cuda_path);#[cfg(target_os = "windows")]- let serve_command = serve_command.env("OLLAMA_ORIGINS", "*");+ {+ serve_command = serve_command.env("OLLAMA_ORIGINS", "*");+ }- let (_, _child) = serve_command- .spawn()- .map_err(|e| {- error!("Failed to spawn sidecar: {}", e);- e.to_string()- })- .unwrap();+ let (mut receiver, _) = serve_command.spawn()?;++ // Stream logs for serve command+ self.stream_logs("ollama-serve", &mut receiver).await?;info!("Waiting for Ollama server to start...");self.wait_for_server().await?;- // now ollama run the model-+ // Now run the model+ info!("Starting Ollama model...");let model_command = app.shell().sidecar("ollama").unwrap();let model_command = model_command.args(&["run", &self.settings.model]).env("CUDA_PATH", &new_cuda_path);#[cfg(target_os = "windows")]- let model_command = model_command.env("OLLAMA_ORIGINS", "*");+ {+ model_command = model_command.env("OLLAMA_ORIGINS", "*");+ }- let (_, _child) = model_command- .spawn()- .map_err(|e| {- error!("Failed to spawn sidecar: {}", e);- e.to_string()- })- .unwrap();+ let (mut receiver, _) = model_command.spawn()?;++ // Stream logs for model command+ self.stream_logs("ollama-model", &mut receiver).await?;info!("Testing Ollama model...");let test_result = self.test_model().await?;@@ -93,6 +93,31 @@ impl LLMSidecar {Ok(test_result)}+ async fn stream_logs(&self, prefix: &str, rx: &mut Receiver<CommandEvent>) -> Result<()> {+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line) => {+ info!("[{}][stdout] {}", prefix, String::from_utf8_lossy(&line));+ }+ CommandEvent::Stderr(line) => {+ info!("[{}][stderr] {}", prefix, String::from_utf8_lossy(&line));+ }+ CommandEvent::Error(e) => {+ error!("[{}][error] {}", prefix, e);+ }+ CommandEvent::Terminated(payload) => {+ info!(+ "[{}][terminated] code: {:?}, signal: {:?}",+ prefix, payload.code, payload.signal+ );+ break;+ }+ _ => {}+ }+ }+ Ok(())+ }+async fn wait_for_server(&self) -> Result<()> {let max_retries = 30;let retry_interval = Duration::from_secs(1);diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex b6004d25c..16329c97f 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -122,9 +122,13 @@ async fn main() {let base_dir =get_base_dir(&app_handle, None).expect("Failed to ensure local data directory");- // Set up file appender- let file_appender =- RollingFileAppender::new(Rotation::NEVER, base_dir.clone(), "screenpipe-app.log");+ // Set up rolling file appender+ let file_appender = RollingFileAppender::builder()+ .rotation(Rotation::DAILY)+ .filename_prefix("screenpipe-app")+ .filename_suffix("log")+ .max_log_files(5)+ .build(&app.path().home_dir().unwrap().join(".screenpipe"))?;// Create a custom layer for file logginglet file_layer = tracing_subscriber::fmt::layer()