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
Bump app to v2.0.88
Louis Beaumont77a7d66d2ca5
diff --git a/content/changelogs/v2.0.88.md b/content/changelogs/v2.0.88.mdnew file mode 100644index 000000000..9dfb06acd--- /dev/null+++ b/content/changelogs/v2.0.88.md@@ -0,0 +1,6 @@+## Bug Fixes+- Fixed timeline navigation jumping back when switching days+- Fixed reset button being incorrectly disabled+- Improved app suggestion autocomplete with dynamic filtering++#### **Full Changelog:** [0e5332dc..5615a230](https://github.com/mediar-ai/screenpipe/compare/0e5332dc..5615a230)diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsxindex 143b8e9a7..2267c10d2 100644--- a/screenpipe-app-tauri/components/global-chat.tsx+++ b/screenpipe-app-tauri/components/global-chat.tsx@@ -924,9 +924,10 @@ export function GlobalChat() {function getOpenAIClient(): OpenAI | null {if (!activePreset) return null;+ // For screenpipe-cloud, use token if available, otherwise "anonymous" for free tierconst apiKey =activePreset.provider === "screenpipe-cloud"- ? settings.user?.token || ""+ ? settings.user?.token || "anonymous": "apiKey" in activePreset? (activePreset.apiKey as string) || "": "";@@ -937,10 +938,17 @@ export function GlobalChat() {? "https://ai-proxy.i-f9f.workers.dev/v1": activePreset.url;+ // Add device ID header for usage tracking (free tier)+ const defaultHeaders: Record<string, string> = {};+ if (activePreset.provider === "screenpipe-cloud" && settings.deviceId) {+ defaultHeaders["X-Device-Id"] = settings.deviceId;+ }+return new OpenAI({apiKey,baseURL,dangerouslyAllowBrowser: true,+ defaultHeaders,});}@@ -1336,7 +1344,7 @@ export function GlobalChat() {<Buttonvariant="default"onClick={() => openUrl("https://screenpi.pe/login")}- className="gap-2 font-medium"+ className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"><ExternalLink className="h-4 w-4" />Login@@ -1516,7 +1524,10 @@ export function GlobalChat() {<div className="absolute top-0 left-4 right-4 h-px bg-gradient-to-r from-transparent via-border/50 to-transparent" /><div className="p-2 border-b border-border/30">- <AIPresetsSelector onPresetChange={setActivePreset} />+ <AIPresetsSelector+ onPresetChange={setActivePreset}+ showLoginCta={false}+ /></div><form onSubmit={handleSubmit} className="p-3">{/* Time context indicator */}diff --git a/screenpipe-app-tauri/components/onboarding/api-setup.tsx b/screenpipe-app-tauri/components/onboarding/api-setup.tsxindex 82c6c259f..4a49e7057 100644--- a/screenpipe-app-tauri/components/onboarding/api-setup.tsx+++ b/screenpipe-app-tauri/components/onboarding/api-setup.tsx@@ -45,14 +45,16 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({// Check if the preset has the required fieldsconst { url, model, provider } = defaultPreset;- const isApiKeyRequired =- url !== "https://ai-proxy.i-f9f.workers.dev/v1" &&+ const isApiKeyRequired =+ url !== "https://ai-proxy.i-f9f.workers.dev/v1" &&url !== "http://localhost:11434/v1";-+// Check if API key is required and present- const hasRequiredApiKey = !isApiKeyRequired ||- ((provider === "openai" || provider === "custom") &&- "apiKey" in defaultPreset &&+ // Screenpipe Cloud no longer requires API key - works with free tier+ const hasRequiredApiKey = !isApiKeyRequired ||+ provider === "screenpipe-cloud" ||+ ((provider === "openai" || provider === "custom") &&+ "apiKey" in defaultPreset &&defaultPreset.apiKey?.trim() !== "");return url?.trim() !== "" &&@@ -80,24 +82,31 @@ const OnboardingAPISetup: React.FC<OnboardingAPISetupProps> = ({const { url, model, provider } = defaultPreset;// Get API key if available based on provider- const apiKey = (provider === "openai" || provider === "custom") && "apiKey" in defaultPreset- ? defaultPreset.apiKey+ // For screenpipe-cloud, use "anonymous" if not logged in (free tier)+ const apiKey = (provider === "openai" || provider === "custom") && "apiKey" in defaultPreset+ ? defaultPreset.apiKey: provider === "screenpipe-cloud"- ? settings?.user?.token+ ? settings?.user?.token || "anonymous": "";-+const t = toast({title: "Validating AI provider",description: "Please wait...",duration: 10000,});-++ // Build headers - include device ID for screenpipe-cloud usage tracking+ const headers: Record<string, string> = {+ "Content-Type": "application/json",+ Authorization: `Bearer ${apiKey}`,+ };+ if (provider === "screenpipe-cloud" && settings?.deviceId) {+ headers["X-Device-Id"] = settings.deviceId;+ }+const response = await fetch(`${url}/chat/completions`, {method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${apiKey}`,- },+ headers,body: JSON.stringify({model: model,messages: [diff --git a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsxindex 1be8271c2..94387e785 100644--- a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx+++ b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx@@ -105,6 +105,7 @@ type RecommendedPreset = BaseRecommendedPreset &interface AIProviderConfigProps {onSubmit: (data: AIPreset) => void;defaultPreset?: AIPreset;+ showLoginCta?: boolean;}interface OpenAIModel {id: string;@@ -122,6 +123,7 @@ export const DEFAULT_PROMPT = `Rules:export function AIProviderConfig({onSubmit,defaultPreset,+ showLoginCta = true,}: AIProviderConfigProps) {const [selectedProvider, setSelectedProvider] = useState<AIPreset["provider"]@@ -290,16 +292,18 @@ export function AIProviderConfig({This preset uses Screenpipe Cloud. Please log in to your Screenpipe account to edit it.</p></div>- <Button- onClick={async () => {- // Open settings window at account section- await commands.showWindow({ Settings: { page: "account" } });- }}- className="gap-2"- >- <LogIn className="h-4 w-4" />- Go to Login- </Button>+ {showLoginCta && (+ <Button+ onClick={async () => {+ // Open settings window at account section+ await commands.showWindow({ Settings: { page: "account" } });+ }}+ className="gap-2"+ >+ <LogIn className="h-4 w-4" />+ Go to Login+ </Button>+ )}</div></div>);@@ -719,12 +723,14 @@ interface AIPresetDialogProps {onOpenChange: (open: boolean) => void;onSave: (preset: Partial<AIPreset>) => void;preset?: AIPreset;+ showLoginCta?: boolean;}interface AIPresetsSelectorProps {recommendedPresets?: RecommendedPreset[];shortcutKey?: string;onPresetChange?: (preset: AIPreset) => void;+ showLoginCta?: boolean;}export const AIPresetDialog = ({@@ -732,6 +738,7 @@ export const AIPresetDialog = ({onOpenChange,onSave,preset,+ showLoginCta = true,}: AIPresetDialogProps) => {const handleProviderSubmit = (providerData: any) => {const newPreset: Partial<AIPreset> = {@@ -784,6 +791,7 @@ export const AIPresetDialog = ({<AIProviderConfigonSubmit={handleProviderSubmit}defaultPreset={defaultPreset}+ showLoginCta={showLoginCta}/></DialogContent></Dialog>@@ -794,6 +802,7 @@ export const AIPresetsSelector = ({recommendedPresets,shortcutKey = "/",onPresetChange,+ showLoginCta = true,}: AIPresetsSelectorProps) => {const { settings, updateSettings } = useSettings();const [open, setOpen] = useState(false);@@ -1035,17 +1044,19 @@ export const AIPresetsSelector = ({<span className="text-amber-600 dark:text-amber-400 flex-1">Login required to use Screenpipe Cloud</span>- <Button- variant="outline"- size="sm"- className="shrink-0 h-7 text-xs border-amber-500/30 hover:bg-amber-500/10"- onClick={async () => {- await commands.showWindow({ Settings: { page: "account" } });- }}- >- <LogIn className="h-3 w-3 mr-1" />- Login- </Button>+ {showLoginCta && (+ <Button+ variant="outline"+ size="sm"+ className="shrink-0 h-7 text-xs border-amber-500/30 hover:bg-amber-500/10"+ onClick={async () => {+ await commands.showWindow({ Settings: { page: "account" } });+ }}+ >+ <LogIn className="h-3 w-3 mr-1" />+ Login+ </Button>+ )}</div>)}<div className="flex w-full items-center gap-2">@@ -1335,6 +1346,7 @@ export const AIPresetsSelector = ({onOpenChange={setDialogOpen}onSave={handleSavePreset}preset={selectedPresetToEdit}+ showLoginCta={showLoginCta}/></>);diff --git a/screenpipe-app-tauri/components/settings/ai-presets.tsx b/screenpipe-app-tauri/components/settings/ai-presets.tsxindex d1a0df6ae..c3f66a746 100644--- a/screenpipe-app-tauri/components/settings/ai-presets.tsx+++ b/screenpipe-app-tauri/components/settings/ai-presets.tsx@@ -537,17 +537,17 @@ const AISection = ({<AIProviderCardtype="screenpipe-cloud"title="Screenpipe Cloud"- description="Use OpenAI, Anthropic and Google models without worrying about API keys or usage"+ description="Use AI models instantly. Free: 25 queries/day. Login for 50/day. Subscribe for unlimited."imageSrc="/images/screenpipe.png"selected={settingsPreset?.provider === "screenpipe-cloud"}onClick={() => handleAiProviderChange("screenpipe-cloud")}- disabled={!settings.user}+ disabled={false}warningText={!settings.user- ? "Login required"- : !settings.user?.credits?.amount- ? "Requires credits"- : undefined+ ? "Free: 25/day"+ : settings.user?.cloud_subscribed+ ? "Unlimited"+ : "50/day"}/>@@ -653,19 +653,13 @@ const AISection = ({!settingsPreset?.model && "text-muted-foreground")}disabled={- (settingsPreset?.provider === "openai" &&- !settingsPreset?.apiKey) ||- (settingsPreset?.provider === "screenpipe-cloud" &&- (!settings.user ||- settings.user.cloud_subscribed === false))+ settingsPreset?.provider === "openai" &&+ !settingsPreset?.apiKey}>{settingsPreset?.provider === "openai" &&!settingsPreset?.apiKey? "API key required to fetch models"- : settingsPreset?.provider === "screenpipe-cloud" &&- (!settings.user || settings.user.cloud_subscribed === false)- ? "Subscription required to access models": settingsPreset?.model || "Select model..."}<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /></Button>diff --git a/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex 46a8ae3d9..d4065e74e 100644--- a/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -52,7 +52,11 @@ export type AIPreset = {});-export type Settings = SettingsStore+// Extend SettingsStore with deviceId (for AI free tier tracking)+// This is added here until the Rust types are regenerated+export type Settings = SettingsStore & {+ deviceId?: string;+}export const DEFAULT_PROMPT = `Rules:- You can analyze/view/show/access videos to the user by putting .mp4 files in a code block (we'll render it) like this: \`/users/video.mp4\`, use the exact, absolute, file path from file_path property@@ -94,8 +98,21 @@ const DEFAULT_IGNORED_WINDOWS_PER_OS: Record<string, string[]> = {linux: ["Info center", "Discover", "Parted"],};+// Default free AI preset that works without login+// Note: screenpipe-cloud provider doesn't require apiKey+const DEFAULT_FREE_PRESET: AIPreset = {+ id: "screenpipe-free",+ provider: "screenpipe-cloud",+ url: "https://ai-proxy.i-f9f.workers.dev/v1",+ model: "claude-haiku-4-5@20251001",+ maxContextChars: 128000,+ defaultPreset: true,+ prompt: DEFAULT_PROMPT,+};+let DEFAULT_SETTINGS: Settings = {- aiPresets: [],+ aiPresets: [DEFAULT_FREE_PRESET as any],+ deviceId: crypto.randomUUID(),deepgramApiKey: "",isLoading: false,userId: "",diff --git a/screenpipe-app-tauri/public/CHANGELOG.md b/screenpipe-app-tauri/public/CHANGELOG.mdindex de1af2f86..9dfb06acd 100644--- a/screenpipe-app-tauri/public/CHANGELOG.md+++ b/screenpipe-app-tauri/public/CHANGELOG.md@@ -1,18 +1,6 @@-## New Features-- Added screenpipe chat integration with cloud provider support-- macOS: Shortcut reminder now responds to hover without requiring window focus--## Improvements-- Onboarding: Added timeout warning when setup is stuck to help users troubleshoot-- Simplified shortcut reminder text for clarity-## Bug Fixes-- Fixed chat URL configuration for screenpipe-cloud provider-- Fixed shortcut reminder window showing titlebar artifacts on macOS-- Fixed shortcut reminder not appearing on macOS-- Fixed timeline overlay allowing accidental window drag-- Fixed video playback crash when frame offset exceeded duration-- Fixed React hooks violation in image card component-- Fixed platform detection for keyboard shortcut display+- Fixed timeline navigation jumping back when switching days+- Fixed reset button being incorrectly disabled+- Improved app suggestion autocomplete with dynamic filtering-#### **Full Changelog:** [6a6d262..491aaf8](https://github.com/mediar-ai/screenpipe/compare/6a6d262..491aaf8)+#### **Full Changelog:** [0e5332dc..5615a230](https://github.com/mediar-ai/screenpipe/compare/0e5332dc..5615a230)diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 478eef69a..408a55079 100644--- a/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "screenpipe-app"-version = "2.0.87"+version = "2.0.88"description = "24/7 memory for your desktop. 100% local."authors = ["you"]license = ""diff --git a/screenpipe-app-tauri/src-tauri/src/store.rs b/screenpipe-app-tauri/src-tauri/src/store.rsindex d6b5e7fdf..8b32d8a79 100644--- a/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/screenpipe-app-tauri/src-tauri/src/store.rs@@ -188,6 +188,13 @@ pub struct SettingsStore {pub enable_realtime_vision: bool,#[serde(rename = "showShortcutOverlay", default = "default_true")]pub show_shortcut_overlay: bool,+ /// Unique device ID for AI usage tracking (generated on first launch)+ #[serde(rename = "deviceId", default = "generate_device_id")]+ pub device_id: String,+}++fn generate_device_id() -> String {+ uuid::Uuid::new_v4().to_string()}fn default_true() -> bool {@@ -364,8 +371,25 @@ impl Default for SettingsStore {"Parted".to_string(),]);+ // Default free AI preset - works without login+ let default_free_preset = AIPreset {+ id: "screenpipe-free".to_string(),+ prompt: r#"Rules:+- You can analyze/view/show/access videos to the user by putting .mp4 files in a code block (we'll render it) like this: `/users/video.mp4`, use the exact, absolute, file path from file_path property+- Do not try to embed video in links (e.g. [](.mp4) or https://.mp4) instead put the file_path in a code block using backticks+- Do not put video in multiline code block it will not render the video (e.g. ```bash\n.mp4```) instead using inline code block with single backtick+- Always answer my question/intent, do not make up things+"#.to_string(),+ provider: AIProviderType::ScreenpipeCloud,+ url: "https://ai-proxy.i-f9f.workers.dev/v1".to_string(),+ model: "claude-haiku-4-5@20251001".to_string(),+ default_preset: true,+ api_key: None,+ max_context_chars: 128000,+ };+Self {- ai_presets: vec![],+ ai_presets: vec![default_free_preset],deepgram_api_key: "".to_string(),is_loading: false,user_id: "".to_string(),@@ -433,6 +457,7 @@ impl Default for SettingsStore {use_all_monitors: false,enable_realtime_vision: true,show_shortcut_overlay: true,+ device_id: uuid::Uuid::new_v4().to_string(),}}}diff --git a/screenpipe-js/ai-proxy/migrations/0001_create_usage_table.sql b/screenpipe-js/ai-proxy/migrations/0001_create_usage_table.sqlnew file mode 100644index 000000000..7e838c470--- /dev/null+++ b/screenpipe-js/ai-proxy/migrations/0001_create_usage_table.sql@@ -0,0 +1,21 @@+-- Migration: Create usage tracking table for free tier AI limits+-- Run with: wrangler d1 execute screenpipe-usage --file=./migrations/0001_create_usage_table.sql++CREATE TABLE IF NOT EXISTS usage (+ device_id TEXT PRIMARY KEY,+ user_id TEXT,+ daily_count INTEGER DEFAULT 0,+ last_reset TEXT NOT NULL,+ tier TEXT DEFAULT 'anonymous',+ created_at TEXT DEFAULT (datetime('now')),+ updated_at TEXT DEFAULT (datetime('now'))+);++-- Index for efficient daily reset queries+CREATE INDEX IF NOT EXISTS idx_usage_last_reset ON usage(last_reset);++-- Index for user lookups (when user logs in, we can link devices)+CREATE INDEX IF NOT EXISTS idx_usage_user_id ON usage(user_id);++-- Index for tier-based analytics+CREATE INDEX IF NOT EXISTS idx_usage_tier ON usage(tier);diff --git a/screenpipe-js/ai-proxy/src/handlers/models.ts b/screenpipe-js/ai-proxy/src/handlers/models.tsindex a8bd10533..e0aaee9a6 100644--- a/screenpipe-js/ai-proxy/src/handlers/models.ts+++ b/screenpipe-js/ai-proxy/src/handlers/models.ts@@ -1,13 +1,15 @@-import { Env } from '../types';+import { Env, UserTier } from '../types';import { createProvider } from '../providers';-import { createSuccessResponse, createErrorResponse } from '../utils/cors';+import { createSuccessResponse, createErrorResponse, addCorsHeaders } from '../utils/cors';+import { TIER_CONFIG, isModelAllowed } from '../services/usage-tracker';/*** Handles model listing requests* @param env Environment variables+ * @param tier User tier for filtering models* @returns Response with list of available AI models*/-export async function handleModelListing(env: Env): Promise<Response> {+export async function handleModelListing(env: Env, tier: UserTier = 'subscribed'): Promise<Response> {try {// Only use Vertex AI which provides both Claude and Geminiconst vertex = createProvider('claude-opus-4-20250514', env);@@ -15,20 +17,42 @@ export async function handleModelListing(env: Env): Promise<Response> {vertex.listModels(),]);- const models = results+ let models = results.filter((result): result is PromiseFulfilledResult<{ id: string; name: string; provider: string }[]> =>result.status === 'fulfilled').flatMap((result) => result.value);- // Return in OpenAI-compatible format (data array)- return createSuccessResponse({ data: models });+ // Filter models based on tier+ if (tier !== 'subscribed') {+ const allowedModels = TIER_CONFIG[tier].allowedModels;+ models = models.filter(model =>+ allowedModels.some(allowed =>+ model.id.toLowerCase().includes(allowed.toLowerCase()) ||+ allowed.toLowerCase().includes(model.id.toLowerCase())+ )+ );++ // Add metadata about tier restrictions+ models = models.map(model => ({+ ...model,+ tier_available: true,+ }));+ }++ // Return in OpenAI-compatible format (data array) with tier info+ return addCorsHeaders(createSuccessResponse({+ data: models,+ models: models, // Also include as 'models' for backwards compatibility+ tier,+ tier_limits: TIER_CONFIG[tier],+ }));} catch (error) {console.error('Error fetching models:', error);- return createErrorResponse(- 500,+ return addCorsHeaders(createErrorResponse(+ 500,`Failed to fetch models: ${error instanceof Error ? error.message : 'Unknown error'}`- );+ ));}-}\ No newline at end of file+}diff --git a/screenpipe-js/ai-proxy/src/index.ts b/screenpipe-js/ai-proxy/src/index.tsindex b71162142..dd23f126b 100644--- a/screenpipe-js/ai-proxy/src/index.ts+++ b/screenpipe-js/ai-proxy/src/index.ts@@ -1,9 +1,10 @@import * as Sentry from '@sentry/cloudflare';-import { Env, RequestBody } from './types';-import { handleOptions, createSuccessResponse, createErrorResponse } from './utils/cors';+import { Env, RequestBody, AuthResult } from './types';+import { handleOptions, createSuccessResponse, createErrorResponse, addCorsHeaders } from './utils/cors';import { validateAuth } from './utils/auth';import { RateLimiter, checkRateLimit } from './utils/rate-limiter';import { setupAnalytics } from './services/analytics';+import { trackUsage, getUsageStatus, isModelAllowed, TIER_CONFIG } from './services/usage-tracker';import { handleChatCompletions } from './handlers/chat';import { handleModelListing } from './handlers/models';import { handleFileTranscription, handleWebSocketUpgrade } from './handlers/transcription';@@ -38,35 +39,69 @@ export default Sentry.withSentry(return handleOptions(request);}- const rateLimit = await checkRateLimit(request, env);- if (!rateLimit.allowed && rateLimit.response) {- return rateLimit.response;- }-const url = new URL(request.url);const path = url.pathname;console.log('path', path);- // Handle WebSocket upgrade for real-time transcription+ // Handle WebSocket upgrade for real-time transcription (no auth required)const upgradeHeader = request.headers.get('upgrade')?.toLowerCase();if (path === '/v1/listen' && upgradeHeader === 'websocket') {console.log('websocket request to /v1/listen detected, bypassing auth');return await handleWebSocketUpgrade(request, env);}- if (path !== '/test') {- const authResult = await validateAuth(request, env);- if (!authResult.isValid) {- return createErrorResponse(401, authResult.error || 'unauthorized');- }- }-+ // Test endpoint - no auth requiredif (path === '/test') {return createSuccessResponse('ai proxy is working!');}+ // Authenticate and get tier info for all other endpoints+ const authResult = await validateAuth(request, env);+ console.log('auth result:', { tier: authResult.tier, deviceId: authResult.deviceId });++ // Check rate limit with tier info+ const rateLimit = await checkRateLimit(request, env, authResult);+ if (!rateLimit.allowed && rateLimit.response) {+ return rateLimit.response;+ }++ // Usage status endpoint - returns current usage without incrementing+ if (path === '/v1/usage' && request.method === 'GET') {+ const status = await getUsageStatus(env, authResult.deviceId, authResult.tier);+ return addCorsHeaders(createSuccessResponse(status));+ }++ // Chat completions - main AI endpointif (path === '/v1/chat/completions' && request.method === 'POST') {const body = (await request.json()) as RequestBody;++ // Check if model is allowed for this tier+ if (!isModelAllowed(body.model, authResult.tier)) {+ const allowedModels = TIER_CONFIG[authResult.tier].allowedModels;+ return addCorsHeaders(createErrorResponse(403, JSON.stringify({+ error: 'model_not_allowed',+ message: `Model "${body.model}" is not available for your tier (${authResult.tier}). Available models: ${allowedModels.join(', ')}`,+ tier: authResult.tier,+ allowed_models: allowedModels,+ })));+ }++ // Track usage and check daily limit+ const usage = await trackUsage(env, authResult.deviceId, authResult.tier, authResult.userId);+ if (!usage.allowed) {+ return addCorsHeaders(createErrorResponse(429, JSON.stringify({+ error: 'daily_limit_exceeded',+ message: `You've used all ${usage.limit} free AI queries for today. Resets at ${usage.resetsAt}`,+ used_today: usage.used,+ limit_today: usage.limit,+ resets_at: usage.resetsAt,+ tier: authResult.tier,+ upgrade_options: authResult.tier === 'anonymous'+ ? { login: { benefit: '+25 daily queries, more models' }, subscribe: { benefit: 'Unlimited queries, all models' } }+ : { subscribe: { benefit: 'Unlimited queries, all models' } },+ })));+ }+return await handleChatCompletions(body, env, langfuse);}@@ -75,7 +110,8 @@ export default Sentry.withSentry(}if (path === '/v1/models' && request.method === 'GET') {- return await handleModelListing(env);+ // Return tier-filtered models for non-subscribed users+ return await handleModelListing(env, authResult.tier);}if (path === '/v1/voice/transcribe' && request.method === 'POST') {@@ -128,7 +164,7 @@ terminal 2HOST=https://ai-proxy.i-f9f.workers.devHOST=http://localhost:8787TOKEN=foobar (check app settings)-in+inless "$HOME/Library/Application Support/screenpipe/store.bin"@@ -141,6 +177,26 @@ curl -X POST $HOST/v1/listen \-H "Authorization: Bearer $TOKEN" \--data-binary "@./screenpipe-audio/test_data/poetic_kapil_gupta.wav"+# Test free tier (no auth)+curl -X POST $HOST/v1/chat/completions \+-H "Content-Type: application/json" \+-H "X-Device-Id: test-device-123" \+-d '{+"model": "claude-haiku-4-5@20251001",+"messages": [+ {+ "role": "user",+ "content": "Tell me a short joke."+ }+],+"stream": true+}' | while read -r line; do+echo "$line" | sed 's/^data: //g' | jq -r '.choices[0].delta.content // empty' 2>/dev/null+done | tr -d '\n'++# Check usage+curl "$HOST/v1/usage" -H "X-Device-Id: test-device-123"+curl -X POST $HOST/v1/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer $TOKEN" \diff --git a/screenpipe-js/ai-proxy/src/services/usage-tracker.ts b/screenpipe-js/ai-proxy/src/services/usage-tracker.tsnew file mode 100644index 000000000..daa43c338--- /dev/null+++ b/screenpipe-js/ai-proxy/src/services/usage-tracker.ts@@ -0,0 +1,222 @@+import { Env, UserTier, TierLimits, UsageResult, UsageStatus } from '../types';++// Tier configuration - models and limits per tier+export const TIER_CONFIG: Record<UserTier, TierLimits> = {+ anonymous: {+ dailyQueries: 25,+ rpm: 5,+ allowedModels: [+ 'claude-haiku-4-5@20251001',+ 'claude-3-haiku-20240307',+ ],+ },+ logged_in: {+ dailyQueries: 50,+ rpm: 10,+ allowedModels: [+ 'claude-haiku-4-5@20251001',+ 'claude-3-haiku-20240307',+ 'claude-sonnet-4-20250514',+ 'claude-3-5-sonnet-20241022',+ 'gpt-4o-mini',+ ],+ },+ subscribed: {+ dailyQueries: -1, // unlimited+ rpm: 30,+ allowedModels: ['*'], // all models+ },+};++// SQL schema for the usage table+export const USAGE_SCHEMA = `+CREATE TABLE IF NOT EXISTS usage (+ device_id TEXT PRIMARY KEY,+ user_id TEXT,+ daily_count INTEGER DEFAULT 0,+ last_reset TEXT,+ tier TEXT DEFAULT 'anonymous',+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+);++CREATE INDEX IF NOT EXISTS idx_usage_last_reset ON usage(last_reset);+CREATE INDEX IF NOT EXISTS idx_usage_user_id ON usage(user_id);+`;++/**+ * Get today's date in UTC as ISO string (YYYY-MM-DD)+ */+function getTodayUTC(): string {+ return new Date().toISOString().split('T')[0];+}++/**+ * Get the reset time for the next day (midnight UTC)+ */+function getNextResetTime(): string {+ const tomorrow = new Date();+ tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);+ tomorrow.setUTCHours(0, 0, 0, 0);+ return tomorrow.toISOString();+}++/**+ * Track a request and check if it's within limits+ */+export async function trackUsage(+ env: Env,+ deviceId: string,+ tier: UserTier,+ userId?: string+): Promise<UsageResult> {+ const today = getTodayUTC();+ const limits = TIER_CONFIG[tier];++ // Subscribed users have unlimited queries+ if (tier === 'subscribed') {+ return {+ used: 0,+ limit: -1,+ remaining: -1,+ allowed: true,+ resetsAt: getNextResetTime(),+ };+ }++ try {+ // Try to get existing record+ const existing = await env.DB.prepare(+ 'SELECT daily_count, last_reset FROM usage WHERE device_id = ?'+ ).bind(deviceId).first<{ daily_count: number; last_reset: string }>();++ let dailyCount = 0;++ if (existing) {+ // Check if we need to reset (new day)+ if (existing.last_reset < today) {+ // Reset count for new day+ await env.DB.prepare(+ 'UPDATE usage SET daily_count = 1, last_reset = ?, tier = ?, user_id = ?, updated_at = CURRENT_TIMESTAMP WHERE device_id = ?'+ ).bind(today, tier, userId || null, deviceId).run();+ dailyCount = 1;+ } else {+ // Increment count+ dailyCount = existing.daily_count + 1;+ await env.DB.prepare(+ 'UPDATE usage SET daily_count = ?, tier = ?, user_id = ?, updated_at = CURRENT_TIMESTAMP WHERE device_id = ?'+ ).bind(dailyCount, tier, userId || null, deviceId).run();+ }+ } else {+ // Create new record+ await env.DB.prepare(+ 'INSERT INTO usage (device_id, user_id, daily_count, last_reset, tier) VALUES (?, ?, 1, ?, ?)'+ ).bind(deviceId, userId || null, today, tier).run();+ dailyCount = 1;+ }++ const allowed = dailyCount <= limits.dailyQueries;++ return {+ used: dailyCount,+ limit: limits.dailyQueries,+ remaining: Math.max(0, limits.dailyQueries - dailyCount),+ allowed,+ resetsAt: getNextResetTime(),+ };+ } catch (error) {+ console.error('Error tracking usage:', error);+ // On error, allow the request but log it+ return {+ used: 0,+ limit: limits.dailyQueries,+ remaining: limits.dailyQueries,+ allowed: true,+ resetsAt: getNextResetTime(),+ };+ }+}++/**+ * Get current usage status without incrementing+ */+export async function getUsageStatus(+ env: Env,+ deviceId: string,+ tier: UserTier+): Promise<UsageStatus> {+ const today = getTodayUTC();+ const limits = TIER_CONFIG[tier];++ let usedToday = 0;++ if (tier !== 'subscribed') {+ try {+ const existing = await env.DB.prepare(+ 'SELECT daily_count, last_reset FROM usage WHERE device_id = ?'+ ).bind(deviceId).first<{ daily_count: number; last_reset: string }>();++ if (existing && existing.last_reset >= today) {+ usedToday = existing.daily_count;+ }+ } catch (error) {+ console.error('Error getting usage status:', error);+ }+ }++ const limitToday = tier === 'subscribed' ? -1 : limits.dailyQueries;+ const remaining = tier === 'subscribed' ? -1 : Math.max(0, limits.dailyQueries - usedToday);++ const status: UsageStatus = {+ tier,+ used_today: usedToday,+ limit_today: limitToday,+ remaining,+ resets_at: getNextResetTime(),+ model_access: limits.allowedModels,+ };++ // Add upgrade options for non-subscribed users+ if (tier === 'anonymous') {+ status.upgrade_options = {+ login: { benefit: '+25 daily queries, access to Sonnet model' },+ subscribe: { benefit: 'Unlimited queries, all models including GPT-4 and Claude Opus' },+ };+ } else if (tier === 'logged_in') {+ status.upgrade_options = {+ subscribe: { benefit: 'Unlimited queries, all models including GPT-4 and Claude Opus' },+ };+ }++ return status;+}++/**+ * Check if a model is allowed for a given tier+ */+export function isModelAllowed(model: string, tier: UserTier): boolean {+ const allowedModels = TIER_CONFIG[tier].allowedModels;++ // Subscribed users can use any model+ if (allowedModels.includes('*')) {+ return true;+ }++ // Check if the model is in the allowed list+ return allowedModels.some(allowed =>+ model.toLowerCase().includes(allowed.toLowerCase()) ||+ allowed.toLowerCase().includes(model.toLowerCase())+ );+}++/**+ * Initialize the database schema+ */+export async function initializeSchema(env: Env): Promise<void> {+ try {+ await env.DB.exec(USAGE_SCHEMA);+ console.log('Usage schema initialized');+ } catch (error) {+ console.error('Error initializing schema:', error);+ }+}diff --git a/screenpipe-js/ai-proxy/src/types.ts b/screenpipe-js/ai-proxy/src/types.tsindex f3835d1a8..53a7f09dd 100644--- a/screenpipe-js/ai-proxy/src/types.ts+++ b/screenpipe-js/ai-proxy/src/types.ts@@ -128,6 +128,50 @@ export interface Env {VERTEX_SERVICE_ACCOUNT_JSON: string;VERTEX_PROJECT_ID: string;VERTEX_REGION: string;+ // D1 database for usage tracking+ DB: D1Database;+}++// User tier for rate limiting and model access+export type UserTier = 'anonymous' | 'logged_in' | 'subscribed';++// Auth result with tier information+export interface AuthResult {+ isValid: boolean;+ tier: UserTier;+ deviceId: string;+ userId?: string;+ error?: string;+}++// Tier limits configuration+export interface TierLimits {+ dailyQueries: number;+ rpm: number;+ allowedModels: string[];+}++// Usage tracking result+export interface UsageResult {+ used: number;+ limit: number;+ remaining: number;+ allowed: boolean;+ resetsAt: string;+}++// Usage status response+export interface UsageStatus {+ tier: UserTier;+ used_today: number;+ limit_today: number;+ remaining: number;+ resets_at: string;+ model_access: string[];+ upgrade_options?: {+ login?: { benefit: string };+ subscribe?: { benefit: string };+ };}export interface ResponseUtils {diff --git a/screenpipe-js/ai-proxy/src/utils/auth.ts b/screenpipe-js/ai-proxy/src/utils/auth.tsindex e6c906d93..e576fcf43 100644--- a/screenpipe-js/ai-proxy/src/utils/auth.ts+++ b/screenpipe-js/ai-proxy/src/utils/auth.ts@@ -1,5 +1,5 @@import { verifyToken } from '@clerk/backend';-import { Env } from '../types';+import { Env, AuthResult, UserTier } from '../types';import { validateSubscription } from './subscription';/**@@ -22,16 +22,35 @@ export async function verifyClerkToken(env: Env, token: string): Promise<boolean}/**- * Validates user authentication from request headers+ * Extracts device ID from request headers+ * Falls back to IP address if no device ID is provided+ */+function getDeviceId(request: Request): string {+ const deviceId = request.headers.get('X-Device-Id');+ if (deviceId && deviceId.length > 0) {+ return deviceId;+ }+ // Fall back to IP address for backwards compatibility+ return request.headers.get('cf-connecting-ip') || 'unknown';+}++/**+ * Validates user authentication from request headers and determines tier* @param request HTTP request* @param env Environment variables- * @returns Object with validation result and optional error message+ * @returns AuthResult with tier information*/-export async function validateAuth(request: Request, env: Env): Promise<{ isValid: boolean; error?: string }> {+export async function validateAuth(request: Request, env: Env): Promise<AuthResult> {+ const deviceId = getDeviceId(request);const authHeader = request.headers.get('Authorization');+ // No auth header = anonymous tier (free usage)if (!authHeader || !(authHeader.startsWith('Bearer ') || authHeader.startsWith('Token '))) {- return { isValid: false, error: 'unauthorized' };+ return {+ isValid: true,+ tier: 'anonymous',+ deviceId,+ };}const token = authHeader.split(' ')[1];@@ -39,20 +58,160 @@ export async function validateAuth(request: Request, env: Env): Promise<{ isVali// Allow test token in development modeif (env.NODE_ENV === 'development' && token === 'test-token') {console.log('using test token in development mode');- return { isValid: true };+ return {+ isValid: true,+ tier: 'subscribed',+ deviceId,+ userId: 'test-user',+ };+ }++ // Check if user has active subscription+ const { isValid: hasSubscription, userId } = await validateSubscriptionWithId(env, token);++ if (hasSubscription) {+ return {+ isValid: true,+ tier: 'subscribed',+ deviceId,+ userId,+ };+ }++ // Check if it's a valid Clerk token (logged in but no subscription)+ const isClerkValid = await verifyClerkToken(env, token);+ if (isClerkValid) {+ return {+ isValid: true,+ tier: 'logged_in',+ deviceId,+ userId: token, // Use token as identifier+ };+ }++ // Check if it's a valid screenpipe JWT token+ const screenpipeUser = await validateScreenpipeToken(token);+ if (screenpipeUser.isValid) {+ // Check if the user has subscription+ if (screenpipeUser.hasSubscription) {+ return {+ isValid: true,+ tier: 'subscribed',+ deviceId,+ userId: screenpipeUser.userId,+ };+ }+ // Logged in but no subscription+ return {+ isValid: true,+ tier: 'logged_in',+ deviceId,+ userId: screenpipeUser.userId,+ };}- let isValid = await validateSubscription(env, token);+ // Invalid token provided = still allow as anonymous+ // This is a design choice: we don't want to block users with expired tokens+ console.log('Token validation failed, falling back to anonymous tier');+ return {+ isValid: true,+ tier: 'anonymous',+ deviceId,+ };+}++/**+ * Legacy validateAuth for backwards compatibility+ * Returns simple isValid/error format+ */+export async function validateAuthLegacy(request: Request, env: Env): Promise<{ isValid: boolean; error?: string }> {+ const result = await validateAuth(request, env);+ return {+ isValid: result.isValid,+ error: result.error,+ };+}++/**+ * Validates subscription and returns user ID+ */+async function validateSubscriptionWithId(env: Env, token: string): Promise<{ isValid: boolean; userId?: string }> {+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+ const CLERK_USER_ID_REGEX = /^user_[a-zA-Z0-9]+$/;++ // Check by UUID (Supabase user ID)+ if (UUID_REGEX.test(token)) {+ try {+ const response = await fetch(`${env.SUPABASE_URL}/rest/v1/rpc/has_active_cloud_subscription`, {+ method: 'POST',+ headers: {+ apikey: env.SUPABASE_ANON_KEY,+ Authorization: `Bearer ${env.SUPABASE_ANON_KEY}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ input_user_id: token }),+ });- // If not valid, try to verify as a clerk token- if (!isValid) {- isValid = await verifyClerkToken(env, token);+ if (!response.ok) {+ console.error('Supabase error:', await response.text());+ return { isValid: false };+ }++ const hasSubscription: boolean = await response.json();+ return { isValid: hasSubscription, userId: token };+ } catch (error) {+ console.error('Error checking subscription:', error);+ return { isValid: false };+ }}- if (!isValid) {- console.log('all validation attempts failed');- return { isValid: false, error: 'invalid subscription' };+ // Clerk user IDs - for now allow all as subscribed (Agent SDK)+ // TODO: Add proper subscription checks for Clerk users+ if (CLERK_USER_ID_REGEX.test(token)) {+ console.log('Allowing Clerk user ID for Agent SDK:', token);+ return { isValid: true, userId: token };+ }++ return { isValid: false };+}++/**+ * Validates a screenpipe JWT token+ */+interface ScreenpipeUserData {+ id?: string;+ email?: string;+ cloud_subscribed?: boolean;+}++async function validateScreenpipeToken(token: string): Promise<{ isValid: boolean; userId?: string; hasSubscription?: boolean }> {+ if (!token.startsWith('eyJ')) {+ return { isValid: false };}- return { isValid: true };-}\ No newline at end of file+ try {+ const response = await fetch('https://screenpi.pe/api/user', {+ method: 'GET',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ });++ if (response.ok) {+ const userData = await response.json() as ScreenpipeUserData;+ console.log('Valid screenpipe user token, user:', userData?.email);+ return {+ isValid: true,+ userId: userData?.id || userData?.email,+ hasSubscription: userData?.cloud_subscribed === true,+ };+ } else {+ console.log('Invalid screenpipe user token');+ return { isValid: false };+ }+ } catch (error) {+ console.error('Error validating screenpipe token:', error);+ return { isValid: false };+ }+}diff --git a/screenpipe-js/ai-proxy/src/utils/rate-limiter.ts b/screenpipe-js/ai-proxy/src/utils/rate-limiter.tsindex ea759a00a..69c41324b 100644--- a/screenpipe-js/ai-proxy/src/utils/rate-limiter.ts+++ b/screenpipe-js/ai-proxy/src/utils/rate-limiter.ts@@ -1,5 +1,6 @@import { createErrorResponse } from './cors';-import { Env } from '../types';+import { Env, UserTier, AuthResult } from '../types';+import { TIER_CONFIG } from '../services/usage-tracker';export class RateLimiter {private state: DurableObjectState;@@ -16,38 +17,47 @@ export class RateLimiter {* @returns Response with rate limit status*/async fetch(request: Request) {- const ip = request.headers.get('cf-connecting-ip') || 'unknown';const url = new URL(request.url);const now = Date.now();- // idk much about limits loius wanted to have- const limits: Record<string, { rpm: number; window: number }> = {- '/v1/chat/completions': { rpm: 20, window: 60000 }, // 20 requests per minute for openai- '/v1/voice/transcribe': { rpm: 15, window: 60000 }, // 15 requests per minute for voice transcription- '/v1/voice/query': { rpm: 10, window: 60000 }, // 10 requests per minute for voice queries- '/v1/text-to-speech': { rpm: 15, window: 60000 }, // 15 requests per minute for text-to-speech- '/v1/voice/chat': { rpm: 8, window: 60000 }, // 8 requests per minute for voice chat- default: { rpm: 60, window: 60000 }, // 60 rpm for other endpoints+ // Get identifier and tier from URL params (passed by checkRateLimit)+ const identifier = url.searchParams.get('id') || 'unknown';+ const tier = (url.searchParams.get('tier') || 'anonymous') as UserTier;++ // Get tier-specific RPM limit+ const tierRpm = TIER_CONFIG[tier]?.rpm || 5;++ // Endpoint-specific limits (as multipliers of base RPM)+ const endpointMultipliers: Record<string, number> = {+ '/v1/chat/completions': 1,+ '/v1/voice/transcribe': 0.75,+ '/v1/voice/query': 0.5,+ '/v1/text-to-speech': 0.75,+ '/v1/voice/chat': 0.4,};- const limit = limits[url.pathname] || limits.default;+ const multiplier = endpointMultipliers[url.pathname] || 1;+ const effectiveRpm = Math.max(1, Math.floor(tierRpm * multiplier));+ const window = 60000; // 1 minute- let tracking = this.requests.get(ip) || { count: 0, lastReset: now };+ let tracking = this.requests.get(identifier) || { count: 0, lastReset: now };- if (now - tracking.lastReset > limit.window) {+ if (now - tracking.lastReset > window) {tracking = { count: 0, lastReset: now };}tracking.count++;- this.requests.set(ip, tracking);+ this.requests.set(identifier, tracking);- const isAllowed = tracking.count <= limit.rpm;+ const isAllowed = tracking.count <= effectiveRpm;return new Response(JSON.stringify({allowed: isAllowed,- remaining: Math.max(0, limit.rpm - tracking.count),- reset_in: Math.ceil((tracking.lastReset + limit.window - now) / 1000),+ remaining: Math.max(0, effectiveRpm - tracking.count),+ reset_in: Math.ceil((tracking.lastReset + window - now) / 1000),+ tier,+ rpm_limit: effectiveRpm,}));}@@ -57,22 +67,50 @@ export class RateLimiter {* Checks if the request exceeds rate limits* @param request The HTTP request* @param env Environment variables+ * @param authResult Optional auth result with tier info* @returns Object indicating if request is allowed and optional error response*/-export async function checkRateLimit(request: Request, env: Env): Promise<{ allowed: boolean; response?: Response }> {- const ip = request.headers.get('cf-connecting-ip') || 'unknown';- const rateLimiterId = env.RATE_LIMITER.idFromName(ip);+export async function checkRateLimit(+ request: Request,+ env: Env,+ authResult?: AuthResult+): Promise<{ allowed: boolean; response?: Response }> {+ // Use device ID if available, fall back to IP+ const identifier = authResult?.deviceId ||+ request.headers.get('X-Device-Id') ||+ request.headers.get('cf-connecting-ip') ||+ 'unknown';++ const tier = authResult?.tier || 'anonymous';++ const rateLimiterId = env.RATE_LIMITER.idFromName(identifier);const rateLimiter = env.RATE_LIMITER.get(rateLimiterId);- const rateLimitResponse = await rateLimiter.fetch(request.url);- const rateLimitData = (await rateLimitResponse.json()) as { allowed: boolean; remaining: number; reset_in: number };+ // Pass tier info to the rate limiter+ const url = new URL(request.url);+ url.searchParams.set('id', identifier);+ url.searchParams.set('tier', tier);++ const rateLimitResponse = await rateLimiter.fetch(url.toString());+ const rateLimitData = (await rateLimitResponse.json()) as {+ allowed: boolean;+ remaining: number;+ reset_in: number;+ tier: string;+ rpm_limit: number;+ };if (!rateLimitData.allowed) {- return {- allowed: false,- response: createErrorResponse(429, 'rate limit exceeded')+ return {+ allowed: false,+ response: createErrorResponse(429, JSON.stringify({+ error: 'rate limit exceeded',+ message: `You've exceeded ${rateLimitData.rpm_limit} requests per minute. Please wait ${rateLimitData.reset_in} seconds.`,+ tier: rateLimitData.tier,+ reset_in: rateLimitData.reset_in,+ }))};}return { allowed: true };-}\ No newline at end of file+}diff --git a/screenpipe-js/ai-proxy/src/utils/subscription.ts b/screenpipe-js/ai-proxy/src/utils/subscription.tsindex 0aa7bd28b..497bde748 100644--- a/screenpipe-js/ai-proxy/src/utils/subscription.ts+++ b/screenpipe-js/ai-proxy/src/utils/subscription.ts@@ -97,7 +97,7 @@ export async function validateSubscription(env: Env, userId: string): Promise<bo});if (response.ok) {- const userData = await response.json();+ const userData = await response.json() as { email?: string };console.log('Valid screenpipe user token, user:', userData?.email);subscriptionCache.set(userId, true);return true;diff --git a/screenpipe-js/ai-proxy/wrangler.toml b/screenpipe-js/ai-proxy/wrangler.tomlindex 256737a69..704cac147 100644--- a/screenpipe-js/ai-proxy/wrangler.toml+++ b/screenpipe-js/ai-proxy/wrangler.toml@@ -51,10 +51,12 @@ VERTEX_REGION = "us-east5"# Bind a D1 database. D1 is Cloudflare's native serverless SQL database.# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases-# [[d1_databases]]-# binding = "MY_DB"-# database_name = "my-database"-# database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"+# NOTE: Create database with: wrangler d1 create screenpipe-usage+# Then update the database_id below with the returned ID+[[d1_databases]]+binding = "DB"+database_name = "screenpipe-usage"+database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"# Bind a dispatch namespace. Use Workers for Platforms to deploy serverless functions programmatically on behalf of your customers.# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#dispatch-namespace-bindings-workers-for-platforms