Vibe coding with Claude Code course Β· Module 9: Discord clone

Voice Channel and Crew Status: a Screen from a Sketch

9 min read
In this lesson8

Before a boarding nobody has time to type in the chat. The crew talks live, and the captain wants to see at a glance who sits in the channel, who is speaking right now, and who has muted their microphone. Discord solves this with voice channels you enter like a cabin, and an activity status next to the name that tells what the pirate is doing outside the chat.

What you will learn

  • order a screen with a sketch instead of a long description, as in location 4;
  • use Cursor's search to find the fields the agent used that are not in the type;
  • ask for the microphone only after a click, and release it when leaving the channel;
  • add an activity status with a duration counted in a pure function.

The voice state type first

Before the screen exists you need the type it will use. Ask Claude for types/voice.ts with the state of one person in a channel. Open the file in Cursor:

export interface VoiceState {
  memberId: string;
  channelId: string;
  selfMute: boolean; // muted themselves
  selfDeaf: boolean; // turned their own sound off
  serverMute: boolean; // muted by a moderator
  serverDeaf: boolean; // sound turned off by a moderator
  speaking: boolean; // in the clone, from test data
}

Muting has two sources and therefore two fields: in the voice state Discord distinguishes self_mute, a mute by the person themselves, and mute, a mute by the server. A pirate muted by a moderator cannot unmute themselves, so the screen must show it differently. The state has no name: you find the person by memberId in the server's member list.

A sketch as a request

A voice channel is easier to draw than to describe: tiles of people, a ring around the one who is speaking, buttons at the bottom. In location 4 you gave Claude an image by a file path, and you will do the same here. The Claude Code documentation advises reaching for an image when words would be unclear or long. Take a screenshot of a voice channel in Discord, or a sketch on paper, and save it as sketches/voice-channel.png.

Request for Claude Code:

First describe in a few sentences what you see in the sketch
sketches/voice-channel.png. Then build a Client Component
components/VoiceChannelView.tsx in the style of @components/ServerSidebar.tsx:
a header with the channel name and the number of people (3/5 with a
limit), tiles of connected people with a green ring around the one who
is speaking, and the buttons Join, Mute, Deafen and Disconnect. The state
is in @types/voice.ts, the people in members. Do not invent fields that
are not there and do not use any. The microphone only after clicking
Join, stopped after disconnecting. At the end lint, types and build.

The first sentence checks that Claude read the sketch the way you do. The sentence about fields and any is deliberate: this is where the agent goes wrong most often.

What Claude wrote: the header

Open components/VoiceChannelView.tsx. The number of people and the state of the Join button have no state of their own, they are computed from the data on every draw:

const joined = stream !== null;
const connected = joined ? [...others, mine] : others;
const isFull = channel.userLimit !== undefined && connected.length >= channel.userLimit;

others are the states of the other people in the channel, and mine is your state built from selfMute and selfDeaf. When the channel has a limit and is full, the button gets disabled and the text "Channel full". Without a limit isFull always gives false, and the header shows just the number of people.

What Claude wrote: the tiles

Each tile looks up the person by identifier, and the ring depends on a field that really is in the type:

const member = members.find((m) => m.id === voice.memberId);
if (!member) return null;
const ring = voice.speaking ? "ring-4 ring-green-500" : "";

Under the name stands a description: "muted by a moderator" when serverMute, "muted" when selfMute, or "speaking". The ring colour is only a hint for the eye, so the text "speaking" is read by a screen reader too. In ours the war-council channel showed 3/5 in the header and three tiles with three different descriptions.

What Claude wrote: the microphone

According to MDN getUserMedia always asks the user for permission, works only in a secure context (HTTPS or localhost), and outside it navigator.mediaDevices is undefined. A refusal ends with a NotAllowedError. That is why the microphone request stands in the click handler, never in the drawing itself:

async function join() {
  if (!navigator.mediaDevices) {
    setError("The microphone works only on an HTTPS page or on localhost.");
    return;
  }
  try {
    setStream(await navigator.mediaDevices.getUserMedia({ audio: true }));
  } catch {
    setError("No microphone access. Check the browser permissions.");
  }
}

The stream goes into state, and an effect takes care of releasing the microphone:

useEffect(() => {
  if (!stream) return;
  return () => stream.getTracks().forEach((track) => track.stop());
}, [stream]);

The function returned from the effect runs when the stream changes or the component leaves the page. "Disconnect" sets the stream to null, so every track gets stop(). According to MDN a stopped track has the ended state at once, and the microphone may switch off when no track uses it any more. Mute changes track.enabled, so the track stays but stops transmitting.

One thing has to be said plainly: this clone does not send voice. Real conversation is WebRTC, and MDN describes that setting up a connection between two devices needs a signalling server. That is a separate, large topic. Pirate's Cove shows the state of the channel: who is there, who is speaking, who is muted.

Captain's review

  1. Fields out of thin air. A typical agent mistake: the component uses a field that is not in the type because it remembers it from other projects, for example voice.isSpeaking or voice.username. Open the project-wide search in Cursor (Cmd+Shift+F on a Mac, Ctrl+Shift+F on Windows and Linux), type voice. and compare every hit with the fields in types/voice.ts. The compiler sees it too, if you do not get in its way. Ours, with such fields, gave:
components/VoiceChannelView.tsx(16,51): error TS2551: Property 'isSpeaking' does not exist on type 'VoiceState'. Did you mean 'speaking'?
components/VoiceChannelView.tsx(17,18): error TS2339: Property 'username' does not exist on type 'VoiceState'.

The first field you fix in the component, because the type has speaking. The second is not in the state and should not be: you take the name from the member list. If a field really were missing from the data, you add it to the type and the data on purpose. Never through any: search the project for any and eslint-disable. In ours npm run lint rejected a prop typed any[] with the line Unexpected any. Specify a different type, but npx tsc --noEmit went silent after such a "fix".

  1. A full channel. Change userLimit to 3 in the data and check that Join is disabled.
  2. The microphone after a click. Open the voice channel and wait a moment: the browser cannot ask for the microphone until you click Join. Then click and deny access. In ours, after the denial the message "No microphone access. Check the browser permissions." appeared under the header.
  3. Proof. Ask for a test with a fake microphone: getUserMedia is not called before the click, and after Disconnect every track gets stop(). Then lint, types and build.

Next step: the activity status

Discord shows next to a name what the pirate is doing: a game, a stream, music or a custom status. Ask for it in a separate request: an Activity type in types/voice.ts, a pure formatElapsed function with tests and an ActivityDisplay component in the member list. The type was built from the fields in the Discord documentation:

export type ActivityType = "playing" | "streaming" | "listening" | "watching" | "custom" | "competing";

export interface Activity {
  type: ActivityType;
  name: string; // "Sea of Thieves"
  details?: string; // what the player is doing right now
  state?: string; // party state or the text of a custom status
  url?: string; // streams only
  timestamps?: { start?: number }; // milliseconds since 1970
  party?: { size: [current: number, max: number] };
}

party.size is a pair of numbers: how many players are in the party and how many will fit. A custom status is an activity of type custom whose text stands in state, so a separate status field is not needed. The "Watch the stream" link appears only when type is streaming and there is a url; Discord checks that address and for streams supports only Twitch and YouTube.

The time since the start is counted by formatElapsed(start, now): for 65 seconds it returns "1:05", and above an hour it adds hours. The function gets now from outside, because Date.now() in the drawing itself is rejected by the react-hooks/purity rule. The current time comes from a small useNow hook that sets state in a setInterval every second. On the first screen the time is not there yet, so the server and the browser draw the same thing. Ask for a commit, for example "Voice channel and activity status".

In the editor below a voice channel is waiting: join, mute yourself, click a tile to make someone start speaking, and watch Anne's play time grow.

Remember: a voice channel is state you can see on the screen, and the captain's eye is a project search that shows whether the agent has added a crew that is not on the list.

Code for this lesson: App.jsx
// Voice channel and activity status in miniature.
// In the project Join calls getUserMedia and Disconnect stops the microphone tracks.
// The editor has no microphone access, so here Join only changes state.
import { useEffect, useState } from 'react';

const members = [
  { id: 'redbeard', displayName: 'Captain Redbeard' },
  { id: 'anne', displayName: 'Anne Bonny' },
  { id: 'jack', displayName: 'Jack Rackham' },
  { id: 'blackbeard', displayName: 'Blackbeard' },
];

const channel = { id: 'war-council', name: 'war-council', userLimit: 5 };

const initialStates = [
  { memberId: 'redbeard', selfMute: false, selfDeaf: false, serverMute: false, serverDeaf: false, speaking: true },
  { memberId: 'anne', selfMute: true, selfDeaf: false, serverMute: false, serverDeaf: false, speaking: false },
  { memberId: 'blackbeard', selfMute: false, selfDeaf: false, serverMute: true, serverDeaf: false, speaking: false },
];

const startedAt = Date.now() - 42 * 60000;

const activities = {
  anne: { type: 'playing', name: 'Sea of Thieves', details: 'Hunting for treasure', timestamps: { start: startedAt }, party: { size: [3, 4] } },
  jack: { type: 'streaming', name: 'Twitch', details: 'Live boarding', url: 'https://www.twitch.tv/' },
  redbeard: { type: 'custom', name: 'Custom Status', state: 'On the bridge until dawn' },
};

const verbs = { playing: 'Playing', streaming: 'Streaming', listening: 'Listening to', watching: 'Watching', competing: 'Competing in' };

// The same pure function as in lib/time.ts.
function formatElapsed(start, now) {
  const total = Math.max(0, Math.floor((now - start) / 1000));
  const hours = Math.floor(total / 3600);
  const minutes = Math.floor((total % 3600) / 60);
  const seconds = String(total % 60).padStart(2, '0');
  return hours > 0 ? hours + ':' + String(minutes).padStart(2, '0') + ':' + seconds : minutes + ':' + seconds;
}

function useNow() {
  const [now, setNow] = useState(null);
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  return now;
}

function ActivityDisplay({ activity }) {
  const now = useNow();
  if (activity.type === 'custom') return <p className="text-xs text-gray-400">{activity.state}</p>;
  const start = activity.timestamps && activity.timestamps.start;
  return (
    <div className="text-xs text-gray-400">
      <p>{verbs[activity.type]} <strong className="text-gray-200">{activity.name}</strong></p>
      {activity.details && <p>{activity.details}</p>}
      {activity.party && <p>Party {activity.party.size[0]} of {activity.party.size[1]}</p>}
      {start !== undefined && now !== null && <p>{formatElapsed(start, now)} since start</p>}
      {activity.type === 'streaming' && activity.url && (
        <a href={activity.url} target="_blank" rel="noreferrer" className="text-indigo-300 underline">Watch the stream</a>
      )}
    </div>
  );
}

export default function App() {
  const [states, setStates] = useState(initialStates);
  const [joined, setJoined] = useState(false);
  const [selfMute, setSelfMute] = useState(false);
  const [selfDeaf, setSelfDeaf] = useState(false);
  const me = { id: 'jack', displayName: 'Jack Rackham' };

  const mine = { memberId: me.id, selfMute, selfDeaf, serverMute: false, serverDeaf: false, speaking: false };
  const connected = joined ? [...states, mine] : states;
  const isFull = connected.length >= channel.userLimit;

  function toggleSpeaking(memberId) {
    setStates((prev) => prev.map((s) => (s.memberId === memberId ? { ...s, speaking: !s.speaking } : s)));
  }

  function leave() {
    setJoined(false);
    setSelfMute(false);
    setSelfDeaf(false);
  }

  return (
    <div className="min-h-screen space-y-4 bg-gray-700 p-4 text-gray-100">
      <section className="space-y-3 rounded-lg bg-gray-900 p-4">
        <header className="flex items-center justify-between">
          <h2 className="font-semibold">
            β™ͺ {channel.name} <span className="text-sm text-gray-400">{connected.length}/{channel.userLimit}</span>
          </h2>
          {!joined && (
            <button onClick={() => setJoined(true)} disabled={isFull} className="rounded bg-green-600 px-3 py-1 font-semibold disabled:bg-gray-600">
              {isFull ? 'Channel full' : 'Join'}
            </button>
          )}
        </header>
        <p className="text-xs text-gray-400">Click a tile to make that person start or stop speaking.</p>
        <ul className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          {connected.map((voice) => {
            const member = members.find((m) => m.id === voice.memberId);
            if (!member) return null;
            const ring = voice.speaking ? 'ring-4 ring-green-500' : '';
            const label = voice.serverMute ? 'muted by a moderator' : voice.selfMute ? 'muted' : voice.speaking ? 'speaking' : '';
            return (
              <li key={voice.memberId}>
                <button onClick={() => toggleSpeaking(voice.memberId)} className="flex w-full flex-col items-center gap-1 rounded-lg bg-gray-800 p-3">
                  <span className={'flex h-12 w-12 items-center justify-center rounded-full bg-indigo-500 font-bold ' + ring}>
                    {member.displayName.slice(0, 2).toUpperCase()}
                  </span>
                  <span className="text-sm">{member.displayName}</span>
                  <span className="text-xs text-gray-400">{label}{voice.serverDeaf || voice.selfDeaf ? ', cannot hear' : ''}</span>
                </button>
              </li>
            );
          })}
        </ul>
        {joined && (
          <div className="flex flex-wrap gap-2">
            <button onClick={() => setSelfMute(!selfMute)} aria-pressed={selfMute} className="rounded bg-gray-800 px-3 py-1">
              {selfMute ? 'Unmute' : 'Mute'}
            </button>
            <button onClick={() => setSelfDeaf(!selfDeaf)} aria-pressed={selfDeaf} className="rounded bg-gray-800 px-3 py-1">
              {selfDeaf ? 'Undeafen' : 'Deafen'}
            </button>
            <button onClick={leave} className="rounded bg-red-600 px-3 py-1">Disconnect</button>
          </div>
        )}
      </section>

      <section className="rounded-lg bg-gray-800 p-4">
        <h3 className="mb-2 text-xs font-semibold uppercase text-gray-400">Activity status</h3>
        <ul className="space-y-3">
          {members.filter((m) => activities[m.id]).map((m) => (
            <li key={m.id}>
              <p className="text-sm font-semibold">{m.displayName}</p>
              <ActivityDisplay activity={activities[m.id]} />
            </li>
          ))}
        </ul>
      </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. 1. Which fields does the VoiceState type have in Pirate's Cove?

  2. 2. Why does VoiceState have selfMute and serverMute separately?

These are 2 of 8 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Horizontal ordering

    Arrange the line from the join function that asks for the microphone: setStream(await navigator.mediaDevices.getUserMedia({ audio: true }));

  • Click in order

    Click to build the definition of the optional userLimit field:

  • Code editor

    Voice channel component

  • Vertical ordering

    Arrange the steps of reviewing a component in which the agent may have used fields outside the type:

  • Click in order

    Click to build the call that counts the time since the activity start: formatElapsed(start, now)

  • Code editor

    Rich presence component

  • Vertical ordering

    Arrange what happens in ActivityDisplay before the time since the start appears:

  • Horizontal ordering

    Arrange the line from the effect that releases the microphone after disconnecting: stream.getTracks().forEach((track) => track.stop())

  1. QuestionQuiz: VoiceState fields
  2. QuestionQuiz: Two kinds of muting
  3. Put in orderOrdering: The microphone request
  4. QuestionQuiz: Who is speaking
  5. Click in orderOrdering: The userLimit field in a type
  6. Coding taskPractice: Voice channel UI
  7. QuestionQuiz: Activity status
  8. QuestionQuiz: Activity types
  9. Put in orderOrdering: Hunting for fields out of thin air
  10. QuestionQuiz: The party field in Activity
  11. Click in orderOrdering: Calling formatElapsed
  12. Coding taskPractice: Activity display
  13. QuestionQuiz: Custom status
  14. Put in orderOrdering: Elapsed time on the screen
  15. QuestionQuiz: The stream link
  16. Put in orderOrdering: Stopping the microphone

Useful articles