Spaces:
Paused
Paused
refactor: migrate dashboard to /dashboard and implement internal reverse proxy for gateway traffic
Browse filesFiles changed (5)
- Dockerfile+3-1
- README.md+6-5
- health-server.js+211-64
- keep-alive.sh+2-2
- start.sh+7-2
34 unmodified lines35363738394041425 unmodified lines48495051525334 unmodified lines# Copy HuggingClaw filesCOPY --chown=1000:1000 dns-fix.js /opt/dns-fix.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 keep-alive.sh /home/node/app/keep-alive.shCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.sh5 unmodified linesWORKDIR /home/node/appEXPOSE 7860CMD ["/home/node/app/start.sh"]34 unmodified lines353637383940414243445 unmodified lines50515253545534 unmodified lines# Copy HuggingClaw filesCOPY --chown=1000:1000 dns-fix.js /opt/dns-fix.jsCOPY --chown=1000:1000 health-server.js /home/node/app/health-server.jsCOPY --chown=1000:1000 iframe-fix.cjs /home/node/app/iframe-fix.cjsCOPY --chown=1000:1000 start.sh /home/node/app/start.shCOPY --chown=1000:1000 keep-alive.sh /home/node/app/keep-alive.shCOPY --chown=1000:1000 wa-guardian.js /home/node/app/wa-guardian.jsCOPY --chown=1000:1000 workspace-sync.py /home/node/app/workspace-sync.pyRUN chmod +x /home/node/app/start.sh /home/node/app/keep-alive.sh5 unmodified linesWORKDIR /home/node/appEXPOSE 7861CMD ["/home/node/app/start.sh"]
3 unmodified lines4567891084 unmodified lines95969798991001018 unmodified lines11011111211311411511648 unmodified lines16516616716816917017154 unmodified lines2262272282292302312323 unmodified linescolorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: truelicense: mit---84 unmodified linesTo use WhatsApp:1. Visit your Space's Dashboard (Port 7861) and click **π Open Control UI**.2. In the Control UI, go to **Channels** β **WhatsApp** β **Login**.3. Scan the QR code with your phone. π±8 unmodified lines## π Dashboard & MonitoringHuggingClaw now features a beautiful web dashboard. Access it by visiting your Space's URL on port 7861 or the internal health endpoint:- **Uptime Tracking:** Real-time uptime monitoring.- **Sync Status:** Visual indicators for workspace backup operations.48 unmodified lines| Variable | Default | Description ||--------------------|----------|-------------------------------------|| `OPENCLAW_VERSION` | `latest` | Pin a specific OpenClaw version || `HEALTH_PORT` | `7861` | Internal health endpoint port |## π€ LLM Providers54 unmodified lines```bashdocker build -t huggingclaw .docker run -p 7860:7860 --env-file .env huggingclaw```**Without Docker:**3 unmodified lines456789101184 unmodified lines969798991001011028 unmodified lines11111211311411511611748 unmodified lines16616716816917017117254 unmodified lines2272282292302312322333 unmodified linescolorFrom: bluecolorTo: purplesdk: dockerapp_port: 7861base_path: /dashboardpinned: truelicense: mit---84 unmodified linesTo use WhatsApp:1. Visit your Space URL. It opens the dashboard at `/dashboard` by default, then click **Open Control UI**.2. In the Control UI, go to **Channels** β **WhatsApp** β **Login**.3. Scan the QR code with your phone. π±8 unmodified lines## π Dashboard & MonitoringHuggingClaw now features a built-in dashboard at `/dashboard`, served from the same public HF Space URL as the Control UI:- **Uptime Tracking:** Real-time uptime monitoring.- **Sync Status:** Visual indicators for workspace backup operations.48 unmodified lines| Variable | Default | Description ||--------------------|----------|-------------------------------------|| `OPENCLAW_VERSION` | `latest` | Pin a specific OpenClaw version || `HEALTH_PORT` | `7861` | Public dashboard / proxy port on HF Spaces |## π€ LLM Providers54 unmodified lines```bashdocker build -t huggingclaw .docker run -p 7861:7861 --env-file .env huggingclaw```**Without Docker:**
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565714 unmodified lines727374757677783 unmodified lines82838485868788135 unmodified lines22422522622722822923023123223323423523623713 unmodified lines2512522532542552562576 unmodified lines2642652662672682692705 unmodified lines2762772782792802812822832842852862877 unmodified lines2952962972982993003013023033043053063073083093104 unmodified lines315316317318319320321322323324325326327328// Lightweight health server and dashboard on port 7861const http = require("http");const fs = require("fs");const PORT = process.env.HEALTH_PORT || 7861;const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || "huggingclaw";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;const server = http.createServer((req, res) => {const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (req.url === "/health") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "ok",uptime: uptime,uptimeHuman: uptimeHuman,timestamp: new Date().toISOString(),}),);return;}if (req.url === "/status") {let syncStatus = { status: "unknown", message: "No sync data yet" };try {if (fs.existsSync("/tmp/sync-status.json")) {syncStatus = JSON.parse(fs.readFileSync("/tmp/sync-status.json", "utf8"),);}} catch (e) {}res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: true,telegram: TELEGRAM_ENABLED,sync: syncStatus,uptime: uptimeHuman,token: GATEWAY_TOKEN,}),);return;}if (req.url === "/") {res.writeHead(200, { "Content-Type": "text/html" });res.end(`<!DOCTYPE html><html lang="en"><head>14 unmodified lines}* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: 'Outfit', sans-serif;background-color: var(--bg);3 unmodified linesalign-items: center;min-height: 100vh;overflow: hidden;background-image:radial-gradient(at 0% 0%, rgba(59, 130, 246, 0.15) 0px, transparent 50%),radial-gradient(at 100% 0%, rgba(139, 92, 246, 0.15) 0px, transparent 50%);}135 unmodified lines}#sync-msg { color: var(--text); display: block; margin-top: 4px; }</style></head><body><div class="dashboard"><header><h1>π¦ HuggingClaw</h1><p class="subtitle">Space Control Panel</p></header><div class="stats-grid">13 unmodified lines<span class="stat-label">Telegram</span><span id="tg-status">Loading...</span></div><a href="/" class="stat-btn">π Open Control UI</a></div><div class="stat-card" style="width: 100%;">6 unmodified lines</div><div class="footer">• Live updates every 10s •</div></div>5 unmodified linesdocument.getElementById('model-id').textContent = data.model;document.getElementById('uptime').textContent = data.uptime;document.getElementById('wa-status').innerHTML = data.whatsapp? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';document.getElementById('tg-status').innerHTML = data.telegram? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';7 unmodified lines} else if (syncData.status === 'syncing') {badgeClass = 'status-syncing';pulseHtml = '<div class="pulse" style="background:#3b82f6"></div>';} else if (syncData.status === 'error') {badgeClass = 'status-offline';}document.getElementById('sync-badge-container').innerHTML ='<div class="status-badge ' + badgeClass + '">' + pulseHtml + syncData.status.toUpperCase() + '</div>';document.getElementById('sync-time').textContent = syncData.timestamp || 'Never';document.getElementById('sync-msg').textContent = syncData.message || 'Waiting for first sync...';} catch (e) {console.error("Failed to fetch status", e);}4 unmodified lines</script></body></html>`);return;}res.writeHead(404);res.end();});server.listen(PORT, "0.0.0.0", () => {console.log(`π₯ Health server & Dashboard listening on port ${PORT}`);});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666714 unmodified lines828384858687883 unmodified lines92939495969798135 unmodified lines23423523623723823924024124224324424524613 unmodified lines2602612622632642652666 unmodified lines2732742752762772782795 unmodified lines2852862872882892902912922932942952967 unmodified lines3043053063073083093103113123133143153164 unmodified lines321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475// Single public entrypoint for HF Spaces: local dashboard + reverse proxy to OpenClaw.const http = require("http");const fs = require("fs");const net = require("net");const PORT = Number(process.env.HEALTH_PORT || 7861);const GATEWAY_PORT = Number(process.env.GATEWAY_PORT || 7860);const GATEWAY_HOST = "127.0.0.1";const startTime = Date.now();const LLM_MODEL = process.env.LLM_MODEL || "Not Set";const TELEGRAM_ENABLED = !!process.env.TELEGRAM_BOT_TOKEN;function getPathname(url) {try {return new URL(url, "http://localhost").pathname;} catch {return "/";}}function isDashboardRoute(pathname) {return pathname === "/dashboard" || pathname === "/dashboard/";}function isLocalRoute(pathname) {return (pathname === "/health" ||pathname === "/status" ||isDashboardRoute(pathname));}function appendForwarded(existingValue, nextValue) {const cleanNext = nextValue || "";if (!existingValue) return cleanNext;if (Array.isArray(existingValue))return `${existingValue.join(", ")}, ${cleanNext}`;return `${existingValue}, ${cleanNext}`;}function buildProxyHeaders(headers, remoteAddress) {return {...headers,host: headers.host || `${GATEWAY_HOST}:${GATEWAY_PORT}`,"x-forwarded-for": appendForwarded(headers["x-forwarded-for"],remoteAddress,),"x-forwarded-host": headers["x-forwarded-host"] || headers.host || "","x-forwarded-proto": headers["x-forwarded-proto"] || "https",};}function readSyncStatus() {try {if (fs.existsSync("/tmp/sync-status.json")) {return JSON.parse(fs.readFileSync("/tmp/sync-status.json", "utf8"));}} catch {}return { status: "unknown", message: "No sync data yet" };}function renderDashboard() {return `<!DOCTYPE html><html lang="en"><head>14 unmodified lines}* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: 'Outfit', sans-serif;background-color: var(--bg);3 unmodified linesalign-items: center;min-height: 100vh;overflow: hidden;background-image:radial-gradient(at 0% 0%, rgba(59, 130, 246, 0.15) 0px, transparent 50%),radial-gradient(at 100% 0%, rgba(139, 92, 246, 0.15) 0px, transparent 50%);}135 unmodified lines}#sync-msg { color: var(--text); display: block; margin-top: 4px; }</style></head><body><div class="dashboard"><header><h1>π¦ HuggingClaw</h1><p class="subtitle">Space Dashboard</p></header><div class="stats-grid">13 unmodified lines<span class="stat-label">Telegram</span><span id="tg-status">Loading...</span></div><a href="/" class="stat-btn">Open Control UI</a></div><div class="stat-card" style="width: 100%;">6 unmodified lines</div><div class="footer">Live updates every 10s</div></div>5 unmodified linesdocument.getElementById('model-id').textContent = data.model;document.getElementById('uptime').textContent = data.uptime;document.getElementById('wa-status').innerHTML = data.whatsapp? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';document.getElementById('tg-status').innerHTML = data.telegram? '<div class="status-badge status-online"><div class="pulse"></div>Active</div>': '<div class="status-badge status-offline">Disabled</div>';7 unmodified lines} else if (syncData.status === 'syncing') {badgeClass = 'status-syncing';pulseHtml = '<div class="pulse" style="background:#3b82f6"></div>';}document.getElementById('sync-badge-container').innerHTML ='<div class="status-badge ' + badgeClass + '">' + pulseHtml + syncData.status.toUpperCase() + '</div>';document.getElementById('sync-time').textContent = syncData.timestamp || 'Never';document.getElementById('sync-msg').textContent = syncData.message || 'Waiting for first sync...';} catch (e) {console.error("Failed to fetch status", e);}4 unmodified lines</script></body></html>`;}function proxyHttp(req, res) {const proxyReq = http.request({hostname: GATEWAY_HOST,port: GATEWAY_PORT,method: req.method,path: req.url,headers: buildProxyHeaders(req.headers, req.socket.remoteAddress),},(proxyRes) => {res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);proxyRes.pipe(res);},);proxyReq.on("error", (error) => {res.writeHead(502, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "error",message: "Gateway unavailable",detail: error.message,}),);});req.pipe(proxyReq);}function serializeUpgradeHeaders(req, remoteAddress) {const forwardedHeaders = [];for (let i = 0; i < req.rawHeaders.length; i += 2) {const name = req.rawHeaders[i];const value = req.rawHeaders[i + 1];const lower = name.toLowerCase();if (lower === "x-forwarded-for" ||lower === "x-forwarded-host" ||lower === "x-forwarded-proto") {continue;}forwardedHeaders.push(`${name}: ${value}`);}forwardedHeaders.push(`X-Forwarded-For: ${appendForwarded(req.headers["x-forwarded-for"], remoteAddress)}`,);forwardedHeaders.push(`X-Forwarded-Host: ${req.headers["x-forwarded-host"] || req.headers.host || ""}`,);forwardedHeaders.push(`X-Forwarded-Proto: ${req.headers["x-forwarded-proto"] || "https"}`,);return forwardedHeaders;}function proxyUpgrade(req, socket, head) {const proxySocket = net.connect(GATEWAY_PORT, GATEWAY_HOST);proxySocket.on("connect", () => {const requestLines = [`${req.method} ${req.url} HTTP/${req.httpVersion}`,...serializeUpgradeHeaders(req, req.socket.remoteAddress),"","",];proxySocket.write(requestLines.join("\r\n"));if (head && head.length > 0) {proxySocket.write(head);}socket.pipe(proxySocket).pipe(socket);});proxySocket.on("error", () => {if (socket.writable) {socket.write("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");}socket.destroy();});socket.on("error", () => {proxySocket.destroy();});}const server = http.createServer((req, res) => {const pathname = getPathname(req.url || "/");const uptime = Math.floor((Date.now() - startTime) / 1000);const uptimeHuman = `${Math.floor(uptime / 3600)}h ${Math.floor((uptime % 3600) / 60)}m`;if (pathname === "/health") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({status: "ok",uptime,uptimeHuman,timestamp: new Date().toISOString(),}),);return;}if (pathname === "/status") {res.writeHead(200, { "Content-Type": "application/json" });res.end(JSON.stringify({model: LLM_MODEL,whatsapp: true,telegram: TELEGRAM_ENABLED,sync: readSyncStatus(),uptime: uptimeHuman,}),);return;}if (isDashboardRoute(pathname)) {res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });res.end(renderDashboard());return;}proxyHttp(req, res);});server.on("upgrade", (req, socket, head) => {const pathname = getPathname(req.url || "/");if (isLocalRoute(pathname)) {socket.destroy();return;}proxyUpgrade(req, socket, head);});server.listen(PORT, "0.0.0.0", () => {console.log(`Health server listening on port ${PORT}; proxying gateway traffic to ${GATEWAY_HOST}:${GATEWAY_PORT}`,);});
17 unmodified lines181920212223242517 unmodified linesexit 0fi# Ping the Space URL β any HTTP response (even 404) counts as activityPING_URL="https://${SPACE_HOST}"echo "π Keep-alive started: pinging ${PING_URL} every ${INTERVAL}s"17 unmodified lines181920212223242517 unmodified linesexit 0fi# Ping the health endpoint so we keep the Space warm without touching the gatewayPING_URL="https://${SPACE_HOST}/health"echo "π Keep-alive started: pinging ${PING_URL} every ${INTERVAL}s"
270 unmodified lines27127227327427527648 unmodified lines325326327328329330331332333334335336270 unmodified linesif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"elseprintf " β %-40s β\n" "Keep-alive: βΈοΈ local mode"fi48 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!# 11. Start WhatsApp Guardian (Automates pairing)node /home/node/app/wa-guardian.js &GUARDIAN_PID=$!echo "π‘οΈ WhatsApp Guardian started (PID: $GUARDIAN_PID)"# 12. Start Workspace Syncpython3 -u /home/node/app/workspace-sync.py &# ββ Launch gateway ββ270 unmodified lines27127227327427527627748 unmodified lines326327328329330331332333334335336337338339340341270 unmodified linesif [ -n "$SPACE_HOST" ]; thenprintf " β %-40s β\n" "Keep-alive: β every ${KEEP_ALIVE_INTERVAL:-300}s"printf " β %-40s β\n" "Control UI: https://${SPACE_HOST}"printf " β %-40s β\n" "Dashboard: https://${SPACE_HOST}/dashboard"elseprintf " β %-40s β\n" "Keep-alive: βΈοΈ local mode"fi48 unmodified linesnode /home/node/app/health-server.js &HEALTH_PID=$!# 11. Start HF keep-alive/home/node/app/keep-alive.sh &KEEP_ALIVE_PID=$!# 12. Start WhatsApp Guardian (Automates pairing)node /home/node/app/wa-guardian.js &GUARDIAN_PID=$!echo "π‘οΈ WhatsApp Guardian started (PID: $GUARDIAN_PID)"# 13. Start Workspace Syncpython3 -u /home/node/app/workspace-sync.py &# ββ Launch gateway ββ
Dockerfile+3-1
README.md+6-5
health-server.js+211-64
keep-alive.sh+2-2
start.sh+7-2