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

fix

Louis Beaumont9e60ae8f3e43
diff --git a/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx b/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx
index 311944c3f..b941f5d31 100644
--- a/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/apple-intelligence-card.tsx
@@ -32,6 +32,7 @@ export function AppleIntelligenceCard() {
} catch {}
return "unknown";
});
+ const [aiStatusReason, setAiStatusReason] = useState<string>("");
const [enabled, setEnabled] = useState(true);
// Wrap setAiStatus to persist to localStorage
@@ -102,46 +103,58 @@ export function AppleIntelligenceCard() {
// Check AI availability (with retry on failure)
const checkStatus = useCallback(async () => {
- const attempt = async () => {
+ const attempt = async (): Promise<{ available: boolean; status: string } | null> => {
const resp = await fetch(`${API}/ai/status`, {
signal: AbortSignal.timeout(10000),
});
if (resp.ok) {
- const data = await resp.json();
- return data.available ? "available" : "unavailable";
+ return await resp.json();
}
+ console.warn("[apple-intelligence] /ai/status returned", resp.status, resp.statusText);
return null;
};
try {
- let result = await attempt();
+ let data = await attempt();
// Retry once after 2s if the first attempt failed
- if (result === null) {
+ if (data === null) {
await new Promise((r) => setTimeout(r, 2000));
- result = await attempt();
+ data = await attempt();
}
- if (result) {
- setAiStatus(result as "available" | "unavailable");
+ if (data) {
+ const result = data.available ? "available" : "unavailable";
+ console.log("[apple-intelligence] status:", data.status, "available:", data.available);
+ setAiStatus(result);
+ setAiStatusReason(data.status || "");
if (!statusCapturedRef.current) {
statusCapturedRef.current = true;
posthog.capture("apple_intelligence_status", {
- available: result === "available",
+ available: data.available,
+ status: data.status,
enabled,
});
}
} else {
+ console.warn("[apple-intelligence] /ai/status unreachable — endpoint may not be compiled in");
setAiStatus("unavailable");
+ setAiStatusReason("endpoint unreachable — build may not include apple-intelligence feature");
}
- } catch {
+ } catch (e) {
// On network error, retry once
try {
await new Promise((r) => setTimeout(r, 2000));
- const result = await attempt();
- setAiStatus(
- result ? (result as "available" | "unavailable") : "unavailable"
- );
+ const data = await attempt();
+ if (data) {
+ setAiStatus(data.available ? "available" : "unavailable");
+ setAiStatusReason(data.status || "");
+ } else {
+ setAiStatus("unavailable");
+ setAiStatusReason("endpoint unreachable");
+ }
} catch {
+ console.error("[apple-intelligence] /ai/status failed after retry:", e);
setAiStatus("unavailable");
+ setAiStatusReason("network error");
}
}
}, [enabled, setAiStatus]);
@@ -337,7 +350,9 @@ export function AppleIntelligenceCard() {
{aiStatus === "unavailable" && (
<p className="text-xs text-muted-foreground mb-3">
<AlertCircle className="h-3 w-3 inline mr-1" />
- Requires macOS 26+ with Apple Intelligence enabled.
+ {aiStatusReason
+ ? `Not available: ${aiStatusReason}`
+ : "Requires macOS 26+ with Apple Intelligence enabled."}
</p>
)}
diff --git a/apps/screenpipe-app-tauri/components/settings/openclaw-card.tsx b/apps/screenpipe-app-tauri/components/settings/openclaw-card.tsx
index a864acbb5..84514aabe 100644
--- a/apps/screenpipe-app-tauri/components/settings/openclaw-card.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/openclaw-card.tsx
@@ -14,7 +14,9 @@ import {
Server,
Eye,
EyeOff,
- ChevronDown,
+ Settings2,
+ Check,
+ X,
} from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import { openUrl } from "@tauri-apps/plugin-opener";
@@ -71,7 +73,6 @@ function saveConfig(config: SyncConfig) {
} catch {}
}
-// Convert frontend config to Rust SyncConfig format
function toRustConfig(config: SyncConfig) {
return {
host: config.host,
@@ -92,8 +93,8 @@ export function OpenClawCard() {
const [lastSync, setLastSync] = useState<string | null>(null);
const [syncError, setSyncError] = useState<string | null>(null);
const [showKey, setShowKey] = useState(false);
+ const [showAdvanced, setShowAdvanced] = useState(false);
const [discoveredHosts, setDiscoveredHosts] = useState<DiscoveredHost[]>([]);
- const [showHostPicker, setShowHostPicker] = useState(false);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
@@ -105,7 +106,6 @@ export function OpenClawCard() {
if (ts) setLastSync(ts);
} catch {}
- // Discover SSH hosts on mount
invoke<DiscoveredHost[]>("remote_sync_discover_hosts")
.then(setDiscoveredHosts)
.catch(() => {});
@@ -118,6 +118,7 @@ export function OpenClawCard() {
return next;
});
setTestResult(null);
+ setSyncError(null);
}, []);
const handleTest = async () => {
@@ -127,11 +128,12 @@ export function OpenClawCard() {
try {
await invoke("remote_sync_test", { config: toRustConfig(config) });
setTestResult({ ok: true });
+ posthog.capture("openclaw_ssh_test", { success: true });
} catch (e) {
setTestResult({ ok: false, error: String(e) });
+ posthog.capture("openclaw_ssh_test", { success: false });
}
setIsTesting(false);
- posthog.capture("openclaw_ssh_test", { success: testResult?.ok });
};
const handleSyncNow = async () => {
@@ -150,14 +152,14 @@ export function OpenClawCard() {
} else {
setSyncError(result.error || "sync failed");
}
+ posthog.capture("openclaw_sync_manual", { success: result.ok });
} catch (e) {
setSyncError(String(e));
+ posthog.capture("openclaw_sync_manual", { success: false });
}
setIsSyncing(false);
- posthog.capture("openclaw_sync_manual", { success: !syncError });
};
- // auto-sync interval
useEffect(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
@@ -166,29 +168,16 @@ export function OpenClawCard() {
if (config.enabled && config.host && config.user) {
handleSyncNow();
-
- intervalRef.current = setInterval(() => {
- handleSyncNow();
- }, config.intervalMinutes * 60 * 1000);
-
+ intervalRef.current = setInterval(handleSyncNow, config.intervalMinutes * 60 * 1000);
posthog.capture("openclaw_sync_enabled", { interval: config.intervalMinutes });
}
return () => {
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- }
+ if (intervalRef.current) clearInterval(intervalRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [config.enabled, config.host, config.user, config.intervalMinutes]);
- const toggleEnabled = (val: boolean) => {
- updateConfig({ enabled: val });
- if (!val) {
- posthog.capture("openclaw_sync_disabled");
- }
- };
-
const selectHost = (host: DiscoveredHost) => {
updateConfig({
host: host.host,
@@ -196,7 +185,6 @@ export function OpenClawCard() {
...(host.user ? { user: host.user } : {}),
...(host.key_path ? { keyPath: host.key_path } : {}),
});
- setShowHostPicker(false);
};
const isConfigured = config.host && config.user;
@@ -205,208 +193,241 @@ export function OpenClawCard() {
<Card className="border-border bg-card overflow-hidden">
<CardContent className="p-0">
<div className="flex items-start p-4 gap-4">
- {/* OpenClaw icon */}
<div className="flex-shrink-0">
- <img
- src="/openclaw-icon.svg"
- alt="OpenClaw"
- className="w-10 h-10 rounded-xl"
- />
+ <img src="/openclaw-icon.svg" alt="OpenClaw" className="w-10 h-10 rounded-xl" />
</div>
- {/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
- <h3 className="text-sm font-semibold text-foreground">
- OpenClaw Sync
- </h3>
- <span className="px-2 py-0.5 text-xs font-medium bg-muted text-muted-foreground rounded-full inline-flex items-center gap-1">
- <Server className="h-2.5 w-2.5" />
- SSH
- </span>
+ <h3 className="text-sm font-semibold text-foreground">OpenClaw Sync</h3>
{config.enabled && isConfigured && (
<span className="px-2 py-0.5 text-xs font-medium bg-foreground text-background rounded-full">
syncing
</span>
)}
+ {testResult?.ok && !config.enabled && (
+ <span className="px-2 py-0.5 text-xs font-medium bg-green-500/15 text-green-600 rounded-full">
+ connected
+ </span>
+ )}
</div>
<p className="text-xs text-muted-foreground mb-3 leading-relaxed">
- Sync your screenpipe data to a remote server over SSH.
- Run OpenClaw or any AI agent on your VPS to query your data 24/7,
- even when your machine is off.
+ sync your screenpipe data to a remote server.
+ run openclaw or any AI agent on your VPS 24/7.
</p>
- {/* SSH config form */}
- <div className="space-y-2 mb-3">
- <div className="flex gap-2">
- <div className="relative flex-1">
- <Input
- placeholder="host (e.g. 100.64.0.1 or my-vps.com)"
- value={config.host}
- onChange={(e) => updateConfig({ host: e.target.value })}
- className="text-xs h-7"
- />
- {discoveredHosts.length > 0 && (
- <button
- type="button"
- onClick={() => setShowHostPicker(!showHostPicker)}
- className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- title="Pick from discovered hosts"
- >
- <ChevronDown className="h-3 w-3" />
- </button>
- )}
- {showHostPicker && discoveredHosts.length > 0 && (
- <div className="absolute z-10 top-full left-0 right-0 mt-1 bg-popover border border-border rounded-md shadow-lg max-h-40 overflow-y-auto">
+ {/* If not configured yet, show discovered hosts or manual form */}
+ {!isConfigured ? (
+ <div className="space-y-2 mb-3">
+ {discoveredHosts.length > 0 && (
+ <>
+ <p className="text-xs text-muted-foreground">pick a server:</p>
+ <div className="flex flex-wrap gap-1.5">
{discoveredHosts.map((h, i) => (
<button
key={i}
onClick={() => selectHost(h)}
- className="w-full text-left px-3 py-1.5 text-xs hover:bg-muted flex justify-between items-center"
+ className="px-2.5 py-1 text-xs border border-border rounded-md hover:bg-muted transition-colors"
>
- <span>
- {h.user ? `${h.user}@` : ""}{h.host}
- {h.port !== 22 ? `:${h.port}` : ""}
- </span>
- <span className="text-muted-foreground ml-2">
- {h.source}
- </span>
+ {h.user ? `${h.user}@` : ""}{h.host}
+ {h.port !== 22 ? `:${h.port}` : ""}
+ <span className="text-muted-foreground ml-1.5">({h.source})</span>
</button>
))}
</div>
- )}
- </div>
- <Input
- placeholder="port"
- value={config.port}
- onChange={(e) => updateConfig({ port: e.target.value })}
- className="text-xs h-7 w-16"
- />
- </div>
- <div className="flex gap-2">
- <Input
- placeholder="user (e.g. root)"
- value={config.user}
- onChange={(e) => updateConfig({ user: e.target.value })}
- className="text-xs h-7 w-32"
- />
- <div className="relative flex-1">
+ <div className="flex items-center gap-2 pt-1">
+ <div className="h-px flex-1 bg-border" />
+ <span className="text-[10px] text-muted-foreground">or enter manually</span>
+ <div className="h-px flex-1 bg-border" />
+ </div>
+ </>
+ )}
+ {/* Manual entry */}
+ <div className="flex gap-2">
<Input
- placeholder="SSH key path"
- type={showKey ? "text" : "password"}
- value={config.keyPath}
- onChange={(e) => updateConfig({ keyPath: e.target.value })}
- className="text-xs h-7 pr-8"
+ placeholder="user@host"
+ value={config.user && config.host ? `${config.user}@${config.host}` : ""}
+ onChange={(e) => {
+ const val = e.target.value;
+ const at = val.indexOf("@");
+ if (at >= 0) {
+ updateConfig({ user: val.slice(0, at), host: val.slice(at + 1) });
+ } else {
+ updateConfig({ host: val });
+ }
+ }}
+ className="text-xs h-7 flex-1"
+ spellCheck={false}
+ autoCorrect="off"
+ autoCapitalize="off"
/>
+ </div>
+ </div>
+ ) : (
+ /* Configured — show compact summary + actions */
+ <div className="space-y-2 mb-3">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-mono bg-muted px-2 py-0.5 rounded">
+ {config.user}@{config.host}{config.port !== "22" ? `:${config.port}` : ""}
+ </span>
<button
- type="button"
- onClick={() => setShowKey(!showKey)}
- className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ onClick={() => updateConfig({ host: "", user: "" })}
+ className="text-muted-foreground hover:text-foreground"
+ title="disconnect"
>
- {showKey ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
+ <X className="h-3 w-3" />
+ </button>
+ <button
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ className="text-muted-foreground hover:text-foreground"
+ title="advanced settings"
+ >
+ <Settings2 className="h-3 w-3" />
</button>
</div>
- </div>
- <div className="flex gap-2">
- <Input
- placeholder="remote path (e.g. ~/screenpipe-data)"
- value={config.remotePath}
- onChange={(e) => updateConfig({ remotePath: e.target.value })}
- className="text-xs h-7 flex-1"
- />
- <Input
- placeholder="min"
- type="number"
- min={1}
- value={config.intervalMinutes}
- onChange={(e) => updateConfig({ intervalMinutes: Math.max(1, parseInt(e.target.value) || 5) })}
- className="text-xs h-7 w-16"
- title="Sync interval in minutes"
- />
- </div>
-
- {testResult && (
- <p className={`text-xs ${testResult.ok ? "text-green-600" : "text-destructive"}`}>
- {testResult.ok ? "SSH connection successful" : `Error: ${testResult.error}`}
- </p>
- )}
- {syncError && (
- <p className="text-xs text-destructive">
- Sync error: {syncError}
- </p>
- )}
- </div>
- {/* Actions */}
- <div className="flex flex-wrap items-center gap-2">
- <Button
- onClick={handleTest}
- disabled={isTesting || !isConfigured}
- variant="outline"
- size="sm"
- className="gap-1.5 h-7 text-xs"
- >
- {isTesting ? (
- <>
- <Loader2 className="h-3 w-3 animate-spin" />
- Testing...
- </>
- ) : (
- "Test SSH"
+ {/* Advanced settings (hidden by default) */}
+ {showAdvanced && (
+ <div className="space-y-2 pt-1">
+ <div className="flex gap-2">
+ <Input
+ placeholder="host"
+ value={config.host}
+ onChange={(e) => updateConfig({ host: e.target.value })}
+ className="text-xs h-7 flex-1"
+ spellCheck={false}
+ autoCorrect="off"
+ />
+ <Input
+ placeholder="port"
+ value={config.port}
+ onChange={(e) => updateConfig({ port: e.target.value })}
+ className="text-xs h-7 w-16"
+ spellCheck={false}
+ autoCorrect="off"
+ />
+ </div>
+ <div className="flex gap-2">
+ <Input
+ placeholder="user"
+ value={config.user}
+ onChange={(e) => updateConfig({ user: e.target.value })}
+ className="text-xs h-7 w-32"
+ spellCheck={false}
+ autoCorrect="off"
+ />
+ <div className="relative flex-1">
+ <Input
+ placeholder="SSH key path"
+ type={showKey ? "text" : "password"}
+ value={config.keyPath}
+ onChange={(e) => updateConfig({ keyPath: e.target.value })}
+ className="text-xs h-7 pr-8"
+ spellCheck={false}
+ autoCorrect="off"
+ />
+ <button
+ type="button"
+ onClick={() => setShowKey(!showKey)}
+ className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ {showKey ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
+ </button>
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <Input
+ placeholder="remote path"
+ value={config.remotePath}
+ onChange={(e) => updateConfig({ remotePath: e.target.value })}
+ className="text-xs h-7 flex-1"
+ spellCheck={false}
+ autoCorrect="off"
+ />
+ <Input
+ placeholder="min"
+ type="number"
+ min={1}
+ value={config.intervalMinutes}
+ onChange={(e) => updateConfig({ intervalMinutes: Math.max(1, parseInt(e.target.value) || 5) })}
+ className="text-xs h-7 w-16"
+ title="sync interval in minutes"
+ />
+ </div>
+ </div>
)}
- </Button>
- <Button
- onClick={handleSyncNow}
- disabled={isSyncing || !isConfigured}
- size="sm"
- className="gap-1.5 h-7 text-xs"
- >
- {isSyncing ? (
- <>
- <Loader2 className="h-3 w-3 animate-spin" />
- Syncing...
- </>
- ) : (
- <>
- <RefreshCw className="h-3 w-3" />
- Sync now
- </>
+ {testResult && (
+ <p className={`text-xs ${testResult.ok ? "text-green-600" : "text-destructive"}`}>
+ {testResult.ok ? "connected" : testResult.error}
+ </p>
+ )}
+ {syncError && (
+ <p className="text-xs text-destructive">{syncError}</p>
)}
- </Button>
+ </div>
+ )}
- <div className="flex items-center gap-1.5 ml-auto">
- <span className="text-xs text-muted-foreground">Auto-sync</span>
- <Switch
- checked={config.enabled}
- onCheckedChange={toggleEnabled}
- disabled={!isConfigured}
- className="scale-75"
- />
+ {/* Actions — only show when configured */}
+ {isConfigured && (
+ <div className="flex items-center gap-2">
+ <Button
+ onClick={handleTest}
+ disabled={isTesting}
+ variant="outline"
+ size="sm"
+ className="h-7 text-xs w-20"
+ >
+ {isTesting ? <Loader2 className="h-3 w-3 animate-spin" /> : "test"}
+ </Button>
+
+ <Button
+ onClick={handleSyncNow}
+ disabled={isSyncing}
+ size="sm"
+ className="h-7 text-xs w-24"
+ >
+ {isSyncing ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <>
+ <RefreshCw className="h-3 w-3 mr-1" />
+ sync now
+ </>
+ )}
+ </Button>
+
+ <div className="flex items-center gap-1.5 ml-auto">
+ <span className="text-xs text-muted-foreground">auto</span>
+ <Switch
+ checked={config.enabled}
+ onCheckedChange={(val) => {
+ updateConfig({ enabled: val });
+ if (!val) posthog.capture("openclaw_sync_disabled");
+ }}
+ className="scale-75"
+ />
+ </div>
</div>
- </div>
+ )}
</div>
</div>
{/* Status bar */}
- <div className="px-4 py-2 bg-muted/50 border-t border-border">
- <div className="flex items-center gap-3 text-xs text-muted-foreground">
- <span>
- {lastSync
- ? `last sync: ${lastSync}`
- : "not synced yet"}
- </span>
- {config.enabled && isConfigured && (
- <span>every {config.intervalMinutes} min</span>
- )}
- <button
- onClick={() => openUrl("https://github.com/openclaw/openclaw")}
- className="ml-auto hover:text-foreground transition-colors"
- >
- openclaw.ai
- </button>
+ {isConfigured && (
+ <div className="px-4 py-2 bg-muted/50 border-t border-border">
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <span>{lastSync ? `last sync: ${lastSync}` : "not synced yet"}</span>
+ {config.enabled && <span>every {config.intervalMinutes} min</span>}
+ <button
+ onClick={() => openUrl("https://github.com/openclaw/openclaw")}
+ className="ml-auto hover:text-foreground transition-colors"
+ >
+ openclaw.ai
+ </button>
+ </div>
</div>
- </div>
+ )}
</CardContent>
</Card>
);
diff --git a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
index c16272e5d..98d607789 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipes-section.tsx
@@ -527,7 +527,7 @@ export function PipesSection() {
});
const data = await res.json();
if (data.error) throw new Error(data.error);
- await navigator.clipboard.writeText(data.url);
+ await commands.copyTextToClipboard(data.url);
posthog.capture("pipe_shared_public", { pipe_name: pipe.config.name, pipe_id: data.id });
toast({ title: "link copied!", description: data.url });
} catch (err: any) {
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index e6d54439b..ddd50f1e8 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -9069,7 +9069,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.2.40"
+version = "2.2.41"
dependencies = [
"anyhow",
"arboard",
diff --git a/crates/screenpipe-core/src/sync/client.rs b/crates/screenpipe-core/src/sync/client.rs
index 3b7f086b1..b528d8025 100644
--- a/crates/screenpipe-core/src/sync/client.rs
+++ b/crates/screenpipe-core/src/sync/client.rs
@@ -3,8 +3,11 @@
//! This module provides the HTTP client for communicating with the
//! Screenpipe cloud sync API.
+use std::time::Duration;
+
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
+use tracing::warn;
use super::blob::{BlobMetadata, BlobType};
use super::error::{SyncError, SyncResult};
@@ -64,18 +67,35 @@ impl SyncClientConfig {
/// Client for sync API operations.
pub struct SyncClient {
config: SyncClientConfig,
+ /// Short-timeout client for metadata/API calls
http: Client,
+ /// Long-timeout client for blob uploads/downloads
+ http_transfer: Client,
}
+/// Maximum retries for transient network errors.
+const MAX_RETRIES: u32 = 3;
+/// Initial backoff delay between retries.
+const INITIAL_BACKOFF: Duration = Duration::from_secs(2);
+
impl SyncClient {
/// Create a new sync client.
pub fn new(config: SyncClientConfig) -> SyncResult<Self> {
let http = Client::builder()
- .timeout(std::time::Duration::from_secs(30))
+ .timeout(Duration::from_secs(30))
.build()
.map_err(|e| SyncError::Network(format!("failed to create HTTP client: {}", e)))?;
- Ok(Self { config, http })
+ let http_transfer = Client::builder()
+ .timeout(Duration::from_secs(120))
+ .build()
+ .map_err(|e| SyncError::Network(format!("failed to create transfer client: {}", e)))?;
+
+ Ok(Self {
+ config,
+ http,
+ http_transfer,
+ })
}
/// Get the device ID.
@@ -274,25 +294,50 @@ impl SyncClient {
/// and require the upload token in the URL path. The URL format is:
/// `{supabaseUrl}/storage/v1/object/upload/sign/{bucket}/{path}?token={token}`
pub async fn upload_to_s3(&self, upload_url: &str, data: &[u8]) -> SyncResult<()> {
- let response = self
- .http
- .put(upload_url)
- .header("Content-Type", "application/octet-stream")
- .header("x-upsert", "true")
- .body(data.to_vec())
- .send()
- .await?;
+ let mut last_err = None;
+ for attempt in 0..MAX_RETRIES {
+ if attempt > 0 {
+ let backoff = INITIAL_BACKOFF * 2u32.pow(attempt - 1);
+ warn!("upload retry {}/{} after {:?}", attempt + 1, MAX_RETRIES, backoff);
+ tokio::time::sleep(backoff).await;
+ }
- if !response.status().is_success() {
- let status = response.status();
- let body = response.text().await.unwrap_or_default();
- return Err(SyncError::Server(format!(
- "S3 upload failed with status: {} body: {}",
- status, body
- )));
+ let result = self
+ .http_transfer
+ .put(upload_url)
+ .header("Content-Type", "application/octet-stream")
+ .header("x-upsert", "true")
+ .body(data.to_vec())
+ .send()
+ .await;
+
+ match result {
+ Ok(response) => {
+ if response.status().is_success() {
+ return Ok(());
+ }
+ let status = response.status();
+ // Don't retry client errors (4xx)
+ if status.is_client_error() {
+ let body = response.text().await.unwrap_or_default();
+ return Err(SyncError::Server(format!(
+ "S3 upload failed with status: {} body: {}",
+ status, body
+ )));
+ }
+ let body = response.text().await.unwrap_or_default();
+ last_err = Some(SyncError::Server(format!(
+ "S3 upload failed with status: {} body: {}",
+ status, body
+ )));
+ }
+ Err(e) => {
+ last_err = Some(SyncError::Network(e.to_string()));
+ }
+ }
}
- Ok(())
+ Err(last_err.unwrap_or_else(|| SyncError::Network("upload failed after retries".to_string())))
}
/// Mark an upload as completed.
@@ -341,25 +386,45 @@ impl SyncClient {
/// Download encrypted data from S3.
pub async fn download_from_s3(&self, download_url: &str) -> SyncResult<Vec<u8>> {
- let response = self.http.get(download_url).send().await?;
+ let mut last_err = None;
+ for attempt in 0..MAX_RETRIES {
+ if attempt > 0 {
+ let backoff = INITIAL_BACKOFF * 2u32.pow(attempt - 1);
+ warn!("download retry {}/{} after {:?}", attempt + 1, MAX_RETRIES, backoff);
+ tokio::time::sleep(backoff).await;
+ }
- if !response.status().is_success() {
- let status = response.status();
- let body = response.text().await.unwrap_or_default();
- // Truncate body to avoid flooding logs with large XML error responses
- let body_preview = if body.len() > 500 {
- &body[..500]
- } else {
- &body
- };
- return Err(SyncError::Server(format!(
- "S3 download failed with status: {} body: {}",
- status, body_preview
- )));
+ let result = self.http_transfer.get(download_url).send().await;
+
+ match result {
+ Ok(response) => {
+ if response.status().is_success() {
+ let bytes = response.bytes().await?;
+ return Ok(bytes.to_vec());
+ }
+ let status = response.status();
+ if status.is_client_error() {
+ let body = response.text().await.unwrap_or_default();
+ let body_preview = if body.len() > 500 { &body[..500] } else { &body };
+ return Err(SyncError::Server(format!(
+ "S3 download failed with status: {} body: {}",
+ status, body_preview
+ )));
+ }
+ let body = response.text().await.unwrap_or_default();
+ let body_preview = if body.len() > 500 { &body[..500] } else { &body };
+ last_err = Some(SyncError::Server(format!(
+ "S3 download failed with status: {} body: {}",
+ status, body_preview
+ )));
+ }
+ Err(e) => {
+ last_err = Some(SyncError::Network(e.to_string()));
+ }
+ }
}
- let bytes = response.bytes().await?;
- Ok(bytes.to_vec())
+ Err(last_err.unwrap_or_else(|| SyncError::Network("download failed after retries".to_string())))
}
// =========================================================================
@@ -504,37 +569,67 @@ impl SyncClient {
body: &T,
) -> SyncResult<R> {
let url = format!("{}{}", self.config.api_url, path);
+ let mut last_err = None;
- let response = self
- .http
- .post(&url)
- .header(
- "Authorization",
- format!("Bearer {}", self.config.auth_token),
- )
- .header("X-Device-Id", &self.config.device_id)
- .json(body)
- .send()
- .await?;
+ for attempt in 0..MAX_RETRIES {
+ if attempt > 0 {
+ let backoff = INITIAL_BACKOFF * 2u32.pow(attempt - 1);
+ warn!("POST {} retry {}/{} after {:?}", path, attempt + 1, MAX_RETRIES, backoff);
+ tokio::time::sleep(backoff).await;
+ }
- self.handle_response(response).await
+ match self
+ .http
+ .post(&url)
+ .header(
+ "Authorization",
+ format!("Bearer {}", self.config.auth_token),
+ )
+ .header("X-Device-Id", &self.config.device_id)
+ .json(body)
+ .send()
+ .await
+ {
+ Ok(response) => return self.handle_response(response).await,
+ Err(e) => {
+ last_err = Some(SyncError::Network(e.to_string()));
+ }
+ }
+ }
+
+ Err(last_err.unwrap_or_else(|| SyncError::Network(format!("POST {} failed after retries", path))))
}
async fn get<R: for<'de> Deserialize<'de>>(&self, path: &str) -> SyncResult<R> {
let url = format!("{}{}", self.config.api_url, path);
+ let mut last_err = None;
- let response = self
- .http
- .get(&url)
- .header(
- "Authorization",
- format!("Bearer {}", self.config.auth_token),
- )
- .header("X-Device-Id", &self.config.device_id)
- .send()
- .await?;
+ for attempt in 0..MAX_RETRIES {
+ if attempt > 0 {
+ let backoff = INITIAL_BACKOFF * 2u32.pow(attempt - 1);
+ warn!("GET {} retry {}/{} after {:?}", path, attempt + 1, MAX_RETRIES, backoff);
+ tokio::time::sleep(backoff).await;
+ }
+
+ match self
+ .http
+ .get(&url)
+ .header(
+ "Authorization",
+ format!("Bearer {}", self.config.auth_token),
+ )
+ .header("X-Device-Id", &self.config.device_id)
+ .send()
+ .await
+ {
+ Ok(response) => return self.handle_response(response).await,
+ Err(e) => {
+ last_err = Some(SyncError::Network(e.to_string()));
+ }
+ }
+ }
- self.handle_response(response).await
+ Err(last_err.unwrap_or_else(|| SyncError::Network(format!("GET {} failed after retries", path))))
}
async fn handle_response<R: for<'de> Deserialize<'de>>(
diff --git a/crates/screenpipe-integrations/src/remote_sync.rs b/crates/screenpipe-integrations/src/remote_sync.rs
index e52f4e1dc..54b8de935 100644
--- a/crates/screenpipe-integrations/src/remote_sync.rs
+++ b/crates/screenpipe-integrations/src/remote_sync.rs
@@ -9,7 +9,7 @@
use anyhow::{Context, Result};
use russh::client;
-use russh::keys::{PrivateKeyWithHashAlg, PublicKey};
+use russh::keys::{HashAlg, PrivateKeyWithHashAlg, PublicKey};
use russh_sftp::client::SftpSession;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
@@ -159,8 +159,11 @@ async fn connect_sftp(config: &SyncConfig) -> Result<(client::Handle<SshHandler>
.await
.with_context(|| format!("SSH connection to {}:{} failed", config.host, config.port))?;
+ // Use SHA-256 for RSA keys (servers reject SHA-1 "ssh-rsa" by default now).
+ // For non-RSA keys (ed25519, ecdsa) the hash_alg is ignored.
+ let key_with_alg = PrivateKeyWithHashAlg::new(key, Some(HashAlg::Sha256));
let auth = session
- .authenticate_publickey(&config.user, PrivateKeyWithHashAlg::new(key, None))
+ .authenticate_publickey(&config.user, key_with_alg)
.await
.context("SSH authentication failed")?;
if !auth.success() {
@@ -405,7 +408,46 @@ pub async fn test_connection(config: &SyncConfig) -> Result<()> {
// ── Host discovery ──────────────────────────────────────────────────────
+/// Scan ~/.ssh/ for available private keys (files named id_* without .pub extension).
+async fn discover_default_key() -> Option<String> {
+ let ssh_dir = dirs::home_dir()?.join(".ssh");
+ let mut entries = match tokio::fs::read_dir(&ssh_dir).await {
+ Ok(e) => e,
+ Err(_) => return None,
+ };
+
+ // Preference order for default keys
+ let preferred = ["id_ed25519", "id_ecdsa", "id_rsa"];
+ let mut found_keys: Vec<String> = Vec::new();
+
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if name.starts_with("id_")
+ && !name.ends_with(".pub")
+ && entry.file_type().await.map(|ft| ft.is_file()).unwrap_or(false)
+ {
+ found_keys.push(name);
+ }
+ }
+
+ // Return the best key by preference order, fallback to first found
+ for pref in &preferred {
+ if found_keys.contains(&pref.to_string()) {
+ return Some(format!("~/.ssh/{}", pref));
+ }
+ }
+ found_keys.first().map(|k| format!("~/.ssh/{}", k))
+}
+
+/// Get the current system username.
+fn current_username() -> Option<String> {
+ std::env::var("USER")
+ .or_else(|_| std::env::var("USERNAME"))
+ .ok()
+}
+
/// Discover SSH hosts from ~/.ssh/config, ~/.ssh/known_hosts, and Tailscale.
+/// Auto-fills missing user (defaults to system username) and key_path (best available key).
pub async fn discover_ssh_hosts() -> Vec<DiscoveredHost> {
let mut hosts = Vec::new();
@@ -430,6 +472,19 @@ pub async fn discover_ssh_hosts() -> Vec<DiscoveredHost> {
&& !h.host.contains("gitpod")
});
+ // Auto-fill missing user and key_path
+ let default_key = discover_default_key().await;
+ let default_user = current_username();
+
+ for host in &mut hosts {
+ if host.user.is_none() {
+ host.user = default_user.clone();
+ }
+ if host.key_path.is_none() {
+ host.key_path = default_key.clone();
+ }
+ }
+
hosts
}
diff --git a/crates/screenpipe-server/src/apple_intelligence_api.rs b/crates/screenpipe-server/src/apple_intelligence_api.rs
index b70625f32..42c2c9910 100644
--- a/crates/screenpipe-server/src/apple_intelligence_api.rs
+++ b/crates/screenpipe-server/src/apple_intelligence_api.rs
@@ -358,9 +358,16 @@ fn parse_tool_calls(text: &str) -> (Option<String>, Vec<ToolCall>) {
/// GET /ai/status
pub async fn ai_status() -> Json<StatusResponse> {
let avail = check_availability();
+ let is_available = avail == Availability::Available;
+ let status_str = avail.to_string();
+ if is_available {
+ info!("apple intelligence status: available");
+ } else {
+ warn!("apple intelligence status: {} (not available)", status_str);
+ }
Json(StatusResponse {
- available: avail == Availability::Available,
- status: avail.to_string(),
+ available: is_available,
+ status: status_str,
model: MODEL_ID.to_string(),
})
}