Spaces:
Runtime error
Runtime error
Download frontend-react/src/components/AppContext.jsx from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/frontend-react/src/components/AppContext.jsx
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing/frontend-react/src/components/AppContext.jsx
-
curl -L -o AppContext.jsx https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/frontend-react/src/components/AppContext.jsx
7.32 kB
| import React, { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react'; | |
| import { SessionService, SpecService, CredentialService } from '../services/api'; | |
| const AppContext = createContext(); | |
| export const useAppContext = () => useContext(AppContext); | |
| const LS_SPEC_ID = 'app_activeSpecId'; | |
| const LS_PLAN = 'app_executionPlan'; | |
| const LS_SCENARIO = 'app_scenario'; | |
| function lsGet(key, fallback = null) { | |
| try { const v = localStorage.getItem(key); return v !== null ? JSON.parse(v) : fallback; } | |
| catch { return fallback; } | |
| } | |
| function lsSet(key, value) { | |
| try { localStorage.setItem(key, JSON.stringify(value)); } catch {} | |
| } | |
| function lsDel(key) { | |
| try { localStorage.removeItem(key); } catch {} | |
| } | |
| export const AppProvider = ({ children }) => { | |
| const [sessionId, setSessionId] = useState(null); | |
| const [specs, setSpecs] = useState([]); | |
| const [activeSpecId, setActiveSpecId] = useState(null); | |
| const [activeSpecName, setActiveSpecName] = useState('None'); | |
| const [activeBaseUrl, setActiveBaseUrl] = useState(''); | |
| const [parsedSpec, setParsedSpec] = useState(null); | |
| const [storedCredentials, setStoredCredentials] = useState({}); | |
| const [sessionContextVars, setSessionContextVars] = useState({}); | |
| const [executionPlan, setExecutionPlan] = useState(null); | |
| const [scenario, setScenario] = useState(''); | |
| const [isLoading, setIsLoading] = useState(true); | |
| const [globalChatId, setGlobalChatId] = useState(null); | |
| const [toasts, setToasts] = useState([]); | |
| const persistReady = useRef(false); | |
| const addToast = useCallback((type, message) => { | |
| const id = Date.now() + Math.random(); | |
| setToasts(prev => [...prev, { id, type, message }]); | |
| }, []); | |
| const removeToast = useCallback((id) => { | |
| setToasts(prev => prev.filter(t => t.id !== id)); | |
| }, []); | |
| // Persist plan + scenario whenever they change (skip the initial mount values) | |
| useEffect(() => { if (persistReady.current) lsSet(LS_PLAN, executionPlan); }, [executionPlan]); | |
| useEffect(() => { if (persistReady.current) lsSet(LS_SCENARIO, scenario); }, [scenario]); | |
| // Initialize Session + restore last active spec | |
| useEffect(() => { | |
| const initSession = async () => { | |
| try { | |
| const data = await SessionService.createSession(); | |
| setSessionId(data.session_id); | |
| } catch (err) { | |
| console.error("Failed to init session", err); | |
| } | |
| }; | |
| initSession(); | |
| const init = async () => { | |
| await fetchSpecs(); | |
| const savedSpecId = lsGet(LS_SPEC_ID); | |
| if (savedSpecId) { | |
| try { | |
| const data = await SpecService.getSpec(savedSpecId); | |
| setParsedSpec(data.parsed_spec); | |
| setActiveSpecName(data.name); | |
| setActiveSpecId(data.id); | |
| const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || ''; | |
| setActiveBaseUrl(resolvedBaseUrl); | |
| const creds = await CredentialService.getCredentials(savedSpecId); | |
| setStoredCredentials(creds || {}); | |
| // Restore plan + scenario saved before refresh | |
| const savedPlan = lsGet(LS_PLAN); | |
| const savedScenario = lsGet(LS_SCENARIO, ''); | |
| if (savedPlan) setExecutionPlan(savedPlan); | |
| if (savedScenario) setScenario(savedScenario); | |
| } catch (err) { | |
| console.error("Failed to restore saved spec", err); | |
| lsDel(LS_SPEC_ID); | |
| } | |
| } | |
| persistReady.current = true; | |
| }; | |
| init(); | |
| }, []); | |
| const fetchSpecs = async () => { | |
| try { | |
| const data = await SpecService.getAllSpecs(); | |
| setSpecs(data); | |
| setIsLoading(false); | |
| } catch (err) { | |
| console.error("Failed to fetch specs", err); | |
| setIsLoading(false); | |
| } | |
| }; | |
| const loadSpec = async (id) => { | |
| try { | |
| const data = await SpecService.getSpec(id); | |
| setParsedSpec(data.parsed_spec); | |
| setActiveSpecName(data.name); | |
| setActiveSpecId(data.id); | |
| lsSet(LS_SPEC_ID, data.id); | |
| // Use saved base_url; fall back to the suggested URL extracted from the spec's servers list | |
| const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || ''; | |
| setActiveBaseUrl(resolvedBaseUrl); | |
| // Keep testing workspace fresh; history preserves past runs | |
| setExecutionPlan(null); | |
| setScenario(''); | |
| lsDel(LS_PLAN); | |
| lsDel(LS_SCENARIO); | |
| const creds = await CredentialService.getCredentials(id); | |
| setStoredCredentials(creds || {}); | |
| setSessionContextVars({}); | |
| } catch (err) { | |
| console.error("Failed to load spec", err); | |
| } | |
| }; | |
| const saveProfile = async (payload) => { | |
| if (!activeSpecId) return; | |
| try { | |
| const data = await CredentialService.saveCredentials(activeSpecId, payload); | |
| setStoredCredentials(data.credentials || {}); | |
| } catch (err) { | |
| console.error("Failed to save credentials", err); | |
| throw err; | |
| } | |
| }; | |
| const deleteSpec = async (id) => { | |
| try { | |
| await SpecService.deleteSpec(id); | |
| if (activeSpecId === id) { | |
| setActiveSpecId(null); | |
| setActiveSpecName('None'); | |
| setParsedSpec(null); | |
| setActiveBaseUrl(''); | |
| setExecutionPlan(null); | |
| setStoredCredentials({}); | |
| lsDel(LS_SPEC_ID); | |
| lsDel(LS_PLAN); | |
| lsDel(LS_SCENARIO); | |
| } | |
| fetchSpecs(); | |
| } catch (err) { | |
| console.error("Failed to delete spec", err); | |
| } | |
| }; | |
| const refreshSessionContext = async () => { | |
| if (!sessionId) return; | |
| try { | |
| const data = await SessionService.getContext(sessionId); | |
| setSessionContextVars(data || {}); | |
| } catch (err) { | |
| console.error("Failed to refresh session context", err); | |
| } | |
| }; | |
| const importSession = async (sessionData) => { | |
| if (sessionData.spec_id && sessionData.spec_id !== activeSpecId) { | |
| await loadSpec(sessionData.spec_id); | |
| } | |
| if (sessionData.stepsForImport) { | |
| setExecutionPlan(sessionData.stepsForImport); | |
| } else if (sessionData.steps) { | |
| setExecutionPlan(sessionData.steps); | |
| } | |
| if (sessionData.scenario) { | |
| setScenario(sessionData.scenario); | |
| } | |
| }; | |
| const startNewSession = async () => { | |
| try { | |
| const data = await SessionService.createSession(); | |
| setSessionId(data.session_id); | |
| setSessionContextVars({}); | |
| return data.session_id; | |
| } catch (err) { | |
| console.error("Failed to start new session", err); | |
| return null; | |
| } | |
| }; | |
| return ( | |
| <AppContext.Provider | |
| value={{ | |
| sessionId, | |
| specs, | |
| // Legacy alias so components migrated incrementally don't break | |
| collections: specs, | |
| activeSpecId, | |
| activeSpecName, | |
| activeBaseUrl, | |
| parsedSpec, | |
| storedCredentials, | |
| sessionContextVars, | |
| executionPlan, | |
| scenario, | |
| isLoading, | |
| setActiveBaseUrl, | |
| setExecutionPlan, | |
| setStoredCredentials, | |
| fetchSpecs, | |
| // Legacy alias | |
| fetchCollections: fetchSpecs, | |
| loadSpec, | |
| deleteSpec, | |
| refreshSessionContext, | |
| saveProfile, | |
| setScenario, | |
| importSession, | |
| startNewSession, | |
| globalChatId, | |
| setGlobalChatId, | |
| toasts, | |
| addToast, | |
| removeToast, | |
| }} | |
| > | |
| {children} | |
| </AppContext.Provider> | |
| ); | |
| }; | |