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(ai-presets): ChatGPT OAuth UX + stale diagnostics across preset flows (#3196)

Ansh Groverfb1122e50b99
diff --git a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
index 4778ec321..5973273e5 100644
--- a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
@@ -260,6 +260,9 @@ const AISection = ({
const diagnosticsAbortRef = useRef<AbortController | null>(null);
const [chatgptLoggedIn, setChatgptLoggedIn] = useState(false);
const [chatgptLoading, setChatgptLoading] = useState(false);
+ const [chatgptChecking, setChatgptChecking] = useState(
+ () => settingsPreset?.provider === "openai-chatgpt"
+ );
// Filter presets the same way the UI does so hidden presets don't block creation
const visiblePresets = useMemo(
@@ -315,11 +318,21 @@ const AISection = ({
// Check ChatGPT OAuth status when provider is selected
useEffect(() => {
if (settingsPreset?.provider === "openai-chatgpt") {
+ setChatgptChecking(true);
+ const timeout = setTimeout(() => setChatgptChecking(false), 5000);
commands.chatgptOauthStatus().then((res) => {
+ clearTimeout(timeout);
if (res.status === "ok") {
setChatgptLoggedIn(res.data.logged_in);
}
+ setChatgptChecking(false);
+ }).catch(() => {
+ clearTimeout(timeout);
+ setChatgptChecking(false);
});
+ return () => clearTimeout(timeout);
+ } else {
+ setChatgptChecking(false);
}
}, [settingsPreset?.provider]);
@@ -494,6 +507,25 @@ const AISection = ({
}, [updateSettingsPreset]);
const handleAiProviderChange = useCallback((newValue: AIPreset["provider"]) => {
+ // No-op if same provider — avoids resetting UI state (e.g. chatgptChecking) unnecessarily
+ if (newValue === settingsPreset?.provider) return;
+
+ // Clear stale diagnostic results so previous provider's errors don't bleed through
+ setTestStatus("idle");
+ setTestResults(INITIAL_DIAGNOSTICS);
+ setDiagnosticsOpen(false);
+ // Reset ChatGPT auth UI — the status-check effect re-runs when provider dep changes
+ setChatgptLoggedIn(false);
+ // chatgptChecking is managed by the status-check effect, not here
+
+ const defaultNames: Record<string, string> = {
+ "openai-chatgpt": "chatgpt",
+ "openai": "openai",
+ "anthropic": "claude",
+ "native-ollama": "ollama",
+ "screenpipe-cloud": "screenpipe-cloud",
+ };
+
let newUrl = "";
let newModel = settingsPreset?.model;
@@ -521,12 +553,14 @@ const AISection = ({
break;
}
- updateSettingsPreset({
- provider: newValue,
- url: newUrl,
- model: newModel,
- });
- }, [settingsPreset?.url, settingsPreset?.model, updateSettingsPreset]);
+ const updates: Partial<AIPreset> = { provider: newValue, url: newUrl, model: newModel };
+ // Auto-fill name only when creating a new preset (no existing id)
+ if (!settingsPreset?.id && defaultNames[newValue]) {
+ updates.id = defaultNames[newValue];
+ }
+
+ updateSettingsPreset(updates);
+ }, [settingsPreset?.id, settingsPreset?.url, settingsPreset?.model, updateSettingsPreset]);
const [models, setModels] = useState<AIModel[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
@@ -1263,39 +1297,67 @@ const AISection = ({
ChatGPT Account
</Label>
<div className="flex items-center gap-3">
- <Button
- type="button"
- variant={chatgptLoggedIn ? "outline" : "default"}
- disabled={chatgptLoading}
- onClick={async () => {
- if (chatgptLoggedIn) {
- setChatgptLoading(true);
- await commands.chatgptOauthLogout();
- setChatgptLoggedIn(false);
- setChatgptLoading(false);
- } else {
- setChatgptLoading(true);
- try {
- const res = await commands.chatgptOauthLogin();
- if (res.status === "ok" && res.data) {
- setChatgptLoggedIn(true);
+ {chatgptChecking ? (
+ <Button type="button" variant="outline" disabled>
+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />
+ Checking connection...
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant={chatgptLoggedIn ? "outline" : "default"}
+ disabled={chatgptLoading}
+ onClick={async () => {
+ if (chatgptLoggedIn) {
+ setChatgptLoading(true);
+ await commands.chatgptOauthLogout();
+ setChatgptLoggedIn(false);
+ setChatgptLoading(false);
+ } else {
+ setChatgptLoading(true);
+ try {
+ const res = await commands.chatgptOauthLogin();
+ if (res.status === "ok" && res.data) {
+ setChatgptLoggedIn(true);
+ toast({
+ title: "ChatGPT connected",
+ description: "Click \"Create preset\" below to save and start using it.",
+ });
+ } else if (res.status === "error") {
+ const msg = String(res.error || "unknown error");
+ console.error("chatgpt oauth failed:", msg);
+ toast({
+ title: "ChatGPT sign-in failed",
+ description: msg.includes("invalid_state")
+ ? "Auth session expired — please try signing in again."
+ : msg.includes("not logged in") || msg.includes("timed out")
+ ? "Sign-in timed out or was cancelled. Please try again."
+ : msg.slice(0, 120),
+ variant: "destructive",
+ });
+ }
+ } catch (e) {
+ console.error("chatgpt oauth failed:", e);
+ toast({
+ title: "ChatGPT sign-in failed",
+ description: "An unexpected error occurred. Please try again.",
+ variant: "destructive",
+ });
}
- } catch (e) {
- console.error("chatgpt oauth failed:", e);
+ setChatgptLoading(false);
}
- setChatgptLoading(false);
- }
- }}
- >
- {chatgptLoading ? (
- <Loader2 className="h-4 w-4 mr-2 animate-spin" />
- ) : chatgptLoggedIn ? (
- <CheckCircle2 className="h-4 w-4 mr-2" />
- ) : null}
- {chatgptLoggedIn ? "Sign out" : "Sign in with ChatGPT"}
- </Button>
- {chatgptLoggedIn && (
- <span className="text-sm text-muted-foreground">Signed in</span>
+ }}
+ >
+ {chatgptLoading ? (
+ <Loader2 className="h-4 w-4 mr-2 animate-spin" />
+ ) : chatgptLoggedIn ? (
+ <CheckCircle2 className="h-4 w-4 mr-2" />
+ ) : null}
+ {chatgptLoggedIn ? "Sign out" : "Sign in with ChatGPT"}
+ </Button>
+ )}
+ {chatgptLoggedIn && !chatgptChecking && (
+ <span className="text-sm text-muted-foreground">Connected</span>
)}
</div>
</div>
@@ -1681,20 +1743,37 @@ const AISection = ({
>
Cancel
</Button>
- <Button
- onClick={updateStoreSettings}
- disabled={isLoading || !isFormValid}
- className="flex items-center gap-2"
- >
- {isLoading ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : isFormValid ? (
- <CheckCircle2 className="w-4 h-4" />
- ) : (
- <AlertCircle className="w-4 h-4" />
- )}
- {preset ? "Update preset" : "Create preset"}
- </Button>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ onClick={updateStoreSettings}
+ disabled={isLoading || !isFormValid}
+ className="flex items-center gap-2"
+ >
+ {isLoading ? (
+ <Loader2 className="w-4 h-4 animate-spin" />
+ ) : isFormValid ? (
+ <CheckCircle2 className="w-4 h-4" />
+ ) : (
+ <AlertCircle className="w-4 h-4" />
+ )}
+ {preset ? "Update preset" : "Create preset"}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {!isFormValid && !isLoading && (
+ <TooltipContent>
+ {!settingsPreset?.id
+ ? "Enter a preset name to continue"
+ : !settingsPreset?.model
+ ? "Select a model to continue"
+ : "Fix validation errors to continue"}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </TooltipProvider>
</div>
</div>
);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
index 411026b27..d685b92a4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
@@ -18,7 +18,9 @@
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use tauri::AppHandle;
+use sqlx::sqlite::SqliteConnectOptions;
+use std::str::FromStr;
+use tauri::{AppHandle, Manager};
use tauri_plugin_opener::OpenerExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tracing::{error, info, warn};
@@ -51,9 +53,15 @@ pub struct ChatGptOAuthStatus {
async fn open_secret_store() -> Result<screenpipe_secrets::SecretStore, String> {
let data_dir = screenpipe_core::paths::default_screenpipe_data_dir();
let db_path = data_dir.join("db.sqlite");
- let db_url = format!("sqlite:{}?mode=rwc", db_path.display());
- let pool = sqlx::SqlitePool::connect(&db_url)
+ // Use SqliteConnectOptions so busy_timeout is set correctly via PRAGMA,
+ // not just as an unrecognised query parameter.
+ let opts = SqliteConnectOptions::from_str(&format!("sqlite:{}", db_path.display()))
+ .map_err(|e| format!("invalid db path: {}", e))?
+ .create_if_missing(true)
+ .busy_timeout(std::time::Duration::from_secs(10));
+
+ let pool = sqlx::SqlitePool::connect_with(opts)
.await
.map_err(|e| format!("failed to open db: {}", e))?;
@@ -74,12 +82,28 @@ async fn read_tokens_from_store() -> Option<OAuthTokens> {
}
async fn write_tokens_to_store(tokens: &OAuthTokens) -> Result<(), String> {
- let store = open_secret_store().await?;
let json = serde_json::to_vec(tokens).map_err(|e| format!("serialize: {}", e))?;
- store
- .set(SECRET_KEY, &json)
- .await
- .map_err(|e| format!("failed to save token: {}", e))
+ // Retry up to 3 times — the screenpipe server may hold a brief write lock.
+ let mut last_err = String::new();
+ for attempt in 0..3u32 {
+ if attempt > 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(200 * (attempt as u64))).await;
+ }
+ match open_secret_store().await {
+ Ok(store) => match store.set(SECRET_KEY, &json).await {
+ Ok(()) => return Ok(()),
+ Err(e) => {
+ last_err = format!("failed to save token: {}", e);
+ warn!("write_tokens_to_store attempt {}: {}", attempt + 1, last_err);
+ }
+ },
+ Err(e) => {
+ last_err = e;
+ warn!("open_secret_store attempt {}: {}", attempt + 1, last_err);
+ }
+ }
+ }
+ Err(last_err)
}
async fn delete_tokens_from_store() -> Result<(), String> {
@@ -349,27 +373,30 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
write_tokens_to_store(&tokens).await?;
info!("ChatGPT OAuth login successful — token saved to secret store");
+ // Bring screenpipe back to the foreground so the user sees the preset form
+ // waiting for them — without this they stay on the browser "Login successful" tab.
+ if let Some(window) = app_handle.get_webview_window("main") {
+ let _ = tauri::WebviewWindow::set_focus(&window);
+ let _ = tauri::WebviewWindow::unminimize(&window);
+ }
+
Ok(true)
}
#[tauri::command]
#[specta::specta]
pub async fn chatgpt_oauth_status() -> Result<ChatGptOAuthStatus, String> {
- match read_tokens_from_store().await {
- Some(tokens) => {
- if is_token_expired(&tokens) {
- match do_refresh_token(&tokens.refresh_token).await {
- Ok(_) => Ok(ChatGptOAuthStatus { logged_in: true }),
- Err(e) => {
- error!("ChatGPT token refresh failed: {}", e);
- Ok(ChatGptOAuthStatus { logged_in: false })
- }
- }
- } else {
- Ok(ChatGptOAuthStatus { logged_in: true })
- }
- }
- None => Ok(ChatGptOAuthStatus { logged_in: false }),
+ // Only check token existence — no network refresh here.
+ // Refresh happens lazily in chatgpt_oauth_get_token when actually needed.
+ // 3-second timeout guards against a locked/slow SQLite DB.
+ match tokio::time::timeout(
+ std::time::Duration::from_secs(3),
+ read_tokens_from_store(),
+ )
+ .await
+ {
+ Ok(Some(_)) => Ok(ChatGptOAuthStatus { logged_in: true }),
+ Ok(None) | Err(_) => Ok(ChatGptOAuthStatus { logged_in: false }),
}
}