Claude Code in Your Own Web App · Part 3 of 16 in the series
Part 3: A tmux Session for Every Site
Give every site a Claude Code session of its own: a tmux server configured to be driven, sessions started in the site's folder through your login shell, and a header that shows whether Claude Code runs, works or has exited.
Claude Code in Your Own Web AppPart 3 of 16
On this page
Quest objectives
- Configure a tmux server that stays out of Claude Code's way
- Keep API keys and the variables of other Claude Code sessions out of the sessions
- Start Claude Code in a login shell, with its arguments passed on untouched
- Tell from tmux alone whether Claude Code runs and whether it works
- Start, continue and end sessions from the page
- Look into a session from your own terminal, and leave it running
In part 1 you ran Claude Code in a tmux session by hand. Now the server does it: every site gets a session named after it, with Claude Code working in the site's folder. The site's header shows the session's state and has the buttons to start and end it.
The sessions belong to tmux, not to the server. Stop the server, and Claude Code carries on; start it again, and it finds the sessions where they are. That makes restarting the server harmless, and you will restart it a lot in this series.
A tmux server made to be driven
Sitesmith runs its own tmux server, -L sitesmith, with a configuration of its own. Create server/tmux.conf:
# The tmux server behind Sitesmith's sessions (tmux -L sitesmith): one session per site, each running
# Claude Code. tmux stays out of the way: no prefix key and no status bar, so every key reaches Claude
# Code and the page shows a plain terminal.
set -g prefix None
set -g status off
set -g escape-time 10
set -g history-limit 50000
set -g default-terminal tmux-256color
set -ga terminal-overrides ',xterm-256color:RGB'
set -g focus-events on
set -g window-size latest
# Sessions run on your Claude Code login, as in any terminal of yours. What the process that started
# this tmux server had in its environment would reach every session: an API key would bill per token
# instead of using your plan, and the variables of a Claude Code session around Sitesmith would make
# Claude Code think it runs inside another one.
set-environment -gu ANTHROPIC_API_KEY
set-environment -gu ANTHROPIC_AUTH_TOKEN
set-environment -gu ANTHROPIC_BASE_URL
set-environment -gu CLAUDECODE
set-environment -gu CLAUDE_CODE_ENTRYPOINT
set-environment -gu CLAUDE_CODE_SSE_PORTThe first block keeps tmux out of the way:
prefix None: tmux normally keeps Ctrl+b for itself, as you saw in part 1. In Sitesmith's sessions every key belongs to Claude Code. The price is that Ctrl+b and d no longer detach; below you will see how to leave instead.status off: no status bar at the bottom. A session shows Claude Code and nothing else, in your terminal and, from part 4 on, in the page.escape-time 10: after an Escape, tmux waits to see whether more keys follow, because Escape also starts many key sequences. Older versions of tmux wait 500 milliseconds by default, long enough to notice; tmux 3.6, used here, already waits 10, and the line makes every version do the same. Escape is how you interrupt Claude Code, and the Stop button of part 5 sends it; 10 milliseconds are enough to tell the two apart.history-limit 50000: lines of scrollback per session, instead of 2,000. A long build scrolls a lot.default-terminal tmux-256color: the terminal type that programs in the session see inTERM: tmux, with 256 colors.terminal-overrides ',xterm-256color:RGB': tells tmux that a terminal of typexterm-256coloron the outside, which most terminal apps and the page's terminal from part 4 are, can show 24-bit color. Claude Code's colors then pass through unchanged.focus-events on: the hint from part 1. tmux passes on when a terminal gains or loses the focus.window-size latest: when several terminals of different sizes show the same session, your own and later the page's, the session takes the size of the one used last.
The second block is about the environment. A tmux server copies the environment of the process that starts it, here Sitesmith's server, and passes it on to every session. set-environment -gu removes a variable from that global environment again (-g global, -u unset):
ANTHROPIC_API_KEYandANTHROPIC_AUTH_TOKEN: with a key or a token, Claude Code can sign in with it instead of your login and bill every token. The sessions are meant to run on your plan.ANTHROPIC_BASE_URLwould send Claude Code's requests to another server. Part 15 sets it on purpose, for one site at a time, to use a local model.CLAUDECODE,CLAUDE_CODE_ENTRYPOINTandCLAUDE_CODE_SSE_PORTare set inside a Claude Code session. Start Sitesmith from one, by asking Claude Code to runnpm startfor example, and every session would believe it runs inside that one. In part 1, a session even took over the editor connection that way.
tmux reads the file only when its server starts. After a change, tmux -L sitesmith source-file server/tmux.conf applies the options to the running server; changes to the environment reach only sessions started after that.
The sessions
Create server/terminals.ts. It starts with a few constants:
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { ServerEvent, TerminalState } from '../shared/types.ts';
/** Sitesmith's own tmux server; SITESMITH_TMUX=<name> uses another one (tests next to a running Sitesmith). */
const SOCKET = process.env.SITESMITH_TMUX ?? 'sitesmith';
/** The program to run; SITESMITH_CLAUDE=<program> runs a stand-in or a wrapper instead. */
const CLAUDE = process.env.SITESMITH_CLAUDE ?? 'claude';
/** Claude Code runs inside your login shell (bash or zsh), so it finds what your terminal finds. */
const SHELL = /\/(bash|zsh)$/.test(process.env.SHELL ?? '') ? process.env.SHELL! : 'bash';
const SHELLS = ['bash', 'zsh', 'sh', 'fish'];
/** The screen changed in at least BUSY_TICKS of the last WINDOW seconds: Claude Code's spinner turns. */
const BUSY_TICKS = 3;
const WINDOW = 5;
export interface Target { name: string; dir: string }
/** tmux's target for a session's pane: `=` asks for this exact name, not one that starts with it. */
const pane = (name: string) => `=${name}:`;SOCKETnames the tmux server.SITESMITH_TMUXpicks another one, so a second copy of Sitesmith, for tests, never touches your sessions.CLAUDEis the program a session runs:claude, or whatSITESMITH_CLAUDEsays. That can be a wrapper that starts Claude Code with a cheaper model, or a stand-in, a small script, while you work on the page and don't need anything built.SHELLis your login shell if it is bash or zsh, and bash otherwise.SHELLSlists the names that mean "a shell is in front"; more on that inpoll.BUSY_TICKSandWINDOWalso belong topoll.panebuilds tmux's target for a session's pane. tmux takes a session name as a prefix if no session has exactly that name:-t maraswould findmaras-bakery. The=asks for this exact name, and the colon after it means the session's current window and pane.
Then the class, with the way it talks to tmux:
/**
* Claude Code in a tmux session per site. The sessions belong to tmux, not to this process: they
* keep running when the server stops, and the server finds them again when it starts. Everything
* it knows about them, it asks tmux.
*/
export class Terminals {
private conf: string;
private emit: (ev: ServerEvent) => void;
private states = new Map<string, TerminalState>();
private ticks = new Map<string, number[]>();
private sent = '';
available = false;
constructor(app: string, emit: (ev: ServerEvent) => void) {
this.conf = path.join(app, 'server', 'tmux.conf');
this.emit = emit;
}
/** Checks that tmux is there, then follows the sessions once a second. */
async init() {
this.available = await this.tmux('-V').then(() => true, () => false);
if (!this.available) return;
await this.poll();
setInterval(() => void this.poll(), 1000).unref();
}
/** Runs a tmux command against our own server (-L) with our config (-f, read when that server starts). */
private tmux(...args: string[]) {
return new Promise<string>((resolve, reject) => {
execFile('tmux', ['-u', '-L', SOCKET, '-f', this.conf, ...args], { timeout: 5000 }, (err, out) => {
if (err) reject(err); else resolve(out);
});
});
}
list() { return [...this.states.values()]; }
get(name: string) { return this.states.get(name); }Terminals keeps nothing of its own except the latest picture tmux gave it. init asks for tmux's version: if tmux is not installed, available stays false and the page says so. Otherwise it looks at the sessions once a second. unref keeps that timer from holding the process alive when everything else has stopped.
Every tmux command goes through tmux:
-umakes tmux use UTF-8 whatever the locale of the server process says. Claude Code draws its screen with❯,─and friends.-Lpicks Sitesmith's tmux server, and-fits configuration. tmux reads the file only on the call that starts the tmux server; on every other call it changes nothing.execFile, notexec: the arguments go to tmux as they are, with no shell in between to interpret them.A timeout of five seconds, so a tmux that hangs can't hang the server.
The heart of the class follows the sessions:
/**
* The sessions, what runs in them and whether their screen moves. `pane_current_command` is the
* program in front: a shell means Claude Code has exited. `window_activity` is the last second
* anything was drawn; Claude Code's spinner draws all the time while it works.
*/
async poll() {
// without sessions there is no tmux server, and tmux exits with an error
const out = await this.tmux('list-panes', '-a', '-F', '#{session_name}\t#{pane_current_command}\t#{window_activity}').catch(() => '');
const now = Math.floor(Date.now() / 1000);
const states = new Map<string, TerminalState>();
for (const line of out.split('\n')) {
const [site, command, activity] = line.split('\t');
if (!site) continue;
const ticks = (this.ticks.get(site) ?? []).filter((t) => t > now - WINDOW);
const last = Number(activity);
if (last > now - WINDOW && !ticks.includes(last)) ticks.push(last);
this.ticks.set(site, ticks);
const claude = !SHELLS.includes(command);
states.set(site, { site, claude, busy: claude && ticks.length >= BUSY_TICKS });
}
for (const site of this.ticks.keys()) if (!states.has(site)) this.ticks.delete(site);
this.states = states;
const sent = JSON.stringify(this.list());
if (sent !== this.sent) {
this.sent = sent;
this.emit({ type: 'terminals', terminals: this.list() });
}
}One list-panes for all sessions, with three values separated by tabs: the session's name and the two values you met in part 1.
Does Claude Code run? pane_current_command names the program in front. When Claude Code exits, the shell of the command below takes over, and the name says bash or zsh. The check asks "is a shell in front?" and not "is claude in front?", because the program may be a wrapper with a name of its own.
Does it work? window_activity is the last second in which anything was drawn. A single change says little: you typed something, or a line was redrawn. But while Claude Code works, its spinner redraws all the time. So poll collects the different seconds with activity within the last five (WINDOW), and calls a session busy when there are at least three (BUSY_TICKS). It is a rough measure, but it needs nothing but tmux and does not depend on what the screen shows. From part 6 on, hooks take over most of this job.
Without any session there is no tmux server at all, and list-panes fails; the catch turns that into an empty list. At the end, poll sends the list to the page only if it differs from the last one it sent. Otherwise every page would get the same news once a second.
Next, a question the page will ask: is there a conversation to continue?
/** Claude Code keeps each folder's conversations in ~/.claude/projects/<the path, with - for other characters>. */
hasConversation(dir: string) {
try {
const folder = path.join(os.homedir(), '.claude', 'projects', dir.replace(/[^a-zA-Z0-9]/g, '-'));
return fs.readdirSync(folder).some((f) => f.endsWith('.jsonl'));
} catch { return false; }
}Claude Code keeps its conversations in ~/.claude/projects, in one folder per project folder. The folder is named after the full path, with every character that is not a letter or a digit replaced by a dash: /home/you/sitesmith/sites/maras-bakery becomes -home-you-sitesmith-sites-maras-bakery. Every conversation is a .jsonl file in it, and if there is one, "Continue last conversation" makes sense.
Now the command a session runs:
/**
* What the session runs: Claude Code in a login shell, and when it exits, an interactive shell in
* the folder, so the session stays open. The shell gets the program and its arguments as "$0"
* and "$@", so no argument is ever parsed by the shell.
*/
private command(opts: { prompt?: string; resume?: boolean }) {
return [SHELL, '-lic', '"$0" "$@"; exec "$SHELL" -i', CLAUDE,
// file edits in the site's folder go ahead; commands still ask
'--permission-mode', 'acceptEdits',
...(opts.resume ? ['--continue'] : []),
...(opts.prompt ? [opts.prompt] : [])];
}Put together, a session runs something like bash -lic '"$0" "$@"; exec "$SHELL" -i' claude --permission-mode acceptEdits. Piece by piece:
-land-imake the shell a login shell and an interactive one, so it reads your profile and your.bashrcor.zshrcfirst. That is where yourPATHgets~/.local/bin, nvm or Homebrew. What your terminal finds, Claude Code finds: the sameclaude, the samenode, the same tools for the commands it runs."$0" "$@"is the whole script. With-c, the words after the script become its arguments:$0is the program,$@the rest. The shell runs them as they are, quoted, never split and never expanded. A first message with quotes, a$or a;in it, which from part 5 on is text you type into the page, can't turn into a command.exec "$SHELL" -i: when Claude Code exits, an interactive shell takes its place, in the site's folder. The session stays open, and the page can bring Claude Code back.--permission-mode acceptEdits: Claude Code edits files in its folder without asking each time. Read-only commands such aslsgo ahead too; commands that reach the network, likecurl, or use certain shell operators still ask. Part 9 brings those questions into the page; until then you answer them in the terminal.--continueloads the folder's last conversation, and apromptbecomes Claude Code's first message, from part 5 on.
Last, starting, restarting and ending:
/** Starts Claude Code in a site's session: fresh, or continuing the folder's last conversation. */
async start(t: Target, opts: { prompt?: string; resume?: boolean } = {}) {
if (this.states.has(t.name)) return;
await this.tmux('new-session', '-d', '-s', t.name, '-x', '120', '-y', '36', '-c', t.dir, ...this.command(opts))
.catch((err: Error) => { if (!/duplicate session/.test(err.message)) throw err; });
await this.poll();
}
/** Claude Code again, in place of the shell it left behind. */
async respawn(t: Target, opts: { prompt?: string; resume?: boolean } = {}) {
await this.tmux('respawn-pane', '-k', '-t', pane(t.name), '-c', t.dir, ...this.command(opts));
await this.poll();
}
/** Ends the session and whatever runs in it. */
async end(t: Target) {
await this.tmux('kill-session', '-t', `=${t.name}`).catch(() => undefined);
await this.poll();
}
}start is part 1's new-session: detached, named after the site, 120 by 36, started in the site's folder (-c), with the command. Given as several arguments, the command is run by tmux directly, without a shell of its own, so the login shell above is the only shell involved, and it gets the arguments as $0 and $@. If two clicks race each other, the second new-session fails with "duplicate session", which is fine.
respawn replaces what runs in the session with a fresh command (-k ends the old one first): Claude Code again, in place of the shell it left behind. end kills the session, with the = for the exact name again. After each of them a poll runs, so the page hears about the change at once and not up to a second later.
Routes
The page needs to know whether there can be sessions at all, and what state they are in. In shared/types.ts, replace everything from Config down:
export interface Config {
/** the preview server's port: the sites are shown from there, never from the page's own address */
previewPort: number;
/** whether tmux was found: without it there are no sessions */
terminals: boolean;
}
/** A site's tmux session, as tmux reports it. */
export interface TerminalState {
site: string;
/** Claude Code runs in it (false: it exited, and a shell waits in the folder) */
claude: boolean;
/** its screen keeps changing: Claude Code is working */
busy: boolean;
}
/** What the server tells every open page, over server-sent events. */
export type ServerEvent =
| { type: 'sites'; sites: Site[] }
| { type: 'files'; site: string }
| { type: 'terminals'; terminals: TerminalState[] };Config.terminals says whether tmux was found. A TerminalState describes one session: does Claude Code run in it, and does it work. A new event carries the list of them.
In server/main.ts, import the class:
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Config, NewSite, ServerEvent } from '../shared/types.ts';
import { HttpError, fileIn, readJson, send, sendFile } from './http.ts';
import { NAME, OWN, Sites } from './sites.ts';
import { Terminals } from './terminals.ts';The config starts without terminals:
const sites = new Sites(path.resolve(option('--sites', path.join(APP, 'sites'))));
const config: Config = { previewPort: PREVIEW_PORT, terminals: false };Below the folder watch, create the terminals and wait for the first look at tmux:
const terminals = new Terminals(APP, broadcast);
await terminals.init();
config.terminals = terminals.available;
/** A site's name and folder: what the terminals need, after checking the site exists. */
function target(name: string) {
const site = sites.get(name);
return { name: site.name, dir: sites.dir(site.name) };
}An await at the top level of a module is fine in an ES module. The server starts listening only after the first poll, so the first page that connects gets the real state. target hands out a site's name and folder, but only for a site that exists: sites.get throws a 404 otherwise. Nothing but a checked site name ever reaches tmux.
Then replace the list of routes:
const routes: Route[] = [
['GET', /^\/api\/config$/, (_req, res) => send(res, 200, config)],
['GET', /^\/api\/sites$/, (_req, res) => send(res, 200, sites.list())],
['POST', /^\/api\/sites$/, async (req, res) => {
const site = sites.create(await readJson<NewSite>(req));
broadcast({ type: 'sites', sites: sites.list() });
send(res, 201, site);
}],
['GET', /^\/api\/sites\/([^/]+)$/, (_req, res, m) => send(res, 200, sites.get(m[1]))],
// a site's session: Claude Code in tmux
['GET', /^\/api\/sites\/([^/]+)\/session$/, (_req, res, m) => {
send(res, 200, { conversation: terminals.hasConversation(target(m[1]).dir) });
}],
['POST', /^\/api\/sites\/([^/]+)\/session\/start$/, async (req, res, m) => {
if (!terminals.available) throw new HttpError(409, 'Sessions need tmux.');
const t = target(m[1]);
const { resume } = await readJson<{ resume: boolean }>(req);
if (terminals.get(t.name)?.claude) throw new HttpError(409, 'Claude Code is already running for this site.');
// a session whose Claude Code has exited gets it back in place of the shell
if (terminals.get(t.name)) await terminals.respawn(t, { resume: resume === true });
else await terminals.start(t, { resume: resume === true });
send(res, 200, {});
}],
['POST', /^\/api\/sites\/([^/]+)\/session\/end$/, async (_req, res, m) => {
await terminals.end(target(m[1]));
send(res, 200, {});
}],
// live updates: one long response per open page, an event per `data:` line
['GET', /^\/api\/events$/, (req, res) => {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(`data: ${JSON.stringify({ type: 'sites', sites: sites.list() } satisfies ServerEvent)}\n\n`);
res.write(`data: ${JSON.stringify({ type: 'terminals', terminals: terminals.list() } satisfies ServerEvent)}\n\n`);
clients.add(res);
// a comment now and then, so no proxy on the way closes a quiet connection
const ping = setInterval(() => res.write(': ping\n\n'), 20000);
req.on('close', () => { clearInterval(ping); clients.delete(res); });
}],
];Three new routes. GET …/session tells whether the folder has a conversation. POST …/session/start answers 409 without tmux, and also when Claude Code already runs in the site's session: a second tab or a late second click would otherwise reach the respawn, and respawn-pane -k kills what runs in the pane, in the middle of its work. Otherwise the route reads resume from the body and either starts a new session or, if the site has one whose Claude Code has exited, respawns it. POST …/session/end ends the session. And the event stream sends the sessions right after the sites, so a page that connects knows both at once.
The header
The session gets a line in the site's header. Create src/session.ts:
import { api } from './api.ts';
import { h } from './dom.ts';
import type { TerminalState } from '../shared/types.ts';
/** The state of a site's session in its header, and the buttons that start and end it. */
export class SessionControls {
readonly el: HTMLElement;
private url: string;
private state: TerminalState | undefined;
/** the session's state when the server was last asked about a conversation */
private asked = '';
private dot = h('span', { class: 'dot', 'aria-hidden': 'true' });
private text = h('span');
private start = h('button', { type: 'button', class: 'small primary' }, 'Start Claude Code');
private resume = h('button', { type: 'button', class: 'small', hidden: true }, 'Continue last conversation');
private end = h('button', { type: 'button', class: 'small ghost danger' }, 'End session');
private msg = h('span', { class: 'hint bad', 'aria-live': 'polite' });
constructor(site: string, available: boolean) {
this.url = `/api/sites/${site}/session`;
this.start.onclick = () => void this.call('start', { resume: false });
this.resume.onclick = () => void this.call('start', { resume: true });
this.end.onclick = () => {
if (this.state?.claude && !confirm('End the session? Claude Code stops, also in the middle of its work.')) return;
void this.call('end');
};
this.el = h('div', { class: 'head-acts' },
h('span', { class: 'session-line' }, this.dot, this.text),
...(available ? [this.start, this.resume, this.end] : []),
this.msg);
if (!available) this.text.textContent = 'Sessions need tmux: install it and restart the server.';
else this.update(undefined);
}
update(state: TerminalState | undefined) {
this.state = state;
this.dot.className = `dot${state?.busy ? ' busy' : state?.claude ? ' on' : ''}`;
this.text.textContent = !state ? 'No session' : state.busy ? 'Claude Code is working' : state.claude ? 'Claude Code is open' : 'Claude Code has exited';
this.start.hidden = Boolean(state?.claude);
this.end.hidden = !state;
// "Continue" only when the folder has a conversation to continue (asked when the session changes)
const key = `${Boolean(state)}-${Boolean(state?.claude)}`;
if (key === this.asked) return;
this.asked = key;
this.resume.hidden = true;
if (!state?.claude) void api<{ conversation: boolean }>('GET', this.url).then((r) => { this.resume.hidden = !r.conversation || Boolean(this.state?.claude); }, () => undefined);
}
private async call(action: 'start' | 'end', body?: unknown) {
this.msg.textContent = '';
try { await api('POST', `${this.url}/${action}`, body); } catch (err) { this.msg.textContent = (err as Error).message; }
}
}A dot, a line of text, three buttons and a place for an error. update gets this site's state, or nothing:
No session: a gray dot, "No session", and Start Claude Code.
Claude Code runs: a green dot and "Claude Code is open", or, while the screen moves, a pulsing dot and "Claude Code is working".
A shell is in front: "Claude Code has exited", and Start Claude Code again, which the server turns into a respawn.
Continue last conversation shows only when Claude Code does not run and the folder has a conversation. The controls ask the server about that only when the session's state changes, not with every event: asked remembers the state they last asked in (is there a session, does Claude Code run in it), and a session that merely turns busy and quiet again doesn't count. End session asks first while Claude Code runs, because ending the session stops whatever it is doing. Without tmux there are no buttons, only a line that says what is missing.
In src/sitePage.ts, the controls go into the header, between the text and the link. The top of the file, down to the end of the constructor:
import { h } from './dom.ts';
import { SessionControls } from './session.ts';
import type { Config, Site, TerminalState } from '../shared/types.ts';
/** One site: what it is about, and the site itself in a frame. */
export class SitePage {
readonly el: HTMLElement;
readonly name: string;
private config: Config;
private site: Site | null = null;
private heading = h('h1', { class: 'site-heading' });
private about = h('p', { class: 'site-about' });
private frame = h('iframe', { class: 'preview-frame', title: 'The site', sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups' });
private empty = h('div', { class: 'preview-empty' }, h('p', {}, 'Nothing built yet.'));
private session: SessionControls;
constructor(name: string, config: Config) {
this.name = name;
this.config = config;
this.session = new SessionControls(name, config.terminals);
this.el = h('section', { class: 'site-page' },
h('header', { class: 'site-head' },
h('div', { class: 'site-head-text' }, this.heading, this.about),
this.session.el,
h('a', { class: 'button small', href: this.previewUrl, target: '_blank', rel: 'noopener' }, 'Open in a new tab')),
h('div', { class: 'preview' }, this.frame, this.empty));
}After update, add a method that hands the controls this site's state:
/** The sessions changed: this site's, or none. */
terminals(list: TerminalState[]) {
this.session.update(list.find((t) => t.site === this.name));
}src/main.ts keeps the latest list and passes it on: to a site page when it opens, and to the open one with every event.
import './style.css';
import { api, events } from './api.ts';
import { h } from './dom.ts';
import { newSiteForm } from './newSite.ts';
import { Sidebar } from './sidebar.ts';
import { SitePage } from './sitePage.ts';
import type { 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 sidebar = new Sidebar();
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);
let sites: Site[] = [];
let terminals: TerminalState[] = [];
let page: SitePage | null = null;
function route() {
const hash = decodeURIComponent(location.hash.slice(1));
const name = hash.startsWith('site/') ? hash.slice(5) : '';
if (page && page.name === name) return;
page?.dispose();
page = null;
if (hash === 'new') main.replaceChildren(newSiteForm((site) => { location.hash = `site/${site.name}`; }));
else if (name) {
page = new SitePage(name, config);
page.update(sites);
page.terminals(terminals);
main.replaceChildren(page.el);
} else {
main.replaceChildren(h('div', { class: 'welcome' },
h('h1', {}, 'Describe a site, Claude Code builds it.'),
h('p', {}, 'Pick a site on the left, or start a new one.'),
h('a', { class: 'button primary', href: '#new' }, 'New site')));
}
sidebar.render(sites, name);
}
function onEvent(ev: ServerEvent) {
if (ev.type === 'sites') {
sites = ev.sites;
sidebar.render(sites, page?.name ?? '');
page?.update(sites);
} else if (ev.type === 'terminals') {
terminals = ev.terminals;
page?.terminals(terminals);
} else if (ev.type === 'files' && ev.site === page?.name) page.filesChanged();
}
events(onEvent, () => { offline.hidden = false; }, () => { offline.hidden = true; });
window.addEventListener('hashchange', route);
route();
}
void start();Try it
Restart the server, open a site and click Start Claude Code. Within a second the header changes:
Behind the page, tmux has a new session. Look at it from a terminal, with the commands from part 1, now on -L sitesmith:
$ tmux -L sitesmith lsmaras-bakery: 1 windows (created Thu Nov 19 13:25:27 2026)$ tmux -L sitesmith list-panes -a -F '#{session_name} #{pane_current_command} #{window_activity}'maras-bakery claude 1795091127$ tmux -L sitesmith capture-pane -p -t =maras-bakery: Accessing workspace: ~/sitesmith/sites/maras-bakery Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first. Claude Code'll be able to read, edit, and execute files here. Security guide ❯ No, exit Yes, I trust this folder Enter to confirm · Esc to cancel# what the page heard over its server events at that moment:data: {"type":"terminals","terminals":[{"site":"maras-bakery","claude":true,"busy":false}]}
The trust dialog again. Claude Code has never seen this folder, so it waits for an answer before anything else. The page reports the session as open and not working, which is true, but it knows nothing about the dialog: no hook reports it. The page learns to answer it in part 10. Until then, answer it from the terminal, with the keys from part 1:
$ tmux -L sitesmith send-keys -t =maras-bakery: Down EnterEach site's folder asks once; after that, Claude Code remembers it.
Look in from your own terminal
Or go into the session and answer it there:
$ tmux -L sitesmith attach -t maras-bakery# no prefix key in these sessions: close the window to leave, or from another terminal:$ tmux -L sitesmith detach-client
This is Claude Code itself, the same session the page starts and ends. Type to it as in any terminal. With the prefix switched off, Ctrl+b and d now go to Claude Code, not to tmux. To leave, close the terminal window or tab: tmux detaches that terminal, and the session goes on. Or run detach-client from another terminal. While you are attached, the session has your terminal's size, because of window-size latest.
When Claude Code exits
Type /exit in the session, or let Claude Code end any other way. The session stays:
# after /exit in Claude Code: the shell stays, pane_current_command says bash$ tmux -L sitesmith list-panes -a -F '#{session_name} #{pane_current_command}'maras-bakery bash# what GET /api/sites/maras-bakery/session answers now:{"conversation":false}# "Continue last conversation" anyway (sent with curl, resume: true); the pane then shows:No conversation found to continueyou@laptop:~/sitesmith/sites/maras-bakery$
A shell is in front now, so the header says "Claude Code has exited" and offers to start it again. There is no conversation yet: Claude Code writes one only once a message has been sent, and none was. Forced anyway, --continue shows why the page hides the button then: Claude Code says there is nothing to continue and exits, and the shell takes over again.
Sessions outlive the server
# stop the server with Ctrl+C, then:$ tmux -L sitesmith ls# the session is still listed; start the server again, and the page finds it$ npm run server
Ctrl+C runs shutdown, which ends the event streams and the two servers but leaves tmux alone. The sessions keep running in tmux's own server process. When Sitesmith starts again, the first poll finds them, and the page, which has reconnected by itself, shows them as before.
What you have now
Every site can have a Claude Code session of its own: started in its folder, through your login shell, on your plan, in a tmux server that keeps out of the way and keeps foreign variables out. The page knows from tmux alone whether Claude Code runs and whether it works, and the sessions keep running whatever happens to the server.
To see what Claude Code does, though, you still need a terminal of your own. In the next part, the terminal comes into the page: xterm.js in the browser, attached to the same session.
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.
