Vibe coding with Claude Code course Β· Module 10: TikTok clone
Duet, Stitch and the Editor: Small Steps and a TODO List
In this lesson11
The crew already has a feed, sounds and a recorder. Now they want to answer other people's clips: record themselves next to the captain's clip, which is a duet, or cut a few seconds out of someone else's clip and add their own ending, which is a stitch. Every recording also has to be trimmed and captioned before it reaches the feed. That is three features at once, and with video that is a straight road to a component that looks finished while half of its buttons do nothing.
What you will learn
- split a big feature into three small requests and read three small diffs instead of one huge one;
- demand from Claude a list of the things it did not do, instead of silent stand-ins;
- check that a type and an interface use the same set of values;
- read an editor that leaves no addresses of recordings behind in memory.
Duet and stitch in Treasure Reels
In the clone a duet is your recording next to someone else's clip, on a split screen, in one of two layouts: side by side or top and bottom. A stitch is a fragment of someone else's clip followed by your recording. In its 2020 announcement of stitch, TikTok let you pick up to five seconds of the original, and in Treasure Reels that limit is the constant MAX_STITCH_SECONDS. In the real TikTok an author can also turn off duets and stitches of their videos with one reuse setting, so in the future the clone will need a similar flag.
Why three steps
A single request "build a duet, a stitch and an editor" gives several hundred lines in several files. At that scope an agent happily leaves a stand-in in the middle: a function that is called but defined nowhere, or a button with an empty click handler. In a huge diff that is easy to miss. Three small requests give three diffs, each of which you read in a few minutes, and three commits you can return to.
Request for Claude Code (step 1):
Step 1 of 3. In types/duet.ts the types of a duet and a stitch: the duet
layouts as one constant array DUET_LAYOUTS from which the type
DuetLayout is derived, DuetVideo with a volume mix, StitchVideo with a
fragment of up to 5 seconds and the phases of creating a stitch. In
lib/duet.ts the functions createDuet and createStitch with tests.
Nothing more. At the end tests and types.What Claude wrote: one set of layouts
Open types/duet.ts in Cursor. At the top stands the array from which the type is derived:
export const DUET_LAYOUTS = ["side-by-side", "top-bottom"] as const;
export type DuetLayout = (typeof DUET_LAYOUTS)[number];as const turns the array into a list of exactly those two strings, and (typeof DUET_LAYOUTS)[number] builds from it the union "side-by-side" | "top-bottom". The type and the choice buttons will read from one place. Below, the file has the type of the stitch phases: "select-clip", then "record-reaction", and finally "preview", that is choosing a fragment, recording the answer and previewing the whole.
In lib/duet.ts there is a function that assembles a new duet:
export function createDuet(originalVideoId: string, layout: DuetLayout): DuetVideo {
return {
id: crypto.randomUUID(),
originalVideoId,
layout,
audioMix: { original: 0.5, duet: 0.5 },
};
}crypto.randomUUID() is a built-in generator of unique identifiers, so you do not have to write your own. According to MDN, in the browser it works only in a secure context, that is on HTTPS or on localhost, like the camera. audioMix starts even: half the volume of the original and half of your recording. createStitch trims the fragment so that it lasts from 1 to 5 seconds and does not run past the length of the original.
Step 2: a view with a TODO list
Request for Claude Code (step 2):
Step 2 of 3. components/DuetRecorder.tsx and the page
app/duet/[videoId]: the original on one side, a place for the camera
on the other, a layout choice from DUET_LAYOUTS. No camera and no
recording yet. Mark everything you do not do with a TODO(duet) comment
and list it at the end of your answer.The last sentence turns silent stand-ins into an open list. In this step the list should have one item: the camera preview and recording. Search the project (Cmd+Shift+F on a Mac, Ctrl+Shift+F on Windows) for TODO(duet) and compare the hits with the list. Every TODO outside the list is a stand-in nobody told you about.
What Claude wrote: choosing a layout
Open components/DuetRecorder.tsx. The buttons come from the array, and the labels from a map:
const LAYOUT_LABELS: Record<DuetLayout, string> = {
"side-by-side": "Side by side",
"top-bottom": "Top and bottom",
};Record<DuetLayout, string> is an object that must have a label for every layout in the union. The buttons themselves come from the array (without the Tailwind classes here):
{DUET_LAYOUTS.map((value) => (
<button key={value} type="button" role="radio" aria-checked={layout === value} onClick={() => setLayout(value)}>
{LAYOUT_LABELS[value]}
</button>
))}A new layout added to the array shows up among the buttons by itself, and the compiler makes sure it has a label. For us adding "green-screen" to the array without a label ended with the error TS2741 and the line Property '"green-screen"' is missing in type. The buttons have role="radio" and aria-checked, because it is a choice of one option from several. After a click on "Top and bottom" the page /duet/v1 showed for us the original at the top and the place for the camera below it.
Step 3: the clip editor
Request for Claude Code (step 3):
Step 3 of 3. components/VideoEditor.tsx for the recording from
@components/VideoRecorder.tsx: a preview, trimming the start and the end
within durationSec, filters that really change the preview, a caption
of up to 150 characters and a save. Create the preview address once per
file and revoke it on cleanup. Use the editor on the /record page after
a recording. At the end lint, types, tests and build.What Claude wrote: the recording's address
A recording from the recorder is a Blob, a file in the browser's memory. The <video> element needs an address, so Claude creates it in an effect:
useEffect(() => {
const url = URL.createObjectURL(blob);
const video = videoRef.current;
if (video) video.src = url;
return () => URL.revokeObjectURL(url);
}, [blob]);According to MDN, every call of createObjectURL creates a new address, even for the same file, and as long as the address lives, the file cannot be removed from memory. That is why the address is created once per file and revoked on the effect's cleanup. In development mode (npm run dev) React runs the effect twice to catch a missing cleanup: for us the browser showed two created addresses and one revoked, and the video played from the second one. The /record page gives the editor key={recording.id}, so a new recording gets a fresh editor with a new trim end.
What Claude wrote: filters and trimming
A filter is a key from a map, and the preview really uses it:
const FILTERS = {
none: { label: "None", css: "none" },
sepia: { label: "Old map", css: "sepia(0.8)" },
mono: { label: "Black and white", css: "grayscale(1)" },
cold: { label: "Cold", css: "hue-rotate(180deg)" },
} as const;The <video> element gets style={{ filter: FILTERS[filter].css }}, which is a CSS filter applied to the picture. It has to be said honestly: the filter changes only the preview, not the file. Saving sends the chosen filter as information, and burning it into the recording is a separate job. Trimming works in the preview like this:
function handleTimeUpdate() {
const video = videoRef.current;
if (video && video.currentTime >= trimEnd) video.currentTime = trimStart;
}timeupdate is an event the player sends several times a second during playback. When the time reaches the trim end, the preview goes back to the start. The trim end starts from durationSec in the recorder's metadata, not from a number typed in by hand. For us with the end set to 2 seconds a clip that had played for 3.5 seconds stood at 1.35 seconds, which means it had turned back.
Captain's review
- Everything defined and imported. A typical agent mistake is calling a function that exists nowhere, for example
generateId(), or a hook without an import. Here the compiler is on your side: for usnpx tsc --noEmitreportederror TS2304: Cannot find name 'generateId', and the build ended with the lineFailed to type check.. So you run the types after every step, not once at the end. - An address in the render. The second typical mistake is
const videoUrl = URL.createObjectURL(blob)in the body of the component. For us it passed lint andtsc, and a test that types three letters of the caption reportedexpected 4 to be 1: four addresses instead of one, none of them revoked. Search forcreateObjectURLand check whetherrevokeObjectURLstands next to it. - Buttons that do something. A filter that changes only the highlight of the button is a component that looks finished. Search the file for
FILTERS[filter]: if the chosen filter does not reach the preview'sstyle, the buttons are decoration. Then click each one in the browser. - One set of values. The layout type and the choice buttons read from
DUET_LAYOUTS. A value typed by hand in a selector, or a third value in a separate union, is a sign that the sets will drift apart.
Next step
After every step ask for a commit, and after the third run the review with fresh eyes from lesson 2_9. /code-review without an argument checks the commits that are not yet in the remote repository and the unsaved changes, so it covers all three steps. You treat every finding as a hypothesis: you check it before you ask for a fix in one narrow request. The item from the TODO list, the camera in the duet, is the next small request on another voyage: it will use the same recorder, so it needs no new camera code.
In the editor below a duet is waiting with a layout choice, and an editor with a counter of object addresses. Type a caption with both agent bugs off, then turn on the address bug and type a few more letters. At the end turn on the second bug and click the filters.
Remember: two pirates in a duet must sing in the same key, and a captain who divides the voyage into short stages knows at every stop what is already in the hold and what is still missing.
Code for this lesson: App.jsx
// Duet and editor in miniature: layouts from one array, filters and a counter of object URLs
import { useEffect, useState } from 'react';
const DUET_LAYOUTS = ['side-by-side', 'top-bottom'];
const LAYOUT_LABELS = { 'side-by-side': 'Side by side', 'top-bottom': 'Top and bottom' };
const FILTERS = {
none: { label: 'None', css: 'none' },
sepia: { label: 'Old map', css: 'sepia(0.8)' },
mono: { label: 'Black and white', css: 'grayscale(1)' },
cold: { label: 'Cold', css: 'hue-rotate(180deg)' },
};
const CAPTION_MAX = 150;
const MIN_CLIP = 0.5;
// Metadata from the recorder: the real length of the recording
const recording = { durationSec: 8.4, blob: new Blob(['fake recording'], { type: 'video/webm' }) };
const stats = { created: 0, revoked: 0 };
function makeUrl(blob) {
stats.created += 1;
return URL.createObjectURL(blob);
}
function revokeUrl(url) {
stats.revoked += 1;
URL.revokeObjectURL(url);
}
function Editor({ urlBug, filterBug }) {
const [trimStart, setTrimStart] = useState(0);
const [trimEnd, setTrimEnd] = useState(recording.durationSec);
const [filter, setFilter] = useState('none');
const [caption, setCaption] = useState('');
// Good version: one URL per file, created in an effect and revoked on cleanup
useEffect(() => {
if (urlBug) return;
const url = makeUrl(recording.blob);
// in a real editor: videoRef.current.src = url
return () => revokeUrl(url);
}, [urlBug]);
// Agent bug: a new URL on every render, never revoked
const buggyUrl = urlBug ? makeUrl(recording.blob) : null;
const previewFilter = filterBug ? 'none' : FILTERS[filter].css;
return (
<div className="space-y-3">
<div
className="flex h-40 items-center justify-center rounded-xl bg-gradient-to-br from-amber-400 via-rose-500 to-indigo-700 text-sm"
style={{ filter: previewFilter }}
>
Preview: {trimStart.toFixed(1)}-{trimEnd.toFixed(1)} s
</div>
{buggyUrl && <p className="truncate text-xs text-gray-400">New URL: {buggyUrl}</p>}
<label className="flex items-center gap-2 text-sm">
Start
<input type="range" min={0} max={trimEnd - MIN_CLIP} step={0.1} value={trimStart} onChange={(e) => setTrimStart(Number(e.target.value))} className="flex-1" />
</label>
<label className="flex items-center gap-2 text-sm">
End
<input type="range" min={trimStart + MIN_CLIP} max={recording.durationSec} step={0.1} value={trimEnd} onChange={(e) => setTrimEnd(Number(e.target.value))} className="flex-1" />
</label>
<div className="flex flex-wrap gap-2">
{Object.keys(FILTERS).map((id) => (
<button
key={id}
type="button"
aria-pressed={filter === id}
onClick={() => setFilter(id)}
className={filter === id ? 'rounded-full bg-white px-3 py-1 text-black' : 'rounded-full bg-gray-700 px-3 py-1'}
>
{FILTERS[id].label}
</button>
))}
</div>
<label className="flex flex-col gap-1 text-sm">
Caption
<textarea value={caption} maxLength={CAPTION_MAX} onChange={(e) => setCaption(e.target.value)} rows={2} className="rounded bg-gray-800 p-2" />
</label>
<p className="text-right text-xs text-gray-400">{caption.length}/{CAPTION_MAX}</p>
</div>
);
}
function UrlCounter() {
const [counts, setCounts] = useState({ ...stats });
useEffect(() => {
const id = setInterval(() => {
setCounts((prev) => (prev.created === stats.created && prev.revoked === stats.revoked ? prev : { ...stats }));
}, 200);
return () => clearInterval(id);
}, []);
return <p>Object URLs: created <strong>{counts.created}</strong>, revoked <strong>{counts.revoked}</strong></p>;
}
export default function App() {
const [layout, setLayout] = useState('side-by-side');
const [urlBug, setUrlBug] = useState(false);
const [filterBug, setFilterBug] = useState(false);
const [showEditor, setShowEditor] = useState(true);
return (
<div className="min-h-screen space-y-4 bg-gray-950 p-4 text-white">
<section className="space-y-2">
<h2 className="font-bold">Duet</h2>
<div role="radiogroup" aria-label="Duet layout" className="flex gap-2">
{DUET_LAYOUTS.map((value) => (
<button
key={value}
type="button"
role="radio"
aria-checked={layout === value}
onClick={() => setLayout(value)}
className={layout === value ? 'rounded-full bg-white px-3 py-1 text-black' : 'rounded-full bg-gray-700 px-3 py-1'}
>
{LAYOUT_LABELS[value]}
</button>
))}
</div>
<div className={layout === 'side-by-side' ? 'grid h-32 grid-cols-2 gap-1' : 'grid h-32 grid-rows-2 gap-1'}>
<div className="flex items-center justify-center rounded bg-sky-800 text-sm">Captain's clip</div>
<div className="flex items-center justify-center rounded bg-gray-800 text-sm text-gray-400">TODO(duet): camera</div>
</div>
</section>
<section className="grid gap-4 md:grid-cols-2">
<div>
<h2 className="mb-2 font-bold">Clip editor ({recording.durationSec} s from the recorder)</h2>
{showEditor ? (
<Editor key={urlBug ? 'bug' : 'ok'} urlBug={urlBug} filterBug={filterBug} />
) : (
<p className="rounded bg-gray-800 p-4 text-sm">Editor closed.</p>
)}
</div>
<div className="space-y-2 text-sm">
<UrlCounter />
<button type="button" onClick={() => setShowEditor((s) => !s)} className="rounded bg-gray-700 px-3 py-1">
{showEditor ? 'Close editor' : 'Open editor'}
</button>
<label className="flex items-center gap-2"><input type="checkbox" checked={urlBug} onChange={(e) => setUrlBug(e.target.checked)} /> Agent bug: a URL on every render</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={filterBug} onChange={(e) => setFilterBug(e.target.checked)} /> Agent bug: filters not connected to the preview</label>
</div>
</section>
</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 is a duet in Treasure Reels?
2. What does the audioMix field in DuetVideo describe?
These are 2 of 9 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Put the steps of building the duet and the editor from the lesson in order (from the first):
- Vertical ordering
Put the pieces of the duet layout choice in order so that each uses the previous one:
- Code editor
Duet recording interface
- Horizontal ordering
Put the line in order that builds the DuetLayout type from the DUET_LAYOUTS array:
- Vertical ordering
Put the phases of creating a stitch from the StitchPhase type in order (from the first):
- Code editor
Video editing interface
- Horizontal ordering
Put the effect cleanup line in order that revokes the recording address:
- Click in order
Build the condition that sends the preview back to the trim start (click in order):
- Vertical ordering
Put the lines of the effect that creates and revokes the recording address in order (top to bottom):
- Click in order
Build the click handler of a duet layout button (click in order):
- Vertical ordering
Put the path of a recording from the camera to the editor in order (from the first step):
- Horizontal ordering
Put in order the start of the map that must have a label for every duet layout:
- Click in order
Build the field with a unique identifier of a new duet (click in order):
Tasks after this lesson
- QuestionA duet in Treasure Reels
- Put in orderThree steps instead of one
- Put in orderFrom the layout array to the buttons
- Coding taskPractice: Duet recorder
- QuestionThe audioMix field
- QuestioncreateStitch and the fragment limit
- Put in orderA type from the layout array
- Put in orderStitch phases
- QuestionA TODO list in the request
- Coding taskPractice: Video editor
- QuestionThe recording address in an effect
- Put in orderRevoking the recording address
- Click in orderBack to the trim start
- Put in orderThe effect with the recording address
- QuestionFilters connected to the preview
- Click in orderChoosing a layout on click
- Put in orderFrom the camera to the editor
- QuestionDuet vs stitch
- Put in orderThe layout label map
- Click in orderThe duet identifier
- QuestionWhen to remove a worktree
- QuestionWorktrees and lint and tests