Amitkasar commited on
Commit
8085285
·
1 Parent(s): aede794

Remove binary files from tracking

Browse files
.dockerignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .env.*
3
+ frontend-react/
4
+ __pycache__
5
+ **/__pycache__
6
+ *.pyc
7
+ .git
8
+ .claude
9
+ backend/uploads/*
10
+ !backend/uploads/.gitkeep
.vercelignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ backend/
2
+ alembic/
3
+ alembic.ini
4
+ requirements.txt
5
+ Procfile
6
+ runtime.txt
7
+ Dockerfile
8
+ .dockerignore
9
+ pytest.ini
10
+ start.ps1
11
+ *.md
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Copy project files
10
+ COPY . .
11
+
12
+ # Create upload directories
13
+ RUN mkdir -p backend/uploads/audio backend/uploads/video backend/uploads/documents backend/uploads/images backend/uploads/specs
14
+
15
+ EXPOSE 7860
16
+
17
+ CMD ["gunicorn", "backend.main:app", "-w", "2", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:7860", "--timeout", "120"]
Project_diagrams.md ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # System Architecture — AI API Testing Assistant
2
+
3
+ ---
4
+
5
+ ## 1. High-Level System Overview
6
+
7
+ ```mermaid
8
+ graph TB
9
+ subgraph CLIENT["🖥️ Client Layer"]
10
+ UI["React + Vite SPA<br/>(frontend-react)"]
11
+ end
12
+
13
+ subgraph BACKEND["⚙️ Backend Layer (FastAPI)"]
14
+ MW["Middleware Stack<br/>(CORS · JWT Auth · Rate Limiter · Logger)"]
15
+ API["REST API Router<br/>/api/v1"]
16
+ SVC["Service Layer"]
17
+ INT["Integrations"]
18
+ end
19
+
20
+ subgraph DATA["🗄️ Data Layer"]
21
+ PG[("PostgreSQL<br/>(via SQLAlchemy)")]
22
+ FS["File Storage<br/>(Uploads Dir / Supabase)"]
23
+ ALB["Alembic<br/>Migrations"]
24
+ end
25
+
26
+ subgraph LLM["🤖 LLM Providers"]
27
+ MISTRAL["Mistral AI"]
28
+ OPENAI["OpenAI"]
29
+ ANTHROPIC["Anthropic Claude"]
30
+ GEMINI["Google Gemini"]
31
+ GROQ["Groq"]
32
+ end
33
+
34
+ subgraph EXT["🌐 External APIs Under Test"]
35
+ TARGET["Target REST APIs<br/>(user-specified base URL)"]
36
+ end
37
+
38
+ UI -->|"HTTPS / REST (JWT)"| MW
39
+ MW --> API
40
+ API --> SVC
41
+ SVC --> INT
42
+ SVC --> PG
43
+ SVC --> FS
44
+ INT -->|"LangChain"| MISTRAL
45
+ INT -->|"LangChain"| OPENAI
46
+ INT -->|"LangChain"| ANTHROPIC
47
+ INT -->|"LangChain"| GEMINI
48
+ INT -->|"LangChain"| GROQ
49
+ SVC -->|"HTTP Requests"| TARGET
50
+ ALB -.->|"schema migrations"| PG
51
+ ```
52
+
53
+ ---
54
+
55
+ ## 2. Frontend Architecture (React SPA)
56
+
57
+ ```mermaid
58
+ graph TD
59
+ subgraph ENTRY["Entry Point"]
60
+ MAIN["main.jsx"]
61
+ APP["App.jsx<br/>(routing + layout)"]
62
+ end
63
+
64
+ subgraph PAGES["Pages"]
65
+ SPECS["SpecsPage<br/>Upload & manage API specs"]
66
+ EXEC["Execution<br/>(workflow/WorkflowPage)"]
67
+ HIST["HistoryPage<br/>Test run history"]
68
+ CHAT["ChatAssistant<br/>AI assistant chat"]
69
+ MEDIA["MediaHubPage<br/>Assets & media"]
70
+ COLL["CollectionsPage<br/>Asset collections"]
71
+ USAGE["UsagePage<br/>LLM token usage"]
72
+ SETTINGS["SettingsPage<br/>LLM provider config"]
73
+ PROFILE["ProfilePage<br/>User profile"]
74
+ LOGIN["LoginPage<br/>JWT auth"]
75
+ end
76
+
77
+ subgraph SHARED["Shared Components"]
78
+ CTX["AppContext.jsx<br/>(React Context — global state)"]
79
+ TOAST["Toast.jsx"]
80
+ ERR["ErrorBoundary.jsx"]
81
+ end
82
+
83
+ subgraph SVCL["API Service Layer"]
84
+ AXIO["services/<br/>Axios calls to /api/v1"]
85
+ end
86
+
87
+ MAIN --> APP
88
+ APP --> CTX
89
+ APP --> PAGES
90
+ PAGES --> SVCL
91
+ SVCL -->|"REST + JWT Bearer"| BACKEND
92
+ PAGES --> SHARED
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 3. Backend API Routes
98
+
99
+ ```mermaid
100
+ graph LR
101
+ subgraph ROUTER["FastAPI Router (/api/v1)"]
102
+ AUTH["/auth<br/>🔓 Public<br/>Login · Register"]
103
+ SPEC["/specs<br/>🔐 Protected<br/>Upload Postman / Swagger"]
104
+ SESS["/sessions<br/>🔐 Protected<br/>CRUD test sessions"]
105
+ EXEC["/execution<br/>🔐 Protected<br/>Plan · Run · Analyze steps"]
106
+ HIST["/history<br/>🔐 Protected<br/>Execution history"]
107
+ CHAT["/chat<br/>🔐 Protected<br/>AI assistant messages"]
108
+ ASSET["/assets<br/>🔐 Protected<br/>File uploads (media/docs)"]
109
+ USE["/usage<br/>🔐 Protected<br/>LLM token usage stats"]
110
+ SET["/settings<br/>🔐 Protected<br/>LLM provider & model config"]
111
+ end
112
+
113
+ AUTH -->|"issues JWT"| CLIENT
114
+ SPEC --> postman_parser & swagger_parser
115
+ EXEC --> llm_planner & api_executor & response_analyzer
116
+ CHAT --> chat_assistant
117
+ ASSET --> asset_service
118
+ USE --> usage_service
119
+ SET --> llm_factory["LLM Factory<br/>(provider registry)"]
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 4. Service Layer Internals
125
+
126
+ ```mermaid
127
+ graph TD
128
+ subgraph SERVICES["backend/services/"]
129
+ PP["postman_parser.py<br/>Parse Postman collections"]
130
+ SP["swagger_parser.py<br/>Parse OpenAPI / Swagger specs"]
131
+ LP["llm_planner.py<br/>Generate AI execution plans"]
132
+ AE["api_executor.py<br/>Execute HTTP steps"]
133
+ RA["response_analyzer.py<br/>Analyze API responses with LLM"]
134
+ CA["chat_assistant.py<br/>AI chat with context"]
135
+ AS["asset_service.py<br/>Manage file assets"]
136
+ CM["context_manager.py<br/>Track session variables"]
137
+ ST["storage.py<br/>File I/O & Supabase storage"]
138
+ US["usage_service.py<br/>Track LLM token consumption"]
139
+ end
140
+
141
+ PP -->|parsed endpoints| LP
142
+ SP -->|parsed endpoints| LP
143
+ LP -->|execution plan JSON| AE
144
+ AE -->|request + response| RA
145
+ RA -->|analysis JSON| DB[(PostgreSQL)]
146
+ CA -->|chat history| DB
147
+ CM -->|context vars| AE
148
+ AS --> ST
149
+ US --> DB
150
+ LP --> LLM_INT["LLM Integration Layer"]
151
+ RA --> LLM_INT
152
+ CA --> LLM_INT
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 5. LLM Integration Layer
158
+
159
+ ```mermaid
160
+ graph TD
161
+ subgraph INTEGRATIONS["backend/integrations/llm/"]
162
+ FAC["factory.py<br/>LLMClientFactory"]
163
+ REG["registry.py<br/>Provider Registry"]
164
+ RES["resolver.py<br/>Task→Provider resolver"]
165
+ BASE["base.py<br/>BaseLLMClient (ABC)"]
166
+ PROV["providers.py<br/>Concrete Clients"]
167
+ end
168
+
169
+ subgraph PROVIDERS["LLM Provider Clients"]
170
+ MC["MistralClient"]
171
+ OC["OpenAIClient"]
172
+ AC["AnthropicClient"]
173
+ GC["GeminiClient"]
174
+ GRC["GroqClient"]
175
+ end
176
+
177
+ subgraph TASK_CONFIG["DB: llm_task_config"]
178
+ T1["plan_generation → provider + model"]
179
+ T2["step_execution → provider + model"]
180
+ T3["response_analysis → provider + model"]
181
+ T4["chat → provider + model"]
182
+ end
183
+
184
+ FAC --> REG
185
+ REG --> RES
186
+ RES -->|reads| TASK_CONFIG
187
+ FAC --> BASE
188
+ BASE --> PROV
189
+ PROV --> MC & OC & AC & GC & GRC
190
+ MC -->|"LangChain"| MistralAI_API["Mistral AI API"]
191
+ OC -->|"LangChain"| OpenAI_API["OpenAI API"]
192
+ AC -->|"LangChain"| Anthropic_API["Anthropic API"]
193
+ GC -->|"LangChain"| Gemini_API["Google Gemini API"]
194
+ GRC -->|"LangChain"| Groq_API["Groq API"]
195
+ ```
196
+
197
+ ---
198
+
199
+ ## 6. Database Schema (ERD)
200
+
201
+ ```mermaid
202
+ erDiagram
203
+ spec_documents {
204
+ string id PK
205
+ string name
206
+ text raw_content
207
+ json parsed_json
208
+ string base_url
209
+ json login_credentials
210
+ json execution_plan
211
+ text scenario
212
+ string file_path
213
+ datetime uploaded_at
214
+ }
215
+
216
+ sessions {
217
+ string id PK
218
+ string user_id
219
+ string spec_id FK
220
+ string spec_name
221
+ string base_url
222
+ text scenario
223
+ json context_variables
224
+ datetime created_at
225
+ }
226
+
227
+ execution_history {
228
+ int id PK
229
+ string session_id
230
+ int step
231
+ json request_json
232
+ json response_json
233
+ json analysis_json
234
+ json step_definition_json
235
+ datetime timestamp
236
+ }
237
+
238
+ collections {
239
+ string id PK
240
+ string name
241
+ text description
242
+ string spec_id FK
243
+ datetime created_at
244
+ }
245
+
246
+ assets {
247
+ string id PK
248
+ string name
249
+ string file_type
250
+ string file_path
251
+ int file_size
252
+ string category
253
+ text description
254
+ json tags
255
+ json metadata_json
256
+ string spec_id FK
257
+ datetime uploaded_at
258
+ }
259
+
260
+ asset_collections {
261
+ string asset_id FK
262
+ string collection_id FK
263
+ }
264
+
265
+ chat_sessions {
266
+ string id PK
267
+ string user_id
268
+ string name
269
+ string spec_id FK
270
+ string session_id
271
+ datetime created_at
272
+ datetime updated_at
273
+ }
274
+
275
+ chat_messages {
276
+ int id PK
277
+ string chat_session_id FK
278
+ string role
279
+ text content
280
+ json action_json
281
+ datetime timestamp
282
+ }
283
+
284
+ llm_usage {
285
+ int id PK
286
+ string session_id
287
+ string user_id
288
+ string call_type
289
+ int prompt_tokens
290
+ int completion_tokens
291
+ int total_tokens
292
+ datetime timestamp
293
+ }
294
+
295
+ llm_providers {
296
+ string provider_id PK
297
+ json api_key_enc
298
+ boolean is_active
299
+ }
300
+
301
+ llm_task_config {
302
+ string task_name PK
303
+ string provider_id FK
304
+ string model_name
305
+ float temperature
306
+ }
307
+
308
+ spec_documents ||--o{ sessions : "has"
309
+ spec_documents ||--o{ assets : "has"
310
+ spec_documents ||--o{ collections : "has"
311
+ spec_documents ||--o{ chat_sessions : "linked to"
312
+ assets }o--o{ collections : "asset_collections"
313
+ chat_sessions ||--o{ chat_messages : "contains"
314
+ llm_providers ||--o{ llm_task_config : "configures"
315
+ ```
316
+
317
+ ---
318
+
319
+ ## 7. Authentication & Security Flow
320
+
321
+ ```mermaid
322
+ sequenceDiagram
323
+ participant Browser as 🖥️ Browser (React)
324
+ participant API as ⚙️ FastAPI
325
+ participant JWT as 🔑 JWT Middleware
326
+ participant DB as 🗄️ PostgreSQL
327
+ participant Enc as 🔒 Fernet Encryption
328
+
329
+ Browser->>API: POST /api/v1/auth/login
330
+ API->>DB: validate credentials
331
+ DB-->>API: user record
332
+ API-->>Browser: JWT token (HS256)
333
+
334
+ Browser->>API: GET /api/v1/specs (Bearer token)
335
+ API->>JWT: extract_user_state middleware
336
+ JWT->>JWT: decode JWT (HS256 + JWT_SECRET)
337
+ JWT-->>API: request.state.user = user_id
338
+ API->>API: verify_token dependency
339
+ API->>DB: fetch protected data
340
+ DB-->>API: result
341
+ API-->>Browser: JSON response
342
+
343
+ Note over API,Enc: LLM API keys stored<br/>encrypted with Fernet<br/>(ENCRYPTION_KEY from .env)
344
+ API->>Enc: decrypt api_key_enc on use
345
+ Enc-->>API: plaintext API key
346
+ ```
347
+
348
+ ---
349
+
350
+ ## 8. API Test Execution Flow
351
+
352
+ ```mermaid
353
+ sequenceDiagram
354
+ participant User as 👤 User
355
+ participant FE as 🖥️ Frontend
356
+ participant BE as ⚙️ Backend
357
+ participant LLM as 🤖 LLM Provider
358
+ participant Target as 🌐 Target API
359
+
360
+ User->>FE: Upload Postman/Swagger spec
361
+ FE->>BE: POST /api/v1/specs
362
+ BE->>BE: postman_parser / swagger_parser
363
+ BE-->>FE: spec_id + parsed endpoints
364
+
365
+ User->>FE: Set base URL + scenario
366
+ FE->>BE: POST /api/v1/sessions
367
+ BE-->>FE: session_id
368
+
369
+ User->>FE: Generate execution plan
370
+ FE->>BE: POST /api/v1/execution/plan
371
+ BE->>LLM: llm_planner (prompt with endpoints + scenario)
372
+ LLM-->>BE: structured execution plan (JSON)
373
+ BE-->>FE: plan steps
374
+
375
+ loop For each step
376
+ User->>FE: Run step
377
+ FE->>BE: POST /api/v1/execution/step
378
+ BE->>BE: context_manager (resolve variables)
379
+ BE->>Target: HTTP request (with auth headers)
380
+ Target-->>BE: HTTP response
381
+ BE->>LLM: response_analyzer (analyze result)
382
+ LLM-->>BE: analysis + pass/fail verdict
383
+ BE->>DB: save execution_history
384
+ BE-->>FE: step result + analysis
385
+ end
386
+ ```
387
+
388
+ ---
389
+
390
+ ## 9. Technology Stack Summary
391
+
392
+ | Layer | Technology |
393
+ |---|---|
394
+ | **Frontend** | React 18, Vite, Vanilla CSS |
395
+ | **Backend** | FastAPI (Python), Uvicorn |
396
+ | **Database** | PostgreSQL (SQLAlchemy ORM, Alembic migrations) |
397
+ | **File Storage** | Local filesystem / Supabase Storage |
398
+ | **Authentication** | JWT (HS256), Fernet encryption for secrets |
399
+ | **LLM Integration** | LangChain (Mistral, OpenAI, Anthropic, Gemini, Groq) |
400
+ | **Rate Limiting** | SlowAPI |
401
+ | **Deployment** | Procfile (Heroku-style), `runtime.txt` |
SYSTEM_ARCHITECTURE.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```mermaid
2
+ graph TB
3
+ subgraph CLIENT["🖥️ Frontend — React + Vite SPA"]
4
+ PAGES["Pages\nSpecs · Workflow · Chat · History\nAssets · Settings · Usage"]
5
+ CTX["AppContext\nGlobal State"]
6
+ CTX -.-> PAGES
7
+ end
8
+
9
+ subgraph BACKEND["⚙️ Backend — FastAPI"]
10
+ MW["Middleware\nCORS · JWT Auth · Rate Limiter · Logger"]
11
+
12
+ subgraph ROUTES["REST API /api/v1"]
13
+ PUB["/auth\n🔓 Public"]
14
+ PROT["/specs · /sessions · /execution\n/history · /chat · /assets\n/usage · /settings\n🔐 JWT Protected"]
15
+ end
16
+
17
+ subgraph SERVICES["Service Layer"]
18
+ PARSERS["Spec Parsers\nPostman · Swagger"]
19
+ CORE["Core Services\nLLM Planner · API Executor\nResponse Analyzer · Chat Assistant\nAsset Service · Usage Service"]
20
+ end
21
+
22
+ subgraph LLM_INT["🔗 LLM Integration — LangChain"]
23
+ FAC["LLMClientFactory\nRegistry · Task Resolver"]
24
+ CLIENTS["Provider Clients\nMistral · OpenAI · Anthropic\nGemini · Groq"]
25
+ FAC --> CLIENTS
26
+ end
27
+
28
+ MW --> ROUTES
29
+ PROT --> PARSERS
30
+ PROT --> CORE
31
+ CORE --> FAC
32
+ end
33
+
34
+ subgraph DATA["🗄️ Data Layer"]
35
+ PG[("PostgreSQL\nspec_documents · sessions\nexecution_history · chat_sessions\nassets · collections\nllm_providers · llm_task_config · llm_usage")]
36
+ FS["File Storage\nLocal / Supabase\naudio · video · images · docs · specs"]
37
+ ALB["Alembic Migrations"]
38
+ ALB -.->|schema upgrades| PG
39
+ end
40
+
41
+ LLM_EXT["🤖 LLM APIs\nMistral · OpenAI · Anthropic\nGoogle Gemini · Groq"]
42
+
43
+ TARGET["🌐 Target REST APIs\nUser-specified Base URL"]
44
+
45
+ %% Global connections
46
+ CLIENT -->|"HTTPS · Bearer JWT"| MW
47
+ CORE -->|"SQLAlchemy ORM"| PG
48
+ CORE -->|"File I/O"| FS
49
+ CLIENTS -->|"API calls"| LLM_EXT
50
+ CORE -->|"HTTP Requests"| TARGET
51
+ ```
TESTING_FLOWS.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Testing Flows for EarWax CRM Mobile API
2
+
3
+ Based on the [openapi.yaml](file:///c:/Users/amitk/OneDrive/Desktop/Testing/Ref/openapi.yaml) specification, here are the end-to-end integration and business flows you can configure and test using this AI API Testing Tool.
4
+
5
+ ---
6
+
7
+ ## 1. Authentication & Security Life Cycle Flow
8
+ Verify user authentication, session security, token rotation, and clean profile termination.
9
+
10
+ ### Scenario Steps:
11
+ 1. **User Login**: `POST /auth/login`
12
+ - **Payload**: `{ "username": "exceladmin", "password": "your_secure_password" }`
13
+ - **Expectation**: Receives `access_token` and `refresh_token` in `TokenPair`, plus the `User` object.
14
+ 2. **Retrieve Profile**: `GET /auth/me`
15
+ - **Headers**: `Authorization: Bearer <access_token>`
16
+ - **Expectation**: Confirms token validation and retrieves profile info.
17
+ 3. **Update Profile**: `POST /auth/update-profile`
18
+ - **Payload**: `{ "full_name": "Admin Tester", "email": "admin@earwaxcrm.com" }`
19
+ - **Expectation**: Patches profile info and returns the updated `User` object.
20
+ 4. **Token Rotation**: `POST /auth/refresh`
21
+ - **Payload**: `{ "refresh_token": "<refresh_token>" }`
22
+ - **Expectation**: Rotates the old refresh token and issues a new `TokenPair`.
23
+ 5. **Change Password**: `POST /auth/change-password`
24
+ - **Payload**: `{ "current_password": "your_secure_password", "new_password": "new_secure_password123" }`
25
+ - **Expectation**: Password changed. All active sessions are invalidated.
26
+ 6. **Logout**: `POST /auth/logout`
27
+ - **Expectation**: Invalidates active tokens immediately.
28
+
29
+ ---
30
+
31
+ ## 2. Lead Intake & Management Flow
32
+ Tests onboarding a new prospect, registering communication notes, and transitioning them through the sales pipeline.
33
+
34
+ ### Scenario Steps:
35
+ 1. **Authentication**: Log in to obtain a Bearer token.
36
+ 2. **Create Prospect Lead**: `POST /leads/create`
37
+ - **Payload**:
38
+ ```json
39
+ {
40
+ "first_name": "John",
41
+ "last_name": "Smith",
42
+ "email": "john.smith@example.com",
43
+ "phone": "+447700900077",
44
+ "qualification": "BSc Audio",
45
+ "status": "new",
46
+ "source": "Mobile App",
47
+ "notes": "Interested in Ear Wax Removal Course."
48
+ }
49
+ ```
50
+ - **Expectation**: Returns `lead_id` (e.g., `45`). Triggers push notification to admins.
51
+ 3. **Inspect Lead Details**: `GET /leads/detail`
52
+ - **Query Parameters**: `?id=<lead_id>`
53
+ - **Expectation**: Retrieves full profile, empty appointments array, and the "Lead Created" activity entry.
54
+ 4. **Append Operator Note**: `POST /leads/add-note`
55
+ - **Payload**: `{ "id": <lead_id>, "note": "Called prospect. Requested booking options." }`
56
+ - **Expectation**: Modifies the plain-text notes and logs a new activity entry.
57
+ 5. **Update Pipeline Status**: `POST /leads/update-status`
58
+ - **Payload**: `{ "id": <lead_id>, "status": "planned_later" }`
59
+ - **Expectation**: Success response. (Fires automatic system email/SMS triggers).
60
+ 6. **Archive Prospect**: `POST /leads/archive` (Admin only)
61
+ - **Payload**: `{ "id": <lead_id>, "archive": true }`
62
+ - **Expectation**: Lead marked as archived, cancelling any scheduled follow-up notifications.
63
+
64
+ ---
65
+
66
+ ## 3. Student Lead-to-Booking Conversion Flow
67
+ The core CRM revenue flow. Tests converting an interested lead into an active student with a booked course, payment confirmation, and invoice creation.
68
+
69
+ ### Scenario Steps:
70
+ 1. **Select Available Course**: `GET /courses`
71
+ - **Expectation**: Retrieves list of active courses. Note down a `course_id` and training details.
72
+ 2. **Onboard Student Lead**: `POST /leads/create`
73
+ - **Payload**: `{ "first_name": "Jane", "email": "jane.doe@example.com", "status": "new" }`
74
+ - **Expectation**: Returns new `lead_id`.
75
+ 3. **Book Appointment**: `POST /appointments/create`
76
+ - **Payload**:
77
+ ```json
78
+ {
79
+ "lead_id": <lead_id>,
80
+ "course_id": <course_id>,
81
+ "appointment_date": "2026-06-15",
82
+ "appointment_time": "09:00",
83
+ "amount_paid": 499.00,
84
+ "payment_method": "Stripe",
85
+ "status": "pending"
86
+ }
87
+ ```
88
+ - **Expectation**: Returns `appointment_id` and a unique `appointment_ref` (e.g., `APT-W4X5Y6`).
89
+ 4. **Inspect Lead Funnel Status**: `GET /leads/detail`
90
+ - **Query Parameters**: `?id=<lead_id>`
91
+ - **Expectation**: Confirms the appointment is now linked and listed in the lead's appointments array.
92
+ 5. **Confirm and Pay Booking**: `POST /appointments/update-status`
93
+ - **Payload**: `{ "id": <appointment_id>, "status": "confirmed" }`
94
+ - **Expectation**: Status successfully transitioned (fires push notifications to admins and updates revenue analytics).
95
+ 6. **Generate PDF Invoice**: `GET /invoice/pdf`
96
+ - **Query Parameters**: `?id=<appointment_id>`
97
+ - **Expectation**: Streams an A4-format PDF file (`Content-Type: application/pdf`).
98
+
99
+ ---
100
+
101
+ ## 4. Mobile Push Notification & Registration Flow
102
+ Tests device token management and clean session tear-down for mobile apps.
103
+
104
+ ### Scenario Steps:
105
+ 1. **Device Registration**: `POST /devices/register`
106
+ - **Payload**:
107
+ ```json
108
+ {
109
+ "push_token": "ExponentPushToken[12345abcde67890fghij]",
110
+ "platform": "ios",
111
+ "device_name": "Developer iPad Air"
112
+ }
113
+ ```
114
+ - **Expectation**: Registers device token linked to active user. Safe to trigger on every startup.
115
+ 2. **Trigger Event Notification**: Run either **Lead Creation** or **Appointment Status Update**.
116
+ - **Expectation**: The backend triggers Expo Push notifications for admins.
117
+ 3. **Device Deregistration via Logout**: `POST /auth/logout`
118
+ - **Payload**: `{ "push_token": "ExponentPushToken[12345abcde67890fghij]" }`
119
+ - **Expectation**: Unregisters only this specific device token during user sign-out.
120
+
121
+ ---
122
+
123
+ ## 5. Administrative Dashboard & User Audit Flow
124
+ Tests management reporting, staff accounts auditing, and access control.
125
+
126
+ ### Scenario Steps:
127
+ 1. **Fetch Dashboard Summary**: `GET /stats/dashboard`
128
+ - **Expectation**: Retrieves KPIs (total leads, enrolled count, upcoming appointments) and lists the 5 most recent leads.
129
+ 2. **Fetch Financial & Pipeline Analytics**: `GET /stats` (Admin only)
130
+ - **Query Parameters**: `?date_from=2026-01-01&date_to=2026-06-30`
131
+ - **Expectation**: Returns detailed monthly revenue charts, lead breakdown by state, and main referral sources.
132
+ 3. **Audit Staff List**: `GET /users` (Admin only)
133
+ - **Expectation**: Lists all registered CRM staff accounts.
134
+ 4. **Provision Staff Account**: `POST /users/create` (Admin only)
135
+ - **Payload**:
136
+ ```json
137
+ {
138
+ "username": "staff_jane",
139
+ "password": "TemporaryPassword123",
140
+ "full_name": "Jane Staff",
141
+ "email": "jane.staff@earwaxcrm.com",
142
+ "role": "staff"
143
+ }
144
+ ```
145
+ - **Expectation**: Returns new `user_id`.
146
+ 5. **Deactivate Staff Member**: `POST /users/deactivate` (Admin only)
147
+ - **Payload**: `{ "id": <user_id>, "active": false }`
148
+ - **Expectation**: Instantly revokes all active tokens for that staff member.
149
+
150
+ ---
151
+
152
+ ## 6. Global Search & Lookup Flow
153
+ Tests operators' ability to quickly find and filter data across the system.
154
+
155
+ ### Scenario Steps:
156
+ 1. **Full-Text Lead Lookup**: `GET /search`
157
+ - **Query Parameters**: `?q=Smith`
158
+ - **Expectation**: Retrieves matching non-archived leads (up to 30 results). Minimum query is 2 characters.
159
+ 2. **Paginated Lead Listing with Filter**: `GET /leads`
160
+ - **Query Parameters**: `?status=new&search=Jane&sort=created_at&dir=desc`
161
+ - **Expectation**: Returns sorted and filtered search results in paginated format.
backend/uploads/.gitkeep ADDED
File without changes
frontend-react/src/components/AppContext.jsx CHANGED
@@ -1,10 +1,25 @@
1
- import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
2
  import { SessionService, SpecService, CredentialService } from '../services/api';
3
 
4
  const AppContext = createContext();
5
 
6
  export const useAppContext = () => useContext(AppContext);
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  export const AppProvider = ({ children }) => {
9
  const [sessionId, setSessionId] = useState(null);
10
  const [specs, setSpecs] = useState([]);
@@ -19,6 +34,7 @@ export const AppProvider = ({ children }) => {
19
  const [isLoading, setIsLoading] = useState(true);
20
  const [globalChatId, setGlobalChatId] = useState(null);
21
  const [toasts, setToasts] = useState([]);
 
22
 
23
  const addToast = useCallback((type, message) => {
24
  const id = Date.now() + Math.random();
@@ -29,7 +45,11 @@ export const AppProvider = ({ children }) => {
29
  setToasts(prev => prev.filter(t => t.id !== id));
30
  }, []);
31
 
32
- // Initialize Session
 
 
 
 
33
  useEffect(() => {
34
  const initSession = async () => {
35
  try {
@@ -40,7 +60,33 @@ export const AppProvider = ({ children }) => {
40
  }
41
  };
42
  initSession();
43
- fetchSpecs();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  }, []);
45
 
46
  const fetchSpecs = async () => {
@@ -60,6 +106,7 @@ export const AppProvider = ({ children }) => {
60
  setParsedSpec(data.parsed_spec);
61
  setActiveSpecName(data.name);
62
  setActiveSpecId(data.id);
 
63
  // Use saved base_url; fall back to the suggested URL extracted from the spec's servers list
64
  const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || '';
65
  setActiveBaseUrl(resolvedBaseUrl);
@@ -67,6 +114,8 @@ export const AppProvider = ({ children }) => {
67
  // Keep testing workspace fresh; history preserves past runs
68
  setExecutionPlan(null);
69
  setScenario('');
 
 
70
 
71
  const creds = await CredentialService.getCredentials(id);
72
  setStoredCredentials(creds || {});
@@ -97,6 +146,9 @@ export const AppProvider = ({ children }) => {
97
  setActiveBaseUrl('');
98
  setExecutionPlan(null);
99
  setStoredCredentials({});
 
 
 
100
  }
101
  fetchSpecs();
102
  } catch (err) {
 
1
+ import React, { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
2
  import { SessionService, SpecService, CredentialService } from '../services/api';
3
 
4
  const AppContext = createContext();
5
 
6
  export const useAppContext = () => useContext(AppContext);
7
 
8
+ const LS_SPEC_ID = 'app_activeSpecId';
9
+ const LS_PLAN = 'app_executionPlan';
10
+ const LS_SCENARIO = 'app_scenario';
11
+
12
+ function lsGet(key, fallback = null) {
13
+ try { const v = localStorage.getItem(key); return v !== null ? JSON.parse(v) : fallback; }
14
+ catch { return fallback; }
15
+ }
16
+ function lsSet(key, value) {
17
+ try { localStorage.setItem(key, JSON.stringify(value)); } catch {}
18
+ }
19
+ function lsDel(key) {
20
+ try { localStorage.removeItem(key); } catch {}
21
+ }
22
+
23
  export const AppProvider = ({ children }) => {
24
  const [sessionId, setSessionId] = useState(null);
25
  const [specs, setSpecs] = useState([]);
 
34
  const [isLoading, setIsLoading] = useState(true);
35
  const [globalChatId, setGlobalChatId] = useState(null);
36
  const [toasts, setToasts] = useState([]);
37
+ const persistReady = useRef(false);
38
 
39
  const addToast = useCallback((type, message) => {
40
  const id = Date.now() + Math.random();
 
45
  setToasts(prev => prev.filter(t => t.id !== id));
46
  }, []);
47
 
48
+ // Persist plan + scenario whenever they change (skip the initial mount values)
49
+ useEffect(() => { if (persistReady.current) lsSet(LS_PLAN, executionPlan); }, [executionPlan]);
50
+ useEffect(() => { if (persistReady.current) lsSet(LS_SCENARIO, scenario); }, [scenario]);
51
+
52
+ // Initialize Session + restore last active spec
53
  useEffect(() => {
54
  const initSession = async () => {
55
  try {
 
60
  }
61
  };
62
  initSession();
63
+
64
+ const init = async () => {
65
+ await fetchSpecs();
66
+ const savedSpecId = lsGet(LS_SPEC_ID);
67
+ if (savedSpecId) {
68
+ try {
69
+ const data = await SpecService.getSpec(savedSpecId);
70
+ setParsedSpec(data.parsed_spec);
71
+ setActiveSpecName(data.name);
72
+ setActiveSpecId(data.id);
73
+ const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || '';
74
+ setActiveBaseUrl(resolvedBaseUrl);
75
+ const creds = await CredentialService.getCredentials(savedSpecId);
76
+ setStoredCredentials(creds || {});
77
+ // Restore plan + scenario saved before refresh
78
+ const savedPlan = lsGet(LS_PLAN);
79
+ const savedScenario = lsGet(LS_SCENARIO, '');
80
+ if (savedPlan) setExecutionPlan(savedPlan);
81
+ if (savedScenario) setScenario(savedScenario);
82
+ } catch (err) {
83
+ console.error("Failed to restore saved spec", err);
84
+ lsDel(LS_SPEC_ID);
85
+ }
86
+ }
87
+ persistReady.current = true;
88
+ };
89
+ init();
90
  }, []);
91
 
92
  const fetchSpecs = async () => {
 
106
  setParsedSpec(data.parsed_spec);
107
  setActiveSpecName(data.name);
108
  setActiveSpecId(data.id);
109
+ lsSet(LS_SPEC_ID, data.id);
110
  // Use saved base_url; fall back to the suggested URL extracted from the spec's servers list
111
  const resolvedBaseUrl = data.base_url || data.parsed_spec?.suggested_base_url || '';
112
  setActiveBaseUrl(resolvedBaseUrl);
 
114
  // Keep testing workspace fresh; history preserves past runs
115
  setExecutionPlan(null);
116
  setScenario('');
117
+ lsDel(LS_PLAN);
118
+ lsDel(LS_SCENARIO);
119
 
120
  const creds = await CredentialService.getCredentials(id);
121
  setStoredCredentials(creds || {});
 
146
  setActiveBaseUrl('');
147
  setExecutionPlan(null);
148
  setStoredCredentials({});
149
+ lsDel(LS_SPEC_ID);
150
+ lsDel(LS_PLAN);
151
+ lsDel(LS_SCENARIO);
152
  }
153
  fetchSpecs();
154
  } catch (err) {
frontend-react/src/components/ChatAssistant.jsx CHANGED
@@ -576,10 +576,10 @@ export default function ChatAssistant({ executeStepFromChat, compact = false, la
576
  {compact && (
577
  <button
578
  onClick={startNewChat}
579
- className="p-1 rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition"
580
  title="New Chat"
581
  >
582
- <Plus size={13} />
583
  </button>
584
  )}
585
  {activeSpecName && activeSpecName !== 'None' && (
 
576
  {compact && (
577
  <button
578
  onClick={startNewChat}
579
+ className="flex items-center gap-1 px-2 py-1 rounded text-[10px] font-semibold uppercase tracking-wider text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] transition active:scale-95"
580
  title="New Chat"
581
  >
582
+ <Plus size={11} /> New Chat
583
  </button>
584
  )}
585
  {activeSpecName && activeSpecName !== 'None' && (
frontend-react/src/components/workflow/ScenarioComposer.jsx CHANGED
@@ -1,11 +1,13 @@
1
  import React from 'react';
2
- import { RefreshCw, Sparkles } from 'lucide-react';
3
 
4
  export default function ScenarioComposer({
5
  scenario, setScenario,
6
  activeSpecId, activeSpecName,
7
  isPlanning,
8
  onGenerate,
 
 
9
  }) {
10
  return (
11
  <div style={{ borderTop: '1px solid var(--line-1)', background: 'var(--bg-1)', flexShrink: 0 }}>
@@ -37,6 +39,11 @@ export default function ScenarioComposer({
37
  <div className="hint">
38
  <kbd>⌘</kbd><kbd>↵</kbd> generate plan
39
  </div>
 
 
 
 
 
40
  <button className="btn btn-ghost" onClick={() => setScenario('')}>Clear</button>
41
  <button
42
  onClick={onGenerate}
 
1
  import React from 'react';
2
+ import { RefreshCw, Sparkles, FilePlus } from 'lucide-react';
3
 
4
  export default function ScenarioComposer({
5
  scenario, setScenario,
6
  activeSpecId, activeSpecName,
7
  isPlanning,
8
  onGenerate,
9
+ onNewPlan,
10
+ hasPlan,
11
  }) {
12
  return (
13
  <div style={{ borderTop: '1px solid var(--line-1)', background: 'var(--bg-1)', flexShrink: 0 }}>
 
39
  <div className="hint">
40
  <kbd>⌘</kbd><kbd>↵</kbd> generate plan
41
  </div>
42
+ {hasPlan && onNewPlan && (
43
+ <button className="btn btn-ghost" onClick={onNewPlan} title="Clear current plan and start fresh">
44
+ <FilePlus size={13}/> New Plan
45
+ </button>
46
+ )}
47
  <button className="btn btn-ghost" onClick={() => setScenario('')}>Clear</button>
48
  <button
49
  onClick={onGenerate}
frontend-react/src/pages/WorkflowPage.jsx CHANGED
@@ -27,7 +27,13 @@ export default function WorkflowPage() {
27
  const [planningStatus, setPlanningStatus] = useState('');
28
  const [executingStep, setExecutingStep] = useState(null);
29
  const [isRunningAll, setIsRunningAll] = useState(false);
30
- const [stepResults, setStepResults] = useState({});
 
 
 
 
 
 
31
  const [otpPrompt, setOtpPrompt] = useState(null);
32
  const [otpInput, setOtpInput] = useState('');
33
  const [selectionPrompt, setSelectionPrompt] = useState(null);
@@ -46,6 +52,7 @@ export default function WorkflowPage() {
46
  setPlanningStatus('Starting…');
47
  setPlanTokenUsage(null);
48
  setStepResults({});
 
49
  setExecutionPlan([]);
50
  setTotalScenarioTokens({ prompt: 0, completion: 0, total: 0 });
51
 
@@ -378,7 +385,7 @@ export default function WorkflowPage() {
378
  isRunningAll={isRunningAll}
379
  executingStep={executingStep}
380
  onRunAll={runAllSteps}
381
- onReset={() => { setExecutionPlan(null); setStepResults({}); }}
382
  onExport={exportAsPostman}
383
  />
384
 
@@ -423,6 +430,12 @@ export default function WorkflowPage() {
423
  activeSpecName={activeSpecName}
424
  isPlanning={isPlanning}
425
  onGenerate={handleGeneratePlan}
 
 
 
 
 
 
426
  />
427
  </div>
428
 
 
27
  const [planningStatus, setPlanningStatus] = useState('');
28
  const [executingStep, setExecutingStep] = useState(null);
29
  const [isRunningAll, setIsRunningAll] = useState(false);
30
+ const [stepResults, setStepResults] = useState(() => {
31
+ try { const v = sessionStorage.getItem('wf_stepResults'); return v ? JSON.parse(v) : {}; } catch { return {}; }
32
+ });
33
+ React.useEffect(() => {
34
+ try { sessionStorage.setItem('wf_stepResults', JSON.stringify(stepResults)); } catch {}
35
+ }, [stepResults]);
36
+
37
  const [otpPrompt, setOtpPrompt] = useState(null);
38
  const [otpInput, setOtpInput] = useState('');
39
  const [selectionPrompt, setSelectionPrompt] = useState(null);
 
52
  setPlanningStatus('Starting…');
53
  setPlanTokenUsage(null);
54
  setStepResults({});
55
+ try { sessionStorage.removeItem('wf_stepResults'); } catch {}
56
  setExecutionPlan([]);
57
  setTotalScenarioTokens({ prompt: 0, completion: 0, total: 0 });
58
 
 
385
  isRunningAll={isRunningAll}
386
  executingStep={executingStep}
387
  onRunAll={runAllSteps}
388
+ onReset={() => { setExecutionPlan(null); setStepResults({}); try { sessionStorage.removeItem('wf_stepResults'); } catch {} }}
389
  onExport={exportAsPostman}
390
  />
391
 
 
430
  activeSpecName={activeSpecName}
431
  isPlanning={isPlanning}
432
  onGenerate={handleGeneratePlan}
433
+ hasPlan={!!executionPlan?.length}
434
+ onNewPlan={() => {
435
+ setExecutionPlan(null);
436
+ setStepResults({});
437
+ try { sessionStorage.removeItem('wf_stepResults'); } catch {}
438
+ }}
439
  />
440
  </div>
441
 
start.ps1 CHANGED
@@ -1,109 +1,50 @@
1
- # # ============================================================
2
- # # AI API Testing Tool - Dev Startup Script
3
- # # Usage: .\start.ps1
4
- # # ============================================================
5
-
6
- # $ErrorActionPreference = "Stop"
7
-
8
- # Write-Host ""
9
- # Write-Host " AI API Testing Tool" -ForegroundColor Cyan
10
- # Write-Host " ===================" -ForegroundColor Cyan
11
- # Write-Host ""
12
-
13
- # # --- 1. Kill any stale process on port 8001 ---
14
- # # --- 1. Kill any stale process on port 8001 ---
15
- # Write-Host "[1/3] Checking for processes on port 8001..." -ForegroundColor Yellow
16
- # $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
17
- # if ($stale) {
18
- # $pid_ = ($stale -split "\s+")[-1]
19
- # Write-Host " Killing stale process (PID $pid_)..." -ForegroundColor DarkYellow
20
- # Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
21
- # Start-Sleep -Seconds 2
22
- # } else {
23
- # Write-Host " Port 8001 is free." -ForegroundColor Green
24
- # }
25
-
26
- # # --- 2. Start FastAPI Backend ---
27
- # Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
28
- # $backend = Start-Process -FilePath "cmd.exe" `
29
- # -ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001" `
30
- # -WorkingDirectory $PSScriptRoot `
31
- # -PassThru
32
-
33
- # Write-Host " Backend PID: $($backend.Id)" -ForegroundColor Green
34
- # Write-Host " Waiting 8s for backend to initialize..." -ForegroundColor DarkGray
35
- # Start-Sleep -Seconds 8
36
-
37
- # # --- 3. Start React Frontend ---
38
- # Write-Host "[3/3] Starting React frontend (Vite dev server)..." -ForegroundColor Yellow
39
- # Start-Process -FilePath "cmd.exe" `
40
- # -ArgumentList "/k", "title Frontend && npm run dev" `
41
- # -WorkingDirectory (Join-Path $PSScriptRoot "frontend-react")
42
-
43
- # Write-Host ""
44
- # Write-Host " All services started!" -ForegroundColor Green
45
- # Write-Host ""
46
- # Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
47
- # Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
48
- # Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
49
- # Write-Host ""
50
-
51
- # ============================================================
52
- # AI API Testing Tool - Dev Startup Script
53
- # Usage: .\start.ps1
54
- # ============================================================
55
-
56
- $ErrorActionPreference = "Stop"
57
-
58
- Write-Host ""
59
- Write-Host " AI API Testing Tool" -ForegroundColor Cyan
60
- Write-Host " ===================" -ForegroundColor Cyan
61
- Write-Host ""
62
-
63
- # ------------------------------------------------------------
64
- # 1. Kill stale process on port 8001
65
- # ------------------------------------------------------------
66
- Write-Host "[1/3] Checking port 8001..." -ForegroundColor Yellow
67
-
68
- $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
69
-
70
- if ($stale) {
71
- $pid_ = ($stale -split "\s+")[-1]
72
-
73
- Write-Host " Killing process PID $pid_..." -ForegroundColor DarkYellow
74
-
75
- Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
76
-
77
- Start-Sleep -Seconds 2
78
- }
79
- else {
80
- Write-Host " Port 8001 is free." -ForegroundColor Green
81
- }
82
-
83
- # ------------------------------------------------------------
84
- # 2. Launch Backend + Frontend in Windows Terminal Tabs
85
- # ------------------------------------------------------------
86
- Write-Host "[2/3] Starting services..." -ForegroundColor Yellow
87
-
88
- $backendPath = $PSScriptRoot
89
- $frontendPath = Join-Path $PSScriptRoot "frontend-react"
90
-
91
- $backend = Start-Job -ScriptBlock { param($p) Set-Location $p; python -m uvicorn backend.main:app --reload --port 8001 } -ArgumentList $backendPath
92
- $frontend = Start-Job -ScriptBlock { param($p) Set-Location $p; npm run dev } -ArgumentList $frontendPath
93
-
94
- Write-Host " Backend Job ID: $($backend.Id)" -ForegroundColor DarkGray
95
- Write-Host " Frontend Job ID: $($frontend.Id)" -ForegroundColor DarkGray
96
- Write-Host ""
97
- Write-Host " To see logs: Receive-Job -Id <JobId> -Keep" -ForegroundColor DarkGray
98
- Write-Host " To stop all: Get-Job | Stop-Job; Get-Job | Remove-Job" -ForegroundColor DarkGray
99
-
100
- # ------------------------------------------------------------
101
- # 3. Final Output
102
- # ------------------------------------------------------------
103
- Write-Host ""
104
- Write-Host " All services started!" -ForegroundColor Green
105
- Write-Host ""
106
- Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
107
- Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
108
- Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
109
- Write-Host ""
 
1
+ # ============================================================
2
+ # AI API Testing Tool - Dev Startup Script
3
+ # Usage: .\start.ps1
4
+ # ============================================================
5
+
6
+ $ErrorActionPreference = "Stop"
7
+
8
+ Write-Host ""
9
+ Write-Host " AI API Testing Tool" -ForegroundColor Cyan
10
+ Write-Host " ===================" -ForegroundColor Cyan
11
+ Write-Host ""
12
+
13
+ # --- 1. Kill any stale process on port 8001 ---
14
+ # --- 1. Kill any stale process on port 8001 ---
15
+ Write-Host "[1/3] Checking for processes on port 8001..." -ForegroundColor Yellow
16
+ $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
17
+ if ($stale) {
18
+ $pid_ = ($stale -split "\s+")[-1]
19
+ Write-Host " Killing stale process (PID $pid_)..." -ForegroundColor DarkYellow
20
+ Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
21
+ Start-Sleep -Seconds 2
22
+ } else {
23
+ Write-Host " Port 8001 is free." -ForegroundColor Green
24
+ }
25
+
26
+ # --- 2. Start FastAPI Backend ---
27
+ Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
28
+ $backend = Start-Process -FilePath "cmd.exe" `
29
+ -ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001" `
30
+ -WorkingDirectory $PSScriptRoot `
31
+ -PassThru
32
+
33
+ Write-Host " Backend PID: $($backend.Id)" -ForegroundColor Green
34
+ Write-Host " Waiting 8s for backend to initialize..." -ForegroundColor DarkGray
35
+ Start-Sleep -Seconds 8
36
+
37
+ # --- 3. Start React Frontend ---
38
+ Write-Host "[3/3] Starting React frontend (Vite dev server)..." -ForegroundColor Yellow
39
+ Start-Process -FilePath "cmd.exe" `
40
+ -ArgumentList "/k", "title Frontend && npm run dev" `
41
+ -WorkingDirectory (Join-Path $PSScriptRoot "frontend-react")
42
+
43
+ Write-Host ""
44
+ Write-Host " All services started!" -ForegroundColor Green
45
+ Write-Host ""
46
+ Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
47
+ Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
48
+ Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
49
+ Write-Host ""
50
+