Vibe coding with Claude Code course Β· Module 13: Twitch clone
The Deck Camera: Player and Chat, Test First
In this lesson9
Ahoy! The captain wants to broadcast voyages live: the crew on shore should see the deck and talk to him during the watch. In this location you build Live from the Deck, a Twitch clone, a service with live broadcasts. A viewer who enters a channel expects two things at once: a picture and a chat. The picture must be possible to pause, mute and enlarge to the full screen. The chat flows fast, and its logic, for example turning emote codes into pictures, breaks in places you do not see at the first click.
What you will learn
- order a player and a chat in plan mode, with a test as the finish line;
- write with Claude a test for the emote parser before the parser exists, and see how it catches sorting in place;
- read a chat with a functional state update, unique identifiers and
onKeyDownin place of a deprecated event; - check fullscreen in a real browser, which no test in the terminal will check.
A new port: the live-from-the-deck project
The clone is a separate app, so you create it with the command from lesson 1_2, changing only the name:
npx create-next-app@latest live-from-the-deck --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npmThen the familiar routine: a claude session in the new folder, a CLAUDE.md that imports @AGENTS.md (lesson 1_7), Vitest with the @types/node fix from lesson 4_1, and a first commit.
One thing has to be said honestly at the start. A real live broadcast needs the picture from the streamer's camera to reach a server that sends it to viewers in a format for browsers. MDN says this takes special software on the server or an outside service, and protocols outside HTTP, such as RTMP, do not work in the <video> element without plugins. That is a topic for a separate course. Our clone plays a local file in a loop and pretends to be a broadcast. Claude will make the test file if you have the ffmpeg program installed:
ffmpeg -f lavfi -i testsrc2=size=640x360:rate=30 -f lavfi -i sine=frequency=440 -t 60 -c:v libx264 -pix_fmt yuv420p -c:a aac -movflags +faststart public/streams/voyage.mp4lavfi is ffmpeg's built-in source of artificial picture and sound: a coloured test card with a clock and a 440 Hz tone. -t 60 cuts the whole thing to a minute, libx264 and aac are codecs that browsers play, and +faststart moves the table of contents of the file to the beginning so the film starts before the whole file is downloaded. Without ffmpeg, drop any short MP4 of your own into public/streams/.
Request for Claude Code
This step touches types, two functions, two components and a page, so you start with a plan, as in lesson 1_6. The most important sentence of the request says what the proof is: a parser test written before the parser, as in lessons 4_1 and 10_4.
Request for Claude Code:
/plan Add a channel page /channel/[handle] with a player and a chat.
Channel data in lib/channels.ts, the broadcast is the file
/streams/voyage.mp4 played in a loop, muted at the start. The player
components/StreamPlayer.tsx: own buttons Play, Mute, Fullscreen;
fullscreen covers the whole container with the buttons, not the video
element alone. The chat components/LiveChat.tsx, local for now, no
server. A message has emotes as character ranges; put the splitting of
text into parts in lib/chat/parseMessageWithEmotes.ts. Test of that
function first: no emotes, an emote at the start, two side by side,
an emote at the end, ranges in any order. Run it and show the failure,
then write the function.
Done when npm run test -- --run, npm run lint and npx tsc --noEmit
pass without errors.In the plan check whether the test appears before the parser and whether fullscreen applies to the container. If the plan is silent about it, correct it with Ctrl+G before you approve.
What Claude wrote: the test before the parser
An emote is a short code in the text, for example :anchor:, which the chat shows as a picture. The chat server can send a message together with a list of ranges: where each code starts and ends. Open lib/chat/types.ts in Cursor:
// lib/chat/types.ts
export interface EmoteRange {
name: string; // "anchor"
start: number; // index of the first character of the emote code
end: number; // index after the last character of the code, as in slice
}end points at the character after the code, like the second argument of slice, so text.slice(start, end) returns exactly :anchor:. Now open the test that Claude wrote first. The last case is the most interesting:
// lib/chat/parseMessageWithEmotes.test.ts
test("ranges in any order, emotes array unchanged", () => {
const emotes = Object.freeze([anchor(10), { name: "rum", start: 0, end: 5 }]);
const parts = parseMessageWithEmotes(":rum: and :anchor:", emotes);
expect(parts.map((p) => p.kind)).toEqual(["emote", "text", "emote"]);
});The ranges arrive in reverse order, and Object.freeze freezes the array: every attempt to change it ends in an error. anchor(10) is a helper at the top of the file that builds the anchor range from the tenth character. The first run, before the parser existed, ended like this for us:
Error: Failed to resolve import "./parseMessageWithEmotes" from "lib/chat/parseMessageWithEmotes.test.ts". Does the file exist?That is a good failure: the test looks for a function that does not exist yet.
What Claude wrote: the parser
Open lib/chat/parseMessageWithEmotes.ts. The agent's first version sorted the ranges like this:
// lib/chat/parseMessageWithEmotes.ts (the agent's version)
const sorted = emotes.sort((a, b) => a.start - b.start);sort changes the array in place, and this array belongs to the message, not to the parser. Four tests passed, the fifth failed with the message TypeError: Cannot assign to read only property '0' of object '[object Array]'. The corrected version:
// lib/chat/parseMessageWithEmotes.ts
export function parseMessageWithEmotes(text: string, emotes: readonly EmoteRange[]): MessagePart[] {
const sorted = [...emotes].sort((a, b) => a.start - b.start);
const parts: MessagePart[] = [];
let pos = 0;
for (const emote of sorted) {
if (emote.start < pos || emote.end > text.length) continue;
if (emote.start > pos) parts.push({ kind: "text", start: pos, text: text.slice(pos, emote.start) });
parts.push({ kind: "emote", start: emote.start, name: emote.name, code: text.slice(emote.start, emote.end) });
pos = emote.end;
}
if (pos < text.length) parts.push({ kind: "text", start: pos, text: text.slice(pos) });
return parts;
}[...emotes] copies the list before sorting, as in lesson 11_2. pos is the place up to which the text is already cut; a range that overlaps the previous one or reaches past the text is skipped by the function instead of falling over. The word readonly in the parameter type is the second barrier: with it npx tsc --noEmit rejects the agent's version with the message Property 'sort' does not exist on type 'readonly EmoteRange[]'. After the fix: Tests 5 passed (5).
What Claude wrote: the chat
Messages typed by a viewer have no ranges, so findEmotes from lib/chat/emotes.ts looks in the text for codes from the EMOTES dictionary and returns them grouped by emote, not by place. That is why the parser has to sort. Open components/LiveChat.tsx:
// components/LiveChat.tsx
function send() {
const text = draft.trim();
if (!text) return;
const message: ChatMessage = { id: crypto.randomUUID(), author: viewerName, text, emotes: findEmotes(text) };
setMessages((prev) => [...prev, message].slice(-MAX_MESSAGES));
setDraft("");
}crypto.randomUUID() gives every message its own identifier, like the blocks of the chronicle in lesson 11_1. prev => ... is an updater function that sees the freshest list. slice(-MAX_MESSAGES) keeps the last 150 messages so the page does not swell through the whole broadcast. A key starts the sending:
// components/LiveChat.tsx
onKeyDown={(e) => {
if (e.key === "Enter") send();
}}MDN marks the keypress event as deprecated and tells you to use keydown or beforeinput. The React types also mark onKeyPress as @deprecated, but the agent's version with onKeyPress passed lint and tsc for us. It was caught only by a component test that sends a message with Enter: Unable to find an element with the text: <b>ahoy</b>. The same test guards a second thing: tags in the message stay text, because the parts go into <span>{part.text}</span>, and React turns them into plain characters. The list scrolls down by itself:
// components/LiveChat.tsx
useEffect(() => {
const list = listRef.current;
if (list && stickToBottom.current) list.scrollTop = list.scrollHeight;
}, [messages]);stickToBottom is a useRef that on every scroll checks the condition from MDN: Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) <= 1. A viewer reading older messages is not yanked to the bottom.
What Claude wrote: the player and fullscreen
Open components/StreamPlayer.tsx. The state of the buttons is read from the element's events, as in lesson 10_1: onPlay, onPause and onVolumeChange. A muted start with autoPlay you know from lesson 9_1. Fullscreen is new:
// components/StreamPlayer.tsx
useEffect(() => {
function sync() {
setFullscreen(document.fullscreenElement === boxRef.current);
}
document.addEventListener("fullscreenchange", sync);
return () => document.removeEventListener("fullscreenchange", sync);
}, []);According to MDN, document.fullscreenElement is the element shown in fullscreen or null, and fullscreenchange arrives on entering and on leaving. The MDN guide reminds you that the browser also closes fullscreen by itself, usually with the Esc key. That is why the button label asks the browser instead of guessing. The button calls boxRef.current?.requestFullscreen() on the container. MDN adds that this method returns a promise and works only after a user gesture, so it has a .catch with a message.
Captain's review
- Sorting. Search the project (Cmd+Shift+F) for
.sort(: every one has[...in front of it. - Text, not HTML. Search for
dangerouslySetInnerHTML: the chat has none. - Keys. Messages have
key={m.id}, not the index. - Fullscreen in the browser. Vitest will not check this: in jsdom, the pretend browser from lesson 4_1,
requestFullscreendoes not exist at all. Runnpm run dev, open/channel/captain-redbeard, turn fullscreen on, press Esc and read the button label. Or ask Claude in Chrome from lesson 3_8 to do it. In our run the agent's version calledrequestFullscreen()on the<video>and set the state by hand. In fullscreen the LIVE badge and our buttons disappeared, and Chrome showed its own controls with a bar0:02 / 1:00, which gives away that this is a recording. After leaving fullscreen without our button the label still said "Exit fullscreen". The corrected version went back to "Fullscreen".
A typical agent mistake with tests is changing the expected value so the test passes. In the diff you see it at once: the test file changed in the same step as the parser. Ask why.
Next step
When the tests and the browser agree, ask for a commit "Player and chat with a parser test". Then a small step, test first again: "Add slow mode: one viewer message per 5 seconds, with a countdown by the button". A real chat in which everyone sees the messages you will build with the pattern from lesson 6_4: sending with a plain POST request and Server-Sent Events to deliver messages. In the editor below waits a miniature chat: type a message with :anchor: and <b>, switch the agent's version on and see what sorting in place does.
Remember: a captain who trusts the spyglass without checking sees the reef only when he is standing on it; a test is the spyglass you set up before you sail.
Code for this lesson: App.tsx
// Deck chat in miniature: emote parser, Enter through onKeyDown and scrolling down
import { useEffect, useRef, useState } from 'react';
interface EmoteRange {
name: string;
start: number;
end: number;
}
interface ChatMessage {
id: string;
author: string;
text: string;
emotes: readonly EmoteRange[];
}
type MessagePart =
| { kind: 'text'; start: number; text: string }
| { kind: 'emote'; start: number; name: string; code: string };
const EMOTES: Record<string, string> = { anchor: 'β', parrot: 'π¦', treasure: 'π°', rum: 'π₯' };
const MAX_MESSAGES = 150;
const CREW_LINES = ['Land in sight :parrot:', 'Who has the watch? :anchor:', ':rum: for the helmsman', 'Chest full of :treasure: :treasure:'];
// Codes are searched by dictionary, so ranges arrive grouped by emote, not by position
function findEmotes(text: string): readonly EmoteRange[] {
const ranges: EmoteRange[] = [];
for (const name of Object.keys(EMOTES)) {
const code = ':' + name + ':';
for (let i = text.indexOf(code); i !== -1; i = text.indexOf(code, i + code.length)) {
ranges.push({ name, start: i, end: i + code.length });
}
}
return Object.freeze(ranges); // message data is read-only, as from a server
}
function parseMessageWithEmotes(text: string, emotes: readonly EmoteRange[], agentBug: boolean): MessagePart[] {
// The agent's version sorts the message array in place; a frozen array then throws a TypeError
const sorted = agentBug ? (emotes as EmoteRange[]).sort((a, b) => a.start - b.start) : [...emotes].sort((a, b) => a.start - b.start);
const parts: MessagePart[] = [];
let pos = 0;
for (const emote of sorted) {
if (emote.start < pos || emote.end > text.length) continue;
if (emote.start > pos) parts.push({ kind: 'text', start: pos, text: text.slice(pos, emote.start) });
parts.push({ kind: 'emote', start: emote.start, name: emote.name, code: text.slice(emote.start, emote.end) });
pos = emote.end;
}
if (pos < text.length) parts.push({ kind: 'text', start: pos, text: text.slice(pos) });
return parts;
}
// In the project the id comes from crypto.randomUUID(); here a counter is enough
let nextId = 1;
function newMessage(author: string, text: string): ChatMessage {
return { id: 'm' + nextId++, author, text, emotes: findEmotes(text) };
}
// We catch the parser error outside JSX: try/catch around JSX does not catch render errors
function safeParse(message: ChatMessage, agentBug: boolean): { parts: MessagePart[] } | { error: string } {
try {
return { parts: parseMessageWithEmotes(message.text, message.emotes, agentBug) };
} catch (error) {
return { error: (error as Error).message };
}
}
function MessageText({ message, agentBug }: { message: ChatMessage; agentBug: boolean }) {
const result = safeParse(message, agentBug);
if ('error' in result) return <span className="text-red-400">Parser error: {result.error}</span>;
return result.parts.map((part) =>
part.kind === 'emote' ? (
<span key={part.start} role="img" aria-label={part.name} title={part.code}>
{EMOTES[part.name]}
</span>
) : (
<span key={part.start}>{part.text}</span>
),
);
}
export default function App() {
const [messages, setMessages] = useState<ChatMessage[]>(() => [
newMessage('Helmsman', 'Ahoy crew :anchor:'),
newMessage('Parrot_Polly', ':parrot: :treasure: the island is in sight!'),
]);
const [draft, setDraft] = useState('');
const [agentBug, setAgentBug] = useState(false);
const [crewTalking, setCrewTalking] = useState(false);
const listRef = useRef<HTMLOListElement>(null);
const stickToBottom = useRef(true);
useEffect(() => {
const list = listRef.current;
if (list && stickToBottom.current) list.scrollTop = list.scrollHeight;
}, [messages]);
useEffect(() => {
if (!crewTalking) return;
let n = 0;
const id = setInterval(() => {
const line = CREW_LINES[n % CREW_LINES.length];
n += 1;
setMessages((prev) => [...prev, newMessage('Crew', line)].slice(-MAX_MESSAGES));
}, 1000);
return () => clearInterval(id);
}, [crewTalking]);
function send() {
const text = draft.trim();
if (!text) return;
setMessages((prev) => [...prev, newMessage('Deckhand', text)].slice(-MAX_MESSAGES));
setDraft('');
}
return (
<div className="min-h-screen bg-zinc-950 p-4 text-zinc-100">
<div className="mx-auto flex h-96 max-w-md flex-col rounded-lg border border-zinc-800 bg-zinc-900">
<h1 className="border-b border-zinc-800 p-3 font-semibold">Deck chat</h1>
<ol
ref={listRef}
onScroll={(e) => {
const el = e.currentTarget;
stickToBottom.current = Math.abs(el.scrollHeight - el.clientHeight - el.scrollTop) <= 1;
}}
className="flex-1 space-y-1 overflow-y-auto p-3 text-sm"
>
{messages.map((m) => (
<li key={m.id}>
<strong className="text-amber-400">{m.author}:</strong> <MessageText message={m} agentBug={agentBug} />
</li>
))}
</ol>
<div className="flex gap-2 border-t border-zinc-800 p-3">
<input
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') send();
}}
maxLength={300}
aria-label="Chat message"
placeholder="Try: <b>ahoy</b> :rum: and :anchor:"
className="min-w-0 flex-1 rounded bg-zinc-800 px-3 py-2"
/>
<button type="button" onClick={send} className="rounded bg-purple-600 px-3 py-2 font-semibold">
Send
</button>
</div>
</div>
<div className="mx-auto mt-3 max-w-md space-y-2 text-sm">
<label className="flex items-center gap-2">
<input type="checkbox" checked={crewTalking} onChange={(e) => setCrewTalking(e.target.checked)} />
The crew writes every second (scroll up: the chat will not yank you)
</label>
<label className="flex items-center gap-2">
<input type="checkbox" checked={agentBug} onChange={(e) => setAgentBug(e.target.checked)} />
The agent's version: emotes.sort(...) in place
</label>
<p className="text-zinc-400">Messages: {messages.length} (the chat keeps at most {MAX_MESSAGES})</p>
</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. How does Live from the Deck show a live broadcast?
2. Why does StreamPlayer set the fullscreen button label in the fullscreenchange event from document.fullscreenElement, instead of toggling state in onClick?
These are 2 of 6 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Click in order
Build the parser line that sorts the emote ranges without changing the message array
- Horizontal ordering
Arrange the line from the send function that appends a message and keeps the last 150 (one line):
- Click in order
Build the condition from the chat field's onKeyDown that sends the message with the Enter key
- Code editor
Build a stream player with video controls
- Vertical ordering
Arrange the steps in which Claude built the emote parser:
- Code editor
Create a real-time chat interface
- Vertical ordering
Arrange the steps of the send function in LiveChat:
- Click in order
Build the line that makes StreamPlayer start listening for fullscreen changes
Tasks after this lesson
- QuestionQuiz: the broadcast in the clone
- QuestionQuiz: fullscreen state
- QuestionQuiz: the end of an emote range
- Click in orderBuild: sorting a copy
- Put in orderOrder: appending a message
- Click in orderBuild: sending with Enter
- Coding taskPractice: Stream player
- QuestionQuiz: what caught onKeyPress
- QuestionQuiz: tags in a message
- Put in orderOrder: test first
- Coding taskPractice: Live chat
- Put in orderOrder: steps of send
- Click in orderBuild: fullscreen listener
- QuestionQuiz: chat scrolling