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
fix: obsidian pipe and pipes logging
Louis Beaumont6da090214b09
diff --git a/pipes/obsidian/package.json b/pipes/obsidian/package.jsonindex 44dbfb0be..8b6e0ea76 100644--- a/pipes/obsidian/package.json+++ b/pipes/obsidian/package.json@@ -1,6 +1,6 @@{"name": "obsidian",- "version": "0.1.6",+ "version": "0.1.9","private": true,"scripts": {"dev": "next dev --turbopack",diff --git a/pipes/obsidian/src/app/api/log/route.ts b/pipes/obsidian/src/app/api/log/route.tsindex dd7cf0e9c..5c63581c2 100644--- a/pipes/obsidian/src/app/api/log/route.ts+++ b/pipes/obsidian/src/app/api/log/route.ts@@ -200,7 +200,7 @@ export async function GET() {startTime: oneHourAgo.toISOString(),endTime: now.toISOString(),limit: pageSize,- contentType: "ocr",+ contentType: "all",});if (!screenData || screenData.data.length === 0) {diff --git a/pipes/obsidian/src/app/api/settings/route.ts b/pipes/obsidian/src/app/api/settings/route.tsindex 9664a1784..9bcd261cc 100644--- a/pipes/obsidian/src/app/api/settings/route.ts+++ b/pipes/obsidian/src/app/api/settings/route.ts@@ -1,68 +1,10 @@-// app/api/settings/route.tsimport { pipe } from "@screenpipe/js";import { NextResponse } from "next/server";import { promises as fs } from "fs";import path from "path";-import os from "os";-// Force Node.js runtime-export const runtime = "nodejs"; // Add this line-export const dynamic = "force-dynamic";--const DEFAULT_INTERVAL_MINUTES = 5;--function getAppDataDir(): string {- const homeDir = os.homedir();- return path.join(homeDir, ".screenpipe");-}--async function updateCronSchedule(intervalMinutes: number) {- try {- const screenpipeDir = process.env.SCREENPIPE_DIR || getAppDataDir();- const pipeConfigPath = path.join(- screenpipeDir,- "pipes",- "obsidian",- "pipe.json"- );-- console.log(`updating cron schedule at: ${pipeConfigPath}`);-- // Load or initialize both configs- let config: any = {};- try {- const content = await fs.readFile(pipeConfigPath, "utf8");- config = JSON.parse(content);- } catch (err) {- console.log(- `no existing config found, creating new one at ${pipeConfigPath}`- );- config = { crons: [] };- }-- // Update cron config- config.crons = [- {- path: "/api/log",- schedule: `0 */${intervalMinutes} * * * *`,- },- {- path: "/api/intelligence",- schedule: "0 0 */1 * * *",- },- ];- config.enabled = config.enabled ?? true;- config.is_nextjs = config.is_nextjs ?? true;-- await fs.writeFile(pipeConfigPath, JSON.stringify(config, null, 2));- console.log(- `updated cron schedule to run every ${intervalMinutes} minutes`- );- } catch (err) {- console.error("failed to update cron schedule:", err);- throw err;- }-}+export const runtime = "nodejs";+export const dynamic = "force-dynamic";export async function GET() {try {@@ -72,12 +14,12 @@ export async function GET() {}// Load persisted settings if they exist- const screenpipeDir = process.env.SCREENPIPE_DIR || getAppDataDir();+ const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();const settingsPath = path.join(screenpipeDir,"pipes","obsidian",- "settings.json"+ "pipe.json");try {@@ -86,13 +28,12 @@ export async function GET() {// Merge with current settingsconst rawSettings = await settingsManager.getAll();- console.log("rawSettings", rawSettings);return NextResponse.json({...rawSettings,customSettings: {...rawSettings.customSettings,- obsidian: {- ...(rawSettings.customSettings?.obsidian || {}),+ ["obsidian"]: {+ ...(rawSettings.customSettings?.["obsidian"] || {}),...persistedSettings,},},@@ -121,22 +62,11 @@ export async function PUT(request: Request) {const body = await request.json();const { key, value, isPartialUpdate, reset, namespace } = body;- // Handle obsidian namespace updates- if (namespace === "obsidian" && isPartialUpdate) {- // Use provided interval or default- const intervalMs = value.interval || DEFAULT_INTERVAL_MINUTES * 60000;- const intervalMinutes = Math.max(1, Math.floor(intervalMs / 60000));- await updateCronSchedule(intervalMinutes);- console.log(`setting interval to ${intervalMinutes} minutes`);- }-if (reset) {if (namespace) {if (key) {- // Reset single key in namespaceawait settingsManager.setCustomSetting(namespace, key, undefined);} else {- // Reset entire namespaceawait settingsManager.updateNamespaceSettings(namespace, {});}} else {diff --git a/pipes/obsidian/src/components/obsidian-settings.tsx b/pipes/obsidian/src/components/obsidian-settings.tsxindex caf6d10cc..0922a0d95 100644--- a/pipes/obsidian/src/components/obsidian-settings.tsx+++ b/pipes/obsidian/src/components/obsidian-settings.tsx@@ -25,6 +25,7 @@ import path from "path";import { FileSuggestTextarea } from "./file-suggest-textarea";import { Skeleton } from "@/components/ui/skeleton";import { debounce } from "lodash";+import { updatePipeConfig } from "@/lib/actions/update-pipe-config";// This interface represents the shape of obsidian settingsinterface ObsidianSettings {@@ -119,6 +120,7 @@ export function ObsidianSettings() {obsidian: obsidianSettings,},});+ await updatePipeConfig(obsidianSettings.interval / 60000);loadingToast.update({id: loadingToast.id,@@ -154,6 +156,7 @@ export function ObsidianSettings() {obsidian: obsidianSettings,},});+ await updatePipeConfig(obsidianSettings.interval / 60000);// Then test log generationconst res = await fetch("/api/log");@@ -570,7 +573,9 @@ export function ObsidianSettings() {</div><div className="space-y-2">- <Label htmlFor="aiModel">ollama/local openai-compatible model</Label>+ <Label htmlFor="aiModel">+ ollama/local openai-compatible model+ </Label><OllamaModelsListdisabled={!pathValidation.isValid}defaultValue={diff --git a/pipes/obsidian/src/lib/actions/update-pipe-config.ts b/pipes/obsidian/src/lib/actions/update-pipe-config.tsnew file mode 100644index 000000000..8ab578cc1--- /dev/null+++ b/pipes/obsidian/src/lib/actions/update-pipe-config.ts@@ -0,0 +1,52 @@+"use server";+import { promises as fs } from "fs";+import path from "path";++export async function updatePipeConfig(intervalMinutes: number) {+ try {+ const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();+ const pipeConfigPath = path.join(+ screenpipeDir,+ "pipes",+ "obsidian",+ "pipe.json"+ );++ console.log(`updating cron schedule at: ${pipeConfigPath}`);++ // Load or initialize both configs+ let config: any = {};++ try {+ const content = await fs.readFile(pipeConfigPath, "utf8");+ config = JSON.parse(content);+ } catch (err) {+ console.log(+ `no existing config found, creating new one at ${pipeConfigPath}`+ );+ config = { crons: [] };+ }++ // Update cron config+ config.crons = [+ {+ path: "/api/log",+ schedule: `0 */${intervalMinutes} * * * *`,+ },+ {+ path: "/api/intelligence",+ schedule: "0 0 */1 * * *",+ },+ ];+ config.enabled = config.enabled ?? true;+ config.is_nextjs = config.is_nextjs ?? true;++ await fs.writeFile(pipeConfigPath, JSON.stringify(config, null, 2));+ console.log(+ `updated cron schedule to run every ${intervalMinutes} minutes`+ );+ } catch (err) {+ console.error("failed to update cron schedule:", err);+ throw err;+ }+}diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex 2605df32f..49ce9394e 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -172,7 +172,7 @@ mod pipes {// Fallback to random port if neededlet port =assigned_port.unwrap_or_else(|| pick_unused_port().expect("No ports free"));- info!("using port {} for next.js pipe", port);+ info!("[{}] using port {} for next.js pipe", pipe, port);// Update pipe.json with the actual port being usedlet mut updated_config = pipe_config.clone();@@ -180,18 +180,25 @@ mod pipes {let updated_pipe_json = serde_json::to_string_pretty(&updated_config)?;let mut file = File::create(&pipe_json_path).await?;file.write_all(updated_pipe_json.as_bytes()).await?;- debug!("updated pipe.json with port configuration");+ info!(+ "[{}] updated pipe.json with port configuration: {}",+ pipe, updated_pipe_json+ );env_vars.push(("PORT".to_string(), port.to_string()));// Handle cron jobs if they existif let Some(crons) = pipe_config.get("crons").and_then(Value::as_array) {- debug!("found {} cron jobs in configuration", crons.len());+ info!(+ "[{}] found {} cron jobs in configuration",+ pipe,+ crons.len()+ );let base_url = format!("http://localhost:{}", port);- debug!("using base url: {} for cron jobs", base_url);+ debug!("[{}] using base url: {} for cron jobs", pipe, base_url);let cron_secret = generate_cron_secret();- debug!("generated cron secret for pipe: {}", pipe);+ debug!("[{}] generated cron secret: {}", pipe, cron_secret);env_vars.push(("CRON_SECRET".to_string(), cron_secret.clone()));let mut handles = Vec::new();@@ -234,7 +241,7 @@ mod pipes {}// Install dependencies using bun- info!("installing dependencies for next.js pipe [{}]", pipe);+ info!("[{}] installing dependencies for next.js pipe", pipe);let install_output = Command::new(&bun_path).arg("install")@@ -246,7 +253,7 @@ mod pipes {if !install_output.status.success() {let err_msg = String::from_utf8_lossy(&install_output.stderr);- error!("failed to install dependencies: {}", err_msg);+ error!("[{}] failed to install dependencies: {}", pipe, err_msg);let err = anyhow::anyhow!("failed to install dependencies for next.js pipe: {}",err_msg@@ -254,12 +261,15 @@ mod pipes {sentry::capture_error(&err.source().unwrap());anyhow::bail!(err);}- debug!("successfully installed dependencies for next.js pipe");+ info!(+ "[{}] successfully installed dependencies for next.js pipe",+ pipe+ );} else {let port = pick_unused_port().expect("No ports free");- debug!(- "no pipe.json found, using random port {} for next.js pipe",- port+ info!(+ "[{}] no pipe.json found, using random port {} for next.js pipe",+ pipe, port);env_vars.push(("PORT".to_string(), port.to_string()));}@@ -291,7 +301,7 @@ mod pipes {if build_success {command.arg("start");} else {- info!("falling back to dev mode due to build failure");+ info!("[{}] falling back to dev mode due to build failure", pipe);command.arg("dev");}@@ -305,7 +315,7 @@ mod pipes {let mut child = command.spawn()?;- debug!("streaming logs for next.js pipe");+ debug!("[{}] streaming logs for next.js pipe", pipe);stream_logs(pipe, &mut child).await?;return Ok((child, PipeState::Port(port)));@@ -313,7 +323,7 @@ mod pipes {// If it's not a Next.js project, run as regular pipelet main_module = find_pipe_file(&pipe_dir)?;- info!("executing pipe: {:?}", main_module);+ info!("[{}] executing pipe: {:?}", pipe, main_module);env_vars.push(("PIPE_FILE".to_string(),@@ -1065,7 +1075,7 @@ mod pipes {}};- debug!(+ info!("next cron execution for pipe {} at path {} in {} seconds",pipe,path,@@ -1075,7 +1085,7 @@ mod pipes {// Wait for either the next execution time or shutdown signaltokio::select! {_ = tokio::time::sleep(duration) => {- debug!("executing cron job for pipe {} at path {}", pipe, path);+ info!("executing cron job for pipe {} at path {}", pipe, path);match client.get(format!("{}{}", base_url, path)).headers(headers.clone())@@ -1126,14 +1136,17 @@ mod pipes {}async fn try_build_nextjs(pipe_dir: &Path, bun_path: &Path) -> Result<bool> {- info!("attempting to build next.js project in: {:?}", pipe_dir);+ info!(+ "checking if i need to build the next.js project in: {:?}",+ pipe_dir+ );// Check if build already exists and is validlet build_dir = pipe_dir.join(".next");if build_dir.exists() {let build_manifest = build_dir.join("build-manifest.json");if build_manifest.exists() {- debug!("found existing next.js build, skipping rebuild");+ info!("found existing next.js build, skipping rebuild");return Ok(true);}// Invalid/incomplete build directory - remove it@@ -1168,7 +1181,11 @@ mod pipes {TcpListener::bind(("127.0.0.1", port)).is_ok()}- pub async fn download_pipe_private(pipe_name: &str, source: &str, screenpipe_dir: PathBuf) -> anyhow::Result<PathBuf> {+ pub async fn download_pipe_private(+ pipe_name: &str,+ source: &str,+ screenpipe_dir: PathBuf,+ ) -> anyhow::Result<PathBuf> {info!("processing private pipe from zip: {}", source);let dest_dir = screenpipe_dir.join("pipes").join(&pipe_name);@@ -1192,11 +1209,11 @@ mod pipes {debug!("unzipping file to temp directory");let temp_zip_path = temp_zip.clone();let temp_dir_path = temp_dir.clone();-+tokio::task::spawn_blocking(move || -> anyhow::Result<()> {let zip_file = std::fs::File::open(&temp_zip_path)?;let mut archive = zip::ZipArchive::new(zip_file)?;-+for i in 0..archive.len() {let mut file = archive.by_index(i)?;let name = file.name().to_string();@@ -1215,7 +1232,8 @@ mod pipes {}}Ok(())- }).await??;+ })+ .await??;// Remove the temporary zip filetokio::fs::remove_file(&temp_zip).await?;