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: cli mode in app

Louis Beaumont1a341eca06be
diff --git a/Cargo.toml b/Cargo.toml
index 3a6aee33c..40510e0b8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,11 +4,11 @@ members = [
"screenpipe-vision",
"screenpipe-audio",
"screenpipe-server",
-
-]
-exclude = [
"examples/apps/screenpipe-app-tauri/src-tauri",
"examples/apps/screenpipe-app-dioxus",
+]
+exclude = [
+
]
resolver = "2"
diff --git a/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx b/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx
index 5a8718e9b..f0b28caed 100644
--- a/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx
+++ b/examples/apps/screenpipe-app-tauri/components/chat-list-openai-v2.tsx
@@ -221,7 +221,7 @@ export function ChatList({
// console.log("toolCalls", text.toolCalls);
// console.log("toolResults", text.toolResults);
- const { textStream } = ollama
+ const { textStream } = useOllama
? await streamText({
model: ollama(model),
prompt: JSON.stringify([
diff --git a/examples/apps/screenpipe-app-tauri/components/screenpipe-status.tsx b/examples/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
index 005e155a2..ccc018d9c 100644
--- a/examples/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/examples/apps/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -15,6 +15,7 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
import { CodeBlock } from "@/components/ui/codeblock";
+import { MemoizedReactMarkdown } from "./markdown";
interface HealthCheckResponse {
status: string;
@@ -30,14 +31,15 @@ const HealthStatus = ({ className }: { className?: string }) => {
const [health, setHealth] = useState<HealthCheckResponse | null>(null);
const [isBlinking, setIsBlinking] = useState(false);
const [isDialogOpen, setIsDialogOpen] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ // const [error, setError] = useState<HealthCheckResponse | null>(null);
useEffect(() => {
const fetchHealth = async () => {
try {
const response = await fetch("http://localhost:3030/health");
if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
+ const text = await response.text();
+ throw new Error(`HTTP error! status: ${response.status} ${text}`);
}
const data: HealthCheckResponse = await response.json();
if (health && data.status !== health.status) {
@@ -45,11 +47,26 @@ const HealthStatus = ({ className }: { className?: string }) => {
setTimeout(() => setIsBlinking(false), 5000); // Blink for 5 seconds on status change
}
setHealth(data);
- setError(null);
+ // setError(null);
} catch (error) {
console.error("Failed to fetch health status:", error);
- setError("Failed to fetch health status. Server might be down.");
- setHealth(null);
+ // setError("Failed to fetch health status. Server might be down.");
+ setHealth({
+ last_frame_timestamp: null,
+ last_audio_timestamp: null,
+ frame_status: "Error",
+ audio_status: "Error",
+ status: "Error",
+ message: "Failed to fetch health status. Server might be down.",
+ verbose_instructions:
+ "If you're experiencing issues, please try the following steps:\n\
+1. Restart the application.\n\
+2. If using a desktop app, reset your Screenpipe OS permissions.\n\
+3. Check your system's audio and video input devices.\n\
+4. Ensure you have granted necessary permissions to the application.\n\
+5. If the problem persists, please contact support with the details of this health check at [email protected].\n\
+6. Last, here are some [FAQ](https://github.com/louis030195/screen-pipe/blob/main/content/docs/NOTES.md) with visuals to help you troubleshoot.",
+ });
}
};
@@ -72,7 +89,7 @@ sqlite3 $HOME/.screenpipe/db.sqlite \\
# View last 10 audio transcriptions:
sqlite3 $HOME/.screenpipe/db.sqlite \\
"SELECT * FROM audio_transcriptions ORDER BY timestamp DESC LIMIT 10;"`;
- if (error) {
+ if (health && health.status === "Error") {
return (
<>
<style jsx>{`
@@ -96,9 +113,22 @@ sqlite3 $HOME/.screenpipe/db.sqlite \\
className={`w-4 h-4 rounded-full bg-red-500 animate-pulse-custom shadow-lg flex items-center justify-center text-white font-bold ${className}`}
/>
</TooltipTrigger>
- <TooltipContent className="w-64 p-2">
+ <TooltipContent className="w-128 p-2">
<h3 className="font-bold mb-2">Error</h3>
- <p className="text-sm">{error}</p>
+ <p className="text-sm">{health.message}</p>
+ {health && health.verbose_instructions && (
+ <div className="text-xs mt-2 text-red-500">
+ <p className="font-bold mb-1">
+ Troubleshooting Instructions:
+ </p>
+ <MemoizedReactMarkdown className="prose prose-sm">
+ {health.verbose_instructions}
+ </MemoizedReactMarkdown>
+ <p className="font-bold mt-2 text-yellow-500">
+ Instructions not working? Open settings and try CLI mode.
+ </p>
+ </div>
+ )}
<Button
variant="outline"
size="sm"
@@ -204,9 +234,15 @@ sqlite3 $HOME/.screenpipe/db.sqlite \\
Last Audio: {formatTimestamp(health.last_audio_timestamp)}
</p>
{health.verbose_instructions && (
- <p className="text-xs mt-2 text-red-500">
- {health.verbose_instructions}
- </p>
+ <div className="text-xs mt-2 text-red-500">
+ <p className="font-bold mb-1">Troubleshooting Instructions:</p>
+ <MemoizedReactMarkdown className="prose prose-sm">
+ {health.verbose_instructions}
+ </MemoizedReactMarkdown>
+ <p className="font-bold mt-2 text-yellow-500">
+ Instructions not working? Open settings and try CLI mode.
+ </p>
+ </div>
)}
<Button
variant="outline"
diff --git a/examples/apps/screenpipe-app-tauri/components/settings.tsx b/examples/apps/screenpipe-app-tauri/components/settings.tsx
index 93ad9fc98..d8cc9f81d 100644
--- a/examples/apps/screenpipe-app-tauri/components/settings.tsx
+++ b/examples/apps/screenpipe-app-tauri/components/settings.tsx
@@ -23,10 +23,24 @@ import { PrettyLink } from "./pretty-link";
import { MemoizedReactMarkdown } from "./markdown";
import { Separator } from "@/components/ui/separator";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import remarkGfm from "remark-gfm";
+import remarkMath from "remark-math";
+import { CodeBlock } from "./ui/codeblock";
+import { ChatMessageActions } from "./chat-message-actions";
+import { useCopyToClipboard } from "@/lib/hooks/use-copy-to-clipboard";
+import { cn } from "@/lib/utils";
+import { IconCheck, IconCopy } from "./ui/icons";
+import { invoke } from "@tauri-apps/api/core";
+import { spinner } from "./spinner";
export function Settings({ className }: { className?: string }) {
const { settings, updateSettings } = useSettings();
const [localSettings, setLocalSettings] = React.useState(settings);
+ const [isTogglingCli, setIsTogglingCli] = React.useState(false);
+ const [isTogglingCliError, setIsTogglingCliError] = React.useState("");
+
+ console.log("localSettings", localSettings);
+ console.log("settings", settings);
const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setLocalSettings({ ...localSettings, openaiApiKey: e.target.value });
@@ -39,6 +53,20 @@ export function Settings({ className }: { className?: string }) {
updateSettings({ ...localSettings, useOllama: checked });
};
+ const handleCliToggle = async (checked: boolean) => {
+ setIsTogglingCli(true);
+ try {
+ await invoke("use_cli", { useCli: checked });
+ setLocalSettings({ ...localSettings, useCli: checked });
+ updateSettings({ ...localSettings, useCli: checked });
+ } catch (error) {
+ console.error("Failed to toggle sidecar:", error);
+ setIsTogglingCliError("Failed to toggle sidecar: " + error);
+ } finally {
+ setIsTogglingCli(false);
+ }
+ };
+
React.useEffect(() => {
setLocalSettings(settings);
}, [settings]);
@@ -56,11 +84,11 @@ export function Settings({ className }: { className?: string }) {
Settings
</Button>
</DialogTrigger>
- <DialogContent className="sm:max-w-[600px]">
+ <DialogContent className="max-w-[80vw] w-full max-h-[100vh] h-full overflow-y-auto">
<DialogHeader>
- <DialogTitle>AI Settings</DialogTitle>
+ <DialogTitle>Settings</DialogTitle>
<DialogDescription>
- Choose your AI provider and enter necessary credentials.
+ Choose your AI provider, enter necessary credentials, and more.
</DialogDescription>
</DialogHeader>
<div className="mt-8 space-y-6">
@@ -68,24 +96,26 @@ export function Settings({ className }: { className?: string }) {
<CardHeader>
<CardTitle className="text-center">OpenAI</CardTitle>
</CardHeader>
- <CardContent>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="apiKey" className="text-right">
- API Key
- </Label>
- <Input
- id="apiKey"
- value={settings.openaiApiKey}
- onChange={handleApiKeyChange}
- className="col-span-3"
- placeholder="Enter your OpenAI API Key"
- />
+ <CardContent className="flex flex-col items-center">
+ <div className="w-full max-w-md">
+ <div className="flex items-center gap-4 mb-4">
+ <Label htmlFor="apiKey" className="min-w-[80px] text-right">
+ API Key
+ </Label>
+ <Input
+ id="apiKey"
+ value={settings.openaiApiKey}
+ onChange={handleApiKeyChange}
+ className="flex-grow"
+ placeholder="Enter your OpenAI API Key"
+ />
+ </div>
</div>
- <p className="mt-2 text-sm text-muted-foreground">
+ <p className="mt-2 text-sm text-muted-foreground text-center">
OpenAI&apos;s GPT models are currently the most reliable for
this application.
</p>
- <p className="mt-1 text-sm text-muted-foreground">
+ <p className="mt-1 text-sm text-muted-foreground text-center">
Don&apos;t have an API key? Get one from{" "}
<a
href="https://platform.openai.com/api-keys"
@@ -201,6 +231,59 @@ export function Settings({ className }: { className?: string }) {
</TooltipProvider>
</CardContent>
</Card>
+
+ <Separator />
+
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-center">CLI Option</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="flex items-center justify-center space-x-4">
+ <Switch
+ id="use-cli"
+ checked={localSettings.useCli}
+ onCheckedChange={handleCliToggle}
+ disabled={isTogglingCli}
+ />
+ <Label
+ htmlFor="use-cli"
+ className="flex items-center space-x-2"
+ >
+ Use screenpipe as a CLI
+ <Badge variant="destructive" className="ml-2">
+ Experimental
+ </Badge>
+ <Badge variant="outline" className="ml-1">
+ Expert Only
+ </Badge>
+ </Label>
+ </div>
+ <p className="text-sm text-center text-yellow-500 font-semibold">
+ Warning: This option is experimental and potentially dangerous.
+ Use at your own risk.
+ </p>
+ <p className="text-sm text-center text-muted-foreground">
+ By default, we run screenpipe in the background for you. Use
+ this option only if the status message keep showing red/error
+ even after restart.
+ </p>
+ {localSettings.useCli && (
+ <>
+ <p className="text-sm text-center text-muted-foreground">
+ Toggle on and copy and paste this in your terminal and press
+ enter:
+ </p>
+ <CodeBlock
+ language="bash"
+ value={`brew tap louis030195/screen-pipe https://github.com/louis030195/screen-pipe.git
+brew install screenpipe
+screenpipe`}
+ />
+ </>
+ )}
+ </CardContent>
+ </Card>
</div>
</DialogContent>
</Dialog>
diff --git a/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index ea4e129fa..6b01d8555 100644
--- a/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/examples/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -4,6 +4,7 @@ interface Settings {
openaiApiKey: string;
useOllama: boolean;
isLoading: boolean;
+ useCli: boolean;
}
export function useSettings() {
@@ -11,16 +12,19 @@ export function useSettings() {
openaiApiKey: "",
useOllama: false,
isLoading: true,
+ useCli: false,
});
useEffect(() => {
const loadSettings = () => {
const savedKey = localStorage.getItem("openaiApiKey") || "";
const savedUseOllama = localStorage.getItem("useOllama") === "true";
+ const savedUseCli = localStorage.getItem("useCli") === "true";
setSettings({
openaiApiKey: savedKey,
useOllama: savedUseOllama,
isLoading: false,
+ useCli: savedUseCli,
});
};
loadSettings();
@@ -31,6 +35,7 @@ export function useSettings() {
const updatedSettings = { ...prevSettings, ...newSettings };
localStorage.setItem("openaiApiKey", updatedSettings.openaiApiKey);
localStorage.setItem("useOllama", updatedSettings.useOllama.toString());
+ localStorage.setItem("useCli", updatedSettings.useCli.toString());
return updatedSettings;
});
};
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 27bca0db8..23d407995 100755
--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -17,14 +17,76 @@ use tauri::Manager;
use tauri::Wry;
use tauri_plugin_store::{with_store, StoreCollection};
+use std::sync::{Arc, Mutex};
+use tauri::State;
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_autostart::ManagerExt;
+use tauri_plugin_shell::process::CommandChild;
mod analytics;
use crate::analytics::start_analytics;
mod logs;
+struct SidecarState(Arc<Mutex<Option<CommandChild>>>);
+
+#[tauri::command]
+async fn use_cli(
+ state: State<'_, SidecarState>,
+ app: tauri::AppHandle,
+ use_cli: bool,
+) -> Result<(), String> {
+ if use_cli {
+ // Kill the sidecar if it's running
+ if let Some(child) = state.0.lock().unwrap().take() {
+ child.kill().map_err(|e| e.to_string())?;
+ }
+ // hard kill the sidecar on port 3030
+ let _ = tokio::process::Command::new("pkill")
+ .arg("-f")
+ .arg("screenpipe")
+ .output()
+ .await;
+ debug!("Killed sidecar thru cli");
+ } else {
+ // Check if sidecar is already running
+ let sidecar_running = state.0.lock().unwrap().is_some();
+ if !sidecar_running {
+ // Spawn the sidecar
+ let child = spawn_sidecar(&app)?;
+ // Update the state after spawning
+ state.0.lock().unwrap().replace(child);
+ }
+ debug!("Spawned sidecar thru cli");
+ }
+ Ok(())
+}
+
+fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
+ let sidecar = app.shell().sidecar("screenpipe").unwrap();
+ let (mut rx, child) = sidecar
+ .args(["--port", "3030", "--debug"])
+ .spawn()
+ .map_err(|e| e.to_string())?;
+
+ debug!("Spawned sidecar");
+ tauri::async_runtime::spawn(async move {
+ while let Some(event) = rx.recv().await {
+ match event {
+ tauri_plugin_shell::process::CommandEvent::Stdout(line) => {
+ debug!("{:?}", line);
+ }
+ tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
+ debug!("{:?}", line);
+ }
+ _ => {}
+ }
+ }
+ });
+
+ Ok(child)
+}
+
fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {
let default_path = home_dir()
.ok_or("Failed to get home directory")
@@ -44,6 +106,7 @@ async fn main() {
release: sentry::release_name!(),
..Default::default()
}));
+ let sidecar_state = SidecarState(Arc::new(Mutex::new(None)));
let app = tauri::Builder::default()
// .plugin(tauri_plugin_updater::Builder::new().build())
@@ -55,6 +118,8 @@ async fn main() {
MacosLauncher::LaunchAgent,
None,
))
+ .manage(sidecar_state)
+ .invoke_handler(tauri::generate_handler![use_cli])
.setup(move |app| {
// let cli = app.cli().matches().expect("Failed to get CLI matches");
@@ -138,31 +203,12 @@ async fn main() {
Ok(())
});
- let sidecar = app.shell().sidecar("screenpipe").unwrap();
- let (mut rx, _child) = sidecar
- .args(["--port", "3030", "--debug"]) // "--disable-audio"
- .spawn()
- .expect("Failed to spawn sidecar");
-
- // .args(if cfg!(target_os = "macos") { // ! hack?
- // vec!["--port", "3030", "--debug", "--data-dir", "/Applications/screenpipe.app/Contents/Resources"]
- // } else {
- // vec!["--port", "3030", "--debug"] // "--disable-audio"
- // })
-
- tauri::async_runtime::spawn(async move {
- while let Some(event) = rx.recv().await {
- match event {
- tauri_plugin_shell::process::CommandEvent::Stdout(line) => {
- debug!("{:?}", line);
- }
- tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
- debug!("{:?}", line);
- }
- _ => {}
- }
- }
- });
+ // Spawn the sidecar initially
+ let sidecar_state = app.state::<SidecarState>();
+ let app_handle = app.handle().clone();
+ let child = spawn_sidecar(&app_handle).expect("Failed to spawn sidecar");
+ let mut sidecar = sidecar_state.0.lock().unwrap();
+ *sidecar = Some(child);
Ok(())
})
@@ -170,7 +216,7 @@ async fn main() {
.expect("error while building tauri application");
// Run the app
- app.run(move |_app_handle, event| match event {
+ app.run(|_app_handle, event| match event {
tauri::RunEvent::Ready { .. } => {
debug!("Ready event");
// tauri::async_runtime::spawn(async move {
@@ -184,13 +230,22 @@ async fn main() {
// tx.send(()).unwrap();
// });
// TODO less dirty stop :D
- tauri::async_runtime::spawn(async move {
- let _ = tokio::process::Command::new("pkill")
- .arg("-f")
- .arg("screenpipe")
- .output()
- .await;
- });
+ // tauri::async_runtime::spawn(async move {
+ // let _ = tokio::process::Command::new("pkill")
+ // .arg("-f")
+ // .arg("screenpipe")
+ // .output()
+ // .await;
+ // });
+ // kill sidecar
+ // let sidecar_state = app.app_handle().state::<SidecarState>();
+ // let mut sidecar = sidecar_state.0.lock().unwrap();
+ // sidecar
+ // .take()
+ // .unwrap()
+ // .kill()
+ // .map_err(|e| e.to_string())
+ // .unwrap();
}
_ => {}
});
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.conf.json b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.conf.json
index 1cb3a6da5..17f52c35c 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.conf.json
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.conf.json
@@ -92,13 +92,13 @@
"security": {
"csp": {
"default-src": "'self' customprotocol: asset:",
- "connect-src": "ipc: http://ipc.localhost https://api.openai.com http://localhost:3030",
+ "connect-src": "ipc: http://ipc.localhost https://api.openai.com http://localhost:3030 http://127.0.0.1:11434 https://api.github.com https://github.com https://*.githubusercontent.com https://*.github.com",
"font-src": [
"https://fonts.gstatic.com",
"tauri://localhost"
],
"media-src": "'self' mediadevices:",
- "img-src": "'self' asset: http://asset.localhost blob: data:",
+ "img-src": "'self' asset: http://asset.localhost blob: data: https://*.githubusercontent.com https://*.github.com https://github.com https://*.s3.amazonaws.com",
"style-src": "'unsafe-inline' 'self' https://fonts.googleapis.com"
}
}