Vibe coding with Claude Code course Β· Module 10: TikTok clone
Sounds and the Recorder: Two Claude Code Sessions at Once in Worktrees
In this lesson12
The feed plays but the crew wants more: to record fifteen seconds of an adventure and lay a shanty under it. That is two features: a sound library where you pick the shanty, and a recorder that turns on the camera. They do not depend on each other and do not share files, so they can be built at the same time, in two Claude Code sessions, like two longboats lowered from one ship.
What you will learn
- recognise when two features can be built in parallel and when it is better to go one after another;
- start two
claude -wsessions and look at both separate folders in Cursor; - read the recorder: the camera after a click, a limit that really works, the camera turned off on exit;
- merge two branches into
mainand clean up after the longboats.
Worktrees in one paragraph
A git worktree is a separate working folder with its own files and its own branch that shares history with the main folder. According to the Claude Code documentation, claude -w <name> (the full flag name is --worktree) creates such a folder in .claude/worktrees/<name>/ on a new branch worktree-<name> and starts a session in it. Two sessions in two worktrees edit two separate copies of the files, so they do not overwrite each other's changes. They meet only when the branches are merged.
When not to work in parallel
Isolation ends at the merge. If both sessions change the same fragment of the same file, Git cannot guess which version is right. For us two branches that added different functions at the end of lib/format.ts ended the merge like this:
Auto-merging lib/format.ts
CONFLICT (content): Merge conflict in lib/format.ts
Automatic merge failed; fix conflicts and then commit the result.So you run in parallel only tasks that touch different files, and dependent tasks you do one after another. The clip editor from lesson 9_3 needs a finished recording from the recorder, so it waits. The documentation also reminds you that several sessions at once use many times more tokens than one.
Before setting sail
Start with a clean list in Source Control and a commit with the feed. Then three matters:
- The worktree folder outside Git. The documentation advises adding
.claude/worktrees/to.gitignore, so the copies of the project do not hang in the main folder as untracked files. Ask Claude for it and commit. - Push first. When the project has a remote repository, for example on GitHub, a new worktree starts from the default branch of that repository, not from your last local commit. For us a worktree created before the push did not have the latest commit from
main. So pushmainbefore you set sail. A project without a remote starts from your current commit. - Secrets. A worktree is a fresh checkout, so it has none of the files from
.gitignore, such as.env.local. Treasure Reels has none yet. When they appear, you add them to a.worktreeincludefile in the project folder, and Claude will copy them into every new worktree.
Two sessions
In Cursor open a second terminal with the + button in the terminal panel. In the first terminal start the sounds session:
claude -w soundsIn the second terminal do the same with a different name: claude -w recorder. The name after -w is the folder name and the end of the branch, so pick a short, descriptive one. A fresh worktree also has no node_modules folder: for us ls node_modules answered No such file or directory. That is why both requests begin with installing dependencies.
Request for Claude Code (sounds session):
You work in a separate worktree on the Treasure Reels sound library.
First install the dependencies (npm install). Then: a type SoundDetails
in types/sound.ts that extends Sound from @types/video.ts (do not copy
it), data in lib/sounds.ts (files from public/sounds), a page
app/sounds/page.tsx with a search by title and the tabs "Trending"
and "All", a preview on the card: only one sound plays at a time.
Do not touch app/layout.tsx, app/page.tsx or components/ForYouFeed.tsx.
At the end lint, types, tests and build, then commit.The recorder request goes to the second terminal. It is longer, because the recorder has more places where something can be switched on forever or never end.
Request for Claude Code (recorder session):
You work in a separate worktree on the Treasure Reels recorder. First
install the dependencies (npm install). Build components/VideoRecorder.tsx
and the page app/record/page.tsx: camera and microphone only after a
click on "Turn on camera", a live preview, recording through
MediaRecorder with a maxSeconds limit (15 by default) that stops by
itself, a time bar, a message when access is denied, the camera turned
off when leaving the page, the result through
onComplete(blob, { durationSec, mimeType }) with the real recording
time. Choose the format with MediaRecorder.isTypeSupported. Do not
touch app/layout.tsx, app/page.tsx or types/video.ts. Add a test with a
fake camera: the recording ends by itself after the limit. At the end
lint, types, tests and build, then commit.The "do not touch" sentences draw the line between the longboats: shared files stay untouched, and links to the new pages you add after the merge. For us both sessions worked at the same time, a few minutes each. Both reported the same trouble: in a fresh worktree npx tsc --noEmit reports the error Cannot find name 'LayoutProps', because route types live in the .next folder, which the checkout does not have. They vanish after npx next typegen or after the first build.
In Cursor: two folders
Expand .claude/worktrees/ in the file tree. sounds and recorder lie there, each with a full copy of the project. A change in one shows up neither in the other nor in the main folder until the merge. Open .claude/worktrees/sounds/types/sound.ts:
import type { Sound } from "@/types/video";
export interface SoundDetails extends Sound {
src: string; // "/sounds/anthem.m4a"
uses: number; // number of videos recorded with this sound
trending: boolean; // goes to the "Trending" tab
}extends takes all the fields of Sound from lesson 9_1 and adds three new ones, so a sound has one definition in the whole project. The preview works like the feed: an effect on playingId plays the chosen <audio> and pauses every other. Claude also used what we said about references: the card's ref function returns a cleanup function that removes the sound from the map when the card leaves the list.
What Claude wrote: the recording format
Now .claude/worktrees/recorder/components/VideoRecorder.tsx. Browsers record in different formats, so a small function picks one:
const MIME_CANDIDATES = [
"video/webm;codecs=vp9,opus",
"video/webm;codecs=vp8,opus",
"video/webm",
"video/mp4;codecs=avc1,mp4a.40.2",
"video/mp4",
];
export function pickMimeType(): string | undefined {
if (typeof MediaRecorder === "undefined" || typeof MediaRecorder.isTypeSupported !== "function") {
return undefined;
}
return MIME_CANDIDATES.find((type) => MediaRecorder.isTypeSupported(type));
}MediaRecorder is a tool built into the browser that records a camera stream to a file. According to MDN, isTypeSupported tells whether the browser can record in a given format, and a constructor given a format it does not know throws NotSupportedError. When no candidate fits, the function returns undefined and the browser chooses the format. The real format of the recording is then given by the recorder.mimeType property, and that is what goes into the metadata.
What Claude wrote: the camera after a click
The request for the camera stands in the button's handler, never in the render itself, like the microphone in location 9. Here is its heart, shortened:
try {
const media = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "user" },
audio: true,
});
setStream(media);
} catch (err) {
setError(cameraErrorMessage(err));
}cameraErrorMessage turns an error name into a sentence in English. MDN describes the three most common: NotAllowedError on a refusal, NotFoundError when there is no camera, and NotReadableError when another application holds the camera. The camera is released by the same pattern as the microphone in location 9: an effect keyed on the stream, whose cleanup calls stop() on every track. An extra effect on leaving the page cuts off a recording in progress without handing in a result.
What Claude wrote: a limit that works
The recording clock counts time from a saved start and calls the stop itself:
timerRef.current = setInterval(() => {
const ms = Date.now() - startedAt;
setElapsed(Math.min(ms / 1000, maxSeconds));
if (ms >= maxSeconds * 1000) stopRecording();
}, 100);A function in setInterval remembers the variables from the moment it was created. This one reads only the start time and the limit, which do not change, so nothing in it goes stale. stopRecording first cleans up the interval and then stops the recording, but only if it is still running:
const recorder = recorderRef.current;
if (recorder && recorder.state !== "inactive") recorder.stop();That condition is not decoration. According to MDN, stop() on an inactive recording throws InvalidStateError, and a click on Stop and the limit can arrive at the same moment. After stop() comes the stop event, in which Claude assembles the result:
recorder.onstop = () => {
const durationSec = (Date.now() - startedAt) / 1000;
const mimeType = recorder.mimeType || preferred || "";
const blob = new Blob(chunks, mimeType ? { type: mimeType } : undefined);
onCompleteRef.current(blob, { durationSec, mimeType });
};durationSec is the measured time from start to stop, not a number from the settings, so the editor in lesson 9_3 will get the real length of the clip.
Captain's review
- Stale state in the interval. A typical agent mistake is an
if (isRecording && ...)condition in the interval.isRecordingin that function has the value from the moment of start, which isfalse, so the recording never ends by itself. For us that version passed lint,tscand the build, and a test with a fake clock failed it with the lineexpected "vi.fn()" to be called once, but got 0 times. You look for state variables inside the interval. - The camera turned off. Search the file for
getTracks,clearIntervalandrevokeObjectURL(the page creates an address for the recording preview). A missing one is a leak: the camera lamp stays on after leaving the page, or memory grows with every recording. - Refusal. Click "Turn on camera" and refuse access. For us a browser with a blocked camera showed the message "Camera and microphone access was denied.", not an empty screen.
- Scope. The file list in each session's commit. The sounds session added
formatDurationto the sharedlib/format.tsfor us. This time the recorder did not touch that file, so the merge went through, but that is exactly the kind of change that ends in a conflict.
Merging and cleaning up
Go back to the main folder: a third terminal, a plain claude, and the request "Merge the branches worktree-sounds and worktree-recorder into main, one after another, then lint, tests and build". For us the first branch came in as Fast-forward, because main had not changed since it started, and the second got a merge commit with the line Merge made by the 'ort' strategy..
Now the cleanup. As long as worktrees lie inside the project, tools in the main folder see them: for us npm run lint reported 7056 problems (364 errors, 6692 warnings) from the .next folders in the worktrees, and Vitest ran 12 test files instead of 5, because it counted the copies from both worktrees. Leave both sessions with /exit. According to the documentation, when a worktree has changes or new commits, Claude asks whether to keep it or remove it. Removing deletes the folder and the branch together with the work, so you choose it only after the merge. If you prefer to keep worktrees longer, ask Claude to add .claude/worktrees/** to the ignored paths in eslint.config.mjs and in vitest.config.mts.
Next step
Links to /sounds and /record in the navigation are a change in the shared app/layout.tsx, so you do it after the merge, in one session. If Claude changes something beyond the navigation along the way, /rewind from lesson 0_6 takes back the whole turn. Then a commit, for example "Sounds and recorder".
In the editor below a recorder is waiting, with a fake camera and a lamp. Set the limit to 5 seconds, turn on the agent bug with stale state and see how the recording passes the limit. Then leave the page with the second bug and watch the lamp.
Remember: two longboats sail faster than one only when each rows to a different bay, and whoever does not put out the lantern leaves it burning all night.
Code for this lesson: App.jsx
// Recorder in miniature: a fake camera, a real limit and the camera lamp
import { useEffect, useRef, useState } from 'react';
const TYPES = ['video/mp4;codecs=avc1.64003E,mp4a.40.2', 'video/webm;codecs=vp8,opus', 'video/webm'];
function supported(type) {
return typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(type);
}
function Recorder({ maxSeconds, deny, bugInterval, bugTracks, onLamp, onComplete }) {
const [stream, setStream] = useState(null);
const [error, setError] = useState('');
const [recording, setRecording] = useState(false);
const [elapsed, setElapsed] = useState(0);
const recorderRef = useRef(null);
const timerRef = useRef(null);
const startedAtRef = useRef(0);
function enableCamera() {
setError('');
if (deny) {
setError('No access to the camera. Allow the camera in your browser settings.');
return;
}
// fake stream: stop() switches the camera lamp off; leaky is the agent bug turned on
setStream({ stop: () => onLamp(false), leaky: bugTracks });
onLamp(true);
}
// Cleanup: the camera goes off when the stream disappears or the recorder leaves the screen
useEffect(() => {
if (!stream) return;
return () => {
clearInterval(timerRef.current);
if (!stream.leaky) stream.stop();
};
}, [stream]);
function stop() {
const recorder = recorderRef.current;
if (!recorder || recorder.state === 'inactive') return;
recorder.state = 'inactive';
clearInterval(timerRef.current);
setRecording(false);
const durationSec = (Date.now() - startedAtRef.current) / 1000;
const mimeType = TYPES.find(supported) || 'no MediaRecorder in this browser';
onComplete({ durationSec, mimeType });
}
function start() {
recorderRef.current = { state: 'recording' };
startedAtRef.current = Date.now();
setElapsed(0);
setRecording(true);
timerRef.current = setInterval(() => {
const seconds = (Date.now() - startedAtRef.current) / 1000;
setElapsed(seconds);
if (bugInterval) {
// agent bug: `recording` comes from the moment of start, so it is false
if (recording && seconds >= maxSeconds) stop();
} else if (seconds >= maxSeconds) {
stop();
}
}, 100);
}
return (
<div className="space-y-3">
<div className="relative flex h-56 items-center justify-center rounded-xl bg-gradient-to-br from-slate-800 to-indigo-900">
<span className="text-lg">{stream ? 'Camera preview' : 'Camera off'}</span>
{recording && <span className="absolute top-3 left-3 rounded-full bg-red-600 px-3 py-1 text-xs">β REC</span>}
</div>
{!stream && (
<button type="button" onClick={enableCamera} className="rounded bg-sky-600 px-4 py-2">Turn on camera</button>
)}
{error && <p role="alert" className="text-red-400">{error}</p>}
{stream && (
<div className="space-y-2">
<div className="h-2 w-full overflow-hidden rounded bg-gray-700">
<div className="h-full bg-red-500" style={{ width: `${Math.min(100, (elapsed / maxSeconds) * 100)}%` }} />
</div>
<p className="text-sm">{elapsed.toFixed(1)} s / {maxSeconds} s</p>
<button
type="button"
onClick={recording ? stop : start}
className="rounded bg-red-600 px-4 py-2"
>
{recording ? 'Stop' : 'Record'}
</button>
</div>
)}
</div>
);
}
export default function App() {
const [page, setPage] = useState('record');
const [lamp, setLamp] = useState(false);
const [maxSeconds, setMaxSeconds] = useState(5);
const [deny, setDeny] = useState(false);
const [bugInterval, setBugInterval] = useState(false);
const [bugTracks, setBugTracks] = useState(false);
const [results, setResults] = useState([]);
return (
<div className="min-h-screen bg-gray-950 p-4 text-white">
<div className="mb-4 flex flex-wrap items-center gap-3">
<button type="button" onClick={() => setPage(page === 'record' ? 'feed' : 'record')} className="rounded bg-gray-700 px-4 py-2">
{page === 'record' ? 'Leave the recording page' : 'Back to recording'}
</button>
<span className={lamp ? 'text-green-400' : 'text-gray-400'}>Camera lamp: {lamp ? 'on' : 'off'}</span>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
{page === 'record' ? (
<Recorder
maxSeconds={maxSeconds}
deny={deny}
bugInterval={bugInterval}
bugTracks={bugTracks}
onLamp={setLamp}
onComplete={(r) => setResults((prev) => [r, ...prev])}
/>
) : (
<p className="rounded-xl bg-gray-800 p-6">For You feed. The recorder has left the screen.</p>
)}
</div>
<div className="space-y-2 text-sm">
<label className="flex items-center gap-2">
Limit:
<select value={maxSeconds} onChange={(e) => setMaxSeconds(Number(e.target.value))} className="rounded bg-gray-800 px-2 py-1">
<option value={5}>5 s</option>
<option value={15}>15 s</option>
</select>
</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={deny} onChange={(e) => setDeny(e.target.checked)} /> Deny camera access</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={bugInterval} onChange={(e) => setBugInterval(e.target.checked)} /> Agent bug: stale state in the interval</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={bugTracks} onChange={(e) => setBugTracks(e.target.checked)} /> Agent bug: no stop() on the tracks (tick before turning on the camera)</label>
<p className="pt-2 font-bold">Formats in your browser (isTypeSupported):</p>
<ul>
{TYPES.map((t) => <li key={t}>{t}: {supported(t) ? 'yes' : 'no'}</li>)}
</ul>
<p className="pt-2 font-bold">Recordings:</p>
<ul>
{results.map((r, i) => <li key={i}>{r.durationSec.toFixed(1)} s, {r.mimeType}</li>)}
</ul>
</div>
</div>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the command claude -w sounds do?
2. How does the SoundDetails type use the Sound type from lesson 9_1?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Put the parallel work on sounds and the recorder in order (from the first step):
- Horizontal ordering
Put the command in order that starts a second Claude Code session in a separate worktree named recorder:
- Code editor
Sounds discovery
- Click in order
Build the condition that stops the recording after the limit (click in order):
- Click in order
Build the expression that picks the first format the browser supports (click in order):
- Horizontal ordering
Put in order the start of the call that asks for the camera and microphone after a click:
- Vertical ordering
Put the recording steps in VideoRecorder in order (from the first):
- Code editor
Video recording interface
- Click in order
Build the creation of a Blob from the recorded chunks (click in order):
- Horizontal ordering
Put the line in order that stops the recording only if it is still running:
Tasks after this lesson
- QuestionWhat claude -w does
- QuestionSoundDetails and Sound
- Put in orderParallel work step by step
- Put in orderA second session in a worktree
- Coding taskPractice: Sounds page
- Click in orderThe recording limit condition
- Click in orderChoosing the recording format
- QuestionWhen not to work in parallel
- Put in orderAsking for the camera
- QuestionStale state in the interval
- Put in orderThe recording cycle
- Coding taskPractice: Video recorder
- QuestionPush before a worktree
- Click in orderA Blob from the recording
- Put in orderA safe stop()