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
Add ai preset to pipes (#1645)
shaik-zeeshan04a85cac4f24
diff --git a/pipes/data-table/bun.lockb b/pipes/data-table/bun.lockbindex 31ebf9cc7..684cfbdca 100755Binary files a/pipes/data-table/bun.lockb and b/pipes/data-table/bun.lockb differdiff --git a/pipes/data-table/package.json b/pipes/data-table/package.jsonindex 5a4fe9467..65eee2841 100644--- a/pipes/data-table/package.json+++ b/pipes/data-table/package.json@@ -14,18 +14,18 @@"@radix-ui/react-checkbox": "^1.1.3","@radix-ui/react-dialog": "^1.1.6","@radix-ui/react-dropdown-menu": "^2.1.3",- "@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-slider": "^1.2.3",+ "@radix-ui/react-slot": "^1.1.2","@radix-ui/react-switch": "^1.1.2","@radix-ui/react-toast": "^1.2.3",- "@radix-ui/react-tooltip": "^1.1.5",- "@screenpipe/browser": "^0.1.28",- "@screenpipe/js": "^1.0.12",+ "@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","@tanstack/react-table": "^8.20.6",@@ -35,7 +35,7 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "1.0.4",+ "cmdk": "1.0.0","date-fns": "^4.1.0","framer-motion": "^11.14.4","install": "^0.13.0",@@ -45,6 +45,7 @@"lucide-react": "^0.468.0","magic-ui": "^0.1.0","next": "15.1.0",+ "next-themes": "^0.4.6","npm": "^10.9.2","openai": "^4.76.3","react": "^19.0.0",@@ -55,6 +56,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/data-table/src/components/ai-presets-selector.tsx b/pipes/data-table/src/components/ai-presets-selector.tsxnew file mode 100644index 000000000..3ab695de7--- /dev/null+++ b/pipes/data-table/src/components/ai-presets-selector.tsx@@ -0,0 +1,1302 @@+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings, type PipeSettings } from "@/lib/hooks/use-settings";+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} modal={false}>+ <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"+ role="combobox"+ >+ <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) => {+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset ? "" : currentValue,+ });+ 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/data-table/src/components/search-command.tsx b/pipes/data-table/src/components/search-command.tsxindex 8f279142c..26e8d29f9 100644--- a/pipes/data-table/src/components/search-command.tsx+++ b/pipes/data-table/src/components/search-command.tsx@@ -2,13 +2,16 @@import * as React from "react";import { useState } from "react";-import { Search, Database, Bot, Copy } from "lucide-react";+import { Database, Bot, Copy } from "lucide-react";import { Button } from "@/components/ui/button";-import { CommandDialog, CommandInput } from "@/components/ui/command";+import {+ CommandDialog,+ CommandInput,+ CommandList,+} from "@/components/ui/command";import OpenAI from "openai";import { toast } from "@/components/ui/use-toast";import { useSettings } from "@/lib/hooks/use-settings";-import { DialogTitle } from "./ui/dialog";import { SheetTitle } from "./ui/sheet";import { Textarea } from "@/components/ui/textarea";import {@@ -26,6 +29,8 @@ import {TooltipProvider,TooltipTrigger,} from "@/components/ui/tooltip";+import { AIPresetsSelector } from "./ai-presets-selector";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";export function SearchCommand() {const [open, setOpen] = useState(false);@@ -33,6 +38,7 @@ export function SearchCommand() {const [sqlQuery, setSqlQuery] = useState("");const [isLoading, setIsLoading] = useState(false);const { settings } = useSettings();+ const { getPreset } = usePipeSettings("data-table");const [results, setResults] = useState<any[]>([]);const [columns, setColumns] = useState<string[]>([]);const [error, setError] = useState<string | null>(null);@@ -61,12 +67,18 @@ export function SearchCommand() {setIsLoading(true);try {+ const aiPreset = getPreset();++ if (!aiPreset) {+ throw Error("please select a preset");+ }+const openai = new OpenAI({apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,+ aiPreset?.provider === "screenpipe-cloud"+ ? settings?.user?.token+ : aiPreset?.apiKey,+ baseURL: aiPreset?.url,dangerouslyAllowBrowser: true,});@@ -96,7 +108,7 @@ export function SearchCommand() {(text, frame_id)- ocr_text_embeddings: vector embeddings(id, frame_id, embedding, created_at)-+2. Audio Recording:- audio_chunks: recorded audio segments(id, file_path, timestamp)@@ -106,13 +118,13 @@ export function SearchCommand() {(transcription, device, audio_chunk_id, speaker_id, start_time, end_time)- speakers: voice identification(id, name, metadata, hallucination)-+3. UI Monitoring:- ui_monitoring: app/window state(id, text_output, timestamp, app, window, initial_traversal_at)- ui_monitoring_fts: optimized UI search(text_output, app, window, ui_id)-+4. Tagging System:- tags: user-defined categories(id, name, created_at)@@ -128,7 +140,7 @@ export function SearchCommand() {- Voice transcriptions: JOIN audio_chunks ac ON at.audio_chunk_id = ac.id- UI events: JOIN ui_monitoring_fts umf ON um.id = umf.ui_id- Tagged content: JOIN tags t ON vt.tag_id = t.id-+Performance Indexes:- frames: timestamp, video_chunk_id- ocr_text: frame_id, app_name, window_name@@ -151,14 +163,17 @@ export function SearchCommand() {];const completion = await openai.chat.completions.create({- model: settings.aiModel,+ model: aiPreset?.model,messages,temperature: 0.3,});let sql = completion.choices[0].message.content!;// Remove SQL code fence markers if present- sql = sql.trim().replace(/```sql\n?|\n?```/g, "").trim();+ sql = sql+ .trim()+ .replace(/```sql\n?|\n?```/g, "")+ .trim();setSqlQuery(sql);// Here you would execute the SQL query@@ -224,7 +239,7 @@ export function SearchCommand() {(row) =>`| ${columns.map((col) => row[col]?.toString() || "N/A")- .join(" | ")} |`+ .join(" | ")} |`,).join("\n");@@ -265,6 +280,10 @@ export function SearchCommand() {}}}/>+ <CommandList></CommandList>+ <div className="w-full">+ <AIPresetsSelector pipeName="data-table" />+ </div><div className="px-4 pb-4"><div className="mt-4 space-y-4"><div className="flex justify-between items-center gap-2">@@ -274,7 +293,7 @@ export function SearchCommand() {<Bot className="h-4 w-4 text-muted-foreground" /></TooltipTrigger><TooltipContent side="right">- <p className="text-xs">using {settings.aiModel}</p>+ <p className="text-xs">using {getPreset()?.model}</p></TooltipContent></Tooltip></TooltipProvider>@@ -305,7 +324,7 @@ export function SearchCommand() {onChange={(e) => setSqlQuery(e.target.value)}className={cn("min-h-[100px] resize-none font-mono",- error && "border-red-500"+ error && "border-red-500",)}onKeyDown={(e) => {if (e.key === "Enter" && e.shiftKey) {diff --git a/pipes/data-table/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/data-table/src/lib/actions/get-screenpipe-app-settings.tsnew file mode 100644index 000000000..608513b37--- /dev/null+++ b/pipes/data-table/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/data-table/src/lib/hooks/use-pipe-settings.tsx b/pipes/data-table/src/lib/hooks/use-pipe-settings.tsxnew file mode 100644index 000000000..0b34c5aeb--- /dev/null+++ b/pipes/data-table/src/lib/hooks/use-pipe-settings.tsx@@ -0,0 +1,40 @@+"use client";++import { useState, useEffect } from "react";+import { settingsStore } from "@/lib/hooks/use-settings";+import type { PipeSettings } from "@/lib/hooks/use-settings";++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/data-table/src/lib/hooks/use-settings.tsx b/pipes/data-table/src/lib/hooks/use-settings.tsxindex 19937b456..347b96e77 100644--- a/pipes/data-table/src/lib/hooks/use-settings.tsx+++ b/pipes/data-table/src/lib/hooks/use-settings.tsx@@ -1,214 +1,235 @@"use client";import { useState, useEffect } from "react";-import { getDefaultSettings, type Settings } from "@screenpipe/browser";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";++export interface PipeSettings {+ exampleSetting: string;+ aiLogPresetId: string;+ aiPresetId: string;+}++type AIPreset = ScreenpipeAppSettings["aiPresets"][number];++export const DEFAULT_SETTINGS: Partial<PipeSettings> = {+ exampleSetting: "default value",+};++type Listener = () => void;++type Store = {+ globalSettings: Partial<ScreenpipeAppSettings> | null;+ pipeSettings: Record<string, Partial<PipeSettings> | null>;+};++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);+ this.notify();+ return true;+ } catch (error) {+ console.error("failed to update global settings:", error);+ return false;+ }+ }++ // load the pipe settings+ async loadPipeSettings(pipeName: string) {+ try {+ const screenpipeSettings = await getScreenpipeAppSettings();+ 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();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>(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,- };+ 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/data-table/src/lib/types.ts b/pipes/data-table/src/lib/types.tsnew file mode 100644index 000000000..bc41e7f19--- /dev/null+++ b/pipes/data-table/src/lib/types.ts@@ -0,0 +1,38 @@+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 {+ prompt: string;+ vaultPath: string;+ logTimeWindow: number;+ logPageSize: number;+ logModel: string;+ analysisModel: string;+ analysisTimeWindow: number;+ deduplicationEnabled: boolean;+ screenpipeAppSettings: ScreenpipeAppSettings;+}diff --git a/pipes/obsidian/bun.lockb b/pipes/obsidian/bun.lockbindex 31348d45b..5d74371ee 100755Binary files a/pipes/obsidian/bun.lockb and b/pipes/obsidian/bun.lockb differdiff --git a/pipes/obsidian/package.json b/pipes/obsidian/package.jsonindex 631161135..915cd6ef7 100644--- a/pipes/obsidian/package.json+++ b/pipes/obsidian/package.json@@ -11,20 +11,20 @@"dependencies": {"@radix-ui/react-accordion": "^1.2.2","@radix-ui/react-checkbox": "^1.1.3",- "@radix-ui/react-dialog": "^1.1.4",- "@radix-ui/react-label": "^2.1.1",- "@radix-ui/react-popover": "^1.1.3",+ "@radix-ui/react-dialog": "^1.1.6",+ "@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-slider": "^1.2.3",+ "@radix-ui/react-slot": "^1.1.2","@radix-ui/react-switch": "^1.1.2","@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.28",- "@screenpipe/js": "1.0.12",+ "@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",@@ -33,7 +33,7 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "1.0.4",+ "cmdk": "1.0.0","date-fns": "^4.1.0","framer-motion": "^11.14.4","install": "^0.13.0",@@ -43,6 +43,7 @@"lucide-react": "^0.468.0","magic-ui": "^0.1.0","next": "15.1.0",+ "next-themes": "^0.4.6","npm": "^10.9.2","ollama-ai-provider": "^1.1.0","openai": "^4.76.3",@@ -53,6 +54,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/obsidian/src/app/api/intelligence/route.ts b/pipes/obsidian/src/app/api/intelligence/route.tsindex b5a0db03e..47f80ca99 100644--- a/pipes/obsidian/src/app/api/intelligence/route.ts+++ b/pipes/obsidian/src/app/api/intelligence/route.ts@@ -6,10 +6,12 @@ import { pipe } from "@screenpipe/js";import * as fs from "fs/promises";import * as path from "path";import { extractLinkedContent } from "@/lib/actions/obsidian";+import { settingsStore } from "@/lib/store/settings-store";+import { OpenAI } from "openai";async function readRecentLogs(obsidianPath: string,- since: Date+ since: Date,): Promise<string> {const logsPath = path.join(path.normalize(obsidianPath), "logs");const today = new Date().toISOString().split("T")[0];@@ -32,15 +34,16 @@ async function readRecentLogs(async function analyzeWithLLM(content: string,- prompt: string,- model: string,- obsidianPath?: string-): Promise<any> {- const provider = ollama(model);+ aiPreset: ReturnType<typeof settingsStore.getPreset>,+ obsidianPath?: string,+): Promise<string> {+ if (!aiPreset) {+ throw new Error("ai preset not configured");+ }- let enrichedPrompt = prompt;+ let enrichedPrompt = aiPreset.prompt || "";if (obsidianPath) {- enrichedPrompt = await extractLinkedContent(prompt, obsidianPath);+ enrichedPrompt = await extractLinkedContent(enrichedPrompt, obsidianPath);}const systemPrompt = `You are an intelligent analysis system that processes user activity logs and creates higher-level insights.@@ -68,7 +71,7 @@ Instructions for Media and Formatting:- Add relevant #tags for categorization- Escape any pipe characters (|) in tables with \\|- Do not hallucinate video paths, use the exact video path from the logs-- All your outputs will be written directly in Obsidian note taking app so use the formatting of the app in your response to maximize readability,+- All your outputs will be written directly in Obsidian note taking app so use the formatting of the app in your response to maximize readability,embeding links, videos, etc. usually mp4 needs video html component and not the link format- If you do not know the answer or do not have the right context, say I do not know, do not hallucinate@@ -93,22 +96,29 @@ Analysis Structure:Generate a structured analysis following the above format.`;- console.log("systemPrompt", systemPrompt);+ const openaiConfig = {+ apiKey: aiPreset.apiKey,+ model: aiPreset.model,+ baseURL: aiPreset.url || undefined,+ };++ const openai = new OpenAI(openaiConfig);- const response = await generateText({- model: provider,+ const response = await openai.chat.completions.create({+ model: aiPreset.model,messages: [{ role: "user", content: systemPrompt }],- maxRetries: 5,});+ let transformedText = response.choices[0].message.content || "";+// Transform <think> tags into Obsidian foldable callouts- let transformedText = response.text.replace(+ transformedText = transformedText.replace(/<think>([\s\S]*?)<\/think>/g,(_, content) =>`> [!note]- Thinking Process\n${content.split("\n").map((line: string) => `> ${line}`)- .join("\n")}`+ .join("\n")}`,);// Transform <video> tags to just 'video'@@ -121,7 +131,7 @@ Generate a structured analysis following the above format.`;async function saveMarkdown(content: string,obsidianPath: string,- filename: string+ filename: string,): Promise<string> {const analysesPath = path.join(path.normalize(obsidianPath), "analyses");await fs.mkdir(analysesPath, { recursive: true });@@ -131,24 +141,29 @@ async function saveMarkdown(const vaultName = path.basename(path.resolve(obsidianPath));return `obsidian://open?vault=${encodeURIComponent(- vaultName+ vaultName,)}&file=analyses/${encodeURIComponent(filename)}`;}export async function GET() {try {- const settings = await pipe.settings.getAll();- const obsidianPath = settings.customSettings?.obsidian?.vaultPath;- const model = settings.customSettings?.obsidian?.analysisModel;- const customPrompt = settings.customSettings?.obsidian?.prompt;- const timeWindow =- settings.customSettings?.obsidian?.analysisTimeWindow ||- 1 * 60 * 60 * 1000;+ const settings = await settingsStore.loadPipeSettings("obsidian");+ const obsidianPath = settings.vaultPath;+ const timeWindow = settings.analysisTimeWindow || 1 * 60 * 60 * 1000;++ const aiPreset = settingsStore.getPreset("obsidian", "aiPresetId");++ if (!aiPreset || !aiPreset.model) {+ return NextResponse.json(+ { error: "ai preset not configured" },+ { status: 400 },+ );+ }if (!obsidianPath) {return NextResponse.json({ error: "obsidian path not configured" },- { status: 400 }+ { status: 400 },);}@@ -162,12 +177,7 @@ export async function GET() {}// Analyze with LLM- const analysis = await analyzeWithLLM(- recentLogs,- customPrompt,- model,- obsidianPath- );+ const analysis = await analyzeWithLLM(recentLogs, aiPreset, obsidianPath);// Save results based on output formatconst filename = `${now@@ -186,7 +196,7 @@ export async function GET() {const deepLink = await saveMarkdown("\n" + analysis,obsidianPath,- filename+ filename,);return NextResponse.json({@@ -203,7 +213,7 @@ export async function GET() {console.error("error in intelligence api:", error);return NextResponse.json({ error: `failed to process intelligence: ${error}` },- { status: 500 }+ { status: 500 },);}}diff --git a/pipes/obsidian/src/app/api/log/route.ts b/pipes/obsidian/src/app/api/log/route.tsindex b458c895b..c24e9f299 100644--- a/pipes/obsidian/src/app/api/log/route.ts+++ b/pipes/obsidian/src/app/api/log/route.ts@@ -2,11 +2,13 @@ import { NextResponse } from "next/server";import { z } from "zod";import { embed, generateObject } from "ai";import { ollama } from "ollama-ai-provider";-import { ContentItem } from "@screenpipe/js";+import { AIPreset, ContentItem } from "@screenpipe/js";import { pipe } from "@screenpipe/js";import * as fs from "fs/promises";import * as path from "path";import { extractLinkedContent } from "@/lib/actions/obsidian";+import { settingsStore } from "@/lib/store/settings-store";+import { OpenAI } from "openai";const workLog = z.object({title: z.string(),@@ -21,17 +23,20 @@ type WorkLog = z.infer<typeof workLog> & {};async function generateWorkLog(- screenData: ContentItem[],- model: string,- startTime: Date,- endTime: Date,- customPrompt?: string,- obsidianPath?: string+ data: ContentItem[],+ obsidianPath: string,+ prevTime: Date,+ curTime: Date,+ aiPreset: ReturnType<typeof settingsStore.getPreset>,): Promise<WorkLog> {- let enrichedPrompt = customPrompt || "";+ if (!aiPreset) {+ throw new Error("ai preset not configured");+ }- if (customPrompt && obsidianPath) {- enrichedPrompt = await extractLinkedContent(customPrompt, obsidianPath);+ let enrichedPrompt = aiPreset.prompt || "";++ if (enrichedPrompt && obsidianPath) {+ enrichedPrompt = await extractLinkedContent(enrichedPrompt, obsidianPath);}const defaultPrompt = `You are analyzing screen recording data from Screenpipe, a desktop app that records screens & mics 24/7 to provide context to AI systems.@@ -42,8 +47,8 @@ async function generateWorkLog(Here are some user instructions:${enrichedPrompt}- Screen data: ${JSON.stringify(screenData)}-+ Screen data: ${JSON.stringify(data)}+Rules:- analyze the screen data carefully to understand the user's work context and activities- generate a clear, specific title that reflects the main activity@@ -56,7 +61,7 @@ async function generateWorkLog(- ensure description and content are properly escaped for markdown table cells (use <br> for newlines)- link to people using [[firstname]]- link to concepts using [[concept-name]]-+Example outputs:{"title": "engineering: implemented rust error handling",@@ -87,13 +92,22 @@ async function generateWorkLog("mediaLinks": ["<video src=\"file:///absolute/path/to/video.mp4\" controls></video>"]}`;- const provider = ollama(model);- const response = await generateObject({- model: provider,+ const openaiConfig = {+ apiKey: aiPreset.apiKey,+ model: aiPreset.model,+ baseURL: aiPreset.url || undefined,+ };++ const openai = new OpenAI(openaiConfig);++ const response = await openai.chat.completions.create({+ model: aiPreset.model,messages: [{ role: "user", content: defaultPrompt }],- schema: workLog,+ response_format: { type: "json_object" },});+ const jsonResponse = JSON.parse(response.choices[0].message.content || "{}");+const formatDate = (date: Date) => {return date.toLocaleString("en-US", {year: "numeric",@@ -106,22 +120,22 @@ async function generateWorkLog(};return {- ...response.object,- startTime: formatDate(startTime),- endTime: formatDate(endTime),+ ...jsonResponse,+ startTime: formatDate(prevTime),+ endTime: formatDate(curTime),};}async function syncLogToObsidian(logEntry: WorkLog,- obsidianPath: string+ obsidianPath: string,): Promise<string> {const logsPath = path.join(path.normalize(obsidianPath), "logs");await fs.mkdir(logsPath, { recursive: true });const today = new Date();const filename = `${today.getFullYear()}-${String(- today.getMonth() + 1+ today.getMonth() + 1,).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}.md`;const filePath = path.join(logsPath, filename);@@ -132,13 +146,13 @@ async function syncLogToObsidian(};const timeRange = `${escapeTableCell(logEntry.startTime)} - ${escapeTableCell(- logEntry.endTime+ logEntry.endTime,)}`;// Combine title with timestamp and description with tagsconst titleWithTime = `${escapeTableCell(logEntry.title)}<br>${timeRange}`;const descriptionWithTags = `${escapeTableCell(- logEntry.description+ logEntry.description,)}<br>${escapeTableCell(logEntry.tags.join("<br>"))}`;const tableHeaders = `| Title | Description | Media |\n|-------|-------------|--------|\n`;@@ -164,7 +178,7 @@ async function syncLogToObsidian(await fs.writeFile(filePath,tableHeaders + existingContent + tableRow,- "utf8"+ "utf8",);} else {// Headers exist - append new row while preserving existing content@@ -181,12 +195,12 @@ async function syncLogToObsidian(// Helper function to generate Obsidian URLfunction getObsidianUrl(vaultName: string, filename: string): string {return `obsidian://open?vault=${encodeURIComponent(- vaultName+ vaultName,)}&file=${encodeURIComponent(filename)}`;}async function deduplicateScreenData(- screenData: ContentItem[]+ screenData: ContentItem[],): Promise<ContentItem[]> {if (!screenData.length) return screenData;@@ -202,8 +216,8 @@ async function deduplicateScreenData(? typeof item.content === "string"? item.content: "text" in item.content- ? item.content.text- : JSON.stringify(item.content)+ ? item.content.text+ : JSON.stringify(item.content): "";if (!textToEmbed.trim()) {@@ -238,7 +252,7 @@ async function deduplicateScreenData(}console.log(- `deduplication: removed ${duplicatesRemoved} duplicates from ${screenData.length} items`+ `deduplication: removed ${duplicatesRemoved} duplicates from ${screenData.length} items`,);return uniqueData;} catch (error) {@@ -256,27 +270,32 @@ function cosineSimilarity(a: number[], b: number[]): number {export async function GET() {try {- const settings = await pipe.settings.getAll();- const interval =- settings.customSettings?.obsidian?.logTimeWindow || 3600000;- const obsidianPath = settings.customSettings?.obsidian?.vaultPath;- const customPrompt = settings.customSettings?.obsidian?.prompt;- const pageSize = settings.customSettings?.obsidian?.logPageSize || 100;- const model = settings.customSettings?.obsidian?.logModel;- const deduplicationEnabled =- settings.customSettings?.obsidian?.deduplicationEnabled;+ const settings = await settingsStore.loadPipeSettings("obsidian");+ const interval = settings.logTimeWindow || 3600000;+ const obsidianPath = settings.vaultPath;+ const pageSize = settings.logPageSize || 100;+ const deduplicationEnabled = settings.deduplicationEnabled;++ const aiPreset = settingsStore.getPreset("obsidian", "aiLogPresetId");++ if (!aiPreset || !aiPreset.model) {+ return NextResponse.json(+ { error: "ai preset not configured" },+ { status: 400 },+ );+ }if (!obsidianPath) {return NextResponse.json({ error: "obsidian path not configured" },- { status: 400 }+ { status: 400 },);}const now = new Date();const oneHourAgo = new Date(now.getTime() - interval);- let screenData = await pipe.queryScreenpipe({+ const screenData = await pipe.queryScreenpipe({startTime: oneHourAgo.toISOString(),endTime: now.toISOString(),limit: pageSize,@@ -294,23 +313,22 @@ export async function GET() {} catch (error) {console.warn("deduplication failed, continuing with original data:",- error+ error,);}}const logEntry = await generateWorkLog(screenData.data,- model,+ obsidianPath,oneHourAgo,now,- customPrompt,- obsidianPath+ aiPreset,);const _ = await syncLogToObsidian(logEntry, obsidianPath);await pipe.captureEvent("obsidian_work_log_synced", {- model,+ model: aiPreset?.model,interval,pageSize,});@@ -323,7 +341,7 @@ export async function GET() {console.error("error in work log api:", error);return NextResponse.json({ error: `failed to process work log: ${error}` },- { status: 500 }+ { status: 500 },);}}diff --git a/pipes/obsidian/src/components/ai-presets-selector.tsx b/pipes/obsidian/src/components/ai-presets-selector.tsxnew file mode 100644index 000000000..c497a8cf3--- /dev/null+++ b/pipes/obsidian/src/components/ai-presets-selector.tsx@@ -0,0 +1,1301 @@+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings } from "@/lib/hooks/use-settings";+import type { 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 as keyof typeof pipeSettings],+ );++ 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 as keyof typeof pipeSettings] === 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.preventDefault();+ 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) => {+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset ? "" : currentValue,+ });+ 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/obsidian/src/components/obsidian-settings.tsx b/pipes/obsidian/src/components/obsidian-settings.tsxindex 268aeba4c..532f60f26 100644--- a/pipes/obsidian/src/components/obsidian-settings.tsx+++ b/pipes/obsidian/src/components/obsidian-settings.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useMemo } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -15,12 +15,10 @@ import {Copy,} from "lucide-react";import { useToast } from "@/hooks/use-toast";-import { OllamaModelsList } from "./ollama-models-list";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { Badge } from "@/components/ui/badge";import path from "path";import { FileSuggestTextarea } from "./file-suggest-textarea";-import { Skeleton } from "@/components/ui/skeleton";import { debounce } from "lodash";import { updatePipeConfig } from "@/lib/actions/update-pipe-config";import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";@@ -30,9 +28,17 @@ import remarkMath from "remark-math";import { CodeBlock } from "./ui/codeblock";import { VideoComponent } from "./video";import { Switch } from "@/components/ui/switch";+import { useSettings } from "@/lib/hooks/use-settings";+import { AIPresetsSelector } from "./ai-presets-selector";+import { Skeleton } from "./ui/skeleton";export function ObsidianSettings() {- const { settings, updateSettings, loading } = usePipeSettings();+ const {+ settings: pipeSettings,+ updateSettings,+ getPreset,+ } = usePipeSettings("obsidian");+ const { settings, updateSettings: updateSettings2, loading } = useSettings();const [lastLog, setLastLog] = useState<any>(null);const { toast } = useToast();const [intelligence, setIntelligence] = useState<string | null>(null);@@ -56,11 +62,22 @@ export function ObsidianSettings() {useState<boolean>(false);const [checkingModel, setCheckingModel] = useState<boolean>(false);+ const logPreset = useMemo(+ () => getPreset("aiLogPresetId"),+ [pipeSettings?.aiLogPresetId],+ );+ const intelligencePreset = useMemo(+ () => getPreset("aiPresetId"),+ [pipeSettings?.aiPresetId],+ );+useEffect(() => {- if (settings) {- setCustomPrompt(settings.prompt || "");+ if (pipeSettings) {+ const preset = getPreset("aiLogPresetId");+ console.log("preset", preset?.prompt);+ setCustomPrompt(preset?.prompt || "");}- }, [settings]);+ }, [pipeSettings?.aiLogPresetId]);useEffect(() => {const fetchPaths = async () => {@@ -120,9 +137,31 @@ export function ObsidianSettings() {};await updateSettings({- ...settings!,...obsidianSettings,});++ // update the aiLogPresetId preset prompt+ const logPreset = getPreset("aiLogPresetId");+ const intelligencePreset = getPreset("aiPresetId");++ if (logPreset?.id === intelligencePreset?.id) {+ await updateSettings2({+ ...settings!,+ aiPresets: settings?.aiPresets?.map((p) =>+ p.id === logPreset?.id ? { ...p, prompt: customPrompt || "" } : p,+ ),+ });+ } else {+ await updateSettings2({+ ...settings!,+ aiPresets: settings?.aiPresets?.map((p) =>+ p.id === logPreset?.id || p.id === intelligencePreset?.id+ ? { ...p, prompt: customPrompt || "" }+ : p,+ ),+ });+ }+await updatePipeConfig(logTimeWindow / 60000);loadingToast.update({@@ -234,11 +273,11 @@ export function ObsidianSettings() {};const openObsidianVault = async () => {- if (!settings?.vaultPath) return;+ if (!pipeSettings?.vaultPath) return;try {// Start from the current path and walk up until we find .obsidian folder- let currentPath = settings.vaultPath;+ let currentPath = pipeSettings.vaultPath;let vaultPath = null;while (currentPath !== "/") {@@ -269,13 +308,13 @@ export function ObsidianSettings() {const vaultName = path.basename(vaultPath);// Get relative path from vault root to AI folder- const relativePath = settings.vaultPath+ const relativePath = pipeSettings.vaultPath.replace(vaultPath, "").replace(/^\//, "");const searchQuery = `path:"${relativePath}"`;const deepLink = `obsidian://search?vault=${encodeURIComponent(- vaultName+ vaultName,)}&query=${encodeURIComponent(searchQuery)}`;window.open(deepLink, "_blank");@@ -371,15 +410,15 @@ export function ObsidianSettings() {});}}, 500),- []+ [],);// Add this new useEffect for initial path validationuseEffect(() => {- if (settings?.vaultPath) {- validatePath(settings.vaultPath);+ if (pipeSettings?.vaultPath) {+ validatePath(pipeSettings.vaultPath);}- }, [settings?.vaultPath, validatePath]);+ }, [pipeSettings?.vaultPath, validatePath]);const setupDeduplication = async () => {setCheckingModel(true);@@ -389,7 +428,7 @@ export function ObsidianSettings() {const models = await checkRes.json();const hasEmbeddingModel = models.models?.some(- (m: { name: string }) => m.name === "nomic-embed-text"+ (m: { name: string }) => m.name === "nomic-embed-text",);if (!hasEmbeddingModel) {@@ -438,7 +477,7 @@ export function ObsidianSettings() {// Update toast with progress if availableif (response.total && response.completed) {const progress = Math.round(- (response.completed / response.total) * 100+ (response.completed / response.total) * 100,);loadingToast.update({id: loadingToast.id,@@ -488,9 +527,9 @@ export function ObsidianSettings() {// Add this useEffect to initialize the state from settingsuseEffect(() => {if (settings) {- setDeduplicationEnabled(settings.deduplicationEnabled || false);+ setDeduplicationEnabled(pipeSettings?.deduplicationEnabled || false);}- }, [settings]);+ }, [pipeSettings?.deduplicationEnabled]);if (loading) {return (@@ -530,6 +569,7 @@ export function ObsidianSettings() {</div>);}+const hasMP4File = (content: string) =>content.trim().toLowerCase().includes(".mp4");return (@@ -551,15 +591,14 @@ export function ObsidianSettings() {<Inputid="vaultPath"name="vaultPath"- defaultValue={settings?.vaultPath}+ defaultValue={pipeSettings?.vaultPath}placeholder="/path/to/vault"- className={`${- pathValidation.isValid+ className={`${pathValidation.isValid? "border-green-500": pathValidation.message- ? "border-red-500"- : ""- }`}+ ? "border-red-500"+ : ""+ }`}onChange={(e) => validatePath(e.target.value)}/>{pathValidation.isChecking && (@@ -573,7 +612,7 @@ export function ObsidianSettings() {className="cursor-pointer hover:bg-muted"onClick={() => {const input = document.getElementById(- "vaultPath"+ "vaultPath",) as HTMLInputElement;if (input) {input.value = path;@@ -610,9 +649,8 @@ export function ObsidianSettings() {{pathValidation.message && (<p- className={`text-sm ${- pathValidation.isValid ? "text-green-500" : "text-red-500"- }`}+ className={`text-sm ${pathValidation.isValid ? "text-green-500" : "text-red-500"+ }`}>{pathValidation.message}</p>@@ -685,8 +723,8 @@ export function ObsidianSettings() {step="1"max="60"defaultValue={- settings?.logTimeWindow- ? settings?.logTimeWindow / 60000+ pipeSettings?.logTimeWindow+ ? pipeSettings?.logTimeWindow / 60000: 5}/>@@ -711,7 +749,7 @@ export function ObsidianSettings() {type="number"min="1"step="1"- defaultValue={settings?.logPageSize || 100}+ defaultValue={pipeSettings?.logPageSize || 100}/><p className="text-xs text-muted-foreground">how many screenpipe results to include in the AI prompt@@ -726,56 +764,36 @@ export function ObsidianSettings() {><Brain className="h-4 w-4" />log generation model- <code className="px-2 py-0.5 bg-muted rounded-md text-xs flex items-center gap-2">- ollama run{" "}- {settings?.logModel || "llama3.2:3b-instruct-q4_K_M"}- <Button- type="button"- variant="ghost"- size="icon"- className="h-4 w-4 p-0"- onClick={() => {- navigator.clipboard.writeText(- `ollama run ${- settings?.logModel ||+ {logPreset?.provider === "native-ollama" && (+ <code className="px-2 py-0.5 bg-muted rounded-md text-xs flex items-center gap-2">+ ollama run{" "}+ {logPreset.model || "llama3.2:3b-instruct-q4_K_M"}+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="h-4 w-4 p-0"+ onClick={() => {+ navigator.clipboard.writeText(+ `ollama run ${logPreset.model ||"llama3.2:3b-instruct-q4_K_M"- }`- );- toast({- title: "copied to clipboard",- duration: 1000,- });- }}- >- <Copy className="h-3 w-3" />- </Button>- </code>+ }`,+ );+ toast({+ title: "copied to clipboard",+ duration: 1000,+ });+ }}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </code>+ )}</Label>- <OllamaModelsList- disabled={!pathValidation.isValid}- defaultValue={- settings?.logModel || "llama3.2:3b-instruct-q4_K_M"- }- onChange={(value) => {- updateSettings({- ...settings,- logModel: value,- });- }}+ <AIPresetsSelector+ pipeName="obsidian"+ aiKey="aiLogPresetId"/>- {settings?.logModel &&- (settings.logModel.includes("deepseek") ||- settings.logModel.includes("o3") ||- settings.logModel.includes("o1")) && (- <p className="text-sm text-red-500">- warning: reasoning models like deepseek are not- recommended for log generation.- </p>- )}- <p className="text-xs text-muted-foreground">- local AI model used for generating individual activity- logs- </p></div></CardContent></Card>@@ -801,8 +819,8 @@ export function ObsidianSettings() {min="1"step="1"defaultValue={- settings?.analysisTimeWindow- ? settings.analysisTimeWindow / (60 * 60 * 1000)+ pipeSettings?.analysisTimeWindow+ ? pipeSettings.analysisTimeWindow / (60 * 60 * 1000): 1}/>@@ -813,54 +831,39 @@ export function ObsidianSettings() {<div className="space-y-2"><Label- htmlFor="analysisModel"+ htmlFor="logModel"className="flex items-center gap-2"><Brain className="h-4 w-4" />- analysis model- <code className="px-2 py-0.5 bg-muted rounded-md text-xs flex items-center gap-2">- ollama run{" "}- {settings?.analysisModel ||- "deepseek-r1:7b-qwen-distill-q4_K_M"}- <Button- type="button"- variant="ghost"- size="icon"- className="h-4 w-4 p-0"- onClick={() => {- navigator.clipboard.writeText(- `ollama run ${- settings?.analysisModel ||- "deepseek-r1:7b-qwen-distill-q4_K_M"- }`- );- toast({- title: "copied to clipboard",- duration: 1000,- });- }}- >- <Copy className="h-3 w-3" />- </Button>- </code>+ log generation model+ {intelligencePreset?.provider === "native-ollama" && (+ <code className="px-2 py-0.5 bg-muted rounded-md text-xs flex items-center gap-2">+ ollama run{" "}+ {intelligencePreset.model ||+ "llama3.2:3b-instruct-q4_K_M"}+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="h-4 w-4 p-0"+ onClick={() => {+ navigator.clipboard.writeText(+ `ollama run ${intelligencePreset.model ||+ "llama3.2:3b-instruct-q4_K_M"+ }`,+ );+ toast({+ title: "copied to clipboard",+ duration: 1000,+ });+ }}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </code>+ )}</Label>- <OllamaModelsList- disabled={!pathValidation.isValid}- defaultValue={- settings?.analysisModel ||- "deepseek-r1:7b-qwen-distill-q4_K_M"- }- onChange={(value) => {- updateSettings({- ...settings,- analysisModel: value,- });- }}- />- <p className="text-xs text-muted-foreground">- local AI model used for generating high-level insights- (typically larger model)- </p>+ <AIPresetsSelector pipeName="obsidian" aiKey="aiPresetId" /></div></CardContent></Card>@@ -881,7 +884,7 @@ export function ObsidianSettings() {disabled={!pathValidation.isValid}/><p className="text-xs text-muted-foreground">- customize how activity logs and insights are generated+ customize how activity logs and insights are generated. you can also link other obsidian notes by typing "@[[notes]]"</p></div></CardContent>@@ -897,7 +900,9 @@ export function ObsidianSettings() {onClick={testLog}variant="outline"disabled={- testLogLoading || !pathValidation.isValid || !settings?.logModel+ testLogLoading ||+ !pathValidation.isValid ||+ !Boolean(pipeSettings?.aiLogPresetId)}className="flex-1">@@ -921,7 +926,7 @@ export function ObsidianSettings() {disabled={intelligenceLoading ||!pathValidation.isValid ||- !settings?.analysisModel+ !Boolean(pipeSettings?.aiPresetId)}className="flex-1">@@ -1082,5 +1087,5 @@ export function ObsidianSettings() {</div></form></div>- );+ );}diff --git a/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsxindex 2ad93f580..b1a8d90ea 100644--- a/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx+++ b/pipes/obsidian/src/lib/hooks/use-pipe-settings.tsx@@ -1,103 +1,38 @@import { useState, useEffect } from "react";-import { Settings } from "@/lib/types";-import {- getScreenpipeAppSettings,- updateScreenpipeAppSettings,-} from "../actions/get-screenpipe-app-settings";+import { settingsStore } from "@/lib/store/settings-store";+import type { PipeSettings } from "@/lib/store/settings-store";-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`,-};--export function usePipeSettings() {- const [settings, setSettings] = useState<Partial<Settings> | null>(null);+export function usePipeSettings(pipeName: string) {+ const [settings, setSettings] = useState<Partial<PipeSettings> | null>(+ settingsStore.getStore().pipeSettings[pipeName] || null,+ );const [loading, setLoading] = useState(true);useEffect(() => {- loadSettings();- }, []);+ const loadSettings = async () => {+ setLoading(true);+ await settingsStore.loadPipeSettings(pipeName);+ setLoading(false);+ };- const loadSettings = async () => {- try {- // Load screenpipe app settings- const screenpipeSettings = await getScreenpipeAppSettings();+ loadSettings();- console.log(screenpipeSettings);+ const unsubscribe = settingsStore.subscribe(() => {+ setSettings(settingsStore.getStore().pipeSettings[pipeName] || null);+ });- const obsidianSettings = {- ...(screenpipeSettings.customSettings?.obsidian && {- ...screenpipeSettings.customSettings?.obsidian,- }),- };+ return () => {+ unsubscribe();+ };+ }, [pipeName]);- // Merge everything together- setSettings({- ...DEFAULT_SETTINGS,- ...obsidianSettings,- screenpipeAppSettings: screenpipeSettings,- });- } catch (error) {- console.error("failed to load settings:", error);- } finally {- setLoading(false);- }+ const updateSettings = async (newSettings: Partial<PipeSettings>) => {+ return settingsStore.updatePipeSettings(pipeName, newSettings);};- const updateSettings = async (newSettings: Partial<Settings>) => {- try {- // Split settings- const { screenpipeAppSettings, ...obsidianSettings } = newSettings;-- const mergedObsidianSettings = {- ...DEFAULT_SETTINGS,- ...obsidianSettings,- };-- // Update screenpipe settings if provided- await updateScreenpipeAppSettings({- ...screenpipeAppSettings,- customSettings: {- ...screenpipeAppSettings?.customSettings,- obsidian: obsidianSettings,- },- });-- // Update state with everything- setSettings({- ...mergedObsidianSettings,- screenpipeAppSettings:- screenpipeAppSettings || settings?.screenpipeAppSettings,- });- return true;- } catch (error) {- console.error("failed to update settings:", error);- return false;- }+ const getPreset = (key: keyof PipeSettings = "aiPresetId") => {+ return settingsStore.getPreset(pipeName, key);};- return { settings, updateSettings, loading };+ return { settings, updateSettings, loading, getPreset };}diff --git a/pipes/obsidian/src/lib/hooks/use-settings.tsx b/pipes/obsidian/src/lib/hooks/use-settings.tsxnew file mode 100644index 000000000..466445d10--- /dev/null+++ b/pipes/obsidian/src/lib/hooks/use-settings.tsx@@ -0,0 +1,39 @@+"use client";++import { useState, useEffect } from "react";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import { settingsStore } 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/obsidian/src/lib/store/settings-store.ts b/pipes/obsidian/src/lib/store/settings-store.tsnew file mode 100644index 000000000..e497dcfe6--- /dev/null+++ b/pipes/obsidian/src/lib/store/settings-store.ts@@ -0,0 +1,209 @@+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";++export interface PipeSettings {+ prompt: string;+ vaultPath: string;+ logTimeWindow: number;+ logPageSize: number;+ analysisTimeWindow: number;+ deduplicationEnabled: boolean;+ exampleSetting: string;+ aiLogPresetId: string;+ aiPresetId: string;+}++type AIPreset = ScreenpipeAppSettings["aiPresets"][number];++export const DEFAULT_SETTINGS: Partial<PipeSettings> = {+ exampleSetting: "default value",+};++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);+ this.notify();+ return true;+ } catch (error) {+ console.error("failed to update global settings:", error);+ return false;+ }+ }++ // load the pipe settings+ async loadPipeSettings(pipeName: string) {+ 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/rewind/bun.lockb b/pipes/rewind/bun.lockbindex b94ad3522..8e6256056 100755Binary files a/pipes/rewind/bun.lockb and b/pipes/rewind/bun.lockb differdiff --git a/pipes/rewind/package.json b/pipes/rewind/package.jsonindex 7e1ed14d8..d7d434627 100644--- a/pipes/rewind/package.json+++ b/pipes/rewind/package.json@@ -16,15 +16,15 @@"@radix-ui/react-popover": "^1.1.6","@radix-ui/react-progress": "^1.1.1","@radix-ui/react-scroll-area": "^1.2.2",- "@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-slider": "^1.2.3","@radix-ui/react-slot": "^1.1.2","@radix-ui/react-switch": "^1.1.2","@radix-ui/react-toast": "^1.2.3",- "@radix-ui/react-tooltip": "^1.1.5",- "@screenpipe/browser": "^0.1.28",- "@screenpipe/js": "^1.0.12",+ "@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",@@ -33,7 +33,7 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "^1.0.4",+ "cmdk": "1.0.0","date-fns": "^4.1.0","framer-motion": "^11.14.4","install": "^0.13.0",@@ -43,6 +43,7 @@"lucide-react": "^0.475.0","magic-ui": "^0.1.0","next": "15.1.0",+ "next-themes": "^0.4.6","npm": "^10.9.2","nuqs": "^2.3.2","openai": "^4.76.3",@@ -53,6 +54,7 @@"react-syntax-highlighter": "^15.6.1","remark-gfm": "^4.0.0","remark-math": "^6.0.0",+ "sonner": "^2.0.1","stopword": "^3.1.4","tailwind-merge": "^2.5.5","tailwindcss-animate": "^1.0.7",diff --git a/pipes/rewind/src/app/layout.tsx b/pipes/rewind/src/app/layout.tsxindex 988043355..191d38130 100644--- a/pipes/rewind/src/app/layout.tsx+++ b/pipes/rewind/src/app/layout.tsx@@ -47,27 +47,25 @@ export default async function RootLayout({<bodyclassName={`${geistSans.variable} ${geistMono.variable} antialiased`}>- <SettingsProvider>- {!enabled ? (- <div className="flex items-center justify-center h-screen">- <div className="text-center space-y-4">- <h2 className="text-xl font-medium">Frame Cache Disabled</h2>- <p className="text-muted-foreground">- Please enable frame cache in settings to use the timeline- feature.- </p>- </div>+ {!enabled ? (+ <div className="flex items-center justify-center h-screen">+ <div className="text-center space-y-4">+ <h2 className="text-xl font-medium">Frame Cache Disabled</h2>+ <p className="text-muted-foreground">+ Please enable frame cache in settings to use the timeline+ feature.+ </p></div>- ) : (- <>- <NuqsAdapter>- <SearchCommand />- {children}- <Toaster />- </NuqsAdapter>- </>- )}- </SettingsProvider>+ </div>+ ) : (+ <>+ <NuqsAdapter>+ <SearchCommand />+ {children}+ <Toaster />+ </NuqsAdapter>+ </>+ )}</body></html>);diff --git a/pipes/rewind/src/components/ai-frame-response.tsx b/pipes/rewind/src/components/ai-frame-response.tsxdeleted file mode 100644index 2d6aa48a4..000000000--- a/pipes/rewind/src/components/ai-frame-response.tsx+++ /dev/null@@ -1,145 +0,0 @@-import { useDebounce } from "@/lib/hooks/use-debounce";-import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";-import { useSettings } from "@/lib/hooks/use-settings";-import OpenAI from "openai";-import { zodResponseFormat } from "openai/helpers/zod.mjs";-import { z } from "zod";-import { useCallback, useEffect, useState } from "react";-import { Button } from "./ui/button";--interface FrameAIResponse {- explain: string;- links: string[];-}--export const AIFrameResponse = () => {- const { settings } = useSettings();- const { currentResultIndex, searchResults } = useKeywordSearchStore();- const debouncedResultIndex = useDebounce(currentResultIndex, 500);- const [aiContent, setAiContent] = useState<FrameAIResponse | null>(null);- const [isLoading, setIsLoading] = useState(false);- const [error, setError] = useState<string | null>(null);-- const generateFrameResponse = useCallback(async () => {- try {- if (aiContent !== null) return;- const currentFrame = searchResults[debouncedResultIndex];- if (settings?.aiModel?.length === 0) {- return;- }- if (!currentFrame) return;-- const frame = {- frame_id: currentFrame.frame_id,- timestamp: currentFrame.timestamp,- window_name: currentFrame.window_name,- app_name: currentFrame.app_name,- text: currentFrame.text,- };-- setIsLoading(true);-- // Initialize OpenAI- const openai = new OpenAI({- apiKey:- settings?.aiProviderType === "screenpipe-cloud"- ? settings?.user?.token- : settings?.openaiApiKey,- baseURL: settings?.aiUrl,- dangerouslyAllowBrowser: true,- });-- const prompt = `${JSON.stringify(frame)}`;-- // Generate suggestions using OpenAI- const response = await openai.chat.completions.create({- model: settings?.aiModel || "",- messages: [- {- role: "system",- content: `-You are an advanced text analyzer. You will be given text and metadata extracted from an image. Your task is to determine its content, identify any website references, and return structured output.--### **Guidelines:**-- **State facts directly**—do not say "the content is about"; simply state what it is.-- **Use present tense**—avoid words like *could be* or *might be*.-- **Address the user as "you"**—never refer to them as "user."-- **Identify social media content**—if the text indicates a social media platform, return the platform's links. If a person's ID is present, generate a link to their profile.--### **Input Format Example:**-{- "frame_id": <frame_id>,- "timestamp": <date and time of frame>,- "app_name": <app_name>,- "window_name": <window_name>,- "text": <ocr content of frame>-}-`,- },- {- role: "user",- content: prompt,- },- ],- response_format: zodResponseFormat(- z.object({- explain: z- .string()- .describe(- "State the content and why you are seeing it, inferred from the text (max 30 words)",- ),- links: z- .array(z.string())- .describe(- "Extracted web links or relevant social media profiles",- ),- }),- "frame_explain_response",- ),- });-- const content = response.choices[0]?.message?.content;-- console.log(JSON.parse(content ?? "{}"));- setAiContent(JSON.parse(content ?? "{}"));- } catch (err) {- setError(- err instanceof Error ? err.message : "failed to get ai response",- );- } finally {- setIsLoading(false);- }- }, [debouncedResultIndex, settings]);-- useEffect(() => {- generateFrameResponse();- }, [generateFrameResponse]);-- return (- <div className="text-neutral-600 w-full break-words">- {isLoading ? (- "Loading"- ) : error ? (- error- ) : (- <div className="space-y-2">- <div>{aiContent?.explain}</div>- <div className="space-y-2">- {aiContent?.links.map((link, i) => {- return (- <Button variant={"link"} key={i} asChild>- <a href={link} target="_blank">- <img- src={`https://www.google.com/s2/favicons?domain=${link}&sz=128`}- className="object-cover h-8 w-8"- />- </a>- </Button>- );- })}- </div>- </div>- )}- </div>- );-};diff --git a/pipes/rewind/src/components/ai-presets-selector.tsx b/pipes/rewind/src/components/ai-presets-selector.tsxnew file mode 100644index 000000000..a3e28ddef--- /dev/null+++ b/pipes/rewind/src/components/ai-presets-selector.tsx@@ -0,0 +1,1299 @@+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings, type PipeSettings } from "@/lib/hooks/use-settings";+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) => {+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset ? "" : currentValue,+ });+ 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/rewind/src/components/chat-message.tsx b/pipes/rewind/src/components/chat-message.tsxindex 762f3031b..103dc4847 100644--- a/pipes/rewind/src/components/chat-message.tsx+++ b/pipes/rewind/src/components/chat-message.tsx@@ -1,7 +1,7 @@import { Message } from "ai";import remarkGfm from "remark-gfm";import remarkMath from "remark-math";-import { useState, useEffect, useRef } from "react";+import { useState, useEffect, useRef, useMemo } from "react";import { cn } from "@/lib/utils";import { CodeBlock } from "@/components/ui/codeblock";@@ -16,6 +16,7 @@ import { ChatMessageActions } from "@/components/chat-message-actions";import { useSettings } from "@/lib/hooks/use-settings";import { VideoComponent } from "./video";import { ArrowDown, ChevronDown } from "lucide-react";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";export interface ChatMessageProps {message: Message;@@ -23,6 +24,7 @@ export interface ChatMessageProps {export function ChatMessage({ message, ...props }: ChatMessageProps) {const { settings } = useSettings();+ const { settings: pipeSettings, getPreset } = usePipeSettings("rewind");const [isThinking, setIsThinking] = useState(false);const [thinkingContent, setThinkingContent] = useState<string[]>([]);const [thinkingTime, setThinkingTime] = useState(0);@@ -77,6 +79,8 @@ export function ChatMessage({ message, ...props }: ChatMessageProps) {return null;}+ const aiPreset = useMemo(() => getPreset(), [pipeSettings]);+return (<divclassName={cn("group relative mb-4 flex items-start w-full")}@@ -92,11 +96,11 @@ export function ChatMessage({ message, ...props }: ChatMessageProps) {>{message.role === "user" ? (<IconUser />- ) : settings?.aiModel?.includes("gpt") ? (+ ) : aiPreset?.model.includes("gpt") ? (<IconOpenAI />- ) : settings?.aiModel?.includes("claude") ? (+ ) : aiPreset?.model?.includes("claude") ? (<IconClaude />- ) : settings?.aiModel?.includes("gemini") ? (+ ) : aiPreset?.model?.includes("gemini") ? (<IconGemini />) : (<>🦙</>diff --git a/pipes/rewind/src/components/timeline/ai-panel.tsx b/pipes/rewind/src/components/timeline/ai-panel.tsxindex 9110bc3cf..aa634a0f5 100644--- a/pipes/rewind/src/components/timeline/ai-panel.tsx+++ b/pipes/rewind/src/components/timeline/ai-panel.tsx@@ -19,6 +19,8 @@ import {} from "@/components/ui/tooltip";import { useSettings } from "@/lib/hooks/use-settings";import { ExportButton } from "../export-button";+import { AIPresetsSelector } from "../ai-presets-selector";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";interface AIPanelProps {position: { x: number; y: number };@@ -40,6 +42,7 @@ export function AIPanel({onExpandedChange,}: AIPanelProps) {const { settings } = useSettings();+ const { getPreset } = usePipeSettings("rewind");const [chatMessages, setChatMessages] = useState<Array<Message>>([]);const [isAiLoading, setIsAiLoading] = useState(false);const [isStreaming, setIsStreaming] = useState(false);@@ -267,12 +270,11 @@ export function AIPanel({new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),);+ const aiPreset = getPreset();+const openai = new OpenAI({- apiKey:- settings?.aiProviderType === "screenpipe-cloud"- ? settings?.user?.token- : settings?.openaiApiKey,- baseURL: settings?.aiUrl,+ apiKey: aiPreset?.apiKey,+ baseURL: aiPreset?.url,dangerouslyAllowBrowser: true,});@@ -286,7 +288,7 @@ export function AIPanel({relevantFrames,openai,{- model: settings?.aiModel || "",+ model: aiPreset?.model || "",onProgress: (chunk) => {currentResponse = chunk;setChatMessages((prev) => [@@ -320,7 +322,7 @@ export function AIPanel({return (<divref={aiPanelRef}- className="ai-panel bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-[100]"+ className="ai-panel bg-background border border-muted-foreground rounded-lg shadow-lg transition-all duration-300 ease-in-out z-10"style={{position: "fixed",left: position.x,@@ -443,6 +445,11 @@ export function AIPanel({))}</select></div>++ <div>+ <AIPresetsSelector pipeName="rewind" />+ </div>+<div className="flex gap-2"><TooltipProvider><Tooltip open={!isAvailable}>diff --git a/pipes/rewind/src/components/ui/textarea.tsx b/pipes/rewind/src/components/ui/textarea.tsxnew file mode 100644index 000000000..4d858bb6b--- /dev/null+++ b/pipes/rewind/src/components/ui/textarea.tsx@@ -0,0 +1,22 @@+import * as React from "react"++import { cn } from "@/lib/utils"++const Textarea = React.forwardRef<+ HTMLTextAreaElement,+ React.ComponentProps<"textarea">+>(({ className, ...props }, ref) => {+ return (+ <textarea+ className={cn(+ "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",+ className+ )}+ ref={ref}+ {...props}+ />+ )+})+Textarea.displayName = "Textarea"++export { Textarea }diff --git a/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.tsindex 743c88999..608513b37 100644--- a/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.ts+++ b/pipes/rewind/src/lib/actions/get-screenpipe-app-settings.ts@@ -4,11 +4,11 @@ import { pipe } from "@screenpipe/js";import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";export async function getScreenpipeAppSettings() {- return await pipe.settings.getAll();+ return await pipe.settings.getAll();}export async function updateScreenpipeAppSettings(- newSettings: Partial<ScreenpipeAppSettings>,+ newSettings: Partial<ScreenpipeAppSettings>) {- return await pipe.settings.update(newSettings);+ return await pipe.settings.update(newSettings);}diff --git a/pipes/rewind/src/lib/hooks/use-pipe-settings.ts b/pipes/rewind/src/lib/hooks/use-pipe-settings.tsnew file mode 100644index 000000000..ecf393cee--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-pipe-settings.ts@@ -0,0 +1,38 @@+import { useState, useEffect } from "react";+import { settingsStore } from "@/lib/hooks/use-settings";+import type { PipeSettings } from "@/lib/hooks/use-settings";++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/rewind/src/lib/hooks/use-settings.ts b/pipes/rewind/src/lib/hooks/use-settings.tsnew file mode 100644index 000000000..b59d2f7c6--- /dev/null+++ b/pipes/rewind/src/lib/hooks/use-settings.ts@@ -0,0 +1,233 @@+import { useState, useEffect } from "react";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import {+ getScreenpipeAppSettings,+ updateScreenpipeAppSettings,+} from "@/lib/actions/get-screenpipe-app-settings";++export interface PipeSettings {+ exampleSetting: string;+ aiLogPresetId: string;+ aiPresetId: string;+}++type AIPreset = ScreenpipeAppSettings["aiPresets"][number];++export const DEFAULT_SETTINGS: Partial<PipeSettings> = {+ exampleSetting: "default value",+};++type Listener = () => void;++type Store = {+ globalSettings: Partial<ScreenpipeAppSettings> | null;+ pipeSettings: Record<string, Partial<PipeSettings> | null>;+};++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);+ this.notify();+ return true;+ } catch (error) {+ console.error("failed to update global settings:", error);+ return false;+ }+ }++ // load the pipe settings+ async loadPipeSettings(pipeName: string) {+ try {+ const screenpipeSettings = await getScreenpipeAppSettings();+ 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();++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/rewind/src/lib/hooks/use-settings.tsx b/pipes/rewind/src/lib/hooks/use-settings.tsxdeleted file mode 100644index e431a8bea..000000000--- a/pipes/rewind/src/lib/hooks/use-settings.tsx+++ /dev/null@@ -1,8 +0,0 @@-import { useContext } from "react";-import { SettingsContext } from "@/components/settings-provider";--export function useSettings() {- const settingsProps = useContext(SettingsContext);-- return { ...settingsProps };-}diff --git a/pipes/rewind/src/lib/types.ts b/pipes/rewind/src/lib/types.tsnew file mode 100644index 000000000..bc41e7f19--- /dev/null+++ b/pipes/rewind/src/lib/types.ts@@ -0,0 +1,38 @@+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 {+ prompt: string;+ vaultPath: string;+ logTimeWindow: number;+ logPageSize: number;+ logModel: string;+ analysisModel: string;+ analysisTimeWindow: number;+ deduplicationEnabled: boolean;+ screenpipeAppSettings: ScreenpipeAppSettings;+}