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: add pipe scheduler
Louis Beaumont20c2e64581b9
diff --git a/screenpipe-js/deno.json b/screenpipe-js/deno.jsonindex c6a373173..0c666f3fb 100644--- a/screenpipe-js/deno.json+++ b/screenpipe-js/deno.json@@ -1,3 +1,3 @@{- "imports": {}-}\ No newline at end of file+ "imports": { "cron-parser": "npm:cron-parser@^4.9.0" }+}diff --git a/screenpipe-js/deno.lock b/screenpipe-js/deno.lockindex 4af223d6b..a141f1ca7 100644--- a/screenpipe-js/deno.lock+++ b/screenpipe-js/deno.lock@@ -2,6 +2,7 @@"version": "4","specifiers": {"npm:@types/node@*": "22.5.4",+ "npm:cron-parser@^4.9.0": "4.9.0","npm:[email protected]": "4.18.2","npm:[email protected]": "5.1.1","npm:[email protected]": "7.1.0"@@ -68,6 +69,12 @@"[email protected]": {"integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw=="},+ "[email protected]": {+ "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",+ "dependencies": [+ "luxon"+ ]+ },"[email protected]": {"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==","dependencies": [@@ -228,6 +235,9 @@"[email protected]": {"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="},+ "[email protected]": {+ "integrity": "sha512-rh+Zjr6DNfUYR3bPwJEnuwDdqMbxZW7LOQfUN4B54+Cl+0o5zaU9RJ6bcidfDtC1cWCZXQ+nvX8bf6bAji37QQ=="+ },"[email protected]": {"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ=="},@@ -379,5 +389,10 @@"[email protected]": {"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="}+ },+ "workspace": {+ "dependencies": [+ "npm:cron-parser@^4.9.0"+ ]}}diff --git a/screenpipe-js/main.ts b/screenpipe-js/main.tsindex 383bdecb3..3c108e46e 100644--- a/screenpipe-js/main.ts+++ b/screenpipe-js/main.ts@@ -1,5 +1,6 @@import * as fs from "node:fs";import process from "node:process";+import cronParser from "npm:cron-parser";// Type definitionsexport interface PipeConfig {@@ -250,10 +251,174 @@ export interface InboxMessageAction {action: string;}+class Task {+ private _name: string;+ private _interval: string | number;+ private _time: string | null = null;+ private _handler: (() => Promise<void>) | null = null;+ private _nextRunTime: Date;++ constructor(name: string) {+ this._name = name;+ this._interval = 0;+ this._nextRunTime = new Date(0); // Set to past date to run immediately+ }++ every(interval: string | number): Task {+ this._interval = interval;+ return this;+ }++ at(time: string): Task {+ this._time = time;+ return this;+ }++ do(handler: () => Promise<void>): Task {+ this._handler = handler;+ return this;+ }++ getNextRunTime(): Date {+ return this._nextRunTime;+ }++ async execute(): Promise<void> {+ if (this._handler) {+ await this._handler();+ this._nextRunTime = this.calculateNextRunTime();+ }+ }++ private calculateNextRunTime(): Date {+ const now = new Date();+ if (typeof this._interval === "number") {+ return new Date(now.getTime() + this._interval);+ }++ const cronExpression = this.toCronExpression();+ const interval = cronParser.parseExpression(cronExpression);+ return interval.next().toDate();+ }++ private toCronExpression(): string {+ if (typeof this._interval === "number") {+ // Convert milliseconds to minutes for cron+ const minutes = Math.floor(this._interval / 60000);+ return `*/${minutes} * * * *`;+ }++ const [value, unit] = this._interval.split(" ");+ switch (unit) {+ case "minute":+ case "minutes":+ return `*/${value} * * * *`;+ case "hour":+ case "hours":+ return `0 */${value} * * *`;+ case "day":+ case "days":+ return `0 0 */${value} * *`;+ default:+ throw new Error(`Unsupported interval unit: ${unit}`);+ }+ }++ getName(): string {+ return this._name;+ }+}++class Scheduler {+ private tasks: Task[] = [];+ private running: boolean = false;++ task(name: string): Task {+ const task = new Task(name);+ this.tasks.push(task);+ return task;+ }++ async start(): Promise<void> {+ 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()}`+ );+ }+ }++ await this.sleep(100); // Check more frequently+ }+ }++ stop(): void {+ this.running = false;+ }++ private sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+ }+}++/**+ * The pipe object is used to interact with the screenpipe higher level functions.+ *+ */export const pipe = {+ /**+ * Send a desktop notification to the user.+ *+ * @example+ * ```typescript+ * pipe.sendDesktopNotification({ title: "Task Completed", body: "Your task has been completed." });+ * ```+ */sendDesktopNotification,+ /**+ * Load the pipe configuration that can be set through the screenpipe app or the pipe.json file.+ *+ * @example+ * ```typescript+ * pipe.loadPipeConfig();+ * ```+ */loadPipeConfig,+ /**+ * Query the screenpipe API.+ *+ * @example+ * ```typescript+ * pipe.queryScreenpipe({ q: "squirrel", contentType: "ocr", limit: 10 });+ * ```+ */queryScreenpipe,+ /**+ * Send a notification to the user's AI inbox.+ *+ * @example+ * ```typescript+ * pipe.inbox.send({ title: "Task Completed", body: "Your task has been completed." });+ * ```+ */inbox: {send: async (message: InboxMessage): Promise<boolean> => {const notificationApiUrl =@@ -271,4 +436,26 @@ export const pipe = {}},},+ /**+ * Scheduler for running tasks at specific times or intervals.+ *+ * @example+ * ```typescript+ * pipe.scheduler.task("dailyReport")+ * .every("1 day")+ * .at("00:00")+ * .do(async () => {+ * console.log("running daily report");+ * });+ *+ * pipe.scheduler.task("everyFiveMinutes")+ * .every("5 minutes")+ * .do(async () => {+ * console.log("running task every 5 minutes");+ * });+ *+ * pipe.scheduler.start();+ * ```+ */+ scheduler: new Scheduler(),};diff --git a/screenpipe-js/tests/scheduler.test.ts b/screenpipe-js/tests/scheduler.test.tsnew file mode 100644index 000000000..045acd76b--- /dev/null+++ b/screenpipe-js/tests/scheduler.test.ts@@ -0,0 +1,93 @@+import { assertEquals } from "jsr:@std/assert";+import { assertSpyCall, spy } from "jsr:@std/testing/mock";+import { pipe } from "../main.ts";++Deno.test("Scheduler - task execution", async () => {+ const scheduler = pipe.scheduler;+ const mockTask = spy(() => Promise.resolve());++ scheduler.task("testTask").every("1 minute").do(mockTask);++ // Mock the Date object to control time+ const originalDate = Date;+ const mockDate = new Date("2023-01-01T00:00:00Z");+ // @ts-ignore: Overriding Date for testing purposes+ Date = class extends Date {+ constructor() {+ super();+ return mockDate;+ }+ static override now() {+ return mockDate.getTime();+ }+ };++ // Start the scheduler+ const schedulerPromise = scheduler.start();++ // Advance time by 1 minute and wait a bit longer+ await new Promise((resolve) => setTimeout(resolve, 100));+ mockDate.setMinutes(mockDate.getMinutes() + 1);+ await new Promise((resolve) => setTimeout(resolve, 100)); // Add this line++ // Stop the scheduler after a longer delay+ setTimeout(() => {+ scheduler.stop();+ }, 500); // Increase this delay++ await schedulerPromise;++ // Restore the original Date object+ Date = originalDate;++ // Assert that the task was called+ assertSpyCall(mockTask, 0);+});++Deno.test("Scheduler - multiple tasks", async () => {+ const scheduler = pipe.scheduler;+ const mockTask1 = spy(() => Promise.resolve());+ const mockTask2 = spy(() => Promise.resolve());++ scheduler.task("task1").every("1 minute").do(mockTask1);++ scheduler.task("task2").every("2 minutes").do(mockTask2);++ // Mock the Date object+ const originalDate = Date;+ const mockDate = new Date("2023-01-01T00:00:00Z");+ // @ts-ignore: Overriding Date for testing purposes+ Date = class extends Date {+ constructor() {+ super();+ return mockDate;+ }+ static override now() {+ return mockDate.getTime();+ }+ };++ // Start the scheduler+ const schedulerPromise = scheduler.start();++ // Advance time by 2 minutes and wait a bit longer+ await new Promise((resolve) => setTimeout(resolve, 100));+ mockDate.setMinutes(mockDate.getMinutes() + 2);+ await new Promise((resolve) => setTimeout(resolve, 100)); // Add this line++ // Stop the scheduler after a longer delay+ setTimeout(() => {+ scheduler.stop();+ }, 500); // Increase this delay++ await schedulerPromise;++ // Restore the original Date object+ Date = originalDate;++ // Assert that tasks were called at least the expected number of times+ assertEquals(mockTask1.calls.length >= 2, true);+ assertEquals(mockTask2.calls.length >= 1, true);+});++// deno test screenpipe-js/tests/scheduler.test.ts