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
Improve notion pipe (#1704)
shaik-zeeshand4bfc2d81924
diff --git a/pipes/notion/bun.lockb b/pipes/notion/bun.lockbindex e4d3e7d8c..ca2e5ecb7 100755Binary files a/pipes/notion/bun.lockb and b/pipes/notion/bun.lockb differdiff --git a/pipes/notion/package.json b/pipes/notion/package.jsonindex 29f67c299..516ecc8a0 100644--- a/pipes/notion/package.json+++ b/pipes/notion/package.json@@ -12,21 +12,22 @@"@notionhq/client": "^2.2.15","@radix-ui/react-accordion": "^1.2.2","@radix-ui/react-checkbox": "^1.1.3",- "@radix-ui/react-dialog": "^1.1.4",+ "@radix-ui/react-dialog": "^1.1.6","@radix-ui/react-dropdown-menu": "^2.1.6",- "@radix-ui/react-label": "^2.1.1",- "@radix-ui/react-popover": "^1.1.3",+ "@radix-ui/react-label": "^2.1.2",+ "@radix-ui/react-popover": "^1.1.6","@radix-ui/react-progress": "^1.1.1",- "@radix-ui/react-select": "^2.1.3",+ "@radix-ui/react-select": "^2.1.6","@radix-ui/react-separator": "^1.1.1",- "@radix-ui/react-slider": "^1.2.2",- "@radix-ui/react-slot": "^1.1.1",- "@radix-ui/react-switch": "^1.1.2",+ "@radix-ui/react-slider": "^1.2.3",+ "@radix-ui/react-slot": "^1.1.2",+ "@radix-ui/react-switch": "^1.1.3","@radix-ui/react-tabs": "^1.1.2","@radix-ui/react-toast": "^1.2.4",- "@radix-ui/react-tooltip": "^1.1.5",- "@screenpipe/browser": "0.1.26",- "@screenpipe/js": "1.0.9",+ "@radix-ui/react-toggle": "^1.1.2",+ "@radix-ui/react-tooltip": "^1.1.8",+ "@screenpipe/browser": "^0.1.37",+ "@screenpipe/js": "^1.0.18","@shadcn/ui": "^0.0.4","@tanstack/react-query": "^5.62.7","@types/js-levenshtein": "^1.1.3",@@ -35,7 +36,7 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "1.0.4",+ "cmdk": "1.0.0","framer-motion": "^11.14.4","install": "^0.13.0","js-levenshtein": "^1.1.6",@@ -44,6 +45,7 @@"lucide-react": "^0.468.0","magic-ui": "^0.1.0","next": "15.1.0",+ "next-themes": "^0.4.6","notion-to-md": "^3.1.4","npm": "^10.9.2","ollama-ai-provider": "^1.1.0",@@ -56,6 +58,7 @@"react-syntax-highlighter": "^15.6.1","remark-gfm": "^4.0.0","remark-math": "^6.0.0",+ "sonner": "^2.0.1","tailwind-merge": "^2.5.5","tailwindcss-animate": "^1.0.7"},diff --git a/pipes/notion/src/app/api/intelligence/route.ts b/pipes/notion/src/app/api/intelligence/route.tsindex 894d23db1..841515351 100644--- a/pipes/notion/src/app/api/intelligence/route.ts+++ b/pipes/notion/src/app/api/intelligence/route.ts@@ -4,7 +4,9 @@ import { generateObject } from "ai";import { ollama } from "ollama-ai-provider";import { Client } from "@notionhq/client";import { NotionClient } from "@/lib/notion/client";-import { getScreenpipeAppSettings } from "@/lib/actions/get-screenpipe-app-settings";+import { settingsStore } from "@/lib/store/settings-store";+import { OpenAI } from "openai";+import { zodResponseFormat } from "openai/helpers/zod";// rich schema for relationship intelligenceconst contactSchema = z.object({@@ -26,57 +28,77 @@ const relationshipIntelligence = z.object({async function analyzeRelationships(recentLogs: string,- model: string,+ aiPreset: ReturnType<typeof settingsStore.getPreset>,): Promise<z.infer<typeof relationshipIntelligence>> {- 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- - spotting business opportunities- - suggesting follow-ups and introductions- - finding patterns in topics discussed- recent logs: ${recentLogs}+ if (!aiPreset) {+ throw new Error("ai preset not found");+ }++ const prompt = `You are a professional relationship intelligence analyst. Your task is to analyze work logs and generate a comprehensive relationship intelligence report.- todays date: ${new Date().toISOString().split("T")[0]}- local time: ${new Date().toLocaleTimeString()}- timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}+ ANALYSIS OBJECTIVES:+ 1. Extract all individuals mentioned, including their full names and organizations+ 2. Determine the nature and quality of each interaction (positive, neutral, negative)+ 3. Calculate sentiment scores (-1 to 1) based on interaction context+ 4. Identify recurring discussion topics and their importance+ 5. Recognize potential business opportunities and collaboration possibilities+ 6. Suggest specific, actionable follow-ups for each contact- return a detailed json object following this structure for relationship intelligence.+ CONTEXT:+ Today's date: ${new Date().toISOString().split("T")[0]}+ Current time: ${new Date().toLocaleTimeString()}+ Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}- example response from you:+ WORK LOGS TO ANALYZE:+ ${recentLogs}+ RESPONSE FORMAT:+ Return a JSON object with the following structure:{"contacts": [{- "name": "John Doe",- "company": "Acme Inc.",- "lastInteraction": "2024-01-01",- "sentiment": 0.8,- "topics": ["sales", "marketing"],- "nextSteps": ["schedule a call", "send a follow-up email"]- }+ "name": "Full Name",+ "company": "Organization Name",+ "lastInteraction": "YYYY-MM-DD",+ "sentiment": 0.X, // Range from -1.0 (negative) to 1.0 (positive)+ "topics": ["topic1", "topic2", "topic3"],+ "nextSteps": ["specific action 1", "specific action 2"]+ },+ // Additional contacts...],"insights": {- "followUps": ["schedule a call", "send a follow-up email"],- "opportunities": ["schedule a call", "send a follow-up email"]+ "followUps": ["priority follow-up 1", "priority follow-up 2"],+ "opportunities": ["business opportunity 1", "business opportunity 2"]}}- 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.+ IMPORTANT:+ - Use only real names and companies found in the logs+ - Ensure sentiment scores accurately reflect interaction quality+ - Provide specific, actionable next steps tailored to each contact+ - Prioritize follow-ups based on urgency and potential value+ - Identify concrete business opportunities with clear potential benefits`;- const provider = ollama(model);+ const openai = new OpenAI({+ apiKey: aiPreset.apiKey,+ baseURL: aiPreset.url,+ dangerouslyAllowBrowser: true,+ });+console.log("prompt", prompt);- const response = await generateObject({- model: provider,+++ const response = await openai.chat.completions.create({+ model: aiPreset.model,messages: [{ role: "user", content: prompt }],- schema: relationshipIntelligence,- maxRetries: 5,+ // response_format: { type: "json_object" },+ response_format: zodResponseFormat(relationshipIntelligence, "relationshipIntelligence"),});- console.log(response.object);- return response.object;+ console.log("relationship intelligence response", response.choices[0].message.content);+ return JSON.parse(response.choices[0].message.content || "{}");}async function readRecentLogs(@@ -121,9 +143,11 @@ async function readRecentLogs(export async function GET() {try {- const settings = (await getScreenpipeAppSettings())["customSettings"]![- "notion"- ];+ const settings = await settingsStore.loadPipeSettings("notion");++ console.log("settings", settings);++ const aiPreset = settingsStore.getPreset("notion", "aiLogPresetId");if (!settings?.notion?.accessToken ||@@ -157,7 +181,7 @@ export async function GET() {const intelligence = await analyzeRelationships(recentLogs,- settings.aiModel || "mistral",+ aiPreset);const notion = new NotionClient(settings.notion);diff --git a/pipes/notion/src/app/api/log/route.ts b/pipes/notion/src/app/api/log/route.tsindex 523de7058..6c181fed0 100644--- a/pipes/notion/src/app/api/log/route.ts+++ b/pipes/notion/src/app/api/log/route.ts@@ -1,25 +1,24 @@import { NextResponse } from "next/server";import { pipe } from "@screenpipe/js";-import { generateWorkLog } from "@/lib/helpers";+import { generateWorkLog, deduplicateScreenData } from "@/lib/helpers";import { NotionClient } from "@/lib/notion/client";-import { getScreenpipeAppSettings } from "@/lib/actions/get-screenpipe-app-settings";+import { settingsStore } from "@/lib/store/settings-store";const minute = (min: number) => min * 60 * 1000;export async function GET() {try {- const settings = (await getScreenpipeAppSettings())["customSettings"]![- "notion"- ];+ const settings = await settingsStore.loadPipeSettings("notion");++ const aiPreset = settingsStore.getPreset("notion", "aiLogPresetId");- const model = settings?.aiModel;const pageSize = settings?.pageSize || 50;const customPrompt = settings?.prompt;- const interval = settings?.interval ? minute(settings.interval) : 3600000;+ const deduplicationEnabled = settings?.deduplicationEnabled ?? false;- if (!model) {+ if (!aiPreset) {return NextResponse.json(- { error: "model not selected" },+ { error: "ai preset not selected" },{ status: 401 },);}@@ -32,7 +31,7 @@ export async function GET() {}const now = new Date();- const oneHourAgo = new Date(now.getTime() - interval);+ const oneHourAgo = new Date(now.getTime() - minute(1));const screenData = await pipe.queryScreenpipe({startTime: oneHourAgo.toISOString(),@@ -48,9 +47,21 @@ export async function GET() {);}+ // Only deduplicate if enabled in settings+ if (deduplicationEnabled) {+ try {+ screenData.data = await deduplicateScreenData(screenData.data);+ } catch (error) {+ console.warn(+ "deduplication failed, continuing with original data:",+ error,+ );+ }+ }+const logEntry = await generateWorkLog(screenData.data,- model,+ aiPreset,oneHourAgo,now,customPrompt,diff --git a/pipes/notion/src/components/ai-presets-selector.tsx b/pipes/notion/src/components/ai-presets-selector.tsxnew file mode 100644index 000000000..aa77cec32--- /dev/null+++ b/pipes/notion/src/components/ai-presets-selector.tsx@@ -0,0 +1,1302 @@+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings } from "@/lib/hooks/use-settings";+import { settingsStore, PipeSettings } from "@/lib/store/settings-store";+import { useMemo, useState, useEffect } from "react";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "./ui/command";+import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "./ui/dialog";+import { Button } from "./ui/button";+import {+ Check,+ ChevronsUpDown,+ Plus,+ Copy,+ Edit2,+ Star,+ Trash2,+ Terminal,+ Loader2,+ HelpCircle,+ Eye,+ EyeOff,+ Settings,+} from "lucide-react";+import { cn } from "@/lib/utils";+import { toast } from "sonner";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "./ui/tooltip";+import { Input } from "./ui/input";+import { Label } from "./ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "./ui/select";+import { Textarea } from "./ui/textarea";+import { Slider } from "./ui/slider";++export const Icons = {+ openai: (props: any) => (+ <svg+ fill="currentColor"+ viewBox="0 0 24 24"+ role="img"+ xmlns="http://www.w3.org/2000/svg"+ {...props}+ >+ <path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.0264 1.1706a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4929 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0264 1.1706a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.8956zm16.0788 3.7951-5.8144-3.3543 2.0264-1.1706a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.4068-.6813zm2.0834-3.0089-.142-.0852-4.7782-2.7913a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1658a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654 2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z" />+ </svg>+ ),+ settings: Settings,+ terminal: Terminal,+ spinner: Loader2,+};++interface BaseAIPreset {+ id: string;+ maxContextChars: number;+ url: string;+ model: string;+ defaultPreset: boolean;+ prompt: string;+}++type AIPreset = BaseAIPreset &+ (+ | {+ provider: "openai";+ apiKey: string;+ }+ | {+ provider: "native-ollama";+ }+ | {+ provider: "screenpipe-cloud";+ }+ | {+ provider: "custom";+ apiKey?: string;+ }+ );++interface BaseRecommendedPreset {+ id: string;+ maxContextChars: number;+ model: string;+ prompt: string;+}++type RecommendedPreset = BaseRecommendedPreset &+ (+ | {+ provider: "openai";+ }+ | {+ provider: "native-ollama";+ }+ | {+ provider: "screenpipe-cloud";+ }+ );++interface AIProviderConfigProps {+ onSubmit: (data: AIProviderData) => void;+ defaultPreset?: {+ provider: "openai" | "native-ollama" | "custom" | "screenpipe-cloud";+ apiKey?: string;+ baseUrl?: string;+ modelName?: string;+ maxContextChars?: number;+ prompt?: string;+ id?: string;+ };+}++interface AIProviderData {+ provider: "openai" | "native-ollama" | "custom" | "screenpipe-cloud";+ apiKey?: string;+ baseUrl?: string;+ modelName?: string;+ maxContextChars?: number;+ prompt?: string;+ id?: string;+}++interface OpenAIModel {+ id: string;+ created?: number;+ owned_by?: string;+}++export const DEFAULT_PROMPT = `Rules:+- You can analyze/view/show/access videos to the user by putting .mp4 files in a code block (we'll render it) like this: \`/users/video.mp4\`, use the exact, absolute, file path from file_path property+- Do not try to embed video in links (e.g. [](.mp4) or https://.mp4) instead put the file_path in a code block using backticks+- Do not put video in multiline code block it will not render the video (e.g. \`\`\`bash\n.mp4\`\`\` IS WRONG) instead using inline code block with single backtick+- Always answer my question/intent, do not make up things+`;++export function AIProviderConfig({+ onSubmit,+ defaultPreset,+}: AIProviderConfigProps) {+ const [selectedProvider, setSelectedProvider] = useState<+ AIProviderData["provider"]+ >(defaultPreset?.provider || "openai");+ const { settings } = useSettings();+ const [isLoading, setIsLoading] = useState(false);+ const [openaiModels, setOpenAIModels] = useState<OpenAIModel[]>([]);+ const [isLoadingModels, setIsLoadingModels] = useState(false);+ const [idError, setIdError] = useState<string | null>(null);+ const [showApiKey, setShowApiKey] = useState(false);+ const [formData, setFormData] = useState<AIProviderData>({+ provider: defaultPreset?.provider || "openai",+ apiKey: defaultPreset?.apiKey || "",+ baseUrl: defaultPreset?.baseUrl || "",+ modelName: defaultPreset?.modelName || "",+ maxContextChars: defaultPreset?.maxContextChars || 512000,+ prompt: defaultPreset?.prompt || DEFAULT_PROMPT,+ id: defaultPreset?.id || "",+ });++ const validateId = (id: string | undefined): boolean => {+ if (!id?.trim()) {+ setIdError("name is required");+ return false;+ }++ // Check if ID ends with 'copy' (case insensitive)+ if (id.trim().toLowerCase().endsWith("copy")) {+ setIdError("name cannot end with 'copy'");+ return false;+ }++ // Check for duplicate IDs, excluding the current preset being edited+ const isDuplicate = settings?.aiPresets?.some(+ (preset) =>+ preset.id.toLowerCase() === id.toLowerCase() &&+ preset.id !== defaultPreset?.id,+ );++ if (isDuplicate) {+ setIdError("name already exists");+ return false;+ }++ setIdError(null);+ return true;+ };++ const handleIdChange = (value: string) => {+ setFormData((prev) => ({ ...prev, id: value }));+ validateId(value);+ };++ const fetchOpenAIModels = async (baseUrl: string, apiKey: string) => {+ setIsLoadingModels(true);+ try {+ const response = await fetch(`${baseUrl}/models`, {+ headers: {+ Authorization: `Bearer ${apiKey}`,+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ throw new Error("failed to fetch models");+ }++ const data = await response.json();+ setOpenAIModels(data.data || []);+ } catch (error) {+ console.error("error fetching models:", error);+ setOpenAIModels([]);+ } finally {+ setIsLoadingModels(false);+ }+ };++ const fetchOllamaModels = async (baseUrl: string) => {+ setIsLoadingModels(true);+ try {+ const response = await fetch(`${baseUrl}/models`);++ if (!response.ok) {+ throw new Error("failed to fetch ollama models");+ }++ const data = (await response.json()) as {+ data: OpenAIModel[];+ };+ setOpenAIModels(data.data || []);+ } catch (error) {+ console.error("error fetching ollama models:", error);+ setOpenAIModels([]);+ } finally {+ setIsLoadingModels(false);+ }+ };++ useEffect(() => {+ setOpenAIModels([]);+ if (selectedProvider === "openai" && formData.apiKey) {+ setOpenAIModels([+ { id: "gpt-4" },+ {+ id: "gpt-3.5-turbo",+ },+ ]);+ } else if (selectedProvider === "native-ollama") {+ const baseUrl = "http://localhost:11434/v1";+ fetchOllamaModels(baseUrl);+ } else if (selectedProvider === "screenpipe-cloud") {+ fetchOpenAIModels(+ "https://ai-proxy.i-f9f.workers.dev/v1",+ settings?.user?.token ?? "",+ );+ } else if (+ selectedProvider === "custom" &&+ formData.baseUrl &&+ formData.apiKey+ ) {+ fetchOpenAIModels(formData.baseUrl, formData.apiKey);+ }+ }, [selectedProvider, formData.apiKey, formData.baseUrl]);++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();++ if (!validateId(formData.id)) {+ return;+ }++ setIsLoading(true);+ try {+ onSubmit({+ ...formData,+ id: formData.id?.trim() || "",+ });+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <div className="w-full space-y-6 rounded-lg bg-card p-6">+ <div>+ <h2 className="text-lg font-semibold">+ {defaultPreset?.id ? "edit ai provider" : "ai provider"}+ </h2>+ <p className="text-sm text-muted-foreground">+ {defaultPreset?.id+ ? "modify your ai provider settings"+ : "configure your ai provider settings"}+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="name" className="flex items-center gap-2">+ name+ {idError && (+ <span className="text-xs text-destructive font-normal">+ {idError}+ </span>+ )}+ </Label>+ <Input+ id="name"+ type="text"+ placeholder="enter preset name"+ value={formData.id || undefined}+ onChange={(e) => handleIdChange(e.target.value)}+ className={cn(+ "font-mono",+ idError && "border-destructive focus-visible:ring-destructive",+ )}+ autoComplete="off"+ autoCorrect="off"+ autoCapitalize="off"+ disabled={+ Boolean(defaultPreset?.id) &&+ !defaultPreset?.id?.endsWith("-copy")+ }+ />+ </div>++ <div className="grid grid-cols-4 gap-4">+ <Button+ type="button"+ variant={selectedProvider === "openai" ? "default" : "outline"}+ className="flex h-24 flex-col items-center justify-center gap-2"+ onClick={() => {+ setSelectedProvider("openai");+ setFormData({ ...formData, provider: "openai" });+ }}+ >+ <Icons.openai className="h-8 w-8" />+ <span>openai</span>+ </Button>++ <Button+ type="button"+ variant={+ selectedProvider === "native-ollama" ? "default" : "outline"+ }+ className="flex h-24 flex-col items-center justify-center gap-2"+ onClick={() => {+ setSelectedProvider("native-ollama");+ setFormData({+ ...formData,+ provider: "native-ollama",+ baseUrl: "http://localhost:11434/v1",+ });+ }}+ >+ <Icons.terminal className="h-8 w-8" />+ <span>ollama</span>+ </Button>++ <Button+ type="button"+ disabled={!settings?.user?.token}+ variant={+ selectedProvider === "screenpipe-cloud" ? "default" : "outline"+ }+ className="flex h-24 flex-col items-center justify-center gap-2"+ onClick={() => {+ setSelectedProvider("screenpipe-cloud");+ setFormData({+ ...formData,+ provider: "screenpipe-cloud",+ baseUrl: "https://ai-proxy.i-f9f.workers.dev/v1",+ });+ }}+ >+ <Icons.terminal className="h-8 w-8" />+ <span>screenpipe</span>+ {!settings?.user?.token && (+ <span className="text-xs text-destructive font-normal">+ login to screenpipe to use this provider+ </span>+ )}+ </Button>++ <Button+ type="button"+ variant={selectedProvider === "custom" ? "default" : "outline"}+ className="flex h-24 flex-col items-center justify-center gap-2"+ onClick={() => {+ setSelectedProvider("custom");+ setFormData({+ ...formData,+ provider: "custom",+ baseUrl: "http://localhost:11434/v1",+ });+ }}+ >+ <Icons.settings className="h-8 w-8" />+ <span>custom</span>+ </Button>+ </div>++ {selectedProvider === "openai" && (+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="apiKey">api key</Label>+ <div className="relative">+ <Input+ id="apiKey"+ type={showApiKey ? "text" : "password"}+ placeholder="sk-..."+ value={formData.apiKey || ""}+ onChange={(e) =>+ setFormData({ ...formData, apiKey: e.target.value })+ }+ className="pr-10"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"+ onClick={() => setShowApiKey(!showApiKey)}+ >+ {showApiKey ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </Button>+ </div>+ </div>+ <div className="space-y-2">+ <Label htmlFor="model">model</Label>+ <Select+ value={formData.modelName}+ onValueChange={(value) =>+ setFormData({ ...formData, modelName: value })+ }+ >+ <SelectTrigger>+ <SelectValue+ placeholder={+ isLoadingModels ? "loading models..." : "select model"+ }+ />+ </SelectTrigger>+ <SelectContent>+ {openaiModels.length > 0 ? (+ openaiModels.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.id}+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-models" disabled>+ {isLoadingModels ? "loading..." : "no models found"}+ </SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}++ {selectedProvider === "native-ollama" && (+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="baseUrl">base url</Label>+ <Input+ id="baseUrl"+ type="text"+ placeholder="http://localhost:11434"+ value={formData.baseUrl || ""}+ onChange={(e) =>+ setFormData({ ...formData, baseUrl: e.target.value })+ }+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="model">model</Label>+ <Select+ value={formData.modelName}+ onValueChange={(value) =>+ setFormData({ ...formData, modelName: value })+ }+ >+ <SelectTrigger>+ <SelectValue+ placeholder={+ isLoadingModels ? "loading models..." : "select model"+ }+ />+ </SelectTrigger>+ <SelectContent>+ {openaiModels.length > 0 ? (+ openaiModels.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.id}+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-models" disabled>+ {isLoadingModels ? "loading..." : "no models found"}+ </SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}++ {selectedProvider === "screenpipe-cloud" && (+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="model">model</Label>+ <Select+ value={formData.modelName}+ onValueChange={(value) =>+ setFormData({ ...formData, modelName: value })+ }+ >+ <SelectTrigger>+ <SelectValue+ placeholder={+ isLoadingModels ? "loading models..." : "select model"+ }+ />+ </SelectTrigger>+ <SelectContent>+ {openaiModels.length > 0 ? (+ openaiModels.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.id}+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-models" disabled>+ {isLoadingModels ? "loading..." : "no models found"}+ </SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}++ {selectedProvider === "custom" && (+ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="baseUrl">base url</Label>+ <Input+ id="baseUrl"+ type="text"+ placeholder="https://api.example.com/v1"+ value={formData.baseUrl || ""}+ onChange={(e) =>+ setFormData({ ...formData, baseUrl: e.target.value })+ }+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="apiKey">api key</Label>+ <div className="relative">+ <Input+ id="apiKey"+ type={showApiKey ? "text" : "password"}+ placeholder="your-api-key"+ value={formData.apiKey || ""}+ onChange={(e) =>+ setFormData({ ...formData, apiKey: e.target.value })+ }+ className="pr-10"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"+ onClick={() => setShowApiKey(!showApiKey)}+ >+ {showApiKey ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </Button>+ </div>+ </div>+ <div className="space-y-2">+ <Label htmlFor="model">model</Label>+ <Select+ value={formData.modelName}+ onValueChange={(value) =>+ setFormData({ ...formData, modelName: value })+ }+ >+ <SelectTrigger>+ <SelectValue+ placeholder={+ isLoadingModels ? "loading models..." : "select model"+ }+ />+ </SelectTrigger>+ <SelectContent>+ {openaiModels.length > 0 ? (+ openaiModels.map((model) => (+ <SelectItem key={model.id} value={model.id}>+ {model.id}+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-models" disabled>+ {isLoadingModels ? "loading..." : "no models found"}+ </SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>+ </div>+ )}++ <div className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="maxContextChars" className="flex items-center">+ max context{" "}+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="ml-2 h-4 w-4 cursor-default" />+ </TooltipTrigger>+ <TooltipContent side="right">+ <p>+ maximum number of characters (think 4 characters per+ token) to send to the ai model. <br />+ usually, openai models support up to 200k tokens, which is+ roughly 1m characters.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </Label>+ <div className="flex items-center gap-4">+ <Slider+ id="maxContextChars"+ min={10000}+ max={1000000}+ step={10000}+ value={[formData.maxContextChars || 512000]}+ onValueChange={([value]) =>+ setFormData({ ...formData, maxContextChars: value })+ }+ className="flex-grow"+ />+ <span className="min-w-[60px] text-right">+ {((formData.maxContextChars || 512000) / 1000).toFixed(0)}k+ </span>+ </div>+ </div>++ <div className="space-y-2">+ <Label htmlFor="prompt">prompt</Label>+ <Textarea+ id="prompt"+ value={formData.prompt || DEFAULT_PROMPT}+ onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>+ setFormData({ ...formData, prompt: e.target.value })+ }+ placeholder="enter your custom prompt here"+ className="min-h-[100px]"+ />+ </div>+ </div>++ <Button+ type="submit"+ className="w-full"+ disabled={+ isLoading ||+ Boolean(!formData.id?.length && !formData.modelName?.length)+ }+ >+ {isLoading ? (+ <Icons.spinner className="mr-2 h-4 w-4 animate-spin" />+ ) : null}+ {defaultPreset ? "save changes" : "continue"}+ </Button>+ </form>+ </div>+ );+}++interface AIPresetDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onSave: (preset: Partial<AIPreset>) => void;+ preset?: AIPreset;+}++interface AIPresetsSelectorProps {+ recommendedPresets?: RecommendedPreset[];+ pipeName: string;+ aiKey?: keyof PipeSettings;+ shortcutKey?: string;+}++export const AIPresetDialog = ({+ open,+ onOpenChange,+ onSave,+ preset,+}: AIPresetDialogProps) => {+ const handleProviderSubmit = (providerData: any) => {+ const newPreset: Partial<AIPreset> = {+ ...preset,+ provider: providerData.provider,+ url: providerData.baseUrl,+ model: providerData.modelName,+ id: providerData.id,+ maxContextChars: providerData.maxContextChars,+ prompt: providerData.prompt,+ };++ // Only add apiKey if provider is openai or custom+ if (+ providerData.provider === "openai" ||+ providerData.provider === "custom"+ ) {+ (newPreset as any).apiKey = providerData.apiKey;+ }++ onSave(newPreset);+ };++ const defaultPreset = preset+ ? {+ id: preset.id,+ provider: preset.provider,+ baseUrl: preset.url,+ modelName: preset.model,+ ...("apiKey" in preset ? { apiKey: preset.apiKey } : {}),+ }+ : undefined;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="w-3/4 max-w-screen-2xl">+ <DialogHeader className="sr-only">+ <DialogTitle>+ {preset ? "Edit Preset" : "Create New Preset"}+ </DialogTitle>+ <DialogDescription>+ {preset+ ? "Modify your AI preset settings here. Click save when you're done."+ : "Configure your AI preset settings here. Click continue when you're done."}+ </DialogDescription>+ </DialogHeader>+ <AIProviderConfig+ onSubmit={handleProviderSubmit}+ defaultPreset={defaultPreset}+ />+ </DialogContent>+ </Dialog>+ );+};++export const AIPresetsSelector = ({+ recommendedPresets,+ pipeName,+ aiKey = "aiPresetId",+ shortcutKey = "/",+}: AIPresetsSelectorProps) => {+ const { settings: pipeSettings, updateSettings: updatePipeSettings } =+ usePipeSettings(pipeName);+ const { settings, updateSettings } = useSettings();+ const [open, setOpen] = useState(false);+ const [dialogOpen, setDialogOpen] = useState(false);+ const [selectedPresetToEdit, setSelectedPresetToEdit] = useState<+ AIPreset | undefined+ >();++ const aiPresets = (settings?.aiPresets || []) as AIPreset[];++ const selectedPreset = useMemo(() => {+ const preset = settings?.aiPresets?.find(+ (preset) => preset.id == pipeSettings?.[aiKey],+ );++ return preset?.id;+ }, [settings?.aiPresets, pipeSettings?.[aiKey]]);++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ // Check for Cmd/Ctrl + /+ if ((e.metaKey || e.ctrlKey) && e.key === shortcutKey) {+ e.preventDefault();+ if (!aiPresets.length) return;++ const currentIndex = selectedPreset+ ? aiPresets.findIndex((p) => p.id === selectedPreset)+ : -1;+ const nextIndex = (currentIndex + 1) % aiPresets.length;+ const nextPreset = aiPresets[nextIndex];++ updatePipeSettings({+ [aiKey]: nextPreset.id,+ });++ toast.success("Preset changed", {+ description: `Switched to ${nextPreset.id} (${nextPreset.model})`,+ });+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [aiPresets, selectedPreset, updatePipeSettings]);++ const handleSavePreset = (preset: Partial<AIPreset>) => {+ if (!preset.id) {+ toast.error("Please enter a name for this preset", {+ description: "Name is required",+ });+ return;+ }++ if (!settings?.aiPresets) {+ toast.error("Error", {+ description: "Settings not initialized",+ });+ return;+ }++ // If we're editing an existing preset+ if (selectedPresetToEdit) {+ // If this is a copy operation, treat it as a new preset+ if (+ preset.id !== selectedPresetToEdit.id ||+ preset.id.endsWith("-copy")+ ) {+ // Check for duplicate ID+ const existingPreset = settings.aiPresets.find(+ (pre) => pre.id === preset.id,+ );++ if (existingPreset) {+ toast.error("Name already exists", {+ description: "Please choose a different name",+ });+ return;+ }++ // Add as new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });++ toast.success("Preset copied", {+ description: "New preset has been created from copy",+ });+ } else {+ // Normal edit operation+ const updatedPresets = settings.aiPresets.map((p) =>+ p.id === selectedPresetToEdit.id+ ? ({ ...preset, defaultPreset: p.defaultPreset } as AIPreset)+ : p,+ );++ // If editing the default preset, update the global settings as well+ const isEditingDefaultPreset = selectedPresetToEdit.defaultPreset;+ if (isEditingDefaultPreset) {+ updateSettings({+ aiPresets: updatedPresets,+ aiModel: preset.model,+ aiProviderType: preset.provider,+ customPrompt: preset.prompt,+ aiMaxContextChars: preset.maxContextChars,+ aiUrl: preset.url,+ ...("apiKey" in preset && {+ openaiApiKey: preset.apiKey,+ }),+ });+ } else {+ updateSettings({+ aiPresets: updatedPresets,+ });+ }++ toast.success("Preset updated", {+ description: "Your changes have been saved",+ });+ }+ } else {+ // Check for duplicate ID only when creating new preset+ const existingPreset = settings.aiPresets.find(+ (pre) => pre.id === preset.id,+ );++ if (existingPreset) {+ toast.error("Name already exists", {+ description: "Please choose a different name",+ });+ return;+ }++ // Handle first preset creation+ if (settings.aiPresets.length === 0) {+ const newPreset = {+ ...preset,+ defaultPreset: true,+ } as AIPreset;++ updateSettings({+ aiPresets: [newPreset],+ aiModel: newPreset.model,+ aiProviderType: newPreset.provider,+ customPrompt: newPreset.prompt,+ aiMaxContextChars: newPreset.maxContextChars,+ aiUrl: newPreset.url,+ ...("apiKey" in newPreset && {+ openaiApiKey: newPreset.apiKey,+ }),+ });+ } else {+ // Adding a new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });+ }++ toast.success("Preset created", {+ description: "New preset has been added",+ });+ }++ setDialogOpen(false);+ setSelectedPresetToEdit(undefined);+ };++ const handleDuplicatePreset = (preset: AIPreset) => {+ setSelectedPresetToEdit({+ ...preset,+ id: `${preset.id}-copy`,+ defaultPreset: false,+ });+ setDialogOpen(true);+ };++ const handleEditPreset = (preset: AIPreset) => {+ setSelectedPresetToEdit(preset);+ setDialogOpen(true);+ };++ const handleSetDefaultPreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) return;++ const updatedPresets = settings.aiPresets.map((p) => ({+ ...p,+ defaultPreset: p.id === preset.id,+ }));++ updateSettings({+ aiPresets: updatedPresets,+ aiModel: preset.model,+ aiProviderType: preset.provider,+ customPrompt: preset.prompt,+ aiMaxContextChars: preset.maxContextChars,+ aiUrl: preset.url,+ ...("apiKey" in preset && {+ openaiApiKey: preset.apiKey,+ }),+ });++ toast.success("Default preset updated", {+ description: `${preset.id} is now the default preset`,+ });+ };++ const handleRemovePreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) {+ toast.error("Cannot delete default preset", {+ description: "Please set another preset as default first",+ });+ return;+ }++ const updatedPresets = settings.aiPresets.filter((p) => p.id !== preset.id);+ updateSettings({+ aiPresets: updatedPresets,+ });++ if (pipeSettings?.[aiKey] === preset.id) {+ updatePipeSettings({+ [aiKey]: "",+ });+ }++ toast.success("Preset removed", {+ description: `${preset.id} has been removed`,+ });+ };++ return (+ <>+ <div className="flex w-full items-center gap-2">+ <Popover open={open} onOpenChange={setOpen}>+ <TooltipProvider>+ <Tooltip>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ role="combobox"+ aria-expanded={open}+ className="w-full justify-between"+ >+ {selectedPreset ? (+ <div className="flex w-full items-center justify-between gap-2 overflow-hidden">+ <span className="font-medium min-w-[80px] max-w-[30%] truncate text-left">+ {+ aiPresets.find(+ (preset) => preset.id === selectedPreset,+ )?.id+ }+ </span>+ <div className="flex items-center gap-2 text-xs text-muted-foreground overflow-hidden">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {+ aiPresets.find(+ (preset) => preset.id === selectedPreset,+ )?.provider+ }+ </span>+ <span className="hidden sm:block truncate max-w-[30%]">+ {+ aiPresets.find(+ (preset) => preset.id === selectedPreset,+ )?.model+ }+ </span>+ <span className="whitespace-nowrap">+ {(+ (aiPresets.find(+ (preset) => preset.id === selectedPreset,+ )?.maxContextChars || 0) / 1000+ ).toFixed(0)}+ k+ </span>+ </div>+ </div>+ ) : (+ "select ai preset..."+ )}+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ </Button>+ </PopoverTrigger>+ <TooltipContent>+ <p className="flex items-center gap-2">+ <span>Press</span>+ <kbd className="px-1.5 py-0.5 text-xs font-semibold bg-muted rounded">+ ⌘/+ </kbd>+ <span>to cycle presets</span>+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <PopoverContent className="min-w-[500px] w-[--radix-popover-trigger-width] p-0">+ <Command>+ <CommandInput placeholder="search presets..." />+ <CommandList>+ <CommandEmpty>no presets found.</CommandEmpty>+ {recommendedPresets && recommendedPresets.length > 0 && (+ <CommandGroup heading="Recommended Presets">+ {recommendedPresets.map((preset) => (+ <CommandItem+ key={`${preset.id}-recommended`}+ value={`${preset.id}-recommened`}+ className="flex py-2"+ >+ <div className="flex w-full items-center justify-between gap-2 overflow-hidden">+ <div className="flex items-center gap-2 min-w-0 flex-shrink">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[30%]">+ {preset.id}+ </span>+ <span className="rounded bg-primary/10 text-primary px-1.5 py-0.5 text-xs font-medium shrink-0">+ recommended+ </span>+ </div>+ <div className="flex items-center justify-end gap-2 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-2">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="hidden sm:block truncate max-w-[30%]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ // Create a full preset from the recommended preset with -copy suffix+ const fullPreset = {+ ...preset,+ id: `${preset.id}`,+ url:+ preset.provider === "openai"+ ? "https://api.openai.com/v1"+ : preset.provider === "screenpipe-cloud"+ ? "https://ai-proxy.i-f9f.workers.dev/v1"+ : preset.provider === "native-ollama"+ ? "http://localhost:11434/v1"+ : "",+ defaultPreset: false,+ } as AIPreset;+ setSelectedPresetToEdit(fullPreset);+ setDialogOpen(true);+ }}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ )}+ <CommandGroup>+ {aiPresets.map((preset) => (+ <CommandItem+ key={preset.id}+ value={preset.id}+ onSelect={(currentValue) => {+ console.log("currentValue", currentValue);+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset ? "" : currentValue,+ });+ console.log("pipeSettings", pipeSettings);+ setOpen(false);+ }}+ className="flex py-2"+ >+ <div className="flex w-full items-center justify-between gap-2 overflow-hidden">+ <div className="flex items-center gap-2 min-w-0">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[120px]">+ {preset.id}+ </span>+ {preset.defaultPreset && (+ <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium shrink-0">+ default+ </span>+ )}+ </div>+ <div className="flex items-center justify-end gap-2 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-2">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="truncate max-w-[120px]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleEditPreset(preset);+ }}+ >+ <Edit2 className="h-3 w-3" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleDuplicatePreset(preset);+ }}+ >+ <Copy className="h-3 w-3" />+ </Button>+ {!preset.defaultPreset && (+ <>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleSetDefaultPreset(preset);+ }}+ >+ <Star className="h-3 w-3" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleRemovePreset(preset);+ }}+ >+ <Trash2 className="h-3 w-3" />+ </Button>+ </>+ )}+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ <CommandGroup>+ <CommandItem+ onSelect={() => {+ setOpen(false);+ setSelectedPresetToEdit(undefined);+ setDialogOpen(true);+ }}+ >+ <Plus className="mr-2 h-4 w-4" />+ create new preset+ </CommandItem>+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ <AIPresetDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ onSave={handleSavePreset}+ preset={selectedPresetToEdit}+ />+ </>+ );+};diff --git a/pipes/notion/src/components/file-suggest-textarea.tsx b/pipes/notion/src/components/file-suggest-textarea.tsxindex b588fa563..f28939b08 100644--- a/pipes/notion/src/components/file-suggest-textarea.tsx+++ b/pipes/notion/src/components/file-suggest-textarea.tsx@@ -3,7 +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";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";interface FileSuggestTextareaProps {value: string;@@ -41,7 +41,7 @@ export function FileSuggestTextarea({placeholder,disabled = false,}: FileSuggestTextareaProps) {- const { settings } = useNotionSettings();+ const { settings } = usePipeSettings("notion");const [showSuggestions, setShowSuggestions] = useState(false);const [searchTerm, setSearchTerm] = useState("");const [cursorCoords, setCursorCoords] = useState({ x: 0, y: 0 });diff --git a/pipes/notion/src/components/notion-settings.tsx b/pipes/notion/src/components/notion-settings.tsxindex 7f0466fd1..75ccf78a5 100644--- a/pipes/notion/src/components/notion-settings.tsx+++ b/pipes/notion/src/components/notion-settings.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -10,12 +10,12 @@ import {CardDescription,CardHeader,CardTitle,+ CardFooter,} from "@/components/ui/card";-import { OllamaModelsList } from "./ollama-models-list";import { validateCredentials } from "@/lib/notion/notion";import { toast } from "@/hooks/use-toast";-import { useNotionSettings } from "@/lib/hooks/use-pipe-settings";-import { ChevronDown, Loader2 } from "lucide-react";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { ChevronDown, Loader2, ExternalLink, Info, Clock, Brain, LineChart } from "lucide-react";import { Settings } from "@/lib/types";import { updatePipeConfig } from "@/lib/actions/update-pipe-config";import { FileSuggestTextarea } from "./file-suggest-textarea";@@ -31,18 +31,37 @@ import {TooltipProvider,TooltipTrigger,} from "./ui/tooltip";-import { NotionIdInput } from "./notion-url-to-input";+import { NotionDatabaseSelector, NotionIdInput } from "./notion-url-to-input";import { INTEGRATION_NAME } from "@/lib/utils";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@/components/ui/tabs";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import { PipeSettings } from "@/lib/store/settings-store";+import { AIPresetsSelector } from "./ai-presets-selector";+import {+ Separator+} from "./ui/separator";+import { Switch } from "./ui/switch";export function NotionSettings() {- const { settings, updateSettings, loading } = useNotionSettings();+ const { settings, updateSettings, loading } = usePipeSettings("notion");const [isSettingUp, setIsSettingUp] = useState(false);-const [testingLog, setTestingLog] = useState(false);const [testingIntelligence, setTestingIntelligence] = useState(false);- const [localSettings, setLocalSettings] = useState<Partial<Settings> | null>(- {},- );+ const [localSettings, setLocalSettings] = useState<Partial<PipeSettings> | null>({});+ const [isConnectedToNotion, setIsConnectedToNotion] = useState<boolean | null>(null);+ const [deduplicationEnabled, setDeduplicationEnabled] =+ useState<boolean>(false);+ const [checkingModel, setCheckingModel] = useState<boolean>(false);useEffect(() => {setLocalSettings({@@ -51,6 +70,7 @@ export function NotionSettings() {}, [settings]);const handleValidate = async () => {+ console.log("handleValidate", settings?.notion);setIsSettingUp(true);try {const isValid = await validateCredentials({@@ -106,8 +126,6 @@ export function NotionSettings() {throw new Error("Invalid credentials");}- console.log(isValid, "done");-await updateSettings({...settings!,notion: notionCreds,@@ -132,10 +150,8 @@ export function NotionSettings() {setTestingLog(true);try {const response = await fetch("/api/log");-const data = await response.json();- console.log(data);if (!response.ok) throw new Error(data.message);toast({@@ -187,8 +203,10 @@ export function NotionSettings() {aiModel: localSettings?.aiModel || settings?.aiModel,prompt: localSettings?.prompt || settings?.prompt,interval: localSettings?.interval || settings?.interval,+ shortTasksInterval: localSettings?.shortTasksInterval || settings?.shortTasksInterval,pageSize: localSettings?.pageSize || settings?.pageSize,workspace: localSettings?.workspace || settings?.workspace,+ deduplicationEnabled: localSettings?.deduplicationEnabled || settings?.deduplicationEnabled,notion: {accessToken:localSettings?.notion?.accessToken ||@@ -205,8 +223,12 @@ export function NotionSettings() {},});+ if (localSettings?.shortTasksInterval !== settings?.shortTasksInterval) {+ await updatePipeConfig(localSettings?.shortTasksInterval || 5, "/api/log", "minute");+ }+if (localSettings?.interval !== settings?.interval) {- await updatePipeConfig(localSettings?.interval || 5);+ await updatePipeConfig(localSettings?.interval || 1, "/api/intelligence", "hour");}toast({@@ -222,258 +244,609 @@ export function NotionSettings() {}};+ // Check if the connection is complete+ const isConnected = !!(+ settings?.notion?.accessToken &&+ settings?.notion?.databaseId &&+ settings?.notion?.intelligenceDbId+ );++++ useEffect(() => {+ const checkConnection = async () => {+ if (!settings?.notion?.accessToken ||+ !settings?.notion?.databaseId ||+ !settings?.notion?.intelligenceDbId) {+ setIsConnectedToNotion(false);+ return;+ }++ try {+ console.log("Checking connection...");+ setIsConnectedToNotion(null);+ const isValid = await validateCredentials({+ accessToken: settings.notion.accessToken,+ databaseId: settings.notion.databaseId,+ intelligenceDbId: settings.notion.intelligenceDbId,+ });+ setIsConnectedToNotion(isValid);+ } catch (error) {+ console.error("Failed to validate Notion credentials:", error);+ setIsConnectedToNotion(false);+ }+ };++ checkConnection();+ }, [settings?.notion?.accessToken, settings?.notion?.databaseId, settings?.notion?.intelligenceDbId]);++ // Check if manual connection is ready+ const isManualConnectionReady = !!(+ localSettings?.notion?.accessToken &&+ localSettings?.notion?.databaseId &&+ localSettings?.notion?.intelligenceDbId+ );+++ // Replace the connection status indicator with an improved version+ const renderConnectionStatus = () => {+ if (isConnectedToNotion === null) {+ return (+ <div className="mt-2 p-2 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md text-blue-700 dark:text-blue-300 text-sm flex items-center gap-2">+ <Loader2 className="h-3 w-3 animate-spin" />+ Checking connection status...+ </div>+ );+ } else if (isConnectedToNotion) {+ return (+ <div className="mt-2 p-2 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md text-green-700 dark:text-green-300 text-sm flex items-center gap-2">+ <div className="h-2 w-2 rounded-full bg-green-500"></div>+ Connected to Notion successfully+ </div>+ );+ } else if (!isConnectedToNotion && settings?.notion?.accessToken) {+ return (+ <div className="mt-2 p-2 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md text-red-700 dark:text-red-300 text-sm flex items-center gap-2">+ <div className="h-2 w-2 rounded-full bg-red-500"></div>+ Failed to connect to Notion+ </div>+ );+ } else {+ return (+ <div className="mt-2 p-2 bg-yellow-50 dark:bg-yellow-950 border border-yellow-200 dark:border-yellow-800 rounded-md text-yellow-700 dark:text-yellow-300 text-sm flex items-center gap-2">+ <div className="h-2 w-2 rounded-full bg-yellow-500"></div>+ Not connected to Notion yet+ </div>+ );+ }+ };++ const setupDeduplication = async () => {+ setCheckingModel(true);+ try {+ // Direct request to Ollama API+ const checkRes = await fetch("http://localhost:11434/api/tags");+ const models = await checkRes.json();++ const hasEmbeddingModel = models.models?.some(+ (m: { name: string }) => m.name === "nomic-embed-text",+ );++ if (!hasEmbeddingModel) {+ // Show loading toast+ const loadingToast = toast({+ title: "pulling embedding model...",+ description: (+ <div>+ <p>downloading nomic-embed-text model</p>+ <p>this may take a few minutes</p>+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ ),+ });++ // Direct pull request to Ollama+ const pullRes = await fetch("http://localhost:11434/api/pull", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "nomic-embed-text" }),+ });++ if (!pullRes.ok) {+ throw new Error("failed to pull model");+ }++ // Handle streaming response+ const reader = pullRes.body?.getReader();+ const decoder = new TextDecoder();++ if (!reader) {+ throw new Error("no response body");+ }++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ const chunk = decoder.decode(value);+ const lines = chunk.split("\n").filter((line) => line.trim());++ for (const line of lines) {+ const response = JSON.parse(line);+ console.log("progress:", response);++ // Update toast with progress if available+ if (response.total && response.completed) {+ const progress = Math.round(+ (response.completed / response.total) * 100,+ );+ loadingToast.update({+ id: loadingToast.id,+ title: "pulling embedding model...",+ description: (+ <div>+ <p>downloading nomic-embed-text model: {progress}%</p>+ <p>{response.status}</p>+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ ),+ });+ }+ }+ }++ loadingToast.update({+ id: loadingToast.id,+ title: "model ready",+ description: "embedding model has been downloaded",+ });+ }++ setDeduplicationEnabled(true);+ await updateSettings({+ ...settings!,+ deduplicationEnabled: true,+ });++ toast({+ title: "deduplication enabled",+ description: "content will be deduplicated before processing",+ });+ } catch (error) {+ console.error("error setting up deduplication:", error);+ toast({+ variant: "destructive",+ title: "error",+ description: "failed to setup deduplication",+ });+ setDeduplicationEnabled(false);+ } finally {+ setCheckingModel(false);+ }+ };++ // Add this useEffect to initialize the state from settings+ useEffect(() => {+ if (settings) {+ setDeduplicationEnabled(settings?.deduplicationEnabled || false);+ }+ }, [settings?.deduplicationEnabled]);++return (- <Card className="w-full max-w-4xl ">+ <Card className="w-full max-w-4xl"><CardHeader>- <CardTitle>Notion Settings</CardTitle>+ <CardTitle className="flex items-center">+ <img+ src="https://img.icons8.com/?size=100&id=o1a4zZIDo6W0&format=png&color=000000"+ alt="Notion"+ className="h-6 w-6 mr-2"+ onError={(e) => e.currentTarget.style.display = 'none'}+ />+ Notion Settings+ </CardTitle><CardDescription>- please have chrome install for connecting with notion automatically{" "}- <br />- otherwise you can set it up manually, then click on manual button in- Connect Notion Dropdown menu if you have setup automatically then the- integration will be {INTEGRATION_NAME}+ Configure your Notion integration to start syncing content</CardDescription></CardHeader>+<CardContent>- <div className="space-y-6">- <div className="space-y-4">- <div>- <Label>AI Model</Label>- <OllamaModelsList- defaultValue={settings?.aiModel || ""}- onChange={(model) => {- setLocalSettings({ ...localSettings!, aiModel: model });- }}- disabled={loading}- />- </div>+ <Tabs defaultValue="connection" className="w-full">+ <TabsList className="grid grid-cols-3 mb-4">+ <TabsTrigger value="connection" className="font-medium">+ Connection+ </TabsTrigger>+ <TabsTrigger value="ai" className="font-medium">+ AI & Prompts+ </TabsTrigger>+ <TabsTrigger value="sync" className="font-medium">+ Sync Settings+ </TabsTrigger>+ </TabsList>+ <TabsContent value="connection" className="space-y-4 px-5"><div className="space-y-2">- <Label>Custom Prompt</Label>- <FileSuggestTextarea- value={localSettings?.prompt || settings?.prompt || ""}- setValue={(value) => {- setLocalSettings({ ...localSettings!, prompt: value });- }}- disabled={loading}- />- <p className="text-xs text-muted-foreground">- 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.- <br />- <br />- <strong>- (make sure these pages are shared with the integration)- </strong>- <br />- <br />- if you have connected with notion automatically, then your- integration name will{" "}- <span className="text-red-400">{INTEGRATION_NAME}</span>- </p>- </div>- <div className="space-y-2">- <Label htmlFor="interval">sync interval (minutes)</Label>- <Input- id="interval"- name="interval"- type="number"- min="1"- step="1"- max="60"- defaultValue={settings?.interval ? settings?.interval : 5}- onChange={(e) => {- setLocalSettings({- ...localSettings!,- interval: parseInt(e.target.value),- });- }}- />- </div>- <div className="space-y-2">- <Label>Workspace Name</Label>+ <Label htmlFor="workspace">Workspace Name</Label><Input+ id="workspace"type="text"placeholder="Required"value={settings?.workspace || ""}onChange={(e) =>- updateSettings({ ...settings!, workspace: e.target.value })+ setLocalSettings({+ ...localSettings!,+ workspace: e.target.value,+ })}/>- <p className="text-xs text-muted-foreground">- this is required when you are connecting automatically. you can- find your workspace name{" "}+ <p className="text-xs text-muted-foreground flex items-center gap-1">+ <Info className="h-3 w-3" />+ Required for automatic connection. Visit{" "}<ahref="https://www.notion.so"target="_blank"rel="noopener noreferrer"- className="text-blue-400 underline"+ className="text-blue-400 underline flex items-center">- here+ Notion <ExternalLink className="h-3 w-3 ml-0.5" /></a>+ {" "}to find your workspace name.</p></div>- <div className="space-y-2">- <Label htmlFor="pageSize">Page size</Label>- <Input- id="pageSize"- name="pageSize"- type="number"- defaultValue={settings?.pageSize || 50}- onChange={(e) =>- setLocalSettings({- ...localSettings!,- pageSize: parseInt(e.target.value),- })- }- />- </div>- <div className="space-y-2">- <Label>- Access Token{" "}- <span className="text-xs text-muted-foreground">- (found in your integration page)- </span>- </Label>- <Input- placeholder="Access Token"- value={localSettings?.notion?.accessToken || ""}- onChange={(e) =>- setLocalSettings({- ...localSettings!,- notion: {- databaseId: localSettings?.notion?.databaseId || "",- intelligenceDbId:- localSettings?.notion?.intelligenceDbId || "",- accessToken: e.target.value,- },- })- }- />- <p className="text-xs text-muted-foreground">- you can create integration{" "}- <a- href="https://www.notion.so/my-integrations"- target="_blank"- className="text-blue-400 underline"- >- {" "}- here- </a>{" "}- if you want to do it manually- </p>- </div>- <div className="space-y-2">- <NotionIdInput- label="Database ID"- value={localSettings?.notion?.databaseId || ""}- onChange={(value) =>- setLocalSettings({- ...localSettings!,- notion: {- accessToken: localSettings?.notion?.accessToken || "",- intelligenceDbId:- localSettings?.notion?.intelligenceDbId || "",- databaseId: value,- },- })+ <Accordion type="single" collapsible defaultValue="credentials">+ <AccordionItem value="credentials">+ <AccordionTrigger>Connection Details</AccordionTrigger>+ <AccordionContent className="space-y-4 pt-4">+ <div className="space-y-2">+ <Label>+ Access Token{" "}+ <span className="text-xs text-muted-foreground">+ (from your integration page)+ </span>+ </Label>+ <Input+ placeholder="Access Token"+ value={localSettings?.notion?.accessToken || ""}+ onChange={(e) =>+ setLocalSettings({+ ...localSettings!,+ notion: {+ ...localSettings?.notion,+ accessToken: e.target.value,+ databaseId: localSettings?.notion?.databaseId || "",+ intelligenceDbId: localSettings?.notion?.intelligenceDbId || "",+ },+ })+ }+ />+ <p className="text-xs text-muted-foreground flex items-center gap-1">+ <Info className="h-3 w-3" />+ Create a Notion integration{" "}+ <a+ href="https://www.notion.so/my-integrations"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-400 underline flex items-center"+ >+ here <ExternalLink className="h-3 w-3 ml-0.5" />+ </a>+ </p>+ </div>++ {+ localSettings?.notion?.accessToken && (+ <>+ <div className="space-y-2">+ <NotionDatabaseSelector+ accessToken={localSettings?.notion?.accessToken || ""}+ label="Database ID"+ value={localSettings?.notion?.databaseId || ""}+ onChange={(value) =>+ setLocalSettings({+ ...localSettings!,+ notion: {+ ...localSettings?.notion,+ databaseId: value,+ accessToken: localSettings?.notion?.accessToken || "",+ intelligenceDbId: localSettings?.notion?.intelligenceDbId || "",+ },+ })+ }+ />+ </div>++ <div className="space-y-2">+ <NotionDatabaseSelector+ accessToken={localSettings?.notion?.accessToken || ""}+ label="Intelligence ID"+ value={localSettings?.notion?.intelligenceDbId || ""}+ onChange={(value) =>+ setLocalSettings({+ ...localSettings!,+ notion: {+ ...localSettings?.notion,+ intelligenceDbId: value,+ accessToken: localSettings?.notion?.accessToken || "",+ databaseId: localSettings?.notion?.databaseId || "",+ },+ })+ }+ />+ </div>+ </>+ )}- dialogTitle="Extract Database ID from URL"+ </AccordionContent>+ </AccordionItem>+ </Accordion>++ <div className="flex flex-col sm:flex-row gap-3 justify-between items-center mt-6">+ <NotionConnectButton+ isAutoDisabled={isSettingUp || !settings?.workspace}+ isManualDisabled={isSettingUp || !isManualConnectionReady}+ handleAuto={handleSetup}+ handleManual={handleValidate}+ isLoading={isSettingUp}/>++ {isConnected && (+ <div className="flex gap-2">+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleTestLog}+ disabled={testingLog}+ variant="secondary"+ size="sm"+ >+ {testingLog ? (+ <>+ <Loader2 className="mr-2 h-3 w-3 animate-spin" />+ Testing+ </>+ ) : (+ "Test Log"+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Create a test log entry in your Notion database</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>++ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleTestIntelligence}+ disabled={testingIntelligence}+ variant="secondary"+ size="sm"+ >+ {testingIntelligence ? (+ <>+ <Loader2 className="mr-2 h-3 w-3 animate-spin" />+ Analyzing+ </>+ ) : (+ "Test Intelligence"+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Test the intelligence generation functionality</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ )}</div>- <div className="space-y-2">- <NotionIdInput- label="Intelligence ID"- value={localSettings?.notion?.intelligenceDbId || ""}- onChange={(value) =>- setLocalSettings({- ...localSettings!,- notion: {- accessToken: localSettings?.notion?.accessToken || "",- databaseId: localSettings?.notion?.databaseId || "",- intelligenceDbId: value,- },- })- }- dialogTitle="Extract Intelligence Database ID from URL"- />++ {renderConnectionStatus()}+ </TabsContent>++ <TabsContent value="ai" className="space-y-6">+ <div className="space-y-6">+ <div className="grid grid-cols-1 gap-4">+ <div className="flex items-center gap-2 mb-2">+ <Brain className="h-4 w-4 text-primary" />+ <h3 className="text-lg font-medium">AI Models</h3>+ </div>++ <div className="space-y-4 p-4 bg-card rounded-lg border shadow-sm">+ <h4 className="text-sm font-medium">Intelligence (Long-term)</h4>+ <AIPresetsSelector+ pipeName="notion"+ aiKey="aiPresetId"+ />+ <p className="text-xs text-muted-foreground">+ Select an AI model preset for intelligence generation+ </p>+ </div>++ <div className="space-y-4 p-4 bg-card rounded-lg border shadow-sm">+ <h4 className="text-sm font-medium">Logs (Short-term)</h4>+ <AIPresetsSelector+ pipeName="notion"+ aiKey="aiLogPresetId"+ />+ <p className="text-xs text-muted-foreground">+ Select an AI model preset for daily log generation+ </p>+ </div>+ </div>++ <Separator className="my-4" />++ <div className="grid grid-cols-2 gap-6">+ {/* Custom Prompt Section */}+ <div className="space-y-4 col-span-2">+ <div className="flex items-center gap-2">+ <Clock className="h-4 w-4 text-blue-500" />+ <h3 className="text-base font-medium">Custom Prompt</h3>+ </div>++ <div className="space-y-2 bg-muted/40 p-4 rounded-lg">+ <Label>Custom Prompt</Label>+ <FileSuggestTextarea+ value={localSettings?.prompt || settings?.prompt || ""}+ setValue={(value) => {+ setLocalSettings({+ ...localSettings!,+ prompt: value+ });+ }}+ disabled={loading}+ placeholder="Enter a prompt for generating daily logs (short tasks)"+ />+ <div className="text-xs text-muted-foreground p-2 bg-muted rounded-md mt-2">+ <p className="font-medium mb-1">Tips for log prompts:</p>+ <ul className="list-disc list-inside space-y-1">+ <li>Keep prompts concise for daily activity logs</li>+ <li>Focus on capturing key activities and time tracking</li>+ <li>Ideal for short, frequent updates</li>+ </ul>+ </div>+ </div>+ </div>+ </div></div>+ </TabsContent>- <div className="flex justify-between items-center">- <div className="flex gap-5 items-center">- <NotionConnectButton- isAutoDisabled={isSettingUp || !settings?.workspace}- isManualDisabled={- isSettingUp ||- !localSettings?.notion?.accessToken ||- !localSettings?.notion?.databaseId ||- !localSettings?.notion?.intelligenceDbId+ <TabsContent value="sync" className="space-y-6">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label htmlFor="interval">Sync Interval (long-term) (hours)</Label>+ <Input+ id="interval"+ name="interval"+ type="number"+ min="1"+ step="1"+ max="24"+ defaultValue={settings?.interval ? settings?.interval : 5}+ onChange={(e) => {+ setLocalSettings({+ ...localSettings!,+ interval: parseInt(e.target.value) || 1,+ });+ }}+ />+ <p className="text-xs text-muted-foreground">+ How often to sync with Notion (1-60 minutes)+ </p>+ </div>++ <div className="space-y-2">+ <Label htmlFor="pageSize">Page Size</Label>+ <Input+ id="pageSize"+ name="pageSize"+ type="number"+ defaultValue={settings?.pageSize || 50}+ min="10"+ max="100"+ onChange={(e) =>+ setLocalSettings({+ ...localSettings!,+ pageSize: parseInt(e.target.value) || 50,+ })}- handleAuto={handleSetup}- handleManual={handleValidate}- isLoading={isSettingUp}/>+ <p className="text-xs text-muted-foreground">+ Number of items to fetch per sync (10-100)+ </p></div>- {settings?.notion && (- <div className="flex gap-2 mt-4">- <Button- onClick={handleTestLog}- disabled={testingLog}- variant="secondary"- >- {testingLog ? (- <>- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- Testing Log- </>- ) : (- "Test Log"- )}- </Button>-- <Button- onClick={handleTestIntelligence}- disabled={testingIntelligence}- variant="secondary"- >- {testingIntelligence ? (- <>- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- Analyzing- </>- ) : (- "Test Intelligence"- )}- </Button>- </div>- )}- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <Button- onClick={handleSaveSettings}- disabled={loading}- variant="outline"- >- Save Settings- </Button>- </TooltipTrigger>- <TooltipContent>- <p>- Saves AI model, prompt, interval, and page size settings- only+ <div className="space-y-2">+ <Label htmlFor="shortTasksInterval"> Sync Interval (short-term) (minutes)</Label>+ <Input+ id="shortTasksInterval"+ name="shortTasksInterval"+ type="number"+ min="1"+ step="1"+ max="60"+ defaultValue={settings?.shortTasksInterval || 5}+ onChange={(e) => {+ setLocalSettings({+ ...localSettings!,+ shortTasksInterval: parseInt(e.target.value) || 1,+ });+ }}+ />+ </div>++ <div className="flex flex-col space-x-2 space-y-2">+ <div className="flex items-center space-x-2 pt-5">+ <Switch+ id="deduplication"+ checked={deduplicationEnabled}+ disabled={checkingModel || !Boolean(isConnectedToNotion)}+ onCheckedChange={async (checked) => {+ if (checked) {+ await setupDeduplication();+ } else {+ setDeduplicationEnabled(false);+ await updateSettings({+ ...settings!,+ deduplicationEnabled: false,+ });+ }+ }}+ />+ <Label htmlFor="deduplication" className="text-sm">+ {checkingModel ? (+ <span className="flex items-center gap-2">+ <Loader2 className="h-4 w-4 animate-spin" />+ downloading model...+ </span>+ ) : (+ "deduplicate similar content before processing"+ )}+ </Label>++ </div>+ <p className="text-xs text-muted-foreground">+ uses embeddings to remove duplicate content, it will+ download the <code>nomic-embed-text</code> model if it is+ not already downloaded</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>+ </div>+</div>- </div>- </div>+ </TabsContent>+ </Tabs></CardContent>++ <CardFooter className="flex justify-end border-t p-4 mt-4">+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={handleSaveSettings}+ disabled={loading}+ className="min-w-[120px]"+ >+ {loading ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ Saving...+ </>+ ) : (+ "Save Settings"+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Save all current settings</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </CardFooter></Card>);}@@ -495,16 +868,35 @@ const NotionConnectButton = ({<DropdownMenu><DropdownMenuTrigger asChild><Button disabled={isLoading} className="group">- {isLoading ? "Connecting..." : "Connect Notion"}- <ChevronDown className="group-aria-expanded:rotate-180 transition duration-200" />+ {isLoading ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ Connecting...+ </>+ ) : (+ <>+ Connect Notion+ <ChevronDown className="ml-2 h-4 w-4 group-aria-expanded:rotate-180 transition duration-200" />+ </>+ )}</Button></DropdownMenuTrigger><DropdownMenuContent>- <DropdownMenuItem onClick={handleAuto} disabled={isAutoDisabled}>+ <DropdownMenuItem+ onClick={handleAuto}+ disabled={isAutoDisabled}+ className={isAutoDisabled ? "opacity-50 cursor-not-allowed" : ""}+ >Automatic+</DropdownMenuItem>- <DropdownMenuItem onClick={handleManual} disabled={isManualDisabled}>+ <DropdownMenuItem+ onClick={handleManual}+ disabled={isManualDisabled}+ className={isManualDisabled ? "opacity-50 cursor-not-allowed" : ""}+ >Manual+ <span className="text-xs ml-2 text-muted-foreground">(Recommended)</span></DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/pipes/notion/src/components/notion-url-to-input.tsx b/pipes/notion/src/components/notion-url-to-input.tsxindex d44ff20dc..7ac5cd4c1 100644--- a/pipes/notion/src/components/notion-url-to-input.tsx+++ b/pipes/notion/src/components/notion-url-to-input.tsx@@ -8,7 +8,10 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Button } from "@/components/ui/button";import { toast } from "@/hooks/use-toast";-import { useState } from "react";+import { useEffect, useState } from "react";+import { getAvailableDatabases } from "@/lib/notion/notion";+import { NotionCredentials } from "@/lib/types";+import { Select, SelectItem, SelectTrigger, SelectValue, SelectContent } from "@/components/ui/select";interface NotionIdInputProps {label: string;@@ -95,3 +98,66 @@ export function NotionIdInput({</div>);}++interface NotionDatabaseSelectorProps {+ label: string;+ value: string;+ onChange: (value: string) => void;+ accessToken: string;+}++interface Database {+ id: string;+ title: string;+}++export function NotionDatabaseSelector({+ label,+ value,+ onChange,+ accessToken,+}: NotionDatabaseSelectorProps) {+ const [databases, setDatabases] = useState<Database[]>([]);+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ const fetchDatabases = async () => {+ if (!accessToken) return;+ setIsLoading(true);+ try {+ const databases = await getAvailableDatabases(accessToken);+ setDatabases(databases);+ } finally {+ setIsLoading(false);+ }+ };+ fetchDatabases();+ }, [accessToken]);+++ return (+ <div className="space-y-2">+ <Label>{label}</Label>+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger>+ <SelectValue placeholder={isLoading ? "Loading databases..." : label}>+ {isLoading ? "Loading..." : databases.find(db => db.id.replaceAll("-", "") === value.replaceAll("-", ""))?.title || label}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {isLoading ? (+ <SelectItem value="loading">Loading...</SelectItem>+ ) : databases.length > 0 ? (+ databases.map((database) => (+ <SelectItem key={database.id} value={database.id}>+ {database.title}+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-databases">No databases found</SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>+ )+}diff --git a/pipes/notion/src/lib/actions/update-pipe-config.ts b/pipes/notion/src/lib/actions/update-pipe-config.tsindex 7f9657b58..1d8259003 100644--- a/pipes/notion/src/lib/actions/update-pipe-config.ts+++ b/pipes/notion/src/lib/actions/update-pipe-config.ts@@ -2,7 +2,7 @@import { promises as fs } from "fs";import path from "path";-export async function updatePipeConfig(intervalMinutes: number) {+export async function updatePipeConfig(interval: number, apiPath: string, schedule: "minute" | "hour" | "day") {try {const screenpipeDir =process.env.SCREENPIPE_DIR ||@@ -30,23 +30,17 @@ export async function updatePipeConfig(intervalMinutes: number) {config = { crons: [] };}- // Update cron config- config.crons = [- {- path: "/api/log",- schedule: `0 */${intervalMinutes} * * * *`,- },- {- path: "/api/intelligence",- schedule: "0 0 */1 * * *",- },- ];+ // get schedule from schedule+ const scheduleTimer = schedule === "minute" ? `0 */${interval} * * * *` : schedule === "hour" ? `0 0 */${interval} * * *` : `0 0 0 */${interval} * *`;++ config.crons = config.crons.map((cron: any) => cron.path === apiPath ? { ...cron, schedule: scheduleTimer } : cron);+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`+ `updated cron schedule to run every ${interval} ${schedule} for ${apiPath}`);} 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 ba79159fc..4a40b87c5 100644--- a/pipes/notion/src/lib/helpers.ts+++ b/pipes/notion/src/lib/helpers.ts@@ -1,11 +1,13 @@import { ContentItem } from "@screenpipe/js";import { WorkLog } from "./types";-import { generateObject } from "ai";+import { embed } from "ai";import { ollama } from "ollama-ai-provider";import { z } from "zod";import { Client } from "@notionhq/client";import { NotionToMarkdown } from "notion-to-md";-import { getScreenpipeAppSettings } from "./actions/get-screenpipe-app-settings";+import { settingsStore } from "./store/settings-store";+import OpenAI from "openai";+import { zodResponseFormat } from "openai/helpers/zod.mjs";export const workLog = z.object({title: z.string(),@@ -18,11 +20,11 @@ async function extractLinkedContent(prompt: string): Promise<string> {// Match @[[file]] or @[[folder/file]] patternsconst linkRegex = /@\[\[(.*?)\]\]/g;const matches = [...prompt.matchAll(linkRegex)];- const settings = await getScreenpipeAppSettings();+ const settings = await settingsStore.loadPipeSettings("notion");let enrichedPrompt = prompt;const notion = new Client({- auth: settings?.customSettings?.notion?.accessToken,+ auth: settings?.notion?.accessToken,});const n2m = new NotionToMarkdown({ notionClient: notion });@@ -50,41 +52,56 @@ async function extractLinkedContent(prompt: string): Promise<string> {export async function generateWorkLog(screenData: ContentItem[],- model: string,+ aiPreset: ReturnType<typeof settingsStore.getPreset>,startTime: Date,endTime: Date,customPrompt?: string): Promise<WorkLog> {- let enrichedPrompt = customPrompt || "";++ if (!aiPreset) {+ throw new Error("ai preset not found");+ }++ let enrichedPrompt = customPrompt || aiPreset.prompt || "";if (customPrompt) {enrichedPrompt = await extractLinkedContent(customPrompt);}- const defaultPrompt = `Based on the following screen data, generate a concise work activity log entry.- Rules:- - use the screen data to generate the log entry- - focus on describing the activity and tags- - use the following context to better understand the user's goals and priorities:+ const defaultPrompt = `You are a helpful assistant that analyzes the following screen data and generates an accurate work activity log entry.++ Instructions:+ - Carefully examine the screen data to identify the main activities performed+ - Extract specific application names, websites visited, and documents worked on+ - Create a precise, factual description of the work completed+ - Identify relevant tags based on the actual content (projects, tools, topics)+ - Use the following context to understand the user's goals and priorities:${enrichedPrompt}Screen data: ${JSON.stringify(screenData)}- Return a JSON object with:+ Return a valid JSON object with exactly this structure:{- "title": "Brief title of the activity",- "description": "Concise description of what was done",- "tags": ["#tag1", "#tag2", "#tag3"]- }`;+ "title": "Specific, accurate title reflecting the main activity",+ "description": "Detailed but concise description of what was accomplished, mentioning specific tools and content",+ "tags": ["#relevant_tag1", "#relevant_tag2", "#relevant_tag3"]+ }++ Ensure the JSON is properly formatted and contains only the requested fields.`;console.log("enrichedPrompt prompt:", enrichedPrompt);- const provider = ollama(model);- const response = await generateObject({- model: provider,+ const openai = new OpenAI({+ apiKey: aiPreset.apiKey,+ baseURL: aiPreset.url,+ dangerouslyAllowBrowser: true,+ });++ const response = await openai.chat.completions.create({+ model: aiPreset.model,messages: [{ role: "user", content: defaultPrompt }],- schema: workLog,+ response_format: zodResponseFormat(workLog, "workLog"),});const formatDate = (date: Date) => {@@ -99,8 +116,77 @@ export async function generateWorkLog(};return {- ...response.object,+ ...JSON.parse(response.choices[0].message.content || "{}"),startTime: formatDate(startTime),endTime: formatDate(endTime),};}++function cosineSimilarity(a: number[], b: number[]): number {+ const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);+ const normA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));+ const normB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));+ return dotProduct / (normA * normB);+}++export async function deduplicateScreenData(+ screenData: ContentItem[],+): Promise<ContentItem[]> {+ if (!screenData.length) return screenData;++ try {+ const provider = ollama.embedding("nomic-embed-text");+ const embeddings: number[][] = [];+ const uniqueData: ContentItem[] = [];+ let duplicatesRemoved = 0;++ for (const item of screenData) {+ const textToEmbed =+ "content" in item+ ? typeof item.content === "string"+ ? item.content+ : "text" in item.content+ ? item.content.text+ : JSON.stringify(item.content)+ : "";++ if (!textToEmbed.trim()) {+ uniqueData.push(item);+ continue;+ }++ try {+ const { embedding } = await embed({+ model: provider,+ value: textToEmbed,+ });++ let isDuplicate = false;+ for (let i = 0; i < embeddings.length; i++) {+ const similarity = cosineSimilarity(embedding, embeddings[i]);+ if (similarity > 0.95) {+ isDuplicate = true;+ duplicatesRemoved++;+ break;+ }+ }++ if (!isDuplicate) {+ embeddings.push(embedding);+ uniqueData.push(item);+ }+ } catch (error) {+ console.warn("embedding failed for item, keeping it:", error);+ uniqueData.push(item);+ }+ }++ console.log(+ `deduplication: removed ${duplicatesRemoved} duplicates from ${screenData.length} items`,+ );+ return uniqueData;+ } catch (error) {+ console.warn("deduplication failed, using original data:", error);+ return screenData;+ }+}diff --git a/pipes/notion/src/lib/hooks/use-pipe-settings.ts b/pipes/notion/src/lib/hooks/use-pipe-settings.tsnew file mode 100644index 000000000..000ce1686--- /dev/null+++ b/pipes/notion/src/lib/hooks/use-pipe-settings.ts@@ -0,0 +1,37 @@+import { useState, useEffect } from "react";+import { settingsStore, PipeSettings } from "@/lib/store/settings-store";++export function usePipeSettings(pipeName: string) {+ const [settings, setSettings] = useState<Partial<PipeSettings> | null>(+ settingsStore.getStore().pipeSettings[pipeName] || null,+ );+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const loadSettings = async () => {+ setLoading(true);+ await settingsStore.loadPipeSettings(pipeName);+ setLoading(false);+ };++ loadSettings();++ const unsubscribe = settingsStore.subscribe(() => {+ setSettings(settingsStore.getStore().pipeSettings[pipeName] || null);+ });++ return () => {+ unsubscribe();+ };+ }, [pipeName]);++ const updateSettings = async (newSettings: Partial<PipeSettings>) => {+ return settingsStore.updatePipeSettings(pipeName, newSettings);+ };++ const getPreset = (key: keyof PipeSettings = "aiPresetId") => {+ return settingsStore.getPreset(pipeName, key);+ };++ return { settings, updateSettings, loading, getPreset };+}diff --git a/pipes/notion/src/lib/hooks/use-pipe-settings.tsx b/pipes/notion/src/lib/hooks/use-pipe-settings.tsxdeleted file mode 100644index 34fb6a166..000000000--- a/pipes/notion/src/lib/hooks/use-pipe-settings.tsx+++ /dev/null@@ -1,112 +0,0 @@-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:-- 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 STORAGE_KEY = "notion-settings";--export function useNotionSettings() {- const [settings, setSettings] = useState<Partial<Settings> | null>(null);- const [loading, setLoading] = useState(true);-- useEffect(() => {- loadSettings();- }, []);-- const loadSettings = async () => {- try {- // Load screenpipe app settings- const screenpipeSettings = await getScreenpipeAppSettings();-- console.log(screenpipeSettings);- // Load notion settings from localStorage- // const storedSettings = localStorage.getItem(STORAGE_KEY);- // const notionSettings = storedSettings- // ? JSON.parse(storedSettings)- // : {- // ...(screenpipeSettings.customSettings?.notion && {- // ...screenpipeSettings.customSettings?.notion,- // }),- // };- const notionSettings = {- ...(screenpipeSettings.customSettings?.notion && {- ...screenpipeSettings.customSettings?.notion,- }),- };-- // 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, ...notionSettings } = newSettings;-- // Update notion settings in localStorage- const mergedNotionSettings = {- ...DEFAULT_SETTINGS,- ...notionSettings,- };-- // Update screenpipe settings if provided- await updateScreenpipeAppSettings({- ...screenpipeAppSettings,- customSettings: {- ...screenpipeAppSettings?.customSettings,- notion: notionSettings,- },- });-- // 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);- return false;- }- };-- return { settings, updateSettings, loading };-}diff --git a/pipes/notion/src/lib/hooks/use-settings.ts b/pipes/notion/src/lib/hooks/use-settings.tsnew file mode 100644index 000000000..02745685b--- /dev/null+++ b/pipes/notion/src/lib/hooks/use-settings.ts@@ -0,0 +1,42 @@+import { useState, useEffect } from "react";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";+import { Settings as PipeSettingsFromTypes } from "@/lib/types";+import { settingsStore, PipeSettings } from "@/lib/store/settings-store";++export function useSettings() {+ const [settings, setSettings] =+ useState<Partial<ScreenpipeAppSettings> | null>(+ settingsStore.getStore().globalSettings,+ );+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ const loadSettings = async () => {+ setLoading(true);+ await settingsStore.loadGlobalSettings();+ setLoading(false);+ };++ loadSettings();++ const unsubscribe = settingsStore.subscribe(() => {+ setSettings(settingsStore.getStore().globalSettings);+ });++ return () => {+ unsubscribe();+ };+ }, []);++ const updateSettings = async (+ newSettings: Partial<ScreenpipeAppSettings>,+ ) => {+ return settingsStore.updateGlobalSettings(newSettings);+ };++ return { settings, updateSettings, loading };+}diff --git a/pipes/notion/src/lib/notion/notion.ts b/pipes/notion/src/lib/notion/notion.tsindex 81abe27ba..a1de6b133 100644--- a/pipes/notion/src/lib/notion/notion.ts+++ b/pipes/notion/src/lib/notion/notion.ts@@ -2,7 +2,7 @@import { Client } from "@notionhq/client";import { WorkLog, Intelligence, NotionCredentials } from "@/lib/types";-import { BlockObjectRequest } from "@notionhq/client/build/src/api-endpoints";+import { BlockObjectRequest, DatabaseObjectResponse } from "@notionhq/client/build/src/api-endpoints";export async function validateCredentials(credentials: NotionCredentials,@@ -293,3 +293,21 @@ function generateInsightsSection(return blocks;}++export async function getAvailableDatabases(accessToken: string) {+ const client = new Client({ auth: accessToken });+ const databases = await client.search({+ query: "",+ filter: {+ property: "object",+ value: "database",+ },+ });+ return databases.results+ .filter((database): database is DatabaseObjectResponse =>+ database.object === "database" && "title" in database)+ .map((database) => ({+ id: database.id,+ title: database.title[0].plain_text,+ }));+}diff --git a/pipes/notion/src/lib/store/settings-store.ts b/pipes/notion/src/lib/store/settings-store.tsnew file mode 100644index 000000000..a12c8ebc5--- /dev/null+++ b/pipes/notion/src/lib/store/settings-store.ts@@ -0,0 +1,229 @@+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";+import { Settings as PipeSettingsFromTypes } from "@/lib/types";++export interface PipeSettings extends PipeSettingsFromTypes {+ shortTasksInterval: number;+ exampleSetting: string;+ aiLogPresetId: string;+ aiPresetId: string;+ deduplicationEnabled: boolean;+}++type AIPreset = ScreenpipeAppSettings["aiPresets"][number];++const DEFAULT_SETTINGS: Partial<PipeSettings> = {+ 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`,+};++type Listener = () => void;++type Store = {+ globalSettings: Partial<ScreenpipeAppSettings> | null;+ pipeSettings: Record<string, Partial<PipeSettings> | null>;+};++export class SettingsStore {+ private store: Store = {+ globalSettings: null,+ pipeSettings: {},+ };+ private listeners: Set<Listener> = new Set();++ // get the store+ getStore() {+ return this.store;+ }++ // subscribe to changes in the store+ subscribe(listener: Listener) {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ // notify the listeners that the store has changed+ private notify() {+ this.listeners.forEach((listener) => listener());+ }++ // set the global settings+ async setGlobalSettings(settings: Partial<ScreenpipeAppSettings> | null) {+ this.store.globalSettings = settings;+ this.notify();+ }++ // set the pipe settings+ async setPipeSettings(+ pipeName: string,+ settings: Partial<PipeSettings> | null,+ ) {+ this.store.pipeSettings[pipeName] = settings;+ this.notify();+ }++ // load the global settings+ async loadGlobalSettings() {+ try {+ const screenpipeSettings = await getScreenpipeAppSettings();+ this.setGlobalSettings(screenpipeSettings);+ return screenpipeSettings;+ } catch (error) {+ console.error("failed to load global settings:", error);+ return null;+ }+ }++ // update the global settings+ async updateGlobalSettings(newSettings: Partial<ScreenpipeAppSettings>) {+ try {+ const mightBeUpdated = await getScreenpipeAppSettings();++ const updatedSettings = {+ ...mightBeUpdated,+ ...newSettings,+ };++ await updateScreenpipeAppSettings(updatedSettings);+ this.setGlobalSettings(updatedSettings);+ return true;+ } catch (error) {+ console.error("failed to update global settings:", error);+ return false;+ }+ }++ // load the pipe settings+ async loadPipeSettings(pipeName: string): Promise<PipeSettings | null> {+ try {+ const screenpipeSettings = await getScreenpipeAppSettings();++ // if global settings are not loaded, load them+ if (!this.store.globalSettings) {+ await this.loadGlobalSettings();+ }++ const settings = {+ ...DEFAULT_SETTINGS,+ ...screenpipeSettings.customSettings?.[pipeName],+ };+ this.setPipeSettings(pipeName, settings);+ return settings;+ } catch (error) {+ console.error("failed to load pipe settings:", error);+ return null;+ }+ }++ // update the pipe settings+ async updatePipeSettings(+ pipeName: string,+ newSettings: Partial<PipeSettings>,+ ) {+ try {+ // get the current settings+ const mightBeUpdated = await getScreenpipeAppSettings();++ const updatedSettings = {+ ...mightBeUpdated,+ customSettings: {+ ...(mightBeUpdated.customSettings || {}),+ [pipeName]: {+ ...(mightBeUpdated.customSettings?.[pipeName] || {}),+ ...newSettings,+ },+ },+ };++ await updateScreenpipeAppSettings(updatedSettings);+ this.setGlobalSettings(updatedSettings);+ this.setPipeSettings(pipeName, {+ ...(mightBeUpdated.customSettings?.[pipeName] || {}),+ ...newSettings,+ });+ return true;+ } catch (error) {+ console.error("failed to update pipe settings:", error);+ return false;+ }+ }++ // get the preset+ getPreset(+ pipeName: string,+ key: keyof PipeSettings = "aiPresetId",+ ): (AIPreset & { apiKey: string }) | undefined {+ try {+ const presetId = this.store.pipeSettings[pipeName]?.[key];+ const screenpipeSettings = this.store.globalSettings;++ let preset: AIPreset | undefined;++ if (presetId) {+ preset = screenpipeSettings?.aiPresets?.find(+ (preset) => preset.id === presetId,+ );+ }++ if (!preset) {+ preset = screenpipeSettings?.aiPresets?.find(+ (preset) => preset.defaultPreset,+ );+ }++ if (!preset) {+ return undefined;+ }++ // Handle different provider types that may have apiKey+ const apiKey =+ "provider" in preset && preset.provider === "screenpipe-cloud"+ ? screenpipeSettings?.user?.token || ""+ : "provider" in preset && "apiKey" in preset+ ? (preset.apiKey as string) || ""+ : "";++ return {+ id: preset.id,+ maxContextChars: preset.maxContextChars,+ url: preset.url,+ model: preset.model,+ defaultPreset: preset.defaultPreset,+ prompt: preset.prompt,+ provider: preset.provider,+ apiKey,+ };+ } catch (error) {+ console.error("failed to get preset:", error);+ return undefined;+ }+ }+}++export const settingsStore = new SettingsStore();\ No newline at end of filediff --git a/pipes/notion/src/lib/types.ts b/pipes/notion/src/lib/types.tsindex 2b8c6502a..1469933ce 100644--- a/pipes/notion/src/lib/types.ts+++ b/pipes/notion/src/lib/types.ts@@ -45,5 +45,7 @@ export interface Settings {backend: "notion";notion: NotionCredentials;prompt: string;+ logPrompt: string;+ longTaskPrompt: string;screenpipeAppSettings: ScreenpipeAppSettings;}