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 #2772

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 1 addition & 1 deletion react/src/components/DynamicStepInputNumber.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const DynamicInputNumber: React.FC<DynamicInputNumberProps> = ({
const [key, updateKey] = useUpdatableState('first');
useEffect(() => {
setTimeout(() => {
updateKey(value);
updateKey(value.toString());
}, 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Expand Down
2 changes: 1 addition & 1 deletion react/src/components/DynamicUnitInputNumberWithSlider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const DynamicUnitInputNumberWithSlider: React.FC<
const [key, updateKey] = useUpdatableState('first');
useEffect(() => {
setTimeout(() => {
updateKey(value);
updateKey(value?.toString());
}, 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
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;
20 changes: 14 additions & 6 deletions react/src/components/VFolderTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@ import { ColumnsType } from 'antd/lib/table';
import graphql from 'babel-plugin-relay/macro';
import dayjs from 'dayjs';
import _ from 'lodash';
import React, { useEffect, useMemo, useState, useTransition } from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useState,
useTransition,
} from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useLazyLoadQuery } from 'react-relay';

Expand Down Expand Up @@ -244,22 +250,23 @@ const VFolderTable: React.FC<VFolderTableProps> = ({
* @param input - The input path to be converted.
* @returns The aliased path based on the name and input.
*/
const inputToAliasPath = useEventNotStable(
const inputToAliasPath = useCallback(
(name: VFolderKey, input?: string) => {
if (_.isEmpty(input)) {
if (input === undefined || input === '') {
return `${aliasBasePath}${name}`;
} else if (input?.startsWith('/')) {
} else if (input.startsWith('/')) {
return input;
} else {
return `${aliasBasePath}${input}`;
}
},
[aliasBasePath],
);

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 @@ -526,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 @@ -535,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;
};
Loading
Loading