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

Closed
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
44 changes: 43 additions & 1 deletion react/src/components/SessionTemplateModal.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,53 @@
import BAIModal, { BAIModalProps } from './BAIModal';
import { Table, Tabs } from 'antd';
import React from 'react';
import { useTranslation } from 'react-i18next';

interface SessionTemplateModalProps extends BAIModalProps {}
const SessionTemplateModal: React.FC<SessionTemplateModalProps> = ({
...modalProps
}) => {
return <BAIModal {...modalProps}></BAIModal>;
const { t } = useTranslation();
return (
<BAIModal title={t('session.launcher.TemplateAndHistory')} {...modalProps}>
<Tabs
defaultActiveKey="history"
items={[
{
key: 'template',
label: t('session.launcher.Template'),
children: <div>Template</div>,
},
{
key: 'history',
label: t('session.launcher.RecentHistory'),
children: (
<Table
columns={[
{
title: t('session.launcher.SessionName'),
dataIndex: 'sessionName',
},
{
title: t('session.launcher.ResourceAllocation'),
dataIndex: 'resourceAllocation',
},
{
title: t('general.Image'),
dataIndex: 'image',
},
{
title: t('session.launcher.CreatedAt'),
dataIndex: 'createdAt',
},
]}
/>
),
},
]}
/>
</BAIModal>
);
};

export default SessionTemplateModal;
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;
};
10 changes: 9 additions & 1 deletion react/src/hooks/useBAISetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,15 @@ interface UserSettings {
summary_items?: Array<Omit<SummaryItem, 'data'>>;
selected_language?: string;
classic_session_launcher?: boolean;
recentSessionHistory?: Array<SessionHistory>;
}

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

interface GeneralSettings {
last_login?: number;
login_attempt?: number;
Expand All @@ -28,8 +35,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
37 changes: 24 additions & 13 deletions react/src/pages/SessionLauncherPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import SessionOwnerSetterCard, {
SessionOwnerSetterFormValues,
} from '../components/SessionOwnerSetterCard';
import { SessionOwnerSetterPreviewCard } from '../components/SessionOwnerSetterCard';
import SessionTemplateModal from '../components/SessionTemplateModal';
import SourceCodeViewer from '../components/SourceCodeViewer';
import VFolderTableFormItem, {
VFolderTableFormValues,
Expand All @@ -45,7 +46,10 @@ import {
useUpdatableState,
useWebUINavigate,
} from '../hooks';
import { useCurrentUserRole } from '../hooks/backendai';
import {
useCurrentUserRole,
useRecentSessionHistory,
} from '../hooks/backendai';
import { useSetBAINotification } from '../hooks/useBAINotification';
import { useCurrentProjectValue } from '../hooks/useCurrentProject';
import { useThemeMode } from '../hooks/useThemeMode';
Expand All @@ -59,7 +63,7 @@ import {
QuestionCircleOutlined,
RightOutlined,
} from '@ant-design/icons';
import { useDebounceFn } from 'ahooks';
import { useDebounceFn, useToggle } from 'ahooks';
import {
Alert,
App,
Expand Down Expand Up @@ -230,7 +234,10 @@ const SessionLauncherPage = () => {
const webuiNavigate = useWebUINavigate();
const currentProject = useCurrentProjectValue();

const [isOpenTemplateModal, { toggle: toggleIsOpenTemplateModal }] =
useToggle();
const { upsertNotification } = useSetBAINotification();
const [, { push: pushSessionHistory }] = useRecentSessionHistory();

const { run: syncFormToURLWithDebounce } = useDebounceFn(
() => {
Expand Down Expand Up @@ -540,6 +547,7 @@ const SessionLauncherPage = () => {
});
await Promise.all(sessionPromises)
.then(([firstSession]) => {
// pushSessionHistory()
// console.log('##sessionPromises', firstSession);
if (
values.num_of_sessions === 1 &&
Expand Down Expand Up @@ -649,21 +657,22 @@ const SessionLauncherPage = () => {
align="stretch"
style={{ flex: 1, maxWidth: 700 }}
>
{/* <Flex direction="row" justify="between">
<Typography.Title level={3} style={{ marginTop: 0 }}>
<Flex direction="row" justify="between">
<Typography.Title level={4} style={{ marginTop: 0 }}>
{t('session.launcher.StartNewSession')}
</Typography.Title>
<Flex direction="row" gap={'sm'}>
<Button
type="link"
icon={<BlockOutlined />}
disabled
// icon={<BlockOutlined />}
// disabled
style={{ paddingRight: 0, paddingLeft: 0 }}
onClick={() => toggleIsOpenTemplateModal()}
>
{t('session.launcher.TemplateAndHistory')}
</Button>
</Flex>
</Flex> */}
</Flex>
{/* <Suspense fallback={<FlexActivityIndicator />}> */}
<Form.Provider
onFormChange={(name, info) => {
Expand Down Expand Up @@ -1769,13 +1778,15 @@ const SessionLauncherPage = () => {
</Flex>
)}
</Flex>
{/* <FolderExplorer
folderName={selectedFolderName}
open={!!selectedFolderName}
onRequestClose={() => {
setSelectedFolderName(undefined);
<SessionTemplateModal
open={isOpenTemplateModal}
onCancel={() => {
toggleIsOpenTemplateModal();
}}
onOk={() => {
toggleIsOpenTemplateModal();
}}
/> */}
/>
{currentStep === steps.length - 1 ? (
<ErrorBoundary fallback={null}>
<SessionLauncherValidationTour
Expand Down
2 changes: 2 additions & 0 deletions react/src/react-app-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ type DeepPartial<T> = {
: T[P];
};

type SelectivePartial<T, K extends keyof T> = Partial<Pick<T, K>> & Omit<T, K>;

type NonNullableItem<T> = NonNullable<NonNullable<NonNullable<T>['items']>>[0];

type NonNullableNodeOnEdges<T extends RelayConnection | null> = NonNullable<
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Das Format der Anschlussnummer ist falsch.",
"DuplicatedPort": "Es gibt doppelte Anschlüsse.",
"FolderAliasOverlappingToAutoMount": "Es existiert ein Auto-Mount-Ordner mit demselben Namen.",
"InsufficientAllocationOfResourcesWarning": "Die zuweisbaren Ressourcen liegen unter der im ausgewählten Bild erforderlichen Mindestressource."
"InsufficientAllocationOfResourcesWarning": "Die zuweisbaren Ressourcen liegen unter der im ausgewählten Bild erforderlichen Mindestressource.",
"RecentHistory": "Jüngste Sitzungen"
},
"Preparing": "Vorbereitung...",
"PreparingSession": "Sitzung vorbereiten...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/el.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Η μορφή του αριθμού θύρας είναι λανθασμένη.",
"DuplicatedPort": "Υπάρχουν διπλές θύρες.",
"FolderAliasOverlappingToAutoMount": "Υπάρχει ένας φάκελος αυτόματης προσάρτησης με το ίδιο όνομα.",
"InsufficientAllocationOfResourcesWarning": "Οι κατανεμητέοι πόροι πέφτουν κάτω από τον ελάχιστο απαιτούμενο πόρο στην επιλεγμένη εικόνα."
"InsufficientAllocationOfResourcesWarning": "Οι κατανεμητέοι πόροι πέφτουν κάτω από τον ελάχιστο απαιτούμενο πόρο στην επιλεγμένη εικόνα.",
"RecentHistory": "Πρόσφατες συνεδρίες"
},
"Preparing": "Προετοιμασία ...",
"PreparingSession": "Προετοιμασία συνεδρίας ...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,8 @@
"InvalidPortFormat": "The port number format is incorrect.",
"DuplicatedPort": "There are duplicate ports.",
"FolderAliasOverlappingToAutoMount": "An auto-mount folder with the same name exists.",
"InsufficientAllocationOfResourcesWarning": "Allocatable resources falls below the minimum resource required in the selected image."
"InsufficientAllocationOfResourcesWarning": "Allocatable resources falls below the minimum resource required in the selected image.",
"RecentHistory": "Recent Sessions"
},
"Preparing": "Preparing...",
"PreparingSession": "Preparing session...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1300,7 +1300,8 @@
"InvalidPortFormat": "El formato del número de puerto es incorrecto.",
"DuplicatedPort": "Hay puertos duplicados.",
"FolderAliasOverlappingToAutoMount": "Existe una carpeta de montaje automático con el mismo nombre.",
"InsufficientAllocationOfResourcesWarning": "Los recursos asignables están por debajo del recurso mínimo requerido en la imagen seleccionada."
"InsufficientAllocationOfResourcesWarning": "Los recursos asignables están por debajo del recurso mínimo requerido en la imagen seleccionada.",
"RecentHistory": "Sesiones recientes"
},
"ExpiresAfter": "Tiempo restante",
"CPU": "CPU",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1297,7 +1297,8 @@
"InvalidPortFormat": "Porttinumeron muoto on virheellinen.",
"DuplicatedPort": "Portteja on päällekkäin.",
"FolderAliasOverlappingToAutoMount": "Samanniminen automaattinen kiinnityskansio on olemassa.",
"InsufficientAllocationOfResourcesWarning": "Allokoitavat resurssit jäävät alle valitussa kuvassa vaaditun vähimmäisresurssin."
"InsufficientAllocationOfResourcesWarning": "Allokoitavat resurssit jäävät alle valitussa kuvassa vaaditun vähimmäisresurssin.",
"RecentHistory": "Viimeisimmät istunnot"
},
"ExpiresAfter": "Jäljellä oleva aika",
"CPU": "CPU",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Le format du numéro de port est incorrect.",
"DuplicatedPort": "Il y a des ports en double.",
"FolderAliasOverlappingToAutoMount": "Il existe un dossier de montage automatique portant le même nom.",
"InsufficientAllocationOfResourcesWarning": "Les ressources allouables sont inférieures à la ressource minimale requise dans l'image sélectionnée."
"InsufficientAllocationOfResourcesWarning": "Les ressources allouables sont inférieures à la ressource minimale requise dans l'image sélectionnée.",
"RecentHistory": "Sessions récentes"
},
"Preparing": "En train de préparer...",
"PreparingSession": "Séance de préparation...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,8 @@
"InvalidPortFormat": "Format nomor port salah.",
"DuplicatedPort": "Terdapat port ganda.",
"FolderAliasOverlappingToAutoMount": "Folder pemasangan otomatis dengan nama yang sama tersedia.",
"InsufficientAllocationOfResourcesWarning": "Sumber daya yang dapat dialokasikan berada di bawah sumber daya minimum yang diperlukan pada gambar yang dipilih."
"InsufficientAllocationOfResourcesWarning": "Sumber daya yang dapat dialokasikan berada di bawah sumber daya minimum yang diperlukan pada gambar yang dipilih.",
"RecentHistory": "Sesi Terbaru"
},
"Preparing": "Mempersiapkan...",
"PreparingSession": "Mempersiapkan sesi...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Il formato del numero di porta non è corretto.",
"DuplicatedPort": "Ci sono porte duplicate.",
"FolderAliasOverlappingToAutoMount": "Esiste una cartella di montaggio automatico con lo stesso nome.",
"InsufficientAllocationOfResourcesWarning": "Le risorse assegnabili sono inferiori alla risorsa minima richiesta nell'immagine selezionata."
"InsufficientAllocationOfResourcesWarning": "Le risorse assegnabili sono inferiori alla risorsa minima richiesta nell'immagine selezionata.",
"RecentHistory": "Sessioni recenti"
},
"Preparing": "Preparazione...",
"PreparingSession": "Preparazione della sessione...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "ポート番号の形式が正しくない。",
"DuplicatedPort": "ポートが重複している。",
"FolderAliasOverlappingToAutoMount": "同名の自動マウントフォルダが存在する。",
"InsufficientAllocationOfResourcesWarning": "割り当て可能なリソースが、選択したイメージに必要な最小リソースを下回ります。"
"InsufficientAllocationOfResourcesWarning": "割り当て可能なリソースが、選択したイメージに必要な最小リソースを下回ります。",
"RecentHistory": "最近のセッション"
},
"Preparing": "準備...",
"PreparingSession": "セッションの準備...",
Expand Down
4 changes: 3 additions & 1 deletion resources/i18n/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,9 @@
"InvalidPortFormat": "포트 형식이 올바르지 않습니다.",
"DuplicatedPort": "중복된 포트가 있습니다.",
"FolderAliasOverlappingToAutoMount": "동일한 이름의 자동 마운트 폴더가 존재합니다.",
"InsufficientAllocationOfResourcesWarning": "할당 가능한 자원이 선택된 이미지에서 요구되는 최소 자원보다 부족합니다."
"InsufficientAllocationOfResourcesWarning": "할당 가능한 자원이 선택된 이미지에서 요구되는 최소 자원보다 부족합니다.",
"RecentHistory": "최근 세션",
"CreatedAt": "생성 시간"
},
"Preparing": "준비중...",
"PreparingSession": "세션 준비중...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/mn.json
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,8 @@
"InvalidPortFormat": "Портын дугаарын формат буруу байна.",
"DuplicatedPort": "Давхардсан портууд байна.",
"FolderAliasOverlappingToAutoMount": "Ижил нэртэй автоматаар холбох хавтас байна.",
"InsufficientAllocationOfResourcesWarning": "Хуваарилах нөөц нь сонгосон зурагт шаардагдах хамгийн бага нөөцөөс доогуур байна."
"InsufficientAllocationOfResourcesWarning": "Хуваарилах нөөц нь сонгосон зурагт шаардагдах хамгийн бага нөөцөөс доогуур байна.",
"RecentHistory": "Сүүлийн хуралдаанууд"
},
"Preparing": "Бэлтгэж байна ...",
"PreparingSession": "Session бэлтгэж байна ...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/ms.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Format nombor port tidak betul.",
"DuplicatedPort": "Terdapat port pendua.",
"FolderAliasOverlappingToAutoMount": "Folder auto-lekap dengan nama yang sama wujud.",
"InsufficientAllocationOfResourcesWarning": "Sumber yang boleh diperuntukkan berada di bawah sumber minimum yang diperlukan dalam imej yang dipilih."
"InsufficientAllocationOfResourcesWarning": "Sumber yang boleh diperuntukkan berada di bawah sumber minimum yang diperlukan dalam imej yang dipilih.",
"RecentHistory": "Sesi Terkini"
},
"Preparing": "Menyiapkan ...",
"PreparingSession": "Menyiapkan sesi ...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "Format numeru portu jest nieprawidłowy.",
"DuplicatedPort": "Istnieją zduplikowane porty.",
"FolderAliasOverlappingToAutoMount": "Istnieje folder automatycznego montażu o tej samej nazwie.",
"InsufficientAllocationOfResourcesWarning": "Zasoby, które można przydzielić, są mniejsze niż minimalne zasoby wymagane w wybranym obrazie."
"InsufficientAllocationOfResourcesWarning": "Zasoby, które można przydzielić, są mniejsze niż minimalne zasoby wymagane w wybranym obrazie.",
"RecentHistory": "Ostatnie sesje"
},
"Preparing": "Przygotowuję...",
"PreparingSession": "Przygotowuję sesję...",
Expand Down
3 changes: 2 additions & 1 deletion resources/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@
"InvalidPortFormat": "O formato do número da porta está incorreto.",
"DuplicatedPort": "Existem portas duplicadas.",
"FolderAliasOverlappingToAutoMount": "Existe uma pasta de montagem automática com o mesmo nome.",
"InsufficientAllocationOfResourcesWarning": "Os recursos alocáveis ​​ficam abaixo do recurso mínimo exigido na imagem selecionada."
"InsufficientAllocationOfResourcesWarning": "Os recursos alocáveis ​​ficam abaixo do recurso mínimo exigido na imagem selecionada.",
"RecentHistory": "Sessões recentes"
},
"Preparing": "Preparando...",
"PreparingSession": "Preparando sessão ...",
Expand Down
Loading
Loading