Examples & Use Cases
Real-world examples of using Dropstone Agent for common development tasks
This guide provides practical, real-world examples of using Dropstone Agent for common development tasks. Each example includes the conversation, what the agent does, and the results.
Table of Contents
- Creating New Features
- Bug Fixing
- Refactoring Code
- Adding Tests
- Code Understanding
- Database & API Work
- UI/UX Implementation
- Performance Optimization
Creating New Features
Example 1: Adding User Authentication
Context: React app without authentication
Conversation:
You: "Add user authentication with login and registration"
Agent: "I'll implement authentication. A few questions:
- Backend framework? (Express, NestJS, etc.)
- Auth method? (JWT, sessions, OAuth?)
- Database? (MongoDB, PostgreSQL, etc.)
- Password requirements?"
You: "Express backend, JWT tokens, MongoDB, standard password requirements"
Agent: "Creating authentication system...
Backend:
✓ Created User model (models/User.ts)
✓ Added password hashing with bcrypt
✓ Created auth routes (routes/auth.ts)
✓ Implemented JWT token generation
✓ Added auth middleware
Frontend:
✓ Created login form (components/Login.tsx)
✓ Created registration form (components/Register.tsx)
✓ Added auth context (contexts/AuthContext.tsx)
✓ Implemented protected routes
✓ Added token storage
Tests:
✓ Auth API tests (15 cases)
✓ Component tests (8 cases)
All tests passing. Try logging in!"
Files Created/Modified:
backend/models/User.ts
backend/routes/auth.ts
backend/middleware/auth.ts
frontend/components/Login.tsx
frontend/components/Register.tsx
frontend/contexts/AuthContext.tsx
frontend/components/ProtectedRoute.tsx
- Tests for all components
Time: 8 minutes (vs. 2-3 hours manually)
Example 2: Building a Dashboard
Conversation:
You: "Create an analytics dashboard showing user stats, sales, and activity"
Agent: "I'll create the dashboard. What data sources?"
You: "@src/api/analytics.ts This API provides the data"
Agent: "Creating dashboard...
Components:
✓ DashboardLayout with sidebar
✓ StatsCard component for metrics
✓ UserActivityChart (Chart.js)
✓ SalesGraph (last 30 days)
✓ RecentActivityTable
Features:
✓ Real-time data updates
✓ Loading states
✓ Error handling
✓ Responsive design
✓ Export to CSV button
Dashboard ready at /dashboard"
Result: Complete analytics dashboard with charts, tables, and real-time updates
Bug Fixing
Example 3: Fixing Login Issue
Conversation:
You: "@mode debug
Users can't login - they get 'Invalid credentials' even with correct password"
Agent: [Debug Mode]
"Investigating login issue...
Hypothesis Generation:
1. Password comparison error (70%)
2. Database query issue (20%)
3. Token generation problem (10%)
Checking password comparison logic..."
[Reads auth controller]
Agent: "Found the issue!
Root Cause:
In UserController.login(), password comparison uses:
`user.password === inputPassword`
Problem:
- Stored password is hashed
- Input password is plaintext
- Direct comparison always fails
Fix:
Use bcrypt.compare() instead:
`await bcrypt.compare(inputPassword, user.password)`
Location: controllers/UserController.ts:45
Should I apply the fix?"
You: "Yes"
Agent: "✓ Fixed password comparison
✓ Updated tests
✓ All 23 auth tests passing
Login working correctly now!"
Before:
if (user.password === inputPassword) {
// This never works!
}
After:
const isValid = await bcrypt.compare(inputPassword, user.password);
if (isValid) {
// Correct comparison
}
Example 4: Memory Leak Fix
Conversation:
You: "@mode debug
App becomes slow after running for a while. Memory usage keeps growing."
Agent: [Debug Mode]
"Analyzing memory issue...
Checking for common causes:
✓ Event listeners cleanup
✓ Interval/timeout cleanup
✓ React useEffect cleanup
✓ WebSocket connections
Found 3 potential leaks:
1. UserListComponent: setInterval never cleared
2. ChatComponent: WebSocket not closed
3. DashboardComponent: Event listeners not removed
Proposing fixes..."
[Shows fixes for each]
Agent: "Applied fixes:
✓ Added cleanup to useEffect hooks
✓ Proper WebSocket close on unmount
✓ Event listener removal
Memory leak resolved!
Tested: Memory stable after 1 hour runtime"
The Fix:
// Before
useEffect(() => {
const interval = setInterval(fetchData, 5000);
// Missing cleanup!
}, []);
// After
useEffect(() => {
const interval = setInterval(fetchData, 5000);
return () => clearInterval(interval); // ✓ Cleanup
}, []);
Refactoring Code
Example 5: Extract Service Layer
Conversation:
You: "This controller has too much logic. Extract it to a service layer."
@src/controllers/UserController.ts
Agent: "Refactoring to service layer...
Analyzing UserController:
- 8 methods with business logic
- Database queries in controller
- Validation mixed with logic
Creating UserService:
✓ Extracted business logic
✓ Moved database operations
✓ Added proper error handling
Updated UserController:
✓ Thin controller layer
✓ Delegates to service
✓ Handles HTTP concerns only
Structure:
controllers/UserController.ts → HTTP layer
services/UserService.ts → Business logic
models/User.ts → Data model
All 45 tests still passing!"
Before:
// Controller with everything
class UserController {
async create(req, res) {
// Validation
// Business logic
// Database operations
// Response formatting
}
}
After:
// Clean separation
class UserController {
async create(req, res) {
const user = await userService.create(req.body);
res.json({ data: user });
}
}
class UserService {
async create(userData) {
// Business logic
// Database operations
return user;
}
}
Example 6: Component Refactoring
Conversation:
You: "This UserProfile component is 500 lines. Break it into smaller components."
@src/components/UserProfile.tsx
Agent: "Refactoring UserProfile...
Identified sections:
1. Profile header (avatar, name, stats)
2. About section (bio, location, links)
3. Activity feed
4. Settings panel
Creating components:
✓ ProfileHeader.tsx
✓ ProfileAbout.tsx
✓ ProfileActivity.tsx
✓ ProfileSettings.tsx
✓ Updated UserProfile.tsx (now 80 lines)
Each component:
✓ Single responsibility
✓ Reusable
✓ Tested independently
Refactoring complete!"
Result:
- 1 large component → 4 focused components
- Better testability
- Easier maintenance
- Reusable pieces
Adding Tests
Example 7: Test Suite Generation
Conversation:
You: "Generate comprehensive tests for the shopping cart logic"
@src/services/CartService.ts
Agent: "Generating test suite for CartService...
Analyzing CartService methods:
- addItem
- removeItem
- updateQuantity
- calculateTotal
- applyDiscount
- clearCart
Creating tests:
✓ Happy path tests (12 cases)
✓ Edge cases (18 cases)
✓ Error scenarios (10 cases)
✓ Integration tests (8 cases)
Generated 48 test cases covering:
- Empty cart operations
- Invalid inputs
- Boundary conditions
- Concurrent updates
- Discount calculations
- Total accuracy
Coverage: 96%
All tests passing!"
Generated Tests Include:
describe('CartService', () => {
describe('addItem', () => {
it('should add item to empty cart')
it('should increase quantity if item exists')
it('should handle invalid quantity')
it('should validate product ID')
})
describe('calculateTotal', () => {
it('should calculate with no discount')
it('should apply percentage discount')
it('should handle multiple discounts')
it('should round to 2 decimals')
})
// ... 40 more test cases
})
Example 8: Adding Tests to Legacy Code
Conversation:
You: "Add tests to this old code that has zero tests"
@src/legacy/PaymentProcessor.js
Agent: "Adding tests to PaymentProcessor...
Challenges detected:
- Tightly coupled code
- External dependencies
- No injection points
Strategy:
1. Create mocks for external services
2. Add minimal refactoring for testability
3. Generate comprehensive tests
Changes:
✓ Added dependency injection
✓ Created mock payment gateway
✓ Generated 35 test cases
Tests cover:
- Successful payments
- Failed payments
- Network errors
- Invalid card data
- Refund scenarios
Coverage: 87% (previously 0%)"
Code Understanding
Example 9: Explaining Complex Code
Conversation:
You: "@mode ask
@src/algorithms/recommendation.ts
How does this recommendation algorithm work?"
Agent: [Ask Mode]
"This recommendation algorithm uses collaborative filtering
with matrix factorization. Let me break it down:
## High-Level Flow
1. User-Item Matrix
- Rows: Users
- Columns: Items
- Values: Ratings/interactions
2. Matrix Factorization
- Decomposes into user/item feature matrices
- Finds latent factors
3. Similarity Calculation
- Cosine similarity between users
- Weighted by confidence scores
4. Recommendation Generation
- Finds similar users
- Aggregates their preferences
- Ranks items by predicted score
## Key Functions
### buildUserItemMatrix()
```typescript
// Creates sparse matrix from user interactions
const matrix = users.map(user => {
return items.map(item =>
user.ratings[item.id] || 0
);
});
factorizeMatrix()
Uses SGD (Stochastic Gradient Descent) to find:
- User features (tastes/preferences)
- Item features (characteristics)
generateRecommendations()
// For target user
const similarUsers = findSimilarUsers(targetUser);
const recommendations = aggregatePreferences(similarUsers);
return rankByPredictedScore(recommendations);
Example
User A likes: [Item1, Item2, Item3] User B likes: [Item2, Item3, Item4] User C likes: [Item1, Item2]
Algorithm finds: A and B are similar Recommends to A: Item4 (because B likes it)
Complexity
Time: O(n * m * k)
- n: users
- m: items
- k: iterations
Space: O(n * m)
Need help implementing something similar?"
---
### Example 10: Architecture Explanation
**Conversation:**
You: "@mode ask Explain how our microservices communicate"
Agent: [Ask Mode] "Your microservices use an event-driven architecture with RabbitMQ.
Architecture Overview
graph LR
A[API Gateway] --> B[Auth Service]
A --> C[User Service]
A --> D[Order Service]
B -.-> E[RabbitMQ]
C -.-> E
D -.-> E
E -.-> F[Notification Service]
E -.-> G[Analytics Service]
Communication Patterns
Synchronous (REST)
- API Gateway → Services
- Direct HTTP calls
- Immediate response needed
Asynchronous (Events)
- Service → RabbitMQ → Service
- Fire and forget
- Eventual consistency
Event Flow Example
Order Creation:
- Order Service receives request
- Creates order in database
- Publishes 'order.created' event
- Notification Service listens
- Sends email to user
- Analytics Service listens
- Updates sales metrics
Message Format
{
"event": "order.created",
"timestamp": "2024-03-20T10:30:00Z",
"data": {
"orderId": "123",
"userId": "456",
"total": 99.99
}
}
Benefits
✓ Loose coupling ✓ Scalable ✓ Resilient ✓ Async processing
Challenges
⚠️ Eventual consistency ⚠️ Message ordering ⚠️ Error handling ⚠️ Debugging distributed
Want me to add a new service or event?"
---
## Database & API Work
### Example 11: Database Schema Design
**Conversation:**
You: "@mode architect Design a database for a blog platform with posts, comments, and tags"
Agent: [Architect Mode] "Designing blog database schema...
erDiagram
User ||--o{ Post : writes
User ||--o{ Comment : writes
Post ||--o{ Comment : has
Post }o--o{ Tag : tagged
User {
uuid id PK
string email UK
string username UK
string passwordHash
timestamp createdAt
}
Post {
uuid id PK
uuid authorId FK
string title
string slug UK
text content
enum status
timestamp publishedAt
}
Comment {
uuid id PK
uuid postId FK
uuid authorId FK
uuid parentId FK
text content
}
Tag {
uuid id PK
string name UK
}
PostTag {
uuid postId FK
uuid tagId FK
}
Key Decisions
-
UUIDs vs Auto-increment
- Chose UUIDs for distributed system support
-
Comment Threading
- Self-referencing parentId
- Supports nested comments
-
Tags (Many-to-Many)
- Junction table PostTag
- Efficient querying
-
Soft Deletes
- Add deletedAt timestamp
- Preserve data
Indexes
CREATE INDEX idx_posts_author ON posts(authorId);
CREATE INDEX idx_posts_slug ON posts(slug);
CREATE INDEX idx_posts_published ON posts(publishedAt)
WHERE status = 'published';
CREATE INDEX idx_comments_post ON comments(postId);
Ready to implement?"
---
### Example 12: API Endpoint Creation
**Conversation:**
You: "Create a REST API for managing blog posts with full CRUD"
Agent: "Creating Posts API...
Endpoints: ✓ GET /api/posts - List all posts ✓ GET /api/posts/:id - Get single post ✓ POST /api/posts - Create post ✓ PUT /api/posts/:id - Update post ✓ DELETE /api/posts/:id - Delete post
Features: ✓ Pagination (limit, offset) ✓ Filtering (status, author) ✓ Sorting (date, title) ✓ Search (title, content) ✓ Authentication required ✓ Input validation (Joi) ✓ Error handling
Tests: ✓ 35 test cases ✓ All CRUD operations ✓ Edge cases covered
API ready at /api/posts"
**Example Usage:**
```bash
# List posts
GET /api/posts?limit=10&status=published&sort=-createdAt
# Create post
POST /api/posts
{
"title": "My Post",
"content": "...",
"tags": ["tech", "tutorial"]
}
# Update post
PUT /api/posts/123
{
"title": "Updated Title"
}
UI/UX Implementation
Example 13: Responsive Navigation
Conversation:
You: "Create a responsive navigation bar with mobile menu"
Agent: "Creating responsive navigation...
Desktop View:
✓ Horizontal nav bar
✓ Logo left, links right
✓ Dropdown for user menu
✓ Search bar
Mobile View (<768px):
✓ Hamburger menu
✓ Slide-in drawer
✓ Touch-friendly spacing
✓ Search in drawer
Features:
✓ Smooth animations
✓ Accessibility (ARIA labels)
✓ Keyboard navigation
✓ Active route highlighting
Components:
- Navbar.tsx (main component)
- MobileMenu.tsx
- NavLink.tsx
- UserMenu.tsx
Ready to use!"
Result:
<Navbar>
<NavLogo />
<NavLinks /> {/* Hidden on mobile */}
<SearchBar />
<UserMenu />
<MobileMenuButton /> {/* Visible on mobile */}
</Navbar>
<MobileDrawer isOpen={isOpen}>
<NavLinks vertical />
<SearchBar />
</MobileDrawer>
Example 14: Form with Validation
Conversation:
You: "Create a user registration form with validation and good UX"
Agent: "Creating registration form...
Fields:
✓ Email (with email validation)
✓ Password (strength indicator)
✓ Confirm password (match validation)
✓ Username (availability check)
✓ Terms acceptance
Validation:
✓ Real-time field validation
✓ Clear error messages
✓ Success indicators
✓ Async username check
UX Features:
✓ Auto-focus first field
✓ Tab navigation
✓ Show/hide password
✓ Disabled submit until valid
✓ Loading states
✓ Success/error feedback
Accessibility:
✓ Proper labels
✓ Error announcements
✓ Focus management
Form ready!"
Features:
- Validates as user types
- Shows password strength
- Checks username availability
- Smooth error messages
- Accessible for screen readers
Performance Optimization
Example 15: React Performance
Conversation:
You: "This product list is slow with 1000 items. Optimize it."
@src/components/ProductList.tsx
Agent: "Analyzing ProductList performance...
Issues Found:
1. Renders all 1000 items (heavy DOM)
2. No memoization on item components
3. Expensive filter on every render
4. Images loaded eagerly
Optimization:
✓ Added virtualization (react-window)
- Renders only visible items (~20)
- 50x faster scrolling
✓ Memoized ProductItem component
- Prevents unnecessary re-renders
✓ Memoized filter calculation
- Computed once per data change
✓ Lazy loading images
- Loads as user scrolls
Performance Results:
- Initial render: 2.3s → 180ms (12x faster)
- Scroll FPS: 15 → 60 (smooth)
- Memory usage: -75%
Optimized!"
Before:
{products.map(product => (
<ProductItem key={product.id} {...product} />
))}
After:
<VirtualList
height={600}
itemCount={products.length}
itemSize={100}
>
{({ index }) => (
<MemoizedProductItem {...products[index]} />
)}
</VirtualList>
Example 16: API Response Optimization
Conversation:
You: "@mode debug
API responses are slow (2-3 seconds per request)"
Agent: [Debug Mode]
"Analyzing API performance...
Diagnosis:
✓ Database queries: 450ms
✓ Data processing: 120ms
✓ N+1 query problem detected!
Issues:
1. Fetches users in loop (N+1)
2. No database indexes
3. Sends unnecessary data
4. No caching
Solutions Applied:
✓ JOIN instead of N+1 queries
- 50 queries → 1 query
✓ Added indexes
- userId, createdAt fields
✓ Selected only needed fields
- Reduced payload 70%
✓ Added Redis caching
- 5min cache for lists
Results:
- Response time: 2.3s → 180ms
- Database queries: 50 → 1
- Payload size: -70%
Performance optimized!"
More Examples
Example 17: Adding TypeScript
Conversation:
You: "Convert this JavaScript file to TypeScript"
@src/utils/helpers.js
Agent: "Converting to TypeScript...
✓ Added type definitions
✓ Created interfaces for objects
✓ Typed all function parameters
✓ Added return type annotations
✓ Fixed type errors (3 found)
✓ Updated imports
✓ Renamed to helpers.ts
Changes:
- Added 8 interfaces
- Typed 15 functions
- Fixed potential runtime errors
- 100% type coverage
TypeScript conversion complete!"
Example 18: Documentation Generation
Conversation:
You: "Generate API documentation for all endpoints"
@src/routes
Agent: "Generating API documentation...
Analyzing routes:
✓ Found 24 endpoints
✓ Extracted parameters
✓ Identified request/response formats
✓ Documented error codes
Created:
✓ README.md with overview
✓ OpenAPI/Swagger spec
✓ Postman collection
✓ Example requests for each endpoint
Documentation includes:
- Endpoint descriptions
- Request examples
- Response schemas
- Error handling
- Authentication requirements
Docs ready in docs/api/"
Quick Reference
Common Requests
Task | Example Request |
---|---|
New Feature | "Add user profile editing functionality" |
Bug Fix | "@mode debug Login returns 500 error" |
Refactor | "Extract validation logic to separate files" |
Tests | "Generate tests for UserService" |
Explain | "@mode ask How does this auth flow work?" |
API | "Create REST API for products with CRUD" |
UI | "Create a responsive product card grid" |
Optimize | "Optimize this slow database query" |
Convert | "Convert this file to TypeScript" |
Document | "Add JSDoc comments to all functions" |
Tips for Better Results
-
Be Specific
- ❌ "Fix this"
- ✅ "Fix the email validation in the registration form"
-
Provide Context
- Use @ mentions for relevant files
- Explain what you've tried
- Share error messages
-
Use Modes
- Debug mode for bugs
- Architect mode for design
- Ask mode for understanding
-
Iterate
- Start simple, build up
- Review and refine
- Provide feedback
Next Steps
- Try these examples in your project
- Adapt patterns to your needs
- Share successful patterns with team
- Explore Best Practices
These examples show real conversations with Dropstone Agent. Your results may vary based on project setup and patterns, but the agent adapts to your specific needs.