import { useEffect, useRef, useState } from "react"; import "./App.css"; import { AudioPlayer, MicCapture, SAMPLE_RATE, hasNativeOutputPicker, listAudioOutputDevices, pickAudioOutputDevice, } from "./voice"; const GATEWAY_URL = "ws://localhost:8080"; const LAST_HOST_KEY = "ts-web-client:last-host"; const LAST_NICKNAME_KEY = "ts-web-client:last-nickname"; type LogEntry = { text: string; kind: "info" | "error" }; interface ChannelInfo { id: number; parent: number; order: number; name: string; } interface ClientInfo { id: number; channel: number; name: string; inputMuted: boolean; outputMuted: boolean; inputHardwareEnabled: boolean; away: boolean; isChannelCommander: boolean; } function ChannelIcon() { return ( ); } function ClientIcon() { return ( ); } function ClientStatusIcons({ client }: { client: ClientInfo }) { return ( {client.isChannelCommander && ⭐} {client.away && πŸ’€} {(client.inputMuted || !client.inputHardwareEnabled) && πŸ”‡} {client.outputMuted && πŸ”•} ); } function ServerIcon() { return ( ); } function ChannelTree({ channels, clients, parent, ownClientId, talkers, onSelectChannel, onOpenPrivateChat, onPokeClient, }: { channels: ChannelInfo[]; clients: ClientInfo[]; parent: number; ownClientId: number | null; talkers: Set; onSelectChannel: (channelId: number) => void; onOpenPrivateChat: (clientId: number, clientName: string) => void; onPokeClient: (clientId: number, clientName: string) => void; }) { const children = channels.filter((c) => c.parent === parent).sort((a, b) => a.order - b.order); if (children.length === 0) return null; return ( ); } interface ChatEntry { from: string; message: string; } interface PmMessage { fromSelf: boolean; message: string; } interface PmThread { partnerId: number; partnerName: string; messages: PmMessage[]; unread: boolean; } type ActiveTab = "channel" | "server" | number; interface PokeNotice { id: number; from: string; message: string; } function App() { const [host, setHost] = useState(() => localStorage.getItem(LAST_HOST_KEY) ?? "localhost"); const [nickname, setNickname] = useState(() => localStorage.getItem(LAST_NICKNAME_KEY) ?? "Claude Code"); const [serverPassword, setServerPassword] = useState(""); const [channelPassword, setChannelPassword] = useState(""); const [showPasswordFields, setShowPasswordFields] = useState(false); const [log, setLog] = useState([]); const [connected, setConnected] = useState(false); const [connecting, setConnecting] = useState(false); const [connectError, setConnectError] = useState(null); const [channels, setChannels] = useState([]); const [clients, setClients] = useState([]); const [chat, setChat] = useState([]); const [serverChat, setServerChat] = useState([]); const [chatInput, setChatInput] = useState(""); const [pmThreads, setPmThreads] = useState>({}); const [pokes, setPokes] = useState([]); const [pokeTarget, setPokeTarget] = useState<{ id: number; name: string } | null>(null); const [pokeMessage, setPokeMessage] = useState(""); const [activeTab, setActiveTab] = useState("channel"); const [theme, setTheme] = useState<"light" | "dark">(() => window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light" ); const [micOn, setMicOn] = useState(false); const [talkers, setTalkers] = useState>(new Set()); const [selfActive, setSelfActive] = useState(false); const [vadThreshold, setVadThreshold] = useState(0.02); const [outputDevices, setOutputDevices] = useState([]); const [outputDeviceId, setOutputDeviceId] = useState(""); const [outputDeviceLabel, setOutputDeviceLabel] = useState("System default"); const socketRef = useRef(null); const chatEndRef = useRef(null); const audioContextRef = useRef(null); const audioPlayerRef = useRef(null); const micCaptureRef = useRef(null); const activeTabRef = useRef("channel"); const hasConnectedRef = useRef(false); const pokeIdRef = useRef(0); useEffect(() => { chatEndRef.current?.scrollIntoView({ block: "nearest" }); }, [chat, serverChat, pmThreads, activeTab]); useEffect(() => { if (micCaptureRef.current) micCaptureRef.current.threshold = vadThreshold; }, [vadThreshold]); useEffect(() => { activeTabRef.current = activeTab; if (activeTab !== "channel") { setPmThreads((prev) => { const thread = prev[activeTab]; if (!thread || !thread.unread) return prev; return { ...prev, [activeTab]: { ...thread, unread: false } }; }); } }, [activeTab]); const refreshOutputDevices = async () => { try { const devices = await listAudioOutputDevices(); setOutputDevices(devices); } catch { // Device labels/enumeration may be unavailable before mic permission is granted. } }; useEffect(() => { navigator.mediaDevices?.addEventListener?.("devicechange", refreshOutputDevices); return () => navigator.mediaDevices?.removeEventListener?.("devicechange", refreshOutputDevices); }, []); useEffect(() => { return () => socketRef.current?.close(); }, []); const appendLog = (entry: LogEntry) => setLog((prev) => [...prev, entry]); const stopMic = () => { micCaptureRef.current?.stop(); micCaptureRef.current = null; setMicOn(false); setSelfActive(false); }; const handleConnect = () => { hasConnectedRef.current = false; setConnecting(true); setConnectError(null); const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE }); audioContextRef.current = audioContext; audioPlayerRef.current = new AudioPlayer(audioContext); const socket = new WebSocket(GATEWAY_URL); socketRef.current = socket; socket.onopen = () => { socket.send( JSON.stringify({ type: "connect", host, nickname, serverPassword: serverPassword || undefined, channelPassword: channelPassword || undefined, }) ); }; socket.onmessage = (event) => { const data = JSON.parse(event.data); switch (data.type) { case "connected": hasConnectedRef.current = true; setConnecting(false); setConnectError(null); setConnected(true); localStorage.setItem(LAST_HOST_KEY, host); localStorage.setItem(LAST_NICKNAME_KEY, nickname); setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]); break; case "channels": setChannels(data.channels); setClients(data.clients); break; case "chatMessage": setChat((prev) => [...prev, { from: data.from, message: data.message }]); break; case "serverMessage": setServerChat((prev) => [...prev, { from: data.from, message: data.message }]); break; case "privateMessage": setPmThreads((prev) => { const existing = prev[data.partnerId]; const thread: PmThread = existing ?? { partnerId: data.partnerId, partnerName: data.partnerName, messages: [], unread: false, }; return { ...prev, [data.partnerId]: { ...thread, partnerName: data.partnerName, messages: [...thread.messages, { fromSelf: data.fromSelf, message: data.message }], unread: thread.unread || (!data.fromSelf && activeTabRef.current !== data.partnerId), }, }; }); break; case "audioOut": audioPlayerRef.current?.playFrame(data.pcm); break; case "talkers": setTalkers(new Set(data.clients)); break; case "poke": { const id = ++pokeIdRef.current; setPokes((prev) => [...prev, { id, from: data.from, message: data.message }]); setTimeout(() => setPokes((prev) => prev.filter((p) => p.id !== id)), 10000); break; } case "disconnected": hasConnectedRef.current = false; setConnecting(false); setConnected(false); setChannels([]); setClients([]); setChat([]); setServerChat([]); setPmThreads({}); setPokes([]); setActiveTab("channel"); setTalkers(new Set()); stopMic(); appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" }); break; case "error": if (hasConnectedRef.current) { appendLog({ text: data.message, kind: "error" }); } else { setConnecting(false); setConnectError(data.message); } break; } }; socket.onerror = () => { if (!hasConnectedRef.current) { setConnecting(false); setConnectError("Could not reach the gateway - is it running?"); } else { appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" }); } }; socket.onclose = () => { if (!hasConnectedRef.current) { setConnecting(false); setConnectError((prev) => prev ?? "Connection closed before the server responded"); } setConnected(false); stopMic(); audioPlayerRef.current?.dispose(); audioPlayerRef.current = null; audioContextRef.current?.close(); audioContextRef.current = null; }; }; const handleDisconnect = () => socketRef.current?.close(); const handleToggleMic = async () => { if (micOn) { stopMic(); return; } const audioContext = audioContextRef.current; if (!audioContext) return; try { const mic = new MicCapture( audioContext, (pcm) => socketRef.current?.send(JSON.stringify({ type: "sendAudio", pcm })), (active) => setSelfActive(active), vadThreshold ); await mic.start(); micCaptureRef.current = mic; setMicOn(true); refreshOutputDevices(); } catch (error) { appendLog({ text: `Microphone error: ${(error as Error).message}`, kind: "error" }); } }; const handleOutputDeviceChange = async (deviceId: string, label?: string) => { setOutputDeviceId(deviceId); setOutputDeviceLabel(label || (deviceId ? `Output ${deviceId.slice(0, 6)}` : "System default")); await audioPlayerRef.current?.setOutputDevice(deviceId); }; const handlePickOutputDevice = async () => { try { const device = await pickAudioOutputDevice(); if (device) await handleOutputDeviceChange(device.deviceId, device.label); } catch (error) { appendLog({ text: `Output device error: ${(error as Error).message}`, kind: "error" }); } }; const handleSelectChannel = (channelId: number) => { socketRef.current?.send(JSON.stringify({ type: "switchChannel", channelId })); }; const handleSendChat = () => { const message = chatInput.trim(); if (!message) return; if (activeTab === "channel") { socketRef.current?.send(JSON.stringify({ type: "sendChatMessage", message })); } else if (activeTab === "server") { socketRef.current?.send(JSON.stringify({ type: "sendServerMessage", message })); } else { socketRef.current?.send(JSON.stringify({ type: "sendPrivateMessage", clientId: activeTab, message })); } setChatInput(""); }; const handleOpenPrivateChat = (clientId: number, clientName: string) => { setPmThreads((prev) => ({ ...prev, [clientId]: prev[clientId] ?? { partnerId: clientId, partnerName: clientName, messages: [], unread: false }, })); setActiveTab(clientId); }; const handlePokeClient = (clientId: number, clientName: string) => { setPokeTarget({ id: clientId, name: clientName }); setPokeMessage(""); }; const handleSendPoke = () => { if (!pokeTarget) return; socketRef.current?.send( JSON.stringify({ type: "sendPoke", clientId: pokeTarget.id, message: pokeMessage }) ); setPokeTarget(null); setPokeMessage(""); }; const handleClosePrivateChat = (clientId: number) => { setPmThreads((prev) => { const next = { ...prev }; delete next[clientId]; return next; }); setActiveTab((current) => (current === clientId ? "channel" : current)); }; const ownClient = clients.find((c) => c.name === nickname) ?? null; const displayTalkers = selfActive && ownClient ? new Set(talkers).add(ownClient.id) : talkers; return (
TS Web Client
{!connected && ( )} {!connected && showPasswordFields && ( <> )} {!connected ? ( ) : ( )} {hasNativeOutputPicker() ? ( ) : ( )}
{connectError && (
⚠️ {connectError}
)} {pokeTarget && (
setPokeTarget(null)}>
e.stopPropagation()}> πŸ‘‰ Poke {pokeTarget.name} setPokeMessage(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") handleSendPoke(); if (e.key === "Escape") setPokeTarget(null); }} placeholder="Optional message..." />
)} {pokes.map((poke) => (
πŸ‘‰ {poke.from} poked you{poke.message ? `: ${poke.message}` : ""}
))}
{connected ? ( <>
{host}
) : (
Not connected
)}
{Object.values(pmThreads).map((thread) => ( ))}
{activeTab === "channel" ? chat.map((entry, i) => (
{entry.from}: {entry.message}
)) : activeTab === "server" ? serverChat.map((entry, i) => (
{entry.from}: {entry.message}
)) : pmThreads[activeTab]?.messages.map((entry, i) => (
{entry.fromSelf ? "You" : pmThreads[activeTab].partnerName}: {" "} {entry.message}
))}
setChatInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleSendChat()} disabled={!connected} placeholder={ !connected ? "Not connected" : activeTab === "channel" ? "Message channel..." : activeTab === "server" ? "Message server..." : `Message ${pmThreads[activeTab]?.partnerName}...` } />
{log.map((entry, i) => (
{entry.text}
))}
); } export default App;