Skip to content

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

feat: embedded LLM, #475

Louis Beaumont2ef28b4075a4
diff --git a/screenpipe-app-tauri/.gitignore b/screenpipe-app-tauri/.gitignore
index 91d80e76a..77c196197 100644
--- a/screenpipe-app-tauri/.gitignore
+++ b/screenpipe-app-tauri/.gitignore
@@ -42,4 +42,5 @@ ffmpeg*
*src-tauri/screenpipe*
*src-tauri/tesseract*
*src-tauri/deno*
+*src-tauri/ollama*
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index 47d5441c5..84a83d9d8 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -49,6 +49,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
+import { LogFileButton } from "./screenpipe-status";
export interface Pipe {
enabled: boolean;
@@ -427,6 +428,7 @@ const PipeDialog: React.FC = () => {
<Heart className="mr-2 h-4 w-4" />
support us
</Button>
+ <LogFileButton />
</div>
<Separator className="my-4" />
@@ -710,10 +712,7 @@ const PipeDialog: React.FC = () => {
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
- <Button
- size="sm"
- onClick={handleResetAllPipes}
- >
+ <Button size="sm" onClick={handleResetAllPipes}>
<Trash2 className="mr-2 h-4 w-4" />
reset all pipes
</Button>
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index a5e0fdfd6..950dbf92d 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -64,8 +64,12 @@ ${cliInstructions}
const logPath =
os === "windows"
- ? `%USERPROFILE%\\.screenpipe\\screenpipe.${new Date().toISOString().split('T')[0]}.log`
- : `$HOME/.screenpipe/screenpipe.${new Date().toISOString().split('T')[0]}.log`;
+ ? `%USERPROFILE%\\.screenpipe\\screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`
+ : `$HOME/.screenpipe/screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`;
const dbPath =
os === "windows"
@@ -386,8 +390,12 @@ const HealthStatus = ({ className }: { className?: string }) => {
const homeDirPath = await homeDir();
const logPath =
platform() === "windows"
- ? `${homeDirPath}\\.screenpipe\\screenpipe.${new Date().toISOString().split('T')[0]}.log`
- : `${homeDirPath}/.screenpipe/screenpipe.${new Date().toISOString().split('T')[0]}.log`;
+ ? `${homeDirPath}\\.screenpipe\\screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`
+ : `${homeDirPath}/.screenpipe/screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`;
await open(logPath);
} catch (error) {
console.error("failed to open log file:", error);
@@ -418,9 +426,13 @@ const HealthStatus = ({ className }: { className?: string }) => {
if (!health) {
return (
- <Badge variant="outline" className="cursor-pointer bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground">
+ <Badge
+ variant="outline"
+ className="cursor-pointer bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground"
+ >
<Activity className="mr-2 h-4 w-4" />
- status <span className="ml-1 w-2 h-2 rounded-full bg-yellow-500 inline-block animate-pulse" />
+ status{" "}
+ <span className="ml-1 w-2 h-2 rounded-full bg-yellow-500 inline-block animate-pulse" />
</Badge>
);
}
@@ -560,23 +572,7 @@ const HealthStatus = ({ className }: { className?: string }) => {
recorder logs
<span>{isLogOpen ? "▲" : "▼"}</span>
</CollapsibleTrigger>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- onClick={handleOpenLogFile}
- className="ml-2"
- >
- <FileText className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>open log file</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
+ <LogFileButton />
</div>
<CollapsibleContent>
<LogViewer className="mt-2" />
@@ -589,4 +585,48 @@ const HealthStatus = ({ className }: { className?: string }) => {
);
};
-export default HealthStatus;
\ No newline at end of file
+export const LogFileButton = ({ className }: { className?: string }) => {
+ const { toast } = useToast();
+ const handleOpenLogFile = async () => {
+ try {
+ const homeDirPath = await homeDir();
+ const logPath =
+ platform() === "windows"
+ ? `${homeDirPath}\\.screenpipe\\screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`
+ : `${homeDirPath}/.screenpipe/screenpipe.${
+ new Date().toISOString().split("T")[0]
+ }.log`;
+ await open(logPath);
+ } catch (error) {
+ console.error("failed to open log file:", error);
+ toast({
+ title: "error",
+ description: "failed to open log file.",
+ variant: "destructive",
+ duration: 3000,
+ });
+ }
+ };
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleOpenLogFile}
+ className="ml-2"
+ >
+ <FileText className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>open log file</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+};
+export default HealthStatus;
diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsx
index 480fe1051..ad58be722 100644
--- a/screenpipe-app-tauri/components/settings.tsx
+++ b/screenpipe-app-tauri/components/settings.tsx
@@ -1,5 +1,5 @@
"use client";
-import React from "react";
+import React, { useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
@@ -23,14 +23,33 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "./ui/textarea";
import { Slider } from "@/components/ui/slider"; // Add this import
-import { Eye, EyeOff, HelpCircle, RefreshCw, Settings2 } from "lucide-react";
+import {
+ Eye,
+ EyeOff,
+ HelpCircle,
+ RefreshCw,
+ Settings2,
+ Check,
+ X,
+ Play,
+ Loader2,
+} from "lucide-react";
import { RecordingSettings } from "./recording-settings";
import { Switch } from "./ui/switch";
+import { Command } from "@tauri-apps/plugin-shell";
+import { LogFileButton } from "./screenpipe-status";
+import { platform } from "@tauri-apps/plugin-os";
+
+import { toast } from "@/components/ui/use-toast";
+import { invoke } from "@tauri-apps/api/core";
export function Settings({ className }: { className?: string }) {
const { settings, updateSettings, resetSetting } = useSettings();
const [localSettings, setLocalSettings] = React.useState(settings);
const [showApiKey, setShowApiKey] = React.useState(false);
+ const [ollamaStatus, setOllamaStatus] = useState<
+ "idle" | "running" | "error"
+ >("idle");
const handleApiUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
@@ -76,14 +95,100 @@ export function Settings({ className }: { className?: string }) {
updateSettings({ aiMaxContextChars: newValue });
};
+ const handleEmbeddedLLMChange = (checked: boolean) => {
+ const newValue = { ...localSettings.embeddedLLM, enabled: checked };
+ setLocalSettings({ ...localSettings, embeddedLLM: newValue });
+ updateSettings({ embeddedLLM: newValue });
+ if (!checked) {
+ setOllamaStatus("idle");
+ }
+ };
+
+ const handleEmbeddedLLMModelChange = (
+ e: React.ChangeEvent<HTMLInputElement>
+ ) => {
+ const newValue = { ...localSettings.embeddedLLM, model: e.target.value };
+ setLocalSettings({ ...localSettings, embeddedLLM: newValue });
+ updateSettings({ embeddedLLM: newValue });
+ };
+
+ const handleEmbeddedLLMPortChange = (
+ e: React.ChangeEvent<HTMLInputElement>
+ ) => {
+ const newValue = {
+ ...localSettings.embeddedLLM,
+ port: parseInt(e.target.value, 10),
+ };
+ setLocalSettings({ ...localSettings, embeddedLLM: newValue });
+ updateSettings({ embeddedLLM: newValue });
+ };
+
React.useEffect(() => {
setLocalSettings(settings);
}, [settings]);
+ const startOllamaSidecar = async () => {
+ setOllamaStatus("running");
+ toast({
+ title: "starting ai",
+ description: "initializing the embedded ai...",
+ });
+
+ try {
+ const result = await invoke<string>("start_ollama_sidecar", {
+ settings: {
+ enabled: localSettings.embeddedLLM.enabled,
+ model: localSettings.embeddedLLM.model,
+ port: localSettings.embeddedLLM.port,
+ },
+ });
+
+ setOllamaStatus("running");
+ toast({
+ title: "ai ready",
+ description: `${localSettings.embeddedLLM.model} is running.`,
+ });
+
+ // Show the LLM test result in a toast
+ toast({
+ title: `${localSettings.embeddedLLM.model} wants to tell you a joke.`,
+ description: result,
+ duration: 10000,
+ });
+ } catch (error) {
+ console.error("Error starting ai sidecar:", error);
+ setOllamaStatus("error");
+ toast({
+ title: "error starting ai",
+ description: "check the console for more details",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleStopLLM = async () => {
+ try {
+ await invoke("stop_ollama_sidecar");
+ setOllamaStatus("idle");
+ toast({
+ title: "ai stopped",
+ description: "the embedded ai has been shut down",
+ });
+ } catch (error) {
+ console.error("error stopping ai:", error);
+ toast({
+ title: "error stopping ai",
+ description: "check the console for more details",
+ variant: "destructive",
+ });
+ }
+ };
+
return (
<Dialog
onOpenChange={(open) => {
- if (!open) { // hack bcs something does not update settings for some reason
+ if (!open) {
+ // hack bcs something does not update settings for some reason
window.location.reload();
}
}}
@@ -300,6 +405,131 @@ export function Settings({ className }: { className?: string }) {
for ollama, or any other provider, use the url running on your
local machine or elsewhere and the exact model name.
</p>
+
+ <Separator className="my-4" />
+
+ <div className="w-full">
+ <div className="flex items-center gap-4 mb-4">
+ <div className="flex items-center min-w-[80px] justify-end">
+ <Label htmlFor="embeddedLLM" className="text-right mr-2">
+ embedded ai
+ </Label>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-4 w-4 cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-[300px]">
+ <p>
+ enable this to use local ai features in screenpipe.
+ you can use it through search or pipes for enhanced
+ functionality without relying on external services.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <div className="flex items-center gap-4">
+ <Switch
+ id="embeddedLLM"
+ checked={localSettings.embeddedLLM.enabled}
+ onCheckedChange={handleEmbeddedLLMChange}
+ />
+ <Button
+ onClick={startOllamaSidecar}
+ disabled={
+ !localSettings.embeddedLLM.enabled ||
+ ollamaStatus === "running"
+ }
+ className="ml-auto"
+ >
+ {ollamaStatus === "running" ? (
+ <Check className="h-4 w-4 mr-2" />
+ ) : ollamaStatus === "error" ? (
+ <X className="h-4 w-4 mr-2" />
+ ) : ollamaStatus === "idle" ? (
+ <Play className="h-4 w-4 mr-2" />
+ ) : (
+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />
+ )}
+ {ollamaStatus === "running"
+ ? "running"
+ : ollamaStatus === "error"
+ ? "error"
+ : "start llm"}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={handleStopLLM}
+ className="ml-auto"
+ >
+ <X className="h-4 w-4 mr-2" />
+ stop llm
+ </Button>
+ <LogFileButton />
+ </div>
+ </div>
+ </div>
+
+ {localSettings.embeddedLLM.enabled && (
+ <>
+ <div className="w-full">
+ <div className="flex items-center gap-4 mb-4">
+ <Label
+ htmlFor="embeddedLLMModel"
+ className="min-w-[80px] text-right"
+ >
+ llm model
+ </Label>
+ <div className="flex-grow flex items-center">
+ <Input
+ id="embeddedLLMModel"
+ value={localSettings.embeddedLLM.model}
+ onChange={handleEmbeddedLLMModelChange}
+ className="flex-grow"
+ placeholder="enter embedded llm model"
+ />
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="ml-2 h-4 w-4 cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent
+ side="right"
+ className="max-w-[300px]"
+ >
+ <p>
+ supported models are the same as ollama. check
+ the ollama documentation for a list of available
+ models.
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ </div>
+
+ <div className="w-full">
+ <div className="flex items-center gap-4 mb-4">
+ <Label
+ htmlFor="embeddedLLMPort"
+ className="min-w-[80px] text-right"
+ >
+ llm port
+ </Label>
+ <Input
+ id="embeddedLLMPort"
+ type="number"
+ value={localSettings.embeddedLLM.port}
+ onChange={handleEmbeddedLLMPortChange}
+ className="flex-grow"
+ placeholder="enter embedded llm port"
+ />
+ </div>
+ </div>
+ </>
+ )}
</CardContent>
</Card>
@@ -360,4 +590,4 @@ export function Settings({ className }: { className?: string }) {
</DialogContent>
</Dialog>
);
-}
\ No newline at end of file
+}
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index e173f4953..6f08b4937 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -5,6 +5,43 @@ import { platform } from "@tauri-apps/plugin-os";
import { Pipe } from "./use-pipes";
import posthog from "posthog-js";
+export type VadSensitivity = "low" | "medium" | "high";
+export type EmbeddedLLMConfig = {
+ enabled: boolean;
+ model: string;
+ port: number;
+};
+
+export interface 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[];
+ aiUrl: string;
+ aiMaxContextChars: number;
+ fps: number;
+ vadSensitivity: VadSensitivity;
+ analyticsEnabled: boolean;
+ audioChunkDuration: number; // new field
+ useChineseMirror: boolean; // Add this line
+ embeddedLLM: EmbeddedLLMConfig;
+}
+
const defaultSettings: Settings = {
openaiApiKey: "",
deepgramApiKey: "7ed2a159a094337b01fd8178b914b7ae0e77822d", // for now we hardcode our key (dw about using it, we have bunch of credits)
@@ -38,38 +75,13 @@ const defaultSettings: Settings = {
analyticsEnabled: true,
audioChunkDuration: 30, // default to 10 seconds
useChineseMirror: false, // Add this line
+ embeddedLLM: {
+ enabled: false,
+ model: "llama3.2:1b-instruct-q4_K_M",
+ port: 11438,
+ },
};
-export type VadSensitivity = "low" | "medium" | "high";
-export interface 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[];
- aiUrl: string;
- aiMaxContextChars: number;
- fps: number;
- vadSensitivity: VadSensitivity;
- analyticsEnabled: boolean;
- audioChunkDuration: number; // new field
- useChineseMirror: boolean; // Add this line
-}
-
let store: Awaited<ReturnType<typeof createStore>> | null = null;
export function useSettings() {
@@ -126,8 +138,7 @@ export function useSettings() {
console.log("savedDevMode", savedDevMode);
const savedAudioTranscriptionEngine =
- (await store!.get<string>("audioTranscriptionEngine")) ||
- "deepgram";
+ (await store!.get<string>("audioTranscriptionEngine")) || "deepgram";
const savedOcrEngine =
(await store!.get<string>("ocrEngine")) || ocrModel;
const savedMonitorIds = (await store!.get<string[]>("monitorIds")) || [
@@ -163,6 +174,13 @@ export function useSettings() {
(await store!.get<number>("audioChunkDuration")) || 30;
const savedUseChineseMirror =
(await store!.get<boolean>("useChineseMirror")) || false;
+ const savedEmbeddedLLM = (await store!.get<EmbeddedLLMConfig>(
+ "embeddedLLM"
+ )) || {
+ enabled: false,
+ model: "llama3.2:1b-instruct-q4_K_M",
+ port: 11438,
+ };
setSettings({
openaiApiKey: savedKey,
deepgramApiKey: savedDeepgramKey,
@@ -190,6 +208,7 @@ export function useSettings() {
analyticsEnabled: savedAnalyticsEnabled,
audioChunkDuration: savedAudioChunkDuration,
useChineseMirror: savedUseChineseMirror,
+ embeddedLLM: savedEmbeddedLLM,
});
} catch (error) {
console.error("failed to load settings:", error);
diff --git a/screenpipe-app-tauri/scripts/pre_build.js b/screenpipe-app-tauri/scripts/pre_build.js
index e384c7226..e1364a6e3 100644
--- a/screenpipe-app-tauri/scripts/pre_build.js
+++ b/screenpipe-app-tauri/scripts/pre_build.js
@@ -95,8 +95,23 @@ const exports = {
cmake: 'C:\\Program Files\\CMake\\bin',
}
+// Add this function to check if Deno is installed
+async function isDenoInstalled() { // assuming it's installed in PATH
+ try {
+ await $`deno --version`.quiet();
+ return true;
+ } catch (error) {
+ return false;
+ }
+}
+
// Add this function to install Deno
async function installDeno() {
+ if (await isDenoInstalled()) {
+ console.log('deno is already installed.');
+ return;
+ }
+
console.log('installing deno...');
if (platform === 'windows') {
@@ -118,7 +133,7 @@ async function installDeno() {
// Add this function to copy the Deno binary
async function copyDenoBinary() {
- console.log('copying deno binary for tauri...');
+ console.log('checking deno binary for tauri...');
let denoSrc, denoDest1, denoDest2;
if (platform === 'windows') {
@@ -147,6 +162,11 @@ async function copyDenoBinary() {
return;
}
+ if (await fs.exists(denoDest1)) {
+ console.log('deno binary already exists for tauri.');
+ return;
+ }
+
try {
// Check if the source file exists
await fs.access(denoSrc);
@@ -635,20 +655,73 @@ if (process.env.GITHUB_ENV) {
await fs.appendFile(process.env.GITHUB_ENV, clblast)
}
- if (hasFeature('older-cpu')) {
- await fs.appendFile(process.env.GITHUB_ENV, `WHISPER_NO_AVX=ON\n`)
- await fs.appendFile(process.env.GITHUB_ENV, `WHISPER_NO_AVX2=ON\n`)
- await fs.appendFile(process.env.GITHUB_ENV, `WHISPER_NO_FMA=ON\n`)
- await fs.appendFile(process.env.GITHUB_ENV, `WHISPER_NO_F16C=ON\n`)
+ }
+}
+
+// Modify the installOllamaSidecar function
+async function installOllamaSidecar() {
+ const arch = process.arch;
+ const ollamaDir = path.join(__dirname, '..', 'src-tauri');
+ const ollamaVersion = 'v0.3.13';
+
+ let ollamaExe;
+
+ if (platform === 'windows') {
+ ollamaExe = 'ollama-x86_64-pc-windows-msvc.exe';
+ } else if (platform === 'macos') {
+ ollamaExe = process.arch === 'arm64' ? 'ollama-aarch64-apple-darwin' : 'ollama-x86_64-apple-darwin';
+ } else if (platform === 'linux') {
+ ollamaExe = 'ollama-x86_64-unknown-linux-gnu';
+ } else {
+ throw new Error('Unsupported platform');
+ }
+
+ const ollamaPath = path.join(ollamaDir, ollamaExe);
+
+ if (await fs.exists(ollamaPath)) {
+ console.log('Ollama sidecar already exists. Skipping installation.');
+ return;
+ }
+
+ try {
+ await fs.mkdir(ollamaDir, { recursive: true });
+ const downloadPath = path.join(ollamaDir, path.basename(ollamaUrl));
+
+ console.log('Downloading Ollama...');
+ await $`wget -q --show-progress ${ollamaUrl} -O ${downloadPath}`;
+
+ console.log('Extracting Ollama...');
+ if (platform === 'windows') {
+ await $`powershell -command "Expand-Archive -Path '${downloadPath}' -DestinationPath '${ollamaDir}'"`;
+ await fs.rename(path.join(ollamaDir, 'ollama.exe'), path.join(ollamaDir, ollamaExe));
+ } else if (platform === 'linux') {
+ await $`tar -xzf "${downloadPath}" -C "${ollamaDir}"`;
+ await fs.rename(path.join(ollamaDir, 'ollama'), path.join(ollamaDir, ollamaExe));
+ } else if (platform === 'macos') {
+ await fs.rename(downloadPath, path.join(ollamaDir, ollamaExe));
}
+
+ console.log('Setting permissions...');
+ if (platform !== 'windows') {
+ await fs.chmod(path.join(ollamaDir, ollamaExe), '755');
+ }
+
+ console.log('Cleaning up...');
+ if (platform !== 'macos') {
+ await fs.unlink(downloadPath);
+ }
+
+ console.log('Ollama sidecar installed successfully');
+ } catch (error) {
+ console.error('Error installing Ollama sidecar:', error);
+ throw error;
}
}
-// Install and setup Deno (add this near the end of the script)
+// Near the end of the script, call these functions
await installDeno();
await copyDenoBinary();
-
-
+await installOllamaSidecar().catch(console.error);
// --dev or --build
const action = process.argv?.[2]
@@ -666,4 +739,4 @@ if (action?.includes('--build' || action.includes('--dev'))) {
}
await $`bun install`
await $`bunx tauri ${action.includes('--dev') ? 'dev' : 'build'}`
-}
\ No newline at end of file
+}
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index e0172d674..db49758cb 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "0.4.5"
+version = "0.4.6"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/capabilities/main.json b/screenpipe-app-tauri/src-tauri/capabilities/main.json
index bb0e8393f..49616fc38 100644
--- a/screenpipe-app-tauri/src-tauri/capabilities/main.json
+++ b/screenpipe-app-tauri/src-tauri/capabilities/main.json
@@ -141,7 +141,38 @@
{
"name": "screenpipe",
"cmd": "screenpipe",
- "args": ["setup"],
+ "args": [
+ "setup"
+ ],
+ "sidecar": true
+ }
+ ]
+ },
+ {
+ "identifier": "shell:allow-spawn",
+ "allow": [
+ {
+ "name": "ollama",
+ "cmd": "ollama",
+ "args": [
+ "serve"
+ ],
+ "sidecar": true
+ }
+ ]
+ },
+ {
+ "identifier": "shell:allow-spawn",
+ "allow": [
+ {
+ "name": "ollama-run",
+ "cmd": "ollama",
+ "args": [
+ "run",
+ {
+ "validator": "\\S*"
+ }
+ ],
"sidecar": true
}
]
@@ -159,4 +190,4 @@
"process:default",
"store:default"
]
-}
+}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
index ec4c29e69..9b3a57c9d 100644
--- a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
+++ b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main"],"permissions":["core:event:allow-listen","core:event:default","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main"],"permissions":["core:event:allow-listen","core:event:default","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default"]}}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
new file mode 100644
index 000000000..d0e7087f6
--- /dev/null
+++ b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
@@ -0,0 +1,212 @@
+use anyhow::{anyhow, Result};
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+use tauri::Emitter;
+use tauri_plugin_shell::ShellExt;
+use tokio::time::sleep;
+use tracing::{error, info};
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EmbeddedLLMSettings {
+ pub enabled: bool,
+ pub model: String,
+ pub port: u16,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum OllamaStatus {
+ Idle,
+ Running,
+ Error,
+}
+
+pub struct LLMSidecar {
+ settings: EmbeddedLLMSettings,
+ status: OllamaStatus,
+}
+
+impl LLMSidecar {
+ pub fn new(settings: EmbeddedLLMSettings) -> Self {
+ Self {
+ settings,
+ status: OllamaStatus::Idle,
+ }
+ }
+
+ pub async fn start(&mut self, app: tauri::AppHandle) -> Result<String> {
+ self.status = OllamaStatus::Running;
+ app.emit("ollama_status", &self.status)?;
+
+ info!("Starting Ollama serve command...");
+ let serve_command = app.shell().sidecar("ollama").unwrap();
+ let serve_command = serve_command.args(&["serve"]).env(
+ "OLLAMA_HOST",
+ &format!("http://localhost:{}", self.settings.port),
+ );
+ let (_, _child) = serve_command
+ .spawn()
+ .map_err(|e| {
+ error!("Failed to spawn sidecar: {}", e);
+ e.to_string()
+ })
+ .unwrap();
+
+ info!("Waiting for Ollama server to start...");
+ self.wait_for_server().await?;
+
+ // now ollama run the model
+
+ let model_command = app.shell().sidecar("ollama").unwrap();
+ let model_command = model_command.args(&["run", &self.settings.model]);
+ let (_, _child) = model_command
+ .spawn()
+ .map_err(|e| {
+ error!("Failed to spawn sidecar: {}", e);
+ e.to_string()
+ })
+ .unwrap();
+
+ info!("Testing Ollama model...");
+ let test_result = self.test_model().await?;
+
+ Ok(test_result)
+ }
+
+ async fn wait_for_server(&self) -> Result<()> {
+ let max_retries = 30;
+ let retry_interval = Duration::from_secs(1);
+
+ for _ in 0..max_retries {
+ if let Ok(response) = reqwest::get(&format!(
+ "http://localhost:{}/api/version",
+ self.settings.port
+ ))
+ .await
+ {
+ if response.status().is_success() {
+ info!("Ollama server started successfully");
+ return Ok(());
+ }
+ }
+ sleep(retry_interval).await;
+ }
+
+ Err(anyhow!(
+ "Ollama server failed to start after maximum retries"
+ ))
+ }
+
+ async fn test_model(&self) -> Result<String> {
+ const MAX_RETRIES: u32 = 3;
+ const RETRY_DELAY: Duration = Duration::from_secs(2);
+
+ for attempt in 1..=MAX_RETRIES {
+ match self.attempt_model_test().await {
+ Ok(result) => {
+ info!("model test successful on attempt {}: {}", attempt, result);
+ return Ok(result);
+ }
+ Err(e) => {
+ if attempt == MAX_RETRIES {
+ return Err(anyhow!(
+ "failed to test model after {} attempts: {}",
+ MAX_RETRIES,
+ e
+ ));
+ }
+ error!("model test failed on attempt {}: {}", attempt, e);
+ sleep(RETRY_DELAY).await;
+ }
+ }
+ }
+
+ unreachable!()
+ }
+
+ async fn attempt_model_test(&self) -> Result<String> {
+ let client = reqwest::Client::new();
+ let response = client
+ .post(&format!(
+ "http://localhost:{}/v1/chat/completions",
+ self.settings.port
+ ))
+ .json(&serde_json::json!({
+ "model": self.settings.model,
+ "messages": [
+ {
+ "role": "user",
+ "content": "say a one sentence joke about screen recording, all lower case"
+ }
+ ],
+ "max_tokens": 50,
+ "stream": false
+ }))
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ return Err(anyhow!("failed to get response from model"));
+ }
+
+ let data: serde_json::Value = response.json().await?;
+ let result = data["choices"][0]["message"]["content"]
+ .as_str()
+ .ok_or_else(|| anyhow!("unexpected response format"))?
+ .trim()
+ .to_string();
+
+ Ok(result)
+ }
+
+ pub async fn stop(&mut self, app: tauri::AppHandle) -> Result<()> {
+ self.status = OllamaStatus::Idle;
+ app.emit("ollama_status", &self.status)?;
+
+ #[cfg(target_os = "windows")]
+ {
+ app.shell()
+ .command("taskkill")
+ .args(&["/F", "/IM", "ollama.exe"])
+ .spawn()
+ .unwrap();
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ {
+ let output = app
+ .shell()
+ .command("pkill")
+ .arg("ollama")
+ .output()
+ .await
+ .unwrap();
+ info!("Ollama stopped: {:?}", output);
+ }
+
+ Ok(())
+ }
+}
+
+#[tauri::command]
+pub async fn start_ollama_sidecar(
+ app: tauri::AppHandle,
+ settings: EmbeddedLLMSettings,
+) -> Result<String, String> {
+ let mut llm_sidecar = LLMSidecar::new(settings);
+ llm_sidecar
+ .start(app)
+ .await
+ .map_err(|e| format!("Failed to start Ollama: {}", e))
+}
+
+#[tauri::command]
+pub async fn stop_ollama_sidecar(app: tauri::AppHandle) -> Result<(), String> {
+ let mut llm_sidecar = LLMSidecar::new(EmbeddedLLMSettings {
+ enabled: false,
+ model: String::new(),
+ port: 0,
+ });
+ llm_sidecar
+ .stop(app)
+ .await
+ .map_err(|e| format!("Failed to stop Ollama: {}", e))
+}
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 2de06dae0..cd830884a 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -35,6 +35,7 @@ mod analytics;
use crate::analytics::start_analytics;
mod commands;
+mod llm_sidecar;
mod server;
mod sidecar;
mod updates;
@@ -115,7 +116,9 @@ async fn main() {
open_screen_capture_preferences,
load_pipe_config,
save_pipe_config,
- reset_all_pipes
+ reset_all_pipes,
+ llm_sidecar::start_ollama_sidecar,
+ llm_sidecar::stop_ollama_sidecar,
])
.setup(|app| {
// Logging setup
@@ -138,31 +141,8 @@ async fn main() {
.with_writer(std::io::stdout)
.with_filter(EnvFilter::new("debug"));
- // Initialize OpenTelemetry
- // let tracer = opentelemetry_otlp::new_pipeline()
- // .tracing()
- // .with_exporter(
- // opentelemetry_otlp::new_exporter()
- // .http()
- // .with_endpoint("https://otel.highlight.io/v1/traces")
- // )
- // .with_trace_config(
- // trace::config()
- // .with_sampler(Sampler::AlwaysOn)
- // .with_resource(Resource::new(vec![opentelemetry::KeyValue::new(
- // "service.name",
- // "screenpipe-app",
- // )]))
- // )
- // .install_batch(opentelemetry::runtime::Tokio)
- // .expect("Failed to initialize OpenTelemetry tracer");
-
- // // Create a tracing layer with the configured tracer
- // let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
-
// Initialize the tracing subscriber with both layers
tracing_subscriber::registry()
- // .with(telemetry)
.with(file_layer)
.with(console_layer)
.init();
@@ -225,7 +205,8 @@ async fn main() {
}
"update_now" => {
use tauri_plugin_notification::NotificationExt;
- app_handle.notification()
+ app_handle
+ .notification()
.builder()
.title("screenpipe")
.body("installing latest version")
@@ -304,7 +285,12 @@ async fn main() {
});
if is_analytics_enabled {
- match start_analytics(unique_id, posthog_api_key, interval_hours, "http://localhost:3030".to_string()) {
+ match start_analytics(
+ unique_id,
+ posthog_api_key,
+ interval_hours,
+ "http://localhost:3030".to_string(),
+ ) {
Ok(analytics_manager) => {
app.manage(analytics_manager);
}
diff --git a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
index 00b8afe09..1be2624c0 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.linux.conf.json
@@ -2,7 +2,8 @@
"bundle": {
"externalBin": [
"screenpipe",
- "deno"
+ "deno",
+ "ollama"
],
"linux": {
"deb": {
diff --git a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
index be05cc9f3..c8dda7c50 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
@@ -25,7 +25,8 @@
"externalBin": [
"screenpipe",
"ffmpeg",
- "deno"
+ "deno",
+ "ollama"
]
}
}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
index 2a8e72c96..52ce93ae4 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.windows.conf.json
@@ -2,7 +2,8 @@
"bundle": {
"externalBin": [
"screenpipe",
- "deno"
+ "deno",
+ "ollama"
],
"resources": {
"ffmpeg\\bin\\x64\\*": "./",