Skip to content

Background Agents

Subagents run inside the parent's session. Agent teams share a task list within a single claude invocation. Both stop when the parent stops. Background agents are different: they are independent Claude Code sessions that run in parallel to your main session, with their own context, their own lifecycle, and no dependency on the parent staying alive. You start one from the terminal, it opens in a dedicated view, and it keeps running while you continue working in your main session or close your laptop entirely.

Owl mascot

What you'll learn

  • Background agents are launched with claude --agent-view, which opens each agent in a separate named tab or tmux pane that persists independently of the parent
  • Unlike subagents and team members, background agents are full Claude Code sessions, they have their own context, can spawn their own subagents, and run until explicitly stopped or the task completes
  • Run multiple independent sessions in parallel: start a background agent for long-running tests, another for documentation generation, and keep working on features in your main session
  • The Agent SDK provides programmatic control in TypeScript and Python, spawn agents, send them prompts, and collect results from scripts rather than the terminal
  • Background agents are the right tool when the task takes longer than you want to wait, requires no mid-stream interaction, and produces a result you can check later

The problem

You're in the middle of implementing a feature. A full test suite run takes 12 minutes. You don't want to stop coding, but you also need the test results before you merge. The options are:

  1. Block: run tests in your main session, stare at the output for 12 minutes
  2. Shell background: claude -p "run the test suite" & , works, but you get no visibility into progress, no way to interact if it gets stuck, and if the parent shell closes the background job might die
  3. Another terminal: open a new terminal, run Claude Code there, works, but now you're managing two terminals, two prompts, and context switching

Background agents give you option 3 with option 1's visibility. Start the test agent in its own view, watch progress if you want to, switch back to your main session and keep coding. The agent runs independently. When it finishes, it shows the result in its view. You check it when you're ready.

--agent-view: the background agent launcher

You can start a long-running process like a test suite in an independent background agent using this launch command.

bash
claude --agent-view "run the full test suite and report results"

This opens a new agent in a dedicated view (a named tmux pane or a terminal tab, depending on your setup). The agent starts working immediately. Your current terminal is free.

You can launch multiple background agents from the same terminal:

bash
# Terminal 1: start a test agent
claude --agent-view "run pytest on the entire project, report failures"

# Terminal 1 (same prompt): start a docs agent
claude --agent-view "regenerate API documentation from docstrings"

# Terminal 1 (same prompt): keep working in main session
claude

Each --agent-view invocation creates a named, independent Claude Code session. They don't share context, they don't coordinate, and they don't block each other. Each is a full Claude Code instance that can spawn subagents and use all tools (subject to its own permissions).

Monitoring background agents

The agent view stays open and shows progress. You can switch to it and interact, ask for status, cancel a stuck task, or redirect the agent:

bash
# List running agents
claude --agent-view --list

# Attach to a specific agent by name
claude --agent-view --attach "test-suite-runner"

# Stop a specific agent
claude --agent-view --stop "test-suite-runner"

If you're in tmux, each agent view is a tmux pane. Use Ctrl+B and arrow keys to navigate between them, your main session, the test agent, and the docs agent are all visible and accessible.

When to use background agents vs. subagents vs. teams

PatternGood forExample
Subagent (delegation)A sub-task within the current task that needs to return results to the parent"While I implement this endpoint, research how the auth middleware handles JWT expiry"
Agent teamMultiple coordinated peers working toward one goal with shared visibility"Build this feature across database, API, and frontend, coordinate the work"
Background agentAn independent, long-running task that doesn't need real-time coordination with what you're doing"Run the full integration test suite while I work on the next feature"
Three background agentsMultiple independent long-running tasks with no interdependencies"Agent 1: run tests. Agent 2: rebuild docs. Agent 3: audit dependencies for CVEs. I'll be coding."

The Agent SDK

For programmatic control, spawning agents from scripts, CI/CD pipelines, or other automated workflows, Claude Code exposes an Agent SDK in TypeScript and Python.

TypeScript example

This snippet demonstrates how to programmatically spawn a background test agent and collect its results using the TypeScript SDK.

typescript
import { ClaudeAgent } from '@anthropic/claude-code-agent';

const agent = new ClaudeAgent({
  cwd: '/home/molsen/projects/my-app',
  model: 'claude-sonnet-4-20250514',
});

// Spawn a background agent for tests
const testRun = await agent.spawn({
  prompt: 'Run the full test suite with pytest. Report only failures and their stack traces.',
  view: 'test-suite-runner',
});

// Keep working in parallel
await agent.send('Implement the user preferences API endpoint...');

// Check on the test agent later
const testResult = await testRun.wait({ timeout: 600_000 }); // 10 minutes
console.log(testResult.summary);

Python example

For Python workflows, this example shows how to launch a background documentation generator while keeping the main session available.

python
from claude_agent import ClaudeCode

agent = ClaudeCode(cwd="/home/molsen/projects/my-app")

# Spawn a background agent
docs_agent = agent.spawn(
    prompt="Regenerate all API docs from the latest docstrings.",
    name="docs-generator",
    background=True
)

# Keep working
agent.send("Add input validation to the user preferences endpoint.")

# Collect the docs agent's result
result = docs_agent.collect(timeout=600)
print(result.output)

The SDK is the bridge between Claude Code and automated systems. A GitHub Actions workflow can spawn a background agent for tests, another for linting, and another for security scanning, all running in parallel, all reporting back to the workflow.

Build it

Step 1: Launch your first background agent

Start a task that takes long enough to notice the parallelism:

bash
# In your main terminal session:
claude --agent-view "List every Python file in this project sorted by line count.
For the 10 largest files, count the number of functions, classes, and docstrings.
Write the report to /tmp/code-stats.md."

The agent view opens. You see it start listing files. Switch back to your main terminal:

bash
# Your terminal is free. Start a main session:
claude

In the main session, keep working. The background agent processes in parallel.

Step 2: Check on the background agent

Switch to the agent view (tmux: Ctrl+B then arrow keys; tabs: switch to the tab). You see the agent's progress. If it finished, the report is at /tmp/code-stats.md. If it's stuck, you can interact with it directly, the agent view is a full interactive session.

Step 3: Launch multiple background agents

You can spin up several independent tasks concurrently by issuing multiple background agent commands from the same prompt.

bash
# Agent 1: test suite
claude --agent-view "Run the full test suite and write results to /tmp/test-results.md"

# Agent 2: dependency audit
claude --agent-view "Check all npm dependencies for known CVEs. Write report to /tmp/cve-audit.md"

# Agent 3: continued feature work
claude

Three Claude Code sessions running in parallel, each independent. The test suite might take 12 minutes; the CVE audit takes 3; your feature work is ongoing. When you're ready to merge, both reports are waiting.

Step 4: Use the SDK from a script

Create scripts/parallel-checks.py:

python
#!/usr/bin/env python3
"""Run test suite and linting in parallel background agents, collect results."""
from claude_agent import ClaudeCode
import sys

project = "/home/molsen/projects/my-app"
agent = ClaudeCode(cwd=project)

# Spawn parallel background agents
tests = agent.spawn(
    prompt="Run pytest. Report only failures. Exit code 0 if all pass.",
    name="tests",
    background=True
)
lint = agent.spawn(
    prompt="Run eslint and prettier --check. Report violations only. Exit code 0 if clean.",
    name="lint",
    background=True
)

# Wait for both (with timeout)
print("Waiting for tests and linting to complete...")
test_result = tests.collect(timeout=600)
lint_result = lint.collect(timeout=300)

# Report combined status
passed = test_result.exit_code == 0 and lint_result.exit_code == 0
print(f"Tests: {'PASS' if test_result.exit_code == 0 else 'FAIL'}")
print(f"Lint:  {'PASS' if lint_result.exit_code == 0 else 'FAIL'}")
sys.exit(0 if passed else 1)

Run it:

Execute the Python script directly from your terminal to trigger the parallel agents.

bash
python3 scripts/parallel-checks.py

Both agents run in parallel. The script blocks until both finish (or timeout), then reports the combined result. This pattern is ideal for CI/CD pipelines.

What goes wrong

MistakeHow you notice itThe fix
Background agent runs forever on an ambiguous promptThe agent view shows the agent still working after 30 minutes, and the output suggests it's branching into sub-tasks you didn't ask forBe specific in background prompts. "Run the test suite" is ambiguous, the agent might try to fix failing tests. Use "Run pytest exactly as configured. Report results. Do not fix failures."
Background agent's file writes conflict with the main sessionBoth the background agent and main session edit config.py, and one's changes get overwrittenBackground agents are independent sessions, they don't know what your main session is doing. Assign non-overlapping domains: "Agent 1 works on src/api/, I work on src/frontend/"
Launching too many background agentsSystem resources exhausted, each agent gets slower as CPU/RAM are divided across 8 Claude Code processesCap background agents at 3–4 for a typical development machine. Each Claude Code process uses a model API call plus system resources. More agents doesn't mean faster, beyond the sweet spot, contention kills throughput
Forgetting about a completed background agentA test report sits unread, and you merge code that the background agent already flagged as brokenHave background agents write results to known paths (/tmp/test-results.md, not random temp files). Check those paths before merging. Better: have the agent post results to a PR comment or Slack
SDK agent spawn fails with authentication errorClaudeAgent constructor throws an auth errorThe SDK uses the same authentication as the CLI. Run claude --version first to verify your CLI auth is working. The SDK reads credentials from the same config file

Confirm it worked

Run these commands to verify that a background task executes independently without blocking your primary interactive session.

bash
# 1. Start a background agent with a measurable task
claude --agent-view "Count the total lines of code in this project, broken down by language.
Write the result to /tmp/loc-report.md. Do not modify any files."

# 2. While it runs, start a main session
claude
# "What is the current working directory? Just confirm it, don't do anything else."

# 3. Switch to the agent view and check progress
# (Ctrl+B + arrows in tmux, or switch tabs)

# 4. After the background agent finishes, verify the report
cat /tmp/loc-report.md

# 5. Verify the main session remained independent
# ,  it didn't know about the background agent's work

# If the report exists, the main session ran independently,
# and both sessions functioned as separate Claude Code instances,
# background agents are working.

Next: Permissions & Security , controlling what every agent can and cannot do.