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(chat): hot-swap pi model on preset change instead of killing the subprocess
Louis Beaumont71baa0387eac
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 9783ec0ba..360e63799 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -1133,7 +1133,18 @@ export function StandaloneChat({ className }: { className?: string } = {}) {const piThinkingStartRef = useRef<number | null>(null);const piSessionSyncedRef = useRef(false);const piSessionIdRef = useRef<string>(crypto.randomUUID());- const piRunningConfigRef = useRef<{ provider: string; model: string; token: string | null } | null>(null);+ // Tracks the config Pi is currently running with so `handlePiRestart` can+ // decide between a hot-swap (`pi_set_model`) and a full respawn. Update+ // this ref on every Pi start/restart/swap.+ const piRunningConfigRef = useRef<{+ provider: string;+ model: string;+ url: string;+ apiKey: string | null;+ maxTokens: number;+ systemPrompt: string | null;+ token: string | null;+ } | null>(null);// Active pipe execution (when watching a running pipe)const [activePipeExecution, setActivePipeExecution] = useState<{@@ -1892,11 +1903,69 @@ export function StandaloneChat({ className }: { className?: string } = {}) {return () => clearInterval(interval);}, []);- // Restart Pi explicitly when user saves a preset — no useEffect, no debounce.+ // Apply a preset change to the running Pi process.+ //+ // - If ONLY provider/model changed: `pi_set_model` — keeps the subprocess+ // alive and preserves the full conversation, so the user can switch+ // haiku ↔ sonnet ↔ opus mid-session without losing context.+ // - If any other spawn-time field changed (url, apiKey, maxTokens, systemPrompt):+ // full restart via `pi_update_config` — those are baked into Pi's CLI args+ // and models.json, so the subprocess has to be respawned to see them.+ //// Called directly from the AIPresetsSelector onPresetSaved callback.const handlePiRestart = useCallback((preset: AIPreset) => {const providerConfig = buildProviderConfig(preset);- console.log("[Pi] User saved preset, restarting:", providerConfig?.provider, providerConfig?.model);+ if (!providerConfig) return;++ // Compare against the currently-running config. If we only know+ // provider+model (older ref shape), we can still decide on the hot-swap+ // path as long as the non-tracked fields are unchanged from the last+ // full restart — which is exactly the invariant we maintain here by+ // updating the ref on every hot-swap/restart.+ const running = piRunningConfigRef.current;+ const providerChanged = !running || running.provider !== providerConfig.provider;+ const modelChanged = !running || running.model !== providerConfig.model;+ const spawnTimeFieldsChanged =+ !running ||+ running.url !== providerConfig.url ||+ running.apiKey !== providerConfig.apiKey ||+ running.maxTokens !== providerConfig.maxTokens ||+ running.systemPrompt !== providerConfig.systemPrompt ||+ running.token !== (settings.user?.token ?? null);++ if (!providerChanged && !modelChanged && !spawnTimeFieldsChanged) {+ // Preset save that didn't actually change anything Pi cares about.+ return;+ }++ if (!spawnTimeFieldsChanged && (providerChanged || modelChanged)) {+ // Hot-swap path — preserves conversation state.+ console.log("[Pi] Hot-swap model:", providerConfig.provider, providerConfig.model);+ commands+ .piSetModel(piSessionIdRef.current, providerConfig)+ .then(() => {+ piRunningConfigRef.current = {+ provider: providerConfig.provider,+ model: providerConfig.model,+ url: providerConfig.url,+ apiKey: providerConfig.apiKey,+ maxTokens: providerConfig.maxTokens,+ systemPrompt: providerConfig.systemPrompt,+ token: settings.user?.token ?? null,+ };+ })+ .catch((e) => {+ console.error("[Pi] Hot-swap failed, falling back to full restart:", e);+ piSessionSyncedRef.current = false;+ commands.piUpdateConfig(settings.user?.token ?? null, providerConfig).catch((err) => {+ console.error("[Pi] Fallback restart also failed:", err);+ });+ });+ return;+ }++ // Full restart — spawn-time field changed.+ console.log("[Pi] Full restart (spawn-time field changed):", providerConfig.provider, providerConfig.model);piSessionSyncedRef.current = false;commands.piUpdateConfig(settings.user?.token ?? null, providerConfig).catch((e) => {console.error("[Pi] Preset switch failed:", e);@@ -2434,7 +2503,15 @@ export function StandaloneChat({ className }: { className?: string } = {}) {piSessionSyncedRef.current = false;// Keep running-config ref in sync so preset watcher doesn't re-triggerif (providerConfig) {- piRunningConfigRef.current = { provider: providerConfig.provider, model: providerConfig.model, token: settings.user?.token ?? null };+ piRunningConfigRef.current = {+ provider: providerConfig.provider,+ model: providerConfig.model,+ url: providerConfig.url,+ apiKey: providerConfig.apiKey,+ maxTokens: providerConfig.maxTokens,+ systemPrompt: providerConfig.systemPrompt,+ token: settings.user?.token ?? null,+ };}} else {console.error("[Pi] Auto-restart failed:", result.error);@@ -2770,7 +2847,15 @@ export function StandaloneChat({ className }: { className?: string } = {}) {piCrashCountRef.current = 0; // reset crash loop counter on manual start// Keep running-config ref in sync so preset watcher doesn't re-triggerif (providerConfig) {- piRunningConfigRef.current = { provider: providerConfig.provider, model: providerConfig.model, token: settings.user?.token ?? null };+ piRunningConfigRef.current = {+ provider: providerConfig.provider,+ model: providerConfig.model,+ url: providerConfig.url,+ apiKey: providerConfig.apiKey,+ maxTokens: providerConfig.maxTokens,+ systemPrompt: providerConfig.systemPrompt,+ token: settings.user?.token ?? null,+ };}} else {const providerLabel = providerConfig?.provider || "AI";diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.tsindex 1c2971966..46ecac269 100644--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts@@ -53,6 +53,15 @@ async checkAccessibilityPermissionCmd() : Promise<OSPermissionStatus> {async checkArcInstalled() : Promise<boolean> {return await TAURI_INVOKE("check_arc_installed");},+/**+ * Returns true on macOS 14.4+ where the CoreAudio Process Tap API is+ * available. Used to gate the "experimental System Audio via CoreAudio"+ * toggle — we don't show it on platforms where flipping it would be a+ * no-op. False on Windows, Linux, and older macOS.+ */+async checkCoreaudioProcessTapAvailable() : Promise<boolean> {+ return await TAURI_INVOKE("check_coreaudio_process_tap_available");+},/*** Check if Automation permission for Arc is already granted.* In production (.app bundle): uses direct FFI check (correct identity, no Terminal).@@ -797,9 +806,31 @@ async piNewSession(sessionId: string | null) : Promise<Result<null, string>> {else return { status: "error", error: e as any };}},+/**+ * Hot-swap Pi's active model without killing the subprocess. Preserves the+ * full conversation state in-place — the user can switch haiku ↔ sonnet ↔ opus+ * mid-session and the new model sees the real threaded history, not a+ * glued-transcript workaround.+ *+ * Pi's RPC `set_model` is the right path for provider+model changes only. If+ * other preset fields change (url, apiKey, maxTokens, systemPrompt) the+ * caller should fall back to `pi_update_config` which does a full restart+ * because those are spawn-time args baked into models.json / CLI flags.+ */+async piSetModel(sessionId: string | null, providerConfig: PiProviderConfig) : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("pi_set_model", { sessionId, providerConfig }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},/*** Update Pi config and restart the chat session so the new model takes effect.* Without restart, Pi keeps using the provider/model from its original CLI args.+ *+ * Prefer `pi_set_model` when only provider+model changed — it preserves the+ * conversation state instead of killing the subprocess.*/async piUpdateConfig(userToken: string | null, providerConfig: PiProviderConfig | null) : Promise<Result<null, string>> {try {@@ -1103,7 +1134,6 @@ export type AudioDeviceInfo = { name: string; isDefault: boolean }export type BrowserAutomationStatus = { name: string; status: string; running: boolean }export type BrowserLogEntry = { level: string; message: string }export type CacheFile = { path: string; label: string; size_bytes: bigint }-export type KeychainStatus = { state: string }export type CachedSuggestions = { suggestions: Suggestion[]; generatedAt: string; mode: string; aiGenerated: boolean; tags: string[] }export type CalendarEventItem = { id: string; title: string;/**@@ -1134,6 +1164,7 @@ export type EmbeddedLLM = { enabled: boolean; model: string; port: number }export type HardwareCapability = { hasGpu: boolean; cpuCores: bigint; totalMemoryGb: number; recommendedEngine: string; reason: string }export type IcsCalendarEntry = { name: string; url: string; enabled: boolean }export type JsonValue = null | boolean | number | string | JsonValue[] | { [key in string]: JsonValue }+export type KeychainStatus = { state: string }export type LogFile = { name: string; path: string; modified_at: bigint }export type MonitorDevice = { id: number; stableId: string; name: string; isDefault: boolean; width: number; height: number }export type OAuthInstanceInfo = { instance: string | null; display_name: string | null }@@ -1231,6 +1262,14 @@ audioDevices: string[];* Automatically follow the system default audio devices.*/useSystemDefaultAudio: boolean;+/**+ * Experimental: capture System Audio via the CoreAudio Process Tap API+ * (macOS 14.4+) instead of ScreenCaptureKit. Avoids SCK's display+ * enumeration failures after sleep/wake and the GPU/compositor wake+ * overhead. Off by default — existing users keep the SCK path.+ * Ignored on macOS <14.4 and on non-macOS platforms.+ */+experimentalCoreaudioSystemAudio?: boolean;/*** Duration of each audio chunk in seconds before transcription.* Stored as i32 to match existing store.bin schema (cast to u64 by engine).@@ -1301,22 +1340,17 @@ ignoredUrls?: string[];ignoreIncognitoWindows: boolean;/*** Experimental: pause screen capture when a DRM-protected streaming app- * (Netflix, Disney+, etc.) or a remote-desktop client (Omnissa/VMware Horizon)- * is focused. These apps blank their windows while screen recording is active.+ * (Netflix, Disney+, etc.) or a remote-desktop client (Omnissa/VMware+ * Horizon) is focused. These apps blank their windows while screen+ * recording is active.* Off by default; engine-only pause (no full app shutdown).*/-pauseOnDrmContent?: boolean;-/**- * Experimental: capture System Audio via the CoreAudio Process Tap API- * on macOS 14.4+ instead of ScreenCaptureKit. Off by default. Ignored on- * older macOS and non-macOS — falls back to SCK there.- */-experimentalCoreaudioSystemAudio?: boolean;+pauseOnDrmContent?: boolean;/*** Continue recording audio when the screen is locked.* Default: false (audio pauses when screen is locked to save resources).*/-recordWhileLocked?: boolean;+recordWhileLocked?: boolean;/*** Automatically append text typed during a meeting to the meeting's note* when the meeting ends. Groups typed text by app/window context.diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex d19f1d372..c6d0c47eb 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -659,6 +659,7 @@ async fn main() {pi::pi_prompt,pi::pi_abort,pi::pi_new_session,+ pi::pi_set_model,pi::pi_update_config,// ChatGPT OAuth commandschatgpt_oauth::chatgpt_oauth_login,@@ -936,6 +937,7 @@ async fn main() {pi::pi_prompt,pi::pi_abort,pi::pi_new_session,+ pi::pi_set_model,pi::pi_update_config,// ChatGPT OAuth commandschatgpt_oauth::chatgpt_oauth_login,@@ -1065,14 +1067,9 @@ async fn main() {}});- // Hide overlay when user switches Spaces (e.g. three-finger swipe).- // This no longer causes feedback loops because we removed- // activateIgnoringOtherApps + activation policy toggling.- space_monitor::setup_space_listener(app.handle().clone());-- // Set up pinch-to-zoom: store the app handle so the gesture- // recognizer callback (in window/gesture.rs) can emit Tauri events.- crate::window::init_magnify_handler(app.handle().clone());+ // 26.5 repro bisect: startup hooks disabled+ // space_monitor::setup_space_listener(app.handle().clone());+ // crate::window::init_magnify_handler(app.handle().clone());}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rsindex 4e4408c1b..9ceed14da 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs@@ -1697,8 +1697,72 @@ pub async fn pi_check() -> Result<PiCheckResult, String> {})}+/// Hot-swap Pi's active model without killing the subprocess. Preserves the+/// full conversation state in-place — the user can switch haiku ↔ sonnet ↔ opus+/// mid-session and the new model sees the real threaded history, not a+/// glued-transcript workaround.+///+/// Pi's RPC `set_model` is the right path for provider+model changes only. If+/// other preset fields change (url, apiKey, maxTokens, systemPrompt) the+/// caller should fall back to `pi_update_config` which does a full restart+/// because those are spawn-time args baked into models.json / CLI flags.+#[tauri::command]+#[specta::specta]+pub async fn pi_set_model(+ state: State<'_, PiState>,+ session_id: Option<String>,+ provider_config: PiProviderConfig,+) -> Result<(), String> {+ let sid = session_id.unwrap_or_else(|| "chat".to_string());++ // Map frontend provider name → Pi's internal registry name. Must stay in+ // sync with the mapping in `pi_start_inner` (line ~1045) — a mismatch+ // means Pi can't find the model and returns "Model not found".+ let pi_provider = match provider_config.provider.as_str() {+ "openai" => "openai-byok",+ "openai-chatgpt" => "openai-chatgpt",+ "native-ollama" => "ollama",+ "anthropic" => "anthropic-byok",+ "custom" if !provider_config.url.is_empty() => "custom",+ "screenpipe-cloud" | "pi" | _ => "screenpipe",+ };+ let pi_model = resolve_screenpipe_model(&provider_config.model, pi_provider);++ let queue = {+ let mut pool = state.0.lock().await;+ let m = pool.sessions.get_mut(&sid).ok_or("Pi not initialized")?;+ if !m.is_running() {+ return Err("Pi is not running".to_string());+ }+ m.last_activity = std::time::Instant::now();+ m.queue_handle+ .clone()+ .ok_or("Pi command queue not initialized")?+ };++ info!(+ "Pi set_model (session '{}'): provider={} model={}",+ sid, pi_provider, pi_model+ );++ let cmd = json!({+ "type": "set_model",+ "provider": pi_provider,+ "modelId": pi_model,+ });++ let rx = queue+ .send(cmd, crate::pi_command_queue::WaitMode::WaitDone)+ .await?;+ rx.await+ .map_err(|_| "Pi command queue dropped".to_string())?+}+/// Update Pi config and restart the chat session so the new model takes effect./// Without restart, Pi keeps using the provider/model from its original CLI args.+///+/// Prefer `pi_set_model` when only provider+model changed — it preserves the+/// conversation state instead of killing the subprocess.#[tauri::command]#[specta::specta]pub async fn pi_update_config(