whatsapp qr code polling, validate token before save, fix bot startup timing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 12:41:46 +00:00
co-authored by Claude Opus 4.6
parent b698e3d962
commit 209d58a525
2 changed files with 62 additions and 103 deletions
@@ -13,10 +13,10 @@ type WhatsAppConfig = {
phone: string | null;
};
type SSEEvent = {
type: 'qr' | 'authenticated' | 'disconnected' | 'waiting';
qr?: string;
phone?: string;
type QRResponse = {
qr: string | null;
running: boolean;
phone: string | null;
};
const SetupGuide = () => {
@@ -72,7 +72,7 @@ export const WhatsAppBotConfig = () => {
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
const [isConnecting, setIsConnecting] = useState(false);
const [isDisconnecting, setIsDisconnecting] = useState(false);
const eventSourceRef = useRef<EventSource | null>(null);
const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fetchConfig = useCallback(() => {
client
@@ -81,60 +81,59 @@ export const WhatsAppBotConfig = () => {
.catch(() => {});
}, [client]);
useEffect(() => {
fetchConfig();
setIsLoading(false);
const stopPolling = useCallback(() => {
if (pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
}, []);
const connectSSE = useCallback(() => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
}
const token = localStorage.getItem('token') ?? sessionStorage.getItem('token') ?? '';
const url = `/api/channels/whatsapp/qr?token=${encodeURIComponent(token)}`;
const es = new EventSource(url);
eventSourceRef.current = es;
es.onmessage = async (ev) => {
try {
const data = JSON.parse(ev.data) as SSEEvent;
if (data.type === 'qr' && data.qr) {
const pollQR = useCallback(() => {
client
.get<QRResponse>('/channels/whatsapp/qr')
.then(async (data) => {
if (data.running) {
// Authenticated — stop polling, update config
stopPolling();
setQrDataUrl(null);
fetchConfig();
return;
}
if (data.qr) {
const dataUrl = await QRCode.toDataURL(data.qr, { width: 256, margin: 2 });
setQrDataUrl(dataUrl);
} else if (data.type === 'authenticated') {
setQrDataUrl(null);
es.close();
fetchConfig();
} else if (data.type === 'disconnected') {
setQrDataUrl(null);
es.close();
fetchConfig();
}
} catch {
// ignore parse errors
}
};
})
.catch(() => {});
}, [client, fetchConfig, stopPolling]);
es.onerror = () => {
es.close();
setQrDataUrl(null);
};
}, [fetchConfig]);
const startPolling = useCallback(() => {
stopPolling();
pollQR();
pollingRef.current = setInterval(pollQR, 2000);
}, [pollQR, stopPolling]);
useEffect(() => {
return () => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
}
};
client
.get<WhatsAppConfig>('/channels/whatsapp/config')
.then((data) => {
setConfig(data);
// Auto-poll QR if bot is enabled but waiting for scan
if (data.enabled && !data.running) {
startPolling();
}
})
.catch(() => {})
.finally(() => setIsLoading(false));
return stopPolling;
}, []);
const handleConnect = async () => {
setIsConnecting(true);
try {
await client.put('/channels/whatsapp/config', { enabled: true });
connectSSE();
startPolling();
} catch {
toast.error('Failed to start WhatsApp connection');
} finally {
@@ -146,10 +145,7 @@ export const WhatsAppBotConfig = () => {
setIsDisconnecting(true);
try {
await client.put('/channels/whatsapp/config', { enabled: false });
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
stopPolling();
setQrDataUrl(null);
toast.success('WhatsApp disconnected');
fetchConfig();
@@ -170,7 +166,11 @@ export const WhatsAppBotConfig = () => {
className={`h-2.5 w-2.5 rounded-full shrink-0 ${config.running ? 'bg-green-500' : 'bg-duck-dark/20 dark:bg-foreground/20'}`}
/>
<span className="text-sm text-duck-dark dark:text-foreground">
{config.running ? `Connected as +${config.phone}` : config.enabled ? 'Starting...' : 'Not connected'}
{config.running
? `Connected as +${config.phone}`
: config.enabled
? 'Waiting for QR scan...'
: 'Not connected'}
</span>
</div>
)}
@@ -189,7 +189,7 @@ export const WhatsAppBotConfig = () => {
</div>
)}
{config?.running ? (
{config?.running || config?.enabled ? (
<Button
type="button"
variant="outline"
+11 -52
View File
@@ -8,7 +8,6 @@ import {
isWhatsAppBotRunning,
getWhatsAppBotPhone,
getWhatsAppQR,
subscribeQR,
disconnectWhatsApp,
} from './whatsapp/bot';
import { generatePairingCode } from './pairing';
@@ -268,13 +267,12 @@ channelsRouter.put('/whatsapp/config', async (ctx) => {
if (enabled === true) {
await upsertServerIntegration('whatsapp', {}, true);
try {
await startWhatsAppBot();
} catch (err) {
// Don't await — initialization is slow (launches Chromium) and QR events
// are delivered via SSE. Return immediately so the client can connect SSE.
startWhatsAppBot().catch((err) => {
console.error('[channels] Failed to start WhatsApp bot:', err);
return ctx.json({ success: true, botStarted: false, error: String(err) });
}
return ctx.json({ success: true, botStarted: true });
});
return ctx.json({ success: true, botStarted: false });
}
if (enabled === false) {
@@ -300,51 +298,12 @@ channelsRouter.get('/whatsapp/qr', async (ctx) => {
const user = ctx.get('user');
if (user.role !== 'Super Admin') return ctx.json({ error: 'Forbidden' }, 403);
// SSE stream for QR code updates
return new Response(
new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const sendEvent = (data: Record<string, unknown>) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
};
// Send current QR if available
const currentQR = getWhatsAppQR();
if (currentQR) {
sendEvent({ type: 'qr', qr: currentQR });
} else if (isWhatsAppBotRunning()) {
sendEvent({ type: 'authenticated', phone: getWhatsAppBotPhone() });
} else {
sendEvent({ type: 'waiting' });
}
const unsubscribe = subscribeQR((qr, event) => {
if (event === 'qr' && qr) {
sendEvent({ type: 'qr', qr });
} else if (event === 'authenticated') {
sendEvent({ type: 'authenticated', phone: getWhatsAppBotPhone() });
} else if (event === 'disconnected') {
sendEvent({ type: 'disconnected' });
}
});
// Clean up when client disconnects
ctx.req.raw.signal.addEventListener('abort', () => {
unsubscribe();
controller.close();
});
},
}),
{
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
},
);
const qr = getWhatsAppQR();
return ctx.json({
qr,
running: isWhatsAppBotRunning(),
phone: getWhatsAppBotPhone(),
});
});
// ── User: WhatsApp pairing ──