From ff0cd587288cbdfff9b8d8f60eb738b7ff336bda Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 19 Feb 2025 11:07:47 -0800 Subject: [PATCH] ensure loading state is used, deduplicate some logic --- core/config/ConfigHandler.ts | 150 +++++++++--------- core/core.ts | 8 +- core/protocol/core.ts | 4 +- core/protocol/coreWebview.ts | 5 +- .../components/modelSelection/ModelSelect.tsx | 7 +- .../platform/AssistantSelect.tsx | 11 ++ gui/src/context/Auth.tsx | 32 ++-- gui/src/hooks/useSetup.ts | 4 +- gui/src/pages/config/index.tsx | 1 + gui/src/redux/slices/sessionSlice.ts | 10 +- gui/src/redux/thunks/profileAndOrg.ts | 46 ++++-- 11 files changed, 161 insertions(+), 117 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 79aadd2b7..74b330c3a 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -47,8 +47,8 @@ type ConfigUpdateFunction = (payload: ConfigResult) => void; export class ConfigHandler { private readonly globalContext = new GlobalContext(); private additionalContextProviders: IContextProvider[] = []; - private profiles: ProfileLifecycleManager[]; - private selectedProfileId: string | null; + private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded + private selectedProfileId: string | null = null; private localProfileManager: ProfileLifecycleManager; private controlPlaneClient: ControlPlaneClient; @@ -77,16 +77,20 @@ export class ConfigHandler { localProfileLoader, this.ide, ); - this.profiles = [this.localProfileManager]; - this.selectedProfileId = localProfileLoader.description.id; + // Profiles are loaded asynchronously void this.init(); } private async init() { - // Always load local profile immediately in case control plane doesn't load 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: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); } catch (e) { @@ -102,14 +106,14 @@ export class ConfigHandler { // 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( + this.profiles?.find( (p) => p.profileDescription.id === this.selectedProfileId, ) ?? null ); } get inactiveProfiles() { - return this.profiles.filter( + return (this.profiles ?? []).filter( (p) => p.profileDescription.id !== this.selectedProfileId, ); } @@ -139,9 +143,10 @@ export class ConfigHandler { const userId = await this.controlPlaneClient.userId; const selectedOrgId = await this.getSelectedOrgId(); + let profiles: ProfileLifecycleManager[] | null = null; if (!userId) { // Not logged in - this.profiles = [this.localProfileManager]; + profiles = [this.localProfileManager]; } else { // Logged in const assistants = @@ -180,34 +185,32 @@ export class ConfigHandler { if (selectedOrgId === null) { // Personal - this.profiles = [...hubProfiles, this.localProfileManager]; + profiles = [...hubProfiles, this.localProfileManager]; } else { // Organization - this.profiles = hubProfiles; + profiles = hubProfiles; } } - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), + await this.updateAvailableProfiles(profiles); + } + + 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(); + const selectedProfileId = + previouslySelectedProfileId ?? profiles[0].profileDescription.id ?? null; + + // Notify listeners + const profileDescriptions = profiles.map( + (profile) => profile.profileDescription, ); - - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - - const selectedProfileId = lastSelectedIds[workspaceId]; - if (selectedProfileId) { - this.selectedProfileId = selectedProfileId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedIds, - ); - } + this.notifyProfileListeners(profileDescriptions, selectedProfileId); + await this.setSelectedProfile(selectedProfileId); } private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; @@ -261,52 +264,38 @@ export class ConfigHandler { PlatformProfileLoader.RELOAD_INTERVAL, ); } else { - this.controlPlaneClient - .listWorkspaces() - .then(async (workspaces) => { - this.profiles = [this.localProfileManager]; - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - this.profiles.push( - new ProfileLifecycleManager(profileLoader, this.ide), - ); - }); - - this.notifyProfileListeners( - this.profiles.map((profile) => profile.profileDescription), + try { + const workspaces = await this.controlPlaneClient.listWorkspaces(); + const profiles = [this.localProfileManager]; + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), ); - // Check the last selected workspace, and reload if it isn't local - const workspaceId = await this.getWorkspaceId(); - const lastSelectedIds = - this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; - const selectedProfileId = lastSelectedIds[workspaceId]; - if (selectedProfileId) { - this.selectedProfileId = selectedProfileId; - await this.loadConfig(); - } else { - // Otherwise we stick with local profile, and record choice - lastSelectedIds[workspaceId] = this.selectedProfileId; - this.globalContext.update( - "lastSelectedProfileForWorkspace", - lastSelectedIds, - ); - } - }) - .catch((e) => { - console.error(e); + profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); + + await this.updateAvailableProfiles(profiles); + } catch (e: any) { + console.error("Failed to load profiles: ", e); + await this.updateAvailableProfiles([this.localProfileManager]); + } } } + 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") ?? {}; @@ -357,16 +346,25 @@ export class ConfigHandler { }); } - private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = []; + private profilesListeners: (( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void)[] = []; onDidChangeAvailableProfiles( - listener: (profiles: ProfileDescription[]) => void, + listener: ( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) => void, ) { this.profilesListeners.push(listener); } - private notifyProfileListeners(profiles: ProfileDescription[]) { + private notifyProfileListeners( + profiles: ProfileDescription[], + selectedProfileId: string | null, + ) { for (const listener of this.profilesListeners) { - listener(profiles); + listener(profiles, selectedProfileId); } } @@ -419,8 +417,8 @@ export class ConfigHandler { ); } - listProfiles(): ProfileDescription[] { - return this.profiles.map((p) => p.profileDescription); + listProfiles(): ProfileDescription[] | null { + return this.profiles?.map((p) => p.profileDescription) ?? null; } async loadConfig(): Promise> { diff --git a/core/core.ts b/core/core.ts index 3002517ce..8316068d5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -130,8 +130,12 @@ export class Core { }); }); - this.configHandler.onDidChangeAvailableProfiles((profiles) => - this.messenger.send("didChangeAvailableProfiles", { profiles }), + this.configHandler.onDidChangeAvailableProfiles( + (profiles, selectedProfileId) => + this.messenger.send("didChangeAvailableProfiles", { + profiles, + selectedProfileId, + }), ); // Codebase Indexer and ContinueServerClient depend on IdeSettings diff --git a/core/protocol/core.ts b/core/protocol/core.ts index c3084f6b8..96eebce84 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -14,11 +14,11 @@ import type { ContextSubmenuItem, DiffLine, DocsIndexingDetails, + ExperimentalModelRoles, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, ModelDescription, - ExperimentalModelRoles, PromptLog, RangeInFile, SerializedContinueConfig, @@ -68,7 +68,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/deleteModel": [{ title: string }, void]; "config/addContextProvider": [ContextProviderWithParams, void]; "config/reload": [undefined, ConfigResult]; - "config/listProfiles": [undefined, ProfileDescription[]]; + "config/listProfiles": [undefined, ProfileDescription[] | null]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, void]; "context/getContextItems": [ diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index ff99acd03..67b5919a4 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -8,5 +8,8 @@ export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedOrg: [{ id: string | null }, void]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { - didChangeAvailableProfiles: [{ profiles: ProfileDescription[] }, void]; + didChangeAvailableProfiles: [ + { profiles: ProfileDescription[]; selectedProfileId: string | null }, + void, + ]; }; diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index efa717a0b..92a37928f 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -10,6 +10,7 @@ import { useContext, useEffect, useRef, useState } from "react"; import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscInputBackground } from ".."; +import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppSelector } from "../../redux/hooks"; @@ -219,9 +220,7 @@ function ModelSelect() { const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, - ); + const { selectedProfile } = useAuth(); // Sort so that options without an API key are at the end useEffect(() => { @@ -351,7 +350,7 @@ function ModelSelect() {
- {selectedProfileId === "local" && ( + {selectedProfile?.id === "local" && ( <> + Loading... +
+ ); + } + if (!selectedProfile) { return (
= ({ // Profiles const profiles = useAppSelector((store) => store.session.availableProfiles); - const selectedProfileId = useAppSelector( - (store) => store.session.selectedProfileId, + const selectedProfile = useAppSelector( + (store) => store.session.selectedProfile, ); - const selectedProfile = useMemo(() => { - if (!selectedProfileId) { - return null; - } - return profiles.find((p) => p.id === selectedProfileId) ?? null; - }, [profiles, selectedProfileId]); const login: AuthContextType["login"] = (useOnboarding: boolean) => { return new Promise((resolve) => { @@ -168,10 +162,30 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ [], ); + useEffect(() => { + ideMessenger.request("config/listProfiles", undefined).then((result) => { + if (result.status === "success") { + console.log("PROFILES: ", result.content); + dispatch( + updateProfilesThunk({ + profiles: result.content, + selectedProfileId: null, + }), + ); + } + }); + }, []); + useWebviewListener( "didChangeAvailableProfiles", async (data) => { - dispatch(updateProfilesThunk(data.profiles)); + console.log("AVAILABLE: ", data.profiles, data.selectedProfileId); + dispatch( + updateProfilesThunk({ + profiles: data.profiles, + selectedProfileId: data.selectedProfileId, + }), + ); }, [], ); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 7f349bc73..714f4ed75 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -13,13 +13,13 @@ import { setInactive, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { selectProfileThunk } from "../redux/thunks/profileAndOrg"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; -import { selectProfileThunk } from "../redux/thunks/profileAndOrg"; function useSetup() { const dispatch = useAppDispatch(); @@ -45,6 +45,7 @@ function useSetup() { } hasLoadedConfig.current = true; dispatch(setConfigResult(configResult)); + console.log("selecting 1", profileId); dispatch(selectProfileThunk(profileId)); // Perform any actions needed with the config @@ -94,6 +95,7 @@ function useSetup() { useWebviewListener( "configUpdate", async (update) => { + console.log("CONFIG UPDATE: ", update); if (!update) { return; } diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index aff6a1069..56fe464f7 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -29,6 +29,7 @@ function ConfigPage() { } = useAuth(); const changeProfileId = (id: string) => { + console.log("selecting 2", id); dispatch(selectProfileThunk(id)); }; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 3fa5b2da0..4192fa98b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -47,7 +47,7 @@ type SessionState = { id: string; /** null indicates loading state */ availableProfiles: ProfileDescription[] | null; - selectedProfileId: string | null; + selectedProfile: ProfileDescription | null; organizations: OrganizationDescription[]; selectedOrganizationId: string | null; streamAborter: AbortController; @@ -89,7 +89,7 @@ const initialState: SessionState = { isStreaming: false, title: NEW_SESSION_TITLE, id: uuidv4(), - selectedProfileId: null, + selectedProfile: null, availableProfiles: null, organizations: [], selectedOrganizationId: "", @@ -537,13 +537,13 @@ export const sessionSlice = createSlice({ // That is done in thunks setSelectedProfileId: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { - state.selectedProfileId = payload; + state.selectedProfile = payload; }, setAvailableProfiles: ( state, - { payload }: PayloadAction, + { payload }: PayloadAction, ) => { state.availableProfiles = payload; }, diff --git a/gui/src/redux/thunks/profileAndOrg.ts b/gui/src/redux/thunks/profileAndOrg.ts index 9b4c774d0..bf2ff87f0 100644 --- a/gui/src/redux/thunks/profileAndOrg.ts +++ b/gui/src/redux/thunks/profileAndOrg.ts @@ -1,7 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ProfileDescription } from "core/config/ConfigHandler"; import { OrganizationDescription } from "core/config/ProfileLifecycleManager"; -import { isLocalProfile } from "../../util"; import { setAvailableProfiles, setOrganizations, @@ -22,10 +21,16 @@ export const selectProfileThunk = createAsyncThunk< return; } - const initialId = state.session.selectedProfileId; + const initialId = state.session.selectedProfile?.id; let newId = id; + console.log( + "Running Thunk: ", + initialId, + newId, + state.session.availableProfiles, + ); // If no profiles, force clear if (state.session.availableProfiles.length === 0) { newId = null; @@ -38,19 +43,24 @@ export const selectProfileThunk = createAsyncThunk< } if (!newId) { // At this point if null ID and there ARE profiles, - // Fallback to a profile, prioritizing local - const localProfile = state.session.availableProfiles.find(isLocalProfile); - if (localProfile) { - newId = localProfile.id; - } else { - newId = state.session.availableProfiles[0].id; - } + // Fallback to a profile, prioritizing the first in the list + newId = state.session.availableProfiles[0].id; } } // Only update if there's a change - if (newId !== initialId) { - dispatch(setSelectedProfileId(newId)); + console.log( + "update selected profile?", + newId, + initialId, + state.session.availableProfiles, + ); + if ((newId ?? null) !== (initialId ?? null)) { + dispatch( + setSelectedProfileId( + state.session.availableProfiles.find((p) => p.id === newId) ?? null, + ), + ); extra.ideMessenger.post("didChangeSelectedProfile", { id: newId, }); @@ -74,8 +84,8 @@ export const cycleProfile = createAsyncThunk( return; } let nextId = profileIds[0]; - if (state.session.selectedProfileId) { - const curIndex = profileIds.indexOf(state.session.selectedProfileId); + if (state.session.selectedProfile) { + const curIndex = profileIds.indexOf(state.session.selectedProfile?.id); const nextIndex = (curIndex + 1) % profileIds.length; nextId = profileIds[nextIndex]; } @@ -85,14 +95,16 @@ export const cycleProfile = createAsyncThunk( export const updateProfilesThunk = createAsyncThunk< void, - ProfileDescription[], + { profiles: ProfileDescription[] | null; selectedProfileId: string | null }, ThunkApiType ->("profiles/update", async (profiles, { dispatch, extra, getState }) => { - const state = getState(); +>("profiles/update", async (data, { dispatch, extra, getState }) => { + const { profiles, selectedProfileId } = data; + dispatch(setAvailableProfiles(profiles)); // This will trigger reselection if needed - dispatch(selectProfileThunk(state.session.selectedProfileId)); + console.log("selecting 3", selectedProfileId); + dispatch(selectProfileThunk(selectedProfileId)); }); export const selectOrgThunk = createAsyncThunk<