File size: 7,317 Bytes
8085285
3c8d218
 
 
 
 
 
8085285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c8d218
 
1e24842
3c8d218
 
 
 
 
 
 
 
 
ef865f2
 
8085285
ef865f2
 
 
 
 
 
 
 
 
3c8d218
8085285
 
 
 
 
3c8d218
 
 
 
 
 
 
 
 
 
8085285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c8d218
 
1e24842
3c8d218
 
1e24842
3c8d218
 
1e24842
3c8d218
 
 
 
 
 
 
 
 
 
8085285
f1c3c6d
 
 
1e24842
 
 
3c8d218
8085285
 
3c8d218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8085285
 
 
3c8d218
1e24842
3c8d218
 
 
 
 
 
 
 
 
 
 
1e24842
3c8d218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
3c8d218
 
 
 
 
 
 
 
 
 
 
 
1e24842
 
 
3c8d218
 
 
 
 
 
6270070
 
ef865f2
 
 
 
3c8d218
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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>
  );
};