diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 031075e90..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.listProfiles(); + 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"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 3a3c81fab..8b469d437 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,32 +25,31 @@ import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; 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; -// Separately manages saving/reloading each profile - 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; controlPlaneClient: ControlPlaneClient; + private readonly globalContext = new GlobalContext(); + private globalLocalProfileManager: ProfileLifecycleManager; - initializedPromise: Promise; + private organizations: OrgWithProfiles[] = []; + currentProfile: ProfileLifecycleManager | null; + currentOrg: OrgWithProfiles; constructor( private readonly ide: IDE, private ideSettingsPromise: Promise, private readonly writeLog: (text: string) => Promise, sessionInfoPromise: Promise, - private readonly didSelectOrganization?: (orgId: string | null) => void, ) { this.ide = ide; this.ideSettingsPromise = ideSettingsPromise; @@ -60,34 +59,233 @@ export class ConfigHandler { ideSettingsPromise, ); - // Set local profile as default - const localProfileLoader = new LocalProfileLoader( - ide, - ideSettingsPromise, - this.controlPlaneClient, - writeLog, - ); - this.localProfileManager = new ProfileLifecycleManager( - localProfileLoader, + // This profile manager will always be available + this.globalLocalProfileManager = new ProfileLifecycleManager( + 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 default personal org with local profile manager + this.currentProfile = this.globalLocalProfileManager; + const personalOrg: OrgWithProfiles = { + currentProfile: this.globalLocalProfileManager, + profiles: [this.globalLocalProfileManager], + ...this.PERSONAL_ORG_DESC, + }; + + this.currentOrg = personalOrg; + this.organizations = [personalOrg]; + + void this.cascadeInit(); } - /** - * Users can define as many local assistants as they want in a `.continue/assistants` folder - */ - private async getLocalAssistantProfiles() { + private workspaceDirs: string[] | null = null; + async getWorkspaceId() { + if (!this.workspaceDirs) { + this.workspaceDirs = await this.ide.getWorkspaceDirs(); + } + return this.workspaceDirs.join("&"); + } + + async getProfileKey(orgId: string) { + const workspaceId = await this.getWorkspaceId(); + return `${workspaceId}:::${orgId}`; + } + + private async cascadeInit() { + this.workspaceDirs = null; // forces workspace dirs reload + + const orgs = await this.getOrgs(); + + // Figure out selected org + const workspaceId = await this.getWorkspaceId(); + const selectedOrgs = + this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {}; + const currentSelection = selectedOrgs[workspaceId]; + + 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.organizations = orgs; + this.currentOrg = selectedOrg; + this.currentProfile = selectedOrg.currentProfile; + await this.reloadConfig(); + } + + private async getOrgs(): Promise { + const userId = await this.controlPlaneClient.userId; + if (userId) { + const orgDescs = await this.controlPlaneClient.listOrganizations(); + if (await useHub(this.ideSettingsPromise)) { + const personalHubOrg = await this.getPersonalHubOrg(); + const hubOrgs = await Promise.all( + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ); + 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))); + } + } 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); + + 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, + orgScopeId, + ); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); + } + + private async getNonPersonalHubOrg( + org: OrganizationDescription, + ): Promise { + const profiles = await this.getHubProfiles(org.id); + return this.rectifyProfilesForOrg(org, profiles); + } + + private PERSONAL_ORG_DESC: OrganizationDescription = { + iconUrl: "", + id: "personal", + name: "Personal", + slug: undefined, + }; + private async getPersonalHubOrg() { + const allLocalProfiles = await this.getAllLocalProfiles(); + 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(this.PERSONAL_ORG_DESC, allLocalProfiles); + } + + 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), + ); + + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + }); + return this.rectifyProfilesForOrg(org, profiles); + } + + private async rectifyProfilesForOrg( + org: OrganizationDescription, + profiles: ProfileLifecycleManager[], + ): Promise { + const profileKey = await this.getProfileKey(org.id); + const selectedProfiles = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + + const currentSelection = selectedProfiles[profileKey]; + + 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() { + /** + * 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( @@ -98,287 +296,27 @@ export class ConfigHandler { assistant, ); }); - return profiles.map( + const localAssistantProfiles = profiles.map( (profile) => new ProfileLifecycleManager(profile, this.ide), ); + return [this.globalLocalProfileManager, ...localAssistantProfiles]; } - /** - * 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); + ////////////////// + // External actions that can cause a cascading config refresh + // Should not be used internally + ////////////////// + async refreshAll() { + await this.cascadeInit(); } - 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(); - } - - try { - const configResult = await this.loadConfig(); - this.notifyConfigListeners(configResult); - } catch (e) { - console.error("Failed to load config: ", e); - } - } - - 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; - 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()); - await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); - } - } - - async listOrganizations() { - return await this.controlPlaneClient.listOrganizations(); - } - - async loadAssistantsForSelectedOrg() { - // 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 - const assistants = - await this.controlPlaneClient.listAssistants(selectedOrgId); - - const hubProfiles = 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, - selectedOrgId, - ); - - return new ProfileLifecycleManager(profileLoader, this.ide); - }), - ); - - if (selectedOrgId === null) { - // Personal - const allLocalProfiles = await this.getAllLocalProfiles(); - profiles = [...hubProfiles, ...allLocalProfiles]; - } else { - // Organization - profiles = hubProfiles; - } - } - - await this.updateAvailableProfiles(profiles); - } - - 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; - } - } - - 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 { - 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)); - }); - - await this.updateAvailableProfiles(profiles); - } catch (e: any) { - console.error("Failed to load profiles: ", e); - await this.loadLocalProfilesOnly(); - } - } - } - - 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) { + // Ide settings change: refresh session and cascade refresh from the top + async updateIdeSettings(ideSettings: IdeSettings) { this.ideSettingsPromise = Promise.resolve(ideSettings); - void this.reloadConfig(); + await this.cascadeInit(); } + // Session change: refresh session and cascade refresh from the top async updateControlPlaneSessionInfo( sessionInfo: ControlPlaneSessionInfo | undefined, ) { @@ -386,38 +324,97 @@ export class ConfigHandler { Promise.resolve(sessionInfo), this.ideSettingsPromise, ); + await this.cascadeInit(); + } - this.fetchControlPlaneProfiles().catch(async (e) => { - console.error("Failed to fetch control plane profiles: ", e); - await this.loadLocalProfilesOnly(); - await this.reloadConfig(); + // Org id: check id validity, save selection, switch and reload + async setSelectedOrgId(orgId: string, profileId?: 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, }); - } - private profilesListeners: (( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void)[] = []; - onDidChangeAvailableProfiles( - listener: ( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) => void, - ) { - this.profilesListeners.push(listener); - } + this.currentOrg = org; - private notifyProfileListeners( - profiles: ProfileDescription[], - selectedProfileId: string | null, - ) { - for (const listener of this.profilesListeners) { - listener(profiles, selectedProfileId); + if (profileId) { + this.setSelectedProfileId(profileId); + } else { + 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 + // Because of e.g. MCP singleton and docs service using things from config + // Could improve this + async reloadConfig() { + if (!this.currentProfile) { + return { + config: undefined, + errors: [], + configLoadInterrupted: true, + }; + } + + 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); + + this.notifyConfigListeners({ config, errors, configLoadInterrupted }); + return { config, errors, configLoadInterrupted }; + } + + // Listeners setup - can listen to current profile updates private notifyConfigListeners(result: ConfigResult) { - // Notify listeners that config changed for (const listener of this.updateListeners) { listener(result); } @@ -429,27 +426,9 @@ export class ConfigHandler { this.updateListeners.push(listener); } - // TODO: this isn't right, there are two different senses in which you want to "reload" - async reloadConfig() { - if (!this.currentProfile) { - return { - config: undefined, - errors: [], - configLoadInterrupted: true, - }; - } - - const { config, errors, configLoadInterrupted } = - await this.currentProfile.reloadConfig(this.additionalContextProviders); - - if (config) { - this.inactiveProfiles.forEach((profile) => profile.clearConfig()); - } - - this.notifyConfigListeners({ config, errors, configLoadInterrupted }); - return { config, errors, configLoadInterrupted }; - } - + // 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 > { @@ -465,10 +444,6 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] | null { - return this.profiles?.map((p) => p.profileDescription) ?? null; - } - async loadConfig(): Promise> { if (!this.currentProfile) { return { @@ -482,6 +457,23 @@ 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(); const model = config?.models.find((m) => m.title === title); @@ -502,8 +494,20 @@ 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); + } } 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/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 11fecffb2..f948491fc 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(); }; @@ -133,7 +126,11 @@ export class Core { this.messenger.send("configUpdate", { result: serializedResult, profileId: - this.configHandler.currentProfile?.profileDescription.id ?? null, + 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 @@ -146,14 +143,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,15 +297,8 @@ 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(); + await this.configHandler.refreshAll(); }); on("config/updateSharedConfig", async (msg) => { @@ -344,10 +326,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); }); @@ -480,6 +458,10 @@ export class Core { result: await this.configHandler.getSerializedConfig(), profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, + usingContinueForTeams: (await ideSettingsPromise) + .enableControlServerBeta, }; }); @@ -775,11 +757,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.loadAssistantsForSelectedOrg(); + localAssistantCreated = true; } } + if (localAssistantCreated) { + await this.configHandler.refreshAll(); + } } }); @@ -829,20 +815,14 @@ export class Core { // on("didChangeSelectedProfile", async (msg) => { - await this.configHandler.setSelectedProfile(msg.data.id); - await this.configHandler.reloadConfig(); + await this.configHandler.setSelectedProfileId(msg.data.id); }); 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(); - } + await this.configHandler.setSelectedOrgId( + msg.data.id, + msg.data.profileId, + ); }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -850,6 +830,7 @@ export class Core { msg.data.sessionInfo, ); }); + on("auth/getAuthUrl", async (msg) => { const url = await getAuthUrlForTokenPage( ideSettingsPromise, diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 03940c283..0213cd0e5 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 { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; @@ -66,14 +65,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { { result: ConfigResult; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string; + usingContinueForTeams: boolean; }, ]; "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 +196,4 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - "controlPlane/listOrganizations": [undefined, OrganizationDescription[]]; }; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 4dcf74ee5..2e1bd3ff1 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -1,19 +1,8 @@ -import { ProfileDescription } from "../config/ConfigHandler.js"; - 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, - ]; -}; -export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [ - { profiles: ProfileDescription[]; selectedProfileId: string | null }, - void, - ]; - didSelectOrganization: [{ orgId: string | null }, void]; + didChangeSelectedProfile: [{ id: string }, void]; + didChangeSelectedOrg: [{ id: string; profileId?: string }, void]; }; +export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index e165f9858..1646d848e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -107,5 +107,4 @@ export type ToWebviewOrCoreFromIdeProtocol = { { 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..6b59fa338 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,11 +1,11 @@ import { ConfigResult } from "@continuedev/config-yaml"; +import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, ContextProviderName, IndexingProgressUpdate, IndexingStatus, - PackageDocsResult, } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { @@ -13,6 +13,9 @@ export type ToWebviewFromIdeOrCoreProtocol = { { result: ConfigResult; profileId: string | null; + organizations: SerializedOrgWithProfiles[]; + selectedOrgId: string | null; + usingContinueForTeams: boolean; }, 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 e1da218c5..031c6b2e9 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 @@ -153,17 +153,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) { _ -> } } }) @@ -239,7 +234,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { "sessionInfo" to initialSessionInfo ) continuePluginService.coreMessenger?.request("didChangeControlPlaneSessionInfo", data, null) { _ -> } - continuePluginService.sendToWebview("didChangeControlPlaneSessionInfo", data) } connection.subscribe(AuthListener.TOPIC, object : AuthListener { @@ -256,7 +250,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 a0d19c7f9..60d2d3b33 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 @@ -66,12 +66,10 @@ class MessageTypes { "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", - "didChangeAvailableProfiles", "setTTSActive", "getWebviewHistoryLength", "getCurrentSessionId", "didCloseFiles", - "didSelectOrganization" ) // Note: If updating these values, make a corresponding update in @@ -88,7 +86,6 @@ class MessageTypes { "config/ideSettingsUpdate", "config/getSerializedProfileInfo", "config/deleteModel", - "config/listProfiles", "config/refreshProfiles", "config/openProfile", "config/updateSharedConfig", @@ -129,8 +126,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 ed6879bd7..41c2c4892 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 @@ -115,7 +115,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..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, }); @@ -334,14 +325,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 +398,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/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/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/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 0b20e2beb..e0d88dc12 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, @@ -9,8 +10,12 @@ import { import { useContext, useEffect, useMemo, useRef } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { cycleProfile, selectProfileThunk } from "../../../redux"; -import { useAppDispatch } from "../../../redux/hooks"; +import { + selectCurrentOrg, + setSelectedOrgId, + setSelectedProfile, +} from "../../../redux"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { fontSize, getMetaKeyLabel, @@ -57,7 +62,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(); } @@ -148,7 +158,9 @@ const AssistantSelectOption = ({ export default function AssistantSelect() { const dispatch = useAppDispatch(); const buttonRef = useRef(null); - const { selectedProfile, selectedOrganization } = useAuth(); + const { selectedProfile, refreshProfiles } = useAuth(); + const currentOrg = useAppSelector(selectCurrentOrg); + const orgs = useAppSelector((store) => store.profiles.organizations); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); @@ -163,14 +175,14 @@ export default function AssistantSelect() { function onNewAssistant() { ideMessenger.post("controlPlane/openUrl", { path: "new", - orgSlug: selectedOrganization?.slug, + orgSlug: currentOrg?.slug, }); close(); } useEffect(() => { let lastToggleTime = 0; - const DEBOUNCE_MS = 500; + const DEBOUNCE_MS = 800; const handleKeyDown = (event: KeyboardEvent) => { if ( @@ -181,8 +193,24 @@ export default function AssistantSelect() { const now = Date.now(); if (now - lastToggleTime >= DEBOUNCE_MS) { - dispatch(cycleProfile()); lastToggleTime = now; + + const profileIds = profiles?.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]; + } + // Optimistic update + dispatch(setSelectedProfile(nextId)); + ideMessenger.post("didChangeSelectedProfile", { + id: nextId, + }); } } }; @@ -191,7 +219,25 @@ export default function AssistantSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, []); + }, [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); @@ -202,7 +248,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" @@ -244,7 +290,7 @@ export default function AssistantSelect() { - +
@@ -268,21 +314,41 @@ export default function AssistantSelect() { }} /> - login(false)} - > +
+ login(false)} + > +
+ + New Assistant +
+
{ + e.stopPropagation(); + refreshProfiles(); + buttonRef.current?.click(); }} > - - New Assistant + + + Refresh +
- +
navigate(ROUTES.CONFIG)} + onClick={cycleOrgs} > - {selectedOrganization?.iconUrl ? ( + {currentOrg?.iconUrl ? ( ) : ( @@ -323,7 +389,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 a049e8adc..329a1ee38 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -5,17 +5,20 @@ import { import { ControlPlaneSessionInfo } from "core/control-plane/client"; import React, { createContext, + useCallback, useContext, useEffect, - useMemo, useState, } from "react"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { updateOrgsThunk, updateProfilesThunk } from "../redux"; -import { selectSelectedProfile } from "../redux/"; +import { + selectCurrentOrg, + selectSelectedProfile, + setOrganizations, + setSelectedOrgId, +} 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"; @@ -28,7 +31,6 @@ interface AuthContextType { refreshProfiles: () => void; controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; - selectedOrganization: OrganizationDescription | null; } const AuthContext = createContext(undefined); @@ -38,26 +40,16 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ }) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - // Session const [session, setSession] = useState( undefined, ); // Orgs - const orgs = useAppSelector((store) => store.organizations.organizations); - const selectedOrgId = useAppSelector( - (store) => store.organizations.selectedOrganizationId, - ); - const selectedOrganization = useMemo(() => { - if (!selectedOrgId) { - return null; - } - return orgs.find((p) => p.id === selectedOrgId) ?? null; - }, [orgs, selectedOrgId]); + const orgs = useAppSelector((store) => store.profiles.organizations); // Profiles - const profiles = useAppSelector((store) => store.profiles.availableProfiles); + const currentOrg = useAppSelector(selectCurrentOrg); const selectedProfile = useAppSelector(selectSelectedProfile); const login: AuthContextType["login"] = (useOnboarding: boolean) => { @@ -90,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)); @@ -100,79 +96,40 @@ 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), - ); - }, []); - - const [controlServerBetaEnabled, setControlServerBetaEnabled] = - useState(false); - - useEffect(() => { - ideMessenger.ide - .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([])); - } - }); + if (result.status === "success") { + setSession(result.content); + } } - }, [session]); + void init(); + }, []); useWebviewListener( - "didChangeIdeSettings", - async (msg) => { - const { settings } = msg; - setControlServerBetaEnabled(settings.enableControlServerBeta); - dispatch( - setLastControlServerBetaEnabledStatus(settings.enableControlServerBeta), - ); + "didChangeControlPlaneSessionInfo", + async (data) => { + setSession(data.sessionInfo); }, [], ); - useEffect(() => { - ideMessenger.request("config/listProfiles", undefined).then((result) => { - if (result.status === "success") { - dispatch( - updateProfilesThunk({ - profiles: result.content.profiles, - selectedProfileId: result.content.selectedProfileId, - }), - ); - } - }); - }, []); + const [controlServerBetaEnabled, setControlServerBetaEnabled] = + useState(false); - const refreshProfiles = async () => { + // Hacky, remove once continue for teams is deprecated + useWebviewListener( + "configUpdate", + async (msg) => { + setControlServerBetaEnabled(msg.usingContinueForTeams); + }, + [], + ); + + const refreshProfiles = useCallback(async () => { try { await ideMessenger.request("config/refreshProfiles", undefined); ideMessenger.post("showToast", ["info", "Config refreshed"]); @@ -180,20 +137,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ console.error("Failed to refresh profiles", e); ideMessenger.post("showToast", ["error", "Failed to refresh config"]); } - }; - - useWebviewListener( - "didChangeAvailableProfiles", - async (data) => { - dispatch( - updateProfilesThunk({ - profiles: data.profiles, - selectedProfileId: data.selectedProfileId, - }), - ); - }, - [], - ); + }, [ideMessenger]); return ( = ({ logout, login, selectedProfile, - profiles, + profiles: currentOrg?.profiles ?? [], refreshProfiles, - selectedOrganization, organizations: orgs, controlServerBetaEnabled, }} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index ded57ee08..5b3e665ad 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -2,12 +2,12 @@ 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 { - initializeProfilePreferencesThunk, - selectProfileThunk, - selectSelectedProfileId, + initializeProfilePreferences, + setOrganizations, + setSelectedOrgId, + setSelectedProfile, } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { @@ -36,30 +36,38 @@ 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 hasLoadedConfig = useRef(false); + const hasDoneInitialConfigLoad = useRef(false); const handleConfigUpdate = useCallback( - async ( - initial: boolean, - result: { - result: ConfigResult; - profileId: string | null; - }, - ) => { - const { result: configResult, profileId } = result; - if (initial && hasLoadedConfig.current) { + async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => { + const { + result: configResult, + profileId, + organizations, + selectedOrgId, + } = result; + if (isInitial && hasDoneInitialConfigLoad.current) { return; } - hasLoadedConfig.current = true; + hasDoneInitialConfigLoad.current = true; + dispatch(setOrganizations(organizations)); + dispatch(setSelectedOrgId(selectedOrgId)); + dispatch(setSelectedProfile(profileId)); dispatch(setConfigResult(configResult)); - dispatch(selectProfileThunk(profileId)); const isNewProfileId = profileId && profileId !== selectedProfileId; if (isNewProfileId) { - dispatch(initializeProfilePreferencesThunk({ profileId })); + dispatch( + initializeProfilePreferences({ + defaultSlashCommands: [], + profileId, + }), + ); } // Perform any actions needed with the config @@ -68,28 +76,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()); @@ -97,13 +108,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", @@ -113,7 +124,7 @@ function useSetup() { } await handleConfigUpdate(false, update); }, - [loadConfig], + [handleConfigUpdate], ); // Load symbols for chat on any session change diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 34dfe2f29..5c3d2e44f 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,5 +1,6 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; +import { useState } from "react"; import { SecondaryButton } from "../../components"; import { Popover, @@ -8,13 +9,14 @@ 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 [open, setOpen] = useState(false); const { session, logout, login, organizations } = useAuth(); - const selectedOrg = useAppSelector(selectSelectedOrganization); + const selectedOrg = useAppSelector(selectCurrentOrg); if (!session) { return ( @@ -29,40 +31,44 @@ export function AccountButton() { 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 311f78d98..ee3bdd42f 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,30 +11,39 @@ import { ListboxOptions, } from "../../components/ui/Listbox"; import { useAuth } from "../../context/Auth"; -import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { selectOrgThunk } from "../../redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + selectCurrentOrg, + setSelectedOrgId, +} from "../../redux/slices/profiles/slice"; -export function ScopeSelect() { - const { organizations, selectedOrganization } = useAuth(); +interface ScopeSelectProps { + onSelect?: () => void; +} +export function ScopeSelect({ onSelect }: ScopeSelectProps) { + const { organizations } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); const selectedOrgId = useAppSelector( - (state) => state.organizations.selectedOrganizationId, + (state) => state.profiles.selectedOrganizationId, ); + const currentOrg = useAppSelector(selectCurrentOrg); 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, + }); + onSelect?.(); }; - useWebviewListener("didSelectOrganization", async (data) => { - handleChange(data.orgId); - }); - const CurScopeEntityFallBackIcon = selectedOrgId ? BuildingOfficeIcon : UserCircleIcon; - const selectedDisplay = selectedOrganization ?? { + const selectedDisplay = currentOrg ?? { name: "Personal", iconUrl: null, }; @@ -68,17 +78,6 @@ export function ScopeSelect() {
))} - - {!!organizations.length && ( -
- )} - - -
- - Personal -
-
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/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"; 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/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 b662d2435..000000000 --- a/gui/src/redux/slices/organizations/slice.ts +++ /dev/null @@ -1,50 +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; - }, - 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, - ) ?? null, - }, -}); - -export const { setOrganizations, setSelectedOrganizationId } = - organizationsSlice.actions; - -export const { - selectOrganizations, - selectSelectedOrganizationId, - selectSelectedOrganization, -} = organizationsSlice.selectors; - -export const { reducer: organizationsReducer } = organizationsSlice; 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)); -}); 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/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 f321f0dae..c69e65315 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -10,11 +10,10 @@ 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"; -import miscReducer from "./slices/miscSlice"; import sessionReducer from "./slices/sessionSlice"; import tabsReducer from "./slices/tabsSlice"; import uiReducer from "./slices/uiSlice"; @@ -26,14 +25,12 @@ export interface ChatMessage { const rootReducer = combineReducers({ session: sessionReducer, - misc: miscReducer, ui: uiReducer, editModeState: editModeStateReducer, config: configReducer, indexing: indexingReducer, tabs: tabsReducer, profiles: profilesReducer, - organizations: organizationsReducer, }); const saveSubsetFilters = [ @@ -47,10 +44,6 @@ const saveSubsetFilters = [ "mode", "codeToEdit", - // TODO consider removing persisted profiles/orgs - "availableProfiles", - "organizations", - // higher risk to persist // codeBlockApplyStates // symbols @@ -62,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 = {