- agents can overwrite each other’s code;
- browser sessions can interfere with each other.
Claude Code worktrees solve the first problem. 2Captcha Browser API helps separate and remotely execute browser workflows.
A reliable parallel workflow therefore requires two levels of isolation:
- one Git worktree for each coding task;
- one independent browser session or browser configuration for each automation task.
This article explains how to combine Claude Code worktrees with 2Captcha Browser API when developing Playwright, Puppeteer, web scraping, browser testing, and AI-controlled browser workflows.
What is a Claude Code worktree?
A Git repository normally has one working directory: one folder containing the current version of the project.
A worktree lets you create additional folders connected to the same Git repository. Each folder can use its own branch while sharing the same Git history.
Think of the repository as one parts warehouse and each worktree as a separate workbench. Every agent receives its own workbench and can modify files without directly overwriting another agent’s work.
Claude Code can create an isolated worktree for a session:
claude --worktree browser-auth
The shorter form is:
claude -w browser-auth
A second agent can work in another tree:
claude --worktree product-parser
The resulting structure may look like this:
project/
├── .git/
├── src/
├── package.json
└── .claude/
└── worktrees/
├── browser-auth/
└── product-parser/Each Claude Code session receives its own files and branch.
This prevents the most basic parallel-agent failure: two agents writing different versions of the same file in the same directory.
Separate terminal windows do not provide this isolation. If two agents use the same working directory, the last process that saves a file can overwrite the other agent’s changes.
The official behavior is described in the Claude Code worktree documentation.
Why browser automation needs another isolation layer
A worktree isolates project files, but it does not isolate external runtime state.
Two agents in separate worktrees can still connect to the same browser environment and interfere with each other.
For example:
- one agent opens the login page while another navigates to the product catalog;
- one agent clears cookies while another depends on the active session;
- one agent closes a tab currently used by another task;
- both agents modify the same localStorage values;
- one agent changes the account language or region;
- both agents save screenshots or downloads to the same external directory;
- one agent logs out while another is extracting authenticated data.
The source code is separated, but the browser state remains shared.
A Git worktree is not a browser isolation mechanism.
For reliable parallel AI browser automation, every independent worktree should use its own browser session, browser login, profile configuration, test account, and output directory.
Two levels of isolation
A correct architecture separates both the development environment and the browser runtime.
| Resource | Claude Code worktree | Independent browser session |
|---|---|---|
| Source files | Yes | No |
| Git branch | Yes | No |
| Local configuration | Yes | No |
| Dependencies | Yes | No |
| Cookies | No | Yes |
| localStorage | No | Yes |
| Browser tabs | No | Yes |
| Authorized session | No | Yes |
| Browser environment | No | Yes |
| Proxy configuration | No | Yes |
| External database | No | No |
| Website account | No | No |
| Shared service balance | No | No |
The recommended mapping is:
One task
↓
One Claude Code worktree
↓
One Git branch
↓
One 2Captcha Browser API session
↓
One output directoryWhere 2Captcha Browser API fits
2Captcha Browser API provides remotely hosted browsers that can be controlled through standard browser automation tools.
Instead of launching Chrome locally, the application connects to a remote browser through a WebSocket or Chrome DevTools Protocol connection.
A basic connection URI has the following structure:
ws://BROWSER_USERNAME:[email protected]:9222
The browser continues to be controlled through the normal Playwright or Puppeteer API. The main difference is how the browser connection is created.
Local Playwright launch:
import { chromium } from "playwright";
const browser = await chromium.launch({
headless: true,
});Remote connection through 2Captcha Browser API:
import { chromium } from "playwright";
const browser = await chromium.connectOverCDP(
process.env.BROWSER_WS_ENDPOINT
);This approach is suitable for AI-generated browser automation because Claude can continue writing familiar Playwright or Puppeteer code without managing a separate local Chrome installation for every parallel task.
2Captcha Browser API can be used as the browser execution layer, while Claude Code remains responsible for generating, editing, testing, and reviewing the automation code.
Example parallel workflow
Assume a project contains two independent browser automation tasks:
- implement authentication and session persistence;
- implement product-page extraction.
These tasks can be assigned to two Claude Code sessions.
Agent 1: authentication workflow
Create a worktree:
claude --worktree browser-auth
Give Claude a narrowly defined task:
Implement the authentication workflow using Playwright and 2Captcha Browser API. Requirements: - work only in the authentication module; - use the browser configuration assigned to this worktree; - preserve the authenticated session; - save screenshots and traces inside artifacts/browser-auth; - do not modify product extraction code; - do not create database migrations.
Recommended mapping:
Worktree: browser-auth Branch: worktree-browser-auth Browser login: claude-browser-auth Output directory: artifacts/browser-auth Responsibility: login and session persistence
Agent 2: product extraction
Create another worktree:
claude --worktree product-parser
Give it a separate task:
Implement product-page extraction using Playwright and 2Captcha Browser API. Requirements: - work only in the extraction module; - use the browser configuration assigned to this worktree; - extract title, price, availability, and canonical URL; - save screenshots and traces inside artifacts/product-parser; - do not modify authentication code; - do not create database migrations.
Recommended mapping:
Worktree: product-parser Branch: worktree-product-parser Browser login: claude-product-parser Output directory: artifacts/product-parser Responsibility: navigation and structured data extraction
The two agents now have separate code directories and separate browser execution contexts.
Connecting Playwright to 2Captcha Browser API
Install the required dependencies:
npm install playwright dotenv
Create a local .env file:
BROWSER_USERNAME=YOUR_BROWSER_USERNAME BROWSER_PASSWORD=YOUR_API_KEY BROWSER_HOST=browser-cloud.2captcha.com BROWSER_PORT=9222
Add sensitive and generated files to .gitignore:
.env .claude/worktrees/ artifacts/
Create browser-example.mjs:
import "dotenv/config";
import { chromium } from "playwright";
import { mkdir } from "node:fs/promises";
import path from "node:path";
const requiredVariables = [
"BROWSER_USERNAME",
"BROWSER_PASSWORD",
"BROWSER_HOST",
"BROWSER_PORT",
];
for (const variable of requiredVariables) {
if (!process.env[variable]) {
throw new Error(`Missing required environment variable: ${variable}`);
}
}
const username = encodeURIComponent(process.env.BROWSER_USERNAME);
const password = encodeURIComponent(process.env.BROWSER_PASSWORD);
const host = process.env.BROWSER_HOST;
const port = process.env.BROWSER_PORT;
const endpoint = `ws://${username}:${password}@${host}:${port}`;
const outputDirectory = path.resolve("artifacts/browser-example");
await mkdir(outputDirectory, { recursive: true });
const browser = await chromium.connectOverCDP(endpoint);
try {
const contexts = browser.contexts();
const context = contexts[0] ?? await browser.newContext();
const pages = context.pages();
const page = pages[0] ?? await context.newPage();
await page.goto("https://example.com", {
waitUntil: "domcontentloaded",
timeout: 60000,
});
const title = await page.title();
const heading = await page.locator("h1").first().textContent();
await page.screenshot({
path: path.join(outputDirectory, "page.png"),
fullPage: true,
});
console.log({
title,
heading: heading?.trim() ?? null,
url: page.url(),
});
} finally {
await browser.close();
}Run the script:
node browser-example.mjs
Claude can use the same connection pattern in every worktree while receiving separate browser credentials, logins, session parameters, proxy settings, test accounts, or output paths.
Mapping worktrees to browser configurations
The simplest approach is to keep a separate local configuration for each worktree.
Example for the authentication task:
BROWSER_USERNAME=claude-auth BROWSER_PASSWORD=YOUR_API_KEY BROWSER_HOST=browser-cloud.2captcha.com BROWSER_PORT=9222 BROWSER_OUTPUT_DIR=artifacts/browser-auth
Example for the extraction task:
BROWSER_USERNAME=claude-products BROWSER_PASSWORD=YOUR_API_KEY BROWSER_HOST=browser-cloud.2captcha.com BROWSER_PORT=9222 BROWSER_OUTPUT_DIR=artifacts/product-parser
The exact connection parameters depend on how browser logins, profiles, and proxies are configured in the project.
The architectural requirement remains the same:
Parallel agents must not control the same persistent browser state simultaneously.
Incorrect mapping:
browser-auth worktree ─────┐
├── shared browser session
product-parser worktree ───┘Recommended mapping:
browser-auth worktree
└── independent Browser API session
product-parser worktree
└── independent Browser API sessionUsing .worktreeinclude
A new worktree is a fresh checkout. Files that are not tracked by Git, such as .env, do not automatically appear inside it.
Claude Code supports a .worktreeinclude file in the repository root. It lists gitignored files that should be copied into newly created worktrees.
For example:
.env.example .env.development
However, copying one shared .env into every worktree can create false isolation.
Suppose every tree receives this configuration:
BROWSER_USERNAME=shared-browser-login BROWSER_OUTPUT_DIR=/tmp/shared-browser-output
The agents have separate code directories, but they still use the same browser configuration and output folder.
A safer approach is to copy only a non-secret template:
BROWSER_USERNAME= BROWSER_PASSWORD= BROWSER_HOST=browser-cloud.2captcha.com BROWSER_PORT=9222 BROWSER_OUTPUT_DIR=
Each worktree can then receive its own local values through:
- a setup script;
- shell environment variables;
- a secret manager;
- separate development credentials;
- a manually created local .env file.
Do not store real production credentials in a tracked file.
Worktree lifecycle and cleanup
Claude Code can remove worktrees after sessions, but cleanup behavior depends on how the session was created and whether the tree contains changes.
Important cases include:
- an unnamed clean worktree may be removed automatically;
- a named worktree may require confirmation;
- a worktree with changes should not be silently deleted;
- non-interactive runs using claude -p may require manual cleanup.
List existing worktrees:
git worktree list
Remove an unused worktree:
git worktree remove .claude/worktrees/browser-auth
Prune stale worktree metadata:
git worktree prune
The worktree directory should be ignored:
.claude/worktrees/
Without regular cleanup, automated sessions can leave unused directories, branches, dependency folders, logs, browser artifacts, and local environment files.
What worktrees do not isolate
Worktrees solve file-level collisions. They do not automatically isolate the rest of the system.
External databases
Two agents in different worktrees can still connect to the same PostgreSQL, MySQL, Supabase, or MongoDB database.
If both create migrations, Git may preserve both files, but it cannot guarantee that the database changes are compatible or applied in the correct order.
Database schema work should remain single-track.
Website accounts
Separate browser sessions do not help when both sessions use the same account and modify shared server-side state.
For example, one agent may:
- change an account setting;
- add products to a cart;
- remove saved data;
- reset a password;
- revoke active sessions;
- submit a form that cannot be repeated safely.
Use separate test accounts where possible.
API balances and quotas
Separate browser sessions may still use the same Browser API account, traffic balance, or concurrency limits.
Isolation prevents session collisions. It does not prevent shared resource exhaustion.
Proxy identity
If multiple sessions use the same proxy or IP address, the target website may still associate their activity.
Use separate proxy configurations when tasks require independent network identities.
Shared output directories
Agents may write screenshots, traces, HAR files, downloads, and JSON results outside their worktrees.
This recreates the same last-write-wins problem at the artifact level.
Bad example:
/tmp/latest-screenshot.png
Better:
artifacts/browser-auth/latest-screenshot.png artifacts/product-parser/latest-screenshot.png
Local ports
Worktrees do not reserve ports.
Two Next.js applications cannot both use port 3000, and two FastAPI applications cannot both use port 8000.
Assign ports through environment variables:
FRONTEND_PORT=3001 BACKEND_PORT=8001
A second worktree can use:
FRONTEND_PORT=3002 BACKEND_PORT=8002
Common mistakes
1. Running two agents in one directory
Two terminal windows do not create isolated filesystems.
If both agents edit the same file, the last save can overwrite the first agent’s changes without producing a Git conflict.
Use one worktree per writing agent.
2. Sharing one browser session
This is the browser equivalent of running two agents in one directory.
The agents may overwrite cookies, navigate the same tabs, modify localStorage, or close each other’s pages.
Use separate browser sessions or independent persistent profiles.
3. Treating worktrees as conflict prevention
Worktrees delay merge conflicts. They do not eliminate them.
If two agents modify the same module, the conflict appears when their branches are merged.
Parallel tasks should have clearly separated responsibilities.
4. Creating parallel database migrations
Two agents can generate migrations that are individually valid but mutually incompatible.
Only one agent should modify the database schema, migration history, or schema documentation at a time.
5. Copying production secrets
Using .worktreeinclude to copy .env creates multiple copies of credentials on disk.
Prefer short-lived development credentials, shell environment variables, or a secret manager.
6. Reusing the same test account
Different browser sessions still affect the same server-side account state.
Use independent test accounts for destructive or state-changing workflows.
7. Writing artifacts outside the worktree
Screenshots, logs, traces, downloads, and extracted data should be stored under a task-specific directory inside the current worktree.
8. Starting dependent tasks in parallel
Authentication and authenticated extraction may look separate, but the second task may depend on code or session state produced by the first.
Run dependent tasks sequentially or define a stable interface before starting both agents.
Recommended CLAUDE.md rules
Add explicit constraints to the project instructions:
## Parallel AI browser automation - Never run two writing agents in the same working directory. - Separate terminal windows do not provide file isolation. - One task must use one worktree, one branch, and one clearly defined concern. - Every parallel worktree must use a separate 2Captcha Browser API session or persistent browser profile. - Never allow two writing agents to control the same persistent browser state simultaneously. - Use separate website test accounts when agents can modify server-side state. - Store screenshots, traces, HAR files, downloads, logs, and extracted data inside the current worktree. - Database migrations and schema documentation are always single-track work. - Do not run parallel agents that both modify database schemas. - Add `.claude/worktrees/` to `.gitignore`. - Do not store production Browser API credentials in tracked files. - Do not copy production credentials into every worktree. - Assign separate local ports to parallel development servers. - Review-only agents must not modify files or browser state. - Remove unused non-interactive worktrees manually with `git worktree remove <path>`.
When this workflow is useful
Claude Code worktrees and 2Captcha Browser API work well together when tasks are genuinely independent.
Good candidates include:
- authentication and public-page extraction;
- desktop and mobile browser flows;
- different target websites;
- a new feature and an unrelated bug fix;
- Playwright tests and scraper development;
- separate regional or proxy configurations;
- independent account workflows;
- browser automation and frontend interface development.
The workflow is especially useful when a team can review multiple branches in parallel.
When sequential development is safer
Do not add parallelism only because Claude Code supports it.
Sequential work is usually safer when:
- both tasks modify the same files;
- one task depends on the result of another;
- both tasks need the same browser state;
- both tasks modify the same website account;
- database migrations are involved;
- the project has no reliable automated tests;
- the reviewer cannot inspect multiple branches carefully;
- the change is too small to justify a separate environment.
Parallel AI agents increase code production. They do not automatically increase review capacity.
Two unreviewed branches are not twice as much completed work. They are twice as much code waiting for verification.
Recommended workflow
A practical workflow can follow these steps:
- Define two tasks that do not overlap by responsibility.
- Create one Claude Code worktree for each task.
- Assign a separate 2Captcha Browser API session to each worktree.
- Use separate test accounts and output directories where required.
- Prevent both agents from creating database migrations.
- Run automated tests in every worktree.
- Review each Git diff independently.
- Merge one branch at a time.
- Run the complete test suite after every merge.
- Remove unused worktrees, branches, browser sessions, and artifacts.
Create the worktrees:
claude --worktree browser-auth claude --worktree product-parser
Inspect the resulting branches:
git branch --list "worktree-*"
Review the changes:
git diff main...worktree-browser-auth git diff main...worktree-product-parser
Merge the first accepted task:
git switch main git merge worktree-browser-auth
Run the tests, then merge the second branch:
git merge worktree-product-parser
Clean up:
git worktree remove .claude/worktrees/browser-auth git worktree remove .claude/worktrees/product-parser git branch -d worktree-browser-auth git branch -d worktree-product-parser git worktree prune
Final recommendation
Claude Code worktrees and 2Captcha Browser API solve different parts of the same parallel automation problem.
Claude Code worktrees isolate:
- source code;
- Git branches;
- local files;
- agent changes.
2Captcha Browser API sessions isolate:
- browser execution;
- tabs and page state;
- cookies and localStorage;
- authentication state;
- browser-specific proxy configuration;
- automation runtime.
The central principle is:
Worktrees isolate the code. 2Captcha Browser API isolates the browser runtime.
Use both when independent Claude agents must develop or execute browser automation in parallel.
Keep the workflow sequential when tasks share files, browser state, website accounts, database schemas, or human review capacity.
Discussion