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: stream logs in UI + other debugging feats

Louis Beaumonta761a0af108d
diff --git a/screenpipe-app-tauri/components/log-viewer-v2.tsx b/screenpipe-app-tauri/components/log-viewer-v2.tsx
new file mode 100644
index 000000000..699976576
--- /dev/null
+++ b/screenpipe-app-tauri/components/log-viewer-v2.tsx
@@ -0,0 +1,54 @@
+import React, { useEffect, useState, useRef } from "react";
+import { listen } from "@tauri-apps/api/event";
+import { cn } from "@/lib/utils";
+import Convert from 'ansi-to-html';
+
+interface LogViewerProps {
+ className?: string;
+}
+
+const convert = new Convert({newline: true});
+
+const LogViewer: React.FC<LogViewerProps> = ({ className }) => {
+ const [logs, setLogs] = useState<string[]>([]);
+ const logContainerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const unlisten = listen<string>("sidecar_log", (event) => {
+ setLogs((prevLogs) => [...prevLogs, event.payload].slice(-100)); // Keep last 100 logs
+ });
+
+ return () => {
+ unlisten.then((f) => f()); // Cleanup listener when component unmounts
+ };
+ }, []);
+
+ useEffect(() => {
+ if (logContainerRef.current) {
+ logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
+ }
+ }, [logs]);
+
+ const htmlLogs = logs.map((log) => convert.toHtml(log));
+
+ return (
+ <div
+ ref={logContainerRef}
+ className={cn(
+ "h-64 overflow-y-auto bg-black p-2 font-mono text-sm text-white",
+ "whitespace-pre-wrap break-words",
+ className
+ )}
+ >
+ {htmlLogs.map((log, index) => (
+ <div
+ key={index}
+ dangerouslySetInnerHTML={{ __html: log }}
+ className="leading-5"
+ />
+ ))}
+ </div>
+ );
+};
+
+export default LogViewer;
diff --git a/screenpipe-app-tauri/components/screenpipe-status.tsx b/screenpipe-app-tauri/components/screenpipe-status.tsx
index 2a9d304ec..062933b57 100644
--- a/screenpipe-app-tauri/components/screenpipe-status.tsx
+++ b/screenpipe-app-tauri/components/screenpipe-status.tsx
@@ -26,9 +26,15 @@ import { Separator } from "./ui/separator";
import { Card, CardContent, CardFooter } from "./ui/card";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { DevSettings } from "./dev-dialog";
-import { Lock, Folder } from "lucide-react";
+import { Lock, Folder, FileText } from "lucide-react";
import { open } from "@tauri-apps/plugin-shell";
import { homeDir } from "@tauri-apps/api/path";
+import LogViewer from "./log-viewer-v2";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
const getDebuggingCommands = (os: string | null) => {
let cliInstructions = "";
@@ -218,10 +224,7 @@ const DevModeSettings = () => {
</Card>
<div className="relative">
- <Badge
- variant="secondary"
- className="text-xs absolute -top-3 left-1/2 transform -translate-x-1/2 z-10"
- >
+ <Badge className="text-xs absolute -top-3 left-1/2 transform -translate-x-1/2 z-10">
expert only
</Badge>
<Card className="p-4">
@@ -333,6 +336,8 @@ const HealthStatus = ({ className }: { className?: string }) => {
const { health } = useHealthCheck();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [isMac, setIsMac] = useState(false);
+ const { settings } = useSettings();
+ const [isLogOpen, setIsLogOpen] = useState(false);
useEffect(() => {
setIsMac(platform() === "macos");
@@ -379,26 +384,82 @@ const HealthStatus = ({ className }: { className?: string }) => {
}
};
- const getStatusColor = (status: string) => {
- switch (status) {
- case "Healthy":
- return "bg-green-500";
- case "Loading":
- return "bg-yellow-500";
- case "Unhealthy":
- case "Error":
- return "bg-red-500";
- default:
- return "bg-red-500";
+ const handleOpenLogFile = async () => {
+ try {
+ const homeDirPath = await homeDir();
+ const logPath =
+ platform() === "windows"
+ ? `${homeDirPath}\\.screenpipe\\screenpipe.log`
+ : `${homeDirPath}/.screenpipe/screenpipe.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,
+ });
}
};
+ const getStatusColor = (
+ status: string,
+ frameStatus: string,
+ audioStatus: string,
+ audioDisabled: boolean
+ ) => {
+ if (status === "loading") return "bg-yellow-500";
+
+ const isVisionOk = frameStatus === "ok" || frameStatus === "disabled";
+ const isAudioOk =
+ audioStatus === "ok" || audioStatus === "disabled" || audioDisabled;
+
+ if (isVisionOk && isAudioOk) return "bg-green-500";
+ return "bg-red-500";
+ };
+
if (!health) return null;
const formatTimestamp = (timestamp: string | null) => {
- return timestamp ? new Date(timestamp).toLocaleString() : "N/A";
+ return timestamp ? new Date(timestamp).toLocaleString() : "n/a";
+ };
+
+ const getStatusMessage = (
+ status: string,
+ frameStatus: string,
+ audioStatus: string,
+ audioDisabled: boolean
+ ) => {
+ if (status === "loading")
+ return "the application is still initializing. please wait...";
+
+ let unhealthySystems = [];
+ if (frameStatus !== "ok" && frameStatus !== "disabled")
+ unhealthySystems.push("vision");
+ if (!audioDisabled && audioStatus !== "ok" && audioStatus !== "disabled")
+ unhealthySystems.push("audio");
+
+ if (unhealthySystems.length === 0)
+ return "all systems are functioning normally";
+ return `some systems are not functioning properly: ${unhealthySystems.join(
+ ", "
+ )}`;
};
+ const statusColor = getStatusColor(
+ health.status,
+ health.frame_status,
+ health.audio_status,
+ settings.disableAudio
+ );
+ const statusMessage = getStatusMessage(
+ health.status,
+ health.frame_status,
+ health.audio_status,
+ settings.disableAudio
+ );
+
return (
<>
<Badge
@@ -408,12 +469,8 @@ const HealthStatus = ({ className }: { className?: string }) => {
>
status{" "}
<span
- className={`ml-1 w-2 h-2 rounded-full ${getStatusColor(
- health.status
- )} inline-block ${
- health.status === "Unhealthy" || health.status === "Error"
- ? "animate-pulse"
- : ""
+ className={`ml-1 w-2 h-2 rounded-full ${statusColor} inline-block ${
+ statusColor === "bg-red-500" ? "animate-pulse" : ""
}`}
/>
</Badge>
@@ -423,11 +480,10 @@ const HealthStatus = ({ className }: { className?: string }) => {
aria-describedby="status-dialog-description"
>
<DialogHeader className="flex flex-row items-center justify-between">
- <DialogTitle>{health.status.toLowerCase()} status</DialogTitle>
+ <DialogTitle>{health.status} status</DialogTitle>
<Button
variant="outline"
- size="sm"
onClick={handleOpenDataDir}
className="flex-shrink-0"
>
@@ -437,22 +493,23 @@ const HealthStatus = ({ className }: { className?: string }) => {
</DialogHeader>
<div className="flex-grow overflow-auto">
<p className="text-sm mb-2">
- {health.message.toLowerCase()}{" "}
- {health.status === "Loading" && (
+ {statusMessage}
+ {health.status === "loading" && (
<span className="ml-1 text-xs">(up to 3m)</span>
)}
</p>
+ <p className="text-xs mb-1">frame: {health.frame_status}</p>
<p className="text-xs mb-1">
- frame: {health.frame_status.toLowerCase()}
- </p>
- <p className="text-xs mb-1">
- audio: {health.audio_status.toLowerCase()}
+ audio: {settings.disableAudio ? "disabled" : health.audio_status}
</p>
<p className="text-xs mb-1">
last frame: {formatTimestamp(health.last_frame_timestamp)}
</p>
<p className="text-xs mb-1">
- last audio: {formatTimestamp(health.last_audio_timestamp)}
+ last audio:{" "}
+ {settings.disableAudio
+ ? "n/a"
+ : formatTimestamp(health.last_audio_timestamp)}
</p>
<div className="text-xs mt-2 relative">
<p className="font-bold mb-1">troubleshooting instructions:</p>
@@ -470,7 +527,6 @@ const HealthStatus = ({ className }: { className?: string }) => {
<TooltipTrigger asChild>
<Button
variant="outline"
- size="sm"
onClick={handleResetScreenPermissions}
className="flex-shrink-0"
>
@@ -488,6 +544,39 @@ const HealthStatus = ({ className }: { className?: string }) => {
</div>
<Separator className="my-4" />
<DevModeSettings />
+
+ <Collapsible
+ open={isLogOpen}
+ onOpenChange={setIsLogOpen}
+ className="w-full mt-4"
+ >
+ <div className="flex items-center justify-between w-full">
+ <CollapsibleTrigger className="flex items-center justify-between p-2 flex-grow border-b border-gray-200">
+ 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>
+ </div>
+ <CollapsibleContent>
+ <LogViewer className="mt-2" />
+ </CollapsibleContent>
+ </Collapsible>
</div>
</DialogContent>
</Dialog>
diff --git a/screenpipe-app-tauri/components/ui/collapsible.tsx b/screenpipe-app-tauri/components/ui/collapsible.tsx
new file mode 100644
index 000000000..9fa48946a
--- /dev/null
+++ b/screenpipe-app-tauri/components/ui/collapsible.tsx
@@ -0,0 +1,11 @@
+"use client"
+
+import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
+
+const Collapsible = CollapsiblePrimitive.Root
+
+const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
+
+const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
+
+export { Collapsible, CollapsibleTrigger, CollapsibleContent }
diff --git a/screenpipe-app-tauri/lib/utils.ts b/screenpipe-app-tauri/lib/utils.ts
index d084ccade..541e0ee36 100644
--- a/screenpipe-app-tauri/lib/utils.ts
+++ b/screenpipe-app-tauri/lib/utils.ts
@@ -1,6 +1,10 @@
-import { type ClassValue, clsx } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { type ClassValue, clsx } from "clsx";
+import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
+ return twMerge(clsx(inputs));
+}
+// Add this function to your existing utils.ts file
+export function stripAnsiCodes(str: string): string {
+ return str.replace(/\x1B\[[0-9;]*[JKmsu]/g, "");
}
diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.json
index 566d0c876..8dd89cae4 100644
--- a/screenpipe-app-tauri/package.json
+++ b/screenpipe-app-tauri/package.json
@@ -15,6 +15,7 @@
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-checkbox": "^1.1.1",
+ "@radix-ui/react-collapsible": "^1.1.0",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-icons": "^1.3.0",
@@ -42,6 +43,7 @@
"@tauri-apps/plugin-store": "2.0.0-beta.7",
"@tauri-apps/plugin-updater": "2.0.0-beta.7",
"ai": "^3.3",
+ "ansi-to-html": "^0.7.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "1.0.0",
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 1184488f2..357fd6617 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.2.47"
+version = "0.2.48"
description = ""
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
index 75f3b63fa..3dcd42bf2 100644
--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs
+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
@@ -11,7 +11,7 @@ use tauri_plugin_store::{with_store, StoreCollection};
use tokio::sync::Mutex;
use tokio::time::sleep;
use tracing::{debug, error, info};
-
+use tauri::Emitter;
#[tauri::command]
pub async fn kill_all_sreenpipes(
state: State<'_, SidecarState>,
@@ -298,18 +298,23 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
return Err(e.to_string());
}
- #[allow(unused_mut, unused_variables)]
let (mut rx, child) = result.unwrap();
+ let app_handle = app.app_handle().clone();
tauri::async_runtime::spawn(async move {
- #[allow(unused_variables)]
- let mut i = 0;
while let Some(event) = rx.recv().await {
- if let CommandEvent::Stdout(line) = event {
- print!("{}", String::from_utf8(line).unwrap());
- i += 1;
- } else if let CommandEvent::Stderr(line) = event {
- error!("Sidecar stderr: {}", String::from_utf8(line).unwrap());
+ match event {
+ CommandEvent::Stdout(line) => {
+ let log_line = String::from_utf8(line).unwrap();
+ print!("{}", log_line);
+ app_handle.emit("sidecar_log", log_line).unwrap();
+ }
+ CommandEvent::Stderr(line) => {
+ let log_line = String::from_utf8(line).unwrap();
+ error!("Sidecar stderr: {}", log_line);
+ app_handle.emit("sidecar_log", format!("ERROR: {}", log_line)).unwrap();
+ }
+ _ => {}
}
}
});
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index c7f1f6b5a..60af653e0 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -360,6 +360,8 @@ async fn main() -> anyhow::Result<()> {
audio_devices_control_server,
local_data_dir_clone_2,
pipe_manager.clone(),
+ cli.disable_vision,
+ cli.disable_audio,
);
let mut pipe_futures = FuturesUnordered::new();
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 7388219bf..8e4bd582b 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -45,6 +45,8 @@ pub struct AppState {
pub app_start_time: DateTime<Utc>,
pub screenpipe_dir: PathBuf,
pub pipe_manager: Arc<PipeManager>,
+ pub vision_disabled: bool,
+ pub audio_disabled: bool,
}
// Update the SearchQuery struct
@@ -467,12 +469,12 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
let (last_frame, last_audio) = match state.db.get_latest_timestamps().await {
Ok((frame, audio)) => (frame, audio),
Err(e) => {
- error!("Failed to get latest timestamps: {}", e);
+ error!("failed to get latest timestamps: {}", e);
(None, None)
}
};
- debug!("Last frame timestamp: {:?}", last_frame);
- debug!("Last audio timestamp: {:?}", last_audio);
+ debug!("last frame timestamp: {:?}", last_frame);
+ debug!("last audio timestamp: {:?}", last_audio);
let now = Utc::now();
let threshold = Duration::from_secs(60);
@@ -483,55 +485,73 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
if time_since_start < chrono::Duration::from_std(loading_threshold).unwrap() {
return JsonResponse(HealthCheckResponse {
- status: "Loading".to_string(),
+ status: "loading".to_string(),
last_frame_timestamp: last_frame,
last_audio_timestamp: last_audio,
- frame_status: "Loading".to_string(),
- audio_status: "Loading".to_string(),
- message: "The application is still initializing. Please wait...".to_string(),
+ frame_status: "loading".to_string(),
+ audio_status: "loading".to_string(),
+ message: "the application is still initializing. please wait...".to_string(),
verbose_instructions: None,
});
}
- let frame_status = match last_frame {
- Some(timestamp)
- if now.signed_duration_since(timestamp)
- < chrono::Duration::from_std(threshold).unwrap() =>
- {
- "OK"
+ let frame_status = if state.vision_disabled {
+ "disabled"
+ } else {
+ match last_frame {
+ Some(timestamp)
+ if now.signed_duration_since(timestamp)
+ < chrono::Duration::from_std(threshold).unwrap() =>
+ {
+ "ok"
+ }
+ Some(_) => "stale",
+ None => "no data",
}
- Some(_) => "Stale",
- None => "No data",
};
- let audio_status = match last_audio {
- Some(timestamp)
- if now.signed_duration_since(timestamp)
- < chrono::Duration::from_std(threshold).unwrap() =>
- {
- "OK"
+ let audio_status = if state.audio_disabled {
+ "disabled"
+ } else {
+ match last_audio {
+ Some(timestamp)
+ if now.signed_duration_since(timestamp)
+ < chrono::Duration::from_std(threshold).unwrap() =>
+ {
+ "ok"
+ }
+ Some(_) => "stale",
+ None => "no data",
}
- Some(_) => "Stale",
- None => "No data",
};
- let (overall_status, message, verbose_instructions) = if frame_status == "OK"
- && audio_status == "OK"
+ let (overall_status, message, verbose_instructions) = if (frame_status == "ok"
+ || frame_status == "disabled")
+ && (audio_status == "ok" || audio_status == "disabled")
{
(
- "Healthy",
- "All systems are functioning normally.".to_string(),
+ "healthy",
+ "all systems are functioning normally.".to_string(),
None,
)
} else {
+ let mut unhealthy_systems = Vec::new();
+ if frame_status != "ok" && frame_status != "disabled" {
+ unhealthy_systems.push("vision");
+ }
+ if audio_status != "ok" && audio_status != "disabled" {
+ unhealthy_systems.push("audio");
+ }
+
(
- "Unhealthy",
- format!("Some systems are not functioning properly. Frame status: {}, Audio status: {}", frame_status, audio_status),
- Some("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 audio/screen recording permissions.\n\
- 3. If the problem persists, please contact support with the details of this health check at [email protected].\n\
- 4. Last, here are some FAQ to help you troubleshoot: https://github.com/mediar-ai/screenpipe/blob/main/content/docs/NOTES.md".to_string())
+ "unhealthy",
+ format!("some systems are not functioning properly: {}. frame status: {}, audio status: {}",
+ unhealthy_systems.join(", "), frame_status, audio_status),
+ Some("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 audio/screen recording permissions.\n\
+ 3. if the problem persists, please contact support with the details of this health check at [email protected].\n\
+ 4. last, here are some faq to help you troubleshoot: https://github.com/mediar-ai/screenpipe/blob/main/content/docs/notes.md".to_string())
)
};
@@ -688,6 +708,8 @@ pub struct Server {
audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
+ vision_disabled: bool,
+ audio_disabled: bool,
}
impl Server {
@@ -698,6 +720,8 @@ impl Server {
audio_devices_control: Arc<SegQueue<(AudioDevice, DeviceControl)>>,
screenpipe_dir: PathBuf,
pipe_manager: Arc<PipeManager>,
+ vision_disabled: bool,
+ audio_disabled: bool,
) -> Self {
Server {
db,
@@ -706,6 +730,8 @@ impl Server {
audio_devices_control,
screenpipe_dir,
pipe_manager,
+ vision_disabled,
+ audio_disabled,
}
}
@@ -717,7 +743,6 @@ impl Server {
where
F: Fn(&axum::http::Request<axum::body::Body>) + Clone + Send + Sync + 'static,
{
- // TODO could init w audio devices
let app_state = Arc::new(AppState {
db: self.db,
vision_control: self.vision_control,
@@ -726,14 +751,14 @@ impl Server {
app_start_time: Utc::now(),
screenpipe_dir: self.screenpipe_dir.clone(),
pipe_manager: self.pipe_manager,
+ vision_disabled: self.vision_disabled,
+ audio_disabled: self.audio_disabled,
});
- // https://github.com/tokio-rs/console
let app = create_router()
.layer(ApiPluginLayer::new(api_plugin))
.layer(CorsLayer::permissive())
.layer(
- // https://github.com/tokio-rs/axum/blob/main/examples/tracing-aka-logging/src/main.rs
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().include_headers(true)),
)
@@ -784,7 +809,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/pipes/info/:pipe_id", get(get_pipe_info_handler))
.route("/pipes/list", get(list_pipes_handler))
.route("/pipes/download", post(download_pipe_handler))
- .route("/pipes/enable", post(run_pipe_handler)) // TODO ?
+ .route("/pipes/enable", post(run_pipe_handler))
.route("/pipes/disable", post(stop_pipe_handler))
.route("/pipes/update", post(update_pipe_config_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))