Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: recent session history #2742

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion react/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ const router = createBrowserRouter([
},
{
path: '/session/start',
handle: { labelKey: 'session.launcher.StartNewSession' },
// handle: { labelKey: 'session.launcher.StartNewSession' },
Component: () => {
const { token } = theme.useToken();
return (
Expand Down
31 changes: 21 additions & 10 deletions react/src/components/SessionOwnerSetterCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,23 @@ import { useTranslation } from 'react-i18next';
import { fetchQuery, useRelayEnvironment } from 'react-relay';

export interface SessionOwnerSetterFormValues {
owner?: {
email: string;
accesskey: string;
project: string;
resourceGroup: string;
enabled: boolean;
domainName: string;
};
owner?:
| {
email: string;
accesskey: string;
project: string;
resourceGroup: string;
enabled: true;
domainName: string;
}
| {
email?: string;
accesskey?: string;
project?: string;
resourceGroup?: string;
enabled: false;
domainName?: string;
};
}

const SessionOwnerSetterCard: React.FC<CardProps> = (props) => {
Expand Down Expand Up @@ -74,8 +83,10 @@ const SessionOwnerSetterCard: React.FC<CardProps> = (props) => {
enabled: !!fetchingEmail,
});

const ownerKeypairs = data?.keypairs;
const owner = data?.user;
const ownerKeypairs = form.getFieldValue(['owner', 'email'])
? data?.keypairs
: undefined;
const owner = form.getFieldValue(['owner', 'email']) ? data?.user : undefined;

const nonExistentOwner = !isFetching && fetchingEmail && !owner;
return (
Expand Down
162 changes: 159 additions & 3 deletions react/src/components/SessionTemplateModal.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,167 @@
import { useBackendAIImageMetaData } from '../hooks';
import { useRecentSessionHistory } from '../hooks/backendai';
import {
ResourceNumbersOfSession,
SessionLauncherFormValue,
} from '../pages/SessionLauncherPage';
import BAIModal, { BAIModalProps } from './BAIModal';
import React from 'react';
import Flex from './Flex';
import ImageMetaIcon from './ImageMetaIcon';
import { Divider, Table, Typography } from 'antd';
import dayjs from 'dayjs';
import _ from 'lodash';
import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

interface SessionTemplateModalProps extends BAIModalProps {}
interface SessionTemplateModalProps
extends Omit<BAIModalProps, 'onOk' | 'onCancel'> {
onRequestClose: (formValue?: SessionLauncherFormValue) => void;
}
const SessionTemplateModal: React.FC<SessionTemplateModalProps> = ({
...modalProps
}) => {
return <BAIModal {...modalProps}></BAIModal>;
const { t } = useTranslation();
const [sessionHistory] = useRecentSessionHistory();

const [, { getImageAliasName, getBaseVersion }] = useBackendAIImageMetaData();

const [selectedHistoryId, setSelectedHistoryId] = useState<string>();

const parsedSessionHistory = useMemo(() => {
return _.map(sessionHistory, (history) => {
const params = new URLSearchParams(history.params);
const formValues: SessionLauncherFormValue = JSON.parse(
params.get('formValues') || '{}',
);
return {
...history,
...formValues,
// resourceAllocation: `${history.cpu}CPU ${history.memory}GB`,
};
});
}, [sessionHistory]);

return (
<BAIModal
width={800}
title={t('session.launcher.RecentHistory')}
okButtonProps={{ disabled: !selectedHistoryId }}
okText={t('button.Apply')}
{...modalProps}
onOk={(e) => {
const params = _.find(sessionHistory, {
id: selectedHistoryId,
})?.params;
modalProps.onRequestClose?.(
JSON.parse(new URLSearchParams(params).get('formValues') || '{}'),
);
}}
onCancel={() => {
// reset
setSelectedHistoryId(undefined);
modalProps.onRequestClose();
}}
>
<Divider style={{ margin: 0 }} />
<Table
showHeader={false}
scroll={{ x: 'max-content' }}
dataSource={parsedSessionHistory}
pagination={false}
rowSelection={{
type: 'radio',
selectedRowKeys: selectedHistoryId ? [selectedHistoryId] : [],
onSelect: (record) => {
setSelectedHistoryId(record.id);
},
}}
onRow={(record) => ({
onClick: () => {
setSelectedHistoryId(record.id);
},
})}
rowKey={(record) => record.id}
columns={[
// {
// title: t('session.launcher.SessionName'),
// dataIndex: 'sessionName',
// render: (sessionName, record) => {
// return sessionName ?? '-';
// },
// },
{
title: t('general.Image'),
dataIndex: ['environments', 'version'],
render: (version, record) => {
const imageStr =
record.environments.version || record.environments.manual;
return (
!!imageStr && (
<Flex gap={'xs'}>
<ImageMetaIcon image={imageStr} />
<Typography.Text>
{getImageAliasName(imageStr)}
</Typography.Text>
<Typography.Text>
{getBaseVersion(imageStr)}
</Typography.Text>
<Typography.Text>
{record.sessionName ? `(${record.sessionName})` : null}
</Typography.Text>
</Flex>
)
);
},
// onCell: () => ({
// style: { maxWidth: 250, textOverflow: 'ellipsis' },
// }),
},
{
title: t('session.launcher.ResourceAllocation'),
dataIndex: 'resource',
render: (resource) => {
// return JSON.stringify(resource)
return (
<Flex>
<ResourceNumbersOfSession resource={resource} />
</Flex>
);
},
},
// {
// dataIndex: 'mounts',
// render: (value, record) => {
// record.mou
// }
// },
{
title: t('session.launcher.CreatedAt'),
dataIndex: 'createdAt',
render: (createdAt: string) => {
return dayjs(createdAt).fromNow();
},
},
]}
/>
{/* <Tabs
defaultActiveKey="history"
items={[
{
key: 'template',
label: t('session.launcher.Template'),
children: <div>Template</div>,
},
{
key: 'history',
label: t('session.launcher.RecentHistory'),
children: (

),
},
]}
/> */}
</BAIModal>
);
};

export default SessionTemplateModal;
5 changes: 3 additions & 2 deletions react/src/components/VFolderTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ const VFolderTable: React.FC<VFolderTableProps> = ({
const handleAliasUpdate = useEventNotStable(() => {
setAliasMap(
_.mapValues(
_.pickBy(internalForm.getFieldsValue(), (v) => !!v), //remove empty
_.pickBy(internalForm.getFieldsValue({ strict: false }), (v) => !!v), //remove empty
(v, k) => inputToAliasPath(k, v), // add alias base path
),
);
Expand Down Expand Up @@ -533,7 +533,7 @@ const VFolderTable: React.FC<VFolderTableProps> = ({
}}
/>
</Flex>
<Form form={internalForm} component={false}>
<Form form={internalForm} component={false} preserve={false}>
<Table
// size="small"
scroll={{ x: 'max-content' }}
Expand All @@ -542,6 +542,7 @@ const VFolderTable: React.FC<VFolderTableProps> = ({
selectedRowKeys,
onChange: (selectedRowKeys) => {
setSelectedRowKeys(selectedRowKeys as VFolderKey[]);
handleAliasUpdate();
},
}}
showSorterTooltip={false}
Expand Down
1 change: 0 additions & 1 deletion react/src/components/VFolderTableFormItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const VFolderTableFormItem: React.FC<VFolderTableFormItemProps> = ({
}) => {
const form = Form.useFormInstance();
const { t } = useTranslation();
Form.useWatch('vfoldersAliasMap', form);
return (
<>
<Form.Item
Expand Down
48 changes: 47 additions & 1 deletion react/src/hooks/backendai.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { useSuspendedBackendaiClient, useUpdatableState } from '.';
import { maskString, useBaiSignedRequestWithPromise } from '../helper';
import {
generateRandomString,
maskString,
useBaiSignedRequestWithPromise,
} from '../helper';
import {
useSuspenseTanQuery,
useTanMutation,
useTanQuery,
} from './reactQueryAlias';
import { SessionHistory, useBAISettingUserState } from './useBAISetting';
import { useEventNotStable } from './useEventNotStable';
import _ from 'lodash';
import { useCallback, useEffect, useMemo, useState } from 'react';

Expand Down Expand Up @@ -304,3 +310,43 @@ export const useAllowedHostNames = () => {
});
return allowedHosts?.allowed;
};

export const useRecentSessionHistory = () => {
const [recentSessionHistory, setRecentSessionHistory] =
useBAISettingUserState('recentSessionHistory');

const push = useEventNotStable(
({
id,
params,
createdAt,
}: SelectivePartial<SessionHistory, 'id' | 'createdAt'>) => {
const newHistory: SessionHistory = {
id: id ?? generateRandomString(8),
params,
createdAt: createdAt ?? new Date().toISOString(),
};
// push new history to the top of recentSessionHistory and keep it up to 5
const newRecentSessionHistory = [
newHistory,
...(recentSessionHistory || []),
].slice(0, 5);
setRecentSessionHistory(newRecentSessionHistory);
},
);
const clear = useEventNotStable(() => setRecentSessionHistory([]));
const remove = useEventNotStable((id: string) => {
const newRecentSessionHistory = (recentSessionHistory || []).filter(
(item) => item.id !== id,
);
setRecentSessionHistory(newRecentSessionHistory);
});
return [
recentSessionHistory,
{
push,
clear,
remove,
},
] as const;
};
11 changes: 10 additions & 1 deletion react/src/hooks/useBAISetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,16 @@ interface UserSettings {
summary_items?: Array<Omit<SummaryItem, 'data'>>;
selected_language?: string;
classic_session_launcher?: boolean;
recentSessionHistory?: Array<SessionHistory>;
}

export type SessionHistory = {
id: string;
name?: string;
params: string;
createdAt: string;
};

interface GeneralSettings {
last_login?: number;
login_attempt?: number;
Expand All @@ -28,8 +36,9 @@ interface GeneralSettings {
export const useBAISettingUserState = <K extends keyof UserSettings>(
name: K,
): [UserSettings[K], (newValue: UserSettings[K]) => void] => {
return useAtom(SettingAtomFamily('user.' + name));
return useAtom<UserSettings[K]>(SettingAtomFamily('user.' + name));
};

export const useBAISettingGeneralState = <K extends keyof GeneralSettings>(
name: K,
): [GeneralSettings[K], (newValue: GeneralSettings[K]) => void] => {
Expand Down
Loading
Loading