GitHub Copilot Chat Guide: Slash Commands, Context Variables, and Agent Mode for VS Code

Why Copilot Chat Is More Powerful Than Most Developers Realize

Most developers use GitHub Copilot Chat as a simple Q&A box — they type a question, get an answer, and move on. But Copilot Chat has a sophisticated system of slash commands, context variables, and agent modes that make it dramatically more effective when used properly.

The difference is context. A bare question like “how do I sort this?” gives Copilot minimal information. A targeted query like /fix #selection — this sort is case-sensitive but should be case-insensitive gives Copilot the exact code, the exact problem, and the exact desired behavior. The quality difference in responses is enormous.

This guide covers every built-in command, context variable, and agent mode — with practical examples of when each one saves the most time.

Slash Commands: Built-In Task Shortcuts

/explain — Code Explanation

Select code and type /explain to get a natural language explanation:

/explain

Copilot analyzes the selected code and explains:

  • What the code does step by step
  • Why specific patterns are used
  • Any edge cases or potential issues

Best for: onboarding to unfamiliar code, understanding legacy systems, code review preparation.

Pro tip: add specificity:

/explain — focus on the error handling logic and why the retry
pattern uses exponential backoff instead of fixed intervals

/fix — Bug Fix Suggestions

Select buggy code and type /fix:

/fix

Copilot identifies issues and suggests fixes. More effective with context:

/fix — this function returns undefined when the array is empty
instead of returning an empty array
/fix — the date comparison is wrong because it compares strings
instead of Date objects, causing incorrect sorting for dates
in different months

/tests — Test Generation

Select a function or class and type /tests:

/tests

Copilot generates test cases covering the happy path, edge cases, and error cases.

Pro tip: specify your test framework:

/tests — use vitest with describe/it blocks, mock the database
with vi.mock, test: valid input, empty input, null input, and
the case where the external API returns a 500 error

/doc — Documentation Generation

Select code and type /doc:

/doc

Copilot generates JSDoc, docstrings, or language-appropriate documentation.

Pro tip: specify documentation style:

/doc — generate TSDoc with @param, @returns, @throws, and
@example sections. Include a usage example showing the most
common use case.

/simplify — Code Simplification

/simplify

Copilot suggests ways to make the selected code more concise and readable while maintaining the same behavior.

/optimize — Performance Optimization

/optimize — this function is called 10,000 times per request
and is the main performance bottleneck

Copilot suggests performance improvements considering the scale you specified.

Context Variables: Precision Targeting

#file — Reference Specific Files

Include a specific file in your query context:

How does the authentication middleware in #file:src/middleware/auth.ts
validate JWT tokens? What happens when a token is expired?

You can reference multiple files:

Compare the error handling approach in #file:src/services/userService.ts
with #file:src/services/orderService.ts — which is more robust and why?

#selection — Current Selection

Reference the currently selected code:

Refactor #selection to use the Strategy pattern instead of the
switch statement. Keep the same external API.

#editor — Current File Content

Reference the entire current file:

Based on #editor, what are the unused imports? Also identify
any functions that are defined but never called within this file.

#terminalLastCommand — Terminal Output

Reference the last terminal command and its output:

Explain the error in #terminalLastCommand — why did the build fail
and how do I fix it?

This is powerful for debugging build errors, test failures, and deployment issues without copy-pasting terminal output.

Where is the validateEmail function defined in #codebase?
Show me all the files that import and use it.

Combining Context Variables

The real power comes from combining variables:

/fix #selection based on the pattern used in #file:src/services/orderService.ts
— make the error handling consistent between these two services
/tests for #selection using the test patterns from
#file:src/__tests__/orderService.test.ts

Agent Modes: Specialized Assistants

@workspace — Codebase-Aware Agent

The @workspace agent searches your entire project to answer questions:

@workspace What design patterns does this project use for
database access? Show me examples from the codebase.
@workspace How is authentication implemented? Trace the flow
from login request to session creation.
@workspace Find all API endpoints that don't have input
validation. List each one with the file path.

@terminal — Terminal Expert

The @terminal agent helps with command-line tasks:

@terminal How do I run just the authentication tests?
Show the exact command for this project's test setup.
@terminal The last npm install failed. What went wrong
and how do I fix the dependency conflict?

@vscode — Editor Configuration

@vscode How do I set up a debug configuration for this
Next.js project? Include server-side debugging.
@vscode Create a tasks.json that runs lint, typecheck,
and tests in sequence before each commit.

Advanced Prompting Techniques

The Context Sandwich

Provide context, then the question, then constraints:

Context: We're migrating from Express to Fastify. The middleware
pattern is different between frameworks.

Question: Convert this Express middleware to Fastify plugin format.
#selection

Constraints:
- Maintain the same authentication logic
- Use Fastify's decorateRequest for adding user to request
- Keep TypeScript types strict (no any)
- Follow the pattern in #file:src/plugins/rateLimiter.ts

Multi-Step Problem Solving

Break complex tasks into steps:

Step 1: Analyze #file:src/services/paymentService.ts and identify
all the external API calls it makes. List them.

[After response]

Step 2: For each API call you identified, what happens if it
times out or returns a 500 error? Are all failure cases handled?

[After response]

Step 3: Generate retry logic with exponential backoff for the
API calls that don't have proper error handling. Follow the
pattern in #file:src/lib/retry.ts

Code Review Assistance

Review #editor for:
1. Security vulnerabilities (SQL injection, XSS, SSRF)
2. Performance issues (N+1 queries, unbounded loops)
3. Error handling gaps (uncaught promises, missing try-catch)
4. TypeScript issues (unsafe type assertions, missing types)

For each issue found, show the exact line and the fix.

Inline Chat (Ctrl+I / Cmd+I)

Inline Chat lets you edit code in place without switching to the chat panel:

  1. Select code in the editor
  2. Press Ctrl+I (Cmd+I on Mac)
  3. Type your instruction
  4. Review the diff and accept or reject

Best for quick transformations:

[Select a function]
Ctrl+I: "Add input validation for all parameters using zod"
[Select a class]
Ctrl+I: "Convert to functional component with hooks"
[Select a test]
Ctrl+I: "Add edge cases: empty array, null input, duplicate values"

Copilot Chat vs. Cursor vs. Claude Code

FeatureCopilot ChatCursorClaude Code
IDE integrationVS Code nativeStandalone editorTerminal + VS Code
Codebase awareness@workspace@CodebaseAutomatic
Multi-file editingLimitedComposerNative
Terminal integration@terminalBuilt-inNative
Inline editingCtrl+ICmd+KN/A (terminal)
Tab completionExcellentExcellentN/A
Autonomous executionLimitedAgent modeFull
Best forVS Code users, tab + chatMulti-file AI editingTerminal power users

Frequently Asked Questions

Does Copilot Chat remember context from previous messages?

Yes, within the same chat session. Each session maintains context. Starting a new session resets context. Use the ”+” button to start fresh or continue in the same session for related questions.

Can I use Copilot Chat with my own model?

Currently, Copilot Chat uses GitHub’s model selection (GPT-4o, Claude Sonnet). You cannot bring your own API key. Model selection may vary by feature and plan.

Does Copilot Chat work offline?

No. All queries are processed through GitHub’s cloud infrastructure. An internet connection is required.

Can Copilot Chat access private repositories?

Copilot Chat accesses the code in your current workspace. For @workspace queries, it searches your local files. It does not access remote repositories unless you have them cloned locally.

How do I get better answers from Copilot Chat?

Three rules: (1) be specific about what you want, (2) use context variables (#file, #selection) to show exactly what you mean, (3) specify constraints and patterns to follow.

Is code shared with Copilot Chat used for training?

For Copilot Business and Enterprise plans, code is not retained or used for training. Individual plans may have different terms. Check GitHub’s current privacy policy.

Explore More Tools

Grok Best Practices for Academic Research and Literature Discovery: Leveraging X/Twitter for Scholarly Intelligence Best Practices Grok Best Practices for Content Strategy: Identify Trending Topics Before They Peak and Create Content That Captures Demand Best Practices Grok Case Study: How a DTC Beauty Brand Used Real-Time Social Listening to Save Their Product Launch Case Study Grok Case Study: How a Pharma Company Tracked Patient Sentiment During a Drug Launch and Caught a Safety Signal 48 Hours Before the FDA Case Study Grok Case Study: How a Disaster Relief Nonprofit Used Real-Time X/Twitter Monitoring to Coordinate Emergency Response 3x Faster Case Study Grok Case Study: How a Political Campaign Used X/Twitter Sentiment Analysis to Reshape Messaging and Win a Swing District Case Study How to Use Grok for Competitive Intelligence: Track Product Launches, Pricing Changes, and Market Positioning in Real Time How-To Grok vs Perplexity vs ChatGPT Search for Real-Time Information: Which AI Search Tool Is Most Accurate in 2026? Comparison How to Use Grok for Crisis Communication Monitoring: Detect, Assess, and Respond to PR Emergencies in Real Time How-To How to Use Grok for Product Improvement: Extract Customer Feedback Signals from X/Twitter That Your Support Team Misses How-To How to Use Grok for Conference Live Monitoring: Extract Event Insights and Identify Networking Opportunities in Real Time How-To How to Use Grok for Influencer Marketing: Discover, Vet, and Track Influencer Partnerships Using Real X/Twitter Data How-To How to Use Grok for Job Market Analysis: Track Industry Hiring Trends, Layoff Signals, and Salary Discussions on X/Twitter How-To How to Use Grok for Investor Relations: Track Earnings Sentiment, Analyst Reactions, and Shareholder Concerns in Real Time How-To How to Use Grok for Recruitment and Talent Intelligence: Identifying Hiring Signals from X/Twitter Data How-To How to Use Grok for Startup Fundraising Intelligence: Track Investor Sentiment, VC Activity, and Funding Trends on X/Twitter How-To How to Use Grok for Regulatory Compliance Monitoring: Real-Time Policy Tracking Across Industries How-To NotebookLM Best Practices for Financial Analysts: Due Diligence, Investment Research & Risk Factor Analysis Across SEC Filings Best Practices NotebookLM Best Practices for Teachers: Build Curriculum-Aligned Lesson Plans, Study Guides, and Assessment Materials from Your Own Resources Best Practices NotebookLM Case Study: How an Insurance Company Built a Claims Processing Training System That Cut Errors by 35% Case Study