diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index a8c23e193..2d750f45d 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -117,7 +117,7 @@ export class ConfigHandler { this.workspaceDirs = null; // forces workspace dirs reload try { - const orgs = await this.getOrgs(signal); + const orgs = await this.getOrgs(); // Figure out selected org const workspaceId = await this.getWorkspaceId(); @@ -162,17 +162,18 @@ export class ConfigHandler { if (e instanceof Error && e.message.includes("AbortError")) { return; } else { + this.setInitialized?.(); // Error case counts for initialization throw e; } } } - private async getOrgs(signal: AbortSignal): Promise { + private async getOrgs(): Promise { if (await this.controlPlaneClient.isSignedIn()) { - const orgDescs = await this.controlPlaneClient.listOrganizations(signal); - const personalHubOrg = await this.getPersonalHubOrg(signal); + const orgDescs = await this.controlPlaneClient.listOrganizations(); + const personalHubOrg = await this.getPersonalHubOrg(); const hubOrgs = await Promise.all( - orgDescs.map((org) => this.getNonPersonalHubOrg(org, signal)), + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), ); return [...hubOrgs, personalHubOrg]; } else { @@ -191,11 +192,8 @@ export class ConfigHandler { })); } - private async getHubProfiles(orgScopeId: string | null, signal: AbortSignal) { - const assistants = await this.controlPlaneClient.listAssistants( - orgScopeId, - signal, - ); + private async getHubProfiles(orgScopeId: string | null) { + const assistants = await this.controlPlaneClient.listAssistants(orgScopeId); return await Promise.all( assistants.map(async (assistant) => { @@ -223,16 +221,12 @@ export class ConfigHandler { private async getNonPersonalHubOrg( org: OrganizationDescription, - signal: AbortSignal, ): Promise { const localProfiles = await this.getLocalProfiles({ includeGlobal: false, includeWorkspace: true, }); - const profiles = [ - ...(await this.getHubProfiles(org.id, signal)), - ...localProfiles, - ]; + const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles]; return this.rectifyProfilesForOrg(org, profiles); } @@ -242,12 +236,12 @@ export class ConfigHandler { name: "Personal", slug: undefined, }; - private async getPersonalHubOrg(signal: AbortSignal) { + private async getPersonalHubOrg() { const localProfiles = await this.getLocalProfiles({ includeGlobal: true, includeWorkspace: true, }); - const hubProfiles = await this.getHubProfiles(null, signal); + const hubProfiles = await this.getHubProfiles(null); const profiles = [...hubProfiles, ...localProfiles]; return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles); } diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index d971785d7..a1fe22099 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -45,7 +45,6 @@ export class ControlPlaneClient { async resolveFQSNs( fqsns: FQSN[], orgScopeId: string | null, - signal?: AbortSignal, ): Promise<(SecretResult | undefined)[]> { if (!(await this.isSignedIn())) { return fqsns.map((fqsn) => ({ @@ -61,7 +60,6 @@ export class ControlPlaneClient { const resp = await this.request("ide/sync-secrets", { method: "POST", body: JSON.stringify({ fqsns, orgScopeId }), - signal, }); return (await resp.json()) as any; } @@ -105,10 +103,7 @@ export class ControlPlaneClient { return resp; } - public async listAssistants( - organizationId: string | null, - signal?: AbortSignal, - ): Promise< + public async listAssistants(organizationId: string | null): Promise< { configResult: ConfigResult; ownerSlug: string; @@ -128,7 +123,6 @@ export class ControlPlaneClient { const resp = await this.request(url, { method: "GET", - signal, }); return (await resp.json()) as any; } catch (e) { @@ -136,9 +130,7 @@ export class ControlPlaneClient { } } - public async listOrganizations( - signal?: AbortSignal, - ): Promise> { + public async listOrganizations(): Promise> { if (!(await this.isSignedIn())) { return []; } @@ -146,7 +138,6 @@ export class ControlPlaneClient { try { const resp = await this.request("ide/list-organizations", { method: "GET", - signal, }); const { organizations } = (await resp.json()) as any; return organizations; @@ -157,7 +148,6 @@ export class ControlPlaneClient { public async listAssistantFullSlugs( organizationId: string | null, - signal?: AbortSignal, ): Promise { if (!(await this.isSignedIn())) { return null; @@ -170,7 +160,6 @@ export class ControlPlaneClient { try { const resp = await this.request(url, { method: "GET", - signal, }); const { fullSlugs } = (await resp.json()) as any; return fullSlugs; @@ -179,9 +168,7 @@ export class ControlPlaneClient { } } - public async getFreeTrialStatus( - signal?: AbortSignal, - ): Promise { + public async getFreeTrialStatus(): Promise { if (!(await this.isSignedIn())) { return null; } @@ -189,7 +176,6 @@ export class ControlPlaneClient { try { const resp = await this.request("ide/free-trial-status", { method: "GET", - signal, }); return (await resp.json()) as FreeTrialStatus; } catch (e) { @@ -204,7 +190,6 @@ export class ControlPlaneClient { */ public async getModelsAddOnCheckoutUrl( vsCodeUriScheme?: string, - signal?: AbortSignal, ): Promise<{ url: string } | null> { if (!(await this.isSignedIn())) { return null; @@ -224,7 +209,6 @@ export class ControlPlaneClient { `ide/get-models-add-on-checkout-url?${params.toString()}`, { method: "GET", - signal, }, ); return (await resp.json()) as { url: string }; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f0f967669..f0137bd0c 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -147,7 +147,9 @@ export class VsCodeExtension { resolveVerticalDiffManager?.(this.verticalDiffManager); void setupRemoteConfigSync(() => - this.configHandler.reloadConfig.bind(this.configHandler), + this.configHandler.reloadConfig.bind(this.configHandler)( + "Remote config sync", + ), ); void this.configHandler.loadConfig().then(({ config }) => { diff --git a/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx index 5947aa12d..7cac430a8 100644 --- a/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx +++ b/gui/src/components/AssistantAndOrgListbox/ScopeSelect.tsx @@ -10,7 +10,6 @@ import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectCurrentOrg, setSelectedOrgId, - setSelectedProfile, } from "../../redux/slices/profilesSlice"; import { Listbox, @@ -45,14 +44,8 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) { const dispatch = useAppDispatch(); const handleChange = (newValue: string) => { - const org = organizations.find((o) => o.id === newValue); - if (!org) { - return; - } - // optimisitic update - dispatch(setSelectedOrgId(org.id)); - dispatch(setSelectedProfile(org.selectedProfileId)); + dispatch(setSelectedOrgId(newValue)); ideMessenger.post("didChangeSelectedOrg", { id: newValue, }); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 261615b8b..dbf019a22 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,10 +21,7 @@ import { SessionMetadata, ThinkingChatMessage, Tool, - ToolCallDelta, - ToolCallState, } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { renderChatMessage, @@ -33,170 +30,13 @@ import { import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; -import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils"; +import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findChatHistoryItemByToolCallId, findToolCallById } from "../util"; +import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; -/** - * Helper function to filter out duplicate edit/search-replace tool calls. - * Only keeps the first occurrence of edit tools. - * - * We don't support multiple parallel apply calls - see tool definitions for - * instructions we provide to models to prevent this behavior. - */ -function filterMultipleEditToolCalls( - toolCalls: ToolCallDelta[], -): ToolCallDelta[] { - const editToolNames = [ - BuiltInToolNames.EditExistingFile, - BuiltInToolNames.SearchAndReplaceInFile, - ]; - let hasSeenEditTool = false; - - return toolCalls.filter((toolCall) => { - const isEditTool = editToolNames.includes(toolCall.function?.name as any); - - if (isEditTool) { - if (hasSeenEditTool) { - return false; // Skip this duplicate edit tool - } - hasSeenEditTool = true; - } - - return true; - }); -} - -/** - * Initializes tool call states for a new message containing tool calls. - * This function is called when we receive a complete message with tool calls, - * typically in non-streaming scenarios or when processing the first chunk - * of a streaming message that contains tool calls. - * - * @param message - The chat message containing tool calls to process - * @param lastItem - The chat history item to attach tool call states to - */ -export function handleToolCallsInMessage( - message: ChatMessage, - lastItem: ChatHistoryItemWithMessageId, -): void { - if ( - (message.role === "assistant" || message.role === "thinking") && - message.toolCalls?.length - ) { - // Filter out duplicate edit/search-replace tool calls - only keep the first one - const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls); - - // Initialize tool call states for each filtered tool call in the message - // Each tool call gets its own state to track generation/execution progress - lastItem.toolCallStates = filteredToolCalls.map((toolCallDelta) => - addToolCallDeltaToState(toolCallDelta, undefined), - ); - - // Update the message's toolCalls array to reflect the processed tool calls - // We can safely cast because we verified the role above - const curMessage = lastItem.message as - | AssistantChatMessage - | ThinkingChatMessage; - curMessage.toolCalls = lastItem.toolCallStates.map( - (state) => state.toolCall, - ); - } -} - -/** - * Applies a single tool call delta to the tool call states array. - * - * This function handles the core logic for OpenAI-style tool call streaming where: - * - Initial tool calls come with full details (ID, name, arguments) - * - Subsequent argument fragments come without IDs and need to update the most recent tool call - * - Multiple parallel tool calls can be streamed simultaneously - * - * @param toolCallDelta - The incoming tool call delta from the LLM stream - * @param toolCallStates - Array of existing tool call states (modified in place) - */ -function applyToolCallDelta( - toolCallDelta: ToolCallDelta, - toolCallStates: ToolCallState[], -): void { - // Find existing state by matching toolCallId - this ensures we update - // the correct tool call even when multiple tool calls are being streamed - let existingStateIndex = -1; - - if (toolCallDelta.id) { - // Tool call has an ID - find by exact match - // This handles: new tool calls or explicit updates to existing ones - existingStateIndex = toolCallStates.findIndex( - (state) => state.toolCallId === toolCallDelta.id, - ); - } else { - // No ID in delta (common in OpenAI streaming fragments) - // Strategy: Update the most recently added tool call that's still being generated - // This handles the pattern: initial tool call with ID, then fragments without ID - existingStateIndex = toolCallStates.length - 1; - - // Ensure we have at least one tool call to update - if (existingStateIndex < 0) { - existingStateIndex = -1; // Will create new tool call - } - } - - const existingState = - existingStateIndex >= 0 ? toolCallStates[existingStateIndex] : undefined; - - // Apply the delta to create an updated state (either updating existing or creating new) - const updatedState = addToolCallDeltaToState(toolCallDelta, existingState); - - if (existingStateIndex >= 0) { - // Update existing tool call state in place - toolCallStates[existingStateIndex] = updatedState; - } else { - // Add new tool call state for a newly discovered tool call - toolCallStates.push(updatedState); - } -} - -/** - * Handles incremental updates to tool calls during streaming responses. - * This function processes streaming deltas for tool calls, updating existing - * tool call states or creating new ones as needed. It uses ID-based matching - * to ensure tool call updates are applied to the correct tool call state. - * - * @param message - The streaming message chunk containing tool call deltas - * @param lastItem - The chat history item containing existing tool call states - */ -export function handleStreamingToolCallUpdates( - message: ChatMessage, - lastItem: ChatHistoryItemWithMessageId, -): void { - if ( - message.role === "assistant" && - message.toolCalls?.length && - lastItem.message.role === "assistant" - ) { - // Start with existing tool call states or empty array if none exist - const existingToolCallStates = lastItem.toolCallStates || []; - const updatedToolCallStates: ToolCallState[] = [...existingToolCallStates]; - - // Filter out duplicate edit/search-replace tool calls - only keep the first one - const filteredToolCalls = filterMultipleEditToolCalls(message.toolCalls); - - // Process each filtered tool call delta, matching by ID to update the correct state - filteredToolCalls.forEach((toolCallDelta) => { - applyToolCallDelta(toolCallDelta, updatedToolCallStates); - }); - - // Replace the entire tool call states array with the updated version - lastItem.toolCallStates = updatedToolCallStates; - - // Update the message's toolCalls array to reflect current tool call states - (lastItem.message as any).toolCalls = updatedToolCallStates.map( - (state) => state.toolCall, - ); - } -} +const getIdeMessenger = () => (window as any).ideMessenger; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -293,18 +133,14 @@ export const sessionSlice = createSlice({ let validAssistantMessageIdx = -1; for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) { const message = state.history[i]; - const hasGeneratedMsg = message.toolCallStates?.some( - (toolCallState) => toolCallState.status !== "generating", - ); - if (message.message.content || hasGeneratedMsg) { + if ( + message.message.content || + message.toolCallState?.status !== "generating" + ) { validAssistantMessageIdx = i; // Cancel any tool calls that are dangling and generated - if (message.toolCallStates) { - message.toolCallStates.forEach((toolCallState) => { - if (toolCallState.status === "generated") { - toolCallState.status = "canceled"; - } - }); + if (message.toolCallState?.status === "generated") { + message.toolCallState.status = "canceled"; } break; } @@ -550,7 +386,30 @@ export const sessionSlice = createSlice({ lastItem = state.history[state.history.length - 1]; lastMessage = lastItem.message; - handleToolCallsInMessage(message, lastItem); + if ( + (message.role === "assistant" || message.role === "thinking") && + message.toolCalls?.[0] + ) { + // Only support one tool call for now. + // There are further changes required throughout the system + // to support multiple tool calls in a single message from + // OpenAI-compatible providers. + const toolCallDelta = message.toolCalls[0]; + const newToolCallState = addToolCallDeltaToState( + toolCallDelta, + lastItem.toolCallState, + ); + lastItem.toolCallState = newToolCallState; + // We know this is one of these two types because we just added it + const curMessage = lastMessage as + | AssistantChatMessage + | ThinkingChatMessage; + if (curMessage.toolCalls) { + curMessage.toolCalls.push(newToolCallState.toolCall); + } else { + curMessage.toolCalls = [newToolCallState.toolCall]; + } + } return; } @@ -559,18 +418,31 @@ export const sessionSlice = createSlice({ // The remainder of this function handles streaming messages if ( lastMessage.role !== message.role || - message.role === "tool" // Tool messages should always create new messages + // This is for when a tool call comes immediately before/after tool call + (lastMessage.role === "assistant" && + message.role === "assistant" && + // Last message isn't completely new + !(!lastMessage.toolCalls?.length && !lastMessage.content) && + // And there's a difference in tool call presence + (lastMessage.toolCalls?.length ?? 0) !== + (message.toolCalls?.length ?? 0)) ) { // Create a new message const historyItem: ChatHistoryItemWithMessageId = { message: { ...message, - content: "", // Start with empty content, let accumulation logic handle it + content: "", id: uuidv4(), }, contextItems: [], }; - handleToolCallsInMessage(message, historyItem); + if (message.role === "assistant" && message.toolCalls?.[0]) { + const toolCallDelta = message.toolCalls[0]; + historyItem.toolCallState = addToolCallDeltaToState( + toolCallDelta, + undefined, + ); + } state.history.push(historyItem); lastItem = state.history[state.history.length - 1]; lastMessage = lastItem.message; @@ -617,10 +489,17 @@ export const sessionSlice = createSlice({ } } else if ( message.role === "assistant" && - message.toolCalls?.length && + message.toolCalls?.[0] && lastMessage.role === "assistant" ) { - handleStreamingToolCallUpdates(message, lastItem); + // Intentionally only supporting one tool call for now. + const toolCallDelta = message.toolCalls[0]; + const newToolCallState = addToolCallDeltaToState( + toolCallDelta, + lastItem.toolCallState, + ); + lastItem.toolCallState = newToolCallState; + lastMessage.toolCalls = [newToolCallState.toolCall]; } } } @@ -768,11 +647,10 @@ export const sessionSlice = createSlice({ tools: Tool[]; }>, ) => { - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); - if (toolCallState) { toolCallState.status = "generated"; @@ -792,17 +670,14 @@ export const sessionSlice = createSlice({ }>, ) => { // Update tool call state and corresponding tool output message - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); if (toolCallState) { toolCallState.output = action.payload.contextItems; } - const toolItem = findChatHistoryItemByToolCallId( - state.history, - action.payload.toolCallId, - ); + const toolItem = findToolOutput(state.history, action.payload.toolCallId); if (toolItem) { toolItem.message.content = renderContextItems( action.payload.contextItems, @@ -818,7 +693,7 @@ export const sessionSlice = createSlice({ toolCallId: string; }>, ) => { - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); @@ -832,7 +707,7 @@ export const sessionSlice = createSlice({ toolCallId: string; }>, ) => { - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); @@ -846,7 +721,7 @@ export const sessionSlice = createSlice({ toolCallId: string; }>, ) => { - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); @@ -860,7 +735,7 @@ export const sessionSlice = createSlice({ toolCallId: string; }>, ) => { - const toolCallState = findToolCallById( + const toolCallState = findToolCall( state.history, action.payload.toolCallId, ); @@ -907,16 +782,23 @@ function addPassthroughCases( ) { thunks.forEach((thunk) => { builder - .addCase(thunk.fulfilled, (_state, _action) => {}) - .addCase(thunk.rejected, (_state, _action) => {}) - .addCase(thunk.pending, (_state, _action) => {}); + .addCase(thunk.fulfilled, (state, action) => {}) + .addCase(thunk.rejected, (state, action) => {}) + .addCase(thunk.pending, (state, action) => {}); }); } +export const selectCurrentToolCall = createSelector( + (store: RootState) => store.session.history, + (history) => { + return findCurrentToolCall(history); + }, +); + export const selectApplyStateByStreamId = createSelector( [ (state: RootState) => state.session.codeBlockApplyStates.states, - (_state: RootState, streamId?: string) => streamId, + (state: RootState, streamId?: string) => streamId, ], (states, streamId) => { return states.find((state) => state.streamId === streamId); @@ -926,7 +808,7 @@ export const selectApplyStateByStreamId = createSelector( export const selectApplyStateByToolCallId = createSelector( [ (state: RootState) => state.session.codeBlockApplyStates.states, - (_state: RootState, toolCallId?: string) => toolCallId, + (state: RootState, toolCallId?: string) => toolCallId, ], (states, toolCallId) => { if (toolCallId) { diff --git a/packages/hub/src/ContinueHubClient.ts b/packages/hub/src/ContinueHubClient.ts index 3a52de8dd..516dee31b 100644 --- a/packages/hub/src/ContinueHubClient.ts +++ b/packages/hub/src/ContinueHubClient.ts @@ -57,19 +57,16 @@ export class ContinueHubClient implements IContinueHubClient { async resolveFQSNs( fqsns: FQSN[], orgScopeId: string | null, - signal?: AbortSignal, ): Promise<(SecretResult | undefined)[]> { const resp = await this.request("ide/sync-secrets", { method: "POST", body: JSON.stringify({ fqsns, orgScopeId }), - signal, }); return (await resp.json()) as any; } async listAssistants(options: { organizationId: string | null; alwaysUseProxy?: boolean; - signal?: AbortSignal; }): Promise< { configResult: ConfigResult; @@ -97,7 +94,6 @@ export class ContinueHubClient implements IContinueHubClient { const resp = await this.request(url, { method: "GET", - signal: options.signal, }); return (await resp.json()) as any; } catch (e) { @@ -107,7 +103,6 @@ export class ContinueHubClient implements IContinueHubClient { async listAssistantFullSlugs( organizationId: string | null, - signal?: AbortSignal, ): Promise { const url = organizationId ? `ide/list-assistant-full-slugs?organizationId=${organizationId}` @@ -116,7 +111,6 @@ export class ContinueHubClient implements IContinueHubClient { try { const resp = await this.request(url, { method: "GET", - signal, }); const { fullSlugs } = (await resp.json()) as any; return fullSlugs;