| | |
| | |
| | |
| | |
| | |
| |
|
| | import { useState, useRef, useCallback, useEffect, useMemo } from 'react'; |
| | import type { |
| | Config, |
| | EditorType, |
| | GeminiClient, |
| | ServerGeminiChatCompressedEvent, |
| | ServerGeminiContentEvent as ContentEvent, |
| | ServerGeminiFinishedEvent, |
| | ServerGeminiStreamEvent as GeminiEvent, |
| | ThoughtSummary, |
| | ToolCallRequestInfo, |
| | GeminiErrorEventValue, |
| | } from '@google/gemini-cli-core'; |
| | import { |
| | GeminiEventType as ServerGeminiEventType, |
| | getErrorMessage, |
| | isNodeError, |
| | MessageSenderType, |
| | logUserPrompt, |
| | GitService, |
| | UnauthorizedError, |
| | UserPromptEvent, |
| | DEFAULT_GEMINI_FLASH_MODEL, |
| | logConversationFinishedEvent, |
| | ConversationFinishedEvent, |
| | ApprovalMode, |
| | parseAndFormatApiError, |
| | } from '@google/gemini-cli-core'; |
| | import { type Part, type PartListUnion, FinishReason } from '@google/genai'; |
| | import type { |
| | HistoryItem, |
| | HistoryItemWithoutId, |
| | HistoryItemToolGroup, |
| | SlashCommandProcessorResult, |
| | } from '../types.js'; |
| | import { StreamingState, MessageType, ToolCallStatus } from '../types.js'; |
| | import { isAtCommand, isSlashCommand } from '../utils/commandUtils.js'; |
| | import { useShellCommandProcessor } from './shellCommandProcessor.js'; |
| | import { handleAtCommand } from './atCommandProcessor.js'; |
| | import { findLastSafeSplitPoint } from '../utils/markdownUtilities.js'; |
| | import { useStateAndRef } from './useStateAndRef.js'; |
| | import type { UseHistoryManagerReturn } from './useHistoryManager.js'; |
| | import { useLogger } from './useLogger.js'; |
| | import type { |
| | TrackedToolCall, |
| | TrackedCompletedToolCall, |
| | TrackedCancelledToolCall, |
| | } from './useReactToolScheduler.js'; |
| | import { promises as fs } from 'node:fs'; |
| | import path from 'node:path'; |
| | import { |
| | useReactToolScheduler, |
| | mapToDisplay as mapTrackedToolCallsToDisplay, |
| | } from './useReactToolScheduler.js'; |
| | import { useSessionStats } from '../contexts/SessionContext.js'; |
| | import { useKeypress } from './useKeypress.js'; |
| | import type { LoadedSettings } from '../../config/settings.js'; |
| |
|
| | enum StreamProcessingStatus { |
| | Completed, |
| | UserCancelled, |
| | Error, |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | export const useGeminiStream = ( |
| | geminiClient: GeminiClient, |
| | history: HistoryItem[], |
| | addItem: UseHistoryManagerReturn['addItem'], |
| | config: Config, |
| | settings: LoadedSettings, |
| | onDebugMessage: (message: string) => void, |
| | handleSlashCommand: ( |
| | cmd: PartListUnion, |
| | ) => Promise<SlashCommandProcessorResult | false>, |
| | shellModeActive: boolean, |
| | getPreferredEditor: () => EditorType | undefined, |
| | onAuthError: () => void, |
| | performMemoryRefresh: () => Promise<void>, |
| | modelSwitchedFromQuotaError: boolean, |
| | setModelSwitchedFromQuotaError: React.Dispatch<React.SetStateAction<boolean>>, |
| | onEditorClose: () => void, |
| | onCancelSubmit: () => void, |
| | ) => { |
| | const [initError, setInitError] = useState<string | null>(null); |
| | const abortControllerRef = useRef<AbortController | null>(null); |
| | const turnCancelledRef = useRef(false); |
| | const [isResponding, setIsResponding] = useState<boolean>(false); |
| | const [thought, setThought] = useState<ThoughtSummary | null>(null); |
| | const [pendingHistoryItemRef, setPendingHistoryItem] = |
| | useStateAndRef<HistoryItemWithoutId | null>(null); |
| | const processedMemoryToolsRef = useRef<Set<string>>(new Set()); |
| | const { startNewPrompt, getPromptCount } = useSessionStats(); |
| | const storage = config.storage; |
| | const logger = useLogger(storage); |
| | const gitService = useMemo(() => { |
| | if (!config.getProjectRoot()) { |
| | return; |
| | } |
| | return new GitService(config.getProjectRoot(), storage); |
| | }, [config, storage]); |
| |
|
| | const [toolCalls, scheduleToolCalls, markToolsAsSubmitted] = |
| | useReactToolScheduler( |
| | async (completedToolCallsFromScheduler) => { |
| | |
| | if (completedToolCallsFromScheduler.length > 0) { |
| | |
| | addItem( |
| | mapTrackedToolCallsToDisplay( |
| | completedToolCallsFromScheduler as TrackedToolCall[], |
| | ), |
| | Date.now(), |
| | ); |
| |
|
| | |
| | await handleCompletedTools( |
| | completedToolCallsFromScheduler as TrackedToolCall[], |
| | ); |
| | } |
| | }, |
| | config, |
| | setPendingHistoryItem, |
| | getPreferredEditor, |
| | onEditorClose, |
| | ); |
| |
|
| | const pendingToolCallGroupDisplay = useMemo( |
| | () => |
| | toolCalls.length ? mapTrackedToolCallsToDisplay(toolCalls) : undefined, |
| | [toolCalls], |
| | ); |
| |
|
| | const loopDetectedRef = useRef(false); |
| |
|
| | const onExec = useCallback(async (done: Promise<void>) => { |
| | setIsResponding(true); |
| | await done; |
| | setIsResponding(false); |
| | }, []); |
| | const { handleShellCommand } = useShellCommandProcessor( |
| | addItem, |
| | setPendingHistoryItem, |
| | onExec, |
| | onDebugMessage, |
| | config, |
| | geminiClient, |
| | ); |
| |
|
| | const streamingState = useMemo(() => { |
| | if (toolCalls.some((tc) => tc.status === 'awaiting_approval')) { |
| | return StreamingState.WaitingForConfirmation; |
| | } |
| | if ( |
| | isResponding || |
| | toolCalls.some( |
| | (tc) => |
| | tc.status === 'executing' || |
| | tc.status === 'scheduled' || |
| | tc.status === 'validating' || |
| | ((tc.status === 'success' || |
| | tc.status === 'error' || |
| | tc.status === 'cancelled') && |
| | !(tc as TrackedCompletedToolCall | TrackedCancelledToolCall) |
| | .responseSubmittedToGemini), |
| | ) |
| | ) { |
| | return StreamingState.Responding; |
| | } |
| | return StreamingState.Idle; |
| | }, [isResponding, toolCalls]); |
| |
|
| | useEffect(() => { |
| | if ( |
| | config.getApprovalMode() === ApprovalMode.YOLO && |
| | streamingState === StreamingState.Idle |
| | ) { |
| | const lastUserMessageIndex = history.findLastIndex( |
| | (item: HistoryItem) => item.type === MessageType.USER, |
| | ); |
| |
|
| | const turnCount = |
| | lastUserMessageIndex === -1 ? 0 : history.length - lastUserMessageIndex; |
| |
|
| | if (turnCount > 0) { |
| | logConversationFinishedEvent( |
| | config, |
| | new ConversationFinishedEvent(config.getApprovalMode(), turnCount), |
| | ); |
| | } |
| | } |
| | }, [streamingState, config, history]); |
| |
|
| | const cancelOngoingRequest = useCallback(() => { |
| | if (streamingState !== StreamingState.Responding) { |
| | return; |
| | } |
| | if (turnCancelledRef.current) { |
| | return; |
| | } |
| | turnCancelledRef.current = true; |
| | abortControllerRef.current?.abort(); |
| | if (pendingHistoryItemRef.current) { |
| | addItem(pendingHistoryItemRef.current, Date.now()); |
| | } |
| | addItem( |
| | { |
| | type: MessageType.INFO, |
| | text: 'Request cancelled.', |
| | }, |
| | Date.now(), |
| | ); |
| | setPendingHistoryItem(null); |
| | onCancelSubmit(); |
| | setIsResponding(false); |
| | }, [ |
| | streamingState, |
| | addItem, |
| | setPendingHistoryItem, |
| | onCancelSubmit, |
| | pendingHistoryItemRef, |
| | ]); |
| |
|
| | useKeypress( |
| | (key) => { |
| | if (key.name === 'escape') { |
| | cancelOngoingRequest(); |
| | } |
| | }, |
| | { isActive: streamingState === StreamingState.Responding }, |
| | ); |
| |
|
| | const prepareQueryForGemini = useCallback( |
| | async ( |
| | query: PartListUnion, |
| | userMessageTimestamp: number, |
| | abortSignal: AbortSignal, |
| | prompt_id: string, |
| | ): Promise<{ |
| | queryToSend: PartListUnion | null; |
| | shouldProceed: boolean; |
| | }> => { |
| | if (turnCancelledRef.current) { |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| | if (typeof query === 'string' && query.trim().length === 0) { |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| |
|
| | let localQueryToSendToGemini: PartListUnion | null = null; |
| |
|
| | if (typeof query === 'string') { |
| | const trimmedQuery = query.trim(); |
| | logUserPrompt( |
| | config, |
| | new UserPromptEvent( |
| | trimmedQuery.length, |
| | prompt_id, |
| | config.getContentGeneratorConfig()?.authType, |
| | trimmedQuery, |
| | ), |
| | ); |
| | onDebugMessage(`User query: '${trimmedQuery}'`); |
| | await logger?.logMessage(MessageSenderType.USER, trimmedQuery); |
| |
|
| | |
| | const slashCommandResult = isSlashCommand(trimmedQuery) |
| | ? await handleSlashCommand(trimmedQuery) |
| | : false; |
| |
|
| | if (slashCommandResult) { |
| | switch (slashCommandResult.type) { |
| | case 'schedule_tool': { |
| | const { toolName, toolArgs } = slashCommandResult; |
| | const toolCallRequest: ToolCallRequestInfo = { |
| | callId: `${toolName}-${Date.now()}-${Math.random().toString(16).slice(2)}`, |
| | name: toolName, |
| | args: toolArgs, |
| | isClientInitiated: true, |
| | prompt_id, |
| | }; |
| | scheduleToolCalls([toolCallRequest], abortSignal); |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| | case 'submit_prompt': { |
| | localQueryToSendToGemini = slashCommandResult.content; |
| |
|
| | return { |
| | queryToSend: localQueryToSendToGemini, |
| | shouldProceed: true, |
| | }; |
| | } |
| | case 'handled': { |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| | default: { |
| | const unreachable: never = slashCommandResult; |
| | throw new Error( |
| | `Unhandled slash command result type: ${unreachable}`, |
| | ); |
| | } |
| | } |
| | } |
| |
|
| | if (shellModeActive && handleShellCommand(trimmedQuery, abortSignal)) { |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| |
|
| | |
| | if (isAtCommand(trimmedQuery)) { |
| | const atCommandResult = await handleAtCommand({ |
| | query: trimmedQuery, |
| | config, |
| | addItem, |
| | onDebugMessage, |
| | messageId: userMessageTimestamp, |
| | signal: abortSignal, |
| | }); |
| |
|
| | |
| | addItem( |
| | { type: MessageType.USER, text: trimmedQuery }, |
| | userMessageTimestamp, |
| | ); |
| |
|
| | if (!atCommandResult.shouldProceed) { |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| | localQueryToSendToGemini = atCommandResult.processedQuery; |
| | } else { |
| | |
| | addItem( |
| | { type: MessageType.USER, text: trimmedQuery }, |
| | userMessageTimestamp, |
| | ); |
| | localQueryToSendToGemini = trimmedQuery; |
| | } |
| | } else { |
| | |
| | localQueryToSendToGemini = query; |
| | } |
| |
|
| | if (localQueryToSendToGemini === null) { |
| | onDebugMessage( |
| | 'Query processing resulted in null, not sending to Gemini.', |
| | ); |
| | return { queryToSend: null, shouldProceed: false }; |
| | } |
| | return { queryToSend: localQueryToSendToGemini, shouldProceed: true }; |
| | }, |
| | [ |
| | config, |
| | addItem, |
| | onDebugMessage, |
| | handleShellCommand, |
| | handleSlashCommand, |
| | logger, |
| | shellModeActive, |
| | scheduleToolCalls, |
| | ], |
| | ); |
| |
|
| | |
| |
|
| | const handleContentEvent = useCallback( |
| | ( |
| | eventValue: ContentEvent['value'], |
| | currentGeminiMessageBuffer: string, |
| | userMessageTimestamp: number, |
| | ): string => { |
| | if (turnCancelledRef.current) { |
| | |
| | return ''; |
| | } |
| | let newGeminiMessageBuffer = currentGeminiMessageBuffer + eventValue; |
| | if ( |
| | pendingHistoryItemRef.current?.type !== 'gemini' && |
| | pendingHistoryItemRef.current?.type !== 'gemini_content' |
| | ) { |
| | if (pendingHistoryItemRef.current) { |
| | addItem(pendingHistoryItemRef.current, userMessageTimestamp); |
| | } |
| | setPendingHistoryItem({ type: 'gemini', text: '' }); |
| | newGeminiMessageBuffer = eventValue; |
| | } |
| | |
| | |
| | const splitPoint = findLastSafeSplitPoint(newGeminiMessageBuffer); |
| | if (splitPoint === newGeminiMessageBuffer.length) { |
| | |
| | setPendingHistoryItem((item) => ({ |
| | type: item?.type as 'gemini' | 'gemini_content', |
| | text: newGeminiMessageBuffer, |
| | })); |
| | } else { |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | const beforeText = newGeminiMessageBuffer.substring(0, splitPoint); |
| | const afterText = newGeminiMessageBuffer.substring(splitPoint); |
| | addItem( |
| | { |
| | type: pendingHistoryItemRef.current?.type as |
| | | 'gemini' |
| | | 'gemini_content', |
| | text: beforeText, |
| | }, |
| | userMessageTimestamp, |
| | ); |
| | setPendingHistoryItem({ type: 'gemini_content', text: afterText }); |
| | newGeminiMessageBuffer = afterText; |
| | } |
| | return newGeminiMessageBuffer; |
| | }, |
| | [addItem, pendingHistoryItemRef, setPendingHistoryItem], |
| | ); |
| |
|
| | const handleUserCancelledEvent = useCallback( |
| | (userMessageTimestamp: number) => { |
| | if (turnCancelledRef.current) { |
| | return; |
| | } |
| | if (pendingHistoryItemRef.current) { |
| | if (pendingHistoryItemRef.current.type === 'tool_group') { |
| | const updatedTools = pendingHistoryItemRef.current.tools.map( |
| | (tool) => |
| | tool.status === ToolCallStatus.Pending || |
| | tool.status === ToolCallStatus.Confirming || |
| | tool.status === ToolCallStatus.Executing |
| | ? { ...tool, status: ToolCallStatus.Canceled } |
| | : tool, |
| | ); |
| | const pendingItem: HistoryItemToolGroup = { |
| | ...pendingHistoryItemRef.current, |
| | tools: updatedTools, |
| | }; |
| | addItem(pendingItem, userMessageTimestamp); |
| | } else { |
| | addItem(pendingHistoryItemRef.current, userMessageTimestamp); |
| | } |
| | setPendingHistoryItem(null); |
| | } |
| | addItem( |
| | { type: MessageType.INFO, text: 'User cancelled the request.' }, |
| | userMessageTimestamp, |
| | ); |
| | setIsResponding(false); |
| | setThought(null); |
| | }, |
| | [addItem, pendingHistoryItemRef, setPendingHistoryItem, setThought], |
| | ); |
| |
|
| | const handleErrorEvent = useCallback( |
| | (eventValue: GeminiErrorEventValue, userMessageTimestamp: number) => { |
| | if (pendingHistoryItemRef.current) { |
| | addItem(pendingHistoryItemRef.current, userMessageTimestamp); |
| | setPendingHistoryItem(null); |
| | } |
| | addItem( |
| | { |
| | type: MessageType.ERROR, |
| | text: parseAndFormatApiError( |
| | eventValue.error, |
| | config.getContentGeneratorConfig()?.authType, |
| | undefined, |
| | config.getModel(), |
| | DEFAULT_GEMINI_FLASH_MODEL, |
| | ), |
| | }, |
| | userMessageTimestamp, |
| | ); |
| | setThought(null); |
| | }, |
| | [addItem, pendingHistoryItemRef, setPendingHistoryItem, config, setThought], |
| | ); |
| |
|
| | const handleCitationEvent = useCallback( |
| | (text: string, userMessageTimestamp: number) => { |
| | if (!settings?.merged?.ui?.showCitations) { |
| | return; |
| | } |
| | if (pendingHistoryItemRef.current) { |
| | addItem(pendingHistoryItemRef.current, userMessageTimestamp); |
| | setPendingHistoryItem(null); |
| | } |
| | addItem({ type: MessageType.INFO, text }, userMessageTimestamp); |
| | }, |
| | [addItem, pendingHistoryItemRef, setPendingHistoryItem, settings], |
| | ); |
| |
|
| | const handleFinishedEvent = useCallback( |
| | (event: ServerGeminiFinishedEvent, userMessageTimestamp: number) => { |
| | const finishReason = event.value; |
| |
|
| | const finishReasonMessages: Record<FinishReason, string | undefined> = { |
| | [FinishReason.FINISH_REASON_UNSPECIFIED]: undefined, |
| | [FinishReason.STOP]: undefined, |
| | [FinishReason.MAX_TOKENS]: 'Response truncated due to token limits.', |
| | [FinishReason.SAFETY]: 'Response stopped due to safety reasons.', |
| | [FinishReason.RECITATION]: 'Response stopped due to recitation policy.', |
| | [FinishReason.LANGUAGE]: |
| | 'Response stopped due to unsupported language.', |
| | [FinishReason.BLOCKLIST]: 'Response stopped due to forbidden terms.', |
| | [FinishReason.PROHIBITED_CONTENT]: |
| | 'Response stopped due to prohibited content.', |
| | [FinishReason.SPII]: |
| | 'Response stopped due to sensitive personally identifiable information.', |
| | [FinishReason.OTHER]: 'Response stopped for other reasons.', |
| | [FinishReason.MALFORMED_FUNCTION_CALL]: |
| | 'Response stopped due to malformed function call.', |
| | [FinishReason.IMAGE_SAFETY]: |
| | 'Response stopped due to image safety violations.', |
| | [FinishReason.UNEXPECTED_TOOL_CALL]: |
| | 'Response stopped due to unexpected tool call.', |
| | }; |
| |
|
| | const message = finishReasonMessages[finishReason]; |
| | if (message) { |
| | addItem( |
| | { |
| | type: 'info', |
| | text: `⚠️ ${message}`, |
| | }, |
| | userMessageTimestamp, |
| | ); |
| | } |
| | }, |
| | [addItem], |
| | ); |
| |
|
| | const handleChatCompressionEvent = useCallback( |
| | (eventValue: ServerGeminiChatCompressedEvent['value']) => |
| | addItem( |
| | { |
| | type: 'info', |
| | text: |
| | `IMPORTANT: This conversation approached the input token limit for ${config.getModel()}. ` + |
| | `A compressed context will be sent for future messages (compressed from: ` + |
| | `${eventValue?.originalTokenCount ?? 'unknown'} to ` + |
| | `${eventValue?.newTokenCount ?? 'unknown'} tokens).`, |
| | }, |
| | Date.now(), |
| | ), |
| | [addItem, config], |
| | ); |
| |
|
| | const handleMaxSessionTurnsEvent = useCallback( |
| | () => |
| | addItem( |
| | { |
| | type: 'info', |
| | text: |
| | `The session has reached the maximum number of turns: ${config.getMaxSessionTurns()}. ` + |
| | `Please update this limit in your setting.json file.`, |
| | }, |
| | Date.now(), |
| | ), |
| | [addItem, config], |
| | ); |
| |
|
| | const handleLoopDetectedEvent = useCallback(() => { |
| | addItem( |
| | { |
| | type: 'info', |
| | text: `A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.`, |
| | }, |
| | Date.now(), |
| | ); |
| | }, [addItem]); |
| |
|
| | const processGeminiStreamEvents = useCallback( |
| | async ( |
| | stream: AsyncIterable<GeminiEvent>, |
| | userMessageTimestamp: number, |
| | signal: AbortSignal, |
| | ): Promise<StreamProcessingStatus> => { |
| | let geminiMessageBuffer = ''; |
| | const toolCallRequests: ToolCallRequestInfo[] = []; |
| | for await (const event of stream) { |
| | switch (event.type) { |
| | case ServerGeminiEventType.Thought: |
| | setThought(event.value); |
| | break; |
| | case ServerGeminiEventType.Content: |
| | geminiMessageBuffer = handleContentEvent( |
| | event.value, |
| | geminiMessageBuffer, |
| | userMessageTimestamp, |
| | ); |
| | break; |
| | case ServerGeminiEventType.ToolCallRequest: |
| | toolCallRequests.push(event.value); |
| | break; |
| | case ServerGeminiEventType.UserCancelled: |
| | handleUserCancelledEvent(userMessageTimestamp); |
| | break; |
| | case ServerGeminiEventType.Error: |
| | handleErrorEvent(event.value, userMessageTimestamp); |
| | break; |
| | case ServerGeminiEventType.ChatCompressed: |
| | handleChatCompressionEvent(event.value); |
| | break; |
| | case ServerGeminiEventType.ToolCallConfirmation: |
| | case ServerGeminiEventType.ToolCallResponse: |
| | |
| | break; |
| | case ServerGeminiEventType.MaxSessionTurns: |
| | handleMaxSessionTurnsEvent(); |
| | break; |
| | case ServerGeminiEventType.Finished: |
| | handleFinishedEvent( |
| | event as ServerGeminiFinishedEvent, |
| | userMessageTimestamp, |
| | ); |
| | break; |
| | case ServerGeminiEventType.Citation: |
| | handleCitationEvent(event.value, userMessageTimestamp); |
| | break; |
| | case ServerGeminiEventType.LoopDetected: |
| | |
| | |
| | loopDetectedRef.current = true; |
| | break; |
| | default: { |
| | |
| | const unreachable: never = event; |
| | return unreachable; |
| | } |
| | } |
| | } |
| | if (toolCallRequests.length > 0) { |
| | scheduleToolCalls(toolCallRequests, signal); |
| | } |
| | return StreamProcessingStatus.Completed; |
| | }, |
| | [ |
| | handleContentEvent, |
| | handleUserCancelledEvent, |
| | handleErrorEvent, |
| | scheduleToolCalls, |
| | handleChatCompressionEvent, |
| | handleFinishedEvent, |
| | handleMaxSessionTurnsEvent, |
| | handleCitationEvent, |
| | ], |
| | ); |
| |
|
| | const submitQuery = useCallback( |
| | async ( |
| | query: PartListUnion, |
| | options?: { isContinuation: boolean }, |
| | prompt_id?: string, |
| | ) => { |
| | if ( |
| | (streamingState === StreamingState.Responding || |
| | streamingState === StreamingState.WaitingForConfirmation) && |
| | !options?.isContinuation |
| | ) |
| | return; |
| |
|
| | const userMessageTimestamp = Date.now(); |
| |
|
| | |
| | if (!options?.isContinuation) { |
| | setModelSwitchedFromQuotaError(false); |
| | config.setQuotaErrorOccurred(false); |
| | } |
| |
|
| | abortControllerRef.current = new AbortController(); |
| | const abortSignal = abortControllerRef.current.signal; |
| | turnCancelledRef.current = false; |
| |
|
| | if (!prompt_id) { |
| | prompt_id = config.getSessionId() + '########' + getPromptCount(); |
| | } |
| |
|
| | const { queryToSend, shouldProceed } = await prepareQueryForGemini( |
| | query, |
| | userMessageTimestamp, |
| | abortSignal, |
| | prompt_id!, |
| | ); |
| |
|
| | if (!shouldProceed || queryToSend === null) { |
| | return; |
| | } |
| |
|
| | if (!options?.isContinuation) { |
| | startNewPrompt(); |
| | setThought(null); |
| | } |
| |
|
| | setIsResponding(true); |
| | setInitError(null); |
| |
|
| | try { |
| | const stream = geminiClient.sendMessageStream( |
| | queryToSend, |
| | abortSignal, |
| | prompt_id!, |
| | ); |
| | const processingStatus = await processGeminiStreamEvents( |
| | stream, |
| | userMessageTimestamp, |
| | abortSignal, |
| | ); |
| |
|
| | if (processingStatus === StreamProcessingStatus.UserCancelled) { |
| | return; |
| | } |
| |
|
| | if (pendingHistoryItemRef.current) { |
| | addItem(pendingHistoryItemRef.current, userMessageTimestamp); |
| | setPendingHistoryItem(null); |
| | } |
| | if (loopDetectedRef.current) { |
| | loopDetectedRef.current = false; |
| | handleLoopDetectedEvent(); |
| | } |
| | } catch (error: unknown) { |
| | if (error instanceof UnauthorizedError) { |
| | onAuthError(); |
| | } else if (!isNodeError(error) || error.name !== 'AbortError') { |
| | addItem( |
| | { |
| | type: MessageType.ERROR, |
| | text: parseAndFormatApiError( |
| | getErrorMessage(error) || 'Unknown error', |
| | config.getContentGeneratorConfig()?.authType, |
| | undefined, |
| | config.getModel(), |
| | DEFAULT_GEMINI_FLASH_MODEL, |
| | ), |
| | }, |
| | userMessageTimestamp, |
| | ); |
| | } |
| | } finally { |
| | setIsResponding(false); |
| | } |
| | }, |
| | [ |
| | streamingState, |
| | setModelSwitchedFromQuotaError, |
| | prepareQueryForGemini, |
| | processGeminiStreamEvents, |
| | pendingHistoryItemRef, |
| | addItem, |
| | setPendingHistoryItem, |
| | setInitError, |
| | geminiClient, |
| | onAuthError, |
| | config, |
| | startNewPrompt, |
| | getPromptCount, |
| | handleLoopDetectedEvent, |
| | ], |
| | ); |
| |
|
| | const handleCompletedTools = useCallback( |
| | async (completedToolCallsFromScheduler: TrackedToolCall[]) => { |
| | if (isResponding) { |
| | return; |
| | } |
| |
|
| | const completedAndReadyToSubmitTools = |
| | completedToolCallsFromScheduler.filter( |
| | ( |
| | tc: TrackedToolCall, |
| | ): tc is TrackedCompletedToolCall | TrackedCancelledToolCall => { |
| | const isTerminalState = |
| | tc.status === 'success' || |
| | tc.status === 'error' || |
| | tc.status === 'cancelled'; |
| |
|
| | if (isTerminalState) { |
| | const completedOrCancelledCall = tc as |
| | | TrackedCompletedToolCall |
| | | TrackedCancelledToolCall; |
| | return ( |
| | completedOrCancelledCall.response?.responseParts !== undefined |
| | ); |
| | } |
| | return false; |
| | }, |
| | ); |
| |
|
| | |
| | const clientTools = completedAndReadyToSubmitTools.filter( |
| | (t) => t.request.isClientInitiated, |
| | ); |
| | if (clientTools.length > 0) { |
| | markToolsAsSubmitted(clientTools.map((t) => t.request.callId)); |
| | } |
| |
|
| | |
| | const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter( |
| | (t) => |
| | t.request.name === 'save_memory' && |
| | t.status === 'success' && |
| | !processedMemoryToolsRef.current.has(t.request.callId), |
| | ); |
| |
|
| | if (newSuccessfulMemorySaves.length > 0) { |
| | |
| | void performMemoryRefresh(); |
| | |
| | newSuccessfulMemorySaves.forEach((t) => |
| | processedMemoryToolsRef.current.add(t.request.callId), |
| | ); |
| | } |
| |
|
| | const geminiTools = completedAndReadyToSubmitTools.filter( |
| | (t) => !t.request.isClientInitiated, |
| | ); |
| |
|
| | if (geminiTools.length === 0) { |
| | return; |
| | } |
| |
|
| | |
| | const allToolsCancelled = geminiTools.every( |
| | (tc) => tc.status === 'cancelled', |
| | ); |
| |
|
| | if (allToolsCancelled) { |
| | if (geminiClient) { |
| | |
| | |
| | const combinedParts = geminiTools.flatMap( |
| | (toolCall) => toolCall.response.responseParts, |
| | ); |
| | geminiClient.addHistory({ |
| | role: 'user', |
| | parts: combinedParts, |
| | }); |
| | } |
| |
|
| | const callIdsToMarkAsSubmitted = geminiTools.map( |
| | (toolCall) => toolCall.request.callId, |
| | ); |
| | markToolsAsSubmitted(callIdsToMarkAsSubmitted); |
| | return; |
| | } |
| |
|
| | const responsesToSend: Part[] = geminiTools.flatMap( |
| | (toolCall) => toolCall.response.responseParts, |
| | ); |
| | const callIdsToMarkAsSubmitted = geminiTools.map( |
| | (toolCall) => toolCall.request.callId, |
| | ); |
| |
|
| | const prompt_ids = geminiTools.map( |
| | (toolCall) => toolCall.request.prompt_id, |
| | ); |
| |
|
| | markToolsAsSubmitted(callIdsToMarkAsSubmitted); |
| |
|
| | |
| | if (modelSwitchedFromQuotaError) { |
| | return; |
| | } |
| |
|
| | submitQuery( |
| | responsesToSend, |
| | { |
| | isContinuation: true, |
| | }, |
| | prompt_ids[0], |
| | ); |
| | }, |
| | [ |
| | isResponding, |
| | submitQuery, |
| | markToolsAsSubmitted, |
| | geminiClient, |
| | performMemoryRefresh, |
| | modelSwitchedFromQuotaError, |
| | ], |
| | ); |
| |
|
| | const pendingHistoryItems = [ |
| | pendingHistoryItemRef.current, |
| | pendingToolCallGroupDisplay, |
| | ].filter((i) => i !== undefined && i !== null); |
| |
|
| | useEffect(() => { |
| | const saveRestorableToolCalls = async () => { |
| | if (!config.getCheckpointingEnabled()) { |
| | return; |
| | } |
| | const restorableToolCalls = toolCalls.filter( |
| | (toolCall) => |
| | (toolCall.request.name === 'replace' || |
| | toolCall.request.name === 'write_file') && |
| | toolCall.status === 'awaiting_approval', |
| | ); |
| |
|
| | if (restorableToolCalls.length > 0) { |
| | const checkpointDir = storage.getProjectTempCheckpointsDir(); |
| |
|
| | if (!checkpointDir) { |
| | return; |
| | } |
| |
|
| | try { |
| | await fs.mkdir(checkpointDir, { recursive: true }); |
| | } catch (error) { |
| | if (!isNodeError(error) || error.code !== 'EEXIST') { |
| | onDebugMessage( |
| | `Failed to create checkpoint directory: ${getErrorMessage(error)}`, |
| | ); |
| | return; |
| | } |
| | } |
| |
|
| | for (const toolCall of restorableToolCalls) { |
| | const filePath = toolCall.request.args['file_path'] as string; |
| | if (!filePath) { |
| | onDebugMessage( |
| | `Skipping restorable tool call due to missing file_path: ${toolCall.request.name}`, |
| | ); |
| | continue; |
| | } |
| |
|
| | try { |
| | if (!gitService) { |
| | onDebugMessage( |
| | `Checkpointing is enabled but Git service is not available. Failed to create snapshot for ${filePath}. Ensure Git is installed and working properly.`, |
| | ); |
| | continue; |
| | } |
| |
|
| | let commitHash: string | undefined; |
| | try { |
| | commitHash = await gitService.createFileSnapshot( |
| | `Snapshot for ${toolCall.request.name}`, |
| | ); |
| | } catch (error) { |
| | onDebugMessage( |
| | `Failed to create new snapshot: ${getErrorMessage(error)}. Attempting to use current commit.`, |
| | ); |
| | } |
| |
|
| | if (!commitHash) { |
| | commitHash = await gitService.getCurrentCommitHash(); |
| | } |
| |
|
| | if (!commitHash) { |
| | onDebugMessage( |
| | `Failed to create snapshot for ${filePath}. Checkpointing may not be working properly. Ensure Git is installed and the project directory is accessible.`, |
| | ); |
| | continue; |
| | } |
| |
|
| | const timestamp = new Date() |
| | .toISOString() |
| | .replace(/:/g, '-') |
| | .replace(/\./g, '_'); |
| | const toolName = toolCall.request.name; |
| | const fileName = path.basename(filePath); |
| | const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`; |
| | const clientHistory = await geminiClient?.getHistory(); |
| | const toolCallWithSnapshotFilePath = path.join( |
| | checkpointDir, |
| | toolCallWithSnapshotFileName, |
| | ); |
| |
|
| | await fs.writeFile( |
| | toolCallWithSnapshotFilePath, |
| | JSON.stringify( |
| | { |
| | history, |
| | clientHistory, |
| | toolCall: { |
| | name: toolCall.request.name, |
| | args: toolCall.request.args, |
| | }, |
| | commitHash, |
| | filePath, |
| | }, |
| | null, |
| | 2, |
| | ), |
| | ); |
| | } catch (error) { |
| | onDebugMessage( |
| | `Failed to create checkpoint for ${filePath}: ${getErrorMessage( |
| | error, |
| | )}. This may indicate a problem with Git or file system permissions.`, |
| | ); |
| | } |
| | } |
| | } |
| | }; |
| | saveRestorableToolCalls(); |
| | }, [ |
| | toolCalls, |
| | config, |
| | onDebugMessage, |
| | gitService, |
| | history, |
| | geminiClient, |
| | storage, |
| | ]); |
| |
|
| | return { |
| | streamingState, |
| | submitQuery, |
| | initError, |
| | pendingHistoryItems, |
| | thought, |
| | cancelOngoingRequest, |
| | }; |
| | }; |
| |
|