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(chat): send real API keys to pi 0.80.6 providers and reject ChatGPT OAuth tokens missing account id (#5216)

Ansh Grover0fc816c980fd
diff --git a/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts b/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
index 9d087ab89..088224578 100644
--- a/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
@@ -65,6 +65,30 @@ describe("provider error copy", () => {
).toContain("Can't reach the AI provider");
});
+ it("maps the ChatGPT missing-account-id error to reconnect guidance", () => {
+ // exact string thrown by pi's openai-codex-responses provider when the
+ // OAuth access token lacks the chatgpt_account_id claim (Enterprise/
+ // Business workspaces without Codex local access enabled)
+ const msg = buildProviderErrorMessage("Failed to extract accountId from token", {
+ provider: "openai-chatgpt",
+ model: "gpt-5.2-codex",
+ });
+
+ expect(msg).toContain("ChatGPT account id");
+ expect(msg).toContain("Reconnect ChatGPT");
+ // provider-independent: the error string alone identifies the failure
+ expect(
+ buildProviderErrorMessage("Error: Failed to extract accountId from token", null)
+ ).toContain("ChatGPT account id");
+ });
+
+ it("does not map unrelated token errors to the ChatGPT account-id message", () => {
+ expect(buildProviderErrorMessage("invalid token", { provider: "openai-chatgpt" })).toBeNull();
+ expect(
+ buildProviderErrorMessage("failed to extract something else", { provider: "openai-chatgpt" })
+ ).toBeNull();
+ });
+
it("leaves non-connection cloud errors untouched (quota/auth handled elsewhere)", () => {
expect(
buildProviderErrorMessage("model_not_allowed", { provider: "screenpipe-cloud", model: "auto" })
diff --git a/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts b/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
index 11975e865..475dd885b 100644
--- a/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
@@ -92,6 +92,10 @@ export function buildContextOverflowMessage(): string {
return "This chat is too long for the selected model. Start a new chat, ask a narrower question, or remove large attachments/screenshots before trying again.";
}
+export function buildChatGptAccountIdMessage(): string {
+ return "Your ChatGPT sign-in doesn't include chat access: the login token has no ChatGPT account id. This usually means an Enterprise/Business workspace where the admin hasn't enabled Codex local app access. Reconnect ChatGPT in Settings → AI with a personal account, or ask your workspace admin to enable access.";
+}
+
export function buildProviderErrorMessage(
errorStr: string,
preset?: ProviderLike | null
@@ -104,6 +108,13 @@ export function buildProviderErrorMessage(
return buildContextOverflowMessage();
}
+ // ChatGPT OAuth tokens from Enterprise/Business workspaces can lack the
+ // chatgpt_account_id claim the Codex backend requires — the pi provider
+ // then throws "Failed to extract accountId from token" on every turn.
+ if (normalized.includes("failed to extract accountid")) {
+ return buildChatGptAccountIdMessage();
+ }
+
if (isNativeOllamaProvider(provider)) {
if (normalized.includes("not found")) {
return model
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 8e520495d..b72969c6a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/chatgpt_oauth.rs
@@ -171,6 +171,40 @@ fn unix_now() -> u64 {
.as_secs()
}
+// ── Account-id claim validation ────────────────────────────────────────
+
+/// JWT claim namespace that carries the ChatGPT account id. The Codex
+/// backend requires this id as the `chatgpt-account-id` header on every
+/// chat request, so a token without it can never be used for chat.
+const JWT_AUTH_CLAIM: &str = "https://api.openai.com/auth";
+
+/// User-facing explanation for tokens missing the account-id claim.
+/// Enterprise/Business workspace tokens lack it unless the workspace admin
+/// enables Codex local app access (same failure class as Codex CLI's
+/// "No eligible ChatGPT workspaces found").
+const MISSING_ACCOUNT_ID_MSG: &str = "This ChatGPT account can't be used for chat: its login \
+ token has no ChatGPT account id. This usually means an Enterprise/Business workspace where \
+ the admin hasn't enabled Codex local app access. Ask your workspace admin to enable it, or \
+ sign in with a personal ChatGPT account.";
+
+/// Extract the `chatgpt_account_id` claim from an access token JWT.
+/// Returns `None` for non-JWT strings (e.g. API keys) or tokens without
+/// the claim — the same check pi's Codex provider performs on every request.
+fn extract_chatgpt_account_id(access_token: &str) -> Option<String> {
+ let mut parts = access_token.split('.');
+ let payload_b64 = match (parts.next(), parts.next(), parts.next(), parts.next()) {
+ (Some(_), Some(payload), Some(_), None) => payload,
+ _ => return None,
+ };
+ let payload_bytes = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
+ let payload: serde_json::Value = serde_json::from_slice(&payload_bytes).ok()?;
+ let account_id = payload.get(JWT_AUTH_CLAIM)?.get("chatgpt_account_id")?;
+ account_id
+ .as_str()
+ .filter(|s| !s.is_empty())
+ .map(|s| s.to_string())
+}
+
// ── PKCE helpers ───────────────────────────────────────────────────────
fn generate_pkce() -> (String, String) {
@@ -231,6 +265,14 @@ async fn do_refresh_token(refresh_token: &str) -> Result<OAuthTokens, String> {
let expires_in = v["expires_in"].as_u64().unwrap_or(3600);
+ // A refreshed token without the account-id claim would make every chat
+ // turn fail in the Codex provider — keep the old (still stored) token
+ // instead of overwriting a working credential.
+ if extract_chatgpt_account_id(&new_access_token).is_none() {
+ warn!("ChatGPT token refresh returned a token without chatgpt_account_id — not storing it");
+ return Err(MISSING_ACCOUNT_ID_MSG.to_string());
+ }
+
let tokens = OAuthTokens {
access_token: new_access_token,
refresh_token: new_refresh_token,
@@ -507,6 +549,13 @@ pub async fn chatgpt_oauth_login(app_handle: AppHandle) -> Result<bool, String>
let expires_in = v["expires_in"].as_u64().unwrap_or(3600);
+ // Fail fast at login instead of letting every chat turn die later with
+ // the pi provider's opaque "Failed to extract accountId from token".
+ if extract_chatgpt_account_id(&access_token).is_none() {
+ warn!("ChatGPT OAuth login returned a token without chatgpt_account_id — rejecting login");
+ return Err(MISSING_ACCOUNT_ID_MSG.to_string());
+ }
+
let tokens = OAuthTokens {
access_token,
refresh_token,
@@ -620,3 +669,61 @@ pub async fn chatgpt_oauth_check_token() -> Result<bool, String> {
Err(_) => Ok(false),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn make_jwt(payload: serde_json::Value) -> String {
+ let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"RS256","typ":"JWT"}"#);
+ let body = URL_SAFE_NO_PAD.encode(payload.to_string().as_bytes());
+ format!("{}.{}.sig", header, body)
+ }
+
+ #[test]
+ fn extracts_account_id_from_valid_token() {
+ let token = make_jwt(serde_json::json!({
+ JWT_AUTH_CLAIM: { "chatgpt_account_id": "acc-123" }
+ }));
+ assert_eq!(
+ extract_chatgpt_account_id(&token),
+ Some("acc-123".to_string())
+ );
+ }
+
+ #[test]
+ fn rejects_token_without_claim() {
+ // Enterprise/workspace-shaped token: auth namespace present but no account id.
+ let token = make_jwt(serde_json::json!({
+ JWT_AUTH_CLAIM: { "organizations": ["org-1"] }
+ }));
+ assert_eq!(extract_chatgpt_account_id(&token), None);
+ }
+
+ #[test]
+ fn rejects_token_without_auth_namespace() {
+ let token = make_jwt(serde_json::json!({ "sub": "user-1" }));
+ assert_eq!(extract_chatgpt_account_id(&token), None);
+ }
+
+ #[test]
+ fn rejects_empty_account_id() {
+ let token = make_jwt(serde_json::json!({
+ JWT_AUTH_CLAIM: { "chatgpt_account_id": "" }
+ }));
+ assert_eq!(extract_chatgpt_account_id(&token), None);
+ }
+
+ #[test]
+ fn rejects_non_jwt_strings() {
+ assert_eq!(extract_chatgpt_account_id("sk-proj-not-a-jwt"), None);
+ assert_eq!(extract_chatgpt_account_id(""), None);
+ assert_eq!(extract_chatgpt_account_id("a.b"), None);
+ assert_eq!(extract_chatgpt_account_id("a.b.c.d"), None);
+ }
+
+ #[test]
+ fn rejects_malformed_base64_payload() {
+ assert_eq!(extract_chatgpt_account_id("head.%%%not-base64%%%.sig"), None);
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 2bf642480..f27952cc4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -1318,8 +1318,10 @@ async fn build_models_json(
) -> serde_json::Value {
let mut providers_map = serde_json::Map::new();
- // Always add screenpipe cloud provider
- let api_key_value = user_token.unwrap_or("SCREENPIPE_API_KEY");
+ // Always add screenpipe cloud provider. A real token is inlined as a
+ // literal; the logged-out fallback must use `$` env-var syntax (pi >= 0.80
+ // treats bare names as literal keys).
+ let api_key_value = user_token.unwrap_or("$SCREENPIPE_API_KEY");
let models = screenpipe_cloud_models(SCREENPIPE_API_URL, user_token).await;
let screenpipe_provider = json!({
"baseUrl": SCREENPIPE_API_URL,
@@ -1360,12 +1362,15 @@ async fn build_models_json(
provider_name
);
} else {
+ // pi >= 0.80 requires explicit `$NAME` syntax for env-var
+ // references; a bare name is sent to the provider as a literal
+ // API key (401 "Incorrect API key provided: CUSTOM_A**_KEY").
let api_key = match config.provider.as_str() {
"native-ollama" => "ollama".to_string(),
- "openai" => "OPENAI_API_KEY".to_string(),
- "openai-chatgpt" => "OPENAI_CHATGPT_TOKEN".to_string(),
- "anthropic" => "ANTHROPIC_API_KEY".to_string(),
- "custom" => "CUSTOM_API_KEY".to_string(),
+ "openai" => "$OPENAI_API_KEY".to_string(),
+ "openai-chatgpt" => "$OPENAI_CHATGPT_TOKEN".to_string(),
+ "anthropic" => "$ANTHROPIC_API_KEY".to_string(),
+ "custom" => "$CUSTOM_API_KEY".to_string(),
_ => "".to_string(),
};
@@ -4722,7 +4727,8 @@ error: InstallFailed extracting tarball"#;
let sp = &providers["screenpipe"];
assert_eq!(sp["baseUrl"], "https://api.screenpipe.com/v1");
assert_eq!(sp["api"], "openai-completions");
- assert_eq!(sp["apiKey"], "SCREENPIPE_API_KEY");
+ // `$` prefix is required: pi >= 0.80 treats bare names as literal keys
+ assert_eq!(sp["apiKey"], "$SCREENPIPE_API_KEY");
assert_eq!(sp["authHeader"], true);
assert!(sp["models"].as_array().unwrap().len() > 0);
}
@@ -4756,13 +4762,38 @@ error: InstallFailed extracting tarball"#;
let openai = &providers["openai-byok"];
assert_eq!(openai["baseUrl"], "https://api.openai.com/v1");
assert_eq!(openai["api"], "openai-completions");
- assert_eq!(openai["apiKey"], "OPENAI_API_KEY");
+ assert_eq!(openai["apiKey"], "$OPENAI_API_KEY");
let models = openai["models"].as_array().unwrap();
assert_eq!(models.len(), 1);
assert_eq!(models[0]["id"], "gpt-4o");
assert_eq!(models[0]["reasoning"], false);
}
+ #[tokio::test]
+ async fn test_build_models_json_api_keys_use_env_var_syntax() {
+ // Regression: pi >= 0.80 sends bare apiKey strings to the provider as
+ // literal keys (user-reported 401 "Incorrect API key provided:
+ // CUSTOM_A**_KEY"; ChatGPT OAuth failed the same way via
+ // "Failed to extract accountId from token"). Env references must be
+ // written as `$NAME`.
+ for (provider, provider_key, expected) in [
+ ("openai", "openai-byok", "$OPENAI_API_KEY"),
+ ("openai-chatgpt", "openai-chatgpt", "$OPENAI_CHATGPT_TOKEN"),
+ ("anthropic", "anthropic-byok", "$ANTHROPIC_API_KEY"),
+ ("custom", "custom", "$CUSTOM_API_KEY"),
+ ] {
+ let mut pc = make_provider_config(provider, "some-model");
+ if provider == "custom" {
+ pc.url = "https://example.com/v1".to_string();
+ }
+ let config = build_models_json(None, Some(&pc)).await;
+ assert_eq!(
+ config["providers"][provider_key]["apiKey"], expected,
+ "provider {provider} must reference its key as {expected}"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_build_models_json_chatgpt_gpt55_supports_reasoning() {
let pc = make_provider_config("openai-chatgpt", "gpt-5.5");
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index c24be6de0..dcfa580dc 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -882,13 +882,14 @@ impl PiExecutor {
};
if should_add_screenpipe {
- // Use actual token value in apiKey — Pi doesn't resolve env var names,
- // so writing the literal string "SCREENPIPE_API_KEY" causes tier=anonymous.
- // Resolve from: argument > env var > literal fallback (last resort).
+ // Use actual token value in apiKey — Pi doesn't resolve bare env var
+ // names, so writing the literal string "SCREENPIPE_API_KEY" causes
+ // tier=anonymous. Resolve from: argument > env var > `$` env-var
+ // reference (last resort; resolves at pi runtime if the var appears).
let api_key_value = user_token
.map(|t| t.to_string())
.or_else(|| std::env::var("SCREENPIPE_API_KEY").ok())
- .unwrap_or_else(|| "SCREENPIPE_API_KEY".to_string());
+ .unwrap_or_else(|| "$SCREENPIPE_API_KEY".to_string());
let api_key_value = api_key_value.as_str();
let models = screenpipe_cloud_models(api_url, user_token).await;
// PiExecutor only runs pipes (PipeManager: scheduled / run-now),
@@ -924,22 +925,24 @@ impl PiExecutor {
provider_url.unwrap_or("http://localhost:11434/v1"),
"ollama",
),
+ // `$NAME` is pi's explicit env-var reference syntax; pi >= 0.80
+ // sends bare names to the provider as literal API keys.
"openai" => (
"openai-byok",
provider_url.unwrap_or("https://api.openai.com/v1"),
- "OPENAI_API_KEY",
+ "$OPENAI_API_KEY",
),
"openai-chatgpt" => (
"openai-chatgpt",
"https://chatgpt.com/backend-api",
- "OPENAI_CHATGPT_TOKEN",
+ "$OPENAI_CHATGPT_TOKEN",
),
"anthropic" => (
"anthropic-byok",
provider_url.unwrap_or("https://api.anthropic.com"),
- "ANTHROPIC_API_KEY",
+ "$ANTHROPIC_API_KEY",
),
- other => (other, provider_url.unwrap_or(""), "CUSTOM_API_KEY"),
+ other => (other, provider_url.unwrap_or(""), "$CUSTOM_API_KEY"),
};
// Pi's models.json schema requires baseUrl to have minLength: 1.