Skip to content

Commit

Permalink
🔧 fix: URL params, package mismatch, typing, shared link redirect, an…
Browse files Browse the repository at this point in the history
…d o1 (azure) (#4899)

* fix: double decoding of URL params

* fix: prevent streaming options for O1 model (azure)

* fix: update @langchain/openai to version 0.3.14 in package-lock.json

* chore(AuthContext): typing

* chore(useTimeout): typing

* fix: shared link redirecting to login when code block includes "Run Code" button

* fix: typing
  • Loading branch information
danny-avila authored Dec 7, 2024
1 parent 85d92c2 commit 2875380
Show file tree
Hide file tree
Showing 8 changed files with 41 additions and 22 deletions.
5 changes: 5 additions & 0 deletions api/app/clients/OpenAIClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -1324,6 +1324,11 @@ ${convo}
/** @type {(value: void | PromiseLike<void>) => void} */
let streamResolve;

if (this.isO1Model === true && this.azure && modelOptions.stream) {
delete modelOptions.stream;
delete modelOptions.stop;
}

if (modelOptions.stream) {
streamPromise = new Promise((resolve) => {
streamResolve = resolve;
Expand Down
7 changes: 6 additions & 1 deletion client/src/components/Messages/Content/RunCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ const RunCode: React.FC<CodeBarProps> = React.memo(({ lang, codeRef, blockIndex

const { messageId, conversationId, partIndex } = useMessageContext();
const normalizedLang = useMemo(() => normalizeLanguage(lang), [lang]);
const { data } = useVerifyAgentToolAuth({ toolId: Tools.execute_code });
const { data } = useVerifyAgentToolAuth(
{ toolId: Tools.execute_code },
{
retry: 1,
},
);
const authType = useMemo(() => data?.message ?? false, [data?.message]);
const isAuthenticated = useMemo(() => data?.authenticated ?? false, [data?.authenticated]);
const { methods, onSubmit, isDialogOpen, setIsDialogOpen, handleRevokeApiKey } =
Expand Down
20 changes: 11 additions & 9 deletions client/src/hooks/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const AuthContextProvider = ({
//@ts-ignore - ok for token to be undefined initially
setTokenHeader(token);
setIsAuthenticated(isAuthenticated);
if (redirect) {
if (redirect != null && redirect) {
navigate(redirect, { replace: true });
}
},
Expand Down Expand Up @@ -83,7 +83,7 @@ const AuthContextProvider = ({
});

const logout = useCallback(() => logoutUser.mutate(undefined), [logoutUser]);
const userQuery = useGetUserQuery({ enabled: !!token });
const userQuery = useGetUserQuery({ enabled: !!(token ?? '') });
const refreshToken = useRefreshTokenMutation();

const login = (data: TLoginUser) => {
Expand All @@ -102,26 +102,26 @@ const AuthContextProvider = ({
};

const silentRefresh = useCallback(() => {
if (authConfig?.test) {
if (authConfig?.test === true) {
console.log('Test mode. Skipping silent refresh.');
return;
}
refreshToken.mutate(undefined, {
onSuccess: (data: TLoginResponse) => {
const { user, token } = data;
onSuccess: (data: TLoginResponse | undefined) => {
const { user, token = '' } = data ?? {};
if (token) {
setUserContext({ token, isAuthenticated: true, user });
} else {
console.log('Token is not present. User is not authenticated.');
if (authConfig?.test) {
if (authConfig?.test === true) {
return;
}
navigate('/login');
}
},
onError: (error) => {
console.log('refreshToken mutation error:', error);
if (authConfig?.test) {
if (authConfig?.test === true) {
return;
}
navigate('/login');
Expand All @@ -136,10 +136,10 @@ const AuthContextProvider = ({
doSetError((userQuery.error as Error).message);
navigate('/login', { replace: true });
}
if (error && isAuthenticated) {
if (error != null && error && isAuthenticated) {
doSetError(undefined);
}
if (!token || !isAuthenticated) {
if (token == null || !token || !isAuthenticated) {
silentRefresh();
}
}, [
Expand All @@ -149,7 +149,9 @@ const AuthContextProvider = ({
userQuery.isError,
userQuery.error,
error,
setUser,
navigate,
silentRefresh,
setUserContext,
]);

Expand Down
6 changes: 2 additions & 4 deletions client/src/hooks/Input/useQueryParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@ export default function useQueryParams({
const maxAttempts = 50; // 5 seconds maximum (50 * 100ms)

useEffect(() => {
const promptParam = searchParams.get('prompt');
if (!promptParam) {
const decodedPrompt = searchParams.get('prompt') ?? '';
if (!decodedPrompt) {
return;
}

const decodedPrompt = decodeURIComponent(promptParam);

const intervalId = setInterval(() => {
// If already processed or max attempts reached, clear interval and stop
if (processedRef.current || attemptsRef.current >= maxAttempts) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useTimeout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function useTimeout({ callback, delay = 400 }: TUseTimeoutParams) {
}

// Set new timeout
if (value) {
if (value != null && value) {
console.log(value);
timeout.current = setTimeout(() => {
callback(value);
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ export const useRegisterUserMutation = (
};

export const useRefreshTokenMutation = (): UseMutationResult<
t.TRefreshTokenResponse,
t.TRefreshTokenResponse | undefined,
unknown,
unknown,
unknown
Expand Down
15 changes: 12 additions & 3 deletions packages/data-provider/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import * as endpoints from './api-endpoints';
import { setTokenHeader } from './headers-helpers';
import type * as t from './types';

async function _get<T>(url: string, options?: AxiosRequestConfig): Promise<T> {
const response = await axios.get(url, { ...options });
Expand Down Expand Up @@ -63,7 +64,8 @@ async function _patch(url: string, data?: any) {
let isRefreshing = false;
let failedQueue: { resolve: (value?: any) => void; reject: (reason?: any) => void }[] = [];

const refreshToken = (retry?: boolean) => _post(endpoints.refreshToken(retry));
const refreshToken = (retry?: boolean): Promise<t.TRefreshTokenResponse | undefined> =>
_post(endpoints.refreshToken(retry));

const dispatchTokenUpdatedEvent = (token: string) => {
setTokenHeader(token);
Expand All @@ -90,6 +92,7 @@ axios.interceptors.response.use(
}

if (error.response.status === 401 && !originalRequest._retry) {
console.warn('401 error, refreshing token');
originalRequest._retry = true;

if (isRefreshing) {
Expand All @@ -107,16 +110,22 @@ axios.interceptors.response.use(
isRefreshing = true;

try {
const { token } = await refreshToken(
const response = await refreshToken(
// Handle edge case where we get a blank screen if the initial 401 error is from a refresh token request
originalRequest.url?.includes('api/auth/refresh') ? true : false,
originalRequest.url?.includes('api/auth/refresh') === true ? true : false,
);

const token = response?.token ?? '';

if (token) {
originalRequest.headers['Authorization'] = 'Bearer ' + token;
dispatchTokenUpdatedEvent(token);
processQueue(null, token);
return await axios(originalRequest);
} else if (window.location.href.includes('share/')) {
console.log(
`Refresh token failed from shared link, attempting request to ${originalRequest.url}`,
);
} else {
window.location.href = '/login';
}
Expand Down

0 comments on commit 2875380

Please sign in to comment.