From b8de35cd8a4e0c0b3ba398ea8601be6701eb8e41 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Apr 2025 15:30:41 -0700 Subject: [PATCH 01/57] BROKEN - cascading config updates part 1 --- core/config/ConfigHandler.test.ts | 2 +- core/config/ConfigHandler.ts | 325 +++++++----------- core/core.ts | 31 +- core/protocol/core.ts | 12 +- core/protocol/coreWebview.ts | 10 +- core/protocol/ide.ts | 5 - core/protocol/passThrough.ts | 4 - core/protocol/webview.ts | 8 +- .../ContinuePluginStartupActivity.kt | 19 +- .../constants/MessageTypes.kt | 5 - .../continue/IdeProtocolClient.kt | 2 +- .../vscode/src/extension/VsCodeExtension.ts | 13 +- .../platform/AssistantSelect.tsx | 32 +- gui/src/context/Auth.tsx | 90 +---- gui/src/hooks/useSetup.ts | 46 ++- gui/src/pages/config/ScopeSelect.tsx | 5 - gui/src/redux/slices/miscSlice.ts | 27 -- gui/src/redux/slices/organizations/slice.ts | 17 +- gui/src/redux/slices/profiles/thunks.ts | 108 ------ gui/src/redux/store.ts | 6 - 20 files changed, 227 insertions(+), 540 deletions(-) delete mode 100644 gui/src/redux/slices/miscSlice.ts delete mode 100644 gui/src/redux/slices/profiles/thunks.ts diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 031075e90..6fdbcf38f 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -9,7 +9,7 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { - const profiles = testConfigHandler.listProfiles(); + const profiles = testConfigHandler.listProfileDescriptions(); expect(profiles?.length).toBe(1); expect(profiles?.[0].id).toBe("local"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 3a3c81fab..f3405a668 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,4 +1,4 @@ -import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; +import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient, @@ -25,6 +25,7 @@ import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { + OrganizationDescription, ProfileDescription, ProfileLifecycleManager, } from "./ProfileLifecycleManager.js"; @@ -38,10 +39,21 @@ type ConfigUpdateFunction = (payload: ConfigResult) => void; export class ConfigHandler { private readonly globalContext = new GlobalContext(); private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded - private selectedProfileId: string | null = null; - private localProfileManager: ProfileLifecycleManager; + private profiles: ProfileLifecycleManager[] = []; + private globalLocalProfileManager: ProfileLifecycleManager; + currentProfile: ProfileLifecycleManager | null = null; + private currentProfileId: string | null = null; controlPlaneClient: ControlPlaneClient; + _selectedOrgId: string | null = null; + _organizations: OrganizationDescription[] = []; + + get organizations() { + return this._organizations; + } + + get selectedOrgId() { + return this._selectedOrgId; + } initializedPromise: Promise; @@ -50,7 +62,6 @@ export class ConfigHandler { private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => Promise, sessionInfoPromise: Promise, - private readonly didSelectOrganization?: (orgId: string | null) => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -67,7 +78,7 @@ export class ConfigHandler { this.controlPlaneClient, writeLog, ); - this.localProfileManager = new ProfileLifecycleManager( + this.globalLocalProfileManager = new ProfileLifecycleManager( localProfileLoader, this.ide, ); @@ -115,13 +126,7 @@ export class ConfigHandler { } private async init() { - try { - await this.fetchControlPlaneProfiles(); - } catch (e) { - // If this fails, make sure at least local profile is loaded - console.error("Failed to fetch control plane profiles in init: ", e); - await this.loadLocalProfilesOnly(); - } + await this.fetchControlPlaneProfiles(); try { const configResult = await this.loadConfig(); @@ -131,33 +136,12 @@ export class ConfigHandler { } } - get currentProfile() { - if (!this.selectedProfileId) { - return null; - } - // IMPORTANT - // We must fall back to null, not the first or local profiles - // Because GUI must be the source of truth for selected profile - return ( - this.profiles?.find( - (p) => p.profileDescription.id === this.selectedProfileId, - ) ?? null - ); - } - - get inactiveProfiles() { - return (this.profiles ?? []).filter( - (p) => p.profileDescription.id !== this.selectedProfileId, - ); - } - async openConfigProfile(profileId?: string) { - let openProfileId = profileId || this.selectedProfileId; + let openProfileId = profileId || this.currentProfileId; const profile = this.profiles?.find( (p) => p.profileDescription.id === openProfileId, ); if (profile?.profileDescription.profileType === "local") { - const ideInfo = await this.ide.getIdeInfo(); await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); @@ -165,8 +149,94 @@ export class ConfigHandler { } } - async listOrganizations() { - return await this.controlPlaneClient.listOrganizations(); + private async cascadeConfigRefresh({ + refetchOrgs, + }: { + refetchOrgs: boolean; + refetchProfiles: boolean; + }) { + async function getWorkspaceId(): Promise { + const orgPart = (await this.getSelectedOrgId()) ?? "personal"; + const dirs = await this.ide.getWorkspaceDirs(); + return `${dirs.join("&")}:::${orgPart}`; + } + + // private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { + // this.profiles = profiles; + + // // If the last selected profile is in the list choose that + // // Otherwise, choose the first profile + // const previouslySelectedProfileId = + // await this.getPersistedSelectedProfileId(); + + // // Check if the previously selected profile exists in the current profiles + // const profileExists = profiles.some( + // (profile) => + // profile.profileDescription.id === previouslySelectedProfileId, + // ); + + // const selectedProfileId = profileExists + // ? previouslySelectedProfileId + // : (profiles[0]?.profileDescription.id ?? null); + + // // Notify listeners + // const profileDescriptions = profiles.map( + // (profile) => profile.profileDescription, + // ); + // this.notifyConfigListeners(); + // this.notifyProfileListeners(profileDescriptions, selectedProfileId); + // await this.setSelectedProfile(selectedProfileId); + // } + + // if (config) { + // this.inactiveProfiles.forEach((profile) => profile.clearConfig()); + // return (this.profiles ?? []).filter( + // (p) => p.profileDescription.id !== this.selectedProfileId, + // ); + // } + + // SET SELECTED PROFILE ID + const result = await this.loadConfig(); + this.notifyConfigListeners(result); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + selectedProfiles[await getWorkspaceId()] = profileId; + this.globalContext.update( + "lastSelectedProfileForWorkspace", + selectedProfiles, + ); + + // OTHER CASCADE STUFF + // async getPersistedSelectedProfileId(): Promise { + // const workspaceId = await this.getWorkspaceId(); + // const lastSelectedIds = + // this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + // return lastSelectedIds[workspaceId] ?? null; + // } + + // async getSelectedOrgId(): Promise { + // const selectedOrgs = + // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + // const workspaceId = await this.getWorkspaceId(); + // return selectedOrgs[workspaceId] ?? null; + // } + + // async setSelectedOrgId(orgId: string | null) { + // const selectedOrgs = + // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + // selectedOrgs[await this.getWorkspaceId()] = orgId; + // this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + // } + } + + async setSelectedOrgId(orgId: string | null) { + this._selectedOrgId = orgId; + await this.cascadeConfigRefresh(); + } + + async setSelectedProfile(profileId: string | null) { + this.currentProfile = profileId; + await this.cascadeConfigRefresh(); } async loadAssistantsForSelectedOrg() { @@ -217,97 +287,20 @@ export class ConfigHandler { } } - await this.updateAvailableProfiles(profiles); + this.profiles = profiles; + await this.cascadeConfigRefresh(); } private async getAllLocalProfiles() { const localAssistantProfiles = await this.getLocalAssistantProfiles(); - return [this.localProfileManager, ...localAssistantProfiles]; - } - - private async loadLocalProfilesOnly() { - const allLocalProfiles = await this.getAllLocalProfiles(); - await this.updateAvailableProfiles(allLocalProfiles); - } - - private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { - this.profiles = profiles; - - // If the last selected profile is in the list choose that - // Otherwise, choose the first profile - const previouslySelectedProfileId = - await this.getPersistedSelectedProfileId(); - - // Check if the previously selected profile exists in the current profiles - const profileExists = profiles.some( - (profile) => - profile.profileDescription.id === previouslySelectedProfileId, - ); - - const selectedProfileId = profileExists - ? previouslySelectedProfileId - : (profiles[0]?.profileDescription.id ?? null); - - // Notify listeners - const profileDescriptions = profiles.map( - (profile) => profile.profileDescription, - ); - this.notifyProfileListeners(profileDescriptions, selectedProfileId); - await this.setSelectedProfile(selectedProfileId); - } - - private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; - // We use this to keep track of whether we should reload the assistants - private lastFullSlugsList: FullSlug[] = []; - - private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean { - if (a.length !== b.length) { - return true; - } - for (let i = 0; i < a.length; i++) { - if (a[i].ownerSlug !== b[i].ownerSlug) { - return true; - } - if (a[i].packageSlug !== b[i].packageSlug) { - return true; - } - if (a[i].versionSlug !== b[i].versionSlug) { - return true; - } - } - return false; - } - - private async reloadHubAssistants() { - const selectedOrgId = await this.getSelectedOrgId(); - const newFullSlugsList = - await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId); - - if (newFullSlugsList) { - const shouldReload = this.fullSlugsListsDiffer( - newFullSlugsList, - this.lastFullSlugsList, - ); - if (shouldReload) { - await this.loadAssistantsForSelectedOrg(); - } - this.lastFullSlugsList = newFullSlugsList; - } + return [this.globalLocalProfileManager, ...localAssistantProfiles]; } private async fetchControlPlaneProfiles() { - if (await useHub(this.ideSettingsPromise)) { - clearInterval(this.platformProfilesRefreshInterval); - await this.loadAssistantsForSelectedOrg(); - - // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds - // If so, we do the full (more expensive) reload - this.platformProfilesRefreshInterval = setInterval( - this.reloadHubAssistants.bind(this), - PlatformProfileLoader.RELOAD_INTERVAL, - ); - } else { - try { + try { + if (await useHub(this.ideSettingsPromise)) { + await this.loadAssistantsForSelectedOrg(); + } else { const workspaces = await this.controlPlaneClient.listWorkspaces(); const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { @@ -323,60 +316,20 @@ export class ConfigHandler { profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); - - await this.updateAvailableProfiles(profiles); - } catch (e: any) { - console.error("Failed to load profiles: ", e); - await this.loadLocalProfilesOnly(); + this.profiles = profiles; } + } catch (e) { + console.error("Failed to load profiles: ", e); + this.profiles = await this.getAllLocalProfiles(); + } finally { + await this.cascadeConfigRefresh(); } } - async getPersistedSelectedProfileId(): Promise { - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - return lastSelectedIds[workspaceId] ?? null; - } - - async getSelectedOrgId(): Promise { - const selectedOrgs = - this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - const workspaceId = await this.getWorkspaceId(); - return selectedOrgs[workspaceId] ?? null; - } - - async setSelectedOrgId(orgId: string | null) { - const selectedOrgs = - this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - selectedOrgs[await this.getWorkspaceId()] = orgId; - this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); - this.didSelectOrganization?.(orgId); - } - - async setSelectedProfile(profileId: string | null) { - this.selectedProfileId = profileId; - const result = await this.loadConfig(); - this.notifyConfigListeners(result); - const selectedProfiles = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - selectedProfiles[await this.getWorkspaceId()] = profileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - selectedProfiles, - ); - } - - // A unique ID for the current workspace, built from folder names - private async getWorkspaceId(): Promise { - const dirs = await this.ide.getWorkspaceDirs(); - return dirs.join("&"); - } - // Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed updateIdeSettings(ideSettings: IdeSettings) { this.ideSettingsPromise = Promise.resolve(ideSettings); - void this.reloadConfig(); + void this.cascadeConfigRefresh(); } async updateControlPlaneSessionInfo( @@ -387,33 +340,7 @@ export class ConfigHandler { this.ideSettingsPromise, ); - this.fetchControlPlaneProfiles().catch(async (e) => { - console.error("Failed to fetch control plane profiles: ", e); - await this.loadLocalProfilesOnly(); - await this.reloadConfig(); - }); - } - - private profilesListeners: (( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void)[] = []; - onDidChangeAvailableProfiles( - listener: ( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void, - ) { - this.profilesListeners.push(listener); - } - - private notifyProfileListeners( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) { - for (const listener of this.profilesListeners) { - listener(profiles, selectedProfileId); - } + await this.fetchControlPlaneProfiles(); } private notifyConfigListeners(result: ConfigResult) { @@ -442,9 +369,7 @@ export class ConfigHandler { const { config, errors, configLoadInterrupted } = await this.currentProfile.reloadConfig(this.additionalContextProviders); - if (config) { - this.inactiveProfiles.forEach((profile) => profile.clearConfig()); - } + await this.cascadeConfigRefresh(); this.notifyConfigListeners({ config, errors, configLoadInterrupted }); return { config, errors, configLoadInterrupted }; @@ -465,8 +390,8 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] | null { - return this.profiles?.map((p) => p.profileDescription) ?? null; + listProfileDescriptions(): ProfileDescription[] { + return this.profiles?.map((p) => p.profileDescription) ?? []; } async loadConfig(): Promise> { diff --git a/core/core.ts b/core/core.ts index 11fecffb2..574fa099c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -108,11 +108,6 @@ export class Core { ideSettingsPromise, this.onWrite, sessionInfoPromise, - (orgId: string | null) => { - void messenger.request("didSelectOrganization", { - orgId, - }); - }, ); this.docsService = DocsService.createSingleton( @@ -123,8 +118,6 @@ export class Core { const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.onConnectionsRefreshed = async () => { - // This ensures that it triggers a NEW load after waiting for config promise to finish - await this.configHandler.loadConfig(); await this.configHandler.reloadConfig(); }; @@ -134,6 +127,9 @@ export class Core { result: serializedResult, profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, + selectedOrgId: this.configHandler.selectedOrgId, + availableOrgProfiles: this.configHandler.listProfileDescriptions(), + availableOrgs: this.configHandler.organizations, }); // update additional submenu context providers registered via VSCode API @@ -146,14 +142,6 @@ export class Core { } }); - this.configHandler.onDidChangeAvailableProfiles( - (profiles, selectedProfileId) => - this.messenger.send("didChangeAvailableProfiles", { - profiles, - selectedProfileId, - }), - ); - // Dev Data Logger const dataLogger = DataLogger.getInstance(); dataLogger.core = this; @@ -308,13 +296,6 @@ export class Core { this.configHandler.updateIdeSettings(msg.data); }); - on("config/listProfiles", async (msg) => { - const profiles = this.configHandler.listProfiles(); - const selectedProfileId = - this.configHandler.currentProfile?.profileDescription.id ?? null; - return { profiles, selectedProfileId }; - }); - on("config/refreshProfiles", async (msg) => { await this.configHandler.loadAssistantsForSelectedOrg(); }); @@ -344,10 +325,6 @@ export class Core { await this.messenger.request("openUrl", url); }); - on("controlPlane/listOrganizations", async (msg) => { - return await this.configHandler.listOrganizations(); - }); - on("mcp/reloadServer", async (msg) => { mcpManager.refreshConnection(msg.data.id); }); @@ -829,7 +806,7 @@ export class Core { // on("didChangeSelectedProfile", async (msg) => { - await this.configHandler.setSelectedProfile(msg.data.id); + await this.configHandler.setSelectedProfileId(msg.data.id); await this.configHandler.reloadConfig(); }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 03940c283..d7a5fdd01 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -5,8 +5,6 @@ import { } from "@continuedev/config-yaml"; import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; -import { OrganizationDescription } from "../config/ProfileLifecycleManager"; import { SharedConfigSchema } from "../config/sharedConfig"; import { GlobalContextModelSelections } from "../util/GlobalContext"; @@ -32,6 +30,7 @@ import type { SlashCommandDescription, ToolCall, } from "../"; +import { ControlPlaneSessionInfo } from "../control-plane/client"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -70,10 +69,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [ - undefined, - { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, - ]; "config/refreshProfiles": [undefined, void]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; @@ -198,5 +193,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - "controlPlane/listOrganizations": [undefined, OrganizationDescription[]]; + didChangeControlPlaneSessionInfo: [ + { sessionInfo: ControlPlaneSessionInfo | undefined }, + void, + ]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 4dcf74ee5..292682f8a 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -1,5 +1,3 @@ -import { ProfileDescription } from "../config/ConfigHandler.js"; - import { ToCoreFromIdeOrWebviewProtocol } from "./core.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; @@ -10,10 +8,4 @@ export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { void, ]; }; -export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [ - { profiles: ProfileDescription[]; selectedProfileId: string | null }, - void, - ]; - didSelectOrganization: [{ orgId: string | null }, void]; -}; +export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5b2a7ab1f..5dc8d3c3b 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -102,9 +102,4 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; - didChangeControlPlaneSessionInfo: [ - { sessionInfo: ControlPlaneSessionInfo | undefined }, - void, - ]; - didChangeIdeSettings: [{ settings: IdeSettings }, void]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index c6ae172f4..272a6d148 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -20,7 +20,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -60,7 +59,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", - "controlPlane/listOrganizations", ]; // Message types to pass through from core to webview @@ -75,10 +73,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 329f71bdc..d8142a9ed 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,11 +1,14 @@ import { ConfigResult } from "@continuedev/config-yaml"; +import { + OrganizationDescription, + ProfileDescription, +} from "../config/ProfileLifecycleManager.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, ContextProviderName, IndexingProgressUpdate, IndexingStatus, - PackageDocsResult, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -13,6 +16,9 @@ export type ToWebviewFromIdeOrCoreProtocol = { { result: ConfigResult; profileId: string | null; + availableOrgs: OrganizationDescription[]; + selectedOrgId: string | null; + availableOrgProfiles: ProfileDescription[]; }, void, ]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 9d48705df..a443ce9e2 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -152,17 +152,12 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { val connection = ApplicationManager.getApplication().messageBus.connect() connection.subscribe(SettingsListener.TOPIC, object : SettingsListener { override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) { - continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", settings, null) { _ -> } - continuePluginService.sendToWebview( - "didChangeIdeSettings", mapOf( - "settings" to mapOf( - "remoteConfigServerUrl" to settings.remoteConfigServerUrl, - "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, - "userToken" to settings.userToken, - "enableControlServerBeta" to settings.enableContinueTeamsBeta - ) - ) - ) + continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf( + "remoteConfigServerUrl" to settings.remoteConfigServerUrl, + "remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod, + "userToken" to settings.userToken, + "enableControlServerBeta" to settings.enableContinueTeamsBeta + ), null) { _ -> } } }) @@ -236,7 +231,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { "sessionInfo" to initialSessionInfo ) continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } connection.subscribe(AuthListener.TOPIC, object : AuthListener { @@ -253,7 +247,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { data, null ) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index b9546aa63..6168df20c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -65,12 +65,10 @@ class MessageTypes { "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization" ) // Note: If updating these values, make a corresponding update in @@ -87,7 +85,6 @@ class MessageTypes { "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -128,8 +125,6 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", - "controlPlane/listOrganizations" - ) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 268a7674f..7e7aa7a98 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -110,7 +110,7 @@ class IdeProtocolClient( .handleUpdatedSessionInfo(null) // Tell the webview that session info changed - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", null, uuid()) + continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", null, null) { _ -> } respond(null) } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 9441d70cd..6852fd4f4 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -334,14 +334,6 @@ export class VsCodeExtension { ); const sessionInfo = await getControlPlaneSessionInfo(true, false); - this.webviewProtocolPromise.then(async (webviewProtocol) => { - void webviewProtocol.request("didChangeControlPlaneSessionInfo", { - sessionInfo, - }); - - // To make sure continue-proxy models and anything else requiring it get updated access token - this.configHandler.reloadConfig(); - }); void this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo, }); @@ -415,10 +407,7 @@ export class VsCodeExtension { vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings(); - const webviewProtocol = await this.webviewProtocolPromise; - void webviewProtocol.request("didChangeIdeSettings", { - settings, - }); + void this.core.invoke("config/ideSettingsUpdate", settings); } }); } diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 151277c9a..65e87941b 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -9,7 +9,7 @@ import { import { useContext, useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { cycleProfile, selectProfileThunk } from "../../../redux"; +import { setSelectedProfile } from "../../../redux"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { fontSize, @@ -52,7 +52,12 @@ const AssistantSelectOption = ({ const ideMessenger = useContext(IdeMessengerContext); function handleOptionClick() { - dispatch(selectProfileThunk(profile.id)); + // optimistic update + dispatch(setSelectedProfile(profile.id)); + // notify core which will handle actual update + ideMessenger.post("didChangeSelectedProfile", { + id: profile.id, + }); onClick(); } @@ -142,6 +147,9 @@ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); const { selectedProfile, selectedOrganization } = useAuth(); + const availableProfiles = useAppSelector( + (store) => store.profiles.availableProfiles, + ); const ideMessenger = useContext(IdeMessengerContext); const isLumpToolbarExpanded = useAppSelector( (state) => state.ui.isBlockSettingsToolbarExpanded, @@ -176,8 +184,24 @@ export default function AssistantSelect() { const now = Date.now(); if (now - lastToggleTime >= DEBOUNCE_MS) { - dispatch(cycleProfile()); lastToggleTime = now; + + const profileIds = + availableProfiles?.map((profile) => profile.id) ?? []; + // In case of 1 or 0 profiles just does nothing + if (profileIds.length < 2) { + return; + } + let nextId = profileIds[0]; + if (selectedProfile) { + const curIndex = profileIds.indexOf(selectedProfile.id); + const nextIndex = (curIndex + 1) % profileIds.length; + nextId = profileIds[nextIndex]; + } + dispatch(setSelectedProfile(nextId)); + ideMessenger.post("didChangeSelectedProfile", { + id: nextId, + }); } } }; @@ -186,7 +210,7 @@ export default function AssistantSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, []); + }, [availableProfiles, selectedProfile]); const tinyFont = useFontSize(-4); const smallFont = useFontSize(-3); diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index a049e8adc..4b6b68fb8 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -11,11 +11,8 @@ import React, { useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; -import { useWebviewListener } from "../hooks/useWebviewListener"; -import { updateOrgsThunk, updateProfilesThunk } from "../redux"; import { selectSelectedProfile } from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; @@ -100,23 +97,17 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ); }; - useWebviewListener("didChangeControlPlaneSessionInfo", async (data) => { - setSession(data.sessionInfo); - // On logout, clear the list of orgs - if (!data.sessionInfo) { - dispatch(updateOrgsThunk([])); - } - }); - useEffect(() => { - ideMessenger - .request("getControlPlaneSessionInfo", { + async function init() { + const result = await ideMessenger.request("getControlPlaneSessionInfo", { silent: true, useOnboarding: false, - }) - .then( - (result) => result.status === "success" && setSession(result.content), - ); + }); + if (result.status === "success") { + setSession(result.content); + } + } + void init(); }, []); const [controlServerBetaEnabled, setControlServerBetaEnabled] = @@ -127,50 +118,20 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ .getIdeSettings() .then(({ enableControlServerBeta, continueTestEnvironment }) => { setControlServerBetaEnabled(enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(enableControlServerBeta), - ); }); }, []); - useEffect(() => { - if (session) { - ideMessenger - .request("controlPlane/listOrganizations", undefined) - .then((result) => { - if (result.status === "success") { - dispatch(updateOrgsThunk(result.content)); - } else { - dispatch(updateOrgsThunk([])); - } - }); - } - }, [session]); - - useWebviewListener( - "didChangeIdeSettings", - async (msg) => { - const { settings } = msg; - setControlServerBetaEnabled(settings.enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), - ); - }, - [], - ); - - useEffect(() => { - ideMessenger.request("config/listProfiles", undefined).then((result) => { - if (result.status === "success") { - dispatch( - updateProfilesThunk({ - profiles: result.content.profiles, - selectedProfileId: result.content.selectedProfileId, - }), - ); - } - }); - }, []); + // useWebviewListener( + // setControlServerBetaEnabled(settings.enableControlServerBeta); + // "didChangeIdeSettings", + // async (msg) => { + // const { settings } = msg; + // dispatch( + // setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), + // ); + // }, + // [], + // ); const refreshProfiles = async () => { try { @@ -182,19 +143,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ } }; - useWebviewListener( - "didChangeAvailableProfiles", - async (data) => { - dispatch( - updateProfilesThunk({ - profiles: data.profiles, - selectedProfileId: data.selectedProfileId, - }), - ); - }, - [], - ); - return ( ; profileId: string | null; }, ) => { const { result: configResult, profileId } = result; - if (initial && hasLoadedConfig.current) { + if (isInitial && hasDoneInitialConfigLoad.current) { return; } - hasLoadedConfig.current = true; + hasDoneInitialConfigLoad.current = true; dispatch(setConfigResult(configResult)); - dispatch(selectProfileThunk(profileId)); + dispatch(setSelectedProfile(profileId)); const isNewProfileId = profileId && profileId !== selectedProfileId; if (isNewProfileId) { - dispatch(initializeProfilePreferencesThunk({ profileId })); + dispatch( + initializeProfilePreferences({ + defaultSlashCommands: [], + profileId, + }), + ); } // Perform any actions needed with the config @@ -64,28 +69,31 @@ function useSetup() { document.body.style.fontSize = `${configResult.config.ui.fontSize}px`; } }, - [dispatch, hasLoadedConfig], + [dispatch, hasDoneInitialConfigLoad], ); - const loadConfig = useCallback( + const initialLoadAuthAndConfig = useCallback( async (initial: boolean) => { + // const authResult = await ideMessenger.request( + // "auth/getState", + // undefined + // ) const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, ); - if (result.status === "error") { - return; + if (result.status === "success") { + await handleConfigUpdate(initial, result.content); } - await handleConfigUpdate(initial, result.content); }, [ideMessenger, handleConfigUpdate], ); // Load config from the IDE useEffect(() => { - loadConfig(true); + initialLoadAuthAndConfig(true); const interval = setInterval(() => { - if (hasLoadedConfig.current) { + if (hasDoneInitialConfigLoad.current) { // Init to run on initial config load ideMessenger.post("docs/initStatuses", undefined); dispatch(updateFileSymbolsFromHistory()); @@ -93,13 +101,13 @@ function useSetup() { // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); - return; + } else { + initialLoadAuthAndConfig(true); } - loadConfig(true); }, 2_000); return () => clearInterval(interval); - }, [hasLoadedConfig, loadConfig, ideMessenger]); + }, [hasDoneInitialConfigLoad, initialLoadAuthAndConfig, ideMessenger]); useWebviewListener( "configUpdate", @@ -109,7 +117,7 @@ function useSetup() { } await handleConfigUpdate(false, update); }, - [loadConfig], + [handleConfigUpdate], ); // Load symbols for chat on any session change diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 311f78d98..dc92f8048 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -10,7 +10,6 @@ import { ListboxOptions, } from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectOrgThunk } from "../../redux"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -25,10 +24,6 @@ export function ScopeSelect() { dispatch(selectOrgThunk(newValue)); }; - useWebviewListener("didSelectOrganization", async (data) => { - handleChange(data.orgId); - }); - const CurScopeEntityFallBackIcon = selectedOrgId ? BuildingOfficeIcon : UserCircleIcon; diff --git a/gui/src/redux/slices/miscSlice.ts b/gui/src/redux/slices/miscSlice.ts deleted file mode 100644 index c78de5155..000000000 --- a/gui/src/redux/slices/miscSlice.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { PayloadAction, createSlice } from "@reduxjs/toolkit"; -import { PackageDocsResult } from "core"; - -export type MiscState = { - lastControlServerBetaEnabledStatus: boolean; -}; - -const initialState: MiscState = { - lastControlServerBetaEnabledStatus: false, -}; - -export const miscSlice = createSlice({ - name: "misc", - initialState, - reducers: { - setLastControlServerBetaEnabledStatus: ( - state, - action: PayloadAction, - ) => { - state.lastControlServerBetaEnabledStatus = action.payload; - } - }, -}); - -export const { setLastControlServerBetaEnabledStatus } = miscSlice.actions; - -export default miscSlice.reducer; diff --git a/gui/src/redux/slices/organizations/slice.ts b/gui/src/redux/slices/organizations/slice.ts index b662d2435..411519b94 100644 --- a/gui/src/redux/slices/organizations/slice.ts +++ b/gui/src/redux/slices/organizations/slice.ts @@ -21,16 +21,8 @@ export const organizationsSlice = createSlice({ ) => { state.organizations = payload; }, - setSelectedOrganizationId: ( - state, - { payload }: PayloadAction, - ) => { - state.selectedOrganizationId = payload; - }, }, selectors: { - selectOrganizations: (state) => state.organizations, - selectSelectedOrganizationId: (state) => state.selectedOrganizationId, selectSelectedOrganization: (state) => state.organizations.find( (org) => org.id === state.selectedOrganizationId, @@ -38,13 +30,8 @@ export const organizationsSlice = createSlice({ }, }); -export const { setOrganizations, setSelectedOrganizationId } = - organizationsSlice.actions; +export const { setOrganizations } = organizationsSlice.actions; -export const { - selectOrganizations, - selectSelectedOrganizationId, - selectSelectedOrganization, -} = organizationsSlice.selectors; +export const { selectSelectedOrganization } = organizationsSlice.selectors; export const { reducer: organizationsReducer } = organizationsSlice; diff --git a/gui/src/redux/slices/profiles/thunks.ts b/gui/src/redux/slices/profiles/thunks.ts deleted file mode 100644 index 14969157f..000000000 --- a/gui/src/redux/slices/profiles/thunks.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { ProfileDescription } from "core/config/ConfigHandler"; -import { ThunkApiType } from "../../store"; -import { - initializeProfilePreferences, - setAvailableProfiles, - setSelectedProfile, -} from "./slice"; - -export const selectProfileThunk = createAsyncThunk< - void, - string | null, - ThunkApiType ->("profiles/select", async (id, { dispatch, extra, getState }) => { - const state = getState(); - - if (state.profiles.availableProfiles === null) { - // Currently in loading state - return; - } - - const initialId = state.profiles.selectedProfileId; - - let newId = id; - - // If no profiles, force clear - if (state.profiles.availableProfiles.length === 0) { - newId = null; - } else { - // If new id doesn't match an existing profile, clear it - if (newId) { - if (!state.profiles.availableProfiles.find((p) => p.id === newId)) { - newId = null; - } - } - if (!newId) { - // At this point if null ID and there ARE profiles, - // Fallback to a profile, prioritizing the first in the list - newId = state.profiles.availableProfiles[0].id; - } - } - - // Only update if there's a change - if ((newId ?? null) !== (initialId ?? null)) { - dispatch(setSelectedProfile(newId)); - - extra.ideMessenger.post("didChangeSelectedProfile", { - id: newId, - }); - } -}); - -export const cycleProfile = createAsyncThunk( - "profiles/cycle", - async (_, { dispatch, getState }) => { - const state = getState(); - - if (state.profiles.availableProfiles === null) { - return; - } - - const profileIds = state.profiles.availableProfiles.map( - (profile) => profile.id, - ); - // In case of no profiles just does nothing - if (profileIds.length === 0) { - return; - } - let nextId = profileIds[0]; - if (state.profiles.selectedProfileId) { - const curIndex = profileIds.indexOf(state.profiles.selectedProfileId); - const nextIndex = (curIndex + 1) % profileIds.length; - nextId = profileIds[nextIndex]; - } - await dispatch(selectProfileThunk(nextId)); - }, -); - -export const updateProfilesThunk = createAsyncThunk< - void, - { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, - ThunkApiType ->("profiles/update", async (data, { dispatch, extra, getState }) => { - const { profiles, selectedProfileId } = data; - - dispatch(setAvailableProfiles(profiles)); - - // This will trigger reselection if needed - dispatch(selectProfileThunk(selectedProfileId)); -}); - -export const initializeProfilePreferencesThunk = createAsyncThunk< - void, - { profileId: string }, - ThunkApiType ->( - "profiles/initializeProfilePreferences", - async (data, { getState, dispatch }) => { - const { profileId } = data; - - dispatch( - initializeProfilePreferences({ - defaultSlashCommands: [], - profileId, - }), - ); - }, -); diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index 8aff8e1de..0113c1b77 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -14,7 +14,6 @@ import { organizationsReducer, profilesReducer } from "./slices"; import configReducer from "./slices/configSlice"; import editModeStateReducer from "./slices/editModeState"; import indexingReducer from "./slices/indexingSlice"; -import miscReducer from "./slices/miscSlice"; import sessionReducer from "./slices/sessionSlice"; import tabsReducer from "./slices/tabsSlice"; import uiReducer from "./slices/uiSlice"; @@ -26,7 +25,6 @@ export interface ChatMessage { const rootReducer = combineReducers({ session: sessionReducer, - misc: miscReducer, ui: uiReducer, editModeState: editModeStateReducer, config: configReducer, @@ -47,10 +45,6 @@ const saveSubsetFilters = [ "mode", "codeToEdit", - // TODO consider removing persisted profiles/orgs - "availableProfiles", - "organizations", - // higher risk to persist // codeBlockApplyStates // symbols From 931ee37e9f1131331eb4e32aaa567f6e01aab8e1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 2 Apr 2025 12:55:20 -0700 Subject: [PATCH 02/57] cascading config p2 --- core/config/ConfigHandler.ts | 442 ++++++++++-------- .../providers/_context-providers.test.ts | 1 - core/core.ts | 14 +- 3 files changed, 256 insertions(+), 201 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index f3405a668..cdb03d93b 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -34,28 +34,23 @@ export type { ProfileDescription }; type ConfigUpdateFunction = (payload: ConfigResult) => void; -// Separately manages saving/reloading each profile +type OrgWithProfiles = OrganizationDescription & { + profiles: ProfileLifecycleManager[]; + currentProfile: ProfileLifecycleManager | null; +}; + +// Continue for Teams: show local + assistants in single org +// Continue Hub: show personal org with local and personal assistants +// Not signed in: show local and personal assistants export class ConfigHandler { - private readonly globalContext = new GlobalContext(); - private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[] = []; - private globalLocalProfileManager: ProfileLifecycleManager; - currentProfile: ProfileLifecycleManager | null = null; - private currentProfileId: string | null = null; controlPlaneClient: ControlPlaneClient; - _selectedOrgId: string | null = null; - _organizations: OrganizationDescription[] = []; + private readonly globalContext = new GlobalContext(); + private globalLocalProfileManager: ProfileLifecycleManager; - get organizations() { - return this._organizations; - } - - get selectedOrgId() { - return this._selectedOrgId; - } - - initializedPromise: Promise; + private organizations: OrgWithProfiles[] = []; + currentProfile: ProfileLifecycleManager; + currentOrg: OrgWithProfiles | null = null; constructor( private readonly ide: IDE, @@ -71,71 +66,37 @@ export class ConfigHandler { ideSettingsPromise, ); - // Set local profile as default - const localProfileLoader = new LocalProfileLoader( - ide, - ideSettingsPromise, - this.controlPlaneClient, - writeLog, - ); + // This profile manager will always be available this.globalLocalProfileManager = new ProfileLifecycleManager( - localProfileLoader, + new LocalProfileLoader( + ide, + ideSettingsPromise, + this.controlPlaneClient, + writeLog, + ), this.ide, ); - // Profiles are loaded asynchronously - this.initializedPromise = new Promise((resolve, reject) => { - this.init() - .then(() => { - resolve(); - }) - .catch((e) => { - reject(e); - }); - }); + // Just to be safe, always force a selected profile + this.currentProfile = this.globalLocalProfileManager; + this.personalOrg = { + currentProfile: this.globalLocalProfileManager, + }; + this.organizations = [this.personalOrg]; + + void this.cascadeInit(); } - /** - * Users can define as many local assistants as they want in a `.continue/assistants` folder - */ - private async getLocalAssistantProfiles() { - const assistantFiles = await getAllAssistantFiles(this.ide); - const profiles = assistantFiles.map((assistant) => { - return new LocalProfileLoader( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.writeLog, - assistant, - ); - }); - return profiles.map( - (profile) => new ProfileLifecycleManager(profile, this.ide), - ); - } - - /** - * Retrieves the titles of additional context providers that are of type "submenu". - * - * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu". - */ - getAdditionalSubmenuContextProviders(): string[] { - return this.additionalContextProviders - .filter((provider) => provider.description.type === "submenu") - .map((provider) => provider.description.title); - } - - private async init() { - await this.fetchControlPlaneProfiles(); - - try { - const configResult = await this.loadConfig(); - this.notifyConfigListeners(configResult); - } catch (e) { - console.error("Failed to load config: ", e); + private workspaceDirs: string[] | null = null; + async workspaceId() { + if (!this.workspaceDirs) { + this.workspaceDirs = await this.ide.getWorkspaceDirs(); } + return this.workspaceDirs.join("&"); } + private PERSONAL_ORG_ID = "personal"; + async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.currentProfileId; const profile = this.profiles?.find( @@ -149,17 +110,68 @@ export class ConfigHandler { } } - private async cascadeConfigRefresh({ - refetchOrgs, - }: { - refetchOrgs: boolean; - refetchProfiles: boolean; - }) { - async function getWorkspaceId(): Promise { - const orgPart = (await this.getSelectedOrgId()) ?? "personal"; - const dirs = await this.ide.getWorkspaceDirs(); - return `${dirs.join("&")}:::${orgPart}`; - } + // Loads orgs + // Loads all profiles for all orgs + // Gets/infers selected org + // Cascades org selection + private async cascadeInit() { + this.workspaceDirs = null; // forces workspace dirs reload + + const userId = await this.controlPlaneClient.userId; + + const orgs = this.controlPlaneClient.listOrganizations(); + } + + // Refresh cascades: org -> profiles -> config + private async cascadeRefreshOrgs() { + // loads orgs + // gets last selected org from context + // checks if valid + // if valid sets selected org + // if not valid defaults to hub org or personal if no hub and saves fallback in context + // cascade refreshes profiles for all orgs + await this.cascadeRefreshProfilesForAllOrgs(); + // const selectedOrgs = + // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + // selectedOrgs[await this.getWorkspaceId()] = orgId; + // this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + } + + private async cascadeRefreshProfilesForAllOrgs() { + await Promise.all( + this.organizations.map((org) => + this.cascadeRefreshProfilesForOrg(org.id), + ), + ); + } + + private async cascadeRefreshProfilesForOrg(orgId: string | null) { + // personal org: local profiles + personal hub if signed in + // + const workspaceId = await this.workspaceId(); + const contextKey = `${workspaceId}:::${orgId ?? this.PERSONAL_ORG_ID}`; + + // loads assistants + // gets last selected profile from context (by org id/workspace id combo) + // checks if valid + // if valid sets selected profile + // if not valid defaults to hub/teams profiles otherwise local, and and saves fallback in context + // reloads config for selected profile + + await this.reloadConfig(); + } + + // Selection cascades: org -> profiles -> config + private async cascadeSelectOrg() {} + + /* + This rectifies selected ids to make sure no invalid state is reached + And walks through the config profile tree logic + Should be the default whenever a refresh is needed + */ + private async cascadeConfigRefresh() { + let resolvedOrgId = this._selectedOrgId; + let resolvedProfileId = this.currentProfileId; // private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { // this.profiles = profiles; @@ -188,16 +200,10 @@ export class ConfigHandler { // await this.setSelectedProfile(selectedProfileId); // } - // if (config) { - // this.inactiveProfiles.forEach((profile) => profile.clearConfig()); - // return (this.profiles ?? []).filter( - // (p) => p.profileDescription.id !== this.selectedProfileId, - // ); - // } - // SET SELECTED PROFILE ID const result = await this.loadConfig(); this.notifyConfigListeners(result); + const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; selectedProfiles[await getWorkspaceId()] = profileId; @@ -222,39 +228,76 @@ export class ConfigHandler { // } // async setSelectedOrgId(orgId: string | null) { - // const selectedOrgs = - // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - // selectedOrgs[await this.getWorkspaceId()] = orgId; - // this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + // } } + // Initialization: + + ////////////////// + // External actions that can cause a cascading config refresh + // Should not be used internally + ////////////////// + + // Ide settings change: refresh session and cascade refresh from the top + async updateIdeSettings(ideSettings: IdeSettings) { + this.ideSettingsPromise = Promise.resolve(ideSettings); + await this.cascadeInit(); + } + + // Session change: refresh session and cascade refresh from the top + async updateControlPlaneSessionInfo( + sessionInfo: ControlPlaneSessionInfo | undefined, + ) { + this.controlPlaneClient = new ControlPlaneClient( + Promise.resolve(sessionInfo), + this.ideSettingsPromise, + ); + await this.cascadeInit(); + } + + // Org id: check id validity, cascade org selection async setSelectedOrgId(orgId: string | null) { - this._selectedOrgId = orgId; - await this.cascadeConfigRefresh(); + if (orgId === (this.currentOrg?.id ?? null)) { + return; + } + if (orgId) { + const org = this.organizations.find((org) => org.id === orgId); + if (!org) { + throw new Error(`Org ${orgId} not found`); + } + } + + await this.cascadeSelectOrg(orgId); } - async setSelectedProfile(profileId: string | null) { - this.currentProfile = profileId; - await this.cascadeConfigRefresh(); + async setSelectedProfileId(profileId: string | null) { + if (profileId === (this.currentProfile?.profileDescription.id ?? null)) { + return; + } + if (orgId) { + const profile = this._organizations.find((org) => org.id === orgId); + if (!profile) { + throw new Error(`Profile ${profileId} not found in current org`); + } + } + // if (config) { + // this.inactiveProfiles.forEach((profile) => profile.clearConfig()); + // return (this.profiles ?? []).filter( + // (p) => p.profileDescription.id !== this.selectedProfileId, + // ); + // } + await this.cascadeP(orgId); } - async loadAssistantsForSelectedOrg() { - // Get the profiles and create their lifecycle managers - const userId = await this.controlPlaneClient.userId; - const selectedOrgId = await this.getSelectedOrgId(); + async getControlPlaneAssistantsForOrg( + orgId: string, + ): Promise { + if (await useHub(this.ideSettingsPromise)) { + // Hub: only show org assistants within org + const assistants = await this.controlPlaneClient.listAssistants(orgId); - let profiles: ProfileLifecycleManager[] | null = null; - if (!userId) { - // Not logged in - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...allLocalProfiles]; - } else { - // Logged in - const assistants = - await this.controlPlaneClient.listAssistants(selectedOrgId); - - const hubProfiles = await Promise.all( + return await Promise.all( assistants.map(async (assistant) => { const profileLoader = await PlatformProfileLoader.create( { @@ -270,12 +313,66 @@ export class ConfigHandler { this.ideSettingsPromise, this.writeLog, assistant.rawYaml, - selectedOrgId, + orgId, ); return new ProfileLifecycleManager(profileLoader, this.ide); }), ); + } else { + // Continue for teams: show local and teams profiles + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = await this.getAllLocalProfiles(); + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); + + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + }); + return profiles; + } + } + + async getAllLocalProfiles() { + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant, + ); + }); + const localAssistantProfiles = profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + return [this.globalLocalProfileManager, ...localAssistantProfiles]; + } + + async refreshAllAssistants(orgId: string | null) { + // Get the profiles and create their lifecycle managers + + const userId = await this.controlPlaneClient.userId; + const selectedOrgId = await this.getSelectedOrgId(); + + let profiles: ProfileLifecycleManager[] | null = null; + if (!userId) { + // Not logged in + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...allLocalProfiles]; + } else { + // Logged in if (selectedOrgId === null) { // Personal @@ -288,75 +385,15 @@ export class ConfigHandler { } this.profiles = profiles; - await this.cascadeConfigRefresh(); + await this.cascadeSelectOrg(orgId); } - private async getAllLocalProfiles() { - const localAssistantProfiles = await this.getLocalAssistantProfiles(); - return [this.globalLocalProfileManager, ...localAssistantProfiles]; - } + async cascadeSelectProfile(id: string) {} - private async fetchControlPlaneProfiles() { - try { - if (await useHub(this.ideSettingsPromise)) { - await this.loadAssistantsForSelectedOrg(); - } else { - const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); - }); - this.profiles = profiles; - } - } catch (e) { - console.error("Failed to load profiles: ", e); - this.profiles = await this.getAllLocalProfiles(); - } finally { - await this.cascadeConfigRefresh(); - } - } - - // Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed - updateIdeSettings(ideSettings: IdeSettings) { - this.ideSettingsPromise = Promise.resolve(ideSettings); - void this.cascadeConfigRefresh(); - } - - async updateControlPlaneSessionInfo( - sessionInfo: ControlPlaneSessionInfo | undefined, - ) { - this.controlPlaneClient = new ControlPlaneClient( - Promise.resolve(sessionInfo), - this.ideSettingsPromise, - ); - - await this.fetchControlPlaneProfiles(); - } - - private notifyConfigListeners(result: ConfigResult) { - // Notify listeners that config changed - for (const listener of this.updateListeners) { - listener(result); - } - } - - private updateListeners: ConfigUpdateFunction[] = []; - - onConfigUpdate(listener: ConfigUpdateFunction) { - this.updateListeners.push(listener); - } - - // TODO: this isn't right, there are two different senses in which you want to "reload" + // Bottom level of cascade: refresh the current profile + // IMPORTANT - must always refresh when switching profiles + // Because of e.g. MCP singleton and docs service using things from config + // Could improve this async reloadConfig() { if (!this.currentProfile) { return { @@ -369,12 +406,26 @@ export class ConfigHandler { const { config, errors, configLoadInterrupted } = await this.currentProfile.reloadConfig(this.additionalContextProviders); - await this.cascadeConfigRefresh(); - this.notifyConfigListeners({ config, errors, configLoadInterrupted }); return { config, errors, configLoadInterrupted }; } + // Listeners setup - can listen to current profile updates + private notifyConfigListeners(result: ConfigResult) { + for (const listener of this.updateListeners) { + listener(result); + } + } + + private updateListeners: ConfigUpdateFunction[] = []; + + onConfigUpdate(listener: ConfigUpdateFunction) { + this.updateListeners.push(listener); + } + + // Methods for loading (without reloading) config + // Serialized for passing to GUI + // Load for just awaiting current config load promise for the profile async getSerializedConfig(): Promise< ConfigResult > { @@ -390,10 +441,6 @@ export class ConfigHandler { ); } - listProfileDescriptions(): ProfileDescription[] { - return this.profiles?.map((p) => p.profileDescription) ?? []; - } - async loadConfig(): Promise> { if (!this.currentProfile) { return { @@ -407,6 +454,7 @@ export class ConfigHandler { ); } + // Only used till we move to using selectedModelByRole.chat async llmFromTitle(title?: string): Promise { const { config } = await this.loadConfig(); const model = config?.models.find((m) => m.title === title); @@ -427,8 +475,24 @@ export class ConfigHandler { return model; } + // Ancient method of adding custom providers through vs code + private additionalContextProviders: IContextProvider[] = []; registerCustomContextProvider(contextProvider: IContextProvider) { this.additionalContextProviders.push(contextProvider); void this.reloadConfig(); } + /** + * Retrieves the titles of additional context providers that are of type "submenu". + * + * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu". + */ + getAdditionalSubmenuContextProviders(): string[] { + return this.additionalContextProviders + .filter((provider) => provider.description.type === "submenu") + .map((provider) => provider.description.title); + } } + +// listProfileDescriptions(): ProfileDescription[] { +// return this.profiles?.map((p) => p.profileDescription) ?? []; +// } diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 345d21e37..21f436b75 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -32,7 +32,6 @@ async function getContextProviderExtras( async (text) => {}, Promise.resolve(undefined), ); - await configHandler.initializedPromise; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); diff --git a/core/core.ts b/core/core.ts index 574fa099c..9ff5c9d08 100644 --- a/core/core.ts +++ b/core/core.ts @@ -297,7 +297,7 @@ export class Core { }); on("config/refreshProfiles", async (msg) => { - await this.configHandler.loadAssistantsForSelectedOrg(); + await this.configHandler.refreshAssistantsForSelectedOrg(); }); on("config/updateSharedConfig", async (msg) => { @@ -754,7 +754,7 @@ export class Core { // If it's a local assistant being created, we want to reload all assistants so it shows up in the list for (const uri of data.uris) { if (isLocalAssistantFile(uri)) { - await this.configHandler.loadAssistantsForSelectedOrg(); + await this.configHandler.refreshAssistantsForSelectedOrg(); } } } @@ -807,19 +807,10 @@ export class Core { on("didChangeSelectedProfile", async (msg) => { await this.configHandler.setSelectedProfileId(msg.data.id); - await this.configHandler.reloadConfig(); }); on("didChangeSelectedOrg", async (msg) => { await this.configHandler.setSelectedOrgId(msg.data.id); - await this.configHandler.loadAssistantsForSelectedOrg(); - if (msg.data.profileId) { - this.invoke("didChangeSelectedProfile", { - id: msg.data.profileId, - }); - } else { - await this.configHandler.reloadConfig(); - } }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -827,6 +818,7 @@ export class Core { msg.data.sessionInfo, ); }); + on("auth/getAuthUrl", async (msg) => { const url = await getAuthUrlForTokenPage( ideSettingsPromise, From c5e002b47520a99cf3e6582471a6dbc5736cb7a0 Mon Sep 17 00:00:00 2001 From: Diwakar Date: Fri, 4 Apr 2025 16:10:49 +0700 Subject: [PATCH 03/57] Update YAML reference docs with fix for useLegacyCompletionsEndpoint --- docs/docs/reference.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 735c89be3..757cfa13e 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -474,7 +474,8 @@ models: - name: qwen2.5-coder-7b <<: *model_defaults model: qwen2.5-coder-7b - useLegacyCompletionsEndpoint: false + env: + useLegacyCompletionsEndpoint: false roles: - autocomplete ``` From 048eaf803eb5a0ecbf046faa9b0c2cc2b9682c22 Mon Sep 17 00:00:00 2001 From: "T. Todua" <7117978+ttodua@users.noreply.github.com> Date: Fri, 4 Apr 2025 17:00:10 +0400 Subject: [PATCH 04/57] doc(ui) - support for array as noted here: https://github.com/continuedev/continue/issues/892#issuecomment-2178910959 it's now supported --- .../customize/tutorials/set-up-codestral.mdx | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/docs/customize/tutorials/set-up-codestral.mdx b/docs/docs/customize/tutorials/set-up-codestral.mdx index 97ec3c981..1ace12f2f 100644 --- a/docs/docs/customize/tutorials/set-up-codestral.mdx +++ b/docs/docs/customize/tutorials/set-up-codestral.mdx @@ -45,13 +45,15 @@ import TabItem from "@theme/TabItem"; "apiBase": "https://codestral.mistral.ai/v1" } ], - "tabAutocompleteModel": { - "title": "Codestral", - "provider": "mistral", - "model": "codestral-latest", - "apiKey": "", - "apiBase": "https://codestral.mistral.ai/v1" - } + "tabAutocompleteModel": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "", + "apiBase": "https://codestral.mistral.ai/v1" + } + ] } ``` From be22741fc0fa0c564b314aa74565bc3c16a00359 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 10:06:53 -0700 Subject: [PATCH 05/57] continued --- core/config/ConfigHandler.ts | 472 ++++++++++++++++------------------- core/protocol/coreWebview.ts | 7 +- 2 files changed, 223 insertions(+), 256 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index cdb03d93b..5753e4d33 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -39,9 +39,8 @@ type OrgWithProfiles = OrganizationDescription & { currentProfile: ProfileLifecycleManager | null; }; -// Continue for Teams: show local + assistants in single org -// Continue Hub: show personal org with local and personal assistants -// Not signed in: show local and personal assistants +const PERSONAL_ORG_ID = "personal"; +const LOCAL_ORG_ID = "local"; export class ConfigHandler { controlPlaneClient: ControlPlaneClient; @@ -49,8 +48,8 @@ export class ConfigHandler { private globalLocalProfileManager: ProfileLifecycleManager; private organizations: OrgWithProfiles[] = []; - currentProfile: ProfileLifecycleManager; - currentOrg: OrgWithProfiles | null = null; + currentProfile: ProfileLifecycleManager | null; + currentOrg: OrgWithProfiles; constructor( private readonly ide: IDE, @@ -77,37 +76,34 @@ export class ConfigHandler { this.ide, ); - // Just to be safe, always force a selected profile + // Just to be safe, always force a default personal org with local profile manager this.currentProfile = this.globalLocalProfileManager; - this.personalOrg = { + const personalOrg: OrgWithProfiles = { currentProfile: this.globalLocalProfileManager, + profiles: [this.globalLocalProfileManager], + name: "Personal", + id: PERSONAL_ORG_ID, + iconUrl: "", + slug: undefined, }; - this.organizations = [this.personalOrg]; + + this.currentOrg = personalOrg; + this.organizations = [personalOrg]; void this.cascadeInit(); } private workspaceDirs: string[] | null = null; - async workspaceId() { + async getWorkspaceId() { if (!this.workspaceDirs) { this.workspaceDirs = await this.ide.getWorkspaceDirs(); } return this.workspaceDirs.join("&"); } - private PERSONAL_ORG_ID = "personal"; - - async openConfigProfile(profileId?: string) { - let openProfileId = profileId || this.currentProfileId; - const profile = this.profiles?.find( - (p) => p.profileDescription.id === openProfileId, - ); - if (profile?.profileDescription.profileType === "local") { - await this.ide.openFile(profile.profileDescription.uri); - } else { - const env = await getControlPlaneEnv(this.ide.getIdeSettings()); - await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); - } + async getProfileKey(orgId: string) { + const workspaceId = await this.getWorkspaceId(); + return `${workspaceId}:::${orgId}`; } // Loads orgs @@ -117,227 +113,133 @@ export class ConfigHandler { private async cascadeInit() { this.workspaceDirs = null; // forces workspace dirs reload - const userId = await this.controlPlaneClient.userId; + const orgs = await this.getOrgs(); - const orgs = this.controlPlaneClient.listOrganizations(); + // this.currentProfile = profile + + // const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + // const profileKey = `${workspaceId}:::${org.id}` + // const selectedProfileId = selectedProfiles[profileKey]; + // const profile = selectedProfileId ? org.profiles.find(profile => profile.profileDescription.id === selectedProfileId) : + // if(!selectedProfile) { + // // + // } + } + + private async getOrgs(): Promise { + let orgs: OrgWithProfiles[]; + const userId = await this.controlPlaneClient.userId; + if (userId) { + if (await useHub(this.ideSettingsPromise)) { + const orgDescs = await this.controlPlaneClient.listOrganizations(); + // const personalOrg = + const hubOrgs = await Promise.all( + orgDescs.map((org) => this.makeNonPersonalHubOrg(org)), + ); + // profiles = [...hubProfiles, ...allLocalProfiles]; + orgs = hubOrgs; + } else { + const teamsOrg = await this.getTeamsOrg(); + orgs = [teamsOrg]; + } + } else { + const localOrg = await this.getLocalOrg(); + orgs = [localOrg]; + } + return orgs; + } + + private async getHubOrg( + org: OrganizationDescription, + orgScopeId: string | null, + ): Promise { + const assistants = await this.controlPlaneClient.listAssistants(orgScopeId); + + const profiles = await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + assistant.rawYaml, + orgScopeId, + ); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); + + return this.rectifyProfilesForOrg(org, profiles); } // Refresh cascades: org -> profiles -> config - private async cascadeRefreshOrgs() { + private async makePersonalHubOrg() { // loads orgs // gets last selected org from context // checks if valid // if valid sets selected org // if not valid defaults to hub org or personal if no hub and saves fallback in context // cascade refreshes profiles for all orgs - await this.cascadeRefreshProfilesForAllOrgs(); - // const selectedOrgs = - // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - // selectedOrgs[await this.getWorkspaceId()] = orgId; - // this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs); + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; + return await this.getHubOrg(); } - private async cascadeRefreshProfilesForAllOrgs() { - await Promise.all( - this.organizations.map((org) => - this.cascadeRefreshProfilesForOrg(org.id), - ), - ); + private async makeNonPersonalHubOrg(): OrgWithProfiles { + profiles = hubProfiles; + return await this.getHubOrg(); } - private async cascadeRefreshProfilesForOrg(orgId: string | null) { - // personal org: local profiles + personal hub if signed in - // - const workspaceId = await this.workspaceId(); - const contextKey = `${workspaceId}:::${orgId ?? this.PERSONAL_ORG_ID}`; - - // loads assistants - // gets last selected profile from context (by org id/workspace id combo) - // checks if valid - // if valid sets selected profile - // if not valid defaults to hub/teams profiles otherwise local, and and saves fallback in context - // reloads config for selected profile - - await this.reloadConfig(); + private async getLocalOrg() { + const allLocalProfiles = await this.getAllLocalProfiles(); + return this.rectifyProfilesForOrg(org, allLocalProfiles); } - // Selection cascades: org -> profiles -> config - private async cascadeSelectOrg() {} + async getTeamsOrg(org: OrganizationDescription): Promise { + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = await this.getAllLocalProfiles(); + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - /* - This rectifies selected ids to make sure no invalid state is reached - And walks through the config profile tree logic - Should be the default whenever a refresh is needed - */ - private async cascadeConfigRefresh() { - let resolvedOrgId = this._selectedOrgId; - let resolvedProfileId = this.currentProfileId; - - // private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { - // this.profiles = profiles; - - // // If the last selected profile is in the list choose that - // // Otherwise, choose the first profile - // const previouslySelectedProfileId = - // await this.getPersistedSelectedProfileId(); - - // // Check if the previously selected profile exists in the current profiles - // const profileExists = profiles.some( - // (profile) => - // profile.profileDescription.id === previouslySelectedProfileId, - // ); - - // const selectedProfileId = profileExists - // ? previouslySelectedProfileId - // : (profiles[0]?.profileDescription.id ?? null); - - // // Notify listeners - // const profileDescriptions = profiles.map( - // (profile) => profile.profileDescription, - // ); - // this.notifyConfigListeners(); - // this.notifyProfileListeners(profileDescriptions, selectedProfileId); - // await this.setSelectedProfile(selectedProfileId); - // } - - // SET SELECTED PROFILE ID - const result = await this.loadConfig(); - this.notifyConfigListeners(result); + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + }); + return rectifyProfilesForOrg({}, profiles); + } + private async rectifyProfilesForOrg( + org: OrganizationDescription, + profiles: ProfileLifecycleManager[], + ): OrgWithProfiles { + const profileKey = await this.getProfileKey(org.id); const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - selectedProfiles[await getWorkspaceId()] = profileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - selectedProfiles, - ); + const selectedProfile = selectedProfiles[profileKey]; - // OTHER CASCADE STUFF - // async getPersistedSelectedProfileId(): Promise { - // const workspaceId = await this.getWorkspaceId(); - // const lastSelectedIds = - // this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - // return lastSelectedIds[workspaceId] ?? null; - // } - - // async getSelectedOrgId(): Promise { - // const selectedOrgs = - // this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; - // const workspaceId = await this.getWorkspaceId(); - // return selectedOrgs[workspaceId] ?? null; - // } - - // async setSelectedOrgId(orgId: string | null) { - - // } - } - - // Initialization: - - ////////////////// - // External actions that can cause a cascading config refresh - // Should not be used internally - ////////////////// - - // Ide settings change: refresh session and cascade refresh from the top - async updateIdeSettings(ideSettings: IdeSettings) { - this.ideSettingsPromise = Promise.resolve(ideSettings); - await this.cascadeInit(); - } - - // Session change: refresh session and cascade refresh from the top - async updateControlPlaneSessionInfo( - sessionInfo: ControlPlaneSessionInfo | undefined, - ) { - this.controlPlaneClient = new ControlPlaneClient( - Promise.resolve(sessionInfo), - this.ideSettingsPromise, - ); - await this.cascadeInit(); - } - - // Org id: check id validity, cascade org selection - async setSelectedOrgId(orgId: string | null) { - if (orgId === (this.currentOrg?.id ?? null)) { - return; - } - if (orgId) { - const org = this.organizations.find((org) => org.id === orgId); - if (!org) { - throw new Error(`Org ${orgId} not found`); - } - } - - await this.cascadeSelectOrg(orgId); - } - - async setSelectedProfileId(profileId: string | null) { - if (profileId === (this.currentProfile?.profileDescription.id ?? null)) { - return; - } - if (orgId) { - const profile = this._organizations.find((org) => org.id === orgId); - if (!profile) { - throw new Error(`Profile ${profileId} not found in current org`); - } - } - // if (config) { - // this.inactiveProfiles.forEach((profile) => profile.clearConfig()); - // return (this.profiles ?? []).filter( - // (p) => p.profileDescription.id !== this.selectedProfileId, - // ); - // } - await this.cascadeP(orgId); - } - - async getControlPlaneAssistantsForOrg( - orgId: string, - ): Promise { - if (await useHub(this.ideSettingsPromise)) { - // Hub: only show org assistants within org - const assistants = await this.controlPlaneClient.listAssistants(orgId); - - return await Promise.all( - assistants.map(async (assistant) => { - const profileLoader = await PlatformProfileLoader.create( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - assistant.rawYaml, - orgId, - ); - - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); + if (!selectedProfile) { } else { - // Continue for teams: show local and teams profiles - const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); - }); - return profiles; } + + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: profileId, + }); } async getAllLocalProfiles() { @@ -360,35 +262,80 @@ export class ConfigHandler { return [this.globalLocalProfileManager, ...localAssistantProfiles]; } - async refreshAllAssistants(orgId: string | null) { - // Get the profiles and create their lifecycle managers - - const userId = await this.controlPlaneClient.userId; - const selectedOrgId = await this.getSelectedOrgId(); - - let profiles: ProfileLifecycleManager[] | null = null; - if (!userId) { - // Not logged in - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...allLocalProfiles]; - } else { - // Logged in - - if (selectedOrgId === null) { - // Personal - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...hubProfiles, ...allLocalProfiles]; - } else { - // Organization - profiles = hubProfiles; - } - } - - this.profiles = profiles; - await this.cascadeSelectOrg(orgId); + ////////////////// + // External actions that can cause a cascading config refresh + // Should not be used internally + ////////////////// + async refreshAll() { + await this.cascadeInit(); } - async cascadeSelectProfile(id: string) {} + // Ide settings change: refresh session and cascade refresh from the top + async updateIdeSettings(ideSettings: IdeSettings) { + this.ideSettingsPromise = Promise.resolve(ideSettings); + await this.cascadeInit(); + } + + // Session change: refresh session and cascade refresh from the top + async updateControlPlaneSessionInfo( + sessionInfo: ControlPlaneSessionInfo | undefined, + ) { + this.controlPlaneClient = new ControlPlaneClient( + Promise.resolve(sessionInfo), + this.ideSettingsPromise, + ); + await this.cascadeInit(); + } + + // Org id: check id validity, save selection, switch and reload + async setSelectedOrgId(orgId: string) { + if (orgId === this.currentOrg.id) { + return; + } + const org = this.organizations.find((org) => org.id === orgId); + if (!org) { + throw new Error(`Org ${orgId} not found`); + } + + const workspaceId = await this.getWorkspaceId(); + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + this.globalContext.update("lastSelectedOrgIdForWorkspace", { + ...selectedOrgs, + [workspaceId]: org.id, + }); + + this.currentOrg = org; + this.currentProfile = org.currentProfile; + await this.reloadConfig(); + } + + // Profile id: check id validity, save selection, switch and reload + async setSelectedProfileId(profileId: string) { + if ( + this.currentProfile && + profileId === this.currentProfile.profileDescription.id + ) { + return; + } + const profile = this.currentOrg.profiles.find( + (profile) => profile.profileDescription.id === profileId, + ); + if (!profile) { + throw new Error(`Profile ${profileId} not found in current org`); + } + + const profileKey = await this.getProfileKey(this.currentOrg.id); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: profileId, + }); + + this.currentProfile = profile; + await this.reloadConfig(); + } // Bottom level of cascade: refresh the current profile // IMPORTANT - must always refresh when switching profiles @@ -403,6 +350,17 @@ export class ConfigHandler { }; } + for (const org of this.organizations) { + for (const profile of org.profiles) { + if ( + profile.profileDescription.id !== + this.currentProfile.profileDescription.id + ) { + profile.clearConfig(); + } + } + } + const { config, errors, configLoadInterrupted } = await this.currentProfile.reloadConfig(this.additionalContextProviders); @@ -454,6 +412,22 @@ export class ConfigHandler { ); } + async openConfigProfile(profileId?: string) { + let openProfileId = profileId || this.currentProfile?.profileDescription.id; + if (!openProfileId) { + return; + } + const profile = this.currentOrg.profiles.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { + await this.ide.openFile(profile.profileDescription.uri); + } else { + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); + } + } + // Only used till we move to using selectedModelByRole.chat async llmFromTitle(title?: string): Promise { const { config } = await this.loadConfig(); @@ -492,7 +466,3 @@ export class ConfigHandler { .map((provider) => provider.description.title); } } - -// listProfileDescriptions(): ProfileDescription[] { -// return this.profiles?.map((p) => p.profileDescription) ?? []; -// } diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 292682f8a..c3c5b7fc3 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -2,10 +2,7 @@ import { ToCoreFromIdeOrWebviewProtocol } from "./core.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { - didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [ - { id: string | null; profileId?: string | null }, - void, - ]; + didChangeSelectedProfile: [{ id: string }, void]; + didChangeSelectedOrg: [{ id: string }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol; From a8cd20832a21931f1dd356d1da047b7a3804b7f3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Sat, 5 Apr 2025 11:32:23 +0530 Subject: [PATCH 06/57] fix pr_checks.yaml linting comment out the empty lists in yaml --- .github/workflows/pr_checks.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index bf8ce2ecb..1dd652de9 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -632,6 +632,6 @@ jobs: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: - allowed-failures: - allowed-skips: + # allowed-failures: + # allowed-skips: jobs: ${{ toJSON(needs) }} From 47caa2e43b25f48d14100bd2c2bed566d238ae43 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:23:16 -0700 Subject: [PATCH 07/57] make a draft main release every friday --- .github/workflows/vscode-version-bump.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index 39dc5b7f1..4c9ebf1a2 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -15,6 +15,10 @@ jobs: with: fetch-depth: 0 # Fetch all history and tags + - name: Setup GitHub CLI + run: | + gh auth login --with-token <<< "${{ github.token }}" + - name: Use Node.js from .nvmrc uses: actions/setup-node@v4 with: @@ -97,6 +101,15 @@ jobs: echo "Pushing branch to origin..." git push origin $NEW_BRANCH + # Add release creation + echo "Creating draft release..." + gh release create "${NEW_BRANCH}" \ + --title "${NEW_BRANCH}" \ + --generate-notes \ + --draft \ + --latest \ + --notes-start-tag "${LAST_1_0_TAG}" + echo "Version bump process completed successfully!" - name: Check for errors From 290b7e0b84f62a6debf9f161a6e92ea7af80e34b Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:24:13 -0700 Subject: [PATCH 08/57] fix grep error --- .github/workflows/auto-release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 5985624de..c1e8c8e3d 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -20,7 +20,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" | head -n 1 || echo "v1.1.0-vscode") + latest_tag=$(git tag --sort=-creatordate | grep "-vscode$" || echo "v1.1.0-vscode") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV @@ -66,7 +66,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" | head -n 1 || echo "v1.1.0-jetbrains") + latest_tag=$(git tag --sort=-creatordate | grep "-jetbrains$" || echo "v1.1.0-jetbrains") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV From 03279380e40fe0da9916aa663b6a94e33f600cb9 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:24:49 -0700 Subject: [PATCH 09/57] run on push for testing --- .github/workflows/auto-release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index c1e8c8e3d..bab22f2f5 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -1,6 +1,9 @@ name: Create Automatic Release on: + push: + branches: + - nate/auto-main-release-draft schedule: - cron: "0 17 * * 1,3,5" # Run at 9am PST (17:00 UTC) on Monday, Wednesday, Friday workflow_dispatch: # Keep manual trigger option From 46cbbee7b007c4361cfa6c407d29cde2e51e5454 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:27:06 -0700 Subject: [PATCH 10/57] fix? --- .github/workflows/auto-release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index bab22f2f5..3c7182ec3 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -23,7 +23,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep "-vscode$" || echo "v1.1.0-vscode") + latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" || echo "v1.1.0-vscode") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV @@ -69,7 +69,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep "-jetbrains$" || echo "v1.1.0-jetbrains") + latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" || echo "v1.1.0-jetbrains") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV From c296d4b435383eb76338a412a5060c77ac49a303 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:30:41 -0700 Subject: [PATCH 11/57] fix again --- .github/workflows/auto-release.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 3c7182ec3..3752fb2d3 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -23,7 +23,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-vscode$" || echo "v1.1.0-vscode") + latest_tag=$(git tag --sort=-creatordate | grep -E '-vscode$' || echo "v1.1.0-vscode") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV @@ -52,7 +52,7 @@ jobs: --generate-notes \ --title "$NEW_VERSION" \ --draft \ - --latest + --latest \ --prerelease create-jetbrains-release: @@ -69,7 +69,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E "-jetbrains$" || echo "v1.1.0-jetbrains") + latest_tag=$(git tag --sort=-creatordate | grep -E '-jetbrains$' || echo "v1.1.0-jetbrains") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV @@ -98,5 +98,5 @@ jobs: --generate-notes \ --title "$NEW_VERSION" \ --draft \ - --latest + --latest \ --prerelease From 80c9911aef06d29f3d3e1db6fbae9ae9c1666084 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:32:40 -0700 Subject: [PATCH 12/57] actual fix --- .github/workflows/auto-release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 3752fb2d3..ab99809ca 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -23,7 +23,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '-vscode$' || echo "v1.1.0-vscode") + latest_tag=$(git tag --sort=-creatordate | grep -E '\-vscode$' || echo "v1.1.0-vscode") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV @@ -69,7 +69,7 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '-jetbrains$' || echo "v1.1.0-jetbrains") + latest_tag=$(git tag --sort=-creatordate | grep -E '\-jetbrains$' || echo "v1.1.0-jetbrains") echo "Latest tag: $latest_tag" echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV From 79ca0fa25ad7cd4c4f36f7788edc9177da565461 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 16:37:03 -0700 Subject: [PATCH 13/57] another fix --- .github/workflows/auto-release.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index ab99809ca..2226fccb0 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -23,9 +23,9 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '\-vscode$' || echo "v1.1.0-vscode") + latest_tag=$(git tag --sort=-creatordate | grep -E '\-vscode$' | head -n1 || echo "v1.1.0-vscode") echo "Latest tag: $latest_tag" - echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV + echo "LATEST_TAG=${latest_tag}" >> "$GITHUB_ENV" - name: Generate next version id: generate_version @@ -69,9 +69,9 @@ jobs: id: get_latest_tag run: | # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '\-jetbrains$' || echo "v1.1.0-jetbrains") + latest_tag=$(git tag --sort=-creatordate | grep -E '\-jetbrains$' | head -n1 || echo "v1.1.0-jetbrains") echo "Latest tag: $latest_tag" - echo "LATEST_TAG=$latest_tag" >> $GITHUB_ENV + echo "LATEST_TAG=${latest_tag}" >> "$GITHUB_ENV" - name: Generate next version id: generate_version From 7215bccddecc8c8083b131f43b9b8bed79948d03 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 19:50:29 -0700 Subject: [PATCH 14/57] use version from gradle.properties and package.json --- .github/workflows/auto-release.yml | 54 ++++++------------------------ 1 file changed, 11 insertions(+), 43 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 2226fccb0..43d65d5b5 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -16,30 +16,13 @@ jobs: steps: - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Important for getting all tags and commits - - name: Get latest tag - id: get_latest_tag + - name: Get version from package.json + id: get_version run: | - # Get the latest tag ending in -vscode or default to v1.1.0-vscode if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '\-vscode$' | head -n1 || echo "v1.1.0-vscode") - echo "Latest tag: $latest_tag" - echo "LATEST_TAG=${latest_tag}" >> "$GITHUB_ENV" - - - name: Generate next version - id: generate_version - run: | - # Extract version numbers (handle the -vscode suffix) - version=${LATEST_TAG#v} # Remove v prefix - version=${version%-vscode} # Remove -vscode suffix - IFS='.' read -ra VERSION_PARTS <<< "$version" - - # Increment patch version - ((VERSION_PARTS[2]++)) - - # Create new version string with -vscode suffix - new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-vscode" + # Read version from package.json and add -vscode suffix + version=$(node -p "require('./extensions/vscode/package.json').version") + new_version="v${version}-vscode" echo "New version will be: $new_version" echo "NEW_VERSION=$new_version" >> $GITHUB_ENV @@ -63,29 +46,14 @@ jobs: steps: - uses: actions/checkout@v4 with: - fetch-depth: 0 # Important for getting all tags and commits + fetch-depth: 0 - - name: Get latest tag - id: get_latest_tag + - name: Get version from gradle.properties + id: get_version run: | - # Get the latest tag ending in -jetbrains or default to v1.1.0-jetbrains if none exists - latest_tag=$(git tag --sort=-creatordate | grep -E '\-jetbrains$' | head -n1 || echo "v1.1.0-jetbrains") - echo "Latest tag: $latest_tag" - echo "LATEST_TAG=${latest_tag}" >> "$GITHUB_ENV" - - - name: Generate next version - id: generate_version - run: | - # Extract version numbers (handle the -jetbrains suffix) - version=${LATEST_TAG#v} # Remove v prefix - version=${version%-jetbrains} # Remove -jetbrains suffix - IFS='.' read -ra VERSION_PARTS <<< "$version" - - # Increment patch version - ((VERSION_PARTS[2]++)) - - # Create new version string with -jetbrains suffix - new_version="v${VERSION_PARTS[0]}.${VERSION_PARTS[1]}.${VERSION_PARTS[2]}-jetbrains" + # Read version from gradle.properties and add -jetbrains suffix + version=$(grep '^pluginVersion=' extensions/intellij/gradle.properties | cut -d'=' -f2) + new_version="v${version}-jetbrains" echo "New version will be: $new_version" echo "NEW_VERSION=$new_version" >> $GITHUB_ENV From 05899e2d68d72f2750233ed5a0dce658e454e631 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 19:51:20 -0700 Subject: [PATCH 15/57] rename --- .github/workflows/vscode-version-bump.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index 4c9ebf1a2..c05da185f 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -1,4 +1,4 @@ -name: VS Code Extension Version Bump +name: Create VS Code main release draft on: schedule: # Runs at 7 AM PST (15:00 UTC) every Friday From 9fcf958d526b15332ed16e014272faa33499640d Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 20:10:09 -0700 Subject: [PATCH 16/57] bump jb version automatically --- .github/workflows/jetbrains-release.yaml | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index a968dcc19..058d6191b 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -37,6 +37,52 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi + bump-version: + runs-on: ubuntu-latest + needs: + - check_release_name + if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' + permissions: + contents: write + pull-requests: write + steps: + # 0. Setup git + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Git + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + + - name: Create PR branch + run: | + BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" + git checkout -b $BRANCH_NAME + echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + + - name: Bump version in gradle.properties + run: | + cd extensions/intelllij + awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties + rm -rf tmp + NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) + echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v5 + with: + token: ${{ secrets.CI_GITHUB_TOKEN }} + commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + body: | + Automated PR to bump the JetBrains extension version after successful pre-release publication. + + - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} + branch: ${{ env.BRANCH_NAME }} + base: main + delete-branch: true + # Prepare and publish the plugin to JetBrains Marketplace repository build: needs: check_release_name From c987b8932b68cd34cd06559adcc8049f3fc2dca7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 5 Apr 2025 22:15:28 -0700 Subject: [PATCH 17/57] bump --- packages/config-yaml/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 0f6e6b82c..f32235580 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.78", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From fd3db4a01a43d3c18f69062dc8cdcea4ed8a8364 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 13:40:58 -0700 Subject: [PATCH 18/57] BROKEN - assistant switch p12 --- core/config/ConfigHandler.ts | 152 +++++++++++-------- gui/src/pages/config/ScopeSelect.tsx | 13 +- gui/src/redux/slices/organizations/slice.ts | 3 + gui/src/redux/slices/organizations/thunks.ts | 47 ------ 4 files changed, 104 insertions(+), 111 deletions(-) delete mode 100644 gui/src/redux/slices/organizations/thunks.ts diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 5753e4d33..68eaeac1d 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -39,9 +39,6 @@ type OrgWithProfiles = OrganizationDescription & { currentProfile: ProfileLifecycleManager | null; }; -const PERSONAL_ORG_ID = "personal"; -const LOCAL_ORG_ID = "local"; - export class ConfigHandler { controlPlaneClient: ControlPlaneClient; private readonly globalContext = new GlobalContext(); @@ -81,10 +78,7 @@ export class ConfigHandler { const personalOrg: OrgWithProfiles = { currentProfile: this.globalLocalProfileManager, profiles: [this.globalLocalProfileManager], - name: "Personal", - id: PERSONAL_ORG_ID, - iconUrl: "", - slug: undefined, + ...this.PERSONAL_ORG_DESC, }; this.currentOrg = personalOrg; @@ -106,56 +100,67 @@ export class ConfigHandler { return `${workspaceId}:::${orgId}`; } - // Loads orgs - // Loads all profiles for all orgs - // Gets/infers selected org - // Cascades org selection private async cascadeInit() { this.workspaceDirs = null; // forces workspace dirs reload const orgs = await this.getOrgs(); - // this.currentProfile = profile + // Figure out selected org + const workspaceId = await this.getWorkspaceId(); + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + const currentSelection = selectedOrgs[workspaceId]; - // const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - // const profileKey = `${workspaceId}:::${org.id}` - // const selectedProfileId = selectedProfiles[profileKey]; - // const profile = selectedProfileId ? org.profiles.find(profile => profile.profileDescription.id === selectedProfileId) : - // if(!selectedProfile) { - // // - // } + const firstNonPersonal = orgs.find( + (org) => org.id !== this.PERSONAL_ORG_DESC.id, + ); + const fallback = firstNonPersonal ?? orgs[0]; + // note, ignoring case of zero orgs since should never happen + + let selectedOrg: OrgWithProfiles; + if (!currentSelection) { + selectedOrg = fallback; + } else { + const match = orgs.find((org) => org.id === currentSelection); + if (match) { + selectedOrg = match; + } else { + selectedOrg = fallback; + } + } + + this.globalContext.update("lastSelectedOrgIdForWorkspace", { + ...selectedOrgs, + [workspaceId]: selectedOrg.id, + }); + + this.currentOrg = selectedOrg; + this.currentProfile = selectedOrg.currentProfile; + await this.reloadConfig(); } private async getOrgs(): Promise { - let orgs: OrgWithProfiles[]; const userId = await this.controlPlaneClient.userId; if (userId) { if (await useHub(this.ideSettingsPromise)) { const orgDescs = await this.controlPlaneClient.listOrganizations(); - // const personalOrg = + const personalHubOrg = await this.getPersonalHubOrg(); const hubOrgs = await Promise.all( - orgDescs.map((org) => this.makeNonPersonalHubOrg(org)), + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), ); - // profiles = [...hubProfiles, ...allLocalProfiles]; - orgs = hubOrgs; + return [personalHubOrg, ...hubOrgs]; } else { - const teamsOrg = await this.getTeamsOrg(); - orgs = [teamsOrg]; + return [await this.getTeamsOrg()]; } } else { - const localOrg = await this.getLocalOrg(); - orgs = [localOrg]; + return [await this.getLocalOrg()]; } - return orgs; } - private async getHubOrg( - org: OrganizationDescription, - orgScopeId: string | null, - ): Promise { + private async getHubProfiles(orgScopeId: string | null) { const assistants = await this.controlPlaneClient.listAssistants(orgScopeId); - const profiles = await Promise.all( + return await Promise.all( assistants.map(async (assistant) => { const profileLoader = await PlatformProfileLoader.create( { @@ -177,34 +182,37 @@ export class ConfigHandler { return new ProfileLifecycleManager(profileLoader, this.ide); }), ); + } + private async getNonPersonalHubOrg( + org: OrganizationDescription, + ): Promise { + const profiles = await this.getHubProfiles(org.id); return this.rectifyProfilesForOrg(org, profiles); } - // Refresh cascades: org -> profiles -> config - private async makePersonalHubOrg() { - // loads orgs - // gets last selected org from context - // checks if valid - // if valid sets selected org - // if not valid defaults to hub org or personal if no hub and saves fallback in context - // cascade refreshes profiles for all orgs + private PERSONAL_ORG_DESC: OrganizationDescription = { + iconUrl: "", + id: "personal", + name: "Personal", + slug: undefined, + }; + private async getPersonalHubOrg() { const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...hubProfiles, ...allLocalProfiles]; - return await this.getHubOrg(); - } - - private async makeNonPersonalHubOrg(): OrgWithProfiles { - profiles = hubProfiles; - return await this.getHubOrg(); + const hubProfiles = await this.getHubProfiles(null); + const profiles = [...hubProfiles, ...allLocalProfiles]; + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles); } private async getLocalOrg() { const allLocalProfiles = await this.getAllLocalProfiles(); - return this.rectifyProfilesForOrg(org, allLocalProfiles); + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); } - async getTeamsOrg(org: OrganizationDescription): Promise { + async getTeamsOrg(): Promise { + const teamsOrgDescription: OrganizationDescription ={ + iconUrl: workspaces. + } const workspaces = await this.controlPlaneClient.listWorkspaces(); const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { @@ -220,26 +228,48 @@ export class ConfigHandler { profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); - return rectifyProfilesForOrg({}, profiles); + return this.rectifyProfilesForOrg(teamsOrgDescription, profiles); } private async rectifyProfilesForOrg( org: OrganizationDescription, profiles: ProfileLifecycleManager[], - ): OrgWithProfiles { + ): Promise { const profileKey = await this.getProfileKey(org.id); const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - const selectedProfile = selectedProfiles[profileKey]; - if (!selectedProfile) { - } else { - } + const currentSelection = selectedProfiles[profileKey]; - this.globalContext.update("lastSelectedProfileForWorkspace", { - ...selectedProfiles, - [profileKey]: profileId, - }); + const firstNonLocal = profiles.find( + (profile) => profile.profileDescription.profileType !== "local", + ); + const fallback = firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null) + + let currentProfile: ProfileLifecycleManager | null; + if (!currentSelection) { + currentProfile = fallback; + } else { + const match = profiles.find((profile) => profile.profileDescription.id === currentSelection); + if (match) { + currentProfile = match; + } else { + currentProfile = fallback; + } + } + + if(currentProfile) { + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: selectedProfiles.id ?? null, + }); + } + + return { + ...org, + profiles, + currentProfile, + } } async getAllLocalProfiles() { diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index dc92f8048..94dfe4039 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -3,6 +3,7 @@ import { ChevronUpDownIcon, } from "@heroicons/react/24/outline"; import { UserCircleIcon } from "@heroicons/react/24/solid"; +import { useContext } from "react"; import { Listbox, ListboxButton, @@ -10,18 +11,24 @@ import { ListboxOptions, } from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; -import { selectOrgThunk } from "../../redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { setSelectedOrgId } from "../../redux"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; export function ScopeSelect() { const { organizations, selectedOrganization } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( (state) => state.organizations.selectedOrganizationId, ); const dispatch = useAppDispatch(); - const handleChange = (newValue: string | null) => { - dispatch(selectOrgThunk(newValue)); + const handleChange = (newValue: string) => { + // optimisitic update + dispatch(setSelectedOrgId(newValue)); + ideMessenger.post("didChangeSelectedOrg", { + id: newValue, + }); }; const CurScopeEntityFallBackIcon = selectedOrgId diff --git a/gui/src/redux/slices/organizations/slice.ts b/gui/src/redux/slices/organizations/slice.ts index 411519b94..097b35a58 100644 --- a/gui/src/redux/slices/organizations/slice.ts +++ b/gui/src/redux/slices/organizations/slice.ts @@ -21,6 +21,9 @@ export const organizationsSlice = createSlice({ ) => { state.organizations = payload; }, + setSelectedOrgId: (state, { payload }: PayloadAction) => { + state.selectedOrganizationId = payload; + }, }, selectors: { selectSelectedOrganization: (state) => diff --git a/gui/src/redux/slices/organizations/thunks.ts b/gui/src/redux/slices/organizations/thunks.ts deleted file mode 100644 index 85aeede0a..000000000 --- a/gui/src/redux/slices/organizations/thunks.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; -import { ThunkApiType } from "../../store"; -import { setAvailableProfiles } from "../profiles/slice"; -import { setOrganizations, setSelectedOrganizationId } from "./slice"; - -export const selectOrgThunk = createAsyncThunk< - void, - string | null, - ThunkApiType ->("organizations/select", async (id, { dispatch, extra, getState }) => { - const state = getState(); - const initialId = state.organizations.selectedOrganizationId; - let newId = id; - - // If no orgs, force clear - if (state.organizations.organizations.length === 0) { - newId = null; - } else if (newId) { - // If new id doesn't match an existing org, clear it - if (!state.organizations.organizations.find((o) => o.id === newId)) { - newId = null; - } - } - // Unlike profiles, don't fallback to the first org, - // Fallback to Personal (org = null) - - if (initialId !== newId) { - dispatch(setAvailableProfiles(null)); - dispatch(setSelectedOrganizationId(newId)); - extra.ideMessenger.post("didChangeSelectedOrg", { - id: newId, - }); - } -}); - -export const updateOrgsThunk = createAsyncThunk< - void, - OrganizationDescription[], - ThunkApiType ->("organizations/update", async (orgs, { dispatch, getState }) => { - const state = getState(); - dispatch(setOrganizations(orgs)); - - // This will trigger reselection if needed - dispatch(selectOrgThunk(state.organizations.selectedOrganizationId)); -}); From 20e5b12c02e6f31254a57ec60bc4104e5cec27fa Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 13:45:10 -0700 Subject: [PATCH 19/57] blah --- core/config/ConfigHandler.ts | 66 ++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 68eaeac1d..34632085b 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -142,15 +142,15 @@ export class ConfigHandler { private async getOrgs(): Promise { const userId = await this.controlPlaneClient.userId; if (userId) { + const orgDescs = await this.controlPlaneClient.listOrganizations(); if (await useHub(this.ideSettingsPromise)) { - const orgDescs = await this.controlPlaneClient.listOrganizations(); const personalHubOrg = await this.getPersonalHubOrg(); const hubOrgs = await Promise.all( orgDescs.map((org) => this.getNonPersonalHubOrg(org)), ); return [personalHubOrg, ...hubOrgs]; } else { - return [await this.getTeamsOrg()]; + return [await this.getTeamsOrg(orgDescs[0])]; } } else { return [await this.getLocalOrg()]; @@ -209,10 +209,7 @@ export class ConfigHandler { return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); } - async getTeamsOrg(): Promise { - const teamsOrgDescription: OrganizationDescription ={ - iconUrl: workspaces. - } + async getTeamsOrg(org: OrganizationDescription): Promise { const workspaces = await this.controlPlaneClient.listWorkspaces(); const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { @@ -228,7 +225,7 @@ export class ConfigHandler { profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); - return this.rectifyProfilesForOrg(teamsOrgDescription, profiles); + return this.rectifyProfilesForOrg(org, profiles); } private async rectifyProfilesForOrg( @@ -241,35 +238,38 @@ export class ConfigHandler { const currentSelection = selectedProfiles[profileKey]; - const firstNonLocal = profiles.find( - (profile) => profile.profileDescription.profileType !== "local", + const firstNonLocal = profiles.find( + (profile) => profile.profileDescription.profileType !== "local", + ); + const fallback = + firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null); + + let currentProfile: ProfileLifecycleManager | null; + if (!currentSelection) { + currentProfile = fallback; + } else { + const match = profiles.find( + (profile) => profile.profileDescription.id === currentSelection, ); - const fallback = firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null) - - let currentProfile: ProfileLifecycleManager | null; - if (!currentSelection) { - currentProfile = fallback; - } else { - const match = profiles.find((profile) => profile.profileDescription.id === currentSelection); - if (match) { - currentProfile = match; - } else { - currentProfile = fallback; - } - } - - if(currentProfile) { - this.globalContext.update("lastSelectedProfileForWorkspace", { - ...selectedProfiles, - [profileKey]: selectedProfiles.id ?? null, - }); + if (match) { + currentProfile = match; + } else { + currentProfile = fallback; } + } - return { - ...org, - profiles, - currentProfile, - } + if (currentProfile) { + this.globalContext.update("lastSelectedProfileForWorkspace", { + ...selectedProfiles, + [profileKey]: selectedProfiles.id ?? null, + }); + } + + return { + ...org, + profiles, + currentProfile, + }; } async getAllLocalProfiles() { From ddcd2bc81964c5bf5f45bbd61a7eb7043bae72da Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 14:59:57 -0700 Subject: [PATCH 20/57] gui updates 1 --- core/config/ConfigHandler.ts | 22 ++++-- core/config/ProfileLifecycleManager.ts | 10 +++ core/core.ts | 17 ++-- core/protocol/core.ts | 3 + core/protocol/webview.ts | 8 +- .../Lump/sections/docs/DocsSection.tsx | 2 - .../platform/AssistantSelect.tsx | 13 ++- gui/src/context/Auth.tsx | 10 +-- gui/src/hooks/useSetup.ts | 29 ++++--- gui/src/pages/config/AccountButton.tsx | 4 +- gui/src/pages/config/ScopeSelect.tsx | 4 +- gui/src/pages/config/UserSettingsForm.tsx | 2 +- gui/src/redux/slices/organizations/index.ts | 2 - gui/src/redux/slices/organizations/slice.ts | 40 ---------- gui/src/redux/slices/profiles/index.ts | 1 - gui/src/redux/slices/profiles/slice.ts | 79 ++++++++++++++++--- gui/src/redux/store.ts | 11 ++- 17 files changed, 147 insertions(+), 110 deletions(-) delete mode 100644 gui/src/redux/slices/organizations/index.ts delete mode 100644 gui/src/redux/slices/organizations/slice.ts diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 34632085b..e43664098 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -26,19 +26,16 @@ import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { OrganizationDescription, + OrgWithProfiles, ProfileDescription, ProfileLifecycleManager, + SerializedOrgWithProfiles, } from "./ProfileLifecycleManager.js"; export type { ProfileDescription }; type ConfigUpdateFunction = (payload: ConfigResult) => void; -type OrgWithProfiles = OrganizationDescription & { - profiles: ProfileLifecycleManager[]; - currentProfile: ProfileLifecycleManager | null; -}; - export class ConfigHandler { controlPlaneClient: ControlPlaneClient; private readonly globalContext = new GlobalContext(); @@ -134,6 +131,7 @@ export class ConfigHandler { [workspaceId]: selectedOrg.id, }); + this.organizations = orgs; this.currentOrg = selectedOrg; this.currentProfile = selectedOrg.currentProfile; await this.reloadConfig(); @@ -150,13 +148,25 @@ export class ConfigHandler { ); return [personalHubOrg, ...hubOrgs]; } else { - return [await this.getTeamsOrg(orgDescs[0])]; + // Should only ever be one teams org. Will be removed soon anyways + return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org))); } } else { return [await this.getLocalOrg()]; } } + getSerializedOrgs(): SerializedOrgWithProfiles[] { + return this.organizations.map((org) => ({ + iconUrl: org.iconUrl, + id: org.id, + name: org.name, + slug: org.slug, + profiles: org.profiles.map((profile) => profile.profileDescription), + selectedProfileId: org.currentProfile?.profileDescription.id || null, + })); + } + private async getHubProfiles(orgScopeId: string | null) { const assistants = await this.controlPlaneClient.listAssistants(orgScopeId); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 9d4bd2842..d93ab9236 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -32,6 +32,16 @@ export interface OrganizationDescription { slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend } +export type OrgWithProfiles = OrganizationDescription & { + profiles: ProfileLifecycleManager[]; + currentProfile: ProfileLifecycleManager | null; +}; + +export type SerializedOrgWithProfiles = OrganizationDescription & { + profiles: ProfileDescription[]; + selectedProfileId: string | null; +}; + export class ProfileLifecycleManager { private savedConfigResult: ConfigResult | undefined; private savedBrowserConfigResult?: ConfigResult; diff --git a/core/core.ts b/core/core.ts index 9ff5c9d08..3610f3dab 100644 --- a/core/core.ts +++ b/core/core.ts @@ -126,10 +126,9 @@ export class Core { this.messenger.send("configUpdate", { result: serializedResult, profileId: - this.configHandler.currentProfile?.profileDescription.id ?? null, - selectedOrgId: this.configHandler.selectedOrgId, - availableOrgProfiles: this.configHandler.listProfileDescriptions(), - availableOrgs: this.configHandler.organizations, + this.configHandler.currentProfile?.profileDescription.id || null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, }); // update additional submenu context providers registered via VSCode API @@ -297,7 +296,7 @@ export class Core { }); on("config/refreshProfiles", async (msg) => { - await this.configHandler.refreshAssistantsForSelectedOrg(); + await this.configHandler.refreshAll(); }); on("config/updateSharedConfig", async (msg) => { @@ -457,6 +456,8 @@ export class Core { result: await this.configHandler.getSerializedConfig(), profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, }; }); @@ -752,11 +753,15 @@ export class Core { void refreshIfNotIgnored(data.uris); // If it's a local assistant being created, we want to reload all assistants so it shows up in the list + let localAssistantCreated = false; for (const uri of data.uris) { if (isLocalAssistantFile(uri)) { - await this.configHandler.refreshAssistantsForSelectedOrg(); + localAssistantCreated = true; } } + if (localAssistantCreated) { + await this.configHandler.refreshAll(); + } } }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index d7a5fdd01..83ad67a85 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -30,6 +30,7 @@ import type { SlashCommandDescription, ToolCall, } from "../"; +import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; import { ControlPlaneSessionInfo } from "../control-plane/client"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -65,6 +66,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { { result: ConfigResult; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string; }, ]; "config/deleteModel": [{ title: string }, void]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index d8142a9ed..74ce31559 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,8 +1,5 @@ import { ConfigResult } from "@continuedev/config-yaml"; -import { - OrganizationDescription, - ProfileDescription, -} from "../config/ProfileLifecycleManager.js"; +import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, @@ -16,9 +13,8 @@ export type ToWebviewFromIdeOrCoreProtocol = { { result: ConfigResult; profileId: string | null; - availableOrgs: OrganizationDescription[]; + organizations: SerializedOrgWithProfiles[]; selectedOrgId: string | null; - availableOrgProfiles: ProfileDescription[]; }, void, ]; diff --git a/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx index cbe7e6e72..e7913d1ef 100644 --- a/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/docs/DocsSection.tsx @@ -1,14 +1,12 @@ import { parseConfigYaml } from "@continuedev/config-yaml"; import { IndexingStatus } from "core"; import { useMemo } from "react"; -import { useDispatch } from "react-redux"; import { useAuth } from "../../../../../context/Auth"; import { useAppSelector } from "../../../../../redux/hooks"; import { ExploreBlocksButton } from "../ExploreBlocksButton"; import DocsIndexingStatus from "./DocsIndexingStatus"; function DocsIndexingStatuses() { - const dispatch = useDispatch(); const config = useAppSelector((store) => store.config.config); const indexingStatuses = useAppSelector( (store) => store.indexing.indexing.statuses, diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 0d82f4183..6877876c1 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -9,7 +9,7 @@ import { import { useContext, useEffect, useMemo, useRef } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { setSelectedProfile } from "../../../redux"; +import { selectCurrentOrg, setSelectedProfile } from "../../../redux"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { fontSize, @@ -154,9 +154,7 @@ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); const { selectedProfile, selectedOrganization } = useAuth(); - const availableProfiles = useAppSelector( - (store) => store.profiles.availableProfiles, - ); + const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); @@ -178,7 +176,7 @@ export default function AssistantSelect() { useEffect(() => { let lastToggleTime = 0; - const DEBOUNCE_MS = 500; + const DEBOUNCE_MS = 800; const handleKeyDown = (event: KeyboardEvent) => { if ( @@ -192,7 +190,7 @@ export default function AssistantSelect() { lastToggleTime = now; const profileIds = - availableProfiles?.map((profile) => profile.id) ?? []; + currentOrg?.profiles.map((profile) => profile.id) ?? []; // In case of 1 or 0 profiles just does nothing if (profileIds.length < 2) { return; @@ -203,6 +201,7 @@ export default function AssistantSelect() { const nextIndex = (curIndex + 1) % profileIds.length; nextId = profileIds[nextIndex]; } + // Optimistic update dispatch(setSelectedProfile(nextId)); ideMessenger.post("didChangeSelectedProfile", { id: nextId, @@ -215,7 +214,7 @@ export default function AssistantSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [availableProfiles, selectedProfile]); + }, [currentOrg, selectedProfile]); const tinyFont = useFontSize(-4); const smallFont = useFontSize(-3); diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 4b6b68fb8..870d9acca 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -11,7 +11,7 @@ import React, { useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; -import { selectSelectedProfile } from "../redux/"; +import { selectCurrentOrg, selectSelectedProfile } from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; @@ -42,9 +42,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ ); // Orgs - const orgs = useAppSelector((store) => store.organizations.organizations); + const orgs = useAppSelector((store) => store.profiles.organizations); const selectedOrgId = useAppSelector( - (store) => store.organizations.selectedOrganizationId, + (store) => store.profiles.selectedOrganizationId, ); const selectedOrganization = useMemo(() => { if (!selectedOrgId) { @@ -54,7 +54,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }, [orgs, selectedOrgId]); // Profiles - const profiles = useAppSelector((store) => store.profiles.availableProfiles); + const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); const login: AuthContextType["login"] = (useOnboarding: boolean) => { @@ -150,7 +150,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ logout, login, selectedProfile, - profiles, + profiles: currentOrg?.profiles ?? [], refreshProfiles, selectedOrganization, organizations: orgs, diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 60fbdcd9b..5b3e665ad 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -2,11 +2,11 @@ import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from "core"; +import { FromCoreProtocol } from "core/protocol"; import { initializeProfilePreferences, - selectSelectedProfileId, + setOrganizations, + setSelectedOrgId, setSelectedProfile, } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; @@ -36,25 +36,28 @@ function useSetup() { const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); const defaultModel = useAppSelector(selectDefaultModel); - const selectedProfileId = useAppSelector(selectSelectedProfileId); + const selectedProfileId = useAppSelector( + (store) => store.profiles.selectedProfileId, + ); const hasDoneInitialConfigLoad = useRef(false); const handleConfigUpdate = useCallback( - async ( - isInitial: boolean, - result: { - result: ConfigResult; - profileId: string | null; - }, - ) => { - const { result: configResult, profileId } = result; + async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { + const { + result: configResult, + profileId, + organizations, + selectedOrgId, + } = result; if (isInitial && hasDoneInitialConfigLoad.current) { return; } hasDoneInitialConfigLoad.current = true; - dispatch(setConfigResult(configResult)); + dispatch(setOrganizations(organizations)); + dispatch(setSelectedOrgId(selectedOrgId)); dispatch(setSelectedProfile(profileId)); + dispatch(setConfigResult(configResult)); const isNewProfileId = profileId && profileId !== selectedProfileId; diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 34dfe2f29..05f50cc2a 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -8,13 +8,13 @@ import { Transition, } from "../../components/ui"; import { useAuth } from "../../context/Auth"; -import { selectSelectedOrganization } from "../../redux"; +import { selectCurrentOrg } from "../../redux"; import { useAppSelector } from "../../redux/hooks"; import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { const { session, logout, login, organizations } = useAuth(); - const selectedOrg = useAppSelector(selectSelectedOrganization); + const selectedOrg = useAppSelector(selectCurrentOrg); if (!session) { return ( diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 94dfe4039..19abd78f5 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -12,14 +12,14 @@ import { } from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setSelectedOrgId } from "../../redux"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setSelectedOrgId } from "../../redux/slices/profiles/slice"; export function ScopeSelect() { const { organizations, selectedOrganization } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( - (state) => state.organizations.selectedOrganizationId, + (state) => state.profiles.selectedOrganizationId, ); const dispatch = useAppDispatch(); diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index d9a5cfd27..152d701ae 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -17,7 +17,7 @@ import { getFontSize } from "../../util"; export function UserSettingsForm() { /////// User settings section ////// const dispatch = useAppDispatch(); - const { selectedProfile, controlServerBetaEnabled } = useAuth(); + const { controlServerBetaEnabled } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); diff --git a/gui/src/redux/slices/organizations/index.ts b/gui/src/redux/slices/organizations/index.ts deleted file mode 100644 index 22be336b5..000000000 --- a/gui/src/redux/slices/organizations/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./slice"; -export * from "./thunks"; diff --git a/gui/src/redux/slices/organizations/slice.ts b/gui/src/redux/slices/organizations/slice.ts deleted file mode 100644 index 097b35a58..000000000 --- a/gui/src/redux/slices/organizations/slice.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; - -export interface OrganizationsState { - organizations: OrganizationDescription[]; - selectedOrganizationId: string | null; -} - -const initialState: OrganizationsState = { - organizations: [], - selectedOrganizationId: null, -}; - -export const organizationsSlice = createSlice({ - name: "organizations", - initialState, - reducers: { - setOrganizations: ( - state, - { payload }: PayloadAction, - ) => { - state.organizations = payload; - }, - setSelectedOrgId: (state, { payload }: PayloadAction) => { - state.selectedOrganizationId = payload; - }, - }, - selectors: { - selectSelectedOrganization: (state) => - state.organizations.find( - (org) => org.id === state.selectedOrganizationId, - ) ?? null, - }, -}); - -export const { setOrganizations } = organizationsSlice.actions; - -export const { selectSelectedOrganization } = organizationsSlice.selectors; - -export const { reducer: organizationsReducer } = organizationsSlice; diff --git a/gui/src/redux/slices/profiles/index.ts b/gui/src/redux/slices/profiles/index.ts index 22be336b5..52fbee8e7 100644 --- a/gui/src/redux/slices/profiles/index.ts +++ b/gui/src/redux/slices/profiles/index.ts @@ -1,2 +1 @@ export * from "./slice"; -export * from "./thunks"; diff --git a/gui/src/redux/slices/profiles/slice.ts b/gui/src/redux/slices/profiles/slice.ts index c8eabf168..6f3144736 100644 --- a/gui/src/redux/slices/profiles/slice.ts +++ b/gui/src/redux/slices/profiles/slice.ts @@ -1,6 +1,6 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { SlashCommandDescription } from "core"; -import { ProfileDescription } from "core/config/ConfigHandler"; +import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager"; const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5; @@ -13,15 +13,40 @@ export interface PreferencesState { } export interface ProfilesState { - availableProfiles: ProfileDescription[] | null; + organizations: SerializedOrgWithProfiles[]; selectedProfileId: string | null; + selectedOrganizationId: string | null; preferencesByProfileId: Record; } const initialState: ProfilesState = { - availableProfiles: null, - selectedProfileId: null, preferencesByProfileId: {}, + selectedProfileId: null, + selectedOrganizationId: null, + organizations: [ + { + id: "personal", + profiles: [ + { + title: "Local Assistant", + id: "local", + errors: [], + profileType: "local", + uri: "", + iconUrl: "", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + }, + ], + slug: "", + selectedProfileId: "local", + name: "Personal", + iconUrl: "", + }, + ], }; export const profilesSlice = createSlice({ @@ -30,12 +55,27 @@ export const profilesSlice = createSlice({ reducers: { setSelectedProfile: (state, { payload }: PayloadAction) => { state.selectedProfileId = payload; + const currentOrg = state.organizations.find( + (o) => o.id === state.selectedOrganizationId, + ); + if (currentOrg) { + currentOrg.selectedProfileId = payload; + } }, - setAvailableProfiles: ( + setOrganizations: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { - state.availableProfiles = payload; + state.organizations = payload; + }, + setSelectedOrgId: (state, { payload }: PayloadAction) => { + state.selectedOrganizationId = payload; + const org = state.organizations.find((o) => o.id === payload); + if (org) { + state.selectedProfileId = org.selectedProfileId; + } else { + state.selectedProfileId = null; + } }, initializeProfilePreferences: ( state, @@ -102,15 +142,27 @@ export const profilesSlice = createSlice({ }, selectors: { selectSelectedProfile: (state) => { - return ( - state.availableProfiles?.find( + const selectedOrg = state.organizations.find( + (org) => org.id === state.selectedOrganizationId, + ); + if (selectedOrg) { + const profile = selectedOrg.profiles.find( (profile) => profile.id === state.selectedProfileId, + ); + return profile ?? null; + } else { + return null; + } + }, + + selectCurrentOrg: (state) => { + return ( + state.organizations.find( + (org) => org.id === state.selectedOrganizationId, ) ?? null ); }, - selectSelectedProfileId: (state) => state.selectedProfileId, - selectBookmarkedSlashCommands: (state) => { if (!state.selectedProfileId) return []; const preferences = state.preferencesByProfileId[state.selectedProfileId]; @@ -122,18 +174,19 @@ export const profilesSlice = createSlice({ }); export const { - setAvailableProfiles, setSelectedProfile, bookmarkSlashCommand, unbookmarkSlashCommand, initializeProfilePreferences, + setOrganizations, + setSelectedOrgId, } = profilesSlice.actions; export const { selectSelectedProfile, - selectSelectedProfileId, selectBookmarkedSlashCommands, selectPreferencesByProfileId, + selectCurrentOrg, } = profilesSlice.selectors; export const { reducer: profilesReducer } = profilesSlice; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index a008c6669..c69e65315 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,7 +10,7 @@ import { createFilter } from "redux-persist-transform-filter"; import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2"; import storage from "redux-persist/lib/storage"; import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger"; -import { organizationsReducer, profilesReducer } from "./slices"; +import { profilesReducer } from "./slices"; import configReducer from "./slices/configSlice"; import editModeStateReducer from "./slices/editModeState"; import indexingReducer from "./slices/indexingSlice"; @@ -31,7 +31,6 @@ const rootReducer = combineReducers({ indexing: indexingReducer, tabs: tabsReducer, profiles: profilesReducer, - organizations: organizationsReducer, }); const saveSubsetFilters = [ @@ -56,8 +55,12 @@ const saveSubsetFilters = [ createFilter("ui", ["toolSettings", "toolGroupSettings"]), createFilter("indexing", []), createFilter("tabs", ["tabs"]), - createFilter("organizations", ["selectedOrganizationId"]), - createFilter("profiles", ["preferencesByProfileId", "selectedProfileId"]), + createFilter("profiles", [ + "preferencesByProfileId", + "selectedProfileId", + "selectedOrganizationId", + "organizations", + ]), ]; const migrations: MigrationManifest = { From ae6e9fa8848c2425262617fe0238ffc7e08f0b73 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 15:12:55 -0700 Subject: [PATCH 21/57] cleanup p1 --- gui/src/redux/slices/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/redux/slices/index.ts b/gui/src/redux/slices/index.ts index 644b24187..09303f508 100644 --- a/gui/src/redux/slices/index.ts +++ b/gui/src/redux/slices/index.ts @@ -1,2 +1 @@ -export * from "./organizations"; export * from "./profiles"; From e7c2d33e58a9f93ba378e1f237a4b3ec362668c7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 15:19:16 -0700 Subject: [PATCH 22/57] pass around continue for teams enabled --- core/core.ts | 4 ++++ core/protocol/core.ts | 1 + core/protocol/webview.ts | 1 + gui/src/context/Auth.tsx | 20 +++++++++----------- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/core/core.ts b/core/core.ts index 3610f3dab..16edc0cee 100644 --- a/core/core.ts +++ b/core/core.ts @@ -129,6 +129,8 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id || null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, + usingContinueForTeams: (await ideSettingsPromise) + .enableControlServerBeta, }); // update additional submenu context providers registered via VSCode API @@ -458,6 +460,8 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id ?? null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, + usingContinueForTeams: (await ideSettingsPromise) + .enableControlServerBeta, }; }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 83ad67a85..c3a2b1a61 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -68,6 +68,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string; + usingContinueForTeams: boolean; }, ]; "config/deleteModel": [{ title: string }, void]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 74ce31559..6b59fa338 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -15,6 +15,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string | null; + usingContinueForTeams: boolean; }, void, ]; diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 870d9acca..f340d5bbb 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -11,6 +11,7 @@ import React, { useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; +import { useWebviewListener } from "../hooks/useWebviewListener"; import { selectCurrentOrg, selectSelectedProfile } from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; @@ -121,17 +122,14 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }); }, []); - // useWebviewListener( - // setControlServerBetaEnabled(settings.enableControlServerBeta); - // "didChangeIdeSettings", - // async (msg) => { - // const { settings } = msg; - // dispatch( - // setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), - // ); - // }, - // [], - // ); + // Hacky, remove once continue for teams is deprecated + useWebviewListener( + "configUpdate", + async (msg) => { + setControlServerBetaEnabled(msg.usingContinueForTeams); + }, + [], + ); const refreshProfiles = async () => { try { From b8c6fc400e46d56bf63d9bf8c52048966d86489c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 15:25:45 -0700 Subject: [PATCH 23/57] fix syntax --- core/config/ConfigHandler.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 6fdbcf38f..bf71952e9 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -9,9 +9,9 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { - const profiles = testConfigHandler.listProfileDescriptions(); + const profiles = testConfigHandler.currentOrg.profiles; expect(profiles?.length).toBe(1); - expect(profiles?.[0].id).toBe("local"); + expect(profiles?.[0].profileDescription.id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; expect(currentProfile?.profileDescription.id).toBe("local"); From 3039592d245670f6f2faa409dfdee040da87d6ec Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 15:31:05 -0700 Subject: [PATCH 24/57] fix deeplink handling --- core/config/ConfigHandler.ts | 11 ++++++++--- core/core.ts | 5 ++++- core/protocol/coreWebview.ts | 2 +- .../vscode/src/extension/VsCodeExtension.ts | 15 +++------------ 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index e43664098..8a50ff1a1 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -328,7 +328,7 @@ export class ConfigHandler { } // Org id: check id validity, save selection, switch and reload - async setSelectedOrgId(orgId: string) { + async setSelectedOrgId(orgId: string, profileId?: string) { if (orgId === this.currentOrg.id) { return; } @@ -346,8 +346,13 @@ export class ConfigHandler { }); this.currentOrg = org; - this.currentProfile = org.currentProfile; - await this.reloadConfig(); + + if (profileId) { + this.setSelectedProfileId(profileId); + } else { + this.currentProfile = org.currentProfile; + await this.reloadConfig(); + } } // Profile id: check id validity, save selection, switch and reload diff --git a/core/core.ts b/core/core.ts index 16edc0cee..f948491fc 100644 --- a/core/core.ts +++ b/core/core.ts @@ -819,7 +819,10 @@ export class Core { }); on("didChangeSelectedOrg", async (msg) => { - await this.configHandler.setSelectedOrgId(msg.data.id); + await this.configHandler.setSelectedOrgId( + msg.data.id, + msg.data.profileId, + ); }); on("didChangeControlPlaneSessionInfo", async (msg) => { diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index c3c5b7fc3..2e1bd3ff1 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -3,6 +3,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string }, void]; - didChangeSelectedOrg: [{ id: string }, void]; + didChangeSelectedOrg: [{ id: string; profileId?: string }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 6852fd4f4..ee28c6c79 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -202,16 +202,10 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId) { - if (orgId === "null") { - orgId = null; - } + if (orgId && orgId !== "null") { // In case org id is passed with profile id // Make sure org is updated before profile is set - if (profileId) { - if (profileId === "null") { - profileId = null; - } + if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedOrg", { id: orgId, profileId, @@ -221,10 +215,7 @@ export class VsCodeExtension { id: orgId, }); } - } else if (profileId) { - if (profileId === "null") { - profileId = null; - } + } else if (profileId && profileId !== "null") { this.core.invoke("didChangeSelectedProfile", { id: profileId, }); From dda316895788f49b0820203ba6c9f513c97c73fa Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 15:55:07 -0700 Subject: [PATCH 25/57] fixes --- core/config/ConfigHandler.ts | 2 +- gui/src/context/Auth.tsx | 13 ++--- gui/src/pages/config/AccountButton.tsx | 66 ++++++++++++++------------ gui/src/pages/config/ScopeSelect.tsx | 17 ++----- 4 files changed, 45 insertions(+), 53 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 8a50ff1a1..8b469d437 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -146,7 +146,7 @@ export class ConfigHandler { const hubOrgs = await Promise.all( orgDescs.map((org) => this.getNonPersonalHubOrg(org)), ); - return [personalHubOrg, ...hubOrgs]; + return [...hubOrgs, personalHubOrg]; } else { // Should only ever be one teams org. Will be removed soon anyways return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org))); diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index f340d5bbb..f8c38d812 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -5,6 +5,7 @@ import { import { ControlPlaneSessionInfo } from "core/control-plane/client"; import React, { createContext, + useCallback, useContext, useEffect, useMemo, @@ -114,14 +115,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const [controlServerBetaEnabled, setControlServerBetaEnabled] = useState(false); - useEffect(() => { - ideMessenger.ide - .getIdeSettings() - .then(({ enableControlServerBeta, continueTestEnvironment }) => { - setControlServerBetaEnabled(enableControlServerBeta); - }); - }, []); - // Hacky, remove once continue for teams is deprecated useWebviewListener( "configUpdate", @@ -131,7 +124,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ [], ); - const refreshProfiles = async () => { + const refreshProfiles = useCallback(async () => { try { await ideMessenger.request("config/refreshProfiles", undefined); ideMessenger.post("showToast", ["info", "Config refreshed"]); @@ -139,7 +132,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ console.error("Failed to refresh profiles", e); ideMessenger.post("showToast", ["error", "Failed to refresh config"]); } - }; + }, [ideMessenger]); return ( - -
- - {selectedOrg === null ? "Personal" : selectedOrg.name} - - {" "} -
-
- - - -
-
- {session.account.label} - - {session.account.id} + {({ close }) => ( + <> + +
+ + {selectedOrg === null ? "Personal" : selectedOrg.name} + {" "}
+
- {organizations.length > 0 && ( -
- - + + +
+
+ {session.account.label} + + {session.account.id} + +
+ + {organizations.length > 0 && ( +
+ + +
+ )} + + + Sign out +
- )} - - - Sign out - -
- - + + + + )} ); } diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 19abd78f5..05735c48c 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -15,7 +15,10 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { setSelectedOrgId } from "../../redux/slices/profiles/slice"; -export function ScopeSelect() { +interface ScopeSelectProps { + onSelect?: () => void; +} +export function ScopeSelect({ onSelect }: ScopeSelectProps) { const { organizations, selectedOrganization } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( @@ -29,6 +32,7 @@ export function ScopeSelect() { ideMessenger.post("didChangeSelectedOrg", { id: newValue, }); + onSelect?.(); }; const CurScopeEntityFallBackIcon = selectedOrgId @@ -70,17 +74,6 @@ export function ScopeSelect() {
))} - - {!!organizations.length && ( -
- )} - - -
- - Personal -
-
From c6d5ba1944b45b8b990214a5bf2568e2a154f0a4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 16:17:33 -0700 Subject: [PATCH 26/57] fix some auth logic --- core/protocol/core.ts | 5 --- core/protocol/ide.ts | 4 +++ .../OnboardingCard/platform/tabs/main.tsx | 5 ++- .../platform/AssistantSelect.tsx | 12 +++---- gui/src/context/Auth.tsx | 32 +++++++++++-------- gui/src/pages/config/ScopeSelect.tsx | 10 ++++-- 6 files changed, 39 insertions(+), 29 deletions(-) diff --git a/core/protocol/core.ts b/core/protocol/core.ts index c3a2b1a61..0213cd0e5 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -31,7 +31,6 @@ import type { ToolCall, } from "../"; import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; -import { ControlPlaneSessionInfo } from "../control-plane/client"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -197,8 +196,4 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - didChangeControlPlaneSessionInfo: [ - { sessionInfo: ControlPlaneSessionInfo | undefined }, - void, - ]; }; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index e590c0ec9..1646d848e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -103,4 +103,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { export type ToWebviewOrCoreFromIdeProtocol = { didChangeActiveTextEditor: [{ filepath: string }, void]; + didChangeControlPlaneSessionInfo: [ + { sessionInfo: ControlPlaneSessionInfo | undefined }, + void, + ]; }; diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx index 8ca75b1e3..ab197b3d4 100644 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ b/gui/src/components/OnboardingCard/platform/tabs/main.tsx @@ -3,6 +3,8 @@ import { useContext } from "react"; import { Button, ButtonSubtext } from "../../.."; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; +import { selectCurrentOrg } from "../../../../redux"; +import { useAppSelector } from "../../../../redux/hooks"; import { hasPassedFTL } from "../../../../util/freeTrial"; import ContinueLogo from "../../../gui/ContinueLogo"; import { useOnboardingCard } from "../../hooks"; @@ -17,6 +19,7 @@ export default function MainTab({ const ideMessenger = useContext(IdeMessengerContext); const onboardingCard = useOnboardingCard(); const auth = useAuth(); + const currentOrg = useAppSelector(selectCurrentOrg); function onGetStarted() { auth.login(true).then((success) => { @@ -29,7 +32,7 @@ export default function MainTab({ function openPastFreeTrialOnboarding() { ideMessenger.post("controlPlane/openUrl", { path: "setup-models", - orgSlug: auth.selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); onboardingCard.close(isDialog); } diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 6877876c1..7796aff8d 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -153,7 +153,7 @@ const AssistantSelectOption = ({ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile, selectedOrganization } = useAuth(); + const { selectedProfile } = useAuth(); const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); @@ -169,7 +169,7 @@ export default function AssistantSelect() { function onNewAssistant() { ideMessenger.post("controlPlane/openUrl", { path: "new", - orgSlug: selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); close(); } @@ -225,7 +225,7 @@ export default function AssistantSelect() { onClick={() => { ideMessenger.request("controlPlane/openUrl", { path: "/new?type=assistant", - orgSlug: selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); }} className="flex cursor-pointer select-none items-center gap-1 text-gray-400" @@ -332,9 +332,9 @@ export default function AssistantSelect() { className="ml-auto flex items-center gap-1" onClick={() => navigate(ROUTES.CONFIG)} > - {selectedOrganization?.iconUrl ? ( + {currentOrg?.iconUrl ? ( ) : ( @@ -346,7 +346,7 @@ export default function AssistantSelect() { fontSize: tinyFont - 1, }} > - {selectedOrganization?.name || "Personal"} + {currentOrg?.name || "Personal"}
diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index f8c38d812..329a1ee38 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -8,12 +8,16 @@ import React, { useCallback, useContext, useEffect, - useMemo, useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { selectCurrentOrg, selectSelectedProfile } from "../redux/"; +import { + selectCurrentOrg, + selectSelectedProfile, + setOrganizations, + setSelectedOrgId, +} from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; @@ -27,7 +31,6 @@ interface AuthContextType { refreshProfiles: () => void; controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; - selectedOrganization: OrganizationDescription | null; } const AuthContext = createContext(undefined); @@ -37,7 +40,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - // Session const [session, setSession] = useState( undefined, @@ -45,15 +47,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ // Orgs const orgs = useAppSelector((store) => store.profiles.organizations); - const selectedOrgId = useAppSelector( - (store) => store.profiles.selectedOrganizationId, - ); - const selectedOrganization = useMemo(() => { - if (!selectedOrgId) { - return null; - } - return orgs.find((p) => p.id === selectedOrgId) ?? null; - }, [orgs, selectedOrgId]); // Profiles const currentOrg = useAppSelector(selectCurrentOrg); @@ -89,6 +82,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ text="Are you sure you want to log out of Continue?" onConfirm={() => { ideMessenger.post("logoutOfControlPlane", undefined); + dispatch( + setOrganizations(orgs.filter((org) => org.id === "personal")), + ); + dispatch(setSelectedOrgId("personal")); }} onCancel={() => { dispatch(setDialogMessage(undefined)); @@ -112,6 +109,14 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ void init(); }, []); + useWebviewListener( + "didChangeControlPlaneSessionInfo", + async (data) => { + setSession(data.sessionInfo); + }, + [], + ); + const [controlServerBetaEnabled, setControlServerBetaEnabled] = useState(false); @@ -143,7 +148,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ selectedProfile, profiles: currentOrg?.profiles ?? [], refreshProfiles, - selectedOrganization, organizations: orgs, controlServerBetaEnabled, }} diff --git a/gui/src/pages/config/ScopeSelect.tsx b/gui/src/pages/config/ScopeSelect.tsx index 05735c48c..ee3bdd42f 100644 --- a/gui/src/pages/config/ScopeSelect.tsx +++ b/gui/src/pages/config/ScopeSelect.tsx @@ -13,17 +13,21 @@ import { import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { setSelectedOrgId } from "../../redux/slices/profiles/slice"; +import { + selectCurrentOrg, + setSelectedOrgId, +} from "../../redux/slices/profiles/slice"; interface ScopeSelectProps { onSelect?: () => void; } export function ScopeSelect({ onSelect }: ScopeSelectProps) { - const { organizations, selectedOrganization } = useAuth(); + const { organizations } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( (state) => state.profiles.selectedOrganizationId, ); + const currentOrg = useAppSelector(selectCurrentOrg); const dispatch = useAppDispatch(); const handleChange = (newValue: string) => { @@ -39,7 +43,7 @@ export function ScopeSelect({ onSelect }: ScopeSelectProps) { ? BuildingOfficeIcon : UserCircleIcon; - const selectedDisplay = selectedOrganization ?? { + const selectedDisplay = currentOrg ?? { name: "Personal", iconUrl: null, }; From 5a3c8f47f09387516663bec88ca2f319df9031dc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 16:35:25 -0700 Subject: [PATCH 27/57] refresh all button --- .../Lump/BlockSettingsTopToolbar.tsx | 56 +++-- .../platform/AssistantSelect.tsx | 222 ++++++++++-------- 2 files changed, 150 insertions(+), 128 deletions(-) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 64a477cbb..405182086 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -97,32 +97,36 @@ export function BlockSettingsTopToolbar() { return (
-
- -
-
- {sections.map((section) => ( - - setSelectedSection( - selectedSection === section.id ? null : section.id, - ) - } - /> - ))} +
+
+ +
+
+ {sections.map((section) => ( + + setSelectedSection( + selectedSection === section.id ? null : section.id, + ) + } + /> + ))} +
diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 7796aff8d..4a81a2265 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -1,4 +1,5 @@ import { + ArrowPathRoundedSquareIcon, ArrowTopRightOnSquareIcon, BuildingOfficeIcon, ChevronDownIcon, @@ -153,7 +154,7 @@ const AssistantSelectOption = ({ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile } = useAuth(); + const { selectedProfile, refreshProfiles } = useAuth(); const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); @@ -189,8 +190,7 @@ export default function AssistantSelect() { if (now - lastToggleTime >= DEBOUNCE_MS) { lastToggleTime = now; - const profileIds = - currentOrg?.profiles.map((profile) => profile.id) ?? []; + const profileIds = profiles?.map((profile) => profile.id) ?? []; // In case of 1 or 0 profiles just does nothing if (profileIds.length < 2) { return; @@ -242,118 +242,136 @@ export default function AssistantSelect() { } return ( - -
- -
-
- -
- - {selectedProfile.title} - -
-
- - - -
- {profiles?.map((profile, idx) => { - return ( - - ); - })} -
- -
-
- - login(false)} + <> + +
+ +
+
+ +
+ + {selectedProfile.title} + +
+
+ + + +
+ {profiles?.map((profile, idx) => { + return ( + + ); + })} +
+ +
+ +
+ login(false)} + > +
+ + New Assistant +
+
+
+ { + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); + }} + /> +
+
+ +
+ +
- - New Assistant -
- - -
- -
- - {getMetaKeyLabel()} ⇧ ' to toggle - -
navigate(ROUTES.CONFIG)} - > - {currentOrg?.iconUrl ? ( - - ) : ( - - )} - {currentOrg?.name || "Personal"} + {getMetaKeyLabel()} ⇧ ' to toggle +
navigate(ROUTES.CONFIG)} + > + {currentOrg?.iconUrl ? ( + + ) : ( + + )} + + {currentOrg?.name || "Personal"} + +
-
- - -
- + + +
+ + + Refresh orgs/assistants + + ); } From 68325392f26722aad16bf9ae7c9a80708a3a5c67 Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Sun, 6 Apr 2025 16:53:01 -0700 Subject: [PATCH 28/57] support fnm as well as nvm --- scripts/install-dependencies.sh | 69 ++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 18 deletions(-) diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index c3262e66c..b5a420eab 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -5,27 +5,60 @@ # - Debug -> Extension set -e -# Check if node version matches .nvmrc -if [ -f .nvmrc ]; then +# Set the correct Node version at the start of the script +setup_node_version() { + # Get required node version from .node-version or .nvmrc + if [ -f .node-version ]; then + required_node_version=$(cat .node-version) + elif [ -f .nvmrc ]; then required_node_version=$(cat .nvmrc) - current_node_version=$(node -v) - - # Remove 'v' prefix from versions for comparison - required_version=${required_node_version#v} - current_version=${current_node_version#v} + else + echo "No .node-version or .nvmrc file found. Skipping Node.js version check." + return + fi - if [ "$required_version" != "$current_version" ]; then - echo "⚠️ Warning: Your Node.js version ($current_node_version) does not match the required version ($required_node_version)" - echo "Please consider switching to the correct version using: nvm use" - - if [ -t 0 ]; then - read -p "Press Enter to continue with installation anyway..." - else - echo "Continuing with installation anyway..." - fi - echo + # Remove 'v' prefix if present + required_version=${required_node_version#v} + + # Try fnm first + if command -v fnm &> /dev/null; then + echo "📦 Using fnm to set Node.js version to $required_version..." + eval "$(fnm env --use-on-cd)" + fnm use "$required_version" || fnm use + # Then try nvm + elif command -v nvm &> /dev/null || [ -s "$NVM_DIR/nvm.sh" ]; then + echo "📦 Using nvm to set Node.js version to $required_version..." + export NVM_DIR="$HOME/.nvm" + [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Load nvm + nvm use "$required_version" || nvm use + # Fall back to version check only + else + echo "Neither fnm nor nvm found. Proceeding with current Node.js version." + fi + + # Verify the current Node.js version after our attempt to set it + current_node_version=$(node -v) + current_version=${current_node_version#v} + + if [ "$required_version" != "$current_version" ]; then + echo "⚠️ Warning: Your Node.js version ($current_node_version) does not match the required version (v$required_version)" + echo "Even after attempting to use version managers, the correct version couldn't be activated." + echo "Please consider switching to the correct version using: `nvm use` or `fnm use` or setting " + echo "the correct version in a .nvmrc or .node-version file." + + if [ -t 0 ]; then + read -p "Press Enter to continue with installation anyway..." + else + echo "Continuing with installation anyway..." fi -fi + echo + else + echo "✅ Using Node.js $current_node_version as required." + fi +} + +# Run the node version setup +setup_node_version echo "Installing root-level dependencies..." npm install From 8eb97b167b6e600196ef2e8467ca5ded8737e771 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 16:53:39 -0700 Subject: [PATCH 29/57] refresh and org toggle functionality --- .../platform/AssistantSelect.tsx | 255 ++++++++++-------- 1 file changed, 140 insertions(+), 115 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index 4a81a2265..e0d88dc12 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -10,7 +10,11 @@ import { import { useContext, useEffect, useMemo, useRef } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { selectCurrentOrg, setSelectedProfile } from "../../../redux"; +import { + selectCurrentOrg, + setSelectedOrgId, + setSelectedProfile, +} from "../../../redux"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { fontSize, @@ -156,6 +160,7 @@ export default function AssistantSelect() { const buttonRef = useRef(null); const { selectedProfile, refreshProfiles } = useAuth(); const currentOrg = useAppSelector(selectCurrentOrg); + const orgs = useAppSelector((store) => store.profiles.organizations); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); @@ -216,6 +221,24 @@ export default function AssistantSelect() { }; }, [currentOrg, selectedProfile]); + const cycleOrgs = () => { + const orgIds = orgs.map((org) => org.id); + if (orgIds.length < 2) { + return; + } + let nextId = orgIds[0]; + if (currentOrg) { + const curIndex = orgIds.indexOf(currentOrg.id); + const nextIndex = (curIndex + 1) % orgIds.length; + nextId = orgIds[nextIndex]; + } + // Optimistic update + dispatch(setSelectedOrgId(nextId)); + ideMessenger.post("didChangeSelectedOrg", { + id: nextId, + }); + }; + const tinyFont = useFontSize(-4); const smallFont = useFontSize(-3); @@ -242,136 +265,138 @@ export default function AssistantSelect() { } return ( - <> - -
- -
-
- -
- - {selectedProfile.title} - + +
+ +
+
+
-
+
- - + + +
+ {profiles?.map((profile, idx) => { + return ( + + ); + })} +
+ +
- {profiles?.map((profile, idx) => { - return ( - - ); - })} -
+ className="my-0 h-[0.5px]" + style={{ + backgroundColor: vscCommandCenterInactiveBorder, + }} + /> -
-
- -
- login(false)} +
+ login(false)} + > +
-
- - New Assistant -
- -
- { - e.stopPropagation(); - refreshProfiles(); - buttonRef.current?.click(); - }} - /> + + New Assistant
-
- +
- -
{ + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); }} > + + Refresh + +
+
+ +
+ +
+ + {getMetaKeyLabel()} ⇧ ' to toggle + +
+ {currentOrg?.iconUrl ? ( + + ) : ( + + )} + - {getMetaKeyLabel()} ⇧ ' to toggle + {currentOrg?.name || "Personal"} -
navigate(ROUTES.CONFIG)} - > - {currentOrg?.iconUrl ? ( - - ) : ( - - )} - - {currentOrg?.name || "Personal"} - -
- - -
- - - Refresh orgs/assistants - - +
+ + +
+ ); } From b6f2f3905dc4d16249a69e50543bd8ce569563b6 Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Sun, 6 Apr 2025 16:56:47 -0700 Subject: [PATCH 30/57] suppress output for fnm and nvm commands --- scripts/install-dependencies.sh | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index b5a420eab..7120e8c5d 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -23,14 +23,15 @@ setup_node_version() { # Try fnm first if command -v fnm &> /dev/null; then echo "📦 Using fnm to set Node.js version to $required_version..." - eval "$(fnm env --use-on-cd)" - fnm use "$required_version" || fnm use + # Capture output to avoid duplicate messages + eval "$(fnm env --use-on-cd)" &> /dev/null + fnm use "$required_version" &> /dev/null || fnm use &> /dev/null # Then try nvm elif command -v nvm &> /dev/null || [ -s "$NVM_DIR/nvm.sh" ]; then echo "📦 Using nvm to set Node.js version to $required_version..." export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Load nvm - nvm use "$required_version" || nvm use + nvm use "$required_version" &> /dev/null || nvm use &> /dev/null # Fall back to version check only else echo "Neither fnm nor nvm found. Proceeding with current Node.js version." @@ -43,9 +44,6 @@ setup_node_version() { if [ "$required_version" != "$current_version" ]; then echo "⚠️ Warning: Your Node.js version ($current_node_version) does not match the required version (v$required_version)" echo "Even after attempting to use version managers, the correct version couldn't be activated." - echo "Please consider switching to the correct version using: `nvm use` or `fnm use` or setting " - echo "the correct version in a .nvmrc or .node-version file." - if [ -t 0 ]; then read -p "Press Enter to continue with installation anyway..." else From 576978e8c9d747363d810f456995293d266aaedb Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Sun, 6 Apr 2025 16:59:09 -0700 Subject: [PATCH 31/57] Add node version for fnm users --- .node-version | 1 + 1 file changed, 1 insertion(+) create mode 100644 .node-version diff --git a/.node-version b/.node-version new file mode 100644 index 000000000..18c284172 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +20.11.0 \ No newline at end of file From 474c52aec15e16664b7f0cd03b8eb39072355e37 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 17:39:29 -0700 Subject: [PATCH 32/57] truncate prefixes --- .../autocomplete/util/AutocompleteLruCache.ts | 42 ++++++++++++------- core/indexing/refreshIndex.ts | 19 +++++---- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/core/autocomplete/util/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts index a93b23c5a..adac906ff 100644 --- a/core/autocomplete/util/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -39,20 +39,28 @@ export class AutocompleteLruCache { // If the query is "co" and we have "c" -> "ontinue" in the cache, // we should return "ntinue" as the completion. // Have to make sure we take the key with shortest length - const result = await this.db.get( - "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", - truncateSqliteLikePattern(prefix), - ); - - // Validate that the cached compeltion is a valid completion for the prefix - if (result && result.value.startsWith(prefix.slice(result.key.length))) { - await this.db.run( - "UPDATE cache SET timestamp = ? WHERE key = ?", - Date.now(), - prefix, + const truncatedPrefix = truncateSqliteLikePattern(prefix); + try { + const result = await this.db.get( + "SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1", + truncatedPrefix, ); - // And then truncate so we aren't writing something that's already there - return result.value.slice(prefix.length - result.key.length); + // Validate that the cached completion is a valid completion for the prefix + if ( + result && + result.value.startsWith(truncatedPrefix.slice(result.key.length)) + ) { + await this.db.run( + "UPDATE cache SET timestamp = ? WHERE key = ?", + Date.now(), + truncatedPrefix, + ); + // And then truncate so we aren't writing something that's already there + return result.value.slice(truncatedPrefix.length - result.key.length); + } + } catch (e) { + // catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX + console.error(e); } return undefined; @@ -60,13 +68,15 @@ export class AutocompleteLruCache { async put(prefix: string, completion: string) { const release = await this.mutex.acquire(); + + const truncatedPrefix = truncateSqliteLikePattern(prefix); try { await this.db.run("BEGIN TRANSACTION"); try { const result = await this.db.get( "SELECT key FROM cache WHERE key = ?", - prefix, + truncatedPrefix, ); if (result) { @@ -74,7 +84,7 @@ export class AutocompleteLruCache { "UPDATE cache SET value = ?, timestamp = ? WHERE key = ?", completion, Date.now(), - prefix, + truncatedPrefix, ); } else { const count = await this.db.get( @@ -89,7 +99,7 @@ export class AutocompleteLruCache { await this.db.run( "INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)", - prefix, + truncatedPrefix, completion, Date.now(), ); diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index ef21149b1..f76c6a7f6 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -158,18 +158,21 @@ async function getAddRemoveForTag( const updateLastUpdated: PathAndCacheKey[] = []; // First, group items by path and find latest timestamp for each - const pathGroups = new Map - }>(); + const pathGroups = new Map< + string, + { + latest: { lastUpdated: number; cacheKey: string }; + allVersions: Array<{ cacheKey: string }>; + } + >(); for (const item of saved) { const { lastUpdated, path, cacheKey } = item; - + if (!pathGroups.has(path)) { pathGroups.set(path, { latest: { lastUpdated, cacheKey }, - allVersions: [{ cacheKey }] + allVersions: [{ cacheKey }], }); } else { const group = pathGroups.get(path)!; @@ -530,6 +533,6 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string { return input.substring(startIndex, input.length); } -export function truncateSqliteLikePattern(input: string) { - return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH); +export function truncateSqliteLikePattern(input: string, safety: number = 100) { + return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety); } From b50bf43b268db8fbd25021dfc34ca02109ace843 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 18:33:03 -0700 Subject: [PATCH 33/57] refresh on any new titles --- core/config/profile/doLoadConfig.ts | 1 + core/context/providers/MCPContextProvider.ts | 9 +++++++++ gui/src/context/SubmenuContextProviders.tsx | 20 ++++++++++++++------ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 6351c4474..b3d0a7ea8 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -160,6 +160,7 @@ export default async function doLoadConfig( const serverContextProvider = new MCPContextProvider({ submenuItems, mcpId: server.id, + serverName: server.name, }); newConfig.contextProviders.push(serverContextProvider); } diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index 0cb8e2c66..a3854edbd 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -10,6 +10,7 @@ import { MCPManagerSingleton } from "../mcp"; interface MCPContextProviderOptions { mcpId: string; + serverName: string; submenuItems: ContextSubmenuItem[]; } @@ -20,6 +21,14 @@ class MCPContextProvider extends BaseContextProvider { description: "Model Context Protocol", type: "submenu", }; + override get description(): ContextProviderDescription { + return { + title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`, + displayTitle: this.options["displayTitle"] ?? "MCP", + description: "Model Context Protocol", + type: "submenu", + }; + } static encodeMCPResourceId(mcpId: string, uri: string): string { return JSON.stringify({ mcpId, uri }); diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index c89a67972..8268377de 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -50,6 +50,7 @@ export const SubmenuContextProvidersProvider = ({ }) => { const ideMessenger = useContext(IdeMessengerContext); const submenuContextProviders = useAppSelector(selectSubmenuContextProviders); + const lastProviders = useRef(submenuContextProviders); const disableIndexing = useAppSelector( (store) => store.config.config.disableIndexing, ); @@ -356,15 +357,22 @@ export const SubmenuContextProvidersProvider = ({ ); // Reload all submenu items on the initial config load - // TODO - could refresh on any change - const initialLoad = useRef(false); useEffect(() => { - if (!submenuContextProviders.length || initialLoad.current) { + if (!submenuContextProviders.length) { return; } - void loadSubmenuItems("all"); - initialLoad.current = true; - }, [loadSubmenuItems, submenuContextProviders, initialLoad]); + // Refresh submenu items when new titles detected + const newTitles = submenuContextProviders + .filter( + (provider) => + !lastProviders.current.find((p) => p.title === provider.title), + ) + .map((provider) => provider.title); + if (newTitles.length > 0) { + loadSubmenuItems(newTitles); + } + lastProviders.current = submenuContextProviders; + }, [loadSubmenuItems, submenuContextProviders]); return ( Date: Sun, 6 Apr 2025 18:35:59 -0700 Subject: [PATCH 34/57] server display title --- core/context/providers/MCPContextProvider.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts index a3854edbd..be9e50cd5 100644 --- a/core/context/providers/MCPContextProvider.ts +++ b/core/context/providers/MCPContextProvider.ts @@ -24,7 +24,9 @@ class MCPContextProvider extends BaseContextProvider { override get description(): ContextProviderDescription { return { title: `${MCPContextProvider.description.title}-${this.options["mcpId"]}`, - displayTitle: this.options["displayTitle"] ?? "MCP", + displayTitle: this.options["serverName"] + ? `${this.options["serverName"]} resources` + : "MCP", description: "Model Context Protocol", type: "submenu", }; From e5608a94e543cd8b66d68c222eacc82e8c021aff Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Sun, 6 Apr 2025 19:58:47 -0700 Subject: [PATCH 35/57] feat: fix ctx providers w/ slash cmds --- core/commands/index.ts | 23 +++++++++++++++++-- .../v1/slashCommandFromPromptFile.ts | 13 ++++++++++- core/promptFiles/v2/renderPromptFile.ts | 10 +++++--- 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index 7115d22be..6837449ef 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,7 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; +import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile"; import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -15,7 +16,16 @@ export function slashFromCustomCommand( name: commandName, description: customCommand.description ?? "", prompt: customCommand.prompt, - run: async function* ({ input, llm, history, ide, completionOptions }) { + run: async function* ({ + input, + llm, + history, + ide, + completionOptions, + config, + selectedCode, + fetch, + }) { // Render prompt template let renderedPrompt: string; if (customCommand.prompt.includes("{{{ input }}}")) { @@ -25,7 +35,16 @@ export function slashFromCustomCommand( { input }, ); } else { - renderedPrompt = customCommand.prompt + "\n\n" + input; + renderedPrompt = await renderPromptFileV2(customCommand.prompt, { + config, + llm, + ide, + selectedCode, + fetch, + fullInput: input, + embeddingsProvider: config.modelsByRole.embed[0], + reranker: config.modelsByRole.rerank[0], + }); } // Replaces slash command messages with the rendered prompt diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 6abd4927f..cfe3d409a 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -2,6 +2,7 @@ import { ContinueSDK, SlashCommand } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { getLastNPathParts } from "../../util/uri"; import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; +import { renderPromptFileV2 } from "../v2/renderPromptFile"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -67,7 +68,17 @@ export function slashCommandFromPromptFileV1( context.llm.systemMessage = systemMessage; const userInput = extractUserInput(context.input, name); - const renderedPrompt = await renderPromptV1(prompt, context, userInput); + const renderedPrompt = await renderPromptFileV2(prompt, { + config: context.config, + fullInput: userInput, + embeddingsProvider: context.config.modelsByRole.embed[0], + reranker: context.config.modelsByRole.rerank[0], + llm: context.llm, + ide: context.ide, + selectedCode: context.selectedCode, + fetch: context.fetch, + }); + const messages = replaceSlashCommandWithPromptInChatHistory( context.history, name, diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 1f08011a8..c13a3ef93 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -65,8 +65,8 @@ async function resolveAttachment( export async function renderPromptFileV2( rawContent: string, extras: ContextProviderExtras, -): Promise<[ContextItem[], string]> { - const [preamble, body] = getPreambleAndBody(rawContent); +) { + const [_, body] = getPreambleAndBody(rawContent); const contextItemsPromises: Promise[] = []; const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => { @@ -76,5 +76,9 @@ export async function renderPromptFileV2( const contextItems = (await Promise.all(contextItemsPromises)).flat(); - return [contextItems, renderedBody]; + return ( + contextItems.map((item) => item.content).join("\n\n") + + "\n\n" + + renderedBody + ); } From 84df7f45bf91c70da79901c0a44cc3b156655f6f Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 09:00:15 -0700 Subject: [PATCH 36/57] fix: return ctx items from prompt file --- core/commands/index.ts | 25 +++++++++++-------- .../v1/slashCommandFromPromptFile.ts | 2 +- core/promptFiles/v2/renderPromptFile.ts | 10 ++++---- 3 files changed, 21 insertions(+), 16 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index 6837449ef..3037d7ef7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -35,16 +35,21 @@ export function slashFromCustomCommand( { input }, ); } else { - renderedPrompt = await renderPromptFileV2(customCommand.prompt, { - config, - llm, - ide, - selectedCode, - fetch, - fullInput: input, - embeddingsProvider: config.modelsByRole.embed[0], - reranker: config.modelsByRole.rerank[0], - }); + const renderedPromptFile = await renderPromptFileV2( + customCommand.prompt, + { + config, + llm, + ide, + selectedCode, + fetch, + fullInput: input, + embeddingsProvider: config.modelsByRole.embed[0], + reranker: config.modelsByRole.rerank[0], + }, + ); + + renderedPrompt = renderedPromptFile[1]; } // Replaces slash command messages with the rendered prompt diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index cfe3d409a..fd0b48b2c 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -68,7 +68,7 @@ export function slashCommandFromPromptFileV1( context.llm.systemMessage = systemMessage; const userInput = extractUserInput(context.input, name); - const renderedPrompt = await renderPromptFileV2(prompt, { + const [_, renderedPrompt] = await renderPromptFileV2(prompt, { config: context.config, fullInput: userInput, embeddingsProvider: context.config.modelsByRole.embed[0], diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index c13a3ef93..4d52c7ba1 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -65,7 +65,7 @@ async function resolveAttachment( export async function renderPromptFileV2( rawContent: string, extras: ContextProviderExtras, -) { +): Promise<[ContextItem[], string]> { const [_, body] = getPreambleAndBody(rawContent); const contextItemsPromises: Promise[] = []; @@ -75,10 +75,10 @@ export async function renderPromptFileV2( }); const contextItems = (await Promise.all(contextItemsPromises)).flat(); - - return ( + const renderedPrompt = contextItems.map((item) => item.content).join("\n\n") + "\n\n" + - renderedBody - ); + renderedBody; + + return [contextItems, renderedPrompt]; } From 204aa51a944906fe629e92095a3f7f86113b9f6c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 10:11:43 -0700 Subject: [PATCH 37/57] feat: updated prompt docs --- .../docs/customize/deep-dives/prompt-files.md | 69 ------------- docs/docs/customize/deep-dives/prompts.md | 97 +++++++++++++++++++ docs/docs/hub/blocks/block-types.md | 7 +- docs/docusaurus.config.js | 4 + 4 files changed, 102 insertions(+), 75 deletions(-) delete mode 100644 docs/docs/customize/deep-dives/prompt-files.md create mode 100644 docs/docs/customize/deep-dives/prompts.md diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md deleted file mode 100644 index 68995746f..000000000 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Prompt files ---- - -Prompt files allow you to build and use local prompts, and provide a convenient way to test and iterate on prompts before publishing them to the Hub. - -:::info -Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) -::: - -## Quick start - -Below is a quick example of setting up a prompt file: - -1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File"). -2. Add a file called `rails.prompt` to this folder. -3. Write the following contents to `rails.prompt` and save. - -```.prompt -name: Rails Project -description: Information about this project ---- -Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb -``` - -Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. - -Then, type / and choose the "Rails Project" prompt. You can now ask any question as usual and the LLM will have the information from your .prompt file. - -## Format - -The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. - -:::info -The current state of this format is experimental and subject to change -::: - -### Preamble - -The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: - -- `name` - The display title -- `description` - The description you will see in the dropdown -- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) - -If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. - -### Context - -Many [context provider](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: - -- `@terminal` - The contents of the terminal -- `@currentFile` - The currently active file -- `@open` - All open files -- `@os` - Information about the operating system -- `@problems` - Problems reported by the language server in the active file -- `@repo-map` - A map of files in the repository -- `@tree` - A tree view of the repository structure - -Or you can directly type URLs and file paths: - -- `@https://github.com/continuedev/continue` - The contents of a URL -- `@src/index.ts` - The contents of a file (VS Code only) - -All references will be attached as context items, rather than injected directly inline. - -## Feedback - -If you have ideas about how to improve the `.prompt` file format, please reach out on [Discord](https://discord.gg/NWtdYexhMs). diff --git a/docs/docs/customize/deep-dives/prompts.md b/docs/docs/customize/deep-dives/prompts.md new file mode 100644 index 000000000..1cd1c0085 --- /dev/null +++ b/docs/docs/customize/deep-dives/prompts.md @@ -0,0 +1,97 @@ +--- +title: Prompts +--- + +Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. + +:::info +Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts) +::: + +## Examples + +Below are some examples to get you started. + +### Security review + +```text title="Security best practices review" +@open - Review these files for the following security best practices: +- Does the architecture follow security-by-design principles? +- Are there potential security vulnerabilities in the system design? +- Is sensitive data handled appropriately throughout the lifecycle? +``` + +### Reference best practice guides + +```text title="Redux best practices review" +@https://redux.js.org/style-guide/ +@currentFile + +Review this code for adherence to Redux best practices. +``` + +### Pull in commonly used files for tasks + +```text title="Generate a new TypeORM entity" +@src/db/dataSource.ts @src/db/entity/SampleEntity.ts + +Use these files to generate a new TypeORM entity based on the following requirements: +``` + +## Including Context Providers in your prompts + +Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is: + +- `@terminal` - The contents of the terminal +- `@currentFile` - The currently active file +- `@open` - All open files +- `@os` - Information about the operating system +- `@problems` - Problems reported by the language server in the active file +- `@repo-map` - A map of files in the repository +- `@tree` - A tree view of the repository structure + +Or you can directly type URLs and file paths: + +- `@https://github.com/continuedev/continue` - The contents of a URL +- `@src/index.ts` - The contents of a file (VS Code only) + +All references will be attached as context items, rather than injected directly inline. + +## Local `.prompt` files + +In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub. + +### Quick Start + +Below is a quick example of setting up a prompt file: + +1. Create a folder called `.continue/prompts` at the top level of your workspace +2. Add a file called `test.prompt` to this folder. +3. Write the following contents to `test.prompt` and save. + +```.prompt +name: Current file prompt +description: A test prompt using the current file context provider +--- +@currentFile +``` + +Now to use this prompt, you can open Chat, type /, select the prompt, and add type out some additional text such as "Review the code for any issues". + +### Format + +The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers. + +:::info +The current state of this format is experimental and subject to change +::: + +### Preamble + +The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: + +- `name` - The display title +- `description` - The description you will see in the dropdown +- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set) + +If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index 0c2698542..2cc58ee5f 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -41,12 +41,7 @@ Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and vi Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. -Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). There are two important differences between prompt blocks and prompt files: - -1. Currently, prompt blocks cannot use context providers -2. Prompt blocks are stored within `config.yaml` rather than `.continue/prompts` in project directory and - -The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). +Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). ## Data diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c74e6a71b..be943b8f9 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -489,6 +489,10 @@ const config = { to: "/getting-started/install", from: "/getting-started", }, + { + to: "/customize/deep-dives/prompt-files", + from: "/customize/deep-dives/prompts", + }, ], }, ], From 3e1e0ea9bdfe2aebf4e222b21f8348001e1bc8cb Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 10:40:55 -0700 Subject: [PATCH 38/57] Update editorConfig.ts --- .../TipTapEditor/utils/editorConfig.ts | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index 8addede87..e50769ac8 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -1,4 +1,4 @@ -import { Editor } from "@tiptap/core"; +import { Editor, JSONContent } from "@tiptap/core"; import Document from "@tiptap/extension-document"; import History from "@tiptap/extension-history"; import Image from "@tiptap/extension-image"; @@ -48,6 +48,28 @@ export function getPlaceholderText( : "Ask a follow-up"; } +/** + * Checks if the editor content is valid for submission. + * A valid submission can contain either text content or prompt/code blocks + * + * @param json The editor JSON content + * @returns true if the content is valid for submission, false otherwise + */ +export function hasValidEditorContent(json: JSONContent): boolean { + // Check for prompt or code blocks + const hasPromptOrCodeBlock = json.content?.some( + (c) => + c.type === ContinueExtensions.PromptBlock.name || + c.type === ContinueExtensions.CodeBlock.name, + ); + + // Check for text content + const hasTextContent = json.content?.some((c) => c.content); + + // Content is valid if it has either text or special blocks + return hasTextContent || hasPromptOrCodeBlock || false; +} + /** * This function is called only once, so we need to use refs to pass in the latest values */ @@ -367,8 +389,8 @@ export function createEditorConfig(options: { const json = editor.getJSON(); - // Don't do anything if input box is empty - if (!json.content?.some((c) => c.content)) { + // Don't do anything if input box doesn't have valid content + if (!hasValidEditorContent(json)) { return; } From 66345e83550a898cd36eae67a68fb020ce957677 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 10:52:56 -0700 Subject: [PATCH 39/57] feat: fix broken links --- docs/docs/customize/context-providers.mdx | 5 ----- docs/docs/customize/deep-dives/slash-commands.mdx | 2 +- docs/docs/customize/deep-dives/vscode-actions.md | 2 +- .../customize/tutorials/build-your-own-context-provider.mdx | 2 +- .../docs/customize/tutorials/build-your-own-slash-command.md | 2 +- docs/docs/hub/blocks/block-types.md | 2 +- .../current/actions/how-to-customize.md | 2 +- .../current/actions/how-to-use-it.md | 2 +- 8 files changed, 7 insertions(+), 12 deletions(-) diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index b31deedf4..204f680f0 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -530,10 +530,6 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a You'll then be able to type "@" and see "MCP" in the context providers dropdown. -### Prompt Files - -See [Prompt Files](./deep-dives/prompt-files.md). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. - ### `@Issue` Reference the conversation in a GitHub issue. @@ -883,7 +879,6 @@ You can override this query by setting the `issueQuery` parameter. You can set the `maxResults` parameter to limit the number of results returned. The default is `50`. - ### `@Discord` Reference the messages in a Discord channel. diff --git a/docs/docs/customize/deep-dives/slash-commands.mdx b/docs/docs/customize/deep-dives/slash-commands.mdx index 0c9796768..059cf8213 100644 --- a/docs/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/docs/customize/deep-dives/slash-commands.mdx @@ -26,7 +26,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/ It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. -Learn more about prompt files [here](./prompt-files.md) +Learn more about prompt files [here](./prompts.md) ### MCP Server prompts diff --git a/docs/docs/customize/deep-dives/vscode-actions.md b/docs/docs/customize/deep-dives/vscode-actions.md index 0c0cdd1f1..d9f1b7b66 100644 --- a/docs/docs/customize/deep-dives/vscode-actions.md +++ b/docs/docs/customize/deep-dives/vscode-actions.md @@ -14,7 +14,7 @@ To make common use cases even more accessible, we provide a handful of other way ## Quick actions -Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompt-files.md) to perform custom actions. +Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions. ![quick-actions](/img/quick-actions.png) diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx index 7710a84c2..1494680c0 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx @@ -50,7 +50,7 @@ Then, create a server that responds to requests as are made from [HttpContextPro The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. :::info -The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompt files](../deep-dives/prompt-files.md) where possible. +The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible. ::: ## Using CustomContextProvider diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md index 27b0517b3..03543a22f 100644 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ b/docs/docs/customize/tutorials/build-your-own-slash-command.md @@ -3,7 +3,7 @@ title: Build your own slash command --- :::info -Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompt-files.md) to achieve similar functionality. +Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompts.md) to achieve similar functionality. ::: There are two ways to add custom slash commands: diff --git a/docs/docs/hub/blocks/block-types.md b/docs/docs/hub/blocks/block-types.md index 2cc58ee5f..b9c5bbd13 100644 --- a/docs/docs/hub/blocks/block-types.md +++ b/docs/docs/hub/blocks/block-types.md @@ -41,7 +41,7 @@ Learn more in the [rules deep dive](../../customize/deep-dives/rules.md), and vi Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub. -Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompt-files.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). +Prompt blocks have the same syntax as [prompt files](../../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../../reference.md#prompts). ## Data diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 2ffc4d0f2..d3c1097e7 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -13,7 +13,7 @@ Continue 有一个大的内置斜杠命令库,但是当你首次安装时, 有两种方法添加定制斜杠命令: -1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。 +1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompts.md) 查看完整参考。 2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数 ### 使用 `config.ts` 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md index f265a9885..a0d4c0023 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md @@ -24,7 +24,7 @@ Actions 是常见用例的快捷方式。例如,你可能想要审查代码, 通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。 -完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。 +完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt.md) 。 :::tip[Prompt 库] 为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求! From 945bd7b7e84263dec705f677cdbe01a09e95f2d5 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 10:57:21 -0700 Subject: [PATCH 40/57] Update docusaurus.config.js --- docs/docusaurus.config.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index be943b8f9..06e717ad7 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -286,7 +286,7 @@ const config = { ], }, { - to: "/customize/deep-dives/prompt-files", + to: "/customize/deep-dives/prompts", from: ["/walkthroughs/prompt-files", "/features/prompt-files"], }, // TODO - actions redirects @@ -490,8 +490,8 @@ const config = { from: "/getting-started", }, { - to: "/customize/deep-dives/prompt-files", - from: "/customize/deep-dives/prompts", + to: "/customize/deep-dives/prompts", + from: "/customize/deep-dives/prompt-files", }, ], }, From 5166e74799ad5d529748ad7ba2c2d674bcf8bfd4 Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Tue, 11 Feb 2025 23:11:20 -0500 Subject: [PATCH 41/57] BaseLLM: don't disguise AbortError when rethrowing When we catch/log/rethrow AbortError, throw it as itself, rather than throw Error(e.message) so that outer callers can detect it by the exception name. --- core/llm/index.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index cc7d7123c..de55528a9 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -460,11 +460,7 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } - //if e instance of LLMError, rethrow - if (e instanceof LLMError) { - throw e; - } - throw new Error(e.message); + throw e; } }; return withExponentialBackoff( From caf7288d36c1361b6cb279821d9ee377636f72f7 Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Tue, 25 Mar 2025 11:34:07 -0400 Subject: [PATCH 42/57] Revert "Add citations to the log" We can't add citations to the rich log until we have them plumbed through with the correct data types. That will happen when they get added to the UI. Since the only appearance so far was in the old text log, just revert the addition for now. This reverts commit 6bc0bfc5f1f77de9228c0ffda6cbb602bc8828e5. --- core/llm/index.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index de55528a9..22f977c2f 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -782,7 +782,6 @@ export abstract class BaseLLM implements ILLM { let thinking = ""; let completion = ""; - let citations: null | string[] = null; try { if (this.templateMessages) { @@ -823,13 +822,6 @@ export abstract class BaseLLM implements ILLM { completion += result.content; yield result; } - if ( - !citations && - (chunk as any).citations && - Array.isArray((chunk as any).citations) - ) { - citations = (chunk as any).citations; - } } } } else { @@ -871,12 +863,6 @@ export abstract class BaseLLM implements ILLM { requests when not using tools, so it's the simplest option to always add to history. */ await this.writeLog(`Completion:\n${completion}\n\n`); - - if (citations) { - await this.writeLog( - `Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`, - ); - } } return { From 3553dfaae44e9655fb0fcda5da3b70e14d159747 Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Tue, 11 Feb 2025 23:14:36 -0500 Subject: [PATCH 43/57] Add rich logging of LLM interactions Instead of treating LLM logging as simply writing lines of text sequentially, emit a stream of typed data objects that include rich information about the interaction, such as timestamps, message types, tool calls, etc. These are then collected by a new custom webview in the vscode extension (the "Continue Console"), allowing a user or developer to browse through the different interactions and view them in detail. In progress interactions are now streamed live, instead of being held back to avoid concurrency issues. This webview could be also exposed for IntelliJ or file logging could be reimplemented on top of the new framework. --- binary/src/index.ts | 4 +- core/config/ConfigHandler.ts | 12 +- core/config/load.ts | 21 +- .../profile/ControlPlaneProfileLoader.ts | 5 +- core/config/profile/LocalProfileLoader.ts | 6 +- core/config/profile/PlatformProfileLoader.ts | 10 +- core/config/profile/doLoadConfig.ts | 7 +- core/config/types.ts | 92 ++++- core/config/yaml/loadYaml.ts | 9 +- core/config/yaml/models.ts | 28 +- .../providers/_context-providers.test.ts | 4 +- core/core.ts | 5 +- core/index.d.ts | 92 ++++- core/indexing/docs/DocsService.skip.ts | 3 +- core/llm/index.test.ts | 7 +- core/llm/index.ts | 369 +++++++++++++----- core/llm/llms/index.ts | 5 +- core/llm/logger.ts | 43 ++ core/test/fixtures.ts | 3 +- extensions/vscode/package.json | 34 ++ .../src/ContinueConsoleWebviewViewProvider.ts | 172 ++++++++ extensions/vscode/src/commands.ts | 8 + .../vscode/src/extension/VsCodeExtension.ts | 32 +- gui/indexConsole.html | 13 + gui/src/components/console/Details.tsx | 116 ++++++ gui/src/components/console/End.tsx | 37 ++ gui/src/components/console/Expander.tsx | 25 ++ gui/src/components/console/Layout.tsx | 30 ++ gui/src/components/console/List.tsx | 53 +++ gui/src/components/console/ListItem.tsx | 55 +++ gui/src/components/console/Message.tsx | 106 +++++ gui/src/components/console/Result.tsx | 37 ++ gui/src/components/console/ResultGroup.tsx | 19 + gui/src/components/console/Start.tsx | 73 ++++ gui/src/components/console/StatusIcon.tsx | 34 ++ gui/src/console.tsx | 12 + gui/src/hooks/useLLMLog.ts | 225 +++++++++++ gui/src/hooks/useLLMSummary.ts | 76 ++++ gui/src/indexConsole.css | 9 + gui/vite.config.ts | 5 + 40 files changed, 1727 insertions(+), 169 deletions(-) create mode 100644 core/llm/logger.ts create mode 100644 extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts create mode 100644 gui/indexConsole.html create mode 100644 gui/src/components/console/Details.tsx create mode 100644 gui/src/components/console/End.tsx create mode 100644 gui/src/components/console/Expander.tsx create mode 100644 gui/src/components/console/Layout.tsx create mode 100644 gui/src/components/console/List.tsx create mode 100644 gui/src/components/console/ListItem.tsx create mode 100644 gui/src/components/console/Message.tsx create mode 100644 gui/src/components/console/Result.tsx create mode 100644 gui/src/components/console/ResultGroup.tsx create mode 100644 gui/src/components/console/Start.tsx create mode 100644 gui/src/components/console/StatusIcon.tsx create mode 100644 gui/src/console.tsx create mode 100644 gui/src/hooks/useLLMLog.ts create mode 100644 gui/src/hooks/useLLMSummary.ts create mode 100644 gui/src/indexConsole.css diff --git a/binary/src/index.ts b/binary/src/index.ts index 32bede332..08adf99f1 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -33,9 +33,7 @@ program.action(async () => { const ide = new IpcIde(messenger); const promptLogsPath = getPromptLogsPath(); - new Core(messenger, ide, async (text) => { - fs.appendFileSync(promptLogsPath, text + "\n\n"); - }); + new Core(messenger, ide); console.log("[binary] Core started"); } catch (e) { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 8b469d437..2d4a471d5 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -12,6 +12,7 @@ import { IDE, IdeSettings, ILLM, + ILLMLogger, } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; @@ -48,12 +49,11 @@ export class ConfigHandler { constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, - private readonly writeLog: (text: string) => Promise, + private llmLogger: ILLMLogger, sessionInfoPromise: Promise, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; - this.writeLog = writeLog; this.controlPlaneClient = new ControlPlaneClient( sessionInfoPromise, ideSettingsPromise, @@ -65,7 +65,7 @@ export class ConfigHandler { ide, ideSettingsPromise, this.controlPlaneClient, - writeLog, + this.llmLogger, ), this.ide, ); @@ -184,7 +184,7 @@ export class ConfigHandler { this.controlPlaneClient, this.ide, this.ideSettingsPromise, - this.writeLog, + this.llmLogger, assistant.rawYaml, orgScopeId, ); @@ -229,7 +229,7 @@ export class ConfigHandler { this.controlPlaneClient, this.ide, this.ideSettingsPromise, - this.writeLog, + this.llmLogger, this.reloadConfig.bind(this), ); @@ -292,7 +292,7 @@ export class ConfigHandler { this.ide, this.ideSettingsPromise, this.controlPlaneClient, - this.writeLog, + this.llmLogger, assistant, ); }); diff --git a/core/config/load.ts b/core/config/load.ts index 1a3acd6c6..b85359641 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -27,6 +27,7 @@ import { IdeSettings, IdeType, ILLM, + ILLMLogger, LLMOptions, ModelDescription, RerankerDescription, @@ -222,7 +223,7 @@ async function intermediateToFinalConfig( ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, loadPromptFiles: boolean = true, allowFreeTrial: boolean = true, @@ -238,7 +239,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, config.completionOptions, config.systemMessage, ); @@ -260,7 +261,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, copyOf(config.completionOptions), config.systemMessage, ); @@ -280,7 +281,7 @@ async function intermediateToFinalConfig( } else { const llm = new CustomLLMClass({ ...desc, - options: { ...desc.options, writeLog } as any, + options: { ...desc.options, logger: llmLogger } as any, }); if (llm.model === "AUTODETECT") { try { @@ -289,7 +290,11 @@ async function intermediateToFinalConfig( (modelName) => new CustomLLMClass({ ...desc, - options: { ...desc.options, model: modelName, writeLog }, + options: { + ...desc.options, + model: modelName, + logger: llmLogger, + }, }), ); @@ -343,7 +348,7 @@ async function intermediateToFinalConfig( ide.readFile.bind(ide), uniqueId, ideSettings, - writeLog, + llmLogger, config.completionOptions, config.systemMessage, ); @@ -831,7 +836,7 @@ async function loadContinueConfigFromJson( ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, overrideConfigJson: SerializedContinueConfig | undefined, ): Promise> { @@ -931,7 +936,7 @@ async function loadContinueConfigFromJson( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, ); return { diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 85130676b..21ea27e14 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -7,6 +7,7 @@ import { ContinueConfig, IDE, IdeSettings, + ILLMLogger, SerializedContinueConfig, } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; @@ -27,7 +28,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, - private writeLog: (message: string) => Promise, + private llmLogger: ILLMLogger, private readonly onReload: () => void, ) { this.description = { @@ -65,7 +66,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { this.ide, this.ideSettingsPromise, this.controlPlaneClient, - this.writeLog, + this.llmLogger, serializedConfig, undefined, undefined, diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 464d16804..f49c8bb7a 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,7 +1,7 @@ import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; -import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; +import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; import { getPrimaryConfigFilePath } from "../../util/paths.js"; @@ -17,7 +17,7 @@ export default class LocalProfileLoader implements IProfileLoader { private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, - private writeLog: (message: string) => Promise, + private llmLogger: ILLMLogger, private overrideAssistantFile?: | { path: string; content: string } | undefined, @@ -59,7 +59,7 @@ export default class LocalProfileLoader implements IProfileLoader { this.ide, this.ideSettingsPromise, this.controlPlaneClient, - this.writeLog, + this.llmLogger, undefined, undefined, undefined, diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 468d3511a..cf9efb399 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; -import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; +import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; @@ -30,7 +30,7 @@ export default class PlatformProfileLoader implements IProfileLoader { private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, - private writeLog: (message: string) => Promise, + private llmLogger: ILLMLogger, readonly description: ProfileDescription, private readonly orgScopeId: string | null, ) {} @@ -44,7 +44,7 @@ export default class PlatformProfileLoader implements IProfileLoader { controlPlaneClient: ControlPlaneClient, ide: IDE, ideSettingsPromise: Promise, - writeLog: (message: string) => Promise, + llmLogger: ILLMLogger, rawYaml: string, orgScopeId: string | null, ): Promise { @@ -74,7 +74,7 @@ export default class PlatformProfileLoader implements IProfileLoader { controlPlaneClient, ide, ideSettingsPromise, - writeLog, + llmLogger, description, orgScopeId, ); @@ -93,7 +93,7 @@ export default class PlatformProfileLoader implements IProfileLoader { this.ide, this.ideSettingsPromise, this.controlPlaneClient, - this.writeLog, + this.llmLogger, undefined, this.configResult.config, { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index b3d0a7ea8..626546b74 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -12,6 +12,7 @@ import { ContinueRcJson, IDE, IdeSettings, + ILLMLogger, SerializedContinueConfig, Tool, } from "../../"; @@ -39,7 +40,7 @@ export default async function doLoadConfig( ide: IDE, ideSettingsPromise: Promise, controlPlaneClient: ControlPlaneClient, - writeLog: (message: string) => Promise, + llmLogger: ILLMLogger, overrideConfigJson: SerializedContinueConfig | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, @@ -74,7 +75,7 @@ export default async function doLoadConfig( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, overrideConfigYaml, platformConfigMetadata, @@ -92,7 +93,7 @@ export default async function doLoadConfig( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, overrideConfigJson, ); diff --git a/core/config/types.ts b/core/config/types.ts index 2a68c4c35..3cf978540 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -90,7 +90,7 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + llmLogger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; @@ -433,6 +433,94 @@ declare global { export type ToastType = "info" | "error" | "warning"; + export interface LLMInteractionBase { + interactionId: string; + timestamp: number; + } + + export interface LLMInteractionStartChat extends LLMInteractionBase { + kind: "startChat"; + messages: ChatMessage[]; + options: CompletionOptions; + } + + export interface LLMInteractionStartComplete extends LLMInteractionBase { + kind: "startComplete"; + prompt: string; + options: CompletionOptions; + } + + export interface LLMInteractionStartFim extends LLMInteractionBase { + kind: "startFim"; + prefix: string; + suffix: string; + options: CompletionOptions; + } + + export interface LLMInteractionChunk extends LLMInteractionBase { + kind: "chunk"; + chunk: string; + } + + export interface LLMInteractionMessage extends LLMInteractionBase { + kind: "message"; + message: ChatMessage; + } + + export interface LLMInteractionEnd extends LLMInteractionBase { + promptTokens: number; + generatedTokens: number; + thinkingTokens: number; + } + + export interface LLMInteractionSuccess extends LLMInteractionEnd { + kind: "success"; + } + + export interface LLMInteractionCancel extends LLMInteractionEnd { + kind: "cancel"; + } + + export interface LLMInteractionError extends LLMInteractionEnd { + kind: "error"; + name: string; + message: string; + } + + export type LLMInteractionItem = + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim + | LLMInteractionChunk + | LLMInteractionMessage + | LLMInteractionSuccess + | LLMInteractionCancel + | LLMInteractionError; + + // When we log a LLM interaction, we want to add the interactionId and timestamp + // in the logger code, so we need a type that omits these members from *each* + // member of the union. This can be done by using the distributive behavior of + // conditional types in Typescript. + // + // www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types + // https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s + type DistributiveOmit = T extends unknown + ? Omit + : never; + + export type LLMInteractionItemDetails = DistributiveOmit< + LLMInteractionItem, + "interactionId" | "timestamp" + >; + + export interface ILLMInteractionLog { + logItem(item: LLMInteractionItemDetails): void; + } + + export interface ILLMLogger { + createInteractionLog(): ILLMInteractionLog; + } + export interface LLMOptions { model: string; @@ -446,7 +534,7 @@ declare global { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; aiGatewaySlug?: string; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f157bf21d..1edb48604 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -20,6 +20,7 @@ import { IDE, IdeInfo, IdeSettings, + ILLMLogger, } from "../.."; import { slashFromCustomCommand } from "../../commands"; import { AllRerankers } from "../../context/allRerankers"; @@ -116,7 +117,7 @@ async function configYamlToContinueConfig( ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, allowFreeTrial: boolean = true, @@ -216,7 +217,7 @@ async function configYamlToContinueConfig( ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config: continueConfig, }); @@ -412,7 +413,7 @@ export async function loadContinueConfigFromYaml( ideSettings: IdeSettings, ideInfo: IdeInfo, uniqueId: string, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, workOsAccessToken: string | undefined, overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, @@ -451,7 +452,7 @@ export async function loadContinueConfigFromYaml( ideSettings, ideInfo, uniqueId, - writeLog, + llmLogger, workOsAccessToken, platformConfigMetadata, ); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 6eabfd040..fa9c92cac 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -1,6 +1,12 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { ContinueConfig, IDE, IdeSettings, LLMOptions } from "../.."; +import { + ContinueConfig, + IDE, + IdeSettings, + ILLMLogger, + LLMOptions, +} from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; @@ -25,14 +31,14 @@ async function modelConfigToBaseLLM({ model, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }: { model: ModelConfig; uniqueId: string; ideSettings: IdeSettings; - writeLog: (log: string) => Promise; + llmLogger: ILLMLogger; platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { @@ -54,7 +60,7 @@ async function modelConfigToBaseLLM({ model.defaultCompletionOptions?.maxTokens ?? cls.defaultOptions?.completionOptions?.maxTokens, }, - writeLog, + logger: llmLogger, uniqueId, title: model.name, systemMessage: config.systemMessage, @@ -141,7 +147,7 @@ async function autodetectModels({ ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }: { @@ -150,7 +156,7 @@ async function autodetectModels({ ide: IDE; uniqueId: string; ideSettings: IdeSettings; - writeLog: (log: string) => Promise; + llmLogger: ILLMLogger; platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { @@ -171,7 +177,7 @@ async function autodetectModels({ }, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }); @@ -189,7 +195,7 @@ export async function llmsFromModelConfig({ ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }: { @@ -197,7 +203,7 @@ export async function llmsFromModelConfig({ ide: IDE; uniqueId: string; ideSettings: IdeSettings; - writeLog: (log: string) => Promise; + llmLogger: ILLMLogger; platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { @@ -205,7 +211,7 @@ export async function llmsFromModelConfig({ model, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }); @@ -220,7 +226,7 @@ export async function llmsFromModelConfig({ ide, uniqueId, ideSettings, - writeLog, + llmLogger, platformConfigMetadata, config, }); diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 21f436b75..d8eb90ef9 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -7,6 +7,7 @@ import { IContextProvider, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; +import { LLMLogger } from "../../llm/logger"; import { TEST_DIR } from "../../test/testDir"; import FileSystemIde from "../../util/filesystem"; @@ -26,10 +27,11 @@ async function getContextProviderExtras( ): Promise { const ide = new FileSystemIde(TEST_DIR); const ideSettingsPromise = ide.getIdeSettings(); + const llmLogger = new LLMLogger(); const configHandler = new ConfigHandler( ide, ideSettingsPromise, - async (text) => {}, + llmLogger, Promise.resolve(undefined), ); const { config } = await configHandler.loadConfig(); diff --git a/core/core.ts b/core/core.ts index f948491fc..d59900cec 100644 --- a/core/core.ts +++ b/core/core.ts @@ -46,6 +46,7 @@ import { isLocalAssistantFile } from "./config/loadLocalAssistants"; import { MCPManagerSingleton } from "./context/mcp"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; +import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -58,6 +59,7 @@ export class Core { codebaseIndexingState: IndexingProgressUpdate; private docsService: DocsService; private globalContext = new GlobalContext(); + llmLogger = new LLMLogger(); private readonly indexingPauseToken = new PauseToken( this.globalContext.get("indexingPaused") === true, @@ -85,7 +87,6 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => {}, ) { // Ensure .continue directory is created migrateV1DevDataFiles(); @@ -106,7 +107,7 @@ export class Core { this.configHandler = new ConfigHandler( this.ide, ideSettingsPromise, - this.onWrite, + this.llmLogger, sessionInfoPromise, ); diff --git a/core/index.d.ts b/core/index.d.ts index dd96d1699..e7fb25ef9 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -90,7 +90,7 @@ export interface ILLM extends LLMOptions { requestOptions?: RequestOptions; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + llmLogger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; @@ -483,6 +483,94 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions { export type ToastType = "info" | "error" | "warning"; +export interface LLMInteractionBase { + interactionId: string; + timestamp: number; +} + +export interface LLMInteractionStartChat extends LLMInteractionBase { + kind: "startChat"; + messages: ChatMessage[]; + options: CompletionOptions; +} + +export interface LLMInteractionStartComplete extends LLMInteractionBase { + kind: "startComplete"; + prompt: string; + options: CompletionOptions; +} + +export interface LLMInteractionStartFim extends LLMInteractionBase { + kind: "startFim"; + prefix: string; + suffix: string; + options: CompletionOptions; +} + +export interface LLMInteractionChunk extends LLMInteractionBase { + kind: "chunk"; + chunk: string; +} + +export interface LLMInteractionMessage extends LLMInteractionBase { + kind: "message"; + message: ChatMessage; +} + +export interface LLMInteractionEnd extends LLMInteractionBase { + promptTokens: number; + generatedTokens: number; + thinkingTokens: number; +} + +export interface LLMInteractionSuccess extends LLMInteractionEnd { + kind: "success"; +} + +export interface LLMInteractionCancel extends LLMInteractionEnd { + kind: "cancel"; +} + +export interface LLMInteractionError extends LLMInteractionEnd { + kind: "error"; + name: string; + message: string; +} + +export type LLMInteractionItem = + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim + | LLMInteractionChunk + | LLMInteractionMessage + | LLMInteractionSuccess + | LLMInteractionCancel + | LLMInteractionError; + +// When we log a LLM interaction, we want to add the interactionId and timestamp +// in the logger code, so we need a type that omits these members from *each* +// member of the union. This can be done by using the distributive behavior of +// conditional types in Typescript. +// +// www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types +// https://stackoverflow.com/questions/57103834/typescript-omit-a-property-from-all-interfaces-in-a-union-but-keep-the-union-s +type DistributiveOmit = T extends unknown + ? Omit + : never; + +export type LLMInteractionItemDetails = DistributiveOmit< + LLMInteractionItem, + "interactionId" | "timestamp" +>; + +export interface ILLMInteractionLog { + logItem(item: LLMInteractionItemDetails): void; +} + +export interface ILLMLogger { + createInteractionLog(): ILLMInteractionLog; +} + export interface LLMOptions { model: string; @@ -496,7 +584,7 @@ export interface LLMOptions { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; rules?: Rule[]; apiKey?: string; diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 6021fc260..9677abfef 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -3,6 +3,7 @@ // */ // import { ConfigHandler } from "../../config/ConfigHandler.js"; // import { SiteIndexingConfig } from "../../index.js"; +// import { LLMLogger } from "../../llm/logger.js"; // import FileSystemIde from "../../util/filesystem.js"; // import { editConfigJson } from "../../util/paths.js"; @@ -48,7 +49,7 @@ // configHandler = new ConfigHandler( // ide, // ideSettingsPromise, -// async () => {}, +// new LLMLogger(), // Promise.resolve(undefined), // ); diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 404902e91..7f535d1fd 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,6 +1,7 @@ import { ChatMessage, LLMOptions } from ".."; import { BaseLLM } from "."; +import { LLMLogger } from "./logger"; class DummyLLM extends BaseLLM { static providerName = "openai"; @@ -30,7 +31,7 @@ describe("BaseLLM", () => { const templatMessagesFunction = (messages: ChatMessage[]) => { return messages[0]?.content.toString() ?? ""; }; - const writeLogFunction = async () => {}; + const llmLogger = new LLMLogger(); const options: LLMOptions = { model: "gpt-3.5-turbo", uniqueId: "testId", @@ -43,7 +44,7 @@ describe("BaseLLM", () => { requestOptions: {}, promptTemplates: {}, templateMessages: templatMessagesFunction, - writeLog: writeLogFunction, + logger: llmLogger, llmRequestHook: () => {}, apiKey: "testApiKey", aiGatewaySlug: "testSlug", @@ -67,7 +68,7 @@ describe("BaseLLM", () => { expect(instance.requestOptions).toEqual({}); expect(instance.promptTemplates).toEqual({}); expect(instance.templateMessages).toEqual(templatMessagesFunction); - expect(instance.writeLog).toBe(writeLogFunction); + expect(instance.logger).toBe(llmLogger); expect(instance.apiKey).toBe("testApiKey"); expect(instance.aiGatewaySlug).toBe("testSlug"); expect(instance.apiBase).toBe("https://api.example.com/"); diff --git a/core/llm/index.ts b/core/llm/index.ts index 22f977c2f..7544b5292 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -16,6 +16,8 @@ import { Chunk, CompletionOptions, ILLM, + ILLMInteractionLog, + ILLMLogger, LLMFullCompletionOptions, LLMOptions, ModelCapability, @@ -72,6 +74,8 @@ export function isModelInstaller(provider: any): provider is ModelInstaller { return provider && typeof provider.installModel === "function"; } +type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -129,7 +133,7 @@ export abstract class BaseLLM implements ILLM { template?: TemplateType; promptTemplates?: Record; templateMessages?: (messages: ChatMessage[]) => string; - writeLog?: (str: string) => Promise; + logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; @@ -220,7 +224,7 @@ export abstract class BaseLLM implements ILLM { options.template, ) ?? undefined; - this.writeLog = options.writeLog; + this.logger = options.logger; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; @@ -345,13 +349,17 @@ export abstract class BaseLLM implements ILLM { ); } - private _logTokensGenerated( + private _logEnd( model: string, prompt: string, completion: string, - ) { + thinking: string | undefined, + interaction: ILLMInteractionLog | undefined, + error?: any, + ): InteractionStatus { let promptTokens = this.countTokens(prompt); let generatedTokens = this.countTokens(completion); + let thinkingTokens = thinking ? this.countTokens(thinking) : 0; void Telemetry.capture( "tokens_generated", @@ -380,6 +388,37 @@ export abstract class BaseLLM implements ILLM { generatedTokens: generatedTokens, }, }); + + if (error !== undefined) { + if (error === "cancel" || error.name === "AbortError") { + interaction?.logItem({ + kind: "cancel", + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "cancelled"; + } else { + console.log(error); + interaction?.logItem({ + kind: "error", + name: error.name, + message: error.message, + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "error"; + } + } else { + interaction?.logItem({ + kind: "success", + promptTokens, + generatedTokens, + thinkingTokens, + }); + return "success"; + } } fetch(url: RequestInfo | URL, init?: RequestInit): Promise { @@ -535,52 +574,89 @@ export abstract class BaseLLM implements ILLM { ): AsyncGenerator { const { completionOptions, logEnabled } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`; if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(fimLog, completionOptions), - ); - } + interaction?.logItem({ + kind: "startFim", + prefix, + suffix, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, fimLog); } } let completion = ""; - - if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { - const stream = this.openaiAdapter.fimStream( - toFimBody(prefix, suffix, completionOptions), - signal, - ); - for await (const chunk of stream) { - const result = fromChatCompletionChunk(chunk); - if (result) { - const content = renderChatMessage(result); - completion += content; - yield content; + try { + if (this.shouldUseOpenAIAdapter("streamFim") && this.openaiAdapter) { + const stream = this.openaiAdapter.fimStream( + toFimBody(prefix, suffix, completionOptions), + signal, + ); + for await (const chunk of stream) { + const result = fromChatCompletionChunk(chunk); + if (result) { + const content = renderChatMessage(result); + interaction?.logItem({ + kind: "chunk", + chunk: content, + }); + completion += content; + yield content; + } + } + } else { + for await (const chunk of this._streamFim( + prefix, + suffix, + signal, + completionOptions, + )) { + interaction?.logItem({ + kind: "chunk", + chunk, + }); + completion += chunk; + yield chunk; } } - } else { - for await (const chunk of this._streamFim( - prefix, - suffix, - signal, - completionOptions, - )) { - completion += chunk; - yield chunk; + + status = this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + fimLog, + completion, + undefined, + interaction, + "cancel", + ); } } - this._logTokensGenerated(completionOptions.model, fimLog, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); - } - return { prompt: fimLog, completion, @@ -595,6 +671,10 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -608,11 +688,11 @@ export abstract class BaseLLM implements ILLM { } if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startComplete", + prompt, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } @@ -640,6 +720,10 @@ export abstract class BaseLLM implements ILLM { )) { const content = chunk.choices[0]?.text ?? ""; completion += content; + interaction?.logItem({ + kind: "chunk", + chunk: content, + }); yield content; } } @@ -650,14 +734,40 @@ export abstract class BaseLLM implements ILLM { completionOptions, )) { completion += chunk; + interaction?.logItem({ + kind: "chunk", + chunk, + }); yield chunk; } } + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + e, + ); + throw e; } finally { - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", + ); } } @@ -676,6 +786,10 @@ export abstract class BaseLLM implements ILLM { ) { const { completionOptions, logEnabled, raw } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; let prompt = pruneRawPromptFromTop( completionOptions.model, @@ -689,34 +803,65 @@ export abstract class BaseLLM implements ILLM { } if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startComplete", + prompt: prompt, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } } - let completion: string; - if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { - const result = await this.openaiAdapter.completionNonStream( - { - ...toCompleteBody(prompt, completionOptions), - stream: false, - }, - signal, + let completion: string = ""; + + try { + if (this.shouldUseOpenAIAdapter("complete") && this.openaiAdapter) { + const result = await this.openaiAdapter.completionNonStream( + { + ...toCompleteBody(prompt, completionOptions), + stream: false, + }, + signal, + ); + completion = result.choices[0].text; + } else { + completion = await this._complete(prompt, signal, completionOptions); + } + + interaction?.logItem({ + kind: "chunk", + chunk: completion, + }); + + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, ); - completion = result.choices[0].text; - } else { - completion = await this._complete(prompt, signal, completionOptions); - } - - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - await this.writeLog(`Completion:\n${completion}\n\n`); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", + ); + } } return completion; @@ -761,6 +906,10 @@ export abstract class BaseLLM implements ILLM { ): AsyncGenerator { let { completionOptions, logEnabled } = this._parseCompletionOptions(options); + const interaction = logEnabled + ? this.logger?.createInteractionLog() + : undefined; + let status: InteractionStatus = "in_progress"; completionOptions = this._modifyCompletionOptions(completionOptions); @@ -770,11 +919,11 @@ export abstract class BaseLLM implements ILLM { ? this.templateMessages(messages) : this._formatChatMessages(messages); if (logEnabled) { - if (this.writeLog) { - await this.writeLog( - this._compilePromptForLog(prompt, completionOptions), - ); - } + interaction?.logItem({ + kind: "startChat", + messages, + options: completionOptions, + }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); } @@ -791,6 +940,10 @@ export abstract class BaseLLM implements ILLM { completionOptions, )) { completion += chunk; + interaction?.logItem({ + kind: "chunk", + chunk: chunk, + }); yield { role: "assistant", content: chunk }; } } else { @@ -820,6 +973,10 @@ export abstract class BaseLLM implements ILLM { const result = fromChatCompletionChunk(chunk); if (result) { completion += result.content; + interaction?.logItem({ + kind: "message", + message: result, + }); yield result; } } @@ -832,38 +989,56 @@ export abstract class BaseLLM implements ILLM { )) { if (chunk.role === "assistant") { completion += chunk.content; - yield chunk; + } else if (chunk.role === "thinking") { + thinking += chunk.content; } - if (chunk.role === "thinking") { - thinking += chunk.content; - yield chunk; - } + interaction?.logItem({ + kind: "message", + message: chunk, + }); + yield chunk; } } } - } catch (error) { - console.log(error); - throw error; - } - - this._logTokensGenerated(completionOptions.model, prompt, completion); - - if (logEnabled && this.writeLog) { - if (thinking) { - await this.writeLog(`Thinking:\n${thinking}\n\n`); + status = this._logEnd( + completionOptions.model, + prompt, + completion, + thinking, + interaction, + ); + } catch (e) { + status = this._logEnd( + completionOptions.model, + prompt, + completion, + thinking, + interaction, + e, + ); + throw e; + } finally { + if (status === "in_progress") { + this._logEnd( + completionOptions.model, + prompt, + completion, + undefined, + interaction, + "cancel", + ); } - /* - TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking - During tool use, you must pass thinking and redacted_thinking blocks back to the API, - and you must include the complete unmodified block back to the API. This is critical - for maintaining the model's reasoning flow and conversation integrity. - - On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent - requests when not using tools, so it's the simplest option to always add to history. - */ - await this.writeLog(`Completion:\n${completion}\n\n`); } + /* + TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking + During tool use, you must pass thinking and redacted_thinking blocks back to the API, + and you must include the complete unmodified block back to the API. This is critical + for maintaining the model's reasoning flow and conversation integrity. + + On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent + requests when not using tools, so it's the simplest option to always add to history. + */ return { modelTitle: this.title ?? completionOptions.model, diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 8e3f68b2e..cef09098c 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -2,6 +2,7 @@ import { BaseCompletionOptions, IdeSettings, ILLM, + ILLMLogger, LLMOptions, ModelDescription, } from "../.."; @@ -115,7 +116,7 @@ export async function llmFromDescription( readFile: (filepath: string) => Promise, uniqueId: string, ideSettings: IdeSettings, - writeLog: (log: string) => Promise, + llmLogger: ILLMLogger, completionOptions?: BaseCompletionOptions, systemMessage?: string, ): Promise { @@ -145,7 +146,7 @@ export async function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens, }, systemMessage, - writeLog, + logger: llmLogger, uniqueId, }; diff --git a/core/llm/logger.ts b/core/llm/logger.ts new file mode 100644 index 000000000..ae4699a45 --- /dev/null +++ b/core/llm/logger.ts @@ -0,0 +1,43 @@ +import { + ILLMLogger, + ILLMInteractionLog, + LLMInteractionItem, + LLMInteractionItemDetails, +} from ".."; + +type LLMLogItemFunction = (item: LLMInteractionItem) => void; + +export class LLMLogger implements ILLMLogger { + private nextId = 0; + + public createInteractionLog(): LLMInteractionLog { + return new LLMInteractionLog(this, (this.nextId++).toString()); + } + + private logItemListeners: LLMLogItemFunction[] = []; + + onLogItem(listener: LLMLogItemFunction) { + this.logItemListeners.push(listener); + } + + public _logItem(item: LLMInteractionItem) { + for (const listener of this.logItemListeners) { + listener(item); + } + } +} + +export class LLMInteractionLog implements ILLMInteractionLog { + constructor( + private logger: LLMLogger, + public interactionId: string, + ) {} + + logItem(item: LLMInteractionItemDetails) { + this.logger._logItem({ + ...item, + interactionId: this.interactionId, + timestamp: Date.now(), + }); + } +} diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index ae54b03db..a394273e9 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -1,6 +1,7 @@ import { ConfigHandler } from "../config/ConfigHandler"; import { ControlPlaneClient } from "../control-plane/client"; import Mock from "../llm/llms/Mock"; +import { LLMLogger } from "../llm/logger"; import FileSystemIde from "../util/filesystem"; import { TEST_DIR } from "./testDir"; @@ -17,7 +18,7 @@ export const testControlPlaneClient = new ControlPlaneClient( export const testConfigHandler = new ConfigHandler( testIde, ideSettingsPromise, - async (text) => {}, + new LLMLogger(), Promise.resolve(undefined), ); diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 459957c8d..6ac6afd30 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -127,6 +127,11 @@ "default": false, "markdownDescription": "Pause Continue's codebase index on start." }, + "continue.enableConsole": { + "type": "boolean", + "default": false, + "markdownDescription": "Enable a console to log and explore model inputs and outputs. It can be found in the bottom panel." + }, "continue.remoteConfigServerUrl": { "type": "string", "default": null, @@ -252,6 +257,13 @@ "title": "View History", "group": "Continue" }, + { + "command": "continue.clearConsole", + "category": "Continue", + "title": "Clear Console", + "icon": "$(clear-all)", + "group": "Continue" + }, { "command": "continue.navigateTo", "category": "Continue", @@ -505,6 +517,11 @@ "command": "continue.openConfigPage", "group": "navigation@4", "when": "view == continue.continueGUIView" + }, + { + "command": "continue.clearConsole", + "group": "navigation@1", + "when": "view == continue.continueConsoleView" } ], "editor/title": [ @@ -533,6 +550,13 @@ "title": "Continue", "icon": "media/sidebar-icon.png" } + ], + "panel": [ + { + "id": "continueConsole", + "title": "Continue Console", + "icon": "$(window)" + } ] }, "views": { @@ -544,6 +568,16 @@ "icon": "media/sidebar-icon.png", "visibility": "visible" } + ], + "continueConsole": [ + { + "type": "webview", + "id": "continue.continueConsoleView", + "name": "Continue Console", + "icon": "$(window)", + "visibility": "visible", + "when": "config.continue.enableConsole" + } ] }, "jsonValidation": [ diff --git a/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts new file mode 100644 index 000000000..a509b6e70 --- /dev/null +++ b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts @@ -0,0 +1,172 @@ +import { LLMInteractionItem } from "core"; +import { EXTENSION_NAME } from "core/control-plane/env"; +import { LLMLogger } from "core/llm/logger"; +import * as vscode from "vscode"; + +import { getExtensionUri, getNonce } from "./util/vscode"; + +interface FromConsoleView { + type: "start" | "stop"; + uuid: string; +} + +export class ContinueConsoleWebviewViewProvider + implements vscode.WebviewViewProvider +{ + public static readonly viewType = "continue.continueConsoleView"; + + resolveWebviewView( + webviewView: vscode.WebviewView, + _context: vscode.WebviewViewResolveContext, + _token: vscode.CancellationToken, + ): void | Thenable { + this._webviewView = webviewView; + this._webview = webviewView.webview; + this._webviewView.onDidDispose(() => { + this._webviewView = undefined; + this._webview = undefined; + }); + webviewView.webview.html = this.getSidebarContent( + this.extensionContext, + webviewView, + ); + this._webview.onDidReceiveMessage((message: FromConsoleView) => { + if (message.type === "start") { + this._currentUuid = message.uuid; + this._webview?.postMessage({ + type: "init", + uuid: this._currentUuid, + items: this._items, + }); + } + }); + this._webviewView.onDidDispose(() => { + this._webview = undefined; + this._webviewView = undefined; + this._currentUuid = undefined; + }); + } + + private _webview?: vscode.Webview; + private _webviewView?: vscode.WebviewView; + private _currentUuid?: string; + private _items: LLMInteractionItem[] = []; + private _saveLog; + + constructor( + private readonly windowId: string, + private readonly extensionContext: vscode.ExtensionContext, + private readonly llmLogger: LLMLogger, + ) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration(`${EXTENSION_NAME}.enableConsole`)) { + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + this._saveLog = config.get("enableConsole"); + if (!this._saveLog) { + this.clearLog(); + } + } + }); + + llmLogger.onLogItem((item) => { + if (!this._saveLog) { + return; + } + + this._items.push(item); + if (this._currentUuid) { + this._webview?.postMessage({ + type: "item", + uuid: this._currentUuid, + item, + }); + } + }); + } + + clearLog() { + this._items = []; + if (this._currentUuid) { + this._webview?.postMessage({ + type: "clear", + uuid: this._currentUuid, + }); + } + } + + private getSidebarContent( + context: vscode.ExtensionContext | undefined, + panel: vscode.WebviewPanel | vscode.WebviewView, + page: string | undefined = undefined, + ): string { + const extensionUri = getExtensionUri(); + let scriptUri: string; + let styleMainUri: string; + + const inDevelopmentMode = + context?.extensionMode === vscode.ExtensionMode.Development; + if (!inDevelopmentMode) { + scriptUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.js"), + ) + .toString(); + styleMainUri = panel.webview + .asWebviewUri( + vscode.Uri.joinPath(extensionUri, "gui/assets/indexConsole.css"), + ) + .toString(); + } else { + scriptUri = "http://localhost:5173/src/console.tsx"; + styleMainUri = "http://localhost:5173/src/indexConsole.css"; + } + + panel.webview.options = { + enableScripts: true, + localResourceRoots: [ + vscode.Uri.joinPath(extensionUri, "gui"), + vscode.Uri.joinPath(extensionUri, "assets"), + ], + enableCommandUris: true, + portMapping: [ + { + webviewPort: 65433, + extensionHostPort: 65433, + }, + ], + }; + + const nonce = getNonce(); + + return ` + + + + + + + + Continue + + +
+ + ${ + inDevelopmentMode + ? `` + : "" + } + + + `; + } +} diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 32d240d5f..9009d2b58 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -27,6 +27,7 @@ import { setupStatusBar, StatusBarStatus, } from "./autocomplete/statusBar"; +import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; import { VerticalDiffManager } from "./diff/vertical/manager"; @@ -318,6 +319,7 @@ const getCommandsMap: ( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -329,6 +331,7 @@ const getCommandsMap: ( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, @@ -672,6 +675,9 @@ const getCommandsMap: ( "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", ); }, + "continue.clearConsole": async () => { + consoleView.clearLog(); + }, "continue.viewLogs": async () => { captureCommandTelemetry("viewLogs"); vscode.commands.executeCommand("workbench.action.toggleDevTools"); @@ -1088,6 +1094,7 @@ export function registerAllCommands( ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, + consoleView: ContinueConsoleWebviewViewProvider, configHandler: ConfigHandler, verticalDiffManager: VerticalDiffManager, continueServerClientPromise: Promise, @@ -1103,6 +1110,7 @@ export function registerAllCommands( ide, extensionContext, sidebar, + consoleView, configHandler, verticalDiffManager, continueServerClientPromise, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index ee28c6c79..c955f8d51 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -21,6 +21,7 @@ import { StatusBarStatus, } from "../autocomplete/statusBar"; import { registerAllCommands } from "../commands"; +import { ContinueConsoleWebviewViewProvider } from "../ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; @@ -48,6 +49,7 @@ export class VsCodeExtension { private configHandler: ConfigHandler; private extensionContext: vscode.ExtensionContext; private ide: VsCodeIde; + private consoleView: ContinueConsoleWebviewViewProvider; private sidebar: ContinueGUIWebviewViewProvider; private windowId: string; private editDecorationManager: EditDecorationManager; @@ -106,10 +108,6 @@ export class VsCodeExtension { ); resolveWebviewProtocol(this.sidebar.webviewProtocol); - // Config Handler with output channel - const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion", - ); const inProcessMessenger = new InProcessMessenger< ToCoreProtocol, FromCoreProtocol @@ -125,19 +123,12 @@ export class VsCodeExtension { this.editDecorationManager, ); - this.core = new Core(inProcessMessenger, this.ide, async (log: string) => { - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.appendLine( - "==========================================================================", - ); - outputChannel.append(log); - }); + this.core = new Core(inProcessMessenger, this.ide); this.configHandler = this.core.configHandler; resolveConfigHandler?.(this.configHandler); this.configHandler.loadConfig(); + this.verticalDiffManager = new VerticalDiffManager( this.configHandler, this.sidebar.webviewProtocol, @@ -244,12 +235,27 @@ export class VsCodeExtension { this.fileSearch, ); + // LLM Log view + this.consoleView = new ContinueConsoleWebviewViewProvider( + this.windowId, + this.extensionContext, + this.core.llmLogger, + ); + + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueConsoleView", + this.consoleView, + ), + ); + // Commands registerAllCommands( context, this.ide, context, this.sidebar, + this.consoleView, this.configHandler, this.verticalDiffManager, this.core.continueServerClientPromise, diff --git a/gui/indexConsole.html b/gui/indexConsole.html new file mode 100644 index 000000000..aaa69903b --- /dev/null +++ b/gui/indexConsole.html @@ -0,0 +1,13 @@ + + + + + + + Continue + + +
+ + + diff --git a/gui/src/components/console/Details.tsx b/gui/src/components/console/Details.tsx new file mode 100644 index 000000000..a9edfa8a6 --- /dev/null +++ b/gui/src/components/console/Details.tsx @@ -0,0 +1,116 @@ +import { useEffect, useRef } from "react"; +import { LLMInteraction } from "../../hooks/useLLMLog"; +import useLLMSummary from "../../hooks/useLLMSummary"; +import End from "./End"; +import ResultGroup from "./ResultGroup"; +import Start from "./Start"; +import StatusIcon from "./StatusIcon"; + +export interface DetailsProps { + interaction: LLMInteraction; +} + +function renderCell(children: React.ReactNode) { + return ( +
+ {children} +
+ ); +} + +/** + * A cell of statistics at the top of the details view + */ +function Cell({ + label, + value, + format, +}: { + label: string; + value: any; + format?: (value: any) => string; +}) { + return renderCell( + value != undefined ? `${label}: ${format ? format(value) : value}` : "", + ); +} + +/** + * A cell of statistics at the top of the details view with custom content + */ +function CustomCell({ children }: { children: React.ReactNode }) { + return renderCell(children); +} + +function formatSeconds(milliseconds: number) { + return (milliseconds / 1000).toFixed(2) + "s"; +} + +export default function Details({ interaction }: DetailsProps) { + const scrollTop = useRef(null); + const lastResult = useRef(null); + const summary = useLLMSummary(interaction); + + useEffect(() => { + if (interaction.end) { + return; + } + + const last = interaction.results[interaction.results.length - 1]; + if (last != lastResult.current) { + lastResult.current = last; + const lastChild = scrollTop.current?.lastChild; + if (lastChild) { + (lastChild as HTMLElement).scrollIntoView({ + behavior: "auto", + block: "end", + }); + } + } + }); + + return ( +
+
+
+ + + Result: + {summary.result} + +
+
+ + + +
+
+ + + v.toFixed(1)} + > +
+
+
+ {interaction.start ? : ""} +
+ {interaction.results.map((group, i) => { + return ; + })} +
+ {interaction.end ? : ""} +
+
+ ); +} diff --git a/gui/src/components/console/End.tsx b/gui/src/components/console/End.tsx new file mode 100644 index 000000000..382ac4bda --- /dev/null +++ b/gui/src/components/console/End.tsx @@ -0,0 +1,37 @@ +import { + LLMInteractionCancel, + LLMInteractionError, + LLMInteractionSuccess, +} from "core"; +import Expander from "./Expander"; +import Message from "./Message"; + +export interface StartProps { + item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel; +} + +export default function Start({ item }: StartProps) { + //
+ switch (item.kind) { + case "success": + return <>; + case "error": + return ( +
+ + Error + + {item.message} +
+ ); + break; + case "cancel": + return ( +
+ + Cancelled + +
+ ); + } +} diff --git a/gui/src/components/console/Expander.tsx b/gui/src/components/console/Expander.tsx new file mode 100644 index 000000000..f7d958463 --- /dev/null +++ b/gui/src/components/console/Expander.tsx @@ -0,0 +1,25 @@ +import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { ReactNode, useState } from "react"; + +export interface ExpanderProps { + label: string; + children: ReactNode; +} + +export default function Expander({ label, children }: ExpanderProps) { + const [expanded, setExpanded] = useState(false); + + return ( +
+
setExpanded(!expanded)}> + {expanded ? ( + + ) : ( + + )}{" "} + {label} +
+ {expanded &&
{children}
} +
+ ); +} diff --git a/gui/src/components/console/Layout.tsx b/gui/src/components/console/Layout.tsx new file mode 100644 index 000000000..d1dcd9266 --- /dev/null +++ b/gui/src/components/console/Layout.tsx @@ -0,0 +1,30 @@ +import { useState } from "react"; +import useLLMLog from "../../hooks/useLLMLog"; +import Details from "./Details"; +import List from "./List"; + +export default function Layout() { + const llmLog = useLLMLog(); + + const [selectedId, setSelectedId] = useState(undefined); + + const interaction = selectedId + ? llmLog.interactions.get(selectedId) + : undefined; + + return llmLog.loading ? ( +
Loading...
+ ) : ( +
+ { + setSelectedId(interactionId); + }} + > + {interaction && ( +
+ )} +
+ ); +} diff --git a/gui/src/components/console/List.tsx b/gui/src/components/console/List.tsx new file mode 100644 index 000000000..b10a15684 --- /dev/null +++ b/gui/src/components/console/List.tsx @@ -0,0 +1,53 @@ +import { useEffect, useRef, useState } from "react"; +import { LLMLog } from "../../hooks/useLLMLog"; +import ListItem from "./ListItem"; + +export interface ListProps { + llmLog: LLMLog; + onClickInteraction: (interactionId: string) => void; +} + +export default function List({ llmLog, onClickInteraction }: ListProps) { + const topRef = useRef(null); + const [selectedId, setSelectedId] = useState(undefined); + + const lastSize = useRef(0); + + useEffect(() => { + if (llmLog.order.length != lastSize.current) { + setSelectedId(llmLog.order[llmLog.order.length - 1]); + onClickInteraction(llmLog.order[llmLog.order.length - 1]); + + lastSize.current = llmLog.order.length; + const lastChild = topRef.current?.lastChild; + if (lastChild) { + (lastChild as HTMLElement).scrollIntoView({ + behavior: "smooth", + block: "end", + }); + } + } + }); + + return ( +
    + {llmLog.order.map((id) => ( + { + topRef.current?.focus(); + setSelectedId(interactionId); + onClickInteraction(interactionId); + }} + selected={id == selectedId} + > + ))} +
+ ); +} diff --git a/gui/src/components/console/ListItem.tsx b/gui/src/components/console/ListItem.tsx new file mode 100644 index 000000000..bbd4a4be3 --- /dev/null +++ b/gui/src/components/console/ListItem.tsx @@ -0,0 +1,55 @@ +import { LLMInteraction } from "../../hooks/useLLMLog"; +import useLLMSummary from "../../hooks/useLLMSummary"; +import StatusIcon from "./StatusIcon"; + +export interface ListItemProps { + interactionId: string; + interaction: LLMInteraction; + selected: boolean; + onClickInteraction: (interactionId: string) => void; +} + +function formatTimestamp(timestamp: number) { + const date = new Date(timestamp); + + const hours = date.getHours().toString().padStart(2, "0"); + const minutes = date.getMinutes().toString().padStart(2, "0"); + const seconds = date.getSeconds(); + const milliseconds = date.getMilliseconds(); + + // Format seconds with one decimal place + const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`; + + return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`; +} + +export default function ListItem({ + interactionId, + interaction, + onClickInteraction, + selected, +}: ListItemProps) { + const summary = useLLMSummary(interaction); + + return ( +
  • onClickInteraction(interactionId)} + > + {" "} + + {interaction.start ? formatTimestamp(interaction.start.timestamp) : ""} + + {summary.type} +
  • + ); +} diff --git a/gui/src/components/console/Message.tsx b/gui/src/components/console/Message.tsx new file mode 100644 index 000000000..8c5c35bc6 --- /dev/null +++ b/gui/src/components/console/Message.tsx @@ -0,0 +1,106 @@ +import { + AssistantChatMessage, + ChatMessage, + ThinkingChatMessage, + UserChatMessage, +} from "core"; +import { memo } from "react"; + +export interface MessageProps { + message: ChatMessage; +} + +function renderMessageText(text: string) { + return {text}; +} + +export function renderMessageRole(role: ChatMessage["role"]) { + return ( +
    + + {role} + +
    + ); +} + +function renderMessageContent( + message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage, +) { + if (typeof message.content == "string") { + return renderMessageText(message.content); + } else { + return message.content.map((part) => { + if (part.type == "text") { + return renderMessageText(part.text); + } else { + return
    Image: {part.imageUrl.url}
    ; + } + }); + } +} + +export function renderMessage(message: ChatMessage, includeRole: boolean) { + switch (message.role) { + case "assistant": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {message.toolCalls + ? message.toolCalls.map((toolCall) => ( +
    Tool call: {JSON.stringify(toolCall, undefined, 2)}
    + )) + : ""} + {renderMessageContent(message)} + + ); + break; + case "thinking": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {message.toolCalls + ? message.toolCalls.map((toolCall) => ( +
    Tool call: {JSON.stringify(toolCall, undefined, 2)}
    + )) + : ""} + {renderMessageContent(message)} + {message.redactedThinking && ( +
    Redacted Thinking: {message.redactedThinking}
    + )} + {message.signature &&
    Signature: {message.signature}
    } + + ); + break; + case "user": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {renderMessageContent(message)} + + ); + break; + case "system": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} + {renderMessageText(message.content)} + + ); + case "tool": + return ( + <> + {includeRole ? renderMessageRole(message.role) : ""} +
    Tool Call ID: {message.toolCallId}
    + {renderMessageText(message.content)} + + ); + break; + } +} + +const Message = memo(function Message({ message }: MessageProps) { + return renderMessage(message, true); +}); + +export default Message; diff --git a/gui/src/components/console/Result.tsx b/gui/src/components/console/Result.tsx new file mode 100644 index 000000000..6122fa2a8 --- /dev/null +++ b/gui/src/components/console/Result.tsx @@ -0,0 +1,37 @@ +import { memo } from "react"; +import { LLMResult } from "../../hooks/useLLMLog"; +import { renderMessage } from "./Message"; + +interface ResultProps { + result: LLMResult; + prevResult: LLMResult | undefined; +} + +const Result = memo(function Result({ result, prevResult }: ResultProps) { + switch (result.kind) { + case "chunk": + return {result.chunk}; + break; + case "message": + switch (result.message.role) { + case "assistant": + case "thinking": + const includeRole = !( + prevResult?.kind === "message" && + prevResult.message.role === result.message.role + ); + return renderMessage(result.message, includeRole); + default: + // We don't expect anything but AssistantChatMessages and ThinkingChatMessages in the reply + // from the LLM output, but log them if they do occur. + return ( +
    + {renderMessage(result.message, true)} +
    + ); + } + break; + } +}); + +export default Result; diff --git a/gui/src/components/console/ResultGroup.tsx b/gui/src/components/console/ResultGroup.tsx new file mode 100644 index 000000000..b7ed2933c --- /dev/null +++ b/gui/src/components/console/ResultGroup.tsx @@ -0,0 +1,19 @@ +import { memo } from "react"; +import { LLMResult } from "../../hooks/useLLMLog"; +import Result from "./Result"; + +interface ResultGroupProps { + group: LLMResult[]; +} + +const ResultGroup = memo(function ResultGroup({ group }: ResultGroupProps) { + return ( + <> + {group.map((result, i) => ( + + ))} + + ); +}); + +export default ResultGroup; diff --git a/gui/src/components/console/Start.tsx b/gui/src/components/console/Start.tsx new file mode 100644 index 000000000..a28601aaa --- /dev/null +++ b/gui/src/components/console/Start.tsx @@ -0,0 +1,73 @@ +import { + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, +} from "core"; +import Expander from "./Expander"; +import Message from "./Message"; + +export interface StartProps { + item: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim; +} + +export default function Start({ item }: StartProps) { + return ( +
    + {(() => { + switch (item.kind) { + case "startChat": + return ( + <> + +
    + {item.messages.map((message, i) => ( + + ))} +
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + break; + case "startComplete": + return ( + <> + +
    {item.prompt}
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + break; + case "startFim": + return ( + <> + +
    {item.prefix}
    +
    + +
    {item.suffix}
    +
    + +
    +                    {JSON.stringify(item.options, undefined, 2)}
    +                  
    +
    + + ); + } + })()} +
    + ); +} diff --git a/gui/src/components/console/StatusIcon.tsx b/gui/src/components/console/StatusIcon.tsx new file mode 100644 index 000000000..51cbe7a91 --- /dev/null +++ b/gui/src/components/console/StatusIcon.tsx @@ -0,0 +1,34 @@ +import { + CheckIcon, + EllipsisHorizontalIcon, + StopCircleIcon, + XCircleIcon, +} from "@heroicons/react/24/outline"; +import { LLMInteraction } from "../../hooks/useLLMLog"; + +export interface StatusIconProps { + interaction: LLMInteraction; +} + +export default function StatusIcon({ interaction }: StatusIconProps) { + if (interaction.end) { + switch (interaction.end.kind) { + case "success": + return ( + + ); + case "cancel": + return ( + + ); + case "error": + return ( + + ); + } + } else { + return ( + + ); + } +} diff --git a/gui/src/console.tsx b/gui/src/console.tsx new file mode 100644 index 000000000..beb7c4e53 --- /dev/null +++ b/gui/src/console.tsx @@ -0,0 +1,12 @@ +import React from "react"; +import ReactDOM from "react-dom/client"; +import Layout from "./components/console/Layout"; +import "./indexConsole.css"; + +(async () => { + ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( + + + , + ); +})(); diff --git a/gui/src/hooks/useLLMLog.ts b/gui/src/hooks/useLLMLog.ts new file mode 100644 index 000000000..0df2c56e1 --- /dev/null +++ b/gui/src/hooks/useLLMLog.ts @@ -0,0 +1,225 @@ +import { + LLMInteractionCancel, + LLMInteractionChunk, + LLMInteractionError, + LLMInteractionItem, + LLMInteractionMessage, + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, + LLMInteractionSuccess, +} from "core"; +import { useEffect, useReducer } from "react"; + +declare const vscode: any; + +export type LLMResult = LLMInteractionMessage | LLMInteractionChunk; + +const MAX_GROUP_LENGTH = 32; + +interface ToConsoleViewInit { + type: "init"; + uuid: string; + items: LLMInteractionItem[]; +} + +interface ToConsoleViewItem { + type: "item"; + uuid: string; + item: LLMInteractionItem; +} + +interface ToConsoleViewClear { + type: "clear"; + uuid: string; +} + +type ToConsoleView = ToConsoleViewInit | ToConsoleViewItem | ToConsoleViewClear; + +/** + * Represents a linear list of LLMInteractionItem, transformed into + * a form that is more convenient for rendering. + */ +export interface LLMInteraction { + start?: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim; + + // We use an array-of-arrays for efficiency when rendering a streamed result + // with lots and lots of separate tokens; instead of having a linear list + // of 1024 Result components, we have 32 ResultGroup components each rendering + // 32 Results. + // + // Inline content can split between one group and the next - we'll let the + // browser engine sort that out. + results: LLMResult[][]; + + end?: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel; +} + +export interface LLMLog { + loading: boolean; + interactions: Map; + order: string[]; +} + +/** + * Appends a new result item (chunk or message) to an interaction, + * existing iteractions must already have been copied with + * copyInteractionForMutation(). + */ +function appendItemToInteractionResult( + interaction: LLMInteraction, + item: LLMInteractionMessage | LLMInteractionChunk, +) { + let lastGroup = interaction.results[interaction.results.length - 1]; + + if (lastGroup == undefined || lastGroup.length == MAX_GROUP_LENGTH) { + interaction.results.push([item]); + } else { + lastGroup.push(item); + } +} + +/** + * Makes a copy of an interaction that can be mutated without changing + * any objects/arrays that are part of the old state. We always make + * a copy of the last (open) result group, so that we can simply append + * to it; this is very slightly inefficient for the case where we're + * handling a single end item with no results, but makes things simpler. + */ +function copyInteractionForMutation(oldInteraction: LLMInteraction) { + const oldResults = oldInteraction.results; + let oldLastGroup = oldInteraction.results[oldInteraction.results.length - 1]; + let newResults; + + if (oldLastGroup == undefined || oldLastGroup.length == MAX_GROUP_LENGTH) { + newResults = [...oldInteraction.results]; + } else { + newResults = oldInteraction.results.slice(0, -1); + newResults.push([...oldLastGroup]); + } + + return { ...oldInteraction, results: newResults }; +} + +function appendItemsToLLMLog( + oldLog: LLMLog, + items: LLMInteractionItem[], +): LLMLog { + const oldInteractions = oldLog.interactions; + const newInteractions: Map = new Map(); + let order = oldLog.order; + let interactionsAdded = false; + + // Add the new items to the log, making mutable copies of old + // LLMInteraction as necessary + for (const item of items) { + let interaction = newInteractions.get(item.interactionId); + if (interaction === undefined) { + const oldInteraction = oldInteractions.get(item.interactionId); + if (oldInteraction) { + interaction = copyInteractionForMutation(oldInteraction); + } else { + interaction = { + results: [], + }; + + if (interactionsAdded) { + order.push(item.interactionId); + } else { + order = [...order, item.interactionId]; + interactionsAdded = true; + } + } + newInteractions.set(item.interactionId, interaction); + } + + switch (item.kind) { + case "startChat": + case "startComplete": + case "startFim": + interaction.start = item; + break; + case "chunk": + case "message": + appendItemToInteractionResult(interaction, item); + break; + case "success": + case "error": + case "cancel": + interaction.end = item; + break; + } + } + + // Copy over unchanged interactions + for (const interactionId of oldInteractions.keys()) { + if (!newInteractions.has(interactionId)) { + newInteractions.set(interactionId, oldInteractions.get(interactionId)!); + } + } + + return { + loading: false, + interactions: newInteractions, + order, + }; +} + +/** + * Hook to accumulate log data structures based on messages passed + * from the core. Note that each call site will create an independent + * data structure, so this should be only used once at a toplevel + * component. + * @returns currently log datastructure. + */ +export default function useLLMLog() { + const [llmLog, dispatchLlmLog] = useReducer( + (llmLog: LLMLog, message: ToConsoleView) => { + switch (message.type) { + case "init": + return appendItemsToLLMLog(llmLog, message.items); + case "item": + return appendItemsToLLMLog(llmLog, [message.item]); + case "clear": + return { + loading: false, + interactions: new Map(), + order: [], + }; + } + }, + { + loading: true, + interactions: new Map(), + order: [], + }, + ); + + useEffect(function () { + // The uuid here marks the "generation" when the webview is + // reloaded, so we don't get confused if there are inflight + // messages from the previous generation. In particular, this + // avoids problems when React.StrictMode runs this effect + // twice - we don't want to process two "init" messages. + const uuid = crypto.randomUUID(); + const onMessage = (event: MessageEvent) => { + if (event.data.uuid !== uuid) { + return; + } + + dispatchLlmLog(event.data); + }; + window.addEventListener("message", onMessage); + vscode.postMessage({ type: "start", uuid }); + + return () => { + vscode.postMessage({ type: "stop", uuid }); + window.removeEventListener("message", onMessage); + }; + }, []); + + return llmLog; +} diff --git a/gui/src/hooks/useLLMSummary.ts b/gui/src/hooks/useLLMSummary.ts new file mode 100644 index 000000000..b5016e767 --- /dev/null +++ b/gui/src/hooks/useLLMSummary.ts @@ -0,0 +1,76 @@ +import { useMemo } from "react"; +import { LLMInteraction } from "./useLLMLog"; + +/** + * Hook returning memoized information about single logged prompt/response + * query to the LLM. + */ +export default function useLLMSummary(interaction: LLMInteraction) { + return useMemo(() => { + if (interaction.start == undefined) { + return { + result: "", + type: "", + }; + } + + const type = interaction.start.kind.slice(5); + + let result; + switch (interaction.end?.kind) { + case "cancel": + result = "Cancelled"; + break; + case "error": + result = "Error"; + break; + case "success": + result = "Success"; + break; + case undefined: + result = ""; + } + + let totalTime, + toFirstToken, + tokensPerSecond, + promptTokens, + generatedTokens, + thinkingTokens; + if (interaction.start != undefined && interaction.results.length > 0) { + const firstGroup = interaction.results[0]; + const firstItem = firstGroup ? firstGroup[0] : undefined; + toFirstToken = firstItem + ? firstItem.timestamp - interaction.start.timestamp + : undefined; + } + if (interaction.end != undefined) { + totalTime = interaction.end.timestamp - interaction.start.timestamp; + promptTokens = interaction.end.promptTokens; + generatedTokens = interaction.end.generatedTokens; + thinkingTokens = interaction.end.thinkingTokens; + if (toFirstToken != undefined) { + tokensPerSecond = + (generatedTokens + thinkingTokens) / + ((totalTime - toFirstToken) / 1000); + } + } else { + const lastGroup = interaction.results[interaction.results.length - 1]; + const lastItem = lastGroup ? lastGroup[lastGroup.length - 1] : undefined; + totalTime = lastItem + ? lastItem.timestamp - interaction.start.timestamp + : undefined; + } + + return { + result, + type, + totalTime, + toFirstToken, + tokensPerSecond, + promptTokens, + generatedTokens, + thinkingTokens, + }; + }, [interaction]); +} diff --git a/gui/src/indexConsole.css b/gui/src/indexConsole.css new file mode 100644 index 000000000..c5e41252f --- /dev/null +++ b/gui/src/indexConsole.css @@ -0,0 +1,9 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +html, +body, +#root { + height: 100%; +} diff --git a/gui/vite.config.ts b/gui/vite.config.ts index 6c5cd6d75..22ce4b733 100644 --- a/gui/vite.config.ts +++ b/gui/vite.config.ts @@ -1,4 +1,5 @@ import react from "@vitejs/plugin-react-swc"; +import { resolve } from "path"; import tailwindcss from "tailwindcss"; import { defineConfig } from "vitest/config"; @@ -9,6 +10,10 @@ export default defineConfig({ // Change the output .js filename to not include a hash rollupOptions: { // external: ["vscode-webview"], + input: { + index: resolve(__dirname, "index.html"), + indexConsole: resolve(__dirname, "indexConsole.html"), + }, output: { entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, From e0ee0f63de2508b06e1ec3b6cc7f49bf7d67d0fc Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Wed, 26 Mar 2025 09:21:02 -0400 Subject: [PATCH 44/57] LLMLogFormatter: rich logging to an output stream Add a streaming implementation of rich LLM logging to use if we don't have the webview connected; it converts the LLMInteractionItems into a human-readable stream with timestamps, handling of overlapping interactions, and so forth. Use this for the binary. --- binary/src/index.ts | 4 +- core/llm/logFormatter.test.ts | 315 +++++++++++++++++++++++++ core/llm/logFormatter.ts | 426 ++++++++++++++++++++++++++++++++++ 3 files changed, 744 insertions(+), 1 deletion(-) create mode 100644 core/llm/logFormatter.test.ts create mode 100644 core/llm/logFormatter.ts diff --git a/binary/src/index.ts b/binary/src/index.ts index 08adf99f1..dce9a25ab 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -1,6 +1,7 @@ process.env.IS_BINARY = "true"; import { Command } from "commander"; import { Core } from "core/core"; +import { LLMLogFormatter } from "core/llm/logFormatter"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { IMessenger } from "core/protocol/messenger"; import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths"; @@ -33,7 +34,8 @@ program.action(async () => { const ide = new IpcIde(messenger); const promptLogsPath = getPromptLogsPath(); - new Core(messenger, ide); + const core = new Core(messenger, ide); + new LLMLogFormatter(core.llmLogger, fs.createWriteStream(promptLogsPath)); console.log("[binary] Core started"); } catch (e) { diff --git a/core/llm/logFormatter.test.ts b/core/llm/logFormatter.test.ts new file mode 100644 index 000000000..80aa92068 --- /dev/null +++ b/core/llm/logFormatter.test.ts @@ -0,0 +1,315 @@ +import { Buffer } from "buffer"; +import { Writable } from "stream"; +import { LLMLogFormatter } from "./logFormatter"; +import { LLMLogger } from "./logger"; + +class MemoryWritable extends Writable { + data: Buffer[] = []; + constructor() { + super(); + this.data = []; + } + + _write( + chunk: Buffer, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void { + this.data.push(chunk); + callback(); + } + + getText() { + const decoder = new TextDecoder(); + return decoder.decode(Buffer.concat(this.data as any)); + } +} + +describe("LLMLogFormatter", () => { + it("should format log items correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startChat", + options: { + model: "granite3.2-dense:8b", + }, + messages: [ + { + role: "system", + content: "You are a helpful assistant", + }, + ], + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "world!", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "\nHow can I help you?", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765434100, + kind: "success", + promptTokens: 10, + generatedTokens: 20, + thinkingTokens: 0, + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Chat]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Role: system", + " | You are a helpful assistant", + " +1.0 Role: assistant", + " | Hello, world!", + " +1.2 | How can I help you?", + " +2.0 Success", + " Prompt Tokens: 10", + " Generated Tokens: 20", + "", + ].join("\n"), + ); + }); + + it("should format completion interactions correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startComplete", + options: { + model: "granite3.2-dense:8b", + }, + prompt: "A horse is a horse", + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "chunk", + chunk: ", of course, of course", + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Complete]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Prompt:", + " | A horse is a horse", + " +1.0 Result:", + " | , of course, of course", + ].join("\n"), + ); + }); + + it("should format FIM interactions correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765432100, + kind: "startFim", + options: { + model: "granite3.2-dense:8b", + }, + prefix: "A\nB", + suffix: "D\nE", + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "chunk", + chunk: "C", + }); + + expect(output.getText()).toBe( + [ + " 15:17:12.1 [Fim]", + " Options: {", + ' "model": "granite3.2-dense:8b"', + " }", + " Prefix:", + " | A", + " | B", + " Suffix:", + " | D", + " | E", + " +1.0 Result:", + " | C", + ].join("\n"), + ); + }); + + it("should interleave log items correctly", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output); + + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "2", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "Hello, ", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "World!", + }, + }); + logger._logItem({ + interactionId: "2", + timestamp: 1698765433400, + kind: "message", + message: { + role: "assistant", + content: "World!", + }, + }); + // Check if we end interaction 2 and start another interaction, + // it gets a different prefix marker. + logger._logItem({ + interactionId: "2", + timestamp: 1698765434000, + kind: "success", + promptTokens: 10, + generatedTokens: 20, + thinkingTokens: 0, + }); + logger._logItem({ + interactionId: "3", + timestamp: 1698765434100, + kind: "message", + message: { + role: "assistant", + content: "Hello, World!", + }, + }); + + expect(output.getText()).toBe( + [ + " 15:17:13.1 Role: assistant", + " | Hello, ", + "|15:17:13.2 Role: assistant", + "| | Hello, ", + " +0.2 | World!", + "| +0.2 | World!", + "| +0.8 Success", + "| Prompt Tokens: 10", + "| Generated Tokens: 20", + "&15:17:14.1 Role: assistant", + "& | Hello, World!", + ].join("\n"), + ); + }); + + it("should wrap long lines", () => { + const logger = new LLMLogger(); + const output = new MemoryWritable(); + const formatter = new LLMLogFormatter(logger, output, 40); + + // Test a single message long enough to wrap; the input is + // "", not "xxxx" to make sure we are writing the correct + // substrings. + logger._logItem({ + interactionId: "1", + timestamp: 1698765433100, + kind: "message", + message: { + role: "assistant", + content: "<" + "x".repeat(58) + ">", + }, + }); + // Test when a first message doesn't wrap, but another message + // that continues the same line causes a wrap + logger._logItem({ + interactionId: "1", + timestamp: 1698765433200, + kind: "message", + message: { + role: "assistant", + content: "\n<" + "y".repeat(29), + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433300, + kind: "message", + message: { + role: "assistant", + content: "y".repeat(29) + ">", + }, + }); + logger._logItem({ + interactionId: "1", + timestamp: 1698765433400, + kind: "message", + message: { + role: "assistant", + content: "\n" + "Artichokes and Beans ".repeat(3), + }, + }); + + expect(output.getText()).toBe( + [ + " 15:17:13.1 Role: assistant", + " | <" + "x".repeat(39), + " . " + "x".repeat(19) + ">", + " +0.1 | <" + "y".repeat(39), + " +0.2 . " + "y".repeat(19) + ">", + " +0.3 | Artichokes and Beans Artichokes and", + " . Beans Artichokes and Beans ", + ].join("\n"), + ); + }); +}); diff --git a/core/llm/logFormatter.ts b/core/llm/logFormatter.ts new file mode 100644 index 000000000..cae469f77 --- /dev/null +++ b/core/llm/logFormatter.ts @@ -0,0 +1,426 @@ +import { Writable } from "stream"; +import { + AssistantChatMessage, + ChatMessage, + LLMInteractionCancel, + LLMInteractionError, + LLMInteractionItem, + LLMInteractionStartChat, + LLMInteractionStartComplete, + LLMInteractionStartFim, + LLMInteractionSuccess, + ThinkingChatMessage, + ToolCallDelta, + UserChatMessage, +} from ".."; +import { LLMLogger } from "./logger"; + +// Markers for different overlapping interactions. +const LOG_PREFIXES = [" ", "|", "&", "%", "#"]; +// Wrap wide to avoid messing up code +const DEFAULT_WRAP_WIDTH = 100; + +interface InteractionData { + prefix: string; + startItem: LLMInteractionItem; + lastItem: LLMInteractionItem | null; +} + +function formatTimestamp(timestamp: number) { + const date = new Date(timestamp); + + const hours = date.getUTCHours().toString().padStart(2, "0"); + const minutes = date.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date.getUTCSeconds(); + const milliseconds = date.getUTCMilliseconds(); + + // Format seconds with one decimal place + const secondsFormatted = `${seconds}.${Math.floor(milliseconds / 100)}`; + + return `${hours}:${minutes}:${secondsFormatted.padStart(4, "0")}`; +} + +/** + * A class that formats LLM log output as a human-readable stream. + * The general appearance of the output is something like: + * + * 01:23:45.6 [Chat] + * Options: { + * "maxTokens": 1000, + * } + * Role: system + * | You are a helpful assistant. + * Role: user + * | Who are you? + * +0.2 Role: assistant + * | How can I help you today? + * +0.3 | I can tell you about the weather or the stock mark + * +0.4 . et. [THIS LINE IS WRAPPED] + * |01:23:46.1 [Complete] + * | Options: { + * | "maxTokens": 1000, + * | } + * | Prefix: + * | | COMPLETE THIS + * +0.6 Success + * PromptTokens: 50 + * GeneratedTokens: 30 + * | +0.2 Result: + * | | COMPLETION + * + * The lines with | are a second interaction that starts while the + * first one is still in progress; every interaction starts with + * an absolute timestamp, and relative timestamps are included for + * separately received results in the same interaction. + */ +export class LLMLogFormatter { + // Current active interactions + private interactions: Record = {}; + private lastItem: LLMInteractionItem | null = null; + // Item that started the current line; we use this to determine + // if the next line needs a timestamp. + private lastLineStartItem: LLMInteractionItem | null = null; + private openLine: boolean = false; + private openLineChars: number = 0; + private lastFreedPrefix: string | null = null; + + /** + * Creates a new LLMLogWriter. + * @param logger - The LLMLogger instance to listen to for log items + * @param output - Stream to write formatted output to + * @param wrapWidth - Maximum width of a line before wrapping + */ + constructor( + private logger: LLMLogger, + private output: Writable, + private wrapWidth: number = DEFAULT_WRAP_WIDTH, + ) { + this.logger.onLogItem((item) => { + this.logItem(item); + }); + } + + private getInteractionData(item: LLMInteractionItem) { + let interaction = this.interactions[item.interactionId]; + if (interaction !== undefined) { + return interaction; + } + + let usedPrefixes = Object.values(this.interactions).map( + (interaction) => interaction.prefix, + ); + + // Select a prefix that is not currently in use, and is + // also not the last retired prefix - but with the + // exception that we can reuse the empty prefix " " + // immediately - this isn't confusing. + let i = 0; + let prefix; + while (true) { + const candidate = i < LOG_PREFIXES.length ? LOG_PREFIXES[i] : `X`; + if ( + !usedPrefixes.includes(candidate) && + (candidate === " " || candidate !== this.lastFreedPrefix) + ) { + prefix = candidate; + break; + } + i++; + } + + this.interactions[item.interactionId] = { + prefix, + startItem: item, + lastItem: null, + }; + + return this.interactions[item.interactionId]; + } + + private formatTimestamp( + interaction: InteractionData, + item: LLMInteractionItem, + ) { + if (item !== this.lastLineStartItem) { + if (item === interaction.startItem) { + return formatTimestamp(item.timestamp); + } else { + const delta = (item.timestamp - interaction.startItem.timestamp) / 1000; + return ("+" + delta.toFixed(1)).padStart(10, " "); + } + } else { + return " "; + } + } + + // the implementation behind logLines and logMessageText + private logFragment( + item: LLMInteractionItem, + fragment: string, + startAt: number, + marker: string = "", + joinBefore: boolean = false, + joinAfter: boolean = false, + wrap: boolean = false, + ) { + const interaction = this.getInteractionData(item); + + if ( + this.openLine && + (!joinBefore || item.interactionId !== this.lastItem?.interactionId) + ) { + this.openLine = false; + this.openLineChars = 0; + this.output.write("\n"); + } + + let continueAt = null; + if ( + wrap && + fragment.length - startAt > this.wrapWidth - this.openLineChars + ) { + continueAt = startAt + this.wrapWidth - this.openLineChars; + + // Look for a better line-breaking point at whitespace + const searchBackwardLimit = Math.max(startAt, continueAt - 20); // Don't look back too far + for (let i = continueAt; i > searchBackwardLimit; i--) { + if (/\s/.test(fragment.charAt(i))) { + continueAt = i + 1; // Break after the whitespace + break; + } + } + + // When there's whitespace immediately after the wrap width, + // the above will result in breaking *after* that, so we exceed + // the wrap width. The trimEnd() avoids that. + fragment = fragment.substring(startAt, continueAt).trimEnd(); + joinAfter = false; + } else if (startAt > 0) { + fragment = fragment.substring(startAt); + } + + if (!this.openLine || !this.openLine) { + let timestamp = this.formatTimestamp(interaction, item); + this.output.write(`${interaction.prefix}${timestamp} ${marker}`); + this.lastLineStartItem = item; + } + + this.output.write(fragment); + this.openLine = joinAfter; + this.lastItem = item; + if (!this.openLine) { + this.output.write("\n"); + this.openLineChars = 0; + } else { + this.openLineChars += fragment.length; + } + + return continueAt; + } + + // Use for everything but text content; a newline is + // implicitly added at the end of content + private logLines( + item: LLMInteractionItem, + content: string, + marker: string = "", + ) { + for (const line of content.split("\n")) { + this.logFragment(item, line, 0, marker); + } + } + + // This logs text context - as compared to logLines: + // - No newline is appended to the end of content + // - consecutive calls to logMessageText for the same interaction + // will join onto a single line + // - It will wrap text at the wrap width + private logMessageText(item: LLMInteractionItem, content: string) { + const lines = content.split("\n"); + for (let i = 0; i < lines.length; i++) { + let startAt: number | null = 0; + let marker = "| "; + while (startAt !== null) { + // When wrapping, the next start position is turned; + // null means we've written everything + startAt = this.logFragment( + item, + lines[i], + startAt, + marker, + true, + i === lines.length - 1, + true, + ); + marker = ". "; + } + } + } + + private logToolcalls(item: LLMInteractionItem, toolsCalls: ToolCallDelta[]) { + for (const toolCall of toolsCalls) { + this.logLines( + item, + `Tool call: ${JSON.stringify(toolCall, undefined, 2)}`, + ); + } + } + + private logMessageContent( + item: LLMInteractionItem, + message: AssistantChatMessage | UserChatMessage | ThinkingChatMessage, + ) { + if (typeof message.content === "string") { + this.logMessageText(item, message.content); + } else { + for (const part of message.content) { + if (part.type === "text") { + this.logMessageText(item, part.text); + } else { + this.logLines(item, `Image: ${part.imageUrl.url}`); + } + } + } + } + + private logMessage( + item: LLMInteractionItem, + message: ChatMessage, + forceRole: boolean = false, + ) { + let showRole = true; + if ( + !forceRole && + (message.role === "assistant" || message.role === "thinking") + ) { + const interaction = this.getInteractionData(item); + const lastMessage = + interaction.lastItem?.kind === "message" + ? interaction.lastItem.message + : null; + if (message.role === lastMessage?.role) { + showRole = false; + } + } + + if (showRole) { + this.logLines(item, "Role: " + message.role); + } + + switch (message.role) { + case "assistant": + if (message.toolCalls) { + this.logToolcalls(item, message.toolCalls); + } + this.logMessageContent(item, message); + break; + case "thinking": + if (message.toolCalls) { + this.logToolcalls(item, message.toolCalls); + } + this.logMessageContent(item, message); + if (message.redactedThinking) { + this.logLines(item, `Redacted Thinking: ${message.redactedThinking}`); + } + if (message.signature) { + this.logLines(item, `Signature: ${message.signature}`); + } + break; + case "user": + this.logMessageContent(item, message); + break; + case "system": + this.logMessageText(item, message.content); + break; + case "tool": + this.logLines(item, `Tool Call ID: ${message.toolCallId}`); + this.logMessageText(item, message.content); + break; + } + } + + private logTokens( + item: LLMInteractionSuccess | LLMInteractionError | LLMInteractionCancel, + ) { + this.logLines(item, `Prompt Tokens: ${item.promptTokens}`); + this.logLines(item, `Generated Tokens: ${item.generatedTokens}`); + if (item.thinkingTokens > 0) { + this.logLines(item, `Thinking Tokens: ${item.thinkingTokens}`); + } + } + + private logOptions( + item: + | LLMInteractionStartChat + | LLMInteractionStartComplete + | LLMInteractionStartFim, + ) { + this.logLines( + item, + "Options: " + JSON.stringify(item.options, undefined, 2), + ); + } + + private logItem(item: LLMInteractionItem) { + const interaction = this.getInteractionData(item); + + switch (item.kind) { + case "startChat": + this.logLines(item, "[Chat]"); + this.logOptions(item); + let lastMessage = null; + for (let message of item.messages) { + this.logMessage(item, message, true); + } + break; + case "startComplete": + this.logLines(item, "[Complete]"); + this.logOptions(item); + this.logLines(item, "Prompt:"); + this.logLines(item, item.prompt, "| "); + break; + case "startFim": + this.logLines(item, "[Fim]"); + this.logOptions(item); + this.logLines(item, "Prefix:"); + this.logLines(item, item.prefix, "| "); + this.logLines(item, "Suffix:"); + this.logLines(item, item.suffix, "| "); + break; + case "chunk": + if (interaction.lastItem?.kind !== "chunk") { + this.logLines(item, "Result:"); + } + this.logMessageText(item, item.chunk); + break; + case "message": + this.logMessage(item, item.message); + break; + case "cancel": + this.logLines(item, "Cancelled"); + this.logTokens(item); + break; + case "error": + this.logLines(item, "Error"); + this.logTokens(item); + break; + case "success": + this.logLines(item, "Success"); + this.logTokens(item); + break; + } + + if ( + item.kind === "cancel" || + item.kind === "error" || + item.kind === "success" + ) { + if (interaction.prefix !== " ") { + this.lastFreedPrefix = interaction.prefix; + } + delete this.interactions[item.interactionId]; + } else { + interaction.lastItem = item; + } + } +} From ffec6c6b5d161c1b45d84bf3c16221755601caff Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Tue, 1 Apr 2025 13:30:09 -0400 Subject: [PATCH 45/57] Console: limit number of interactions that we retain Only retain and display the 50 most recent interactions; this prevents the stored items from growing without bound if the user is using the vscode instance to edit for a long time. --- .../src/ContinueConsoleWebviewViewProvider.ts | 81 +++++++++++++++---- gui/src/hooks/useLLMLog.ts | 29 ++++++- 2 files changed, 93 insertions(+), 17 deletions(-) diff --git a/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts index a509b6e70..6427091ff 100644 --- a/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueConsoleWebviewViewProvider.ts @@ -10,6 +10,10 @@ interface FromConsoleView { uuid: string; } +// Maximum interactions we retain; when we exceed this, we drop the +// oldest and also send a message to the view to do the same. +const MAX_INTERACTIONS = 50; + export class ContinueConsoleWebviewViewProvider implements vscode.WebviewViewProvider { @@ -36,7 +40,7 @@ export class ContinueConsoleWebviewViewProvider this._webview?.postMessage({ type: "init", uuid: this._currentUuid, - items: this._items, + items: this.getAllItems(), }); } }); @@ -50,7 +54,8 @@ export class ContinueConsoleWebviewViewProvider private _webview?: vscode.Webview; private _webviewView?: vscode.WebviewView; private _currentUuid?: string; - private _items: LLMInteractionItem[] = []; + private _currentInteractions = new Map(); + private _completedInteractions: LLMInteractionItem[][] = []; private _saveLog; constructor( @@ -71,24 +76,68 @@ export class ContinueConsoleWebviewViewProvider } }); - llmLogger.onLogItem((item) => { - if (!this._saveLog) { - return; - } + llmLogger.onLogItem((item) => this.addItem(item)); + } - this._items.push(item); - if (this._currentUuid) { - this._webview?.postMessage({ - type: "item", - uuid: this._currentUuid, - item, - }); - } - }); + private addItem(item: LLMInteractionItem) { + if (!this._saveLog) { + return; + } + + let iteractionItems = this._currentInteractions.get(item.interactionId); + if (iteractionItems === undefined) { + iteractionItems = []; + this._currentInteractions.set(item.interactionId, iteractionItems); + } + + iteractionItems.push(item); + switch (item.kind) { + case "success": + case "cancel": + case "error": + this._completedInteractions.push(iteractionItems); + this._currentInteractions.delete(item.interactionId); + break; + default: + break; + } + + if (this._currentUuid) { + this._webview?.postMessage({ + type: "item", + uuid: this._currentUuid, + item, + }); + } + + while ( + this._completedInteractions.length > 0 && + this._completedInteractions.length + this._currentInteractions.size > + MAX_INTERACTIONS + ) { + let toRemove = this._completedInteractions.shift(); + this._webview?.postMessage({ + type: "remove", + uuid: this._currentUuid, + interactionId: toRemove![0].interactionId, + }); + } + } + + private getAllItems() { + let items = this._completedInteractions.flat(); + + for (const interactionItems of this._currentInteractions.values()) { + items.push(...interactionItems); + } + + return items; } clearLog() { - this._items = []; + this._completedInteractions = []; + this._currentInteractions = new Map(); + if (this._currentUuid) { this._webview?.postMessage({ type: "clear", diff --git a/gui/src/hooks/useLLMLog.ts b/gui/src/hooks/useLLMLog.ts index 0df2c56e1..3b20d1628 100644 --- a/gui/src/hooks/useLLMLog.ts +++ b/gui/src/hooks/useLLMLog.ts @@ -29,12 +29,22 @@ interface ToConsoleViewItem { item: LLMInteractionItem; } +interface ToConsoleViewRemove { + type: "remove"; + uuid: string; + interactionId: string; +} + interface ToConsoleViewClear { type: "clear"; uuid: string; } -type ToConsoleView = ToConsoleViewInit | ToConsoleViewItem | ToConsoleViewClear; +type ToConsoleView = + | ToConsoleViewInit + | ToConsoleViewItem + | ToConsoleViewRemove + | ToConsoleViewClear; /** * Represents a linear list of LLMInteractionItem, transformed into @@ -168,6 +178,21 @@ function appendItemsToLLMLog( }; } +function removeInteractionFromLLMLog( + llmLog: LLMLog, + interactionId: string, +): LLMLog { + const newInteractions = new Map(llmLog.interactions); + newInteractions.delete(interactionId); + const newOrder = llmLog.order.filter((id) => id !== interactionId); + + return { + loading: false, + interactions: newInteractions, + order: newOrder, + }; +} + /** * Hook to accumulate log data structures based on messages passed * from the core. Note that each call site will create an independent @@ -183,6 +208,8 @@ export default function useLLMLog() { return appendItemsToLLMLog(llmLog, message.items); case "item": return appendItemsToLLMLog(llmLog, [message.item]); + case "remove": + return removeInteractionFromLLMLog(llmLog, message.interactionId); case "clear": return { loading: false, From 25ee72e8fbbe9871823462d4e8bd72de36a5a6c3 Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Mon, 7 Apr 2025 13:57:03 -0400 Subject: [PATCH 46/57] e2e: select quick picks based on strings, not harcoded indexes Selecting the 14th view container ran into problems when an (emty) Continue Console view container was added. This also changes it to move to new secondary sidebar container rather than reusing one from Copilot. --- extensions/vscode/e2e/actions/GUI.actions.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index ace296ca3..ef2bf0c16 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -16,8 +16,12 @@ export class GUIActions { await GUIActions.toggleGui(); await TestUtils.waitForSuccess(async () => { await new Workbench().executeCommand("View: Move View"); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(4); - await (await InputBox.create(DEFAULT_TIMEOUT.MD)).selectQuickPick(14); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("Continue"); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("New Secondary Side Bar Entry"); }); // first call focuses the input From d174689ee22318cf83c3b87013262234c991ea71 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 7 Apr 2025 12:36:54 -0700 Subject: [PATCH 47/57] Update LlamaCpp.ts --- core/llm/llms/LlamaCpp.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index a8b7e08b3..4833405ae 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM { ...this.requestOptions?.headers, }; - const resp = await this.fetch(new URL("completion", this.apiBase), { + const resp = await this.fetch(new URL("completions", this.apiBase), { method: "POST", headers, body: JSON.stringify({ From eeaf3ba6434d6c48d9a55ea1122c4a1f074ed607 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 7 Apr 2025 12:39:09 -0700 Subject: [PATCH 48/57] remove vscode-webview package --- gui/package-lock.json | 54 +-------------------------------- gui/package.json | 4 +-- gui/src/context/IdeMessenger.ts | 1 - gui/vite.config.ts | 1 - 4 files changed, 2 insertions(+), 58 deletions(-) diff --git a/gui/package-lock.json b/gui/package-lock.json index df7ea183b..69c571f84 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -25,7 +25,6 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", @@ -63,8 +62,7 @@ "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", @@ -3237,11 +3235,6 @@ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==" }, - "node_modules/@types/vscode-webview": { - "version": "1.57.5", - "resolved": "https://registry.npmjs.org/@types/vscode-webview/-/vscode-webview-1.57.5.tgz", - "integrity": "sha512-iBAUYNYkz+uk1kdsq05fEcoh8gJmwT3lqqFPN7MGyjQ3HVloViMdo7ZJ8DFIP8WOK74PjOEilosqAyxV2iUFUw==" - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.16.0.tgz", @@ -5960,19 +5953,6 @@ "url": "https://github.com/sponsors/rawify" } }, - "node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -6176,11 +6156,6 @@ "url": "https://github.com/sindresorhus/got?sponsor=1" } }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" - }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -7667,17 +7642,6 @@ "node": ">=6" } }, - "node_modules/jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", - "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -12180,14 +12144,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "engines": { - "node": ">= 10.0.0" - } - }, "node_modules/update-browserslist-db": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", @@ -13429,14 +13385,6 @@ } } }, - "node_modules/vscode-webview": { - "version": "1.0.1-beta.1", - "resolved": "https://registry.npmjs.org/vscode-webview/-/vscode-webview-1.0.1-beta.1.tgz", - "integrity": "sha512-8H2icqlb93qIvZs7Me/0sALMqJrX2e2W7JVE0mfK8exUPETP9Bmg+feivaByd1Xbg78lcKaNF9ZRrIFSenUVxQ==", - "dependencies": { - "fs-extra": "^10.0.0" - } - }, "node_modules/w3c-keyname": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", diff --git a/gui/package.json b/gui/package.json index fa4b439af..2d4ed109b 100644 --- a/gui/package.json +++ b/gui/package.json @@ -33,7 +33,6 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", - "@types/vscode-webview": "^1.57.1", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", @@ -71,8 +70,7 @@ "tailwind-merge": "^3.0.2", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", - "uuid": "^9.0.1", - "vscode-webview": "^1.0.1-beta.1" + "uuid": "^9.0.1" }, "devDependencies": { "@swc/cli": "^0.3.14", diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index c2e848446..4d0258efd 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -15,7 +15,6 @@ import { } from "core/protocol/util"; import { createContext } from "react"; import { v4 as uuidv4 } from "uuid"; -import "vscode-webview"; import { isJetBrains } from "../util"; interface vscode { diff --git a/gui/vite.config.ts b/gui/vite.config.ts index 6c5cd6d75..50c8d6495 100644 --- a/gui/vite.config.ts +++ b/gui/vite.config.ts @@ -8,7 +8,6 @@ export default defineConfig({ build: { // Change the output .js filename to not include a hash rollupOptions: { - // external: ["vscode-webview"], output: { entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, From 7aada94288fc8984b19a25fad1fb8658711c4f77 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 20:07:41 +0000 Subject: [PATCH 49/57] build(deps): bump estree-util-value-to-estree in /docs Bumps [estree-util-value-to-estree](https://github.com/remcohaszing/estree-util-value-to-estree) from 3.2.1 to 3.3.3. - [Release notes](https://github.com/remcohaszing/estree-util-value-to-estree/releases) - [Commits](https://github.com/remcohaszing/estree-util-value-to-estree/compare/v3.2.1...v3.3.3) --- updated-dependencies: - dependency-name: estree-util-value-to-estree dependency-version: 3.3.3 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- docs/package-lock.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/package-lock.json b/docs/package-lock.json index f9c2ca21c..deb0071b8 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -8022,9 +8022,10 @@ } }, "node_modules/estree-util-value-to-estree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.2.1.tgz", - "integrity": "sha512-Vt2UOjyPbNQQgT5eJh+K5aATti0OjCIAGc9SgMdOFYbohuifsWclR74l0iZTJwePMgWYdX1hlVS+dedH9XV8kw==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/estree-util-value-to-estree/-/estree-util-value-to-estree-3.3.3.tgz", + "integrity": "sha512-Db+m1WSD4+mUO7UgMeKkAwdbfNWwIxLt48XF2oFU9emPfXkIu+k5/nlOj313v7wqtAPo0f9REhUvznFrPkG8CQ==", + "license": "MIT", "dependencies": { "@types/estree": "^1.0.0" }, From 1611bae1fbc8bf34feedca858403bc4e10ea9566 Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 7 Apr 2025 17:06:46 -0400 Subject: [PATCH 50/57] Forbid file mentioning for large files When the context items provided by user overflow the context length and are truncated, it is very confusing for the user. This is a first step that catches an common case at the least confusing time - when the user is selecting a file. A more general check that warns whenever the most recent message is truncated is something that can be added later. Granite-Code/granite-code#22 --- core/core.ts | 21 ++++ core/protocol/core.ts | 4 + core/protocol/passThrough.ts | 1 + .../constants/MessageTypes.kt | 1 + .../mainInput/AtMentionDropdown/index.tsx | 112 +++++++++++++++++- 5 files changed, 138 insertions(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index f948491fc..81afbcbb9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -22,6 +22,7 @@ import { DataLogger } from "./data/log"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { countTokens } from "./llm/countTokens"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -888,6 +889,26 @@ export class Core { return { contextItems }; }); + + on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + const { config } = await this.configHandler.loadConfig(); + + if (!config) { + return false; + } + + const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + + // Count the size of the file tokenwise + const tokens = countTokens(item.content); + + // File exceeds context length of the model + if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { + return true; + } + + return false; + }); } private indexingCancellationController: AbortController | undefined; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 0213cd0e5..7f29c2e25 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -196,4 +196,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; + isItemTooBig: [ + { item: ContextItemWithId; selectedModelTitle: string | undefined }, + boolean, + ]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 272a6d148..9564f557d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -59,6 +59,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "isItemTooBig", ]; // Message types to pass through from core to webview diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 60d2d3b33..5d17fbe6c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -126,6 +126,7 @@ class MessageTypes { "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "isItemTooBig", ) } } \ No newline at end of file diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index beeb37070..c028b7a87 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -5,6 +5,7 @@ import { PlusIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; +import { RangeInFile } from "core"; import { forwardRef, useContext, @@ -24,6 +25,7 @@ import { vscQuickInputBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useAppSelector } from "../../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -138,11 +140,31 @@ interface AtMentionDropdownProps { onClose: () => void; } +const formatFileSize = (fileSize: number) => { + const KB = 1000; + const MB = 1000_000; + const GB = 1000_000_000; + + if (fileSize > GB) { + return `${(fileSize / GB).toFixed(1)} GB`; + } else if (fileSize > MB) { + return `${(fileSize / MB).toFixed(1)} MB`; + } else if (fileSize > KB) { + return `${(fileSize / KB).toFixed(1)} KB`; + } + + return `${fileSize} byte${fileSize > 1 ? "s" : ""}`; +}; + const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); + const selectedModelTitle = useAppSelector( + (store) => store.config.defaultModelTitle, + ); + const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -157,6 +179,88 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const [allItems, setAllItems] = useState([]); + async function isItemTooBig( + name: string, + query: string, + ): Promise<[boolean, number]> { + const selectedCode: RangeInFile[] = []; + // Get context item from core + const contextResult = await ideMessenger.request( + "context/getContextItems", + { + name, + query, + fullInput: "", + selectedCode, + selectedModelTitle: selectedModelTitle ?? "", + }, + ); + + if (contextResult.status === "error") { + return [false, -1]; + } + + const item = contextResult.content[0]; + + // Check if the context item exceeds the context length of the selected model + const result = await ideMessenger.request("isItemTooBig", { + item, + selectedModelTitle: selectedModelTitle, + }); + + if (result.status === "error") { + return [false, -1]; + } + + const size = new Blob([item.content]).size; + + return [result.content, size]; + } + + function handleItemTooBig( + fileExceeds: boolean, + fileSize: number, + item: ComboBoxItem, + ) { + if (fileExceeds) { + props.editor + .chain() + .focus() + .command(({ tr, state }) => { + const text = state.doc.textBetween( + 0, + state.selection.from, + "\n", + "\n", + ); // Get the text before the cursor + const lastAtIndex = text.lastIndexOf("@"); + + if (lastAtIndex !== -1) { + // Delete text after the last "@" + tr.delete(lastAtIndex + 1, state.selection.from); + return true; + } + return false; + }) + .run(); + + // Trigger warning message + ideMessenger.ide.showToast( + "warning", + fileSize > 0 ? "File exceeds context length" : "Can't load the file", + { + modal: true, + detail: + fileSize > 0 + ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model` + : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, + }, + ); + } else { + props.command({ ...item, itemType: item.type }); + } + } + useEffect(() => { const items = [...props.items]; if (subMenuTitle === "Type to search docs") { @@ -243,7 +347,13 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { } if (item) { - props.command({ ...item, itemType: item.type }); + if (item.type === "file" && item.query) { + isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) => + handleItemTooBig(fileExceeds, fileSize, item), + ); + } else { + props.command({ ...item, itemType: item.type }); + } } }; From 01d0b4e58b5073884e79c0dc162ece372ca24432 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 8 Apr 2025 10:58:28 +0530 Subject: [PATCH 51/57] remove options --- .github/workflows/pr_checks.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 1dd652de9..c7e37773a 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -632,6 +632,4 @@ jobs: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: - # allowed-failures: - # allowed-skips: jobs: ${{ toJSON(needs) }} From b6592d37a49b58a85dfd14f22bdf901f30a46faa Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 8 Apr 2025 17:55:31 +0530 Subject: [PATCH 52/57] fix code block preview needing to click twice to hide --- .../components/ExpandableToolbarPreview.tsx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index 16e959ebb..8aa9560d2 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -118,23 +118,20 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { props.itemId, props.initiallyHidden, ]); - const [hidden, setHidden] = useState(calculatedInitiallyHidden); const [isExpanded, setIsExpanded] = useState(false); // Track if user has manually toggled visibility - const [userToggled, setUserToggled] = useState(false); - const contentRef = useRef(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); useEffect(() => { - // Only update hidden state from props if user hasn't manually toggled - // or if initiallyHidden isn't explicitly set to false - if (!userToggled || props.initiallyHidden !== false) { + // Only update hidden state from props if initiallyHidden isn't explicitly set to false + if (props.initiallyHidden !== false) { setHidden(calculatedInitiallyHidden); } - }, [calculatedInitiallyHidden, userToggled, props.initiallyHidden]); + }, [calculatedInitiallyHidden, props.initiallyHidden]); + useEffect(() => { const resizeObserver = new ResizeObserver(() => { setContentDims({ @@ -166,7 +163,6 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { fontSize: getFontSize() - 3, }} onClick={() => { - setUserToggled(true); setHidden(!hidden); }} > From ba28e703107bc2faab2c65687567d001da9977eb Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 8 Apr 2025 18:04:59 +0530 Subject: [PATCH 53/57] revert accidental unwanted change --- .../TipTapEditor/components/ExpandableToolbarPreview.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index 8aa9560d2..4e5c1775c 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -118,6 +118,7 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { props.itemId, props.initiallyHidden, ]); + const [hidden, setHidden] = useState(calculatedInitiallyHidden); const [isExpanded, setIsExpanded] = useState(false); From 9ee0f3d4eff7e6f90dbf679d743196c9c93f29b3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 8 Apr 2025 18:06:17 +0530 Subject: [PATCH 54/57] remove accidental change --- .../TipTapEditor/components/ExpandableToolbarPreview.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index 4e5c1775c..db923f59b 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -122,7 +122,6 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { const [hidden, setHidden] = useState(calculatedInitiallyHidden); const [isExpanded, setIsExpanded] = useState(false); - // Track if user has manually toggled visibility const contentRef = useRef(null); const [contentDims, setContentDims] = useState({ width: 0, height: 0 }); From e77aaf0b72ab0b6f751fcb9dfe538691847b93b1 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Tue, 8 Apr 2025 08:41:07 -0700 Subject: [PATCH 55/57] Update package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 6ac6afd30..3948b3c8e 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.21", + "version": "1.1.22", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From dffdfd790e40ce8978914444b9f8dc7d7fc43865 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 8 Apr 2025 08:51:49 -0700 Subject: [PATCH 56/57] Update reference.md --- docs/docs/reference.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 757cfa13e..b9ae84846 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -142,6 +142,7 @@ The `models` section defines the language models used in your configuration. Mod - `name` (**required**): A unique name to identify the model within your configuration. - `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). - `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). +- `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: From 481d60a74d9b7cd0492aa5875d89e5b4e2e00c51 Mon Sep 17 00:00:00 2001 From: Sahil Date: Tue, 8 Apr 2025 22:05:29 +0530 Subject: [PATCH 57/57] fix: Use MCP server_name from JSON config as display name --- packages/config-yaml/src/converter.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/config-yaml/src/converter.ts b/packages/config-yaml/src/converter.ts index 13f54cb8c..84786c880 100644 --- a/packages/config-yaml/src/converter.ts +++ b/packages/config-yaml/src/converter.ts @@ -70,13 +70,13 @@ function convertCustomCommand( function convertMcp(mcp: any): NonNullable[number] { const { transport } = mcp; - const { command, args, env } = transport; + const { command, args, env, server_name } = transport; return { command, args, env, - name: "MCP Server", + name: server_name || "MCP Server", }; }