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

improve pipe update functionality and ux (#1598)

shaik-zeeshan419dcf6a8154
diff --git a/screenpipe-app-tauri/components/pipe-store.tsx b/screenpipe-app-tauri/components/pipe-store.tsx
index cbe125cc6..e383bfdd8 100644
--- a/screenpipe-app-tauri/components/pipe-store.tsx
+++ b/screenpipe-app-tauri/components/pipe-store.tsx
@@ -1,8 +1,17 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useState, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
-import { Loader2, Power, Search, Trash2, RefreshCw } from "lucide-react";
+import {
+ Loader2,
+ Power,
+ Search,
+ Trash2,
+ RefreshCw,
+ Download,
+ Bell,
+ HardDriveDownload,
+} from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import {
@@ -35,41 +44,53 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
import localforage from "localforage";
import { useLoginDialog } from "./login-dialog";
import { PermissionButtons } from "./status/permission-buttons";
import { usePlatform } from "@/lib/hooks/use-platform";
import { invoke } from "@tauri-apps/api/core";
+import { cn } from "@/lib/utils";
+import { getAllWindows } from "@tauri-apps/api/window";
const corePipes: string[] = [];
export const PipeStore: React.FC = () => {
const { health } = useHealthCheck();
const [selectedPipe, setSelectedPipe] = useState<PipeWithStatus | null>(null);
- const { settings } = useSettings();
+ const { settings, updateSettings } = 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 { checkLogin } = useLoginDialog();
const { open: openStatusDialog } = useStatusDialog();
const [loadingPurchases, setLoadingPurchases] = useState<Set<string>>(
- new Set()
+ new Set(),
);
const [loadingInstalls, setLoadingInstalls] = useState<Set<string>>(
- new Set()
+ new Set(),
);
const { isMac: isMacOS } = usePlatform();
const [isRestarting, setIsRestarting] = useState(false);
+ const [availableUpdates, setAvailableUpdates] = useState<PipeWithStatus[]>(
+ [],
+ );
+ const [updatePopoverOpen, setUpdatePopoverOpen] = useState(false);
+ const [isUpdating, setIsUpdating] = useState(false);
const filteredPipes = pipes
.filter(
(pipe) =>
pipe.id.toLowerCase().includes(searchQuery.toLowerCase()) &&
(!showInstalledOnly || pipe.is_installed) &&
- !pipe.is_installing
+ !pipe.is_installing,
)
.sort((a, b) => {
// Sort by downloads count first
@@ -101,25 +122,6 @@ export const PipeStore: React.FC = () => {
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!);
@@ -131,26 +133,27 @@ export const PipeStore: React.FC = () => {
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
+ (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", "")
- )
+ (plugin) => plugin.name === p.id?.replace("._temp", ""),
+ ),
)
.map((p) => {
const pluginName = p.config?.source?.split("/").pop();
@@ -191,7 +194,7 @@ export const PipeStore: React.FC = () => {
const handlePurchasePipe = async (
pipe: PipeWithStatus,
- onComplete?: () => void
+ onComplete?: () => void,
) => {
try {
if (!checkLogin(settings.user)) return;
@@ -318,7 +321,7 @@ export const PipeStore: React.FC = () => {
const handleInstallPipe = async (
pipe: PipeWithStatus,
- onComplete?: () => void
+ onComplete?: () => void,
) => {
try {
if (!checkLogin(settings.user)) return;
@@ -326,8 +329,8 @@ export const PipeStore: React.FC = () => {
// 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
- )
+ p.id === pipe.id ? { ...p, is_installing: true } : p,
+ ),
);
setLoadingInstalls((prev) => new Set(prev).add(pipe.id));
@@ -358,7 +361,7 @@ export const PipeStore: React.FC = () => {
pipe_id: pipe.id,
url: response.download_url,
}),
- }
+ },
);
const data = await downloadResponse.json();
@@ -377,8 +380,8 @@ export const PipeStore: React.FC = () => {
is_installed: true,
is_installing: false,
}
- : p
- )
+ : p,
+ ),
);
onComplete?.();
@@ -389,8 +392,8 @@ export const PipeStore: React.FC = () => {
// Reset the pipe's status on error
setPipes((prevPipes) =>
prevPipes.map((p) =>
- p.id === pipe.id ? { ...p, is_installing: false } : p
- )
+ p.id === pipe.id ? { ...p, is_installing: false } : p,
+ ),
);
if ((error as Error).cause === PipeDownloadError.PURCHASE_REQUIRED) {
return toast({
@@ -481,7 +484,7 @@ export const PipeStore: React.FC = () => {
console.error("failed to reset pipes:", error);
toast({
title: "error resetting pipes",
- description: `error: ${(error as Error).message}...}`,
+ description: `error: ${(error as Error).message}...}`,
variant: "destructive",
});
} finally {
@@ -509,9 +512,7 @@ export const PipeStore: React.FC = () => {
}
// Filter installed pipes that have updates available
- const pipesToUpdate = pipes.filter(
- (pipe) => pipe.is_installed && pipe.has_update
- );
+ const pipesToUpdate = availableUpdates;
if (pipesToUpdate.length === 0) {
if (t) {
@@ -568,7 +569,23 @@ export const PipeStore: React.FC = () => {
duration: 100000,
});
- await handleUpdatePipe(pipe);
+ await handleUpdatePipe(pipe); // Set all pipes to be updated to "in_progress" status
+ setPipes((prevPipes) =>
+ prevPipes.map((p) => {
+ if (
+ pipesToUpdate.some((pipeToUpdate) => pipeToUpdate.id === p.id)
+ ) {
+ return {
+ ...p,
+ installed_config: {
+ ...p.installed_config!,
+ buildStatus: "in_progress",
+ },
+ };
+ }
+ return p;
+ }),
+ );
}
t.update({
@@ -594,7 +611,7 @@ export const PipeStore: React.FC = () => {
const handleTogglePipe = async (
pipe: PipeWithStatus,
- onComplete: () => void
+ onComplete: () => void,
) => {
try {
const t = toast({
@@ -651,7 +668,7 @@ export const PipeStore: React.FC = () => {
`Failed to ${
pipe.installed_config?.enabled ? "disable" : "enable"
} pipe:`,
- error
+ error,
);
toast({
title: "error toggling pipe",
@@ -662,7 +679,7 @@ export const PipeStore: React.FC = () => {
};
const handleLoadFromLocalFolder = async (
- setNewRepoUrl: (url: string) => void
+ setNewRepoUrl: (url: string) => void,
) => {
try {
const selectedFolder = await open({
@@ -808,10 +825,40 @@ export const PipeStore: React.FC = () => {
try {
if (!checkLogin(settings.user)) return;
+ // Set the pipe status to in_progress so the user gets feedback in the UI
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id
+ ? {
+ ...p,
+ installed_config: {
+ ...p.installed_config!,
+ buildStatus: "in_progress",
+ },
+ }
+ : p,
+ ),
+ );
+
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) {
+ // Reset the status if no update is available
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id
+ ? {
+ ...p,
+ installed_config: {
+ ...p.installed_config!,
+ buildStatus: "success",
+ },
+ }
+ : p,
+ ),
+ );
+
toast({
title: "no update available",
description: "the pipe is already up to date",
@@ -854,6 +901,14 @@ export const PipeStore: React.FC = () => {
),
});
+ const windows = await getAllWindows();
+ console.log("windows", windows, pipe);
+ const window = windows.find((w) => w.label === pipe.name);
+ console.log("window", window);
+ if (window) {
+ window.close();
+ }
+
const response = await fetch(
`http://localhost:3030/pipes/update-version`,
{
@@ -865,11 +920,25 @@ export const PipeStore: React.FC = () => {
pipe_id: pipe.name,
source: responseDownload.download_url,
}),
- }
+ },
);
const data = await response.json();
if (!data.success) {
+ // Set status to error if update fails
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id
+ ? {
+ ...p,
+ installed_config: {
+ ...p.installed_config!,
+ buildStatus: "error",
+ },
+ }
+ : p,
+ ),
+ );
throw new Error(data.error);
}
@@ -888,9 +957,28 @@ export const PipeStore: React.FC = () => {
await fetchInstalledPipes();
+ // Update the available updates state
+ setAvailableUpdates((prev) => prev.filter((p) => p.id !== pipe.id));
+
t.dismiss();
} catch (error) {
console.error("failed to update pipe:", error);
+
+ // Set status to error if update fails
+ setPipes((prevPipes) =>
+ prevPipes.map((p) =>
+ p.id === pipe.id
+ ? {
+ ...p,
+ installed_config: {
+ ...p.installed_config!,
+ buildStatus: "error",
+ },
+ }
+ : p,
+ ),
+ );
+
toast({
title: "error updating pipe",
description: "please try again or check the logs for more information.",
@@ -939,40 +1027,42 @@ export const PipeStore: React.FC = () => {
}
};
- useEffect(() => {
- fetchStorePlugins();
- }, [installedPipes, purchaseHistory]);
-
- useEffect(() => {
- fetchPurchaseHistory();
- }, [settings.user.token]);
-
- useEffect(() => {
- fetchInstalledPipes();
- }, [health]);
-
- useEffect(() => {
- const interval = setInterval(() => {
- fetchInstalledPipes();
- }, 3000);
- return () => clearInterval(interval);
- }, []);
+ // Define the checkForUpdates function before it's used
+ const checkForUpdates = useCallback(
+ async (silent: boolean = false) => {
+ setIsUpdating(true);
+ console.log(
+ "[pipe-update] checkForUpdates called at",
+ new Date().toISOString(),
+ );
- useEffect(() => {
- const checkForUpdates = async () => {
- if (!settings.user.token) {
+ if (!settings.user?.token) {
console.log("[pipe-update] Update check skipped: No user token");
+ toast({
+ title: "error checking for updates",
+ description: "please login to check for updates",
+ variant: "destructive",
+ });
+ setIsUpdating(true)
return;
}
// Get last check time from local storage
- const lastCheckTime = await localforage.getItem<number>(
- "lastUpdateCheck"
- );
+ 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) {
- console.log("[pipe-update] Skipping check - last check was less than 5 minutes ago");
+ if (lastCheckTime && now - lastCheckTime < 5 * 60 * 1000 && !silent) {
+ console.log(
+ "[pipe-update] Skipping check - last check was less than 5 minutes ago",
+ "Last check:",
+ new Date(lastCheckTime).toISOString(),
+ "Now:",
+ new Date(now).toISOString(),
+ "Diff (minutes):",
+ (now - lastCheckTime) / (60 * 1000),
+ );
+ setIsUpdating(false);
return;
}
@@ -981,7 +1071,7 @@ export const PipeStore: React.FC = () => {
console.log("[pipe-update] Checking for updates...");
const installedPipes = pipes.filter(
- (pipe) => pipe.is_installed && pipe.installed_config?.version
+ (pipe) => pipe.is_installed && pipe.installed_config?.version,
);
// Skip if no pipes to check
@@ -989,45 +1079,132 @@ export const PipeStore: React.FC = () => {
console.log("[pipe-update] No installed pipes to check");
return;
}
-
+
try {
// Format pipes for batch update check
const pluginsToCheck = installedPipes.map((pipe) => ({
pipe_id: pipe.id,
version: pipe.installed_config!.version!,
}));
-
- console.log("[pipe-update] Sending update check request:", pluginsToCheck);
-
+
+ console.log(
+ "[pipe-update] Sending update check request:",
+ pluginsToCheck,
+ );
+
const storeApi = await PipeApi.create(settings.user.token);
const updates = await storeApi.checkUpdates(pluginsToCheck);
-
+
console.log("[pipe-update] Update check response:", updates);
-
- // Process updates
- for (const pipe of installedPipes) {
+
+ // Process updates - only mark them as having updates, don't auto-update
+ const pipesWithUpdates: PipeWithStatus[] = [];
+
+ // Create a new array with updated pipe information
+ const updatedPipes = pipes.map((pipe) => {
const update = updates.results.find((u) => u.pipe_id === pipe.id);
- console.log(`[pipe-update] Update check for ${pipe.name}:`, update);
- if (update && "has_update" in update && update.has_update) {
+ const hasUpdate =
+ update && "has_update" in update && update.has_update;
+
+ if (hasUpdate) {
console.log(`[pipe-update] Update available for ${pipe.name}`);
+ pipesWithUpdates.push(pipe);
+ // Return a new object with has_update set to true
+ return { ...pipe, has_update: true };
+ }
+
+ return pipe;
+ });
+
+ // Update the pipes state with the new information
+ setPipes(updatedPipes);
+
+ // Update the available updates state
+ setAvailableUpdates(pipesWithUpdates);
+
+ // If auto-update is enabled and there are updates, update all pipes
+ console.log("autoUpdatePipes", settings.autoUpdatePipes);
+ if (settings.autoUpdatePipes && pipesWithUpdates.length > 0) {
+ console.log("autoUpdatePipes", settings.autoUpdatePipes);
+ for (const pipe of pipesWithUpdates) {
await handleUpdatePipe(pipe);
- } else {
- console.log(`[pipe-update] No update needed for ${pipe.name}`);
}
+ } else if (pipesWithUpdates.length > 0 && !silent) {
+ // Show a notification to the user
+ toast({
+ title: "Updates available",
+ description: `Updates are available for ${pipesWithUpdates.length} pipe${pipesWithUpdates.length > 1 ? "s" : ""}.`,
+ duration: 5000,
+ });
}
+ setIsUpdating(false);
} catch (error) {
console.error("[pipe-update] Error checking for updates:", error);
+ setIsUpdating(false);
}
- };
+ },
+ [
+ settings.user,
+ pipes,
+ setPipes,
+ settings.autoUpdatePipes,
+ handleUpdateAllPipes,
+ ],
+ );
+
+ // Create a ref to store the latest version of checkForUpdates
+ const checkForUpdatesRef = React.useRef(checkForUpdates);
+
+ // Update the ref whenever checkForUpdates changes
+ useEffect(() => {
+ checkForUpdatesRef.current = checkForUpdates;
+ }, [checkForUpdates]);
- // Run check immediately
- checkForUpdates();
+ useEffect(() => {
+ fetchStorePlugins();
+ }, [installedPipes, purchaseHistory]);
+
+ useEffect(() => {
+ fetchPurchaseHistory();
+ }, [settings.user.token]);
- // Set up interval to check every 10 seconds actual check is done in the function
- const interval = setInterval(checkForUpdates, 10 * 1000);
+ useEffect(() => {
+ fetchInstalledPipes();
+ }, [health]);
+ useEffect(() => {
+ const interval = setInterval(() => {
+ fetchInstalledPipes();
+ }, 3000);
return () => clearInterval(interval);
- }, [settings.user.token, pipes]);
+ }, []);
+
+ // Add periodic update check
+ useEffect(() => {
+ // Define the update check interval (5 minutes in milliseconds)
+ const UPDATE_CHECK_INTERVAL = 5 * 60 * 1000;
+
+ // Run check immediately with a small delay to allow component to fully initialize
+ const initialCheckTimeout = setTimeout(
+ () => checkForUpdatesRef.current(),
+ 2000,
+ );
+
+ // Set up interval to check every 5 minutes
+ const interval = setInterval(
+ () => checkForUpdatesRef.current(),
+ UPDATE_CHECK_INTERVAL,
+ );
+
+ console.log(
+ `[pipe-update] Set up update check interval: ${UPDATE_CHECK_INTERVAL}ms (${UPDATE_CHECK_INTERVAL / (60 * 1000)} minutes)`,
+ );
+
+ return () => {
+ clearTimeout(initialCheckTimeout);
+ clearInterval(interval);
+ };
+ }, []); // Empty dependency array
useEffect(() => {
const setupDeepLink = async () => {
@@ -1080,6 +1257,49 @@ export const PipeStore: React.FC = () => {
};
}, [pipes]);
+ // Update the event listener effect to use the memoized functions
+ useEffect(() => {
+ const unsubscribePromise = listen("update-all-pipes", async () => {
+ try {
+ if (!checkLogin(settings.user, false)) return;
+
+ // If auto-update is enabled, update all pipes
+ if (settings.autoUpdatePipes) {
+ // Filter pipes that need updates
+ const pipesToUpdate = pipes.filter(
+ (pipe) => pipe.is_installed && pipe.has_update,
+ );
+
+ if (pipesToUpdate.length === 0) {
+ console.log("No updates available for any pipes");
+ return;
+ }
+
+ console.log(`Found ${pipesToUpdate.length} pipes to update`);
+
+ for (const pipe of pipesToUpdate) {
+ try {
+ await handleUpdatePipe(pipe);
+ } catch (error) {
+ console.error(`Failed to update pipe ${pipe.name}:`, error);
+ }
+ }
+
+ await fetchInstalledPipes();
+ } else {
+ // Just check for updates but don't install them
+ await checkForUpdatesRef.current(true);
+ }
+ } catch (error) {
+ console.error("Error in update-all-pipes handler:", error);
+ }
+ });
+
+ return () => {
+ unsubscribePromise.then((unsubscribe) => unsubscribe());
+ };
+ }, [pipes, settings.user, settings.autoUpdatePipes, fetchInstalledPipes]);
+
if (health?.status === "error") {
return (
<div className="flex flex-col items-center justify-center h-screen p-4 space-y-4">
@@ -1144,132 +1364,183 @@ export const PipeStore: React.FC = () => {
}
return (
- <div className="overflow-hidden flex flex-col space-y-4">
- <div className="flex flex-col flex-1 overflow-hidden space-y-4 p-4">
- <div className="space-y-4">
- <div className="flex flex-col gap-4 md:w-[50%] w-full">
- <div className="flex-1 relative py-2">
- <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>
+ <div className="flex flex-col h-full mt-5 p-5">
+ <div className="flex flex-col md:flex-row sm:items-center justify-between gap-4 mb-4">
+ <div className="flex items-center space-x-2 flex-wrap gap-2">
+ <Input
+ placeholder="search pipes..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full sm:w-64"
+ />
+ <div className="flex items-center space-x-2">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => setConfirmOpen(true)}
+ className="flex items-center gap-2"
+ disabled={isPurging}
+ >
+ <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={() => setShowInstalledOnly(!showInstalledOnly)}
+ >
+ <HardDriveDownload
+ className={cn(
+ "h-4 w-4",
+ showInstalledOnly && "text-green-500",
+ )}
+ />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>
+ {showInstalledOnly
+ ? "showing installed pipes only"
+ : "showing all pipes"}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ <div className="flex items-center space-x-2 mt-2 sm:mt-0">
+ {availableUpdates.length > 0 && (
+ <Popover
+ open={updatePopoverOpen}
+ onOpenChange={setUpdatePopoverOpen}
+ >
+ <PopoverTrigger asChild>
+ <Button variant="outline" className="relative">
+ <Download className="h-4 w-4 mr-2" />
+ <span className="hidden sm:inline">Updates</span>
+ <span className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs">
+ {availableUpdates.length}
+ </span>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[90vw] sm:w-[500px]">
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h4 className="font-medium">Available Updates</h4>
<Button
- variant="outline"
- size="icon"
- onClick={() => setConfirmOpen(true)}
- className="flex items-center gap-2"
- disabled={isPurging}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>reset all pipes</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>confirm deletion of all pipes?</DialogTitle>
- <DialogDescription>
- are you sure you want to delete all pipes? <br/> you&apos;ll have to download them again
- </DialogDescription>
- </DialogHeader>
- <div className="flex justify-end gap-4">
- <Button
- onClick={() => setConfirmOpen(false)}
- disabled={isPurging}
- variant={"outline"}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ handleUpdateAllPipes();
+ setUpdatePopoverOpen(false);
+ }}
>
- cancel
- </Button>
- <Button
- onClick={handleResetAllPipes}
- disabled={isPurging}
- >
- {isPurging ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- reseting all pipes...
- </>
- ) : (
- "confirm"
- )}
+ Update All
</Button>
</div>
- </DialogContent>
- </Dialog>
- <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 className="space-y-2 max-h-60 overflow-y-auto">
+ {availableUpdates.map((pipe) => (
+ <div
+ key={pipe.id}
+ className="flex items-center justify-between border p-2 rounded"
+ >
+ <div>
+ <p className="font-medium">{pipe.name}</p>
+ <p className="text-xs text-muted-foreground">
+ {pipe.installed_config?.version} → newer version
+ </p>
+ </div>
+ <Button
+ size="sm"
+ onClick={() => {
+ handleUpdatePipe(pipe);
+ }}
+ >
+ Update
+ </Button>
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center pt-2 border-t">
+ <Switch
+ id="auto-update-toggle"
+ checked={settings.autoUpdatePipes}
+ onCheckedChange={(checked) => {
+ updateSettings({ autoUpdatePipes: checked });
+ }}
+ className="mr-2"
+ />
+ <label htmlFor="auto-update-toggle" className="text-sm">
+ Auto-update pipes
+ </label>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ <Button
+ onClick={async () => {
+ const lastCheckTime =
+ await localforage.getItem("lastUpdateCheck");
+ if (lastCheckTime) {
+ await localforage.removeItem("lastUpdateCheck");
+ }
+ checkForUpdates();
+ }}
+ variant="outline"
+ className="whitespace-nowrap"
+ disabled={isUpdating}
+ >
+ <RefreshCw
+ className={cn("h-4 w-4 mr-2", isUpdating && "animate-spin")}
+ />
+ <span className="hidden sm:inline">Check for Updates</span>
+ <span className="inline sm:hidden">Check</span>
+ </Button>
</div>
+ </div>
- <div className="flex-1 overflow-y-auto">
- <div className="grid grid-cols-1 md: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 className="flex-1 overflow-y-auto">
+ <div className="grid grid-cols-1 md: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>
- <AddPipeForm
- onAddPipe={handleInstallSideload}
- isHealthy={health?.status !== "error"}
- onLoadFromLocalFolder={handleLoadFromLocalFolder}
- />
+ <div className="flex items-center justify-center my-4">
+ <AddPipeForm
+ onAddPipe={handleInstallSideload}
+ isHealthy={health?.status !== "error"}
+ onLoadFromLocalFolder={handleLoadFromLocalFolder}
+ />
+ </div>
</div>
</div>
);
diff --git a/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx b/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
index 362ec8379..c28ee38f2 100644
--- a/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
+++ b/screenpipe-app-tauri/components/pipe-store/pipe-card.tsx
@@ -125,7 +125,7 @@ export const PipeCard: React.FC<PipeCardProps> = ({
const data = await response.json();
console.log(data, pipe.installed_config?.buildStatus);
if (
- data.buildStatus.length > 0 &&
+ data.buildStatus?.length > 0 &&
JSON.stringify(data.buildStatus) !==
JSON.stringify(pipe.installed_config?.buildStatus)
) {
@@ -162,6 +162,15 @@ export const PipeCard: React.FC<PipeCardProps> = ({
let buildStatusInterval: NodeJS.Timeout | null = null;
const buildStatus = pipe.installed_config?.buildStatus;
+
+ const isUpdating =
+ buildStatus === "updating" ||
+ (typeof buildStatus === "object" && buildStatus.status === "updating");
+
+ if (isUpdating) {
+ return;
+ }
+
const isInProgress =
buildStatus === "in_progress" ||
(typeof buildStatus === "object" && buildStatus.status === "in_progress");
@@ -181,6 +190,22 @@ export const PipeCard: React.FC<PipeCardProps> = ({
const buildStatus = pipe.installed_config?.buildStatus;
const status = getBuildStatus(buildStatus);
+ if (status === "updating") {
+ 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>updating...</span>
+ </div>
+ </Button>
+ );
+ }
+
if (status === "not_started" || status === "in_progress") {
return (
<Button
diff --git a/screenpipe-app-tauri/components/pipe-store/types.ts b/screenpipe-app-tauri/components/pipe-store/types.ts
index 494bdd88b..265ab8fda 100644
--- a/screenpipe-app-tauri/components/pipe-store/types.ts
+++ b/screenpipe-app-tauri/components/pipe-store/types.ts
@@ -3,7 +3,7 @@ import { PipeStorePlugin } from "@/lib/api/store";
export type BuildStatus =
| string
| {
- status: "in_progress" | "error" | "success" | "not_started";
+ status: "in_progress" | "error" | "success" | "not_started" | "updating";
step: string;
progress?: number;
error?: string;
diff --git a/screenpipe-app-tauri/components/settings/general-settings.tsx b/screenpipe-app-tauri/components/settings/general-settings.tsx
index 6b5a3e256..ce1f2db8f 100644
--- a/screenpipe-app-tauri/components/settings/general-settings.tsx
+++ b/screenpipe-app-tauri/components/settings/general-settings.tsx
@@ -31,6 +31,22 @@ export default function GeneralSettings() {
}
/>
</div>
+
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h4 className="font-medium">auto-update pipes</h4>
+ <p className="text-sm text-muted-foreground">
+ automatically update pipes when updates are available
+ </p>
+ </div>
+ <Switch
+ id="auto-update-toggle"
+ checked={settings.autoUpdatePipes}
+ onCheckedChange={(checked) =>
+ handleSettingsChange({ autoUpdatePipes: checked })
+ }
+ />
+ </div>
</div>
</div>
);
diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 8c1b5725b..7ffdec231 100644
--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -132,6 +132,7 @@ export type Settings = {
useAllMonitors: boolean;
aiPresets: AIPreset[];
enableRealtimeVision: boolean;
+ autoUpdatePipes: boolean;
};
export const DEFAULT_PROMPT = `Rules:
@@ -199,7 +200,8 @@ const DEFAULT_SETTINGS: Settings = {
realtimeAudioTranscriptionEngine: "deepgram",
disableVision: false,
useAllMonitors: false,
- enableRealtimeVision: true,
+ enableRealtimeVision: false,
+ autoUpdatePipes: false, // Default to false for auto-updating pipes
};
const DEFAULT_IGNORED_WINDOWS_IN_ALL_OS = [
@@ -324,7 +326,8 @@ const tauriStorage: PersistStorage = {
// Set new flattened values
for (const [key, val] of Object.entries(flattenedValue)) {
if (!key || !key.length) continue;
- const defaultValue = key in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[key as keyof Settings] : "";
+ const defaultValue =
+ key in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[key as keyof Settings] : "";
await tauriStore.set(key, val === undefined ? defaultValue : val);
}
diff --git a/screenpipe-app-tauri/src-tauri/capabilities/main.json b/screenpipe-app-tauri/src-tauri/capabilities/main.json
index e650c8cb8..517f21103 100644
--- a/screenpipe-app-tauri/src-tauri/capabilities/main.json
+++ b/screenpipe-app-tauri/src-tauri/capabilities/main.json
@@ -45,6 +45,9 @@
"global-shortcut:default",
"sentry:default",
"opener:allow-open-url",
+ "core:window:default",
+ "core:window:allow-get-all-windows",
+ "core:window:allow-close",
{
"identifier": "fs:scope",
"allow": [
diff --git a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
index 30250083f..7d66de201 100644
--- a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
+++ b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","remote":{"urls":["http://localhost:*"]},"local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","shell:allow-open","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default","opener:allow-open-url",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":true,"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default","fs:allow-write-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPLOCALDATA"},{"path":"$APPLOCALDATA/**"}]},"opener:default","opener:default"]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","remote":{"urls":["http://localhost:*"]},"local":true,"windows":["*"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","shell:allow-open","store:default","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default","sentry:default","opener:allow-open-url","core:window:default","core:window:allow-get-all-windows","core:window:allow-close",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":true,"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","core:webview:allow-internal-toggle-devtools",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]},{"identifier":"http:default","allow":[{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"http://**/*"},{"methods":["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],"url":"https://**/*"}]},"deep-link:default","fs:allow-write-text-file",{"identifier":"fs:scope","allow":[{"path":"$APPLOCALDATA"},{"path":"$APPLOCALDATA/**"}]},"opener:default","opener:default"]}}
\ No newline at end of file
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 18212d980..c0cb4070d 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -584,17 +584,83 @@ impl PipeManager {
let config = tokio::fs::read_to_string(&pipe_json_path).await?;
let mut config: Value = serde_json::from_str(&config)?;
+ // Save the build status from the existing config
+ let build_status = config.get("buildStatus").cloned();
+ debug!("preserving build status: {:?}", build_status);
+
+ // Update build status to indicate update has started
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "preparing",
+ "message": "Starting update process"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// Create temp directory outside of pipes dir
- let tmp_dir = std::env::temp_dir().join(format!("screenpipe_update_{}", id));
+ let tmp_dir = std::env::temp_dir().join(format!("{}_update", id));
tokio::fs::create_dir_all(&tmp_dir).await?;
debug!("created temp dir: {:?}", tmp_dir);
+ // Update build status to indicate downloading
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "downloading",
+ "message": "Downloading new version"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// Download new version to temp directory
- let tmp_pipe_dir = download_pipe_private(id, source, tmp_dir.clone()).await?;
- debug!("downloaded new version to temp dir: {:?}", tmp_pipe_dir);
+ let tmp_pipe_dir = match download_pipe_private(id, source, tmp_dir.clone()).await {
+ Ok(dir) => {
+ debug!("downloaded new version to temp dir: {:?}", dir);
+ dir
+ },
+ Err(e) => {
+ // Update build status to indicate download failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "downloading",
+ "error": format!("Failed to download: {}", e)
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ return Err(anyhow::anyhow!("failed to download new version: {}", e));
+ }
+ };
// Verify temp directory exists and contains the pipe files
if !tmp_pipe_dir.exists() {
+ // Update build status to indicate verification failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "verification",
+ "message": "Temp pipe directory not found"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
error!("temp pipe directory not found: {:?}", tmp_pipe_dir);
return Err(anyhow::anyhow!(
"temp pipe directory not found: {:?}",
@@ -602,13 +668,75 @@ impl PipeManager {
));
}
+ // Update build status to indicate extracting version
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "extracting version",
+ "message": "Extracting version information"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// Get version from new pipe.json in temp dir
let new_pipe_package_json_path = tmp_pipe_dir.join("package.json");
- let new_config = tokio::fs::read_to_string(&new_pipe_package_json_path)
- .await
- .map_err(|e| anyhow::anyhow!("failed to read new package.json: {}", e))?;
- let new_config: Value = serde_json::from_str(&new_config)
- .map_err(|e| anyhow::anyhow!("failed to parse new package.json: {}", e))?;
+ let new_config = match tokio::fs::read_to_string(&new_pipe_package_json_path).await {
+ Ok(content) => {
+ match serde_json::from_str::<Value>(&content) {
+ Ok(config) => config,
+ Err(e) => {
+ // Update build status to indicate parsing failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "extracting version",
+ "error": format!("Failed to parse package.json: {}", e)
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ return Err(anyhow::anyhow!("failed to parse new package.json: {}", e));
+ }
+ }
+ },
+ Err(e) => {
+ // Update build status to indicate reading failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "extracting version",
+ "error": format!("Failed to read package.json: {}", e)
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ return Err(anyhow::anyhow!("failed to read new package.json: {}", e));
+ }
+ };
+
+ // Update build status to indicate stopping pipe
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "stopping pipe",
+ "message": "Stopping current pipe"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
// Update version in existing config
if let Some(new_version) = new_config.get("version").and_then(Value::as_str) {
@@ -617,22 +745,48 @@ impl PipeManager {
"version".to_string(),
Value::String(new_version.to_string()),
);
+
// Write updated config back to file
- let updated_config = serde_json::to_string_pretty(&config)
- .map_err(|e| anyhow::anyhow!("failed to serialize updated config: {}", e))?;
- tokio::fs::write(&pipe_json_path, updated_config)
- .await
- .map_err(|e| anyhow::anyhow!("failed to write updated config: {}", e))?;
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
debug!("updated version in pipe.json to: {}", new_version);
}
}
// 2. Stop current pipe if running
- self.stop_pipe(id)
- .await
- .map_err(|e| anyhow::anyhow!("failed to stop pipe: {}", e))?;
+ if let Err(e) = self.stop_pipe(id).await {
+ // Update build status to indicate stopping failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "stopping pipe",
+ "error": format!("Failed to stop pipe: {}", e)
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ warn!("failed to stop pipe: {}", e);
+ // Continue with update despite stopping failure
+ }
debug!("stopped running pipe");
+ // Update build status to indicate removing old files
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "removing old files",
+ "message": "Removing old files"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// 3. Remove old files
let files_to_remove = ["node_modules", "bun.lockb", "package.json"];
for file in files_to_remove {
@@ -649,6 +803,20 @@ impl PipeManager {
debug!("moved old files to trash");
+ // Update build status to indicate copying new files
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "copying new files",
+ "message": "Copying new files"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// 4. Move new files from temp to pipe dir
let mut entries = tokio::fs::read_dir(&tmp_pipe_dir).await?;
while let Some(entry) = entries.next_entry().await? {
@@ -681,15 +849,76 @@ impl PipeManager {
tokio::fs::remove_dir_all(&tmp_dir).await?;
debug!("cleaned up temp dir");
+ // Update build status to indicate restarting pipe
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "in_progress",
+ "step": "restarting",
+ "message": "Restarting pipe"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+
// 5. Restart pipe if it was enabled
if config
.get("enabled")
.and_then(Value::as_bool)
.unwrap_or(false)
{
- let future = self.start_pipe_task(id.to_string()).await?;
- tokio::spawn(future);
- debug!("restarted pipe");
+ match self.start_pipe_task(id.to_string()).await {
+ Ok(future) => {
+ tokio::spawn(future);
+ debug!("restarted pipe");
+
+ // Update build status to indicate success
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "success",
+ "step": "completed",
+ "message": "Update completed successfully"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ },
+ Err(e) => {
+ // Update build status to indicate restart failure
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "error",
+ "step": "restarting",
+ "error": format!("Update completed but failed to restart pipe: {}", e)
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
+ warn!("failed to restart pipe: {}", e);
+ }
+ }
+ } else {
+ // Update build status to indicate success (no restart needed)
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "buildStatus".to_string(),
+ serde_json::json!({
+ "status": "success",
+ "step": "completed",
+ "message": "Update completed successfully (pipe not enabled)"
+ }),
+ );
+ let updated_config = serde_json::to_string_pretty(&config)?;
+ tokio::fs::write(&pipe_json_path, updated_config).await?;
+ }
}
info!("pipe {} updated successfully", id);
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 8aa2ff369..215651e6c 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -2517,65 +2517,131 @@ async fn get_pipe_build_status(
State(state): State<Arc<AppState>>,
) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
let pipe_dir = state.screenpipe_dir.join("pipes").join(&pipe_id);
+ let update_temp_dir = std::env::temp_dir().join(format!("{}_update", 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)
+
+ // 1. First check if the update temp directory exists
+ if update_temp_dir.exists() {
+ debug!("Update temp directory exists for pipe: {}", pipe_id);
+
+ // Check if there's a pipe.json in the update temp directory
+ let update_pipe_json_path = update_temp_dir.join("pipe.json");
+ if update_pipe_json_path.exists() {
+ let pipe_json = tokio::fs::read_to_string(&update_pipe_json_path)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(
- json!({"error": format!("Failed to read temp pipe config: {}", e)}),
- ),
+ JsonResponse(json!({"error": format!("Failed to read update 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)}),
- ),
+ JsonResponse(json!({"error": format!("Failed to parse update 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 })));
+ // Return the buildStatus if it exists
+ if let Some(build_status) = pipe_config.get("buildStatus") {
+ debug!("Found build status in update temp directory for pipe: {}", pipe_id);
+ return Ok(JsonResponse(build_status.clone()));
+ }
}
+
+ // If no buildStatus found in update temp directory, return a default in_progress status
+ return Ok(JsonResponse(json!({
+ "status": "in_progress",
+ "step": "downloading",
+ "message": "Update in progress"
+ })));
}
- // 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() {
+ // 2. Check if the pipe directory exists
+ if pipe_dir.exists() {
+ // Then check if there's a pipe.json file
+ let pipe_json_path = pipe_dir.join("pipe.json");
+ if pipe_json_path.exists() {
+ 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)})),
+ )
+ })?;
+
+ // Check if there's a buildStatus field
+ if let Some(build_status) = pipe_config.get("buildStatus") {
+ // Return the build status directly
+ return Ok(JsonResponse(build_status.clone()));
+ }
+ } else {
+ // Pipe directory exists but pipe.json doesn't exist yet
+ // This likely means the pipe is still being created
+ debug!("Pipe directory exists but pipe.json not found for pipe: {}", pipe_id);
+ return Ok(JsonResponse(json!({
+ "status": "in_progress",
+ "step": "creating_config",
+ "message": "Creating pipe configuration"
+ })));
+ }
+ } else {
+ // If pipe directory doesn't exist, check temp directory
+ 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)}),
+ ),
+ )
+ })?;
+
+ debug!("Found build status in temp directory for pipe: {}", pipe_id);
+ if let Some(build_status) = pipe_config.get("buildStatus") {
+ return Ok(JsonResponse(build_status.clone()));
+ }
+ }
+
+ // Temp directory exists but no pipe.json or no buildStatus
+ return Ok(JsonResponse(json!({
+ "status": "in_progress",
+ "step": "initializing",
+ "message": "Initializing pipe"
+ })));
+ }
+
+ // If neither pipe directory nor temp directory exists, return not found
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 })))
+ // If we get here, there's a pipe.json but no buildStatus field
+ Ok(JsonResponse(json!(null)))
}
#[oasgen]