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

Bump app to v2.0.162

Louis Beaumonta4b9a5004c48
diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsx
index 05383ccbc..60ad68c3b 100644
--- a/screenpipe-app-tauri/components/global-chat.tsx
+++ b/screenpipe-app-tauri/components/global-chat.tsx
@@ -439,18 +439,15 @@ EXAMPLES:
type: "function",
function: {
name: "web_search",
- description: `Search the web for current, up-to-date information. Use this when:
-- User asks about recent news, events, or current information
-- User wants to verify or supplement screen data with web sources
-- User asks about topics that need real-time data (stocks, weather, news)
-- Combining screen context with external web information
+ description: `Search the internet for current information using Google Search. YOU MUST CALL THIS FUNCTION when:
+- User says "search", "look up", "find", "google", or "search the web/internet"
+- User asks about news, current events, people, companies, or real-time data
+- User asks "what is [topic]" where the topic is a public person, company, or concept
+- User wants to combine screen context with external information
-This tool uses Google Search to ground responses in current web data and provides cited sources.
+IMPORTANT: When user asks to search the internet/web, ALWAYS call this function - do NOT say you cannot search.
-EXAMPLES:
-- "What's the latest news about [topic from my screen]?"
-- "Search the web for current ECB rates"
-- "Find recent articles about [something I was researching]"`,
+Returns search results with cited sources from the web.`,
parameters: {
type: "object",
properties: {
@@ -465,17 +462,20 @@ EXAMPLES:
},
];
-const SYSTEM_PROMPT = `You are a helpful AI assistant that can search through the user's Screenpipe data - their screen recordings, audio transcriptions, and UI interactions. You also have access to web search for current information.
+const SYSTEM_PROMPT = `You are a helpful AI assistant with two powerful tools:
+
+1. **search_content**: Search the user's Screenpipe data (screen recordings, audio transcriptions, UI interactions)
+2. **web_search**: Search the LIVE INTERNET via Google Search (you CAN do this!)
-CAPABILITIES:
-1. **Screen/Audio Search** (search_content): Search user's captured screen text, audio transcriptions, UI elements
-2. **Web Search** (web_search): Search the internet for current news, real-time data, and external information
+IMPORTANT - WEB SEARCH CAPABILITY:
+You HAVE the ability to search the internet. When the user asks you to "search the internet", "look up", "google", or find information about a person, company, news, or any topic - YOU MUST call the web_search function. Do NOT say you cannot search the internet.
-WHEN TO USE WEB SEARCH:
-- User asks about current events, news, or real-time information
-- User wants to combine screen context with external web data (e.g., "based on what I was looking at, search for...")
-- Topics that need up-to-date information (stock prices, news, weather, recent developments)
-- Verifying or supplementing information from screen captures
+WHEN TO USE web_search (CALL THE FUNCTION):
+- User says "search", "look up", "find", "google something"
+- User asks about people (e.g., "Sam Altman", "Elon Musk")
+- User asks about companies, products, news, current events
+- User asks "what is X" where X is a public topic
+- Any request that requires current/real-time information from the web
CRITICAL SCREEN SEARCH RULES (database has 600k+ entries - ALWAYS use time filters):
1. ALWAYS include start_time in EVERY search - NEVER search without a time range
diff --git a/screenpipe-app-tauri/components/rewind/timeline.tsx b/screenpipe-app-tauri/components/rewind/timeline.tsx
index 523d67f60..c2ecee6c7 100644
--- a/screenpipe-app-tauri/components/rewind/timeline.tsx
+++ b/screenpipe-app-tauri/components/rewind/timeline.tsx
@@ -95,7 +95,7 @@ export default function Timeline() {
setShowAudioTranscript(true);
}, [currentIndex]);
- const { currentDate, setCurrentDate, fetchTimeRange, hasDateBeenFetched, loadingProgress, onWindowFocus, newFramesCount, lastFlushTimestamp, clearNewFramesCount, clearSentRequestForDate } =
+ const { currentDate, setCurrentDate, fetchTimeRange, hasDateBeenFetched, loadingProgress, onWindowFocus, newFramesCount, lastFlushTimestamp, clearNewFramesCount, clearSentRequestForDate, clearFramesForNavigation } =
useTimelineStore();
const { frames, isLoading, error, message, fetchNextDayData, websocket } =
@@ -230,11 +230,36 @@ export default function Timeline() {
isSameDay(new Date(frame.timestamp), targetDate)
);
if (isSameDay(targetDate, currentDate) && hasFramesForTargetDate) {
- console.log("Frames loaded, jumping to pending navigation:", targetDate);
- jumpToTime(targetDate);
+ console.log("[pendingNavigation] Frames loaded for target date, jumping:", targetDate.toISOString());
+
+ // Find the first frame of the target day (frames are sorted newest-first)
+ const targetDayStart = startOfDay(targetDate);
+ const targetDayEnd = endOfDay(targetDate);
+
+ // Find the LAST frame in the array that's within the target day
+ // (since frames are sorted newest-first, last match = earliest frame)
+ let firstFrameIndex = -1;
+ for (let i = frames.length - 1; i >= 0; i--) {
+ const frameDate = new Date(frames[i].timestamp);
+ if (frameDate >= targetDayStart && frameDate <= targetDayEnd) {
+ firstFrameIndex = i;
+ break;
+ }
+ }
+
+ if (firstFrameIndex !== -1) {
+ setCurrentIndex(firstFrameIndex);
+ setCurrentFrame(frames[firstFrameIndex]);
+ console.log("[pendingNavigation] Jumped to frame index:", firstFrameIndex);
+ } else {
+ // Fallback: just use jumpToTime
+ jumpToTime(targetDate);
+ }
+
+ // Clear pending navigation and UI state
pendingNavigationRef.current = null;
- // Clear seeking overlay
setSeekingTimestamp(null);
+ isNavigatingRef.current = false;
}
}
}, [frames, currentDate]);
@@ -578,17 +603,15 @@ export default function Timeline() {
// Set navigation flag to prevent frame-date sync from fighting
isNavigatingRef.current = true;
- // Clear the sent request cache for this date to force a fresh fetch
- // This ensures clicking on a date in the calendar always loads fresh data
- clearSentRequestForDate(newDate);
-
console.log("[handleDateChange] called with:", newDate.toISOString(), "currentDate:", currentDate.toISOString());
try {
+ // Check if target date has frames in the database
const checkFramesForDate = await hasFramesForDate(newDate);
console.log("[handleDateChange] hasFramesForDate result:", checkFramesForDate);
if (!checkFramesForDate) {
+ // No frames for this date - try adjacent dates
let subDate;
if (isAfter(currentDate, newDate)) {
subDate = subDays(newDate, 1);
@@ -599,10 +622,12 @@ export default function Timeline() {
// Limit recursion - don't go past start date or future
if (isAfter(startAndEndDates.start, subDate)) {
console.log("[handleDateChange] Reached start date boundary, stopping navigation");
+ isNavigatingRef.current = false;
return;
}
if (isAfter(startOfDay(subDate), startOfDay(new Date()))) {
console.log("[handleDateChange] Reached today boundary, stopping navigation");
+ isNavigatingRef.current = false;
return;
}
@@ -610,11 +635,9 @@ export default function Timeline() {
return await handleDateChange(subDate);
}
- // Already on this day - but still allow jumping to first frame of the day
- // This helps when user wants to "reset" to the start of the current day
+ // Already on this day - jump to first frame of the day
if (isSameDay(newDate, currentDate)) {
console.log("[handleDateChange] Same day, jumping to first frame of day");
- // Find and jump to first frame of target date
const targetDayStart = startOfDay(newDate);
const targetDayEnd = endOfDay(newDate);
const targetIndex = frames.findIndex((frame) => {
@@ -625,12 +648,14 @@ export default function Timeline() {
setCurrentIndex(targetIndex);
setCurrentFrame(frames[targetIndex]);
}
+ isNavigatingRef.current = false;
return;
}
// Don't go before start date
if (isAfter(startAndEndDates.start, newDate)) {
console.log("[handleDateChange] Before start date, stopping");
+ isNavigatingRef.current = false;
return;
}
@@ -640,40 +665,46 @@ export default function Timeline() {
to_date: newDate.toISOString(),
});
- // Store pending navigation - will be processed when frames are available
+ // CRITICAL: Clear old frames before navigating to prevent confusion
+ // This ensures we wait for the new date's frames to load
+ clearFramesForNavigation();
+
+ // Clear the sent request cache for this date to force a fresh fetch
+ clearSentRequestForDate(newDate);
+
+ // Store pending navigation - will be processed when frames arrive
pendingNavigationRef.current = newDate;
- // Clear frame first to prevent sync effect from reverting
+ // Show seeking overlay while waiting for frames
+ setSeekingTimestamp(newDate.toISOString());
+
+ // Clear current frame and update date
+ // This triggers the effect that fetches frames for the new date
setCurrentFrame(null);
+ setCurrentIndex(0);
setCurrentDate(newDate);
- // Find and jump to first frame of target date (frames are sorted newest-first)
- const targetDayStart = startOfDay(newDate);
- const targetDayEnd = endOfDay(newDate);
-
- // Find first frame that falls within the target date
- const targetIndex = frames.findIndex((frame) => {
- const frameDate = new Date(frame.timestamp);
- return frameDate >= targetDayStart && frameDate <= targetDayEnd;
- });
+ // DON'T try to find frames here - they won't be loaded yet!
+ // The pending navigation effect (line ~224) handles jumping to the
+ // correct frame once the new date's frames arrive via WebSocket.
+ console.log("[handleDateChange] Navigation initiated, waiting for frames to load...");
- if (targetIndex !== -1) {
- setCurrentIndex(targetIndex);
- setCurrentFrame(frames[targetIndex]);
- pendingNavigationRef.current = null; // Clear pending since we found it
- setSeekingTimestamp(null); // Clear any seeking state
- } else {
- // Frames not loaded yet - set pending navigation and wait
- // DON'T set currentIndex(0) as that causes a visible jump to "today"
- pendingNavigationRef.current = newDate;
- // Show seeking overlay while waiting for frames
- setSeekingTimestamp(newDate.toISOString());
- }
- } finally {
- // Clear navigation flag after a short delay to let state settle
+ // Safety timeout: clear navigation state if frames don't arrive within 10s
+ // This prevents the app from getting stuck in a loading state
setTimeout(() => {
- isNavigatingRef.current = false;
- }, 500);
+ if (pendingNavigationRef.current && isSameDay(pendingNavigationRef.current, newDate)) {
+ console.warn("[handleDateChange] Timeout: frames didn't arrive, clearing navigation state");
+ pendingNavigationRef.current = null;
+ setSeekingTimestamp(null);
+ isNavigatingRef.current = false;
+ }
+ }, 10000);
+
+ } catch (error) {
+ console.error("[handleDateChange] Error:", error);
+ isNavigatingRef.current = false;
+ pendingNavigationRef.current = null;
+ setSeekingTimestamp(null);
}
};
diff --git a/screenpipe-app-tauri/components/rewind/video.tsx b/screenpipe-app-tauri/components/rewind/video.tsx
index 86705b9e9..7e247cc7a 100644
--- a/screenpipe-app-tauri/components/rewind/video.tsx
+++ b/screenpipe-app-tauri/components/rewind/video.tsx
@@ -1,7 +1,10 @@
-import { memo, useCallback, useEffect, useState } from "react";
+import { memo, useCallback, useEffect, useState, useRef } from "react";
import { cn } from "@/lib/utils";
import { getMediaFile } from '@/lib/actions/video-actions'
+const MAX_RETRIES = 3;
+const INITIAL_RETRY_DELAY = 500; // ms
+
export const VideoComponent = memo(function VideoComponent({
filePath,
customDescription,
@@ -14,6 +17,8 @@ export const VideoComponent = memo(function VideoComponent({
const [mediaSrc, setMediaSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [isAudio, setIsAudio] = useState(false);
+ const [retryCount, setRetryCount] = useState(0);
+ const mediaSrcRef = useRef<string | null>(null);
const sanitizeFilePath = useCallback((path: string): string => {
const isWindows = navigator.userAgent.includes("Windows");
@@ -32,60 +37,87 @@ export const VideoComponent = memo(function VideoComponent({
</div>
);
- const getMimeType = (path: string): string => {
- const ext = path.split(".").pop()?.toLowerCase();
- switch (ext) {
- case "mp4":
- return "video/mp4";
- case "webm":
- return "video/webm";
- case "ogg":
- return "video/ogg";
- case "mp3":
- return "audio/mpeg";
- case "wav":
- return "audio/wav";
- default:
- return isAudio ? "audio/mpeg" : "video/mp4";
- }
- };
-
useEffect(() => {
- async function loadMedia() {
+ let isCancelled = false;
+ let retryTimeout: NodeJS.Timeout | null = null;
+
+ async function loadMedia(attempt: number = 0) {
try {
- console.log("Loading media:", filePath);
+ console.log(`Loading media (attempt ${attempt + 1}/${MAX_RETRIES + 1}):`, filePath);
const sanitizedPath = sanitizeFilePath(filePath);
console.log("Sanitized path:", sanitizedPath);
if (!sanitizedPath) {
throw new Error("Invalid file path");
}
- setIsAudio(
- sanitizedPath.toLowerCase().includes("input") ||
- sanitizedPath.toLowerCase().includes("output")
- );
+ const isAudioFile = sanitizedPath.toLowerCase().includes("input") ||
+ sanitizedPath.toLowerCase().includes("output");
+
+ if (!isCancelled) {
+ setIsAudio(isAudioFile);
+ }
const { data, mimeType } = await getMediaFile(sanitizedPath);
+
+ if (isCancelled) return;
+
const binaryData = atob(data);
const bytes = new Uint8Array(binaryData.length);
for (let i = 0; i < binaryData.length; i++) {
bytes[i] = binaryData.charCodeAt(i);
}
const blob = new Blob([bytes], { type: mimeType });
- setMediaSrc(URL.createObjectURL(blob));
+ const blobUrl = URL.createObjectURL(blob);
+
+ // Clean up previous blob URL before setting new one
+ if (mediaSrcRef.current) {
+ URL.revokeObjectURL(mediaSrcRef.current);
+ }
+ mediaSrcRef.current = blobUrl;
+ setMediaSrc(blobUrl);
+ setError(null);
+ setRetryCount(0);
+ console.log("Media loaded successfully:", filePath);
} catch (error) {
- console.warn("Failed to load media:", error);
- setError(
- `Failed to load media: ${
- error instanceof Error ? error.message : "Unknown error"
- }`
- );
+ if (isCancelled) return;
+
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ console.warn(`Failed to load media (attempt ${attempt + 1}):`, errorMessage);
+
+ // Retry with exponential backoff for transient errors
+ if (attempt < MAX_RETRIES) {
+ const delay = INITIAL_RETRY_DELAY * Math.pow(2, attempt);
+ console.log(`Retrying in ${delay}ms...`);
+ setRetryCount(attempt + 1);
+ retryTimeout = setTimeout(() => {
+ if (!isCancelled) {
+ loadMedia(attempt + 1);
+ }
+ }, delay);
+ } else {
+ setError(`Failed to load media: ${errorMessage}`);
+ setRetryCount(0);
+ }
}
}
+ // Reset state when filePath changes
+ setError(null);
+ setMediaSrc(null);
+ setRetryCount(0);
+
loadMedia();
+
return () => {
- if (mediaSrc) URL.revokeObjectURL(mediaSrc);
+ isCancelled = true;
+ if (retryTimeout) {
+ clearTimeout(retryTimeout);
+ }
+ // Clean up blob URL using ref (avoids stale closure)
+ if (mediaSrcRef.current) {
+ URL.revokeObjectURL(mediaSrcRef.current);
+ mediaSrcRef.current = null;
+ }
};
}, [filePath, sanitizeFilePath]);
diff --git a/screenpipe-app-tauri/lib/actions/has-frames-date.ts b/screenpipe-app-tauri/lib/actions/has-frames-date.ts
index e7a032d20..bff2d86de 100644
--- a/screenpipe-app-tauri/lib/actions/has-frames-date.ts
+++ b/screenpipe-app-tauri/lib/actions/has-frames-date.ts
@@ -7,10 +7,12 @@ export async function hasFramesForDate(date: Date): Promise<boolean> {
startOfDay.setHours(0, 0, 0, 0);
let endOfDay = new Date(date);
- if (isSameDay(startOfDay, new Date())) {
- endOfDay.setMinutes(endOfDay.getMinutes() - 5);
- } else {
- endOfDay.setHours(23, 59, 59, 999);
+ endOfDay.setHours(23, 59, 59, 999);
+
+ // For today, use current time minus buffer to avoid querying future
+ const now = new Date();
+ if (isSameDay(startOfDay, now)) {
+ endOfDay = new Date(now.getTime() - 5 * 60 * 1000); // 5 minutes ago
}
const query = `
diff --git a/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx b/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
index 933f78d16..c08ad9b8a 100644
--- a/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-timeline-store.tsx
@@ -56,6 +56,7 @@ interface TimelineState {
onWindowFocus: () => void;
clearNewFramesCount: () => void;
clearSentRequestForDate: (date: Date) => void;
+ clearFramesForNavigation: () => void; // Clear frames when navigating to new date
}
export const useTimelineStore = create<TimelineState>((set, get) => ({
@@ -87,6 +88,24 @@ export const useTimelineStore = create<TimelineState>((set, get) => ({
});
},
+ // Clear frames when navigating to a new date to avoid confusion between old/new frames
+ clearFramesForNavigation: () => {
+ // Clear the frame buffer too
+ frameBuffer = [];
+ if (flushTimer) {
+ clearTimeout(flushTimer);
+ flushTimer = null;
+ }
+ set({
+ frames: [],
+ frameTimestamps: new Set<string>(),
+ isLoading: true,
+ loadingProgress: { loaded: 0, isStreaming: false },
+ error: null,
+ message: null,
+ });
+ },
+
hasDateBeenFetched: (date: Date) => {
const { sentRequests } = get();
const dateKey = `${date.getDate()}-${date.getMonth()}-${date.getFullYear()}`;
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 7136c3cf6..15477a329 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.161"
+version = "2.0.162"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 26bf8e1c1..01fa1b44b 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -446,35 +446,76 @@ use tokio::time::{sleep, Duration};
async fn get_media_file(file_path: &str) -> Result<serde_json::Value, String> {
use std::path::Path;
+ const MAX_RETRIES: u32 = 3;
+ const INITIAL_DELAY_MS: u64 = 100;
+
debug!("Reading media file: {}", file_path);
let path = Path::new(file_path);
- if !path.exists() {
- return Err(format!("File does not exist: {}", file_path));
- }
- // Read file contents
- let file_contents = match tokio::fs::read(path).await {
- Ok(contents) => {
- debug!("Successfully read file of size: {} bytes", contents.len());
- contents
+ // Retry loop to handle files that may be in the process of being written
+ let mut last_error = String::new();
+ for attempt in 0..=MAX_RETRIES {
+ if attempt > 0 {
+ let delay = INITIAL_DELAY_MS * (1 << (attempt - 1)); // exponential backoff
+ debug!(
+ "Retry attempt {} for {}, waiting {}ms",
+ attempt, file_path, delay
+ );
+ sleep(Duration::from_millis(delay)).await;
}
- Err(e) => {
- error!("Failed to read file: {}", e);
- return Err(format!("Failed to read file: {}", e));
+
+ if !path.exists() {
+ last_error = format!("File does not exist: {}", file_path);
+ if attempt < MAX_RETRIES {
+ continue;
+ }
+ return Err(last_error);
}
- };
- // Convert to base64
- let data = base64::prelude::BASE64_STANDARD.encode(&file_contents);
+ // Read file contents
+ match tokio::fs::read(path).await {
+ Ok(contents) => {
+ // Check for empty or suspiciously small files (might still be writing)
+ if contents.is_empty() {
+ last_error = "File is empty (may still be writing)".to_string();
+ debug!("{}: {}", last_error, file_path);
+ if attempt < MAX_RETRIES {
+ continue;
+ }
+ return Err(last_error);
+ }
+
+ debug!(
+ "Successfully read file of size: {} bytes (attempt {})",
+ contents.len(),
+ attempt + 1
+ );
+
+ // Convert to base64
+ let data = base64::prelude::BASE64_STANDARD.encode(&contents);
+
+ // Determine MIME type
+ let mime_type = get_mime_type(file_path);
- // Determine MIME type
- let mime_type = get_mime_type(file_path);
+ return Ok(serde_json::json!({
+ "data": data,
+ "mimeType": mime_type
+ }));
+ }
+ Err(e) => {
+ last_error = format!("Failed to read file: {}", e);
+ debug!("{} (attempt {})", last_error, attempt + 1);
+ if attempt < MAX_RETRIES {
+ continue;
+ }
+ error!("{}", last_error);
+ return Err(last_error);
+ }
+ }
+ }
- Ok(serde_json::json!({
- "data": data,
- "mimeType": mime_type
- }))
+ Err(last_error)
}
fn get_mime_type(path: &str) -> String {
diff --git a/screenpipe-js/ai-proxy/src/providers/gemini.ts b/screenpipe-js/ai-proxy/src/providers/gemini.ts
index 3bc43de58..771c6c752 100644
--- a/screenpipe-js/ai-proxy/src/providers/gemini.ts
+++ b/screenpipe-js/ai-proxy/src/providers/gemini.ts
@@ -252,6 +252,12 @@ export class GeminiProvider implements AIProvider {
const requestBody = this.buildRequestBody(body, hasWebSearch);
console.log('[Gemini Vertex] Streaming request to:', url);
+ console.log('[Gemini Vertex] Request body:', JSON.stringify({
+ hasSystemInstruction: !!requestBody.systemInstruction,
+ hasTools: !!(requestBody.tools?.length),
+ toolNames: requestBody.tools?.[0]?.functionDeclarations?.map((f: any) => f.name) || [],
+ hasToolConfig: !!requestBody.toolConfig,
+ }));
const response = await fetch(url, {
method: 'POST',
@@ -287,6 +293,15 @@ export class GeminiProvider implements AIProvider {
const query = pendingWebSearch.args?.query || pendingWebSearch.args?.q || '';
console.log('[Gemini Vertex] Executing pending web_search:', query);
+ // Stream a searching indicator
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: { content: `\n\n*Searching the web for "${query}"...*\n\n` } }],
+ })}\n\n`
+ )
+ );
+
try {
const searchResult = await self.executeWebSearch(query);
@@ -308,6 +323,15 @@ export class GeminiProvider implements AIProvider {
)
);
}
+
+ // Send proper finish_reason after web search completes
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: {}, finish_reason: 'stop' }],
+ })}\n\n`
+ )
+ );
}
controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));
@@ -340,6 +364,7 @@ export class GeminiProvider implements AIProvider {
// Handle function calls
if (part.functionCall) {
const funcName = part.functionCall.name;
+ console.log('[Gemini Vertex] Model called function:', funcName, JSON.stringify(part.functionCall.args || {}));
// If it's web_search, save it for execution after stream ends
if (funcName === 'web_search' || funcName === 'google_search') {
@@ -347,7 +372,7 @@ export class GeminiProvider implements AIProvider {
name: funcName,
args: part.functionCall.args || {},
};
- console.log('[Gemini Vertex] Detected web_search call, will execute after stream');
+ console.log('[Gemini Vertex] Saving web_search for execution after stream ends');
// Don't emit the tool call - we'll handle it ourselves
} else {
// For other tools, emit the tool call for client to handle
@@ -376,19 +401,26 @@ export class GeminiProvider implements AIProvider {
}
}
- // Check for finish reason (but don't close if we have pending web search)
+ // Check for finish reason
const finishReason = data.candidates?.[0]?.finishReason;
if (finishReason) {
- const mappedReason = finishReason === 'STOP' ? 'stop' :
- finishReason === 'MAX_TOKENS' ? 'length' :
- finishReason === 'TOOL_USE' ? 'tool_calls' : 'stop';
- controller.enqueue(
- new TextEncoder().encode(
- `data: ${JSON.stringify({
- choices: [{ delta: {}, finish_reason: mappedReason }],
- })}\n\n`
- )
- );
+ // If we have a pending web search, don't send 'tool_calls' finish reason
+ // because we'll handle the tool ourselves
+ if (pendingWebSearch && finishReason === 'TOOL_USE') {
+ console.log('[Gemini Vertex] Suppressing tool_calls finish_reason for web_search');
+ // Don't emit finish_reason yet - we'll send 'stop' after web search completes
+ } else {
+ const mappedReason = finishReason === 'STOP' ? 'stop' :
+ finishReason === 'MAX_TOKENS' ? 'length' :
+ finishReason === 'TOOL_USE' ? 'tool_calls' : 'stop';
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: {}, finish_reason: mappedReason }],
+ })}\n\n`
+ )
+ );
+ }
}
} catch (e) {
// Skip invalid JSON
@@ -405,6 +437,8 @@ export class GeminiProvider implements AIProvider {
}
private buildRequestBody(body: RequestBody, _hasWebSearch: boolean): any {
+ // Extract system message for systemInstruction
+ const systemMsg = body.messages.find(m => m.role === 'system');
const contents = this.formatMessages(body.messages);
const requestBody: any = {
@@ -414,6 +448,17 @@ export class GeminiProvider implements AIProvider {
},
};
+ // Add system instruction properly (Gemini's native way)
+ if (systemMsg) {
+ const systemText = typeof systemMsg.content === 'string' ? systemMsg.content : '';
+ if (systemText) {
+ requestBody.systemInstruction = {
+ parts: [{ text: systemText }],
+ };
+ console.log('[Gemini Vertex] System instruction set');
+ }
+ }
+
// Add response format if specified
if (body.response_format?.type === 'json_schema' && body.response_format.schema) {
requestBody.generationConfig.responseMimeType = 'application/json';
@@ -428,6 +473,12 @@ export class GeminiProvider implements AIProvider {
const functionDeclarations = this.convertToolsToGeminiFormat(body.tools);
if (functionDeclarations.length > 0) {
requestBody.tools = [{ functionDeclarations }];
+ // Enable automatic function calling mode
+ requestBody.toolConfig = {
+ functionCallingConfig: {
+ mode: 'AUTO',
+ },
+ };
console.log('[Gemini Vertex] Tools available:', functionDeclarations.map(f => f.name));
}
}
@@ -551,7 +602,7 @@ export class GeminiProvider implements AIProvider {
for (const msg of messages) {
if (msg.role === 'system') {
- // Gemini doesn't have a system role, prepend to first user message
+ // System messages are handled via systemInstruction in buildRequestBody
continue;
}
@@ -637,14 +688,8 @@ export class GeminiProvider implements AIProvider {
}
}
- // Handle system message by prepending to first user message
- const systemMsg = messages.find(m => m.role === 'system');
- if (systemMsg && formatted.length > 0 && formatted[0].role === 'user') {
- const systemText = typeof systemMsg.content === 'string' ? systemMsg.content : '';
- if (systemText) {
- formatted[0].parts.unshift({ text: `System: ${systemText}\n\n` });
- }
- }
+ // Note: System message is now handled via systemInstruction in buildRequestBody
+ // No need to prepend to first user message anymore
return formatted;
}