feat: MVP two-user chat via embedded SPA (#9)
All checks were successful
check / check (push) Successful in 1m51s

Backend:
- Session/client UUID model: sessions table (uuid, nick, signing_key),
  clients table (uuid, session_id, token) with per-client message queues
- MOTD delivery as IRC numeric messages (375/372/376) on connect
- EnqueueToSession fans out to all clients of a session
- EnqueueToClient for targeted delivery (MOTD)
- All queries updated for session/client model

SPA client:
- Long-poll loop (15s timeout) instead of setInterval
- IRC message envelope parsing (command/from/to/body)
- Display JOIN/PART/NICK/TOPIC/QUIT system messages
- Nick change via /nick command
- Topic display in header bar
- Unread count badges on inactive tabs
- Auto-rejoin channels on reconnect (localStorage)
- Connection status indicator
- Message deduplication by UUID
- Channel history loaded on join
- /topic command support

Closes #9
This commit is contained in:
clawbot
2026-02-27 02:21:48 -08:00
parent 2d08a8476f
commit 32419fb1f7
8 changed files with 921 additions and 880 deletions

466
web/dist/app.js vendored

File diff suppressed because one or more lines are too long

43
web/dist/style.css vendored
View File

@@ -14,6 +14,9 @@
--tab-active: #e94560;
--tab-bg: #16213e;
--tab-hover: #1a1a3e;
--topic-bg: #121a30;
--unread-bg: #e94560;
--warn: #f0ad4e;
}
html, body, #root {
@@ -86,6 +89,7 @@ html, body, #root {
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex-shrink: 0;
align-items: center;
}
.tab {
@@ -95,6 +99,7 @@ html, body, #root {
white-space: nowrap;
color: var(--text-muted);
user-select: none;
position: relative;
}
.tab:hover {
@@ -116,6 +121,43 @@ html, body, #root {
color: var(--accent);
}
.tab .unread-badge {
display: inline-block;
background: var(--unread-bg);
color: white;
font-size: 10px;
font-weight: bold;
padding: 1px 5px;
border-radius: 8px;
margin-left: 6px;
min-width: 16px;
text-align: center;
}
/* Connection status */
.connection-status {
padding: 4px 12px;
background: var(--warn);
color: #1a1a2e;
font-size: 12px;
font-weight: bold;
white-space: nowrap;
flex-shrink: 0;
}
/* Topic bar */
.topic-bar {
padding: 6px 12px;
background: var(--topic-bg);
border-bottom: 1px solid var(--border);
color: var(--text-muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 0;
}
/* Content area */
.content {
display: flex;
@@ -243,6 +285,7 @@ html, body, #root {
gap: 8px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border);
margin-left: auto;
}
.join-dialog input {

View File

@@ -1,13 +1,17 @@
import { h, render, Component } from 'preact';
import { h, render } from 'preact';
import { useState, useEffect, useRef, useCallback } from 'preact/hooks';
const API = '/api/v1';
const POLL_TIMEOUT = 15;
const RECONNECT_DELAY = 3000;
const MEMBER_REFRESH_INTERVAL = 10000;
function api(path, opts = {}) {
const token = localStorage.getItem('chat_token');
const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
if (token) headers['Authorization'] = `Bearer ${token}`;
return fetch(API + path, { ...opts, headers }).then(async r => {
const { signal, ...rest } = opts;
return fetch(API + path, { ...rest, headers, signal }).then(async r => {
const data = await r.json().catch(() => null);
if (!r.ok) throw { status: r.status, data };
return data;
@@ -19,7 +23,6 @@ function formatTime(ts) {
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
// Nick color hashing
function nickColor(nick) {
let h = 0;
for (let i = 0; i < nick.length; i++) h = nick.charCodeAt(i) + ((h << 5) - h);
@@ -39,10 +42,9 @@ function LoginScreen({ onLogin }) {
if (s.name) setServerName(s.name);
if (s.motd) setMotd(s.motd);
}).catch(() => {});
// Check for saved token
const saved = localStorage.getItem('chat_token');
if (saved) {
api('/state').then(u => onLogin(u.nick, saved)).catch(() => localStorage.removeItem('chat_token'));
api('/state').then(u => onLogin(u.nick)).catch(() => localStorage.removeItem('chat_token'));
}
inputRef.current?.focus();
}, []);
@@ -56,7 +58,7 @@ function LoginScreen({ onLogin }) {
body: JSON.stringify({ nick: nick.trim() })
});
localStorage.setItem('chat_token', res.token);
onLogin(res.nick, res.token);
onLogin(res.nick);
} catch (err) {
setError(err.data?.error || 'Connection failed');
}
@@ -84,11 +86,19 @@ function LoginScreen({ onLogin }) {
}
function Message({ msg }) {
if (msg.system) {
return (
<div class="message system">
<span class="timestamp">{formatTime(msg.ts)}</span>
<span class="content">{msg.text}</span>
</div>
);
}
return (
<div class={`message ${msg.system ? 'system' : ''}`}>
<span class="timestamp">{formatTime(msg.createdAt)}</span>
<span class="nick" style={{ color: msg.system ? undefined : nickColor(msg.nick) }}>{msg.nick}</span>
<span class="content">{msg.content}</span>
<div class="message">
<span class="timestamp">{formatTime(msg.ts)}</span>
<span class="nick" style={{ color: nickColor(msg.from) }}>{msg.from}</span>
<span class="content">{msg.text}</span>
</div>
);
}
@@ -98,93 +108,194 @@ function App() {
const [nick, setNick] = useState('');
const [tabs, setTabs] = useState([{ type: 'server', name: 'Server' }]);
const [activeTab, setActiveTab] = useState(0);
const [messages, setMessages] = useState({ server: [] }); // keyed by tab name
const [members, setMembers] = useState({}); // keyed by channel name
const [messages, setMessages] = useState({ Server: [] });
const [members, setMembers] = useState({});
const [topics, setTopics] = useState({});
const [unread, setUnread] = useState({});
const [input, setInput] = useState('');
const [joinInput, setJoinInput] = useState('');
const [lastMsgId, setLastMsgId] = useState(0);
const [connected, setConnected] = useState(true);
const lastIdRef = useRef(0);
const seenIdsRef = useRef(new Set());
const pollAbortRef = useRef(null);
const tabsRef = useRef(tabs);
const activeTabRef = useRef(activeTab);
const nickRef = useRef(nick);
const messagesEndRef = useRef();
const inputRef = useRef();
const pollRef = useRef();
useEffect(() => { tabsRef.current = tabs; }, [tabs]);
useEffect(() => { activeTabRef.current = activeTab; }, [activeTab]);
useEffect(() => { nickRef.current = nick; }, [nick]);
// Persist joined channels
useEffect(() => {
const channels = tabs.filter(t => t.type === 'channel').map(t => t.name);
localStorage.setItem('chat_channels', JSON.stringify(channels));
}, [tabs]);
// Clear unread on tab switch
useEffect(() => {
const tab = tabs[activeTab];
if (tab) setUnread(prev => ({ ...prev, [tab.name]: 0 }));
}, [activeTab, tabs]);
const addMessage = useCallback((tabName, msg) => {
if (msg.id && seenIdsRef.current.has(msg.id)) return;
if (msg.id) seenIdsRef.current.add(msg.id);
setMessages(prev => ({
...prev,
[tabName]: [...(prev[tabName] || []), msg]
}));
const currentTab = tabsRef.current[activeTabRef.current];
if (!currentTab || currentTab.name !== tabName) {
setUnread(prev => ({ ...prev, [tabName]: (prev[tabName] || 0) + 1 }));
}
}, []);
const addSystemMessage = useCallback((tabName, text) => {
addMessage(tabName, {
id: Date.now(),
nick: '*',
content: text,
createdAt: new Date().toISOString(),
system: true
});
}, [addMessage]);
setMessages(prev => ({
...prev,
[tabName]: [...(prev[tabName] || []), {
id: 'sys-' + Date.now() + '-' + Math.random(),
ts: new Date().toISOString(),
text,
system: true
}]
}));
}, []);
const onLogin = useCallback((userNick, token) => {
setNick(userNick);
setLoggedIn(true);
addSystemMessage('server', `Connected as ${userNick}`);
// Fetch server info
api('/server').then(s => {
if (s.motd) addSystemMessage('server', `MOTD: ${s.motd}`);
const refreshMembers = useCallback((channel) => {
const chName = channel.replace('#', '');
api(`/channels/${chName}/members`).then(m => {
setMembers(prev => ({ ...prev, [channel]: m }));
}).catch(() => {});
}, [addSystemMessage]);
}, []);
// Poll for new messages
const processMessage = useCallback((msg) => {
const body = Array.isArray(msg.body) ? msg.body.join('\n') : '';
const base = { id: msg.id, ts: msg.ts, from: msg.from, to: msg.to, command: msg.command };
switch (msg.command) {
case 'PRIVMSG':
case 'NOTICE': {
const parsed = { ...base, text: body, system: false };
const target = msg.to;
if (target && target.startsWith('#')) {
addMessage(target, parsed);
} else {
const dmPeer = msg.from === nickRef.current ? msg.to : msg.from;
setTabs(prev => {
if (!prev.find(t => t.type === 'dm' && t.name === dmPeer)) {
return [...prev, { type: 'dm', name: dmPeer }];
}
return prev;
});
addMessage(dmPeer, parsed);
}
break;
}
case 'JOIN': {
const text = `${msg.from} has joined ${msg.to}`;
if (msg.to) addMessage(msg.to, { ...base, text, system: true });
if (msg.to && msg.to.startsWith('#')) refreshMembers(msg.to);
break;
}
case 'PART': {
const reason = body ? ': ' + body : '';
const text = `${msg.from} has left ${msg.to}${reason}`;
if (msg.to) addMessage(msg.to, { ...base, text, system: true });
if (msg.to && msg.to.startsWith('#')) refreshMembers(msg.to);
break;
}
case 'QUIT': {
const reason = body ? ': ' + body : '';
const text = `${msg.from} has quit${reason}`;
tabsRef.current.forEach(tab => {
if (tab.type === 'channel') {
addMessage(tab.name, { ...base, text, system: true });
}
});
break;
}
case 'NICK': {
const newNick = Array.isArray(msg.body) ? msg.body[0] : body;
const text = `${msg.from} is now known as ${newNick}`;
tabsRef.current.forEach(tab => {
if (tab.type === 'channel') {
addMessage(tab.name, { ...base, text, system: true });
}
});
if (msg.from === nickRef.current && newNick) setNick(newNick);
// Refresh members in all channels
tabsRef.current.forEach(tab => {
if (tab.type === 'channel') refreshMembers(tab.name);
});
break;
}
case 'TOPIC': {
const text = `${msg.from} set the topic: ${body}`;
if (msg.to) {
addMessage(msg.to, { ...base, text, system: true });
setTopics(prev => ({ ...prev, [msg.to]: body }));
}
break;
}
case '375':
case '372':
case '376':
addMessage('Server', { ...base, text: body, system: true });
break;
default:
addMessage('Server', { ...base, text: body || msg.command, system: true });
}
}, [addMessage, refreshMembers]);
// Long-poll loop
useEffect(() => {
if (!loggedIn) return;
let alive = true;
const poll = async () => {
try {
const msgs = await api(`/messages?after=${lastMsgId}`);
if (!alive) return;
let maxId = lastMsgId;
for (const msg of msgs) {
if (msg.id > maxId) maxId = msg.id;
if (msg.isDm) {
const dmTab = msg.nick === nick ? msg.dmTarget : msg.nick;
// Ensure DM tab exists
setTabs(prev => {
if (!prev.find(t => t.type === 'dm' && t.name === dmTab)) {
return [...prev, { type: 'dm', name: dmTab }];
}
return prev;
});
addMessage(dmTab, msg);
} else if (msg.channel) {
addMessage(msg.channel, msg);
while (alive) {
try {
const controller = new AbortController();
pollAbortRef.current = controller;
const result = await api(
`/messages?after=${lastIdRef.current}&timeout=${POLL_TIMEOUT}`,
{ signal: controller.signal }
);
if (!alive) break;
setConnected(true);
if (result.messages) {
for (const m of result.messages) processMessage(m);
}
if (result.last_id > lastIdRef.current) {
lastIdRef.current = result.last_id;
}
} catch (err) {
if (!alive) break;
if (err.name === 'AbortError') continue;
setConnected(false);
await new Promise(r => setTimeout(r, RECONNECT_DELAY));
}
if (maxId > lastMsgId) setLastMsgId(maxId);
} catch (err) {
// silent
}
};
pollRef.current = setInterval(poll, 1500);
poll();
return () => { alive = false; clearInterval(pollRef.current); };
}, [loggedIn, lastMsgId, nick, addMessage]);
// Fetch members for active channel tab
poll();
return () => { alive = false; pollAbortRef.current?.abort(); };
}, [loggedIn, processMessage]);
// Refresh members for active channel
useEffect(() => {
if (!loggedIn) return;
const tab = tabs[activeTab];
if (!tab || tab.type !== 'channel') return;
const chName = tab.name.replace('#', '');
api(`/channels/${chName}/members`).then(m => {
setMembers(prev => ({ ...prev, [tab.name]: m }));
}).catch(() => {});
const iv = setInterval(() => {
api(`/channels/${chName}/members`).then(m => {
setMembers(prev => ({ ...prev, [tab.name]: m }));
}).catch(() => {});
}, 5000);
refreshMembers(tab.name);
const iv = setInterval(() => refreshMembers(tab.name), MEMBER_REFRESH_INTERVAL);
return () => clearInterval(iv);
}, [loggedIn, activeTab, tabs]);
}, [loggedIn, activeTab, tabs, refreshMembers]);
// Auto-scroll
useEffect(() => {
@@ -192,9 +303,37 @@ function App() {
}, [messages, activeTab]);
// Focus input on tab change
useEffect(() => { inputRef.current?.focus(); }, [activeTab]);
// Fetch topic for active channel
useEffect(() => {
inputRef.current?.focus();
}, [activeTab]);
if (!loggedIn) return;
const tab = tabs[activeTab];
if (!tab || tab.type !== 'channel') return;
api('/channels').then(channels => {
const ch = channels.find(c => c.name === tab.name);
if (ch && ch.topic) setTopics(prev => ({ ...prev, [tab.name]: ch.topic }));
}).catch(() => {});
}, [loggedIn, activeTab, tabs]);
const onLogin = useCallback(async (userNick) => {
setNick(userNick);
setLoggedIn(true);
addSystemMessage('Server', `Connected as ${userNick}`);
// Auto-rejoin saved channels
const saved = JSON.parse(localStorage.getItem('chat_channels') || '[]');
for (const ch of saved) {
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'JOIN', to: ch }) });
setTabs(prev => {
if (prev.find(t => t.type === 'channel' && t.name === ch)) return prev;
return [...prev, { type: 'channel', name: ch }];
});
} catch (e) {
// Channel may not exist anymore
}
}
}, [addSystemMessage]);
const joinChannel = async (name) => {
if (!name) return;
@@ -206,22 +345,29 @@ function App() {
if (prev.find(t => t.type === 'channel' && t.name === name)) return prev;
return [...prev, { type: 'channel', name }];
});
setActiveTab(tabs.length); // switch to new tab
addSystemMessage(name, `Joined ${name}`);
setActiveTab(tabs.length);
// Load history
try {
const hist = await api(`/history?target=${encodeURIComponent(name)}&limit=50`);
if (Array.isArray(hist)) {
for (const m of hist) processMessage(m);
}
} catch (e) {
// History may be empty
}
setJoinInput('');
} catch (err) {
addSystemMessage('server', `Failed to join ${name}: ${err.data?.error || 'error'}`);
addSystemMessage('Server', `Failed to join ${name}: ${err.data?.error || 'error'}`);
}
};
const partChannel = async (name) => {
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'PART', to: name }) });
} catch (err) { /* ignore */ }
setTabs(prev => {
const next = prev.filter(t => !(t.type === 'channel' && t.name === name));
return next;
});
} catch (e) {
// Ignore
}
setTabs(prev => prev.filter(t => !(t.type === 'channel' && t.name === name)));
setActiveTab(0);
};
@@ -240,7 +386,8 @@ function App() {
if (prev.find(t => t.type === 'dm' && t.name === targetNick)) return prev;
return [...prev, { type: 'dm', name: targetNick }];
});
setActiveTab(tabs.findIndex(t => t.type === 'dm' && t.name === targetNick) || tabs.length);
const idx = tabs.findIndex(t => t.type === 'dm' && t.name === targetNick);
setActiveTab(idx >= 0 ? idx : tabs.length);
};
const sendMessage = async () => {
@@ -250,46 +397,45 @@ function App() {
const tab = tabs[activeTab];
if (!tab || tab.type === 'server') return;
// Handle /commands
if (text.startsWith('/')) {
const parts = text.split(' ');
const cmd = parts[0].toLowerCase();
if (cmd === '/join' && parts[1]) {
joinChannel(parts[1]);
return;
}
if (cmd === '/part') {
if (tab.type === 'channel') partChannel(tab.name);
return;
}
if (cmd === '/join' && parts[1]) { joinChannel(parts[1]); return; }
if (cmd === '/part') { if (tab.type === 'channel') partChannel(tab.name); return; }
if (cmd === '/msg' && parts[1] && parts.slice(2).join(' ')) {
const target = parts[1];
const msg = parts.slice(2).join(' ');
const body = parts.slice(2).join(' ');
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'PRIVMSG', to: target, body: [msg] }) });
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'PRIVMSG', to: target, body: [body] }) });
openDM(target);
} catch (err) {
addSystemMessage('server', `Failed to send DM: ${err.data?.error || 'error'}`);
addSystemMessage('Server', `DM failed: ${err.data?.error || 'error'}`);
}
return;
}
if (cmd === '/nick' && parts[1]) {
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'NICK', body: [parts[1]] }) });
setNick(parts[1]);
addSystemMessage('server', `Nick changed to ${parts[1]}`);
} catch (err) {
addSystemMessage('server', `Nick change failed: ${err.data?.error || 'error'}`);
addSystemMessage('Server', `Nick change failed: ${err.data?.error || 'error'}`);
}
return;
}
addSystemMessage('server', `Unknown command: ${cmd}`);
if (cmd === '/topic' && tab.type === 'channel') {
const topicText = parts.slice(1).join(' ');
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'TOPIC', to: tab.name, body: [topicText] }) });
} catch (err) {
addSystemMessage('Server', `Topic failed: ${err.data?.error || 'error'}`);
}
return;
}
addSystemMessage('Server', `Unknown command: ${cmd}`);
return;
}
const to = tab.type === 'channel' ? tab.name : tab.name;
try {
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'PRIVMSG', to, body: [text] }) });
await api('/messages', { method: 'POST', body: JSON.stringify({ command: 'PRIVMSG', to: tab.name, body: [text] }) });
} catch (err) {
addSystemMessage(tab.name, `Send failed: ${err.data?.error || 'error'}`);
}
@@ -300,16 +446,21 @@ function App() {
const currentTab = tabs[activeTab] || tabs[0];
const currentMessages = messages[currentTab.name] || [];
const currentMembers = members[currentTab.name] || [];
const currentTopic = topics[currentTab.name] || '';
return (
<div class="app">
<div class="tab-bar">
{!connected && <div class="connection-status"> Reconnecting...</div>}
{tabs.map((tab, i) => (
<div
class={`tab ${i === activeTab ? 'active' : ''}`}
onClick={() => setActiveTab(i)}
>
{tab.type === 'dm' ? `${tab.name}` : tab.name}
{unread[tab.name] > 0 && i !== activeTab && (
<span class="unread-badge">{unread[tab.name]}</span>
)}
{tab.type !== 'server' && (
<span class="close-btn" onClick={(e) => { e.stopPropagation(); closeTab(i); }}>×</span>
)}
@@ -326,30 +477,27 @@ function App() {
</div>
</div>
{currentTab.type === 'channel' && currentTopic && (
<div class="topic-bar" title={currentTopic}>{currentTopic}</div>
)}
<div class="content">
<div class="messages-pane">
{currentTab.type === 'server' ? (
<div class="server-messages">
{currentMessages.map(m => <Message msg={m} />)}
<div ref={messagesEndRef} />
<div class={currentTab.type === 'server' ? 'server-messages' : 'messages'}>
{currentMessages.map(m => <Message msg={m} />)}
<div ref={messagesEndRef} />
</div>
{currentTab.type !== 'server' && (
<div class="input-bar">
<input
ref={inputRef}
placeholder={`Message ${currentTab.name}...`}
value={input}
onInput={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && sendMessage()}
/>
<button onClick={sendMessage}>Send</button>
</div>
) : (
<>
<div class="messages">
{currentMessages.map(m => <Message msg={m} />)}
<div ref={messagesEndRef} />
</div>
<div class="input-bar">
<input
ref={inputRef}
placeholder={`Message ${currentTab.name}...`}
value={input}
onInput={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && sendMessage()}
/>
<button onClick={sendMessage}>Send</button>
</div>
</>
)}
</div>

View File

@@ -14,6 +14,9 @@
--tab-active: #e94560;
--tab-bg: #16213e;
--tab-hover: #1a1a3e;
--topic-bg: #121a30;
--unread-bg: #e94560;
--warn: #f0ad4e;
}
html, body, #root {
@@ -86,6 +89,7 @@ html, body, #root {
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex-shrink: 0;
align-items: center;
}
.tab {
@@ -95,6 +99,7 @@ html, body, #root {
white-space: nowrap;
color: var(--text-muted);
user-select: none;
position: relative;
}
.tab:hover {
@@ -116,6 +121,43 @@ html, body, #root {
color: var(--accent);
}
.tab .unread-badge {
display: inline-block;
background: var(--unread-bg);
color: white;
font-size: 10px;
font-weight: bold;
padding: 1px 5px;
border-radius: 8px;
margin-left: 6px;
min-width: 16px;
text-align: center;
}
/* Connection status */
.connection-status {
padding: 4px 12px;
background: var(--warn);
color: #1a1a2e;
font-size: 12px;
font-weight: bold;
white-space: nowrap;
flex-shrink: 0;
}
/* Topic bar */
.topic-bar {
padding: 6px 12px;
background: var(--topic-bg);
border-bottom: 1px solid var(--border);
color: var(--text-muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 0;
}
/* Content area */
.content {
display: flex;
@@ -243,6 +285,7 @@ html, body, #root {
gap: 8px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border);
margin-left: auto;
}
.join-dialog input {