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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: replace local backup rollback with R2 version picker
Louis Beaumont72d9efb6a170
diff --git a/apps/screenpipe-app-tauri/components/__tests__/text-overlay.test.tsx b/apps/screenpipe-app-tauri/components/__tests__/text-overlay.test.tsxindex 40b7c8c1e..9f53c34bd 100644--- a/apps/screenpipe-app-tauri/components/__tests__/text-overlay.test.tsx+++ b/apps/screenpipe-app-tauri/components/__tests__/text-overlay.test.tsx@@ -59,7 +59,7 @@ describe("TextOverlay", () => {expect(container.firstChild).toBeNull();});- it("should render selectable text spans when selectable", () => {+ it("should render clickable text blocks when selectable", () => {const positions = [createTextPosition("Hello world", 0.1, 0.05, 0.2, 0.02),];@@ -74,8 +74,9 @@ describe("TextOverlay", () => {/>);expect(container.firstChild).not.toBeNull();- // The text should be present in the DOM (invisible but selectable)- expect(container.textContent).toContain("Hello world");+ // Should have clickable block divs (one per text position)+ const blocks = container.querySelectorAll('[style*="pointer"]');+ expect(blocks.length).toBeGreaterThan(0);});it("should render a whole-block URL as clickable link", () => {diff --git a/apps/screenpipe-app-tauri/components/settings/general-settings.tsx b/apps/screenpipe-app-tauri/components/settings/general-settings.tsxindex 4ac49d9bc..42ff16eeb 100644--- a/apps/screenpipe-app-tauri/components/settings/general-settings.tsx+++ b/apps/screenpipe-app-tauri/components/settings/general-settings.tsx@@ -21,12 +21,12 @@ export default function GeneralSettings() {const { theme, setTheme } = useTheme();const { toast } = useToast();const [currentVersion, setCurrentVersion] = useState<string | null>(null);- const [rollbackVersion, setRollbackVersion] = useState<string | null>(null);+ const [availableVersions, setAvailableVersions] = useState<string[]>([]);const [isRollingBack, setIsRollingBack] = useState(false);+ const [showVersions, setShowVersions] = useState(false);useEffect(() => {getVersion().then(setCurrentVersion).catch(() => {});- invoke<string | null>("get_rollback_version").then(setRollbackVersion).catch(() => {});}, []);const handleSettingsChange = (newSettings: Partial<Settings>) => {@@ -56,16 +56,40 @@ export default function GeneralSettings() {},];- const handleRollback = async () => {- if (!rollbackVersion || isRollingBack) return;+ const fetchVersions = async () => {+ if (availableVersions.length > 0) {+ setShowVersions(!showVersions);+ return;+ }+ try {+ // Detect target arch+ const { arch, type: osType } = await import("@tauri-apps/plugin-os").then(m => ({ arch: m.arch(), type: m.type() }));+ let targetArch = "darwin-aarch64";+ if (osType === "macos") targetArch = arch === "x86_64" ? "darwin-x86_64" : "darwin-aarch64";+ else if (osType === "windows") targetArch = "windows-x86_64";++ const resp = await fetch(`https://screenpi.pe/api/app-update/versions/${targetArch}`);+ if (!resp.ok) throw new Error("failed to fetch versions");+ const data = await resp.json();+ // Filter out current version+ const versions = (data.versions || []).filter((v: string) => v !== currentVersion);+ setAvailableVersions(versions);+ setShowVersions(true);+ } catch (e: any) {+ toast({ title: "failed to load versions", description: e?.toString(), variant: "destructive" });+ }+ };++ const handleRollback = async (version: string) => {+ if (isRollingBack) return;setIsRollingBack(true);try {toast({- title: "rolling back...",- description: `restoring v${rollbackVersion}. the app will restart.`,- duration: 5000,+ title: "downloading...",+ description: `installing v${version}. this is at your own risk — db migrations are not reversed.`,+ duration: 10000,});- await invoke("rollback_to_previous_version");+ await invoke("rollback_to_version", { version });} catch (e: any) {setIsRollingBack(false);toast({@@ -156,24 +180,41 @@ export default function GeneralSettings() {Version{currentVersion ? ` ${currentVersion}` : ""}</h3><p className="text-xs text-muted-foreground">- {rollbackVersion && rollbackVersion !== currentVersion- ? `previous: v${rollbackVersion}`- : "no previous version saved yet"}+ install a previous version (at your own risk)</p></div></div>- {rollbackVersion && rollbackVersion !== currentVersion && (- <Button- variant="outline"- size="sm"- onClick={handleRollback}- disabled={isRollingBack}- className="ml-4 h-7 text-xs"- >- {isRollingBack ? "rolling back..." : `rollback to v${rollbackVersion}`}- </Button>- )}+ <Button+ variant="outline"+ size="sm"+ onClick={fetchVersions}+ disabled={isRollingBack}+ className="ml-4 h-7 text-xs"+ >+ {isRollingBack ? "installing..." : showVersions ? "hide" : "show versions"}+ </Button></div>+ {showVersions && availableVersions.length > 0 && (+ <div className="mt-3 space-y-1 border-t pt-2">+ <p className="text-[10px] text-muted-foreground mb-2">+ ⚠️ database migrations are not reversed. use at your own risk.+ </p>+ {availableVersions.map((v) => (+ <div key={v} className="flex items-center justify-between py-0.5">+ <span className="text-xs text-muted-foreground">v{v}</span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => handleRollback(v)}+ disabled={isRollingBack}+ className="h-6 text-[11px] px-2"+ >+ install+ </Button>+ </div>+ ))}+ </div>+ )}</CardContent></Card>diff --git a/apps/screenpipe-app-tauri/components/text-overlay.tsx b/apps/screenpipe-app-tauri/components/text-overlay.tsxindex a82d2f858..389c8af46 100644--- a/apps/screenpipe-app-tauri/components/text-overlay.tsx+++ b/apps/screenpipe-app-tauri/components/text-overlay.tsx@@ -8,7 +8,7 @@ import { cn } from "@/lib/utils";import { open as shellOpen } from "@tauri-apps/plugin-shell";import { commands } from "@/lib/utils/tauri";import type { TextPosition } from "@/lib/hooks/use-frame-ocr-data";-import { Copy, Check } from "lucide-react";+import { Check } from "lucide-react";/*** Check if a string looks like a URL.@@ -199,8 +199,7 @@ export const TextOverlay = memo(function TextOverlay({}: TextOverlayProps) {const [hoveredLinkIndex, setHoveredLinkIndex] = useState<number | null>(null);const [hoveredBlockIndex, setHoveredBlockIndex] = useState<number | null>(null);- const [copiedIndex, setCopiedIndex] = useState<number | null>(null); // -1 = "copy all"- const [showCopyAll, setShowCopyAll] = useState(false);+ const [copiedIndex, setCopiedIndex] = useState<number | null>(null);// Compute pixel-positioned blocks for the text layerconst textBlocks = useMemo(() => {@@ -338,26 +337,21 @@ export const TextOverlay = memo(function TextOverlay({[]);- const copyText = useCallback((text: string, feedbackIndex: number) => {- navigator.clipboard.writeText(text).catch(() => {});- setCopiedIndex(feedbackIndex);+ const flashCopied = useCallback((index: number) => {+ setCopiedIndex(index);setTimeout(() => setCopiedIndex(null), 1200);}, []);- const handleCopyAll = useCallback(() => {- // Sort blocks in reading order (top to bottom, left to right)- const sorted = [...textPositions]- .filter(p => p.confidence >= minConfidence && p.text.trim().length > 0)- .sort((a, b) => {- const dy = a.bounds.top - b.bounds.top;- if (Math.abs(dy) < Math.min(a.bounds.height, b.bounds.height) * 0.5) {- return a.bounds.left - b.bounds.left;- }- return dy;- });- const text = sorted.map(p => p.text).join("\n");- copyText(text, -1);- }, [textPositions, minConfidence, copyText]);+ const handleBlockClick = useCallback((blockIndex: number, e: React.MouseEvent) => {+ e.stopPropagation();+ const block = textBlocks.find(b => b.index === blockIndex);+ if (block) {+ navigator.clipboard.writeText(block.text).catch(() => {});+ flashCopied(blockIndex);+ }+ }, [textBlocks, flashCopied]);++const hasContent =(clickableUrls && urlLinks.length > 0) ||@@ -376,8 +370,7 @@ export const TextOverlay = memo(function TextOverlay({height: displayedHeight,pointerEvents: "none",}}- onMouseEnter={() => setShowCopyAll(true)}- onMouseLeave={() => { setShowCopyAll(false); setHoveredBlockIndex(null); }}+ onMouseLeave={() => { setHoveredBlockIndex(null); }}>{/* Search term highlights */}{highlights.map((hl) => (@@ -412,17 +405,12 @@ export const TextOverlay = memo(function TextOverlay({cursor: "pointer",pointerEvents: "auto",backgroundColor: isCopied- ? "rgba(74, 222, 128, 0.25)"+ ? "rgba(255, 255, 255, 0.25)": isHovered- ? "rgba(59, 130, 246, 0.18)"+ ? "rgba(255, 255, 255, 0.10)": "transparent",- border: isCopied- ? "1px solid rgba(74, 222, 128, 0.6)"- : isHovered- ? "1px solid rgba(59, 130, 246, 0.4)"- : "1px solid transparent",borderRadius: "2px",- transition: "background-color 0.1s, border-color 0.1s",+ transition: "background-color 0.15s",...(debug? {backgroundColor: "rgba(0, 255, 0, 0.1)",@@ -432,11 +420,7 @@ export const TextOverlay = memo(function TextOverlay({}}onMouseEnter={() => setHoveredBlockIndex(block.index)}onMouseLeave={() => setHoveredBlockIndex(null)}- onClick={(e) => {- e.stopPropagation();- copyText(block.text, block.index);- }}- title={block.text}+ onClick={(e) => handleBlockClick(block.index, e)}/>);})}@@ -503,42 +487,23 @@ export const TextOverlay = memo(function TextOverlay({</a>);})}- {/* "Copy all text" button — top-right corner, shown on hover */}- {selectable && textBlocks.length > 0 && (showCopyAll || copiedIndex === -1) && (- <button- className="absolute flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium shadow-lg transition-all"+ {/* "Copied" floating toast */}+ {copiedIndex !== null && (+ <div+ className="absolute pointer-events-none flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium shadow-lg"style={{top: 8,- right: 8,- zIndex: 20,- pointerEvents: "auto",- backgroundColor: copiedIndex === -1- ? "rgba(74, 222, 128, 0.9)"- : "rgba(0, 0, 0, 0.75)",- color: copiedIndex === -1- ? "rgba(0, 0, 0, 0.9)"- : "rgba(255, 255, 255, 0.9)",+ left: "50%",+ transform: "translateX(-50%)",+ zIndex: 30,+ backgroundColor: "rgba(0, 0, 0, 0.85)",+ color: "rgba(255, 255, 255, 0.9)",border: "1px solid rgba(255, 255, 255, 0.15)",- backdropFilter: "blur(8px)",- }}- onClick={(e) => {- e.stopPropagation();- handleCopyAll();}}- title="Copy all text from this screenshot">- {copiedIndex === -1 ? (- <>- <Check className="w-3.5 h-3.5" />- copied!- </>- ) : (- <>- <Copy className="w-3.5 h-3.5" />- copy all text- </>- )}- </button>+ <Check className="w-3.5 h-3.5" />+ copied+ </div>)}</div>);diff --git a/apps/screenpipe-app-tauri/components/update-banner.tsx b/apps/screenpipe-app-tauri/components/update-banner.tsxindex 2d061364d..9912f077d 100644--- a/apps/screenpipe-app-tauri/components/update-banner.tsx+++ b/apps/screenpipe-app-tauri/components/update-banner.tsx@@ -103,12 +103,7 @@ export function UpdateBanner({ className, compact = false }: UpdateBannerProps)}if (update?.available) {- // Backup before installing- try {- await invoke("backup_current_app");- } catch (e) {- console.warn("rollback backup failed, continuing with update:", e);- }+await update.downloadAndInstall();diff --git a/apps/screenpipe-app-tauri/components/updater.tsx b/apps/screenpipe-app-tauri/components/updater.tsxindex bf641ee6f..4647648bc 100644--- a/apps/screenpipe-app-tauri/components/updater.tsx+++ b/apps/screenpipe-app-tauri/components/updater.tsx@@ -104,13 +104,7 @@ Release notes: ${update.body}});try {- // Back up current app bundle before replacing it (for rollback)- try {- await invoke("backup_current_app");- } catch (_) {- // Non-fatal — proceed with update even if backup fails- console.warn("rollback backup failed, continuing with update");- }+await update.downloadAndInstall((event: any) => {if (event?.event === "progress") {const pct = event.data?.contentLengthdiff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex efce17fa6..ebcfd151f 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -251,28 +251,17 @@ async unregisterWindowShortcuts() : Promise<Result<null, string>> {}},/**- * Get the version of the backed-up app (if any), so the UI can show a rollback button+ * Install a specific older version from R2. Downloads and installs via Tauri updater,+ * then restarts the app.*/-async getRollbackVersion() : Promise<string | null> {- return await TAURI_INVOKE("get_rollback_version");-},-/**- * Roll back to the previous version. Spawns a helper script, then the app must quit.- */-async rollbackToPreviousVersion() : Promise<Result<null, string>> {+async rollbackToVersion(version: string) : Promise<Result<null, string>> {try {- return { status: "ok", data: await TAURI_INVOKE("rollback_to_previous_version") };+ return { status: "ok", data: await TAURI_INVOKE("rollback_to_version", { version }) };} catch (e) {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}},-/**- * Back up the current app bundle (called from frontend before JS-driven updates)- */-async backupCurrentApp() : Promise<void> {- await TAURI_INVOKE("backup_current_app");-},async setTrayUnhealthIcon() : Promise<void> {await TAURI_INVOKE("set_tray_unhealth_icon");},@@ -406,7 +395,7 @@ async piInfo() : Promise<Result<PiInfo, string>> {}},/**- * Start the Pi sidecar in RPC mode+ * Start the Pi sidecar in RPC mode (Tauri command wrapper)*/async piStart(projectDir: string, userToken: string | null, providerConfig: PiProviderConfig | null) : Promise<Result<PiInfo, string>> {try {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rsindex 8eddd6417..2c48dbd80 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs@@ -793,28 +793,16 @@ pub fn unregister_window_shortcuts(app_handle: tauri::AppHandle) -> Result<(), S-/// Get the version of the backed-up app (if any), so the UI can show a rollback button+/// Install a specific older version from R2. Downloads and installs via Tauri updater,+/// then restarts the app.#[tauri::command]#[specta::specta]-pub fn get_rollback_version() -> Option<String> {- crate::updates::rollback_version()-}--/// Back up the current app bundle (called from frontend before JS-driven updates)-#[tauri::command]-#[specta::specta]-pub fn backup_current_app() {- crate::updates::backup_current_app_cmd();-}--/// Roll back to the previous version. Spawns a helper script, then the app must quit.-#[tauri::command]-#[specta::specta]-pub async fn rollback_to_previous_version(+pub async fn rollback_to_version(app_handle: tauri::AppHandle,+ version: String,) -> Result<(), String> {use crate::RecordingState;- info!("rollback_to_previous_version: starting rollback");+ info!("rollback_to_version: installing v{}", version);// Stop recording firstif let Err(e) = crate::stop_screenpipe(@@ -822,15 +810,12 @@ pub async fn rollback_to_previous_version(app_handle.clone(),).await {error!("rollback: failed to stop recording: {}", e);- // Continue anyway — the rollback script will kill us}- // Perform the rollback (spawns helper script)- crate::updates::perform_rollback()?;+ // Download and install the target version+ crate::updates::install_specific_version(&app_handle, &version).await?;- // Quit the app so the helper script can replace the bundle- info!("rollback: quitting app for replacement");- app_handle.exit(0);- Ok(())+ info!("rollback: v{} installed, restarting", version);+ app_handle.restart();}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex e1fae9c03..824417d45 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -1109,9 +1109,7 @@ async fn main() {commands::register_window_shortcuts,commands::unregister_window_shortcuts,// Rollback commands- commands::get_rollback_version,- commands::rollback_to_previous_version,- commands::backup_current_app,+ commands::rollback_to_version,// Commands from tray.rsset_tray_unhealth_icon,set_tray_health_icon,@@ -1581,6 +1579,16 @@ async fn main() {.or_else(|| store_for_pi.ai_presets.first());if let Some(preset) = default_preset {+ // Normalize model name: old "pi" presets used hyphens (e.g. claude-haiku-4-5-20251001)+ // but screenpipe cloud expects @ separator (claude-haiku-4-5@20251001)+ let model = if matches!(preset.provider, crate::store::AIProviderType::Pi | crate::store::AIProviderType::ScreenpipeCloud) {+ // Fix known model name patterns: last hyphen before date → @+ preset.model.replace("4-5-2025", "4-5@2025")+ .replace("4-6-2025", "4-6@2025")+ } else {+ preset.model.clone()+ };+let provider_config = pi::PiProviderConfig {provider: match preset.provider {crate::store::AIProviderType::OpenAI => "openai".to_string(),@@ -1590,7 +1598,7 @@ async fn main() {crate::store::AIProviderType::Pi => "screenpipe-cloud".to_string(),},url: preset.url.clone(),- model: preset.model.clone(),+ model,api_key: preset.api_key.clone(),};@@ -1601,16 +1609,31 @@ async fn main() {let user_token = store_for_pi.user.token.clone();if let Some(pi_state) = app_handle_pi_boot.try_state::<pi::PiState>() {- info!("Auto-starting Pi agent with provider: {}, model: {}", provider_config.provider, provider_config.model);- match pi::pi_start(- app_handle_pi_boot.clone(),- pi_state,- project_dir,- user_token,- Some(provider_config),- ).await {- Ok(info) => info!("Pi auto-started successfully: {:?}", info),- Err(e) => warn!("Pi auto-start failed (non-fatal): {}", e),+ let pi_state_clone = pi_state.inner().clone();+ // Retry up to 3 times (Pi might still be installing)+ for attempt in 1..=3u32 {+ info!("Auto-starting Pi agent (attempt {}/3) with provider: {}, model: {}", attempt, provider_config.provider, provider_config.model);++ let result = pi::pi_start_inner(+ app_handle_pi_boot.clone(),+ &pi_state_clone,+ project_dir.clone(),+ user_token.clone(),+ Some(provider_config.clone()),+ ).await;++ match result {+ Ok(info) => {+ info!("Pi auto-started successfully: {:?}", info);+ break;+ }+ Err(e) => {+ warn!("Pi auto-start attempt {} failed: {}", attempt, e);+ if attempt < 3 {+ tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;+ }+ }+ }}}}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex ed1e6dcdf..e5e9cb2e1 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -57,6 +57,7 @@ const PI_PACKAGE: &str = "@mariozechner/pi-coding-agent";const SCREENPIPE_API_URL: &str = "https://api.screenpi.pe/v1";/// State for managing the Pi sidecar process+#[derive(Clone)]pub struct PiState(pub Arc<Mutex<Option<PiManager>>>);#[derive(Debug, Clone, Serialize, Deserialize, Type)]@@ -476,7 +477,7 @@ pub async fn pi_stop(state: State<'_, PiState>) -> Result<PiInfo, String> {}}-/// Start the Pi sidecar in RPC mode+/// Start the Pi sidecar in RPC mode (Tauri command wrapper)#[tauri::command]#[specta::specta]pub async fn pi_start(@@ -485,6 +486,17 @@ pub async fn pi_start(project_dir: String,user_token: Option<String>,provider_config: Option<PiProviderConfig>,+) -> Result<PiInfo, String> {+ pi_start_inner(app, &state, project_dir, user_token, provider_config).await+}++/// Core Pi start logic — callable from both Tauri commands and Rust boot code.+pub async fn pi_start_inner(+ app: AppHandle,+ state: &PiState,+ project_dir: String,+ user_token: Option<String>,+ provider_config: Option<PiProviderConfig>,) -> Result<PiInfo, String> {let project_dir = project_dir.trim().to_string();if project_dir.is_empty() {diff --git a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs b/apps/screenpipe-app-tauri/src-tauri/src/updates.rsindex 5a2e41667..ef7fd0555 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs@@ -10,7 +10,6 @@ use anyhow::Error;use dark_light::Mode;use log::{error, info, warn};use serde_json;-use std::path::PathBuf;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use std::time::Duration;@@ -26,326 +25,66 @@ use tokio::sync::Mutex;use tokio::time::interval;// ----------------------------------------------------------------------------// Rollback: backup current app bundle before updates, restore on demand+// Rollback: download a specific older version from R2 via the website API// ----------------------------------------------------------------------------/// Directory where we keep the previous version's app bundle-fn rollback_dir() -> Option<PathBuf> {- dirs::home_dir().map(|h| h.join(".screenpipe").join("rollback"))-}--/// Read the version string stored alongside the rollback backup-pub fn rollback_version() -> Option<String> {- let dir = rollback_dir()?;- let version_file = dir.join("version.txt");- std::fs::read_to_string(version_file).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())-}--/// Public wrapper for the Tauri command (frontend JS-driven updates)-pub fn backup_current_app_cmd() {- backup_current_app();-}--/// Back up the currently-running app bundle so we can rollback later.-/// Called right before `download_and_install`.-fn backup_current_app() {- let current_version = env!("CARGO_PKG_VERSION");-- #[cfg(target_os = "macos")]- {- // Resolve /Applications/screenpipe.app from the running binary- // Binary is at <app>/Contents/MacOS/screenpipe- let exe = match std::env::current_exe() {- Ok(p) => p,- Err(e) => { warn!("rollback: cannot resolve exe path: {}", e); return; }- };- // Walk up: MacOS -> Contents -> screenpipe.app- let app_bundle = match exe.parent().and_then(|p| p.parent()).and_then(|p| p.parent()) {- Some(p) => p.to_path_buf(),- None => { warn!("rollback: cannot derive .app bundle from exe"); return; }- };- if !app_bundle.exists() {- warn!("rollback: app bundle not found at {:?}", app_bundle);- return;- }- let dir = match rollback_dir() {- Some(d) => d,- None => return,- };- let dest = dir.join("screenpipe.app");- // Atomic-ish: copy to tmp dir first, then rename- let tmp_dest = dir.join("screenpipe.app.tmp");- // Clean up any leftovers- let _ = std::fs::remove_dir_all(&tmp_dest);- let _ = std::fs::remove_dir_all(&dest);- if let Err(e) = std::fs::create_dir_all(&dir) {- warn!("rollback: cannot create rollback dir: {}", e);- return;- }- info!("rollback: backing up {:?} -> {:?}", app_bundle, tmp_dest);- match copy_dir_recursive(&app_bundle, &tmp_dest) {- Ok(_) => {- if let Err(e) = std::fs::rename(&tmp_dest, &dest) {- warn!("rollback: rename failed: {}", e);- let _ = std::fs::remove_dir_all(&tmp_dest);- return;- }- if let Err(e) = std::fs::write(dir.join("version.txt"), current_version) {- warn!("rollback: failed to write version.txt: {}", e);- }- info!("rollback: backed up v{} successfully", current_version);- }- Err(e) => {- warn!("rollback: copy failed: {}", e);- let _ = std::fs::remove_dir_all(&tmp_dest);- }+/// Install a specific version from R2 via the Tauri updater.+/// The website's /rollback endpoint returns a manifest with a fake high version+/// so the updater accepts it as an "update".+pub async fn install_specific_version(app: &tauri::AppHandle, version: &str) -> Result<(), String> {+ let target_arch = get_target_arch();+ let rollback_url = format!(+ "https://screenpi.pe/api/app-update/rollback/{}/{}",+ target_arch, version+ );++ info!("rollback: installing v{} from {}", version, rollback_url);++ // Build updater pointed at our rollback endpoint+ let mut builder = app.updater_builder()+ .endpoints(vec![rollback_url.parse().map_err(|e| format!("invalid url: {}", e))?])+ .map_err(|e| format!("failed to build updater: {}", e))?;++ // Add auth header so R2 download works for paid users+ if let Ok(Some(settings)) = SettingsStore::get(app) {+ if let Some(ref token) = settings.user.token {+ builder = builder.header("Authorization", format!("Bearer {}", token))+ .map_err(|e| format!("failed to set auth header: {}", e))?;}}- #[cfg(target_os = "windows")]- {- // On Windows the Tauri updater replaces the exe in-place via NSIS/WiX.- // We back up the entire install directory.- let exe = match std::env::current_exe() {- Ok(p) => p,- Err(e) => { warn!("rollback: cannot resolve exe path: {}", e); return; }- };- let install_dir = match exe.parent() {- Some(p) => p.to_path_buf(),- None => return,- };- let dir = match rollback_dir() {- Some(d) => d,- None => return,- };- let dest = dir.join("app");- let tmp_dest = dir.join("app.tmp");- let _ = std::fs::remove_dir_all(&tmp_dest);- let _ = std::fs::remove_dir_all(&dest);- if let Err(e) = std::fs::create_dir_all(&dir) {- warn!("rollback: cannot create rollback dir: {}", e);- return;- }- info!("rollback: backing up {:?} -> {:?}", install_dir, tmp_dest);- match copy_dir_recursive(&install_dir, &tmp_dest) {- Ok(_) => {- if let Err(e) = std::fs::rename(&tmp_dest, &dest) {- warn!("rollback: rename failed: {}", e);- let _ = std::fs::remove_dir_all(&tmp_dest);- return;- }- if let Err(e) = std::fs::write(dir.join("version.txt"), current_version) {- warn!("rollback: failed to write version.txt: {}", e);- }- info!("rollback: backed up v{} successfully", current_version);- }- Err(e) => {- warn!("rollback: copy failed: {}", e);- let _ = std::fs::remove_dir_all(&tmp_dest);- }- }- }+ let update = builder.build()+ .map_err(|e| format!("failed to build updater: {}", e))?+ .check().await+ .map_err(|e| format!("failed to check rollback endpoint: {}", e))?+ .ok_or_else(|| "rollback endpoint returned no update (version may not exist)".to_string())?;- #[cfg(target_os = "linux")]- {- // AppImage: back up the AppImage file itself- if let Ok(appimage) = std::env::var("APPIMAGE") {- let src = PathBuf::from(&appimage);- if src.exists() {- let dir = match rollback_dir() {- Some(d) => d,- None => return,- };- if let Err(e) = std::fs::create_dir_all(&dir) {- warn!("rollback: cannot create rollback dir: {}", e);- return;- }- let dest = dir.join(src.file_name().unwrap_or_default());- info!("rollback: backing up {:?} -> {:?}", src, dest);- if let Err(e) = std::fs::copy(&src, &dest) {- warn!("rollback: copy failed: {}", e);- return;- }- if let Err(e) = std::fs::write(dir.join("version.txt"), current_version) {- warn!("rollback: failed to write version.txt: {}", e);- }- info!("rollback: backed up v{} successfully", current_version);- }- }- }-}+ info!("rollback: downloading v{}", version);-/// Recursively copy a directory-fn copy_dir_recursive(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {- std::fs::create_dir_all(dst)?;- for entry in std::fs::read_dir(src)? {- let entry = entry?;- let ty = entry.file_type()?;- let dest_path = dst.join(entry.file_name());- if ty.is_dir() {- copy_dir_recursive(&entry.path(), &dest_path)?;- } else if ty.is_symlink() {- let target = std::fs::read_link(entry.path())?;- #[cfg(unix)]- std::os::unix::fs::symlink(&target, &dest_path)?;- #[cfg(windows)]- {- if target.is_dir() {- std::os::windows::fs::symlink_dir(&target, &dest_path)?;- } else {- std::os::windows::fs::symlink_file(&target, &dest_path)?;- }- }- } else {- std::fs::copy(entry.path(), &dest_path)?;- }- }+ update.download_and_install(|_, _| {}, || {}).await+ .map_err(|e| format!("failed to download/install v{}: {}", version, e))?;++ info!("rollback: v{} installed, restart required", version);Ok(())}-/// Perform rollback: restore the backed-up app bundle and relaunch.-/// Returns an error string if something goes wrong.-pub fn perform_rollback() -> Result<(), String> {- let dir = rollback_dir().ok_or("cannot determine rollback directory")?;- let version = rollback_version().ok_or("no previous version available")?;-- #[cfg(target_os = "macos")]- {- let backup = dir.join("screenpipe.app");- if !backup.exists() {- return Err("rollback backup not found".into());- }- // Resolve current .app location- let exe = std::env::current_exe().map_err(|e| format!("cannot resolve exe: {}", e))?;- let current_app = exe.parent()- .and_then(|p| p.parent())- .and_then(|p| p.parent())- .ok_or("cannot derive .app from exe")?- .to_path_buf();-- info!("rollback: restoring v{} from {:?} -> {:?}", version, backup, current_app);-- // We can't replace ourselves while running. Spawn a helper script that:- // 1. Waits for us to quit- // 2. Replaces the .app bundle- // 3. Relaunches- let script = format!(- r#"#!/bin/bash-sleep 2-rm -rf "{current_app}"-cp -R "{backup}" "{current_app}"-open "{current_app}"-rm -f /tmp/screenpipe-rollback.sh-"#,- current_app = current_app.display(),- backup = backup.display(),- );- let script_path = "/tmp/screenpipe-rollback.sh";- std::fs::write(script_path, &script).map_err(|e| format!("failed to write rollback script: {}", e))?;- std::fs::set_permissions(script_path, std::os::unix::fs::PermissionsExt::from_mode(0o755))- .map_err(|e| format!("failed to chmod rollback script: {}", e))?;-- // Launch the script detached- std::process::Command::new("/bin/bash")- .arg(script_path)- .stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .spawn()- .map_err(|e| format!("failed to spawn rollback script: {}", e))?;-- info!("rollback: script spawned, app will quit now");- Ok(())- }-- #[cfg(target_os = "windows")]- {- let backup = dir.join("app");- if !backup.exists() {- return Err("rollback backup not found".into());- }- let exe = std::env::current_exe().map_err(|e| format!("cannot resolve exe: {}", e))?;- let install_dir = exe.parent().ok_or("cannot derive install dir")?.to_path_buf();- let exe_name = exe.file_name().ok_or("cannot get exe name")?.to_string_lossy().to_string();-- info!("rollback: restoring v{} from {:?} -> {:?}", version, backup, install_dir);-- // PowerShell script to replace files after process exits- let script = format!(- r#"Start-Sleep -Seconds 2-Remove-Item -Recurse -Force "{install_dir}\*"-Copy-Item -Recurse -Force "{backup}\*" "{install_dir}\"-Start-Process "{install_dir}\{exe_name}"-"#,- install_dir = install_dir.display(),- backup = backup.display(),- exe_name = exe_name,- );- let script_path = std::env::temp_dir().join("screenpipe-rollback.ps1");- std::fs::write(&script_path, &script).map_err(|e| format!("failed to write rollback script: {}", e))?;-- let mut rollback_cmd = std::process::Command::new("powershell");- rollback_cmd- .args(["-ExecutionPolicy", "Bypass", "-File"])- .arg(&script_path)- .stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null());- #[cfg(target_os = "windows")]- {- use std::os::windows::process::CommandExt;- const CREATE_NO_WINDOW: u32 = 0x08000000;- rollback_cmd.creation_flags(CREATE_NO_WINDOW);- }- rollback_cmd.spawn()- .map_err(|e| format!("failed to spawn rollback script: {}", e))?;-- info!("rollback: script spawned, app will quit now");- Ok(())- }-- #[cfg(target_os = "linux")]- {- // Find the backed-up AppImage- let entries = std::fs::read_dir(&dir).map_err(|e| format!("cannot read rollback dir: {}", e))?;- let appimage_backup = entries- .filter_map(|e| e.ok())- .find(|e| e.path().extension().map_or(false, |ext| ext == "AppImage"))- .map(|e| e.path())- .ok_or("no AppImage backup found")?;-- let current_appimage = std::env::var("APPIMAGE").map_err(|_| "not running as AppImage")?;-- info!("rollback: restoring v{} from {:?} -> {:?}", version, appimage_backup, current_appimage);-- let script = format!(- r#"#!/bin/bash-sleep 2-cp -f "{backup}" "{current}"-chmod +x "{current}"-"{current}" &-rm -f /tmp/screenpipe-rollback.sh-"#,- backup = appimage_backup.display(),- current = current_appimage,- );- let script_path = "/tmp/screenpipe-rollback.sh";- std::fs::write(script_path, &script).map_err(|e| format!("failed to write rollback script: {}", e))?;- #[cfg(unix)]- std::fs::set_permissions(script_path, std::os::unix::fs::PermissionsExt::from_mode(0o755))- .map_err(|e| format!("failed to chmod rollback script: {}", e))?;-- std::process::Command::new("/bin/bash")- .arg(script_path)- .stdin(std::process::Stdio::null())- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .spawn()- .map_err(|e| format!("failed to spawn rollback script: {}", e))?;-- info!("rollback: script spawned, app will quit now");- Ok(())- }+/// Get Tauri target-arch string for the current platform+fn get_target_arch() -> &'static str {+ #[cfg(all(target_os = "macos", target_arch = "aarch64"))]+ { "darwin-aarch64" }+ #[cfg(all(target_os = "macos", target_arch = "x86_64"))]+ { "darwin-x86_64" }+ #[cfg(all(target_os = "windows", target_arch = "x86_64"))]+ { "windows-x86_64" }+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]+ { "linux-x86_64" }+ #[cfg(not(any(+ all(target_os = "macos", target_arch = "aarch64"),+ all(target_os = "macos", target_arch = "x86_64"),+ all(target_os = "windows", target_arch = "x86_64"),+ all(target_os = "linux", target_arch = "x86_64"),+ )))]+ { "unknown" }}/// Check if this is a source/community build (not an official release)@@ -502,8 +241,6 @@ impl UpdatesManager {error!("Failed to stop recording before update: {}", err);}}- // Back up current app bundle before replacing it- backup_current_app();let app_handle = self.app.clone();let update_version = update.version.clone();let menu_item = self.update_menu_item.clone();@@ -660,8 +397,6 @@ impl UpdatesManager {error!("Failed to stop recording: {}", err);}- // Back up current app before replacing it- backup_current_app();let menu_item_win = self.update_menu_item.clone();let mut dl: u64 = 0;let mut lp: u8 = 0;@@ -782,20 +517,13 @@ pub fn start_update_check() -> Result<Arc<UpdatesManager>, Box<dyn std::error::Error>> {let updates_manager = Arc::new(UpdatesManager::new(app, interval_minutes)?);- // Back up current app on launch ONLY if no backup exists yet.- // The pre-update backup (before download_and_install) is the real rollback target.- // Previously this ran unconditionally, overwriting the previous version backup- // with the current version — making rollback useless.- if !is_source_build(app) && !cfg!(debug_assertions) {- std::thread::spawn(|| {- if rollback_version().is_none() {- info!("rollback: no backup exists, backing up current version");- backup_current_app();- } else {- info!("rollback: backup already exists (v{}), skipping launch backup",- rollback_version().unwrap_or_default());- }- });+ // Clean up old rollback directory if it exists (legacy, no longer needed)+ if let Some(home) = dirs::home_dir() {+ let rollback_dir = home.join(".screenpipe").join("rollback");+ if rollback_dir.exists() {+ let _ = std::fs::remove_dir_all(&rollback_dir);+ info!("rollback: cleaned up legacy rollback directory");+ }}// Check for updates at bootdiff --git a/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs b/apps/screenpipe-app-tauri/src-tauri/src/window_api.rsindex 75b7f5d84..3bd106e79 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/window_api.rs@@ -658,7 +658,21 @@ impl ShowRewindWindow {use tauri_nspanel::cocoa::base::{id as cocoa_id, nil as cocoa_nil};if let Ok(ns_win) = window.ns_window() {unsafe {+ // Activate the app so it comes to the foreground+ let ns_app: cocoa_id = msg_send![objc::class!(NSApplication), sharedApplication];+ let _: () = msg_send![ns_app, activateIgnoringOtherApps: true];++ // Move the window to the active space (current workspace)+ // NSWindowCollectionBehaviorMoveToActiveSpace = 1 << 1 = 2+ let behavior: u64 = msg_send![ns_win as cocoa_id, collectionBehavior];+ let move_to_active: u64 = 1 << 1;+ let _: () = msg_send![ns_win as cocoa_id, setCollectionBehavior: behavior | move_to_active];++ // Bring window to front and make it keylet _: () = msg_send![ns_win as cocoa_id, makeKeyAndOrderFront: cocoa_nil];++ // Remove MoveToActiveSpace so the window stays pinned to this space+ let _: () = msg_send![ns_win as cocoa_id, setCollectionBehavior: behavior];}}}