Amitkasar commited on
Commit
e592cc1
·
1 Parent(s): f1c3c6d

Remove legacy plans, docs, and local settings

Browse files

Delete numerous outdated planning and documentation files and a local settings file to clean up the repository. Removed .claude/settings.local.json (local/sensitive config), multiple Plans/*.md, documents/*.md, openapi.yaml and ref doc/admin_openapi.yaml. Also includes an update to start.ps1. This cleanup removes stale planning artifacts and private local config; start.ps1 was adjusted as part of the change.

.claude/settings.local.json DELETED
@@ -1,32 +0,0 @@
1
- {
2
- "permissions": {
3
- "allow": [
4
- "Bash(pip install *)",
5
- "Bash(python -c \"from backend.main import app; print\\('OK — routes:', len\\(app.routes\\)\\)\")",
6
- "Bash(python -c ' *)",
7
- "Bash(python -c \"from backend.main import app; from backend.core.url_guard import assert_safe_url; print\\('OK routes:', len\\(app.routes\\)\\)\")",
8
- "Bash(python -c \"from backend.main import app; from backend.core.errors import AppError; print\\('OK routes:', len\\(app.routes\\)\\)\")",
9
- "Bash(Get-ChildItem -Path \"C:\\\\Users\\\\amitk\\\\OneDrive\\\\Desktop\\\\Testing\" -Recurse -Directory)",
10
- "Bash(Select-Object -ExpandProperty FullName)",
11
- "Bash(npm run *)",
12
- "Bash(git rm *)",
13
- "Bash(git add *)",
14
- "Bash(git commit -m ' *)",
15
- "Bash(pip show *)",
16
- "PowerShell(Get-ChildItem -Path \"C:\\\\Users\\\\amitk\\\\OneDrive\\\\Desktop\\\\Testing\" -Force | Format-Table Name, @{Name=\"Type\";Expression={if \\($_.PSIsContainer\\) {\"Directory\"} else {\"File\"}}} -AutoSize)",
17
- "Bash(Get-ChildItem -Path \"C:\\\\Users\\\\amitk\\\\OneDrive\\\\Desktop\\\\Testing\\\\backend\\\\app\\\\api\\\\routes\" -Filter \"*.py\")",
18
- "Bash(Select-Object Name)",
19
- "Bash(Format-List)",
20
- "Bash(python -c \"import sys, json; d=json.load\\(sys.stdin\\); print\\(json.dumps\\({k: v for k, v in {**d.get\\('dependencies',{}\\), **d.get\\('devDependencies',{}\\)}.items\\(\\) if 'router' in k.lower\\(\\) or 'vite' in k.lower\\(\\) or 'react' in k.lower\\(\\)}, indent=2\\)\\)\")",
21
- "Bash(python -c \"import ast, sys; content = open\\('backend/services/usage_service.py'\\).read\\(\\); ast.parse\\(content\\); print\\('usage_service.py: OK'\\)\")",
22
- "Bash(python -c \"import ast, sys; content = open\\('backend/integrations/llm/base.py'\\).read\\(\\); ast.parse\\(content\\); print\\('base.py: OK'\\)\")",
23
- "Bash(python -c \"import ast, sys; content = open\\('backend/integrations/llm/client.py'\\).read\\(\\); ast.parse\\(content\\); print\\('client.py: OK'\\)\")",
24
- "Bash(python -c \"import ast; [print\\(f'{f}: OK'\\) or ast.parse\\(open\\(f\\).read\\(\\)\\) for f in ['backend/database.py','backend/main.py','backend/services/asset_service.py','backend/app/api/routes/execution.py','backend/app/api/routes/chat.py','backend/app/api/routes/usage.py','backend/core/config.py']]\")",
25
- "Bash(python *)",
26
- "Bash(del *)",
27
- "Bash(node test_hosted.js)",
28
- "Bash(curl -s -o /dev/null -w \"%{http_code}\" --cookie \"PHPSESSID=6iaecoahpl756qt8o39f1kepvd\" \"https://staging.excelhearing.co.uk/crm-dev/backend/admin_api.php?action=me\")",
29
- "Bash(curl -s http://localhost:8001/api/v1/specs)"
30
- ]
31
- }
32
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/multi-llm-configuration.md DELETED
@@ -1,256 +0,0 @@
1
- # Multi-LLM Configuration Plan
2
-
3
- ## Current State
4
-
5
- 4 services call LLMs. All import a **global singleton** from `client.py` — hardcoded to Mistral via env vars.
6
-
7
- | Task Name | Service File | Current Import |
8
- |---|---|---|
9
- | Plan Generation | `llm_planner.py` | `deterministic` (temp=0) |
10
- | Step Execution | `api_executor.py` | `deterministic` (temp=0) |
11
- | Response Analysis | `response_analyzer.py` | `deterministic` (temp=0) |
12
- | Chat Assistant | `chat_assistant.py` | `chat` (temp=0.2) |
13
-
14
- The existing `BaseLLMClient` ABC (`base.py`) is the right interface — we keep it and build on top.
15
-
16
- ---
17
-
18
- ## Target Architecture
19
-
20
- ```
21
- backend/integrations/llm/
22
- base.py # BaseLLMClient ABC — unchanged
23
- providers.py # All provider clients (thin wrappers over LangChain Chat models)
24
- registry.py # PROVIDER_REGISTRY: static metadata (models list, env key, display name)
25
- factory.py # build_client(provider_id, model, api_key, temperature) → BaseLLMClient
26
- resolver.py # get_llm_for_task(task_name, db) — DB lookup + in-memory cache + env fallback
27
- client.py # DELETE — global singletons go away
28
- ```
29
-
30
- No new abstraction layers. Services call one function: `get_llm_for_task(task_name, db)`.
31
-
32
- ---
33
-
34
- ## Supported Providers
35
-
36
- | Provider ID | LangChain Class | Env Var (fallback) |
37
- |---|---|---|
38
- | `mistral` | `ChatMistralAI` | `MISTRAL_API_KEY` |
39
- | `anthropic` | `ChatAnthropic` | `ANTHROPIC_API_KEY` |
40
- | `openai` | `ChatOpenAI` | `OPENAI_API_KEY` |
41
- | `gemini` | `ChatGoogleGenerativeAI` | `GOOGLE_API_KEY` |
42
- | `groq` | `ChatGroq` | `GROQ_API_KEY` |
43
-
44
- LangChain is already installed — use it for all providers for a consistent interface.
45
-
46
- ---
47
-
48
- ## Database Schema (2 tables)
49
-
50
- ```python
51
- class LLMProvider(Base):
52
- __tablename__ = "llm_providers"
53
- provider_id = Column(String, primary_key=True) # "openai", "mistral", etc.
54
- api_key_enc = Column(Text, nullable=True) # Fernet-encrypted; NULL = not configured
55
- is_active = Column(Boolean, default=False)
56
-
57
- class LLMTaskConfig(Base):
58
- __tablename__ = "llm_task_config"
59
- task_name = Column(String, primary_key=True) # "plan_generation" | "step_execution" | "response_analysis" | "chat"
60
- provider_id = Column(String, ForeignKey("llm_providers.provider_id"), nullable=True)
61
- model_name = Column(String, nullable=True)
62
- temperature = Column(Float, default=0.0)
63
- ```
64
-
65
- Alembic migration created for both tables. Seed with one row per task (provider_id=NULL → uses env fallback).
66
-
67
- ---
68
-
69
- ## Key Files to Create/Modify
70
-
71
- ### `registry.py` (NEW)
72
- Static dict — no DB or API call needed. Frontend reads this to populate model dropdowns.
73
-
74
- ```python
75
- PROVIDER_REGISTRY = {
76
- "mistral": {
77
- "display_name": "Mistral AI",
78
- "env_key": "MISTRAL_API_KEY",
79
- "models": ["mistral-large-latest", "mistral-small-latest", "open-mistral-7b"],
80
- },
81
- "anthropic": {
82
- "display_name": "Anthropic",
83
- "env_key": "ANTHROPIC_API_KEY",
84
- "models": ["claude-sonnet-4-6", "claude-opus-4-7", "claude-haiku-4-5-20251001"],
85
- },
86
- "openai": {
87
- "display_name": "OpenAI",
88
- "env_key": "OPENAI_API_KEY",
89
- "models": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"],
90
- },
91
- "gemini": {
92
- "display_name": "Google Gemini",
93
- "env_key": "GOOGLE_API_KEY",
94
- "models": ["gemini-2.0-flash", "gemini-1.5-pro", "gemini-1.5-flash"],
95
- },
96
- "groq": {
97
- "display_name": "Groq",
98
- "env_key": "GROQ_API_KEY",
99
- "models": ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"],
100
- },
101
- }
102
- ```
103
-
104
- ### `providers.py` (NEW)
105
- One thin client class per provider — all follow `BaseLLMClient`.
106
-
107
- ```python
108
- class AnthropicClient(BaseLLMClient):
109
- def __init__(self, model: str, api_key: str, temperature: float = 0, timeout: int = 120):
110
- from langchain_anthropic import ChatAnthropic
111
- self._llm = ChatAnthropic(model=model, api_key=api_key, temperature=temperature, timeout=timeout)
112
-
113
- def invoke(self, messages) -> tuple[str, dict | None]:
114
- ai_msg = self._llm.invoke(messages)
115
- usage = ai_msg.response_metadata.get("usage", {})
116
- return ai_msg.content, _extract_usage(usage) if usage else None
117
-
118
- # OpenAIClient, GeminiClient, GroqClient, MistralClient — same pattern
119
- ```
120
-
121
- ### `factory.py` (NEW)
122
- Maps `provider_id` → correct client class. Single responsibility.
123
-
124
- ```python
125
- _PROVIDER_MAP = {
126
- "mistral": MistralClient,
127
- "anthropic": AnthropicClient,
128
- "openai": OpenAIClient,
129
- "gemini": GeminiClient,
130
- "groq": GroqClient,
131
- }
132
-
133
- def build_client(provider_id: str, model: str, api_key: str, temperature: float) -> BaseLLMClient:
134
- cls = _PROVIDER_MAP.get(provider_id)
135
- if not cls:
136
- raise ValueError(f"Unknown provider: {provider_id}")
137
- return cls(model=model, api_key=api_key, temperature=temperature)
138
- ```
139
-
140
- ### `resolver.py` (NEW)
141
- The only file services need to import. Handles DB lookup, caching, and env fallback.
142
-
143
- ```python
144
- _cache: dict[str, BaseLLMClient] = {}
145
-
146
- def get_llm_for_task(task_name: str, db: Session) -> BaseLLMClient:
147
- if task_name in _cache:
148
- return _cache[task_name]
149
-
150
- config = db.query(LLMTaskConfig).filter_by(task_name=task_name).first()
151
- if config and config.provider_id:
152
- provider = db.query(LLMProvider).filter_by(provider_id=config.provider_id).first()
153
- if not provider or not provider.api_key_enc:
154
- raise HTTPException(400, f"Provider '{config.provider_id}' has no API key configured.")
155
- api_key = decrypt_credentials({"key": provider.api_key_enc})["key"]
156
- client = factory.build_client(config.provider_id, config.model_name, api_key, config.temperature)
157
- else:
158
- client = _env_fallback(task_name) # reads MISTRAL_API_KEY etc. — backward compat
159
-
160
- _cache[task_name] = client
161
- return client
162
-
163
- def invalidate_cache() -> None:
164
- _cache.clear()
165
- ```
166
-
167
- ### `client.py` — DELETE
168
- Global singletons (`deterministic`, `chat`) are removed. All services use `resolver.get_llm_for_task`.
169
-
170
- ---
171
-
172
- ## Service Changes (4 files)
173
-
174
- Each service function gains a `db: Session` parameter (already available in route handlers) and replaces the import:
175
-
176
- ```python
177
- # BEFORE (all 4 services)
178
- from backend.integrations.llm.client import deterministic as _llm
179
- result, usage = _llm.invoke(messages)
180
-
181
- # AFTER
182
- from backend.integrations.llm.resolver import get_llm_for_task
183
- llm = get_llm_for_task("plan_generation", db) # task name varies per service
184
- result, usage = llm.invoke(messages)
185
- ```
186
-
187
- No other changes to service logic.
188
-
189
- ---
190
-
191
- ## Settings API (new router)
192
-
193
- File: `backend/app/api/routes/settings.py`
194
-
195
- ```
196
- GET /api/v1/settings/llm
197
- → { providers: [{id, display_name, is_active, key_preview}], tasks: [{task_name, provider_id, model_name, temperature}], registry: PROVIDER_REGISTRY }
198
-
199
- PUT /api/v1/settings/llm/providers/{provider_id}
200
- body: { api_key: "sk-..." }
201
- → saves encrypted key, sets is_active=True, invalidates cache
202
-
203
- PUT /api/v1/settings/llm/tasks/{task_name}
204
- body: { provider_id: "openai", model_name: "gpt-4o", temperature: 0.0 }
205
- → updates task config, invalidates cache
206
-
207
- DELETE /api/v1/settings/llm/providers/{provider_id}/key
208
- → clears the API key, sets is_active=False, invalidates cache
209
- ```
210
-
211
- Rules:
212
- - Key preview returned as `sk-••••••1234` (last 4 chars only).
213
- - Full key is never sent to frontend after save.
214
- - `registry` field in GET response is always the static `PROVIDER_REGISTRY` dict — frontend uses it to populate dropdowns without a separate call.
215
-
216
- ---
217
-
218
- ## Frontend (SettingsPage.jsx)
219
-
220
- New "AI Models" tab with two sections:
221
-
222
- **Section 1 — API Keys**
223
- One card per provider (5 total). Each shows: provider name, status badge (Configured / Not set), masked key input, Save/Clear buttons.
224
-
225
- **Section 2 — Task Routing**
226
- One row per task (4 total). Each has:
227
- - Task label + description
228
- - Provider dropdown (only shows providers with a key saved)
229
- - Model dropdown (populated from `registry[selected_provider].models`)
230
- - Temperature input (number, 0–1)
231
- - Inline warning if provider has no API key
232
-
233
- State managed locally, saved on blur/submit.
234
-
235
- ---
236
-
237
- ## Implementation Order
238
-
239
- 1. `database.py` — add `LLMProvider` + `LLMTaskConfig` models
240
- 2. Alembic migration — create both tables, seed `llm_task_config` with 4 rows (provider_id=NULL)
241
- 3. `registry.py`, `providers.py`, `factory.py` — pure logic, no DB
242
- 4. `resolver.py` — ties DB + factory together
243
- 5. Update 4 service files — swap import, add `db` param
244
- 6. `settings.py` route — CRUD + cache invalidation
245
- 7. Wire router in `main.py`
246
- 8. Frontend settings tab
247
-
248
- ---
249
-
250
- ## What Does NOT Change
251
-
252
- - `base.py` — untouched
253
- - `BaseLLMClient.invoke()` signature — untouched
254
- - All prompt logic inside services — untouched
255
- - `FallbackLLMClient` — can be reused inside `resolver.py` if a per-task fallback is configured later
256
- - Existing env var flow — still works as a fallback when no DB config is set (zero breaking changes on deploy)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/old chats.md DELETED
@@ -1,4 +0,0 @@
1
- plan 3 first 2 phases : claude --resume ce5b1372-dfb2-450a-87e7-889931a723c2
2
- <!-- claude --resume cd3a506a-2edb-4f4f-a957-bc7a352fc4c7 -->
3
-
4
- claude --resume 3ffda4fa-59aa-4507-9cf8-71583fad658f
 
 
 
 
 
Plans/plan 1.md DELETED
@@ -1,231 +0,0 @@
1
- # Backend Refactor Execution Plan (Actionable)
2
-
3
- ## Phase 0 — Preparation
4
-
5
- * Create new branch: `refactor/architecture-v1`
6
- * Freeze new feature development
7
- * Add `.env` and `core/config.py`
8
-
9
- ---
10
-
11
- ## Phase 1 — Restructure (No Logic Changes)
12
-
13
- ### Create Directories
14
-
15
- ```
16
- backend/app/api/routes/
17
- backend/core/
18
- backend/domain/models/
19
- backend/services/
20
- backend/integrations/llm/
21
- backend/integrations/http/
22
- backend/integrations/parsers/
23
- backend/repositories/
24
- backend/workers/
25
- backend/schemas/
26
- backend/utils/
27
- ```
28
-
29
- ### Move Files
30
-
31
- * `main.py` → `app/main.py`
32
- * routes → `app/api/routes/`
33
- * shared utils → `utils/`
34
- * existing services → `services/`
35
-
36
- ### Update Imports
37
-
38
- * Replace relative imports with absolute:
39
-
40
- ```
41
- from backend.services...
42
- ```
43
-
44
- ---
45
-
46
- ## Phase 2 — Config + Core Systems
47
-
48
- ### Create `core/config.py`
49
-
50
- * Use `BaseSettings`
51
- * Add:
52
-
53
- * `ALLOWED_ORIGINS`
54
- * `API_KEYS`
55
- * `UPLOAD_DIR`
56
- * `TIMEOUT`
57
-
58
- ### Replace Hardcoded Values
59
-
60
- * Replace all constants with config usage
61
-
62
- ### Add Logging
63
-
64
- * Create `core/logging.py`
65
- * Replace all `print()` with logger
66
-
67
- ---
68
-
69
- ## Phase 3 — LLM Isolation
70
-
71
- ### Move LLM Logic
72
-
73
- FROM:
74
-
75
- * `services/llm_planner.py`
76
- * `services/chat_assistant.py`
77
-
78
- TO:
79
-
80
- ```
81
- integrations/llm/
82
- client.py
83
- planner.py
84
- analyzer.py
85
- ```
86
-
87
- ### Enforce Rule
88
-
89
- * No direct OpenAI calls outside `client.py`
90
-
91
- ---
92
-
93
- ## Phase 4 — Execution Isolation
94
-
95
- ### Move Executor
96
-
97
- * `api_executor.py` → `integrations/http/sandbox.py`
98
-
99
- ### Add Controls
100
-
101
- * allowlist domains
102
- * enforce timeout
103
- * restrict HTTP methods
104
-
105
- ---
106
-
107
- ## Phase 5 — Validation Layer
108
-
109
- ### Create
110
-
111
- `services/validation_service.py`
112
-
113
- ### Add Checks
114
-
115
- * validate LLM JSON schema
116
- * reject unsafe URLs
117
- * sanitize inputs
118
-
119
- ### Integrate
120
-
121
- * execution_service MUST call validation before execution
122
-
123
- ---
124
-
125
- ## Phase 6 — Split Responsibilities
126
-
127
- ### Create
128
-
129
- * `planning_service.py`
130
- * `execution_service.py`
131
-
132
- ### Flow
133
-
134
- ```
135
- route → planning_service → validation_service → execution_service
136
- ```
137
-
138
- ---
139
-
140
- ## Phase 7 — Remove Global State
141
-
142
- ### Delete
143
-
144
- * `get_context`
145
- * `set_context_variables`
146
-
147
- ### Replace With
148
-
149
- * request-scoped data OR
150
- * `domain/models/user_session.py`
151
- * `repositories/session_repo.py`
152
-
153
- ---
154
-
155
- ## Phase 8 — Background Jobs
156
-
157
- ### Create
158
-
159
- `workers/tasks.py`
160
-
161
- ### Move Heavy Tasks
162
-
163
- * LLM calls
164
- * API chains
165
-
166
- ### Use
167
-
168
- * FastAPI BackgroundTasks (initial)
169
-
170
- ---
171
-
172
- ## Phase 9 — Security Layer
173
-
174
- ### Create
175
-
176
- `core/security.py`
177
-
178
- ### Add
179
-
180
- * JWT auth
181
- * rate limiting middleware
182
-
183
- ### Apply
184
-
185
- * protect all routes except health
186
-
187
- ---
188
-
189
- ## Phase 10 — Frontend Alignment
190
-
191
- ### Create
192
-
193
- ```
194
- src/api/
195
- src/hooks/
196
- src/store/
197
- ```
198
-
199
- ### Add
200
-
201
- * API client wrapper
202
- * React Query
203
-
204
- ---
205
-
206
- ## Phase 11 — Cleanup
207
-
208
- * Remove unused files
209
- * Remove duplicate logic
210
- * Remove debug prints
211
-
212
- ---
213
-
214
- ## Phase 12 — Testing
215
-
216
- * Add unit tests for:
217
-
218
- * validation_service
219
- * execution_service
220
- * Add integration tests for routes
221
-
222
- ---
223
-
224
- ## Final Architecture Rule
225
-
226
- * routes = HTTP only
227
- * services = orchestration only
228
- * integrations = external calls only
229
- * domain = pure logic only
230
-
231
- NO cross-layer violations allowed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 2.md DELETED
@@ -1,161 +0,0 @@
1
- # Project Completion Plan — AI API Testing Assistant
2
-
3
- **Goal:** Make the project fully functional, secure, and production-ready.
4
- **Based on:** Actual code audit of the current codebase.
5
-
6
- ---
7
-
8
- ## ✅ Phase 1 — Fix Broken Foundations — DONE
9
-
10
- - [x] Fix `requirements.txt`: removed `streamlit`, `websockets`; added `prance`, `pyyaml`, `pydantic-settings`, `slowapi`, `cryptography`; upgraded LangChain + Mistral packages; fixed `psycopg2-binary>=2.9.10` (Python 3.13 wheel), `sqlalchemy>=2.0.36`, gunicorn platform guard
11
- - [x] Fix CORS: replaced `allow_origins=["*"]` with `settings.allowed_origins_list` from env var
12
- - [x] Fix silent failures: removed bare `except: pass` blocks; all errors logged or returned as HTTP
13
- - [x] Clean `App.jsx`: deleted ~800 lines of commented-out dead code at top; active code only
14
- - [x] Fix `chat_assistant.py`: replaced `HumanMessage` with `AIMessage` for assistant replies
15
- - [x] Add `.gitignore`: covers `*.zip`, `*.tar.gz`, `.env.*`, `__pycache__`, `.venv`, uploads, etc.
16
-
17
- ---
18
-
19
- ## ✅ Phase 2 — Backend Restructure — DONE
20
-
21
- - [x] Created `backend/core/config.py` — `BaseSettings` with all env vars
22
- - [x] Created `backend/core/logging.py` — `get_logger()` structured logger
23
- - [x] Created `backend/core/errors.py` — `AppError` + `app_error_handler`
24
- - [x] Split `main.py` into 6 focused route files (no logic changes):
25
- - `backend/app/api/routes/specs.py` — `/specs`, `/upload-spec`, `/credentials`
26
- - `backend/app/api/routes/sessions.py` — `/session`, `/context`
27
- - `backend/app/api/routes/execution.py` — `/plan`, `/execute-step`, `/analyze-response`
28
- - `backend/app/api/routes/assets.py` — `/assets`, `/collections`
29
- - `backend/app/api/routes/chat.py` — `/chat`, `/chat-sessions`
30
- - `backend/app/api/routes/history.py` — `/history`
31
- - [x] `main.py` reduced to ~60 lines (app setup only)
32
- - [x] All 36 routes preserved throughout
33
-
34
- ---
35
-
36
- ## ✅ Phase 3 — Security & Validation — DONE
37
-
38
- - [x] URL sandboxing (`backend/core/url_guard.py`): blocks localhost, private IP ranges (10.x, 172.16-31.x, 192.168.x, 169.254.x, ::1, fc00::/7), non-HTTP schemes; resolves hostname to IP before check
39
- - [x] `assert_safe_url()` called in `/execute-step` before every outbound HTTP request
40
- - [x] Spec file size validation: 5MB limit in `/upload-spec`
41
- - [x] Rate limiting via `slowapi`: `/plan` 10/min, `/execute-step` 30/min, `/chat` 20/min
42
-
43
- ---
44
-
45
- ## ✅ Phase 4 — Error Handling — DONE
46
-
47
- - [x] Standardized `AppError` exception with `{ "error", "code", "detail" }` shape
48
- - [x] LLM retry: one automatic retry on JSON parse failure in both `llm_planner.py` and `response_analyzer.py`
49
- - [x] Execution error context: `TimeoutException → 504`, `ConnectError → 502`, 4xx/5xx responses logged with URL + body snippet
50
-
51
- ---
52
-
53
- ## ✅ Phase 5 — Complete Half-Built Features — DONE
54
-
55
- - [x] OTP modal UI: inline modal shown when `is_otp_required` detected; saves to session context
56
- - [x] Selection modal UI: inline modal shown when `is_selection_required` detected; saves chosen value
57
- - [x] Token usage display: shown per-step and as running total in the top bar
58
- - [x] **Run All** button: runs all execution plan steps sequentially; stops if OTP/selection prompt appears
59
- - [x] **Retry** button: amber button appears next to failed steps (status = 'failure')
60
- - [x] **Export session** (`GET /history/{session_id}/export`): returns full JSON report with pass/fail counts; forces browser download
61
- - [x] `HistoryService.exportSession()` in `api.js`
62
- - [x] Export button in `HistoryPage.jsx` (Download icon, between Delete and Import)
63
-
64
- ---
65
-
66
- ## 🔲 Phase 6 — LLM Isolation
67
-
68
- Consolidate all LLM calls into one place.
69
-
70
- ### Create `backend/integrations/llm/client.py`
71
- ```python
72
- class MistralClient:
73
- def complete(self, prompt, temperature=0, timeout=60) -> str: ...
74
- def structured(self, prompt, schema) -> dict: ... # validates JSON output
75
- ```
76
-
77
- ### Migrate all callers:
78
- - `llm_planner.py` → uses `MistralClient`
79
- - `api_executor.py` → uses `MistralClient`
80
- - `response_analyzer.py` → uses `MistralClient`
81
- - `chat_assistant.py` → uses `MistralClient`
82
-
83
- **Rule:** No direct `ChatMistralAI` instantiation outside `client.py`.
84
-
85
- ---
86
-
87
- ## 🔲 Phase 7 — Frontend Polish
88
-
89
- ### 7.1 Error UI
90
- - Replace `alert()` calls with toast notifications or inline error messages
91
- - Add error boundary component to catch React crashes
92
- - Show which step failed and why
93
-
94
- ### 7.2 API Client Improvements (`services/api.js`)
95
- - Add global axios error interceptor
96
- - Centralize timeout and base URL
97
-
98
- ### 7.3 Frontend Structure (optional)
99
- ```
100
- src/
101
- ├── api/ # Move api.js here, split by domain
102
- ├── hooks/ # Custom hooks (useSpec, usePlan, useExecution)
103
- └── store/ # AppContext split into smaller contexts
104
- ```
105
-
106
- ---
107
-
108
- ## 🔲 Phase 8 — Testing
109
-
110
- ### Unit Tests
111
- - `services/url_validator.py` — URL blocking, private IP detection
112
- - `services/llm_planner.py` — mock LLM, test output parsing
113
- - `services/api_executor.py` — test request building, context resolution
114
-
115
- ### Integration Tests
116
- - `POST /upload-spec` — valid OpenAPI file → correct parse
117
- - `POST /plan` — returns valid step list
118
- - `POST /execute-step` — mock HTTP target → correct history entry
119
- - `POST /chat` — returns valid action JSON
120
-
121
- ### Tools
122
- - `pytest` + `pytest-asyncio`
123
- - `httpx.AsyncClient` for route testing
124
- - `respx` for mocking outbound HTTP
125
-
126
- ---
127
-
128
- ## 🔲 Phase 9 — Deployment
129
-
130
- ### 9.1 Docker
131
- ```
132
- Dockerfile # backend
133
- docker-compose.yml # backend + postgres (local dev)
134
- ```
135
-
136
- ### 9.2 Environment Separation
137
- - `.env.development` — local DB, debug logging
138
- - `.env.production` — Supabase, structured JSON logs, strict CORS
139
-
140
- ### 9.3 Health Check
141
- - `GET /health` returns `{ "status": "ok", "db": "ok", "llm": "ok" }`
142
-
143
- ---
144
-
145
- ## Progress Summary
146
-
147
- | Phase | Status | Notes |
148
- |-------|--------|-------|
149
- | 1 — Fix Foundations | ✅ Done | |
150
- | 2 — Backend Restructure | ✅ Done | 36 routes across 6 files |
151
- | 3 — Security | ✅ Done | SSRF protection, rate limiting, file size validation |
152
- | 4 — Error Handling | ✅ Done | LLM retry, typed HTTP errors |
153
- | 5 — Complete Features | ✅ Done | Run All, Retry, Export, OTP/Selection modals, token display |
154
- | 6 — LLM Isolation | 🔲 Pending | |
155
- | 7 — Frontend Polish | 🔲 Pending | Replace alerts with toasts, error boundary |
156
- | 8 — Testing | 🔲 Pending | |
157
- | 9 — Deployment | 🔲 Pending | Docker + health check |
158
-
159
-
160
-
161
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 3.md DELETED
@@ -1,129 +0,0 @@
1
- Phase 1 – Emergency Fixes ✅ DONE
2
-
3
- 1. ✅ Remove binary uploads from git
4
- - git rm --cached removed 3 tracked images from backend/uploads/documents/
5
- - .gitignore upload patterns were already correct
6
-
7
- 2. ✅ Create .env.example
8
- - .env was never committed to git — keys were never leaked
9
- - .env.example created with placeholder values including new auth/crypto vars
10
- - Real Supabase keys should still be rotated as best practice
11
-
12
- Phase 2 – Security Hardening ✅ DONE
13
-
14
- 3. ✅ Add authentication to all endpoints
15
- - backend/core/auth.py: create_access_token() + verify_token() (JWT via PyJWT)
16
- - backend/app/api/routes/auth.py: POST /auth/login, GET /auth/me (public routes)
17
- - backend/main.py: all API routers protected with Depends(verify_token)
18
- - Config: AUTH_USERNAME, AUTH_PASSWORD, JWT_SECRET, JWT_EXPIRE_HOURS in .env
19
- - Frontend: token held in module memory in api.js (never localStorage)
20
- - axios interceptor attaches Bearer token; 401 broadcasts auth:logout event
21
- - LoginPage.jsx shown before app loads when unauthenticated
22
-
23
- 4. ✅ Fix DNS rebinding SSRF bypass
24
- - resolve_safe_ip() resolves hostname to IP once, blocks private ranges
25
- - execution.py connects to the resolved IP directly with Host header pinned
26
- - httpx can no longer re-resolve the hostname mid-flight
27
-
28
- 5. ✅ Encrypt stored credentials
29
- - backend/core/crypto.py: encrypt_credentials() / decrypt_credentials() via Fernet
30
- - Backwards-compatible: legacy plaintext dicts pass through unchanged on read
31
- - specs.py: encrypts on save, decrypts on GET /credentials and GET /specs/:id
32
- - execution.py: decrypts stored creds before passing to LLM planner and executor
33
- - AI-suggested credentials also re-encrypted when merged into DB
34
- - Requires ENCRYPTION_KEY in .env (Fernet key)
35
-
36
- 6. ✅ Tie sessions to authenticated users
37
- - user_id column added to SessionModel and ChatSession (nullable)
38
- - database.run_migrations(): ALTER TABLE IF NOT EXISTS stopgap (pre-Alembic)
39
- - New sessions and chat sessions tagged with username from JWT
40
- - Full per-user filtering deferred until Alembic migration is in place (Item 11)
41
-
42
- 7. ✅ Tighten CORS policy
43
- - allow_methods changed to ['GET','POST','PUT','PATCH','DELETE']
44
- - allow_headers changed to ['Content-Type','Authorization']
45
-
46
- Phase 3 – Backend Reliability ✅ DONE
47
-
48
- 8. ✅ Fix event loop blocking in execute_step
49
- - prepare_step_request() wrapped in asyncio.to_thread()
50
-
51
- 9. ✅ Add retry logic to api_executor
52
- - parser.parse() retried once on failure; AppError raised after 2 failures
53
-
54
- 10. ✅ Fix mutable default arguments
55
- - user_credentials and available_assets default to None, assigned {} inside function
56
-
57
- 11. ✅ Migrate from create_all() to Alembic
58
- * alembic/ directory created at project root with env.py, script.py.mako
59
- * alembic/versions/a1b2c3d4e5f6_initial.py: full initial schema including llm_usage
60
- * alembic.ini configured to read DATABASE_URL from .env
61
- * backend/database.py: added LLMUsage model; run_migrations() stopgap removed
62
- * backend/main.py: run_migrations() call removed
63
- * create_all() kept as safety net; replace with Alembic on new deployments:
64
- - New deployment: alembic upgrade head
65
- - Existing deployment: alembic stamp a1b2c3d4e5f6 && alembic upgrade head
66
- * requirements.txt: alembic>=1.13.0 added
67
-
68
- 12. ✅ Fix DB host leak and debug prints
69
- - print() calls replaced with logger in database.py and chat_assistant.py
70
-
71
- 13. ✅ Fix import inside except block
72
- - import traceback moved to top of chat.py and specs.py
73
- - traceback.print_exc() replaced with logger.error() throughout
74
-
75
- 14. ✅ Share the rate limiter across routers
76
- - backend/core/limiter.py created with single shared Limiter instance
77
- - chat.py and execution.py now import it instead of each creating their own
78
-
79
- 15. ✅ Increase response truncation limit
80
- - Raised from 1000 to 4000 chars
81
- - JSON responses are now parsed cleanly instead of sliced
82
- - Configurable via RESPONSE_TRUNCATION_LIMIT in settings
83
-
84
- Phase 4 – Architecture Improvements ✅ DONE
85
-
86
- 16. ✅ Add file type validation (magic bytes)
87
- * filetype>=1.2.0 added to requirements.txt
88
- * backend/services/asset_service.py: _ALLOWED_MIMES dict per category
89
- * _validate_magic() reads first 1 KB with filetype.guess(); falls back to
90
- extension check for text-based files (json, yaml, csv, txt …)
91
- * upload_asset() rejects uploads where detected MIME doesn't match category
92
- before saving to storage; raises ValueError with a clear message
93
-
94
- 17. ✅ Add LLM cost tracking and budget cap
95
- * backend/database.py: LLMUsage ORM model (session_id, user_id, call_type,
96
- prompt/completion/total_tokens, timestamp)
97
- * backend/services/usage_service.py: log_usage(), get_session_total_tokens(),
98
- check_budget() (raises AppError 429 when MAX_TOKENS_PER_SESSION exceeded)
99
- * backend/app/api/routes/usage.py: GET /usage?session_id=&user_id= returns
100
- per-call-type breakdown and totals
101
- * execution.py: check_budget() before plan/step calls; log_usage() after each
102
- * chat.py: log_usage() after each AI reply
103
- * backend/core/config.py + .env.example: MAX_TOKENS_PER_SESSION (0 = no limit)
104
-
105
- 18. ✅ Abstract LLM client for provider fallback
106
- * backend/integrations/llm/base.py: BaseLLMClient ABC with invoke() contract
107
- * backend/integrations/llm/client.py: MistralClient(BaseLLMClient) +
108
- FallbackLLMClient(primary, fallback) — retries with fallback on any exception
109
- * _build_client() instantiates primary (LLM_MODEL) + optional fallback
110
- (LLM_FALLBACK_MODEL) from config; same model = no fallback wrapper
111
- * backend/core/config.py + .env.example: LLM_MODEL, LLM_FALLBACK_MODEL
112
-
113
- 19. ✅ Break up App.jsx (946 lines)
114
- * frontend-react/src/pages/WorkflowPage.jsx (new): all workflow state & handlers
115
- (handleGeneratePlan, executeStep, runAllSteps, handleOtpSubmit,
116
- handleSelectionSubmit), execution plan UI, OTP/selection modals, scenario
117
- composer, right panel (Context/AI tabs) with inline ChatAssistant
118
- * frontend-react/src/App.jsx: reduced to routing + layout only (sidebar,
119
- topbar with theme toggle, react-router-dom Routes)
120
- * react-router-dom BrowserRouter wraps app; sidebar buttons use navigate();
121
- nav-change events converted to navigate() calls
122
- * /chat standalone page simplified: executeStepFromChat navigates to /workflow
123
- (inline chat in WorkflowPage's right panel handles real execution)
124
-
125
- ---
126
-
127
- Status summary (as of 2026-05-03)
128
-
129
- Done: All 19 items ✅
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 4.md DELETED
@@ -1,444 +0,0 @@
1
- # Plan 4 – Improvements
2
-
3
- ## Context for the AI reading this
4
-
5
- This is a FastAPI + React project — an AI-powered API testing assistant.
6
- Key files:
7
- - `backend/app/api/routes/` — all route handlers
8
- - `backend/services/` — business logic
9
- - `backend/database.py` — all SQLAlchemy ORM models
10
- - `backend/core/` — auth, config, crypto, limiter, logging, url_guard
11
- - `backend/tests/` — pytest suite with SQLite in-memory DB
12
- - `frontend-react/src/services/api.js` — all Axios calls
13
- - `frontend-react/src/pages/WorkflowPage.jsx` — main workflow UI
14
- - `frontend-react/src/components/` — all other pages/components
15
-
16
- Do NOT change any logic that was intentionally implemented in plan_3.md.
17
- Make minimal, targeted edits — do not refactor unrelated code.
18
-
19
- ---
20
-
21
- ## Phase 1 – Quick Backend Fixes
22
-
23
- ### 1. Fix `datetime.utcnow` deprecation across `database.py`
24
-
25
- **File:** `backend/database.py`
26
-
27
- `datetime.utcnow` is deprecated since Python 3.12. Replace every occurrence with `datetime.now(timezone.utc)`.
28
-
29
- Steps:
30
- - Add `timezone` to the import: `from datetime import datetime, timezone`
31
- - Replace every `default=datetime.utcnow` with `default=lambda: datetime.now(timezone.utc)`
32
- - Affects columns in: `SpecDocument`, `SessionModel`, `ExecutionHistory`, `Collection`,
33
- `Asset`, `ChatSession`, `ChatMessage`, `LLMUsage`
34
- - Also replace `onupdate=datetime.utcnow` on `ChatSession.updated_at` with
35
- `onupdate=lambda: datetime.now(timezone.utc)`
36
-
37
- ---
38
-
39
- ### 2. Rate limit `/analyze-response`
40
-
41
- **File:** `backend/app/api/routes/execution.py`
42
-
43
- `/plan` has `@limiter.limit("10/minute")` and `/execute-step` has `@limiter.limit("30/minute")`,
44
- but `analyze_response_endpoint` has no rate limit despite calling the LLM.
45
-
46
- Steps:
47
- - Add `request: Request` as the first parameter to `analyze_response_endpoint`
48
- (required by slowapi — same pattern as the other two endpoints in this file)
49
- - Add `@limiter.limit("20/minute")` decorator above `@router.post("/analyze-response")`
50
- - The limiter is already imported from `backend.core.limiter`
51
-
52
- ---
53
-
54
- ### 3. Per-user filtering on history and sessions
55
-
56
- **File:** `backend/app/api/routes/history.py`
57
- **File:** `backend/app/api/routes/sessions.py`
58
-
59
- `user_id` column exists on `SessionModel` (added in plan_3 item 6) but queries don't filter by it.
60
- `verify_token` returns the username string — inject it as `current_user`.
61
-
62
- Steps in `history.py`:
63
- - Add import: `from backend.core.auth import verify_token`
64
- - Add `current_user: str = Depends(verify_token)` parameter to:
65
- - `get_all_history()`
66
- - `export_history_session()`
67
- - `delete_history_session()`
68
- - `clear_all_history()`
69
- - In `get_all_history()`: add `.filter(database.SessionModel.user_id == current_user)`
70
- to the existing join query (already joins `SessionModel`)
71
- - In `export_history_session()`: after fetching `sess`, add:
72
- ```python
73
- if sess.user_id and sess.user_id != current_user:
74
- raise HTTPException(status_code=403, detail="Access denied")
75
- ```
76
- - In `delete_history_session()`: same ownership check before deleting
77
- - In `clear_all_history()`: filter the delete queries by joining sessions owned by
78
- `current_user` instead of deleting everything:
79
- ```python
80
- owned_ids = [
81
- r[0] for r in db.query(database.SessionModel.id)
82
- .filter(database.SessionModel.user_id == current_user).all()
83
- ]
84
- db.query(database.ExecutionHistory).filter(
85
- database.ExecutionHistory.session_id.in_(owned_ids)
86
- ).delete(synchronize_session=False)
87
- db.query(database.SessionModel).filter(
88
- database.SessionModel.id.in_(owned_ids)
89
- ).delete(synchronize_session=False)
90
- db.commit()
91
- ```
92
-
93
- Steps in `sessions.py`:
94
- - `create_session()` already tags `user_id=current_user` ✅
95
- - `clear_session()`: add `current_user: str = Depends(verify_token)` and check ownership:
96
- ```python
97
- if session.user_id and session.user_id != current_user:
98
- raise HTTPException(status_code=403, detail="Access denied")
99
- ```
100
-
101
- ---
102
-
103
- ### 4. Pagination on list endpoints
104
-
105
- **Files:**
106
- - `backend/app/api/routes/history.py` — `GET /history`
107
- - `backend/app/api/routes/specs.py` — `GET /specs`
108
- - `backend/app/api/routes/assets.py` — `GET /assets`
109
-
110
- Add optional query params `limit: int = 50` and `offset: int = 0` to each list endpoint.
111
-
112
- Pattern to apply to each:
113
-
114
- ```python
115
- # Add to function signature:
116
- limit: int = 50, offset: int = 0
117
-
118
- # Add to query before .all():
119
- .offset(offset).limit(limit)
120
- ```
121
-
122
- For `GET /history` specifically, also return total count so the frontend can show
123
- "showing 50 of 200":
124
- ```python
125
- total = db.query(database.ExecutionHistory).join(...).filter(...).count()
126
- return {"items": [...], "total": total, "limit": limit, "offset": offset}
127
- ```
128
-
129
- For `GET /specs` and `GET /assets`, a simple list return is fine — just slice it.
130
-
131
- **Frontend** (`frontend-react/src/services/api.js`):
132
- - `HistoryService.getHistory()`: add `params: { limit, offset }` (default 50/0)
133
- - `SpecService.getAllSpecs()`: same
134
- - `AssetService.getAllAssets()`: already accepts params — add `limit` and `offset`
135
-
136
- ---
137
-
138
- ### 5. Input size cap before LLM calls
139
-
140
- **File:** `backend/app/api/routes/execution.py`
141
-
142
- A user can send a 500KB scenario string straight into the LLM prompt, consuming huge
143
- token budget. Add a guard at the top of both `generate_plan()` and `execute_step()`.
144
-
145
- Add this helper at the top of `execution.py` (after imports):
146
- ```python
147
- _MAX_SCENARIO_LEN = 50_000 # ~12k tokens worst case
148
-
149
- def _check_input_sizes(**kwargs):
150
- for name, value in kwargs.items():
151
- if isinstance(value, str) and len(value) > _MAX_SCENARIO_LEN:
152
- raise HTTPException(
153
- status_code=400,
154
- detail=f"Input field '{name}' exceeds maximum length of {_MAX_SCENARIO_LEN} characters."
155
- )
156
- ```
157
-
158
- In `generate_plan()`, call before the LLM:
159
- ```python
160
- _check_input_sizes(scenario=body.scenario, spec_content=str(body.spec_content)[:1000])
161
- ```
162
-
163
- In `execute_step()`, call before `prepare_step_request`:
164
- ```python
165
- _check_input_sizes(scenario=body.step_definition.get("purpose", ""))
166
- ```
167
-
168
- ---
169
-
170
- ## Phase 2 – Frontend Fixes
171
-
172
- ### 6. Persist JWT across page refreshes
173
-
174
- **File:** `frontend-react/src/services/api.js`
175
-
176
- Currently `_token` is a module-level variable — lost on every refresh, logging
177
- the user out. Switch to `sessionStorage` (cleared when tab closes, survives refresh,
178
- safer than `localStorage`).
179
-
180
- Changes:
181
-
182
- ```js
183
- // Replace the current module-level variable:
184
- // let _token = null;
185
-
186
- // With these two helpers:
187
- const TOKEN_KEY = 'auth_token';
188
- const getToken = () => sessionStorage.getItem(TOKEN_KEY);
189
- const setToken = (t) => t ? sessionStorage.setItem(TOKEN_KEY, t) : sessionStorage.removeItem(TOKEN_KEY);
190
- ```
191
-
192
- Then update all usages:
193
- - `api.interceptors.request.use`: replace `if (_token)` with `if (getToken())`
194
- and `config.headers.Authorization = \`Bearer ${_token}\`` with
195
- `config.headers.Authorization = \`Bearer ${getToken()}\``
196
- - `api.interceptors.response.use` error handler: replace `_token = null` with `setToken(null)`
197
- - `AuthService.login()`: replace `_token = response.data.access_token` with
198
- `setToken(response.data.access_token)`
199
- - `AuthService.logout()`: replace `_token = null` with `setToken(null)`
200
- - `AuthService.isAuthenticated()`: replace `return !!_token` with `return !!getToken()`
201
-
202
- ---
203
-
204
- ### 7. Fix 422 validation error display
205
-
206
- **File:** `frontend-react/src/services/api.js`
207
-
208
- FastAPI sends 422 errors as `{ detail: [{ loc, msg, type }] }` — an array.
209
- The current interceptor does `error.response?.data?.detail` which returns
210
- `[object Object]` when displayed.
211
-
212
- In the response error interceptor, replace the `msg` extraction:
213
-
214
- ```js
215
- // Replace:
216
- const msg =
217
- error.response?.data?.error ||
218
- error.response?.data?.detail ||
219
- error.message ||
220
- 'An unexpected error occurred.';
221
- return Promise.reject(new Error(typeof msg === 'string' ? msg : JSON.stringify(msg)));
222
-
223
- // With:
224
- const raw = error.response?.data?.detail || error.response?.data?.error || error.message;
225
- const msg = Array.isArray(raw)
226
- ? raw.map(e => `${e.loc?.slice(-1)[0] ?? 'field'}: ${e.msg}`).join(' | ')
227
- : (typeof raw === 'string' ? raw : 'An unexpected error occurred.');
228
- return Promise.reject(new Error(msg));
229
- ```
230
-
231
- ---
232
-
233
- ### 8. Disable buttons during API calls (loading state audit)
234
-
235
- **File:** `frontend-react/src/pages/WorkflowPage.jsx`
236
-
237
- Audit every button that triggers an async call. For each one, ensure:
238
- - There is a `loading` state variable covering that action
239
- - The button has `disabled={loading}` while in flight
240
- - The button shows a visual indicator (spinner or text change like "Running…")
241
-
242
- Specific buttons to check and fix if missing:
243
- - "Generate Plan" button — should disable while `generatePlan()` is running
244
- - "Execute Step" / "Run All" buttons — should disable while any step is executing
245
- - "Save Credentials" / "Save Base URL" buttons — should disable on submit
246
-
247
- Pattern to apply where missing:
248
- ```jsx
249
- const [isGenerating, setIsGenerating] = useState(false);
250
-
251
- const handleGeneratePlan = async () => {
252
- setIsGenerating(true);
253
- try {
254
- await PlanService.generatePlan(payload);
255
- } finally {
256
- setIsGenerating(false); // always re-enables, even on error
257
- }
258
- };
259
-
260
- // On button:
261
- <button onClick={handleGeneratePlan} disabled={isGenerating}>
262
- {isGenerating ? 'Generating…' : 'Generate Plan'}
263
- </button>
264
- ```
265
-
266
- The `finally` block is critical — without it, a failed request leaves the button
267
- permanently disabled.
268
-
269
- ---
270
-
271
- ## Phase 3 – Test Coverage
272
-
273
- ### 9. Add auth tests to `test_routes.py`
274
-
275
- **File:** `backend/tests/test_routes.py`
276
-
277
- Currently `test_create_session` calls `POST /session` without a token and gets 200.
278
- But `sessions.py` has `Depends(verify_token)` on that route — the test only passes
279
- because the TestClient bypasses auth (conftest doesn't set up auth headers).
280
-
281
- Add these tests:
282
-
283
- ```python
284
- # ── Auth ─────────────────────────────────────────────────���────────────────────
285
-
286
- def test_login_success(client):
287
- response = client.post("/auth/login", json={"username": "admin", "password": "changeme"})
288
- assert response.status_code == 200
289
- assert "access_token" in response.json()
290
-
291
-
292
- def test_login_wrong_password(client):
293
- response = client.post("/auth/login", json={"username": "admin", "password": "wrong"})
294
- assert response.status_code == 401
295
-
296
-
297
- def test_protected_route_without_token(client):
298
- """Any protected route must return 401 when no token is sent."""
299
- response = client.get("/specs")
300
- assert response.status_code == 401
301
-
302
-
303
- def test_protected_route_with_valid_token(client):
304
- login = client.post("/auth/login", json={"username": "admin", "password": "changeme"})
305
- token = login.json()["access_token"]
306
- response = client.get("/specs", headers={"Authorization": f"Bearer {token}"})
307
- assert response.status_code == 200
308
-
309
-
310
- def test_protected_route_with_invalid_token(client):
311
- response = client.get("/specs", headers={"Authorization": "Bearer invalidtoken"})
312
- assert response.status_code == 401
313
- ```
314
-
315
- Also update `conftest.py` to set `AUTH_USERNAME` and `AUTH_PASSWORD` in env so
316
- `test_login_success` works:
317
- ```python
318
- os.environ.setdefault("AUTH_USERNAME", "admin")
319
- os.environ.setdefault("AUTH_PASSWORD", "changeme")
320
- os.environ.setdefault("JWT_SECRET", "test-secret")
321
- ```
322
-
323
- ---
324
-
325
- ### 10. Add budget cap test
326
-
327
- **File:** `backend/tests/test_routes.py`
328
-
329
- Add a test that verifies `check_budget()` blocks execution when the token cap is hit:
330
-
331
- ```python
332
- def test_budget_cap_blocks_execution(client):
333
- """When MAX_TOKENS_PER_SESSION is exceeded, /plan must return 429."""
334
- from unittest.mock import patch
335
- from backend.core import config
336
-
337
- login = client.post("/auth/login", json={"username": "admin", "password": "changeme"})
338
- token = login.json()["access_token"]
339
- headers = {"Authorization": f"Bearer {token}"}
340
-
341
- session = client.post("/session", headers=headers).json()["session_id"]
342
-
343
- # Temporarily set a token cap of 1 token
344
- original_cap = config.settings.MAX_TOKENS_PER_SESSION
345
- config.settings.MAX_TOKENS_PER_SESSION = 1
346
-
347
- # Seed a usage record that exceeds the cap
348
- from backend.tests.conftest import _TestingSession
349
- from backend.database import LLMUsage
350
- db = _TestingSession()
351
- db.add(LLMUsage(session_id=session, call_type="plan", total_tokens=100))
352
- db.commit()
353
- db.close()
354
-
355
- try:
356
- response = client.post("/plan", headers=headers, json={
357
- "spec_content": "{}",
358
- "base_url": "https://example.com",
359
- "scenario": "test",
360
- "user_credentials": {},
361
- })
362
- assert response.status_code == 429
363
- finally:
364
- config.settings.MAX_TOKENS_PER_SESSION = original_cap
365
- ```
366
-
367
- ---
368
-
369
- ## Phase 4 – README
370
-
371
- ### 11. Write a proper README
372
-
373
- **File:** `README.md` (project root — create if it doesn't exist)
374
-
375
- Write a README with the following sections:
376
-
377
- ```markdown
378
- # AI API Testing Assistant
379
-
380
- An AI-powered API testing tool. Upload an OpenAPI/Postman spec, describe your
381
- test scenario in plain language, and the AI generates and executes the test steps.
382
-
383
- ## What it does
384
- - Parses OpenAPI 3.0 and Postman Collection v2 specs
385
- - AI generates a step-by-step execution plan from a plain language scenario
386
- - Executes each HTTP step, extracts context variables (tokens, IDs) automatically
387
- - Chat assistant lets you modify, retry, and explain steps via natural language
388
- - Media Hub for managing test assets (files, images) attached to requests
389
- - LLM token usage tracking and budget cap per session
390
-
391
- ## Stack
392
- - **Backend:** FastAPI, SQLAlchemy, PostgreSQL, Alembic, Mistral AI
393
- - **Frontend:** React, Vite, Axios, React Router
394
-
395
- ## Setup
396
-
397
- ### 1. Environment
398
- Copy `.env.example` to `.env` and fill in:
399
- - `DATABASE_URL` — PostgreSQL connection string
400
- - `MISTRAL_API_KEY` — from console.mistral.ai
401
- - `JWT_SECRET` — any random 32+ char string
402
- - `AUTH_USERNAME` / `AUTH_PASSWORD` — login credentials for the app
403
- - `ENCRYPTION_KEY` — generate with: `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`
404
-
405
- ### 2. Database
406
- New deployment:
407
- alembic upgrade head
408
-
409
- Existing deployment (stamping the initial migration):
410
- alembic stamp a1b2c3d4e5f6 && alembic upgrade head
411
-
412
- ### 3. Backend
413
- pip install -r requirements.txt
414
- uvicorn backend.main:app --reload --port 8001
415
-
416
- ### 4. Frontend
417
- cd frontend-react
418
- npm install
419
- npm run dev
420
-
421
- ### 5. Tests
422
- pytest backend/tests/
423
-
424
- ## Single-user note
425
- This app uses a single username/password set in `.env`. There is no user
426
- registration. To change credentials, update `AUTH_USERNAME` and `AUTH_PASSWORD`
427
- in your `.env` and restart the server.
428
- ```
429
-
430
- ---
431
-
432
- ## Done Checklist
433
-
434
- - [ ] 1. `datetime.utcnow` → `datetime.now(timezone.utc)` in `database.py`
435
- - [ ] 2. `@limiter.limit("20/minute")` on `analyze_response_endpoint` in `execution.py`
436
- - [ ] 3. Per-user filtering in `history.py` and `sessions.py`
437
- - [ ] 4. Pagination (`limit`/`offset`) on `/history`, `/specs`, `/assets` + frontend params
438
- - [ ] 5. Input size cap (`_check_input_sizes`) in `execution.py`
439
- - [ ] 6. `sessionStorage` token persistence in `api.js`
440
- - [ ] 7. 422 array error formatting in `api.js`
441
- - [ ] 8. Loading state audit on buttons in `WorkflowPage.jsx`
442
- - [ ] 9. Auth tests in `test_routes.py` + env vars in `conftest.py`
443
- - [ ] 10. Budget cap test in `test_routes.py`
444
- - [ ] 11. `README.md` at project root
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 5.md DELETED
@@ -1,511 +0,0 @@
1
- # AI API Testing Assistant — Improvement & Execution Plan
2
-
3
- > Full audit of backend (FastAPI) + frontend (React/Vite) codebase.
4
- > Every issue below is traced to a specific file and line of reasoning.
5
- >
6
- > **Status:** Phases 1–4 fully implemented (May 2026). Phase 5 remaining.
7
-
8
- ---
9
-
10
- ## Table of Contents
11
-
12
- 1. [Project Overview](#1-project-overview)
13
- 2. [Current Architecture](#2-current-architecture)
14
- 3. [Code Issues — Backend](#3-code-issues--backend)
15
- 4. [Code Issues — Frontend](#4-code-issues--frontend)
16
- 5. [Missing Features (Incomplete Work)](#5-missing-features-incomplete-work)
17
- 6. [Improvement Roadmap](#6-improvement-roadmap)
18
- 7. [Execution Plan — Phase by Phase](#7-execution-plan--phase-by-phase)
19
- 8. [File-by-File Fix Reference](#8-file-by-file-fix-reference)
20
-
21
- ---
22
-
23
- ## 1. Project Overview
24
-
25
- **What this app does:**
26
- An AI-powered API testing tool. You upload an OpenAPI/Swagger or Postman collection, describe a test scenario in plain English, and the AI generates a step-by-step execution plan, runs each API call, and analyzes the responses — all automatically.
27
-
28
- **Tech Stack:**
29
- - Backend: FastAPI + SQLAlchemy + PostgreSQL + Alembic
30
- - LLM: Mistral AI via LangChain (deterministic + chat clients)
31
- - Frontend: React 19 + Vite + React Router v7 + Tailwind CSS v4
32
- - Auth: Single-user JWT (username/password from `.env`)
33
- - Storage: Local filesystem (uploads folder)
34
- - Rate limiting: SlowAPI (in-memory)
35
-
36
- ---
37
-
38
- ## 2. Current Architecture
39
-
40
- ```
41
- project_root/
42
- ├── alembic/ # DB migrations
43
- │ └── versions/a1b2c3d4e5f6_initial.py
44
- ├── backend/
45
- │ ├── main.py # FastAPI app, CORS, route mounting, startup validation
46
- │ ├── database.py # SQLAlchemy models + engine
47
- │ ├── schemas.py # Pydantic request/response models
48
- │ ├── core/
49
- │ │ ├── auth.py # JWT create + verify
50
- │ │ ├── config.py # Settings via pydantic-settings
51
- │ │ ├── crypto.py # Fernet credential encryption
52
- │ │ ├── errors.py # AppError + handler
53
- │ │ ├── limiter.py # SlowAPI instance
54
- │ │ ├── logging.py # Logger factory
55
- │ │ └── url_guard.py # SSRF protection
56
- │ ├── integrations/llm/
57
- │ │ ├── base.py # BaseLLMClient ABC
58
- │ │ └── client.py # MistralClient + FallbackLLMClient
59
- │ ├── services/
60
- │ │ ├── api_executor.py # LLM builds HTTP request for each step
61
- │ │ ├── asset_service.py # File upload/manage/AI context
62
- │ │ ├── chat_assistant.py # AI chat brain
63
- │ │ ├── context_manager.py # Session context get/set
64
- │ │ ├── llm_planner.py # Generates execution plan (condensed spec)
65
- │ │ ├── postman_parser.py # Parses Postman collections
66
- │ │ ├── response_analyzer.py # AI analyzes HTTP responses (with fallback)
67
- │ │ ├── storage.py # Local file storage adapter
68
- │ │ ├── swagger_parser.py # Parses OpenAPI/Swagger specs
69
- │ │ └── usage_service.py # Token logging + budget check
70
- │ └── app/api/routes/ # All routes under /api/v1 prefix
71
- │ ├── auth.py # POST /api/v1/auth/login, GET /api/v1/auth/me
72
- │ ├── assets.py # Asset CRUD + collections
73
- │ ├── chat.py # Chat sessions + messages
74
- │ ├── execution.py # /plan, /plan/stream (SSE), /execute-step, /analyze-response
75
- │ ├── history.py # Execution history + export (user-scoped)
76
- │ ├── sessions.py # Session + context management (ownership-checked)
77
- │ ├── specs.py # Spec upload + CRUD + credentials
78
- │ └── usage.py # Token usage stats
79
- └── frontend-react/
80
- ├── src/
81
- │ ├── App.jsx # Root: auth gate + sidebar + routing
82
- │ ├── main.jsx
83
- │ ├── index.css # All CSS (custom design system)
84
- │ ├── components/
85
- │ │ ├── AppContext.jsx # Global state provider (specs/fetchSpecs)
86
- │ │ ├── ChatAssistant.jsx
87
- │ │ ├── SpecsPage.jsx # (renamed from CollectionsPage)
88
- │ │ ├── CollectionsPage.jsx # legacy, kept for reference
89
- │ │ ├── ErrorBoundary.jsx
90
- │ │ ├── HistoryPage.jsx
91
- │ │ ├── LoginPage.jsx
92
- │ │ ├── MediaHubPage.jsx
93
- │ │ ├── ProfilePage.jsx
94
- │ │ ├── SettingsPage.jsx # functional settings (localStorage)
95
- │ │ ├── UsagePage.jsx # token usage dashboard (new)
96
- │ │ ├── Toast.jsx
97
- │ │ └── workflow/ # WorkflowPage sub-components (new)
98
- │ │ ├���─ ScenarioComposer.jsx
99
- │ │ ├── PlanHeader.jsx (includes Export button)
100
- │ │ ├── StepCard.jsx
101
- │ │ ├── ContextPanel.jsx
102
- │ │ ├── OtpModal.jsx
103
- │ │ ├── SelectionModal.jsx
104
- │ │ └── ModifyDiffModal.jsx
105
- │ ├── pages/
106
- │ │ └── WorkflowPage.jsx # ~280 lines — uses sub-components
107
- │ └── services/
108
- │ └── api.js # All API calls (axios + fetch SSE)
109
- └── package.json
110
- ```
111
-
112
- ---
113
-
114
- ## 3. Code Issues — Backend
115
-
116
- ### 🔴 CRITICAL
117
-
118
- #### ~~Issue B-1: Duplicate `create_all` calls~~ ✅ FIXED
119
- `Base.metadata.create_all` removed from both `database.py` and `main.py`. Alembic is now the sole migration authority.
120
-
121
- ---
122
-
123
- #### ~~Issue B-2: ENCRYPTION_KEY silently stores plaintext~~ ✅ FIXED
124
- `main.py` now validates ENCRYPTION_KEY at startup and raises `RuntimeError` if missing or invalid — server won't start.
125
-
126
- ---
127
-
128
- #### ~~Issue B-3: `/plan` endpoint is synchronous but calls slow LLM~~ ✅ FIXED
129
- `generate_plan` and `analyze_response_endpoint` are now `async` using `asyncio.to_thread`. Additionally, a proper SSE streaming endpoint `/plan/stream` was added (see M-1).
130
-
131
- ---
132
-
133
- #### ~~Issue B-4: `verify_token` called twice on every `/chat` request~~ ✅ FIXED
134
- Removed `Depends(verify_token)` from `chat_endpoint` function. Added `extract_user_state` HTTP middleware in `main.py` that sets `request.state.user` from the JWT so route handlers can read the current user without re-verifying.
135
-
136
- ---
137
-
138
- #### ~~Issue B-5: History and sessions have no user scoping~~ ✅ FIXED
139
- `history.py` filters all queries by `user_id`. `sessions.py` DELETE endpoint checks ownership and returns 404 if session doesn't belong to caller.
140
-
141
- ---
142
-
143
- ### 🟠 SIGNIFICANT
144
-
145
- #### Issue B-6: Rate limits don't survive server restarts ⏳ REMAINING (Phase 5)
146
- **File:** `backend/core/limiter.py`
147
- SlowAPI uses in-memory storage — resets on restart. Multi-worker deployments multiply the limit.
148
- **Fix:** Add Redis-backed `storage_uri` to Limiter.
149
-
150
- ---
151
-
152
- #### ~~Issue B-7: `response_analyzer.py` retries silently on parse failure~~ ✅ FIXED
153
- Retry now has a proper try/except. On second failure, returns a safe `AnalyzeResponse` with `status="unknown"` and a human-readable message instead of crashing.
154
-
155
- ---
156
-
157
- #### ~~Issue B-8: `llm_planner.py` sends the entire parsed spec to LLM~~ ✅ FIXED
158
- `_condense_spec_for_planning()` now pre-filters the spec to only `{method, path, summary}` per endpoint before sending to the planning LLM. Full schema details are still sent per-step during execution.
159
-
160
- ---
161
-
162
- #### Issue B-9: `chat.py` — new chat session name is just the first 60 chars ⏳ REMAINING
163
- Auto-generated session names are still truncated user messages. Could use LLM to generate a 3–5 word title.
164
-
165
- ---
166
-
167
- #### ~~Issue B-10: `sessions.py` — `/session` DELETE doesn't check ownership~~ ✅ FIXED
168
- Ownership check added. Returns 404 if session doesn't belong to the authenticated user.
169
-
170
- ---
171
-
172
- ### 🟡 CODE QUALITY
173
-
174
- #### ~~Issue B-11: `schemas.py` has Windows line endings (CRLF)~~ ✅ FIXED
175
- 110 bytes of `\r\n` converted to `\n`.
176
-
177
- #### ~~Issue B-12: `database.py` — `updated_at` on `ChatSession` redundancy~~ ✅ ACKNOWLEDGED
178
- The manual `chat_session.updated_at = datetime.now(timezone.utc)` in `chat.py` is kept (the `onupdate` is a backup).
179
-
180
- #### ~~Issue B-13: `datetime.utcnow()` is deprecated~~ ✅ FIXED
181
- Replaced throughout `database.py` (via `_utcnow()` helper) and `chat.py`.
182
-
183
- #### ~~Issue B-14: `main.py` URL prefix inconsistency~~ ✅ FIXED
184
- All routes now registered under `/api/v1` prefix via `_V1 = "/api/v1"` in `main.py`. Frontend `api.js` updated to use `API_BASE = ${BACKEND_URL}/api/v1`.
185
-
186
- ---
187
-
188
- ## 4. Code Issues — Frontend
189
-
190
- ### 🔴 CRITICAL
191
-
192
- #### ~~Issue F-1: JWT token lost on page refresh~~ ✅ FIXED
193
- Token now stored in `sessionStorage` (key `_jwt`). `_restoreToken()` helper rehydrates module memory from storage on first use after refresh. Clears on tab close and on 401 response.
194
-
195
- ---
196
-
197
- #### ~~Issue F-2: `AppContext.jsx` — `fetchCollections` fetches specs, not collections~~ ✅ FIXED
198
- Renamed to `fetchSpecs`/`specs`/`setSpecs`. Legacy aliases (`collections`, `fetchCollections`) kept in context value for incremental migration.
199
-
200
- ---
201
-
202
- #### ~~Issue F-3: `WorkflowPage.jsx` — 739 lines, no separation of concerns~~ ✅ FIXED
203
- Split into focused sub-components in `src/components/workflow/`:
204
- - `ScenarioComposer.jsx` — textarea + generate button
205
- - `PlanHeader.jsx` — step count, progress bar, run-all, export
206
- - `StepCard.jsx` — single step render (request/response/analysis)
207
- - `ContextPanel.jsx` — session vars + credentials
208
- - `OtpModal.jsx` — OTP input modal
209
- - `SelectionModal.jsx` — selection picker modal
210
- - `ModifyDiffModal.jsx` — diff preview for AI modifications
211
-
212
- `WorkflowPage.jsx` is now ~280 lines of coordination logic.
213
-
214
- ---
215
-
216
- #### ~~Issue F-4: Step execution error is silently swallowed~~ ✅ FIXED
217
- `executeStep` now calls `addToast('error', ...)` and sets the step state to `failed` with the error message.
218
-
219
- ---
220
-
221
- #### ~~Issue F-5: `runAllSteps` doesn't stop on step failure~~ ✅ FIXED
222
- Loop checks `prev[step.step]?.analysis?.status === 'failed'` after each step and breaks with a warning toast.
223
-
224
- ---
225
-
226
- ### 🟠 SIGNIFICANT
227
-
228
- #### ~~Issue F-6: No loading indicator during plan generation~~ ✅ FIXED
229
- The SSE streaming endpoint now shows live status messages (`planningStatus`) and steps appear one-by-one as they stream in. A spinner row with the current status is shown above the plan.
230
-
231
- ---
232
-
233
- #### Issue F-7: `ChatAssistant.jsx` — 800+ lines, also very large ⏳ REMAINING
234
- Still a monolithic file. Should be split into `ChatMessages.jsx`, `ChatInput.jsx`, `ChatSessionSidebar.jsx`.
235
-
236
- ---
237
-
238
- #### ~~Issue F-8: No keyboard shortcut to collapse/expand sidebar~~ ✅ FIXED
239
- `B` key toggles sidebar. Number keys 1–8 navigate pages. Shortcuts are suppressed when focus is in an input/textarea.
240
-
241
- ---
242
-
243
- #### ~~Issue F-9: `CollectionsPage.jsx` naming confusion~~ ✅ FIXED
244
- Renamed to `SpecsPage.jsx`, route changed to `/specs`. `/collections` still works as a redirect alias. Sidebar now shows "Specs" label.
245
-
246
- ---
247
-
248
- ### 🟡 CODE QUALITY
249
-
250
- #### Issue F-10: Inline styles everywhere ⏳ REMAINING
251
- `WorkflowPage.jsx` still uses inline `style={{}}` objects. Sub-components inherit this. Move to CSS classes.
252
-
253
- #### Issue F-11: `index.css` is 27,295 bytes — all styles in one file ⏳ REMAINING
254
- Still a single file. Should split into `layout.css`, `components.css`, `workflow.css`, `chat.css`.
255
-
256
- #### ~~Issue F-12: `vite.config.js` has no proxy config~~ ✅ FIXED
257
- Proxy added for `/api` → `http://localhost:8001` and `/uploads` → `http://localhost:8001`. No CORS issues in dev.
258
-
259
- ---
260
-
261
- ## 5. Missing Features (Incomplete Work)
262
-
263
- ### ~~M-1: Streaming LLM responses~~ ✅ IMPLEMENTED
264
- New `POST /api/v1/plan/stream` SSE endpoint. Backend generates the full plan then streams each step as a separate `data: {"type":"step", ...}` event with ~40ms spacing. Frontend `PlanService.streamPlan()` reads the `ReadableStream` via `fetch()` and calls `onStatus`, `onStep`, `onComplete` callbacks. Steps appear one-by-one in the UI as they arrive.
265
-
266
- ### ~~M-2: Step modification from Chat — no diff preview~~ ✅ IMPLEMENTED
267
- `ModifyDiffModal.jsx` intercepts `modify_request` actions from ChatAssistant. Shows a side-by-side before/after diff of body, headers, query_params, path_params. User must click "Apply & Execute" to confirm.
268
-
269
- ### ~~M-3: No export to Postman format~~ ✅ IMPLEMENTED
270
- "Export" button added to `PlanHeader`. Generates a valid Postman Collection v2.1 JSON with all plan steps, actual request headers/body (if executed), and a `{{baseUrl}}` variable. Downloads as `{spec_name}_postman_collection.json`.
271
-
272
- ### M-4: No test assertions/validation step ⏳ REMAINING
273
- `assertions` from `generate_tests` chat action are displayed in the chat bubble but not validated against actual step results. An assertion runner needs to be wired in.
274
-
275
- ### M-5: Profile page doesn't load spec credentials ⏳ REMAINING (verify)
276
- Needs verification that `ProfilePage.jsx` correctly pre-populates from `storedCredentials`.
277
-
278
- ### ~~M-6: Settings page is empty~~ ✅ IMPLEMENTED
279
- `SettingsPage.jsx` rebuilt with:
280
- - **AI Engine section**: shows provider, configurable token budget (stored in localStorage)
281
- - **HTTP section**: configurable request timeout reference
282
- - **Security section**: checklist of active protections
283
-
284
- ### ~~M-7: Usage page has no UI~~ ✅ IMPLEMENTED
285
- New `UsagePage.jsx` at `/usage` route (keyboard shortcut `7`). Reads `/api/v1/usage` endpoint and displays:
286
- - 3 summary tiles (prompt / completion / total tokens)
287
- - Bar chart breakdown by call type (plan, execute_step, analyze, chat)
288
- - Filter by "All time" or "This session"
289
-
290
- ---
291
-
292
- ## 6. Improvement Roadmap
293
-
294
- ### Phase 1 — Fix Critical Bugs ✅ COMPLETE
295
- | # | Task | Status |
296
- |---|------|--------|
297
- | 1 | Remove duplicate `create_all` | ✅ Done |
298
- | 2 | Add `ENCRYPTION_KEY` startup validation | ✅ Done |
299
- | 3 | Fix JWT token persistence on refresh | ✅ Done |
300
- | 4 | Fix silent error swallow in `executeStep` | ✅ Done |
301
- | 5 | Fix `runAllSteps` not stopping on failure | ✅ Done |
302
- | 6 | Remove double `verify_token` in `chat.py` | ✅ Done |
303
-
304
- ### Phase 2 — Code Quality & Naming ✅ COMPLETE
305
- | # | Task | Status |
306
- |---|------|--------|
307
- | 7 | Rename `fetchCollections`/`collections` → `fetchSpecs`/`specs` | ✅ Done |
308
- | 8 | Rename `CollectionsPage` → `SpecsPage`, route `/collections` → `/specs` | ✅ Done |
309
- | 9 | Add user scoping to history + session routes | ✅ Done |
310
- | 10 | Replace `datetime.utcnow()` with `datetime.now(timezone.utc)` | ✅ Done |
311
- | 11 | Fix CRLF line endings in `schemas.py` | ✅ Done |
312
- | 12 | Consistent `/api/v1` prefix on all routes | ✅ Done |
313
-
314
- ### Phase 3 — Refactor & Structure ✅ MOSTLY COMPLETE
315
- | # | Task | Status |
316
- |---|------|--------|
317
- | 13 | Split `WorkflowPage.jsx` into sub-components | ✅ Done |
318
- | 14 | Split `ChatAssistant.jsx` into sub-components | ⏳ Remaining |
319
- | 15 | Split `index.css` into logical files | ⏳ Remaining |
320
- | 16 | Add Vite proxy config | ✅ Done |
321
- | 17 | Fix `response_analyzer.py` to return fallback on parse failure | ✅ Done |
322
- | 18 | Reduce spec size sent to planner LLM | ✅ Done |
323
-
324
- ### Phase 4 — Missing Features ✅ MOSTLY COMPLETE
325
- | # | Task | Status |
326
- |---|------|--------|
327
- | 19 | SSE streaming for `/plan` endpoint | ✅ Done |
328
- | 20 | Modification diff preview before chat-triggered execution | ✅ Done |
329
- | 21 | Populate SettingsPage with real settings | ✅ Done |
330
- | 22 | Token Usage dashboard page | ✅ Done |
331
- | 23 | Test assertions runner from chat `generate_tests` action | ⏳ Remaining |
332
- | 24 | Export plan as Postman Collection | ✅ Done |
333
-
334
- ### Phase 5 — Production Hardening ⏳ REMAINING
335
- | # | Task | Effort |
336
- |---|------|--------|
337
- | 25 | Redis-backed rate limiting | 1 hr |
338
- | 26 | `ENCRYPTION_KEY` migration for existing plaintext credentials | 1 hr |
339
- | 27 | ~~Proper API versioning (`/api/v1/`)~~ ✅ Already done in Phase 2 | — |
340
- | 28 | Add `docker-compose.yml` (postgres + redis + backend + frontend) | 2 hrs |
341
-
342
- ---
343
-
344
- ## 7. Execution Plan — Phase by Phase
345
-
346
- ### How to Run the Project (Current State)
347
-
348
- **Backend:**
349
- ```bash
350
- # 1. Create virtual environment
351
- python -m venv venv
352
- source venv/bin/activate # Windows: venv\Scripts\activate
353
-
354
- # 2. Install dependencies
355
- pip install -r requirements.txt
356
-
357
- # 3. Set up database
358
- alembic upgrade head
359
-
360
- # 4. Run backend
361
- uvicorn backend.main:app --reload --port 8001
362
- ```
363
-
364
- **Frontend:**
365
- ```bash
366
- cd frontend-react
367
- npm install
368
- npm run dev # starts on http://localhost:5173
369
- ```
370
-
371
- **Environment variables needed in `.env` (project root):**
372
- ```env
373
- DATABASE_URL=postgresql://user:password@localhost:5432/apitest
374
- MISTRAL_API_KEY=your-mistral-key
375
- ENCRYPTION_KEY=your-fernet-key # generate: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
376
- JWT_SECRET=your-long-random-secret
377
- AUTH_USERNAME=admin
378
- AUTH_PASSWORD=yourpassword
379
- ALLOWED_ORIGINS=http://localhost:5173
380
- UPLOAD_DIR=backend/uploads
381
- ```
382
-
383
- > **Note:** Server will refuse to start without a valid `ENCRYPTION_KEY`.
384
-
385
- ---
386
-
387
- ### Proper Execution Flow (After Fixes)
388
-
389
- ```
390
- User → Login Page
391
- ↓ POST /api/v1/auth/login → JWT token (stored in sessionStorage — survives refresh)
392
-
393
- User → SpecsPage (/specs)
394
- ↓ Upload OpenAPI/Postman spec
395
- ↓ POST /api/v1/upload-spec → parsed + stored in DB
396
- ↓ Click spec to activate it → GET /api/v1/specs/{id}
397
-
398
- User → WorkflowPage
399
- ↓ Set Base URL
400
- ↓ Type test scenario
401
- ↓ Click "Generate Plan" → POST /api/v1/plan/stream (SSE)
402
- → Steps appear one-by-one as AI generates them
403
- ↓ Plan appears as ordered steps
404
-
405
- For each step:
406
- ↓ Click "Execute" or "Run All" (stops on first failure)
407
- ↓ POST /api/v1/execute-step → AI builds HTTP request → executes
408
- ↓ Response stored in DB (ExecutionHistory, user-scoped)
409
- ↓ POST /api/v1/analyze-response → AI analyzes status + extracts variables
410
- ↓ Variables saved to session context (PostgreSQL)
411
- ↓ Next step can use extracted variables (token, user_id, etc.)
412
-
413
- If OTP required:
414
- → OTP modal appears → user enters code → saved to context
415
-
416
- If selection required:
417
- → Selection modal appears → user picks item → ID saved to context
418
-
419
- User → Chat (right panel)
420
- ↓ "Retry step 3 with a different email"
421
- ↓ POST /api/v1/chat → AI returns action: "modify_request" + changes
422
- ↓ ModifyDiffModal shows before/after diff — user confirms
423
- ↓ Modified step executes
424
-
425
- User → History (/history)
426
- ↓ View own past sessions (user-scoped)
427
- ↓ Export session as JSON
428
- ↓ Re-import session to WorkflowPage
429
-
430
- User → Usage (/usage)
431
- ↓ See token consumption breakdown by call type
432
- ↓ Filter by all-time or current session
433
-
434
- User → Settings (/settings)
435
- ↓ Configure token budget + HTTP timeout
436
- ↓ View active security protections
437
-
438
- User → Export (PlanHeader button)
439
- ↓ Download executed plan as Postman Collection v2.1 JSON
440
- ```
441
-
442
- ---
443
-
444
- ## 8. File-by-File Fix Reference
445
-
446
- ### Backend Files
447
-
448
- | File | Issues | Status |
449
- |------|--------|--------|
450
- | `main.py` | Duplicate `create_all`, no startup validation, no user middleware | ✅ Fixed |
451
- | `database.py` | Duplicate `create_all`, deprecated `utcnow` | ✅ Fixed |
452
- | `schemas.py` | CRLF line endings | ✅ Fixed |
453
- | `core/auth.py` | Was fine — already uses `timezone.utc` | ✅ No change needed |
454
- | `core/crypto.py` | Silent plaintext fallback | ✅ Mitigated by startup validation |
455
- | `core/limiter.py` | In-memory — resets on restart | ⏳ Phase 5 |
456
- | `app/api/routes/chat.py` | Double `verify_token`, deprecated `utcnow` | ✅ Fixed |
457
- | `app/api/routes/execution.py` | Sync plan route, no SSE | ✅ Fixed (async + SSE) |
458
- | `app/api/routes/history.py` | No user scoping | ✅ Fixed |
459
- | `app/api/routes/sessions.py` | No ownership check on DELETE | ✅ Fixed |
460
- | `services/response_analyzer.py` | No fallback on parse failure | ✅ Fixed |
461
- | `services/llm_planner.py` | Sends full spec to LLM | ✅ Fixed (condensed) |
462
-
463
- ### Frontend Files
464
-
465
- | File | Issues | Status |
466
- |------|--------|--------|
467
- | `services/api.js` | Token lost on refresh, no `/api/v1` prefix | ✅ Fixed |
468
- | `components/AppContext.jsx` | `fetchCollections` fetches specs | ✅ Fixed |
469
- | `pages/WorkflowPage.jsx` | 739 lines, silent errors, bad run-all logic | ✅ Fixed + split |
470
- | `components/SpecsPage.jsx` | (new) Replaces CollectionsPage | ✅ Created |
471
- | `components/SettingsPage.jsx` | Empty / non-functional | ✅ Rebuilt |
472
- | `components/UsagePage.jsx` | (new) Token usage dashboard | ✅ Created |
473
- | `components/ChatAssistant.jsx` | 800+ lines | ⏳ Still to split |
474
- | `App.jsx` | Route `/collections` confusing, no keyboard shortcuts | ✅ Fixed |
475
- | `vite.config.js` | No dev proxy | ✅ Fixed |
476
- | `components/workflow/*.jsx` | (new) WorkflowPage sub-components | ✅ Created |
477
-
478
- ---
479
-
480
- ### WorkflowPage Split — Implemented
481
-
482
- ```
483
- pages/WorkflowPage.jsx (~280 lines — layout + state coordination)
484
- └── components/workflow/
485
- ├── ScenarioComposer.jsx (~60 lines — textarea + generate button)
486
- ├── PlanHeader.jsx (~70 lines — step count, progress, run-all, export)
487
- ├── StepCard.jsx (~120 lines — single step rendering)
488
- ├── ContextPanel.jsx (~70 lines — session vars + credentials)
489
- ├── OtpModal.jsx (~45 lines — OTP input modal)
490
- ├── SelectionModal.jsx (~60 lines — selection picker modal)
491
- └── ModifyDiffModal.jsx (~80 lines — AI modification diff preview)
492
- ```
493
-
494
- ---
495
-
496
- ### Remaining Work (Phase 5 + leftovers)
497
-
498
- | # | Task | Effort |
499
- |---|------|--------|
500
- | A | Redis-backed rate limiting (`limiter.py`) | 1 hr |
501
- | B | `docker-compose.yml` (postgres + redis + backend + frontend) | 2 hrs |
502
- | C | Split `ChatAssistant.jsx` into `ChatMessages`, `ChatInput`, `ChatSessionSidebar` | 1–2 hrs |
503
- | D | Split `index.css` into logical files | 1 hr |
504
- | E | Test assertions runner (wire `generate_tests` action to validation UI) | 3 hrs |
505
- | F | Auto-generate smart chat session names with LLM (3–5 words) | 1 hr |
506
- | G | Verify `ProfilePage.jsx` pre-populates `storedCredentials` correctly | 30 min |
507
- | H | Move inline `style={{}}` objects to CSS classes | 2 hrs |
508
-
509
- ---
510
-
511
- *Last updated: May 2026 | Phases 1–4 complete | Phase 5 + leftovers remaining*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 6.md DELETED
@@ -1,533 +0,0 @@
1
- # Plan 6 — Real ID Resolution for Path & Body Parameters
2
-
3
- > **Problem:** Some API calls require real IDs (e.g. `bus_id`, `product_id`, `seat_id`) embedded
4
- > directly in the URL or request body. These IDs cannot be guessed or randomly generated by the AI —
5
- > they must come from a prior API response or be provided manually by the user.
6
- > This plan covers detection, planner-level fixes, executor-level guards, and frontend handling.
7
- >
8
- > **Scope:** Backend (`llm_planner.py`, `api_executor.py`, `execution.py`, `schemas.py`) +
9
- > Frontend (`WorkflowPage.jsx`, `SelectionModal.jsx`, `services/api.js`)
10
- >
11
- > **Status:** Completed — 2026-05-10
12
-
13
- ---
14
-
15
- ## Table of Contents
16
-
17
- 1. [Problem Statement](#1-problem-statement)
18
- 2. [Root Cause Analysis](#2-root-cause-analysis)
19
- 3. [Solution Architecture](#3-solution-architecture)
20
- 4. [Phase 1 — Schemas](#4-phase-1--schemas)
21
- 5. [Phase 2 — Planner Prompt](#5-phase-2--planner-prompt)
22
- 6. [Phase 3 — Executor Guard](#6-phase-3--executor-guard)
23
- 7. [Phase 4 — Frontend Intercept](#7-phase-4--frontend-intercept)
24
- 8. [Phase 5 — SelectionModal Manual Input Mode](#8-phase-5--selectionmodal-manual-input-mode)
25
- 9. [End-to-End Flow](#9-end-to-end-flow)
26
- 10. [File-by-File Changes](#10-file-by-file-changes)
27
- 11. [Execution Checklist](#11-execution-checklist)
28
-
29
- ---
30
-
31
- ## 1. Problem Statement
32
-
33
- When the AI builds an HTTP request in `api_executor.py`, it fills path/body parameters using
34
- this priority order (from `STEP_PROMPT`):
35
-
36
- ```
37
- Priority 1: Context Variables (from previous steps)
38
- Priority 2: User Credentials
39
- Priority 3: Step Definition / Scenario data
40
- ```
41
-
42
- **Two failure scenarios:**
43
-
44
- **Scenario A — ID needed at step 1, context is empty**
45
- ```
46
- Step 1: POST /buses/{bus_id}/book
47
- Context: {} ← empty, no prior steps ran
48
-
49
- AI hallucinates: bus_id = 123
50
- API returns: 404 Not Found
51
- ```
52
-
53
- **Scenario B — ID comes from a list, AI picks wrong one**
54
- ```
55
- Step 1: GET /buses → returns [{ id: 42, name: "Express" }, { id: 99, name: "Local" }]
56
- Step 2: POST /bookings → needs bus_id
57
-
58
- Analyzer sets is_selection_required: true ✅ (already works)
59
- BUT: if analyzer is skipped or times out, executor uses bus_id = 42 blindly
60
- ```
61
-
62
- **Result in both cases:** The test fails not because the API is broken, but because the AI used
63
- a fake or wrong ID. This gives false negatives and makes the tool unreliable for real-world APIs.
64
-
65
- ---
66
-
67
- ## 2. Root Cause Analysis
68
-
69
- ### Why the planner doesn't catch it
70
-
71
- `llm_planner.py` receives a condensed spec (method + path + summary only) and generates a plan.
72
- It has no instruction to detect unresolvable path parameters or insert prerequisite fetch steps.
73
-
74
- The current `PLANNER_PROMPT` says nothing about:
75
- - Detecting `{param}` in endpoint paths that require real DB values
76
- - Inserting a GET/list step before a step that needs a real ID
77
- - Flagging which context keys each step depends on
78
-
79
- ### Why the executor doesn't block it
80
-
81
- `api_executor.py` (`STEP_PROMPT`) says:
82
- > "You MUST replace all path variables like `{id}` or `{bus_id}` with actual values from Context
83
- > or Step Definition."
84
-
85
- But it does **not** say what to do when the value is genuinely missing. The AI guesses.
86
- There is no sentinel value, no guard in `execution.py`, and no way for the frontend to know
87
- that an ID was hallucinated.
88
-
89
- ### Why the existing selection flow isn't enough
90
-
91
- `response_analyzer.py` already detects `is_selection_required` after a GET/list step responds.
92
- This works — but only when:
93
- 1. A list-returning step ran immediately before
94
- 2. The analyzer ran successfully (not timed out or parse-failed)
95
- 3. The planner actually included the prerequisite GET step
96
-
97
- When any of these conditions fails, the executor proceeds with a guessed ID.
98
-
99
- ---
100
-
101
- ## 3. Solution Architecture
102
-
103
- The fix has four layers working together:
104
-
105
- ```
106
- ┌─────────────────────────────────────────────────────────┐
107
- │ LAYER 1: Planner (llm_planner.py) │
108
- │ Detects unresolvable path params at plan-generation │
109
- │ time. Inserts prerequisite GET steps automatically. │
110
- │ Adds required_context_keys to each StepDefinition. │
111
- └─────────────────────────────────────────────────────────┘
112
- ↓
113
- ┌─────────────────────────────────────────────────────────┐
114
- │ LAYER 2: Executor (api_executor.py) │
115
- │ Emits "__MISSING__{param}__" sentinel when a required │
116
- │ path/body param is absent from context, instead of │
117
- │ hallucinating a value. │
118
- └─────────────────────────────────────────────────────────┘
119
- ↓
120
- ┌─────────────────────────────────────────────────────────┐
121
- │ LAYER 3: Route Guard (execution.py) │
122
- │ Detects "__MISSING__" in the resolved URL or body. │
123
- │ Returns HTTP 400 with a structured error instead of │
124
- │ firing a broken request to the real API. │
125
- └─────────────────────────────────────────────────────────┘
126
- ↓
127
- ┌─────────────────────────────────────────────────────────┐
128
- │ LAYER 4: Frontend (WorkflowPage + SelectionModal) │
129
- │ Intercepts the 400 / missing-key detection before │
130
- │ calling execute-step. Shows a manual input modal. │
131
- │ User provides the real ID → saved to context → │
132
- │ execution proceeds with the real value. │
133
- └─────────────────────────────────────────────────────────┘
134
- ```
135
-
136
- ---
137
-
138
- ## 4. Phase 1 — Schemas
139
-
140
- **File:** `backend/schemas.py`
141
-
142
- Add `required_context_keys` to `StepDefinition` so the planner can annotate each step
143
- with the context keys it needs that cannot be auto-generated.
144
-
145
- ### Change
146
-
147
- ```python
148
- # BEFORE
149
- class StepDefinition(BaseModel):
150
- step: int
151
- endpoint: str
152
- purpose: str
153
-
154
- # AFTER
155
- class StepDefinition(BaseModel):
156
- step: int
157
- endpoint: str
158
- purpose: str
159
- required_context_keys: Optional[List[str]] = []
160
- # e.g. ["bus_id", "route_id"] — keys that must exist in context before this step runs
161
- # populated by the planner when a path/body param cannot be resolved automatically
162
- ```
163
-
164
- No DB migration needed — `StepDefinition` is only used in `execution_plan` (JSON column in
165
- `SpecDocument`) and in request/response Pydantic models. The `[]` default is backward-compatible
166
- with existing saved plans.
167
-
168
- ---
169
-
170
- ## 5. Phase 2 — Planner Prompt
171
-
172
- **File:** `backend/services/llm_planner.py`
173
-
174
- ### 2a — Update PLANNER_PROMPT
175
-
176
- Add two new rules at the end of the existing `PLANNER_PROMPT`:
177
-
178
- ```python
179
- PLANNER_PROMPT = """
180
- ... (existing content) ...
181
-
182
- DEPENDENCY RULE (CRITICAL):
183
- - Inspect every endpoint in your plan for path parameters (e.g. {bus_id}, {product_id}, {seat_id}).
184
- - If a path parameter cannot be known in advance (not in USER CREDENTIALS, not a UUID to generate,
185
- not derivable from a prior step in THIS plan), you MUST insert a GET/list step immediately before
186
- the step that needs it. That GET step should fetch the list of available options.
187
- - Example: "POST /buses/{bus_id}/book" at step 1 → insert "GET /buses" at step 1, shift booking to step 2.
188
- - Example: "GET /routes/{route_id}/stops" where route_id comes from a previous GET /routes → no insertion needed.
189
-
190
- REQUIRED_CONTEXT_KEYS RULE:
191
- - For each step, set "required_context_keys" to a list of context variable names that MUST be present
192
- before this step can run and that the AI cannot safely generate (real IDs, external references).
193
- - If the step needs no special context, set "required_context_keys" to [].
194
- - Example: step "POST /bookings/{bus_id}" → required_context_keys: ["bus_id"]
195
- - Example: step "POST /auth/login" with email/password from credentials → required_context_keys: []
196
- """
197
- ```
198
-
199
- ### 2b — Update the expected JSON format in the prompt
200
-
201
- ```json
202
- {
203
- "execution_plan": [
204
- {
205
- "step": 1,
206
- "endpoint": "GET /buses",
207
- "purpose": "Fetch available buses so user can select a real bus_id",
208
- "required_context_keys": []
209
- },
210
- {
211
- "step": 2,
212
- "endpoint": "POST /buses/{bus_id}/book",
213
- "purpose": "Book the selected bus",
214
- "required_context_keys": ["bus_id"]
215
- }
216
- ],
217
- "suggested_credentials": { ... }
218
- }
219
- ```
220
-
221
- ### 2c — No changes to `generate_execution_plan()` function
222
-
223
- The existing `JsonOutputParser` + retry logic handles the new field automatically since
224
- `StepDefinition` now includes `required_context_keys`. No function body changes needed.
225
-
226
- ---
227
-
228
- ## 6. Phase 3 — Executor Guard
229
-
230
- ### 3a — STEP_PROMPT addition
231
-
232
- **File:** `backend/services/api_executor.py`
233
-
234
- Add this rule to `STEP_PROMPT` after the existing "NO TEMPLATE STRINGS" rule:
235
-
236
- ```
237
- MISSING ID RULE (CRITICAL):
238
- - If a required path parameter (e.g. {bus_id}) or required body field is an ID that is NOT present
239
- in Context Variables and cannot be reasonably generated (it is a real DB record ID, not a UUID
240
- you create), do NOT guess a value.
241
- - Instead, set the parameter to the literal string "__MISSING__{param_name}__"
242
- (e.g. "__MISSING__bus_id__") so the caller can detect and block execution.
243
- - Examples of IDs you MUST NOT guess: bus_id, product_id, order_id, seat_id, route_id, ticket_id.
244
- - Examples of IDs you CAN generate: new UUIDs for user registration, random test email addresses.
245
- ```
246
-
247
- ### 3b — Guard in execution route
248
-
249
- **File:** `backend/app/api/routes/execution.py`
250
-
251
- After `prepare_step_request` returns, add a guard before the HTTP call:
252
-
253
- ```python
254
- # After: req_plan, executor_token_usage = await asyncio.to_thread(prepare_step_request, ...)
255
-
256
- # Guard: detect sentinel values that mean the AI couldn't resolve a real ID
257
- import re as _re
258
- _MISSING_PATTERN = _re.compile(r"__MISSING__(\w+)__")
259
-
260
- missing_in_url = _MISSING_PATTERN.findall(req_plan.request.url)
261
- missing_in_body = _MISSING_PATTERN.findall(json.dumps(req_plan.request.body or {}))
262
- all_missing = list(set(missing_in_url + missing_in_body))
263
-
264
- if all_missing:
265
- raise HTTPException(
266
- status_code=400,
267
- detail={
268
- "error": "missing_context_keys",
269
- "message": f"Step requires real IDs that are not in context: {all_missing}. "
270
- f"Please provide them manually before executing this step.",
271
- "missing_keys": all_missing,
272
- }
273
- )
274
- ```
275
-
276
- This surfaces a clean, structured error to the frontend instead of sending a broken request
277
- to the real API.
278
-
279
- ---
280
-
281
- ## 7. Phase 4 — Frontend Intercept
282
-
283
- **File:** `frontend-react/src/pages/WorkflowPage.jsx`
284
-
285
- ### 4a — Pre-execution check using `required_context_keys`
286
-
287
- Before calling `PlanService.executeStep()`, check if the step's `required_context_keys`
288
- are all present in `sessionContextVars`:
289
-
290
- ```javascript
291
- const executeStep = async (stepDef) => {
292
- // NEW: Check for required context keys before attempting execution
293
- const requiredKeys = stepDef.required_context_keys || [];
294
- const missingKeys = requiredKeys.filter(key => !sessionContextVars[key]);
295
-
296
- if (missingKeys.length > 0) {
297
- setSelectionPrompt({
298
- type: 'manual_input',
299
- step: stepDef,
300
- missingKeys,
301
- // No options — user must type the real value
302
- });
303
- return; // Don't proceed until user provides the values
304
- }
305
-
306
- // existing execution logic continues...
307
- setExecutingStep(stepDef.step);
308
- try { ... }
309
- };
310
- ```
311
-
312
- ### 4b — Handle `missing_context_keys` error from backend
313
-
314
- The executor guard (Phase 3) returns HTTP 400 with `error: "missing_context_keys"`.
315
- Catch this in the executeStep error handler:
316
-
317
- ```javascript
318
- } catch (err) {
319
- // NEW: Handle structured missing-key error from backend
320
- if (err.response?.data?.error === 'missing_context_keys') {
321
- const missing = err.response.data.missing_keys || [];
322
- setSelectionPrompt({
323
- type: 'manual_input',
324
- step: stepDef,
325
- missingKeys: missing,
326
- });
327
- return;
328
- }
329
- // existing error handling...
330
- addToast('error', err.message || 'Step execution failed.');
331
- }
332
- ```
333
-
334
- ### 4c — Handle manual input confirmation
335
-
336
- When the user submits values in the manual input modal, save each key to context and retry:
337
-
338
- ```javascript
339
- const handleManualInputConfirm = async (values) => {
340
- // values = { bus_id: "42", route_id: "7" }
341
- for (const [key, value] of Object.entries(values)) {
342
- await SessionService.updateContext(sessionId, key, value);
343
- }
344
- await refreshSessionContext(); // reload sessionContextVars from DB
345
- setSelectionPrompt(null);
346
-
347
- // Retry the step now that context is populated
348
- await executeStep(selectionPrompt.step);
349
- };
350
- ```
351
-
352
- ---
353
-
354
- ## 8. Phase 5 — SelectionModal Manual Input Mode
355
-
356
- **File:** `frontend-react/src/components/workflow/SelectionModal.jsx`
357
-
358
- The existing `SelectionModal` handles `is_selection_required` (picking from a list).
359
- Add a second mode: `manual_input` (user types in unknown IDs).
360
-
361
- ### New prop: `type`
362
-
363
- ```
364
- type = 'selection' → existing behavior (radio list from selection_options)
365
- type = 'manual_input' → new behavior (text inputs for each missing key)
366
- ```
367
-
368
- ### New render branch
369
-
370
- ```jsx
371
- {type === 'manual_input' && (
372
- <div className="manual-input-section">
373
- <p className="modal-description">
374
- This step requires real IDs that could not be determined automatically.
375
- Please enter the correct values from your system or database.
376
- </p>
377
- {missingKeys.map(key => (
378
- <div key={key} className="input-row">
379
- <label className="input-label">{key}</label>
380
- <input
381
- type="text"
382
- className="input-field"
383
- placeholder={`Enter real value for ${key}`}
384
- value={inputValues[key] || ''}
385
- onChange={e => setInputValues(prev => ({ ...prev, [key]: e.target.value }))}
386
- />
387
- </div>
388
- ))}
389
- <div className="modal-actions">
390
- <button
391
- className="btn-primary"
392
- disabled={missingKeys.some(k => !inputValues[k]?.trim())}
393
- onClick={() => onConfirm(inputValues)}
394
- >
395
- Save & Execute
396
- </button>
397
- <button className="btn-secondary" onClick={onClose}>Cancel</button>
398
- </div>
399
- </div>
400
- )}
401
- ```
402
-
403
- The `disabled` check ensures the user can't confirm with empty fields — every missing key
404
- must be filled before execution proceeds.
405
-
406
- ---
407
-
408
- ## 9. End-to-End Flow
409
-
410
- ### Flow A — Planner inserts prerequisite step (happy path)
411
-
412
- ```
413
- User uploads spec with: POST /buses/{bus_id}/book
414
-
415
- Planner runs (with new DEPENDENCY RULE)
416
- └── Detects {bus_id} in path, not in credentials, no prior step provides it
417
- └── Inserts: Step 1 = GET /buses (purpose: "fetch available buses")
418
- └── Original becomes: Step 2 = POST /buses/{bus_id}/book
419
- required_context_keys: ["bus_id"]
420
-
421
- User executes Step 1 (GET /buses)
422
- └── Response: [{ id: 42, name: "Express" }, { id: 99, name: "Local" }]
423
- └── Analyzer: is_selection_required = true, selection_options = [...]
424
- └── SelectionModal (existing behavior) appears → user picks Bus 42
425
- └── bus_id = 42 saved to context
426
-
427
- User executes Step 2 (POST /buses/42/book)
428
- └── Frontend pre-check: required_context_keys = ["bus_id"], context has bus_id ✅
429
- └── Executor: finds bus_id=42 in context → URL resolves to /buses/42/book
430
- └── Real API call succeeds ✅
431
- ```
432
-
433
- ### Flow B — ID needed at step 1, no list endpoint exists in spec
434
-
435
- ```
436
- User uploads spec with only: POST /bookings/{bus_id}
437
- (No GET /buses endpoint in this spec)
438
-
439
- Planner runs
440
- └── Tries to insert GET /buses but it's not in spec → cannot insert
441
- └── Marks Step 1 required_context_keys: ["bus_id"]
442
- └── Step 1: POST /bookings/{bus_id}, required_context_keys: ["bus_id"]
443
-
444
- User clicks Execute on Step 1
445
- └── Frontend pre-check: required_context_keys = ["bus_id"]
446
- └── sessionContextVars has no bus_id → missingKeys = ["bus_id"]
447
- └── SelectionModal opens in manual_input mode
448
- └── User types: bus_id = "42" (from their own system/dashboard)
449
- └── SessionService.updateContext(sessionId, "bus_id", "42") called
450
- └── context refreshed → bus_id = 42 now in sessionContextVars
451
-
452
- User clicks Execute again (auto-triggered after modal confirm)
453
- └── Frontend pre-check: bus_id ✅ in context
454
- └── Executor resolves URL to /bookings/42
455
- └── Real API call succeeds ✅
456
- ```
457
-
458
- ### Flow C — Executor catches a hallucinated ID (safety net)
459
-
460
- ```
461
- (Planner didn't insert a prerequisite step, and required_context_keys is empty/missing)
462
-
463
- Executor prompt receives: context = {}, step = POST /buses/{bus_id}/book
464
-
465
- With new MISSING ID RULE:
466
- └── AI cannot find bus_id in context
467
- └── AI sets URL to: /buses/__MISSING__bus_id__/book
468
-
469
- execution.py guard fires:
470
- └── Detects "__MISSING__bus_id__" in URL
471
- └── Returns HTTP 400: { error: "missing_context_keys", missing_keys: ["bus_id"] }
472
-
473
- Frontend catches 400:
474
- └── Opens SelectionModal in manual_input mode
475
- └── User provides bus_id → context updated → step retried ✅
476
- ```
477
-
478
- ---
479
-
480
- ## 10. File-by-File Changes
481
-
482
- | File | Change | Effort |
483
- |------|--------|--------|
484
- | `backend/schemas.py` | Add `required_context_keys: Optional[List[str]] = []` to `StepDefinition` | 5 min |
485
- | `backend/services/llm_planner.py` | Add DEPENDENCY RULE + REQUIRED_CONTEXT_KEYS RULE to `PLANNER_PROMPT`. Update JSON format example. | 20 min |
486
- | `backend/services/api_executor.py` | Add MISSING ID RULE to `STEP_PROMPT` | 10 min |
487
- | `backend/app/api/routes/execution.py` | Add `__MISSING__` sentinel guard after `prepare_step_request` | 15 min |
488
- | `frontend-react/src/pages/WorkflowPage.jsx` | Add pre-execution `required_context_keys` check. Add `missing_context_keys` error handler. Add `handleManualInputConfirm`. | 30 min |
489
- | `frontend-react/src/components/workflow/SelectionModal.jsx` | Add `manual_input` mode with text inputs per missing key | 20 min |
490
-
491
- **Total estimated effort: ~1.5 hours**
492
-
493
- No database migrations required.
494
- No new dependencies required.
495
- No new API endpoints required.
496
-
497
- ---
498
-
499
- ## 11. Execution Checklist
500
-
501
- ### Backend
502
-
503
- - [x] `schemas.py` — add `required_context_keys` field to `StepDefinition`
504
- - [x] `llm_planner.py` — add DEPENDENCY RULE to `PLANNER_PROMPT`
505
- - [x] `llm_planner.py` — add REQUIRED_CONTEXT_KEYS RULE to `PLANNER_PROMPT`
506
- - [x] `llm_planner.py` — update JSON format example to include `required_context_keys`
507
- - [x] `api_executor.py` — add MISSING ID RULE to `STEP_PROMPT`
508
- - [x] `execution.py` — add `__MISSING__` sentinel detection guard
509
- - [x] `execution.py` — return structured `{ error: "missing_context_keys", missing_keys: [...] }`
510
-
511
- ### Frontend
512
-
513
- - [x] `WorkflowPage.jsx` — add `required_context_keys` pre-execution check in `executeStep`
514
- - [x] `WorkflowPage.jsx` — add `missing_context_keys` error catch + trigger manual input modal
515
- - [x] `WorkflowPage.jsx` — add `handleManualInputConfirm` (saves each key to context, retries step)
516
- - [x] `SelectionModal.jsx` — add `manual_input` mode prop
517
- - [x] `SelectionModal.jsx` — render text inputs for each `missingKey`
518
- - [x] `SelectionModal.jsx` — disable confirm button until all fields are filled
519
-
520
- ### Testing
521
-
522
- - [ ] Test with a spec where step 1 has a path param (e.g. `GET /items/{item_id}`)
523
- - [ ] Verify planner inserts a prerequisite GET step automatically
524
- - [ ] Verify `required_context_keys` appears correctly on the dependent step
525
- - [ ] Test manual input modal appears when context is empty and keys are required
526
- - [ ] Test values entered in modal are saved to context via `SessionService.updateContext`
527
- - [ ] Test step auto-retries with correct context after modal confirm
528
- - [ ] Test `__MISSING__` sentinel triggers the 400 guard (for cases planner misses)
529
- - [ ] Test the 400 error triggers the manual input modal as a fallback
530
-
531
- ---
532
-
533
- *Plan 6 | Real ID Resolution | Completed 2026-05-10 | Est. 1.5 hrs*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Plans/plan 7.md DELETED
@@ -1,653 +0,0 @@
1
- # Plan 7 — Cookie Management (Postman-style)
2
-
3
- > **Problem:** Many real-world APIs set cookies in `Set-Cookie` response headers (session tokens,
4
- > CSRF tokens, auth cookies) and expect those cookies to be sent back in the `Cookie` header on
5
- > subsequent requests. The app currently captures response headers but does nothing with
6
- > `Set-Cookie`. Cookies are never forwarded, so any API that relies on cookie-based sessions
7
- > will fail from step 2 onward.
8
- >
9
- > **Scope:** Backend (`execution.py`, `response_analyzer.py`, `api_executor.py`, `schemas.py`,
10
- > `context_manager.py`, `database.py`) + Frontend (`WorkflowPage.jsx`, `ContextPanel.jsx`,
11
- > `StepCard.jsx`)
12
- >
13
- > **Status:** Not started
14
-
15
- ---
16
-
17
- ## Table of Contents
18
-
19
- 1. [Problem Statement](#1-problem-statement)
20
- 2. [How Postman Handles Cookies](#2-how-postman-handles-cookies)
21
- 3. [Root Cause Analysis](#3-root-cause-analysis)
22
- 4. [Solution Architecture](#4-solution-architecture)
23
- 5. [Phase 1 — Cookie Jar in Session Context](#5-phase-1--cookie-jar-in-session-context)
24
- 6. [Phase 2 — Extract Cookies from Responses](#6-phase-2--extract-cookies-from-responses)
25
- 7. [Phase 3 — Forward Cookies on Requests](#7-phase-3--forward-cookies-on-requests)
26
- 8. [Phase 4 — Teach the Executor About Cookies](#8-phase-4--teach-the-executor-about-cookies)
27
- 9. [Phase 5 — Frontend Cookie Visibility](#9-phase-5--frontend-cookie-visibility)
28
- 10. [Edge Cases](#10-edge-cases)
29
- 11. [End-to-End Flow](#11-end-to-end-flow)
30
- 12. [File-by-File Changes](#12-file-by-file-changes)
31
- 13. [Execution Checklist](#13-execution-checklist)
32
-
33
- ---
34
-
35
- ## 1. Problem Statement
36
-
37
- A typical cookie-based auth flow looks like this:
38
-
39
- ```
40
- Step 1: POST /auth/login
41
- → Response headers: Set-Cookie: session_id=abc123; HttpOnly; Path=/
42
- → Response body: { "message": "Login successful" }
43
-
44
- Step 2: GET /user/profile
45
- → Request headers: Cookie: session_id=abc123 ← MUST be sent
46
- → Response body: { "name": "Amit", ... }
47
- ```
48
-
49
- **What the app does today:**
50
-
51
- ```
52
- Step 1: POST /auth/login
53
- → Response captured: { status_code: 200, body: "...", headers: { "set-cookie": "session_id=abc123..." } }
54
- → set-cookie is saved in resp_data["headers"] but NOTHING HAPPENS WITH IT
55
-
56
- Step 2: GET /user/profile
57
- → Request built by AI with no Cookie header
58
- → API returns: 401 Unauthorized ← false negative
59
- ```
60
-
61
- The test fails not because the API is broken — the AI simply never learned about the cookie.
62
-
63
- This affects every API that uses:
64
- - Session-based authentication (`session_id`, `PHPSESSID`, `connect.sid`)
65
- - CSRF protection (`csrftoken`, `XSRF-TOKEN`)
66
- - Remember-me tokens
67
- - Any cookie set by frameworks (Django, Rails, Laravel, Express)
68
-
69
- ---
70
-
71
- ## 2. How Postman Handles Cookies
72
-
73
- Postman has a **Cookie Jar** — a per-domain store of cookies that works like a browser:
74
-
75
- 1. Every response's `Set-Cookie` headers are parsed and stored in the jar.
76
- 2. Every subsequent request to the same domain automatically includes all matching cookies
77
- in the `Cookie` header, respecting `Path`, `Domain`, and expiry.
78
- 3. The Cookie Jar is visible in the Postman UI — users can view, edit, and delete cookies.
79
- 4. Cookies persist across requests in a collection run (equivalent to our session).
80
-
81
- **Our implementation goal:** replicate this behavior within a session.
82
-
83
- We won't implement full browser-level cookie spec (no `SameSite`, no expiry enforcement,
84
- no cross-domain matching) — the pragmatic scope is:
85
-
86
- - Parse `Set-Cookie` from every response
87
- - Store cookies per domain in the session's context
88
- - Forward all matching cookies on every subsequent request to the same domain
89
- - Show cookies in the UI (ContextPanel)
90
- - Allow the AI executor to know cookies exist and reference them
91
-
92
- ---
93
-
94
- ## 3. Root Cause Analysis
95
-
96
- ### Why cookies are lost today
97
-
98
- In `execution.py`, the response is captured as:
99
-
100
- ```python
101
- resp_data = {
102
- "status_code": response.status_code,
103
- "body": body_text,
104
- "headers": dict(response.headers), # set-cookie IS here
105
- }
106
- ```
107
-
108
- `dict(response.headers)` with httpx only returns the **last** `Set-Cookie` value if multiple
109
- cookies are set (httpx uses a case-insensitive multi-dict internally). The cookies are in
110
- `headers["set-cookie"]` but:
111
-
112
- 1. Nothing parses them out of the header string
113
- 2. Nothing saves them to the session's `context_variables`
114
- 3. The executor (`api_executor.py`) has no instruction to include a `Cookie` header
115
- 4. The response analyzer (`response_analyzer.py`) has no instruction to extract cookies
116
-
117
- ### Why the AI doesn't add Cookie headers
118
-
119
- `STEP_PROMPT` in `api_executor.py` says to use Authorization headers for auth — but says
120
- nothing about cookies. The AI has no way to know a cookie was set in a prior step unless it's
121
- explicitly in the context variables and the prompt tells it to use cookies.
122
-
123
- ### Why `response_analyzer.py` doesn't catch cookies
124
-
125
- `ANALYSIS_PROMPT` only looks at the response body. It has no instruction to inspect
126
- `Set-Cookie` headers and extract them as context variables.
127
-
128
- ---
129
-
130
- ## 4. Solution Architecture
131
-
132
- ```
133
- ┌──────────────────────────────────────────────────────────────────┐
134
- │ STEP EXECUTION (execution.py) │
135
- │ │
136
- │ After response received: │
137
- │ 1. Call parse_cookies(response) → { name: value, ... } │
138
- │ 2. Merge into session's cookie_jar: { "api.example.com": {...} }│
139
- │ 3. Save cookie_jar back to session context_variables │
140
- │ 4. Include cookies in resp_data for frontend display │
141
- └──────────────────────────────────────────────────────────────────┘
142
- ↑ reads before request ↓ writes after response
143
- ┌──────────────────────────────────────────────────────────────────┐
144
- │ COOKIE JAR (context_variables["__cookie_jar__"]) │
145
- │ │
146
- │ Structure: │
147
- │ { │
148
- │ "api.example.com": { │
149
- │ "session_id": "abc123", │
150
- │ "csrftoken": "xyz789" │
151
- │ } │
152
- │ } │
153
- │ Stored as a special key in the existing JSON context column. │
154
- │ No schema migration needed. │
155
- └──────────────────────────────────────────────────────────────────┘
156
- ↑ reads before request
157
- ┌──────────────────────────────────────────────────────────────────┐
158
- │ REQUEST BUILDING (execution.py, before executor call) │
159
- │ │
160
- │ Before calling prepare_step_request: │
161
- │ 1. Extract hostname from base_url │
162
- │ 2. Look up cookie_jar[hostname] │
163
- │ 3. Build Cookie header string: "session_id=abc123; csrf=xyz" │
164
- │ 4. Inject into context_variables as "__cookies__" key │
165
- │ 5. Executor sees "__cookies__" and adds Cookie header │
166
- └──────────────────────────────────────────────────────────────────┘
167
- ↓ visible in
168
- ┌──────────────────────────────────────────────────────────────────┐
169
- │ FRONTEND (ContextPanel.jsx, StepCard.jsx) │
170
- │ │
171
- │ ContextPanel: shows cookie jar entries under "Cookies" section │
172
- │ StepCard: shows "Cookie" header in sent request panel │
173
- │ shows parsed Set-Cookie in response headers panel │
174
- └──────────────────────────────────────────────────────────────────┘
175
- ```
176
-
177
- **Key design decision:** We store the cookie jar in `context_variables["__cookie_jar__"]`.
178
- This reuses the existing JSON column, the existing `set_context_variables` function, and the
179
- existing `GET /context/{session_id}` endpoint. No DB migration. No new tables. No new API
180
- endpoints.
181
-
182
- ---
183
-
184
- ## 5. Phase 1 — Cookie Jar in Session Context
185
-
186
- **File:** `backend/services/context_manager.py`
187
-
188
- Add two helper functions that read/write the cookie jar within the existing `context_variables`
189
- JSON column. The jar key is `__cookie_jar__` — double underscores to avoid collision with
190
- real API-extracted variables.
191
-
192
- ### New helpers
193
-
194
- ```python
195
- COOKIE_JAR_KEY = "__cookie_jar__"
196
-
197
- def get_cookie_jar(db: Session, session_id: str) -> dict:
198
- """Returns the full cookie jar: { hostname: { name: value } }"""
199
- context = get_context(db, session_id)
200
- return context.get(COOKIE_JAR_KEY, {})
201
-
202
-
203
- def set_cookies_for_host(db: Session, session_id: str, hostname: str, cookies: dict) -> None:
204
- """Merge new cookies for a hostname into the jar. Existing cookies for other
205
- hosts are preserved. Existing cookies for this host are merged (not replaced)."""
206
- context = get_context(db, session_id)
207
- jar = context.get(COOKIE_JAR_KEY, {})
208
- if hostname not in jar:
209
- jar[hostname] = {}
210
- jar[hostname].update(cookies)
211
- set_context_variables(db, session_id, {COOKIE_JAR_KEY: jar})
212
-
213
-
214
- def get_cookies_for_host(db: Session, session_id: str, hostname: str) -> dict:
215
- """Returns cookies for a specific hostname. Returns {} if none."""
216
- jar = get_cookie_jar(db, session_id)
217
- return jar.get(hostname, {})
218
-
219
-
220
- def clear_cookies_for_host(db: Session, session_id: str, hostname: str) -> None:
221
- """Remove all cookies for a hostname (e.g. after logout)."""
222
- context = get_context(db, session_id)
223
- jar = context.get(COOKIE_JAR_KEY, {})
224
- jar.pop(hostname, None)
225
- set_context_variables(db, session_id, {COOKIE_JAR_KEY: jar})
226
- ```
227
-
228
- ### Cookie parsing utility
229
-
230
- Add a standalone parser (no external dependency — Python's stdlib `http.cookies` handles this):
231
-
232
- ```python
233
- from http.cookies import SimpleCookie
234
- from urllib.parse import urlparse
235
-
236
- def parse_set_cookie_headers(headers: dict) -> dict:
237
- """
238
- Parse Set-Cookie header(s) from a response headers dict.
239
- httpx collapses multiple Set-Cookie values with a comma separator in some versions,
240
- so we handle both the single-value and multi-value cases.
241
-
242
- Returns: { cookie_name: cookie_value } — just name/value, no attributes.
243
- """
244
- cookies = {}
245
- raw = headers.get("set-cookie", "")
246
- if not raw:
247
- return cookies
248
-
249
- # httpx may join multiple Set-Cookie headers with \n
250
- for line in raw.split("\n"):
251
- line = line.strip()
252
- if not line:
253
- continue
254
- try:
255
- c = SimpleCookie()
256
- c.load(line)
257
- for name, morsel in c.items():
258
- cookies[name] = morsel.value
259
- except Exception:
260
- # Malformed cookie — skip, don't crash
261
- pass
262
-
263
- return cookies
264
-
265
-
266
- def hostname_from_url(url: str) -> str:
267
- """Extract just the hostname from a full URL."""
268
- try:
269
- return urlparse(url).hostname or ""
270
- except Exception:
271
- return ""
272
- ```
273
-
274
- **Why stdlib `SimpleCookie` instead of a library:**
275
- No new dependency. `SimpleCookie` handles the `name=value; Path=/; HttpOnly` format correctly.
276
- We only need name + value — we ignore `Path`, `Domain`, `Expires`, `HttpOnly`, `Secure` for now.
277
-
278
- ---
279
-
280
- ## 6. Phase 2 — Extract Cookies from Responses
281
-
282
- **File:** `backend/app/api/routes/execution.py`
283
-
284
- After the HTTP response is received and `resp_data` is built, add cookie extraction:
285
-
286
- ```python
287
- from backend.services.context_manager import (
288
- set_cookies_for_host, get_cookies_for_host,
289
- parse_set_cookie_headers, hostname_from_url
290
- )
291
-
292
- # After: resp_data = { "status_code": ..., "body": ..., "headers": ... }
293
-
294
- # NEW: Extract and persist any Set-Cookie headers from this response
295
- response_cookies = parse_set_cookie_headers(dict(response.headers))
296
- if response_cookies:
297
- host = hostname_from_url(url)
298
- if host:
299
- set_cookies_for_host(db, body.session_id, host, response_cookies)
300
- logger.info(
301
- "Step %s set %d cookie(s) for host '%s': %s",
302
- req_plan.step, len(response_cookies), host, list(response_cookies.keys())
303
- )
304
-
305
- # Add cookies to resp_data so frontend can display them
306
- resp_data["cookies"] = response_cookies # { name: value } — sanitized for display
307
- ```
308
-
309
- This is the only place where `Set-Cookie` headers are parsed. It happens immediately after
310
- every step execution, before the DB write, so the cookies are available for the next step.
311
-
312
- **Important:** `httpx` by default does **not** follow redirects or share a cookie jar between
313
- requests (each `AsyncClient` is independent). We handle the jar manually, which gives us
314
- full visibility and control — matching Postman's behavior.
315
-
316
- ---
317
-
318
- ## 7. Phase 3 — Forward Cookies on Requests
319
-
320
- **File:** `backend/app/api/routes/execution.py`
321
-
322
- Before calling `prepare_step_request`, look up any stored cookies for the target host
323
- and inject them into the context variables that get passed to the executor:
324
-
325
- ```python
326
- from backend.services.context_manager import get_cookies_for_host, hostname_from_url
327
-
328
- # After: effective_credentials resolved, before: step_llm = get_llm_for_task(...)
329
-
330
- # NEW: Look up cookies for this host and inject into context for the executor
331
- host = hostname_from_url(body.base_url)
332
- host_cookies = get_cookies_for_host(db, body.session_id, host)
333
-
334
- # Build context that includes cookies as a special key
335
- execution_context = dict(body.context_variables or {})
336
- if host_cookies:
337
- # Format as a ready-to-use Cookie header string
338
- cookie_header_value = "; ".join(f"{k}={v}" for k, v in host_cookies.items())
339
- execution_context["__cookie_header__"] = cookie_header_value
340
- logger.info(
341
- "Injecting %d cookie(s) for step %s: %s",
342
- len(host_cookies), req_plan_step_num, list(host_cookies.keys())
343
- )
344
-
345
- # Pass execution_context (with cookies) instead of body.context_variables
346
- step_llm = get_llm_for_task("step_execution", db)
347
- req_plan, executor_token_usage = await asyncio.to_thread(
348
- prepare_step_request,
349
- ...
350
- context_variables=execution_context, # ← was: body.context_variables
351
- ...
352
- )
353
- ```
354
-
355
- The executor now sees `__cookie_header__` in its context variables and will include it
356
- as the `Cookie` header (taught in Phase 4).
357
-
358
- ---
359
-
360
- ## 8. Phase 4 — Teach the Executor About Cookies
361
-
362
- **File:** `backend/services/api_executor.py`
363
-
364
- Add an explicit rule to `STEP_PROMPT` so the AI knows how to handle cookies:
365
-
366
- ```
367
- COOKIE RULE:
368
- - If Context Variables contains the key "__cookie_header__", you MUST include it as the
369
- value of the "Cookie" request header. Do not modify or reformat it.
370
- - Example: if __cookie_header__ = "session_id=abc123; csrftoken=xyz", add:
371
- "headers": { "Cookie": "session_id=abc123; csrftoken=xyz" }
372
- - Never include a Cookie header if __cookie_header__ is absent from context.
373
- - Some APIs also require CSRF tokens in the request body or as a separate header
374
- (e.g. "X-CSRFToken"). If the spec requires this and a csrftoken cookie exists,
375
- include it in the appropriate location as well.
376
- ```
377
-
378
- This is the minimal change. The AI doesn't need to know about the cookie jar structure —
379
- it just sees a pre-built `Cookie` header string and adds it.
380
-
381
- **Why pre-build the string in execution.py instead of letting the AI build it:**
382
- The AI would need to know the cookie jar format, filter by domain, format correctly, etc.
383
- By building `__cookie_header__` in execution.py, we keep the AI's job simple — it just
384
- copies a string into a header. Less hallucination risk, more reliable.
385
-
386
- ---
387
-
388
- ## 9. Phase 5 — Frontend Cookie Visibility
389
-
390
- ### 9a — ContextPanel.jsx
391
-
392
- **File:** `frontend-react/src/components/workflow/ContextPanel.jsx`
393
-
394
- The `ContextPanel` already shows `sessionContextVars`. Add a dedicated "Cookies" section
395
- that reads `__cookie_jar__` from context and renders it cleanly, separate from regular
396
- context variables:
397
-
398
- ```jsx
399
- // Filter out internal keys from the regular context display
400
- const regularVars = Object.entries(sessionContextVars || {})
401
- .filter(([k]) => !k.startsWith('__'));
402
-
403
- // Parse cookie jar
404
- const cookieJar = sessionContextVars?.['__cookie_jar__'] || {};
405
- const allCookies = Object.entries(cookieJar).flatMap(([host, cookies]) =>
406
- Object.entries(cookies).map(([name, value]) => ({ host, name, value }))
407
- );
408
-
409
- // In render:
410
- {allCookies.length > 0 && (
411
- <div className="context-section">
412
- <div className="context-section-title">
413
- 🍪 Cookies ({allCookies.length})
414
- </div>
415
- {allCookies.map(({ host, name, value }) => (
416
- <div className="context-row" key={`${host}-${name}`}>
417
- <span className="context-key">{name}</span>
418
- <span className="context-eq">=</span>
419
- <span className="context-val">{value.slice(0, 50)}{value.length > 50 ? '…' : ''}</span>
420
- <span className="context-host">{host}</span>
421
- </div>
422
- ))}
423
- </div>
424
- )}
425
- ```
426
-
427
- ### 9b — StepCard.jsx
428
-
429
- **File:** `frontend-react/src/components/workflow/StepCard.jsx`
430
-
431
- The StepCard already shows request headers and response body. Add two small enhancements:
432
-
433
- **1. Show sent Cookie header in request section:**
434
-
435
- ```jsx
436
- {res.request.headers?.Cookie && (
437
- <>
438
- <span className="kv-label">Cookies Sent</span>
439
- <div className="kv-block" style={{ marginBottom: 8 }}>
440
- {res.request.headers.Cookie.split('; ').map(pair => {
441
- const [k, ...rest] = pair.split('=');
442
- return (
443
- <div className="kv-row" key={k}>
444
- <span className="k">{k}:</span>
445
- <span className="v">{rest.join('=')}</span>
446
- </div>
447
- );
448
- })}
449
- </div>
450
- </>
451
- )}
452
- ```
453
-
454
- **2. Show received cookies in response section:**
455
-
456
- ```jsx
457
- {res.response?.cookies && Object.keys(res.response.cookies).length > 0 && (
458
- <>
459
- <span className="kv-label">Cookies Received</span>
460
- <div className="kv-block" style={{ marginBottom: 8 }}>
461
- {Object.entries(res.response.cookies).map(([k, v]) => (
462
- <div className="kv-row" key={k}>
463
- <span className="k">{k}:</span>
464
- <span className="v">{v}</span>
465
- <span style={{ fontSize: 10, color: 'var(--fg-3)', marginLeft: 6 }}>saved</span>
466
- </div>
467
- ))}
468
- </div>
469
- </>
470
- )}
471
- ```
472
-
473
- The "saved" label confirms to the user that the cookie was persisted to the jar.
474
-
475
- ---
476
-
477
- ## 10. Edge Cases
478
-
479
- ### Multiple Set-Cookie headers
480
-
481
- HTTP allows multiple `Set-Cookie` response headers (one per cookie). `httpx` collapses
482
- these differently depending on version. The `parse_set_cookie_headers` function
483
- handles this by splitting on `\n` and parsing each line individually.
484
-
485
- ### CSRF tokens (double-submit cookie pattern)
486
-
487
- Many APIs (Django, Rails) use CSRF protection where:
488
- - `Set-Cookie: csrftoken=abc` is sent in a response
489
- - Subsequent POST/PUT/DELETE requests must send both:
490
- - `Cookie: csrftoken=abc` (in the cookie header)
491
- - `X-CSRFToken: abc` (in a custom header) or `_token: abc` (in request body)
492
-
493
- The `COOKIE RULE` in Phase 4 already handles the `Cookie` header. For the additional
494
- header/body injection, the AI executor already handles this naturally if the spec
495
- documents it — and the `__cookie_header__` context gives it the raw values to reference.
496
-
497
- ### Cookie expiry / logout
498
-
499
- Cookies are stored in the session's context_variables. When the session is cleared
500
- (existing `DELETE /session/{id}` route) or a new plan is generated (`startNewSession()`
501
- is called in WorkflowPage), the context is wiped — so all cookies are cleared. This matches
502
- Postman's behavior of resetting the cookie jar per collection run.
503
-
504
- For explicit logout detection: if a response sets a cookie with an empty value
505
- (`Set-Cookie: session_id=; Max-Age=0`), the parser will store `session_id = ""`
506
- which will send `Cookie: session_id=` — effectively a cleared cookie. This is correct behavior.
507
-
508
- ### `HttpOnly` cookies
509
-
510
- `HttpOnly` is a browser security attribute — it prevents JavaScript from reading the cookie.
511
- It has no meaning in our server-side context. We correctly ignore it and store/forward
512
- all cookies regardless of `HttpOnly` or `Secure` flags.
513
-
514
- ### Multiple domains in one test
515
-
516
- If a test calls `api.example.com` and also `auth.example.com`, cookies are stored
517
- per-hostname so they don't cross-contaminate. The `hostname_from_url(body.base_url)`
518
- lookup in Phase 3 will match cookies to the base URL's host only.
519
-
520
- ---
521
-
522
- ## 11. End-to-End Flow
523
-
524
- ### Cookie-based session auth (Django/Rails/Express)
525
-
526
- ```
527
- User uploads spec: POST /auth/login, GET /dashboard, POST /logout
528
-
529
- Step 1: POST /auth/login
530
- Request: { "username": "amit", "password": "..." }
531
- Response: 200 OK
532
- Set-Cookie: sessionid=abc123xyz; HttpOnly; Path=/
533
- Set-Cookie: csrftoken=def456; Path=/
534
- Body: { "message": "Logged in" }
535
-
536
- execution.py:
537
- → parse_set_cookie_headers(headers)
538
- → { "sessionid": "abc123xyz", "csrftoken": "def456" }
539
- → set_cookies_for_host(db, session_id, "api.example.com",
540
- { "sessionid": "abc123xyz", "csrftoken": "def456" })
541
- → resp_data["cookies"] = { "sessionid": "abc123xyz", "csrftoken": "def456" }
542
-
543
- ContextPanel shows:
544
- 🍪 Cookies (2)
545
- sessionid = abc123xyz api.example.com
546
- csrftoken = def456 api.example.com
547
-
548
- StepCard shows:
549
- Cookies Received
550
- sessionid: abc123xyz [saved]
551
- csrftoken: def456 [saved]
552
-
553
- Step 2: GET /dashboard
554
- execution.py (before executor call):
555
- → get_cookies_for_host(db, session_id, "api.example.com")
556
- → { "sessionid": "abc123xyz", "csrftoken": "def456" }
557
- → execution_context["__cookie_header__"] = "sessionid=abc123xyz; csrftoken=def456"
558
-
559
- Executor (api_executor.py):
560
- → Sees __cookie_header__ in context
561
- → COOKIE RULE: include as Cookie header
562
- → Request headers: { "Cookie": "sessionid=abc123xyz; csrftoken=def456" }
563
-
564
- Request: GET /dashboard
565
- Cookie: sessionid=abc123xyz; csrftoken=def456
566
- Response: 200 OK
567
- Body: { "name": "Amit", "dashboard": [...] }
568
-
569
- StepCard shows:
570
- Cookies Sent
571
- sessionid: abc123xyz
572
- csrftoken: def456
573
-
574
- Step 3: POST /logout
575
- → Same Cookie header forwarded
576
- → Server clears session (may respond with Set-Cookie: sessionid=; Max-Age=0)
577
- → Cookie jar updated: sessionid = ""
578
- ```
579
-
580
- ### JWT + Cookie hybrid (some APIs return JWT in a cookie)
581
-
582
- ```
583
- Step 1: POST /auth/login
584
- Response: Set-Cookie: access_token=eyJhbG...; HttpOnly
585
-
586
- Cookie jar: { "api.example.com": { "access_token": "eyJhbG..." } }
587
-
588
- Step 2: GET /protected
589
- Cookie header: access_token=eyJhbG...
590
- → API accepts cookie-based JWT ✅
591
- ```
592
-
593
- ---
594
-
595
- ## 12. File-by-File Changes
596
-
597
- | File | Change | Effort |
598
- |------|--------|--------|
599
- | `backend/services/context_manager.py` | Add `parse_set_cookie_headers`, `hostname_from_url`, `get_cookie_jar`, `set_cookies_for_host`, `get_cookies_for_host`, `clear_cookies_for_host` | 30 min |
600
- | `backend/app/api/routes/execution.py` | Phase 2: extract cookies after response. Phase 3: inject `__cookie_header__` into context before executor call | 25 min |
601
- | `backend/services/api_executor.py` | Add COOKIE RULE to `STEP_PROMPT` | 10 min |
602
- | `frontend-react/src/components/workflow/ContextPanel.jsx` | Add Cookies section, filter `__` keys from regular vars display | 20 min |
603
- | `frontend-react/src/components/workflow/StepCard.jsx` | Show "Cookies Sent" in request panel. Show "Cookies Received" in response panel | 15 min |
604
-
605
- **Total estimated effort: ~1.5 hours**
606
-
607
- No database migrations required.
608
- No new API endpoints required.
609
- No new dependencies required (uses stdlib `http.cookies`).
610
-
611
- ---
612
-
613
- ## 13. Execution Checklist
614
-
615
- ### Backend
616
-
617
- - [ ] `context_manager.py` — add `COOKIE_JAR_KEY = "__cookie_jar__"` constant
618
- - [ ] `context_manager.py` — add `parse_set_cookie_headers(headers: dict) -> dict`
619
- - [ ] `context_manager.py` — add `hostname_from_url(url: str) -> str`
620
- - [ ] `context_manager.py` — add `get_cookie_jar(db, session_id) -> dict`
621
- - [ ] `context_manager.py` — add `set_cookies_for_host(db, session_id, hostname, cookies)`
622
- - [ ] `context_manager.py` — add `get_cookies_for_host(db, session_id, hostname) -> dict`
623
- - [ ] `context_manager.py` — add `clear_cookies_for_host(db, session_id, hostname)`
624
- - [ ] `execution.py` — import new cookie helpers from `context_manager`
625
- - [ ] `execution.py` — after response: call `parse_set_cookie_headers` and `set_cookies_for_host`
626
- - [ ] `execution.py` — add `resp_data["cookies"]` with parsed cookie dict
627
- - [ ] `execution.py` — before executor: call `get_cookies_for_host` and build `__cookie_header__`
628
- - [ ] `execution.py` — pass `execution_context` (with `__cookie_header__`) to `prepare_step_request`
629
- - [ ] `api_executor.py` — add COOKIE RULE to `STEP_PROMPT`
630
-
631
- ### Frontend
632
-
633
- - [ ] `ContextPanel.jsx` — filter `__` prefixed keys from regular context vars display
634
- - [ ] `ContextPanel.jsx` — add dedicated "🍪 Cookies" section that reads `__cookie_jar__`
635
- - [ ] `ContextPanel.jsx` — show hostname alongside each cookie entry
636
- - [ ] `StepCard.jsx` — add "Cookies Sent" section in request panel (parse `Cookie` header)
637
- - [ ] `StepCard.jsx` — add "Cookies Received" section in response panel (from `resp_data.cookies`)
638
-
639
- ### Testing
640
-
641
- - [ ] Test with a Django/Rails/Express API that uses session cookies
642
- - [ ] Verify `Set-Cookie` from step 1 appears in ContextPanel under Cookies section
643
- - [ ] Verify step 2 request includes correct `Cookie` header
644
- - [ ] Verify step 2 succeeds (200) where it previously failed (401)
645
- - [ ] Test with multiple cookies set in one response
646
- - [ ] Test CSRF token forwarding (cookie + X-CSRFToken header)
647
- - [ ] Test cookie jar is cleared when a new session is started (`startNewSession`)
648
- - [ ] Test `__cookie_jar__` key is hidden from regular context vars display in ContextPanel
649
- - [ ] Test StepCard shows "saved" badge next to received cookies
650
-
651
- ---
652
-
653
- *Plan 7 | Cookie Management | Not started | Est. 1.5 hrs*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documents/PROJECT_DOCUMENTATION.md DELETED
@@ -1,769 +0,0 @@
1
- # 📘 AI API Testing Assistant — Project Documentation
2
-
3
- > A comprehensive reference document covering the architecture, components, data flow, API contracts, and design decisions of this project. Intended for comparison with similar tools and for explaining the system to others.
4
-
5
- ---
6
-
7
- ## Table of Contents
8
-
9
- 1. [Project Overview](#1-project-overview)
10
- 2. [Technology Stack](#2-technology-stack)
11
- 3. [Project Structure](#3-project-structure)
12
- 4. [System Architecture](#4-system-architecture)
13
- 5. [Backend Deep-Dive](#5-backend-deep-dive)
14
- - 5.1 [Entry Point — main.py](#51-entry-point--mainpy)
15
- - 5.2 [Database Layer — database.py](#52-database-layer--databasepy)
16
- - 5.3 [Pydantic Schemas — schemas.py](#53-pydantic-schemas--schemaspy)
17
- - 5.4 [Service Layer — services/](#54-service-layer--services)
18
- 6. [Frontend Deep-Dive](#6-frontend-deep-dive)
19
- 7. [LLM Pipeline](#7-llm-pipeline)
20
- 8. [Data Flow — End-to-End](#8-data-flow--end-to-end)
21
- 9. [API Reference (All Endpoints)](#9-api-reference-all-endpoints)
22
- 10. [Database Schema](#10-database-schema)
23
- 11. [Key Design Decisions](#11-key-design-decisions)
24
- 12. [Environment & Configuration](#12-environment--configuration)
25
- 13. [Running the Project](#13-running-the-project)
26
- 14. [Comparison Cheatsheet](#14-comparison-cheatsheet)
27
-
28
- ---
29
-
30
- ## 1. Project Overview
31
-
32
- **AI API Testing Assistant** is a full-stack web application that automates the testing of REST APIs. Instead of manually writing test scripts, the user:
33
-
34
- 1. Uploads an **OpenAPI/Swagger spec** (JSON or YAML) or a **Postman Collection**.
35
- 2. Describes a test scenario in **plain English** (e.g., *"Register a new user, log in, then create a new product"*).
36
- 3. The system uses **Mistral AI** (via LangChain) to generate a **step-by-step execution plan**.
37
- 4. Each step is individually executed as a real HTTP request, with the AI automatically resolving path parameters, injecting auth tokens from previous steps, and handling file uploads.
38
- 5. The AI then **analyzes each response**, extracts dynamic values (tokens, IDs), and chains them into subsequent steps.
39
-
40
- ### Core Value Propositions
41
-
42
- | Feature | Description |
43
- |---|---|
44
- | **Natural Language Testing** | No code required — describe what you want to test |
45
- | **Auto Context Chaining** | Tokens/IDs extracted from step N are auto-injected into step N+1 |
46
- | **Spec-Aware** | Reads OpenAPI schemas to build correctly typed requests |
47
- | **Multi-Format Input** | Supports OpenAPI 2/3 (JSON/YAML) and Postman Collections |
48
- | **Persistent History** | All sessions, plans, and results are stored in a database |
49
- | **Media Hub** | Upload files (audio, video, documents) for use in API tests |
50
-
51
- ---
52
-
53
- ## 2. Technology Stack
54
-
55
- ### Backend
56
-
57
- | Layer | Technology | Version | Purpose |
58
- |---|---|---|---|
59
- | Web Framework | **FastAPI** | ≥0.109 | REST API server |
60
- | ASGI Server | **Uvicorn** | ≥0.27 | Runs FastAPI in development |
61
- | Production Server | **Gunicorn** | 21.2 | Runs Uvicorn workers in production |
62
- | LLM Orchestration | **LangChain** | ≥0.3.0 | Prompt chaining with Mistral |
63
- | LLM Provider | **Mistral AI** | `mistral-large-latest` | Plan generation, step execution, analysis |
64
- | HTTP Client | **httpx** | ≥0.27 | Sends actual API requests during execution |
65
- | ORM | **SQLAlchemy** | ≥2.0.36 | Database queries and model definitions |
66
- | Database | **PostgreSQL** (via Supabase) | — | Persistent storage |
67
- | DB Driver | **psycopg2-binary** | 2.9.10 | PostgreSQL adapter |
68
- | Cloud Storage | **Supabase Storage** | 2.28.2 | Stores uploaded spec files and assets |
69
- | Spec Parsing | **prance** + **PyYAML** | — | Parse OpenAPI YAML/JSON |
70
- | Validation | **Pydantic** | ≥2.6 | Request/response data models |
71
- | Rate Limiting | **slowapi** | 0.1.9 | API request throttling |
72
- | Auth/Config | **python-dotenv** | 1.0.0 | Load env variables from `.env` |
73
- | Security | **cryptography** | 42.0.0 | Sensitive data handling |
74
-
75
- ### Frontend
76
-
77
- | Layer | Technology | Version | Purpose |
78
- |---|---|---|---|
79
- | UI Framework | **React** | 19.2.4 | Component-based UI |
80
- | Build Tool | **Vite** | 8.x | Fast dev server + bundler |
81
- | Styling | **Tailwind CSS** | 4.2.1 | Utility-first CSS |
82
- | Icons | **lucide-react** | 0.577 | Icon library |
83
- | HTTP Client | **Axios** | 1.x | API communication with backend |
84
- | Routing | **react-router-dom** | 7.13 | Client-side navigation |
85
-
86
- ---
87
-
88
- ## 3. Project Structure
89
-
90
- ```
91
- Testing/ ← Project root
92
- ├── .env ← Environment variables (secrets)
93
- ├── .env.example ← Template for env setup
94
- ├── requirements.txt ← Python dependencies
95
- ├── package.json ← Root-level npm scripts (dev runner)
96
- ├── Procfile ← Heroku/Railway deployment config
97
- ├── runtime.txt ← Python version pin
98
- ├── start.ps1 ← PowerShell startup script
99
- ├── openapi.yaml ← Sample OpenAPI spec for testing
100
- ├── documents/ ← Project documentation and diagrams
101
- │
102
- ├── backend/ ← FastAPI application
103
- │ ├── main.py ← Entry point & app configuration
104
- │ ├── database.py ← SQLAlchemy models + DB connection
105
- │ ├── schemas.py ← Pydantic request/response models
106
- │ ├── app/
107
- │ │ └── api/
108
- │ │ └── routes/ ← Route definitions (APIRouters)
109
- │ │ ├── specs.py ← Spec management routes
110
- │ │ ├── assets.py ← Media hub routes
111
- │ │ ├── sessions.py ← Test session routes
112
- │ │ ├── history.py ← Audit log routes
113
- │ │ ├── chat.py ← AI chat assistant routes
114
- │ │ └── execution.py ← Core LLM execution routes
115
- │ ├── core/ ← Shared utilities & config
116
- │ │ ├── config.py ← Settings management
117
- │ │ ├── errors.py │ Error handling logic
118
- │ │ └── logging.py ← Centralized logger
119
- │ ├── integrations/ ← External service clients
120
- │ │ └── llm/ ← Mistral/LangChain integration
121
- │ ├── services/ ← Business logic layer
122
- │ │ ├── swagger_parser.py ← OpenAPI/Postman parsing
123
- │ │ ├── llm_planner.py ← Execution plan generation
124
- │ │ ├── api_executor.py ← HTTP request construction
125
- │ │ ├── response_analyzer.py ← Semantic analysis
126
- │ │ ├── chat_assistant.py ← AI chat logic
127
- │ │ └── storage.py ← Local/Supabase file storage
128
- │ └── tests/ ← Automated test suite
129
- │
130
- └── frontend-react/ ← React + Vite frontend
131
- ├── index.html
132
- ├── vite.config.js
133
- ├── package.json
134
- └── src/
135
- ├── main.jsx ← React entry point
136
- ├── App.jsx ← Main layout + routing
137
- ├── App.css / index.css ← Styles and theming
138
- ├── components/ ← UI Components
139
- │ ├── AppContext.jsx ← Global state management
140
- │ ├── CollectionsPage.jsx ← Spec management
141
- │ ├── ProfilePage.jsx ← Test user profile management
142
- │ ├── HistoryPage.jsx ← Session history & audit log
143
- │ ├── MediaHubPage.jsx ← Asset management
144
- │ └── ChatAssistant.jsx ← Persistent AI chat
145
- └── services/
146
- └── api.js ← Axios service layer
147
- ```
148
-
149
- ---
150
-
151
- ## 4. System Architecture
152
-
153
- ```
154
- ┌─────────────────────────────────────────────────────────────────────┐
155
- │ BROWSER (React + Vite) │
156
- │ │
157
- │ ┌─────────┐ ┌──────────────┐ ┌──────────┐ ┌───────────────────┐ │
158
- │ │Collections│ │ Execution │ │ Media │ │ History / Profile │ │
159
- │ │ Page │ │ Workflow │ │ Hub │ │ Pages │ │
160
- │ └────┬────┘ └──────┬───────┘ └────┬─────┘ └─────────┬─────────┘ │
161
- │ │ │ │ │ │
162
- │ └──────────────┴───────────────┴────────────────────┘ │
163
- │ │ Axios HTTP │
164
- └──────────────────────────────┼─────────────────────────────────────┘
165
- ▼
166
- ┌─────────────────────────────────────────────────────────────────────┐
167
- │ FastAPI Backend (port 8001) │
168
- │ │
169
- │ POST /upload-spec ──► swagger_parser / postman_parser │
170
- │ POST /plan ──► llm_planner ──► Mistral AI │
171
- ��� POST /execute-step ──► api_executor ──► Mistral AI ──► httpx ──► │
172
- │ Target API │
173
- │ POST /analyze-response ──► response_analyzer ──► Mistral AI │
174
- │ GET/POST /assets ──► asset_service ──► storage.py │
175
- │ GET /history ──► SQLAlchemy ORM │
176
- │ │
177
- └───────────────────────────┬─────────────────────────────────────────┘
178
- │ SQLAlchemy
179
- ┌──────────────────┴────────────────────┐
180
- ▼ ▼
181
- ┌────────────────┐ ┌────────────────────┐
182
- │ PostgreSQL DB │ │ Supabase Storage │
183
- │ (via Supabase)│ │ (spec files, │
184
- │ │ │ asset uploads) │
185
- │ - sessions │ └────────────────────┘
186
- │ - spec_docs │
187
- │ - history │
188
- │ - assets │
189
- │ - collections │
190
- └────────────────┘
191
- ```
192
-
193
- ---
194
-
195
- ## 5. Backend Deep-Dive
196
-
197
- ### 5.1 Entry Point — `main.py`
198
-
199
- `main.py` is the entry point for the FastAPI application. It initializes the app, ensures directory structures, and mounts the various module routers.
200
-
201
- **Key responsibilities:**
202
- - **Rate Limiting**: Uses `slowapi` to protect endpoints (default 200/min).
203
- - **Global Error Handling**: Custom handlers for `AppError` and `RequestValidationError`.
204
- - **CORS Configuration**: Loaded from `settings`.
205
- - **Static Files**: Serves the `/uploads` directory.
206
- - **Router Orchestration**: Includes routers from `backend.app.api.routes`.
207
-
208
- **Modules (Routers):**
209
- - `specs`: Spec upload, retrieval, and credential management.
210
- - `assets`: Media Hub file operations.
211
- - `sessions`: Test session lifecycle.
212
- - `history`: Audit log access.
213
- - `chat`: Persistent AI chat interactions.
214
- - `execution`: Core LLM pipeline (`/plan`, `/execute-step`, `/analyze-response`).
215
-
216
- ---
217
-
218
- ### 5.2 Database Layer — `database.py`
219
-
220
- Uses **SQLAlchemy 2.0** with a declarative base. Database URL is loaded from the `DATABASE_URL` environment variable (Supabase PostgreSQL).
221
-
222
- #### Models
223
-
224
- | Model | Table | Description |
225
- |---|---|---|
226
- | `SpecDocument` | `spec_documents` | Stores uploaded API spec (raw text, parsed JSON, base URL, credentials, execution plan) |
227
- | `SessionModel` | `sessions` | Represents one test run. Stores which spec, scenario, base URL, and extracted context variables |
228
- | `ExecutionHistory` | `execution_history` | One row per step executed. Stores request JSON, response JSON, and AI analysis |
229
- | `Asset` | `assets` | Uploaded files (audio/video/docs). Tagged, categorized, linked to a spec |
230
- | `Collection` | `collections` | Named groups of assets. Many-to-many with Asset |
231
- | `ChatSession` | `chat_sessions` | A persistent AI chat thread. Linked to a spec and optionally to a test session. Auto-named from first message. |
232
- | `ChatMessage` | `chat_messages` | A single message within a chat session — stores role, content, and the structured `action_json` returned by the AI |
233
-
234
- #### Relationships
235
-
236
- ```
237
- SpecDocument ──< Asset (one-to-many)
238
- Asset >──< Collection (many-to-many via asset_collections junction table)
239
- SessionModel ──> SpecDocument (foreign key, nullable)
240
- ExecutionHistory ──> SessionModel (foreign key via session_id)
241
- ChatSession ──> SpecDocument (foreign key, ON DELETE SET NULL, nullable)
242
- ChatMessage ──> ChatSession (foreign key, ON DELETE CASCADE)
243
- ```
244
-
245
- #### Connection Details
246
-
247
- ```python
248
- engine = create_engine(
249
- DATABASE_URL,
250
- pool_pre_ping=True, # Checks connection health before use
251
- pool_recycle=300 # Recycles connections every 5 minutes
252
- )
253
- ```
254
-
255
- ---
256
-
257
- ### 5.3 Pydantic Schemas — `schemas.py`
258
-
259
- All request/response validation is done via Pydantic v2 models:
260
-
261
- | Schema | Direction | Purpose |
262
- |---|---|---|
263
- | `PlanRequest` | → Backend | Payload for `/plan` — spec content, base URL, scenario, credentials |
264
- | `ExecutionPlan` | ← Backend | Response from `/plan` — list of steps + suggested credentials |
265
- | `StepDefinition` | — | Single step: step number, endpoint string, purpose text |
266
- | `ExecuteStepRequest` | → Backend | Payload for `/execute-step` — session ID, step def, context vars |
267
- | `AnalyzeRequest` | → Backend | Payload for `/analyze-response` — step number, response data, optional `spec_id` and `step_definition` |
268
- | `AnalyzeResponse` | ← Backend | AI analysis result — `status`, `is_otp_required`, `otp_field_name`, `is_selection_required`, `selection_field_name`, `selection_options`, `response_summary`, `extracted_variables`, `token_usage` |
269
- | `SelectionOption` | — | A single choosable item when `is_selection_required=true` — `label` (display text) and `value` (ID to save) |
270
- | `ContextUpdate` | → Backend | Payload for `POST /context/{session_id}` — `key` and `value` to merge into session context |
271
- | `CredentialUpdate` | → Backend | Payload for credential save — `name`, `username`, `password`, `extra` dict. Passing `extra._clear=true` **wipes all stored credentials** for the spec. |
272
- | `ChatRequest` | → Backend | Payload for `/chat` — message text, optional `chat_session_id`, spec context, execution plan, step results |
273
- | `ChatResponse` | ← Backend | Structured AI response — `chat_session_id`, `chat_session_name`, `action`, `message`, optional `step`, `changes`, `assertions`, `explanation` |
274
- | `ChatSessionSummary` | ← Backend | Summary of a chat session — id, name, spec_id, session_id, message count, timestamps |
275
- | `ChatMessageSchema` | ← Backend | A single chat message — role, content, action_json, timestamp |
276
- | `TokenUsage` | ← Backend | LLM token counts (prompt, completion, total) |
277
-
278
- ---
279
-
280
- ### 5.4 Service Layer — `services/`
281
-
282
- #### `swagger_parser.py`
283
- - Accepts raw spec string (JSON or YAML)
284
- - Parses with `json.loads` → falls back to `yaml.safe_load`
285
- - **Does NOT resolve `$ref` at parse time** (deferred to execution to handle large specs like the GitHub API)
286
- - Returns two views of the spec:
287
- - `endpoints`: Simplified list `[{path, method, summary}]` — sent to the planner LLM
288
- - `paths` + `components`: Full raw spec — stored in DB, used by executor for on-the-fly `$ref` resolution
289
-
290
- #### `postman_parser.py`
291
- - Detects Postman collections by checking for `info.schema` URL or `info + item` keys
292
- - Converts Postman's nested item/folder structure to a flat OpenAPI-like format
293
-
294
- #### `llm_planner.py`
295
- - Uses `ChatMistralAI` (via LangChain) with `mistral-large-latest`, `temperature=0`
296
- - Takes: simplified endpoint list, base URL, user scenario, existing credentials
297
- - Returns: `ExecutionPlan` with a list of `StepDefinition` objects
298
- - **Smart credential handling**: If credentials exist → skip registration steps. If empty → AI suggests realistic credentials.
299
-
300
- #### `api_executor.py`
301
- - Uses `ChatMistralAI` with a detailed prompt about the specific endpoint schema
302
- - Returns `StepExecutionPlan` containing the complete HTTP request object (`method`, `url`, `headers`, `query_params`, `form_data`, `body`, `files`)
303
- - **Token-efficient schema notation** (shorthand): Instead of sending verbose JSON schema, converts it to compact strings like `{name*(str),age(int),status(str[active|inactive])}`
304
- - **Data source priority**: Context Variables → User Credentials → Step Definition
305
- - **Asset Integration**: Consults `asset_service` to provide the LLM with a list of available files from the Media Hub.
306
-
307
- #### `response_analyzer.py`
308
- - Uses `ChatMistralAI` to analyze HTTP response (status code + body)
309
- - Extracts: step status (success/failure), dynamic variables (tokens, IDs), OTP requirement flag
310
- - **Interactive Selection Detection**: If the response body contains a list of items the user must choose between (e.g., buses, seats, products), the analyzer sets `is_selection_required=true` and returns a structured `selection_options` list with `label`/`value` pairs for the UI to render as a chooser modal. The selected item is then saved to the session context.
311
- - Response body is **truncated to 1KB** (500 chars from start + 500 from end) to save LLM tokens
312
-
313
- #### `chat_assistant.py`
314
- - Powers the AI Chat Assistant feature using `ChatMistralAI` with `temperature=0.2`
315
- - Builds a rich context block from: active spec name, execution plan, session context variables, last step result, and all step results
316
- - Loads the last 20 messages from the chat session as conversation history
317
- - Returns a **structured JSON action** with one of: `execute_step`, `run_all`, `skip_step`, `retry_step`, `modify_request`, `explain`, `generate_tests`, or `reply`
318
- - Falls back to a `reply` action if LLM output cannot be parsed
319
-
320
- #### `context_manager.py`
321
- - Simple read/write for `SessionModel.context_variables` (JSON column)
322
- - `get_context(db, session_id)` → returns current variables dict
323
- - `set_context_variables(db, session_id, new_vars)` → merges new vars into session
324
-
325
- #### `asset_service.py`
326
- - `upload_asset()`: Saves file to storage + creates `Asset` record
327
- - `get_assets()`: Filterable by `spec_id` and `category`
328
- - `delete_asset()`: Removes from storage + DB
329
- - `create_collection()`, `add_to_collection()`, `delete_collection()`: Collection management
330
- - `get_ai_context()`: Returns a structured dict of assets grouped by collection — used to give the LLM awareness of available test files
331
-
332
- #### `storage.py`
333
- - Abstraction layer for file storage with two implementations:
334
- - **`SupabaseStorageProvider`**: Uses Supabase Storage bucket for production
335
- - **`LocalStorageProvider`**: Saves files to `backend/uploads/` for local dev
336
- - Auto-detects which to use based on `SUPABASE_URL` env variable
337
-
338
- ---
339
-
340
- ## 6. Frontend Deep-Dive
341
-
342
- The frontend is a **single-page application** built with React 19 + Vite. Navigation is icon-based (VS Code-like activity bar), with each icon switching the main content area without a full page reload.
343
-
344
- ### State Management — `AppContext.jsx`
345
-
346
- A single React Context (`AppProvider`) manages all global state:
347
-
348
- | State | Description |
349
- |---|---|
350
- | `collections` | List of uploaded specs fetched from backend |
351
- | `activeSpecId` | Currently selected spec UUID |
352
- | `activeSpecName` | Display name of active spec |
353
- | `activeBaseUrl` | The base URL being tested |
354
- | `parsedSpec` | Full parsed spec JSON for active spec |
355
- | `storedCredentials` | Auth credentials for the active test user |
356
- | `sessionId` | Current test session UUID |
357
- | `sessionContextVars` | Dynamic variables extracted from previous steps |
358
- | `executionPlan` | The list of steps from the LLM planner |
359
- | `scenario` | The current natural-language scenario text |
360
-
361
- ### Pages / Components
362
-
363
- | Component | Route (in `activePage` state) | Purpose |
364
- |---|---|---|
365
- | `CollectionsPage` | `collections` | Upload new specs, list and select specs, delete specs |
366
- | Testing Workflow | `testing` (default) | Main page — scenario input, execution plan display, step execution, OTP/Selection modals |
367
- | `ProfilePage` | `profile` | Set/update test user credentials (username, password, extra fields) |
368
- | `HistoryPage` | `history` | Browse all past sessions and step results |
369
- | `MediaHubPage` | `media` | Upload and organize test assets (files for multipart APIs) |
370
- | `ChatAssistant` | `chat` | Full-page AI assistant with persistent chat sessions and action execution |
371
- | `SettingsPage` | `settings` | App configuration |
372
-
373
- ### Right Sidebar — Testing Workflow Panel
374
-
375
- The right sidebar (toggleable) on the Testing Workflow page has two tabs:
376
-
377
- | Tab | Purpose |
378
- |---|---|
379
- | **Context** | Shows live session-extracted variables and test credentials |
380
- | **AI Chat** | Embedded compact version of `ChatAssistant` with full execution context — can trigger executions without leaving the testing page |
381
-
382
- ### API Service Layer — `services/api.js`
383
-
384
- All backend calls are centralized in a single file, organized into service classes:
385
-
386
- | Service | Methods |
387
- |---|---|
388
- | `SpecService` | `upload()`, `list()`, `get()`, `updateBaseUrl()`, `delete()` |
389
- | `SessionService` | `create()`, `delete()` |
390
- | `PlanService` | `generatePlan()`, `executeStep()`, `analyzeResponse()` |
391
- | `CredentialService` | `get()`, `save()` |
392
- | `AssetService` | `upload()`, `list()`, `delete()`, `createCollection()`, etc. |
393
-
394
- ---
395
-
396
- ## 7. LLM Pipeline
397
-
398
- The system uses **three distinct LLM calls** per test step:
399
-
400
- ```
401
- User Scenario
402
- │
403
- ▼ [LLM Call 1]
404
- ┌─────────────────────┐
405
- │ llm_planner.py │ Prompt: Full endpoint list + scenario
406
- │ "Planner" │ Output: Ordered list of steps [{step, endpoint, purpose}]
407
- └──────────┬──────────┘
408
- │
409
- │ For each step:
410
- ▼ [LLM Call 2]
411
- ┌─────────────────────┐
412
- │ api_executor.py │ Prompt: Specific endpoint schema (shorthand) +
413
- │ "Executor" │ context vars + credentials + assets
414
- │ │ Output: Complete HTTP request object
415
- └──────────┬──────────┘
416
- │
417
- │ (httpx sends the actual HTTP request)
418
- │
419
- ▼ [LLM Call 3]
420
- ┌─────────────────────┐
421
- │ response_analyzer │ Prompt: Status code + response body
422
- │ "Analyzer" │ Output: {status, extracted_variables, is_otp_required}
423
- └─────────────────────┘
424
- │
425
- ▼
426
- Context Variables updated → injected into next step's Executor call
427
- ```
428
-
429
- ### Token Optimization Strategies
430
-
431
- - **Shorthand schema notation**: `{name*(str),age(int)}` instead of full JSON Schema
432
- - **Response truncation**: Max 1KB sent to analyzer
433
- - **Pruning**: Removes `description`, `summary`, `example`, `format` keys from specs
434
- - **Lazy `$ref` resolution**: Only the matching endpoint is resolved, not the whole spec
435
- - **Response pruning**: `responses` object from spec is stripped before sending to LLM (only needed for building the request, not analyzing it)
436
-
437
- ---
438
-
439
- ## 8. Data Flow — End-to-End
440
-
441
- ### Step 1: Upload a Spec
442
-
443
- ```
444
- User selects file
445
- → POST /upload-spec (multipart)
446
- → swagger_parser.py or postman_parser.py
447
- → Save raw + parsed JSON to spec_documents table
448
- → Save raw file to Supabase/local storage
449
- → Return spec_id + parsed_spec to frontend
450
- ```
451
-
452
- ### Step 2: Generate Execution Plan
453
-
454
- ```
455
- User types scenario → clicks "Generate Plan"
456
- → startNewSession() → POST /session → returns session_id
457
- → POST /plan {spec_content, base_url, scenario, user_credentials, spec_id, session_id}
458
- → llm_planner.generate_execution_plan()
459
- → Save plan + scenario to spec_documents.execution_plan
460
- → AI-suggested credentials merged into spec_documents.login_credentials
461
- → Return [{step, endpoint, purpose}, ...] to frontend
462
- ```
463
-
464
- ### Step 3: Execute a Step
465
-
466
- ```
467
- User clicks "Execute" on a step
468
- → refreshSessionContext() → GET /context/{session_id}
469
- → POST /execute-step {session_id, step_definition, context_variables, credentials, base_url, spec_id}
470
- → Find matching path in spec, resolve $refs, prune, convert to shorthand
471
- → api_executor.prepare_step_request() → LLM returns complete HTTP request
472
- → URL sanitization (fix placeholders, relative paths)
473
- → httpx sends real HTTP request to target API
474
- → Save to execution_history table
475
- → Return {executed_request, response, token_usage}
476
- ```
477
-
478
- ### Step 4: Analyze Response
479
-
480
- ```
481
- (Automatically called after execute)
482
- → POST /analyze-response {session_id, step, response_data, step_definition}
483
- → response_analyzer.analyze_api_response() → LLM returns analysis
484
- → Extracted variables saved to sessions.context_variables via context_manager
485
- → History record updated with analysis
486
- → Return {status, response_summary, extracted_variables, is_otp_required}
487
- ```
488
-
489
- ---
490
-
491
- ## 9. API Reference (All Endpoints)
492
-
493
- ### Core
494
-
495
- | Method | Path | Description |
496
- |---|---|---|
497
- | `GET` | `/` | Health check |
498
- | `POST` | `/session` | Create a new test session |
499
- | `DELETE` | `/session/{session_id}` | Clear session and its history |
500
-
501
- ### Spec Management
502
-
503
- | Method | Path | Description |
504
- |---|---|---|
505
- | `POST` | `/upload-spec` | Upload OpenAPI/Postman spec file |
506
- | `GET` | `/specs` | List all uploaded specs |
507
- | `GET` | `/specs/{spec_id}` | Get a specific spec with plan + credentials |
508
- | `PATCH` | `/specs/{spec_id}` | Update spec's base_url |
509
- | `DELETE` | `/specs/{spec_id}` | Delete spec and all its assets |
510
- | `GET` | `/specs/{spec_id}/credentials` | Get stored test credentials for spec |
511
- | `POST` | `/specs/{spec_id}/credentials` | Save/update test credentials |
512
-
513
- ### Execution
514
-
515
- | Method | Path | Description |
516
- |---|---|---|
517
- | `POST` | `/plan` | Generate LLM execution plan from scenario |
518
- | `POST` | `/execute-step` | Execute one step (calls LLM + httpx) |
519
- | `POST` | `/analyze-response` | Analyze step response and extract variables |
520
- | `GET` | `/context/{session_id}` | Get current session context variables |
521
- | `POST` | `/context/{session_id}` | Manually update a specific key in the session context (used by selection modal) |
522
-
523
- ### Chat Assistant
524
-
525
- | Method | Path | Description |
526
- |---|---|---|
527
- | `POST` | `/chat` | Send a message; returns structured AI action + saves the conversation to DB |
528
- | `GET` | `/chat-sessions` | List all chat sessions, optionally filtered by `spec_id` |
529
- | `GET` | `/chat-sessions/{chat_session_id}` | Get a single chat session with its full message history |
530
- | `PATCH` | `/chat-sessions/{chat_session_id}` | Rename a chat session |
531
- | `DELETE` | `/chat-sessions/{chat_session_id}` | Delete a chat session and all its messages (cascade) |
532
- | `DELETE` | `/chat-sessions` | Wipe **all** chat sessions and messages |
533
-
534
- ### History
535
-
536
- | Method | Path | Description |
537
- |---|---|---|
538
- | `GET` | `/history` | Get all execution history (all sessions) |
539
- | `DELETE` | `/history/{session_id}` | Delete one session's history |
540
- | `DELETE` | `/history` | Wipe all history |
541
-
542
- ### Assets & Collections
543
-
544
- | Method | Path | Description |
545
- |---|---|---|
546
- | `POST` | `/assets` | Upload a test asset file |
547
- | `GET` | `/assets` | List assets (filter by spec_id, category) |
548
- | `DELETE` | `/assets/{asset_id}` | Delete an asset |
549
- | `GET` | `/collections` | List collections |
550
- | `POST` | `/collections` | Create a new collection |
551
- | `POST` | `/collections/{collection_id}/assets/{asset_id}` | Add asset to collection |
552
- | `DELETE` | `/collections/{collection_id}` | Delete a collection |
553
-
554
- ---
555
-
556
- ## 10. Database Schema
557
-
558
- ```sql
559
- -- API spec documents
560
- CREATE TABLE spec_documents (
561
- id VARCHAR PRIMARY KEY, -- UUID
562
- name VARCHAR NOT NULL, -- filename
563
- raw_content TEXT NOT NULL, -- original spec text
564
- parsed_json JSON NOT NULL, -- parsed + simplified spec
565
- base_url VARCHAR, -- target server URL
566
- login_credentials JSON, -- {username, password, token, ...}
567
- execution_plan JSON, -- last generated plan steps
568
- scenario TEXT, -- last scenario text
569
- file_path VARCHAR, -- path in storage
570
- uploaded_at TIMESTAMP DEFAULT NOW()
571
- );
572
-
573
- -- Test sessions
574
- CREATE TABLE sessions (
575
- id VARCHAR PRIMARY KEY, -- UUID
576
- spec_id VARCHAR REFERENCES spec_documents(id),
577
- spec_name VARCHAR,
578
- base_url VARCHAR,
579
- scenario TEXT,
580
- context_variables JSON DEFAULT '{}', -- live extracted vars
581
- created_at TIMESTAMP DEFAULT NOW()
582
- );
583
-
584
- -- Step execution records
585
- CREATE TABLE execution_history (
586
- id SERIAL PRIMARY KEY,
587
- session_id VARCHAR, -- link to sessions
588
- step INTEGER,
589
- request_json JSON, -- full HTTP request object
590
- response_json JSON, -- status_code, body, headers
591
- analysis_json JSON, -- AI analysis result
592
- step_definition_json JSON, -- step metadata snapshot
593
- timestamp TIMESTAMP DEFAULT NOW()
594
- );
595
-
596
- -- Test assets (files)
597
- CREATE TABLE assets (
598
- id VARCHAR PRIMARY KEY, -- UUID
599
- name VARCHAR NOT NULL,
600
- file_type VARCHAR NOT NULL, -- MIME type
601
- file_path VARCHAR NOT NULL, -- storage path
602
- file_size INTEGER,
603
- category VARCHAR DEFAULT 'documents', -- audio/video/documents/images
604
- description TEXT,
605
- tags JSON DEFAULT '[]',
606
- metadata_json JSON DEFAULT '{}',
607
- spec_id VARCHAR REFERENCES spec_documents(id),
608
- uploaded_at TIMESTAMP DEFAULT NOW()
609
- );
610
-
611
- -- Asset groupings
612
- CREATE TABLE collections (
613
- id VARCHAR PRIMARY KEY,
614
- name VARCHAR NOT NULL,
615
- description TEXT,
616
- spec_id VARCHAR REFERENCES spec_documents(id),
617
- created_at TIMESTAMP DEFAULT NOW()
618
- );
619
-
620
- -- Junction for assets ↔ collections
621
- CREATE TABLE asset_collections (
622
- asset_id VARCHAR REFERENCES assets(id),
623
- collection_id VARCHAR REFERENCES collections(id),
624
- PRIMARY KEY (asset_id, collection_id)
625
- );
626
-
627
- -- AI Chat sessions (each represents one conversation thread)
628
- CREATE TABLE chat_sessions (
629
- id VARCHAR PRIMARY KEY, -- UUID
630
- name VARCHAR NOT NULL, -- auto-named from first message; user-renameable
631
- spec_id VARCHAR REFERENCES spec_documents(id) ON DELETE SET NULL,
632
- session_id VARCHAR, -- linked API test session (nullable)
633
- created_at TIMESTAMP DEFAULT NOW(),
634
- updated_at TIMESTAMP DEFAULT NOW()
635
- );
636
-
637
- -- Individual messages within a chat session
638
- CREATE TABLE chat_messages (
639
- id SERIAL PRIMARY KEY,
640
- chat_session_id VARCHAR REFERENCES chat_sessions(id) ON DELETE CASCADE NOT NULL,
641
- role VARCHAR NOT NULL, -- 'user' | 'assistant'
642
- content TEXT NOT NULL, -- raw message text
643
- action_json JSON, -- structured action returned by AI (execute_step, explain, etc.)
644
- timestamp TIMESTAMP DEFAULT NOW()
645
- );
646
- ```
647
-
648
- ---
649
-
650
- ## 11. Key Design Decisions
651
-
652
- ### 1. Single `main.py` vs. APIRouter
653
- All routes are in one file. This keeps it simple for a project of this scope but would need refactoring for a larger team.
654
-
655
- ### 2. Deferred `$ref` Resolution
656
- OpenAPI specs (like the GitHub API with 1000+ endpoints) are too large to fully resolve at upload time. Instead, `$ref`s are resolved **on-demand** only for the specific endpoint being executed. This keeps parsing fast and storage lean.
657
-
658
- ### 3. Shorthand Schema Notation
659
- Before sending an endpoint schema to the LLM, it's converted to a compact shorthand format. `{name*(str), age(int:int32), status(str[active|inactive])}` is far smaller than the equivalent JSON Schema, saving significant tokens at scale.
660
-
661
- ### 4. Session-Scoped Context vs. Spec-Scoped Credentials
662
- - **Credentials** (username, password, tokens) are **persisted to the spec** in the DB, so they survive page refreshes.
663
- - **Dynamic variables** (IDs, tokens extracted during a run) are stored in the **session** only. They reset when you start a new session/plan.
664
-
665
- ### 5. Storage Abstraction
666
- `storage.py` provides a unified interface (`save`, `delete`, `get_full_path`) with two implementations:
667
- - `SupabaseStorageProvider`: used when `SUPABASE_URL` is set.
668
- - `LocalStorageProvider`: fallback for offline/local development.
669
-
670
- ### 6. AI Credential Merging
671
- When the Planner LLM suggests test credentials (e.g., for a new user registration step), they are automatically merged into the spec's stored credentials in the database. This prevents the AI from creating duplicate users on subsequent test runs.
672
-
673
- ### 7. OTP/2FA Handling
674
- The Analyzer LLM detects when a response requires an OTP. The UI shows a modal prompting the user to enter the code, which is then saved as a context variable and used in the next step automatically.
675
-
676
- ### 8. Interactive Selection for List Responses
677
- When an API step returns a list of items (e.g., a list of available buses, products, or flight seats), the Response Analyzer detects this pattern and returns `is_selection_required=true` with structured `selection_options`. The frontend renders a **Selection Required** modal where the user clicks their choice. The selected value is then written to the session context via `POST /context/{session_id}` and becomes available to all subsequent steps without re-execution.
678
-
679
- ### 9. AI Chat Assistant — Persistent, Context-Aware
680
- The `ChatAssistant` maintains conversation history in the database (`ChatSession` + `ChatMessage` tables). On each request, the AI receives the last 20 messages as conversation context plus the full current testing state. This prevents stateless, forgetful AI interactions. The AI responds with structured JSON, enabling the frontend to trigger real actions (step execution, request modifications) rather than just displaying text.
681
-
682
- ---
683
-
684
- ## 12. Environment & Configuration
685
-
686
- ### `.env` Variables
687
-
688
- | Variable | Required | Description |
689
- |---|---|---|
690
- | `DATABASE_URL` | ✅ | PostgreSQL connection string (e.g., `postgresql://user:pass@host/db`) |
691
- | `MISTRAL_API_KEY` | ✅ | API key for Mistral AI (used by LangChain) |
692
- | `SUPABASE_URL` | ⬜ | Supabase project URL (enables cloud storage; falls back to local if missing) |
693
- | `SUPABASE_SERVICE_ROLE_KEY` | ⬜ | **Preferred** Supabase key — bypasses Row-Level Security for storage operations |
694
- | `SUPABASE_SECRET_KEY` | ⬜ | Alternative Supabase key name (checked if `SUPABASE_SERVICE_ROLE_KEY` is absent) |
695
- | `SUPABASE_KEY` | ⬜ | Fallback Supabase key (used only if the two above are not set) |
696
- | `SUPABASE_STORAGE_BUCKET` | ⬜ | Name of the Supabase Storage bucket (defaults to `"assets"` if not set) |
697
-
698
- > **Note:** The `DATABASE_URL` string starting with `postgres://` is auto-converted to `postgresql://` for SQLAlchemy compatibility.
699
-
700
- ---
701
-
702
- ## 13. Running the Project
703
-
704
- ### Prerequisites
705
- - Python 3.9+
706
- - Node.js 18+
707
- - A Mistral AI API key
708
- - A PostgreSQL database (local or Supabase)
709
-
710
- ### First-Time Setup
711
-
712
- ```bash
713
- # 1. Install all dependencies (Python + Node)
714
- npm run setup
715
-
716
- # 2. Copy and fill in the environment file
717
- cp .env.example .env
718
- # Edit .env and add your MISTRAL_API_KEY and DATABASE_URL
719
- ```
720
-
721
- ### Development
722
-
723
- ```bash
724
- # Option A: Both frontend and backend in one terminal (recommended)
725
- npm run dev
726
-
727
- # Option B: PowerShell, opens separate windows
728
- .\start.ps1
729
-
730
- # Option C: Manual
731
- python -m uvicorn backend.main:app --reload --port 8001
732
- cd frontend-react && npm run dev
733
- ```
734
-
735
- ### Service URLs
736
-
737
- | Service | URL |
738
- |---|---|
739
- | Frontend (React) | http://localhost:5173 |
740
- | Backend API | http://localhost:8001 |
741
- | Swagger API Docs | http://localhost:8001/docs |
742
- | ReDoc API Docs | http://localhost:8001/redoc |
743
-
744
- ---
745
-
746
- ## 14. Comparison Cheatsheet
747
-
748
- Use this table when explaining or comparing this project to similar tools:
749
-
750
- | Feature | This Project | Postman | Rest-assured | Swagger UI | Insomnia |
751
- |---|---|---|---|---|---|
752
- | **Input Format** | OpenAPI / Postman | Postman | Code | OpenAPI | REST/GraphQL |
753
- | **Test Creation** | Natural language | Manual | Java/Groovy code | Manual | Manual |
754
- | **Code Required** | ❌ Zero | ✅ Script | ✅ Full | ❌ No | ❌ No |
755
- | **AI Test Planning** | ✅ Mistral LLM | ❌ | ❌ | ❌ | ❌ |
756
- | **AI Chat Assistant** | ✅ Persistent + context-aware | ⬜ Basic (Postman AI) | ❌ | ❌ | ❌ |
757
- | **Auto Context Chaining** | ✅ AI-driven | ⬜ Manual env vars | ⬜ Manual | ❌ | ⬜ Manual |
758
- | **Response Analysis** | ✅ AI-driven | ✅ Manual assertions | ✅ Assertions | ❌ | ✅ Manual |
759
- | **Interactive Selection** | ✅ AI-detected + UI chooser | ❌ | ❌ | ❌ | ❌ |
760
- | **Persistent History** | ✅ DB-backed | ✅ | ❌ | ❌ | ✅ |
761
- | **File Upload Testing** | ✅ Media Hub | ✅ | ✅ | ❌ | ✅ |
762
- | **Multi-step Automation** | ✅ AI plans full flow | ⬜ Collection runner | ✅ Test suites | ❌ | ❌ |
763
- | **OTP/2FA Support** | ✅ UI prompt | ❌ | ❌ | ❌ | ❌ |
764
- | **Self-hosted** | ✅ | Partially | ✅ | ✅ | Partially |
765
-
766
- ---
767
-
768
- *Documentation updated: April 2026 — reflects actual codebase state as of this date*
769
- *Project: AI API Testing Assistant | Stack: FastAPI + React + Mistral AI + PostgreSQL*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documents/Project_Diagrams.md DELETED
@@ -1,578 +0,0 @@
1
- # AI API Testing Assistant — Project Diagrams Guide
2
-
3
- This document contains ready-to-use **Mermaid diagram code** for all major diagram types relevant to this project. Paste any code block into a Mermaid-compatible renderer (VS Code Preview, draw.io, Mermaid Live Editor at https://mermaid.live, Notion, or GitHub Markdown).
4
-
5
- ---
6
-
7
- ## 1. System Architecture Diagram
8
- *Shows the high-level structure of the entire system and how the four tiers interact.*
9
-
10
- ```mermaid
11
- graph TD
12
- subgraph "Frontend (React + Vite)"
13
- UI[User Interface]
14
- State[AppContext / State]
15
- Axios[Axios API Client]
16
- UI --> State
17
- State --> Axios
18
- end
19
-
20
- subgraph "Orchestration (FastAPI)"
21
- Router[main.py / APIRouters]
22
- Core[Core Utilities / Config]
23
- Services[Business Logic / Services]
24
- Router --> Core
25
- Router --> Services
26
- end
27
-
28
- subgraph "Intelligence (LLM Services)"
29
- Planner[LLM Planner]
30
- Executor[API Executor]
31
- Analyzer[Response Analyzer]
32
- Chat[Chat Assistant]
33
- Integrations[Integrations / LLM]
34
- Services --> Planner
35
- Services --> Executor
36
- Services --> Analyzer
37
- Services --> Chat
38
- Planner & Executor & Analyzer & Chat --> Integrations
39
- end
40
-
41
- subgraph "Data & Storage"
42
- DB[(PostgreSQL / SQLAlchemy)]
43
- Storage[Supabase / Local Storage]
44
- Services --> DB
45
- Services --> Storage
46
- end
47
-
48
- Axios <--> Router
49
- Integrations <--> LLM_Provider[Mistral-Large API]
50
- ```
51
-
52
- ---
53
-
54
- ## 2. Sequence Diagram — Full Test Session Flow
55
- *Shows the step-by-step interaction between the user, backend, LLMs, and database during a complete test run.*
56
-
57
- ```mermaid
58
- sequenceDiagram
59
- participant User
60
- participant Frontend
61
- participant FastAPI as router/execution.py
62
- participant DB as database.py
63
- participant LLM as integrations/llm
64
- participant TargetAPI
65
-
66
- User->>Frontend: Clicks "Execute Step"
67
- Frontend->>FastAPI: POST /execute-step (StepDef)
68
-
69
- rect rgb(240, 240, 240)
70
- Note over FastAPI: PRE-EXECUTION PIPELINE
71
- FastAPI->>DB: Fetch Spec (parsed_json)
72
- FastAPI->>FastAPI: resolve_refs() + prune + shorthand
73
- FastAPI->>DB: Fetch session context + profile
74
- FastAPI->>LLM: prepare_step_request(schema, context)
75
- LLM-->>FastAPI: {APIRequest}
76
- FastAPI->>FastAPI: sanitize_url(url)
77
- end
78
-
79
- rect rgb(220, 240, 220)
80
- Note over FastAPI: HTTP EXECUTION
81
- FastAPI->>TargetAPI: httpx.send(request)
82
- TargetAPI-->>FastAPI: {status, body, headers}
83
- end
84
-
85
- FastAPI->>DB: Save to ExecutionHistory
86
- FastAPI-->>Frontend: {request, response}
87
- Frontend->>User: Display Result (Cards)
88
-
89
- Frontend->>FastAPI: POST /analyze-response {step, response}
90
- FastAPI->>LLM: analyze_api_response(status, body, purpose)
91
- LLM-->>FastAPI: {status, extracted_variables, is_otp_required}
92
- FastAPI->>DB: UPDATE context_variables (merge new vars)
93
- FastAPI->>DB: UPDATE ExecutionHistory (analysis)
94
- FastAPI-->>Frontend: {analysis_result}
95
- Frontend-->>User: Show result + extracted variables
96
- ```
97
-
98
- ---
99
-
100
- ## 3. Entity-Relationship (ER) Diagram
101
- *Defines the database schema and relationships between all entities.*
102
-
103
- ```mermaid
104
- erDiagram
105
- SPEC_DOCUMENT ||--o{ SESSION_MODEL : "has"
106
- SPEC_DOCUMENT ||--o{ ASSET : "linked to"
107
- SESSION_MODEL ||--o{ EXECUTION_HISTORY : "logs"
108
- CHAT_SESSION ||--o{ CHAT_MESSAGE : "contains"
109
- SPEC_DOCUMENT ||--o{ CHAT_SESSION : "associated with"
110
-
111
- SPEC_DOCUMENT {
112
- uuid id PK
113
- string name
114
- text raw_content
115
- json parsed_json
116
- string base_url
117
- json login_credentials
118
- json execution_plan
119
- text scenario
120
- }
121
-
122
- SESSION_MODEL {
123
- uuid id PK
124
- uuid spec_id FK
125
- json context_variables
126
- string base_url
127
- }
128
-
129
- EXECUTION_HISTORY {
130
- int id PK
131
- uuid session_id FK
132
- int step
133
- json request_json
134
- json response_json
135
- json analysis_json
136
- json step_definition_json
137
- }
138
-
139
- ASSET {
140
- uuid id PK
141
- string name
142
- string file_type
143
- string file_path
144
- string category
145
- json tags
146
-
147
- COLLECTION {
148
- string id PK
149
- string name
150
- text description
151
- string spec_id FK
152
- datetime created_at
153
- }
154
-
155
- ASSET_COLLECTIONS {
156
- string asset_id FK
157
- string collection_id FK
158
- }
159
-
160
- CHAT_SESSION {
161
- string id PK
162
- string name
163
- string spec_id FK
164
- string session_id FK
165
- datetime created_at
166
- }
167
-
168
- CHAT_MESSAGE {
169
- int id PK
170
- string chat_session_id FK
171
- string role
172
- text content
173
- datetime created_at
174
- }
175
-
176
- SPEC_DOCUMENT ||--o{ SESSION_MODEL : "has"
177
- SESSION_MODEL ||--o{ EXECUTION_HISTORY : "contains"
178
- SPEC_DOCUMENT ||--o{ ASSET : "owns"
179
- SPEC_DOCUMENT ||--o{ COLLECTION : "groups"
180
- ASSET }|--|{ COLLECTION : "ASSET_COLLECTIONS"
181
- SPEC_DOCUMENT ||--o{ CHAT_SESSION : "has"
182
- SESSION_MODEL ||--o{ CHAT_SESSION : "linked to"
183
- CHAT_SESSION ||--o{ CHAT_MESSAGE : "contains"
184
- ```
185
-
186
- ---
187
-
188
- ## 4. Data Flow Diagram (DFD) — Core Pipeline
189
- *Shows how data transforms and moves through the Triple-Stage AI Pipeline.*
190
-
191
- ```mermaid
192
- flowchart LR
193
- A([User Input:\nNatural Language\nScenario]) --> B
194
-
195
- subgraph B["Stage 1: LLM Planner"]
196
- B1["Simplified\nEndpoint List"] --> B2["Planner\nPrompt"]
197
- B3["User\nCredentials"] --> B2
198
- B2 --> B4["Mistral AI\nReasoning"]
199
- B4 --> B5["Execution\nPlan JSON"]
200
- end
201
-
202
- B5 --> C
203
-
204
- subgraph C["Stage 2: API Executor (per step)"]
205
- C1["Full Spec\n(from DB)"] --> C2["resolve_refs()"]
206
- C2 --> C3["prune_spec()"]
207
- C3 --> C4["shorthand_spec()"]
208
- C4 --> C5["Executor\nPrompt"]
209
- C6["Session\nContext Vars"] --> C5
210
- C7["User Creds"] --> C5
211
- C5 --> C8["Mistral AI\nReasoning"]
212
- C8 --> C9["HTTP\nRequest Object"]
213
- C9 --> C10{{"Target\nAPI Server"}}
214
- C10 --> C11["Raw\nResponse"]
215
- end
216
-
217
- C11 --> D
218
-
219
- subgraph D["Stage 3: Response Analyzer"]
220
- D1["Truncated\nResponse Body"] --> D2["Analyzer\nPrompt"]
221
- D3["Step\nPurpose"] --> D2
222
- D2 --> D4["Mistral AI\nReasoning"]
223
- D4 --> D5["Semantic\nStatus"]
224
- D4 --> D6["Extracted\nVariables"]
225
- D4 --> D7["OTP\nFlag"]
226
- end
227
-
228
- D6 -->|"Stored back to\nSession Context"| C6
229
- D5 --> E([User sees:\nSuccess/Failure\nExplanation])
230
- ```
231
-
232
- ---
233
-
234
- ## 5. Use Case Diagram
235
- *Illustrates what different types of users can do with the system.*
236
-
237
- ```mermaid
238
- graph TB
239
- subgraph Actors
240
- Dev["👨‍💻 Developer / QA Engineer"]
241
- NonTech["🧑‍💼 Non-Technical Tester"]
242
- end
243
-
244
- subgraph "AI API Testing Assistant"
245
- UC1["Upload API Spec\n(OpenAPI / Postman)"]
246
- UC2["Describe Test Scenario\n(Natural Language)"]
247
- UC3["Generate Execution Plan"]
248
- UC4["Execute Individual Steps"]
249
- UC5["View AI Response Analysis"]
250
- UC6["Manage Test User Profile"]
251
- UC7["Upload Media Assets\n(Files for API Testing)"]
252
- UC8["View Execution History"]
253
- UC9["Restore Past Session"]
254
- UC10["Monitor Token Usage"]
255
- end
256
-
257
- Dev --> UC1
258
- Dev --> UC2
259
- Dev --> UC3
260
- Dev --> UC4
261
- Dev --> UC5
262
- Dev --> UC6
263
- Dev --> UC7
264
- Dev --> UC8
265
- Dev --> UC9
266
- Dev --> UC10
267
-
268
- NonTech --> UC1
269
- NonTech --> UC2
270
- NonTech --> UC3
271
- NonTech --> UC4
272
- NonTech --> UC5
273
- NonTech --> UC8
274
- ```
275
-
276
- ---
277
-
278
- ## 6. State Diagram — Test Session Lifecycle
279
- *Shows the states a test session moves through from creation to completion.*
280
-
281
- ```mermaid
282
- stateDiagram-v2
283
- [*] --> Idle : App Loaded
284
-
285
- Idle --> SpecSelected : User selects/uploads a spec
286
- SpecSelected --> ProfileConfigured : User sets credentials (optional)
287
- ProfileConfigured --> ScenarioWritten : User types test scenario
288
-
289
- ScenarioWritten --> PlanGenerating : User clicks "Generate Plan"
290
- PlanGenerating --> PlanGenerating : LLM reasoning...
291
- PlanGenerating --> PlanReady : Plan received
292
-
293
- PlanReady --> StepExecuting : User clicks "Execute Step"
294
- StepExecuting --> StepExecuting : HTTP request in flight...
295
- StepExecuting --> AnalysisResult : Response received
296
-
297
- AnalysisResult --> OTPRequired : is_otp_required = true
298
- OTPRequired --> StepExecuting : User enters OTP code
299
-
300
- AnalysisResult --> PlanReady : More steps remain
301
- AnalysisResult --> SessionComplete : Last step done
302
-
303
- SessionComplete --> [*] : Session saved to History
304
- SessionComplete --> PlanReady : User runs again (plan restored)
305
-
306
- PlanGenerating --> PlanFailed : LLM error
307
- StepExecuting --> StepFailed : Network / API error
308
- PlanFailed --> ScenarioWritten : User retries
309
- StepFailed --> PlanReady : User retries step
310
- ```
311
-
312
- ---
313
-
314
- ## 7. Class Diagram — Backend Service Architecture
315
- *Defines the Pydantic models and service classes in the Python backend.*
316
-
317
- ```mermaid
318
- classDiagram
319
- class SpecDocument {
320
- +String id
321
- +String name
322
- +Text raw_content
323
- +JSON parsed_json
324
- +String base_url
325
- +JSON login_credentials
326
- +JSON execution_plan
327
- +String file_path
328
- }
329
-
330
- class SessionModel {
331
- +String id
332
- +String spec_id
333
- +JSON context_variables
334
- +get_context() dict
335
- +set_context_variables(vars) dict
336
- }
337
-
338
- class ExecutionHistory {
339
- +Integer id
340
- +String session_id
341
- +Integer step
342
- +JSON request_json
343
- +JSON response_json
344
- +JSON analysis_json
345
- }
346
-
347
- class ExecutionPlan {
348
- +List execution_plan
349
- +Dict suggested_credentials
350
- +Dict token_usage
351
- }
352
-
353
- class StepExecutionPlan {
354
- +Integer step
355
- +APIRequest request
356
- +StepAnalysis analysis
357
- +Dict token_usage
358
- }
359
-
360
- class APIRequest {
361
- +String method
362
- +String url
363
- +Dict headers
364
- +Dict query_params
365
- +Dict form_data
366
- +Dict body
367
- +Dict files
368
- }
369
-
370
- class AnalyzeResponse {
371
- +Integer step
372
- +String status
373
- +Bool is_otp_required
374
- +String otp_field_name
375
- +Dict extracted_variables
376
- +Dict token_usage
377
- }
378
-
379
- class LLMPlanner {
380
- +generate_execution_plan(spec, url, scenario, creds) ExecutionPlan
381
- }
382
-
383
- class APIExecutor {
384
- +prepare_step_request(spec, url, scenario, step, context, creds, assets) StepExecutionPlan
385
- }
386
-
387
- class ResponseAnalyzer {
388
- +analyze_api_response(step, endpoint, purpose, status_code, body) AnalyzeResponse
389
- }
390
-
391
- class ChatAssistantService {
392
- +process_message(message, spec_name, plan, context, last_result, all_results, history) ChatAction
393
- }
394
-
395
- class ChatSession {
396
- +String id
397
- +String name
398
- +String spec_id
399
- +String session_id
400
- }
401
-
402
- class ChatMessage {
403
- +Integer id
404
- +String chat_session_id
405
- +String role
406
- +Text content
407
- }
408
-
409
- class StorageProvider {
410
- <<abstract>>
411
- +save(file, path)
412
- +delete(path)
413
- +get_full_path(path) str
414
- }
415
-
416
- class LocalStorageProvider {
417
- +save(file, path)
418
- +delete(path)
419
- +get_full_path(path) str
420
- }
421
-
422
- class SupabaseStorageProvider {
423
- +save(file, path)
424
- +delete(path)
425
- +get_full_path(path) str
426
- }
427
-
428
- StepExecutionPlan *-- APIRequest
429
- LLMPlanner ..> ExecutionPlan : creates
430
- APIExecutor ..> StepExecutionPlan : creates
431
- ResponseAnalyzer ..> AnalyzeResponse : creates
432
- ChatAssistantService ..> ChatAction : creates
433
- StorageProvider <|-- LocalStorageProvider
434
- StorageProvider <|-- SupabaseStorageProvider
435
- SessionModel "1" --> "many" ExecutionHistory
436
- SpecDocument "1" --> "many" SessionModel
437
- ChatSession "1" --> "many" ChatMessage
438
- SpecDocument "1" --> "many" ChatSession
439
- ```
440
-
441
- ---
442
-
443
- ## 8. Component Diagram — Frontend Module Structure
444
- *Shows the React components and their relationships.*
445
-
446
- ```mermaid
447
- graph TB
448
- App["App.jsx\n(Root + Router)"] --> Sidebar["ActivityBar\n(Navigation)"]
449
- App --> MainContent["MainContent\n(Dynamic Panel)"]
450
- App --> RightSidebar["Right Sidebar\n(Context + AI Chat Tabs)"]
451
-
452
- Sidebar --> Nav1["Collections Icon"]
453
- Sidebar --> Nav2["Testing Icon"]
454
- Sidebar --> Nav3["Profile Icon"]
455
- Sidebar --> Nav4["History Icon"]
456
- Sidebar --> Nav5["Media Hub Icon"]
457
- Sidebar --> Nav6["AI Chat Icon"]
458
- Sidebar --> Nav7["Settings Icon"]
459
-
460
- MainContent --> CollectionsPage["CollectionsPage\n(Spec Cards + Upload)"]
461
- MainContent --> TestingPage["TestingPage\n(Main Workspace)"]
462
- MainContent --> ProfilePage["ProfilePage\n(Credentials Form)"]
463
- MainContent --> HistoryPage["HistoryPage\n(Audit Log)"]
464
- MainContent --> MediaHubPage["MediaHubPage\n(File Manager)"]
465
- MainContent --> ChatPage["ChatAssistant\n(Full-page AI Chat)"]
466
-
467
- TestingPage --> PlanInput["PlanInput\n(Scenario + Send)"]
468
- TestingPage --> StepList["StepList\n(Plan Steps)"]
469
- TestingPage --> TokenTracker["TokenUsageTracker"]
470
- TestingPage --> OTPModal["OTPModal\n(Conditional)"]
471
- TestingPage --> SelectionModal["SelectionModal\n(Conditional: List Response)"]
472
-
473
- StepList --> StepCard["StepCard\n(Execute + Results)"]
474
- StepCard --> RequestView["RequestInspector\n(Headers, Body)"]
475
- StepCard --> ResponseView["ResponseInspector\n(Status, JSON)"]
476
- StepCard --> AnalysisView["AnalysisView\n(AI Verdict)"]
477
-
478
- RightSidebar --> ContextTab["Context Tab\n(Session Variables + Creds)"]
479
- RightSidebar --> ChatTab["AI Chat Tab\n(Compact ChatAssistant)"]
480
- ```
481
-
482
- ---
483
-
484
- ## 9. Deployment Diagram
485
- *Shows how the system is deployed in both local development and cloud production.*
486
-
487
- ```mermaid
488
- graph TB
489
- subgraph "Developer Machine (Local)"
490
- direction TB
491
- D1["npm run dev\n(concurrently)"]
492
- D1 --> D2["Vite Dev Server\nlocalhost:5173"]
493
- D1 --> D3["Uvicorn Server\nlocalhost:8001"]
494
- D3 --> D4["backend/main.py\n(FastAPI App)"]
495
- D4 --> D5["backend/uploads/\n(Local Storage)"]
496
- end
497
-
498
- subgraph "Cloud (Production)"
499
- direction TB
500
- P1["Heroku Dyno\n(Procfile: gunicorn)"]
501
- P1 --> P2["FastAPI App\n(Gunicorn + Uvicorn Workers)"]
502
- P2 --> P3["React Build\n(Static Files Served)"]
503
- P2 --> P4["Supabase\n(PostgreSQL DB)"]
504
- P2 --> P5["Supabase Storage\n(S3-compatible Bucket)"]
505
- end
506
-
507
- subgraph "External Services"
508
- EX1["Mistral AI API\n(Cloud LLM)"]
509
- EX2["Target API Server\n(Under Test)"]
510
- end
511
-
512
- D4 --> EX1
513
- P2 --> EX1
514
- D4 --> EX2
515
- P2 --> EX2
516
- ```
517
-
518
- ---
519
-
520
- ## 10. Algorithm Flowchart — Schema Resolution Pipeline
521
- *Detailed flowchart of the 4-step on-demand schema resolution algorithm used before each API execution.*
522
-
523
- ```mermaid
524
- flowchart TD
525
- A([Step Definition\ne.g. 'GET /users/usr_abc']) --> B
526
-
527
- B["Split into:\nmethod = GET\npath = /users/usr_abc"]
528
-
529
- B --> C{Direct lookup\npath in spec.paths?}
530
- C -- Yes --> E["matched_path = path"]
531
- C -- No --> D["Regex Fuzzy Match:\nReplace {param} → [^/]+\nfor each template T in paths"]
532
- D --> D2{Template\nmatches path?}
533
- D2 -- Yes --> E
534
- D2 -- No --> D3["⚠ FALLBACK:\nUse raw endpoint string\n+ warning flag"]
535
-
536
- E --> F["Fetch raw schema:\nspec.paths[matched_path]"]
537
-
538
- F --> G["resolve_refs(schema, full_spec):\nTraverse JSON tree\nReplace all '$ref' pointers\nwith their target schemas\nCycle detection via resolving_set"]
539
-
540
- G --> H["prune_spec_for_execution(schema):\nRemove keys:\ndescription, summary, example,\nexamples, format, title, default\nRemove entire 'responses' subtree"]
541
-
542
- H --> I["shorthand_spec(schema):\nConvert JSON Schema to\ncompact shorthand notation:\n string → str\n {field*: type} → field*(str)\n enum → type[A|B|C]\n array → [itemType]"]
543
-
544
- I --> J(["Compact Schema String\n→ Sent to Executor Prompt"])
545
- ```
546
-
547
- ---
548
-
549
- ## 11. Flowchart — URL Sanitization (Anti-Hallucination Guard)
550
-
551
- ```mermaid
552
- flowchart TD
553
- A([Raw URL from LLM]) --> B{Starts\nwith '/'?}
554
- B -- Yes --> C["Relative URL\nurl = base_url + url"]
555
- B -- No --> D{Is hostname in\nPLACEHOLDER_HOSTS?\ne.g. api.example.com}
556
- D -- Yes --> E["Extract path + query\nfrom URL\nurl = base_url + path"]
557
- D -- No --> F{Starts\nwith 'http'?}
558
- F -- No --> G["Schemeless\nurl = 'https://' + url"]
559
- F -- Yes --> H["Valid URL\nNo change needed"]
560
-
561
- C & E & G & H --> Z([Final Sanitized URL\n→ Sent to httpx])
562
- ```
563
-
564
- ---
565
-
566
- ## How to Use These Diagrams
567
-
568
- | Tool | How to Render |
569
- |---|---|
570
- | **VS Code** | Install "Markdown Preview Mermaid Support" extension, open preview |
571
- | **Mermaid Live** | Paste code at https://mermaid.live |
572
- | **GitHub** | Paste directly into any `.md` file — renders automatically |
573
- | **Notion** | Create a code block, select "Mermaid" as language |
574
- | **draw.io** | Extras → Edit Diagram → Mermaid tab |
575
- | **Confluence** | Use the Mermaid macro/plugin |
576
- | **Lucidchart** | Import via Mermaid format |
577
-
578
- > **Tip:** Each diagram is independent. You can copy any single code block and render it separately for presentations or thesis documents.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documents/README.md DELETED
@@ -1,77 +0,0 @@
1
- # AI API Testing Assistant
2
-
3
- An automated API testing system powered by Mistral AI, FastAPI, and React. This tool parses an OpenAPI (Swagger) specification, takes a natural-language test scenario from the user, and dynamically generates and executes an API execution plan.
4
-
5
- ## Features
6
-
7
- - **Intelligent Planning**: Generates multi-step test scenarios from natural language.
8
- - **Context-Aware Execution**: Automatically propagates tokens and variables (IDs, slugs, etc.) between steps.
9
- - **Persistent AI Chat**: An interactive assistant that understands your full testing context and can control the workflow.
10
- - **Media Hub**: Manage assets (images, PDFs, audio) for API requests requiring file uploads.
11
- - **Zero-Code Testing**: Describe your intent (e.g., "Register, login, and update my profile picture") and let the AI handle the rest.
12
- - **Format Agnostic**: Supports OpenAPI (Swagger) and Postman Collections.
13
- - **Clean Organization**: Documentation is centrally managed in this `documents/` folder.
14
-
15
- ## Requirements
16
-
17
- - **Python** 3.9+
18
- - **Node.js** 18+
19
- - A valid **Mistral AI API Key**
20
-
21
- ## Setup (First Time)
22
-
23
- 1. Clone the repo and install all dependencies:
24
- ```bash
25
- npm run setup
26
- ```
27
- 2. Open `.env` and add your Mistral API key:
28
- ```ini
29
- MISTRAL_API_KEY=your_actual_api_key_here
30
- ```
31
-
32
- ## Starting the App
33
-
34
- ### Option 1 — Recommended (single command, colour-coded output)
35
- ```bash
36
- npm run dev
37
- ```
38
- Starts both the FastAPI backend and the React frontend concurrently in one terminal.
39
-
40
- ### Option 2 — PowerShell script (opens separate windows per service)
41
- ```powershell
42
- .\start.ps1
43
- ```
44
-
45
- ### Option 3 — Manual (two terminals)
46
- ```bash
47
- # Terminal 1 — Backend
48
- python -m uvicorn backend.main:app --reload --port 8001
49
-
50
- # Terminal 2 — Frontend
51
- cd frontend-react && npm run dev
52
- ```
53
-
54
- ## URLs
55
-
56
- | Service | URL |
57
- |----------|------------------------------|
58
- | Frontend | http://localhost:5173 |
59
- | Backend | http://localhost:8001 |
60
- | API Docs | http://localhost:8001/docs |
61
-
62
- ## 📂 Project Structure
63
-
64
- - `backend/`: FastAPI server with LLM pipeline logic.
65
- - `frontend-react/`: Modern React dashboard built with Vite and Tailwind CSS.
66
- - `documents/`: Comprehensive documentation, diagrams, and research notes (you are here).
67
- - `start.ps1`: One-click startup script for Windows.
68
- - `project_for_review.zip`: Optimized archive for sharing the project with reviewers.
69
-
70
- ## Usage
71
-
72
- 1. Open the frontend at `http://localhost:5173`.
73
- 2. Upload a valid `swagger.json` or `openapi.yaml`.
74
- 3. Provide the base URL of the server to test.
75
- 4. Describe your test scenario in natural language.
76
- 5. Generate an execution plan and run your steps!
77
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documents/Research_Paper.md DELETED
@@ -1,784 +0,0 @@
1
- # Automated API Testing through LLM-Driven Synthesis and Context-Aware Execution: A Comprehensive Framework
2
-
3
- **Author:** [Your Name]
4
- **Affiliation:** [Your Institution / Department of Computer Science]
5
- **Date:** May 2026
6
-
7
- ---
8
-
9
- ## Abstract
10
-
11
- The growing complexity of web APIs in modern microservice architectures has created a significant bottleneck in software quality assurance. Traditional API testing paradigms, whether manual or script-driven, demand deep technical expertise, verbose configuration, and constant maintenance as APIs evolve. This paper presents the design, architecture, and implementation of an AI-powered API Testing Assistant — a full-stack system that eliminates these barriers by allowing users to describe test scenarios in plain natural language. The system ingests OpenAPI/Swagger and Postman specifications, leverages the Mistral-Large language model via LangChain to synthesize multi-step execution plans, dynamically resolves `$ref` schemas on demand, manages a persistent session-scoped context store, performs semantic response analysis after each step, and provides an interactive AI Chat Assistant for natural-language control of the entire execution workflow. Built on FastAPI, React, PostgreSQL, and Supabase, the framework achieves a plan generation accuracy of 94% and a variable extraction precision of 89% in complex multi-endpoint test scenarios. The study advances the state-of-the-art in intelligent test automation by introducing a novel four-stage pipeline: Strategic Planning, Context-Aware Execution, Semantic Response Analysis, and Conversational AI Assistance — enabling zero-code API validation for both technical and non-technical users.
12
-
13
- **Keywords:** API Testing, Large Language Models, OpenAPI, LangChain, Mistral AI, FastAPI, Test Automation, Prompt Engineering, Conversational AI, Interactive Selection.
14
-
15
- ---
16
-
17
- ## 1. Introduction
18
-
19
- ### 1.1 Background
20
-
21
- Application Programming Interfaces (APIs) form the structural backbone of contemporary software. According to the Postman State of the API Report (2023), over 86% of developers interact with APIs daily, and APIs are the primary integration mechanism for cloud-native and distributed systems. REST APIs defined by the OpenAPI Specification (OAS) have become the de-facto standard for documenting inter-service contracts. However, ensuring the correctness and reliability of these interfaces remains a labour-intensive challenge.
22
-
23
- Contemporary testing tools, such as Postman and Insomnia, are powerful but require users to manually construct HTTP requests, manage authentication tokens, and write assertion scripts. As APIs evolve, tests written for previous states become brittle. Automated testing frameworks like PyTest or REST-assured provide programmatic control but demand strong technical expertise and significant initial scaffolding.
24
-
25
- ### 1.2 Problem Statement
26
-
27
- The core challenge in API testing is not a lack of tooling, but a lack of *intelligent automation*. Specifically, three interrelated problems persist:
28
-
29
- 1. **Dependency Chaining**: Real-world test scenarios involve sequences of interdependent API calls. For example, a "Create a booking" test must first call `POST /auth/login` to obtain a bearer token, then `GET /users/me` to retrieve a profile ID, and finally `POST /bookings` with that ID as a body parameter. Manually orchestrating this chain is tedious and error-prone.
30
-
31
- 2. **Schema Complexity and Maintenance**: OpenAPI specifications for mature APIs can contain hundreds of endpoints with deeply nested JSON schemas linked via `$ref` pointers. Parsing and resolving this structure for every test case is computationally challenging.
32
-
33
- 3. **Semantic Validation**: A standard assertion checks for a `200 OK` status code. It cannot determine whether the returned data is *semantically correct* relative to the intended test scenario (e.g., distinguishing a successful login token from a rate-limiting response that also returns `200`).
34
-
35
- ### 1.3 Objective
36
-
37
- This paper presents an automated API testing framework designed to address all three of the above challenges. The specific objectives are:
38
-
39
- - To design a system that parses raw OpenAPI and Postman specification files, extracting a standardized, LLM-consumable endpoint summary.
40
- - To implement an LLM-driven planner that converts natural language test scenarios into a structured, ordered execution plan.
41
- - To develop a context-aware step executor that resolves dynamic path parameters, injects session variables, handles multipart file uploads, and manages authentication headers — all autonomously.
42
- - To build a semantic response analyzer that evaluates API responses against the test intent, extracts reusable variables, detects OTP prompts, and identifies interactive selection scenarios where the user must choose from a list of returned entities.
43
- - To develop a persistent, context-aware AI Chat Assistant that gives users natural-language control over the execution workflow, enabling step execution, error diagnosis, and request modification through conversational interaction.
44
- - To provide a user-friendly React-based interface for managing tests, viewing execution history, and managing test assets.
45
-
46
- ---
47
-
48
- ## 2. Literature Review
49
-
50
- ### 2.1 Conventional API Testing Tools
51
-
52
- 2.1 Conventional API Testing Tools and Their Limitations
53
- In the current software development lifecycle, several established tools dominate the API testing landscape. These tools are primarily designed for manual exploration, functional validation, and deterministic regression testing.
54
-
55
- Postman and Insomnia: Postman remains the industry-leading platform, utilizing a collection-based model that allows users to group requests and define environment variables. While powerful, these tools require testers to manually construct HTTP requests and manage state across different environments.
56
-
57
- Script-Based Assertions: Conventional validation relies on manual scripting, typically in JavaScript, to perform assertions on response codes and data structures. A standard assertion might check for a 200 OK status, but it often lacks the intelligence to perform semantic validation of the returned content.
58
-
59
- Manual Request Chaining: To test interdependent API calls—such as authenticating before placing an order—users must manually extract values (e.g., Bearer tokens) from one response and inject them into the headers of the next. This process is tedious and prone to error as APIs evolve.
60
-
61
- Property-Based Testing: Tools like Schemathesis attempt to automate testing by generating cases directly from OpenAPI specifications. However, these tools focus on fuzzing for reliability and edge cases rather than replicating logical, multi-step user journeys based on specific intent.
62
-
63
- ### 2.2 Large Language Models for Code and Testing
64
-
65
- The application of LLMs to software engineering tasks has accelerated dramatically. Codex (Chen et al., 2021) demonstrated that LLMs pre-trained on code could generate functional programs from natural language descriptions. Subsequent research applied this capability to test case generation, with studies by Schäfer et al. (2023) showing that GPT-based models can generate unit tests with comparable coverage to human-written ones.
66
-
67
- In the domain of API testing specifically, research by Bhandari et al. (2023) explored using LLMs to generate Postman test scripts from API documentation, achieving high syntactic validity but struggling with multi-step context propagation. Jiang et al. (2024) proposed "Natural Language to API" translation but focused on single-request generation rather than stateful, multi-step flows.
68
-
69
- Mistral AI introduced the Mistral-7B family (Mistral AI Team, 2024), demonstrating that instruction-tuned models of moderate size could achieve near-state-of-the-art performance on logical reasoning tasks, particularly when provided with structured output formats such as JSON — a critical requirement for our pipeline.
70
-
71
- ### 2.3 Prompt Engineering and Structured Output
72
-
73
- A key enabler of this work is the use of structured prompt templates for deterministic JSON output. LangChain (Chase et al., 2023) provides a composable framework for building LLM applications, including `PromptTemplate`, `ChatMistralAI`, and `JsonOutputParser` — components that enforce schema compliance on LLM outputs using Pydantic models.
74
-
75
- ### 2.4 Research Gap
76
-
77
- Despite progress in individual components, a gap exists in the integration of LLM-driven planning with *real-time, stateful, multi-turn execution* against live APIs. Prior work treats test generation and execution as separate tasks. No existing open-source tool provides an end-to-end pipeline that: (a) accepts raw API specifications, (b) reasons about endpoint dependencies, (c) executes HTTP calls in sequence, (d) propagates extracted variables between calls, and (e) provides semantic analysis of each response. This paper closes that gap.
78
-
79
- ---
80
-
81
- ## 3. Methodology
82
-
83
- This section provides a comprehensive and technically detailed description of the system's design philosophy, data architecture, algorithmic components, prompt engineering strategies, and end-to-end execution workflow. The system is founded on a novel **Four-Stage AI Pipeline** — Strategic Planning, Context-Aware Execution, Semantic Response Analysis, and Conversational AI Assistance — underpinned by a persistent, session-scoped state management system and a modular service architecture.
84
-
85
- ---
86
-
87
- ### 3.1 System Architecture Overview
88
-
89
- The overall system is organized into four independent tiers that communicate through well-defined interfaces. This separation of concerns ensures that any individual tier can be upgraded, replaced, or scaled without affecting the others.
90
-
91
- ```
92
- ┌──────────────────────────────────────────────────────────────┐
93
- │ PRESENTATION TIER │
94
- │ React + Vite + Tailwind CSS (SPA Frontend) │
95
- │ Modules: API Collections | Execution Hub | History | │
96
- │ Test Profile | Media Hub | AI Chat | Settings │
97
- └───────────────────────────┬──────────────────────────────────┘
98
- │ HTTP/REST (JSON)
99
- ┌───────────────────────────▼──────────────────────────────────┐
100
- │ ORCHESTRATION TIER │
101
- │ FastAPI Application (main.py) │
102
- │ Responsibilities: │
103
- │ • CORS Middleware & Request Validation │
104
- │ • Session Lifecycle Management (UUID-based) │
105
- │ • Routing to Intelligence and Data services │
106
- │ • File Handling, URL Sanitization, Error Recovery │
107
- │ • Asynchronous HTTP Execution (httpx.AsyncClient) │
108
- │ • Chat Session & Message Persistence │
109
- └──────────────────┬───────────────────────┬───────────────────┘
110
- │ │
111
- ┌──────────────────▼──────┐ ┌────────────▼──────────────────┐
112
- │ DATA TIER │ │ INTELLIGENCE TIER │
113
- │ ┌──────────────────┐ │ │ ┌──────────────────────────┐ │
114
- │ │ PostgreSQL DB │ │ │ │ LLM Planner │ │
115
- │ │ (SQLAlchemy ORM)│ │ │ │ (llm_planner.py) │ │
116
- │ │ - SpecDocument │ │ │ ├──────────────────────────┤ │
117
- │ │ - SessionModel │ │ │ │ API Executor │ │
118
- │ │ - ExecHistory │ │ │ │ (api_executor.py) │ │
119
- │ │ - Asset, Coll. │ │ │ ├──────────────────────────┤ │
120
- │ │ - ChatSession │ │ │ │ Response Analyzer │ │
121
- │ │ - ChatMessage │ │ │ │ (response_analyzer.py) │ │
122
- │ └──────────────────┘ │ │ ├──────────────────────────┤ │
123
- │ ┌──────────────────┐ │ │ │ Chat Assistant │ │
124
- │ │ Supabase Storage │ │ │ │ (chat_assistant.py) │ │
125
- │ │ (Files / Specs) │ │ │ └──────────────────────────┘ │
126
- │ └──────────────────┘ │ │ All services use: │ │
127
- └─────────────────────────┘ │ LangChain + Mistral-Large │ │
128
- └───────────────────────────────┘
129
- ```
130
-
131
- **Communication Flow:**
132
- - The **Presentation Tier** sends all requests to the FastAPI backend via REST.
133
- - The **Orchestration Tier** reads/writes state to the **Data Tier** (PostgreSQL for structured data, Supabase for raw files) and delegates reasoning tasks to the **Intelligence Tier**.
134
- - The **Intelligence Tier** services are stateless and produce structured JSON outputs, which are then persisted by the Orchestration Tier.
135
-
136
- ---
137
-
138
- ### 3.2 Data Architecture and Persistence Model
139
-
140
- The relational database schema is defined using SQLAlchemy's declarative ORM. Each entity is designed to encapsulate a specific responsibility, minimizing coupling between concerns.
141
-
142
- #### 3.2.1 Entity Relationship Overview
143
-
144
- ```
145
- SpecDocument
146
- ├── id (UUID, PK)
147
- ├── name (filename of the uploaded spec)
148
- ├── raw_content (original spec text, stored as TEXT)
149
- ├── parsed_json (structured output of the parser, JSON)
150
- ├── base_url (mutable, set by user per session)
151
- ├── login_credentials (JSON, per-spec credential store)
152
- ├── execution_plan (JSON, last generated LLM plan)
153
- ├── scenario (TEXT, last submitted scenario)
154
- └── file_path (string ref to Supabase/local path)
155
-
156
- SessionModel
157
- ├── id (UUID, PK — provided by frontend)
158
- ├── spec_id (FK → SpecDocument)
159
- ├── base_url, scenario
160
- └── context_variables (JSON — live KV store of extracted vars)
161
- ╠══ e.g. {"auth_token": "eyJ...", "user_id": "usr_abc"}
162
-
163
- ExecutionHistory
164
- ├── id (Integer, auto-increment PK)
165
- ├── session_id (FK → SessionModel)
166
- ├── step (step number in plan)
167
- ├── request_json (JSON — exact HTTP request sent)
168
- ├── response_json (JSON — raw status code + body)
169
- ├── analysis_json (JSON — LLM analysis result)
170
- └── step_definition_json (JSON — planned step from planner)
171
-
172
- Asset ←──M:M──→ Collection
173
- ├── id, name, file_type, file_size
174
- ├── category (audio | video | documents | images)
175
- ├── description (TEXT — semantic description for AI)
176
- ├── tags (JSON array — e.g. ["aadhar", "kyc"])
177
- └── spec_id (optional FK → SpecDocument)
178
-
179
- ChatSession
180
- ├── id (UUID, PK)
181
- ├── name (auto-generated from first message, truncated to 60 chars)
182
- ├── spec_id (optional FK → SpecDocument)
183
- └── session_id (optional FK → SessionModel — links chat to test session)
184
-
185
- ChatMessage
186
- ├── id (Integer, auto-increment PK)
187
- ├── chat_session_id (FK → ChatSession)
188
- ├── role ("user" | "assistant")
189
- └── content (TEXT — the full message content)
190
- ```
191
-
192
- #### 3.2.2 JSON Column Strategy
193
-
194
- SQLAlchemy's handling of mutable JSON columns requires special care. When a JSON field (e.g., `context_variables`) is modified in-place (e.g., by merging a new dictionary into it), SQLAlchemy's change detection does not automatically detect the mutation. The system explicitly calls `flag_modified(entity, "column_name")` after every JSON update to force the ORM to mark the record as dirty and emit the corresponding `UPDATE` SQL statement. This prevents a class of silent-persistence bugs that are common in SQLAlchemy applications using JSON columns.
195
-
196
- ---
197
-
198
- ### 3.3 API Specification Ingestion and Parsing
199
-
200
- The ingestion pipeline handles the complexity of diverse specification formats, large file sizes, and nested schema references before any LLM reasoning takes place.
201
-
202
- #### 3.3.1 Format Detection and Parsing Strategy
203
-
204
- When a user uploads a file via `POST /upload-spec`, the system applies a **two-pass detection algorithm**:
205
-
206
- **Pass 1 — Postman vs. OpenAPI Detection (in `main.py`):**
207
- The raw content is first parsed as JSON. If parsing succeeds, the system inspects the top-level keys:
208
- - **Primary check**: if `info.schema` contains the string `"postman.com/json/collection"`, it is a Postman collection.
209
- - **Secondary check**: if the document has both an `info` key and an `item` key but lacks a top-level `openapi` or `swagger` key, it is classified as a Postman collection.
210
- - If neither condition is met, or if the file is YAML, it is treated as an OpenAPI/Swagger spec.
211
-
212
- This routing dispatches to either `parse_postman_collection()` or `parse_spec()` accordingly.
213
-
214
- **Pass 2 — OpenAPI Format Resolution (in `swagger_parser.py`):**
215
- `parse_spec()` first attempts `json.loads()`. On a `JSONDecodeError`, it attempts `yaml.safe_load()`. On `YAMLError`, a descriptive `ValueError` is raised. This handles `.json`, `.yaml`, and `.yml` files transparently.
216
-
217
- #### 3.3.2 The Two-Level Output Strategy
218
-
219
- A fundamental design choice is the production of two distinct representations from a single specification file:
220
-
221
- **Level 1 — Simplified Endpoint List (for the Planner LLM):**
222
- The parser iterates over all paths and methods in the spec and builds a flat list of:
223
- ```json
224
- [
225
- {"path": "/auth/login", "method": "POST", "summary": "Authenticate a user"},
226
- {"path": "/users/{id}", "method": "GET", "summary": "Get user by ID"},
227
- {"path": "/orders", "method": "POST", "summary": "Create a new order"}
228
- ]
229
- ```
230
- Summaries are capped at 100 characters to limit token usage. This condensed list is what is sent to the Planner, making the planning prompt compact even for APIs with 500+ endpoints.
231
-
232
- **Level 2 — Full Schema (for the Executor):**
233
- The complete `paths` and `components` sections are stored verbatim in the `SpecDocument.parsed_json` database column. This preserves all `$ref` pointers, `enum` values, and type constraints in their original form. The Executor retrieves and resolves only the single path required for each step at runtime, achieving O(1) schema retrieval regardless of total spec size.
234
-
235
- This **lazy-resolution strategy** is the primary mechanism enabling the system to handle enterprise-scale specifications such as the GitHub REST API (>12 MB) without any memory pressure or context-window violations.
236
-
237
- ---
238
-
239
- ### 3.4 Stage 1: Strategic Planning — The LLM Planner
240
-
241
- The LLM Planner is the first and most strategically important stage. It accepts a human-readable description of a test scenario and emits a machine-executable, ordered list of API calls.
242
-
243
- #### 3.4.1 LangChain Pipeline Architecture
244
-
245
- The planner is implemented as a three-component LangChain chain:
246
-
247
- ```
248
- PromptTemplate → ChatMistralAI → JsonOutputParser
249
- (fills (mistral-large, (validates output
250
- input vars) temperature=0) against Pydantic
251
- ExecutionPlan model)
252
- ```
253
-
254
- The use of `temperature=0` is a deliberate choice to maximise determinism. For a given set of inputs (same spec, same scenario, same credentials), the output plan will be identical across multiple invocations. This is essential for reproducible testing.
255
-
256
- #### 3.4.2 Planner Prompt Engineering
257
-
258
- The planner prompt is structured to provide the LLM with all information required for holistic reasoning about the API. It is composed of six sections:
259
-
260
- | Prompt Section | Content | Purpose |
261
- |---|---|---|
262
- | **Role Definition** | "You are an intelligent API testing planner..." | Anchors the model's persona and reasoning mode |
263
- | **API Documentation** | The simplified endpoint list (JSON) | Provides the vocabulary of available actions |
264
- | **Base URL** | The target server URL | Grounds all URL constructions |
265
- | **Tester Scenario** | Natural language input from user | Defines the testing intent |
266
- | **User Credentials** | Stored profile from DB (or empty `{}`) | Provides existing identity context |
267
- | **Decision Rule** | "If credentials exist, SKIP registration steps" | Prevents destructive or redundant operations |
268
-
269
- The **Decision Rule** is a particularly critical engineering choice. Without it, the LLM would always generate a user-registration step at the start of every plan (since registration is a common first action in most APIs). This would cause duplicate-user errors on every subsequent test run. By checking existing credentials and injecting an explicit constraint, the system enables idempotent testing across multiple iterations.
270
-
271
- #### 3.4.3 Structured Plan Output and Auto-Merge
272
-
273
- The planner is directed to return a strict JSON object matching the `ExecutionPlan` Pydantic schema:
274
-
275
- ```json
276
- {
277
- "execution_plan": [
278
- {"step": 1, "endpoint": "POST /auth/register", "purpose": "Create a new test user"},
279
- {"step": 2, "endpoint": "POST /auth/login", "purpose": "Authenticate and receive token"},
280
- {"step": 3, "endpoint": "GET /profile", "purpose": "Fetch authenticated user profile"},
281
- {"step": 4, "endpoint": "PUT /profile", "purpose": "Update user's bio field"}
282
- ],
283
- "suggested_credentials": {
284
- "name": "Tester User",
285
- "username": "tester_user_01",
286
- "email": "tester@example.com",
287
- "password": "SecurePass123!"
288
- }
289
- }
290
- ```
291
-
292
- When the plan is received, the Orchestration Tier applies an **Auto-Merge** algorithm:
293
- 1. Retrieve the current `login_credentials` for the active spec from the database.
294
- 2. If `suggested_credentials` is non-empty, perform a selective merge: for each key-value pair in `suggested_credentials`, update the stored credentials only if the key is absent or the value has changed.
295
- 3. Persist the merged credentials back to `SpecDocument.login_credentials`.
296
-
297
- This means that after the very first test run, the system "remembers" the test user it created, ensuring all future runs skip the registration step.
298
-
299
- #### 3.4.4 Plan Persistence
300
-
301
- The generated `execution_plan` array and the `scenario` text are also persisted directly to the `SpecDocument` record. This allows the frontend to reload the last-used plan when a user returns to a previously-tested API collection, eliminating the need to re-run the planner for unchanged scenarios.
302
-
303
- ---
304
-
305
- ### 3.5 Stage 2: Context-Aware Execution — The API Executor
306
-
307
- The Execution Stage is the most technically intricate component of the system. It bridges the gap between the abstract plan (a step definition like `{"endpoint": "GET /users/{id}"}`) and a concrete, executable HTTP request populated with real data.
308
-
309
- #### 3.5.1 Pre-Execution: On-Demand Schema Resolution Pipeline
310
-
311
- Before any LLM reasoning occurs for a step, the system performs a four-step schema preparation pipeline entirely in Python:
312
-
313
- **Step A — Path Template Matching:**
314
- The endpoint string from the plan (e.g., `"GET /users/usr_abc123"`) is split into method (`GET`) and path (`/users/usr_abc123`). The system must find the corresponding OpenAPI path template (`/users/{id}`) in the spec. A direct dictionary lookup is attempted first. On failure, a regex-based fuzzy matcher is applied:
315
- ```
316
- For each path template P in spec.paths:
317
- pattern = replace_all("{param}" in P with "[^/]+")
318
- pattern = "^" + pattern.rstrip("/") + "/?$"
319
- if regex_match(pattern, actual_path):
320
- matched_template = P; break
321
- ```
322
- This correctly maps runtime paths with substituted values (e.g., `/users/usr_abc123`) back to their OpenAPI template (`/users/{id}`), retrieving the correct schema.
323
-
324
- **Step B — `$ref` Inlining (`resolve_refs`):**
325
- The raw spec for the matched path frequently contains `$ref` pointers that point to shared schema definitions. The `resolve_refs()` function resolves these recursively:
326
- ```
327
- function resolve_refs(obj, full_spec, resolving_set):
328
- if obj is a dict and has "$ref":
329
- ref_path = obj["$ref"] // e.g. "#/components/schemas/User"
330
- if ref_path in resolving_set: // Cycle detection
331
- return {"$ref_loop": ref_path}
332
- target = traverse(full_spec, ref_path.split("/"))
333
- return resolve_refs(target, full_spec, resolving_set ∪ {ref_path})
334
- if obj is a dict:
335
- return {k: resolve_refs(v, ...) for k, v in obj}
336
- if obj is a list:
337
- return [resolve_refs(item, ...) for item in obj]
338
- return obj // Primitive — return as-is
339
- ```
340
- The `_resolving` set passed between recursive calls ensures that circular references (where Schema A references Schema B which references Schema A) do not cause infinite recursion. This is a critical correctness guarantee for real-world enterprise API specs.
341
-
342
- **Step C — Spec Pruning (`prune_spec_for_execution`):**
343
- The fully-resolved schema is then passed through a pruning filter. Keys that are informational but not needed to construct an HTTP request are removed: `description`, `summary`, `example`, `examples`, `format`, `title`, `default`, and `enum_descriptions`. This can reduce the schema size by 40–60% for documentation-heavy specifications like the GitHub API.
344
-
345
- The `responses` sub-tree of each HTTP method is also explicitly removed. Since the executor only needs to *build* the request (not understand its response), the entire response schema section is irrelevant and would consume tokens unnecessarily.
346
-
347
- **Step D — Shorthand Notation Conversion (`shorthand_spec`):**
348
- The pruned, resolved schema is finally converted from verbose JSON Schema format into a compact shorthand string designed to be maximally information-dense for the LLM:
349
-
350
- | Source JSON Schema | Shorthand Output |
351
- |---|---|
352
- | `{"type": "string"}` | `str` |
353
- | `{"type": "integer"}` | `int` |
354
- | `{"type": "string", "format": "date-time"}` | `str:date-time` |
355
- | `{"type": "string", "enum": ["active", "inactive"]}` | `str[active\|inactive]` |
356
- | Object with `required: ["email"]` | `{email*(str),name(str)}` |
357
- | Array of strings | `[str]` |
358
-
359
- The `*` suffix on a field name indicates it is **required**. This notation gives the LLM all the information it needs to construct a valid request body in a fraction of the tokens required by the full JSON Schema representation.
360
-
361
- #### 3.5.2 Step Request Construction via LLM
362
-
363
- The compressed schema and a multi-source context object are provided to `prepare_step_request()` in `api_executor.py`. This function invokes a second LLM call with a carefully engineered prompt.
364
-
365
- **Input Context Hierarchy (Priority Order):**
366
-
367
- The prompt explicitly defines a data source priority, which the LLM is instructed to strictly honour:
368
-
369
- ```
370
- Priority 1 (HIGHEST): Context Variables — values from previous steps
371
- e.g., auth_token, user_id, booking_id
372
-
373
- Priority 2: User Credentials — from the Test Profile
374
- e.g., email, password, static API keys
375
-
376
- Priority 3: Scenario / Spec — logical values derived
377
- e.g., enum values chosen per intent, generated data
378
- ```
379
-
380
- This hierarchy prevents the LLM from "inventing" a new auth token when a valid one already exists in the session context, which would cause an `Unauthorized` error on the target API.
381
-
382
- **Core Execution Rules Encoded in Prompt:**
383
- 1. **Path Variable Substitution**: All URL path templates like `{id}` or `{booking_id}` must be replaced with actual values from the highest-priority context source. The prompt provides an explicit example: `if URL is "/users/{id}" and context has user_id="usr_abc", the final URL must be "/users/usr_abc"`.
384
- 2. **Authorization Header Logic**: The LLM determines the correct authentication scheme (no default is assumed). It selects `"Bearer <token>"`, `"Token <token>"`, `"Basic <base64>"`, or `"Api-Key <key>"` based on the spec's `securitySchemes` definition and the available credential data.
385
- 3. **Content-Type Routing**: The LLM discriminates between `application/json` (places data in `body` field), `application/x-www-form-urlencoded` (places data in `form_data` field), and `multipart/form-data` (places file references in `files` field).
386
- 4. **Enum Adherence**: If a field has an enum constraint (e.g., `status[active|inactive]`), the LLM must select exactly one of the declared values.
387
-
388
- **Output Pydantic Schema (`StepExecutionPlan`):**
389
- ```python
390
- class APIRequest(BaseModel):
391
- method: str # e.g., "POST"
392
- url: str # Fully constructed URL with path params replaced
393
- headers: Dict # e.g., {"Authorization": "Bearer eyJ..."}
394
- query_params: Dict # e.g., {"page": 1, "limit": 10}
395
- form_data: Dict # For application/x-www-form-urlencoded
396
- body: Dict # For application/json
397
- files: Dict[str,str] # {fieldName: fileName} for multipart uploads
398
-
399
- class StepExecutionPlan(BaseModel):
400
- step: int
401
- request: APIRequest
402
- analysis: StepAnalysis # Metadata: which fields came from where
403
- ```
404
-
405
- #### 3.5.3 HTTP Execution via `httpx`
406
-
407
- The resolved `StepExecutionPlan` is translated into a real HTTP request using `httpx.AsyncClient` with a 60-second timeout. Several engineering decisions ensure reliability:
408
-
409
- **URL Sanitization (Anti-Hallucination Guard):**
410
- LLMs sometimes return placeholder URLs (e.g., `https://api.example.com/users/1`) instead of using the user-provided base URL. The system applies a two-check sanitization pass:
411
- ```
412
- if url.startswith("/"):
413
- → Relative URL: prepend base_url
414
- elif parse(url).hostname in PLACEHOLDER_HOSTS:
415
- → Placeholder: extract path + query, rebuild with base_url
416
- elif not url.startswith("http"):
417
- → Schemeless: prepend "https://"
418
- ```
419
- `PLACEHOLDER_HOSTS` is a known-bad set: `{"api.example.com", "example.com", "<base_url>", "your-api.com"}`.
420
-
421
- **Multipart File Attachment:**
422
- When the LLM's output includes a `files` dictionary (e.g., `{"avatar": "profile_photo.jpg"}`), the system:
423
- 1. Queries the `Asset` table by filename to retrieve the file record.
424
- 2. Uses the `StorageProvider` to resolve the full disk path (`storage.get_full_path(asset.file_path)`).
425
- 3. Opens the file in binary mode (`"rb"`).
426
- 4. Attaches it to the `httpx` request as `files={"avatar": ("profile_photo.jpg", f, "image/jpeg")}`.
427
- 5. Closes all opened file handles in a `finally` block, ensuring no resource leaks even on request failure.
428
-
429
- **Response Capture:**
430
- The full response object is captured as `{"status_code": int, "body": str, "headers": dict}` and appended to the `ExecutionHistory` table for the current session and step.
431
-
432
- ---
433
-
434
- ### 3.6 Stage 3: Semantic Response Analysis — The Response Analyzer
435
-
436
- Once an API call has been executed and its raw response is captured, the system performs AI-driven semantic analysis to determine the true meaning of the result.
437
-
438
- #### 3.6.1 Why Semantic Analysis Supersedes Status Codes
439
-
440
- Conventional assertion frameworks evaluate success purely by HTTP status code. This model fails in several well-documented scenarios:
441
- - An API may return `200 OK` with a body of `{"error": "Invalid credentials"}`.
442
- - A rate-limiting response may return `200 OK` with an error payload instead of `429 Too Many Requests`.
443
- - A partial failure in a batch operation may return `207 Multi-Status`, which is neither `200` (full success) nor `400` (failure).
444
-
445
- The semantic analyzer resolves this by providing both the status code *and* the full response body to the LLM, along with the *intent* of the step (the `purpose` string from the execution plan). The LLM is then asked to reason: *"Given that the goal of this step was to authenticate the user, did this response achieve that goal?"*
446
-
447
- #### 3.6.2 Analysis Prompt Design
448
-
449
- The analysis prompt is intentionally kept lean to minimise latency and cost. It supplies:
450
- - The step number, endpoint, and purpose string.
451
- - The HTTP status code.
452
- - The (possibly truncated) response body.
453
-
454
- It requests the following structured JSON output:
455
-
456
- ```json
457
- {
458
- "step": 2,
459
- "status": "success",
460
- "is_otp_required": false,
461
- "otp_field_name": "otp_code",
462
- "is_selection_required": false,
463
- "selection_field_name": null,
464
- "selection_options": null,
465
- "extracted_variables": {
466
- "auth_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
467
- "user_id": "usr_7f3d9a1c",
468
- "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4..."
469
- }
470
- }
471
- ```
472
-
473
- **`status`**: Either `"success"` or `"failure"`, reflecting the LLM's semantic judgment.
474
-
475
- **`is_otp_required`**: A boolean flag. If the response body contains phrases like `"OTP sent"`, `"verification code required"`, or `"enter the code"`, this flag is set to `true`. The `otp_field_name` indicates which request field the OTP should be provided in. The frontend responds to this by displaying an OTP input modal, pausing the execution loop until the user supplies the code, which is then written into the session context for the next step.
476
-
477
- **`is_selection_required`**: A boolean flag introduced to handle APIs that return a **list of entities** requiring user selection before the next step can proceed (e.g., a `GET /buses` enumerating available services before a booking is made). When `true`, the analyzer also populates:
478
- - **`selection_field_name`**: The context key to which the chosen value will be saved (e.g., `"bus_id"`).
479
- - **`selection_options`**: A structured list of `{label, value}` objects extracted from the response body, where `label` is a human-readable string and `value` is the entity identifier to be stored.
480
-
481
- The frontend renders a **Selection Required modal** displaying these options as clickable cards. Upon selection, the chosen value is written to the session context via `POST /context/{session_id}` and becomes immediately available as a **Priority 1** variable for all subsequent Executor calls. This mechanism extends the system's automation capabilities to multi-choice user journeys without requiring hard-coded selection logic.
482
-
483
- **`extracted_variables`**: A dictionary of key-value pairs the LLM identifies as useful for future steps. The LLM uses semantic reasoning — it understands that a field called `"access_token"` or `"token"` in a login response is an authentication credential, and renames it to the generalised key `"auth_token"` for consistent downstream use.
484
-
485
- #### 3.6.3 Response Truncation Algorithm
486
-
487
- Large response bodies (e.g., a list-all-orders endpoint returning 10,000 records) are truncated before being sent to the LLM to maintain constant token cost:
488
-
489
- ```
490
- MAX_SIZE = 1000 characters
491
- if len(body) > MAX_SIZE:
492
- body = body[:500] + "\n... [TRUNCATED] ...\n" + body[-500:]
493
- ```
494
-
495
- This strategy preserves the beginning of the response (which typically contains the response's primary object, such as a token or ID) and the end (which often contains closing structures), giving the analyzer sufficient context to identify success status and extract key variables while discarding verbose middle content.
496
-
497
- #### 3.6.4 Context Variable Persistence
498
-
499
- Extracted variables are committed to the database via the **Context Manager** (`context_manager.py`):
500
-
501
- ```
502
- function set_context_variables(db, session_id, new_variables):
503
- session = db.query(SessionModel).filter(id == session_id).first()
504
- current_context = session.context_variables or {}
505
- current_context.update(new_variables) // Merge (new overwrites old)
506
- session.context_variables = current_context
507
- flag_modified(session, "context_variables") // Force SQLAlchemy change detection
508
- db.commit()
509
- db.refresh(session)
510
- return session.context_variables
511
- ```
512
-
513
- The `update()` operation implements a **last-write-wins** merge strategy: if a variable key already exists in the session context (e.g., an `auth_token` from a login step is refreshed in a subsequent call), the new value replaces the old one. All variables extracted from the previous step become available in the next step's Executor prompt under **Priority 1** — the highest priority data source.
514
-
515
- ---
516
-
517
- ### 3.7 End-to-End Session Lifecycle
518
-
519
- The following sequence diagram illustrates the complete data and control flow for a full test session from spec upload to final analysis:
520
-
521
- ```
522
- User/Frontend Orchestration Layer (FastAPI) Intelligence Tier Data Tier
523
- │ │ │ │
524
- │──POST /session──────────►│ │ │
525
- │◄──{session_id}──────────│ ── INSERT SessionModel ───────────────────────────►│
526
- │ │ │ │
527
- │──POST /upload-spec──────►│ │ │
528
- │ │── parse_spec() ─────────────────────────────────── │
529
- │ │── storage.save(file) ─────────────────────────────►│
530
- │ │── INSERT SpecDocument ────────────────────────────►│
531
- │◄──{spec_id, endpoints}──│ │ │
532
- │ │ │ │
533
- │──POST /plan─────────────►│ │ │
534
- │ │──generate_execution_plan()───►│ │
535
- │ │ │ LLM: plan + creds │
536
- │ │◄──{execution_plan}────────────│ │
537
- │ │── MERGE credentials ──────────────────────────────►│
538
- │ │── UPDATE SpecDocument ────────────────────────────►│
539
- │◄──{execution_plan}──────│ │ │
540
- │ │ │ │
541
- │──[For each step]────────►│ │ │
542
- │──POST /execute-step──────►│ │ │
543
- │ │── resolve_refs(path) ─────────────────────────────►│
544
- │ │── shorthand_spec(schema) │
545
- │ │── get_ai_context(assets) ─────────────────────────►│
546
- │ │──prepare_step_request()──────►│ │
547
- │ │ │ LLM: build request │
548
- │ │◄──{StepExecutionPlan}─────────│ │
549
- │ │── sanitize_url() │ │
550
- │ │── httpx.send(request)──►[Target API Server] │
551
- │ │◄──{status_code, body}───────────────── │
552
- │ │── INSERT ExecutionHistory ────────────────────────►│
553
- │◄──{request, response}───│ │ │
554
- │ │ │ │
555
- │──POST /analyze-response──►│ │ │
556
- │ │──analyze_api_response()──────►│ │
557
- │ │ │ LLM: semantic eval │
558
- │ │◄──{status, vars, otp_flag}────│ │
559
- │ │── set_context_variables() ────────────────────────►│
560
- │ │── UPDATE ExecutionHistory ────────────────────────►│
561
- │◄──{analysis_result}─────│ │ │
562
- │──[Repeat for next step]─►│ │ │
563
- ```
564
-
565
- This lifecycle ensures that the output of every step (specifically, the `extracted_variables`) is durably stored in the database before the next step begins. This guarantees that the system can recover from mid-session interruptions and resume execution without losing context.
566
-
567
- ---
568
-
569
- ### 3.8 Stage 4: Conversational AI Assistance — The Chat Assistant
570
-
571
- The fourth stage of the pipeline introduces an interactive, context-aware AI assistant that gives users natural-language control over the entire test execution workflow. Unlike the first three stages which are automatically triggered as part of a fixed pipeline, the Chat Assistant is a demand-driven, user-initiated interface.
572
-
573
- #### 3.8.1 Architecture and Context Injection
574
-
575
- The Chat Assistant is implemented in `chat_assistant.py` using `ChatMistralAI` with `temperature=0.2` — intentionally slightly higher than the other services to allow for more natural, varied conversational responses while still remaining focused and deterministic.
576
-
577
- On every interaction, the assistant receives a rich, composite context block including:
578
- - **Active Spec Name**: Grounds the assistant in the current testing domain.
579
- - **Execution Plan**: The full list of generated steps, enabling the assistant to reference specific step numbers and endpoints.
580
- - **Session Context Variables**: The live key-value store of extracted runtime values, allowing the assistant to reason about what data has already been captured.
581
- - **Last Step Result**: The most recent HTTP request, response body, status code, and AI analysis.
582
- - **All Step Results Summary**: A compact listing of all executed steps and their status codes in the current session.
583
- - **Chat History**: The last 20 messages from the current `ChatSession`, enabling multi-turn, stateful conversation.
584
-
585
- #### 3.8.2 Structured Action Protocol
586
-
587
- A key architectural decision is that the Chat Assistant does **not** return free-form text to be displayed as-is. Instead, it always returns a **structured JSON action object** that the frontend interprets and acts upon:
588
-
589
- ```json
590
- {
591
- "action": "modify_request",
592
- "message": "I'll update Step 3 to use the admin role and retry it.",
593
- "step": 3,
594
- "changes": {
595
- "body": {"role": "admin"},
596
- "headers": {"X-Custom-Flag": "true"}
597
- }
598
- }
599
- ```
600
-
601
- The complete vocabulary of actions is:
602
-
603
- | Action | Triggered When | Effect |
604
- |---|---|---|
605
- | `execute_step` | User asks to run a specific step | Frontend calls `executeStep(stepDef)` |
606
- | `run_all` | User asks to run all pending steps | Frontend iterates and executes each step |
607
- | `retry_step` | User asks to retry the last or a specific step | Re-runs `executeStep` with original definition |
608
- | `modify_request` | User provides corrected values or new params | Frontend deep-merges `changes` into the step definition, then re-executes |
609
- | `skip_step` | User wants to bypass a step | Frontend marks step as skipped |
610
- | `explain` | User asks why a step failed or what it means | Long-form technical breakdown returned in `explanation` field |
611
- | `generate_tests` | User asks for test assertions | Returns `assertions` list of semantic checks |
612
- | `reply` | General question or clarification | Conversational response, no side effect |
613
-
614
- This action-driven design creates a clear separation between the AI reasoning layer (which action to take and what parameters to use) and the execution layer (which already handles the mechanics of HTTP dispatch, history persistence, and context updating). The frontend acts as a thin orchestration layer that interprets the action and delegates to the appropriate existing function.
615
-
616
- #### 3.8.3 Chat Session Persistence
617
-
618
- Conversation history is persisted in two new database tables: `ChatSession` (one record per conversation thread, named from the first message) and `ChatMessage` (one record per message, with `role` = `"user"` or `"assistant"`). On each API call to `POST /chat`, the system:
619
- 1. Resolves or auto-creates a `ChatSession` record.
620
- 2. Saves the incoming user message to `ChatMessage`.
621
- 3. Loads the last 20 messages as the `chat_history` context.
622
- 4. Invokes `process_message()` in `chat_assistant.py`.
623
- 5. Saves the AI's response as another `ChatMessage` record.
624
-
625
- This design ensures that conversations survive page refreshes, browser restarts, and server restarts — a critical requirement for long-running API debugging sessions.
626
-
627
- #### 3.8.4 Dual Entry Points in the UI
628
-
629
- The Chat Assistant is accessible through two UI entry points:
630
- 1. **Full-Page Chat** (`/chat` route): A dedicated page with a full conversation view, suitable for extended interactive sessions.
631
- 2. **Embedded Panel**: A compact version mounted in a tab of the right sidebar on the Execution Workflow page, allowing the user to interact with the AI without leaving the primary testing workspace.
632
-
633
- Both entry points share the same backend and conversation history, providing a seamless, unified experience.
634
-
635
- ---
636
-
637
-
638
-
639
- ## 4. Implementation
640
-
641
- ### 4.1 Technology Stack
642
-
643
- | Layer | Technology | Version / Notes |
644
- |---|---|---|
645
- | Backend Language | Python | 3.10+ |
646
- | API Framework | FastAPI | ≥ 0.109.0 (async, routers) |
647
- | LLM Orchestration | LangChain | ≥ 0.3.0 |
648
- | LLM Model | Mistral Large | `mistral-large-latest`, temp=0 |
649
- | HTTP Client | httpx | ≥ 0.27.2 (async) |
650
- | ORM | SQLAlchemy | ≥ 2.0.36 |
651
- | Database | PostgreSQL (via Supabase) | + `psycopg2-binary` driver |
652
- | File Storage | Supabase Storage | SDK v2.28.2 |
653
- | Frontend Framework | React + Vite | ES6+, SWC compiler |
654
- | Frontend Styling | Tailwind CSS | 4.x Modern Design |
655
- | ASGI Server | Uvicorn (dev) / Gunicorn (prod) | With standard extras |
656
-
657
- ### 4.2 FastAPI Endpoint Design
658
-
659
- The backend exposes a clear RESTful API surface. Key endpoints include:
660
-
661
- - `POST /upload-spec` — Accepts multipart file upload, auto-detects format, parses, and stores the spec.
662
- - `POST /plan` — Accepts a scenario string, calls the LLM Planner, persists and returns the execution plan.
663
- - `POST /execute-step` — The primary execution endpoint; resolves schema, calls the executor LLM, runs the HTTP request, stores history.
664
- - `POST /analyze-response` — Calls the analyzer LLM, persists extracted variables to session context.
665
- - `GET /context/{session_id}` — Returns the live context variable map for a session.
666
- - `POST /context/{session_id}` — Manually writes a single key-value pair to the session context. Used by the frontend selection modal to save the user-chosen entity ID (e.g., `bus_id`) without triggering a full step re-execution.
667
- - `GET /history` — Returns a full join of `ExecutionHistory` and `SessionModel` records.
668
- - `POST /specs/{spec_id}/credentials` — Saves per-spec test user profiles, supporting partial updates and a `_clear` flag to reset.
669
- - `POST /assets`, `GET /assets` — Manages the Media Hub file lifecycle.
670
- - `POST /chat` — Accepts a user message plus full testing context; returns a structured AI action object and persists the conversation.
671
- - `GET /chat/sessions` — Lists all chat sessions for a given spec or test session.
672
- - `GET /chat/sessions/{id}/messages` — Returns the full message history for a chat session.
673
- - `DELETE /chat/sessions/{id}` — Deletes a chat session and all its messages.
674
-
675
- ### 4.3 Frontend Architecture
676
-
677
- The React frontend implements a sidebar-based navigation structure with the following modules functionally separated:
678
-
679
- - **API Collections**: Displays spec cards fetched from `GET /specs`. Handles drag-and-drop upload and spec deletion.
680
- - **Execution Workflow**: The primary workspace. Manages plan generation state, step card rendering, step execution, and real-time analysis display. Includes the **OTP Modal** (for entering verification codes) and the **Selection Modal** (for choosing from a list of returned entities — see Section 3.6). The right sidebar on this page has two switchable tabs: a **Context Tab** (showing live session variables and credentials) and an **AI Chat Tab** (embedding the `ChatAssistant` component for in-workflow assistance).
681
- - **Test User Profile**: A form-based interface for managing credentials and custom key-value pairs per spec.
682
- - **Execution History**: A read-only audit log with session grouping, color-coded status indicators, and an "Import Session" feature to restore a past session for re-running.
683
- - **Media Hub**: A file management interface with category tabs (Documents, Images, Audio, Video), asset descriptions, tagging, and collection management.
684
- - **AI Chat Assistant**: A full-page conversational assistant (`ChatAssistant.jsx`) that maintains persistent chat sessions, displays the conversation history, and renders AI-suggested actions as interactive UI elements. The `modify_request` action, for example, renders a confirmation card showing the proposed changes before the user approves execution.
685
-
686
- ### 4.4 Storage Abstraction Layer
687
-
688
- The `storage.py` service implements a `StorageProvider` abstraction with two concrete implementations: `LocalStorageProvider` (writes to the `backend/uploads/` directory) and `SupabaseStorageProvider` (uploads to an S3-compatible Supabase bucket). The backend selects the appropriate provider based on the `STORAGE_MODE` environment variable, enabling easy transition between local development and cloud production environments.
689
-
690
- ---
691
-
692
- ## 5. Results and Discussion
693
-
694
- ### 5.1 Evaluation Methodology
695
-
696
- The system was evaluated against three APIs of varying complexity:
697
- 1. A custom-built **User Management API** (12 endpoints): covering registration, authentication, profile management.
698
- 2. A **Transport Management API** (52 endpoints): covering vehicles, routes, bookings, and payments.
699
- 3. A subset of the **GitHub REST API** (OpenAPI spec >12 MB): testing the large-spec lazy-loading strategy.
700
-
701
- ### 5.2 Quantitative Results
702
-
703
- | Metric | User Mgmt API | Transport API | Notes |
704
- |---|---|---|---|
705
- | Plan Generation Accuracy | 100% | 94% | Measured over 20 distinct scenarios each |
706
- | Variable Extraction Precision | 96% | 89% | Variables correctly identified and named |
707
- | Path Template Match Success | 100% | 97% | Regex matcher vs. direct lookup |
708
- | Avg. Plan Generation Latency | 1.8s | 3.1s | Scales with number of endpoints in spec |
709
- | Avg. Step Execution Latency | 2.1s | 2.5s | LLM + network |
710
- | Large Spec Load Time (GitHub) | <0.5s | — | Lazy resolution strategy; only the matched path is resolved |
711
-
712
- The 6% drop in plan accuracy on the Transport API is attributed to ambiguous endpoint naming (multiple PATCH endpoints differing only in path parameters), where the LLM occasionally selected a sub-optimal ordering. Future work involves enriching the planner prompt with endpoint response schemas to improve dependency reasoning.
713
-
714
- ### 5.3 Qualitative Observations
715
-
716
- **Semantic superiority over status-code assertions**: In testing, the system correctly identified 4 cases where a `200 OK` response body contained an error message (e.g., `{"error": "Session already active"}`). A conventional assertion framework would have marked these steps as passed.
717
-
718
- **Zero-touch credential propagation**: In all multi-step tests requiring authentication, the `auth_token` extracted by the response analyzer in the login step was automatically injected into the `Authorization` header of all subsequent steps without any manual mapping.
719
-
720
- **OTP Flow Handling**: The system successfully paused execution and prompted for a user-input OTP code in a 2FA-enabled API scenario, then resumed execution seamlessly upon receiving the code — a workflow not achievable with any static test automation framework.
721
-
722
- **Interactive Selection Handling**: In evaluations using a bus-booking API, a `GET /buses` step returned a list of 12 available bus services. The response analyzer correctly set `is_selection_required=true`, extracted 12 `{label, value}` option pairs, and presented them to the user as a chooser modal. The selected `bus_id` was stored in the session context and automatically used in the subsequent `POST /bookings` step — requiring zero manual intervention or script modification.
723
-
724
- **AI Chat-Driven Request Modification**: In a scenario where a `POST /orders` step failed with `422 Unprocessable Entity`, the user typed *"Change the quantity to 2 and retry step 3"* in the Chat Assistant. The assistant correctly identified the step, generated a `modify_request` action with `{"body": {"quantity": 2}}`, and the frontend re-executed the modified step — which succeeded. This demonstrates the system's ability to close the diagnostic-correction-retry loop entirely within the conversational interface.
725
-
726
- **Large Spec Scalability**: The lazy `$ref` resolution strategy allowed the system to process the 12 MB GitHub OpenAPI spec without any memory issues or context window violations. The planner received only the simplified endpoint list (a few kilobytes), while the executor received only the single, resolved path schema for each step.
727
-
728
- ### 5.4 Limitations
729
-
730
- - **LLM Hallucination Risk**: At `temperature=0`, the LLM is deterministic but can still hallucinate parameter names or values not present in the spec. The `analysis` field in the step executor output (tracking `generated_test_data`) makes this observable.
731
- - **Latency**: Each step incurs 1.5–3.5 seconds of LLM latency, making it unsuitable for high-frequency regression testing. However, it excels for exploratory and integration testing.
732
- - **Context Window in Planning**: For very large APIs (>500 endpoints), even the simplified endpoint list may approach model context limits. API chunking or hierarchical planning would be required.
733
-
734
- ---
735
-
736
- ## 6. Conclusion
737
-
738
- ### 6.1 Summary
739
-
740
- This paper presented the architecture, methodology, and evaluation of an AI-powered API Testing Assistant. By combining a two-level OpenAPI parsing strategy with a four-stage LLM pipeline — Strategic Planning, Context-Aware Execution, Semantic Response Analysis, and Conversational AI Assistance — the system achieves robust, intent-driven API testing that significantly surpasses the capabilities of conventional tools.
741
-
742
- The key contributions are:
743
- 1. A **lazy `$ref` resolution algorithm** that enables efficient handling of large-scale API specifications.
744
- 2. A **shorthand schema notation** that reduces LLM prompt size by up to 60% while preserving semantic completeness.
745
- 3. A **session-scoped context manager** that propagates dynamic variables across dependent API calls without user intervention.
746
- 4. A **semantic response analyzer** with **interactive selection detection** — identifying when a response requires human disambiguation between multiple entities and presenting a structured chooser UI, writing the selection back to the context without re-execution.
747
- 5. A **persistent, context-aware AI Chat Assistant** that allows users to control, diagnose, modify, and retry test steps through natural language, with full conversation history persisted across sessions.
748
-
749
- ### 6.2 Future Work
750
-
751
- - **GraphQL Support**: Extending the spec parser to handle GraphQL schemas and SDL files.
752
- - **Autonomous Error Recovery**: Enabling the AI Chat Assistant to automatically diagnose a failed step, adjust the request parameters, and retry — forming a fully closed-loop execution agent without requiring user confirmation for straightforward fixes.
753
- - **Parallel Step Execution**: For steps with no inter-dependencies, executing them concurrently to reduce test session time.
754
- - **Local LLM Support**: Integrating Ollama-compatible models (e.g., Llama-3, Mistral-7B) for privacy-sensitive enterprise deployments.
755
- - **CI/CD Pipeline Integration**: A headless CLI mode to run scenario files as part of automated deployment pipelines.
756
- - **Multi-Turn Conversation Planning**: Extending the Chat Assistant to refine and regenerate execution plans interactively (e.g., *"Add a step to delete the user at the end"*), enabling dynamic scenario editing without restarting the session.
757
-
758
- ---
759
-
760
- ## 7. References
761
-
762
- [1] Postman, Inc. (2023). *State of the API Report 2023*. Postman, Inc.
763
-
764
- [2] OpenAPI Initiative. (2021). *OpenAPI Specification 3.1.0*. Linux Foundation. https://spec.openapis.org/oas/v3.1.0
765
-
766
- [3] Chen, M., Tworek, J., Jun, H., Yuan, Q., Pinto, H. P. D. O., Kaplan, J., ... & Zaremba, W. (2021). Evaluating large language models trained on code. *arXiv preprint arXiv:2107.03374*.
767
-
768
- [4] Schäfer, M., Nadi, S., Eghbali, A., & Mezini, M. (2023). An empirical evaluation of using large language models for automated unit test generation. *IEEE Transactions on Software Engineering*, 50(1), 85–105.
769
-
770
- [5] Mistral AI Team. (2024). *Mistral-7B*. Technical Report, Mistral AI. https://mistral.ai/news/announcing-mistral-7b
771
-
772
- [6] Chase, H. et al. (2023). *LangChain: Building applications with LLMs through composability* [Software]. https://github.com/langchain-ai/langchain
773
-
774
- [7] Bhandari, G., Bhatt, A., & Lal, R. (2023). A study of LLM-generated test cases for REST API testing. *Proceedings of the 2023 IEEE International Conference on Software Testing*.
775
-
776
- [8] Jiang, S., Wang, X., & Zhao, L. (2024). Natural Language to API: A Cross-Domain Translation Approach. *Journal of Systems and Software*, 198, 111–124.
777
-
778
- [9] Lorikeet Labs. (2022). *Schemathesis: A modern API testing tool for web applications*. https://github.com/schemathesis/schemathesis
779
-
780
- [10] Tiark, R., Massacci, F., & Brosscombe, D. (2023). Large Language Models for Software Testing: A Survey. *IEEE Transactions on Software Engineering*, 49(8), 4012–4032.
781
-
782
- [11] FastAPI. (2024). *FastAPI Documentation: Modern, fast (high-performance), web framework for building APIs*. https://fastapi.tiangolo.com/
783
-
784
- [12] Supabase, Inc. (2024). *Supabase: The Open Source Firebase Alternative*. https://supabase.com/docs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documents/UI_DOCUMENTATION.md DELETED
@@ -1,109 +0,0 @@
1
- # API Testing Assistant - UI Documentation
2
-
3
- This document provides a comprehensive overview of the User Interface (UI) functionality for the API Testing Assistant. The application is designed to help users interact with, test, and analyze APIs through an AI-driven interface.
4
-
5
- ## 1. Activity Bar (Sidebar)
6
- The left sidebar provides global navigation across different modules of the application.
7
-
8
- - **API Collections**: (`CollectionsPage.jsx`) Browse, upload, and manage OpenAPI/Swagger/Postman specifications.
9
- - **Execution Workflow**: (Main `App.jsx` workspace) The core interface for defining scenarios and executing steps.
10
- - **Test User Profile**: (`ProfilePage.jsx`) Manage credentials and variables for the active collection.
11
- - **Execution History**: (`HistoryPage.jsx`) View past test sessions and their detailed logs.
12
- - **Media Hub**: (`MediaHubPage.jsx`) Manage assets (images, audio, video, documents) for API testing.
13
- - **AI Chat Assistant**: (`ChatAssistant.jsx`) Full-page AI context-aware interaction.
14
- - **System Settings**: (`SettingsPage.jsx`) Global application configuration.
15
-
16
- ---
17
-
18
- ## 2. API Collections Module
19
- This module handles the management of API definitions.
20
-
21
- - **Upload Spec**: Users can upload `.json`, `.yaml`, or `.yml` files containing OpenAPI/Swagger specifications.
22
- - **Search & Filter**: Quickly find a specific collection by name.
23
- - **Selection**: Clicking a collection card makes it the "Active Spec," enabling testing and profile management for that specific API.
24
- - **Deletion**: Remove unwanted specifications from the system.
25
-
26
- ---
27
-
28
- ## 3. Execution Workflow (Testing)
29
- This is the primary workspace for API interaction.
30
-
31
- ### Header & Configuration
32
- - **Active Spec Name**: Displays the name of the currently selected API collection.
33
- - **Base URL Input**: Allow users to set or update the target environment (e.g., `https://api.example.com`). This value is saved per collection.
34
- - **Token Usage Tracker**: Displays real-time LLM token consumption for both plan generation and current scenario execution.
35
-
36
- ### Scenario Definition & Planning
37
- - **Chat Input**: A natural language input area where users describe what they want to test (e.g., "Login as a user, fetch their profile, and update their bio").
38
- - **AI Plan Generation**: Pressing "Send" or Enter uses an LLM to parse the API spec and the user's intent to generate a multi-step execution plan.
39
-
40
- ### Step Execution & Results
41
- - **Step Overview**: Each generated step shows the target endpoint, HTTP method, and a summary of its purpose.
42
- - **Execution**: A "Execute" button triggers the individual API call.
43
- - **AI Analysis**: After execution, the AI analyzes the response to determine success or failure, provides a summary, and automatically extracts key variables for subsequent steps.
44
- - **Technical Inspection**: A detailed breakdown showing the raw **Request** (URL, Headers, Body, Params) and **Response** (Status Code, JSON body).
45
- - **OTP Handling**: If an API requires a verification code (OTP), a modal prompt appears to allow the user to input the code, which is then saved to the session context.
46
- - **Interactive Selection**: If an API returns a list of items that the user must choose between (e.g., a list of buses, products, or flights), a **Selection Required** modal automatically appears. The AI extracts the available options and presents them as clickable cards. The selected value (e.g., a `bus_id`) is saved to the session context and used in subsequent steps automatically.
47
-
48
- ---
49
-
50
- ## 4. Test User Profile
51
- Profiles are isolated per API collection to maintain clean testing environments.
52
-
53
- - **Core Authentication**: Fields for common credentials like Full Name, Email/Username, Password, and Static Access Tokens.
54
- - **Custom Fields (KV Map)**: Users can define arbitrary key-value pairs (e.g., `account_id`, `special_flag`) that the AI can use during planning and execution.
55
- - **Sensitive Data Masking**: Passwords and tokens are masked in the UI for security.
56
-
57
- ---
58
-
59
- ## 5. Right Sidebar: Context & Variables
60
- A persistent panel (toggleable) on the Testing Workflow page. It has two tabs:
61
-
62
- ### Context Tab
63
- - **Session Extracted Variables**: Displays values captured from previous steps' responses (e.g., `userId`, `authToken`).
64
- - **Test Credentials**: Live view of current profile data being used in the session.
65
- - **Refresh Control**: Manual trigger to update the local context from the backend state.
66
-
67
- ### AI Chat Tab
68
- - An embedded, compact version of the AI Chat Assistant that lives directly beside the execution workflow.
69
- - Provides the same AI capabilities without leaving the testing workspace.
70
- - Receives full context from the current session (all step results, plan, extracted variables).
71
- - Can trigger step executions or request modifications from within the panel.
72
-
73
- ---
74
-
75
- ## 6. Execution History
76
- A permanent log of all test activities.
77
-
78
- - **Session Grouping**: Individual API calls are grouped by their parent test scenario and session ID.
79
- - **Status Indicators**: Visual cues (Success/Failure) for each session and step.
80
- - **Restoration**: An "Import" feature allows users to load a past session back into the main Testing workspace to re-run or continue work.
81
- - **Management**: Search through history by scenario or spec name, delete individual sessions, or clear the entire history.
82
-
83
- ---
84
-
85
- ## 7. Media Hub
86
- A central repository for managing test data files.
87
-
88
- - **Asset Categorization**: Automatically categorizes files into Documents, Images, Audio, and Video.
89
- - **Collection-Based Organization**: Assets can be grouped into custom media collections.
90
- - **AI Descriptions**: Users can add semantic descriptions to files, helping the AI understand which assets to use for specific API requirements (e.g., "This is a sample PDF for identity verification").
91
- - **Search & Tagging**: Tag assets for even faster retrieval and management.
92
-
93
- ---
94
-
95
- ## 8. AI Chat Assistant
96
- A dedicated full-page AI assistant (`/chat` page) designed for advanced, context-aware interaction with the testing workflow.
97
-
98
- - **Full Testing Context**: The AI receives the current execution plan, all step results, session variables, and the active spec name, allowing it to give highly relevant assistance.
99
- - **Persistent Chat Sessions**: Conversations are saved to the database and persist across page refreshes.
100
- - **Structured Actions**: The AI returns structured actions that the frontend can act on:
101
- - `execute_step` — Triggers execution of a specific step.
102
- - `run_all` — Runs all steps in the plan sequentially.
103
- - `modify_request` — AI suggests changes to a request's body/params/headers before re-execution. The user confirms, and the modified step is executed.
104
- - `retry_step` — Re-runs the last failed step.
105
- - `explain` — Provides a detailed technical breakdown of an error or result.
106
- - `generate_tests` — Generates a list of practical test assertions relevant to the current response.
107
- - `reply` — A general conversational answer with no side effect.
108
- - **Chat History Side Panel**: Previous messages in the active session are visible, making the interaction feel like a live conversation.
109
- - **Dual Entry Points**: Accessible as a full page via the activity bar, or as an embedded panel in the right sidebar of the Testing Workflow.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openapi.yaml DELETED
@@ -1,1517 +0,0 @@
1
- openapi: "3.0.3"
2
-
3
- info:
4
- title: EarWax CRM Mobile API
5
- version: "1"
6
- description: |
7
- JWT-authenticated REST API for the React Native mobile app.
8
- All protected routes require `Authorization: Bearer <access_token>`.
9
-
10
- **URL mapping:** All endpoints share one PHP entry point. The semantic paths
11
- in this spec (e.g. `/auth/login`) map to the `?action=` query parameter on
12
- the real server URL. Always append `&v=1` (optional for v1, required for
13
- future versions).
14
-
15
- **Example:** `POST https://yourcrm.com/crm/backend/mobile_api.php?action=login&v=1`
16
-
17
- **Error codes** returned in `error_code` on every failure response:
18
-
19
- | Code | Meaning |
20
- |------|---------|
21
- | `ERR_AUTH` | Invalid or expired token / wrong credentials |
22
- | `ERR_FORBIDDEN` | Authenticated but role is insufficient |
23
- | `ERR_NOT_FOUND` | Resource does not exist |
24
- | `ERR_VALIDATION` | Missing or invalid input field |
25
- | `ERR_CONFLICT` | Uniqueness constraint violated |
26
- | `ERR_METHOD` | Wrong HTTP method for this action |
27
- | `ERR_VERSION` | Unsupported API version |
28
- | `ERR_RATE_LIMIT` | Too many requests (100 / 60 s per IP) |
29
- | `ERR_DB` | Database error |
30
- | `ERR_SERVER` | Unexpected server error |
31
-
32
- servers:
33
- - url: https://yourcrm.com/crm/backend/mobile_api.php
34
- description: "Production — every path maps to ?action=<action>&v=1"
35
-
36
- security:
37
- - bearerAuth: []
38
-
39
- tags:
40
- - { name: Auth, description: Authentication and token management }
41
- - { name: Leads, description: Lead CRUD }
42
- - { name: Appointments, description: Appointment CRUD }
43
- - { name: Courses, description: Course catalogue (read-only) }
44
- - { name: Users, description: CRM user management (admin only) }
45
- - { name: Stats, description: Dashboard and analytics }
46
- - { name: Search, description: Cross-entity search }
47
- - { name: Notifications, description: Push notification device registration }
48
- - { name: Invoice, description: PDF invoice generation }
49
-
50
- # ═══════════════════════════════════════════════════════════════════════════════
51
- # Reusable components
52
- # ═══════════════════════════════════════════════════════════════════════════════
53
-
54
- components:
55
-
56
- securitySchemes:
57
- bearerAuth:
58
- type: http
59
- scheme: bearer
60
- bearerFormat: JWT
61
-
62
- # ── Reusable parameters ────────────────────────────────────────────────────
63
-
64
- parameters:
65
-
66
- ApiVersion:
67
- name: v
68
- in: query
69
- description: "API version (only 1 is supported)"
70
- schema: { type: integer, enum: [1], default: 1 }
71
-
72
- PageParam:
73
- name: page
74
- in: query
75
- schema: { type: integer, minimum: 1, default: 1 }
76
-
77
- IdQuery:
78
- name: id
79
- in: query
80
- required: true
81
- schema: { type: integer }
82
-
83
- # ── Schemas ────────────────────────────────────────────────────────────────
84
-
85
- schemas:
86
-
87
- # ── Response envelopes ───────────────────────────────────────────────────
88
-
89
- SuccessEnvelope:
90
- type: object
91
- properties:
92
- success: { type: boolean, example: true }
93
- message: { type: string }
94
- data: { type: object }
95
-
96
- ErrorEnvelope:
97
- type: object
98
- properties:
99
- success:
100
- type: boolean
101
- example: false
102
- message:
103
- type: string
104
- example: "Lead not found."
105
- error_code:
106
- type: string
107
- enum:
108
- - ERR_AUTH
109
- - ERR_FORBIDDEN
110
- - ERR_NOT_FOUND
111
- - ERR_VALIDATION
112
- - ERR_CONFLICT
113
- - ERR_METHOD
114
- - ERR_VERSION
115
- - ERR_RATE_LIMIT
116
- - ERR_DB
117
- - ERR_SERVER
118
- - ERR_UNKNOWN
119
- data:
120
- type: object
121
-
122
- # ── Domain entities ──────────────────────────────────────────────────────
123
-
124
- Lead:
125
- type: object
126
- properties:
127
- id: { type: integer, readOnly: true }
128
- first_name: { type: string }
129
- last_name: { type: string }
130
- email: { type: string, format: email }
131
- phone: { type: string }
132
- gender: { type: string }
133
- preferred_name: { type: string }
134
- qualification: { type: string }
135
- experience: { type: string }
136
- device_type: { type: string }
137
- source: { type: string }
138
- status:
139
- type: string
140
- enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed]
141
- address_line1: { type: string }
142
- address_line2: { type: string }
143
- city: { type: string }
144
- county: { type: string }
145
- postcode: { type: string }
146
- country: { type: string }
147
- shipping_address_line1: { type: string }
148
- shipping_address_line2: { type: string }
149
- shipping_city: { type: string }
150
- shipping_county: { type: string }
151
- shipping_postcode: { type: string }
152
- shipping_country: { type: string }
153
- shipping_phone: { type: string }
154
- notes: { type: string }
155
- archived: { type: integer, enum: [0, 1] }
156
- lead_date: { type: string, format: date }
157
- created_at: { type: string, format: date-time, readOnly: true }
158
- updated_at: { type: string, format: date-time, readOnly: true }
159
- appointment_count:
160
- type: integer
161
- readOnly: true
162
- description: "Present on list responses only"
163
-
164
- Appointment:
165
- type: object
166
- properties:
167
- id: { type: integer, readOnly: true }
168
- appointment_ref: { type: string, readOnly: true, example: "APT-A3B2C1" }
169
- lead_id: { type: integer }
170
- course_id: { type: integer, nullable: true }
171
- appointment_date: { type: string, format: date }
172
- appointment_time: { type: string, example: "09:00" }
173
- duration: { type: string, example: "1 day" }
174
- status:
175
- type: string
176
- enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show]
177
- amount_paid: { type: number, format: float }
178
- transaction_fee: { type: number, format: float }
179
- payment_method: { type: string }
180
- payment_ref: { type: string }
181
- payment_date: { type: string, format: date, nullable: true }
182
- training_location: { type: string, nullable: true }
183
- training_address: { type: string, nullable: true }
184
- course_type: { type: string, nullable: true }
185
- course_name:
186
- type: string
187
- readOnly: true
188
- description: "Resolved from course_id or woo_product_name"
189
- notes: { type: string }
190
- archived: { type: integer, enum: [0, 1] }
191
- status_changed_at: { type: string, format: date-time, readOnly: true, nullable: true }
192
- created_at: { type: string, format: date-time, readOnly: true }
193
- updated_at: { type: string, format: date-time, readOnly: true }
194
-
195
- AppointmentSummary:
196
- description: "Lightweight row returned in list and dashboard responses"
197
- type: object
198
- properties:
199
- id: { type: integer }
200
- appointment_ref: { type: string }
201
- appointment_date: { type: string, format: date }
202
- appointment_time: { type: string }
203
- status: { type: string }
204
- amount_paid: { type: number }
205
- payment_method: { type: string }
206
- training_location: { type: string }
207
- course_type: { type: string }
208
- duration: { type: string }
209
- course_name: { type: string }
210
- lead_id: { type: integer }
211
- student_name: { type: string }
212
- student_email: { type: string }
213
- student_phone: { type: string }
214
-
215
- Course:
216
- type: object
217
- properties:
218
- id: { type: integer }
219
- name: { type: string }
220
- location: { type: string }
221
- course_type: { type: string }
222
- price: { type: number }
223
- duration: { type: string }
224
- max_capacity: { type: integer }
225
- description: { type: string }
226
-
227
- User:
228
- type: object
229
- properties:
230
- id: { type: integer, readOnly: true }
231
- username: { type: string }
232
- full_name: { type: string }
233
- email: { type: string, format: email, nullable: true }
234
- role: { type: string, enum: [admin, staff] }
235
- is_active: { type: boolean }
236
- last_login: { type: string, format: date-time, readOnly: true, nullable: true }
237
-
238
- ActivityEntry:
239
- type: object
240
- properties:
241
- action: { type: string }
242
- description: { type: string }
243
- created_by: { type: string }
244
- created_at: { type: string, format: date-time }
245
-
246
- SearchResult:
247
- type: object
248
- properties:
249
- id: { type: integer }
250
- first_name: { type: string }
251
- last_name: { type: string }
252
- email: { type: string }
253
- phone: { type: string }
254
- status: { type: string }
255
- city: { type: string }
256
- created_at: { type: string, format: date-time }
257
- appointment_count:{ type: integer }
258
-
259
- TokenPair:
260
- type: object
261
- properties:
262
- access_token: { type: string }
263
- refresh_token: { type: string }
264
- expires_in: { type: integer, description: "Access token TTL in seconds (3600)" }
265
- refresh_expires_in: { type: integer, description: "Refresh token TTL in seconds (2592000)" }
266
-
267
- # ── Pagination ───────────────────────────────────────────────────────────
268
-
269
- Pagination:
270
- type: object
271
- properties:
272
- total: { type: integer }
273
- page: { type: integer }
274
- per_page: { type: integer, example: 20 }
275
- total_pages: { type: integer }
276
-
277
- PaginatedLeads:
278
- allOf:
279
- - $ref: '#/components/schemas/Pagination'
280
- - type: object
281
- properties:
282
- leads:
283
- type: array
284
- items: { $ref: '#/components/schemas/Lead' }
285
-
286
- PaginatedAppointments:
287
- allOf:
288
- - $ref: '#/components/schemas/Pagination'
289
- - type: object
290
- properties:
291
- appointments:
292
- type: array
293
- items: { $ref: '#/components/schemas/AppointmentSummary' }
294
-
295
- # ── Composite response data ──────────────────────────────────────────────
296
-
297
- LeadDetail:
298
- type: object
299
- properties:
300
- lead:
301
- $ref: '#/components/schemas/Lead'
302
- appointments:
303
- type: array
304
- items: { $ref: '#/components/schemas/Appointment' }
305
- activity:
306
- type: array
307
- items: { $ref: '#/components/schemas/ActivityEntry' }
308
-
309
- AppointmentDetail:
310
- type: object
311
- properties:
312
- appointment:
313
- allOf:
314
- - $ref: '#/components/schemas/Appointment'
315
- - type: object
316
- description: "Includes joined lead fields and course_location"
317
- properties:
318
- course_location: { type: string }
319
- first_name: { type: string }
320
- last_name: { type: string }
321
- email: { type: string }
322
- phone: { type: string }
323
- gender: { type: string }
324
- qualification: { type: string }
325
- activity:
326
- type: array
327
- items: { $ref: '#/components/schemas/ActivityEntry' }
328
-
329
- DashboardStats:
330
- type: object
331
- properties:
332
- total_leads: { type: integer }
333
- enrolled: { type: integer }
334
- new_today: { type: integer }
335
- upcoming_appointments: { type: integer }
336
- today_appointments: { type: integer }
337
- total_revenue: { type: number, description: "Admin only" }
338
- month_revenue: { type: number, description: "Admin only" }
339
-
340
- DashboardData:
341
- type: object
342
- properties:
343
- stats:
344
- $ref: '#/components/schemas/DashboardStats'
345
- upcoming:
346
- type: array
347
- description: "Next 5 upcoming appointments"
348
- items: { $ref: '#/components/schemas/AppointmentSummary' }
349
- recent_leads:
350
- type: array
351
- description: "5 most recently created leads"
352
- items: { $ref: '#/components/schemas/Lead' }
353
-
354
- RevenueByMonth:
355
- type: object
356
- properties:
357
- month: { type: string, example: "2026-01" }
358
- bookings: { type: integer }
359
- revenue: { type: number }
360
-
361
- StatusCount:
362
- type: object
363
- properties:
364
- status: { type: string }
365
- count: { type: integer }
366
-
367
- SourceCount:
368
- type: object
369
- properties:
370
- source: { type: string }
371
- count: { type: integer }
372
-
373
- StatsData:
374
- type: object
375
- properties:
376
- revenue_by_month:
377
- type: array
378
- items: { $ref: '#/components/schemas/RevenueByMonth' }
379
- lead_breakdown:
380
- type: array
381
- items: { $ref: '#/components/schemas/StatusCount' }
382
- appointment_breakdown:
383
- type: array
384
- items: { $ref: '#/components/schemas/StatusCount' }
385
- top_sources:
386
- type: array
387
- items: { $ref: '#/components/schemas/SourceCount' }
388
- filters:
389
- type: object
390
- properties:
391
- date_from: { type: string, format: date, nullable: true }
392
- date_to: { type: string, format: date, nullable: true }
393
-
394
- # ── Reusable responses ──────────────────────────────────��──────────────────
395
-
396
- responses:
397
-
398
- Unauthorised:
399
- description: Invalid or expired access token
400
- content:
401
- application/json:
402
- schema: { $ref: '#/components/schemas/ErrorEnvelope' }
403
- example: { success: false, message: "Unauthorised — invalid or expired token.", error_code: ERR_AUTH, data: {} }
404
-
405
- Forbidden:
406
- description: Authenticated but role is insufficient (admin required)
407
- content:
408
- application/json:
409
- schema: { $ref: '#/components/schemas/ErrorEnvelope' }
410
- example: { success: false, message: "Admin access required.", error_code: ERR_FORBIDDEN, data: {} }
411
-
412
- NotFound:
413
- description: Resource does not exist
414
- content:
415
- application/json:
416
- schema: { $ref: '#/components/schemas/ErrorEnvelope' }
417
- example: { success: false, message: "Lead not found.", error_code: ERR_NOT_FOUND, data: {} }
418
-
419
- ValidationError:
420
- description: Missing or invalid input field
421
- content:
422
- application/json:
423
- schema: { $ref: '#/components/schemas/ErrorEnvelope' }
424
- example: { success: false, message: "email is required.", error_code: ERR_VALIDATION, data: {} }
425
-
426
- Conflict:
427
- description: Uniqueness constraint violated (e.g. duplicate username)
428
- content:
429
- application/json:
430
- schema: { $ref: '#/components/schemas/ErrorEnvelope' }
431
- example: { success: false, message: "Username already exists.", error_code: ERR_CONFLICT, data: {} }
432
-
433
- SimpleOk:
434
- description: Action completed successfully
435
- content:
436
- application/json:
437
- schema:
438
- type: object
439
- properties:
440
- success: { type: boolean, example: true }
441
- message: { type: string }
442
- data: { type: object }
443
-
444
- # ═══════════════════════════════════════════════════════════════════════════════
445
- # Paths
446
- # ═══════════════════════════════════════════════════════════════════════════════
447
-
448
- paths:
449
-
450
- # ── Auth ───────────────────────────────────────────────────────────────────
451
-
452
- /auth/login:
453
- post:
454
- operationId: login
455
- summary: Authenticate and receive token pair
456
- description: |
457
- Returns a 1-hour access token and a 30-day refresh token.
458
- **Real URL:** `POST ?action=login`
459
- security: []
460
- tags: [Auth]
461
- parameters:
462
- - name: action
463
- in: query
464
- required: true
465
- schema: { type: string, enum: [login] }
466
- - $ref: '#/components/parameters/ApiVersion'
467
- requestBody:
468
- required: true
469
- content:
470
- application/json:
471
- schema:
472
- type: object
473
- required: [username, password]
474
- properties:
475
- username: { type: string, example: exceladmin }
476
- password: { type: string, format: password }
477
- responses:
478
- "200":
479
- description: Login successful
480
- content:
481
- application/json:
482
- schema:
483
- type: object
484
- properties:
485
- success: { type: boolean, example: true }
486
- message: { type: string }
487
- data:
488
- allOf:
489
- - $ref: '#/components/schemas/TokenPair'
490
- - type: object
491
- properties:
492
- user: { $ref: '#/components/schemas/User' }
493
- "400": { $ref: '#/components/responses/ValidationError' }
494
- "401": { $ref: '#/components/responses/Unauthorised' }
495
-
496
- /auth/refresh:
497
- post:
498
- operationId: refreshToken
499
- summary: Rotate refresh token and issue new access token
500
- description: |
501
- The old refresh token is invalidated on use (rotation).
502
- **Real URL:** `POST ?action=refresh`
503
- security: []
504
- tags: [Auth]
505
- parameters:
506
- - name: action
507
- in: query
508
- required: true
509
- schema: { type: string, enum: [refresh] }
510
- - $ref: '#/components/parameters/ApiVersion'
511
- requestBody:
512
- required: true
513
- content:
514
- application/json:
515
- schema:
516
- type: object
517
- required: [refresh_token]
518
- properties:
519
- refresh_token: { type: string }
520
- responses:
521
- "200":
522
- description: New token pair issued
523
- content:
524
- application/json:
525
- schema:
526
- type: object
527
- properties:
528
- success: { type: boolean, example: true }
529
- message: { type: string }
530
- data: { $ref: '#/components/schemas/TokenPair' }
531
- "401": { $ref: '#/components/responses/Unauthorised' }
532
-
533
- /auth/logout:
534
- post:
535
- operationId: logout
536
- summary: Invalidate all tokens for this user
537
- description: |
538
- Increments `token_version`, immediately invalidating all active access tokens
539
- on all devices. Pass `push_token` to also remove that device's push registration;
540
- omit to remove all push tokens for this user.
541
- **Real URL:** `POST ?action=logout`
542
- tags: [Auth]
543
- parameters:
544
- - name: action
545
- in: query
546
- required: true
547
- schema: { type: string, enum: [logout] }
548
- - $ref: '#/components/parameters/ApiVersion'
549
- requestBody:
550
- required: false
551
- content:
552
- application/json:
553
- schema:
554
- type: object
555
- properties:
556
- push_token:
557
- type: string
558
- description: "If provided, removes only this device token; otherwise removes all."
559
- responses:
560
- "200": { $ref: '#/components/responses/SimpleOk' }
561
- "401": { $ref: '#/components/responses/Unauthorised' }
562
-
563
- /auth/me:
564
- get:
565
- operationId: getMe
566
- summary: Get current user profile
567
- description: "**Real URL:** `GET ?action=me`"
568
- tags: [Auth]
569
- parameters:
570
- - name: action
571
- in: query
572
- required: true
573
- schema: { type: string, enum: [me] }
574
- - $ref: '#/components/parameters/ApiVersion'
575
- responses:
576
- "200":
577
- description: Current user profile
578
- content:
579
- application/json:
580
- schema:
581
- type: object
582
- properties:
583
- success: { type: boolean, example: true }
584
- message: { type: string }
585
- data:
586
- type: object
587
- properties:
588
- user: { $ref: '#/components/schemas/User' }
589
- "401": { $ref: '#/components/responses/Unauthorised' }
590
-
591
- /auth/update-profile:
592
- post:
593
- operationId: updateProfile
594
- summary: Update own profile (patch-style)
595
- description: |
596
- Only send fields you want to change; omitted fields are left as-is.
597
- **Real URL:** `POST ?action=update_profile`
598
- tags: [Auth]
599
- parameters:
600
- - name: action
601
- in: query
602
- required: true
603
- schema: { type: string, enum: [update_profile] }
604
- - $ref: '#/components/parameters/ApiVersion'
605
- requestBody:
606
- required: true
607
- content:
608
- application/json:
609
- schema:
610
- type: object
611
- minProperties: 1
612
- properties:
613
- full_name: { type: string }
614
- email: { type: string, format: email }
615
- username: { type: string }
616
- responses:
617
- "200":
618
- description: Profile updated; returns updated user object
619
- content:
620
- application/json:
621
- schema:
622
- type: object
623
- properties:
624
- success: { type: boolean, example: true }
625
- message: { type: string }
626
- data:
627
- type: object
628
- properties:
629
- user: { $ref: '#/components/schemas/User' }
630
- "400": { $ref: '#/components/responses/ValidationError' }
631
- "401": { $ref: '#/components/responses/Unauthorised' }
632
- "409": { $ref: '#/components/responses/Conflict' }
633
-
634
- /auth/change-password:
635
- post:
636
- operationId: changePassword
637
- summary: Change own password
638
- description: |
639
- Invalidates all tokens on all devices after a successful change. The user
640
- must log in again.
641
- **Real URL:** `POST ?action=change_password`
642
- tags: [Auth]
643
- parameters:
644
- - name: action
645
- in: query
646
- required: true
647
- schema: { type: string, enum: [change_password] }
648
- - $ref: '#/components/parameters/ApiVersion'
649
- requestBody:
650
- required: true
651
- content:
652
- application/json:
653
- schema:
654
- type: object
655
- required: [current_password, new_password]
656
- properties:
657
- current_password: { type: string, format: password }
658
- new_password: { type: string, format: password, minLength: 8 }
659
- responses:
660
- "200": { $ref: '#/components/responses/SimpleOk' }
661
- "400": { $ref: '#/components/responses/ValidationError' }
662
- "401": { $ref: '#/components/responses/Unauthorised' }
663
-
664
- # ── Leads ──────────────────────────────────────────────────────────────────
665
-
666
- /leads:
667
- get:
668
- operationId: listLeads
669
- summary: Paginated lead list
670
- description: "**Real URL:** `GET ?action=leads`"
671
- tags: [Leads]
672
- parameters:
673
- - name: action
674
- in: query
675
- required: true
676
- schema: { type: string, enum: [leads] }
677
- - $ref: '#/components/parameters/ApiVersion'
678
- - $ref: '#/components/parameters/PageParam'
679
- - name: status
680
- in: query
681
- schema: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed] }
682
- - name: search
683
- in: query
684
- schema: { type: string, description: "Matches first_name, last_name, email, or phone" }
685
- - name: sort
686
- in: query
687
- schema: { type: string, enum: [created_at, lead_date, first_name, status], default: created_at }
688
- - name: dir
689
- in: query
690
- schema: { type: string, enum: [asc, desc], default: desc }
691
- responses:
692
- "200":
693
- description: Paginated lead list
694
- content:
695
- application/json:
696
- schema:
697
- type: object
698
- properties:
699
- success: { type: boolean, example: true }
700
- message: { type: string }
701
- data: { $ref: '#/components/schemas/PaginatedLeads' }
702
- "401": { $ref: '#/components/responses/Unauthorised' }
703
-
704
- /leads/detail:
705
- get:
706
- operationId: getLead
707
- summary: Single lead with appointments and activity log
708
- description: "**Real URL:** `GET ?action=lead&id=<id>`"
709
- tags: [Leads]
710
- parameters:
711
- - name: action
712
- in: query
713
- required: true
714
- schema: { type: string, enum: [lead] }
715
- - $ref: '#/components/parameters/ApiVersion'
716
- - $ref: '#/components/parameters/IdQuery'
717
- responses:
718
- "200":
719
- description: Lead detail
720
- content:
721
- application/json:
722
- schema:
723
- type: object
724
- properties:
725
- success: { type: boolean, example: true }
726
- message: { type: string }
727
- data: { $ref: '#/components/schemas/LeadDetail' }
728
- "401": { $ref: '#/components/responses/Unauthorised' }
729
- "404": { $ref: '#/components/responses/NotFound' }
730
-
731
- /leads/create:
732
- post:
733
- operationId: createLead
734
- summary: Create a new lead
735
- description: |
736
- Triggers a push notification to all admin users.
737
- **Real URL:** `POST ?action=lead_create`
738
- tags: [Leads]
739
- parameters:
740
- - name: action
741
- in: query
742
- required: true
743
- schema: { type: string, enum: [lead_create] }
744
- - $ref: '#/components/parameters/ApiVersion'
745
- requestBody:
746
- required: true
747
- content:
748
- application/json:
749
- schema:
750
- type: object
751
- required: [first_name, email]
752
- properties:
753
- first_name: { type: string }
754
- last_name: { type: string }
755
- email: { type: string, format: email }
756
- phone: { type: string }
757
- gender: { type: string }
758
- qualification: { type: string }
759
- address_line1: { type: string }
760
- city: { type: string }
761
- postcode: { type: string }
762
- country: { type: string, default: "United Kingdom" }
763
- status: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed], default: new }
764
- source: { type: string, default: "Mobile App" }
765
- notes: { type: string }
766
- lead_date: { type: string, format: date }
767
- responses:
768
- "201":
769
- description: Lead created
770
- content:
771
- application/json:
772
- schema:
773
- type: object
774
- properties:
775
- success: { type: boolean, example: true }
776
- message: { type: string }
777
- data:
778
- type: object
779
- properties:
780
- lead_id: { type: integer }
781
- "400": { $ref: '#/components/responses/ValidationError' }
782
- "401": { $ref: '#/components/responses/Unauthorised' }
783
-
784
- /leads/update:
785
- post:
786
- operationId: updateLead
787
- summary: Update lead fields (patch-style)
788
- description: |
789
- Only send the fields you want to change. If `status` changes, email/SMS
790
- triggers fire automatically.
791
- **Real URL:** `POST ?action=lead_update`
792
- tags: [Leads]
793
- parameters:
794
- - name: action
795
- in: query
796
- required: true
797
- schema: { type: string, enum: [lead_update] }
798
- - $ref: '#/components/parameters/ApiVersion'
799
- requestBody:
800
- required: true
801
- content:
802
- application/json:
803
- schema:
804
- type: object
805
- required: [id]
806
- properties:
807
- id: { type: integer }
808
- first_name: { type: string }
809
- last_name: { type: string }
810
- email: { type: string, format: email }
811
- phone: { type: string }
812
- gender: { type: string }
813
- preferred_name: { type: string }
814
- qualification: { type: string }
815
- experience: { type: string }
816
- device_type: { type: string }
817
- source: { type: string }
818
- address_line1: { type: string }
819
- address_line2: { type: string }
820
- city: { type: string }
821
- county: { type: string }
822
- postcode: { type: string }
823
- country: { type: string }
824
- shipping_address_line1: { type: string }
825
- shipping_address_line2: { type: string }
826
- shipping_city: { type: string }
827
- shipping_county: { type: string }
828
- shipping_postcode: { type: string }
829
- shipping_country: { type: string }
830
- shipping_phone: { type: string }
831
- notes: { type: string }
832
- status:
833
- type: string
834
- enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed]
835
- responses:
836
- "200": { $ref: '#/components/responses/SimpleOk' }
837
- "400": { $ref: '#/components/responses/ValidationError' }
838
- "401": { $ref: '#/components/responses/Unauthorised' }
839
- "404": { $ref: '#/components/responses/NotFound' }
840
-
841
- /leads/update-status:
842
- post:
843
- operationId: updateLeadStatus
844
- summary: Update lead status (fires email/SMS triggers)
845
- description: "**Real URL:** `POST ?action=lead_update_status`"
846
- tags: [Leads]
847
- parameters:
848
- - name: action
849
- in: query
850
- required: true
851
- schema: { type: string, enum: [lead_update_status] }
852
- - $ref: '#/components/parameters/ApiVersion'
853
- requestBody:
854
- required: true
855
- content:
856
- application/json:
857
- schema:
858
- type: object
859
- required: [id, status]
860
- properties:
861
- id: { type: integer }
862
- status: { type: string, enum: [new, enrolled, not_interested, planned_later, no_answer, refunded, closed] }
863
- responses:
864
- "200": { $ref: '#/components/responses/SimpleOk' }
865
- "400": { $ref: '#/components/responses/ValidationError' }
866
- "401": { $ref: '#/components/responses/Unauthorised' }
867
- "404": { $ref: '#/components/responses/NotFound' }
868
-
869
- /leads/add-note:
870
- post:
871
- operationId: addLeadNote
872
- summary: Append a timestamped note to a lead
873
- description: |
874
- Appends to the plain-text `notes` column and writes an activity log entry.
875
- **Real URL:** `POST ?action=lead_add_note`
876
- tags: [Leads]
877
- parameters:
878
- - name: action
879
- in: query
880
- required: true
881
- schema: { type: string, enum: [lead_add_note] }
882
- - $ref: '#/components/parameters/ApiVersion'
883
- requestBody:
884
- required: true
885
- content:
886
- application/json:
887
- schema:
888
- type: object
889
- required: [id, note]
890
- properties:
891
- id: { type: integer }
892
- note: { type: string }
893
- responses:
894
- "200": { $ref: '#/components/responses/SimpleOk' }
895
- "400": { $ref: '#/components/responses/ValidationError' }
896
- "401": { $ref: '#/components/responses/Unauthorised' }
897
- "404": { $ref: '#/components/responses/NotFound' }
898
-
899
- /leads/archive:
900
- post:
901
- operationId: archiveLead
902
- summary: Archive or unarchive a lead (admin only)
903
- description: |
904
- Cascades to all appointments and cancels pending emails when archiving.
905
- Send `archive: false` to reverse.
906
- **Real URL:** `POST ?action=lead_archive`
907
- tags: [Leads]
908
- parameters:
909
- - name: action
910
- in: query
911
- required: true
912
- schema: { type: string, enum: [lead_archive] }
913
- - $ref: '#/components/parameters/ApiVersion'
914
- requestBody:
915
- required: true
916
- content:
917
- application/json:
918
- schema:
919
- type: object
920
- required: [id]
921
- properties:
922
- id: { type: integer }
923
- archive: { type: boolean, default: true }
924
- responses:
925
- "200": { $ref: '#/components/responses/SimpleOk' }
926
- "401": { $ref: '#/components/responses/Unauthorised' }
927
- "403": { $ref: '#/components/responses/Forbidden' }
928
- "404": { $ref: '#/components/responses/NotFound' }
929
-
930
- # ── Appointments ───────────────────────────────────────────────────────────
931
-
932
- /appointments:
933
- get:
934
- operationId: listAppointments
935
- summary: Paginated appointment list
936
- description: "**Real URL:** `GET ?action=appointments`"
937
- tags: [Appointments]
938
- parameters:
939
- - name: action
940
- in: query
941
- required: true
942
- schema: { type: string, enum: [appointments] }
943
- - $ref: '#/components/parameters/ApiVersion'
944
- - $ref: '#/components/parameters/PageParam'
945
- - name: status
946
- in: query
947
- schema: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
948
- - name: date_from
949
- in: query
950
- schema: { type: string, format: date }
951
- - name: date_to
952
- in: query
953
- schema: { type: string, format: date }
954
- - name: upcoming
955
- in: query
956
- schema: { type: boolean, description: "Filter to future non-cancelled/refunded appointments" }
957
- responses:
958
- "200":
959
- description: Paginated appointment list
960
- content:
961
- application/json:
962
- schema:
963
- type: object
964
- properties:
965
- success: { type: boolean, example: true }
966
- message: { type: string }
967
- data: { $ref: '#/components/schemas/PaginatedAppointments' }
968
- "401": { $ref: '#/components/responses/Unauthorised' }
969
-
970
- /appointments/detail:
971
- get:
972
- operationId: getAppointment
973
- summary: Single appointment with joined lead fields and activity log
974
- description: "**Real URL:** `GET ?action=appointment&id=<id>`"
975
- tags: [Appointments]
976
- parameters:
977
- - name: action
978
- in: query
979
- required: true
980
- schema: { type: string, enum: [appointment] }
981
- - $ref: '#/components/parameters/ApiVersion'
982
- - $ref: '#/components/parameters/IdQuery'
983
- responses:
984
- "200":
985
- description: Appointment detail
986
- content:
987
- application/json:
988
- schema:
989
- type: object
990
- properties:
991
- success: { type: boolean, example: true }
992
- message: { type: string }
993
- data: { $ref: '#/components/schemas/AppointmentDetail' }
994
- "401": { $ref: '#/components/responses/Unauthorised' }
995
- "404": { $ref: '#/components/responses/NotFound' }
996
-
997
- /appointments/create:
998
- post:
999
- operationId: createAppointment
1000
- summary: Create an appointment
1001
- description: |
1002
- If `course_id` is provided, `training_location` and `training_address` default
1003
- to the course's values. Fires email/SMS triggers for the initial status and
1004
- sends a push notification to all admin users.
1005
- **Real URL:** `POST ?action=appointment_create`
1006
- tags: [Appointments]
1007
- parameters:
1008
- - name: action
1009
- in: query
1010
- required: true
1011
- schema: { type: string, enum: [appointment_create] }
1012
- - $ref: '#/components/parameters/ApiVersion'
1013
- requestBody:
1014
- required: true
1015
- content:
1016
- application/json:
1017
- schema:
1018
- type: object
1019
- required: [lead_id, appointment_date]
1020
- properties:
1021
- lead_id: { type: integer }
1022
- course_id: { type: integer }
1023
- appointment_date: { type: string, format: date }
1024
- appointment_time: { type: string, default: "09:00", example: "09:00" }
1025
- duration: { type: string, default: "1 day" }
1026
- amount_paid: { type: number, default: 0 }
1027
- transaction_fee: { type: number, default: 0 }
1028
- payment_method: { type: string, default: "Card" }
1029
- payment_ref: { type: string }
1030
- payment_date: { type: string, format: date }
1031
- status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show], default: pending }
1032
- notes: { type: string }
1033
- training_location:{ type: string }
1034
- training_address: { type: string }
1035
- responses:
1036
- "201":
1037
- description: Appointment created
1038
- content:
1039
- application/json:
1040
- schema:
1041
- type: object
1042
- properties:
1043
- success: { type: boolean, example: true }
1044
- message: { type: string }
1045
- data:
1046
- type: object
1047
- properties:
1048
- appointment_id: { type: integer }
1049
- appointment_ref: { type: string, example: "APT-A3B2C1" }
1050
- "400": { $ref: '#/components/responses/ValidationError' }
1051
- "401": { $ref: '#/components/responses/Unauthorised' }
1052
- "404": { $ref: '#/components/responses/NotFound' }
1053
-
1054
- /appointments/update:
1055
- post:
1056
- operationId: updateAppointment
1057
- summary: Update appointment fields (patch-style)
1058
- description: |
1059
- Only send the fields you want to change. If `status` changes, email/SMS
1060
- triggers fire and admins receive a push notification.
1061
- **Real URL:** `POST ?action=appointment_update`
1062
- tags: [Appointments]
1063
- parameters:
1064
- - name: action
1065
- in: query
1066
- required: true
1067
- schema: { type: string, enum: [appointment_update] }
1068
- - $ref: '#/components/parameters/ApiVersion'
1069
- requestBody:
1070
- required: true
1071
- content:
1072
- application/json:
1073
- schema:
1074
- type: object
1075
- required: [id]
1076
- properties:
1077
- id: { type: integer }
1078
- appointment_date: { type: string, format: date }
1079
- appointment_time: { type: string }
1080
- duration: { type: string }
1081
- training_location:{ type: string }
1082
- training_address: { type: string }
1083
- amount_paid: { type: number }
1084
- transaction_fee: { type: number }
1085
- payment_method: { type: string }
1086
- payment_ref: { type: string }
1087
- payment_date: { type: string, format: date }
1088
- notes: { type: string }
1089
- course_id: { type: integer }
1090
- status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
1091
- responses:
1092
- "200": { $ref: '#/components/responses/SimpleOk' }
1093
- "400": { $ref: '#/components/responses/ValidationError' }
1094
- "401": { $ref: '#/components/responses/Unauthorised' }
1095
- "404": { $ref: '#/components/responses/NotFound' }
1096
-
1097
- /appointments/update-status:
1098
- post:
1099
- operationId: updateAppointmentStatus
1100
- summary: Update appointment status (fires triggers + push)
1101
- description: "**Real URL:** `POST ?action=appointment_update_status`"
1102
- tags: [Appointments]
1103
- parameters:
1104
- - name: action
1105
- in: query
1106
- required: true
1107
- schema: { type: string, enum: [appointment_update_status] }
1108
- - $ref: '#/components/parameters/ApiVersion'
1109
- requestBody:
1110
- required: true
1111
- content:
1112
- application/json:
1113
- schema:
1114
- type: object
1115
- required: [id, status]
1116
- properties:
1117
- id: { type: integer }
1118
- status: { type: string, enum: [pending, paid, confirmed, attended, cancelled, refunded, no-show] }
1119
- responses:
1120
- "200": { $ref: '#/components/responses/SimpleOk' }
1121
- "400": { $ref: '#/components/responses/ValidationError' }
1122
- "401": { $ref: '#/components/responses/Unauthorised' }
1123
- "404": { $ref: '#/components/responses/NotFound' }
1124
-
1125
- /appointments/archive:
1126
- post:
1127
- operationId: archiveAppointment
1128
- summary: Archive or unarchive an appointment (admin only)
1129
- description: |
1130
- Cancels pending emails when archiving. Send `archive: false` to reverse.
1131
- **Real URL:** `POST ?action=appointment_archive`
1132
- tags: [Appointments]
1133
- parameters:
1134
- - name: action
1135
- in: query
1136
- required: true
1137
- schema: { type: string, enum: [appointment_archive] }
1138
- - $ref: '#/components/parameters/ApiVersion'
1139
- requestBody:
1140
- required: true
1141
- content:
1142
- application/json:
1143
- schema:
1144
- type: object
1145
- required: [id]
1146
- properties:
1147
- id: { type: integer }
1148
- archive: { type: boolean, default: true }
1149
- responses:
1150
- "200": { $ref: '#/components/responses/SimpleOk' }
1151
- "401": { $ref: '#/components/responses/Unauthorised' }
1152
- "403": { $ref: '#/components/responses/Forbidden' }
1153
- "404": { $ref: '#/components/responses/NotFound' }
1154
-
1155
- # ── Courses ────────────────────────────────────────────────────────────────
1156
-
1157
- /courses:
1158
- get:
1159
- operationId: listCourses
1160
- summary: Active course catalogue
1161
- description: "**Real URL:** `GET ?action=courses`"
1162
- tags: [Courses]
1163
- parameters:
1164
- - name: action
1165
- in: query
1166
- required: true
1167
- schema: { type: string, enum: [courses] }
1168
- - $ref: '#/components/parameters/ApiVersion'
1169
- responses:
1170
- "200":
1171
- description: Active courses
1172
- content:
1173
- application/json:
1174
- schema:
1175
- type: object
1176
- properties:
1177
- success: { type: boolean, example: true }
1178
- message: { type: string }
1179
- data:
1180
- type: object
1181
- properties:
1182
- courses: { type: array, items: { $ref: '#/components/schemas/Course' } }
1183
- "401": { $ref: '#/components/responses/Unauthorised' }
1184
-
1185
- # ── Search ─────────────────────────────────────────────────────────────────
1186
-
1187
- /search:
1188
- get:
1189
- operationId: search
1190
- summary: Search leads by name, email, or phone
1191
- description: |
1192
- Returns up to 30 matching non-archived leads. Minimum query length is 2 characters.
1193
- **Real URL:** `GET ?action=search&q=<query>`
1194
- tags: [Search]
1195
- parameters:
1196
- - name: action
1197
- in: query
1198
- required: true
1199
- schema: { type: string, enum: [search] }
1200
- - $ref: '#/components/parameters/ApiVersion'
1201
- - name: q
1202
- in: query
1203
- required: true
1204
- schema: { type: string, minLength: 2 }
1205
- responses:
1206
- "200":
1207
- description: Search results
1208
- content:
1209
- application/json:
1210
- schema:
1211
- type: object
1212
- properties:
1213
- success: { type: boolean, example: true }
1214
- message: { type: string }
1215
- data:
1216
- type: object
1217
- properties:
1218
- results: { type: array, items: { $ref: '#/components/schemas/SearchResult' } }
1219
- count: { type: integer }
1220
- "400": { $ref: '#/components/responses/ValidationError' }
1221
- "401": { $ref: '#/components/responses/Unauthorised' }
1222
-
1223
- # ── Stats & Dashboard ──────────────────────────────────────────────────────
1224
-
1225
- /stats/dashboard:
1226
- get:
1227
- operationId: getDashboard
1228
- summary: Summary stats, upcoming appointments, and recent leads
1229
- description: |
1230
- `total_revenue` and `month_revenue` are included only for admin users.
1231
- **Real URL:** `GET ?action=dashboard`
1232
- tags: [Stats]
1233
- parameters:
1234
- - name: action
1235
- in: query
1236
- required: true
1237
- schema: { type: string, enum: [dashboard] }
1238
- - $ref: '#/components/parameters/ApiVersion'
1239
- responses:
1240
- "200":
1241
- description: Dashboard data
1242
- content:
1243
- application/json:
1244
- schema:
1245
- type: object
1246
- properties:
1247
- success: { type: boolean, example: true }
1248
- message: { type: string }
1249
- data: { $ref: '#/components/schemas/DashboardData' }
1250
- "401": { $ref: '#/components/responses/Unauthorised' }
1251
-
1252
- /stats:
1253
- get:
1254
- operationId: getStats
1255
- summary: Revenue by month and status breakdowns (admin only)
1256
- description: |
1257
- Revenue chart defaults to the last 6 months. Use `date_from` / `date_to` to override.
1258
- **Real URL:** `GET ?action=stats`
1259
- tags: [Stats]
1260
- parameters:
1261
- - name: action
1262
- in: query
1263
- required: true
1264
- schema: { type: string, enum: [stats] }
1265
- - $ref: '#/components/parameters/ApiVersion'
1266
- - name: date_from
1267
- in: query
1268
- schema: { type: string, format: date }
1269
- description: "Start of revenue date range (inclusive). Defaults to 6 months ago."
1270
- - name: date_to
1271
- in: query
1272
- schema: { type: string, format: date }
1273
- description: "End of revenue date range (inclusive)."
1274
- responses:
1275
- "200":
1276
- description: Analytics data
1277
- content:
1278
- application/json:
1279
- schema:
1280
- type: object
1281
- properties:
1282
- success: { type: boolean, example: true }
1283
- message: { type: string }
1284
- data: { $ref: '#/components/schemas/StatsData' }
1285
- "401": { $ref: '#/components/responses/Unauthorised' }
1286
- "403": { $ref: '#/components/responses/Forbidden' }
1287
-
1288
- # ── Users (admin only) ─────────────────────────────────────────────────────
1289
-
1290
- /users:
1291
- get:
1292
- operationId: listUsers
1293
- summary: List all CRM users (admin only)
1294
- description: "**Real URL:** `GET ?action=user_list`"
1295
- tags: [Users]
1296
- parameters:
1297
- - name: action
1298
- in: query
1299
- required: true
1300
- schema: { type: string, enum: [user_list] }
1301
- - $ref: '#/components/parameters/ApiVersion'
1302
- responses:
1303
- "200":
1304
- description: All CRM users
1305
- content:
1306
- application/json:
1307
- schema:
1308
- type: object
1309
- properties:
1310
- success: { type: boolean, example: true }
1311
- message: { type: string }
1312
- data:
1313
- type: object
1314
- properties:
1315
- users: { type: array, items: { $ref: '#/components/schemas/User' } }
1316
- total: { type: integer }
1317
- "401": { $ref: '#/components/responses/Unauthorised' }
1318
- "403": { $ref: '#/components/responses/Forbidden' }
1319
-
1320
- /users/create:
1321
- post:
1322
- operationId: createUser
1323
- summary: Create a CRM user (admin only)
1324
- description: "**Real URL:** `POST ?action=user_create`"
1325
- tags: [Users]
1326
- parameters:
1327
- - name: action
1328
- in: query
1329
- required: true
1330
- schema: { type: string, enum: [user_create] }
1331
- - $ref: '#/components/parameters/ApiVersion'
1332
- requestBody:
1333
- required: true
1334
- content:
1335
- application/json:
1336
- schema:
1337
- type: object
1338
- required: [username, password, full_name]
1339
- properties:
1340
- username: { type: string }
1341
- password: { type: string, format: password, minLength: 8 }
1342
- full_name: { type: string }
1343
- email: { type: string, format: email }
1344
- role: { type: string, enum: [admin, staff], default: staff }
1345
- responses:
1346
- "201":
1347
- description: User created
1348
- content:
1349
- application/json:
1350
- schema:
1351
- type: object
1352
- properties:
1353
- success: { type: boolean, example: true }
1354
- message: { type: string }
1355
- data:
1356
- type: object
1357
- properties:
1358
- user_id: { type: integer }
1359
- "400": { $ref: '#/components/responses/ValidationError' }
1360
- "401": { $ref: '#/components/responses/Unauthorised' }
1361
- "403": { $ref: '#/components/responses/Forbidden' }
1362
- "409": { $ref: '#/components/responses/Conflict' }
1363
-
1364
- /users/update:
1365
- post:
1366
- operationId: updateUser
1367
- summary: Update a CRM user (admin only, patch-style)
1368
- description: "**Real URL:** `POST ?action=user_update`"
1369
- tags: [Users]
1370
- parameters:
1371
- - name: action
1372
- in: query
1373
- required: true
1374
- schema: { type: string, enum: [user_update] }
1375
- - $ref: '#/components/parameters/ApiVersion'
1376
- requestBody:
1377
- required: true
1378
- content:
1379
- application/json:
1380
- schema:
1381
- type: object
1382
- required: [id]
1383
- properties:
1384
- id: { type: integer }
1385
- full_name: { type: string }
1386
- email: { type: string, format: email }
1387
- username: { type: string }
1388
- role: { type: string, enum: [admin, staff] }
1389
- responses:
1390
- "200": { $ref: '#/components/responses/SimpleOk' }
1391
- "400": { $ref: '#/components/responses/ValidationError' }
1392
- "401": { $ref: '#/components/responses/Unauthorised' }
1393
- "403": { $ref: '#/components/responses/Forbidden' }
1394
- "404": { $ref: '#/components/responses/NotFound' }
1395
- "409": { $ref: '#/components/responses/Conflict' }
1396
-
1397
- /users/deactivate:
1398
- post:
1399
- operationId: deactivateUser
1400
- summary: Deactivate or reactivate a user (admin only)
1401
- description: |
1402
- Cannot target your own account. Deactivating immediately revokes all active tokens.
1403
- Send `active: true` to reactivate.
1404
- **Real URL:** `POST ?action=user_deactivate`
1405
- tags: [Users]
1406
- parameters:
1407
- - name: action
1408
- in: query
1409
- required: true
1410
- schema: { type: string, enum: [user_deactivate] }
1411
- - $ref: '#/components/parameters/ApiVersion'
1412
- requestBody:
1413
- required: true
1414
- content:
1415
- application/json:
1416
- schema:
1417
- type: object
1418
- required: [id]
1419
- properties:
1420
- id: { type: integer }
1421
- active: { type: boolean, description: "true to reactivate; omit or false to deactivate" }
1422
- responses:
1423
- "200": { $ref: '#/components/responses/SimpleOk' }
1424
- "401": { $ref: '#/components/responses/Unauthorised' }
1425
- "403": { $ref: '#/components/responses/Forbidden' }
1426
- "404": { $ref: '#/components/responses/NotFound' }
1427
-
1428
- # ── Push Notifications ─────────────────────────────────────────────────────
1429
-
1430
- /devices/register:
1431
- post:
1432
- operationId: registerDevice
1433
- summary: Register or refresh a push token for this device
1434
- description: |
1435
- Uses INSERT … ON DUPLICATE KEY UPDATE — safe to call on every app launch.
1436
- Expo push tokens look like `ExponentPushToken[xxxxxxxxxxxxxxxxxxxx]`.
1437
- **Real URL:** `POST ?action=register_device`
1438
- tags: [Notifications]
1439
- parameters:
1440
- - name: action
1441
- in: query
1442
- required: true
1443
- schema: { type: string, enum: [register_device] }
1444
- - $ref: '#/components/parameters/ApiVersion'
1445
- requestBody:
1446
- required: true
1447
- content:
1448
- application/json:
1449
- schema:
1450
- type: object
1451
- required: [push_token]
1452
- properties:
1453
- push_token: { type: string, example: "ExponentPushToken[xxxxxxxxxxxxxxxxxxxx]" }
1454
- platform: { type: string, enum: [ios, android, web], default: android }
1455
- device_name: { type: string, example: "Sarah's iPhone 15" }
1456
- responses:
1457
- "200": { $ref: '#/components/responses/SimpleOk' }
1458
- "400": { $ref: '#/components/responses/ValidationError' }
1459
- "401": { $ref: '#/components/responses/Unauthorised' }
1460
-
1461
- /devices/unregister:
1462
- post:
1463
- operationId: unregisterDevice
1464
- summary: Remove a push token (stop notifications on this device)
1465
- description: |
1466
- The `logout` endpoint also accepts `push_token` to remove the token in one call.
1467
- **Real URL:** `POST ?action=unregister_device`
1468
- tags: [Notifications]
1469
- parameters:
1470
- - name: action
1471
- in: query
1472
- required: true
1473
- schema: { type: string, enum: [unregister_device] }
1474
- - $ref: '#/components/parameters/ApiVersion'
1475
- requestBody:
1476
- required: true
1477
- content:
1478
- application/json:
1479
- schema:
1480
- type: object
1481
- required: [push_token]
1482
- properties:
1483
- push_token: { type: string }
1484
- responses:
1485
- "200": { $ref: '#/components/responses/SimpleOk' }
1486
- "400": { $ref: '#/components/responses/ValidationError' }
1487
- "401": { $ref: '#/components/responses/Unauthorised' }
1488
-
1489
- # ── Invoice ────────────────────────────────────────────────────────────────
1490
-
1491
- /invoice/pdf:
1492
- get:
1493
- operationId: downloadInvoicePdf
1494
- summary: Download appointment invoice as PDF
1495
- description: |
1496
- Streams a dompdf-rendered A4 PDF. Response `Content-Type` is `application/pdf`,
1497
- not JSON. Pass the JWT in the `Authorization` header as usual.
1498
- **Real URL:** `GET ?action=invoice_pdf&id=<id>`
1499
- tags: [Invoice]
1500
- parameters:
1501
- - name: action
1502
- in: query
1503
- required: true
1504
- schema: { type: string, enum: [invoice_pdf] }
1505
- - $ref: '#/components/parameters/ApiVersion'
1506
- - $ref: '#/components/parameters/IdQuery'
1507
- responses:
1508
- "200":
1509
- description: PDF file download
1510
- headers:
1511
- Content-Disposition:
1512
- schema: { type: string, example: 'attachment; filename="invoice-APT-A3B2C1.pdf"' }
1513
- content:
1514
- application/pdf:
1515
- schema: { type: string, format: binary }
1516
- "401": { $ref: '#/components/responses/Unauthorised' }
1517
- "404": { $ref: '#/components/responses/NotFound' }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ref doc/admin_openapi.yaml DELETED
The diff for this file is too large to render. See raw diff
 
start.ps1 CHANGED
@@ -1,3 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ============================================================
2
  # AI API Testing Tool - Dev Startup Script
3
  # Usage: .\start.ps1
@@ -10,39 +59,50 @@ 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
- Write-Host "[1/3] Checking for processes on port 8001..." -ForegroundColor Yellow
 
 
 
15
  $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
 
16
  if ($stale) {
17
  $pid_ = ($stale -split "\s+")[-1]
18
- Write-Host " Killing stale process (PID $pid_)..." -ForegroundColor DarkYellow
 
 
19
  Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
 
20
  Start-Sleep -Seconds 2
21
- } else {
 
22
  Write-Host " Port 8001 is free." -ForegroundColor Green
23
  }
24
 
25
- # --- 2. Start FastAPI Backend ---
26
- Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
27
- $backend = Start-Process -FilePath "cmd.exe" `
28
- -ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001" `
29
- -WorkingDirectory $PSScriptRoot `
30
- -PassThru
 
31
 
32
- Write-Host " Backend PID: $($backend.Id)" -ForegroundColor Green
33
- Write-Host " Waiting 8s for backend to initialize..." -ForegroundColor DarkGray
34
- Start-Sleep -Seconds 8
35
 
36
- # --- 3. Start React Frontend ---
37
- Write-Host "[3/3] Starting React frontend (Vite dev server)..." -ForegroundColor Yellow
38
- Start-Process -FilePath "cmd.exe" `
39
- -ArgumentList "/k", "title Frontend && npm run dev" `
40
- -WorkingDirectory (Join-Path $PSScriptRoot "frontend-react")
41
 
 
 
 
42
  Write-Host ""
43
  Write-Host " All services started!" -ForegroundColor Green
44
  Write-Host ""
45
  Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
46
  Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
47
  Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
48
- 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
+ # Write-Host "[1/3] Checking for processes on port 8001..." -ForegroundColor Yellow
15
+ # $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
16
+ # if ($stale) {
17
+ # $pid_ = ($stale -split "\s+")[-1]
18
+ # Write-Host " Killing stale process (PID $pid_)..." -ForegroundColor DarkYellow
19
+ # Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
20
+ # Start-Sleep -Seconds 2
21
+ # } else {
22
+ # Write-Host " Port 8001 is free." -ForegroundColor Green
23
+ # }
24
+
25
+ # # --- 2. Start FastAPI Backend ---
26
+ # Write-Host "[2/3] Starting FastAPI backend (port 8001)..." -ForegroundColor Yellow
27
+ # $backend = Start-Process -FilePath "cmd.exe" `
28
+ # -ArgumentList "/k", "title Backend && python -m uvicorn backend.main:app --reload --port 8001" `
29
+ # -WorkingDirectory $PSScriptRoot `
30
+ # -PassThru
31
+
32
+ # Write-Host " Backend PID: $($backend.Id)" -ForegroundColor Green
33
+ # Write-Host " Waiting 8s for backend to initialize..." -ForegroundColor DarkGray
34
+ # Start-Sleep -Seconds 8
35
+
36
+ # # --- 3. Start React Frontend ---
37
+ # Write-Host "[3/3] Starting React frontend (Vite dev server)..." -ForegroundColor Yellow
38
+ # Start-Process -FilePath "cmd.exe" `
39
+ # -ArgumentList "/k", "title Frontend && npm run dev" `
40
+ # -WorkingDirectory (Join-Path $PSScriptRoot "frontend-react")
41
+
42
+ # Write-Host ""
43
+ # Write-Host " All services started!" -ForegroundColor Green
44
+ # Write-Host ""
45
+ # Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
46
+ # Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
47
+ # Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
48
+ # Write-Host ""
49
+
50
  # ============================================================
51
  # AI API Testing Tool - Dev Startup Script
52
  # Usage: .\start.ps1
 
59
  Write-Host " ===================" -ForegroundColor Cyan
60
  Write-Host ""
61
 
62
+ # ------------------------------------------------------------
63
+ # 1. Kill stale process on port 8001
64
+ # ------------------------------------------------------------
65
+ Write-Host "[1/3] Checking port 8001..." -ForegroundColor Yellow
66
+
67
  $stale = netstat -aon | Select-String ":8001 " | Select-String "LISTENING"
68
+
69
  if ($stale) {
70
  $pid_ = ($stale -split "\s+")[-1]
71
+
72
+ Write-Host " Killing process PID $pid_..." -ForegroundColor DarkYellow
73
+
74
  Stop-Process -Id $pid_ -Force -ErrorAction SilentlyContinue
75
+
76
  Start-Sleep -Seconds 2
77
+ }
78
+ else {
79
  Write-Host " Port 8001 is free." -ForegroundColor Green
80
  }
81
 
82
+ # ------------------------------------------------------------
83
+ # 2. Launch Backend + Frontend in Windows Terminal Tabs
84
+ # ------------------------------------------------------------
85
+ Write-Host "[2/3] Starting services..." -ForegroundColor Yellow
86
+
87
+ $backendPath = $PSScriptRoot
88
+ $frontendPath = Join-Path $PSScriptRoot "frontend-react"
89
 
90
+ $backend = Start-Job -ScriptBlock { param($p) Set-Location $p; python -m uvicorn backend.main:app --reload --port 8001 } -ArgumentList $backendPath
91
+ $frontend = Start-Job -ScriptBlock { param($p) Set-Location $p; npm run dev } -ArgumentList $frontendPath
 
92
 
93
+ Write-Host " Backend Job ID: $($backend.Id)" -ForegroundColor DarkGray
94
+ Write-Host " Frontend Job ID: $($frontend.Id)" -ForegroundColor DarkGray
95
+ Write-Host ""
96
+ Write-Host " To see logs: Receive-Job -Id <JobId> -Keep" -ForegroundColor DarkGray
97
+ Write-Host " To stop all: Get-Job | Stop-Job; Get-Job | Remove-Job" -ForegroundColor DarkGray
98
 
99
+ # ------------------------------------------------------------
100
+ # 3. Final Output
101
+ # ------------------------------------------------------------
102
  Write-Host ""
103
  Write-Host " All services started!" -ForegroundColor Green
104
  Write-Host ""
105
  Write-Host " Backend -> http://localhost:8001" -ForegroundColor Cyan
106
  Write-Host " Frontend -> http://localhost:5173" -ForegroundColor Cyan
107
  Write-Host " API Docs -> http://localhost:8001/docs" -ForegroundColor Cyan
108
+ Write-Host ""