ANTIGRAVITY LABJP
Articles/Tips & Best Practices
Tips & Best Practices/2026-03-20Intermediate

Antigravity Practical Techniques [Part 1] — Editor Operations, Agents & Basic Workflows

Curated practical techniques from Antigravity Lab premium articles. Part 1 covers Cmd+K patterns, agent operations, AGENTS.md, and Figma integration basics.

Antigravity326practical-techniques2editor31agents126part-1tutorial6

Setup and context — About This Article Series

After learning Antigravity basics, the next step is "practice." This series shares frequently-used techniques with code examples.

Part 1 (This Article) Content

  • Cmd+K practical patterns
  • Basic agent operations
  • Effective AGENTS.md writing
  • Basic Figma-to-code conversion
  • Next.js + Supabase scaffolding

Part 2 (Premium Article) Content

  • Multi-agent orchestration
  • Production app development (SwiftUI, Android, Edge AI)
  • Custom MCP server building
  • SaaS monetization pipeline

Editor Operation Best Practices

Cmd+K Practical Patterns (Refactoring, Test Generation, Type Safety)

Cmd+K isn't just a code fix tool—strategic usage multiplies development productivity.

Pattern 1: TypeScript Type Annotations

Scenario: Migrating existing JavaScript to TypeScript

Before

function calculateDiscount(price, discountPercent) {
  return price * (1 - discountPercent / 100);
}

Cmd+K Prompt

Add TypeScript types to this function. price and discountPercent are both number, return value is also number

After

function calculateDiscount(price: number, discountPercent: number): number {
  return price * (1 - discountPercent / 100);
}

Pattern 2: Automated Test Generation

Scenario: Testing complex calculation logic

Before

export function validateEmail(email: string): boolean {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email) && email.length <= 254;
}

Cmd+K Prompt

Write Jest tests for this function with 100% coverage. Include happy paths and edge cases

After

describe('validateEmail', () => {
  it('accepts valid email addresses', () => {
    expect(validateEmail('user@example.com')).toBe(true);
  });
 
  it('rejects email without domain', () => {
    expect(validateEmail('invalid')).toBe(false);
  });
 
  it('rejects emails exceeding 254 characters', () => {
    expect(validateEmail('a'.repeat(250) + '@example.com')).toBe(false);
  });
 
  it('rejects emails with spaces', () => {
    expect(validateEmail('user name@example.com')).toBe(false);
  });
});

Pattern 3: React Component Modernization

Scenario: Converting class components to function components with Hooks

Before

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { user: null, loading: true };
  }
 
  componentDidMount() {
    fetch(`/api/users/${this.props.userId}`)
      .then(r => r.json())
      .then(user => this.setState({ user, loading: false }));
  }
 
  render() {
    const { user, loading } = this.state;
    return loading ? <div>Loading...</div> : <div>{user.name}</div>;
  }
}

Cmd+K Prompt

Rewrite this class component using React Hooks. Use useEffect and useState

After

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = React.useState<User | null>(null);
  const [loading, setLoading] = React.useState(true);
 
  React.useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(user => {
        setUser(user);
        setLoading(false);
      });
  }, [userId]);
 
  return loading ? <div>Loading...</div> : <div>{user?.name}</div>;
}

Efficient Code Context Management

Chat features can reference large codebases, but inefficient management wastes tokens.

Tips 1: Open Only Related Files

Before starting chat, open only relevant file tabs. Antigravity prioritizes open tabs.

1. Component being discussed in chat
2. Utilities it imports
3. Type definition files
→ Open only these 3, then start chat

Tips 2: Keep AGENTS.md Current

Outdated AGENTS.md means chat wastes time on explanation. Update regularly.

## Updated: 2026-03-20
Document recent architecture changes and new agent additions here

Tips 3: Explicit Line References

For large documents, specify lines you're referencing:

Chat prompt:
"Regarding the authenticateUser function in src/api/auth.ts lines 45-60..."

Basic Agent Operations

Agent Manager Usage

Antigravity's agent feature is a "multi-agent system" where multiple AIs work simultaneously.

1. Agent Creation Flow

Step 1: Open Agent Manager

Left sidebar → Agent icon → "New Agent"

Step 2: Define Role

Name: "Frontend Developer"
Description: "Responsible for React component and page implementation"
Permissions: src/components, src/app directories
Restrictions: src/api directory off-limits

Step 3: Assign Task

Natural language task assignment:
"Create Dashboard page at /app/dashboard.
  Responsive design with TailwindCSS.
  Fetch data from /api/analytics"

Step 4: Execute and Monitor

Execute → AI starts editing → Review each step and adjust

2. Inter-Agent Collaboration

Multiple agents work on same project:

Frontend Agent creates components
  ↓
Backend Agent implements required API endpoints
  ↓
Test Agent generates E2E tests
  ↓
Deploy Agent handles build and deployment

Each agent automatically adjusts per AGENTS.md definitions.

Effective AGENTS.md Writing (with Template)

AGENTS.md isn't just documentation—it's the principle governing agent behavior.

Template: Startup SaaS

# Antigravity SaaS Starter Template
 
## Project Overview
 
**Project Name**: Analytics Dashboard SaaS
**Purpose**: Real-time analytics platform for small businesses
**Status**: MVP phase (March 2026)
 
## Tech Stack & Architecture
 
### Frontend
- Framework: Next.js 15 (App Router)
- Styling: TailwindCSS v4
- State: TanStack Query, Zustand
- Components: shadcn/ui
 
### Backend
- Runtime: Node.js 22
- Framework: Express.js
- Database: PostgreSQL (Supabase)
- Real-time: Supabase Realtime
 
### DevOps
- Hosting: Vercel (Frontend), Render (Backend)
- CI/CD: GitHub Actions
- Monitoring: Sentry
 
## Directory Structure
 

/app # Next.js application /dashboard # Main dashboard /auth # Auth flow /api # API routes /lib # Utilities and hooks /components # React components /migrations # DB migrations /tests # Test code


## Agent Definitions

### Agent: Frontend Developer

**Responsibility**
- React component and page implementation
- UI/UX implementation (per design spec)
- Client-side data management

**Permissions**
- Read: All files
- Write: /components, /app, /lib (client-side utilities)

**Prohibitions**
- API route editing (/app/api)
- Database migration execution
- Environment variable changes

**Connected MCPs**
- Figma Dev Mode (design to code auto-generation)

**Task Example**

"Implement Dashboard page chart component. Design: Reference Dashboard Frame in Figma. Data: Fetch from /api/analytics/monthly-stats. Responsive: Mobile support (Tailwind breakpoints)"


### Agent: Backend Engineer

**Responsibility**
- API route development
- Database logic implementation
- Authentication and authorization

**Permissions**
- Read: All files
- Write: /app/api, /migrations, /lib (server-side utilities)

**Prohibitions**
- React component editing
- Figma file editing

**Connected MCPs**
- Supabase Admin (PostgreSQL, Auth)
- GitHub (commits, PR creation)

**Task Example**

"Implement GET /api/analytics/monthly-stats endpoint. Auth: Supabase Auth JWT validation Query: Past 12 months statistics Cache: Hold in Redis for 1 hour"


### Agent: QA Automation

**Responsibility**
- E2E test auto-generation and execution
- Performance testing
- Pre-deployment checks

**Permissions**
- Read: All files
- Write: /tests

**Connected MCPs**
- Browser Sub-Agent (Playwright)
- GitHub Actions

**Task Example**

"Create E2E tests for Dashboard page with Playwright. Scenarios:

  1. Login
  2. Show Dashboard
  3. Verify chart display
  4. Test data filter operation
  5. Logout"

## Knowledge Items

### Design Specs
- Figma: https://figma.com/design/xxx
- Color System: Primary #0066FF, Secondary #666666
- Typography: Inter, Mono (coding)

### API Documentation
- OpenAPI Spec: /docs/openapi.json
- Auth: JWT Bearer Token (Supabase Auth)
- Rate Limit: 100 req/min

### Database Schema
```sql
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE analytics_events (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES users(id),
  event_type VARCHAR(50),
  data JSONB,
  created_at TIMESTAMP DEFAULT NOW()
);

Deployment Checklist

  • [ ] All tests pass
  • [ ] Environment variables configured
  • [ ] Database migration executed
  • [ ] Sentry integration enabled

---

## Design to Code Basic Workflow

### Figma Dev Mode Integration Fundamentals

Figma Dev Mode **auto-generates code from designer-created components**.

#### Step 1: Prepare Figma File

Organize Figma structure:

Design System ├── Colors ├── Typography ├── Components │ ├── Button (Primary, Secondary, Disabled) │ ├── Input (Default, Error, Disabled) │ └── Card └── Screens └── Dashboard


#### Step 2: Connect MCP

Authenticate Figma Dev Mode MCP in Antigravity settings:

Settings → MCP → Add Figma → Input API Key → Connect


#### Step 3: Use in Chat

Frontend Agent task: "Convert Figma Button component (Primary variant) to React component. props: label (string), onClick (function), disabled (boolean)"


Antigravity auto-extracts from Figma and generates React:

```typescript
// components/Button.tsx
export interface ButtonProps {
  label: string;
  onClick: () => void;
  disabled?: boolean;
  variant?: 'primary' | 'secondary';
}

export function Button({
  label,
  onClick,
  disabled = false,
  variant = 'primary',
}: ButtonProps) {
  const baseStyles = 'px-4 py-2 rounded-lg font-medium transition';
  const variantStyles = {
    primary: 'bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400',
    secondary: 'bg-gray-200 text-gray-900 hover:bg-gray-300 disabled:bg-gray-100',
  };

  return (
    <button
      className={`${baseStyles} ${variantStyles[variant]}`}
      onClick={onClick}
      disabled={disabled}
    >
      {label}
    </button>
  );
}

Google Stitch for UI Design Codification

Google Stitch is Google Workspace integration MCP.

Create Settings Generator from Spreadsheet

Create feature list in Google Sheets:

| Feature | Status | Assigned | Due Date |
|---------|--------|----------|----------|
| Login | In Progress | Frontend | 2026-03-25 |
| Dashboard | Not Started | Backend | 2026-03-30 |

Task Antigravity:

"Read Google Sheets https://docs.google.com/spreadsheets/d/xxx
  and auto-update AGENTS.md task list"

Basic App Development Patterns

Next.js + Supabase Scaffolding

Initial project setup can be automated by Antigravity.

Initial Setup Instruction

Prompt

Create Next.js 15 + Supabase blog platform.
Requirements:
- User authentication (Supabase Auth)
- Blog post list and detail pages
- Admin dashboard (post creation/editing)
- TailwindCSS styling

Structure:
/app/page.tsx          - Landing
/app/blog/[id].tsx     - Blog detail
/app/admin/posts.tsx   - Admin dashboard
/app/api/posts.ts      - API route
/lib/supabase.ts       - Supabase client

Generated Backend Code

// lib/supabase.ts
import { createClient } from '@supabase/supabase-js';
 
export const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
 
export const supabaseAdmin = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);
// app/api/posts.ts
import { supabaseAdmin } from '@/lib/supabase';
 
export async function GET() {
  const { data, error } = await supabaseAdmin
    .from('posts')
    .select('*')
    .order('created_at', { ascending: false });
 
  if (error) return new Response(JSON.stringify(error), { status: 500 });
  return new Response(JSON.stringify(data), { status: 200 });
}
 
export async function POST(req: Request) {
  const { title, content } = await req.json();
  const { data, error } = await supabaseAdmin
    .from('posts')
    .insert([{ title, content, published: false }]);
 
  if (error) return new Response(JSON.stringify(error), { status: 500 });
  return new Response(JSON.stringify(data), { status: 201 });
}

Unity C# Basic Refactoring

Antigravity powers game development too.

Scenario: Modernize Old MonoBehaviour

Before

public class PlayerController : MonoBehaviour
{
    public float speed = 5f;
    private Rigidbody rb;
 
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
 
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        rb.velocity = new Vector3(h * speed, rb.velocity.y, v * speed);
    }
}

Cmd+K Prompt

Modernize this code:
1. Use InputManager pattern for input handling separation
2. Add SerializeField for settings visibility
3. Cache GetComponent calls
4. Add Quaternion.LookRotation for rotation control

After

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 5f;
    [SerializeField] private float rotationSpeed = 5f;
 
    private Rigidbody rb;
    private InputManager inputManager;
 
    private void Awake()
    {
        rb = GetComponent<Rigidbody>();
        inputManager = GetComponent<InputManager>();
    }
 
    private void FixedUpdate()
    {
        Vector3 input = inputManager.GetMovementInput();
        MovePlayer(input);
        RotatePlayer(input);
    }
 
    private void MovePlayer(Vector3 direction)
    {
        Vector3 velocity = direction * moveSpeed;
        velocity.y = rb.velocity.y;
        rb.velocity = velocity;
    }
 
    private void RotatePlayer(Vector3 direction)
    {
        if (direction.magnitude > 0.1f)
        {
            Quaternion targetRotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Lerp(
                transform.rotation,
                targetRotation,
                Time.deltaTime * rotationSpeed
            );
        }
    }
}

Next Steps — What Part 2 (Premium) Covers

Part 1 covered foundational techniques.

Part 2 (Premium) covers advanced techniques:

  • Multi-Agent Orchestration Design: Router patterns, pipeline patterns
  • Production App Development: SwiftUI, Android, Edge AI
  • Custom MCP Server Building: TypeScript implementation with tool extension
  • SaaS Monetization Pipeline: Stripe integration, YouTube automation, Kindle writing

Become an Antigravity Lab Premium member to master AI-driven development at production scale.

Share

Thank You for Reading

Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Tips2026-03-25
The Complete Automated Revenue Playbook with Antigravity— Turning Every AI IDE Feature into a Revenue Stream
A comprehensive playbook for automated monetization using every Antigravity IDE feature — AI agents, MCP, multi-agent orchestration, and Manager Surface. Covers the 3-axis framework: dev speed to revenue, product scaling, and continuous deploy monetization.
Tips2026-03-20
Antigravity Practical Techniques [Part 2] — Multi-Agent, Production Development & Monetization
Advanced techniques from Antigravity Lab premium articles. Part 2 covers multi-agent orchestration, production app development, custom MCP servers, and SaaS monetization.
Tips2026-07-10
You Can Measure a Request Before You Send It — Sizing Agent Tasks by Working Backward from Rework Rate
When an Antigravity agent returns code that misses the mark, the cause is rarely the wording of the prompt. It is the size of the task. Here is a Python scorer that grades a request before you send it, plus what happened when I scored 80 past requests against their actual rework outcomes.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →