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
refactor ai settings (#1515)
shaik-zeeshan0ff866bfcc18
diff --git a/pipes/example-pipe/bun.lockb b/pipes/example-pipe/bun.lockbindex 7630032f3..b4c35798a 100755Binary files a/pipes/example-pipe/bun.lockb and b/pipes/example-pipe/bun.lockb differdiff --git a/pipes/example-pipe/components/ai-presets-dialog.tsx b/pipes/example-pipe/components/ai-presets-dialog.tsxnew file mode 100644index 000000000..1195b1e01--- /dev/null+++ b/pipes/example-pipe/components/ai-presets-dialog.tsx@@ -0,0 +1,1315 @@+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,+} from "./ui/command";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "./ui/dialog";+import { Button } from "./ui/button";+import {+ Check,+ Plus,+ Copy,+ Edit2,+ Star,+ Trash2,+ Settings,+ Terminal,+ Loader2,+ HelpCircle,+ Eye,+ EyeOff,+} from "lucide-react";+import { cn } from "@/lib/utils";+import { toast } from "@/hooks/use-toast";+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;+}++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>+ );+};++interface AIPresetsDialogProps {+ children?: React.ReactNode;+ recommendedPresets?: RecommendedPreset[];+ pipeName: string;+ aiKey?: keyof PipeSettings;+ shortcutKey?: string;+}++export const AIPresetsDialog = ({+ children,+ recommendedPresets,+ pipeName,+ aiKey = "aiPresetId",+ shortcutKey = "/",+}: AIPresetsDialogProps) => {+ const { settings: pipeSettings, updateSettings: updatePipeSettings } =+ usePipeSettings(pipeName);+ const { settings, updateSettings } = useSettings();+ const [dialogOpen, setDialogOpen] = useState(false);+ const [presetDialogOpen, setPresetDialogOpen] = 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;+ }, [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.id)+ : -1;+ const nextIndex = (currentIndex + 1) % aiPresets.length;+ const nextPreset = aiPresets[nextIndex];++ updatePipeSettings({+ [aiKey]: nextPreset.id,+ });++ toast({+ title: "Preset changed",+ description: `Switched to ${nextPreset.id} (${nextPreset.model})`,+ });+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [aiPresets, selectedPreset, updatePipeSettings, aiKey]);++ const handleSavePreset = (preset: Partial<AIPreset>) => {+ if (!preset.id) {+ toast({+ title: "please enter a name for this preset",+ description: "name is required",+ variant: "destructive",+ });+ return;+ }++ if (!settings?.aiPresets) {+ toast({+ title: "error",+ description: "settings not initialized",+ variant: "destructive",+ });+ 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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ return;+ }++ // Add as new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });++ toast({+ title: "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({+ title: "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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ 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({+ title: "preset created",+ description: "new preset has been added",+ });+ }++ setPresetDialogOpen(false);+ setSelectedPresetToEdit(undefined);+ };++ const handleDuplicatePreset = (preset: AIPreset) => {+ setSelectedPresetToEdit({+ ...preset,+ id: `${preset.id}-copy`,+ defaultPreset: false,+ });+ setPresetDialogOpen(true);+ };++ const handleEditPreset = (preset: AIPreset) => {+ setSelectedPresetToEdit(preset);+ setPresetDialogOpen(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({+ title: "default preset updated",+ description: `${preset.id} is now the default preset`,+ });+ };++ const handleRemovePreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) {+ toast({+ title: "cannot delete default preset",+ description: "please set another preset as default first",+ variant: "destructive",+ });+ return;+ }++ const updatedPresets = settings.aiPresets.filter((p) => p.id !== preset.id);+ updateSettings({+ aiPresets: updatedPresets,+ });++ if (pipeSettings?.[aiKey] === preset.id) {+ updatePipeSettings({+ [aiKey]: "",+ });+ }++ toast({+ title: "preset removed",+ description: `${preset.id} has been removed`,+ });+ };++ const renderTrigger = () => {+ const content = children || (+ <Button variant="outline" className="flex w-full items-center">+ <Settings className="mr-2 h-4 w-4" />+ Manage AI Presets+ </Button>+ );++ return (+ <TooltipProvider delayDuration={0}>+ <Tooltip>+ <TooltipTrigger asChild>+ <DialogTrigger asChild onClick={() => setDialogOpen(true)}>+ {content}+ </DialogTrigger>+ </TooltipTrigger>+ <TooltipContent className="space-y-1 text-justify">+ <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>+ {selectedPreset && (+ <div className="mt-2 pt-2 border-t">+ <div className="font-medium truncate max-w-[200px]">+ {selectedPreset.id}+ </div>+ <div className="text-xs text-muted-foreground space-y-0.5">+ <div className="flex items-center gap-2">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {selectedPreset.provider}+ </span>+ <span className="truncate max-w-[120px]">+ {selectedPreset.model}+ </span>+ </div>+ <div className="whitespace-nowrap">+ Context:{" "}+ {(selectedPreset.maxContextChars / 1000).toFixed(0)}k chars+ </div>+ {selectedPreset.defaultPreset && (+ <div className="text-primary">Default Preset</div>+ )}+ </div>+ </div>+ )}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+ };++ return (+ <>+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ {renderTrigger()}+ <DialogContent className="w-[95vw] sm:w-[640px] md:w-[768px] lg:w-[1024px] xl:w-[1280px] max-w-[95vw]">+ <DialogHeader>+ <DialogTitle>AI Presets</DialogTitle>+ <DialogDescription>+ Manage your AI presets. You can create, edit, duplicate, and+ delete presets.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <Command>+ <CommandInput placeholder="search presets..." />+ <CommandEmpty>no presets found.</CommandEmpty>+ {recommendedPresets && recommendedPresets.length > 0 && (+ <CommandGroup heading="Recommended Presets">+ {recommendedPresets.map((preset) => (+ <CommandItem+ key={`${preset.id}-recommended`}+ value={`${preset.id}-recommended`}+ className="flex py-3"+ >+ <div className="flex w-full items-center justify-between gap-4 overflow-hidden">+ <div className="flex items-center gap-3 min-w-0">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset?.id === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[180px]">+ {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-4 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-3">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="truncate max-w-[180px]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 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);+ setPresetDialogOpen(true);+ }}+ >+ <Copy className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ )}+ <CommandGroup heading="Your Presets">+ {aiPresets.map((preset) => (+ <CommandItem+ key={preset.id}+ value={preset.id}+ onSelect={(currentValue) => {+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset?.id+ ? ""+ : currentValue,+ });+ }}+ className="flex py-3"+ >+ <div className="flex w-full items-center justify-between gap-4 overflow-hidden">+ <div className="flex items-center gap-3 min-w-0">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset?.id === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[180px]">+ {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-4 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-3">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="truncate max-w-[180px]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleEditPreset(preset);+ }}+ >+ <Edit2 className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleDuplicatePreset(preset);+ }}+ >+ <Copy className="h-4 w-4" />+ </Button>+ {!preset.defaultPreset && (+ <>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleSetDefaultPreset(preset);+ }}+ >+ <Star className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleRemovePreset(preset);+ }}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </>+ )}+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ <CommandGroup>+ <CommandItem+ onSelect={() => {+ setSelectedPresetToEdit(undefined);+ setPresetDialogOpen(true);+ }}+ >+ <Plus className="mr-2 h-4 w-4" />+ create new preset+ </CommandItem>+ </CommandGroup>+ </Command>+ </div>+ </DialogContent>+ </Dialog>+ <AIPresetDialog+ open={presetDialogOpen}+ onOpenChange={setPresetDialogOpen}+ onSave={handleSavePreset}+ preset={selectedPresetToEdit}+ />+ </>+ );+};diff --git a/pipes/example-pipe/components/ai-presets-selector.tsx b/pipes/example-pipe/components/ai-presets-selector.tsxnew file mode 100644index 000000000..c9415a495--- /dev/null+++ b/pipes/example-pipe/components/ai-presets-selector.tsx@@ -0,0 +1,1312 @@+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,+} 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 "@/hooks/use-toast";+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({+ title: "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({+ title: "please enter a name for this preset",+ description: "name is required",+ variant: "destructive",+ });+ return;+ }++ if (!settings?.aiPresets) {+ toast({+ title: "error",+ description: "settings not initialized",+ variant: "destructive",+ });+ 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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ return;+ }++ // Add as new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });++ toast({+ title: "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({+ title: "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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ 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({+ title: "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({+ title: "default preset updated",+ description: `${preset.id} is now the default preset`,+ });+ };++ const handleRemovePreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) {+ toast({+ title: "cannot delete default preset",+ description: "please set another preset as default first",+ variant: "destructive",+ });+ return;+ }++ const updatedPresets = settings.aiPresets.filter((p) => p.id !== preset.id);+ updateSettings({+ aiPresets: updatedPresets,+ });++ if (pipeSettings?.[aiKey] === preset.id) {+ updatePipeSettings({+ [aiKey]: "",+ });+ }++ toast({+ title: "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..." />+ <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>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ <AIPresetDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ onSave={handleSavePreset}+ preset={selectedPresetToEdit}+ />+ </>+ );+};diff --git a/pipes/example-pipe/components/ready-to-use-examples/realtime-audio.tsx b/pipes/example-pipe/components/ready-to-use-examples/realtime-audio.tsxindex 1e6f81169..68b38b4d3 100644--- a/pipes/example-pipe/components/ready-to-use-examples/realtime-audio.tsx+++ b/pipes/example-pipe/components/ready-to-use-examples/realtime-audio.tsx@@ -6,12 +6,18 @@ import { Button } from "@/components/ui/button";import { Loader2 } from "lucide-react";import { useSettings } from "@/lib/settings-provider";-export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, error: string | null) => void }) {+export function RealtimeAudio({+ onDataChange,+}: {+ onDataChange?: (data: any, error: string | null) => void;+}) {const { settings } = useSettings();- const [transcription, setTranscription] = useState<TranscriptionChunk | null>(null);+ const [transcription, setTranscription] = useState<TranscriptionChunk | null>(+ null,+ );const [isStreaming, setIsStreaming] = useState(false);const [error, setError] = useState<string | null>(null);- const [history, setHistory] = useState('');+ const [history, setHistory] = useState("");const historyRef = useRef(history);const streamRef = useRef<any>(null);@@ -23,34 +29,37 @@ export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, errconst startStreaming = async () => {try {// Check if realtime transcription is enabled- if (!settings?.screenpipeAppSettings?.enableRealtimeAudioTranscription) {- const errorMessage = "realtime audio transcription is not enabled in settings, go to account-> settings -> recording -> enable realtime audiotranscription -> models to use: screenpipe cloud. Then Refresh. If it doesn't start you might need to restart.";+ if (!settings?.enableRealtimeAudioTranscription) {+ const errorMessage =+ "realtime audio transcription is not enabled in settings, go to account-> settings -> recording -> enable realtime audiotranscription -> models to use: screenpipe cloud. Then Refresh. If it doesn't start you might need to restart.";setError(errorMessage);-+// Pass the error to the parent componentif (onDataChange) {onDataChange(null, errorMessage);}-+return; // Exit early}-+setError(null);setIsStreaming(true);-+// Add error handling for the analytics connection issueconst originalConsoleError = console.error;- console.error = function(msg, ...args) {+ console.error = function (msg, ...args) {// Filter out the analytics connection errors- if (typeof msg === 'string' &&- (msg.includes('failed to fetch settings') ||- msg.includes('ERR_CONNECTION_REFUSED'))) {+ if (+ typeof msg === "string" &&+ (msg.includes("failed to fetch settings") ||+ msg.includes("ERR_CONNECTION_REFUSED"))+ ) {// Suppress these specific errorsreturn;}originalConsoleError.apply(console, [msg, ...args]);};-+const stream = pipe.streamTranscriptions();streamRef.current = stream;@@ -59,43 +68,43 @@ export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, errconst chunk: TranscriptionChunk = {transcription: event.choices[0].text,timestamp: event.metadata?.timestamp || new Date().toISOString(),- device: event.metadata?.device || 'unknown',+ device: event.metadata?.device || "unknown",is_input: event.metadata?.isInput || false,- is_final: event.choices[0].finish_reason !== null+ is_final: event.choices[0].finish_reason !== null,};-+setTranscription(chunk);- const newHistory = historyRef.current + ' ' + chunk.transcription;+ const newHistory = historyRef.current + " " + chunk.transcription;setHistory(newHistory);-+// Pass the raw data to the parent component for display in the raw output tabif (onDataChange) {onDataChange(chunk, null);}-+console.log("transcription:", {text: chunk.transcription,device: chunk.device,- isFinal: chunk.is_final+ isFinal: chunk.is_final,});}}-+// Restore original console.errorconsole.error = originalConsoleError;-} catch (error) {console.error("audio stream failed:", error);- const errorMessage = error instanceof Error- ? `Failed to stream audio: ${error.message}`- : "Failed to stream audio";+ const errorMessage =+ error instanceof Error+ ? `Failed to stream audio: ${error.message}`+ : "Failed to stream audio";setError(errorMessage);-+// Pass the error to the parent componentif (onDataChange) {onDataChange(null, errorMessage);}-+setIsStreaming(false);}};@@ -130,19 +139,19 @@ export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, err<div className="grid grid-cols-2 gap-2"><div><span className="font-semibold">type: </span>- <span>{transcription.is_input ? 'Input' : 'Output'}</span>+ <span>{transcription.is_input ? "Input" : "Output"}</span></div><div><span className="font-semibold">final: </span>- <span>{transcription.is_final ? 'Yes' : 'No'}</span>+ <span>{transcription.is_final ? "Yes" : "No"}</span></div></div></div>-+<div className="bg-slate-100 rounded p-2 overflow-auto max-h-[100px] whitespace-pre-wrap font-mono text-xs">{transcription.transcription}</div>-+{history && (<div className="mt-2"><div className="text-slate-600 font-semibold mb-1">History:</div>@@ -158,8 +167,8 @@ export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, errreturn (<div className="space-y-2"><div className="flex justify-between items-center">- <Button- onClick={isStreaming ? stopStreaming : startStreaming}+ <Button+ onClick={isStreaming ? stopStreaming : startStreaming}size="sm">{isStreaming ? (@@ -168,33 +177,35 @@ export function RealtimeAudio({ onDataChange }: { onDataChange?: (data: any, errStop Streaming</>) : (- 'Start Audio Transcritpion Stream'+ "Start Audio Transcritpion Stream")}</Button>-+{history && (- <Button- variant="outline"+ <Button+ variant="outline"size="sm"onClick={() => {navigator.clipboard.writeText(history);- setHistory('');+ setHistory("");}}>Clear History</Button>)}</div>-+{error && <p className="text-xs text-red-500">{error}</p>}{transcription && renderTranscriptionContent(transcription)}-+<div className="flex items-center gap-1.5 text-right justify-end">- <div className={`w-1.5 h-1.5 rounded-full ${isStreaming ? 'bg-green-500' : 'bg-gray-400'}`} />+ <div+ className={`w-1.5 h-1.5 rounded-full ${isStreaming ? "bg-green-500" : "bg-gray-400"}`}+ /><span className="text-xs text-gray-500 font-mono">- {isStreaming ? 'streaming' : 'stopped'}+ {isStreaming ? "streaming" : "stopped"}</span></div></div>);-}\ No newline at end of file+}diff --git a/pipes/example-pipe/lib/hooks/generic-settings.tsx b/pipes/example-pipe/lib/hooks/generic-settings.tsxindex 5e56abd00..0e6974f14 100644--- a/pipes/example-pipe/lib/hooks/generic-settings.tsx+++ b/pipes/example-pipe/lib/hooks/generic-settings.tsx@@ -1,16 +1,16 @@"use client";-import { useSettings } from "../settings-provider";import { useState } from "react";+import { usePipeSettings } from "./use-pipe-settings";export function GenericSettings() {- const { settings, updateSettings, loading } = useSettings();+ const { settings, updateSettings, loading } = usePipeSettings("example");const [isSaving, setIsSaving] = useState(false);-+if (loading) {return <div>loading settings...</div>;}-+const handleSave = async () => {setIsSaving(true);try {@@ -22,28 +22,32 @@ export function GenericSettings() {setIsSaving(false);}};-+return (<div className="w-full max-w-2xl p-4 border rounded-lg"><h2 className="text-lg font-medium mb-4">pipe settings</h2>-+{/* Add your settings UI here */}<div className="space-y-4">{/* Example setting field */}<div>- <label className="block text-sm font-medium mb-1">example setting</label>- <input+ <label className="block text-sm font-medium mb-1">+ example setting+ </label>+ <inputtype="text"className="w-full p-2 border rounded"value={settings?.exampleSetting || ""}- onChange={(e) => updateSettings({- ...settings!,- exampleSetting: e.target.value- })}+ onChange={(e) =>+ updateSettings({+ ...settings!,+ exampleSetting: e.target.value,+ })+ }/></div></div>-+<div className="mt-4"><buttonclassName="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"@@ -55,4 +59,4 @@ export function GenericSettings() {</div></div>);-}\ No newline at end of file+}diff --git a/pipes/example-pipe/lib/hooks/use-pipe-settings.tsx b/pipes/example-pipe/lib/hooks/use-pipe-settings.tsxindex cc3c9fc12..ecf393cee 100644--- a/pipes/example-pipe/lib/hooks/use-pipe-settings.tsx+++ b/pipes/example-pipe/lib/hooks/use-pipe-settings.tsx@@ -1,95 +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/hooks/use-settings";+import type { PipeSettings } from "@/lib/hooks/use-settings";-const DEFAULT_SETTINGS: Partial<Settings> = {- exampleSetting: "default value",- 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();-- console.log("loaded settings:", screenpipeSettings);+ loadSettings();- // Merge with defaults- setSettings({- ...DEFAULT_SETTINGS,- ...screenpipeSettings.customSettings?.pipe,- screenpipeAppSettings: screenpipeSettings,- });- } catch (error) {- console.error("failed to load settings:", error);- } finally {- setLoading(false);- }- };+ const unsubscribe = settingsStore.subscribe(() => {+ setSettings(settingsStore.getStore().pipeSettings[pipeName] || null);+ });- const updateSettings = async (newSettings: Partial<Settings>) => {- try {- // Split settings- const { screenpipeAppSettings, ...pipeSettings } = newSettings;+ return () => {+ unsubscribe();+ };+ }, [pipeName]);- // Update screenpipe settings- await updateScreenpipeAppSettings({- ...screenpipeAppSettings,- customSettings: {- ...screenpipeAppSettings?.customSettings,- pipe: pipeSettings,- },- });+ const updateSettings = async (newSettings: Partial<PipeSettings>) => {+ return settingsStore.updatePipeSettings(pipeName, newSettings);+ };- // Update local state- setSettings({- ...DEFAULT_SETTINGS,- ...pipeSettings,- screenpipeAppSettings: screenpipeAppSettings || settings?.screenpipeAppSettings,- });-- console.log("settings updated successfully");- 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/example-pipe/lib/hooks/use-settings.tsx b/pipes/example-pipe/lib/hooks/use-settings.tsxnew file mode 100644index 000000000..b59d2f7c6--- /dev/null+++ b/pipes/example-pipe/lib/hooks/use-settings.tsx@@ -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/example-pipe/lib/settings-provider.tsx b/pipes/example-pipe/lib/settings-provider.tsxindex 9404d56c8..31488b045 100644--- a/pipes/example-pipe/lib/settings-provider.tsx+++ b/pipes/example-pipe/lib/settings-provider.tsx@@ -1,19 +1,24 @@"use client";import { createContext, useContext, ReactNode } from "react";-import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings as useSettingsApp } from "@/lib/hooks/use-settings";// Create a context for settings-type SettingsContextType = ReturnType<typeof usePipeSettings>;+type SettingsContextType = ReturnType<typeof useSettingsApp>;-const SettingsContext = createContext<SettingsContextType | undefined>(undefined);+const SettingsContext = createContext<SettingsContextType | undefined>(+ undefined,+);// Provider componentexport function SettingsProvider({ children }: { children: ReactNode }) {- const settingsData = usePipeSettings();-- console.log("settings provider initialized with data:", settingsData.loading ? "loading..." : "loaded");-+ const settingsData = useSettingsApp();++ console.log(+ "settings provider initialized with data:",+ settingsData.loading ? "loading..." : "loaded",+ );+return (<SettingsContext.Provider value={settingsData}>{children}@@ -28,4 +33,4 @@ export function useSettings() {throw new Error("useSettings must be used within a SettingsProvider");}return context;-}\ No newline at end of file+}diff --git a/pipes/example-pipe/package.json b/pipes/example-pipe/package.jsonindex e231af0d6..e229277a2 100644--- a/pipes/example-pipe/package.json+++ b/pipes/example-pipe/package.json@@ -11,26 +11,26 @@"dependencies": {"@radix-ui/react-accordion": "^1.2.3","@radix-ui/react-checkbox": "^1.1.4",- "@radix-ui/react-dialog": "^1.0.5",+ "@radix-ui/react-dialog": "^1.1.6","@radix-ui/react-label": "^2.1.0","@radix-ui/react-popover": "^1.1.6","@radix-ui/react-progress": "^1.1.2",- "@radix-ui/react-select": "^2.1.4",+ "@radix-ui/react-select": "^2.1.6","@radix-ui/react-separator": "^1.0.3",- "@radix-ui/react-slider": "^1.1.2",+ "@radix-ui/react-slider": "^1.2.3","@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3","@radix-ui/react-tabs": "^1.1.3","@radix-ui/react-toast": "^1.2.1",- "@radix-ui/react-tooltip": "^1.1.6",+ "@radix-ui/react-tooltip": "^1.1.8","@screenpipe/browser": "0.1.26",- "@screenpipe/js": "1.0.9",+ "@screenpipe/js": "1.0.18","@types/lodash": "^4.17.13","@types/nodemailer": "^6.4.17","ai": "^4.0.18","cheerio": "^1.0.0","class-variance-authority": "^0.7.1",- "cmdk": "0.2.1",+ "cmdk": "1.0.0","framer-motion": "^12.4.7","js-levenshtein": "^1.1.6","lodash": "^4.17.21",diff --git a/pipes/search/bun.lockb b/pipes/search/bun.lockbindex ae1d90712..32bc51283 100755Binary files a/pipes/search/bun.lockb and b/pipes/search/bun.lockb differdiff --git a/pipes/search/next.config.ts b/pipes/search/next.config.tsindex b6d621fe0..d3706c2ad 100644--- a/pipes/search/next.config.ts+++ b/pipes/search/next.config.ts@@ -1,14 +1,16 @@import type { NextConfig } from "next";const nextConfig: NextConfig = {- transpilePackages: ["@screenpipe/js"],- webpack: (config, { }) => {- return config;- },- devIndicators: {- buildActivity: false,- appIsrStatus: false- }+ transpilePackages: ["@screenpipe/js"],+ webpack: (config, {}) => {+ // TODO: remove this in when merging+ config.resolve.symlinks = true;+ return config;+ },+ devIndicators: {+ buildActivity: false,+ appIsrStatus: false,+ },};export default nextConfig;diff --git a/pipes/search/package.json b/pipes/search/package.jsonindex 412803a2f..61fc0748e 100644--- a/pipes/search/package.json+++ b/pipes/search/package.json@@ -3,7 +3,7 @@"version": "0.1.32","private": true,"scripts": {- "dev": "next dev --turbopack",+ "dev": "next dev","build": "next build","start": "next start","lint": "next lint"@@ -25,7 +25,7 @@"@radix-ui/react-toast": "^1.2.3","@radix-ui/react-tooltip": "^1.1.5","@screenpipe/browser": "^0.1.35",- "@screenpipe/js": "^1.0.16",+ "@screenpipe/js": "^1.0.18","@shadcn/ui": "^0.0.4","@tanstack/react-query": "^5.62.7","@types/js-levenshtein": "^1.1.3",diff --git a/pipes/search/src/app/page.tsx b/pipes/search/src/app/page.tsxindex a3c457cd0..5394e511c 100644--- a/pipes/search/src/app/page.tsx+++ b/pipes/search/src/app/page.tsx@@ -1,23 +1,25 @@"use client";-import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";import { useSettings } from "@/lib/hooks/use-settings";import { Terminal } from "lucide-react";import { SearchChat } from "@/components/search-chat";-export default function SearchPage() {-const { settings } = useSettings();- const aiDisabled = settings.aiProviderType === "screenpipe-cloud" && !settings.user.token;+ const aiDisabled =+ settings?.aiProviderType === "screenpipe-cloud" && !settings?.user?.token;return (- <div className={`flex flex-col gap-4 items-center justify-center h-full ${aiDisabled ? "mt-2" : "mt-12"}`}>- {aiDisabled &&(+ <div+ className={`flex flex-col gap-4 items-center justify-center h-full ${aiDisabled ? "mt-2" : "mt-12"}`}+ >+ {aiDisabled && (<Alert className="w-[70%] shadow-sm"><Terminal className="h-4 w-4" /><AlertTitle>heads up!</AlertTitle><AlertDescription className="text-muted-foreground">- your ai provider is set to 'screenpipe-cloud' and you don't have logged in <br/>+ your ai provider is set to 'screenpipe-cloud' and you+ don't have logged in <br />please login to use this pipe, go to app > settings > login</AlertDescription></Alert>diff --git a/pipes/search/src/components/ai-presets-dialog.tsx b/pipes/search/src/components/ai-presets-dialog.tsxnew file mode 100644index 000000000..e04d4bf5a--- /dev/null+++ b/pipes/search/src/components/ai-presets-dialog.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,+} from "./ui/command";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "./ui/dialog";+import { Button } from "./ui/button";+import {+ Check,+ Plus,+ Copy,+ Edit2,+ Star,+ Trash2,+ Settings,+ Terminal,+ Loader2,+ HelpCircle,+ Eye,+ EyeOff,+} from "lucide-react";+import { cn } from "@/lib/utils";+import { toast } from "@/lib/use-toast";+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;+}++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>+ );+};++interface AIPresetsDialogProps {+ children?: React.ReactNode;+ recommendedPresets?: RecommendedPreset[];+ pipeName: string;+ aiKey?: keyof PipeSettings;+ shortcutKey?: string;+}++export const AIPresetsDialog = ({ children, recommendedPresets, pipeName, aiKey = "aiPresetId", shortcutKey = "/" }: AIPresetsDialogProps) => {+ const { settings: pipeSettings, updateSettings: updatePipeSettings } =+ usePipeSettings(pipeName);+ const { settings, updateSettings } = useSettings();+ const [dialogOpen, setDialogOpen] = useState(false);+ const [presetDialogOpen, setPresetDialogOpen] = 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;+ }, [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.id)+ : -1;+ const nextIndex = (currentIndex + 1) % aiPresets.length;+ const nextPreset = aiPresets[nextIndex];++ updatePipeSettings({+ [aiKey]: nextPreset.id,+ });++ toast({+ title: "Preset changed",+ description: `Switched to ${nextPreset.id} (${nextPreset.model})`,+ });+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [aiPresets, selectedPreset, updatePipeSettings, aiKey]);++ const handleSavePreset = (preset: Partial<AIPreset>) => {+ if (!preset.id) {+ toast({+ title: "please enter a name for this preset",+ description: "name is required",+ variant: "destructive",+ });+ return;+ }++ if (!settings?.aiPresets) {+ toast({+ title: "error",+ description: "settings not initialized",+ variant: "destructive",+ });+ 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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ return;+ }++ // Add as new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });++ toast({+ title: "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({+ title: "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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ 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({+ title: "preset created",+ description: "new preset has been added",+ });+ }++ setPresetDialogOpen(false);+ setSelectedPresetToEdit(undefined);+ };++ const handleDuplicatePreset = (preset: AIPreset) => {+ setSelectedPresetToEdit({+ ...preset,+ id: `${preset.id}-copy`,+ defaultPreset: false,+ });+ setPresetDialogOpen(true);+ };++ const handleEditPreset = (preset: AIPreset) => {+ setSelectedPresetToEdit(preset);+ setPresetDialogOpen(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({+ title: "default preset updated",+ description: `${preset.id} is now the default preset`,+ });+ };++ const handleRemovePreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) {+ toast({+ title: "cannot delete default preset",+ description: "please set another preset as default first",+ variant: "destructive",+ });+ return;+ }++ const updatedPresets = settings.aiPresets.filter((p) => p.id !== preset.id);+ updateSettings({+ aiPresets: updatedPresets,+ });++ if (pipeSettings?.[aiKey] === preset.id) {+ updatePipeSettings({+ [aiKey]: "",+ });+ }++ toast({+ title: "preset removed",+ description: `${preset.id} has been removed`,+ });+ };++ const renderTrigger = () => {+ const content = children || (+ <Button+ variant="outline"+ className="flex w-full items-center">+ <Settings className="mr-2 h-4 w-4" />+ Manage AI Presets+ </Button>+ );++ return (+ <TooltipProvider delayDuration={0}>+ <Tooltip>+ <TooltipTrigger asChild>+ <DialogTrigger asChild+ onClick={() => setDialogOpen(true)}+ >+ {content}+ </DialogTrigger>+ </TooltipTrigger>+ <TooltipContent className="space-y-1 text-justify">+ <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>+ {selectedPreset && (+ <div className="mt-2 pt-2 border-t">+ <div className="font-medium truncate max-w-[200px]">{selectedPreset.id}</div>+ <div className="text-xs text-muted-foreground space-y-0.5">+ <div className="flex items-center gap-2">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {selectedPreset.provider}+ </span>+ <span className="truncate max-w-[120px]">+ {selectedPreset.model}+ </span>+ </div>+ <div className="whitespace-nowrap">+ Context: {(selectedPreset.maxContextChars / 1000).toFixed(0)}k chars+ </div>+ {selectedPreset.defaultPreset && (+ <div className="text-primary">Default Preset</div>+ )}+ </div>+ </div>+ )}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+ };++ return (+ <>+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ {renderTrigger()}+ <DialogContent className="w-[95vw] sm:w-[640px] md:w-[768px] lg:w-[1024px] xl:w-[1280px] max-w-[95vw]">+ <DialogHeader>+ <DialogTitle>AI Presets</DialogTitle>+ <DialogDescription>+ Manage your AI presets. You can create, edit, duplicate, and delete presets.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <Command>+ <CommandInput placeholder="search presets..." />+ <CommandEmpty>no presets found.</CommandEmpty>+ {recommendedPresets && recommendedPresets.length > 0 && (+ <CommandGroup heading="Recommended Presets">+ {recommendedPresets.map((preset) => (+ <CommandItem+ key={`${preset.id}-recommended`}+ value={`${preset.id}-recommended`}+ className="flex py-3"+ >+ <div className="flex w-full items-center justify-between gap-4 overflow-hidden">+ <div className="flex items-center gap-3 min-w-0">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset?.id === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[180px]">+ {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-4 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-3">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="truncate max-w-[180px]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 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);+ setPresetDialogOpen(true);+ }}+ >+ <Copy className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ )}+ <CommandGroup heading="Your Presets">+ {aiPresets.map((preset) => (+ <CommandItem+ key={preset.id}+ value={preset.id}+ onSelect={(currentValue) => {+ updatePipeSettings({+ [aiKey]:+ currentValue === selectedPreset?.id ? "" : currentValue,+ });+ }}+ className="flex py-3"+ >+ <div className="flex w-full items-center justify-between gap-4 overflow-hidden">+ <div className="flex items-center gap-3 min-w-0">+ <Check+ className={cn(+ "h-4 w-4 shrink-0",+ selectedPreset?.id === preset.id+ ? "opacity-100"+ : "opacity-0",+ )}+ />+ <span className="font-medium truncate max-w-[180px]">+ {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-4 text-xs text-muted-foreground shrink-0">+ <div className="flex items-center gap-3">+ <span className="rounded bg-muted px-1.5 py-0.5 whitespace-nowrap">+ {preset.provider}+ </span>+ <span className="truncate max-w-[180px]">+ {preset.model}+ </span>+ </div>+ <span className="whitespace-nowrap">+ {(preset.maxContextChars / 1000).toFixed(0)}k+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleEditPreset(preset);+ }}+ >+ <Edit2 className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleDuplicatePreset(preset);+ }}+ >+ <Copy className="h-4 w-4" />+ </Button>+ {!preset.defaultPreset && (+ <>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleSetDefaultPreset(preset);+ }}+ >+ <Star className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 shrink-0"+ onClick={(e) => {+ e.stopPropagation();+ handleRemovePreset(preset);+ }}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </>+ )}+ </div>+ </div>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ <CommandGroup>+ <CommandItem+ onSelect={() => {+ setSelectedPresetToEdit(undefined);+ setPresetDialogOpen(true);+ }}+ >+ <Plus className="mr-2 h-4 w-4" />+ create new preset+ </CommandItem>+ </CommandGroup>+ </Command>+ </div>+ </DialogContent>+ </Dialog>+ <AIPresetDialog+ open={presetDialogOpen}+ onOpenChange={setPresetDialogOpen}+ onSave={handleSavePreset}+ preset={selectedPresetToEdit}+ />+ </>+ );+};\ No newline at end of filediff --git a/pipes/search/src/components/ai-presets-selector.tsx b/pipes/search/src/components/ai-presets-selector.tsxnew file mode 100644index 000000000..cb42cc49e--- /dev/null+++ b/pipes/search/src/components/ai-presets-selector.tsx@@ -0,0 +1,1282 @@+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,+} 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 "@/lib/use-toast";+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({+ title: "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({+ title: "please enter a name for this preset",+ description: "name is required",+ variant: "destructive",+ });+ return;+ }++ if (!settings?.aiPresets) {+ toast({+ title: "error",+ description: "settings not initialized",+ variant: "destructive",+ });+ 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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ return;+ }++ // Add as new preset+ updateSettings({+ aiPresets: [+ ...settings.aiPresets,+ {+ ...preset,+ defaultPreset: false,+ } as AIPreset,+ ],+ });++ toast({+ title: "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({+ title: "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({+ title: "name already exists",+ description: "please choose a different name",+ variant: "destructive",+ });+ 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({+ title: "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({+ title: "default preset updated",+ description: `${preset.id} is now the default preset`,+ });+ };++ const handleRemovePreset = (preset: AIPreset) => {+ if (!settings?.aiPresets) return;+ if (preset.defaultPreset) {+ toast({+ title: "cannot delete default preset",+ description: "please set another preset as default first",+ variant: "destructive",+ });+ return;+ }++ const updatedPresets = settings.aiPresets.filter((p) => p.id !== preset.id);+ updateSettings({+ aiPresets: updatedPresets,+ });++ if (pipeSettings?.[aiKey] === preset.id) {+ updatePipeSettings({+ [aiKey]: "",+ });+ }++ toast({+ title: "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..." />+ <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>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ <AIPresetDialog+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ onSave={handleSavePreset}+ preset={selectedPresetToEdit}+ />+ </>+ );+};diff --git a/pipes/search/src/components/ai-provider-config.tsx b/pipes/search/src/components/ai-provider-config.tsxnew file mode 100644index 000000000..5d02e01dd--- /dev/null+++ b/pipes/search/src/components/ai-provider-config.tsx@@ -0,0 +1,628 @@+"use client";++import { useState, useEffect } from "react";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { Label } from "./ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "./ui/select";+import { Settings, Terminal, Loader2, HelpCircle, Eye, EyeOff } from "lucide-react";+import { useSettings } from "@/lib/hooks/use-settings";+import { Textarea } from "./ui/textarea";+import { Slider } from "./ui/slider";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "./ui/tooltip";+import { toast } from "@/lib/use-toast";+import { cn } from "@/lib/utils";++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 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>+ );+}diff --git a/pipes/search/src/components/example-search-cards.tsx b/pipes/search/src/components/example-search-cards.tsxindex 275a2a32f..5adb1f210 100644--- a/pipes/search/src/components/example-search-cards.tsx+++ b/pipes/search/src/components/example-search-cards.tsx@@ -72,7 +72,7 @@ export function ExampleSearchCards({ onSelect }: ExampleSearchCardsProps) {const isHealthError = !health || health?.status === "error";const isAiDisabled =- !settings.user?.token && settings.aiProviderType === "screenpipe-cloud";+ !settings?.user?.token && settings?.aiProviderType === "screenpipe-cloud";return (<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">@@ -82,7 +82,9 @@ export function ExampleSearchCards({ onSelect }: ExampleSearchCardsProps) {<TooltipTrigger asChild><divclassName={`relative group h-[150px] ${- (isHealthError || isAiDisabled) ? "opacity-50 cursor-not-allowed" : ""+ isHealthError || isAiDisabled+ ? "opacity-50 cursor-not-allowed"+ : ""}`}><div className="absolute inset-0 rounded-lg transition-all duration-300 ease-out group-hover:before:opacity-100 group-hover:before:scale-100 before:absolute before:inset-0 before:rounded-lg before:border-2 before:border-black dark:before:border-white before:opacity-0 before:scale-95 group-hover:before:opacity-100 group-hover:before:scale-100 before:transition-all before:duration-300 before:ease-out" />@@ -122,10 +124,11 @@ export function ExampleSearchCards({ onSelect }: ExampleSearchCardsProps) {{(isHealthError || isAiDisabled) && (<TooltipContent><p>- {(isAiDisabled && isHealthError) ? (+ {isAiDisabled && isHealthError ? (<><AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />- you don't have access to screenpipe-cloud, <br /> and screenpipe backend is not running!+ you don't have access to screenpipe-cloud, <br /> and+ screenpipe backend is not running!</>) : isHealthError ? (<>@@ -135,7 +138,8 @@ export function ExampleSearchCards({ onSelect }: ExampleSearchCardsProps) {) : isAiDisabled ? (<><AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />- you don't have access to screenpipe-cloud :( <br/> please consider login!+ you don't have access to screenpipe-cloud :( <br /> please+ consider login!</>) : (""diff --git a/pipes/search/src/components/icons.tsx b/pipes/search/src/components/icons.tsxnew file mode 100644index 000000000..b65efdb7d--- /dev/null+++ b/pipes/search/src/components/icons.tsx@@ -0,0 +1,18 @@+import { Settings, Terminal, Loader2 } from "lucide-react";++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,+};diff --git a/pipes/search/src/components/search-chat.tsx b/pipes/search/src/components/search-chat.tsxindex 2ea3d8573..cc96bd72e 100644--- a/pipes/search/src/components/search-chat.tsx+++ b/pipes/search/src/components/search-chat.tsx@@ -11,36 +11,35 @@ import { Switch } from "@/components/ui/switch";import { Label } from "@/components/ui/label";import { useAiProvider } from "@/lib/hooks/use-ai-provider";import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,} from "@/components/ui/select";import { Progress } from "@/components/ui/progress";import { DateTimePicker } from "./date-time-picker";import { Badge } from "./ui/badge";import {- ChevronDown,- ChevronLeft,- ChevronRight,- HelpCircle,- Laptop,- Layers,- Layout,- Loader2,- Search,- Send,- Square,- Clock,- Check,- Plus,- AlertCircle,- SpeechIcon,- ChevronsUpDown,- Bot,- Settings,- Copy,+ ChevronDown,+ ChevronLeft,+ ChevronRight,+ HelpCircle,+ Laptop,+ Layers,+ Layout,+ Loader2,+ Search,+ Send,+ Square,+ Clock,+ Check,+ Plus,+ AlertCircle,+ Bot,+ Settings,+ Copy,+ SparklesIcon,} from "lucide-react";import { useToast } from "@/lib/use-toast";import { AnimatePresence, motion } from "framer-motion";@@ -49,26 +48,26 @@ import { OpenAI } from "openai";import { ChatMessage } from "@/components/chat-message";import { spinner } from "@/components/spinner";import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,} from "@/components/ui/accordion";import { VideoComponent } from "@/components/video";import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,- DialogFooter,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+ DialogFooter,} from "@/components/ui/dialog";import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,} from "@/components/ui/tooltip";import { Separator } from "@/components/ui/separator";import { ContextUsageIndicator } from "@/components/context-usage-indicator";@@ -78,2062 +77,2082 @@ import { CodeBlock } from "@/components/ui/codeblock";import { SqlAutocompleteInput } from "@/components/sql-autocomplete-input";import { cn, removeDuplicateSelections } from "@/lib/utils";import {- ExampleSearch,- ExampleSearchCards,+ ExampleSearch,+ ExampleSearchCards,} from "@/components/example-search-cards";import { useDebounce } from "@/lib/hooks/use-debounce";import { useHealthCheck } from "@/lib/hooks/use-health-check";import {- SearchHistory,- useSearchHistory,+ SearchHistory,+ useSearchHistory,} from "@/lib/hooks/use-search-history";import {- CommandInput,- CommandList,- CommandEmpty,- CommandGroup,- CommandItem,- Command,+ CommandInput,+ CommandList,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ Command,} from "./ui/command";import { type Speaker } from "@screenpipe/browser";import {- Popover,- PopoverContent,- PopoverTrigger,+ Popover,+ PopoverContent,+ PopoverTrigger,} from "@/components/ui/popover";import { useSettings } from "@/lib/hooks/use-settings";import { SearchFilterGenerator } from "./search-filter-generator";import {- MultiSelectCombobox,- type BaseOption,+ MultiSelectCombobox,+ type BaseOption,} from "@/components/ui/multi-select-combobox";+import { AIPresetsDialog } from "./ai-presets-dialog";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import type { Settings as AppSettings } from "@screenpipe/js";+import { DEFAULT_PROMPT } from "./ai-presets-dialog";+import { AIPresetsSelector } from "./ai-presets-selector";interface Agent {- id: string;- name: string;- description: string;- dataSelector: (results: ContentItem[]) => any;- systemPrompt: string;+ id: string;+ name: string;+ description: string;+ dataSelector: (results: ContentItem[]) => any;+ systemPrompt: string;}const AGENTS: Agent[] = [- {- id: "context-master",- name: "context master",- description: "analyzes everything: apps, windows, text & audio",- systemPrompt:- "you analyze all types of data from screen recordings and audio transcriptions. provide comprehensive insights.",- dataSelector: (results) => results,- },- {- id: "window-detective",- name: "window detective",- description: "focuses on app usage patterns",- systemPrompt:- "you specialize in analyzing app usage patterns and window switching behavior. help users understand their app usage.",- dataSelector: (results) =>- results- .filter(- (item) =>- item.type === "OCR" &&- (item.content.appName || item.content.windowName)- )- .map((item) => ({- timestamp: item.content.timestamp,- // @ts-ignore- appName: item.content.appName,- // @ts-ignore- windowName: item.content.windowName,- })),- },- {- id: "text-oracle",- name: "text oracle",- description: "analyzes screen text (OCR)",- systemPrompt:- "you focus on text extracted from screen recordings. help users find and understand text content.",- dataSelector: (results) =>- results- .filter((item) => item.type === "OCR")- .map((item) => ({- timestamp: item.content.timestamp,- text: item.content.text,- appName: item.content.appName,- })),- },- {- id: "voice-sage",- name: "voice sage",- description: "focuses on audio transcriptions",- systemPrompt:- "you analyze audio transcriptions from recordings. help users understand spoken content.",- dataSelector: (results) =>- results- .filter((item) => item.type === "Audio")- .map((item) => ({- timestamp: item.content.timestamp,- transcription: item.content.transcription,- })),- },+ {+ id: "context-master",+ name: "context master",+ description: "analyzes everything: apps, windows, text & audio",+ systemPrompt:+ "you analyze all types of data from screen recordings and audio transcriptions. provide comprehensive insights.",+ dataSelector: (results) => results,+ },+ {+ id: "window-detective",+ name: "window detective",+ description: "focuses on app usage patterns",+ systemPrompt:+ "you specialize in analyzing app usage patterns and window switching behavior. help users understand their app usage.",+ dataSelector: (results) =>+ results+ .filter(+ (item) =>+ item.type === "OCR" &&+ (item.content.appName || item.content.windowName),+ )+ .map((item) => ({+ timestamp: item.content.timestamp,+ // @ts-ignore+ appName: item.content.appName,+ // @ts-ignore+ windowName: item.content.windowName,+ })),+ },+ {+ id: "text-oracle",+ name: "text oracle",+ description: "analyzes screen text (OCR)",+ systemPrompt:+ "you focus on text extracted from screen recordings. help users find and understand text content.",+ dataSelector: (results) =>+ results+ .filter((item) => item.type === "OCR")+ .map((item) => ({+ timestamp: item.content.timestamp,+ text: item.content.text,+ appName: item.content.appName,+ })),+ },+ {+ id: "voice-sage",+ name: "voice sage",+ description: "focuses on audio transcriptions",+ systemPrompt:+ "you analyze audio transcriptions from recordings. help users understand spoken content.",+ dataSelector: (results) =>+ results+ .filter((item) => item.type === "Audio")+ .map((item) => ({+ timestamp: item.content.timestamp,+ transcription: item.content.transcription,+ })),+ },];// Add this helper function to highlight keywords in textconst highlightKeyword = (text: string, keyword: string): JSX.Element => {- if (!keyword || !text) return <>{text}</>;-- const parts = text.split(new RegExp(`(${keyword})`, "gi"));- return (- <>- {parts.map((part, i) =>- part.toLowerCase() === keyword.toLowerCase() ? (- <span- key={i}- className="bg-yellow-200 dark:bg-yellow-800 rounded px-0.5"- >- {part}- </span>- ) : (- part- )- )}- </>- );+ if (!keyword || !text) return <>{text}</>;++ const parts = text.split(new RegExp(`(${keyword})`, "gi"));+ return (+ <>+ {parts.map((part, i) =>+ part.toLowerCase() === keyword.toLowerCase() ? (+ <span+ key={i}+ className="bg-yellow-200 dark:bg-yellow-800 rounded px-0.5"+ >+ {part}+ </span>+ ) : (+ part+ ),+ )}+ </>+ );};// Update the getContextAroundKeyword function to return both text and positionsconst getContextAroundKeyword = (- text: string,- keyword: string,- contextLength: number = 40+ text: string,+ keyword: string,+ contextLength: number = 40,): string => {- if (!keyword || !text) return text;+ if (!keyword || !text) return text;- const index = text.toLowerCase().indexOf(keyword.toLowerCase());- if (index === -1) return text;+ const index = text.toLowerCase().indexOf(keyword.toLowerCase());+ if (index === -1) return text;- const start = Math.max(0, index - contextLength);- const end = Math.min(text.length, index + keyword.length + contextLength);+ const start = Math.max(0, index - contextLength);+ const end = Math.min(text.length, index + keyword.length + contextLength);- let result = text.slice(start, end);- if (start > 0) result = "..." + result;- if (end < text.length) result = result + "...";+ let result = text.slice(start, end);+ if (start > 0) result = "..." + result;+ if (end < text.length) result = result + "...";- return result;+ return result;};export function SearchChat() {- const {- searches,- currentSearchId,- setCurrentSearchId,- addSearch,- deleteSearch,- isCollapsed,- toggleCollapse,- } = useSearchHistory();- // Search state- const { health, isServerDown } = useHealthCheck();- const [query, setQuery] = useState("");- const [results, setResults] = useState<ContentItem[]>([]);- const [isLoading, setIsLoading] = useState(false);- const [startDate, setStartDate] = useState<Date>(- new Date(Date.now() - 24 * 3600000)- );- const [endDate, setEndDate] = useState<Date>(new Date());- const [includeFrames, setIncludeFrames] = useState(false);- const [limit, setLimit] = useState(30);- const [appName, setAppName] = useState("");- const [windowName, setWindowName] = useState("");- const [contentType, setContentType] = useState("all");- const [offset, setOffset] = useState(0);- const [totalResults, setTotalResults] = useState(0);- const { settings } = useSettings();- const { isAvailable, error } = useAiProvider(settings);- const [isAiLoading, setIsAiLoading] = useState(false);- const [minLength, setMinLength] = useState(50);- const [maxLength, setMaxLength] = useState(10000);- const [speakers, setSpeakers] = useState<Speaker[]>([]);- const [selectedSpeakers, setSelectedSpeakers] = useState<{- [key: number]: Speaker;- }>({});- const [openSpeakers, setOpenSpeakers] = useState(false);- // Chat state- const [chatMessages, setChatMessages] = useState<Array<Message>>([]);-- const { toast } = useToast();- const [progress, setProgress] = useState(0);-- const [floatingInput, setFloatingInput] = useState("");- const [isFloatingInputVisible, setIsFloatingInputVisible] = useState(false);-- const floatingInputRef = useRef<HTMLInputElement>(null);- const [showScrollButton, setShowScrollButton] = useState(false);-- const [isUserScrolling, setIsUserScrolling] = useState(false);- const lastScrollPosition = useRef(0);-- const MAX_CONTENT_LENGTH = settings.aiMaxContextChars;-- const [selectedResults, setSelectedResults] = useState<Set<number>>(- new Set()- );- const [similarityThreshold, setSimilarityThreshold] = useState(1);-- const [isStreaming, setIsStreaming] = useState(false);- const abortControllerRef = useRef<AbortController | null>(null);-- const [selectAll, setSelectAll] = useState(true);-- const [showExamples, setShowExamples] = useState(true);-- const [hasSearched, setHasSearched] = useState(false);-- const [isFiltering, setIsFiltering] = useState(false);- const debouncedThreshold = useDebounce(similarityThreshold, 300);-- const [isQueryParamsDialogOpen, setIsQueryParamsDialogOpen] = useState(false);-- // Add state for individual content types- const [selectedContentTypes, setSelectedContentTypes] = useState<string[]>(- []- );-- // Define content type options- const contentTypeOptions: BaseOption[] = [- { label: "Speech", value: "audio" },- { label: "Screen UI", value: "ui" },- { label: "Screen Capture", value: "ocr" },- ];-- // Define content type descriptions for tooltips- const contentTypeDescriptions: Record<string, string> = {- audio: "audio transcripts",- ui: "text emitted directly from the source code of the desktop applications",- ocr: "recognized text from screenshots taken every 5s by default",- };- const [selectedTypes, setSelectedTypes] = useState({- ocr: false,- audio: false,- ui: false,- });-- // Add new state near the top with other state declarations- const [hideDeselected, setHideDeselected] = useState(false);-- const [currentPlatform, setCurrentPlatform] = useState<string | null>(null);-- const [speakerSearchQuery, setSpeakerSearchQuery] = useState("");-- const [frameName, setFrameName] = useState<string>("");-- // Add this state for browser URL- const [browserUrl, setBrowserUrl] = useState("");-- useEffect(() => {- if (Object.keys(selectedSpeakers).length > 0) {- setSelectedContentTypes(["audio"]);- setContentType("audio");- }- }, [selectedSpeakers]);-- useEffect(() => {- // More reliable OS detection using navigator.userAgentData when available- if ("userAgentData" in navigator) {- // @ts-ignore - TypeScript doesn't know about userAgentData yet- const platform = navigator.userAgent.toLowerCase();- setCurrentPlatform(- platform.includes("mac")- ? "macos"- : platform.includes("win")- ? "windows"- : platform.includes("linux")- ? "linux"- : "unknown"- );- } else {- // Fallback to platform for older browsers- const platform = window.navigator.platform.toLowerCase();- setCurrentPlatform(- platform.includes("mac")- ? "macos"- : platform.includes("win")- ? "windows"- : platform.includes("linux")- ? "linux"- : "unknown"- );- }- }, []);-- // Add keyboard shortcut handler- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- if (- e.key === "Enter" &&- ((currentPlatform === "macos" && e.metaKey) ||- (currentPlatform !== "macos" && e.ctrlKey))- ) {- e.preventDefault();- handleSearch(0);- }- };-- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [currentPlatform]);-- const handleSpeakerChange = (speaker: Speaker) => {- setSelectedSpeakers((prev) => {- const newSpeakers = { ...prev, [speaker.id]: speaker };-- if (prev[speaker.id]) {- delete newSpeakers[speaker.id];- }-- return newSpeakers;- });- };-- useEffect(() => {- if (isQueryParamsDialogOpen && !speakers.length) {- loadSpeakers();- }- }, [isQueryParamsDialogOpen]);-- useEffect(() => {- loadSpeakers();- }, [speakerSearchQuery]);-- const loadSpeakers = async () => {- try {- const getSpeakers = await fetch(- `http://localhost:3030/speakers/search?name=${speakerSearchQuery}`- );- const speakers = await getSpeakers.json();- setSpeakers(speakers);- } catch (error) {- console.error("Error loading speakers:", error);- setSpeakers([]);- }- };-- // Update content type when checkboxes change- const handleContentTypeChange = (values: string[]) => {- setSelectedContentTypes(values);-- // Convert selected values to content type- if (values.length === 0) {- setContentType("all");- } else if (values.length === 3) {- setContentType("all");- } else if (- values.includes("audio") &&- values.includes("ui") &&- !values.includes("ocr")- ) {- setContentType("audio+ui");- } else if (- values.includes("ocr") &&- values.includes("ui") &&- !values.includes("audio")- ) {- setContentType("ocr+ui");- } else if (- values.includes("audio") &&- values.includes("ocr") &&- !values.includes("ui")- ) {- setContentType("audio+ocr");- } else if (values.includes("audio")) {- setContentType("audio");- } else if (values.includes("ocr")) {- setContentType("ocr");- } else if (values.includes("ui")) {- setContentType("ui");- } else {- setContentType("all");- }-- // Update selectedTypes for backward compatibility- setSelectedTypes({- ocr: values.includes("ocr"),- audio: values.includes("audio"),- ui: values.includes("ui"),- });- };-- const handleContentTypeFromFilter = (contentType: string) => {- // Update content type- setContentType(contentType);-- // Update selected content types based on content type- const newSelectedTypes: string[] = [];- if (contentType === "all") {- // Keep empty to indicate all- } else {- if (contentType.includes("ocr")) newSelectedTypes.push("ocr");- if (contentType.includes("audio")) newSelectedTypes.push("audio");- if (contentType.includes("ui")) newSelectedTypes.push("ui");- }- setSelectedContentTypes(newSelectedTypes);-- // Update checkbox states for backward compatibility- setSelectedTypes({- ocr: contentType.includes("ocr") || contentType === "all",- audio: contentType.includes("audio") || contentType === "all",- ui: contentType.includes("ui") || contentType === "all",- });- };-- const [selectedAgent, setSelectedAgent] = useState<Agent>(AGENTS[0]);-- useEffect(() => {- const updateDates = () => {- const now = new Date();- setEndDate(now);- // Optionally update startDate if you want to maintain a rolling time window- // setStartDate(new Date(now.getTime() - 24 * 3600000)); // 24 hours ago- };-- // Update dates immediately- updateDates();-- // Set up interval to update dates every 5 minutes- const intervalId = setInterval(updateDates, 5 * 60 * 1000);-- // Add event listener for when the page becomes visible- document.addEventListener("visibilitychange", () => {- if (!document.hidden) {- updateDates();- }- });-- // Clean up on component unmount- return () => {- clearInterval(intervalId);- document.removeEventListener("visibilitychange", updateDates);- };- }, []);-- const isAiDisabled =- !settings.user?.token && settings.aiProviderType === "screenpipe-cloud";-- const handleExampleSelect = async (example: ExampleSearch) => {- if (isAiDisabled) {- toast({- title: "error",- description:- "your selected ai provider is screenpipe-cloud. consider login in app to use screenpipe-cloud",- variant: "destructive",- });- return;- }- const newWindowName = example.windowName || "";- const newAppName = example.appName || "";- const newLimit = example.limit || limit;- const newMinLength = example.minLength || minLength;- const newContentType =- (example.contentType as "all" | "ocr" | "audio") || contentType;- const newStartDate = example.startDate;-- setWindowName(newWindowName);- setAppName(newAppName);- setLimit(newLimit);- setMinLength(newMinLength);- setContentType(newContentType);- setStartDate(newStartDate);- setShowExamples(false);-- handleSearch(0, {- windowName: newWindowName,- appName: newAppName,- limit: newLimit,- minLength: newMinLength,- contentType: newContentType,- startDate: newStartDate,- });- };-- const generateCurlCommand = () => {- const baseUrl = "http://localhost:3030";- const params = {- content_type: contentType,- limit: limit.toString(),- offset: offset.toString(),- start_time: startDate.toISOString(),- end_time: endDate.toISOString(),- min_length: minLength.toString(),- max_length: maxLength.toString(),- q: query,- app_name: appName,- window_name: windowName,- browser_url: browserUrl,- include_frames: includeFrames ? "true" : undefined,- };-- const queryParams = Object.entries(params)- .filter(([_, value]) => value !== undefined && value !== "")- .map(([key, value]) => `${key}=${encodeURIComponent(value!)}`)- .join("&");-- return `curl "${baseUrl}/search?${queryParams}" | jq`;- };-- useEffect(() => {- if (results.length > 0) {- setSelectedResults(new Set(results.map((_, index) => index)));- setSelectAll(true);- }- }, [results]);-- useEffect(() => {- handleFilterDuplicates();- }, [debouncedThreshold, results]);-- const handleFilterDuplicates = async () => {- if (similarityThreshold === 1) {- setSelectedResults(new Set(results.map((_, index) => index)));- setSelectAll(true);- return;- }- setIsFiltering(true);- // simulate a delay to show loading state- await new Promise((resolve) => setTimeout(resolve, 100));-- const allIndices = new Set(results.map((_, index) => index));- setSelectedResults(- removeDuplicateSelections(results, allIndices, debouncedThreshold)- );- setSelectAll(false);- setIsFiltering(false);- };-- useEffect(() => {- const handleScroll = () => {- const currentScrollPosition = window.scrollY;- const scrollPercentage =- (currentScrollPosition /- (document.documentElement.scrollHeight - window.innerHeight)) *- 100;- const shouldShow = scrollPercentage < 90; // Show when scrolled up more than 10%-- setShowScrollButton(shouldShow);-- // Check if user is scrolling up while AI is loading- if (isAiLoading && currentScrollPosition < lastScrollPosition.current) {- setIsUserScrolling(true);- }-- lastScrollPosition.current = currentScrollPosition;- };-- window.addEventListener("scroll", handleScroll);-- return () => window.removeEventListener("scroll", handleScroll);- }, [isAiLoading]);-- const scrollToBottom = () => {- if (!isUserScrolling) {- window.scrollTo({- top: document.documentElement.scrollHeight,- behavior: "smooth",- });- }- };-- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === "/") {- event.preventDefault();- setIsFloatingInputVisible(true);- } else if (event.key === "Escape") {- setIsFloatingInputVisible(false);- }- };-- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, []);-- useEffect(() => {- if (isFloatingInputVisible && floatingInputRef.current) {- floatingInputRef.current.focus();- }- }, [isFloatingInputVisible]);-- const handleResultSelection = (index: number) => {- setSelectedResults((prev) => {- const newSet = new Set(prev);- if (newSet.has(index)) {- newSet.delete(index);- } else {- newSet.add(index);- }- return newSet;- });- };-- const calculateSelectedContentLength = () => {- return Array.from(selectedResults).reduce((total, index) => {- const item = results[index];- if (!item || !item.type) return total; // Add this check-- const contentLength =- item.type === "OCR"- ? item.content.text.length- : item.type === "Audio"- ? item.content.transcription.length- : item.type === "UI"- ? item.content.text.length- : 0;- return total + contentLength;- }, 0);- };-- const handleFloatingInputSubmit = async (e: React.FormEvent) => {- e.preventDefault();- if (!floatingInput.trim() && !isStreaming) return;-- if (isStreaming) {- handleStopStreaming();- return;- }-- scrollToBottom();-- const selectedContentLength = calculateSelectedContentLength();- if (selectedContentLength > MAX_CONTENT_LENGTH) {- toast({- title: "Content too large",- description: `The selected content length (${selectedContentLength} characters) exceeds the maximum allowed (${MAX_CONTENT_LENGTH} characters). Please unselect some items to reduce the amount of content.`,- variant: "destructive",- });- return;- }-- const userMessage = {- id: generateId(),- role: "user" as const,- content: floatingInput,- };- setChatMessages((prevMessages) => [- ...prevMessages,- userMessage,- { id: generateId(), role: "assistant", content: "" },- ]);- setFloatingInput("");- setIsAiLoading(true);-- try {- console.log("settings", settings);- const openai = new OpenAI({- apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,- dangerouslyAllowBrowser: true,- });-- const model = settings.aiModel;- const customPrompt = settings.customPrompt || "";-- const messages = [- {- role: "user" as const, // claude does not support system messages?- content: `You are a helpful assistant specialized as a "${- selectedAgent.name- }". ${selectedAgent.systemPrompt}+ const {+ searches,+ currentSearchId,+ setCurrentSearchId,+ addSearch,+ deleteSearch,+ isCollapsed,+ toggleCollapse,+ } = useSearchHistory();+ // Search state+ const { health, isServerDown } = useHealthCheck();+ const [query, setQuery] = useState("");+ const [results, setResults] = useState<ContentItem[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [startDate, setStartDate] = useState<Date>(+ new Date(Date.now() - 24 * 3600000),+ );+ const [endDate, setEndDate] = useState<Date>(new Date());+ const [includeFrames, setIncludeFrames] = useState(false);+ const [limit, setLimit] = useState(30);+ const [appName, setAppName] = useState("");+ const [windowName, setWindowName] = useState("");+ const [contentType, setContentType] = useState("all");+ const [offset, setOffset] = useState(0);+ const [totalResults, setTotalResults] = useState(0);+ const { settings } = useSettings();+ const { settings: settingsPipe, getPreset } = usePipeSettings("search");+ const { isAvailable, error } = useAiProvider(settings as AppSettings);+ const [isAiLoading, setIsAiLoading] = useState(false);+ const [minLength, setMinLength] = useState(50);+ const [maxLength, setMaxLength] = useState(10000);+ const [speakers, setSpeakers] = useState<Speaker[]>([]);+ const [selectedSpeakers, setSelectedSpeakers] = useState<{+ [key: number]: Speaker;+ }>({});+ const [openSpeakers, setOpenSpeakers] = useState(false);+ // Chat state+ const [chatMessages, setChatMessages] = useState<Array<Message>>([]);++ const { toast } = useToast();+ const [progress, setProgress] = useState(0);++ const [floatingInput, setFloatingInput] = useState("");+++ const floatingInputRef = useRef<HTMLInputElement>(null);+ const [showScrollButton, setShowScrollButton] = useState(false);++ const [isUserScrolling, setIsUserScrolling] = useState(false);+ const lastScrollPosition = useRef(0);++ const MAX_CONTENT_LENGTH = settings?.aiMaxContextChars ?? 51200;++ const [selectedResults, setSelectedResults] = useState<Set<number>>(+ new Set(),+ );+ const [similarityThreshold, setSimilarityThreshold] = useState(1);++ const [isStreaming, setIsStreaming] = useState(false);+ const abortControllerRef = useRef<AbortController | null>(null);++ const [selectAll, setSelectAll] = useState(true);++ const [showExamples, setShowExamples] = useState(true);++ const [hasSearched, setHasSearched] = useState(false);++ const [isFiltering, setIsFiltering] = useState(false);+ const debouncedThreshold = useDebounce(similarityThreshold, 300);++ const [isQueryParamsDialogOpen, setIsQueryParamsDialogOpen] = useState(false);++ // Add state for individual content types+ const [selectedContentTypes, setSelectedContentTypes] = useState<string[]>(+ [],+ );++ // Define content type options+ const contentTypeOptions: BaseOption[] = [+ { label: "Speech", value: "audio" },+ { label: "Screen UI", value: "ui" },+ { label: "Screen Capture", value: "ocr" },+ ];++ // Define content type descriptions for tooltips+ const contentTypeDescriptions: Record<string, string> = {+ audio: "audio transcripts",+ ui: "text emitted directly from the source code of the desktop applications",+ ocr: "recognized text from screenshots taken every 5s by default",+ };+ const [selectedTypes, setSelectedTypes] = useState({+ ocr: false,+ audio: false,+ ui: false,+ });++ // Add new state near the top with other state declarations+ const [hideDeselected, setHideDeselected] = useState(false);++ const [currentPlatform, setCurrentPlatform] = useState<string | null>(null);++ const [speakerSearchQuery, setSpeakerSearchQuery] = useState("");++ const [frameName, setFrameName] = useState<string>("");++ // Add this state for browser URL+ const [browserUrl, setBrowserUrl] = useState("");++ useEffect(() => {+ if (Object.keys(selectedSpeakers).length > 0) {+ setSelectedContentTypes(["audio"]);+ setContentType("audio");+ }+ }, [selectedSpeakers]);++ useEffect(() => {+ // More reliable OS detection using navigator.userAgentData when available+ if ("userAgentData" in navigator) {+ // @ts-ignore - TypeScript doesn't know about userAgentData yet+ const platform = navigator.userAgent.toLowerCase();+ setCurrentPlatform(+ platform.includes("mac")+ ? "macos"+ : platform.includes("win")+ ? "windows"+ : platform.includes("linux")+ ? "linux"+ : "unknown",+ );+ } else {+ // Fallback to platform for older browsers+ const platform = window.navigator.platform.toLowerCase();+ setCurrentPlatform(+ platform.includes("mac")+ ? "macos"+ : platform.includes("win")+ ? "windows"+ : platform.includes("linux")+ ? "linux"+ : "unknown",+ );+ }+ }, []);++ // Add keyboard shortcut handler+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ if (+ e.key === "Enter" &&+ ((currentPlatform === "macos" && e.metaKey) ||+ (currentPlatform !== "macos" && e.ctrlKey))+ ) {+ e.preventDefault();+ handleSearch(0);+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [currentPlatform]);++ const handleSpeakerChange = (speaker: Speaker) => {+ setSelectedSpeakers((prev) => {+ const newSpeakers = { ...prev, [speaker.id]: speaker };++ if (prev[speaker.id]) {+ delete newSpeakers[speaker.id];+ }++ return newSpeakers;+ });+ };++ useEffect(() => {+ if (isQueryParamsDialogOpen && !speakers.length) {+ loadSpeakers();+ }+ }, [isQueryParamsDialogOpen]);++ useEffect(() => {+ loadSpeakers();+ }, [speakerSearchQuery]);++ const loadSpeakers = async () => {+ try {+ const getSpeakers = await fetch(+ `http://localhost:3030/speakers/search?name=${speakerSearchQuery}`,+ );+ const speakers = await getSpeakers.json();+ setSpeakers(speakers);+ } catch (error) {+ console.error("Error loading speakers:", error);+ setSpeakers([]);+ }+ };++ // Update content type when checkboxes change+ const handleContentTypeChange = (values: string[]) => {+ setSelectedContentTypes(values);++ // Convert selected values to content type+ if (values.length === 0) {+ setContentType("all");+ } else if (values.length === 3) {+ setContentType("all");+ } else if (+ values.includes("audio") &&+ values.includes("ui") &&+ !values.includes("ocr")+ ) {+ setContentType("audio+ui");+ } else if (+ values.includes("ocr") &&+ values.includes("ui") &&+ !values.includes("audio")+ ) {+ setContentType("ocr+ui");+ } else if (+ values.includes("audio") &&+ values.includes("ocr") &&+ !values.includes("ui")+ ) {+ setContentType("audio+ocr");+ } else if (values.includes("audio")) {+ setContentType("audio");+ } else if (values.includes("ocr")) {+ setContentType("ocr");+ } else if (values.includes("ui")) {+ setContentType("ui");+ } else {+ setContentType("all");+ }++ // Update selectedTypes for backward compatibility+ setSelectedTypes({+ ocr: values.includes("ocr"),+ audio: values.includes("audio"),+ ui: values.includes("ui"),+ });+ };++ const handleContentTypeFromFilter = (contentType: string) => {+ // Update content type+ setContentType(contentType);++ // Update selected content types based on content type+ const newSelectedTypes: string[] = [];+ if (contentType === "all") {+ // Keep empty to indicate all+ } else {+ if (contentType.includes("ocr")) newSelectedTypes.push("ocr");+ if (contentType.includes("audio")) newSelectedTypes.push("audio");+ if (contentType.includes("ui")) newSelectedTypes.push("ui");+ }+ setSelectedContentTypes(newSelectedTypes);++ // Update checkbox states for backward compatibility+ setSelectedTypes({+ ocr: contentType.includes("ocr") || contentType === "all",+ audio: contentType.includes("audio") || contentType === "all",+ ui: contentType.includes("ui") || contentType === "all",+ });+ };++ const [selectedAgent, setSelectedAgent] = useState<Agent>(AGENTS[0]);++ useEffect(() => {+ const updateDates = () => {+ const now = new Date();+ setEndDate(now);+ // Optionally update startDate if you want to maintain a rolling time window+ // setStartDate(new Date(now.getTime() - 24 * 3600000)); // 24 hours ago+ };++ // Update dates immediately+ updateDates();++ // Set up interval to update dates every 5 minutes+ const intervalId = setInterval(updateDates, 5 * 60 * 1000);++ // Add event listener for when the page becomes visible+ document.addEventListener("visibilitychange", () => {+ if (!document.hidden) {+ updateDates();+ }+ });++ // Clean up on component unmount+ return () => {+ clearInterval(intervalId);+ document.removeEventListener("visibilitychange", updateDates);+ };+ }, []);++ const isAiDisabled =+ !settings?.user?.token && settings?.aiProviderType === "screenpipe-cloud";++ const handleExampleSelect = async (example: ExampleSearch) => {+ if (isAiDisabled) {+ toast({+ title: "error",+ description:+ "your selected ai provider is screenpipe-cloud. consider login in app to use screenpipe-cloud",+ variant: "destructive",+ });+ return;+ }+ const newWindowName = example.windowName || "";+ const newAppName = example.appName || "";+ const newLimit = example.limit || limit;+ const newMinLength = example.minLength || minLength;+ const newContentType =+ (example.contentType as "all" | "ocr" | "audio") || contentType;+ const newStartDate = example.startDate;++ setWindowName(newWindowName);+ setAppName(newAppName);+ setLimit(newLimit);+ setMinLength(newMinLength);+ setContentType(newContentType);+ setStartDate(newStartDate);+ setShowExamples(false);++ handleSearch(0, {+ windowName: newWindowName,+ appName: newAppName,+ limit: newLimit,+ minLength: newMinLength,+ contentType: newContentType,+ startDate: newStartDate,+ });+ };++ const generateCurlCommand = () => {+ const baseUrl = "http://localhost:3030";+ const params = {+ content_type: contentType,+ limit: limit.toString(),+ offset: offset.toString(),+ start_time: startDate.toISOString(),+ end_time: endDate.toISOString(),+ min_length: minLength.toString(),+ max_length: maxLength.toString(),+ q: query,+ app_name: appName,+ window_name: windowName,+ browser_url: browserUrl,+ include_frames: includeFrames ? "true" : undefined,+ };++ const queryParams = Object.entries(params)+ .filter(([_, value]) => value !== undefined && value !== "")+ .map(([key, value]) => `${key}=${encodeURIComponent(value!)}`)+ .join("&");++ return `curl "${baseUrl}/search?${queryParams}" | jq`;+ };++ useEffect(() => {+ if (results.length > 0) {+ setSelectedResults(new Set(results.map((_, index) => index)));+ setSelectAll(true);+ }+ }, [results]);++ useEffect(() => {+ handleFilterDuplicates();+ }, [debouncedThreshold, results]);++ const handleFilterDuplicates = async () => {+ if (similarityThreshold === 1) {+ setSelectedResults(new Set(results.map((_, index) => index)));+ setSelectAll(true);+ return;+ }+ setIsFiltering(true);+ // simulate a delay to show loading state+ await new Promise((resolve) => setTimeout(resolve, 100));++ const allIndices = new Set(results.map((_, index) => index));+ setSelectedResults(+ removeDuplicateSelections(results, allIndices, debouncedThreshold),+ );+ setSelectAll(false);+ setIsFiltering(false);+ };++ useEffect(() => {+ const handleScroll = () => {+ const currentScrollPosition = window.scrollY;+ const scrollPercentage =+ (currentScrollPosition /+ (document.documentElement.scrollHeight - window.innerHeight)) *+ 100;+ const shouldShow = scrollPercentage < 90; // Show when scrolled up more than 10%++ setShowScrollButton(shouldShow);++ // Check if user is scrolling up while AI is loading+ if (isAiLoading && currentScrollPosition < lastScrollPosition.current) {+ setIsUserScrolling(true);+ }++ lastScrollPosition.current = currentScrollPosition;+ };++ window.addEventListener("scroll", handleScroll);++ return () => window.removeEventListener("scroll", handleScroll);+ }, [isAiLoading]);++ const scrollToBottom = () => {+ if (!isUserScrolling) {+ window.scrollTo({+ top: document.documentElement.scrollHeight,+ behavior: "smooth",+ });+ }+ };++++ const handleResultSelection = (index: number) => {+ setSelectedResults((prev) => {+ const newSet = new Set(prev);+ if (newSet.has(index)) {+ newSet.delete(index);+ } else {+ newSet.add(index);+ }+ return newSet;+ });+ };++ const calculateSelectedContentLength = () => {+ return Array.from(selectedResults).reduce((total, index) => {+ const item = results[index];+ if (!item || !item.type) return total; // Add this check++ const contentLength =+ item.type === "OCR"+ ? item.content.text.length+ : item.type === "Audio"+ ? item.content.transcription.length+ : item.type === "UI"+ ? item.content.text.length+ : 0;+ return total + contentLength;+ }, 0);+ };++ const handleFloatingInputSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!floatingInput.trim() && !isStreaming) return;++ if (isStreaming) {+ handleStopStreaming();+ return;+ }++ scrollToBottom();++ const selectedContentLength = calculateSelectedContentLength();+ if (selectedContentLength > MAX_CONTENT_LENGTH) {+ toast({+ title: "Content too large",+ description: `The selected content length (${selectedContentLength} characters) exceeds the maximum allowed (${MAX_CONTENT_LENGTH} characters). Please unselect some items to reduce the amount of content.`,+ variant: "destructive",+ });+ return;+ }++ const userMessage = {+ id: generateId(),+ role: "user" as const,+ content: floatingInput,+ };+ setChatMessages((prevMessages) => [+ ...prevMessages,+ userMessage,+ { id: generateId(), role: "assistant", content: "" },+ ]);+ setFloatingInput("");+ setIsAiLoading(true);++ const preset = getPreset();++ if (!preset) {+ toast({+ title: "there is no ai settings selected",+ description: "please create new or select existing ones",+ variant: "destructive",+ });+ return;+ }++ let apiKey = "";+ if (preset.provider === "openai" || preset.provider === "custom") {+ if ("apiKey" in preset) {+ apiKey == preset.apiKey;+ } else {+ toast({+ title: "please provide api key",+ description: "api key is required",+ variant: "destructive",+ });+ return;+ }+ }++ try {+ console.log("settings", preset);+ const openai = new OpenAI({+ apiKey:+ preset.provider === "screenpipe-cloud"+ ? settings?.user?.token+ : apiKey,+ baseURL: preset.url,+ dangerouslyAllowBrowser: true,+ });++ const model = preset.model;+ const customPrompt = preset.prompt || "";++ const messages = [+ {+ role: "user" as const, // claude does not support system messages?+ content: `You are a helpful assistant specialized as a "${+ selectedAgent.name+ }". ${selectedAgent.systemPrompt}Rules:- Current time (JavaScript Date.prototype.toString): ${new Date().toString()}- User timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}- User timezone offset: ${new Date().getTimezoneOffset()}- ${customPrompt ? `Custom prompt: ${customPrompt}` : ""}`,- },- ...chatMessages.map((msg) => ({- role: msg.role as "user" | "assistant" | "system",- content: msg.content,- })),- {- role: "user" as const,- content: `Context data: ${JSON.stringify(- selectedAgent.dataSelector(- results.filter((_, index) => selectedResults.has(index))- )- )}+ },+ ...chatMessages.map((msg) => ({+ role: msg.role as "user" | "assistant" | "system",+ content: msg.content,+ })),+ {+ role: "user" as const,+ content: `Context data: ${JSON.stringify(+ selectedAgent.dataSelector(+ results.filter((_, index) => selectedResults.has(index)),+ ),+ )}User query: ${floatingInput}`,- },- ];-- console.log("messages", messages);-- abortControllerRef.current = new AbortController();- setIsStreaming(true);-- const stream = await openai.chat.completions.create(- {- model: model,- messages: messages,- stream: true,- },- {- signal: abortControllerRef.current.signal,- }- );-- let fullResponse = "";- // @ts-ignore- setChatMessages((prevMessages) => [- ...prevMessages.slice(0, -1),- { id: generateId(), role: "assistant", content: fullResponse },- ]);-- setIsUserScrolling(false);- lastScrollPosition.current = window.scrollY;- scrollToBottom();-- for await (const chunk of stream) {- console.log("chunk", chunk);- const content = chunk.choices[0]?.delta?.content || "";- fullResponse += content;- // @ts-ignore- setChatMessages((prevMessages) => [- ...prevMessages.slice(0, -1),- { id: generateId(), role: "assistant", content: fullResponse },- ]);- scrollToBottom();- }- } catch (error: any) {- if (error.toString().includes("unauthorized")) {- toast({- title: "Error",- description: "Please sign in to use AI features",- variant: "destructive",- });- } else if (error.toString().includes("aborted")) {- console.log("Streaming was aborted");- } else {- console.error("Error generating AI response:", error);- toast({- title: "Error",- description: "Failed to generate AI response. Please try again.",- variant: "destructive",- });- }- } finally {- setIsAiLoading(false);- setIsFloatingInputVisible(false);- setIsStreaming(false);- if (!isUserScrolling) {- scrollToBottom();- }- }- };-- const handleStopStreaming = () => {- if (abortControllerRef.current) {- abortControllerRef.current.abort();- setIsStreaming(false);- setIsAiLoading(false);- }- };-- const handleSearch = async (newOffset = 0, overrides: any = {}) => {- if (isAiDisabled) {- toast({- title: "error",- description:- "your ai provider is screenpipe-cloud. consider login in app to use screenpipe-cloud",- duration: 3000,- variant: "destructive",- });- return;- }- await pipe.captureMainFeatureEvent("search", {- contentType: overrides.contentType || contentType,- limit: overrides.limit || limit,- offset: newOffset,- startDate: overrides.startDate || startDate,- });- setHasSearched(true);- setShowExamples(false);- setIsLoading(true);- setOffset(newOffset);- setProgress(0);- setChatMessages([]);- scrollToBottom();- setResults([]);- setSimilarityThreshold(1); // Reset similarity threshold to 1-- try {- // if browserUrl contains special characters like :, /, etc, wrap in double quotes- // bcs it's FTS- const bUrl = browserUrl.includes(":") ? `"${browserUrl}"` : browserUrl;- const wName = windowName.includes(":") ? `"${windowName}"` : windowName;- const aName = appName.includes(":") ? `"${appName}"` : appName;- const searchParams = {- q: query || undefined,- contentType: overrides.contentType || contentType,- limit: overrides.limit || limit,- offset: newOffset,- startTime:- overrides.startDate?.toISOString() || startDate.toISOString(),- endTime: endDate.toISOString(),- appName: overrides.appName || appName || undefined,- windowName: overrides.windowName || windowName || undefined,- browserUrl: bUrl || undefined,- includeFrames: includeFrames,- minLength: overrides.minLength || minLength,- maxLength: maxLength,- speakerIds: Object.values(selectedSpeakers).map(- (speaker) => speaker.id- ),- ...(frameName && { frame_name: frameName }),- };-- const response = await pipe.queryScreenpipe(searchParams);-- // Add debug logging- console.log("search response:", response);-- if (!response || !Array.isArray(response.data)) {- throw new Error("invalid response data");- }-- setResults(response.data);- setTotalResults(response.pagination.total);-- // Save search to history- // await onAddSearch(searchParams, response.data);- } catch (error) {- console.error("search error:", error);- toast({- title: "error",- description: "failed to fetch search results. please try again.",- variant: "destructive",- });- setResults([]);- setTotalResults(0);- } finally {- setIsLoading(false);- }- };-- const handleNextPage = () => {- if (offset + limit < totalResults) {- handleSearch(offset + limit);- }- };-- const handlePrevPage = () => {- if (offset - limit >= 0) {- handleSearch(offset - limit);- }- };-- const handleBadgeClick = (value: string, type: "app" | "window") => {- if (type === "app") {- setAppName(value);- } else if (type === "window") {- setWindowName(value);- }- handleSearch(0);- };-- const handleSelectAll = (checked: boolean) => {- setSelectAll(checked);- if (checked) {- setSelectedResults(new Set(results.map((_, index) => index)));- } else {- setSelectedResults(new Set());- }- };-- const handleQuickTimeFilter = (minutes: number) => {- const now = new Date();- const newStartDate = new Date(now.getTime() - minutes * 60000);- setStartDate(newStartDate);- setEndDate(now);- };-- const renderSearchResults = () => {- if (isLoading) {- return Array(3)- .fill(0)- .map((_, index) => (- <Card key={index}>- <CardContent className="p-4">- <Skeleton className="h-4 w-1/4 mb-2" />- <Skeleton className="h-4 w-full mb-2" />- <Skeleton className="h-4 w-full mb-2" />- <Skeleton className="h-4 w-3/4" />- </CardContent>- </Card>- ));- }-- if (hasSearched && results.length === 0) {- return <p className="text-center">no results found</p>;- }-- if (!hasSearched || results.length === 0) {- return null;- }-- // First filter results based on hideDeselected setting- const visibleResults = results- .map((item, index) => ({ item, originalIndex: index }))- .filter(- ({ originalIndex }) =>- !hideDeselected || selectedResults.has(originalIndex)- );-- return visibleResults.map(({ item, originalIndex }) => (- <motion.div- key={originalIndex}- className="flex items-center mb-4 relative pl-8"- >- <div className="absolute left-0 top-1/2 transform -translate-y-1/2">- <Checkbox- checked={selectedResults.has(originalIndex)}- onCheckedChange={() => handleResultSelection(originalIndex)}- />- </div>- <Card className="w-full">- <CardContent className="p-4">- <Accordion type="single" collapsible className="w-full">- <AccordionItem value={`item-${originalIndex}`}>- <AccordionTrigger className="flex flex-col w-full py-2">- {/* Main content */}- <div className="flex w-full items-center gap-2">- <span className="text-left truncate">- {item.type === "OCR" &&- highlightKeyword(- getContextAroundKeyword(item.content.text, query),- query- )}- {item.type === "Audio" &&- highlightKeyword(- getContextAroundKeyword(- item.content.transcription,- query- ),- query- )}- {item.type === "UI" &&- highlightKeyword(- getContextAroundKeyword(item.content.text, query),- query- )}- </span>- </div>- </AccordionTrigger>- <AccordionContent>- {item.type === "UI" && (- <>- <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">- <p className="whitespace-pre-line">- {highlightKeyword(item.content.text, query)}- </p>- </div>- <div className="flex justify-center mt-4">- <VideoComponent filePath={item.content.filePath} />- </div>- <div className="flex flex-wrap items-center gap-2 mt-2">- {item.content.appName && (- <Badge- className="text-xs cursor-pointer"- onClick={() =>- handleBadgeClick(item.content.appName, "app")- }- >- {item.content.appName}- </Badge>- )}- {item.content.windowName && (- <Badge- className="text-xs cursor-pointer"- onClick={() =>- handleBadgeClick(- item.content.windowName,- "window"- )- }- >- {item.content.windowName}- </Badge>- )}- </div>- </>- )}- {item.type === "OCR" && (- <>- <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">- <p className="whitespace-pre-line">- {highlightKeyword(item.content.text, query)}- </p>- </div>- <div className="flex justify-center mt-4">- <VideoComponent filePath={item.content.filePath} />- </div>- {includeFrames && item.content.frame && (- <div className="mt-2 flex items-center">- <Dialog>- <DialogTrigger asChild>- <img- src={`data:image/jpeg;base64,${item.content.frame}`}- alt="Frame"- className="w-24 h-auto cursor-pointer"- />- </DialogTrigger>- <DialogContent className="sm:max-w-[80vw]">- <img- src={`data:image/jpeg;base64,${item.content.frame}`}- alt="Frame"- className="w-full h-auto"- />- </DialogContent>- </Dialog>- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>this is the frame where the text appeared</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- )}- </>- )}- {item.type === "Audio" && (- <>- <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">- <p className="whitespace-pre-line">- {highlightKeyword(item.content.transcription, query)}- </p>- </div>- {item.content.filePath &&- item.content.filePath.trim() !== "" ? (- <div className="flex justify-center mt-4">- <VideoComponent- filePath={item.content.filePath}- startTime={item.content.startTime}- endTime={item.content.endTime}- speaker={item.content.speaker}- />- </div>- ) : (- <p className="text-gray-500 italic mt-2">- no file path available for this audio.- </p>- )}- </>- )}- </AccordionContent>- </AccordionItem>- </Accordion>- <div className="flex flex-wrap items-center gap-2 mt-2">- <Badge variant="outline" className="text-xs">- {item.type}- </Badge>- <p className="text-xs text-gray-400">- {new Date(item.content.timestamp).toLocaleString()}{" "}- {/* Display local time */}- </p>- {item.type === "Audio" && item.content.speaker?.name && (- <p className="text-xs text-gray-400">- {item.content.speaker.name}- </p>- )}- {item.type === "OCR" && item.content.appName && (- <div className="flex items-center gap-1">- <span className="text-xs text-muted-foreground">app:</span>- <Badge- className="text-xs cursor-pointer"- onClick={() =>- handleBadgeClick(item.content.appName, "app")- }- >- {item.content.appName}- </Badge>- </div>- )}- {item.type === "OCR" && item.content.browserUrl && (- <div className="flex items-center gap-1">- <span className="text-xs text-muted-foreground">url:</span>- <div className="flex items-center">- <Badge- className="text-xs cursor-pointer "- title={item.content.browserUrl}- onClick={() =>- window.open(- item.content.browserUrl,- "_blank",- "noreferrer"- )- }- >- {new URL(item.content.browserUrl).hostname}- </Badge>- <Button- variant="outline"- size="icon"- className="h-5 w-5 ml-0.5"- onClick={(e) => {- e.stopPropagation();- navigator.clipboard.writeText(item.content.browserUrl!);- toast({- title: "copied",- description: "url copied to clipboard",- duration: 2000,- });- }}- title="copy url"- >- <Copy className="h-3 w-3" />- </Button>- </div>- </div>- )}- {item.type === "OCR" && item.content.windowName && (- <div className="flex items-center gap-1">- <span className="text-xs text-muted-foreground">window:</span>- <Badge- className="text-xs cursor-pointer"- onClick={() =>- handleBadgeClick(item.content.windowName, "window")- }- >- {item.content.windowName}- </Badge>- </div>- )}- {"tags" in item.content &&- item.content.tags &&- item.content.tags.map((tag: string, index: number) => (- <Badge key={index} className="text-xs">- {tag}- </Badge>- ))}- </div>- </CardContent>- </Card>- </motion.div>- ));- };-- // Add effect to restore search when currentSearchId changes- useEffect(() => {- // if (currentSearchId) {- const selectedSearch = searches.find((s) => s.id === currentSearchId);- if (selectedSearch) {- // Restore search parameters- setQuery(selectedSearch.searchParams.q || "");- setContentType(selectedSearch.searchParams.content_type);- setLimit(selectedSearch.searchParams.limit);- setStartDate(new Date(selectedSearch.searchParams.start_time));- setEndDate(new Date(selectedSearch.searchParams.end_time));- setAppName(selectedSearch.searchParams.app_name || "");- setWindowName(selectedSearch.searchParams.window_name || "");- setIncludeFrames(selectedSearch.searchParams.include_frames);- setMinLength(selectedSearch.searchParams.min_length);- setMaxLength(selectedSearch.searchParams.max_length);-- // Restore results- setResults(selectedSearch.results);- setTotalResults(selectedSearch.results.length);- setHasSearched(true);- setShowExamples(false);-- // Restore messages if any- if (selectedSearch.messages) {- setChatMessages(- selectedSearch.messages.map((msg) => ({- id: msg.id,- role: msg.type === "ai" ? "assistant" : "user",- content: msg.content,- }))- );- }- }- // }- }, [currentSearchId, searches]);-- const handleNewSearch = () => {- // setCurrentSearchId(null);- location.reload();- // Add any other reset logic you need- };-- // Add this effect near other useEffect hooks- useEffect(() => {- const handleKeyDown = (e: KeyboardEvent) => {- // Check for Cmd+Shift (macOS) or Ctrl+Shift (Windows/Linux)- if (- e.shiftKey &&- ((currentPlatform === "macos" && e.metaKey) ||- (currentPlatform !== "macos" && e.ctrlKey)) &&- !e.altKey && // ensure alt/option isn't pressed- !e.key.match(/^[a-zA-Z0-9]$/) // prevent triggering on letter/number keys- ) {- e.preventDefault();- if (floatingInputRef.current && results.length > 0) {- handleFloatingInputSubmit(new Event("submit") as any);- }- }- };-- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [currentPlatform, results.length, floatingInput, isStreaming]);-- return (- <div className="w-full max-w-4xl mx-auto p-4 mt-12">- <div className="fixed top-4 left-4 z-50 flex items-center gap-2">- {/* <SidebarTrigger className="h-8 w-8" /> */}- <Button- variant="ghost"- size="icon"- onClick={handleNewSearch}- className="h-8 w-8"- >- <Plus className="h-4 w-4" />- </Button>- </div>-- <div className="flex items-center justify-center mb-16">- {/* Add the new SearchFilterGenerator component */}- <SearchFilterGenerator- onApplyFilters={(filters) => {- // Always use empty string instead of undefined for text inputs- setQuery(filters.query ?? "");- setAppName(filters.appName ?? "");- setWindowName(filters.windowName ?? "");-- // Use default values for other types- handleContentTypeFromFilter(filters.contentType ?? "all");- setStartDate(- filters.startDate ?? new Date(Date.now() - 24 * 3600000)- );- setEndDate(filters.endDate ?? new Date());- setLimit(filters.limit ?? 30);-- // Automatically perform search with new filters- handleSearch(0);- }}- />- </div>- {/* Content Type Checkboxes and Code Button */}- <div className="flex items-center justify-center mb-4 gap-4">- {/* Remove MultiSelectCombobox from here */}-- {/* Add browser URL input */}- <SqlAutocompleteInput- id="browser-url"- type="url"- value={browserUrl}- onChange={setBrowserUrl}- placeholder="filter by browser URL"- className="w-[350px]"- icon={<Search className="h-4 w-4" />}- />-- {/* Window name filter - increased width */}- <SqlAutocompleteInput- id="window-name"- type="window"- value={windowName}- onChange={setWindowName}- placeholder="filter by window"- className="w-[350px]"- icon={<Layout className="h-4 w-4" />}- />-- {/* Advanced button */}- <Button- variant="outline"- onClick={() => setIsQueryParamsDialogOpen(true)}- >- <Settings className="h-4 w-4" />- </Button>-- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <span>- <Button- onClick={() => handleSearch(0)}- disabled={- isLoading ||- isAiDisabled ||- !health ||- health?.status === "error"- }- className="disabled:cursor-not-allowed"- >- {isLoading ? (- <>- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- searching...- </>- ) : (- <>- <Search className="mr-2 h-4 w-4" />- {currentPlatform === "macos" ? "⌘" : "ctrl"} + ↵- </>- )}- </Button>- </span>- </TooltipTrigger>- {(!health || health?.status === "error" || isAiDisabled) && (- <TooltipContent>- <p>- {isAiDisabled && isServerDown ? (- <>- <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />- you don't have access to screenpipe-cloud <br /> and- screenpipe server is down!- </>- ) : isServerDown ? (- <>- <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />- screenpipe is not running...- </>- ) : isAiDisabled ? (- <>- <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />- you don't have access to screenpipe-cloud :( <br /> please- consider login!- </>- ) : (- ""- )}- </p>- </TooltipContent>- )}- </Tooltip>- </TooltipProvider>- </div>-- {/* Quick time filter badges */}- <div className="flex mt-2 mb-4 space-x-2 justify-center">- <Badge- variant="outline"- className="cursor-pointer hover:bg-secondary"- onClick={() => handleQuickTimeFilter(30)}- >- <Clock className="mr-2 h-4 w-4" />- last 30m- </Badge>- <Badge- variant="outline"- className="cursor-pointer hover:bg-secondary"- onClick={() => handleQuickTimeFilter(60)}- >- <Clock className="mr-2 h-4 w-4" />- last 60m- </Badge>- <Badge- variant="outline"- className="cursor-pointer hover:bg-secondary"- onClick={() => handleQuickTimeFilter(24 * 60)}- >- <Clock className="mr-2 h-4 w-4" />- last 24h- </Badge>- <Badge- variant="outline"- className="cursor-pointer hover:bg-secondary"- onClick={() => handleQuickTimeFilter(7 * 24 * 60)}- >- <Clock className="mr-2 h-4 w-4" />- last 7d- </Badge>- <Badge- variant="outline"- className="cursor-pointer hover:bg-secondary"- onClick={() => handleQuickTimeFilter(30 * 24 * 60)}- >- <Clock className="mr-2 h-4 w-4" />- last 30d- </Badge>- </div>-- <Dialog- open={isQueryParamsDialogOpen}- onOpenChange={setIsQueryParamsDialogOpen}- >- <DialogContent className="sm:max-w-[705px] max-h-[80vh] overflow-y-auto">- <DialogHeader>- <DialogTitle>advanced search parameters</DialogTitle>- <DialogDescription>- adjust additional search parameters here.- </DialogDescription>- </DialogHeader>- <div className="grid gap-4 py-4">- {/* Add the curl command button at the top */}- <div className="flex justify-end">- <Dialog>- <DialogTrigger asChild>- <Button variant="outline" className="text-sm">- <IconCode className="h-4 w-4 mx-2" />- curl command- </Button>- </DialogTrigger>- <DialogContent className="max-w-2xl">- <DialogHeader>- <DialogTitle>curl command</DialogTitle>- <DialogDescription>- you can use this curl command to make the same search- request from the command line.- <br />- <br />- <span className="text-xs text-gray-500">- note: you need to have `jq` installed to use the- command.- </span>{" "}- </DialogDescription>- </DialogHeader>- <div className="overflow-x-auto">- <CodeBlock language="bash" value={generateCurlCommand()} />- </div>- </DialogContent>- </Dialog>- </div>-- {/* Move content type selection here */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="content-type" className="text-right">- content type- </Label>- <div className="col-span-3">- <MultiSelectCombobox- label="content type"- options={contentTypeOptions}- value={selectedContentTypes}- onChange={handleContentTypeChange}- placeholder="Filter by content type..."- renderItem={(option) => (- <div className="flex items-center justify-between w-full">- <span>{option.label}</span>- <span className="text-xs text-muted-foreground items-end">- {contentTypeDescriptions[option.value]}- </span>- </div>- )}- renderSelectedItem={(values) => (- <div className="flex gap-1 items-center">- {values.length === 0 ? (- <span>All content types</span>- ) : (- <>- {values.map((value) => {- const option = contentTypeOptions.find(- (opt) => opt.value === value- );- return option ? (- <Badge- key={value}- variant="secondary"- className="gap-1 px-1.5"- >- {option.label}- </Badge>- ) : null;- })}- </>- )}- </div>- )}- />- </div>- </div>-- {/* Add keyword search field */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="keyword-search" className="text-right">- keyword search- </Label>- <div className="col-span-3 flex items-center">- <Input- id="keyword-search"- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="search for specific keywords"- className="flex-grow"- autoCorrect="off"- autoComplete="off"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>search for specific keywords in all content</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>-- {/* Add browser URL field in advanced settings too */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="browser-url" className="text-right">- browser URL- </Label>- <div className="col-span-3 flex items-center">- <Input- id="browser-url"- type="text"- value={browserUrl}- onChange={(e) => setBrowserUrl(e.target.value)}- placeholder="filter by browser URL"- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>filter results by specific browser URLs</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>-- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="speakers" className="text-right">- speakers- </Label>- <div className="col-span-3 w-full">- <MultiSelectCombobox- label="speakers"- options={speakers.map((speaker) => ({- label: speaker.name || `Speaker ${speaker.id}`,- value: speaker.id.toString(),- }))}- value={Object.values(selectedSpeakers).map((speaker) =>- speaker.id.toString()- )}- onChange={(selectedIds) => {- // Convert from array of IDs to object with speaker objects- const newSelectedSpeakers: { [key: number]: Speaker } = {};- selectedIds.forEach((id) => {- const speakerId = parseInt(id);- const speaker = speakers.find((s) => s.id === speakerId);- if (speaker) {- newSelectedSpeakers[speakerId] = speaker;- }- });- setSelectedSpeakers(newSelectedSpeakers);- }}- placeholder="Search speakers..."- renderItem={(option) => (- <div className="flex items-center justify-between w-full">- <span>{option.label}</span>- </div>- )}- renderSelectedItem={(values) => (- <div className="flex gap-1 items-center w-full">- {values.length === 0 ? (- <span>Select speakers</span>- ) : (- <>- {values.map((value) => {- const speaker = speakers.find(- (s) => s.id.toString() === value- );- return speaker ? (- <Badge- key={value}- variant="secondary"- className="gap-1 px-1.5"- >- {speaker.name || `Speaker ${speaker.id}`}- </Badge>- ) : null;- })}- </>- )}- </div>- )}- />- </div>- </div>-- {/* Add date pickers here */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="start-date" className="text-right">- start date- </Label>- <div className="col-span-3">- <DateTimePicker- date={startDate}- setDate={setStartDate}- className="w-full"- />- </div>- </div>-- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="end-date" className="text-right">- end date- </Label>- <div className="col-span-3">- <DateTimePicker- date={endDate}- setDate={setEndDate}- className="w-full"- />- </div>- </div>-- {/* Rest of the advanced settings content */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="app-name" className="text-right">- app name- </Label>- <div className="col-span-3 flex items-center">- <SqlAutocompleteInput- id="app-name"- type="app"- icon={<Laptop className="h-4 w-4" />}- value={appName}- onChange={setAppName}- placeholder="filter by app name"- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>filter results by specific application names</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>-- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="min-length" className="text-right">- min length- </Label>- <div className="col-span-3 flex items-center">- <Input- id="min-length"- type="number"- value={minLength}- onChange={(e) => setMinLength(Number(e.target.value))}- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- enter the minimum length of the content to search for- <br />- usually transcriptions are short while text extracted- from images can be long.- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="max-length" className="text-right">- max length- </Label>- <div className="col-span-3 flex items-center">- <Input- id="max-length"- type="number"- value={maxLength}- onChange={(e) => setMaxLength(Number(e.target.value))}- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- enter the maximum length of the content to search for- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>-- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="limit-slider" className="text-right">- page size: {limit}- </Label>- <div className="col-span-3 flex items-center">- <Slider- id="limit-slider"- value={[limit]}- onValueChange={(value: number[]) => setLimit(value[0])}- min={10}- max={15000}- step={10}- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- select the number of results to display. usually ai- cannot ingest more than 30 OCR results at a time and- 1000 audio results at a time.- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>- </div>-- {/* Add frame name input after app name */}- <div className="grid grid-cols-4 items-center gap-4">- <Label htmlFor="frame-name" className="text-right">- frame name- </Label>- <div className="col-span-3 flex items-center">- <Input- id="frame-name"- type="text"- value={frameName}- onChange={(e) => setFrameName(e.target.value)}- placeholder="filter by frame name"- className="flex-grow"- />- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- filter results by specific frame names (by default frame- name is mp4 video file path)- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>- <div className="flex items-center justify-center space-x-2">- <Switch- id="include-frames"- checked={includeFrames}- onCheckedChange={setIncludeFrames}- />- <Label htmlFor="include-frames">include frames</Label>- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>- include frames in the search results. this shows the frame- where the text appeared. only works for ocr. this may slow- down the search.- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- <DialogFooter>- <Button onClick={() => setIsQueryParamsDialogOpen(false)}>- done- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- {isLoading ? (- <div className="my-8 flex justify-center">- <Loader2 className="h-8 w-8 animate-spin" />- </div>- ) : (- showExamples &&- results.length === 0 && (- <div className="my-8 flex justify-center">- <ExampleSearchCards onSelect={handleExampleSelect} />- </div>- )- )}- {isLoading && (- <div className="my-2">- <Progress value={progress} className="w-full" />- </div>- )}- {results.length > 0 && (- <div className="flex flex-col space-y-4 mb-4 my-8">- <div className="flex justify-between items-center">- <div className="flex items-center space-x-4">- <div className="flex items-center space-x-2">- <Checkbox- id="select-all"- checked={selectAll}- onCheckedChange={handleSelectAll}- />- <Label htmlFor="select-all">select all results</Label>- </div>-- <Separator orientation="vertical" className="h-4" />-- <div className="flex items-center space-x-2">- <Switch- id="hide-deselected"- checked={hideDeselected}- onCheckedChange={setHideDeselected}- />- <Label htmlFor="hide-deselected">hide unselected</Label>- </div>- </div>-- <div className="flex items-center space-x-2">- <Button- variant="outline"- size="sm"- onClick={() => {}}- disabled={isFiltering}- className="flex items-center gap-2 disabled:opacity-100"- >- {isFiltering ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : similarityThreshold === 0.5 ? (- <Check className="h-4 w-4" />- ) : (- <Layers className="h-4 w-4" />- )}- {similarityThreshold === 0.5- ? "duplicates removed"- : "remove duplicates"}- </Button>-- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <HelpCircle className="h-4 w-4 text-gray-400 cursor-help" />- </TooltipTrigger>- <TooltipContent>- <p>automatically unselect similar or duplicate results</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </div>- </div>- )}- <div className="space-y-4">- {renderSearchResults()}- {totalResults > 0 && (- <div className="flex justify-between items-center mt-4">- <Button- onClick={handlePrevPage}- disabled={offset === 0}- variant="outline"- size="sm"- >- <ChevronLeft className="mr-2 h-4 w-4" /> Previous- </Button>- <span className="text-sm text-gray-500">- Showing {offset + 1} - {Math.min(offset + limit, totalResults)} of{" "}- {totalResults}- </span>- <Button- onClick={handleNextPage}- disabled={offset + limit >= totalResults}- variant="outline"- size="sm"- >- Next <ChevronRight className="ml-2 h-4 w-4" />- </Button>- </div>- )}- </div>-- <AnimatePresence>- {results.length > 0 && (- <motion.div- initial={{ opacity: 0, y: 50 }}- animate={{ opacity: 1, y: 0 }}- exit={{ opacity: 0, y: 50 }}- className="fixed bottom-4 left-0 right-0 mx-auto w-full max-w-2xl z-50"- >- <form- onSubmit={handleFloatingInputSubmit}- className="flex flex-col space-y-2 bg-white dark:bg-gray-800 shadow-lg rounded-lg overflow-hidden p-4 border border-gray-200 dark:border-gray-700"- >- <div className="relative flex-grow flex items-center space-x-2">- <TooltipProvider>- <Tooltip>- <TooltipTrigger>- <div className="text-muted-foreground">- <Bot className="h-4 w-4 mr-2" />- </div>- </TooltipTrigger>- <TooltipContent>- <p>using {settings.aiModel}</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- <TooltipProvider>- <Tooltip open={!isAvailable}>- <TooltipTrigger asChild>- <div className="flex-1">- <Input- ref={floatingInputRef}- type="text"- placeholder="ask a question about the results..."- value={floatingInput}- disabled={- calculateSelectedContentLength() >- MAX_CONTENT_LENGTH ||- isAiDisabled ||- !isAvailable- }- onChange={(e) => setFloatingInput(e.target.value)}- className="flex-1 h-12 focus:outline-none focus:ring-0 border-0 focus:border-black dark:focus:border-white focus:border-b transition-all duration-200"- />- </div>- </TooltipTrigger>- <TooltipContent side="top">- <p className="text-sm text-destructive">{error}</p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- <Select- value={selectedAgent.id}- onValueChange={(value) =>- setSelectedAgent(- AGENTS.find((a) => a.id === value) || AGENTS[0]- )- }- >- <SelectTrigger- className="w-[170px] h-12"- title={selectedAgent.description}- >- <SelectValue placeholder="select agent" />- </SelectTrigger>- <SelectContent>- {AGENTS.map((agent) => (- <SelectItem- key={agent.id}- value={agent.id}- title={- AGENTS.find((a) => a.id === agent.id)?.description- }- >- <span className="font-mono text-sm">{agent.name}</span>- </SelectItem>- ))}- </SelectContent>- </Select>-- <Button- type="submit"- className="w-12"- disabled={- calculateSelectedContentLength() > MAX_CONTENT_LENGTH ||- isAiDisabled- }- title={- isAiDisabled- ? "Please sign in to use AI features"- : `${currentPlatform === "macos" ? "⌘" : "ctrl"}+shift`- }- >- {isStreaming ? (- <Square className="h-4 w-4" />- ) : (- <div className="flex items-center">- <Send className="h-4 w-4" />- <span className="sr-only">- {currentPlatform === "macos" ? "⌘" : "ctrl"}+shift- </span>- </div>- )}- </Button>-- <TooltipProvider>- <Tooltip>- <TooltipTrigger asChild>- <span>- <ContextUsageIndicator- currentSize={calculateSelectedContentLength()}- maxSize={MAX_CONTENT_LENGTH}- />- </span>- </TooltipTrigger>- <TooltipContent>- <p className="text-sm">- {calculateSelectedContentLength() > MAX_CONTENT_LENGTH- ? `selected content exceeds maximum allowed: ${calculateSelectedContentLength()} / ${MAX_CONTENT_LENGTH} characters. unselect some items to use AI.`- : `${calculateSelectedContentLength()} / ${MAX_CONTENT_LENGTH} characters used for AI message`}- <br />- <span className="text-muted-foreground mt-1 block">- ai models can only process a limited amount of text at- once. the circle indicates your current usage.- </span>- </p>- </TooltipContent>- </Tooltip>- </TooltipProvider>- </div>- </form>- </motion.div>- )}- </AnimatePresence>-- {results.length > 0 && <Separator className="my-8" />}-- {/* Display chat messages - Update this section */}- {(chatMessages.length > 0 || isAiLoading) && (- <>- <div className="flex flex-col items-start flex-1 max-w-2xl gap-8 px-4 mx-auto">- {chatMessages.map((msg, index) => (- <ChatMessage key={index} message={msg} />- ))}- {isAiLoading && spinner}- </div>- </>- )}-- {/* Scroll to Bottom Button */}- {showScrollButton && (- <Button- className="fixed bottom-4 right-4 rounded-full p-2"- onClick={scrollToBottom}- >- <ChevronDown className="h-6 w-6" />- </Button>- )}- {results.length > 0 && <div className="h-32" />}- </div>- );+ },+ ];++ console.log("messages", messages);++ abortControllerRef.current = new AbortController();+ setIsStreaming(true);++ const stream = await openai.chat.completions.create(+ {+ model: model,+ messages: messages,+ stream: true,+ },+ {+ signal: abortControllerRef.current.signal,+ },+ );++ let fullResponse = "";+ // @ts-ignore+ setChatMessages((prevMessages) => [+ ...prevMessages.slice(0, -1),+ { id: generateId(), role: "assistant", content: fullResponse },+ ]);++ setIsUserScrolling(false);+ lastScrollPosition.current = window.scrollY;+ scrollToBottom();++ for await (const chunk of stream) {+ console.log("chunk", chunk);+ const content = chunk.choices[0]?.delta?.content || "";+ fullResponse += content;+ // @ts-ignore+ setChatMessages((prevMessages) => [+ ...prevMessages.slice(0, -1),+ { id: generateId(), role: "assistant", content: fullResponse },+ ]);+ scrollToBottom();+ }+ } catch (error: any) {+ if (error.toString().includes("unauthorized")) {+ toast({+ title: "Error",+ description: "Please sign in to use AI features",+ variant: "destructive",+ });+ } else if (error.toString().includes("aborted")) {+ console.log("Streaming was aborted");+ } else {+ console.error("Error generating AI response:", error);+ toast({+ title: "Error",+ description: "Failed to generate AI response. Please try again.",+ variant: "destructive",+ });+ }+ } finally {+ setIsAiLoading(false);+ setIsStreaming(false);+ if (!isUserScrolling) {+ scrollToBottom();+ }+ }+ };++ const handleStopStreaming = () => {+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ setIsStreaming(false);+ setIsAiLoading(false);+ }+ };++ const handleSearch = async (newOffset = 0, overrides: any = {}) => {+ if (isAiDisabled) {+ toast({+ title: "error",+ description:+ "your ai provider is screenpipe-cloud. consider login in app to use screenpipe-cloud",+ duration: 3000,+ variant: "destructive",+ });+ return;+ }+ await pipe.captureMainFeatureEvent("search", {+ contentType: overrides.contentType || contentType,+ limit: overrides.limit || limit,+ offset: newOffset,+ startDate: overrides.startDate || startDate,+ });+ setHasSearched(true);+ setShowExamples(false);+ setIsLoading(true);+ setOffset(newOffset);+ setProgress(0);+ setChatMessages([]);+ scrollToBottom();+ setResults([]);+ setSimilarityThreshold(1); // Reset similarity threshold to 1++ try {+ // if browserUrl contains special characters like :, /, etc, wrap in double quotes+ // bcs it's FTS+ const bUrl = browserUrl.includes(":") ? `"${browserUrl}"` : browserUrl;+ const wName = windowName.includes(":") ? `"${windowName}"` : windowName;+ const aName = appName.includes(":") ? `"${appName}"` : appName;+ const searchParams = {+ q: query || undefined,+ contentType: overrides.contentType || contentType,+ limit: overrides.limit || limit,+ offset: newOffset,+ startTime:+ overrides.startDate?.toISOString() || startDate.toISOString(),+ endTime: endDate.toISOString(),+ appName: overrides.appName || appName || undefined,+ windowName: overrides.windowName || windowName || undefined,+ browserUrl: bUrl || undefined,+ includeFrames: includeFrames,+ minLength: overrides.minLength || minLength,+ maxLength: maxLength,+ speakerIds: Object.values(selectedSpeakers).map(+ (speaker) => speaker.id,+ ),+ ...(frameName && { frame_name: frameName }),+ };++ const response = await pipe.queryScreenpipe(searchParams);++ // Add debug logging+ console.log("search response:", response);++ if (!response || !Array.isArray(response.data)) {+ throw new Error("invalid response data");+ }++ setResults(response.data);+ setTotalResults(response.pagination.total);++ // Save search to history+ // await onAddSearch(searchParams, response.data);+ } catch (error) {+ console.error("search error:", error);+ toast({+ title: "error",+ description: "failed to fetch search results. please try again.",+ variant: "destructive",+ });+ setResults([]);+ setTotalResults(0);+ } finally {+ setIsLoading(false);+ }+ };++ const handleNextPage = () => {+ if (offset + limit < totalResults) {+ handleSearch(offset + limit);+ }+ };++ const handlePrevPage = () => {+ if (offset - limit >= 0) {+ handleSearch(offset - limit);+ }+ };++ const handleBadgeClick = (value: string, type: "app" | "window") => {+ if (type === "app") {+ setAppName(value);+ } else if (type === "window") {+ setWindowName(value);+ }+ handleSearch(0);+ };++ const handleSelectAll = (checked: boolean) => {+ setSelectAll(checked);+ if (checked) {+ setSelectedResults(new Set(results.map((_, index) => index)));+ } else {+ setSelectedResults(new Set());+ }+ };++ const handleQuickTimeFilter = (minutes: number) => {+ const now = new Date();+ const newStartDate = new Date(now.getTime() - minutes * 60000);+ setStartDate(newStartDate);+ setEndDate(now);+ };++ const renderSearchResults = () => {+ if (isLoading) {+ return Array(3)+ .fill(0)+ .map((_, index) => (+ <Card key={index}>+ <CardContent className="p-4">+ <Skeleton className="h-4 w-1/4 mb-2" />+ <Skeleton className="h-4 w-full mb-2" />+ <Skeleton className="h-4 w-full mb-2" />+ <Skeleton className="h-4 w-3/4" />+ </CardContent>+ </Card>+ ));+ }++ if (hasSearched && results.length === 0) {+ return <p className="text-center">no results found</p>;+ }++ if (!hasSearched || results.length === 0) {+ return null;+ }++ // First filter results based on hideDeselected setting+ const visibleResults = results+ .map((item, index) => ({ item, originalIndex: index }))+ .filter(+ ({ originalIndex }) =>+ !hideDeselected || selectedResults.has(originalIndex),+ );++ return visibleResults.map(({ item, originalIndex }) => (+ <motion.div+ key={originalIndex}+ className="flex items-center mb-4 relative pl-8"+ >+ <div className="absolute left-0 top-1/2 transform -translate-y-1/2">+ <Checkbox+ checked={selectedResults.has(originalIndex)}+ onCheckedChange={() => handleResultSelection(originalIndex)}+ />+ </div>+ <Card className="w-full">+ <CardContent className="p-4">+ <Accordion type="single" collapsible className="w-full">+ <AccordionItem value={`item-${originalIndex}`}>+ <AccordionTrigger className="flex flex-col w-full py-2">+ {/* Main content */}+ <div className="flex w-full items-center gap-2">+ <span className="text-left truncate">+ {item.type === "OCR" &&+ highlightKeyword(+ getContextAroundKeyword(item.content.text, query),+ query,+ )}+ {item.type === "Audio" &&+ highlightKeyword(+ getContextAroundKeyword(+ item.content.transcription,+ query,+ ),+ query,+ )}+ {item.type === "UI" &&+ highlightKeyword(+ getContextAroundKeyword(item.content.text, query),+ query,+ )}+ </span>+ </div>+ </AccordionTrigger>+ <AccordionContent>+ {item.type === "UI" && (+ <>+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">+ <p className="whitespace-pre-line">+ {highlightKeyword(item.content.text, query)}+ </p>+ </div>+ <div className="flex justify-center mt-4">+ <VideoComponent filePath={item.content.filePath} />+ </div>+ <div className="flex flex-wrap items-center gap-2 mt-2">+ {item.content.appName && (+ <Badge+ className="text-xs cursor-pointer"+ onClick={() =>+ handleBadgeClick(item.content.appName, "app")+ }+ >+ {item.content.appName}+ </Badge>+ )}+ {item.content.windowName && (+ <Badge+ className="text-xs cursor-pointer"+ onClick={() =>+ handleBadgeClick(+ item.content.windowName,+ "window",+ )+ }+ >+ {item.content.windowName}+ </Badge>+ )}+ </div>+ </>+ )}+ {item.type === "OCR" && (+ <>+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">+ <p className="whitespace-pre-line">+ {highlightKeyword(item.content.text, query)}+ </p>+ </div>+ <div className="flex justify-center mt-4">+ <VideoComponent filePath={item.content.filePath} />+ </div>+ {includeFrames && item.content.frame && (+ <div className="mt-2 flex items-center">+ <Dialog>+ <DialogTrigger asChild>+ <img+ src={`data:image/jpeg;base64,${item.content.frame}`}+ alt="Frame"+ className="w-24 h-auto cursor-pointer"+ />+ </DialogTrigger>+ <DialogContent className="sm:max-w-[80vw]">+ <img+ src={`data:image/jpeg;base64,${item.content.frame}`}+ alt="Frame"+ className="w-full h-auto"+ />+ </DialogContent>+ </Dialog>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>this is the frame where the text appeared</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ )}+ </>+ )}+ {item.type === "Audio" && (+ <>+ <div className="max-h-[400px] overflow-y-auto rounded border border-gray-100 dark:border-gray-800 p-4">+ <p className="whitespace-pre-line">+ {highlightKeyword(item.content.transcription, query)}+ </p>+ </div>+ {item.content.filePath &&+ item.content.filePath.trim() !== "" ? (+ <div className="flex justify-center mt-4">+ <VideoComponent+ filePath={item.content.filePath}+ startTime={item.content.startTime}+ endTime={item.content.endTime}+ speaker={item.content.speaker}+ />+ </div>+ ) : (+ <p className="text-gray-500 italic mt-2">+ no file path available for this audio.+ </p>+ )}+ </>+ )}+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ <div className="flex flex-wrap items-center gap-2 mt-2">+ <Badge variant="outline" className="text-xs">+ {item.type}+ </Badge>+ <p className="text-xs text-gray-400">+ {new Date(item.content.timestamp).toLocaleString()}{" "}+ {/* Display local time */}+ </p>+ {item.type === "Audio" && item.content.speaker?.name && (+ <p className="text-xs text-gray-400">+ {item.content.speaker.name}+ </p>+ )}+ {item.type === "OCR" && item.content.appName && (+ <div className="flex items-center gap-1">+ <span className="text-xs text-muted-foreground">app:</span>+ <Badge+ className="text-xs cursor-pointer"+ onClick={() =>+ handleBadgeClick(item.content.appName, "app")+ }+ >+ {item.content.appName}+ </Badge>+ </div>+ )}+ {item.type === "OCR" && item.content.browserUrl && (+ <div className="flex items-center gap-1">+ <span className="text-xs text-muted-foreground">url:</span>+ <div className="flex items-center">+ <Badge+ className="text-xs cursor-pointer "+ title={item.content.browserUrl}+ onClick={() =>+ window.open(+ item.content.browserUrl,+ "_blank",+ "noreferrer",+ )+ }+ >+ {new URL(item.content.browserUrl).hostname}+ </Badge>+ <Button+ variant="outline"+ size="icon"+ className="h-5 w-5 ml-0.5"+ onClick={(e) => {+ e.stopPropagation();+ navigator.clipboard.writeText(item.content.browserUrl!);+ toast({+ title: "copied",+ description: "url copied to clipboard",+ duration: 2000,+ });+ }}+ title="copy url"+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ </div>+ )}+ {item.type === "OCR" && item.content.windowName && (+ <div className="flex items-center gap-1">+ <span className="text-xs text-muted-foreground">window:</span>+ <Badge+ className="text-xs cursor-pointer"+ onClick={() =>+ handleBadgeClick(item.content.windowName, "window")+ }+ >+ {item.content.windowName}+ </Badge>+ </div>+ )}+ {"tags" in item.content &&+ item.content.tags &&+ item.content.tags.map((tag: string, index: number) => (+ <Badge key={index} className="text-xs">+ {tag}+ </Badge>+ ))}+ </div>+ </CardContent>+ </Card>+ </motion.div>+ ));+ };++ // Add effect to restore search when currentSearchId changes+ useEffect(() => {+ // if (currentSearchId) {+ const selectedSearch = searches.find((s) => s.id === currentSearchId);+ if (selectedSearch) {+ // Restore search parameters+ setQuery(selectedSearch.searchParams.q || "");+ setContentType(selectedSearch.searchParams.content_type);+ setLimit(selectedSearch.searchParams.limit);+ setStartDate(new Date(selectedSearch.searchParams.start_time));+ setEndDate(new Date(selectedSearch.searchParams.end_time));+ setAppName(selectedSearch.searchParams.app_name || "");+ setWindowName(selectedSearch.searchParams.window_name || "");+ setIncludeFrames(selectedSearch.searchParams.include_frames);+ setMinLength(selectedSearch.searchParams.min_length);+ setMaxLength(selectedSearch.searchParams.max_length);++ // Restore results+ setResults(selectedSearch.results);+ setTotalResults(selectedSearch.results.length);+ setHasSearched(true);+ setShowExamples(false);++ // Restore messages if any+ if (selectedSearch.messages) {+ setChatMessages(+ selectedSearch.messages.map((msg) => ({+ id: msg.id,+ role: msg.type === "ai" ? "assistant" : "user",+ content: msg.content,+ })),+ );+ }+ }+ // }+ }, [currentSearchId, searches]);++ const handleNewSearch = () => {+ // setCurrentSearchId(null);+ location.reload();+ // Add any other reset logic you need+ };++ // Add this effect near other useEffect hooks+ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ // Check for Cmd+Shift (macOS) or Ctrl+Shift (Windows/Linux)+ if (+ e.shiftKey &&+ ((currentPlatform === "macos" && e.metaKey) ||+ (currentPlatform !== "macos" && e.ctrlKey)) &&+ !e.altKey && // ensure alt/option isn't pressed+ !e.key.match(/^[a-zA-Z0-9]$/) // prevent triggering on letter/number keys+ ) {+ e.preventDefault();+ if (floatingInputRef.current && results.length > 0) {+ handleFloatingInputSubmit(new Event("submit") as any);+ }+ }+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [currentPlatform, results.length, floatingInput, isStreaming]);++ return (+ <div className="w-full max-w-4xl mx-auto p-4 mt-12">+ <div className="fixed top-4 left-4 z-50 flex items-center gap-2">+ {/* <SidebarTrigger className="h-8 w-8" /> */}+ <Button+ variant="ghost"+ size="icon"+ onClick={handleNewSearch}+ className="h-8 w-8"+ >+ <Plus className="h-4 w-4" />+ </Button>+ </div>++ <div className="flex items-center justify-center mb-16">+ {/* Add the new SearchFilterGenerator component */}+ <SearchFilterGenerator+ onApplyFilters={(filters) => {+ // Always use empty string instead of undefined for text inputs+ setQuery(filters.query ?? "");+ setAppName(filters.appName ?? "");+ setWindowName(filters.windowName ?? "");++ // Use default values for other types+ handleContentTypeFromFilter(filters.contentType ?? "all");+ setStartDate(+ filters.startDate ?? new Date(Date.now() - 24 * 3600000),+ );+ setEndDate(filters.endDate ?? new Date());+ setLimit(filters.limit ?? 30);++ // Automatically perform search with new filters+ handleSearch(0);+ }}+ />+ </div>+ {/* Content Type Checkboxes and Code Button */}+ <div className="flex items-center justify-center mb-4 gap-4">+ {/* Remove MultiSelectCombobox from here */}++ {/* Add browser URL input */}+ <SqlAutocompleteInput+ id="browser-url"+ type="url"+ value={browserUrl}+ onChange={setBrowserUrl}+ placeholder="filter by browser URL"+ className="w-[350px]"+ icon={<Search className="h-4 w-4" />}+ />++ {/* Window name filter - increased width */}+ <SqlAutocompleteInput+ id="window-name"+ type="window"+ value={windowName}+ onChange={setWindowName}+ placeholder="filter by window"+ className="w-[350px]"+ icon={<Layout className="h-4 w-4" />}+ />++ {/* Advanced button */}+ <Button+ variant="outline"+ onClick={() => setIsQueryParamsDialogOpen(true)}+ >+ <Settings className="h-4 w-4" />+ </Button>++ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button+ onClick={() => handleSearch(0)}+ disabled={+ isLoading ||+ isAiDisabled ||+ !health ||+ health?.status === "error"+ }+ className="disabled:cursor-not-allowed"+ >+ {isLoading ? (+ <>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ searching...+ </>+ ) : (+ <>+ <Search className="mr-2 h-4 w-4" />+ {currentPlatform === "macos" ? "⌘" : "ctrl"} + ↵+ </>+ )}+ </Button>+ </span>+ </TooltipTrigger>+ {(!health || health?.status === "error" || isAiDisabled) && (+ <TooltipContent>+ <p>+ {isAiDisabled && isServerDown ? (+ <>+ <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />+ you don't have access to screenpipe-cloud <br /> and+ screenpipe server is down!+ </>+ ) : isServerDown ? (+ <>+ <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />+ screenpipe is not running...+ </>+ ) : isAiDisabled ? (+ <>+ <AlertCircle className="mr-1 h-4 w-4 text-red-500 inline" />+ you don't have access to screenpipe-cloud :( <br /> please+ consider login!+ </>+ ) : (+ ""+ )}+ </p>+ </TooltipContent>+ )}+ </Tooltip>+ </TooltipProvider>+ </div>++ {/* Quick time filter badges */}+ <div className="flex mt-2 mb-4 space-x-2 justify-center">+ <Badge+ variant="outline"+ className="cursor-pointer hover:bg-secondary"+ onClick={() => handleQuickTimeFilter(30)}+ >+ <Clock className="mr-2 h-4 w-4" />+ last 30m+ </Badge>+ <Badge+ variant="outline"+ className="cursor-pointer hover:bg-secondary"+ onClick={() => handleQuickTimeFilter(60)}+ >+ <Clock className="mr-2 h-4 w-4" />+ last 60m+ </Badge>+ <Badge+ variant="outline"+ className="cursor-pointer hover:bg-secondary"+ onClick={() => handleQuickTimeFilter(24 * 60)}+ >+ <Clock className="mr-2 h-4 w-4" />+ last 24h+ </Badge>+ <Badge+ variant="outline"+ className="cursor-pointer hover:bg-secondary"+ onClick={() => handleQuickTimeFilter(7 * 24 * 60)}+ >+ <Clock className="mr-2 h-4 w-4" />+ last 7d+ </Badge>+ <Badge+ variant="outline"+ className="cursor-pointer hover:bg-secondary"+ onClick={() => handleQuickTimeFilter(30 * 24 * 60)}+ >+ <Clock className="mr-2 h-4 w-4" />+ last 30d+ </Badge>+ </div>++ <Dialog+ open={isQueryParamsDialogOpen}+ onOpenChange={setIsQueryParamsDialogOpen}+ >+ <DialogContent className="sm:max-w-[705px] max-h-[80vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>advanced search parameters</DialogTitle>+ <DialogDescription>+ adjust additional search parameters here.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ {/* Add the curl command button at the top */}+ <div className="flex justify-end">+ <Dialog>+ <DialogTrigger asChild>+ <Button variant="outline" className="text-sm">+ <IconCode className="h-4 w-4 mx-2" />+ curl command+ </Button>+ </DialogTrigger>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>curl command</DialogTitle>+ <DialogDescription>+ you can use this curl command to make the same search+ request from the command line.+ <br />+ <br />+ <span className="text-xs text-gray-500">+ note: you need to have `jq` installed to use the+ command.+ </span>{" "}+ </DialogDescription>+ </DialogHeader>+ <div className="overflow-x-auto">+ <CodeBlock language="bash" value={generateCurlCommand()} />+ </div>+ </DialogContent>+ </Dialog>+ </div>++ {/* Move content type selection here */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="content-type" className="text-right">+ content type+ </Label>+ <div className="col-span-3">+ <MultiSelectCombobox+ label="content type"+ options={contentTypeOptions}+ value={selectedContentTypes}+ onChange={handleContentTypeChange}+ placeholder="Filter by content type..."+ renderItem={(option) => (+ <div className="flex items-center justify-between w-full">+ <span>{option.label}</span>+ <span className="text-xs text-muted-foreground items-end">+ {contentTypeDescriptions[option.value]}+ </span>+ </div>+ )}+ renderSelectedItem={(values) => (+ <div className="flex gap-1 items-center">+ {values.length === 0 ? (+ <span>All content types</span>+ ) : (+ <>+ {values.map((value) => {+ const option = contentTypeOptions.find(+ (opt) => opt.value === value,+ );+ return option ? (+ <Badge+ key={value}+ variant="secondary"+ className="gap-1 px-1.5"+ >+ {option.label}+ </Badge>+ ) : null;+ })}+ </>+ )}+ </div>+ )}+ />+ </div>+ </div>++ {/* Add keyword search field */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="keyword-search" className="text-right">+ keyword search+ </Label>+ <div className="col-span-3 flex items-center">+ <Input+ id="keyword-search"+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="search for specific keywords"+ className="flex-grow"+ autoCorrect="off"+ autoComplete="off"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>search for specific keywords in all content</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>++ {/* Add browser URL field in advanced settings too */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="browser-url" className="text-right">+ browser URL+ </Label>+ <div className="col-span-3 flex items-center">+ <Input+ id="browser-url"+ type="text"+ value={browserUrl}+ onChange={(e) => setBrowserUrl(e.target.value)}+ placeholder="filter by browser URL"+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>filter results by specific browser URLs</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>++ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="speakers" className="text-right">+ speakers+ </Label>+ <div className="col-span-3 w-full">+ <MultiSelectCombobox+ label="speakers"+ options={speakers.map((speaker) => ({+ label: speaker.name || `Speaker ${speaker.id}`,+ value: speaker.id.toString(),+ }))}+ value={Object.values(selectedSpeakers).map((speaker) =>+ speaker.id.toString(),+ )}+ onChange={(selectedIds) => {+ // Convert from array of IDs to object with speaker objects+ const newSelectedSpeakers: { [key: number]: Speaker } = {};+ selectedIds.forEach((id) => {+ const speakerId = parseInt(id);+ const speaker = speakers.find((s) => s.id === speakerId);+ if (speaker) {+ newSelectedSpeakers[speakerId] = speaker;+ }+ });+ setSelectedSpeakers(newSelectedSpeakers);+ }}+ placeholder="Search speakers..."+ renderItem={(option) => (+ <div className="flex items-center justify-between w-full">+ <span>{option.label}</span>+ </div>+ )}+ renderSelectedItem={(values) => (+ <div className="flex gap-1 items-center w-full">+ {values.length === 0 ? (+ <span>Select speakers</span>+ ) : (+ <>+ {values.map((value) => {+ const speaker = speakers.find(+ (s) => s.id.toString() === value,+ );+ return speaker ? (+ <Badge+ key={value}+ variant="secondary"+ className="gap-1 px-1.5"+ >+ {speaker.name || `Speaker ${speaker.id}`}+ </Badge>+ ) : null;+ })}+ </>+ )}+ </div>+ )}+ />+ </div>+ </div>++ {/* Add date pickers here */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="start-date" className="text-right">+ start date+ </Label>+ <div className="col-span-3">+ <DateTimePicker+ date={startDate}+ setDate={setStartDate}+ className="w-full"+ />+ </div>+ </div>++ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="end-date" className="text-right">+ end date+ </Label>+ <div className="col-span-3">+ <DateTimePicker+ date={endDate}+ setDate={setEndDate}+ className="w-full"+ />+ </div>+ </div>++ {/* Rest of the advanced settings content */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="app-name" className="text-right">+ app name+ </Label>+ <div className="col-span-3 flex items-center">+ <SqlAutocompleteInput+ id="app-name"+ type="app"+ icon={<Laptop className="h-4 w-4" />}+ value={appName}+ onChange={setAppName}+ placeholder="filter by app name"+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>filter results by specific application names</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>++ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="min-length" className="text-right">+ min length+ </Label>+ <div className="col-span-3 flex items-center">+ <Input+ id="min-length"+ type="number"+ value={minLength}+ onChange={(e) => setMinLength(Number(e.target.value))}+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ enter the minimum length of the content to search for+ <br />+ usually transcriptions are short while text extracted+ from images can be long.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="max-length" className="text-right">+ max length+ </Label>+ <div className="col-span-3 flex items-center">+ <Input+ id="max-length"+ type="number"+ value={maxLength}+ onChange={(e) => setMaxLength(Number(e.target.value))}+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ enter the maximum length of the content to search for+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>++ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="limit-slider" className="text-right">+ page size: {limit}+ </Label>+ <div className="col-span-3 flex items-center">+ <Slider+ id="limit-slider"+ value={[limit]}+ onValueChange={(value: number[]) => setLimit(value[0])}+ min={10}+ max={15000}+ step={10}+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ select the number of results to display. usually ai+ cannot ingest more than 30 OCR results at a time and+ 1000 audio results at a time.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ </div>++ {/* Add frame name input after app name */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="frame-name" className="text-right">+ frame name+ </Label>+ <div className="col-span-3 flex items-center">+ <Input+ id="frame-name"+ type="text"+ value={frameName}+ onChange={(e) => setFrameName(e.target.value)}+ placeholder="filter by frame name"+ className="flex-grow"+ />+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 ml-2 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ filter results by specific frame names (by default frame+ name is mp4 video file path)+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ <div className="flex items-center justify-center space-x-2">+ <Switch+ id="include-frames"+ checked={includeFrames}+ onCheckedChange={setIncludeFrames}+ />+ <Label htmlFor="include-frames">include frames</Label>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>+ include frames in the search results. this shows the frame+ where the text appeared. only works for ocr. this may slow+ down the search.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ <DialogFooter>+ <Button onClick={() => setIsQueryParamsDialogOpen(false)}>+ done+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {isLoading ? (+ <div className="my-8 flex justify-center">+ <Loader2 className="h-8 w-8 animate-spin" />+ </div>+ ) : (+ showExamples &&+ results.length === 0 && (+ <div className="my-8 flex justify-center">+ <ExampleSearchCards onSelect={handleExampleSelect} />+ </div>+ )+ )}+ {isLoading && (+ <div className="my-2">+ <Progress value={progress} className="w-full" />+ </div>+ )}+ {results.length > 0 && (+ <div className="flex flex-col space-y-4 mb-4 my-8">+ <div className="flex justify-between items-center">+ <div className="flex items-center space-x-4">+ <div className="flex items-center space-x-2">+ <Checkbox+ id="select-all"+ checked={selectAll}+ onCheckedChange={handleSelectAll}+ />+ <Label htmlFor="select-all">select all results</Label>+ </div>++ <Separator orientation="vertical" className="h-4" />++ <div className="flex items-center space-x-2">+ <Switch+ id="hide-deselected"+ checked={hideDeselected}+ onCheckedChange={setHideDeselected}+ />+ <Label htmlFor="hide-deselected">hide unselected</Label>+ </div>+ </div>++ <div className="flex items-center space-x-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => {}}+ disabled={isFiltering}+ className="flex items-center gap-2 disabled:opacity-100"+ >+ {isFiltering ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : similarityThreshold === 0.5 ? (+ <Check className="h-4 w-4" />+ ) : (+ <Layers className="h-4 w-4" />+ )}+ {similarityThreshold === 0.5+ ? "duplicates removed"+ : "remove duplicates"}+ </Button>++ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="h-4 w-4 text-gray-400 cursor-help" />+ </TooltipTrigger>+ <TooltipContent>+ <p>automatically unselect similar or duplicate results</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ </div>+ )}+ <div className="space-y-4">+ {renderSearchResults()}+ {totalResults > 0 && (+ <div className="flex justify-between items-center mt-4">+ <Button+ onClick={handlePrevPage}+ disabled={offset === 0}+ variant="outline"+ size="sm"+ >+ <ChevronLeft className="mr-2 h-4 w-4" /> Previous+ </Button>+ <span className="text-sm text-gray-500">+ Showing {offset + 1} - {Math.min(offset + limit, totalResults)} of{" "}+ {totalResults}+ </span>+ <Button+ onClick={handleNextPage}+ disabled={offset + limit >= totalResults}+ variant="outline"+ size="sm"+ >+ Next <ChevronRight className="ml-2 h-4 w-4" />+ </Button>+ </div>+ )}+ </div>++ <AnimatePresence>+ {results.length > 0 && (+ <motion.div+ initial={{ opacity: 0, y: 50 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 50 }}+ className="fixed bottom-4 left-0 right-0 mx-auto w-full max-w-2xl z-50"+ >+ <form+ onSubmit={handleFloatingInputSubmit}+ className="flex flex-col space-y-2 bg-white dark:bg-gray-800 shadow-lg rounded-lg overflow-hidden p-4 border border-gray-200 dark:border-gray-700"+ >+ <div className="relative flex-grow flex items-center space-x-2">+ <AIPresetsDialog+ pipeName={"search"}+ recommendedPresets={[+ {+ id: "search-chat",+ model: "gemma:2b",+ provider: "native-ollama",+ prompt: DEFAULT_PROMPT,+ maxContextChars: 512000,+ },+ ]}+ >+ <Button type="button" variant="outline" size="icon" className=" p-2">+ <SparklesIcon className="h-4 w-4" />+ </Button>+ </AIPresetsDialog>+ <TooltipProvider>+ <Tooltip open={!isAvailable}>+ <TooltipTrigger asChild>+ <div className="flex-1">+ <Input+ ref={floatingInputRef}+ type="text"+ placeholder="ask a question about the results..."+ value={floatingInput}+ disabled={+ calculateSelectedContentLength() >+ MAX_CONTENT_LENGTH ||+ isAiDisabled ||+ !isAvailable+ }+ onChange={(e) => setFloatingInput(e.target.value)}+ className="flex-1 h-12 focus:outline-none focus:ring-0 border-0 focus:border-black dark:focus:border-white focus:border-b transition-all duration-200"+ />+ </div>+ </TooltipTrigger>+ <TooltipContent side="top">+ <p className="text-sm text-destructive">{error}</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <Select+ value={selectedAgent.id}+ onValueChange={(value) =>+ setSelectedAgent(+ AGENTS.find((a) => a.id === value) || AGENTS[0],+ )+ }+ >+ <SelectTrigger+ className="w-[170px] h-12"+ title={selectedAgent.description}+ >+ <SelectValue placeholder="select agent" />+ </SelectTrigger>+ <SelectContent>+ {AGENTS.map((agent) => (+ <SelectItem+ key={agent.id}+ value={agent.id}+ title={+ AGENTS.find((a) => a.id === agent.id)?.description+ }+ >+ <span className="font-mono text-sm">{agent.name}</span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Button+ type="submit"+ className="w-12"+ disabled={+ calculateSelectedContentLength() > MAX_CONTENT_LENGTH ||+ isAiDisabled+ }+ title={+ isAiDisabled+ ? "Please sign in to use AI features"+ : `${currentPlatform === "macos" ? "⌘" : "ctrl"}+shift`+ }+ >+ {isStreaming ? (+ <Square className="h-4 w-4" />+ ) : (+ <div className="flex items-center">+ <Send className="h-4 w-4" />+ <span className="sr-only">+ {currentPlatform === "macos" ? "⌘" : "ctrl"}+shift+ </span>+ </div>+ )}+ </Button>++ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <ContextUsageIndicator+ currentSize={calculateSelectedContentLength()}+ maxSize={MAX_CONTENT_LENGTH}+ />+ </span>+ </TooltipTrigger>+ <TooltipContent>+ <p className="text-sm">+ {calculateSelectedContentLength() > MAX_CONTENT_LENGTH+ ? `selected content exceeds maximum allowed: ${calculateSelectedContentLength()} / ${MAX_CONTENT_LENGTH} characters. unselect some items to use AI.`+ : `${calculateSelectedContentLength()} / ${MAX_CONTENT_LENGTH} characters used for AI message`}+ <br />+ <span className="text-muted-foreground mt-1 block">+ ai models can only process a limited amount of text at+ once. the circle indicates your current usage.+ </span>+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </form>+ </motion.div>+ )}+ </AnimatePresence>++ {results.length > 0 && <Separator className="my-8" />}++ {/* Display chat messages - Update this section */}+ {(chatMessages.length > 0 || isAiLoading) && (+ <>+ <div className="flex flex-col items-start flex-1 max-w-2xl gap-8 px-4 mx-auto">+ {chatMessages.map((msg, index) => (+ <ChatMessage key={index} message={msg} />+ ))}+ {isAiLoading && spinner}+ </div>+ </>+ )}++ <div className="w-1/3 mx-auto">+ <AIPresetsSelector pipeName={"search"} />+ </div>++ {/* Scroll to Bottom Button */}+ {showScrollButton && (+ <Button+ className="fixed bottom-4 right-4 rounded-full p-2"+ onClick={scrollToBottom}+ >+ <ChevronDown className="h-6 w-6" />+ </Button>+ )}+ {results.length > 0 && <div className="h-32" />}+ </div>+ );}diff --git a/pipes/search/src/components/search-filter-generator.tsx b/pipes/search/src/components/search-filter-generator.tsxindex f76732f16..edc02ac36 100644--- a/pipes/search/src/components/search-filter-generator.tsx+++ b/pipes/search/src/components/search-filter-generator.tsx@@ -6,7 +6,8 @@ import { Bot, Wand2, Search } from "lucide-react";import { Button } from "@/components/ui/button";import { CommandDialog, CommandInput } from "@/components/ui/command";import OpenAI from "openai";-import { useSettings } from "@/lib/hooks/use-settings";+import { usePipeSettings } from "@/lib/hooks/use-pipe-settings";+import { useSettings, type PipeSettings } from "@/lib/hooks/use-settings";import {Tooltip,TooltipContent,@@ -47,9 +48,10 @@ export function SearchFilterGenerator({const [isLoading, setIsLoading] = useState(false);const [isMac, setIsMac] = useState(false);const [filterVariants, setFilterVariants] = useState<SearchFilterVariant[]>(- []+ [],);const { settings } = useSettings();+ const { getPreset } = usePipeSettings("search");const { items: appStats } = useSqlAutocomplete("app");const { items: windowStats } = useSqlAutocomplete("window");@@ -72,6 +74,24 @@ export function SearchFilterGenerator({if (!prompt.trim()) return;setIsLoading(true);setFilterVariants([]);+ const preset = getPreset();++ if (!preset) {+ toast({+ title: "there is no ai settings selected",+ description: "please create new or select existing ones",+ variant: "destructive",+ });+ return;+ }++ let apiKey = "";+ if (+ (preset.provider === "openai" || preset.provider === "custom") &&+ "apiKey" in preset+ ) {+ apiKey == preset.apiKey;+ }try {// Format top apps and windows for the prompt@@ -86,17 +106,17 @@ export function SearchFilterGenerator({const openai = new OpenAI({apiKey:- settings.aiProviderType === "screenpipe-cloud"- ? settings.user.token- : settings.openaiApiKey,- baseURL: settings.aiUrl,+ preset.provider === "screenpipe-cloud"+ ? settings?.user?.token+ : apiKey,+ baseURL: preset.url,dangerouslyAllowBrowser: true,});const currentDate = new Date().toISOString();const completion = await openai.chat.completions.create({- model: settings.aiModel,+ model: preset.model,messages: [{role: "system",@@ -160,18 +180,18 @@ search patterns:- slack chat → use OCR type + Slack app filter (no query)generate these 3 variations:-1. broad:+1. broad:- wider time range- multiple content types- minimal filtering- empty query for OCR content-+2. focused:- specific content type- exact app/window names- narrower time range- single-word query only if audio-+3. balanced:- medium scope- optimal filter combination@@ -199,7 +219,7 @@ do not include any explanation or additional text in the response - only the jsoconsole.log(completion.choices[0].message.content);const { variants } = JSON.parse(- completion.choices[0].message.content || "[]"+ completion.choices[0].message.content || "[]",) as { variants: SearchFilterVariant[] };if (variants) {const now = new Date();@@ -228,7 +248,7 @@ do not include any explanation or additional text in the response - only the jso},description: `variant ${i + 1}`,title: filters.title || `variant ${i + 1}`,- }))+ })),);}} catch (error: any) {@@ -315,7 +335,7 @@ do not include any explanation or additional text in the response - only the jso<Bot className="h-4 w-4 text-muted-foreground" /></TooltipTrigger><TooltipContent side="left">- <p className="text-xs">using {settings.aiModel}</p>+ <p className="text-xs">using {getPreset()?.model}</p></TooltipContent></Tooltip></TooltipProvider>diff --git a/pipes/search/src/components/ui/textarea.tsx b/pipes/search/src/components/ui/textarea.tsxnew file mode 100644index 000000000..de9a17e85--- /dev/null+++ b/pipes/search/src/components/ui/textarea.tsx@@ -0,0 +1,24 @@+import * as React from "react";++import { cn } from "@/lib/utils";++export interface TextareaProps+ extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}++const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(+ ({ 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-sm 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",+ className,+ )}+ ref={ref}+ {...props}+ />+ );+ },+);+Textarea.displayName = "Textarea";++export { Textarea };\ No newline at end of filediff --git a/pipes/search/src/lib/actions/get-screenpipe-app-settings.ts b/pipes/search/src/lib/actions/get-screenpipe-app-settings.tsnew file mode 100644index 000000000..b81572b8d--- /dev/null+++ b/pipes/search/src/lib/actions/get-screenpipe-app-settings.ts@@ -0,0 +1,22 @@+"use server";++import { pipe } from "@screenpipe/js";+import type { Settings as ScreenpipeAppSettings } from "@screenpipe/js";+import { type PipeSettings } from "@/lib/hooks/use-settings";++export async function getScreenpipeAppSettings() {+ return await pipe.settings.getAll();+}++export async function updateScreenpipeAppSettings(+ newSettings: Partial<ScreenpipeAppSettings>,+) {+ return await pipe.settings.update(newSettings);+}++export async function updatePipeSettings(+ pipeName: string,+ newSettings: Partial<PipeSettings>,+) {+ return await pipe.settings.updateNamespaceSettings(pipeName, newSettings);+}diff --git a/pipes/search/src/lib/hooks/use-ai-provider.tsx b/pipes/search/src/lib/hooks/use-ai-provider.tsxindex d784a47be..4f6d25c9a 100644--- a/pipes/search/src/lib/hooks/use-ai-provider.tsx+++ b/pipes/search/src/lib/hooks/use-ai-provider.tsx@@ -6,7 +6,9 @@ interface AIProviderStatus {error: string;}-export function useAiProvider(settings: Settings): AIProviderStatus {+export function useAiProvider(+ settings: Settings | undefined,+): AIProviderStatus {const [status, setStatus] = useState<AIProviderStatus>({isAvailable: true,error: "",@@ -15,6 +17,11 @@ export function useAiProvider(settings: Settings): AIProviderStatus {useEffect(() => {const checkAiProvider = async () => {try {+ if (!settings) {+ setStatus({ isAvailable: false, error: "no ai-provider is set" });+ return;+ }+if (!settings.aiProviderType) {setStatus({ isAvailable: false, error: "no ai-provider is set" });return;@@ -75,10 +82,10 @@ export function useAiProvider(settings: Settings): AIProviderStatus {checkAiProvider();}, [- settings.aiProviderType,- settings.openaiApiKey,- settings.aiUrl,- settings.user?.token,+ settings?.aiProviderType,+ settings?.openaiApiKey,+ settings?.aiUrl,+ settings?.user?.token,]);return status;diff --git a/pipes/search/src/lib/hooks/use-pipe-settings.ts b/pipes/search/src/lib/hooks/use-pipe-settings.tsnew file mode 100644index 000000000..cc3ccff68--- /dev/null+++ b/pipes/search/src/lib/hooks/use-pipe-settings.ts@@ -0,0 +1,39 @@+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/search/src/lib/hooks/use-settings.tsx b/pipes/search/src/lib/hooks/use-settings.tsxindex cd7d2076e..8128e12b3 100644--- a/pipes/search/src/lib/hooks/use-settings.tsx+++ b/pipes/search/src/lib/hooks/use-settings.tsx@@ -1,96 +1,230 @@-"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 function useSettings() {- const defaultSettings = getDefaultSettings();- const [settings, setSettings] = useState<Settings>(defaultSettings);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<Error | null>(null);-- useEffect(() => {- const loadSettings = async () => {- setLoading(true);- try {- const response = await fetch("/api/settings");- const data = await response.json();- setSettings({ ...defaultSettings, ...data });- } catch (err) {- 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, 30000);-- return () => {- window.removeEventListener("focus", onFocus);- clearInterval(interval);- };- }, []);-- const updateSetting = async <T extends keyof Settings>(- key: T,- value: Settings[T]- ) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ key, value }),- });- setSettings((prev) => ({ ...prev, [key]: value }));- } catch (err) {- setError(err as Error);- }- };-- const updateSettings = async (newSettings: Partial<Settings>) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ value: newSettings, isPartialUpdate: true }),- });- setSettings((prev) => ({ ...prev, ...newSettings }));- } catch (err) {- setError(err as Error);- }- };-- const resetSettings = async (settingKey?: keyof Settings) => {- try {- await fetch("/api/settings", {- method: "PUT",- body: JSON.stringify({ reset: true, key: settingKey }),- });- if (settingKey) {- setSettings((prev) => ({- ...prev,- [settingKey]: defaultSettings[settingKey],- }));- } else {- setSettings(defaultSettings);- }- } catch (err) {- setError(err as Error);- }- };-- return {- settings,- loading,- error,- updateSetting,- updateSettings,- resetSettings,- };+export interface PipeSettings {+ aiLogPresetId:string;+ aiPresetId: string;}++type AIPreset = ScreenpipeAppSettings["aiPresets"][number];++const DEFAULT_SETTINGS: Partial<PipeSettings> = {};++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 };+}\ No newline at end of filediff --git a/pipes/search/src/lib/types.ts b/pipes/search/src/lib/types.tsnew file mode 100644index 000000000..926cb00cf--- /dev/null+++ b/pipes/search/src/lib/types.ts@@ -0,0 +1,30 @@+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 {+ screenpipeAppSettings: ScreenpipeAppSettings;+}diff --git a/screenpipe-app-tauri/bun.lockb b/screenpipe-app-tauri/bun.lockbindex 9892f7d08..100ce673b 100755Binary files a/screenpipe-app-tauri/bun.lockb and b/screenpipe-app-tauri/bun.lockb differdiff --git a/screenpipe-app-tauri/components/onboarding/api-setup.tsx b/screenpipe-app-tauri/components/onboarding/api-setup.tsxindex 681c12523..cb6342c34 100644--- a/screenpipe-app-tauri/components/onboarding/api-setup.tsx+++ b/screenpipe-app-tauri/components/onboarding/api-setup.tsx@@ -1,14 +1,13 @@-import React, { useEffect } from "react";+import React, { useEffect, useRef } from "react";import { useToast } from "@/components/ui/use-toast";import { useSettings } from "@/lib/hooks/use-settings";-import { Card, CardContent } from "@/components/ui/card";+import { CardContent } from "@/components/ui/card";import { ArrowUpRight } from "lucide-react";-import { DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DialogTitle } from "@/components/ui/dialog";import { open } from "@tauri-apps/plugin-shell";import OnboardingNavigation from "@/components/onboarding/navigation";--import AISection from "../settings/ai-section";+import { AIPresets } from "../settings/ai-presets";interface OnboardingAPISetupProps {className?: string;@@ -22,168 +21,168 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({handlePrevSlide,}) => {const { toast } = useToast();- const { settings, updateSettings } = useSettings();- const [localSettings, setLocalSettings] = React.useState(settings);- const [areAllInputsFilled, setAreAllInputsFilled] = React.useState(false);- const [errors, setErrors] = React.useState<{ [key: string]: string }>({});+ const { settings } = useSettings();const [isValidating, setIsValidating] = React.useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ // Add effect to scroll to top when component mountsuseEffect(() => {- const { aiUrl, openaiApiKey, aiModel } = localSettings;- const isApiKeyRequired =- aiUrl !== "https://ai-proxy.i-f9f.workers.dev/v1" &&- aiUrl !== "http://localhost:11434/v1";+ if (containerRef.current) {+ containerRef.current.scrollTo({+ top: 0,+ behavior: "auto"+ });+ }+ }, []);- setAreAllInputsFilled(- aiUrl.trim() !== "" &&- aiModel.trim() !== "" &&- (!isApiKeyRequired || openaiApiKey.trim() !== "")- );- }, [localSettings]);+ // Check if at least one preset exists and has required fields+ const hasValidPreset = React.useMemo(() => {+ if (!settings.aiPresets || settings.aiPresets.length === 0) return false;++ // Find the default preset or the first one if no default is set+ const defaultPreset = settings.aiPresets.find(p => p.defaultPreset) || settings.aiPresets[0];++ if (!defaultPreset) return false;++ // Check if the preset has the required fields+ const { url, model, provider } = defaultPreset;+ const isApiKeyRequired =+ url !== "https://ai-proxy.i-f9f.workers.dev/v1" &&+ url !== "http://localhost:11434/v1";++ // Check if API key is required and present+ const hasRequiredApiKey = !isApiKeyRequired ||+ ((provider === "openai" || provider === "custom") &&+ "apiKey" in defaultPreset &&+ defaultPreset.apiKey?.trim() !== "");++ return url?.trim() !== "" &&+ model?.trim() !== "" &&+ hasRequiredApiKey;+ }, [settings.aiPresets]);- const validateInputs = async () => {- const { aiUrl, openaiApiKey, aiModel } = localSettings;- const newErrors: { [key: string]: string } = {};+ const handleValidationMoveNextSlide = async () => {+ setIsValidating(true);+try {+ // Find the default preset or the first one+ const defaultPreset = settings.aiPresets.find(p => p.defaultPreset) || settings.aiPresets[0];++ if (!defaultPreset) {+ toast({+ title: "No AI preset found",+ description: "Please create at least one AI preset",+ variant: "destructive",+ });+ setIsValidating(false);+ return false;+ }++ const { url, model, provider } = defaultPreset;+ // Get API key if available based on provider+ const apiKey = (provider === "openai" || provider === "custom") && "apiKey" in defaultPreset+ ? defaultPreset.apiKey+ : "";+const t = toast({- title: "validating AI provider",- description: "please wait...",+ title: "Validating AI provider",+ description: "Please wait...",duration: 10000,});- const response = await fetch(`${aiUrl}/chat/completions`, {++ const response = await fetch(`${url}/chat/completions`, {method: "POST",headers: {"Content-Type": "application/json",- Authorization: `Bearer ${openaiApiKey}`,+ Authorization: `Bearer ${apiKey}`,},body: JSON.stringify({- model: aiModel,+ model: model,messages: [{role: "user",content: "You are a helpful assistant that tells short jokes.",},- {- role: "user",- content:- "Tell me a very short joke (1-2 sentences) about screen recording, AI, and screenpipe, answer in lower case only.",- },],- max_tokens: 60,- stream: false,+ max_tokens: 5,}),});-- if (response.ok) {- const data = await response.json();- const joke = data.choices[0].message.content.trim();-- console.log("ai is ready!", joke);- t.update({- id: t.id,- title: "ai is ready!",- description: `here's a joke: ${joke}`,- duration: 5000,- });- } else {++ t.dismiss();++ if (!response.ok) {const errorData = await response.json();- console.log("errorData", errorData);-- if (response.status === 401) {- if (aiUrl.includes("worker")) {- newErrors.openaiApiKey =- "unauthorized: please login or check your subscription";- } else {- newErrors.openaiApiKey = "unauthorized: invalid api key";- }- } else {- newErrors.openaiApiKey = `invalid api key or model: ${- errorData.error?.message?.toLowerCase() || "unknown error"- }`;- }- }- } catch (error: any) {- if (error.message.includes("Failed to fetch")) {- newErrors.openaiApiKey =- "connection failed: check your internet or ai provider url";- } else {- newErrors.openaiApiKey = `failed to validate api key: ${error.message.toLowerCase()}`;+ toast({+ title: "Error validating AI provider",+ description: errorData.error?.message || "Unknown error",+ variant: "destructive",+ });+ setIsValidating(false);+ return false;}- }-- setErrors(newErrors);- Object.keys(newErrors).forEach((key) => {+toast({- title: "api key validation error",- description: newErrors[key],- variant: "destructive",+ title: "AI provider validated successfully",+ description: "You're all set!",});- });- return Object.keys(newErrors).length === 0;- };-- const handleValidationMoveNextSlide = async () => {- setIsValidating(true);- // Update settings here, before validation- updateSettings(localSettings);- const isValid = await validateInputs();- setIsValidating(false);- if (isValid) {++ setIsValidating(false);handleNextSlide();+ return true;+ } catch (error) {+ toast({+ title: "Error validating AI provider",+ description: error instanceof Error ? error.message : "Unknown error",+ variant: "destructive",+ });+ setIsValidating(false);+ return false;}};- React.useEffect(() => {- setLocalSettings(settings);- }, [settings]);-return (- <div className={`flex h-[80%] flex-col ${className}`}>- <DialogHeader className="flex flex-col px-2 justify-center items-center">- <img- className="w-24 h-24 justify-center"- src="/128x128.png"- alt="screenpipe-logo"- />- <DialogTitle className="text-center text-2xl">- setup your ai settings- </DialogTitle>- </DialogHeader>- <Card className="mt-4">- <CardContent className="flex flex-col items-center space-y-4 max-h-[60vh] overflow-y-auto ">- <AISection />- <div className="mb-16" />- <div className="mb-16" />- <div className="mb-16" />- <div className="mb-16" />- <div className="mb-16" />- <div className="mb-16" />- </CardContent>- </Card>- <a- onClick={() =>- open("https://github.com/ollama/ollama?tab=readme-ov-file#ollama")- }- href="#"- className="mt-4 text-muted-foreground text-sm mr-auto ml-auto !text-center hover:underline"- >- don't have api key ? set up ollama locally- <ArrowUpRight className="inline w-4 h-4 ml-1 " />- </a>+ <div+ ref={containerRef}+ className={`${className} w-full flex flex-col items-center relative max-h-full overflow-y-auto`}>+ <div className="flex flex-col items-center justify-start w-full overflow-visible pt-4">+ <div className="flex flex-col px-2 justify-center items-center">+ <img+ className="w-24 h-24 justify-center"+ src="/128x128.png"+ alt="screenpipe-logo"+ />+ <DialogTitle className="text-center text-2xl">+ setup your ai settings+ </DialogTitle>+ </div>+ <div className="mt-4 h-full w-full">+ <CardContent className="flex flex-col items-center space-y-4 h-full">+ <AIPresets />+ <a+ onClick={() =>+ open("https://github.com/ollama/ollama?tab=readme-ov-file#ollama")+ }+ href="#"+ className="text-muted-foreground text-sm !text-center hover:underline"+ >+ don't have api key ? set up ollama locally+ <ArrowUpRight className="inline w-4 h-4 ml-1" />+ </a>+ </CardContent>+ </div>++ </div><OnboardingNavigation- className="mt-8"+ className="pt-8"isLoading={isValidating}handlePrevSlide={handlePrevSlide}handleNextSlide={- areAllInputsFilled+ hasValidPreset? handleValidationMoveNextSlide- : () => {- updateSettings(localSettings);- handleNextSlide();- }+ : handleNextSlide}prevBtnText="previous"- nextBtnText={areAllInputsFilled ? "setup" : "i'll setup later"}+ nextBtnText={hasValidPreset ? "setup" : "i'll setup later"}/></div>);diff --git a/screenpipe-app-tauri/components/onboarding/navigation.tsx b/screenpipe-app-tauri/components/onboarding/navigation.tsxindex 87cb94cfa..dd1497593 100644--- a/screenpipe-app-tauri/components/onboarding/navigation.tsx+++ b/screenpipe-app-tauri/components/onboarding/navigation.tsx@@ -20,7 +20,7 @@ const OnboardingNavigation: React.FC<OnboardingNavigationProps> = ({handleNextSlide,}) => {return (- <div className={`flex justify-between items-center mx-auto ${className} fixed bottom-0 left-20 right-20 p-4 bg-transparent max-w-screen-lg`}>+ <div className={`flex justify-between items-center mx-auto ${className} w-full p-4 bg-transparent max-w-screen-lg`}><ButtonclassName="flex items-center w-fit min-w-32 disabled:!cursor-not-allowed disabled:!pointer-events-auto"variant={"outline"}diff --git a/screenpipe-app-tauri/components/onboarding/status.tsx b/screenpipe-app-tauri/components/onboarding/status.tsxindex 022da0852..f0fb46dc7 100644--- a/screenpipe-app-tauri/components/onboarding/status.tsx+++ b/screenpipe-app-tauri/components/onboarding/status.tsx@@ -244,17 +244,18 @@ const OnboardingStatus: React.FC<OnboardingStatusProps> = ({return (<divref={containerRef}- className={`${className} w-full flex flex-col items-center overflow-y-auto max-h-[80vh] pb-4 relative`}+ className={`${className} w-full flex flex-col items-center relative max-h-full`}>- <DialogHeader className="flex flex-col px-2 justify-center items-center sticky top-0 bg-background z-10 w-full pt-4 pb-2">- <img className="w-24 h-24" src="/128x128.png" alt="screenpipe-logo" />+ <div className="flex flex-col items-center justify-start w-full overflow-y-auto py-4">+ <div className="w-32 h-32 flex items-center justify-center">+ <img className="w-32 h-32" src="/128x128.png" alt="screenpipe-logo" />+ </div><DialogTitle className="text-center text-2xl">setting up screenpipe</DialogTitle>- <p className="text-sm text-muted-foreground mt-2">+ <p className="text-sm text-muted-foreground pt-2">100% local-first • your data never leaves your device</p>- </DialogHeader>{isMacOS && (<div className="mt-6 pt-4 border-t w-full flex flex-col items-center">@@ -424,15 +425,13 @@ const OnboardingStatus: React.FC<OnboardingStatusProps> = ({<ChevronDown className="h-4 w-4" /></button>)}-- <div className="sticky bottom-0 bg-background pt-2 pb-1 w-full">+ </div><OnboardingNavigationhandlePrevSlide={handlePrev}handleNextSlide={handleNext}prevBtnText="previous"nextBtnText="next"/>- </div></div>);};diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsxindex 4189a824c..adef58b5d 100644--- a/screenpipe-app-tauri/components/settings.tsx+++ b/screenpipe-app-tauri/components/settings.tsx@@ -21,6 +21,7 @@ import { AccountSection } from "./settings/account-section";import ShortcutSection from "./settings/shortcut-section";import DiskUsage from "./settings/disk-usage";import AISection from "./settings/ai-section";+import { AIPresets } from "./settings/ai-presets";import {DropdownMenu,DropdownMenuContent,@@ -110,7 +111,7 @@ export function Settings() {case "general":return <GeneralSettings />;case "ai":- return <AISection />;+ return <AIPresets />;case "account":return <AccountSection />;case "recording":@@ -265,7 +266,7 @@ export function Settings() {"flex items-center space-x-2 px-4 py-1.5 rounded-lg transition-colors",activeSection === section.id? "bg-black/90 text-white"- : "hover:bg-black/10"+ : "hover:bg-black/10",)}>{section.icon}diff --git a/screenpipe-app-tauri/components/settings/ai-presets.tsx b/screenpipe-app-tauri/components/settings/ai-presets.tsxnew file mode 100644index 000000000..c3b64819d--- /dev/null+++ b/screenpipe-app-tauri/components/settings/ai-presets.tsx@@ -0,0 +1,967 @@+import { useEffect, useMemo, useState } from "react";+import { Button } from "../ui/button";+import {+ AIPreset,+ DEFAULT_PROMPT,+ useSettings,+} from "@/lib/hooks/use-settings";+import { AIModel, AIProviderCard, OllamaModel } from "./ai-section";+import { Label } from "../ui/label";+import { Input } from "../ui/input";+import {+ ArrowLeft,+ ChevronsUpDown,+ Eye,+ EyeOff,+ HelpCircle,+ Loader2,+ Plus,+ RefreshCw,+ Settings2,+ Trash2,+ XIcon,+} from "lucide-react";+import { Textarea } from "../ui/textarea";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "../ui/tooltip";+import { Slider } from "../ui/slider";+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "../ui/command";+import { Badge } from "../ui/badge";+import { toast } from "../ui/use-toast";+import { Card } from "../ui/card";+import { AIProviderType } from "@screenpipe/browser";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { cn } from "@/lib/utils";++const AISection = ({+ preset,+ setDialog,+ isDuplicating,+}: {+ preset?: AIPreset;+ setDialog: (value: boolean) => void;+ isDuplicating?: boolean;+}) => {+ const { settings, updateSettings } = useSettings();+ const [settingsPreset, setSettingsPreset] = useState<+ Partial<AIPreset> | undefined+ >(preset);+ const [isLoading, setIsLoading] = useState(false);+ const [showApiKey, setShowApiKey] = useState(false);+ const [nameError, setNameError] = useState<string | null>(null);++ const validateName = (name: string) => {+ if (!name) {+ setNameError("name is required");+ return false;+ }+ if (name.trim().toLowerCase().endsWith("copy")) {+ setNameError("name cannot end with 'copy'");+ return false;+ }+ if (settings.aiPresets.find(+ (p) => p.id.toLowerCase() === name.toLowerCase() && p.id !== preset?.id+ )) {+ setNameError("name already exists");+ return false;+ }+ setNameError(null);+ return true;+ };++ const updateStoreSettings = async () => {+ setIsLoading(true);+ try {+ if (!settingsPreset?.id) {+ toast({+ title: "please enter a name",+ description: "name is required",+ variant: "destructive",+ });+ return;+ }++ if (!validateName(settingsPreset.id)) {+ return;+ }++ // If this is the first preset, make it default+ if (!settings.aiPresets.length) {+ const defaultPreset = {+ ...settingsPreset,+ prompt: settingsPreset?.prompt || DEFAULT_PROMPT,+ maxContextChars: settingsPreset?.maxContextChars || 512000,+ defaultPreset: true,+ } as AIPreset;++ await updateSettings({+ aiModel: defaultPreset?.model,+ aiProviderType: defaultPreset?.provider,+ customPrompt: defaultPreset?.prompt,+ aiMaxContextChars: defaultPreset?.maxContextChars,+ aiUrl: defaultPreset?.url,+ ...("apiKey" in defaultPreset && {+ openaiApiKey: defaultPreset.apiKey,+ }),+ aiPresets: [defaultPreset],+ });++ toast({+ title: "preset created",+ description: "default preset has been created",+ });++ setDialog(false);+ return;+ }++ // Handle update case+ if (preset && !isDuplicating) {+ const updatedPresets = settings.aiPresets.map((p) => {+ if (p.id === preset.id) {+ const updatedPreset = {+ ...settingsPreset,+ prompt: settingsPreset?.prompt || DEFAULT_PROMPT,+ maxContextChars: settingsPreset?.maxContextChars || 512000,+ defaultPreset: p.defaultPreset,+ } as AIPreset;++ // If this is the default preset, update global settings too+ if (p.defaultPreset) {+ updateSettings({+ aiModel: updatedPreset.model,+ aiProviderType: updatedPreset.provider,+ customPrompt: updatedPreset.prompt,+ aiMaxContextChars: updatedPreset.maxContextChars,+ aiUrl: updatedPreset.url,+ ...("apiKey" in updatedPreset && {+ openaiApiKey: updatedPreset.apiKey,+ }),+ });+ }++ return updatedPreset;+ }+ return p;+ });++ await updateSettings({+ aiPresets: updatedPresets,+ });++ toast({+ title: "preset updated",+ description: "changes have been saved",+ });+ } else {+ // Handle create case (new preset or duplicate)+ const newPreset = {+ ...settingsPreset,+ prompt: settingsPreset?.prompt || DEFAULT_PROMPT,+ maxContextChars: settingsPreset?.maxContextChars || 512000,+ defaultPreset: false,+ } as AIPreset;++ await updateSettings({+ aiPresets: [...settings.aiPresets, newPreset],+ });++ toast({+ title: isDuplicating ? "preset duplicated" : "preset created",+ description: isDuplicating ? "duplicate has been saved" : "new preset has been added",+ });+ }++ setDialog(false);+ } catch (error) {+ toast({+ title: "error saving preset",+ description: "something went wrong while saving the preset",+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ }+ };++ const updateSettingsPreset = (presetsObject: Partial<AIPreset>) => {+ setSettingsPreset({ ...settingsPreset, ...presetsObject });+ };++ const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const value = e.target.value;+ updateSettingsPreset({+ apiKey: value,+ });+ };++ const handleMaxContextCharsChange = (value: number[]) => {+ updateSettingsPreset({+ maxContextChars: value[0],+ });+ };++ const handleCustomPromptChange = (+ e: React.ChangeEvent<HTMLTextAreaElement>,+ ) => {+ updateSettingsPreset({+ prompt: e.target.value ?? DEFAULT_PROMPT,+ });+ };++ const handleResetCustomPrompt = () => {+ updateSettingsPreset({+ prompt: DEFAULT_PROMPT,+ });+ };++ const handleAiProviderChange = (newValue: AIPreset["provider"]) => {+ let newUrl = "";+ let newModel = settingsPreset?.model;++ switch (newValue) {+ case "openai":+ newUrl = "https://api.openai.com/v1";+ break;+ case "native-ollama":+ newUrl = "http://localhost:11434/v1";+ break;+ case "screenpipe-cloud":+ newUrl = "https://ai-proxy.i-f9f.workers.dev/v1";+ break;+ case "custom":+ newUrl = settingsPreset?.url || "";+ break;+ }++ updateSettingsPreset({+ provider: newValue,+ url: newUrl,+ model: newModel,+ });+ };++ const isApiKeyRequired =+ settingsPreset?.url !== "https://ai-proxy.i-f9f.workers.dev/v1" &&+ settingsPreset?.url !== "http://localhost:11434/v1" &&+ settingsPreset?.url !== "embedded";++ const [models, setModels] = useState<AIModel[]>([]);+ const [isLoadingModels, setIsLoadingModels] = useState(false);++ const fetchModels = async () => {+ setIsLoadingModels(true);+ console.log(settingsPreset);+ try {+ switch (settingsPreset?.provider) {+ case "screenpipe-cloud":+ const response = await fetch(+ "https://ai-proxy.i-f9f.workers.dev/v1/models",+ {+ headers: {+ Authorization: `Bearer ${settings.user?.id || ""}`,+ },+ },+ );+ if (!response.ok) throw new Error("Failed to fetch models");+ const data = await response.json();+ setModels(data.models);+ break;++ case "native-ollama":+ const ollamaResponse = await fetch("http://localhost:11434/api/tags");+ if (!ollamaResponse.ok)+ throw new Error("Failed to fetch Ollama models");+ const ollamaData = (await ollamaResponse.json()) as {+ models: OllamaModel[];+ };+ setModels(+ (ollamaData.models || []).map((model) => ({+ id: model.name,+ name: model.name,+ provider: "ollama",+ })),+ );+ break;++ case "openai":+ setModels([+ { id: "gpt-4", name: "gpt-4", provider: "openai" },+ {+ id: "gpt-3.5-turbo",+ name: "gpt-3.5-turbo",+ provider: "openai",+ },+ ]);+ break;++ case "custom":+ try {+ const customResponse = await fetch(+ `${settingsPreset?.url}/models`,+ {+ headers: settingsPreset.apiKey+ ? { Authorization: `Bearer ${settingsPreset?.apiKey}` }+ : {},+ },+ );+ if (!customResponse.ok)+ throw new Error("Failed to fetch custom models");+ const customData = await customResponse.json();+ console.log(customData);+ setModels(+ (customData.data || []).map((model: { id: string }) => ({+ id: model.id,+ name: model.id,+ provider: "custom",+ })),+ );+ } catch (error) {+ console.error(+ "Failed to fetch custom models, allowing manual input:",+ error,+ );+ setModels([]);+ }+ break;++ default:+ setModels([]);+ }+ } catch (error) {+ console.error(+ `Failed to fetch models for ${settingsPreset?.provider}:`,+ error,+ );+ setModels([]);+ } finally {+ setIsLoadingModels(false);+ }+ };++ const apiKey = useMemo(() => {+ if (settingsPreset && "apiKey" in settingsPreset) {+ return settingsPreset?.apiKey;+ }+ return "";+ }, [settingsPreset]);++ useEffect(() => {+ console.log("hello");+ fetchModels();+ }, [settingsPreset?.provider, apiKey, settingsPreset?.url]);++ return (+ <div className="w-full space-y-6 py-4">+ <div className="flex flex-col gap-2">+ <Button+ className="w-max flex gap-2"+ variant={"link"}+ onClick={() => setDialog(false)}+ >+ <ArrowLeft className="w-4 h-4" /> back+ </Button>+ <h1 className="text-2xl font-bold">+ {preset ? "update preset" : "create preset"}+ </h1>+ </div>+ <div className="w-full">+ <div className="flex flex-col gap-2">+ <Label htmlFor="aiUrl" className="min-w-[80px]">+ ai provider+ </Label>+ </div>+ <div className="grid grid-cols-2 gap-4 mb-4 mt-4">+ <AIProviderCard+ type="openai"+ title="openai"+ description="use your own openai api key for gpt-4 and other models"+ imageSrc="/images/openai.png"+ selected={settingsPreset?.provider === "openai"}+ onClick={() => handleAiProviderChange("openai")}+ />++ <AIProviderCard+ type="screenpipe-cloud"+ title="screenpipe cloud"+ description="use openai, anthropic and google models without worrying about api keys or usage"+ imageSrc="/images/screenpipe.png"+ selected={settingsPreset?.provider === "screenpipe-cloud"}+ onClick={() => handleAiProviderChange("screenpipe-cloud")}+ disabled={!settings.user}+ warningText={+ !settings.user+ ? "login required"+ : !settings.user?.credits?.amount+ ? "requires credits"+ : undefined+ }+ />++ <AIProviderCard+ type="native-ollama"+ title="ollama"+ description="run ai models locally using your existing ollama installation"+ imageSrc="/images/ollama.png"+ selected={settingsPreset?.provider === "native-ollama"}+ onClick={() => handleAiProviderChange("native-ollama")}+ />++ <AIProviderCard+ type="custom"+ title="custom"+ description="connect to your own ai provider or self-hosted models"+ imageSrc="/images/custom.png"+ selected={settingsPreset?.provider === "custom"}+ onClick={() => handleAiProviderChange("custom")}+ />+ </div>+ </div>+ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4">+ <Label htmlFor="preset_id" className="flex items-center gap-2">+ name+ {nameError && (+ <span className="text-xs text-destructive font-normal">+ {nameError}+ </span>+ )}+ </Label>+ <Input+ id="preset_id"+ value={settingsPreset?.id}+ onChange={(e) => {+ const namePreset = e.target.value;+ validateName(namePreset);+ updateSettingsPreset({ id: namePreset });+ }}+ className={cn(+ "flex-grow",+ nameError && "border-destructive focus-visible:ring-destructive"+ )}+ placeholder="enter name"+ autoCorrect="off"+ autoCapitalize="off"+ autoComplete="off"+ type="text"+ disabled={!!preset && !isDuplicating && preset.id !== undefined}+ />+ </div>+ </div>++ {settingsPreset?.provider === "custom" && (+ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4">+ <Label htmlFor="customAiUrl">custom url</Label>+ <Input+ id="customAiUrl"+ value={settingsPreset?.url}+ onChange={(e) => {+ const newUrl = e.target.value;+ updateSettingsPreset({ url: newUrl });+ }}+ className="flex-grow"+ placeholder="enter custom ai url"+ autoCorrect="off"+ autoCapitalize="off"+ autoComplete="off"+ type="text"+ />+ </div>+ </div>+ )}+ {isApiKeyRequired &&+ (settingsPreset?.provider === "openai" ||+ settingsPreset?.provider === "custom") && (+ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4 w-full">+ <Label htmlFor="aiApiKey">API Key</Label>+ <div className="flex-grow relative">+ <Input+ id="aiApiKey"+ type={showApiKey ? "text" : "password"}+ value={settingsPreset?.apiKey}+ onChange={handleApiKeyChange}+ className="pr-10"+ placeholder="enter your ai api key"+ autoCorrect="off"+ autoCapitalize="off"+ autoComplete="off"+ />+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="absolute right-0 top-0 h-full"+ onClick={() => setShowApiKey(!showApiKey)}+ >+ {showApiKey ? (+ <EyeOff className="h-4 w-4" />+ ) : (+ <Eye className="h-4 w-4" />+ )}+ </Button>+ </div>+ </div>+ </div>+ )}++ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4 w-full">+ <Label htmlFor="aiModel">ai model</Label>+ <Popover modal={true}>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ role="combobox"+ className="w-full justify-between"+ >+ {settingsPreset?.model || "select model..."}+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-full p-0">+ <Command>+ <CommandInput placeholder="select or type model name" />+ <CommandList>+ <CommandEmpty>+ press enter to use "{settingsPreset?.model}"+ </CommandEmpty>+ <CommandGroup heading="Suggestions">+ {isLoadingModels ? (+ <CommandItem value="loading" disabled>+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ loading models...+ </CommandItem>+ ) : (+ models.map((model) => (+ <CommandItem+ key={model.id}+ value={model.id}+ onSelect={() => {+ updateSettingsPreset({ model: model.id });+ }}+ >+ {model.name}+ <Badge variant="outline" className="ml-2">+ {model.provider}+ </Badge>+ </CommandItem>+ ))+ )}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </div>+ </div>+ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4 w-full">+ <Label htmlFor="customPrompt">prompt</Label>+ <div className="flex-grow relative">+ <Textarea+ id="customPrompt"+ value={settingsPreset?.prompt || DEFAULT_PROMPT}+ onChange={handleCustomPromptChange}+ className="min-h-[100px]"+ placeholder="enter your custom prompt here"+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="absolute right-2 top-2"+ onClick={handleResetCustomPrompt}+ >+ <RefreshCw className="h-4 w-4 mr-2" />+ reset+ </Button>+ </div>+ </div>+ </div>++ <div className="w-full">+ <div className="flex flex-col gap-4 mb-4 w-full">+ <Label htmlFor="aiMaxContextChars" className="flex items-center">+ max context{" "}+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <HelpCircle className="ml-2 h-4 w-4 cursor-default" />+ </TooltipTrigger>+ <TooltipContent side="left">+ <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. <br />+ we'll use this for UI purposes to show you how much you+ can send.+ </p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </Label>+ <div className="flex-grow flex items-center">+ <Slider+ id="aiMaxContextChars"+ min={10000}+ max={1000000}+ step={10000}+ value={+ settingsPreset?.maxContextChars+ ? [settingsPreset?.maxContextChars]+ : [512000]+ }+ onValueChange={handleMaxContextCharsChange}+ className="flex-grow"+ />+ <span className="ml-2 min-w-[60px] text-right">+ {settingsPreset?.maxContextChars?.toLocaleString() ?? 512000}+ </span>+ </div>+ </div>+ </div>+ <div className="flex justify-end">+ <Button+ onClick={() => updateStoreSettings()}+ disabled={isLoading}+ >+ {isLoading ? (+ <Loader2 className="w-4 h-4 animate-spin mr-2" />+ ) : null}+ {preset ? "update preset" : "create preset"}+ </Button>+ </div>+ </div>+ );+};++const providerImageSrc: Record<AIPreset["provider"], string> = {+ openai: "/images/openai.png",+ "screenpipe-cloud": "/images/screenpipe.png",+ "native-ollama": "/images/ollama.png",+ custom: "/images/custom.png",+};++export const AIPresets = () => {+ const { settings, updateSettings } = useSettings();+ const [createPresetsDialog, setCreatePresentDialog] = useState(false);+ const [selectedPreset, setSelectedPreset] = useState<AIPreset | undefined>();+ const [isLoading, setIsLoading] = useState(false);+ const [presetToDelete, setPresetToDelete] = useState<string | null>(null);+ const [presetToSetDefault, setPresetToSetDefault] = useState<string | null>(null);+ const [isDuplicating, setIsDuplicating] = useState(false);++ useEffect(() => {+ if (!createPresetsDialog) {+ setSelectedPreset(undefined);+ setIsDuplicating(false);+ }+ }, [createPresetsDialog]);++ if (createPresetsDialog)+ return (+ <AISection+ setDialog={setCreatePresentDialog}+ preset={selectedPreset}+ isDuplicating={isDuplicating}+ />+ );++ const removePreset = async (id: string) => {+ setIsLoading(true);+ try {+ const checkIfDefault = settings.aiPresets.find(+ (preset) => preset.id === id,+ )?.defaultPreset;++ if (checkIfDefault) {+ toast({+ title: "cannot delete default preset",+ description: "please set another preset as default first",+ variant: "destructive",+ });+ return;+ }++ const checkIfIDPresent = settings.aiPresets.find(+ (preset) => preset.id === id,+ );++ if (!checkIfIDPresent) {+ toast({+ title: "preset not found",+ description: "the preset you're trying to delete doesn't exist",+ variant: "destructive",+ });+ return;+ }++ const filteredPresets = settings.aiPresets.filter(+ (preset) => preset.id !== id,+ );++ await updateSettings({+ aiPresets: filteredPresets,+ });++ toast({+ title: "preset deleted",+ description: "the preset has been removed successfully",+ });+ } catch (error) {+ toast({+ title: "error deleting preset",+ description: "something went wrong while deleting the preset",+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ setPresetToDelete(null);+ }+ };++ const setDefaultPreset = async (id: string) => {+ setIsLoading(true);+ try {+ const selectedPreset = settings.aiPresets.find((p) => p.id === id);+ if (!selectedPreset) return;++ const updatedPresets = settings.aiPresets.map((preset) => ({+ ...preset,+ defaultPreset: preset.id === id,+ }));++ const updateData: any = {+ aiPresets: updatedPresets,+ aiModel: selectedPreset.model,+ aiProviderType: selectedPreset.provider,+ customPrompt: selectedPreset.prompt,+ aiMaxContextChars: selectedPreset.maxContextChars,+ aiUrl: selectedPreset.url,+ };++ if ('apiKey' in selectedPreset) {+ updateData.openaiApiKey = selectedPreset.apiKey;+ }++ await updateSettings(updateData);++ toast({+ title: "default preset updated",+ description: "the preset has been set as default",+ });+ } catch (error) {+ toast({+ title: "error updating default preset",+ description: "something went wrong while updating the default preset",+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ setPresetToSetDefault(null);+ }+ };++ const duplicatePreset = async (id: string) => {+ const presetToDuplicate = settings.aiPresets.find((p) => p.id === id);+ if (!presetToDuplicate) return;++ const newPreset = {+ ...presetToDuplicate,+ id: `${presetToDuplicate.id} copy`,+ defaultPreset: false,+ };++ setSelectedPreset(newPreset);+ setIsDuplicating(true);+ setCreatePresentDialog(true);+ };++ if (!settings.aiPresets?.length) {+ return (+ <div className="w-full h-[400px] flex flex-col items-center justify-center space-y-4">+ <Settings2 className="w-12 h-12 text-muted-foreground" />+ <h2 className="text-xl font-medium text-muted-foreground">no presets yet</h2>+ <p className="text-sm text-muted-foreground">create your first ai preset to get started</p>+ <Button onClick={() => setCreatePresentDialog(true)}>+ <Plus className="w-4 h-4 mr-2" />+ create preset+ </Button>+ </div>+ );+ }++ return (+ <div className="w-full space-y-6 py-4">+ <div className="flex items-center justify-between">+ <h1 className="text-2xl font-bold">ai settings</h1>+ <Button onClick={() => setCreatePresentDialog(true)}>+ <Plus className="w-4 h-4 mr-2" />+ create preset+ </Button>+ </div>+ <div className="w-full grid grid-cols-1 md:grid-cols-2 gap-4">+ {settings.aiPresets.map((preset) => {+ const isDefault = preset.defaultPreset;+ return (+ <Card+ key={preset.id}+ className="p-4 relative group transition-all hover:shadow-md"+ >+ <div+ className="flex justify-between items-start cursor-pointer"+ onClick={() => {+ setSelectedPreset(preset);+ setIsDuplicating(false);+ setCreatePresentDialog(true);+ }}+ >+ <div className="space-y-2">+ <div className="text-lg font-semibold text-foreground flex items-center gap-2">+ {preset.id}+ {isDefault && (+ <Badge variant="secondary" className="font-normal">+ default+ </Badge>+ )}+ </div>+ <div className="text-sm text-muted-foreground space-y-1">+ <div className="flex items-center gap-2">+ <span>model:</span>+ <span className="font-medium">{preset.model}</span>+ </div>+ <div className="flex items-center gap-2">+ <span>context:</span>+ <span className="font-medium">+ {preset.maxContextChars?.toLocaleString()}+ </span>+ </div>+ </div>+ </div>+ <img+ src={providerImageSrc[preset.provider]}+ alt={`${preset.provider} logo`}+ className="w-10 h-10 opacity-80 group-hover:opacity-100 transition-opacity"+ />+ </div>+ <div className="flex justify-end gap-2 mt-4">+ <Button+ className="text-xs"+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ duplicatePreset(preset.id);+ }}+ disabled={isLoading}+ >+ duplicate+ </Button>+ <Button+ className="text-xs"+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ setPresetToSetDefault(preset.id);+ }}+ disabled={isLoading || isDefault}+ >+ {isDefault ? "current default" : "set as default"}+ </Button>+ <Button+ className="text-xs text-destructive"+ variant="ghost"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ setPresetToDelete(preset.id);+ }}+ disabled={isLoading || isDefault}+ >+ <Trash2 className="w-3 h-3 mr-1" />+ remove+ </Button>+ </div>+ </Card>+ );+ })}+ </div>++ <AlertDialog open={!!presetToDelete} onOpenChange={() => setPresetToDelete(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>are you sure?</AlertDialogTitle>+ <AlertDialogDescription>+ this action cannot be undone. this will permanently delete the preset.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>cancel</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"+ onClick={() => presetToDelete && removePreset(presetToDelete)}+ >+ {isLoading ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ "delete"+ )}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={!!presetToSetDefault}+ onOpenChange={() => setPresetToSetDefault(null)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>change default preset?</AlertDialogTitle>+ <AlertDialogDescription>+ this will set this preset as the default and apply its settings.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => presetToSetDefault && setDefaultPreset(presetToSetDefault)}+ >+ {isLoading ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ "continue"+ )}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+};diff --git a/screenpipe-app-tauri/components/settings/ai-section.tsx b/screenpipe-app-tauri/components/settings/ai-section.tsxindex 163241dec..7d69ca2f1 100644--- a/screenpipe-app-tauri/components/settings/ai-section.tsx+++ b/screenpipe-app-tauri/components/settings/ai-section.tsx@@ -39,9 +39,8 @@ import {PopoverContent,PopoverTrigger,} from "@/components/ui/popover";-import posthog from "posthog-js";-interface AIProviderCardProps {+export interface AIProviderCardProps {type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded";title: string;description: string;@@ -53,20 +52,20 @@ interface AIProviderCardProps {imageClassName?: string;}-interface OllamaModel {+export interface OllamaModel {name: string;size: number;digest: string;modified_at: string;}-interface AIModel {+export interface AIModel {id: string;name: string;provider: string;}-const AIProviderCard = ({+export const AIProviderCard = ({type,title,description,@@ -83,7 +82,7 @@ const AIProviderCard = ({className={cn("flex py-4 px-4 rounded-lg hover:bg-accent transition-colors h-[145px] w-full cursor-pointer",selected ? "border-black/60 border-[1.5px]" : "",- disabled && "opacity-50 cursor-not-allowed"+ disabled && "opacity-50 cursor-not-allowed",)}><CardContent className="flex flex-col p-0 w-full">@@ -95,7 +94,7 @@ const AIProviderCard = ({"rounded-lg shrink-0 size-8",type === "native-ollama" &&"outline outline-gray-300 outline-1 outline-offset-2",- imageClassName+ imageClassName,)}/><span className="text-lg font-medium truncate">{title}</span>@@ -123,7 +122,7 @@ const AISection = () => {};const handleCustomPromptChange = (- e: React.ChangeEvent<HTMLTextAreaElement>+ e: React.ChangeEvent<HTMLTextAreaElement>,) => {updateSettings({ customPrompt: e.target.value });};@@ -182,7 +181,7 @@ const AISection = () => {headers: {Authorization: `Bearer ${settings.user?.id || ""}`,},- }+ },);if (!response.ok) throw new Error("Failed to fetch models");const data = await response.json();@@ -201,7 +200,7 @@ const AISection = () => {id: model.name,name: model.name,provider: "ollama",- }))+ })),);break;@@ -228,12 +227,12 @@ const AISection = () => {id: model.id,name: model.id,provider: "custom",- }))+ })),);} catch (error) {console.error("Failed to fetch custom models, allowing manual input:",- error+ error,);setModels([]);}@@ -245,7 +244,7 @@ const AISection = () => {} catch (error) {console.error(`Failed to fetch models for ${settings.aiProviderType}:`,- error+ error,);setModels([]);} finally {@@ -286,8 +285,8 @@ const AISection = () => {!settings.user? "login required": !settings.user?.credits?.amount- ? "requires credits"- : undefined+ ? "requires credits"+ : undefined}/>diff --git a/screenpipe-app-tauri/components/ui/alert-dialog.tsx b/screenpipe-app-tauri/components/ui/alert-dialog.tsxnew file mode 100644index 000000000..010910e7f--- /dev/null+++ b/screenpipe-app-tauri/components/ui/alert-dialog.tsx@@ -0,0 +1,139 @@+import * as React from "react"+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"++import { cn } from "@/lib/utils"+import { buttonVariants } from "@/components/ui/button"++const AlertDialog = AlertDialogPrimitive.Root++const AlertDialogTrigger = AlertDialogPrimitive.Trigger++const AlertDialogPortal = AlertDialogPrimitive.Portal++const AlertDialogOverlay = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Overlay+ className={cn(+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className+ )}+ {...props}+ ref={ref}+ />+))+AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName++const AlertDialogContent = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>+>(({ className, ...props }, ref) => (+ <AlertDialogPortal>+ <AlertDialogOverlay />+ <AlertDialogPrimitive.Content+ ref={ref}+ className={cn(+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",+ className+ )}+ {...props}+ />+ </AlertDialogPortal>+))+AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName++const AlertDialogHeader = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col space-y-2 text-center sm:text-left",+ className+ )}+ {...props}+ />+)+AlertDialogHeader.displayName = "AlertDialogHeader"++const AlertDialogFooter = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ className+ )}+ {...props}+ />+)+AlertDialogFooter.displayName = "AlertDialogFooter"++const AlertDialogTitle = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Title+ ref={ref}+ className={cn("text-lg font-semibold", className)}+ {...props}+ />+))+AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName++const AlertDialogDescription = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Description>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Description+ ref={ref}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+))+AlertDialogDescription.displayName =+ AlertDialogPrimitive.Description.displayName++const AlertDialogAction = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Action>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Action+ ref={ref}+ className={cn(buttonVariants(), className)}+ {...props}+ />+))+AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName++const AlertDialogCancel = React.forwardRef<+ React.ElementRef<typeof AlertDialogPrimitive.Cancel>,+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>+>(({ className, ...props }, ref) => (+ <AlertDialogPrimitive.Cancel+ ref={ref}+ className={cn(+ buttonVariants({ variant: "outline" }),+ "mt-2 sm:mt-0",+ className+ )}+ {...props}+ />+))+AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName++export {+ AlertDialog,+ AlertDialogPortal,+ AlertDialogOverlay,+ AlertDialogTrigger,+ AlertDialogContent,+ AlertDialogHeader,+ AlertDialogFooter,+ AlertDialogTitle,+ AlertDialogDescription,+ AlertDialogAction,+ AlertDialogCancel,+}\ No newline at end of filediff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex 3f951b0ed..6dac7b2b3 100644--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -3,11 +3,11 @@ import { platform } from "@tauri-apps/plugin-os";import { Pipe } from "./use-pipes";import { Language } from "@/lib/language";import {- action,- Action,- persist,- PersistStorage,- createContextStore,+ action,+ Action,+ persist,+ PersistStorage,+ createContextStore,} from "easy-peasy";import { LazyStore, LazyStore as TauriStore } from "@tauri-apps/plugin-store";import { localDataDir } from "@tauri-apps/api/path";@@ -19,222 +19,255 @@ import localforage from "localforage";export type VadSensitivity = "low" | "medium" | "high";export type AIProviderType =- | "native-ollama"- | "openai"- | "custom"- | "embedded"- | "screenpipe-cloud";+ | "native-ollama"+ | "openai"+ | "custom"+ | "embedded"+ | "screenpipe-cloud";export type EmbeddedLLMConfig = {- enabled: boolean;- model: string;- port: number;+ enabled: boolean;+ model: string;+ port: number;};export enum Shortcut {- SHOW_SCREENPIPE = "show_screenpipe",- START_RECORDING = "start_recording",- STOP_RECORDING = "stop_recording",+ SHOW_SCREENPIPE = "show_screenpipe",+ START_RECORDING = "start_recording",+ STOP_RECORDING = "stop_recording",}export type User = {- id?: string;- email?: string;- name?: string;- image?: string;- token?: string;- clerk_id?: string;- api_key?: string;- credits?: {- amount: number;- };- stripe_connected?: boolean;- stripe_account_status?: "active" | "pending";- github_username?: string;- bio?: string;- website?: string;- contact?: string;- cloud_subscribed?: boolean;+ id?: string;+ email?: string;+ name?: string;+ image?: string;+ token?: string;+ clerk_id?: string;+ api_key?: string;+ credits?: {+ amount: number;+ };+ stripe_connected?: boolean;+ stripe_account_status?: "active" | "pending";+ github_username?: string;+ bio?: string;+ website?: string;+ contact?: string;+ cloud_subscribed?: boolean;};+export type AIPreset = {+ id: string;+ maxContextChars: number;+ url: string;+ model: string;+ defaultPreset: boolean;+ prompt: string;+ //provider: AIProviderType;+} & (+ | {+ provider: "openai";+ apiKey: string;+ }+ | {+ provider: "native-ollama";+ }+ | {+ provider: "screenpipe-cloud";+ }+ | {+ provider: "custom";+ apiKey?: string;+ }+);+export type Settings = {- openaiApiKey: string;- deepgramApiKey: string;- isLoading: boolean;- aiModel: string;- installedPipes: Pipe[];- userId: string;- customPrompt: string;- devMode: boolean;- audioTranscriptionEngine: string;- ocrEngine: string;- monitorIds: string[];- audioDevices: string[];- usePiiRemoval: boolean;- restartInterval: number;- port: number;- dataDir: string;- disableAudio: boolean;- ignoredWindows: string[];- includedWindows: string[];- aiProviderType: AIProviderType;- aiUrl: string;- aiMaxContextChars: number;- fps: number;- vadSensitivity: VadSensitivity;- analyticsEnabled: boolean;- audioChunkDuration: number; // new field- useChineseMirror: boolean; // Add this line- embeddedLLM: EmbeddedLLMConfig;- languages: Language[];- enableBeta: boolean;- isFirstTimeUser: boolean;- autoStartEnabled: boolean- enableFrameCache: boolean; // Add this line- enableUiMonitoring: boolean; // Add this line- platform: string; // Add this line- disabledShortcuts: Shortcut[];- user: User;- showScreenpipeShortcut: string;- startRecordingShortcut: string;- stopRecordingShortcut: string;- startAudioShortcut: string;- stopAudioShortcut: string;- pipeShortcuts: Record<string, string>;- enableRealtimeAudioTranscription: boolean;- realtimeAudioTranscriptionEngine: string;- disableVision: boolean;- useAllMonitors: boolean;- enableRealtimeVision: boolean;+ openaiApiKey: string;+ deepgramApiKey: string;+ isLoading: boolean;+ aiModel: string;+ installedPipes: Pipe[];+ userId: string;+ customPrompt: string;+ devMode: boolean;+ audioTranscriptionEngine: string;+ ocrEngine: string;+ monitorIds: string[];+ audioDevices: string[];+ usePiiRemoval: boolean;+ restartInterval: number;+ port: number;+ dataDir: string;+ disableAudio: boolean;+ ignoredWindows: string[];+ includedWindows: string[];+ aiProviderType: AIProviderType;+ aiUrl: string;+ aiMaxContextChars: number;+ fps: number;+ vadSensitivity: VadSensitivity;+ analyticsEnabled: boolean;+ audioChunkDuration: number; // new field+ useChineseMirror: boolean; // Add this line+ embeddedLLM: EmbeddedLLMConfig;+ languages: Language[];+ enableBeta: boolean;+ isFirstTimeUser: boolean;+ autoStartEnabled: boolean;+ enableFrameCache: boolean; // Add this line+ enableUiMonitoring: boolean; // Add this line+ platform: string; // Add this line+ disabledShortcuts: Shortcut[];+ user: User;+ showScreenpipeShortcut: string;+ startRecordingShortcut: string;+ stopRecordingShortcut: string;+ startAudioShortcut: string;+ stopAudioShortcut: string;+ pipeShortcuts: Record<string, string>;+ enableRealtimeAudioTranscription: boolean;+ realtimeAudioTranscriptionEngine: string;+ disableVision: boolean;+ useAllMonitors: boolean;+ aiPresets: AIPreset[];+ enableRealtimeVision: boolean;};-const DEFAULT_SETTINGS: Settings = {- openaiApiKey: "",- deepgramApiKey: "", // for now we hardcode our key (dw about using it, we have bunch of credits)- isLoading: true,- aiModel: "gpt-4o",- installedPipes: [],- userId: "",- customPrompt: `Rules:+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+`;+const DEFAULT_SETTINGS: Settings = {+ aiPresets: [],+ openaiApiKey: "",+ deepgramApiKey: "", // for now we hardcode our key (dw about using it, we have bunch of credits)+ isLoading: true,+ aiModel: "gpt-4o",+ installedPipes: [],+ userId: "",+ customPrompt: `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`,- devMode: false,- audioTranscriptionEngine: "deepgram",- ocrEngine: "default",- monitorIds: ["default"],- audioDevices: ["default"],- usePiiRemoval: false,- restartInterval: 0,- port: 3030,- dataDir: "default",- disableAudio: false,- ignoredWindows: [],- includedWindows: [],- aiProviderType: "openai",- aiUrl: "https://api.openai.com/v1",- aiMaxContextChars: 512000,- fps: 0.5,- vadSensitivity: "high",- analyticsEnabled: true,- audioChunkDuration: 30, // default to 10 seconds- useChineseMirror: false, // Add this line- languages: [],- embeddedLLM: {- enabled: false,- model: "llama3.2:1b-instruct-q4_K_M",- port: 11434,- },- enableBeta: false,- isFirstTimeUser: true,- autoStartEnabled: true,- enableFrameCache: true, // Add this line- enableUiMonitoring: false, // Change from true to false- platform: "unknown", // Add this line- disabledShortcuts: [],- user: {},- showScreenpipeShortcut: "Super+Alt+S",- startRecordingShortcut: "Super+Alt+R",- stopRecordingShortcut: "Super+Alt+X",- startAudioShortcut: "",- stopAudioShortcut: "",- pipeShortcuts: {},- enableRealtimeAudioTranscription: false,- realtimeAudioTranscriptionEngine: "whisper-large-v3-turbo",- disableVision: false,- useAllMonitors: false,- enableRealtimeVision: false,+ devMode: false,+ audioTranscriptionEngine: "deepgram",+ ocrEngine: "default",+ monitorIds: ["default"],+ audioDevices: ["default"],+ usePiiRemoval: false,+ restartInterval: 0,+ port: 3030,+ dataDir: "default",+ disableAudio: false,+ ignoredWindows: [],+ includedWindows: [],+ aiProviderType: "openai",+ aiUrl: "https://api.openai.com/v1",+ aiMaxContextChars: 512000,+ fps: 0.5,+ vadSensitivity: "high",+ analyticsEnabled: true,+ audioChunkDuration: 30, // default to 10 seconds+ useChineseMirror: false, // Add this line+ languages: [],+ embeddedLLM: {+ enabled: false,+ model: "llama3.2:1b-instruct-q4_K_M",+ port: 11434,+ },+ enableBeta: false,+ isFirstTimeUser: true,+ autoStartEnabled: true,+ enableFrameCache: true, // Add this line+ enableUiMonitoring: false, // Change from true to false+ platform: "unknown", // Add this line+ disabledShortcuts: [],+ user: {},+ showScreenpipeShortcut: "Super+Alt+S",+ startRecordingShortcut: "Super+Alt+R",+ stopRecordingShortcut: "Super+Alt+X",+ startAudioShortcut: "",+ stopAudioShortcut: "",+ pipeShortcuts: {},+ enableRealtimeAudioTranscription: false,+ realtimeAudioTranscriptionEngine: "whisper-large-v3-turbo",+ disableVision: false,+ useAllMonitors: false,+ enableRealtimeVision: false,};const DEFAULT_IGNORED_WINDOWS_IN_ALL_OS = [- "bit",- "VPN",- "Trash",- "Private",- "Incognito",- "Wallpaper",- "Settings",- "Keepass",- "Recorder",- "Vaults",- "OBS Studio",- "screenpipe",+ "bit",+ "VPN",+ "Trash",+ "Private",+ "Incognito",+ "Wallpaper",+ "Settings",+ "Keepass",+ "Recorder",+ "Vaults",+ "OBS Studio",+ "screenpipe",];const DEFAULT_IGNORED_WINDOWS_PER_OS: Record<string, string[]> = {- macos: [- ".env",- "Item-0",- "App Icon Window",- "Battery",- "Shortcuts",- "WiFi",- "BentoBox",- "Clock",- "Dock",- "DeepL",- "Control Center",- ],- windows: ["Nvidia", "Control Panel", "System Properties"],- linux: ["Info center", "Discover", "Parted"],+ macos: [+ ".env",+ "Item-0",+ "App Icon Window",+ "Battery",+ "Shortcuts",+ "WiFi",+ "BentoBox",+ "Clock",+ "Dock",+ "DeepL",+ "Control Center",+ ],+ windows: ["Nvidia", "Control Panel", "System Properties"],+ linux: ["Info center", "Discover", "Parted"],};// Model definitionexport interface StoreModel {- settings: Settings;- setSettings: Action<StoreModel, Partial<Settings>>;- resetSettings: Action<StoreModel>;- resetSetting: Action<StoreModel, keyof Settings>;+ settings: Settings;+ setSettings: Action<StoreModel, Partial<Settings>>;+ resetSettings: Action<StoreModel>;+ resetSetting: Action<StoreModel, keyof Settings>;}export function createDefaultSettingsObject(): Settings {- let defaultSettings = { ...DEFAULT_SETTINGS };- try {- const currentPlatform = platform();-- const ocrModel =- currentPlatform === "macos"- ? "apple-native"- : currentPlatform === "windows"- ? "windows-native"- : "tesseract";-- defaultSettings.ocrEngine = ocrModel;- defaultSettings.fps = currentPlatform === "macos" ? 0.5 : 1;- defaultSettings.platform = currentPlatform;-- defaultSettings.ignoredWindows = [- ...DEFAULT_IGNORED_WINDOWS_IN_ALL_OS,- ...(DEFAULT_IGNORED_WINDOWS_PER_OS[currentPlatform] ?? []),- ];-- return defaultSettings;- } catch (e) {- return DEFAULT_SETTINGS;- }+ let defaultSettings = { ...DEFAULT_SETTINGS };+ try {+ const currentPlatform = platform();++ const ocrModel =+ currentPlatform === "macos"+ ? "apple-native"+ : currentPlatform === "windows"+ ? "windows-native"+ : "tesseract";++ defaultSettings.ocrEngine = ocrModel;+ defaultSettings.fps = currentPlatform === "macos" ? 0.5 : 1;+ defaultSettings.platform = currentPlatform;++ defaultSettings.ignoredWindows = [+ ...DEFAULT_IGNORED_WINDOWS_IN_ALL_OS,+ ...(DEFAULT_IGNORED_WINDOWS_PER_OS[currentPlatform] ?? []),+ ];++ return defaultSettings;+ } catch (e) {+ return DEFAULT_SETTINGS;+ }}// Create a singleton store instance@@ -244,217 +277,214 @@ let storePromise: Promise<LazyStore> | null = null;* @warning Do not change autoSave to true, it causes race conditions*/export const getStore = async () => {- if (!storePromise) {- storePromise = (async () => {- const dir = await localDataDir();- const profilesStore = new TauriStore(`${dir}/screenpipe/profiles.bin`, {- autoSave: false,- });- const activeProfile =- (await profilesStore.get("activeProfile")) || "default";- const file =- activeProfile === "default"- ? `store.bin`- : `store-${activeProfile}.bin`;- console.log("activeProfile", activeProfile, file);- return new TauriStore(`${dir}/screenpipe/${file}`, {- autoSave: false,- });- })();- }- return storePromise;+ if (!storePromise) {+ storePromise = (async () => {+ const dir = await localDataDir();+ const profilesStore = new TauriStore(`${dir}/screenpipe/profiles.bin`, {+ autoSave: false,+ });+ const activeProfile =+ (await profilesStore.get("activeProfile")) || "default";+ const file =+ activeProfile === "default"+ ? `store.bin`+ : `store-${activeProfile}.bin`;+ console.log("activeProfile", activeProfile, file);+ return new TauriStore(`${dir}/screenpipe/${file}`, {+ autoSave: false,+ });+ })();+ }+ return storePromise;};const tauriStorage: PersistStorage = {- getItem: async (_key: string) => {- const tauriStore = await getStore();- const allKeys = await tauriStore.keys();- const values: Record<string, any> = {};-- for (const k of allKeys) {- values[k] = await tauriStore.get(k);- }-- return { settings: unflattenObject(values) };- },- setItem: async (_key: string, value: any) => {- const tauriStore = await getStore();-- delete value.settings.customSettings;- const flattenedValue = flattenObject(value.settings);-- // Delete all existing keys first- //const existingKeys = await tauriStore.keys();- //for (const key of existingKeys) {- // await tauriStore.delete(key);- //}-- // Only delete keys that are present in the new settings- for (const key of Object.keys(flattenedValue)) {- await tauriStore.delete(key);- }-- // Set new flattened values- for (const [key, val] of Object.entries(flattenedValue)) {- await tauriStore.set(key, val);- }-- await tauriStore.save();- },- removeItem: async (_key: string) => {- const tauriStore = await getStore();- const keys = await tauriStore.keys();- for (const key of keys) {- await tauriStore.delete(key);- }- await tauriStore.save();- },+ getItem: async (_key: string) => {+ const tauriStore = await getStore();+ const allKeys = await tauriStore.keys();+ const values: Record<string, any> = {};++ for (const k of allKeys) {+ values[k] = await tauriStore.get(k);+ }++ return { settings: unflattenObject(values) };+ },+ setItem: async (_key: string, value: any) => {+ const tauriStore = await getStore();++ delete value.settings.customSettings;+ const flattenedValue = flattenObject(value.settings);++ // Only delete keys that are present in the new settings+ for (const key of Object.keys(flattenedValue)) {+ await tauriStore.delete(key);+ }++ // Set new flattened values+ for (const [key, val] of Object.entries(flattenedValue)) {+ if (!key || !key.length) continue;+ const defaultValue = key in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[key as keyof Settings] : "";+ await tauriStore.set(key, val === undefined ? defaultValue : val);+ }++ await tauriStore.save();+ },+ removeItem: async (_key: string) => {+ const tauriStore = await getStore();+ const keys = await tauriStore.keys();+ for (const key of keys) {+ await tauriStore.delete(key);+ }+ await tauriStore.save();+ },};export const store = createContextStore<StoreModel>(- persist(- {- settings: createDefaultSettingsObject(),- setSettings: action((state, payload) => {- state.settings = {- ...state.settings,- ...payload,- };- }),- resetSettings: action((state) => {- state.settings = createDefaultSettingsObject();- }),- resetSetting: action((state, key) => {- const defaultValue = createDefaultSettingsObject()[key];- (state.settings as any)[key] = defaultValue;- }),- },- {- storage: tauriStorage,- mergeStrategy: "mergeDeep",- }- )+ persist(+ {+ settings: createDefaultSettingsObject(),+ setSettings: action((state, payload) => {+ console.log(state, payload);+ state.settings = {+ ...state.settings,+ ...payload,+ };+ }),+ resetSettings: action((state) => {+ state.settings = createDefaultSettingsObject();+ }),+ resetSetting: action((state, key) => {+ const defaultValue = createDefaultSettingsObject()[key];+ (state.settings as any)[key] = defaultValue;+ }),+ },+ {+ storage: tauriStorage,+ mergeStrategy: "mergeDeep",+ },+ ),);export function useSettings() {- const settings = store.useStoreState((state) => state.settings);- const setSettings = store.useStoreActions((actions) => actions.setSettings);- const resetSettings = store.useStoreActions(- (actions) => actions.resetSettings- );- const resetSetting = store.useStoreActions((actions) => actions.resetSetting);-- useEffect(() => {- if (settings.user?.id) {- posthog.identify(settings.user?.id, {- email: settings.user?.email,- name: settings.user?.name,- github_username: settings.user?.github_username,- website: settings.user?.website,- contact: settings.user?.contact,- });- }- }, [settings.user?.id]);-- const getDataDir = async () => {- const homeDirPath = await homeDir();-- if (- settings.dataDir !== "default" &&- settings.dataDir &&- settings.dataDir !== ""- )- return settings.dataDir;-- let p = "macos";- try {- p = platform();- } catch (e) {}-- return p === "macos" || p === "linux"- ? `${homeDirPath}/.screenpipe`- : `${homeDirPath}\\.screenpipe`;- };-- const loadUser = async (token: string, forceReload = false) => {- try {- // try to get from cache first (unless force reload)- const cacheKey = `user_data_${token}`;- if (!forceReload) {- const cached = await localforage.getItem<{- data: User;- timestamp: number;- }>(cacheKey);-- // use cache if less than 30s old- if (cached && Date.now() - cached.timestamp < 30000) {- setSettings({- user: cached.data,- });- return;- }- }-- const response = await fetch(`https://screenpi.pe/api/user`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ token }),- });-- if (!response.ok) {- throw new Error("failed to verify token");- }-- const data = await response.json();- const userData = {- ...data.user,- } as User;-- // if user was not logged in, send posthog event app_login with email- if (!settings.user?.id) {- posthog.capture("app_login", {- email: userData.email,- });- }-- // cache the result- await localforage.setItem(cacheKey, {- data: userData,- timestamp: Date.now(),- });-- setSettings({- user: userData,- });- } catch (err) {- console.error("failed to load user:", err);- throw err;- }- };-- const reloadStore = async () => {- const store = await getStore();- await store.reload();-- const allKeys = await store.keys();- const values: Record<string, any> = {};-- for (const k of allKeys) {- values[k] = await store.get(k);- }-- setSettings(unflattenObject(values));- };-- return {- settings,- updateSettings: setSettings,- resetSettings,- reloadStore,- loadUser,- resetSetting,- getDataDir,- };+ const settings = store.useStoreState((state) => state.settings);+ const setSettings = store.useStoreActions((actions) => actions.setSettings);+ const resetSettings = store.useStoreActions(+ (actions) => actions.resetSettings,+ );+ const resetSetting = store.useStoreActions((actions) => actions.resetSetting);++ useEffect(() => {+ if (settings.user?.id) {+ posthog.identify(settings.user?.id, {+ email: settings.user?.email,+ name: settings.user?.name,+ github_username: settings.user?.github_username,+ website: settings.user?.website,+ contact: settings.user?.contact,+ });+ }+ }, [settings.user?.id]);++ const getDataDir = async () => {+ const homeDirPath = await homeDir();++ if (+ settings.dataDir !== "default" &&+ settings.dataDir &&+ settings.dataDir !== ""+ )+ return settings.dataDir;++ let p = "macos";+ try {+ p = platform();+ } catch (e) {}++ return p === "macos" || p === "linux"+ ? `${homeDirPath}/.screenpipe`+ : `${homeDirPath}\\.screenpipe`;+ };++ const loadUser = async (token: string, forceReload = false) => {+ try {+ // try to get from cache first (unless force reload)+ const cacheKey = `user_data_${token}`;+ if (!forceReload) {+ const cached = await localforage.getItem<{+ data: User;+ timestamp: number;+ }>(cacheKey);++ // use cache if less than 30s old+ if (cached && Date.now() - cached.timestamp < 30000) {+ setSettings({+ user: cached.data,+ });+ return;+ }+ }++ const response = await fetch(`https://screenpi.pe/api/user`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ token }),+ });++ if (!response.ok) {+ throw new Error("failed to verify token");+ }++ const data = await response.json();+ const userData = {+ ...data.user,+ } as User;++ // if user was not logged in, send posthog event app_login with email+ if (!settings.user?.id) {+ posthog.capture("app_login", {+ email: userData.email,+ });+ }++ // cache the result+ await localforage.setItem(cacheKey, {+ data: userData,+ timestamp: Date.now(),+ });++ setSettings({+ user: userData,+ });+ } catch (err) {+ console.error("failed to load user:", err);+ throw err;+ }+ };++ const reloadStore = async () => {+ const store = await getStore();+ await store.reload();++ const allKeys = await store.keys();+ const values: Record<string, any> = {};++ for (const k of allKeys) {+ values[k] = await store.get(k);+ }++ setSettings(unflattenObject(values));+ };++ return {+ settings,+ updateSettings: setSettings,+ resetSettings,+ reloadStore,+ loadUser,+ resetSetting,+ getDataDir,+ };}diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.jsonindex e7e4573e4..c395d114d 100644--- a/screenpipe-app-tauri/package.json+++ b/screenpipe-app-tauri/package.json@@ -13,6 +13,7 @@"@patternfly/react-core": "^6.1.0","@patternfly/react-log-viewer": "^6.1.0","@radix-ui/react-accordion": "^1.2.0",+ "@radix-ui/react-alert-dialog": "^1.1.6","@radix-ui/react-avatar": "^1.1.0","@radix-ui/react-checkbox": "^1.1.1","@radix-ui/react-collapsible": "^1.1.0",diff --git a/screenpipe-js/common/types.ts b/screenpipe-js/common/types.tsindex 7e7a9c469..2b39e921e 100644--- a/screenpipe-js/common/types.ts+++ b/screenpipe-js/common/types.ts@@ -224,6 +224,31 @@ export interface User {};}+export type AIPreset = {+ id: string;+ maxContextChars: number;+ url: string;+ model: string;+ defaultPreset: boolean;+ prompt: string;+ //provider: AIProviderType;+} & (+ | {+ provider: "openai";+ apiKey: string;+ }+ | {+ provider: "native-ollama";+ }+ | {+ provider: "screenpipe-cloud";+ }+ | {+ provider: "custom";+ apiKey?: string;+ }+);+export interface Settings {openaiApiKey: string;deepgramApiKey: string;@@ -249,6 +274,7 @@ export interface Settings {enableRealtimeAudioTranscription: boolean;realtimeAudioTranscriptionEngine: string;disableVision: boolean;+ aiPresets: AIPreset[];}/**diff --git a/screenpipe-js/common/utils.ts b/screenpipe-js/common/utils.tsindex b996bb387..734e179a3 100644--- a/screenpipe-js/common/utils.ts+++ b/screenpipe-js/common/utils.ts@@ -37,7 +37,7 @@ const unflattenObject = (obj: Record<string, any>): any => {// Helper functions that work in both environmentsfunction toCamelCase(str: string): string {return str.replace(/([-_][a-z])/g, (group) =>- group.toUpperCase().replace("-", "").replace("_", "")+ group.toUpperCase().replace("-", "").replace("_", ""),);}@@ -69,7 +69,6 @@ function getDefaultSettings(): Settings {- 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-`,port: 3030,dataDir: "default",@@ -96,6 +95,7 @@ function getDefaultSettings(): Settings {enableRealtimeAudioTranscription: false,realtimeAudioTranscriptionEngine: "deepgram",disableVision: false,+ aiPresets: [],};}diff --git a/screenpipe-js/node-sdk/package.json b/screenpipe-js/node-sdk/package.jsonindex e639afacd..5c161b816 100644--- a/screenpipe-js/node-sdk/package.json+++ b/screenpipe-js/node-sdk/package.json@@ -1,6 +1,6 @@{"name": "@screenpipe/js",- "version": "1.0.17",+ "version": "1.0.18","type": "module","main": "./dist/index.cjs","module": "./dist/index.js",