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
fix(sentry): retire 5 top issues across app, engine, and ai-gateway (#3663)
Louis Beaumont982e1b2849b8
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rsindex 0778c55a5..573418dbc 100644--- a/crates/screenpipe-core/src/agents/pi.rs+++ b/crates/screenpipe-core/src/agents/pi.rs@@ -1568,39 +1568,60 @@ fn seed_pi_package_json(install_dir: &Path) {}});if pkg_path.exists() {- if let Ok(contents) = std::fs::read_to_string(&pkg_path) {- if let Ok(mut pkg) = serde_json::from_str::<serde_json::Value>(&contents) {- let mut changed = false;- if let Some(obj) = pkg.as_object_mut() {- if obj.get("overrides") != Some(&expected_overrides) {- obj.insert("overrides".to_string(), expected_overrides.clone());+ let read_result = std::fs::read_to_string(&pkg_path);+ let parse_result = read_result+ .as_ref()+ .ok()+ .and_then(|c| serde_json::from_str::<serde_json::Value>(c).ok());+ // Detect corruption: a partial bun-install write can leave NUL bytes+ // in package.json (SCREENPIPE-APP-AR — bun then errors at SyntaxError).+ // Read failures and parse failures land here too. Wipe and re-seed+ // rather than silently exiting and letting the next `bun install`+ // re-fail on the same garbled file.+ let corrupted = parse_result.is_none()+ || read_result+ .as_ref()+ .map(|c| c.contains('\0'))+ .unwrap_or(true);+ if corrupted {+ warn!(+ "pi-agent package.json at {} is unreadable or corrupted — re-seeding",+ pkg_path.display()+ );+ let _ = std::fs::remove_file(&pkg_path);+ let _ = std::fs::remove_file(install_dir.join("bun.lock"));+ let _ = std::fs::remove_file(install_dir.join("bun.lockb"));+ // Fall through to the fresh-seed path below.+ } else if let Some(mut pkg) = parse_result {+ let mut changed = false;+ if let Some(obj) = pkg.as_object_mut() {+ if obj.get("overrides") != Some(&expected_overrides) {+ obj.insert("overrides".to_string(), expected_overrides.clone());+ changed = true;+ }+ if let Some(deps_obj) = obj.get_mut("dependencies").and_then(|d| d.as_object_mut())+ {+ let legacy: Vec<String> = deps_obj+ .keys()+ .filter(|k| k.starts_with("@mariozechner/"))+ .cloned()+ .collect();+ for k in &legacy {+ deps_obj.remove(k);changed = true;}- if let Some(deps_obj) =- obj.get_mut("dependencies").and_then(|d| d.as_object_mut())- {- let legacy: Vec<String> = deps_obj- .keys()- .filter(|k| k.starts_with("@mariozechner/"))- .cloned()- .collect();- for k in &legacy {- deps_obj.remove(k);- changed = true;- }- }}- if changed {- if let Ok(new_contents) = serde_json::to_string_pretty(&pkg) {- let _ = std::fs::write(&pkg_path, new_contents);- let _ = std::fs::remove_file(install_dir.join("bun.lock"));- let _ = std::fs::remove_file(install_dir.join("bun.lockb"));- info!("Patched pi-agent package.json (overrides + legacy dep cleanup)");- }+ }+ if changed {+ if let Ok(new_contents) = serde_json::to_string_pretty(&pkg) {+ let _ = std::fs::write(&pkg_path, new_contents);+ let _ = std::fs::remove_file(install_dir.join("bun.lock"));+ let _ = std::fs::remove_file(install_dir.join("bun.lockb"));+ info!("Patched pi-agent package.json (overrides + legacy dep cleanup)");}}+ return;}- return;}let pkg_json = json!({"overrides": {@@ -2360,4 +2381,42 @@ mod tests {assert_eq!(exec_a.current_user_token(), None);assert_eq!(exec_b.current_user_token(), None);}++ /// Regression guard for SCREENPIPE-APP-AR: a corrupted package.json+ /// (NUL bytes from a partial bun-install write) used to silently exit+ /// `seed_pi_package_json` and leave bun looping on the same broken file.+ #[test]+ fn seed_pi_package_json_recovers_from_nul_byte_corruption() {+ let dir = tempfile::tempdir().expect("tempdir");+ let pkg_path = dir.path().join("package.json");+ let lock_path = dir.path().join("bun.lock");++ // Simulate the observed corruption: garbled package name + NUL padding+ // (matches the actual bytes from `Pi background install failed`).+ std::fs::write(+ &pkg_path,+ b"{\n \"dependencies\": {\n \"@mariozech\0\0\0\0\0\0\0\0\0\0\0\0",+ )+ .expect("write corrupt pkg");+ std::fs::write(&lock_path, b"stale-lock").expect("write stale lock");++ seed_pi_package_json(dir.path());++ let contents = std::fs::read_to_string(&pkg_path).expect("re-seeded pkg readable");+ assert!(+ !contents.contains('\0'),+ "re-seeded package.json must not contain NUL bytes; got: {:?}",+ contents+ );+ let parsed: serde_json::Value =+ serde_json::from_str(&contents).expect("re-seeded pkg must parse");+ assert!(+ parsed.get("overrides").is_some(),+ "re-seeded pkg must include the lru-cache overrides"+ );+ assert!(+ !lock_path.exists(),+ "stale bun.lock must be cleared so bun re-resolves from the fresh manifest"+ );+ }}diff --git a/crates/screenpipe-engine/src/auth_key.rs b/crates/screenpipe-engine/src/auth_key.rsindex 70c305fe8..88afca83f 100644--- a/crates/screenpipe-engine/src/auth_key.rs+++ b/crates/screenpipe-engine/src/auth_key.rs@@ -37,17 +37,20 @@ pub async fn resolve_api_auth_key(data_dir: &Path, settings_key: Option<&str>) -// can read the secrets table but the keychain ACL denies the decrypt// for `screenpi.pe`. Result: rotation, mismatched in-memory caches,// 401 storms — observed for [email protected] 2026-05-06.+ let mut stored_unreadable = false;let stored_key: Option<String> = if let Some(ref s) = store {match s.get("api_auth_key").await {Ok(Some(bytes)) => String::from_utf8(bytes).ok().filter(|k| !k.is_empty()),Ok(None) => None,Err(e) => {+ stored_unreadable = true;tracing::error!("api auth: failed to read api_auth_key from secret store — \- resolver will fall through to auto-generate, rotating the \- key out from under cached consumers. Likely cause: keychain \- ACL mismatch (dev↔prod bundle id, recent encryption toggle, \- or revoked keychain item). Error: {}",+ keeping the encrypted blob intact and minting a one-shot \+ ephemeral key for this process to avoid overwriting the \+ user's persisted key. Likely cause: keychain ACL mismatch \+ (dev↔prod bundle id, recent encryption toggle, or revoked \+ keychain item). Error: {}",e);None@@ -72,8 +75,15 @@ pub async fn resolve_api_auth_key(data_dir: &Path, settings_key: Option<&str>) -// reader (running server, MCP, `screenpipe auth token` CLI) agrees on// the same value regardless of which source it originally came from.// Skip the write if the stored value already matches.+ //+ // SAFETY: never persist when the existing row was unreadable. Writing+ // would clobber the encrypted blob with a fresh plaintext key, silently+ // rotating the user's API key (SCREENPIPE-APP-9Z: 25 events / 18 users,+ // including the Pattern.com whitelabel build). The in-memory key still+ // works for this process; the user can recover by clearing the secrets+ // table or restoring the keychain item.if let Some(s) = store {- if stored_key.as_deref() != Some(key.as_str()) {+ if !stored_unreadable && stored_key.as_deref() != Some(key.as_str()) {if let Err(e) = s.set("api_auth_key", key.as_bytes()).await {tracing::warn!("failed to persist api auth key: {}", e);}diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rsindex af081e684..c5639beae 100644--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs@@ -500,6 +500,9 @@ async fn main() -> anyhow::Result<()> {r"no such table: main\.speaker_embeddings",// Concurrent DB access / user ran CLI while app was runningr"database is locked",+ // Port conflict — another screenpipe instance is already bound+ // (CLI-2J: 659 events / 649 users — user environment, not a bug)+ r"you're likely already running screenpipe instance",// Broken Homebrew install — external dylib missingr"Library not loaded.*libx265\.",// Linux system library missing — distro-local, not our bugdiff --git a/packages/ai-gateway/src/providers/gemini.ts b/packages/ai-gateway/src/providers/gemini.tsindex ae5957353..e239885a2 100644--- a/packages/ai-gateway/src/providers/gemini.ts+++ b/packages/ai-gateway/src/providers/gemini.ts@@ -650,7 +650,15 @@ export class GeminiProvider implements AIProvider {const converted: any = { type: rawType.toUpperCase() };if (params.description) converted.description = params.description;- if (params.enum) converted.enum = params.enum;+ // Gemini requires enum values to be TYPE_STRING regardless of the+ // declared property type — upstream tools with integer/boolean enums+ // (e.g. `enum: [4, 5, 6, 7]`) 400 with "Invalid value at … (TYPE_STRING)".+ // Coerce every entry to string so the request survives. SCREENPIPE-AI-PROXY-8.+ if (Array.isArray(params.enum)) {+ converted.enum = params.enum.map((v: unknown) =>+ typeof v === 'string' ? v : String(v)+ );+ }if (rawType === 'object' || params.properties) {converted.type = 'OBJECT';diff --git a/packages/ai-gateway/src/services/cost-tracker.ts b/packages/ai-gateway/src/services/cost-tracker.tsindex b7e87188c..31f33c700 100644--- a/packages/ai-gateway/src/services/cost-tracker.ts+++ b/packages/ai-gateway/src/services/cost-tracker.ts@@ -77,7 +77,10 @@ const DEFAULT_OUTPUT_TOKENS = 500;* Fuzzy-match a model string to a pricing entry.* E.g. "claude-haiku-4-5-20251001" → "claude-haiku-4-5"*/-function findPricing(model: string): ModelPricing | null {+function findPricing(model: string | null | undefined): ModelPricing | null {+ // Callers (isZeroCostModel, getModelCost, inferProvider) are reached from+ // request-parsing paths that don't enforce a model field. SCREENPIPE-AI-PROXY-1D.+ if (typeof model !== 'string' || model.length === 0) return null;const lower = model.toLowerCase();// Exact match firstif (MODEL_PRICING[lower]) return MODEL_PRICING[lower];@@ -96,7 +99,7 @@ function findPricing(model: string): ModelPricing | null {* When tokens are unknown (streaming without usage tracking), estimates based* on average request size and the model's actual pricing — NOT a flat fallback.*/-export function getModelCost(model: string, inputTokens: number | null, outputTokens: number | null): number {+export function getModelCost(model: string | null | undefined, inputTokens: number | null, outputTokens: number | null): number {const pricing = findPricing(model);if (!pricing) {// Unknown model — use a conservative estimate@@ -153,7 +156,8 @@ export async function logCost(env: Env, entry: CostLogEntry): Promise<void> {/*** Determine provider from model name.*/-export function inferProvider(model: string): string {+export function inferProvider(model: string | null | undefined): string {+ if (typeof model !== 'string' || model.length === 0) return 'unknown';const lower = model.toLowerCase();if (lower.includes('claude')) return 'anthropic';if (lower.includes('gpt') || lower.includes('o1') || lower.includes('o3') || lower.includes('o4')) return 'openai';@@ -166,7 +170,7 @@ export function inferProvider(model: string): string {}/** Returns true for models that cost us $0 (free on OpenRouter, free Gemini tier, etc.) */-export function isZeroCostModel(model: string): boolean {+export function isZeroCostModel(model: string | null | undefined): boolean {const pricing = findPricing(model);return pricing !== null && pricing.input === 0 && pricing.output === 0;}diff --git a/packages/ai-gateway/src/test/gemini.unit.test.ts b/packages/ai-gateway/src/test/gemini.unit.test.tsindex 436f5b1ea..6635885a6 100644--- a/packages/ai-gateway/src/test/gemini.unit.test.ts+++ b/packages/ai-gateway/src/test/gemini.unit.test.ts@@ -142,6 +142,29 @@ describe('GeminiProvider tool schema conversion (Sentry SCREENPIPE-AI-PROXY-9)',expect(out.properties.status.enum).toEqual(['ok', 'error']);});+ it('coerces non-string enum values to strings (SCREENPIPE-AI-PROXY-8)', () => {+ // Gemini requires TYPE_STRING enum entries — upstream tools with+ // numeric/boolean enums (e.g. priority levels [1,2,3,4]) 400 otherwise.+ const out = convert({+ type: 'object',+ properties: {+ priority: { type: 'integer', enum: [1, 2, 3, 4] },+ active: { type: 'boolean', enum: [true, false] },+ },+ });+ expect(out.properties.priority.enum).toEqual(['1', '2', '3', '4']);+ expect(out.properties.active.enum).toEqual(['true', 'false']);+ });++ it('drops enum when params.enum is not an array', () => {+ const out = convert({+ type: 'string',+ // malformed upstream schema — `enum` should be array but came as object+ enum: { invalid: 'shape' } as any,+ });+ expect(out.enum).toBeUndefined();+ });+it('preserves required arrays at every depth', () => {const out = convert({type: 'object',diff --git a/packages/ai-gateway/src/test/openai-models.unit.test.ts b/packages/ai-gateway/src/test/openai-models.unit.test.tsindex ebba417ae..ece708e47 100644--- a/packages/ai-gateway/src/test/openai-models.unit.test.ts+++ b/packages/ai-gateway/src/test/openai-models.unit.test.ts@@ -123,6 +123,20 @@ describe('OpenAI API accounting and routing', () => {expect(isZeroCostModel('gpt-5.4-nano')).toBe(false);});+ it('does not crash when model is undefined / null / empty (SCREENPIPE-AI-PROXY-1D)', () => {+ // Request bodies without a model field used to crash findPricing at+ // `model.toLowerCase()` — propagated through isZeroCostModel and+ // killed the request handler.+ expect(() => isZeroCostModel(undefined as any)).not.toThrow();+ expect(() => isZeroCostModel(null as any)).not.toThrow();+ expect(() => isZeroCostModel('')).not.toThrow();+ expect(isZeroCostModel(undefined as any)).toBe(false);+ expect(inferProvider(undefined as any)).toBe('unknown');+ expect(inferProvider(null as any)).toBe('unknown');+ // getModelCost returns the conservative fallback when pricing is null+ expect(getModelCost(undefined as any, null, null)).toBe(0.01);+ });+it('assigns quota weights for expensive and cheap OpenAI models', () => {expect(getModelWeight('gpt-5.5-pro')).toBe(36);expect(getModelWeight('gpt-5.5')).toBe(6);