Trae Loop Engineering Guide
Complete guide to Trae (ByteDance) for loop engineering — build-on-reference mode, autonomous agent, and free AI-powered coding workflows.
Introduction: What Is Trae?
Trae is ByteDance's AI-native Integrated Development Environment -- the same company behind TikTok, Douyin, and a sprawling ecosystem of consumer applications. Launched internationally on January 19, 2025, Trae represents China's first purpose-built AI IDE, branded as "The Real AI Engineer."
Unlike traditional IDEs that bolt AI features onto an existing editor, Trae was designed from the ground up around the concept of an AI agent as first-class citizen in the development workflow. The core philosophy: the developer describes intent, and the AI agent autonomously plans, writes, tests, and iterates on code -- with the human guiding decisions rather than typing syntax.
For loop engineering practitioners, Trae offers something unique: a free IDE with premium AI models (Claude, GPT-4o, Gemini 2.5 Pro, DeepSeek R1), a fully autonomous agent mode called SOLO, and a Build-on-Reference pipeline that converts screenshots and design mockups into working code. These capabilities map directly onto the core loop engineering pattern: define a goal, let the AI agent attempt implementation, review the output, and iterate until quality standards are met.
ByteDance's AI Coding Ecosystem
================================
+------------------+ +------------------+ +------------------+
| TikTok / | | Trae IDE | | Trae Agent |
| Douyin |---->| (VS Code fork) |---->| CLI (open-src) |
| (Consumer) | | GUI-based | | Terminal-based |
+------------------+ +------------------+ +------------------+
|
+--------------+--------------+
| | |
+-----------+ +-----------+ +-----------+
| Claude | | GPT-4o | | DeepSeek |
| Sonnet | | 4.1 | | R1 |
+-----------+ +-----------+ +-----------+
| | |
+--------------+--------------+
|
Shared AI Agent Layer
(SOLO + Builder + Chat)
Why Trae Matters for Loop Engineering
Loop engineering is the practice of injecting engineering rigor into AI-assisted development through structured plan-code-review-iterate cycles. Trae's architecture is uniquely aligned with this methodology:
- Autonomous execution via SOLO mode means the AI agent completes full implementation cycles without manual intervention
- Session memory (Agent 2.0) retains context across loop iterations, so each cycle builds on the last
- Built-in terminal integration allows the agent to run tests, observe failures, and self-correct -- closing the feedback loop
- Build-on-Reference mode creates a design-to-code loop where visual fidelity can be iteratively improved
The result is a development environment where the loop engineering cycle runs at machine speed, with human judgment injected at the right checkpoints.
Architecture: Inside ByteDance's AI IDE
Trae is built on a VS Code / Code OSS fork, which means it inherits the familiar Electron + Monaco editor architecture that millions of developers already know. On top of this foundation, ByteDance has layered a sophisticated AI integration stack.
Three-Layer Architecture
Trae IDE -- Technical Architecture
===================================
+----------------------------------------------------------+
| LAYER 3: AI INTEGRATION |
| +----------------------------------------------------+ |
| | Multi-Model LLM Router | |
| | [Claude] [GPT-4o] [Gemini 2.5] [DeepSeek R1] | |
| +----------------------------------------------------+ |
| | Agent Orchestration | |
| | SOLO Mode | Builder Mode | Chat (Agent 2.0) | |
| +----------------------------------------------------+ |
| | Tool Layer | |
| | File Edit | Terminal | Browser Preview | MCP | |
| | 140+ MCP servers supported | |
| +----------------------------------------------------+ |
+----------------------------------------------------------+
| LAYER 2: BYTEDANCE INFRASTRUCTURE |
| +----------------------------------------------------+ |
| | Session Memory (Agent 2.0 long-term context) | |
| | TRAE Rules (project-level coding standards) | |
| | TRAE Skills (reusable task templates) | |
| | Model routing and API management | |
| +----------------------------------------------------+ |
+----------------------------------------------------------+
| LAYER 1: VS CODE / CODE OSS FORK |
| +----------------------------------------------------+ |
| | Electron Shell | |
| | Monaco Editor (syntax highlighting, multi-cursor) | |
| | Extension Host (VS Code extensions compatible) | |
| | LSP, Terminal, File Explorer, Debug Adapter | |
| +----------------------------------------------------+ |
+----------------------------------------------------------+
Agent 2.0: The Unified Full Agent Architecture
In 2026, Trae introduced Agent 2.0, a significant architectural shift that elevated Chat mode to the same autonomy level as Builder mode. Previously, Chat was reactive (answer questions, generate snippets) while Builder was autonomous (plan, scaffold, iterate). Agent 2.0 unified these into a single full agent architecture where every interaction mode has access to the same tools:
- File editing across the entire workspace
- Terminal command execution for builds, tests, and git operations
- Browser preview for visual verification
- MCP tool calls for external data sources
- Test-time scaling at inference time for improved reasoning (documented in an arXiv paper)
This unification is critical for loop engineering because it means the review-iterate cycle is seamless regardless of which mode you start in. You can begin with a conversational prompt, escalate to autonomous execution, review results, and refine -- all within a single session.
Trae Agent CLI: Open-Source Terminal Agent
For developers who prefer terminal-based workflows, ByteDance open-sourced the Trae Agent CLI (bytedance/trae-agent on GitHub). This CLI tool provides:
- File editing and project scaffolding from the terminal
- Bash command execution for builds and tests
- Structured thinking chains for complex reasoning tasks
- Task completion workflows with built-in retry logic
The CLI agent uses the same underlying architecture as the GUI IDE, making it suitable for CI/CD integration and automated loop engineering pipelines.
MCP Server Integration
Trae supports 140+ MCP (Model Context Protocol) servers, allowing the AI agent to connect with external tools and data sources. Three transport types are supported. Common integrations include:
| MCP Server | Use Case for Loop Engineering |
|---|---|
| Database connectors | Agent queries actual schema to generate accurate migrations |
| API documentation | Agent references live API specs for correct endpoint usage |
| Testing frameworks | Agent runs tests and reads results for auto-correction loops |
| CI/CD systems | Agent monitors build status and iterates on failures |
| Design tools (Figma) | Agent pulls latest design specs for Build-on-Reference mode |
Key Features for Loop Engineering
Build-on-Reference Mode (Design to Code)
Trae's Builder Mode with Build-on-Reference is one of its most distinctive features. Instead of describing UI in natural language and hoping the AI interprets it correctly, you provide a visual reference -- a screenshot, UI mockup, or design draft -- and Trae generates the corresponding code.
Build-on-Reference Loop
=======================
+------------------+ +------------------+
| Design Mockup | | Generated Code |
| (Screenshot / |------->| (HTML/CSS/ |
| Figma export) | | Components) |
+------------------+ +------------------+
|
v
+------------------+ +------------------+
| Iteration N+1 |<-------| Live Preview |
| (Refined code | | (Built-in |
| based on diff) | | webview) |
+------------------+ +------------------+
This creates a tight design-to-code loop:
- Input: Paste or upload a screenshot of the target UI
- Generate: Trae analyzes the visual layout and produces matching code
- Preview: Use the built-in webview to compare generated output with the reference
- Iterate: Describe specific differences ("the sidebar should be 240px wide, not 320px") and Trae regenerates
For loop engineering, this pattern is powerful because the feedback signal is visual and immediate. You can see exactly how close the generated code is to the target design, making the review step fast and objective.
Code Example -- Generating a Component from a Screenshot:
// After providing a screenshot reference in Builder Mode,
// Trae generates components like this:
// src/components/Dashboard.tsx
export function Dashboard() {
return (
<div className="flex h-screen bg-gray-50">
{/* Sidebar -- 240px, dark background */}
<aside className="w-60 bg-slate-900 text-white p-6">
<div className="flex items-center gap-3 mb-8">
<div className="w-8 h-8 rounded-lg bg-indigo-500" />
<span className="font-semibold text-lg">Dashboard</span>
</div>
<nav className="space-y-1">
{navItems.map((item) => (
<a
key={item.id}
href={item.path}
className={cn(
"flex items-center gap-3 px-3 py-2 rounded-lg text-sm",
item.active
? "bg-indigo-500/20 text-indigo-300"
: "text-slate-400 hover:bg-slate-800"
)}
>
<item.icon className="w-5 h-5" />
{item.label}
</a>
))}
</nav>
</aside>
{/* Main content area */}
<main className="flex-1 p-8 overflow-auto">
<header className="flex items-center justify-between mb-8">
<h1 className="text-2xl font-bold text-gray-900">
Overview
</h1>
<div className="flex items-center gap-4">
{/* Stat cards */}
<StatCard title="Revenue" value="$45,231" change="+20.1%" />
<StatCard title="Users" value="2,350" change="+15.3%" />
</div>
</header>
</main>
</div>
);
}
After the initial generation, the loop continues with targeted refinements:
# Prompt: "Make the sidebar collapsible with a hamburger button"
# Prompt: "Change stat cards to use sparkline charts"
# Prompt: "Add a notification bell with a badge count"
Each prompt triggers a new iteration cycle, and Trae applies changes while preserving the existing working code.
SOLO Mode: Autonomous Agent Coding
SOLO mode is Trae's flagship autonomous coding agent, which reached General Availability (GA) in November 2025 with version 3.0.0. SOLO operates on a fundamentally different paradigm than traditional code completion or chat-based assistance.
SOLO Mode -- Autonomous Loop
=============================
Human Input AI Agent Execution Output
============ ================== ======
"Build a REST +---------------------+
API with auth, | 1. PLAN |
CRUD for users | - Read project | +------------------+
and posts" | structure |------>| scaffold/ |
| - Design schema | | project/ |
+---------------------+ | - Plan files | | api/ |
| 2. IMPLEMENT | | - Order tasks | | src/ |
| - Create routes |+---------------------+ | tests/ |
| - Write models | +--->+ package.json |
| - Add middleware | 3. EXECUTE | +------------------+
| - Generate tests | - Write files |
| - Run build | - Install deps |
+---------------------+ | - Run tests |-----> Terminal output
| - Fix errors | (auto-shown in
+---------------------+ | - Iterate | IDE panel)
| 4. REVIEW & REPORT | |
| - Summary of | 5. SELF-CORRECT | +------------------+
| changes | - Read test fail |------>| Working |
| - Files modified | - Fix root cause | | implementation |
| - Tests status | - Re-run tests | +------------------+
+---------------------+ +---------------------+
Key SOLO capabilities for loop engineering:
| Capability | Description | Loop Engineering Application |
|---|---|---|
| Project scaffolding | Creates full project structure from a description | Jumpstarts the initial loop cycle |
| Multi-file editing | Simultaneously modifies files across the workspace | Maintains consistency across iterations |
| Terminal execution | Runs build, test, and lint commands autonomously | Closes the feedback loop automatically |
| Error auto-correction | Reads terminal errors and applies fixes | Self-healing loop iterations |
| Multi-tasking | Works on multiple tasks concurrently | Parallel loop execution |
| SOLO Coder | Specialized agent for complex programming tasks | Deep reasoning for difficult problems |
Example SOLO prompt for a feature implementation loop:
Implement user authentication with the following requirements:
- JWT-based auth with refresh tokens
- Registration with email verification
- Password reset flow
- Rate limiting on auth endpoints
- Use the existing User model in src/models/User.ts
- Write tests for all endpoints
- Ensure all existing tests still pass
Tech stack: Express.js, TypeScript, Prisma ORM, Jest
SOLO will plan the implementation, create the necessary files, write the code, run the tests, fix any failures, and report back with a summary -- all autonomously. The human then reviews the output, provides feedback, and SOLO iterates.
Real-Time Code Completion
Trae provides inline code completion powered by LLMs. As you type, Trae analyzes the current context -- open files, project structure, recent edits, and inline comments -- and generates grayed-out suggestions that you accept with Tab.
Real-Time Completion Flow
=========================
Developer types: Trae suggests (ghosted):
================ ========================
function fetchUsers( function fetchUsers(
page: number, page: number,
limit: number limit: number
): Promise< ): Promise<{
User[] data: User[];
} { total: number;
const resp }>
// fetch from API } {
const response = await fetch(
`/api/users?page=${page}&limit=${limit}`
);
const { data, total } = await response.json();
return { data, total };
}
For loop engineering, inline completion accelerates the manual refinement step within each cycle. When the AI agent's output needs small adjustments, the developer can accept smart completions rather than typing boilerplate manually.
Terminal Integration
Trae's terminal integration is a critical enabler for closed-loop engineering. The AI agent can execute commands in the terminal, read output, and make decisions based on results.
Terminal-Driven Auto-Correction Loop
====================================
+----------+ +------------+ +-----------+ +----------+
| Agent |---->| Execute |---->| Parse |---->| Fix |
| writes | | npm test | | output | | source |
| code | | | | | | code |
+----------+ +------------+ +-----------+ +----------+
^ |
| |
+----------------------------------------------------+
Loop continues until
all tests pass
Configuration options for terminal integration:
| Setting | Description | Recommended Value |
|---|---|---|
| Execution mode | How the agent runs terminal commands | Auto-approve for trusted commands |
| Command allowlist | Commands the agent can run without confirmation | npm test, npm run build, npm run lint |
| Output capture | How much terminal output the agent reads | Full output for test/build results |
| Timeout | Maximum execution time per command | 60 seconds for tests, 120 for builds |
Free Tier Availability
One of Trae's most compelling advantages is its free tier, which provides access to premium AI models at zero cost:
| Feature | Free Tier | Paid (Pro) |
|---|---|---|
| Cost | $0 | ~$10-30/month |
| AI Models | Claude 3.5-4.6, GPT-4o/4.1, Gemini 2.5 Pro, DeepSeek R1 | Same models, higher limits |
| Auto-completions | ~5,000/month | Unlimited |
| SOLO / Builder Mode | Full access | Full access |
| Cloud Tasks | Up to 10 concurrent | More concurrent |
| Pro Trial | 14-day trial available | -- |
ByteDance subsidizes the AI compute costs, making this the most generous free tier among AI IDEs. For loop engineering practitioners who run many iteration cycles per session, the free tier's ~5,000 completions per month is sufficient for most workflows, with SOLO mode handling the heavy lifting without consuming completion credits.
Fork Chat: Parallel Exploration
A unique Trae feature is Fork Chat, which allows you to branch from any point in an AI conversation to explore different directions:
Fork Chat -- Parallel Loop Exploration
=======================================
Original Conversation
=====================
[Message 1] "Build a payment module"
[Message 2] "Use Stripe for processing"
[Message 3] "Add webhook handling" <-- Fork point
|
+-------> Fork A: "Use subscription model"
| [A1] Generate subscription code
| [A2] Add billing portal
| [A3] Write tests
|
+-------> Fork B: "Use one-time payments"
[B1] Generate checkout flow
[B2] Add receipt generation
[B3] Write tests
This enables parallel loop engineering -- exploring multiple implementation approaches simultaneously, comparing results, and merging the best solution. It is particularly valuable during the planning phase when architectural decisions have high downstream impact.
Setting Up Trae for Loop Engineering
Installation
- Download Trae from trae.ai
- Install on macOS, Windows, or Linux
- Launch and import your existing project workspace
Trae is built on VS Code, so your existing settings, keybindings, and extensions transfer seamlessly.
Initial Configuration
After installation, configure these settings for optimal loop engineering:
// Trae Settings (Cmd/Ctrl + ,)
{
// Model selection -- Claude for reasoning, GPT-4o for speed
"trae.model.default": "claude-sonnet-4-20250514",
"trae.model.completion": "gpt-4o",
// Terminal execution -- enable auto-run for trusted commands
"trae.terminal.autoRunTests": true,
"trae.terminal.autoRunBuild": true,
"trae.terminal.commandTimeout": 60,
// Context configuration -- what the AI sees
"trae.context.includeFiles": [
"src/**/*.{ts,tsx,js,jsx}",
"package.json",
"tsconfig.json",
".env.example"
],
"trae.context.excludeFiles": [
"node_modules/**",
"dist/**",
"coverage/**",
"*.min.js"
],
// Agent behavior
"trae.agent.maxIterations": 10,
"trae.agent.autoFixOnTestFailure": true,
"trae.agent.reviewBeforeCommit": true
}
Configuring TRAE Rules
TRAE Rules are project-level configuration files that enforce coding standards and architectural preferences. Every loop iteration automatically respects these rules, reducing drift across AI-generated code cycles.
Create a .trae/rules.md file in your project root:
# TRAE Rules -- Project Conventions
## Code Style
- Use TypeScript strict mode for all new files
- Prefer functional components with hooks over class components
- Use named exports, not default exports
- Place utility functions in src/lib/
## Architecture
- API routes follow RESTful conventions in src/app/api/
- Database queries go through Prisma client in src/db/
- Shared types defined in src/types/
- Environment variables accessed via process.env with validation
## Testing
- All new functions must have unit tests
- Test files co-located with source: Component.test.tsx
- Use vitest for unit tests, playwright for e2e
- Coverage threshold: 80% for new code
## Commit Conventions
- Follow conventional commits: feat:, fix:, chore:
- Keep commits atomic -- one logical change per commit
- Reference issue numbers when applicable
Setting Up MCP Servers
Connect external tools to enhance the agent's context:
// .trae/mcp.json
{
"servers": {
"database": {
"type": "stdio",
"command": "npx",
"args": ["@trae/mcp-postgres", "postgresql://localhost/mydb"]
},
"figma": {
"type": "sse",
"url": "https://mcp.figma.com/sse/v1",
"headers": { "Authorization": "Bearer ${FIGMA_TOKEN}" }
},
"github": {
"type": "stdio",
"command": "npx",
"args": ["@trae/mcp-github"],
"env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
}
}
}
Model Selection Strategy
Different tasks benefit from different models. Configure Trae to use the right model for each loop engineering phase:
| Loop Phase | Recommended Model | Reason |
|---|---|---|
| Planning & Architecture | Claude Sonnet 4.6 | Best at multi-step reasoning |
| Code Generation | Claude Sonnet 4.6 or GPT-4o | Balanced speed and quality |
| Test Writing | DeepSeek R1 | Strong at edge case reasoning |
| Quick Completions | GPT-4o | Fastest inference latency |
| Complex Debugging | Claude Sonnet 4.6 | Best at following error chains |
| Documentation | GPT-4o | Natural language fluency |
Loop Patterns with Trae
Pattern 1: Design-to-Code Loop with Build-on-Reference
This pattern is ideal for frontend development where designs exist as screenshots or Figma mockups.
Design-to-Code Loop Pattern
============================
+------------------+
| 1. INPUT |
| Paste |
| screenshot |
| into Builder |
+--------+---------+
|
v
+------------------+ +------------------+
| 2. GENERATE |---->| 3. PREVIEW |
| Trae creates | | Built-in |
| component | | webview shows |
| code | | rendered UI |
+------------------+ +------------------+
| |
v v
+------------------+ +------------------+
| 4. COMPARE |<----| 5. DIFF CHECK |
| Visual side- | | Pixel-by- |
| by-side | | pixel analysis |
+--------+---------+ +------------------+
|
v
+------------------+
| 6. REFINE |
| "Sidebar is |
| too narrow, |
| increase to |
| 280px" |
+--------+---------+
|
| (Loop back to step 2)
+-------->
Implementation example:
# Step 1: Open Builder Mode (Cmd/Ctrl + Shift + B)
# Step 2: Paste the design screenshot
# Step 3: Trae generates initial code
# Output: src/components/DashboardLayout.tsx (187 lines)
# Step 4: Review in live preview
# Observation: Sidebar is 240px but design shows 280px
# Card border-radius is 8px but design shows 12px
# Step 5: Provide targeted feedback
# Prompt: "Fix three issues:
# 1. Sidebar width should be 280px
# 2. Card border-radius should be 12px
# 3. Header font weight should be 600, not 700"
# Step 6: Trae applies targeted fixes
# Step 7: Preview again -- confirm matches design
# Step 8: Accept and commit
Key principle: Each iteration targets specific, measurable differences between the current output and the desired outcome. This makes the loop converge quickly rather than generating progressively divergent code.
Pattern 2: Auto-Correction Loop with Terminal Commands
This pattern leverages Trae's terminal integration to create self-healing code loops.
# SOLO Mode prompt:
# "Implement the UserService class with CRUD operations.
# Write comprehensive unit tests.
# Run tests and fix any failures until all pass."
# What happens internally:
#
# Iteration 1:
# Agent generates UserService.ts + UserService.test.ts
# Agent runs: npm test -- UserService.test.ts
# Output: 3 passing, 2 failing
# - FAIL: deleteUser should throw if user not found
# - FAIL: updateUser should validate email format
#
# Iteration 2:
# Agent reads test output, identifies root causes
# Agent modifies UserService.ts:
# + Added null check in deleteUser
# + Added email validation with regex
# Agent runs: npm test -- UserService.test.ts
# Output: 5 passing, 0 failing
#
# Iteration 3 (verification):
# Agent runs full test suite: npm test
# Output: 142 passing, 0 failing (no regressions)
# Agent reports: "All tests passing. 2 files created, 1 modified."
Auto-Correction Loop -- Detailed Flow
=====================================
+-----------+ +----------+ +-----------+
| Generate |---->| Run |---->| Parse |
| Code | | Tests | | Results |
+-----------+ +----------+ +-----------+
^ |
| |
| +-----------+ +--------+ |
+-----| Analyze |<----| Fail? | |
| Root | | Yes | |
| Cause | +---+----+ |
+-----+-----+ | |
| | No |
| | |
| +-----+------+|
+---------| Report |
| Success |
+------------+
Pattern 3: Feature Implementation Loop
This pattern covers the full lifecycle of implementing a new feature using SOLO mode with human review checkpoints.
Feature Implementation Loop
============================
Phase 1: PLAN (Human + AI)
+---------------------------+
| Human provides feature |
| requirements and context |
| |
| SOLO analyzes codebase, |
| identifies files to |
| modify, creates plan |
+---------------------------+
|
v
Phase 2: IMPLEMENT (AI Agent)
+---------------------------+
| SOLO creates/modifies |
| files according to plan |
| |
| Writes new code, updates |
| existing files, creates |
| tests |
+---------------------------+
|
v
Phase 3: VERIFY (AI Agent)
+---------------------------+
| SOLO runs build, linter, |
| and tests |
| |
| Fixes any failures |
| autonomously |
+---------------------------+
|
v
Phase 4: REVIEW (Human)
+---------------------------+
| Human reviews: |
| - Code quality |
| - Architecture decisions |
| - Edge cases |
| - Security considerations |
+---------------------------+
|
v
Phase 5: ITERATE (Human + AI)
+---------------------------+
| Human provides feedback: |
| "Change X, fix Y, add Z" |
| |
| Loop back to Phase 2 |
+---------------------------+
Concrete example -- implementing a notification system:
# Phase 1: PLAN
# Prompt to SOLO:
# "Add a real-time notification system to our Next.js app.
# Requirements:
# - WebSocket connection using our existing Socket.io server
# - Notification bell in the header with unread count badge
# - Dropdown panel showing recent notifications
# - Mark-as-read functionality
# - Notification preferences stored in user settings
# Reference: src/components/layout/Header.tsx (existing header)
# src/lib/socket.ts (existing socket client)"
# Phase 2: IMPLEMENT (SOLO autonomously)
# SOLO creates:
# src/components/notifications/NotificationBell.tsx
# src/components/notifications/NotificationPanel.tsx
# src/components/notifications/NotificationItem.tsx
# src/hooks/useNotifications.ts
# src/lib/notificationTypes.ts
# SOLO modifies:
# src/components/layout/Header.tsx (adds NotificationBell)
# src/lib/socket.ts (adds notification event handlers)
# Phase 3: VERIFY (SOLO autonomously)
# SOLO runs: npm run build -> Success
# SOLO runs: npm run lint -> 0 warnings
# SOLO runs: npm test -> 87 passing, 0 failing
# Phase 4: REVIEW (Human inspects code)
# Feedback: "The NotificationPanel should lazy-load.
# Add loading skeleton and error boundary.
# Notifications should be grouped by date."
# Phase 5: ITERATE (Loop back to Phase 2)
# SOLO implements the feedback, re-verifies, reports back
Pattern 4: Code Migration Loop
Use this pattern when migrating code between frameworks, upgrading dependencies, or refactoring large codebases.
# Migration prompt for SOLO:
# "Migrate all class components in src/components/ to
# functional components with hooks.
#
# Rules:
# - Convert this.state to useState
# - Convert lifecycle methods: componentDidMount -> useEffect
# - Convert class methods to plain functions
# - Preserve all existing tests (update syntax if needed)
# - Run full test suite after each file conversion
# - Stop and report if any test fails after conversion
#
# Process:
# - Convert one file at a time
# - Run tests after each conversion
# - Fix any failures before proceeding to next file"
# Loop execution:
#
# File 1: src/components/UserProfile.tsx
# Convert class -> functional ... npm test ... PASS
#
# File 2: src/components/SearchBar.tsx
# Convert class -> functional ... npm test ... FAIL
# Error: SearchBar.test.tsx - ref access changed
# Fix: Update test to use useRef pattern ... npm test ... PASS
#
# File 3: src/components/DataGrid.tsx
# Convert class -> functional ... npm test ... PASS
#
# ... continues through all class components
Pattern 5: Documentation-Driven Development Loop
Use Trae to maintain documentation that stays in sync with code through iterative refinement.
# Prompt: "Generate API documentation for all routes in src/app/api/.
# Output as Markdown in docs/api-reference.md.
# Include request/response types, authentication requirements,
# rate limits, and example curl commands.
# Use the existing Zod schemas in src/schemas/ for type information."
# After generation, review and iterate:
# "The authentication section is incomplete -- add details about
# JWT token refresh and the 401 response format.
# Also add the new webhook endpoints from src/app/api/webhooks/."
# Each iteration enriches the documentation based on human review.
Best Practices and Configuration
1. Use TRAE Rules Aggressively
TRAE Rules are the single most impactful configuration for loop engineering. By defining project conventions, preferred patterns, and architectural decisions, every AI interaction automatically respects your standards. This prevents the common problem of AI-generated code drifting away from project conventions over successive loop iterations.
Key rules to configure:
- Import order: Enforce consistent import sorting
- Naming conventions: Specify camelCase, PascalCase, or your preferred style
- File organization: Define where new files should be created
- Technology choices: Lock in specific libraries (e.g., "use Zod for validation")
- Test requirements: Specify minimum coverage and testing patterns
2. Leverage Fork Chat for Exploration
When uncertain about an architectural approach, use Fork Chat to explore multiple paths in parallel rather than committing to one direction and discovering it was wrong three iterations later. This reduces the cost of exploration and accelerates convergence on the optimal solution.
When to Fork vs When to Continue
=================================
Fork the conversation when:
- Choosing between architectural patterns (REST vs GraphQL)
- Evaluating different libraries for the same task
- Comparing performance approaches (SSR vs CSR)
- Deciding on database schema design
Continue the conversation when:
- Refining implementation details
- Fixing specific bugs
- Adding incremental features
- Polishing UI output
3. Match Model to Task Complexity
Not every loop iteration needs the most powerful model. Reserve Claude for planning and complex reasoning, use GPT-4o for fast generation and completions, and try DeepSeek R1 for test generation and edge case analysis.
# Quick iteration -- use GPT-4o for speed
# Model: gpt-4o
# Prompt: "Add a loading state to the submit button"
# Complex reasoning -- use Claude for depth
# Model: claude-sonnet-4-20250514
# Prompt: "Refactor the authentication flow to support
# multi-factor auth while maintaining backward compatibility
# with existing sessions"
# Test generation -- use DeepSeek R1 for thoroughness
# Model: deepseek-r1
# Prompt: "Generate edge case tests for the payment processing
# module, covering timeout handling, partial payments,
# refund edge cases, and currency conversion rounding"
4. Manage Session Memory Wisely
Agent 2.0's long-term memory persists context across extended conversations. While powerful, this can accumulate stale context that confuses later iterations.
Best practices:
- Start a fresh session when switching to an unrelated task
- Explicitly tell Trae to "forget previous context about X" when changing direction
- For long sessions, periodically summarize what the agent should remember
- Use TRAE Rules for persistent preferences rather than relying on session memory
5. Review Before Accepting
Despite SOLO's autonomy, always review generated code before committing. Key areas to check:
- Security: Authentication, authorization, input validation
- Performance: N+1 queries, unnecessary re-renders, memory leaks
- Error handling: Graceful degradation, proper error messages
- Test quality: Tests that actually verify behavior, not just coverage
- Architectural consistency: New code follows established patterns
6. Use MCP Servers for Rich Context
Connect your project's data sources via MCP to give the AI agent accurate, real-time context:
- Database schemas: The agent generates correct queries and migrations
- API documentation: The agent uses correct endpoints and parameters
- Design systems: The agent references current component libraries
- Monitoring data: The agent can analyze error rates and performance metrics
Trae vs Windsurf: A Brief Comparison
Since both Trae and Windsurf are AI IDEs built on VS Code forks with autonomous agent modes, here is a focused comparison for loop engineering practitioners:
| Dimension | Trae | Windsurf (Codeium) |
|---|---|---|
| Pricing | Free (ByteDance subsidized) | $15-20/month |
| AI Models | Claude, GPT-4o, Gemini 2.5, DeepSeek | Multi-model |
| Autonomous Agent | SOLO Mode (GA Nov 2025) | Cascade / Flow |
| Screenshot to Code | Build-on-Reference (strong) | Limited |
| MCP Support | 140+ servers | Yes |
| Fork Chat | Yes (unique feature) | No |
| Free Tier | Full features, ~5K completions/mo | Credit-based, limited |
| Session Memory | Agent 2.0 long-term memory | Session-based |
| Privacy | ByteDance telemetry concerns | Standard Codeium policy |
| Open Source Agent | Yes (trae-agent CLI) | No CLI agent |
| Maturity | Newer (Jan 2025) | More established |
When to choose Trae: Budget-conscious developers, teams that need screenshot-to-code workflows, projects that benefit from Fork Chat exploration, and developers comfortable with ByteDance's data practices.
When to choose Windsurf: Teams with strict data privacy requirements, enterprises that need established vendor relationships, and developers who prefer a more mature product ecosystem.
For a deeper comparison, see Windsurf vs Trae for Loop Engineering.
Privacy Considerations
Before adopting Trae for production work, be aware of documented privacy characteristics:
- Telemetry: Trae maintains connections to multiple ByteDance domains, transmitting usage data, machine identifiers, and project metadata
- Data exposure: Code snippets sent to AI models are processed by third-party LLM providers (Anthropic, OpenAI, Google)
- Opt-out limitations: Some telemetry continues even when privacy settings are disabled (ByteDance attributes this to VS Code extension behavior)
- Enterprise option: TRAE Enterprise (launched 2026) offers enhanced privacy controls for organizations with compliance requirements
Developers handling proprietary code, working under compliance frameworks (SOC 2, HIPAA), or with strict data sovereignty requirements should evaluate whether Trae's free tier meets their obligations, or whether the Enterprise edition with enhanced controls is necessary.
Key Takeaways
- Trae is ByteDance's free AI IDE offering premium models (Claude, GPT-4o, Gemini 2.5, DeepSeek) at zero cost, making it the most accessible AI IDE for loop engineering practitioners
- SOLO mode provides true autonomous coding -- the AI agent plans, implements, tests, and self-corrects without manual intervention, enabling fully automated loop cycles
- Build-on-Reference mode creates a fast design-to-code loop where screenshots and mockups become working components through iterative visual comparison
- Agent 2.0's unified architecture means Chat, Builder, and SOLO modes all have full agent capabilities, enabling seamless transitions between interactive and autonomous workflows within a single loop cycle
- TRAE Rules are essential for loop engineering -- they prevent code drift across iterations by enforcing consistent standards without manual intervention
- Fork Chat enables parallel exploration -- a unique feature that lets loop engineering practitioners compare multiple implementation approaches before committing to one
- Terminal integration closes the feedback loop by letting the agent run tests, observe failures, and auto-correct, reducing human intervention in the test-fix cycle
- Privacy considerations matter -- ByteDance's telemetry practices require evaluation, especially for proprietary code and compliance-governed projects