Skip to content

Claude Code in Your Own Web App · Part 13 of 16 in the series

Part 13: Tell Me When It Needs Me

A switch in the sidebar turns on browser notifications and a short chime: for a question in a site you are not looking at, and for the end of a run while the tab is in the background. Clicking a notification opens the site.

Quest objectives

  • Ask for permission to show notifications, on a click, and remember the choice
  • Know why notifications need a secure page, and why localhost is one
  • Play a short chime with the Web Audio API once the browser allows sound
  • Decide when a change is worth telling: you are away, it is new, and only once
  • Keep one notification per site, and open the site with a click on it

Since part 12 the sidebar shows which site waits for you, and the tab's title counts them. That helps as long as you look at the page. But a build takes a minute or more, and nobody watches a progress feed for that long. You switch to your editor or your mail, and the question Claude Code asked in the meantime waits, patiently, for hours if need be: the hook from part 8 holds it for up to a day.

This part makes the page speak up. A switch at the bottom of the sidebar turns on two things the browser offers any page: a notification on your desktop, and a short chime. The server does not change at all. The page already hears every change of every site over the server-sent events; it only has to decide which ones are worth interrupting you for.

Claude Code asks while you are elsewhere, and the page rings a small bell.
Claude Code asks while you are elsewhere, and the page rings a small bell.

There is no screenshot in this part: a notification is drawn by your operating system, outside the page, and looks different on every desktop. What it says is the site, what Claude Code waits for, and a line of detail, for example Bergblick Ski School: Claude Code has a question for you above the question itself.

What a notification says

Everything goes into one new file. Create src/notify.ts and start it with the text of the notifications:

src/notify.ts
import { h } from './dom.ts';
import type { AgentState } from '../shared/types.ts';

const KEY = 'sitesmith:notify';

/** What the notification says when Claude Code starts waiting for you. */
function askText(state: AgentState) {
  const ask = state.ask;
  if (state.needsTerminal && !ask) return { title: 'waits for you in the terminal', body: 'It asks something the page can’t show.' };
  switch (ask?.kind) {
    case 'questions': return { title: ask.questions.length > 1 ? 'has questions for you' : 'has a question for you', body: ask.questions[0]?.question ?? '' };
    case 'permission': return { title: 'asks for permission', body: ask.summary };
    case 'plan': return { title: 'has a plan for you to approve', body: '' };
    case 'trust': return { title: 'asks whether you trust the folder', body: ask.dir };
  }
  return null;
}

askText turns the site's state into a title and a body, one case for each kind of Ask from parts 8 to 11. A question shows its own text, a permission prompt the one-line summary from describeTool, and the trust dialog the folder. A plan gets no body: it is a page of Markdown, and a notification has room for a line or two. The first line covers the case from part 10 where Claude Code waits for something only the terminal can show.

The switch

Below it, the class begins with the button and the things it needs before anything can be shown or played:

src/notify.ts
/**
 * Tells you when Claude Code needs you while you look elsewhere: a browser notification (with
 * your permission) and a short sound. Questions in another site count as elsewhere too; the end
 * of a run only when the tab is in the background. Clicking the notification opens the site.
 */
export class Notifier {
  readonly el: HTMLButtonElement;
  private on = false;
  private audio: AudioContext | null = null;
  private seen = new Set<string>();

  constructor() {
    this.el = h('button', { type: 'button', class: 'small ghost', onclick: () => void this.toggle() });
    try { this.on = localStorage.getItem(KEY) === 'on'; } catch { /* storage blocked: off */ }
    this.render();
  }

  /** Notifications need a secure page (https, or localhost) and the browser's permission. */
  private get available() { return 'Notification' in window && window.isSecureContext; }

  private render() {
    if (!this.available) {
      this.el.textContent = 'Sound on';
      this.el.title = 'Browser notifications need https or localhost: only the sound is left here';
    } else if (Notification.permission === 'denied') {
      this.el.textContent = 'Notifications blocked';
      this.el.title = 'Allow notifications for this page in the browser’s site settings';
    } else this.el.textContent = this.on ? 'Notifications on' : 'Notify me';
    this.el.setAttribute('aria-pressed', String(this.on));
  }

  /** A click: the browser asks for permission, and the sound may play from now on. */
  private async toggle() {
    this.on = !this.on;
    if (this.on) {
      this.unlockSound();
      if (this.available && Notification.permission === 'default') this.on = (await Notification.requestPermission()) === 'granted';
    }
    try { localStorage.setItem(KEY, this.on ? 'on' : 'off'); } catch { /* not remembered */ }
    this.render();
  }

  /** Browsers start audio only after a click on the page. */
  unlockSound() {
    this.audio ??= new AudioContext();
    void this.audio.resume();
  }

Available. Browsers offer notifications only to a secure context: a page loaded over HTTPS, or from your own machine. http://localhost and http://127.0.0.1 count as secure, because nothing between the browser and the server could read or change them. So on localhost:5400 everything here works. Opened from another machine over plain HTTP, which is what part 16 does, it does not, and the button then says Sound on: the chime is all that is left there.

The permission. A page may show notifications only after you allowed it, and the browser asks you on behalf of the page when it calls Notification.requestPermission(). That call sits in toggle, which runs on a click, on purpose: browsers expect a permission request to follow something you did, and some ignore it otherwise. The answer is kept by the browser. If it was no, the browser will not ask again, and the button says Notifications blocked until you change it in the site settings.

Remembered. Whether the switch is on goes into localStorage, so a reload keeps it. Both accesses sit in a try: a browser can block storage, and then the switch is simply off after a reload.

Sound. Browsers do not let a page make noise before you have clicked on it, so nobody gets blasted by an ad they never touched. An AudioContext created before that starts suspended, and resume() works only from a click onwards. unlockSound creates the context once and resumes it. The switch calls it, and so will a listener for the first click anywhere on the page.

A chime without a sound file

The sound is made on the spot, with the Web Audio API. Add the method to the class:

src/notify.ts
/** Two rising notes for "it waits for you", one soft note for "it is done". */
private chime(kind: 'ask' | 'done') {
  const ctx = this.audio;
  if (!ctx || ctx.state !== 'running') return;
  const notes = kind === 'ask' ? [660, 880] : [520];
  notes.forEach((freq, i) => {
    const t = ctx.currentTime + i * 0.16;
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type = 'sine';
    osc.frequency.value = freq;
    gain.gain.setValueAtTime(0, t);
    gain.gain.linearRampToValueAtTime(0.18, t + 0.02);
    gain.gain.exponentialRampToValueAtTime(0.001, t + 0.45);
    osc.connect(gain).connect(ctx.destination);
    osc.start(t);
    osc.stop(t + 0.5);
  });
}

An oscillator produces a tone of one frequency; a gain node sets its volume. For each note, the volume rises from zero to 0.18 within 20 milliseconds, so the tone starts without a click, and then fades away over the next 430. The fade is exponential, which sounds like a struck bell, and an exponential curve can never reach zero, hence the 0.001. Each oscillator is stopped after half a second and then thrown away by the browser; a new note needs a new one.

"It waits for you" is two rising notes, 660 and 880 Hz, 160 milliseconds apart. "It is done" is a single lower note. You learn the difference after a day and stop looking up for the second one. If the context is not running yet, because nobody has clicked since the page was loaded, chime stays silent rather than queueing a sound for later.

When to tell you

The rest of the class decides. Add the two remaining methods:

src/notify.ts
  private show(site: string, siteTitle: string, title: string, body: string, kind: 'ask' | 'done') {
    this.chime(kind);
    if (!this.available || Notification.permission !== 'granted') return;
    // one notification per site: a newer one replaces the older
    const n = new Notification(`${siteTitle}: Claude Code ${title}`, { body, tag: `sitesmith-${site}` });
    n.onclick = () => {
      window.focus();
      location.hash = `site/${site}`;
      n.close();
    };
  }

  /** A site's state changed: is this something to tell you about? */
  agentChanged(prev: AgentState | undefined, next: AgentState, siteTitle: string, isOpen: boolean) {
    if (!this.on) return;
    const away = document.hidden || !isOpen;
    const waits = next.ask?.id ?? (next.needsTerminal ? `terminal-${next.run?.id}` : null);
    if (waits && !this.seen.has(waits) && away) {
      this.seen.add(waits);
      const text = askText(next);
      if (text) this.show(next.site, siteTitle, text.title, text.body, 'ask');
    }
    const run = next.run;
    const ended = run && ['done', 'failed', 'stopped'].includes(run.status) && prev?.run?.id === run.id && prev.run.status !== run.status;
    if (ended && run.status !== 'stopped' && document.hidden && !this.seen.has(`end-${run.id}-${run.ended}`)) {
      this.seen.add(`end-${run.id}-${run.ended}`);
      this.show(next.site, siteTitle, run.status === 'done' ? 'is done' : 'could not finish', (run.summary ?? run.error ?? '').slice(0, 160), 'done');
    }
  }
}

agentChanged is called for every state the server sends, and there are many: every tool Claude Code uses sends one. Most of them are not news. Three rules sort them out.

Only when you are away. away is true when the tab is hidden, behind another tab or in a minimized window, or when the site is not the one open in the page. The second case matters since part 12: the dialog comes up only for the open site, so a question in another one would otherwise just be a badge in the sidebar.

Only once. Each Ask has an id, and seen keeps the ones already told. A site that needs the terminal gets an id made of its run, so that, too, is told once. Without this you would hear the chime with every file Claude Code reads while the question waits.

The end only in the background. A run has ended when the previous state had the same run with another status, and the new status is done, failed or stopped. Stopped is left out: that is mostly you, with the Stop button or Escape in the terminal. And the end is told only while the tab is hidden. With the page in front of you, the feed and the summary already show it, and a notification for every finished change would be noise. Its body is the start of Claude Code's summary from part 7.

show plays the chime first, so the sound works even where notifications do not. Then it creates the notification with a tag. Notifications with the same tag replace each other, so each site has at most one on your screen: a later "is done" for the same site takes the place of the question from before. A click on it brings the window to the front and switches the page to the site, through the same #site/… address the sidebar's links use.

Wiring it in

The switch goes at the bottom of the sidebar. In src/sidebar.ts, the constructor takes whatever should go there:

src/sidebar.ts
export class Sidebar {
  readonly el: HTMLElement;
  private list = h('nav', { class: 'site-list', 'aria-label': 'Sites' });

  /** `foot`: what goes at the bottom (the notifications switch) */
  constructor(...foot: HTMLElement[]) {
    this.el = h('aside', { class: 'sidebar' },
      h('a', { class: 'brand', href: '#' }, h('span', { class: 'brand-mark', 'aria-hidden': 'true' }), 'Sitesmith'),
      h('a', { class: 'button primary', href: '#new' }, 'New site'),
      this.list,
      h('div', { class: 'sidebar-foot' }, ...foot));
  }

The class sidebar-foot is in style.css already: on a wide screen it pushes the switch down to the bottom, on a narrow one it puts it at the end of the top bar.

In src/main.ts, import the Notifier and create it at the start of start():

src/main.ts
import './style.css';
import { api, events } from './api.ts';
import { AskDialog } from './askDialog.ts';
import { h } from './dom.ts';
import { newSiteForm } from './newSite.ts';
import { Notifier } from './notify.ts';
import { Sidebar } from './sidebar.ts';
import { SitePage } from './sitePage.ts';
import type { AgentState, Config, ServerEvent, Site, TerminalState } from '../shared/types.ts';

/**
 * The page: the sites on the left, the open one on the right. Addresses: #new, #site/<name>.
 * Everything that changes comes from the server's events, whoever changed it.
 */
async function start() {
  const config = await api<Config>('GET', '/api/config');
  const notifier = new Notifier();
  // any click may start the sound (browsers allow audio only after one)
  document.addEventListener('pointerdown', () => notifier.unlockSound(), { once: true });
  const sidebar = new Sidebar(notifier.el);
  const main = h('main', { class: 'main' });
  const offline = h('p', { class: 'offline', hidden: true }, 'The server is not answering. Waiting for it…');
  document.querySelector('#app')!.append(sidebar.el, main, offline);

The listener with once: true unlocks the sound with your first click anywhere on the page, so the chime works after a reload even if you never touch the switch again. And onEvent hands every new state to the Notifier, before it replaces the old one in the map:

src/main.ts
function onEvent(ev: ServerEvent) {
  if (ev.type === 'sites') {
    sites = ev.sites;
    page?.update(sites);
    overview();
  } else if (ev.type === 'terminals') {
    terminals = ev.terminals;
    page?.terminals(terminals);
    overview();
  } else if (ev.type === 'agent') {
    const title = sites.find((s) => s.name === ev.state.site)?.title ?? ev.state.site;
    notifier.agentChanged(agents.get(ev.state.site), ev.state, title, page?.name === ev.state.site);
    agents.set(ev.state.site, ev.state);
    if (ev.state.site === page?.name) page.agentChanged(ev.state);
    overview();
    syncAsk();
  } else if (ev.type === 'files' && ev.site === page?.name) page.filesChanged();
}

The order is the point: agents.get(…) still returns the previous state, which is how the Notifier sees that a run has just ended.

Try it

Rebuild the page, or let the dev server reload it, and click Notify me. The browser asks whether the page may show notifications; allow it, and the button says Notifications on. Then send a site a request that leaves something open, such as a new section without saying what goes into it, and switch to another site or another tab while Claude Code works.

For this series, the page ran in a headless Chromium, which has no desktop to show anything on. So the test spied on Notification, recording what the page asked it to show, and counted the oscillators the chime started:

Terminal
# Headless Chromium, notifications granted, Notification and the oscillators spied onswitch: Notifications onafter the question: [{"title":"Bergblick Ski School: Claude Code has a question for you","body":"Should the footer link to the Schladming tourism office?"}] chime oscillators: 2after the end: [… ,{"title":"Bergblick Ski School: Claude Code is done","body":"I added a \"Schladming tourism office\" link to the footer on all three pages …"}] chime oscillators: 3

The question in Bergblick Ski School came with its notification and two notes. When the run ended with the tab in the background, the second notification followed, with the start of the summary as its body, and one more note: three oscillators in all.

What you have now

Sitesmith calls you when it needs you: a notification you can click and a sound you learn to tell apart, for questions in any site you are not looking at, and for the end of the work while you do something else. One new file and a few lines to wire it in, all of it in the page.

So far Claude Code has had only your words to go by. In the next part you hand it files: the bakery's logo, photos, a menu as a PDF, dropped onto the page and named in the request, so Claude Code looks at them before it starts.

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.