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: persist scheduler state to disk
Louis Beaumont988455464e22
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1716e4ba5..142de11f6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -49,6 +49,11 @@ jobs:run: cargo test- name: Run deno tests+ env:+ SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipe+ PIPE_ID: test+ PIPE_FILE: pipe.ts+ PIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/testrun: deno test --allow-env --allow-write --allow-readworking-directory: ./screenpipe-js@@ -90,6 +95,11 @@ jobs:run: cargo test test_process_ocr_task_windows- name: Run deno tests+ env:+ SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipe+ PIPE_ID: test+ PIPE_FILE: pipe.ts+ PIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/testrun: deno test --allow-env --allow-write --allow-readworking-directory: ./screenpipe-js@@ -136,5 +146,10 @@ jobs:run: cargo test test_apple_native_ocr- name: Run deno tests+ env:+ SCREENPIPE_DIR: ${{ runner.workspace }}/screenpipe+ PIPE_ID: test+ PIPE_FILE: pipe.ts+ PIPE_DIR: ${{ runner.workspace }}/screenpipe/pipes/testrun: deno test --allow-env --allow-write --allow-readworking-directory: ./screenpipe-jsdiff --git a/examples/typescript/pipe-email-daily-log/pipe.json b/examples/typescript/pipe-email-daily-log/pipe.jsonindex a566fe72a..3af6472f4 100644--- a/examples/typescript/pipe-email-daily-log/pipe.json+++ b/examples/typescript/pipe-email-daily-log/pipe.json@@ -57,8 +57,8 @@{"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 that will be used to summarize the logs previously extracted and send a mail"+ "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 summary will be sent as an email to my address. Additionally, based on the activities and patterns observed, suggest 10 possible action items or tasks for the next day. These should be practical, relevant, and aimed at improving productivity or addressing any pending matters identified in the daily summary.",+ "description": "Summary prompt for the AI assistant that will be used to summarize the logs previously extracted, suggest action items for the next day, and send an email"},{"name": "windowName",@@ -66,6 +66,12 @@"default": "","description": "Specific window name to filter the screen data, for example 'gmail', 'john', 'slack', 'myCodeFile.tsx', etc. this will filter out audio"},+ {+ "name": "appName",+ "type": "string",+ "default": "",+ "description": "Specific application name to filter the screen data, for example 'Chrome', 'Visual Studio Code', 'Slack', etc. Leave empty to include all applications"+ },{"name": "contentType","type": "contentType",diff --git a/examples/typescript/pipe-email-daily-log/pipe.ts b/examples/typescript/pipe-email-daily-log/pipe.tsindex dfdc8f52c..633d9d14f 100644--- a/examples/typescript/pipe-email-daily-log/pipe.ts+++ b/examples/typescript/pipe-email-daily-log/pipe.ts@@ -5,6 +5,7 @@ import process from "node:process";import { z } from "zod";import { generateObject, generateText } from "ai";import { createOllama } from "ollama-ai-provider";+import { pipe } from "screenpipe";interface DailyLog {activity: string;@@ -200,8 +201,9 @@ async function dailyLogPipeline(): Promise<void> {const ollamaModel = config.ollamaModel;const ollamaApiUrl = config.ollamaApiUrl;const windowName = config.windowName || "";+ const appName = config.appName || "";const pageSize = config.pageSize;- const contentType = config.contentType || "ocr"; // Default to 'ocr' if not specified+ const contentType = config.contentType || "ocr";console.log("creating logs dir");const logsDir = `${process.env.PIPE_DIR}/logs`;@@ -212,9 +214,9 @@ async function dailyLogPipeline(): Promise<void> {console.warn("error creating logs dir, probably already exists");}- let lastEmailSent = new Date(0); // Initialize to a past date+ let lastEmailSent = new Date(0);- // send a welcome email to announce what will happen, when it will happen, and what it will do+ // Send welcome emailconst welcomeEmail = `Welcome to the daily log pipeline!@@ -224,7 +226,6 @@ async function dailyLogPipeline(): Promise<void> {? `It will run at ${emailTime} every day.`: `It will run every ${summaryFrequency} hours.`}-`;await sendEmail(emailAddress,@@ -233,8 +234,16 @@ async function dailyLogPipeline(): Promise<void> {welcomeEmail);- while (true) {- try {+ await pipe.inbox.send({+ title: "Daily Log Started",+ body: "A new day of activity logging has begun. Your summary will be sent later as scheduled.",+ });++ // Schedule regular log generation+ pipe.scheduler+ .task("generateLog")+ .every(interval)+ .do(async () => {const now = new Date();const oneMinuteAgo = new Date(now.getTime() - interval);@@ -242,6 +251,7 @@ async function dailyLogPipeline(): Promise<void> {startTime: oneMinuteAgo.toISOString(),endTime: now.toISOString(),windowName: windowName,+ appName: appName,limit: pageSize,contentType: contentType,});@@ -256,54 +266,89 @@ async function dailyLogPipeline(): Promise<void> {console.log("log entry:", logEntry);await saveDailyLog(logEntry);}+ });- let shouldSendSummary = false;+ // Schedule summary generation and email sending+ if (summaryFrequency === "daily") {+ const [emailHour, emailMinute] = emailTime.split(":").map(Number);+ pipe.scheduler+ .task("dailySummary")+ .every("1 day")+ .at(`${emailHour}:${emailMinute}`)+ .do(async () => {+ await generateAndSendSummary();+ });+ } else if (summaryFrequency.startsWith("hourly:")) {+ const hours = parseInt(summaryFrequency.split(":")[1], 10);+ pipe.scheduler+ .task("hourlySummary")+ .every(`${hours} hours`)+ .do(async () => {+ await generateAndSendSummary();+ });+ }- if (summaryFrequency === "daily") {- const [emailHour, emailMinute] = emailTime.split(":").map(Number);- const emailTimeToday = new Date(- now.getFullYear(),- now.getMonth(),- now.getDate(),- emailHour,- emailMinute- );- shouldSendSummary =- now >= emailTimeToday &&- now.getTime() - lastEmailSent.getTime() > 24 * 60 * 60 * 1000;- } else if (summaryFrequency.startsWith("hourly:")) {- const hours = parseInt(summaryFrequency.split(":")[1], 10);- shouldSendSummary =- now.getTime() - lastEmailSent.getTime() >= hours * 60 * 60 * 1000;- }+ async function generateAndSendSummary() {+ const todayLogs = getTodayLogs();+ console.log("today's logs:", todayLogs);++ if (todayLogs.length > 0) {+ const summary = await generateDailySummary(+ todayLogs,+ summaryPrompt,+ ollamaModel,+ ollamaApiUrl+ );+ console.log("summary:", summary);++ // Send email+ await sendEmail(+ emailAddress,+ emailPassword,+ "Daily Activity Summary",+ summary+ );++ // Send notification to AI inbox+ await pipe.inbox.send({+ title: "Daily Activity Summary",+ body: "Your daily activity summary has been generated and sent to your email.",+ });- if (shouldSendSummary) {- const todayLogs = await getTodayLogs();- console.log("today's logs:", todayLogs);-- if (todayLogs.length > 0) {- const summary = await generateDailySummary(- todayLogs,- summaryPrompt,- ollamaModel,- ollamaApiUrl- );- console.log("summary:", summary);- await sendEmail(- emailAddress,- emailPassword,- "activity summary",- summary- );- lastEmailSent = now;- }- }- } catch (error) {- console.warn("error in daily log pipeline:", error);+ lastEmailSent = new Date();+ } else {+ // Send notification if no logs were found+ await pipe.inbox.send({+ title: "No Activity Logged",+ body: "No activity logs were found for today. Make sure Screenpipe is running and capturing your screen data.",+ });}- console.log("sleeping for", interval, "ms");- await new Promise((resolve) => setTimeout(resolve, interval));}++ // Add a new task to send a daily start notification+ pipe.scheduler+ .task("dailyStartNotification")+ .every("1 day")+ .at("00:01") // Just after midnight+ .do(async () => {+ await pipe.inbox.send({+ title: "Daily Log Started",+ body: "A new day of activity logging has begun. Your summary will be sent later as scheduled.",+ actions: [+ {+ label: "View Yesterday's Summary",+ action: "view_yesterday_summary",+ },+ {+ label: "Dismiss",+ action: "dismiss",+ },+ ],+ });+ });++ // Start the scheduler+ pipe.scheduler.start();}dailyLogPipeline();diff --git a/scheduler_state.json b/scheduler_state.jsonnew file mode 100644index 000000000..9020eec7e--- /dev/null+++ b/scheduler_state.json@@ -0,0 +1 @@+{"testTask":{"lastRunTime":1729101565657,"nextRunTime":1729101600000},"task1":{"lastRunTime":1729101565657,"nextRunTime":1729101600000},"task2":{"lastRunTime":1729101565657,"nextRunTime":1729101600000},"persistentTask":{"lastRunTime":1729101565657,"nextRunTime":1729101600000}}\ No newline at end of filediff --git a/screenpipe-js/main.ts b/screenpipe-js/main.tsindex 3c108e46e..86825fe3a 100644--- a/screenpipe-js/main.ts+++ b/screenpipe-js/main.ts@@ -1,4 +1,5 @@import * as fs from "node:fs";+import * as path from "node:path";import process from "node:process";import cronParser from "npm:cron-parser";@@ -251,17 +252,32 @@ export interface InboxMessageAction {action: string;}+interface TaskState {+ lastRunTime: number;+ nextRunTime: number;+}++interface SchedulerState {+ [taskName: string]: TaskState;+}+class Task {private _name: string;private _interval: string | number;private _time: string | null = null;private _handler: (() => Promise<void>) | null = null;private _nextRunTime: Date;+ private _state?: TaskState;- constructor(name: string) {+ constructor(name: string, state?: TaskState) {this._name = name;this._interval = 0;- this._nextRunTime = new Date(0); // Set to past date to run immediately+ if (state) {+ this._nextRunTime = new Date(state.nextRunTime);+ } else {+ this._nextRunTime = new Date(0);+ }+ this._state = state;}every(interval: string | number): Task {@@ -332,9 +348,52 @@ class Task {class Scheduler {private tasks: Task[] = [];private running: boolean = false;+ private state: SchedulerState = {};+ private stateFilePath: string;++ constructor() {+ const pipeId = process.env.PIPE_ID;+ if (!pipeId) {+ throw new Error("PIPE_ID environment variable is not set");+ }+ this.stateFilePath = path.join(+ process.env.SCREENPIPE_DIR || "",+ "pipes",+ pipeId,+ "scheduler_state.json"+ );+ this.loadState();+ }++ private loadState() {+ try {+ if (fs.existsSync(this.stateFilePath)) {+ const stateData = fs.readFileSync(this.stateFilePath, "utf8");+ this.state = JSON.parse(stateData);+ } else {+ console.log("No existing state file found. Starting with empty state.");+ this.state = {};+ }+ } catch (error) {+ console.warn("Failed to load scheduler state:", error);+ this.state = {};+ }+ }++ private saveState() {+ try {+ const dir = path.dirname(this.stateFilePath);+ if (!fs.existsSync(dir)) {+ fs.mkdirSync(dir, { recursive: true });+ }+ fs.writeFileSync(this.stateFilePath, JSON.stringify(this.state), "utf8");+ } catch (error) {+ console.error("Failed to save scheduler state:", error);+ }+ }task(name: string): Task {- const task = new Task(name);+ const task = new Task(name, this.state[name]);this.tasks.push(task);return task;}@@ -343,30 +402,17 @@ class Scheduler {this.running = true;while (this.running) {const now = new Date();- console.log(`Current time: ${now.toISOString()}`);- console.log(`Tasks: ${this.tasks.map((t) => t.getName()).join(", ")}`);-for (const task of this.tasks) {if (task.getNextRunTime() <= now) {- console.log(- `Executing task: ${task.getName()} at ${now.toISOString()}`- );await task.execute();- console.log(- `Task ${task.getName()} executed, next run time: ${task- .getNextRunTime()- .toISOString()}`- );- } else {- console.log(- `Task ${task.getName()} not due yet. Next run time: ${task- .getNextRunTime()- .toISOString()}`- );+ this.state[task.getName()] = {+ lastRunTime: now.getTime(),+ nextRunTime: task.getNextRunTime().getTime(),+ };+ this.saveState();}}-- await this.sleep(100); // Check more frequently+ await this.sleep(100);}}diff --git a/screenpipe-js/tests/scheduler.test.ts b/screenpipe-js/tests/scheduler.test.tsindex 045acd76b..3cabf880a 100644--- a/screenpipe-js/tests/scheduler.test.ts+++ b/screenpipe-js/tests/scheduler.test.ts@@ -90,4 +90,50 @@ Deno.test("Scheduler - multiple tasks", async () => {assertEquals(mockTask2.calls.length >= 1, true);});-// deno test screenpipe-js/tests/scheduler.test.ts+Deno.test("Scheduler - state persistence", async () => {+ const tempDir = await Deno.makeTempDir();+ const originalEnv = Deno.env.get("SCREENPIPE_DIR");+ Deno.env.set("SCREENPIPE_DIR", tempDir);++ const scheduler = pipe.scheduler;+ const mockTask = spy(() => Promise.resolve());++ scheduler.task("persistentTask").every("1 minute").do(mockTask);++ // Mock Date as before+ // ...++ // Run scheduler for a short time+ const schedulerPromise = scheduler.start();+ await new Promise((resolve) => setTimeout(resolve, 200));+ scheduler.stop();+ await schedulerPromise;++ // Create a new scheduler instance (simulating process restart)+ const newScheduler = pipe.scheduler;+ newScheduler.task("persistentTask").every("1 minute").do(mockTask);++ // Verify that the task's next run time was loaded from the persistent state+ const task = newScheduler["tasks"][0];+ assertEquals(task.getNextRunTime().getTime() > Date.now(), true);++ // Clean up+ await Deno.remove(tempDir, { recursive: true });+ if (originalEnv) {+ Deno.env.set("SCREENPIPE_DIR", originalEnv);+ } else {+ Deno.env.delete("SCREENPIPE_DIR");+ }+});++/*++export SCREENPIPE_DIR="$HOME/.screenpipe"+export PIPE_ID="test-scheduler"+export PIPE_FILE="pipe.ts"+export PIPE_DIR="$SCREENPIPE_DIR/pipes/test-scheduler"+++deno test screenpipe-js/tests/scheduler.test.ts --allow-env --allow-read --allow-write++*/\ No newline at end of file