From b8de35cd8a4e0c0b3ba398ea8601be6701eb8e41 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Apr 2025 15:30:41 -0700 Subject: [PATCH 01/14] 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/14] 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 be22741fc0fa0c564b314aa74565bc3c16a00359 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 10:06:53 -0700 Subject: [PATCH 03/14] 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 fd3db4a01a43d3c18f69062dc8cdcea4ed8a8364 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 13:40:58 -0700 Subject: [PATCH 04/14] 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 05/14] 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 06/14] 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 07/14] 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 08/14] 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 09/14] 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 10/14] 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 11/14] 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 12/14] 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 13/14] 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 8eb97b167b6e600196ef2e8467ca5ded8737e771 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 6 Apr 2025 16:53:39 -0700 Subject: [PATCH 14/14] 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 - - +
+ + +
+ ); }