ensure loading state is used, deduplicate some logic

This commit is contained in:
Nate 2025-02-19 11:07:47 -08:00
parent 9e112b1313
commit ff0cd58728
11 changed files with 161 additions and 117 deletions

View file

@ -47,8 +47,8 @@ type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => 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<string | null> {
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
return lastSelectedIds[workspaceId] ?? null;
}
async getSelectedOrgId(): Promise<string | null> {
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<ConfigResult<ContinueConfig>> {

View file

@ -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

View file

@ -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<BrowserSerializedContinueConfig>];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/listProfiles": [undefined, ProfileDescription[] | null];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, void];
"context/getContextItems": [

View file

@ -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,
];
};

View file

@ -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<HTMLButtonElement>(null);
const [options, setOptions] = useState<Option[]>([]);
const [sortedOptions, setSortedOptions] = useState<Option[]>([]);
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() {
<div className="mt-auto">
<Divider className="!my-0" />
{selectedProfileId === "local" && (
{selectedProfile?.id === "local" && (
<>
<StyledListboxOption
key={options.length}

View file

@ -42,6 +42,17 @@ export default function AssistantSelect() {
};
}, []);
if (!profiles) {
return (
<div
className="text-lightgray hover:bg mb-1 mr-3 flex items-center gap-1"
style={{ fontSize: `${getFontSize() - 2}px` }}
>
Loading...
</div>
);
}
if (!selectedProfile) {
return (
<div

View file

@ -59,15 +59,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
// 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,
}),
);
},
[],
);

View file

@ -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;
}

View file

@ -29,6 +29,7 @@ function ConfigPage() {
} = useAuth();
const changeProfileId = (id: string) => {
console.log("selecting 2", id);
dispatch(selectProfileThunk(id));
};

View file

@ -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<string | null>,
{ payload }: PayloadAction<ProfileDescription | null>,
) => {
state.selectedProfileId = payload;
state.selectedProfile = payload;
},
setAvailableProfiles: (
state,
{ payload }: PayloadAction<ProfileDescription[]>,
{ payload }: PayloadAction<ProfileDescription[] | null>,
) => {
state.availableProfiles = payload;
},

View file

@ -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<void, undefined, ThunkApiType>(
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<void, undefined, ThunkApiType>(
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<