Amitkasar commited on
Commit
97fada4
Β·
1 Parent(s): 481e01c

Add UI docs; refine executor and parser behavior

Browse files

Adds a new UI_DOCUMENTATION.md describing the app UI and workflows. Updates backend/services/api_executor.py to clarify authentication rules (use credentials appropriately, only include Authorization when required, do not default to Bearer) and adjust the example Authorization placeholder. Updates backend/services/swagger_parser.py to stop resolving $refs at parse time (return raw spec to defer $ref resolution to execution time for large files), make endpoint extraction more robust, and expose paths/components/openapi/title/version from the raw spec. Removes an obsolete Supabase implementation/plan file.

UI_DOCUMENTATION.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 / Specs**: Browse, upload, and manage OpenAPI/Swagger specifications.
9
+ - **Execution Workflow (Testing)**: The core interface for defining test scenarios and executing steps.
10
+ - **Test User Profile**: Manage credentials and custom variables for the active collection.
11
+ - **Execution History**: View and review past test sessions and their detailed logs.
12
+ - **Media Hub**: Manage assets (images, audio, video, documents) used for API testing.
13
+ - **System Settings**: Access global application configuration and preferences.
14
+
15
+ ---
16
+
17
+ ## 2. API Collections Module
18
+ This module handles the management of API definitions.
19
+
20
+ - **Upload Spec**: Users can upload `.json`, `.yaml`, or `.yml` files containing OpenAPI/Swagger specifications.
21
+ - **Search & Filter**: Quickly find a specific collection by name.
22
+ - **Selection**: Clicking a collection card makes it the "Active Spec," enabling testing and profile management for that specific API.
23
+ - **Deletion**: Remove unwanted specifications from the system.
24
+
25
+ ---
26
+
27
+ ## 3. Execution Workflow (Testing)
28
+ This is the primary workspace for API interaction.
29
+
30
+ ### Header & Configuration
31
+ - **Active Spec Name**: Displays the name of the currently selected API collection.
32
+ - **Base URL Input**: Allow users to set or update the target environment (e.g., `https://api.example.com`). This value is saved per collection.
33
+ - **Token Usage Tracker**: Displays real-time LLM token consumption for both plan generation and current scenario execution.
34
+
35
+ ### Scenario Definition & Planning
36
+ - **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").
37
+ - **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.
38
+
39
+ ### Step Execution & Results
40
+ - **Step Overview**: Each generated step shows the target endpoint, HTTP method, and a summary of its purpose.
41
+ - **Execution**: A "Execute" button triggers the individual API call.
42
+ - **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.
43
+ - **Technical Inspection**: A detailed breakdown showing the raw **Request** (URL, Headers, Body, Params) and **Response** (Status Code, JSON body).
44
+ - **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.
45
+
46
+ ---
47
+
48
+ ## 4. Test User Profile
49
+ Profiles are isolated per API collection to maintain clean testing environments.
50
+
51
+ - **Core Authentication**: Fields for common credentials like Full Name, Email/Username, Password, and Static Access Tokens.
52
+ - **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.
53
+ - **Sensitive Data Masking**: Passwords and tokens are masked in the UI for security.
54
+
55
+ ---
56
+
57
+ ## 5. Right Sidebar: Context & Variables
58
+ A persistent panel (toggleable) that tracks state during a test session.
59
+
60
+ - **Session Extracted Variables**: Displays values captured from previous steps' responses (e.g., `userId`, `authToken`).
61
+ - **Test Credentials**: Live view of current profile data being used in the session.
62
+ - **Refresh Control**: Manual trigger to update the local context from the backend state.
63
+
64
+ ---
65
+
66
+ ## 6. Execution History
67
+ A permanent log of all test activities.
68
+
69
+ - **Session Grouping**: Individual API calls are grouped by their parent test scenario and session ID.
70
+ - **Status Indicators**: Visual cues (Success/Failure) for each session and step.
71
+ - **Restoration**: An "Import" feature allows users to load a past session back into the main Testing workspace to re-run or continue work.
72
+ - **Management**: Search through history by scenario or spec name, delete individual sessions, or clear the entire history.
73
+
74
+ ---
75
+
76
+ ## 7. Media Hub
77
+ A central repository for managing test data files.
78
+
79
+ - **Asset Categorization**: Automatically categorizes files into Documents, Images, Audio, and Video.
80
+ - **Collection-Based Organization**: Assets can be grouped into custom media collections.
81
+ - **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").
82
+ - **Search & Tagging**: Tag assets for even faster retrieval and management.
backend/services/api_executor.py CHANGED
@@ -49,7 +49,9 @@ CORE EXECUTION RULES:
49
  - You MUST replace all path variables like {{id}} or {{bus_id}} with actual values from Context or Step Definition.
50
  - Example: If URL is "/buses/{{bus_id}}" and Context has bus_id=101, result URL must be "/buses/101".
51
  2. AUTHORIZATION:
52
- - If User Credentials or Context Variables contain a "token", "access_token", or "jwt", you MUST include an "Authorization": "Bearer <token>" header unless otherwise specified.
 
 
53
  3. DATA SOURCE PRIORITY:
54
  - Priority 1: Context Variables (from previous steps).
55
  - Priority 2: User Credentials (for login/auth).
@@ -65,7 +67,7 @@ RETURN JSON ONLY:
65
  {{
66
  "step": 1,
67
  "request": {{
68
- "method": "POST", "url": "<FULL_URL_WITH_PARAMS_REPLACED>", "headers": {{"Authorization": "Bearer ..."}},
69
  "query_params": {{}}, "form_data": {{}}, "body": {{}}, "files": {{}}
70
  }},
71
  "analysis": {{
 
49
  - You MUST replace all path variables like {{id}} or {{bus_id}} with actual values from Context or Step Definition.
50
  - Example: If URL is "/buses/{{bus_id}}" and Context has bus_id=101, result URL must be "/buses/101".
51
  2. AUTHORIZATION:
52
+ - Use credentials from "User Credentials" or "Context Variables" to satisfy authentication (token, api_key, etc).
53
+ - Only include an "Authorization" header if required by the spec. Use the correct format (e.g., "Bearer <token>", "Token <token>", or "Basic <base64>") as needed.
54
+ - DO NOT default to "Bearer" if the credential type is not specified.
55
  3. DATA SOURCE PRIORITY:
56
  - Priority 1: Context Variables (from previous steps).
57
  - Priority 2: User Credentials (for login/auth).
 
67
  {{
68
  "step": 1,
69
  "request": {{
70
+ "method": "POST", "url": "<FULL_URL_WITH_PARAMS_REPLACED>", "headers": {{"Authorization": "..."}},
71
  "query_params": {{}}, "form_data": {{}}, "body": {{}}, "files": {{}}
72
  }},
73
  "analysis": {{
backend/services/swagger_parser.py CHANGED
@@ -6,8 +6,8 @@ from typing import Dict, Any
6
  def parse_spec(spec_content: str) -> Dict[str, Any]:
7
  """
8
  Parses a Swagger/OpenAPI spec (JSON or YAML string).
9
- Returns the FULL resolved spec (all $refs inlined by prance) so that
10
- the executor can look up exact request body schemas from `paths`.
11
  """
12
  try:
13
  spec_dict = json.loads(spec_content)
@@ -17,31 +17,37 @@ def parse_spec(spec_content: str) -> Dict[str, Any]:
17
  except yaml.YAMLError as e:
18
  raise ValueError(f"Failed to parse spec as JSON or YAML: {e}")
19
 
20
- # prance resolves all $ref references inline β€” use the fully resolved spec
21
- parser = ResolvingParser(spec_string=json.dumps(spec_dict), backend='openapi-spec-validator')
22
- resolved_spec = parser.specification
23
-
24
- # Build a simplified endpoint list for the planner LLM (no $refs remain since prance resolved them)
25
  simplified_endpoints = []
26
- paths = resolved_spec.get("paths", {})
27
  for path, methods in paths.items():
 
 
28
  for method, details in methods.items():
29
  if method.lower() not in ["get", "post", "put", "delete", "patch"]:
30
  continue
31
- endpoint_info = {
32
- "path": path,
33
- "method": method.upper(),
34
- "summary": details.get("summary", details.get("description", ""))[:100] # Cap summary length
35
- }
36
- simplified_endpoints.append(endpoint_info)
 
 
 
 
37
 
38
  return {
39
- # Full resolved spec β€” used by executor to look up exact endpoint schemas
40
  "paths": paths,
41
- "components": resolved_spec.get("components", {}),
 
42
  # Metadata
43
- "title": resolved_spec.get("info", {}).get("title", "API Spec"),
44
- "version": resolved_spec.get("info", {}).get("version", "1.0"),
45
  # Simplified list β€” used by planner LLM
46
  "endpoints": simplified_endpoints
47
  }
 
6
  def parse_spec(spec_content: str) -> Dict[str, Any]:
7
  """
8
  Parses a Swagger/OpenAPI spec (JSON or YAML string).
9
+ Returns the RAW spec dictionary. Resolution of $refs is deferred to execution time
10
+ to handle large files (e.g. GitHub API) efficiently.
11
  """
12
  try:
13
  spec_dict = json.loads(spec_content)
 
17
  except yaml.YAMLError as e:
18
  raise ValueError(f"Failed to parse spec as JSON or YAML: {e}")
19
 
20
+ # We skip ResolvingParser for large spec support.
21
+ # The executor (main.py) already handles on-the-fly $ref resolution.
22
+
23
+ # Build a simplified endpoint list for the planner LLM
 
24
  simplified_endpoints = []
25
+ paths = spec_dict.get("paths", {})
26
  for path, methods in paths.items():
27
+ if not isinstance(methods, dict):
28
+ continue
29
  for method, details in methods.items():
30
  if method.lower() not in ["get", "post", "put", "delete", "patch"]:
31
  continue
32
+
33
+ # Note: details might be a $ref, but usually in OpenAPI 'paths' contain
34
+ # the methods directly, or a $ref to a path item.
35
+ if isinstance(details, dict):
36
+ endpoint_info = {
37
+ "path": path,
38
+ "method": method.upper(),
39
+ "summary": details.get("summary", details.get("description", ""))[:100] # Cap summary length
40
+ }
41
+ simplified_endpoints.append(endpoint_info)
42
 
43
  return {
44
+ # Raw spec β€” used by executor to look up and resolve specific schemas on-the-fly
45
  "paths": paths,
46
+ "components": spec_dict.get("components", {}),
47
+ "openapi": spec_dict.get("openapi", spec_dict.get("swagger", "3.0")),
48
  # Metadata
49
+ "title": spec_dict.get("info", {}).get("title", "API Spec"),
50
+ "version": spec_dict.get("info", {}).get("version", "1.0"),
51
  # Simplified list β€” used by planner LLM
52
  "endpoints": simplified_endpoints
53
  }
supbase implementation implementation_plan DELETED
@@ -1,65 +0,0 @@
1
- # Supabase Database Integration Plan
2
-
3
- Replace the local SQLite database with Supabase (PostgreSQL). No auth changes. Data models stay the same.
4
-
5
- ## How It Works
6
-
7
- The backend already uses SQLAlchemy ORM and already reads `DATABASE_URL` from the environment. Supabase provides a standard PostgreSQL connection string, so all we need to do is:
8
- 1. Create the tables in Supabase.
9
- 2. Set the `DATABASE_URL` env variable to point to Supabase.
10
- 3. Remove the SQLite migration logic (no longer needed).
11
- 4. Install the `psycopg2` PostgreSQL driver.
12
-
13
- ---
14
-
15
- ## Proposed Changes
16
-
17
- ### Backend
18
-
19
- #### [MODIFY] [database.py](file:///C:/Users/amitk/OneDrive/Desktop/Testing/backend/database.py)
20
- - Remove [run_migrations()](file:///C:/Users/amitk/OneDrive/Desktop/Testing/backend/database.py#101-162) function and the `connect_args` SQLite workaround.
21
- - Add a check: if no `DATABASE_URL` is set, raise a clear error instead of defaulting to SQLite.
22
- - Ensure `create_all()` runs on startup to create any missing tables in Supabase automatically.
23
-
24
- #### [MODIFY] [requirements.txt](file:///C:/Users/amitk/OneDrive/Desktop/Testing/requirements.txt)
25
- - Add `psycopg2-binary` (PostgreSQL driver for Python).
26
-
27
- #### [MODIFY] [.env.example](file:///C:/Users/amitk/OneDrive/Desktop/Testing/.env.example)
28
- - Add `SUPABASE_DB_URL` or `DATABASE_URL` example pointing to the Supabase connection string format.
29
-
30
- ### Supabase Setup (One-time, manual)
31
-
32
- > [!IMPORTANT]
33
- > You need to get your Supabase **Connection String** (Session Mode / Pooler) from your project's **Settings β†’ Database** page.
34
-
35
- The connection string format is:
36
- ```
37
- postgresql://postgres.<project-ref>:<password>@aws-0-<region>.pooler.supabase.com:5432/postgres
38
- ```
39
-
40
- Set this as `DATABASE_URL` in your `.env` file. SQLAlchemy's `create_all()` will automatically create the tables on first boot.
41
-
42
- ---
43
-
44
- ## Tables That Will Be Created
45
-
46
- | Table | Description |
47
- |---|---|
48
- | `spec_documents` | API collections/specs with credentials and plans |
49
- | `sessions` | Active test sessions and context |
50
- | `execution_history` | Step-by-step results from test runs |
51
- | `collections` | Logical groupings for assets |
52
- | `assets` | Uploaded files (audio, video, docs, images) |
53
- | `asset_collections` | Many-to-many junction table |
54
-
55
- ---
56
-
57
- ## Verification Plan
58
-
59
- ### Automated Tests
60
- - Run `npm run dev` and start the backend β€” no startup errors should occur.
61
- - Upload a spec, run a plan, and verify data persists in Supabase's Table Editor.
62
-
63
- ### Manual Verification
64
- - Visit Supabase β†’ Table Editor and confirm all 6 tables exist with the correct columns.
65
- - Add a collection, then restart the server β€” data should still be present.