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 both notion, obsidian, and how settings are managed in pipes #1221
Louis Beaumont1a1c5add3ad9
diff --git a/metadata.json b/metadata.jsondeleted file mode 100644index bb46b7d37..000000000--- a/metadata.json+++ /dev/null@@ -1,31 +0,0 @@-{- "overrides": [- {- "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video1.mp4",- "metadata": {- "creation_time": "2024-03-20T10:00:00Z",- "fps": 30.0,- "duration": 300.0,- "device_name": "MacBook Pro"- }- },- {- "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video2.mp4",- "metadata": {- "creation_time": "2024-03-21T15:30:00Z",- "fps": 24.0,- "duration": 400.0,- "device_name": "External Monitor"- }- },- {- "file_path": "/Users/louisbeaumont/Downloads/tmpvideos/video3.mp4",- "metadata": {- "creation_time": "2024-03-22T09:15:00Z",- "fps": 60.0,- "duration": 200.0,- "device_name": "iPad Screen"- }- }- ]-}diff --git a/pipes/notion/package.json b/pipes/notion/package.jsonindex d0074f5ac..44497c424 100644--- a/pipes/notion/package.json+++ b/pipes/notion/package.json@@ -1,6 +1,6 @@{"name": "notion",- "version": "0.1.12",+ "version": "0.1.13","private": true,"scripts": {"dev": "next dev --turbopack",diff --git a/pipes/notion/src/app/api/intelligence/route.ts b/pipes/notion/src/app/api/intelligence/route.tsindex b7f328dfc..95a9e4bd3 100644--- a/pipes/notion/src/app/api/intelligence/route.ts+++ b/pipes/notion/src/app/api/intelligence/route.ts@@ -4,31 +4,31 @@ import { generateObject } from "ai";import { ollama } from "ollama-ai-provider";import { Client } from "@notionhq/client";import { NotionClient } from "@/lib/notion/client";-import { getNotionSettings } from "@/lib/actions/namespace-settings";+import { pipe } from "@screenpipe/js";// rich schema for relationship intelligenceconst contactSchema = z.object({- name: z.string(),- company: z.string().optional(),- lastInteraction: z.string(),- sentiment: z.number(), // -1 to 1- topics: z.array(z.string()),- nextSteps: z.array(z.string()),+ name: z.string(),+ company: z.string().optional(),+ lastInteraction: z.string(),+ sentiment: z.number(), // -1 to 1+ topics: z.array(z.string()),+ nextSteps: z.array(z.string()),});const relationshipIntelligence = z.object({- contacts: z.array(contactSchema),- insights: z.object({- followUps: z.array(z.string()),- opportunities: z.array(z.string()),- }),+ contacts: z.array(contactSchema),+ insights: z.object({+ followUps: z.array(z.string()),+ opportunities: z.array(z.string()),+ }),});async function analyzeRelationships(- recentLogs: string,- model: string,+ recentLogs: string,+ model: string): Promise<z.infer<typeof relationshipIntelligence>> {- const prompt = `analyze these work logs and create a comprehensive relationship intelligence report.+ const prompt = `analyze these work logs and create a comprehensive relationship intelligence report.focus on:- identifying key people and their roles- tracking interaction patterns and sentiment@@ -66,118 +66,118 @@ async function analyzeRelationships(of course adapt the example response to the actual data you have, do not use John Doe in your example response, use the names and companies of the people you see in the logs.`;- const provider = ollama(model);- console.log("prompt", prompt);- const response = await generateObject({- model: provider,- messages: [{ role: "user", content: prompt }],- schema: relationshipIntelligence,- maxRetries: 5,- });-- console.log(response.object);- return response.object;+ const provider = ollama(model);+ console.log("prompt", prompt);+ const response = await generateObject({+ model: provider,+ messages: [{ role: "user", content: prompt }],+ schema: relationshipIntelligence,+ maxRetries: 5,+ });++ console.log(response.object);+ return response.object;}async function readRecentLogs(- client: Client,- databaseId: string,- since: Date,+ client: Client,+ databaseId: string,+ since: Date): Promise<string> {- try {- const response = await client.databases.query({- database_id: databaseId,- filter: {- and: [- {- property: "Date",- date: {- on_or_after: since.toISOString().split("T")[0],- },- },- ],- },- sorts: [- {- property: "Date",- direction: "ascending",- },- ],- });-- return response.results- .map((page: any) => {- const title = page.properties.Title?.title[0]?.text?.content || "";- const description =- page.properties.Description?.rich_text[0]?.text?.content || "";- return `${title}\n${description}`;- })- .join("\n\n");- } catch (error) {- console.error("Failed to read logs:", error);- return "";- }+ try {+ const response = await client.databases.query({+ database_id: databaseId,+ filter: {+ and: [+ {+ property: "Date",+ date: {+ on_or_after: since.toISOString().split("T")[0],+ },+ },+ ],+ },+ sorts: [+ {+ property: "Date",+ direction: "ascending",+ },+ ],+ });++ return response.results+ .map((page: any) => {+ const title = page.properties.Title?.title[0]?.text?.content || "";+ const description =+ page.properties.Description?.rich_text[0]?.text?.content || "";+ return `${title}\n${description}`;+ })+ .join("\n\n");+ } catch (error) {+ console.error("Failed to read logs:", error);+ return "";+ }}export async function GET() {- try {- const settings = await getNotionSettings();-- if (- !settings?.notion?.accessToken ||- !settings?.notion?.databaseId ||- !settings?.notion?.intelligenceDbId- ) {- return NextResponse.json(- { error: "notion not configured" },- { status: 400 },- );- }-- const client = new Client({ auth: settings.notion.accessToken });-- // Get last 24 hours of logs- const today = new Date();- const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);-- const recentLogs = await readRecentLogs(- client,- settings.notion.databaseId,- yesterday,- );-- if (!recentLogs) {- return NextResponse.json(- { message: "no logs found for analysis" },- { status: 404 },- );- }-- const intelligence = await analyzeRelationships(- recentLogs,- settings.aiModel || "mistral",- );-- const notion = new NotionClient(settings.notion);-- const deepLink = await notion.createIntelligence(intelligence);-- return NextResponse.json({- message: "relationship intelligence updated",- intelligence,- deepLink,- summary: {- contacts: intelligence.contacts.length,- opportunities: intelligence.insights.opportunities.length,- needsFollowUp: intelligence.insights.followUps.length,- logsAnalyzed: recentLogs.length,- },- });- } catch (error) {- console.error("error in intelligence api:", error);- return NextResponse.json(- { error: `failed to process intelligence: ${error}` },- { status: 500 },- );- }+ try {+ const settings = await pipe.settings.getNamespaceSettings("notion");++ if (+ !settings?.notion?.accessToken ||+ !settings?.notion?.databaseId ||+ !settings?.notion?.intelligenceDbId+ ) {+ return NextResponse.json(+ { error: "notion not configured" },+ { status: 400 }+ );+ }++ const client = new Client({ auth: settings.notion.accessToken });++ // Get last 24 hours of logs+ const today = new Date();+ const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);++ const recentLogs = await readRecentLogs(+ client,+ settings.notion.databaseId,+ yesterday+ );++ if (!recentLogs) {+ return NextResponse.json(+ { message: "no logs found for analysis" },+ { status: 404 }+ );+ }++ const intelligence = await analyzeRelationships(+ recentLogs,+ settings.aiModel || "mistral"+ );++ const notion = new NotionClient(settings.notion);++ const deepLink = await notion.createIntelligence(intelligence);++ return NextResponse.json({+ message: "relationship intelligence updated",+ intelligence,+ deepLink,+ summary: {+ contacts: intelligence.contacts.length,+ opportunities: intelligence.insights.opportunities.length,+ needsFollowUp: intelligence.insights.followUps.length,+ logsAnalyzed: recentLogs.length,+ },+ });+ } catch (error) {+ console.error("error in intelligence api:", error);+ return NextResponse.json(+ { error: `failed to process intelligence: ${error}` },+ { status: 500 }+ );+ }}diff --git a/pipes/notion/src/app/api/log/route.ts b/pipes/notion/src/app/api/log/route.tsindex 71f8ee2b2..bad605369 100644--- a/pipes/notion/src/app/api/log/route.ts+++ b/pipes/notion/src/app/api/log/route.ts@@ -2,74 +2,72 @@ import { NextResponse } from "next/server";import { pipe } from "@screenpipe/js";import { generateWorkLog } from "@/lib/helpers";import { NotionClient } from "@/lib/notion/client";-import { getNotionSettings } from "@/lib/actions/namespace-settings";const minute = (min: number) => min * 60 * 1000;export async function GET() {- try {- const settings = await getNotionSettings();+ try {+ const settings = await pipe.settings.getNamespaceSettings("notion");- const model = settings?.aiModel;- const pageSize = settings?.pageSize || 50;- const customPrompt = settings?.prompt;- const interval = settings?.interval ? minute(settings.interval) : 3600000;+ const model = settings?.aiModel;+ const pageSize = settings?.pageSize || 50;+ const customPrompt = settings?.prompt;+ const interval = settings?.interval ? minute(settings.interval) : 3600000;- if (!model) {- return NextResponse.json(- { error: "model not selected" },- { status: 401 },- );- }+ if (!model) {+ return NextResponse.json(+ { error: "model not selected" },+ { status: 401 }+ );+ }- if (!settings?.notion?.accessToken || !settings?.notion?.databaseId) {- return NextResponse.json(- { error: "notion not configured" },- { status: 400 },- );- }+ if (!settings?.notion?.accessToken || !settings?.notion?.databaseId) {+ return NextResponse.json(+ { error: "notion not configured" },+ { status: 400 }+ );+ }- const now = new Date();- const oneHourAgo = new Date(now.getTime() - interval);+ const now = new Date();+ const oneHourAgo = new Date(now.getTime() - interval);- const screenData = await pipe.queryScreenpipe({- startTime: oneHourAgo.toISOString(),- endTime: now.toISOString(),- limit: pageSize,- contentType: "all",- });+ const screenData = await pipe.queryScreenpipe({+ startTime: oneHourAgo.toISOString(),+ endTime: now.toISOString(),+ limit: pageSize,+ contentType: "all",+ });- console.log(screenData);- if (!screenData || screenData.data.length === 0) {- return NextResponse.json(- { message: "no screen data found" },- { status: 404 },- );- }+ if (!screenData || screenData.data.length === 0) {+ return NextResponse.json(+ { message: "no screen data found" },+ { status: 404 }+ );+ }- const logEntry = await generateWorkLog(- screenData.data,- model,- oneHourAgo,- now,- customPrompt,- );+ const logEntry = await generateWorkLog(+ screenData.data,+ model,+ oneHourAgo,+ now,+ customPrompt+ );- console.log(logEntry);+ console.log(logEntry);- const notionClient = new NotionClient(settings.notion);- const deepLink = await notionClient.createLog(logEntry);+ const notionClient = new NotionClient(settings.notion);+ const deepLink = await notionClient.createLog(logEntry);- return NextResponse.json({- message: "work log synced successfully",- logEntry,- deepLink: deepLink,- });- } catch (error) {- console.error("error in work log api:", error);- return NextResponse.json(- { error: `failed to process work log: ${error}` },- { status: 500 },- );- }+ return NextResponse.json({+ message: "work log synced successfully",+ logEntry,+ deepLink: deepLink,+ });+ } catch (error) {+ console.error("error in work log api:", error);+ return NextResponse.json(+ { error: `failed to process work log: ${error}` },+ { status: 500 }+ );+ }}diff --git a/pipes/notion/src/app/api/notion/pages/route.ts b/pipes/notion/src/app/api/notion/pages/route.tsindex d47ba4138..ed4584e91 100644--- a/pipes/notion/src/app/api/notion/pages/route.ts+++ b/pipes/notion/src/app/api/notion/pages/route.ts@@ -1,22 +1,20 @@import { NextResponse } from "next/server";import { Client } from "@notionhq/client";-import { getNotionSettings } from "@/lib/actions/namespace-settings";export async function GET(request: Request) {try {const { searchParams } = new URL(request.url);- const query = searchParams.get("q");+ const query = searchParams.get("q")?.toLowerCase().trim();+ const accessToken = searchParams.get("accessToken");- const settings = await getNotionSettings();-- if (!settings?.notion?.accessToken) {+ if (!accessToken) {return NextResponse.json({ error: "notion not configured" },- { status: 400 },+ { status: 400 });}- const client = new Client({ auth: settings.notion.accessToken });+ const client = new Client({ auth: accessToken });const response = await client.search({filter: {@@ -51,7 +49,7 @@ export async function GET(request: Request) {console.error("error fetching pages:", error);return NextResponse.json({ error: "Failed to fetch pages" },- { status: 500 },+ { status: 500 });}}diff --git a/pipes/notion/src/app/api/settings/route.ts b/pipes/notion/src/app/api/settings/route.tsdeleted file mode 100644index 287fba333..000000000--- a/pipes/notion/src/app/api/settings/route.ts+++ /dev/null@@ -1,109 +0,0 @@-import { pipe } from "@screenpipe/js";-import { NextResponse } from "next/server";-import { promises as fs } from "fs";-import path from "path";--export const runtime = "nodejs";-export const dynamic = "force-dynamic";--export async function GET() {- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }-- // Load persisted settings if they exist- const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();- const settingsPath = path.join(- screenpipeDir,- "pipes",- "notion",- "pipe.json",- );-- try {- const settingsContent = await fs.readFile(settingsPath, "utf8");- const persistedSettings = JSON.parse(settingsContent);-- // Merge with current settings- const rawSettings = await settingsManager.getAll();- return NextResponse.json({- ...rawSettings,- customSettings: {- ...rawSettings.customSettings,- ["notion"]: {- ...(rawSettings.customSettings?.["notion"] || {}),- ...persistedSettings,- },- },- });- } catch (err) {- // If no persisted settings, return normal settings- const rawSettings = await settingsManager.getAll();- return NextResponse.json(rawSettings);- }- } catch (error) {- console.error("failed to get settings:", error);- return NextResponse.json(- { error: "failed to get settings" },- { status: 500 },- );- }-}--export async function PUT(request: Request) {- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }-- const body = await request.json();- const { key, value, isPartialUpdate, reset, namespace } = body;-- if (reset) {- if (namespace) {- if (key) {- await settingsManager.setCustomSetting(namespace, key, undefined);- } else {- await settingsManager.updateNamespaceSettings(namespace, {});- }- } else {- if (key) {- await settingsManager.resetKey(key);- } else {- await settingsManager.reset();- }- }- return NextResponse.json({ success: true });- }-- if (namespace) {- if (isPartialUpdate) {- const currentSettings =- (await settingsManager.getNamespaceSettings(namespace)) || {};- await settingsManager.updateNamespaceSettings(namespace, {- ...currentSettings,- ...value,- });- } else {- await settingsManager.setCustomSetting(namespace, key, value);- }- } else if (isPartialUpdate) {- const serializedSettings = JSON.parse(JSON.stringify(value));- await settingsManager.update(serializedSettings);- } else {- const serializedValue = JSON.parse(JSON.stringify(value));- await settingsManager.set(key, serializedValue);- }-- return NextResponse.json({ success: true });- } catch (error) {- console.error("failed to update settings:", error);- return NextResponse.json(- { error: "failed to update settings" },- { status: 500 },- );- }-}diff --git a/pipes/notion/src/app/api/setup/route.ts b/pipes/notion/src/app/api/setup/route.tsindex 54181e732..e9bbd62fd 100644--- a/pipes/notion/src/app/api/setup/route.ts+++ b/pipes/notion/src/app/api/setup/route.ts@@ -1,18 +1,17 @@import { NextResponse } from "next/server";import { automateNotionSetup } from "@/lib/notion/setup";-import { Settings } from "@/lib/types";-import { getNotionSettings } from "@/lib/actions/namespace-settings";+import { pipe } from "@screenpipe/js";export async function GET() {- try {- const settings = (await getNotionSettings()) as Settings;- const credentials = await automateNotionSetup(settings.workspace);- return NextResponse.json(credentials);- } catch (error) {- console.log(error);- return NextResponse.json(- { error: "Failed to setup Notion" },- { status: 500 },- );- }+ try {+ const settings = await pipe.settings.getNamespaceSettings("notion");+ const credentials = await automateNotionSetup(settings?.workspace);+ return NextResponse.json(credentials);+ } catch (error) {+ console.log(error);+ return NextResponse.json(+ { error: "Failed to setup Notion" },+ { status: 500 }+ );+ }}diff --git a/pipes/notion/src/components/file-suggest-textarea.tsx b/pipes/notion/src/components/file-suggest-textarea.tsxindex ec0074956..b588fa563 100644--- a/pipes/notion/src/components/file-suggest-textarea.tsx+++ b/pipes/notion/src/components/file-suggest-textarea.tsx@@ -3,6 +3,7 @@import { useState, useRef, useCallback, useEffect } from "react";import { Command } from "cmdk";import React from "react";+import { useNotionSettings } from "@/lib/hooks/use-pipe-settings";interface FileSuggestTextareaProps {value: string;@@ -40,6 +41,7 @@ export function FileSuggestTextarea({placeholder,disabled = false,}: FileSuggestTextareaProps) {+ const { settings } = useNotionSettings();const [showSuggestions, setShowSuggestions] = useState(false);const [searchTerm, setSearchTerm] = useState("");const [cursorCoords, setCursorCoords] = useState({ x: 0, y: 0 });@@ -62,7 +64,9 @@ export function FileSuggestTextarea({searchTimeout.current = setTimeout(async () => {try {const res = await fetch(- `/api/notion/pages?q=${encodeURIComponent(search)}`,+ `/api/notion/pages?q=${encodeURIComponent(search)}&accessToken=${+ settings?.notion?.accessToken+ }`);const data = await res.json();setFiles(data.pages ?? []);@@ -182,8 +186,9 @@ export function FileSuggestTextarea({ref={textareaRef}value={value}onChange={handleTextareaChange}- className={`w-full min-h-[100px] p-2 rounded-md border bg-background ${disabled ? "opacity-50 cursor-not-allowed" : ""- } ${className}`}+ className={`w-full min-h-[100px] p-2 rounded-md border bg-background ${+ disabled ? "opacity-50 cursor-not-allowed" : ""+ } ${className}`}placeholder={placeholder}rows={10}disabled={disabled}diff --git a/pipes/notion/src/components/notion-settings.tsx b/pipes/notion/src/components/notion-settings.tsxindex 2f777957c..d2dab6cac 100644--- a/pipes/notion/src/components/notion-settings.tsx+++ b/pipes/notion/src/components/notion-settings.tsx@@ -14,7 +14,7 @@ import {import { OllamaModelsList } from "./ollama-models-list";import { validateCredentials } from "@/lib/notion/notion";import { toast } from "@/hooks/use-toast";-import { useNotionSettings } from "@/lib/hooks/use-notion-settings";+import { useNotionSettings } from "@/lib/hooks/use-pipe-settings";import { ChevronDown, Loader2 } from "lucide-react";import { NotionCredentials, Settings } from "@/lib/types";import { updatePipeConfig } from "@/lib/actions/update-pipe-config";@@ -37,24 +37,15 @@ import { INTEGRATION_NAME } from "@/lib/utils";export function NotionSettings() {const { settings, updateSettings, loading } = useNotionSettings();const [isSettingUp, setIsSettingUp] = useState(false);- const [credentials, setCredentials] = useState<NotionCredentials>({- accessToken: "",- databaseId: "",- intelligenceDbId: "",- });+const [testingLog, setTestingLog] = useState(false);const [testingIntelligence, setTestingIntelligence] = useState(false);const [localSettings, setLocalSettings] = useState<Partial<Settings> | null>({});- useEffect(() => {- setCredentials({- accessToken: settings?.notion?.accessToken || "",- databaseId: settings?.notion?.databaseId || "",- intelligenceDbId: settings?.notion?.intelligenceDbId || "",- });+ useEffect(() => {setLocalSettings({...settings,});@@ -63,14 +54,22 @@ export function NotionSettings() {const handleValidate = async () => {setIsSettingUp(true);try {- const isValid = await validateCredentials(credentials);+ const isValid = await validateCredentials({+ accessToken: settings?.notion?.accessToken || "",+ databaseId: settings?.notion?.databaseId || "",+ intelligenceDbId: settings?.notion?.intelligenceDbId || "",+ });if (!isValid) {throw new Error("Invalid credentials");}await updateSettings({...settings!,- notion: credentials,+ notion: {+ accessToken: settings?.notion?.accessToken || "",+ databaseId: settings?.notion?.databaseId || "",+ intelligenceDbId: settings?.notion?.intelligenceDbId || "",+ },});toast({@@ -190,6 +189,21 @@ export function NotionSettings() {prompt: localSettings?.prompt || settings?.prompt,interval: localSettings?.interval || settings?.interval,pageSize: localSettings?.pageSize || settings?.pageSize,+ workspace: localSettings?.workspace || settings?.workspace,+ notion: {+ accessToken:+ localSettings?.notion?.accessToken ||+ settings?.notion?.accessToken ||+ "",+ databaseId:+ localSettings?.notion?.databaseId ||+ settings?.notion?.databaseId ||+ "",+ intelligenceDbId:+ localSettings?.notion?.intelligenceDbId ||+ settings?.notion?.intelligenceDbId ||+ "",+ },});if (localSettings?.interval !== settings?.interval) {@@ -248,8 +262,13 @@ export function NotionSettings() {make sure to keep the prompt within llm context window size.<br />protip: use the @mention feature to link to other pages in your- notion as context.(make sure the page is shared with- integration)+ notion as context.+ <br />+ <br />+ <strong>+ (make sure these pages are shared with the integration)+ </strong>+ <br /><br />if you have connected with notion automatically, then yourintegration name will{" "}@@ -288,7 +307,7 @@ export function NotionSettings() {this is required when you are connecting automatically. you canfind your workspace name{" "}<a- href="https://www.notion.so/settings/workspace-settings"+ href="https://www.notion.so"target="_blank"rel="noopener noreferrer"className="text-blue-400 underline"@@ -322,12 +341,15 @@ export function NotionSettings() {</Label><Inputplaceholder="Access Token"- value={credentials.accessToken}+ value={localSettings?.notion?.accessToken || ""}onChange={(e) =>- setCredentials((prev) => ({- ...prev,- accessToken: e.target.value,- }))+ setLocalSettings({+ ...localSettings!,+ notion: {+ ...localSettings?.notion!,+ accessToken: e.target.value,+ },+ })}/><p className="text-xs text-muted-foreground">@@ -346,9 +368,12 @@ export function NotionSettings() {<div className="space-y-2"><NotionIdInputlabel="Database ID"- value={credentials.databaseId}+ value={localSettings?.notion?.databaseId || ""}onChange={(value) =>- setCredentials((prev) => ({ ...prev, databaseId: value }))+ setLocalSettings({+ ...localSettings!,+ notion: { ...localSettings?.notion!, databaseId: value },+ })}dialogTitle="Extract Database ID from URL"/>@@ -356,12 +381,15 @@ export function NotionSettings() {<div className="space-y-2"><NotionIdInputlabel="Intelligence ID"- value={credentials.intelligenceDbId}+ value={localSettings?.notion?.intelligenceDbId || ""}onChange={(value) =>- setCredentials((prev) => ({- ...prev,- intelligenceDbId: value,- }))+ setLocalSettings({+ ...localSettings!,+ notion: {+ ...localSettings?.notion!,+ intelligenceDbId: value,+ },+ })}dialogTitle="Extract Intelligence Database ID from URL"/>@@ -373,9 +401,9 @@ export function NotionSettings() {isAutoDisabled={isSettingUp || !settings?.workspace}isManualDisabled={isSettingUp ||- !credentials.accessToken ||- !credentials.databaseId ||- !credentials.intelligenceDbId+ !localSettings?.notion?.accessToken ||+ !localSettings?.notion?.databaseId ||+ !localSettings?.notion?.intelligenceDbId}handleAuto={handleSetup}handleManual={handleValidate}diff --git a/pipes/notion/src/components/notion-url-to-input.tsx b/pipes/notion/src/components/notion-url-to-input.tsxindex a429c0060..d44ff20dc 100644--- a/pipes/notion/src/components/notion-url-to-input.tsx+++ b/pipes/notion/src/components/notion-url-to-input.tsx@@ -1,8 +1,8 @@import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -11,87 +11,87 @@ import { toast } from "@/hooks/use-toast";import { useState } from "react";interface NotionIdInputProps {- label: string;- value: string;- onChange: (value: string) => void;- dialogTitle: string;+ label: string;+ value: string;+ onChange: (value: string) => void;+ dialogTitle: string;}export function NotionIdInput({- label,- value,- onChange,- dialogTitle,+ label,+ value,+ onChange,+ dialogTitle,}: NotionIdInputProps) {- const [isDialogOpen, setIsDialogOpen] = useState(false);+ const [isDialogOpen, setIsDialogOpen] = useState(false);- const extractIdFromUrl = (url: string) => {- try {- const match = url.match(/notion\.so\/(?:[^-]*-)?([a-zA-Z0-9]{32})/);- return match ? match[1] : null;- } catch (error) {- return null;- }- };+ const extractIdFromUrl = (url: string) => {+ try {+ const match = url.match(/notion\.so\/(?:[^/]+\/)?([a-zA-Z0-9]{32})/);+ return match ? match[1] : null;+ } catch (error) {+ return null;+ }+ };- const handleUrlSubmit = (url: string) => {- const id = extractIdFromUrl(url);- if (id) {- onChange(id);- setIsDialogOpen(false);- } else {- toast({- title: "Error",- description: "Invalid Notion URL",- variant: "destructive",- });- }- };+ const handleUrlSubmit = (url: string) => {+ const id = extractIdFromUrl(url);+ if (id) {+ onChange(id);+ setIsDialogOpen(false);+ } else {+ toast({+ title: "Error",+ description: "Invalid Notion URL",+ variant: "destructive",+ });+ }+ };- return (- <div className="space-y-2">- <Label>{label}</Label>- <div className="flex gap-2">- <Input- placeholder={label}- value={value}- onChange={(e) => onChange(e.target.value)}- />- <Button variant="outline" onClick={() => setIsDialogOpen(true)}>- Get ID from URL- </Button>- </div>+ return (+ <div className="space-y-2">+ <Label>{label}</Label>+ <div className="flex gap-2">+ <Input+ placeholder={label}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ <Button variant="outline" onClick={() => setIsDialogOpen(true)}>+ Get ID from URL+ </Button>+ </div>- <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>- <DialogContent>- <DialogHeader>- <DialogTitle>{dialogTitle}</DialogTitle>- </DialogHeader>- <div className="space-y-4">- <div className="space-y-2">- <Label>Notion Database URL</Label>- <Input- placeholder="https://www.notion.so/..."- onKeyDown={(e) => {- if (e.key === "Enter") {- handleUrlSubmit(e.currentTarget.value);- }- }}- />- </div>- <Button- className="w-full"- onClick={(e) => {- const input =- e.currentTarget.parentElement?.querySelector("input");- if (input) handleUrlSubmit(input.value);- }}- >- Extract ID- </Button>- </div>- </DialogContent>- </Dialog>- </div>- );+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{dialogTitle}</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label>Notion Database URL</Label>+ <Input+ placeholder="https://www.notion.so/..."+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ handleUrlSubmit(e.currentTarget.value);+ }+ }}+ />+ </div>+ <Button+ className="w-full"+ onClick={(e) => {+ const input =+ e.currentTarget.parentElement?.querySelector("input");+ if (input) handleUrlSubmit(input.value);+ }}+ >+ Extract ID+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );}diff --git a/pipes/notion/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/notion/src/lib/actions/get-screenpipe-app-settings.tsnew file mode 100644index 000000000..608513b37--- /dev/null+++ b/pipes/notion/src/lib/actions/get-screenpipe-app-settings.ts@@ -0,0 +1,14 @@+"use server";++import { pipe } from "@screenpipe/js";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";++export async function getScreenpipeAppSettings() {+ return await pipe.settings.getAll();+}++export async function updateScreenpipeAppSettings(+ newSettings: Partial<ScreenpipeAppSettings>+) {+ return await pipe.settings.update(newSettings);+}diff --git a/pipes/notion/src/lib/actions/namespace-settings.ts b/pipes/notion/src/lib/actions/namespace-settings.tsdeleted file mode 100644index 7bec856dc..000000000--- a/pipes/notion/src/lib/actions/namespace-settings.ts+++ /dev/null@@ -1,14 +0,0 @@-"use server";--import { pipe } from "@screenpipe/js";-import { Settings } from "../types";--export async function getNotionSettings() {- return (await pipe.settings.getAll())["customSettings"]![- "notion"- ] as Partial<Settings>;-}--export async function updateNotionSettings(newSettings: Partial<Settings>) {- return await pipe.settings.updateNamespaceSettings("notion", newSettings);-}diff --git a/pipes/notion/src/lib/actions/update-pipe-config.ts b/pipes/notion/src/lib/actions/update-pipe-config.tsindex aab43f41e..7f9657b58 100644--- a/pipes/notion/src/lib/actions/update-pipe-config.ts+++ b/pipes/notion/src/lib/actions/update-pipe-config.ts@@ -4,12 +4,15 @@ import path from "path";export async function updatePipeConfig(intervalMinutes: number) {try {- const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();+ const screenpipeDir =+ process.env.SCREENPIPE_DIR ||+ (process.env.HOME && path.join(process.env.HOME, ".screenpipe")) ||+ process.cwd();const pipeConfigPath = path.join(screenpipeDir,"pipes","notion",- "pipe.json",+ "pipe.json");console.log(`updating cron schedule at: ${pipeConfigPath}`);@@ -22,7 +25,7 @@ export async function updatePipeConfig(intervalMinutes: number) {config = JSON.parse(content);} catch (err) {console.log(- `no existing config found, creating new one at ${pipeConfigPath}`,+ `no existing config found, creating new one at ${pipeConfigPath}`);config = { crons: [] };}@@ -43,7 +46,7 @@ export async function updatePipeConfig(intervalMinutes: number) {await fs.writeFile(pipeConfigPath, JSON.stringify(config, null, 2));console.log(- `updated cron schedule to run every ${intervalMinutes} minutes`,+ `updated cron schedule to run every ${intervalMinutes} minutes`);} catch (err) {console.error("failed to update cron schedule:", err);diff --git a/pipes/notion/src/lib/helpers.ts b/pipes/notion/src/lib/helpers.tsindex 64806816e..ba79159fc 100644--- a/pipes/notion/src/lib/helpers.ts+++ b/pipes/notion/src/lib/helpers.ts@@ -3,9 +3,9 @@ import { WorkLog } from "./types";import { generateObject } from "ai";import { ollama } from "ollama-ai-provider";import { z } from "zod";-import { getNotionSettings } from "./actions/namespace-settings";import { Client } from "@notionhq/client";import { NotionToMarkdown } from "notion-to-md";+import { getScreenpipeAppSettings } from "./actions/get-screenpipe-app-settings";export const workLog = z.object({title: z.string(),@@ -18,10 +18,12 @@ async function extractLinkedContent(prompt: string): Promise<string> {// Match @[[file]] or @[[folder/file]] patternsconst linkRegex = /@\[\[(.*?)\]\]/g;const matches = [...prompt.matchAll(linkRegex)];- const settings = await getNotionSettings();+ const settings = await getScreenpipeAppSettings();let enrichedPrompt = prompt;- const notion = new Client({ auth: settings?.notion?.accessToken });+ const notion = new Client({+ auth: settings?.customSettings?.notion?.accessToken,+ });const n2m = new NotionToMarkdown({ notionClient: notion });for (const match of matches) {@@ -33,7 +35,7 @@ async function extractLinkedContent(prompt: string): Promise<string> {enrichedPrompt = enrichedPrompt.replace(match[0],- `\n--- Content of ${pageId} ---\n${mdString.parent}\n---\n`,+ `\n--- Content of ${pageId} ---\n${mdString.parent}\n---\n`);} catch (error) {console.error(error, `of ${pageId}`);@@ -51,7 +53,7 @@ export async function generateWorkLog(model: string,startTime: Date,endTime: Date,- customPrompt?: string,+ customPrompt?: string): Promise<WorkLog> {let enrichedPrompt = customPrompt || "";diff --git a/pipes/notion/src/lib/hooks/use-notion-settings.tsx b/pipes/notion/src/lib/hooks/use-pipe-settings.tsxsimilarity index 52%rename from pipes/notion/src/lib/hooks/use-notion-settings.tsxrename to pipes/notion/src/lib/hooks/use-pipe-settings.tsxindex dd0876719..b1c0cfe38 100644--- a/pipes/notion/src/lib/hooks/use-notion-settings.tsx+++ b/pipes/notion/src/lib/hooks/use-pipe-settings.tsx@@ -1,9 +1,9 @@import { useState, useEffect } from "react";import { Settings } from "@/lib/types";import {- getNotionSettings,- updateNotionSettings,-} from "../actions/namespace-settings";+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "../actions/get-screenpipe-app-settings";const DEFAULT_SETTINGS: Partial<Settings> = {prompt: `yo, you're my personal data detective! 🕵@@ -29,6 +29,8 @@ style rules:remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!`,};+const STORAGE_KEY = "notion-settings";+export function useNotionSettings() {const [settings, setSettings] = useState<Partial<Settings> | null>(null);const [loading, setLoading] = useState(true);@@ -39,13 +41,20 @@ export function useNotionSettings() {const loadSettings = async () => {try {- const data = await getNotionSettings();- console.log(data);- setSettings(- data ? { ...DEFAULT_SETTINGS, ...data } : { ...DEFAULT_SETTINGS },- );+ // Load notion settings from localStorage+ const storedSettings = localStorage.getItem(STORAGE_KEY);+ const notionSettings = storedSettings ? JSON.parse(storedSettings) : {};++ // Load screenpipe app settings+ const screenpipeSettings = await getScreenpipeAppSettings();+ // Merge everything together+ setSettings({+ ...DEFAULT_SETTINGS,+ ...notionSettings,+ screenpipeAppSettings: screenpipeSettings,+ });} catch (error) {- console.error("Failed to load settings:", error);+ console.error("failed to load settings:", error);} finally {setLoading(false);}@@ -53,12 +62,37 @@ export function useNotionSettings() {const updateSettings = async (newSettings: Partial<Settings>) => {try {- const mergedSettings = { ...DEFAULT_SETTINGS, ...newSettings };- await updateNotionSettings(mergedSettings);- setSettings(mergedSettings);+ // Split settings+ const { screenpipeAppSettings, ...notionSettings } = newSettings;++ // Update notion settings in localStorage+ const mergedNotionSettings = {+ ...DEFAULT_SETTINGS,+ ...notionSettings,+ };++ // Update screenpipe settings if provided+ if (screenpipeAppSettings) {+ await updateScreenpipeAppSettings({+ ...screenpipeAppSettings,+ customSettings: {+ ...screenpipeAppSettings.customSettings,+ notion: mergedNotionSettings,+ },+ });+ }++ localStorage.setItem(STORAGE_KEY, JSON.stringify(mergedNotionSettings));++ // Update state with everything+ setSettings({+ ...mergedNotionSettings,+ screenpipeAppSettings:+ screenpipeAppSettings || settings?.screenpipeAppSettings,+ });return true;} catch (error) {- console.error("Failed to update settings:", error);+ console.error("failed to update settings:", error);return false;}};diff --git a/pipes/notion/src/lib/hooks/use-settings.tsx b/pipes/notion/src/lib/hooks/use-settings.tsxdeleted file mode 100644index d9d8ec400..000000000--- a/pipes/notion/src/lib/hooks/use-settings.tsx+++ /dev/null@@ -1,210 +0,0 @@-"use client";--import { useState, useEffect } from "react";-import { getDefaultSettings, type Settings } from "@screenpipe/browser";--export function useSettings() {- const defaultSettings = getDefaultSettings();-- defaultSettings.customSettings = {- ...(defaultSettings.customSettings || {}),- notion: {- prompt: `yo, you're my personal data detective! 🕵--rules for the investigation:-- extract names of people i interact with and what we discussed, when i encounter a person, make sure to extract their name like this [[John Doe]] so it's linked in my notes-- identify recurring topics/themes in my convos, use tags or [[Link them]] to my notes-- spot any promises or commitments made (by me or others)-- catch interesting ideas or insights dropped in casual chat-- note emotional vibes and energy levels in conversations-- highlight potential opportunities or connections-- track project progress and blockers mentioned--style rules:-- keep it real and conversational-- use bullet points for clarity-- include relevant timestamps-- group related info together-- max 4 lines per insight-- no corporate speak, keep it human-- for tags use hyphen between words, no spaces, eg: #my-tag not #my tag nor #myTag nor #my_tag--remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!`,- },- };-- const [settings, setSettings] = useState<Settings | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<Error | null>(null);-- useEffect(() => {- const loadSettings = async () => {- if (!loading) setLoading(true);- try {- const response = await fetch("/api/settings");- const data = await response.json();- setSettings({ ...defaultSettings, ...data });- } catch (err) {- console.error("failed to load settings:", err);- setSettings(defaultSettings);- setError(err as Error);- } finally {- setLoading(false);- }- };-- // Initial load- loadSettings();-- // Refresh on window focus- const onFocus = () => loadSettings();- window.addEventListener("focus", onFocus);-- // Optional: periodic refresh every 30s- const interval = setInterval(loadSettings, 2000);-- return () => {- window.removeEventListener("focus", onFocus);- clearInterval(interval);- };- }, []);-- const updateSetting = async <T extends keyof Settings>(- key: T,- value: Settings[T],- namespace?: string,- ) => {- if (!settings) return;- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ key, value, namespace }),- });-- if (namespace) {- setSettings((prev) => {- if (!prev) return defaultSettings;- return {- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- [key]: value,- },- },- };- });- } else {- setSettings((prev) => {- if (!prev) return defaultSettings;- return { ...prev, [key]: value };- });- }- } catch (err) {- setError(err as Error);- }- };-- const updateSettings = async (- newSettings: Partial<Settings>,- namespace?: string,- ) => {- if (!settings) return;- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({- value: newSettings,- isPartialUpdate: true,- namespace,- }),- });-- if (namespace) {- setSettings((prev) => {- if (!prev) return defaultSettings;- return {- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- ...newSettings,- },- },- };- });- } else {- setSettings((prev) => {- if (!prev) return defaultSettings;- return { ...prev, ...newSettings };- });- }- } catch (err) {- setError(err as Error);- }- };-- const resetSettings = async (- settingKey?: keyof Settings,- namespace?: string,- ) => {- if (!settings) return;- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ reset: true, key: settingKey, namespace }),- });-- if (namespace) {- setSettings((prev) => {- if (!prev) return defaultSettings;- if (settingKey) {- return {- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {- ...(prev.customSettings?.[namespace] || {}),- [settingKey]: undefined,- },- },- };- } else {- return {- ...prev,- customSettings: {- ...prev.customSettings,- [namespace]: {},- },- };- }- });- } else {- if (settingKey) {- setSettings((prev) => {- if (!prev) return defaultSettings;- return {- ...prev,- [settingKey]: defaultSettings[settingKey],- };- });- } else {- setSettings(defaultSettings);- }- }- } catch (err) {- setError(err as Error);- }- };-- return {- settings: settings || defaultSettings,- loading,- error,- updateSetting,- updateSettings,- resetSettings,- };-}diff --git a/pipes/notion/src/lib/types.ts b/pipes/notion/src/lib/types.tsindex 510e43a81..2b8c6502a 100644--- a/pipes/notion/src/lib/types.ts+++ b/pipes/notion/src/lib/types.ts@@ -1,3 +1,5 @@+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+export interface NotionCredentials {accessToken: string;databaseId: string;@@ -43,4 +45,5 @@ export interface Settings {backend: "notion";notion: NotionCredentials;prompt: string;+ screenpipeAppSettings: ScreenpipeAppSettings;}diff --git a/pipes/obsidian/package.json b/pipes/obsidian/package.jsonindex efd857b0e..a66435262 100644--- a/pipes/obsidian/package.json+++ b/pipes/obsidian/package.json@@ -1,6 +1,6 @@{"name": "obsidian",- "version": "0.1.13",+ "version": "0.1.15","private": true,"scripts": {"dev": "next dev --turbopack",diff --git a/pipes/obsidian/src/app/api/settings/route.ts b/pipes/obsidian/src/app/api/settings/route.tsdeleted file mode 100644index 4646b26ad..000000000--- a/pipes/obsidian/src/app/api/settings/route.ts+++ /dev/null@@ -1,117 +0,0 @@-import { pipe } from "@screenpipe/js";-import { NextResponse } from "next/server";-import { promises as fs } from "fs";-import path from "path";--export const runtime = "nodejs";-export const dynamic = "force-dynamic";--export async function GET() {- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }-- // get home dir- const homeDir = process.env.HOME;-- // Load persisted settings if they exist- const screenpipeDir =- process.env.SCREENPIPE_DIR ||- (homeDir && path.join(homeDir, ".screenpipe")) ||- process.cwd();- const settingsPath = path.join(- screenpipeDir,- "pipes",- "obsidian",- "pipe.json"- );-- try {- const settingsContent = await fs.readFile(settingsPath, "utf8");- const persistedSettings = JSON.parse(settingsContent);-- // Merge with current settings- const rawSettings = await settingsManager.getAll();- return NextResponse.json({- ...rawSettings,- customSettings: {- ...rawSettings.customSettings,- ["obsidian"]: {- ...(rawSettings.customSettings?.["obsidian"] || {}),- ...persistedSettings,- },- },- });- } catch (err) {- console.log("route err", err);- // If no persisted settings, return normal settings- const rawSettings = await settingsManager.getAll();- console.log("route rawSettings", rawSettings);- return NextResponse.json(rawSettings);- }- } catch (error) {- console.error("failed to get settings:", error);- return NextResponse.json(- { error: "failed to get settings" },- { status: 500 }- );- }-}--export async function PUT(request: Request) {- try {- const settingsManager = pipe.settings;- if (!settingsManager) {- throw new Error("settingsManager not found");- }-- const body = await request.json();- const { key, value, isPartialUpdate, reset, namespace } = body;-- if (reset) {- if (namespace) {- if (key) {- await settingsManager.setCustomSetting(namespace, key, undefined);- } else {- await settingsManager.updateNamespaceSettings(namespace, {});- }- } else {- if (key) {- await settingsManager.resetKey(key);- } else {- await settingsManager.reset();- }- }- return NextResponse.json({ success: true });- }-- if (namespace) {- if (isPartialUpdate) {- const currentSettings =- (await settingsManager.getNamespaceSettings(namespace)) || {};- await settingsManager.updateNamespaceSettings(namespace, {- ...currentSettings,- ...value,- });- } else {- await settingsManager.setCustomSetting(namespace, key, value);- }- } else if (isPartialUpdate) {- const serializedSettings = JSON.parse(JSON.stringify(value));- await settingsManager.update(serializedSettings);- } else {- const serializedValue = JSON.parse(JSON.stringify(value));- await settingsManager.set(key, serializedValue);- }-- return NextResponse.json({ success: true });- } catch (error) {- console.error("failed to update settings:", error);- return NextResponse.json(- { error: "failed to update settings" },- { status: 500 }- );- }-}diff --git a/pipes/obsidian/src/components/obsidian-settings.tsx b/pipes/obsidian/src/components/obsidian-settings.tsxindex fdd3c40ae..888fcf120 100644--- a/pipes/obsidian/src/components/obsidian-settings.tsx+++ b/pipes/obsidian/src/components/obsidian-settings.tsx@@ -1,7 +1,6 @@"use client";import { useState, useEffect, useCallback } from "react";-import { useSettings } from "@/lib/hooks/use-settings";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -26,18 +25,11 @@ 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 settings-interface ObsidianSettings {- path: string;- interval: number;- pageSize: number;- aiModel: string;- prompt: string | null;-}+import { Settings } from "@/lib/types";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";export function ObsidianSettings() {- const { settings, updateSettings, loading } = useSettings();+ const { settings, updateSettings, loading } = usePipeSettings();const [lastLog, setLastLog] = useState<any>(null);const { toast } = useToast();const [intelligence, setIntelligence] = useState<any>(null);@@ -62,10 +54,10 @@ export function ObsidianSettings() {const [suggestedPaths, setSuggestedPaths] = useState<string[]>([]);useEffect(() => {- if (settings?.customSettings?.obsidian?.prompt) {- setCustomPrompt(settings.customSettings.obsidian.prompt);+ if (settings) {+ setCustomPrompt(settings.prompt || "");}- }, [settings?.customSettings?.obsidian?.prompt]);+ }, [settings]);useEffect(() => {const fetchPaths = async () => {@@ -107,20 +99,17 @@ export function ObsidianSettings() {});try {- const obsidianSettings: ObsidianSettings = {- path: formData.get("path") as string,- interval: parseInt(formData.get("interval") as string) * 60000,+ const interval = parseInt(formData.get("interval") as string) * 60000;+ const obsidianSettings = {+ vaultPath: formData.get("path") as string,+ interval,pageSize: parseInt(formData.get("pageSize") as string),aiModel: formData.get("aiModel") as string,- prompt: customPrompt,+ prompt: customPrompt || "",};- await updateSettings({- customSettings: {- obsidian: obsidianSettings,- },- });- await updatePipeConfig(obsidianSettings.interval / 60000);+ await updateSettings(obsidianSettings);+ await updatePipeConfig(interval / 60000);loadingToast.update({id: loadingToast.id,@@ -142,20 +131,17 @@ export function ObsidianSettings() {const formData = new FormData(document.querySelector("form") as HTMLFormElement);- const obsidianSettings: ObsidianSettings = {- path: formData.get("path") as string,- interval: parseInt(formData.get("interval") as string) * 60000,+ const interval = parseInt(formData.get("interval") as string) * 60000;+ const obsidianSettings = {+ vaultPath: formData.get("path") as string,+ interval,pageSize: parseInt(formData.get("pageSize") as string),aiModel: formData.get("aiModel") as string,- prompt: customPrompt,+ prompt: customPrompt || "",};- await updateSettings({- customSettings: {- obsidian: obsidianSettings,- },- });- await updatePipeConfig(obsidianSettings.interval / 60000);+ await updateSettings(obsidianSettings);+ await updatePipeConfig(interval / 60000);// Then test log generationconst res = await fetch("/api/log");@@ -198,12 +184,7 @@ export function ObsidianSettings() {}await updateSettings({- customSettings: {- obsidian: {- ...settings.customSettings?.obsidian,- path,- },- },+ vaultPath: path,});toast({@@ -255,11 +236,11 @@ export function ObsidianSettings() {};const openObsidianVault = async () => {- if (!settings.customSettings?.obsidian?.path) return;+ if (!settings?.vaultPath) return;try {// Start from the current path and walk up until we find .obsidian folder- let currentPath = settings.customSettings.obsidian.path;+ let currentPath = settings.vaultPath;let vaultPath = null;while (currentPath !== "/") {@@ -290,7 +271,7 @@ export function ObsidianSettings() {const vaultName = path.basename(vaultPath);// Get relative path from vault root to AI folder- const relativePath = settings.customSettings.obsidian.path+ const relativePath = settings.vaultPath.replace(vaultPath, "").replace(/^\//, "");const searchQuery = `path:"${relativePath}"`;@@ -310,11 +291,6 @@ export function ObsidianSettings() {}};- // Helper function to check if vault path is set- const isVaultPathSet = () => {- return Boolean(settings.customSettings?.obsidian?.path?.trim());- };-const validatePath = useCallback(debounce(async (inputPath: string) => {if (!inputPath?.trim()) {@@ -402,10 +378,10 @@ export function ObsidianSettings() {// Add this new useEffect for initial path validationuseEffect(() => {- if (settings?.customSettings?.obsidian?.path) {- validatePath(settings.customSettings.obsidian.path);+ if (settings?.vaultPath) {+ validatePath(settings.vaultPath);}- }, [settings?.customSettings?.obsidian?.path, validatePath]);+ }, [settings?.vaultPath, validatePath]);if (loading) {return (@@ -470,7 +446,7 @@ export function ObsidianSettings() {<Inputid="path"name="path"- defaultValue={settings.customSettings?.obsidian?.path}+ defaultValue={settings?.vaultPath}placeholder="/path/to/vault"className={`${pathValidation.isValid@@ -548,9 +524,7 @@ export function ObsidianSettings() {step="1"max="60"defaultValue={- settings.customSettings?.obsidian?.interval- ? settings.customSettings?.obsidian?.interval / 60000- : 5+ settings?.interval ? settings?.interval / 60000 : 5}/></div>@@ -562,9 +536,7 @@ export function ObsidianSettings() {id="pageSize"name="pageSize"type="number"- defaultValue={- settings.customSettings?.obsidian?.pageSize || 100- }+ defaultValue={settings?.pageSize || 100}/></div>@@ -575,18 +547,11 @@ export function ObsidianSettings() {<OllamaModelsListdisabled={!pathValidation.isValid}defaultValue={- settings.customSettings?.obsidian?.aiModel ||- "llama3.2:3b-instruct-q4_K_M"+ settings?.aiModel || "llama3.2:3b-instruct-q4_K_M"}onChange={(value) => {updateSettings({- customSettings: {- ...settings.customSettings,- obsidian: {- ...settings.customSettings?.obsidian,- aiModel: value,- },- },+ aiModel: value,});}}/>diff --git a/pipes/obsidian/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/obsidian/src/lib/actions/get-screenpipe-app-settings.tsnew file mode 100644index 000000000..608513b37--- /dev/null+++ b/pipes/obsidian/src/lib/actions/get-screenpipe-app-settings.ts@@ -0,0 +1,14 @@+"use server";++import { pipe } from "@screenpipe/js";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";++export async function getScreenpipeAppSettings() {+ return await pipe.settings.getAll();+}++export async function updateScreenpipeAppSettings(+ newSettings: Partial<ScreenpipeAppSettings>+) {+ return await pipe.settings.update(newSettings);+}diff --git a/pipes/obsidian/src/lib/actions/update-pipe-config.ts b/pipes/obsidian/src/lib/actions/update-pipe-config.tsindex 8ab578cc1..3a768bf4f 100644--- a/pipes/obsidian/src/lib/actions/update-pipe-config.ts+++ b/pipes/obsidian/src/lib/actions/update-pipe-config.ts@@ -4,7 +4,10 @@ import path from "path";export async function updatePipeConfig(intervalMinutes: number) {try {- const screenpipeDir = process.env.SCREENPIPE_DIR || process.cwd();+ const screenpipeDir =+ process.env.SCREENPIPE_DIR ||+ (process.env.HOME && path.join(process.env.HOME, ".screenpipe")) ||+ process.cwd();const pipeConfigPath = path.join(screenpipeDir,"pipes",diff --git a/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsxnew file mode 100644index 000000000..08e302f04--- /dev/null+++ b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx@@ -0,0 +1,108 @@+import { useState, useEffect } from "react";+import { Settings } from "@/lib/types";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "../actions/get-screenpipe-app-settings";++const DEFAULT_SETTINGS: Partial<Settings> = {+ prompt: `yo, you're my personal data detective! 🕵️♂️++rules for the investigation:+- extract names of people i interact with and what we discussed, when i encounter a person, make sure to extract their name like this [[John Doe]] so it's linked in my notes+- identify recurring topics/themes in my convos, use tags or [[Link them]] to my notes+- spot any promises or commitments made (by me or others)+- catch interesting ideas or insights dropped in casual chat+- note emotional vibes and energy levels in conversations+- highlight potential opportunities or connections+- track project progress and blockers mentioned++style rules:+- always put people's names in double square brackets, eg: [[John Doe]] to link to their notes, same for companies, eg: [[Google]], or projects, eg: [[Project X]]+- keep it real and conversational+- use bullet points for clarity+- include relevant timestamps+- group related info together+- max 4 lines per insight+- no corporate speak, keep it human+- for tags use hyphen between words, no spaces, eg: #my-tag not #my tag nor #myTag nor #my_tag++remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!+you'll get chunks of 5 mins roughly of data screen & audio recordings and have to write logs.+this data will be used later for analysis, it must contains valuable insights on what i am doing.+if you do your job well, i'll give you a 🍺 and $1m`,+};++const STORAGE_KEY = "obsidian-settings";++export function usePipeSettings() {+ const [settings, setSettings] = useState<Partial<Settings> | null>(null);+ const [loading, setLoading] = useState(true);++ console.log("settings", settings);++ useEffect(() => {+ loadSettings();+ }, []);++ const loadSettings = async () => {+ try {+ // Load notion settings from localStorage+ const storedSettings = localStorage.getItem(STORAGE_KEY);+ const notionSettings = storedSettings ? JSON.parse(storedSettings) : {};++ // Load screenpipe app settings+ const screenpipeSettings = await getScreenpipeAppSettings();++ // Merge everything together+ setSettings({+ ...DEFAULT_SETTINGS,+ ...notionSettings,+ screenpipeAppSettings: screenpipeSettings,+ });+ } catch (error) {+ console.error("failed to load settings:", error);+ } finally {+ setLoading(false);+ }+ };++ const updateSettings = async (newSettings: Partial<Settings>) => {+ try {+ // Split settings+ const { screenpipeAppSettings, ...obsidianSettings } = newSettings;++ const mergedObsidianSettings = {+ ...DEFAULT_SETTINGS,+ ...obsidianSettings,+ };++ // Update screenpipe settings if provided+ if (screenpipeAppSettings) {+ await updateScreenpipeAppSettings({+ ...screenpipeAppSettings,+ customSettings: {+ ...screenpipeAppSettings.customSettings,+ obsidian: mergedObsidianSettings,+ },+ });+ }++ // Update notion settings in localStorage+ localStorage.setItem(STORAGE_KEY, JSON.stringify(mergedObsidianSettings));++ // Update state with everything+ setSettings({+ ...mergedObsidianSettings,+ screenpipeAppSettings:+ screenpipeAppSettings || settings?.screenpipeAppSettings,+ });+ return true;+ } catch (error) {+ console.error("failed to update settings:", error);+ return false;+ }+ };++ return { settings, updateSettings, loading };+}diff --git a/pipes/obsidian/src/lib/hooks/use-settings.tsx b/pipes/obsidian/src/lib/hooks/use-settings.tsxdeleted file mode 100644index efeb16c6b..000000000--- a/pipes/obsidian/src/lib/hooks/use-settings.tsx+++ /dev/null@@ -1,120 +0,0 @@-"use client";--import { useState, useEffect } from "react";-import { getDefaultSettings, type Settings } from "@screenpipe/browser";--const SETTINGS_KEY = "screenpipe_settings";--export function useSettings() {- const defaultSettings = getDefaultSettings();-- defaultSettings.customSettings = {- ...(defaultSettings.customSettings || {}),- obsidian: {- prompt: `yo, you're my personal data detective! 🕵️♂️--rules for the investigation:-- extract names of people i interact with and what we discussed, when i encounter a person, make sure to extract their name like this [[John Doe]] so it's linked in my notes-- identify recurring topics/themes in my convos, use tags or [[Link them]] to my notes-- spot any promises or commitments made (by me or others)-- catch interesting ideas or insights dropped in casual chat-- note emotional vibes and energy levels in conversations-- highlight potential opportunities or connections-- track project progress and blockers mentioned--style rules:-- always put people's names in double square brackets, eg: [[John Doe]] to link to their notes, same for companies, eg: [[Google]], or projects, eg: [[Project X]]-- keep it real and conversational-- use bullet points for clarity-- include relevant timestamps-- group related info together-- max 4 lines per insight-- no corporate speak, keep it human-- for tags use hyphen between words, no spaces, eg: #my-tag not #my tag nor #myTag nor #my_tag--remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!-you'll get chunks of 5 mins roughly of data screen & audio recordings and have to write logs.-this data will be used later for analysis, it must contains valuable insights on what i am doing.-if you do your job well, i'll give you a 🍺 and $1m`,- },- };-- const [settings, setSettings] = useState<Settings | null>(() => {- if (typeof window !== "undefined") {- const saved = localStorage.getItem(SETTINGS_KEY);- return saved ? JSON.parse(saved) : null;- }- return null;- });- const [loading, setLoading] = useState(true);- const [error, setError] = useState<Error | null>(null);-- useEffect(() => {- setLoading(false);- }, []);-- const updateSetting = async <T extends keyof Settings>(- key: T,- value: Settings[T],- namespace?: string- ) => {- if (!settings) return;- try {- const updatedSettings = {- ...settings,- customSettings: {- ...settings.customSettings,- [namespace || "default"]: {- ...(settings.customSettings?.[namespace || "default"] || {}),- [key]: value,- },- },- };- setSettings(updatedSettings);- localStorage.setItem(SETTINGS_KEY, JSON.stringify(updatedSettings));- } catch (err) {- setError(err as Error);- }- };-- const updateSettings = async (newSettings: any) => {- const updatedSettings = {- ...settings,- ...newSettings,- };- setSettings(updatedSettings);- localStorage.setItem(SETTINGS_KEY, JSON.stringify(updatedSettings));- };-- const resetSettings = async (- settingKey?: keyof Settings,- namespace?: string- ) => {- if (!settings) return;- try {- const updatedSettings = {- ...settings,- customSettings: {- ...settings.customSettings,- [namespace || ("default" as string)]: {- ...(settings.customSettings?.[namespace || "default"] || {}),- [settingKey as string]: undefined,- },- },- };- setSettings(updatedSettings);- localStorage.setItem(SETTINGS_KEY, JSON.stringify(updatedSettings));- } catch (err) {- setError(err as Error);- }- };-- return {- settings: settings || defaultSettings,- loading,- error,- updateSetting,- updateSettings,- resetSettings,- };-}diff --git a/pipes/obsidian/src/lib/types.ts b/pipes/obsidian/src/lib/types.tsnew file mode 100644index 000000000..e072860b1--- /dev/null+++ b/pipes/obsidian/src/lib/types.ts@@ -0,0 +1,35 @@+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";++export interface WorkLog {+ title: string;+ description: string;+ tags: string[];+ startTime: string;+ endTime: string;+}++export interface Contact {+ name: string;+ company?: string;+ lastInteraction: string;+ sentiment: number;+ topics: string[];+ nextSteps: string[];+}++export interface Intelligence {+ contacts: Contact[];+ insights: {+ followUps: string[];+ opportunities: string[];+ };+}++export interface Settings {+ interval: number;+ pageSize: number;+ aiModel: string;+ vaultPath: string;+ prompt: string;+ screenpipeAppSettings: ScreenpipeAppSettings;+}diff --git a/screenpipe-js/cli/src/commands/components/commands/add/registry/registry.json b/screenpipe-js/cli/src/commands/components/commands/add/registry/registry.jsonindex 11d34f436..252581921 100644--- a/screenpipe-js/cli/src/commands/components/commands/add/registry/registry.json+++ b/screenpipe-js/cli/src/commands/components/commands/add/registry/registry.json@@ -10,24 +10,35 @@"@types/lodash"]},- "use-settings": {- "name": "use-settings",- "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/obsidian/src/lib/hooks/use-settings.tsx",- "target": "./src/hooks/use-settings.ts",+ "use-pipe-settings": {+ "name": "use-pipe-settings",+ "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx",+ "target": "./src/lib/hooks/use-pipe-settings.ts","dependencies": ["@screenpipe/browser"],"registryDependencies": [- "route-settings"+ "get-screenpipe-app-settings",+ "types"]},- "route-settings": {- "name": "route-settings",- "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/obsidian/src/app/api/settings/route.ts",- "target": "./src/app/api/settings/route.ts",+ "get-screenpipe-app-settings": {+ "name": "get-screenpipe-app-settings",+ "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/obsidian/src/lib/actions/get-screenpipe-app-settings.ts",+ "target": "./src/lib/actions/get-screenpipe-app-settings.ts","dependencies": ["@screenpipe/js"- ]+ ],+ "registryDependencies": []+ },+ "types": {+ "name": "types",+ "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/obsidian/src/lib/types.ts",+ "target": "./src/lib/types.ts",+ "dependencies": [+ "@screenpipe/js"+ ],+ "registryDependencies": []},"use-sql-autocomplete": {"name": "use-sql-autocomplete",@@ -46,24 +57,6 @@"use-sql-autocomplete"]},- "use-search-history": {- "name": "use-search-history",- "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/data-table/src/lib/hooks/use-search-history.tsx",- "target": "./src/hooks/use-search-history.tsx",- "dependencies": [- "localforage"- ],- "registryDependencies": [],- "devDependencies": []- },- "keyword-cloud": {- "name": "keyword-cloud",- "src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/pipe-simple-nextjs/components/keyword-cloud.tsx",- "target": "./src/components/keyword-cloud.tsx",- "dependencies": [],- "registryDependencies": [],- "devDependencies": []- },"use-ai-provider": {"name": "use-ai-provider","src": "https://api.github.com/repos/mediar-ai/screenpipe/contents/pipes/search/src/lib/hooks/use-ai-provider.tsx",@@ -74,4 +67,4 @@"registryDependencies": [],"devDependencies": []}-}\ No newline at end of file+}