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: improve store pipes ux (#1428)

shaik-zeeshan97868ed3bb83
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index e1c244983..857f54de4 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -7,9 +7,9 @@ import { toast } from "@/components/ui/use-toast";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { Command } from "@tauri-apps/plugin-shell";
import {
- PipeApi,
- PipeDownloadError,
- PurchaseHistoryItem,
+ PipeApi,
+ PipeDownloadError,
+ PurchaseHistoryItem,
} from "@/lib/api/store";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { listen } from "@tauri-apps/api/event";
@@ -25,1104 +25,1092 @@ import { LoginDialog, useLoginCheck } from "./login-dialog";
import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
import { useStatusDialog } from "@/lib/hooks/use-status-dialog";
import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
} from "@/components/ui/tooltip";
import localforage from "localforage";
const corePipes: string[] = ["data-table", "search"];
export const PipeStore: React.FC = () => {
- const { health } = useHealthCheck();
- const [selectedPipe, setSelectedPipe] = useState<PipeWithStatus | null>(null);
- const { settings, loadUser } = useSettings();
- const [pipes, setPipes] = useState<PipeWithStatus[]>([]);
- const [installedPipes, setInstalledPipes] = useState<InstalledPipe[]>([]);
- const [searchQuery, setSearchQuery] = useState("");
- const [showInstalledOnly, setShowInstalledOnly] = useState(false);
- const [purchaseHistory, setPurchaseHistory] = useState<PurchaseHistoryItem[]>(
- [],
- );
- const { showLoginDialog, setShowLoginDialog, checkLogin } = useLoginCheck();
- const { open: openStatusDialog } = useStatusDialog();
- const [loadingPurchases, setLoadingPurchases] = useState<Set<string>>(
- new Set(),
- );
- const [loadingInstalls, setLoadingInstalls] = useState<Set<string>>(
- new Set(),
- );
-
- const filteredPipes = pipes
- .filter(
- (pipe) =>
- pipe.id.toLowerCase().includes(searchQuery.toLowerCase()) &&
- (!showInstalledOnly || pipe.is_installed) &&
- !pipe.is_installing,
- )
- .sort((a, b) => Number(b.is_paid) - Number(a.is_paid));
-
- // Add debounced search tracking
- useEffect(() => {
- const timeoutId = setTimeout(() => {
- if (searchQuery) {
- posthog.capture("search_pipes", {
- query: searchQuery,
- results_count: filteredPipes.length,
- });
- }
- }, 1000); // Debounce for 1 second
-
- return () => clearTimeout(timeoutId);
- }, [searchQuery, filteredPipes.length]);
-
- useEffect(() => {
- const unsubscribePromise = listen("update-all-pipes", async () => {
- // not sure this is a good idea ... basically pipes will break in the hand of users when update will happen
- if (!checkLogin(settings.user, false)) return;
-
- for (const pipe of pipes) {
- // Then download the new version
- await handleUpdatePipe(pipe);
- }
-
- // Refresh the pipe list
- await fetchInstalledPipes();
- });
-
- return () => {
- unsubscribePromise.then((unsubscribe) => unsubscribe());
- };
- }, []);
-
- const fetchStorePlugins = async () => {
- try {
- const pipeApi = await PipeApi.create(settings.user?.token!);
- const plugins = await pipeApi.listStorePlugins();
-
- // Create PipeWithStatus objects for store plugins
- const storePluginsWithStatus = await Promise.all(
- plugins.map(async (plugin) => {
- const installedPipe = installedPipes.find(
- (p) => p.config?.id === plugin.id,
- );
-
- return {
- ...plugin,
- is_installed: !!installedPipe,
- installed_config: installedPipe?.config,
- has_purchased: purchaseHistory.some(
- (p) => p.plugin_id === plugin.id,
- ),
- is_core_pipe: corePipes.includes(plugin.name),
- is_enabled: installedPipe?.config?.enabled ?? false,
- has_update: false,
- };
- }),
- );
-
- const customPipes = installedPipes
- .filter((p) => !plugins.some((plugin) => plugin.id === p.config?.id))
- .map((p) => {
- const pluginName = p.config?.source?.split("/").pop();
- const is_local = p.id.endsWith("_local");
- return {
- id: p.id || "",
- name: pluginName || "",
- description: p.desc,
- version: p.config?.version || "0.0.0",
- is_paid: false,
- price: 0,
- status: "active",
- created_at: new Date().toISOString(),
- developer_accounts: { developer_name: "You" },
- plugin_analytics: { downloads_count: 0 },
- is_installed: true,
- installed_config: p.config,
- has_purchased: true,
- is_core_pipe: false,
- is_enabled: p.config?.enabled || false,
- source_code: p.config?.source || "",
- is_local,
- };
- });
-
- setPipes([...storePluginsWithStatus, ...customPipes]);
- } catch (error) {
- console.warn("Failed to fetch store plugins:", error);
- }
- };
-
- const fetchPurchaseHistory = async () => {
- if (!settings.user?.token) return;
- const pipeApi = await PipeApi.create(settings.user!.token!);
- const purchaseHistory = await pipeApi.getUserPurchaseHistory();
- setPurchaseHistory(purchaseHistory);
- };
-
- const handlePurchasePipe = async (
- pipe: PipeWithStatus,
- onComplete?: () => void,
- ) => {
- try {
- if (!checkLogin(settings.user)) return;
-
- setLoadingPurchases((prev) => new Set(prev).add(pipe.id));
-
- const pipeApi = await PipeApi.create(settings.user!.token!);
- const response = await pipeApi.purchasePipe(pipe.id);
-
- if (response.data.payment_successful) {
- await handleInstallPipe(pipe);
- toast({
- title: "purchase & install successful",
- description: "payment processed with saved card",
- });
- } else if (response.data.already_purchased) {
- await handleInstallPipe(pipe);
- toast({
- title: "pipe already purchased",
- description: "installing pipe...",
- });
- } else if (response.data.used_credits) {
- await handleInstallPipe(pipe);
- toast({
- title: "purchase & install successful",
- description: "your pipe has been purchased and installed",
- });
- } else if (response.data.checkout_url) {
- openUrl(response.data.checkout_url);
- toast({
- title: "redirecting to checkout",
- description: "you'll be able to install the pipe after purchase",
- });
- }
- onComplete?.();
- } catch (error) {
- console.error("error purchasing pipe:", error);
- toast({
- title: "error purchasing pipe",
- description: "please try again or check the logs",
- variant: "destructive",
- });
- } finally {
- setLoadingPurchases((prev) => {
- const next = new Set(prev);
- next.delete(pipe.id);
- return next;
- });
- }
- };
-
- const handleInstallSideload = async (url: string) => {
- posthog.capture("add_own_pipe", {
- newRepoUrl: url,
- });
- try {
- const t = toast({
- title: "adding custom pipe",
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">starting installation...</p>
- </div>
- ),
- duration: 100000,
- });
- let value = 0;
-
- const progressInterval = setInterval(() => {
- value += 3;
- t.update({
- id: t.id,
- title: "adding custom pipe",
- description: (
- <div className="space-y-2">
- <Progress value={value} className="h-1" />
- <p className="text-xs">installing dependencies...</p>
- </div>
- ),
- duration: 100000,
- });
- }, 500);
-
- const response = await fetch("http://localhost:3030/pipes/download", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ url: url }),
- });
-
- const data = await response.json();
-
- clearInterval(progressInterval);
-
- if (!data.success) {
- throw new Error(data.error || "Failed to download pipe");
- }
-
- t.update({
- id: t.id,
- title: "pipe added",
- description: (
- <div className="space-y-2">
- <Progress value={100} className="h-1" />
- <p className="text-xs">completed successfully</p>
- </div>
- ),
- duration: 2000,
- });
-
- await fetchInstalledPipes();
-
- t.dismiss();
- } catch (error) {
- console.error("failed to add custom pipe:", error);
- toast({
- title: "error adding custom pipe",
- description: "please check the url and try again.",
- variant: "destructive",
- });
- }
- };
-
- const handleInstallPipe = async (
- pipe: PipeWithStatus,
- onComplete?: () => void,
- ) => {
- try {
- if (!checkLogin(settings.user)) return;
-
- // Keep the pipe in its current position by updating its status
- setPipes((prevPipes) =>
- prevPipes.map((p) =>
- p.id === pipe.id ? { ...p, is_installing: true } : p,
- ),
- );
-
- setLoadingInstalls((prev) => new Set(prev).add(pipe.id));
-
- const t = toast({
- title: "downloading pipe",
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">downloading from server...</p>
- </div>
- ),
- duration: 100000,
- });
-
- const pipeApi = await PipeApi.create(settings.user!.token!);
- const response = await pipeApi.downloadPipe(pipe.id);
-
- t.update({
- id: t.id,
- title: "installing pipe",
- description: (
- <div className="space-y-2">
- <Progress value={50} className="h-1" />
- <p className="text-xs">installing dependencies...</p>
- </div>
- ),
- duration: 100000,
- });
-
- const downloadResponse = await fetch(
- "http://localhost:3030/pipes/download-private",
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- pipe_name: pipe.name,
- pipe_id: pipe.id,
- url: response.download_url,
- }),
- },
- );
-
- const data = await downloadResponse.json();
- if (!data.success) {
- throw new Error(data.error || "Failed to download pipe");
- }
-
- await fetchInstalledPipes();
-
- t.update({
- id: t.id,
- title: "pipe installed",
- description: (
- <div className="space-y-2">
- <Progress value={100} className="h-1" />
- <p className="text-xs">completed successfully</p>
- </div>
- ),
- duration: 2000,
- });
-
- // Update the pipe's status after successful installation
- setPipes((prevPipes) =>
- prevPipes.map((p) =>
- p.id === pipe.id
- ? { ...p, is_installed: true, is_installing: false }
- : p,
- ),
- );
-
- onComplete?.();
- t.dismiss();
- } catch (error) {
- // Reset the pipe's status on error
- setPipes((prevPipes) =>
- prevPipes.map((p) =>
- p.id === pipe.id ? { ...p, is_installing: false } : p,
- ),
- );
- if ((error as Error).cause === PipeDownloadError.PURCHASE_REQUIRED) {
- return toast({
- title: "paid pipe",
- description:
- "this pipe requires purchase. please visit screenpi.pe to buy credits.",
- variant: "destructive",
- });
- }
- toast({
- title: "error installing pipe",
- description: (error as Error).message,
- variant: "destructive",
- });
- } finally {
- setLoadingInstalls((prev) => {
- const next = new Set(prev);
- next.delete(pipe.id);
- return next;
- });
- }
- };
-
- const fetchInstalledPipes = async () => {
- if (!health || health?.status === "error") return;
- try {
- const response = await fetch("http://localhost:3030/pipes/list");
- const data = (await response.json()) as {
- data: InstalledPipe[];
- success: boolean;
- };
-
- if (!data.success) throw new Error("Failed to fetch installed pipes");
-
- setInstalledPipes(data.data);
- return data.data;
- } catch (error) {
- console.error("Error fetching installed pipes:", error);
- toast({
- title: "error fetching installed pipes",
- description: "please try again or check the logs",
- variant: "destructive",
- });
- }
- };
-
- const handleResetAllPipes = async () => {
- try {
- const t = toast({
- title: "resetting pipes",
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">deleting all pipes...</p>
- </div>
- ),
- duration: 100000,
- });
-
- const response = await fetch(`http://localhost:3030/pipes/purge`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
- if (!response.ok) {
- toast({
- title: "failed to purge pipes",
- description: "failed to purge pipes, please try again",
- variant: "destructive",
- });
- return;
- }
- await fetchInstalledPipes();
-
- t.update({
- id: t.id,
- title: "pipes reset",
- description: (
- <div className="space-y-2">
- <Progress value={100} className="h-1" />
- <p className="text-xs">all pipes have been deleted</p>
- </div>
- ),
- duration: 2000,
- });
- } catch (error) {
- console.error("failed to reset pipes:", error);
- toast({
- title: "error resetting pipes",
- description: "please try again or check the logs",
- variant: "destructive",
- });
- }
- };
-
- const handleUpdateAllPipes = async (delayToast: boolean = false) => {
- try {
- if (!checkLogin(settings.user)) return;
-
- let t;
- if (!delayToast) {
- t = toast({
- title: "checking for updates",
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">checking installed pipes...</p>
- </div>
- ),
- duration: 100000,
- });
- }
-
- // Filter installed pipes that have updates available
- const pipesToUpdate = pipes.filter(
- (pipe) => pipe.is_installed && pipe.has_update,
- );
-
- if (pipesToUpdate.length === 0) {
- if (t) {
- t.update({
- id: t.id,
- title: "no updates available",
- description: "all pipes are up to date",
- duration: 2000,
- });
- }
- return;
- }
-
- // Update progress message
- if (t) {
- t.update({
- id: t.id,
- title: `updating ${pipesToUpdate.length} pipes`,
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">starting updates...</p>
- </div>
- ),
- duration: 100000,
- });
- } else {
- t = toast({
- title: `updating ${pipesToUpdate.length} pipes`,
- description: (
- <div className="space-y-2">
- <Progress value={0} className="h-1" />
- <p className="text-xs">starting updates...</p>
- </div>
- ),
- duration: 100000,
- });
- }
-
- // Update each pipe sequentially
- for (let i = 0; i < pipesToUpdate.length; i++) {
- const pipe = pipesToUpdate[i];
- const progress = Math.round((i / pipesToUpdate.length) * 100);
-
- t.update({
- id: t.id,
- title: `updating pipes (${i + 1}/${pipesToUpdate.length})`,
- description: (
- <div className="space-y-2">
- <Progress value={progress} className="h-1" />
- <p className="text-xs">updating {pipe.name}...</p>
- </div>
- ),
- duration: 100000,
- });
-
- await handleUpdatePipe(pipe);
- }
-
- t.update({
- id: t.id,
- title: "all pipes updated",
- description: (
- <div className="space-y-2">
- <Progress value={100} className="h-1" />
- <p className="text-xs">completed successfully</p>
- </div>
- ),
- duration: 2000,
- });
- } catch (error) {
- console.error("failed to update all pipes:", error);
- toast({
- title: "error updating pipes",
- description: "please try again or check the logs",
- variant: "destructive",
- });
- }
- };
-
- const handleTogglePipe = async (
- pipe: PipeWithStatus,
- onComplete: () => void,
- ) => {
- try {
- const t = toast({
- title: "loading pipe",
- description: "please wait...",
- action: (
- <div className="flex items-center">
- <Loader2 className="h-4 w-4 animate-spin" />
- </div>
- ),
- duration: 4000,
- });
-
- const endpoint = pipe.installed_config?.enabled ? "disable" : "enable";
- console.log("toggel", pipe, endpoint);
-
- const id = pipe.is_local ? pipe.id : pipe.name;
- const response = await fetch(`http://localhost:3030/pipes/${endpoint}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ pipe_id: id }),
- });
-
- const data = await response.json();
- if (!data.success) {
- throw new Error(data.error);
- }
-
- toast({
- title: `pipe ${endpoint}d`,
- });
- const installedPipes = await fetchInstalledPipes();
- console.log("installed Pipes", installedPipes);
- const pp = installedPipes?.find((p) => p.config.id === pipe.id);
- const port = pp?.config.port;
-
- setSelectedPipe((prev) => {
- if (!prev) return prev;
- return {
- ...prev,
- installed_config: {
- port,
- ...prev.installed_config!,
- enabled: !pipe.installed_config?.enabled,
- buildStatus: "in_progress",
- },
- };
- });
- onComplete();
- } catch (error) {
- console.error(
- `Failed to ${
- pipe.installed_config?.enabled ? "disable" : "enable"
- } pipe:`,
- error,
- );
- toast({
- title: "error toggling pipe",
- description: "please try again or check the logs for more information.",
- variant: "destructive",
- });
- }
- };
-
- const handleLoadFromLocalFolder = async (
- setNewRepoUrl: (url: string) => void,
- ) => {
- try {
- const selectedFolder = await open({
- directory: true,
- multiple: false,
- });
-
- if (selectedFolder) {
- console.log("loading from local folder", selectedFolder);
- // set in the bar
- setNewRepoUrl(selectedFolder);
- }
- } catch (error) {
- console.error("failed to load pipe from local folder:", error);
- toast({
- title: "error loading pipe",
- description: "please try again or check the logs for more information.",
- variant: "destructive",
- });
- }
- };
-
- const handleConfigSave = async (config: Record<string, any>) => {
- if (selectedPipe) {
- try {
- const id = selectedPipe.is_local ? selectedPipe.id : selectedPipe.name;
- const response = await fetch("http://localhost:3030/pipes/update", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- pipe_id: id,
- config: config,
- }),
- });
-
- const data = await response.json();
- if (!data.success) {
- throw new Error(data.error || "Failed to update pipe configuration");
- }
-
- toast({
- title: "Configuration saved",
- description: "The pipe configuration has been updated.",
- });
-
- setSelectedPipe({
- ...selectedPipe,
- installed_config: {
- ...selectedPipe.installed_config!,
- ...config,
- },
- });
- } catch (error) {
- console.error("Failed to save config:", error);
- toast({
- title: "error saving configuration",
- description:
- "please try again or check the logs for more information.",
- variant: "destructive",
- });
- }
- }
- };
- const handleDeletePipe = async (pipe: PipeWithStatus) => {
- try {
- toast({
- title: "deleting pipe",
- description: "please wait...",
- });
- setSelectedPipe(null);
-
- const id = pipe.is_local ? pipe.id : pipe.name;
- const response = await fetch("http://localhost:3030/pipes/delete", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ pipe_id: id }),
- });
-
- const data = await response.json();
- if (!data.success) {
- throw new Error(data.error);
- }
-
- // First unselect the pipe, then fetch the updated list
- await fetchInstalledPipes();
-
- toast({
- title: "pipe deleted",
- description: "the pipe has been successfully removed",
- });
-
- setSelectedPipe(null);
- } catch (error) {
- console.error("failed to delete pipe:", error);
- toast({
- title: "error deleting pipe",
- description: "please try again or check the logs for more information.",
- variant: "destructive",
- });
- }
- };
-
- const handleRefreshFromDisk = async (pipe: PipeWithStatus) => {
- try {
- toast({
- title: "refreshing pipe",
- description: "please wait...",
- });
-
- const response = await fetch(`http://localhost:3030/pipes/download`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ url: pipe.installed_config?.source }),
- });
- if (!response.ok) {
- throw new Error("failed to refresh pipe");
- }
-
- await fetchInstalledPipes();
- toast({
- title: "pipe refreshed",
- description: "the pipe has been successfully refreshed from disk.",
- });
- } catch (error) {
- console.error("failed to refresh pipe from disk:", error);
- toast({
- title: "error refreshing pipe",
- description: "please try again or check the logs for more information.",
- variant: "destructive",
- });
- } finally {
- setSelectedPipe(null);
- }
- };
-
- const handleUpdatePipe = async (pipe: PipeWithStatus) => {
- try {
- if (!checkLogin(settings.user)) return;
-
- const currentVersion = pipe.installed_config?.version!;
- const storeApi = await PipeApi.create(settings.user!.token!);
- const update = await storeApi.checkUpdate(pipe.id, currentVersion);
- if (!update.has_update) {
- toast({
- title: "no update available",
- description: "the pipe is already up to date",
- });
- return;
- }
-
- const t = toast({
- title: "updating pipe",
- description: (
- <div className="space-y-2">
- <Progress value={25} className="h-1" />
- <p className="text-xs">checking for updates...</p>
- </div>
- ),
- duration: 100000,
- });
-
- // Update progress for download start
- t.update({
- id: t.id,
- description: (
- <div className="space-y-2">
- <Progress value={50} className="h-1" />
- <p className="text-xs">downloading update...</p>
- </div>
- ),
- });
-
- const responseDownload = await storeApi.downloadPipe(pipe.id);
-
- // Update progress for installation
- t.update({
- id: t.id,
- description: (
- <div className="space-y-2">
- <Progress value={75} className="h-1" />
- <p className="text-xs">installing update...</p>
- </div>
- ),
- });
-
- const response = await fetch(
- `http://localhost:3030/pipes/update-version`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- pipe_id: pipe.name,
- source: responseDownload.download_url,
- }),
- },
- );
-
- const data = await response.json();
- if (!data.success) {
- throw new Error(data.error);
- }
-
- // Update progress for completion
- t.update({
- id: t.id,
- title: "pipe updated",
- description: (
- <div className="space-y-2">
- <Progress value={100} className="h-1" />
- <p className="text-xs">completed successfully</p>
- </div>
- ),
- duration: 2000,
- });
-
- await fetchInstalledPipes();
-
- t.dismiss();
- } catch (error) {
- console.error("failed to update pipe:", error);
- toast({
- title: "error updating pipe",
- description: "please try again or check the logs for more information.",
- variant: "destructive",
- });
- }
- };
-
- useEffect(() => {
- fetchStorePlugins();
- }, [installedPipes, purchaseHistory]);
-
- useEffect(() => {
- fetchPurchaseHistory();
- }, [settings.user.token]);
-
- useEffect(() => {
- fetchInstalledPipes();
- }, [health]);
-
- useEffect(() => {
- const interval = setInterval(() => {
- fetchInstalledPipes();
- }, 1000);
- return () => clearInterval(interval);
- }, []);
-
- useEffect(() => {
- const checkForUpdates = async () => {
- if(!settings.user.token){
- return;
- }
- // Get last check time from local storage
- const lastCheckTime = await localforage.getItem<number>('lastUpdateCheck');
- const now = Date.now();
-
- // Check if 5 minutes have passed since last check
- if (lastCheckTime && now - lastCheckTime < 5 * 60 * 1000) {
- return;
- }
-
- // Store current time as last check
- await localforage.setItem('lastUpdateCheck', now);
-
- const installedPipes = pipes.filter((pipe) => pipe.is_installed);
-
- const storeApi = await PipeApi.create(settings.user.token);
- for (const pipe of installedPipes) {
- const update = await storeApi.checkUpdate(pipe.id, pipe.installed_config?.version!);
- if (update.has_update) {
- await handleUpdatePipe(pipe);
- }
- }
- };
-
- // Run check immediately
- checkForUpdates();
-
- // Set up interval to check every 10 seconds actual check is done in the function
- const interval = setInterval(checkForUpdates, 10 * 1000);
-
- return () => clearInterval(interval);
- }, [settings.user.token]);
-
- useEffect(() => {
- const setupDeepLink = async () => {
- const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
- console.log("received deep link urls:", urls);
- for (const url of urls) {
- if (url.includes("purchase-successful")) {
- const urlObj = new URL(url);
- const pipeId = urlObj.searchParams.get("pipe_id");
-
- if (!pipeId) {
- toast({
- title: "purchase successful",
- description: "your purchase was successful",
- });
- return;
- }
-
- await new Promise((resolve) => setTimeout(resolve, 1000));
-
- // First update purchase history to reflect the new purchase
- await fetchPurchaseHistory();
-
- // Find the pipe in the store
- const purchasedPipe = pipes.find((pipe) => pipe.id === pipeId);
- if (!purchasedPipe) {
- toast({
- title: "error installing pipe",
- description: "could not find the purchased pipe",
- variant: "destructive",
- });
- return;
- }
-
- // Install the pipe
- await handleInstallPipe(purchasedPipe);
- }
- }
- });
- return unsubscribeDeepLink;
- };
-
- let deepLinkUnsubscribe: (() => void) | undefined;
-
- setupDeepLink().then((unsubscribe) => {
- deepLinkUnsubscribe = unsubscribe;
- });
- return () => {
- if (deepLinkUnsubscribe) deepLinkUnsubscribe();
- };
- }, [pipes]);
-
- if (health?.status === "error") {
- return (
- <div className="flex flex-col items-center justify-center h-screen p-4 space-y-4">
- <div className="text-center space-y-4">
- <h3 className="text-lg font-medium">screenpipe is not recording</h3>
- <p className="text-sm text-muted-foreground">
- please start the screenpipe service to browse and manage pipes
- </p>
- <Button
- variant="outline"
- onClick={openStatusDialog}
- className="gap-2"
- >
- <Power className="h-4 w-4" />
- check service status
- </Button>
- </div>
- </div>
- );
- }
-
- if (selectedPipe) {
- return (
- <PipeDetails
- pipe={selectedPipe}
- onClose={() => setSelectedPipe(null)}
- onToggle={handleTogglePipe}
- onConfigSave={handleConfigSave}
- onDelete={handleDeletePipe}
- onRefreshFromDisk={handleRefreshFromDisk}
- onUpdate={handleUpdatePipe}
- />
- );
- }
-
- return (
- <div className="overflow-hidden flex flex-col space-y-4 min-w-[800px]">
- <div className="flex flex-col flex-1 overflow-hidden space-y-4 p-4 min-w-[800px]">
- <div className="space-y-4 min-w-[800px]">
- <div className="flex flex-col gap-4 w-[50%]">
- <div className="flex-1 relative">
- <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
- <Input
- placeholder="search community pipes..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-9"
- autoCorrect="off"
- autoComplete="off"
- />
- </div>
- <div className="flex items-center gap-2">
- <span className="text-sm text-gray-600">show installed only</span>
- <Switch
- checked={showInstalledOnly}
- onCheckedChange={setShowInstalledOnly}
- />
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="icon"
- onClick={handleResetAllPipes}
- className="flex items-center gap-2"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>reset all pipes</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="icon"
- onClick={() => handleUpdateAllPipes()}
- className="flex items-center gap-2"
- disabled={
- !pipes.some(
- (pipe) => pipe.is_installed && pipe.has_update,
- )
- }
- >
- <RefreshCw className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>update all pipes</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- </div>
- </div>
-
- <div className="flex-1 overflow-y-auto">
- <div className="grid grid-cols-2 gap-4">
- {filteredPipes.map((pipe) => (
- <PipeCard
- key={pipe.id}
- pipe={pipe}
- setPipe={(updatedPipe) => {
- setPipes((prevPipes) => {
- return prevPipes.map((p) =>
- p.id === updatedPipe.id ? updatedPipe : p,
- );
- });
- }}
- onInstall={handleInstallPipe}
- onClick={setSelectedPipe}
- onPurchase={handlePurchasePipe}
- isLoadingPurchase={loadingPurchases.has(pipe.id)}
- isLoadingInstall={loadingInstalls.has(pipe.id)}
- onToggle={handleTogglePipe}
- />
- ))}
- </div>
- </div>
-
- <AddPipeForm
- onAddPipe={handleInstallSideload}
- isHealthy={health?.status !== "error"}
- onLoadFromLocalFolder={handleLoadFromLocalFolder}
- />
- </div>
- <LoginDialog open={showLoginDialog} onOpenChange={setShowLoginDialog} />
- </div>
- );
+ const { health } = useHealthCheck();
+ const [selectedPipe, setSelectedPipe] = useState<PipeWithStatus | null>(null);
+ const { settings, loadUser } = useSettings();
+ const [pipes, setPipes] = useState<PipeWithStatus[]>([]);
+ const [installedPipes, setInstalledPipes] = useState<InstalledPipe[]>([]);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [showInstalledOnly, setShowInstalledOnly] = useState(false);
+ const [purchaseHistory, setPurchaseHistory] = useState<PurchaseHistoryItem[]>(
+ [],
+ );
+ const { showLoginDialog, setShowLoginDialog, checkLogin } = useLoginCheck();
+ const { open: openStatusDialog } = useStatusDialog();
+ const [loadingPurchases, setLoadingPurchases] = useState<Set<string>>(
+ new Set(),
+ );
+ const [loadingInstalls, setLoadingInstalls] = useState<Set<string>>(
+ new Set(),
+ );
+
+ const filteredPipes = pipes
+ .filter(
+ (pipe) =>
+ pipe.id.toLowerCase().includes(searchQuery.toLowerCase()) &&
+ (!showInstalledOnly || pipe.is_installed) &&
+ !pipe.is_installing,
+ )
+ .sort((a, b) => Number(b.is_paid) - Number(a.is_paid));
+
+ // Add debounced search tracking
+ useEffect(() => {
+ const timeoutId = setTimeout(() => {
+ if (searchQuery) {
+ posthog.capture("search_pipes", {
+ query: searchQuery,
+ results_count: filteredPipes.length,
+ });
+ }
+ }, 1000); // Debounce for 1 second
+
+ return () => clearTimeout(timeoutId);
+ }, [searchQuery, filteredPipes.length]);
+
+ useEffect(() => {
+ const unsubscribePromise = listen("update-all-pipes", async () => {
+ // not sure this is a good idea ... basically pipes will break in the hand of users when update will happen
+ if (!checkLogin(settings.user, false)) return;
+
+ for (const pipe of pipes) {
+ // Then download the new version
+ await handleUpdatePipe(pipe);
+ }
+
+ // Refresh the pipe list
+ await fetchInstalledPipes();
+ });
+
+ return () => {
+ unsubscribePromise.then((unsubscribe) => unsubscribe());
+ };
+ }, []);
+
+ const fetchStorePlugins = async () => {
+ try {
+ const pipeApi = await PipeApi.create(settings.user?.token!);
+ const plugins = await pipeApi.listStorePlugins();
+
+ // Create PipeWithStatus objects for store plugins
+ const storePluginsWithStatus = await Promise.all(
+ plugins.map(async (plugin) => {
+ const installedPipe = installedPipes.find((p) => {
+ return p.id?.replace("._temp", "") === plugin.name;
+ });
+ return {
+ ...plugin,
+ is_installed: !!installedPipe,
+ installed_config: installedPipe?.config,
+ has_purchased: purchaseHistory.some(
+ (p) => p.plugin_id === plugin.id,
+ ),
+ is_core_pipe: corePipes.includes(plugin.name),
+ is_enabled: installedPipe?.config?.enabled ?? false,
+ has_update: false,
+ };
+ }),
+ );
+
+ const customPipes = installedPipes
+ .filter(
+ (p) =>
+ !plugins.find(
+ (plugin) => plugin.name === p.id?.replace("._temp", ""),
+ ),
+ )
+ .map((p) => {
+ const pluginName = p.config?.source?.split("/").pop();
+ const is_local = p.id.endsWith("_local");
+ return {
+ id: p.id || "",
+ name: pluginName || "",
+ description: p.desc,
+ version: p.config?.version || "0.0.0",
+ is_paid: false,
+ price: 0,
+ status: "active",
+ created_at: new Date().toISOString(),
+ developer_accounts: { developer_name: "You" },
+ plugin_analytics: { downloads_count: 0 },
+ is_installed: true,
+ installed_config: p.config,
+ has_purchased: true,
+ is_core_pipe: false,
+ is_enabled: p.config?.enabled || false,
+ source_code: p.config?.source || "",
+ is_local,
+ };
+ });
+
+ setPipes([...storePluginsWithStatus, ...customPipes]);
+ } catch (error) {
+ console.warn("Failed to fetch store plugins:", error);
+ }
+ };
+
+ const fetchPurchaseHistory = async () => {
+ if (!settings.user?.token) return;
+ const pipeApi = await PipeApi.create(settings.user!.token!);
+ const purchaseHistory = await pipeApi.getUserPurchaseHistory();
+ setPurchaseHistory(purchaseHistory);
+ };
+
+ const handlePurchasePipe = async (
+ pipe: PipeWithStatus,
+ onComplete?: () => void,
+ ) => {
+ try {
+ if (!checkLogin(settings.user)) return;
+
+ setLoadingPurchases((prev) => new Set(prev).add(pipe.id));
+
+ const pipeApi = await PipeApi.create(settings.user!.token!);
+ const response = await pipeApi.purchasePipe(pipe.id);
+
+ if (response.data.payment_successful) {
+ await handleInstallPipe(pipe);
+ toast({
+ title: "purchase & install successful",
+ description: "payment processed with saved card",
+ });
+ } else if (response.data.already_purchased) {
+ await handleInstallPipe(pipe);
+ toast({
+ title: "pipe already purchased",
+ description: "installing pipe...",
+ });
+ } else if (response.data.used_credits) {
+ await handleInstallPipe(pipe);
+ toast({
+ title: "purchase & install successful",
+ description: "your pipe has been purchased and installed",
+ });
+ } else if (response.data.checkout_url) {
+ openUrl(response.data.checkout_url);
+ toast({
+ title: "redirecting to checkout",
+ description: "you'll be able to install the pipe after purchase",
+ });
+ }
+ onComplete?.();
+ } catch (error) {
+ console.error("error purchasing pipe:", error);
+ toast({
+ title: "error purchasing pipe",
+ description: "please try again or check the logs",
+ variant: "destructive",
+ });
+ } finally {
+ setLoadingPurchases((prev) => {
+ const next = new Set(prev);
+ next.delete(pipe.id);
+ return next;
+ });
+ }
+ };
+
+ const handleInstallSideload = async (url: string) => {
+ posthog.capture("add_own_pipe", {
+ newRepoUrl: url,
+ });
+ try {
+ const t = toast({
+ title: "adding custom pipe",
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">starting installation...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+ let value = 0;
+
+ const progressInterval = setInterval(() => {
+ value += 3;
+ t.update({
+ id: t.id,
+ title: "adding custom pipe",
+ description: (
+ <div className="space-y-2">
+ <Progress value={value} className="h-1" />
+ <p className="text-xs">installing dependencies...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+ }, 500);
+
+ const response = await fetch("http://localhost:3030/pipes/download", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ url: url }),
+ });
+
+ const data = await response.json();
+
+ clearInterval(progressInterval);
+
+ if (!data.success) {
+ throw new Error(data.error || "Failed to download pipe");
+ }
+
+ t.update({
+ id: t.id,
+ title: "pipe added",
+ description: (
+ <div className="space-y-2">
+ <Progress value={100} className="h-1" />
+ <p className="text-xs">completed successfully</p>
+ </div>
+ ),
+ duration: 2000,
+ });
+
+ await fetchInstalledPipes();
+
+ t.dismiss();
+ } catch (error) {
+ console.error("failed to add custom pipe:", error);
+ toast({
+ title: "error adding custom pipe",
+ description: "please check the url and try again.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleInstallPipe = async (
+ pipe: PipeWithStatus,
+ onComplete?: () => void,
+ ) => {
+ try {
+ if (!checkLogin(settings.user)) return;
+
+ // Keep the pipe in its current position by updating its status
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id ? { ...p, is_installing: true } : p,
+ ),
+ );
+
+ setLoadingInstalls((prev) => new Set(prev).add(pipe.id));
+
+ const t = toast({
+ title: "creating pipe",
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">creating pipe...</p>
+ </div>
+ ),
+ duration: 10000,
+ });
+
+ const pipeApi = await PipeApi.create(settings.user!.token!);
+ const response = await pipeApi.downloadPipe(pipe.id);
+
+ const downloadResponse = await fetch(
+ "http://localhost:3030/pipes/download-private",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ pipe_name: pipe.name,
+ pipe_id: pipe.id,
+ url: response.download_url,
+ }),
+ },
+ );
+
+ const data = await downloadResponse.json();
+ if (!data.success) {
+ throw new Error(data.error || "Failed to download pipe");
+ }
+
+ await fetchInstalledPipes();
+
+ // Update the pipe's status after successful installation
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id
+ ? {
+ ...p,
+ is_installed: true,
+ is_installing: false,
+ }
+ : p,
+ ),
+ );
+
+ onComplete?.();
+ t.dismiss();
+ } catch (error) {
+ // Reset the pipe's status on error
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id ? { ...p, is_installing: false } : p,
+ ),
+ );
+ if ((error as Error).cause === PipeDownloadError.PURCHASE_REQUIRED) {
+ return toast({
+ title: "paid pipe",
+ description:
+ "this pipe requires purchase. please visit screenpi.pe to buy credits.",
+ variant: "destructive",
+ });
+ }
+ toast({
+ title: "error installing pipe",
+ description: (error as Error).message,
+ variant: "destructive",
+ });
+ } finally {
+ setLoadingInstalls((prev) => {
+ const next = new Set(prev);
+ next.delete(pipe.id);
+ return next;
+ });
+ }
+ };
+
+ const fetchInstalledPipes = async () => {
+ if (!health || health?.status === "error") return;
+ try {
+ const response = await fetch("http://localhost:3030/pipes/list");
+ const data = (await response.json()) as {
+ data: InstalledPipe[];
+ success: boolean;
+ };
+
+ if (!data.success) throw new Error("Failed to fetch installed pipes");
+
+ setInstalledPipes(data.data);
+ return data.data;
+ } catch (error) {
+ console.error("Error fetching installed pipes:", error);
+ toast({
+ title: "error fetching installed pipes",
+ description: "please try again or check the logs",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleResetAllPipes = async () => {
+ try {
+ const t = toast({
+ title: "resetting pipes",
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">deleting all pipes...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+
+ const response = await fetch(`http://localhost:3030/pipes/purge`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({}),
+ });
+ if (!response.ok) {
+ toast({
+ title: "failed to purge pipes",
+ description: "failed to purge pipes, please try again",
+ variant: "destructive",
+ });
+ return;
+ }
+ await fetchInstalledPipes();
+
+ t.update({
+ id: t.id,
+ title: "pipes reset",
+ description: (
+ <div className="space-y-2">
+ <Progress value={100} className="h-1" />
+ <p className="text-xs">all pipes have been deleted</p>
+ </div>
+ ),
+ duration: 2000,
+ });
+ } catch (error) {
+ console.error("failed to reset pipes:", error);
+ toast({
+ title: "error resetting pipes",
+ description: "please try again or check the logs",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleUpdateAllPipes = async (delayToast: boolean = false) => {
+ try {
+ if (!checkLogin(settings.user)) return;
+
+ let t;
+ if (!delayToast) {
+ t = toast({
+ title: "checking for updates",
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">checking installed pipes...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+ }
+
+ // Filter installed pipes that have updates available
+ const pipesToUpdate = pipes.filter(
+ (pipe) => pipe.is_installed && pipe.has_update,
+ );
+
+ if (pipesToUpdate.length === 0) {
+ if (t) {
+ t.update({
+ id: t.id,
+ title: "no updates available",
+ description: "all pipes are up to date",
+ duration: 2000,
+ });
+ }
+ return;
+ }
+
+ // Update progress message
+ if (t) {
+ t.update({
+ id: t.id,
+ title: `updating ${pipesToUpdate.length} pipes`,
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">starting updates...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+ } else {
+ t = toast({
+ title: `updating ${pipesToUpdate.length} pipes`,
+ description: (
+ <div className="space-y-2">
+ <Progress value={0} className="h-1" />
+ <p className="text-xs">starting updates...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+ }
+
+ // Update each pipe sequentially
+ for (let i = 0; i < pipesToUpdate.length; i++) {
+ const pipe = pipesToUpdate[i];
+ const progress = Math.round((i / pipesToUpdate.length) * 100);
+
+ t.update({
+ id: t.id,
+ title: `updating pipes (${i + 1}/${pipesToUpdate.length})`,
+ description: (
+ <div className="space-y-2">
+ <Progress value={progress} className="h-1" />
+ <p className="text-xs">updating {pipe.name}...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+
+ await handleUpdatePipe(pipe);
+ }
+
+ t.update({
+ id: t.id,
+ title: "all pipes updated",
+ description: (
+ <div className="space-y-2">
+ <Progress value={100} className="h-1" />
+ <p className="text-xs">completed successfully</p>
+ </div>
+ ),
+ duration: 2000,
+ });
+ } catch (error) {
+ console.error("failed to update all pipes:", error);
+ toast({
+ title: "error updating pipes",
+ description: "please try again or check the logs",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleTogglePipe = async (
+ pipe: PipeWithStatus,
+ onComplete: () => void,
+ ) => {
+ try {
+ const t = toast({
+ title: "loading pipe",
+ description: "please wait...",
+ action: (
+ <div className="flex items-center">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ ),
+ duration: 4000,
+ });
+
+ const endpoint = pipe.installed_config?.enabled ? "disable" : "enable";
+ console.log("toggel", pipe, endpoint);
+
+ const id = pipe.is_local ? pipe.id : pipe.name;
+ const response = await fetch(`http://localhost:3030/pipes/${endpoint}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ pipe_id: id }),
+ });
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(data.error);
+ }
+
+ toast({
+ title: `pipe ${endpoint}d`,
+ });
+ const installedPipes = await fetchInstalledPipes();
+ console.log("installed Pipes", installedPipes);
+ const pp = installedPipes?.find((p) => p.config.id === pipe.id);
+ const port = pp?.config.port;
+
+ setSelectedPipe((prev) => {
+ if (!prev) return prev;
+ return {
+ ...prev,
+ installed_config: {
+ port,
+ ...prev.installed_config!,
+ enabled: !pipe.installed_config?.enabled,
+ buildStatus: "in_progress",
+ },
+ };
+ });
+ onComplete();
+ } catch (error) {
+ console.error(
+ `Failed to ${
+ pipe.installed_config?.enabled ? "disable" : "enable"
+ } pipe:`,
+ error,
+ );
+ toast({
+ title: "error toggling pipe",
+ description: "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleLoadFromLocalFolder = async (
+ setNewRepoUrl: (url: string) => void,
+ ) => {
+ try {
+ const selectedFolder = await open({
+ directory: true,
+ multiple: false,
+ });
+
+ if (selectedFolder) {
+ console.log("loading from local folder", selectedFolder);
+ // set in the bar
+ setNewRepoUrl(selectedFolder);
+ }
+ } catch (error) {
+ console.error("failed to load pipe from local folder:", error);
+ toast({
+ title: "error loading pipe",
+ description: "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleConfigSave = async (config: Record<string, any>) => {
+ if (selectedPipe) {
+ try {
+ const id = selectedPipe.is_local ? selectedPipe.id : selectedPipe.name;
+ const response = await fetch("http://localhost:3030/pipes/update", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ pipe_id: id,
+ config: config,
+ }),
+ });
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(data.error || "Failed to update pipe configuration");
+ }
+
+ toast({
+ title: "Configuration saved",
+ description: "The pipe configuration has been updated.",
+ });
+
+ setSelectedPipe({
+ ...selectedPipe,
+ installed_config: {
+ ...selectedPipe.installed_config!,
+ ...config,
+ },
+ });
+ } catch (error) {
+ console.error("Failed to save config:", error);
+ toast({
+ title: "error saving configuration",
+ description:
+ "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ }
+ }
+ };
+ const handleDeletePipe = async (pipe: PipeWithStatus) => {
+ try {
+ toast({
+ title: "deleting pipe",
+ description: "please wait...",
+ });
+ setSelectedPipe(null);
+
+ const id = pipe.is_local ? pipe.id : pipe.name;
+ const response = await fetch("http://localhost:3030/pipes/delete", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ pipe_id: id }),
+ });
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(data.error);
+ }
+
+ // First unselect the pipe, then fetch the updated list
+ await fetchInstalledPipes();
+
+ toast({
+ title: "pipe deleted",
+ description: "the pipe has been successfully removed",
+ });
+
+ setSelectedPipe(null);
+ } catch (error) {
+ console.error("failed to delete pipe:", error);
+ toast({
+ title: "error deleting pipe",
+ description: "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleRefreshFromDisk = async (pipe: PipeWithStatus) => {
+ try {
+ toast({
+ title: "refreshing pipe",
+ description: "please wait...",
+ });
+
+ const response = await fetch(`http://localhost:3030/pipes/download`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ url: pipe.installed_config?.source }),
+ });
+ if (!response.ok) {
+ throw new Error("failed to refresh pipe");
+ }
+
+ await fetchInstalledPipes();
+ toast({
+ title: "pipe refreshed",
+ description: "the pipe has been successfully refreshed from disk.",
+ });
+ } catch (error) {
+ console.error("failed to refresh pipe from disk:", error);
+ toast({
+ title: "error refreshing pipe",
+ description: "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ } finally {
+ setSelectedPipe(null);
+ }
+ };
+
+ const handleUpdatePipe = async (pipe: PipeWithStatus) => {
+ try {
+ if (!checkLogin(settings.user)) return;
+
+ const currentVersion = pipe.installed_config?.version!;
+ const storeApi = await PipeApi.create(settings.user!.token!);
+ const update = await storeApi.checkUpdate(pipe.id, currentVersion);
+ if (!update.has_update) {
+ toast({
+ title: "no update available",
+ description: "the pipe is already up to date",
+ });
+ return;
+ }
+
+ const t = toast({
+ title: "updating pipe",
+ description: (
+ <div className="space-y-2">
+ <Progress value={25} className="h-1" />
+ <p className="text-xs">checking for updates...</p>
+ </div>
+ ),
+ duration: 100000,
+ });
+
+ // Update progress for download start
+ t.update({
+ id: t.id,
+ description: (
+ <div className="space-y-2">
+ <Progress value={50} className="h-1" />
+ <p className="text-xs">downloading update...</p>
+ </div>
+ ),
+ });
+
+ const responseDownload = await storeApi.downloadPipe(pipe.id);
+
+ // Update progress for installation
+ t.update({
+ id: t.id,
+ description: (
+ <div className="space-y-2">
+ <Progress value={75} className="h-1" />
+ <p className="text-xs">installing update...</p>
+ </div>
+ ),
+ });
+
+ const response = await fetch(
+ `http://localhost:3030/pipes/update-version`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ pipe_id: pipe.name,
+ source: responseDownload.download_url,
+ }),
+ },
+ );
+
+ const data = await response.json();
+ if (!data.success) {
+ throw new Error(data.error);
+ }
+
+ // Update progress for completion
+ t.update({
+ id: t.id,
+ title: "pipe updated",
+ description: (
+ <div className="space-y-2">
+ <Progress value={100} className="h-1" />
+ <p className="text-xs">completed successfully</p>
+ </div>
+ ),
+ duration: 2000,
+ });
+
+ await fetchInstalledPipes();
+
+ t.dismiss();
+ } catch (error) {
+ console.error("failed to update pipe:", error);
+ toast({
+ title: "error updating pipe",
+ description: "please try again or check the logs for more information.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ useEffect(() => {
+ fetchStorePlugins();
+ }, [installedPipes, purchaseHistory]);
+
+ useEffect(() => {
+ fetchPurchaseHistory();
+ }, [settings.user.token]);
+
+ useEffect(() => {
+ fetchInstalledPipes();
+ }, [health]);
+
+ useEffect(() => {
+ const interval = setInterval(() => {
+ fetchInstalledPipes();
+ }, 3000);
+ return () => clearInterval(interval);
+ }, []);
+
+ useEffect(() => {
+ const checkForUpdates = async () => {
+ if (!settings.user.token) {
+ return;
+ }
+ // Get last check time from local storage
+ const lastCheckTime =
+ await localforage.getItem<number>("lastUpdateCheck");
+ const now = Date.now();
+
+ // Check if 5 minutes have passed since last check
+ if (lastCheckTime && now - lastCheckTime < 5 * 60 * 1000) {
+ return;
+ }
+
+ // Store current time as last check
+ await localforage.setItem("lastUpdateCheck", now);
+
+ const installedPipes = pipes.filter((pipe) => pipe.is_installed);
+
+ const storeApi = await PipeApi.create(settings.user.token);
+ for (const pipe of installedPipes) {
+ const update = await storeApi.checkUpdate(
+ pipe.id,
+ pipe.installed_config?.version!,
+ );
+ if (update.has_update) {
+ await handleUpdatePipe(pipe);
+ }
+ }
+ };
+
+ // Run check immediately
+ checkForUpdates();
+
+ // Set up interval to check every 10 seconds actual check is done in the function
+ const interval = setInterval(checkForUpdates, 10 * 1000);
+
+ return () => clearInterval(interval);
+ }, [settings.user.token]);
+
+ useEffect(() => {
+ const setupDeepLink = async () => {
+ const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
+ console.log("received deep link urls:", urls);
+ for (const url of urls) {
+ if (url.includes("purchase-successful")) {
+ const urlObj = new URL(url);
+ const pipeId = urlObj.searchParams.get("pipe_id");
+
+ if (!pipeId) {
+ toast({
+ title: "purchase successful",
+ description: "your purchase was successful",
+ });
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+
+ // First update purchase history to reflect the new purchase
+ await fetchPurchaseHistory();
+
+ // Find the pipe in the store
+ const purchasedPipe = pipes.find((pipe) => pipe.id === pipeId);
+ if (!purchasedPipe) {
+ toast({
+ title: "error installing pipe",
+ description: "could not find the purchased pipe",
+ variant: "destructive",
+ });
+ return;
+ }
+
+ // Install the pipe
+ await handleInstallPipe(purchasedPipe);
+ }
+ }
+ });
+ return unsubscribeDeepLink;
+ };
+
+ let deepLinkUnsubscribe: (() => void) | undefined;
+
+ setupDeepLink().then((unsubscribe) => {
+ deepLinkUnsubscribe = unsubscribe;
+ });
+ return () => {
+ if (deepLinkUnsubscribe) deepLinkUnsubscribe();
+ };
+ }, [pipes]);
+
+ if (health?.status === "error") {
+ return (
+ <div className="flex flex-col items-center justify-center h-screen p-4 space-y-4">
+ <div className="text-center space-y-4">
+ <h3 className="text-lg font-medium">screenpipe is not recording</h3>
+ <p className="text-sm text-muted-foreground">
+ please start the screenpipe service to browse and manage pipes
+ </p>
+ <Button
+ variant="outline"
+ onClick={openStatusDialog}
+ className="gap-2"
+ >
+ <Power className="h-4 w-4" />
+ check service status
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (selectedPipe) {
+ return (
+ <PipeDetails
+ pipe={selectedPipe}
+ onClose={() => setSelectedPipe(null)}
+ onToggle={handleTogglePipe}
+ onConfigSave={handleConfigSave}
+ onDelete={handleDeletePipe}
+ onRefreshFromDisk={handleRefreshFromDisk}
+ onUpdate={handleUpdatePipe}
+ />
+ );
+ }
+
+ return (
+ <div className="overflow-hidden flex flex-col space-y-4 min-w-[800px]">
+ <div className="flex flex-col flex-1 overflow-hidden space-y-4 p-4 min-w-[800px]">
+ <div className="space-y-4 min-w-[800px]">
+ <div className="flex flex-col gap-4 w-[50%]">
+ <div className="flex-1 relative">
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
+ <Input
+ placeholder="search community pipes..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-9"
+ autoCorrect="off"
+ autoComplete="off"
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-gray-600">show installed only</span>
+ <Switch
+ checked={showInstalledOnly}
+ onCheckedChange={setShowInstalledOnly}
+ />
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={handleResetAllPipes}
+ className="flex items-center gap-2"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>reset all pipes</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => handleUpdateAllPipes()}
+ className="flex items-center gap-2"
+ disabled={
+ !pipes.some(
+ (pipe) => pipe.is_installed && pipe.has_update,
+ )
+ }
+ >
+ <RefreshCw className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>update all pipes</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex-1 overflow-y-auto">
+ <div className="grid grid-cols-2 gap-4">
+ {filteredPipes.map((pipe) => (
+ <PipeCard
+ key={pipe.id}
+ pipe={pipe}
+ setPipe={(updatedPipe) => {
+ setPipes((prevPipes) => {
+ return prevPipes.map((p) =>
+ p.id === updatedPipe.id ? updatedPipe : p,
+ );
+ });
+ }}
+ onInstall={handleInstallPipe}
+ onClick={setSelectedPipe}
+ onPurchase={handlePurchasePipe}
+ isLoadingPurchase={loadingPurchases.has(pipe.id)}
+ isLoadingInstall={loadingInstalls.has(pipe.id)}
+ onToggle={handleTogglePipe}
+ />
+ ))}
+ </div>
+ </div>
+
+ <AddPipeForm
+ onAddPipe={handleInstallSideload}
+ isHealthy={health?.status !== "error"}
+ onLoadFromLocalFolder={handleLoadFromLocalFolder}
+ />
+ </div>
+ <LoginDialog open={showLoginDialog} onOpenChange={setShowLoginDialog} />
+ </div>
+ );
};
diff --git a/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx b/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
index 83afb6d6a..bf02bf7d0 100644
--- a/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
+++ b/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
@@ -1,4 +1,10 @@
-import React, { useEffect, useRef, useState } from "react";
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { Button } from "@/components/ui/button";
import {
Download,
@@ -7,6 +13,7 @@ import {
Loader2,
Power,
ArrowUpCircle,
+ AlertCircle,
} from "lucide-react";
import { PipeStoreMarkdown } from "@/components/pipe-store-markdown";
import { BuildStatus, PipeWithStatus } from "./types";
@@ -15,6 +22,12 @@ import { toast } from "@/components/ui/use-toast";
import { motion } from "framer-motion";
import posthog from "posthog-js";
import { useSettings } from "@/lib/hooks/use-settings";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
interface PipeCardProps {
pipe: PipeWithStatus;
@@ -27,6 +40,34 @@ interface PipeCardProps {
setPipe: (pipe: PipeWithStatus) => void;
}
+export function getBuildStatus(status: BuildStatus | undefined): string {
+ return typeof status === "object" ? status.status : status || "";
+}
+
+function getBuildStepMessage(buildStatus: BuildStatus | undefined): string {
+ if (typeof buildStatus !== "object") return "building...";
+
+ const { step, status } = buildStatus;
+ if (status === "not_started") {
+ return "waiting to start...";
+ }
+
+ switch (step) {
+ case "downloading":
+ return "downloading files...";
+ case "extracting":
+ return "extracting files...";
+ case "installing":
+ return "installing dependencies...";
+ case "completed":
+ return "completed installation";
+ case "building":
+ return "building application...";
+ default:
+ return step || "processing...";
+ }
+}
+
export const PipeCard: React.FC<PipeCardProps> = ({
pipe,
onInstall,
@@ -39,13 +80,14 @@ export const PipeCard: React.FC<PipeCardProps> = ({
}) => {
const [isLoading, setIsLoading] = useState(false);
const { settings } = useSettings();
+
const handleOpenWindow = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
if (pipe.installed_config?.port) {
await invoke("open_pipe_window", {
port: pipe.installed_config.port,
- title: pipe.name, // atm we don't support pipes with same name
+ title: pipe.name,
});
}
} catch (err) {
@@ -62,26 +104,28 @@ export const PipeCard: React.FC<PipeCardProps> = ({
const pollBuildStatus = async () => {
const id = pipe.is_local ? pipe.id : pipe.name;
try {
- const response = await fetch(`http://localhost:3030/pipes/info/${id}`);
+ const response = await fetch(
+ `http://localhost:3030/pipes/build-status/${id}`,
+ );
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
-
+ console.log(data, pipe.installed_config?.buildStatus);
if (
- data.success &&
- data.data.config.buildStatus !== pipe.installed_config?.buildStatus
+ data.buildStatus.length > 0 &&
+ JSON.stringify(data.buildStatus) !==
+ JSON.stringify(pipe.installed_config?.buildStatus)
) {
- // Update pipe with new build status
setPipe({
...pipe,
installed_config: {
...pipe.installed_config,
is_nextjs: pipe.installed_config?.is_nextjs ?? false,
source: pipe.installed_config?.source ?? "",
- buildStatus: data.data.config.buildStatus as BuildStatus,
+ buildStatus: data.buildStatus as BuildStatus,
},
});
}
@@ -93,28 +137,118 @@ export const PipeCard: React.FC<PipeCardProps> = ({
...pipe.installed_config,
is_nextjs: pipe.installed_config?.is_nextjs ?? false,
source: pipe.installed_config?.source ?? "",
- buildStatus: "error",
+ buildStatus: {
+ status: "error",
+ step: "failed",
+ error:
+ error instanceof Error
+ ? error.message
+ : "Unknown error occurred",
+ } as BuildStatus,
},
});
}
};
let buildStatusInterval: NodeJS.Timeout | null = null;
- if (pipe.installed_config?.buildStatus === "in_progress") {
+ const buildStatus = pipe.installed_config?.buildStatus;
+ const isInProgress =
+ buildStatus === "in_progress" ||
+ (typeof buildStatus === "object" && buildStatus.status === "in_progress");
+
+ if (isInProgress) {
buildStatusInterval = setInterval(pollBuildStatus, 3000);
- } else {
- if (!buildStatusInterval) return;
- clearInterval(buildStatusInterval);
}
- console.log("buildStatus", pipe.installed_config?.buildStatus);
-
return () => {
- if (!buildStatusInterval) return;
- clearInterval(buildStatusInterval);
+ if (buildStatusInterval) {
+ clearInterval(buildStatusInterval);
+ }
};
}, [pipe.installed_config?.buildStatus]);
+ const renderInstallationStatus = useCallback(() => {
+ const buildStatus = pipe.installed_config?.buildStatus;
+ const status = getBuildStatus(buildStatus);
+
+ if (status === "not_started" || status === "in_progress") {
+ return (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled
+ className="hover:bg-muted font-medium relative hover:!bg-muted no-card-hover"
+ >
+ <Loader2 className="h-3.5 w-3.5 mr-2 animate-spin" />
+ <div className="flex flex-col items-start">
+ <span>{getBuildStepMessage(buildStatus)}</span>
+ </div>
+ </Button>
+ );
+ }
+
+ if (status === "error") {
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="sm"
+ variant="destructive"
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsLoading(true);
+ onToggle(pipe, () => setIsLoading(false));
+ }}
+ className="font-medium no-card-hover"
+ disabled={isLoading}
+ >
+ <AlertCircle className="h-3.5 w-3.5 mr-2" />
+ retry
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {typeof buildStatus === "object" && buildStatus.error
+ ? buildStatus.error
+ : "Installation failed"}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+ }
+
+ if (!pipe.is_enabled && buildStatus === "success") {
+ return (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsLoading(true);
+ onToggle(pipe, () => setIsLoading(false));
+ }}
+ className="hover:bg-muted font-medium relative hover:!bg-muted no-card-hover"
+ disabled={isLoading}
+ >
+ <Power className="h-3.5 w-3.5 mr-2" />
+ enable
+ </Button>
+ );
+ }
+
+ return (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleOpenWindow}
+ className="hover:bg-muted font-medium relative no-card-hover"
+ >
+ <Puzzle className="h-3.5 w-3.5 mr-2" />
+ open
+ </Button>
+ );
+ }, [pipe.installed_config?.buildStatus]);
+
return (
<motion.div
className="group border rounded-xl p-5 hover:bg-muted/40 has-[.no-card-hover:hover]:hover:bg-transparent transition-all duration-200 cursor-pointer backdrop-blur-sm"
@@ -125,7 +259,6 @@ export const PipeCard: React.FC<PipeCardProps> = ({
boxShadow: "0 0 10px rgba(255,255,255,0.1)",
transition: { duration: 0.2 },
}}
- layout
>
<div className="flex flex-col h-full justify-between space-y-4">
<div className="flex items-start justify-between gap-4">
@@ -144,69 +277,7 @@ export const PipeCard: React.FC<PipeCardProps> = ({
</div>
<div className="flex items-center gap-2 isolate">
{pipe.is_installed ? (
- <>
- {pipe.installed_config?.buildStatus === "in_progress" ? (
- <Button
- size="sm"
- variant="outline"
- disabled
- className="hover:bg-muted font-medium relative hover:!bg-muted no-card-hover"
- >
- <Loader2 className="h-3.5 w-3.5 mr-2 animate-spin" />
- building...
- </Button>
- ) : pipe.installed_config?.buildStatus === "error" ? (
- <Button
- size="sm"
- variant="destructive"
- onClick={(e) => {
- e.stopPropagation();
- setIsLoading(true);
- onToggle(pipe, () => setIsLoading(false));
- }}
- className="font-medium no-card-hover"
- disabled={isLoading}
- >
- <ArrowUpCircle className="h-3.5 w-3.5 mr-2" />
- retry build
- </Button>
- ) : !pipe.is_enabled ? (
- <Button
- size="sm"
- variant="outline"
- onClick={(e) => {
- e.stopPropagation();
- setIsLoading(true);
- onToggle(pipe, () => setIsLoading(false));
- }}
- className="hover:bg-muted font-medium relative hover:!bg-muted no-card-hover"
- disabled={isLoading}
- >
- <Power className="h-3.5 w-3.5 mr-2" />
- enable
- </Button>
- ) : (
- <Button
- size="sm"
- variant="outline"
- onClick={handleOpenWindow}
- className="hover:bg-muted font-medium relative no-card-hover"
- disabled={
- pipe.installed_config?.buildStatus &&
- pipe.installed_config?.buildStatus === "not_started"
- }
- >
- {pipe.installed_config?.buildStatus === "not_started" ? (
- <>wait for app to start building</>
- ) : (
- <>
- <Puzzle className="h-3.5 w-3.5 mr-2" />
- open
- </>
- )}
- </Button>
- )}
- </>
+ renderInstallationStatus()
) : (
<Button
size="sm"
@@ -233,9 +304,7 @@ export const PipeCard: React.FC<PipeCardProps> = ({
disabled={isLoadingPurchase}
>
{isLoadingPurchase ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- </>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : pipe.is_paid && !pipe.has_purchased ? (
`$${pipe.price}`
) : (
diff --git a/screenpipe-app-tauri/components/pipe-store/pipe-details.tsx b/screenpipe-app-tauri/components/pipe-store/pipe-details.tsx
index fd3694023..ad55b0542 100644
--- a/screenpipe-app-tauri/components/pipe-store/pipe-details.tsx
+++ b/screenpipe-app-tauri/components/pipe-store/pipe-details.tsx
@@ -22,6 +22,7 @@ import { invoke } from "@tauri-apps/api/core";
import { PipeConfigForm } from "../pipe-config-form";
import { open as openUrl } from "@tauri-apps/plugin-shell";
import { Badge } from "../ui/badge";
+import { getBuildStatus } from "./pipe-card";
interface PipeDetailsProps {
pipe: PipeWithStatus;
@@ -223,7 +224,7 @@ export const PipeDetails: React.FC<PipeDetailsProps> = ({
<div className="max-w-3xl mx-auto p-8 ">
{pipe.installed_config?.enabled &&
!buildStatusNotAllows.includes(
- pipe.installed_config.buildStatus ?? "",
+ getBuildStatus(pipe.installed_config.buildStatus) ?? "",
) &&
pipe.installed_config?.port && (
<div>
diff --git a/screenpipe-app-tauri/components/pipe-store/types.ts b/screenpipe-app-tauri/components/pipe-store/types.ts
index 2d9a5ac92..494bdd88b 100644
--- a/screenpipe-app-tauri/components/pipe-store/types.ts
+++ b/screenpipe-app-tauri/components/pipe-store/types.ts
@@ -1,9 +1,25 @@
import { PipeStorePlugin } from "@/lib/api/store";
-export type BuildStatus = "not_started" | "in_progress" | "success" | "error";
+export type BuildStatus =
+ | string
+ | {
+ status: "in_progress" | "error" | "success" | "not_started";
+ step: string;
+ progress?: number;
+ error?: string;
+ };
+
+export interface InstalledConfig {
+ port?: number;
+ enabled?: boolean;
+ version?: string;
+ buildStatus?: BuildStatus;
+ is_nextjs?: boolean;
+ source?: string;
+}
export interface InstalledPipe {
- config: {
+ config: InstalledConfig & {
id?: string;
enabled?: boolean;
is_nextjs: boolean;
@@ -15,7 +31,6 @@ export interface InstalledPipe {
}[];
fields?: Record<string, any>;
version?: string;
- buildStatus?: BuildStatus;
};
desc: string;
id: string;
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index d4a2b1355..373544da3 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -1503,31 +1503,121 @@ done
let temp_dir = dest_dir.with_extension("_temp");
tokio::fs::create_dir_all(&temp_dir).await?;
+ // Create initial pipe.json in temp directory with download status
+ let temp_pipe_json = temp_dir.join("pipe.json");
+ let initial_config = json!({
+ "buildStatus": {
+ "status": "in_progress",
+ "step": "downloading",
+ }
+ });
+ tokio::fs::write(
+ &temp_pipe_json,
+ serde_json::to_string_pretty(&initial_config)?,
+ )
+ .await?;
+
+ // Helper function to update build status
+ async fn update_build_status(
+ path: &Path,
+ status: &str,
+ step: &str,
+ error: Option<&str>,
+ ) -> anyhow::Result<()> {
+ if path.exists() {
+ let pipe_json = tokio::fs::read_to_string(path).await?;
+ let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
+ pipe_config["buildStatus"] = match error {
+ Some(err) => json!({
+ "status": status,
+ "step": step,
+ "error": err
+ }),
+ None => json!({
+ "status": status,
+ "step": step
+ }),
+ };
+ let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
+ tokio::fs::write(path, updated_pipe_json).await?;
+ }
+ Ok(())
+ }
+
+ // Cleanup function
+ async fn cleanup_temp(temp_dir: &Path, temp_zip: &Path) -> anyhow::Result<()> {
+ if temp_zip.exists() {
+ if let Err(e) = tokio::fs::remove_file(temp_zip).await {
+ warn!("Failed to remove temporary zip file: {}", e);
+ }
+ }
+ if temp_dir.exists() {
+ if let Err(e) = tokio::fs::remove_dir_all(temp_dir).await {
+ warn!("Failed to remove temporary directory: {}", e);
+ }
+ }
+ Ok(())
+ }
+
// Download zip file
debug!("downloading zip file from: {}", source);
let client = Client::new();
- let response = client.get(source).send().await?;
- let zip_content = response.bytes().await?;
+ let response = match client.get(source).send().await {
+ Ok(res) => res,
+ Err(e) => {
+ let err_msg = format!("Failed to download zip: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
+ };
+
+ let zip_content = match response.bytes().await {
+ Ok(content) => content,
+ Err(e) => {
+ let err_msg = format!("Failed to read zip content: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_dir.join("temp.zip")).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
+ };
// Create temporary zip file
let temp_zip = temp_dir.join("temp.zip");
- tokio::fs::write(&temp_zip, &zip_content).await?;
+ if let Err(e) = tokio::fs::write(&temp_zip, &zip_content).await {
+ let err_msg = format!("Failed to write temporary zip file: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
- // Unzip the file using tokio spawn_blocking to handle sync operations
+ // Update status before extraction
+ let temp_pipe_json = temp_dir.join("pipe.json");
+ update_build_status(&temp_pipe_json, "in_progress", "extracting", None).await?;
+
+ // Unzip the file
debug!("unzipping file to temp directory");
let temp_zip_path = temp_zip.clone();
let temp_dir_path = temp_dir.clone();
- tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
+ let extraction_result = tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
let zip_file = std::fs::File::open(&temp_zip_path)?;
let mut archive = zip::ZipArchive::new(zip_file)?;
+ let total_files = archive.len();
- for i in 0..archive.len() {
+ for i in 0..total_files {
let mut file = archive.by_index(i)?;
let name = file.name().to_string();
+
+ // Check for zip slip vulnerability
+ if name.contains("..") {
+ return Err(anyhow::anyhow!(
+ "Invalid zip file: potential path traversal attack"
+ ));
+ }
+
let outpath = temp_dir_path.join(&name);
- let ends_with_slash = name.ends_with('/');
- if ends_with_slash {
+ if name.ends_with('/') {
std::fs::create_dir_all(&outpath)?;
} else {
if let Some(p) = outpath.parent() {
@@ -1541,18 +1631,52 @@ done
}
Ok(())
})
- .await??;
+ .await;
+
+ // Handle extraction errors
+ if let Err(e) = extraction_result {
+ let err_msg = format!("Extraction task failed: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
+
+ if let Err(e) = extraction_result.unwrap() {
+ let err_msg = format!("Failed to extract zip: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&temp_pipe_json, "error", "extracting", Some(&err_msg)).await?;
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
// Remove the temporary zip file
- tokio::fs::remove_file(&temp_zip).await?;
+ if let Err(e) = tokio::fs::remove_file(&temp_zip).await {
+ warn!("Failed to remove temporary zip file: {}", e);
+ }
// Move temp dir to final location
if dest_dir.exists() {
- tokio::fs::remove_dir_all(&dest_dir).await?;
+ if let Err(e) = tokio::fs::remove_dir_all(&dest_dir).await {
+ let err_msg = format!("Failed to remove existing destination directory: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
}
- tokio::fs::rename(&temp_dir, &dest_dir).await?;
- // Check if it's a Next.js project
+ if let Err(e) = tokio::fs::rename(&temp_dir, &dest_dir).await {
+ let err_msg = format!("Failed to move files to destination: {}", e);
+ error!("{}", err_msg);
+ cleanup_temp(&temp_dir, &temp_zip).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
+
+ // Update status for installation
+ let final_pipe_json = dest_dir.join("pipe.json");
+ update_build_status(&final_pipe_json, "in_progress", "installing", None).await?;
+
+ // Check if it's a Next.js project and handle installation
let package_json_path = dest_dir.join("package.json");
let is_nextjs = if package_json_path.exists() {
let package_json = tokio::fs::read_to_string(&package_json_path).await?;
@@ -1565,21 +1689,31 @@ done
// Find bun path
let bun_path = find_bun_path().ok_or_else(|| anyhow::anyhow!("bun not found"))?;
- // Run bun install
+ // Run bun install with error handling
info!("installing dependencies");
- retry_install(&bun_path, &dest_dir, 3).await?;
+ if let Err(e) = retry_install(&bun_path, &dest_dir, 3).await {
+ let err_msg = format!("Failed to install dependencies: {}", e);
+ error!("{}", err_msg);
+ update_build_status(&final_pipe_json, "error", "installing", Some(&err_msg)).await?;
+ return Err(anyhow::anyhow!(err_msg));
+ }
if is_nextjs {
- info!("detected next.js project, starting in production mode");
- // Update pipe.json to indicate it's a Next.js project
- let pipe_json_path = dest_dir.join("pipe.json");
- if pipe_json_path.exists() {
- let pipe_json = tokio::fs::read_to_string(&pipe_json_path).await?;
+ info!("detected next.js project, updating configuration");
+ if final_pipe_json.exists() {
+ let pipe_json = tokio::fs::read_to_string(&final_pipe_json).await?;
let mut pipe_config: Value = serde_json::from_str(&pipe_json)?;
pipe_config["is_nextjs"] = json!(true);
+ pipe_config["buildStatus"] = json!({
+ "status": "success",
+ "step": "completed"
+ });
let updated_pipe_json = serde_json::to_string_pretty(&pipe_config)?;
- tokio::fs::write(&pipe_json_path, updated_pipe_json).await?;
+ tokio::fs::write(&final_pipe_json, updated_pipe_json).await?;
}
+ } else {
+ // Update final success status for non-Next.js projects
+ update_build_status(&final_pipe_json, "success", "completed", None).await?;
}
info!("pipe downloaded and set up successfully at: {:?}", dest_dir);
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 162b457a0..3deb19e9f 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -258,6 +258,7 @@ impl PipeManager {
"source": "store",
"version": version,
"id": pipe_id,
+ "enabled": true,
}),
)
.await?;
@@ -281,14 +282,14 @@ impl PipeManager {
for pipe in pipes {
if pipe.enabled {
debug!("stopping pipe [{}] before purge", pipe.id);
- match self.stop_pipe(&pipe.id).await {
- Ok(_) => {
- debug!("successfully killed pipe process [{}]", &pipe.id);
- }
- Err(_) => {
- debug!("failed to stop pipe [{}],", &pipe.id);
- }
- };
+ match self.stop_pipe(&pipe.id).await {
+ Ok(_) => {
+ debug!("successfully killed pipe process [{}]", &pipe.id);
+ }
+ Err(_) => {
+ debug!("failed to stop pipe [{}],", &pipe.id);
+ }
+ };
}
}
@@ -314,7 +315,10 @@ impl PipeManager {
Err(e) => {
if retries > 0 {
retries -= 1;
- debug!("failed to purge pipes, retrying! ({} retries left)", retries);
+ debug!(
+ "failed to purge pipes, retrying! ({} retries left)",
+ retries
+ );
} else {
return Err(e.into());
}
@@ -443,7 +447,7 @@ impl PipeManager {
);
}
}
- #[cfg(windows)]
+ #[cfg(windows)]
{
const CREATE_NO_WINDOW: u32 = 0x08000000;
let output = tokio::process::Command::new("netstat")
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 9d9c2b906..9c421b572 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -2052,6 +2052,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/ws/events", get(ws_events_handler))
.route("/semantic-search", get(semantic_search_handler))
.route("/frames/:frame_id", get(get_frame_data))
+ .route("/pipes/build-status/:pipe_id", get(get_pipe_build_status))
.route("/search/keyword", get(keyword_search_handler))
// .route("/vision/start", post(start_vision_device))
// .route("/vision/stop", post(stop_vision_device))
@@ -2067,6 +2068,72 @@ pub fn create_router() -> Router<Arc<AppState>> {
router
}
+async fn get_pipe_build_status(
+ Path(pipe_id): Path<String>,
+ State(state): State<Arc<AppState>>,
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
+ let pipe_dir = state.screenpipe_dir.join("pipes").join(&pipe_id);
+ let temp_dir = pipe_dir.with_extension("_temp");
+
+ // First check temp directory if it exists
+ if temp_dir.exists() {
+ let temp_pipe_json = temp_dir.join("pipe.json");
+ if temp_pipe_json.exists() {
+ let pipe_json = tokio::fs::read_to_string(&temp_pipe_json)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(
+ json!({"error": format!("Failed to read temp pipe config: {}", e)}),
+ ),
+ )
+ })?;
+
+ let pipe_config: Value = serde_json::from_str(&pipe_json).map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(
+ json!({"error": format!("Failed to parse temp pipe config: {}", e)}),
+ ),
+ )
+ })?;
+
+ info!("{:?}", pipe_config);
+ let build_status = pipe_config.get("buildStatus").unwrap_or(&Value::Null);
+ return Ok(JsonResponse(json!({ "buildStatus": build_status })));
+ }
+ }
+
+ // If no temp directory or no pipe.json in temp, check the main pipe directory
+ let pipe_json_path = pipe_dir.join("pipe.json");
+ if !pipe_json_path.exists() {
+ return Err((
+ StatusCode::NOT_FOUND,
+ JsonResponse(json!({"error": "Pipe not found"})),
+ ));
+ }
+
+ let pipe_json = tokio::fs::read_to_string(&pipe_json_path)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("Failed to read pipe config: {}", e)})),
+ )
+ })?;
+
+ let pipe_config: Value = serde_json::from_str(&pipe_json).map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("Failed to parse pipe config: {}", e)})),
+ )
+ })?;
+
+ let build_status = pipe_config.get("buildStatus").unwrap_or(&Value::Null);
+ Ok(JsonResponse(json!({ "buildStatus": build_status })))
+}
+
async fn keyword_search_handler(
Query(query): Query<KeywordSearchRequest>,
State(state): State<Arc<AppState>>,
@@ -2495,8 +2562,7 @@ pub struct RestartAudioDevicesResponse {
}
#[derive(Debug, Deserialize)]
-pub struct PurgePipeRequest {
-}
+pub struct PurgePipeRequest {}
// async fn restart_audio_devices(
// State(state): State<Arc<AppState>>,