Vibe coding with Claude Code course · Module 8: Slack clone

The Ship's Bell: Mentions, Notifications and the Notification Hook

9 min read
In this lesson9

In the #general channel a lot goes on, and you only want to know when someone needs something from you. Slack solves this with mentions: you type @ and a name, and that person gets a notification. It is the bell that calls one particular sailor on deck, not the whole fleet.

The problem: four kinds of calls

In Ship's Comms a mention has four forms: @redbeard calls one person, @channel all members of the channel, @here only those who are online right now, and @everyone we treat like @channel. A mention has to be found in the text, highlighted on screen and turned into a notification for the right people. Each of those steps can break so that the screen looks fine while the bell rings for someone else. That is why you start with tests.

Request for Claude Code:

Add mentions. First tests for parseMentions(text, members)
in lib/mentions.test.ts: @RedBeard finds the member regardless of
letter case, @Łukasz with a Polish letter too, @channel and @here
have a real position in the text, two mentions side by side, an
unknown name and an email address are skipped. Run the tests, show
the failure, then the implementation. Do not change the tests to
make them pass.

What the first run showed

Claude wrote the tests and then a first version of the function: the expression /@(\w+)/g for crew members and text.includes("@channel") for special mentions. Four of the five tests failed. The most important fragment of the output:

FAIL  lib/mentions.test.ts > parseMentions > records the real position of @channel
- Expected
+ Received

  [
    {
-     "end": 17,
+     "end": 0,
      "kind": "channel",
-     "start": 9,
+     "start": 0,
    },
  ]

The test passed the text "Wake up, @channel" and expected a position from 9 to 17, exactly where the word stands. includes says only that @channel is somewhere, so the function wrote the position 0-0. On screen that would give an empty highlight at the start of the message, while the real @channel text would stay plain: easy to miss by eye, and a test catches it at once. The same 0-0 position broke the test with @here next to @anne. On top of that \w does not know Polish letters, so @Łukasz was lost, and in the address captain@anne.com the function found a mention of Anne.

What Claude wrote: one expression for all

Open lib/mentions.ts. The second version looks for all mentions with one regular expression:

const MENTION = /(?<![\p{L}\p{N}_])@([\p{L}\p{N}_]+)/gu;
const SPECIAL = ["channel", "here", "everyone"] as const;

\p{L} is any letter, Polish ones included, and \p{N} a digit; both notations work only with the u flag. The beginning (?<!...) is the condition "before the @ there is no letter or digit", so an email address drops out. The loop in parseMentions goes over the matches from text.matchAll(MENTION), turns the name into lowercase with toLocaleLowerCase("en"), and takes the position from match.index and the length of the match. A name from the SPECIAL list gives a special mention, any other looks up a crew member by handle, and an unknown one is dropped. All five tests passed, and not a single line of their content changed.

Highlighting on screen

The splitByMentions function from the same file cuts the text by position into plain pieces and mentions. The components/MessageText.tsx component draws mentions in a <mark> tag: other people's in blue, yours in yellow. The message content does not change, only how it looks on screen. Had the positions been wrong, this is where you would see the empty highlight.

Suggestions after typing @

The old suggestion list had a query state that nobody set, so the filter never worked and always showed the same five members. Claude derived the query from the text before the cursor, with no extra state:

const QUERY = /(?<![\p{L}\p{N}_])@([\p{L}\p{N}_]*)$/u;

export function mentionQuery(text: string, caret: number): string | null {
  const match = QUERY.exec(text.slice(0, caret));
  return match ? match[1].toLocaleLowerCase("en") : null;
}

For the text "Ahoy @An" with the cursor at the end the function returns "an", and after a space null, meaning "do not show the list". In MessageInput the field is now controlled: the text and the cursor position (selectionStart) live in state, and the list is suggestMembers(query, members), at most five people who may see the channel. Everything is computed during render, so there is no effect that npm run lint would reject with the react-hooks/set-state-in-effect rule. Arrows change the highlighted person, Enter or Tab inserts @handle, and Escape closes the list. MentionAutocomplete itself only draws the list with role="listbox".

The notification center

A notification is created on the server, in the sendMessage action, right after the message is saved. The type is called AppNotification, because the browser already has its own Notification type for system notifications. Who gets the bell is decided by the pure function recipientsFor from lib/notify.ts, checked by four tests. Here is its ending:

ids.delete(authorId);
return members
  .filter((m) => ids.has(m.id) && canSeeChannel(channel, m))
  .map((m) => m.id);

Earlier the function collects identifiers into a Set, so someone called twice gets one notification. Then it removes the author, because nobody needs a bell for their own message, and keeps only the people who may see the channel: a mention @jack on a private channel will not send Jack a preview of a secret conversation. A reply in a thread also gives a reply notification to the author of the parent message.

After saving the message and the notifications the action calls revalidatePath("/", "layout"). According to the Next.js documentation such a call refreshes all pages under the root layout: the author sees their message at once, and the sidebar, present on every page, recounts its badges. The recipient will see their badge on the next visit to any page, because pages render on every request. A live bell, without reloading, is not in this lesson yet.

The /activity page shows your notifications, the number of unread ones and the button "Mark all as read". A read notification has a date in the readAt field, so unread ones are those without it. Clicking a notification calls an action that checks it is yours, marks it as read and opens the thread. In the sidebar next to the "Activity" link stands UnreadBadge: at zero it disappears, and above 99 it shows "99+", because its text comes from formatBadge with the line return count > 99 ? "99+" : String(count);.

Captain's review

  1. Two people. Change the logged-in member in lib/session.ts to anne, write "@redbeard, the barrels are ready" and switch back to redbeard. For us the badge showed 1, and the click opened the thread with the mention highlighted in yellow.
  2. Tests as a contract. Check in the diff that between the failure and the success lib/mentions.test.ts did not change. A typical agent mistake: "fixing" a test by writing the position 0-0 into it.
  3. A leak from the cabin. The test "does not leak from a private channel to someone outside it" is the most important case of this lesson. If it is missing, ask for it.
  4. Proof. Tests, lint, types, build and npx prettier --check ..

Your own bell: the Notification hook

When Claude works for a longer time you switch to the browser, and meanwhile it waits for your approval. The Notification event fires exactly when Claude Code is waiting for you. The matcher here filters the notification type: permission_prompt is a request for permission that you have not answered for about six seconds, and idle_prompt is the moment when Claude finished answering about a minute ago and you wrote nothing.

Request for Claude Code:

Add a Notification hook that shows a system notification when I am
being waited for, for my approval or for my reply. I use macOS.
Save it in my user settings, not in the project. Run the command
by hand before saving.

Claude saved the hook in ~/.claude/settings.json:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "permission_prompt|idle_prompt",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code is waiting for you\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

osascript is a macOS system command, and display notification shows a bubble in the corner of the screen. On Linux the documentation gives notify-send, and on Windows PowerShell. That is exactly why the hook went into the user settings: it works in all your projects and does not land in the repository, so someone from the crew on Linux does not get a command their system does not know. In /hooks you will see it with a different source than the Prettier hook.

The manual test ended with code 0. If the bubble did not show, that is a known trap from the documentation: osascript sends notifications through the Script Editor app, and without its consent it stays silent. Open System Settings, the Notifications section, find Script Editor and turn notifications on. Then a live test: switch the session with Shift+Tab to Manual, ask for something that needs approval and move to another window.

This hook blocks nothing, because for the Notification event the exit code is ignored. It is a pure signal, and a more reliable one than the sentence "let me know when you are done" in CLAUDE.md, which the model may not obey.

Next step

Ask for a commit, for example "Mentions and notifications". The Notification hook does not go into the commit, because it lives outside the project. Then a small step:

Add tests: @channel at the end of a sentence with a full stop and a
mention right after a new line. Show the result. If you break
something, we will undo it with /rewind.

The editor below holds a field with suggestions: type @ and a piece of a name, choose a person with the arrows, send the message and see who heard the bell.

Remember: the bell calls one particular sailor, the test makes sure it calls the right one, and the hook makes sure you hear it when Claude waits on deck.

Code for this lesson: App.jsx
// Mentions and the bell in miniature: parseMentions, suggestions after @ and notification recipients.
// In the project the functions live in lib/mentions.ts and lib/notify.ts (with tests),
// and the notifications are saved by the sendMessage action on the server.
import { useState } from 'react';

const members = [
  { id: 'u1', handle: 'redbeard', name: 'Captain Redbeard', role: 'owner', presence: 'online' },
  { id: 'u2', handle: 'anne', name: 'Anne Bonny', role: 'admin', presence: 'online' },
  { id: 'u3', handle: 'łukasz', name: 'Łukasz Sternik', role: 'member', presence: 'away' },
  { id: 'u4', handle: 'jack', name: 'Jack Rackham', role: 'member', presence: 'offline' },
];

const channels = [
  { id: 'c1', name: 'general', isPrivate: false, memberIds: ['u1', 'u2', 'u3', 'u4'] },
  { id: 'c5', name: 'captains-secrets', isPrivate: true, memberIds: ['u1', 'u2'] },
];

function canSeeChannel(channel, member) {
  if (channel.isPrivate || member.role === 'guest') return channel.memberIds.includes(member.id);
  return true;
}

const MENTION = /(?<![\p{L}\p{N}_])@([\p{L}\p{N}_]+)/gu;
const QUERY = /(?<![\p{L}\p{N}_])@([\p{L}\p{N}_]*)$/u;
const SPECIAL = ['channel', 'here', 'everyone'];

function parseMentions(text) {
  const mentions = [];
  for (const match of text.matchAll(MENTION)) {
    const name = match[1].toLocaleLowerCase('en');
    const start = match.index;
    const end = start + match[0].length;
    if (SPECIAL.includes(name)) {
      mentions.push({ kind: name, start, end });
      continue;
    }
    const member = members.find((m) => m.handle === name);
    if (member) mentions.push({ kind: 'member', memberId: member.id, start, end });
  }
  return mentions;
}

function splitByMentions(text, mentions) {
  const segments = [];
  let last = 0;
  for (const mention of mentions) {
    if (mention.start > last) segments.push({ text: text.slice(last, mention.start) });
    segments.push({ text: text.slice(mention.start, mention.end), mention });
    last = mention.end;
  }
  if (last < text.length) segments.push({ text: text.slice(last) });
  return segments;
}

function mentionQuery(text, caret) {
  const match = QUERY.exec(text.slice(0, caret));
  return match ? match[1].toLocaleLowerCase('en') : null;
}

function suggestMembers(query, list) {
  return list
    .filter((m) => m.handle.startsWith(query) || m.name.toLocaleLowerCase('en').startsWith(query))
    .slice(0, 5);
}

function recipientsFor(mentions, channel, authorId) {
  const ids = new Set();
  for (const mention of mentions) {
    if (mention.kind === 'member') ids.add(mention.memberId);
    else if (mention.kind === 'here') {
      members.filter((m) => m.presence === 'online' && channel.memberIds.includes(m.id)).forEach((m) => ids.add(m.id));
    } else channel.memberIds.forEach((id) => ids.add(id));
  }
  ids.delete(authorId);
  return members.filter((m) => ids.has(m.id) && canSeeChannel(channel, m)).map((m) => m.id);
}

function formatBadge(count) {
  return count > 99 ? '99+' : String(count);
}

function MessageText({ text, meId }) {
  return (
    <p className="whitespace-pre-wrap text-sm">
      {splitByMentions(text, parseMentions(text)).map((segment, index) => {
        if (!segment.mention) return <span key={index}>{segment.text}</span>;
        const isMe = segment.mention.kind === 'member' && segment.mention.memberId === meId;
        return (
          <mark key={index} className={'rounded-sm px-0.5 font-semibold ' + (isMe ? 'bg-yellow-200 text-yellow-900' : 'bg-blue-100 text-blue-800')}>
            {segment.text}
          </mark>
        );
      })}
    </p>
  );
}

export default function App() {
  const [meId, setMeId] = useState('u1');
  const [channelId, setChannelId] = useState('c1');
  const [text, setText] = useState('');
  const [caret, setCaret] = useState(0);
  const [active, setActive] = useState(0);
  const [open, setOpen] = useState(true);
  const [messages, setMessages] = useState([]);
  const [notifications, setNotifications] = useState([]);

  const me = members.find((m) => m.id === meId);
  const channel = channels.find((c) => c.id === channelId);
  const visibleMembers = members.filter((m) => canSeeChannel(channel, m));
  const query = open ? mentionQuery(text, caret) : null;
  const suggestions = query === null ? [] : suggestMembers(query, visibleMembers);
  const activeIndex = Math.min(active, suggestions.length - 1);
  const mine = notifications.filter((n) => n.recipientId === meId);
  const unread = mine.filter((n) => !n.read).length;

  function pick(member) {
    const before = text.slice(0, caret).replace(/@[\p{L}\p{N}_]*$/u, '@' + member.handle + ' ');
    setText(before + text.slice(caret));
    setCaret(before.length);
    setActive(0);
  }

  function send() {
    const clean = text.trim();
    if (!clean) return;
    const id = 'm' + Date.now();
    const recipients = recipientsFor(parseMentions(clean), channel, meId);
    setMessages([...messages, { id, channelId, authorId: meId, text: clean, recipients }]);
    setNotifications([
      ...notifications,
      ...recipients.map((recipientId) => ({ id: id + recipientId, recipientId, fromId: meId, channelName: channel.name, preview: clean, read: false })),
    ]);
    setText('');
    setCaret(0);
  }

  function handleKeyDown(e) {
    if (suggestions.length > 0) {
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        e.preventDefault();
        const step = e.key === 'ArrowDown' ? 1 : -1;
        setActive((activeIndex + step + suggestions.length) % suggestions.length);
        return;
      }
      if (e.key === 'Enter' || e.key === 'Tab') {
        e.preventDefault();
        pick(suggestions[activeIndex]);
        return;
      }
      if (e.key === 'Escape') {
        setOpen(false);
        return;
      }
    }
    if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
      e.preventDefault();
      send();
    }
  }

  function addTestNotifications() {
    const extra = Array.from({ length: 120 }, (_, i) => ({ id: 'test' + i + '-' + notifications.length, recipientId: meId, fromId: 'u2', channelName: 'general', preview: 'Test notification ' + (i + 1), read: false }));
    setNotifications([...notifications, ...extra]);
  }

  return (
    <div className="min-h-screen bg-gray-100 p-3 text-gray-900">
      <div className="mb-2 flex flex-wrap items-center gap-2 text-sm">
        <label htmlFor="me">Logged in as:</label>
        <select
          id="me"
          value={meId}
          onChange={(e) => {
            const next = members.find((m) => m.id === e.target.value);
            setMeId(next.id);
            if (!canSeeChannel(channel, next)) setChannelId('c1');
          }}
          className="rounded-md border border-gray-300 bg-white px-2 py-1"
        >
          {members.map((m) => (
            <option key={m.id} value={m.id}>{m.name}</option>
          ))}
        </select>
        <label htmlFor="channel">Channel:</label>
        <select id="channel" value={channelId} onChange={(e) => setChannelId(e.target.value)} className="rounded-md border border-gray-300 bg-white px-2 py-1">
          {channels.filter((c) => canSeeChannel(c, me)).map((c) => (
            <option key={c.id} value={c.id}>#{c.name}</option>
          ))}
        </select>
      </div>

      <div className="grid gap-3 md:grid-cols-3">
        <section className="flex flex-col rounded-lg border border-gray-200 bg-white md:col-span-2">
          <h1 className="border-b border-gray-200 px-3 py-2 font-bold">#{channel.name}</h1>
          <ol className="flex-1 space-y-2 p-3">
            {messages.filter((m) => m.channelId === channelId).map((m) => (
              <li key={m.id}>
                <p className="text-xs font-bold">{members.find((x) => x.id === m.authorId).name}</p>
                <MessageText text={m.text} meId={meId} />
                <p className="text-xs text-gray-500">
                  Heard the bell: {m.recipients.length ? m.recipients.map((id) => members.find((x) => x.id === id).name).join(', ') : 'nobody'}
                </p>
              </li>
            ))}
          </ol>
          <form onSubmit={(e) => { e.preventDefault(); send(); }} className="relative border-t border-gray-200 p-2">
            {suggestions.length > 0 && (
              <ul role="listbox" aria-label="Mention suggestions" className="absolute bottom-full left-2 mb-1 w-60 rounded-md border border-gray-200 bg-white py-1 shadow-lg">
                {suggestions.map((m, index) => (
                  <li
                    key={m.id}
                    role="option"
                    aria-selected={index === activeIndex}
                    onMouseDown={(e) => { e.preventDefault(); pick(m); }}
                    className="cursor-pointer px-3 py-1 text-sm aria-selected:bg-blue-50"
                  >
                    <span className="font-semibold">{m.name}</span> <span className="text-gray-500">@{m.handle}</span>
                  </li>
                ))}
              </ul>
            )}
            <label htmlFor="text" className="sr-only">Message</label>
            <textarea
              id="text"
              rows={2}
              value={text}
              placeholder="Type @ and the start of a name"
              onChange={(e) => {
                setText(e.target.value);
                setCaret(e.target.selectionStart);
                setActive(0);
                setOpen(true);
              }}
              onSelect={(e) => setCaret(e.currentTarget.selectionStart)}
              onKeyDown={handleKeyDown}
              className="w-full resize-none rounded-md border border-gray-300 p-2 text-sm"
            />
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span>Arrows choose, Enter or Tab inserts, Escape closes</span>
              <button className="rounded-md bg-green-700 px-3 py-1 text-sm font-semibold text-white">Send</button>
            </div>
          </form>
        </section>

        <aside className="rounded-lg border border-gray-200 bg-white">
          <div className="flex items-center justify-between border-b border-gray-200 px-3 py-2">
            <h2 className="flex items-center gap-2 font-bold">
              Activity
              {unread > 0 && (
                <span className="rounded-full bg-red-600 px-2 text-xs text-white">
                  {formatBadge(unread)}
                  <span className="sr-only"> unread</span>
                </span>
              )}
            </h2>
            {unread > 0 && (
              <button
                onClick={() => setNotifications(notifications.map((n) => (n.recipientId === meId ? { ...n, read: true } : n)))}
                className="text-xs font-semibold text-blue-700 hover:underline"
              >
                Mark all as read
              </button>
            )}
          </div>
          {mine.length === 0 ? (
            <p className="p-3 text-sm text-gray-500">Quiet on deck: nobody has called you yet.</p>
          ) : (
            <ol className="max-h-72 overflow-y-auto">
              {[...mine].reverse().map((n) => (
                <li key={n.id} className={'border-b border-gray-200 px-3 py-2 text-sm ' + (n.read ? '' : 'bg-blue-50')}>
                  <span className="font-semibold">{members.find((x) => x.id === n.fromId).name}</span> mentioned you in #{n.channelName}
                  <span className="block truncate text-xs text-gray-600">{n.preview}</span>
                </li>
              ))}
            </ol>
          )}
          <button onClick={addTestNotifications} className="m-3 rounded-md border border-gray-300 px-2 py-1 text-xs">Add 120 test notifications</button>
        </aside>
      </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. 1. Which kinds of mentions does parseMentions recognise in Ship's Comms?

  2. 2. How does @channel differ from @here?

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

Hands-on tasks in the game

  • Click in order

    Arrange the line from mentionQuery that looks for @ right before the cursor: const match = QUERY.exec(text.slice(0, caret));

  • Code editor

    Mention autocomplete popup

  • Horizontal ordering

    Arrange on one line the filter from recipientsFor: .filter((m) => ids.has(m.id) && canSeeChannel(channel, m))

  • Vertical ordering

    Anne sends "@redbeard, the barrels are ready". Order what happens:

  • Code editor

    Notifications panel

  • Click in order

    Arrange the line from recipientsFor that removes the author from the recipients: ids.delete(authorId);

  • Vertical ordering

    Arrange the lines of the Notification hook in the settings file from the outside in:

  • Click in order

    Arrange the last line of mentionQuery: return match ? match[1].toLocaleLowerCase("en") : null;

  • Horizontal ordering

    Arrange on one line the command of the Notification hook on macOS:

  • Horizontal ordering

    Arrange on one line the beginning of the function: export function mentionQuery(text: string, caret: number): string | null {

  • Click in order

    Arrange the line that shows 99+ for a number above 99: return count > 99 ? "99+" : String(count);

  • Vertical ordering

    Order the flow in Ship's Comms from choosing a channel to opening a notification:

  1. QuestionQuiz: Kinds of mentions
  2. QuestionQuiz: @channel versus @here
  3. Click in orderSorting: The query before the cursor
  4. Coding taskPractice: Mention autocomplete
  5. Put in orderSorting: Recipient filter
  6. QuestionQuiz: Kinds of AppNotification
  7. QuestionQuiz: The AppNotification name
  8. Put in orderSorting: From a mention to a badge
  9. Coding taskPractice: Notification center
  10. QuestionQuiz: Number of unread
  11. Click in orderSorting: The author without a bell
  12. QuestionQuiz: Clicking a notification
  13. Put in orderSorting: The Notification hook in settings
  14. Click in orderSorting: The result of mentionQuery
  15. QuestionQuiz: Highlighting a mention
  16. Put in orderSorting: The macOS notification command
  17. Put in orderSorting: The mentionQuery signature
  18. QuestionQuiz: When the badge disappears
  19. Click in orderSorting: The 99+ badge
  20. QuestionQuiz: The result of parseMentions
  21. QuestionQuiz: Where the Notification hook lives
  22. Put in orderSorting: From a channel to a notification
  23. QuestionQuiz: Exit code of the Notification hook
  24. QuestionQuiz: Ship's Comms versus Kraken's Call

Useful articles