Documentation
Core Features/AI Sandbox Debugging

AI Sandbox Debugging

ThinkCode's AI Sandbox is a revolutionary feature that allows you to debug and understand code behavior through AI-powered simulations. This guide explains how to leverage this powerful tool to solve complex problems and gain deeper insights into your code.

What is AI Sandbox Debugging?

AI Sandbox Debugging creates a secure, isolated environment where the AI can:

  1. Analyze code execution
  2. Simulate function calls and system behavior
  3. Trace variable states
  4. Identify logical errors
  5. Suggest improvements

Unlike traditional debugging that requires running code, AI Sandbox operates by creating mental models of how your code would execute.

graph TD
    A[Your Code] --> B[AI Sandbox]
    B --> C[Execution Simulation]
    B --> D[Variable Tracing]
    B --> E[Edge Case Detection]
    B --> F[Error Identification]
    
    C --> G[Debugging Insights]
    D --> G
    E --> G
    F --> G
    
    G --> H[Fix Suggestions]
    
    style B fill:#f96,stroke:#333,stroke-width:2px

When to Use AI Sandbox Debugging

AI Sandbox is particularly valuable when:

  • You're experiencing subtle bugs that are hard to reproduce
  • You want to understand complex code behavior without executing it
  • You need to identify edge cases and potential errors
  • Traditional debugging methods are impractical (e.g., in production environments)
  • You want to explore "what if" scenarios quickly

Getting Started with AI Sandbox

Accessing the Sandbox

There are several ways to access the AI Sandbox:

  1. From the Think Panel: Click the "Sandbox" button in the Think Panel
  2. Context Menu: Right-click on selected code and choose "Analyze in AI Sandbox"
  3. Command Palette: Press Ctrl+Shift+P (Cmd+Shift+P on macOS) and type "Think: Open AI Sandbox"
  4. Keyboard Shortcut: Press Ctrl+Alt+S (Cmd+Option+S on macOS)

Basic Sandbox Analysis

To perform a basic analysis:

  1. Select the code you want to analyze
  2. Access the AI Sandbox using one of the methods above
  3. The AI will:
    • Parse your code
    • Identify potential issues
    • Simulate execution paths
    • Provide insights about the code's behavior

Interactive Debugging

The AI Sandbox provides an interactive experience:

  1. You can ask questions about specific parts of the code
  2. Request explanations of the execution flow
  3. Test "what if" scenarios by modifying inputs
  4. Explore edge cases by specifying conditions

Key Features

Code Execution Simulation

The Sandbox simulates how your code executes:

function calculateDiscount(price, quantity) {
  let discount = 0;
  
  if (quantity > 10) {
    discount = 0.1;
  } else if (quantity > 5) {
    discount = 0.05;
  }
  
  return price * (1 - discount);
}

In this example, the Sandbox can:

  • Trace values of discount for different inputs
  • Show execution paths for various quantity values
  • Identify edge cases (e.g., negative quantities)
  • Detect possible numeric precision issues

Variable State Tracing

Track how variables change throughout code execution:

Input: calculateDiscount(100, 7)

Execution trace:
1. price = 100, quantity = 7
2. discount = 0
3. quantity > 10? No
4. quantity > 5? Yes
5. discount = 0.05
6. return 100 * (1 - 0.05) = 95

Edge Case Detection

The Sandbox automatically identifies edge cases:

Potential edge cases detected:

1. Zero price: calculateDiscount(0, 10) = 0
2. Negative quantity: calculateDiscount(100, -5) doesn't handle negative values
3. Zero quantity: calculateDiscount(100, 0) = 100
4. Float quantity: calculateDiscount(100, 5.5) treats as 5

Error Identification

The Sandbox detects potential runtime errors:

function processUserData(user) {
  const fullName = user.firstName + ' ' + user.lastName;
  const age = calculateAge(user.birthDate);
  return { fullName, age };
}

Sandbox analysis might show:

Potential errors detected:

1. TypeError if 'user' is null or undefined
2. TypeError if 'user.firstName' or 'user.lastName' is undefined
3. Reference to undeclared function 'calculateAge'
4. Potential date parsing issues in 'calculateAge'

Advanced Sandbox Techniques

Multi-File Analysis

AI Sandbox can analyze code that spans multiple files:

  1. Select the main function or entry point
  2. The AI will trace references and dependencies across files
  3. Provide a holistic analysis of the entire execution path

Data Flow Analysis

Trace how data moves through your application:

Input data flow:
user input → validateInput() → transformData() → processResult()

When input = "John123":
1. validateInput("John123") → passes validation
2. transformData("John123") → extracts "John" and "123"
3. processResult({name: "John", id: 123}) → returns formatted output

Regression Testing

Test changes to ensure they don't break existing functionality:

  1. Select the modified code
  2. Ask the Sandbox to compare behavior before and after changes
  3. Identify potential issues with the changes

Collaborative Debugging

Share sandbox sessions with teammates:

  1. Click "Share Sandbox" in the sandbox interface
  2. Send the generated link to teammates
  3. Collaborate on the same session with shared context

Sandbox Debug Commands

The AI Sandbox responds to specific debug commands:

CommandDescription
trace variable [name]Show how a variable changes through execution
explain line [number]Get detailed explanation of a specific line
show execution pathDisplay all possible execution paths
find edge casesIdentify potential edge cases
predict output for [input]Simulate output for a specific input
suggest fix for [issue]Get AI suggestions to fix a specific issue
optimize [goal]Get optimization suggestions (performance, memory, etc.)

Real-World Examples

Example 1: Debugging a Recursive Function

function fibonacci(n) {
  if (n <= 0) return 0;
  if (n === 1) return 1;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

Sandbox analysis:

Performance issue detected:
The fibonacci function has exponential time complexity O(2^n) due to redundant calculations.

Execution trace for fibonacci(5):
fibonacci(5)
├─ fibonacci(4) + fibonacci(3)
│  ├─ fibonacci(3) + fibonacci(2)
│  │  ├─ fibonacci(2) + fibonacci(1)
│  │  │  ├─ fibonacci(1) + fibonacci(0)
│  │  │  │  ├─ return 1
│  │  │  │  └─ return 0
│  │  │  └─ return 1
│  │  └─ return 1 + 1 = 2
│  └─ fibonacci(2) + fibonacci(1)
│     ├─ fibonacci(1) + fibonacci(0)
│     │  ├─ return 1
│     │  └─ return 0
│     └─ return 1
├─ return 3 + 2 = 5

Recommendation: Implement memoization to avoid redundant calculations.

Example 2: Asynchronous Code Analysis

async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) throw new Error('User not found');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch user data:', error);
    return null;
  }
}

Sandbox analysis:

Asynchronous flow analysis:

Happy path:
1. Call fetch() with URL `/api/users/${userId}`
2. Await Promise resolution
3. Check if response.ok is true
4. Call response.json()
5. Await Promise resolution
6. Return parsed data

Error paths:
1. Network error in fetch(): moves to catch block, returns null
2. response.ok is false: throws Error('User not found'), moves to catch block, returns null
3. Error in response.json(): moves to catch block, returns null

Potential issues:
1. Function returns different types (object or null) which may cause issues for callers
2. No timeout handling for slow network requests
3. Specific HTTP error codes are not handled differently

Best Practices

Preparing Code for Sandbox Analysis

For the best results when using AI Sandbox:

  1. Select complete functions: Include the entire function rather than fragments
  2. Include necessary context: Make sure the Sandbox can see relevant imports and dependencies
  3. Specify inputs: Provide example inputs for more accurate analysis
  4. Ask specific questions: Be clear about what aspects you want to analyze

Interpreting Sandbox Results

When reviewing Sandbox analysis:

  1. Verify findings: Cross-check the AI's analysis with your understanding
  2. Prioritize issues: Focus on critical issues like security vulnerabilities first
  3. Test suggestions: Always test the AI's suggested fixes in your actual environment
  4. Look for patterns: Identify recurring issues that might indicate systemic problems

Enhancing Sandbox with Documentation

Improve Sandbox accuracy with good documentation:

  1. Add type annotations: Helps the Sandbox understand expected data types
  2. Include JSDoc/docstrings: Provides context about function purpose and parameters
  3. Document assumptions: Note any assumptions your code makes
  4. Explain complex logic: Add comments for complex algorithms or business logic

Troubleshooting

Common Sandbox Issues

IssueSolution
Inaccurate analysisProvide more context, including imports and related code
Missing dependenciesEnsure all referenced files are in your workspace
Complex logic confusionBreak down complex functions into smaller parts
Language-specific featuresSpecify the exact language/runtime version you're using
Performance constraintsLimit analysis to smaller code segments

Feedback and Improvement

The AI Sandbox learns from feedback:

  1. Use the "Helpful" / "Not Helpful" buttons in the Sandbox interface
  2. Provide specific feedback on what was accurate or inaccurate
  3. Report recurring issues through ThinkCode's feedback channels

Advanced Configuration

Customize the AI Sandbox behavior:

{
  "think.sandbox.maxDepth": 10,
  "think.sandbox.timeout": 30000,
  "think.sandbox.includeNodeModules": false,
  "think.sandbox.preferredLanguages": {
    "typescript": true,
    "javascript": true,
    "python": true
  }
}

Next Steps

To further enhance your debugging skills with ThinkCode:

Pro Tip

Use AI Sandbox in tandem with traditional debugging for the best results. Start with Sandbox to identify potential issues, then verify with actual execution if needed.