Transaltor / hub.html
Aichatbot12321's picture
Upload 2 files
2e5a181 verified
Raw History Blame Contribute Delete
89.8 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>HF Space Commander β€” AI PRO SUITE</title> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet"> <style> :root { --bg-main: #070b14; --bg-card: #0f172a; --bg-elevated: #1e293b; --bg-input: #090d16; --primary: #f59e0b; --primary-hover: #d97706; --accent: #38bdf8; --success: #10b981; --danger: #ef4444; --warning: #f59e0b; --purple: #8b5cf6; --text-main: #f8fafc; --text-muted: #94a3b8; --border-light: rgba(148, 163, 184, 0.18); --border-focus: rgba(245, 158, 11, 0.65); --shadow-lg: 0 16px 40px rgba(0, 0, 0, 0.55); } * { box-sizing: border-box; margin: 0; padding: 0; } body { background: radial-gradient(circle at 15% 0%, rgba(245, 158, 11, 0.10), transparent 35%), radial-gradient(circle at 85% 10%, rgba(56, 189, 248, 0.10), transparent 40%), var(--bg-main); color: var(--text-main); font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; min-height: 100vh; overflow-x: hidden; } /* OTP SECURITY GATE SCREEN */ .auth-gate-screen { position: fixed; inset: 0; z-index: 5000; background: radial-gradient(circle at 50% 20%, rgba(245, 158, 11, 0.14), rgba(7, 11, 20, 0.98) 65%); backdrop-filter: blur(18px); display: flex; align-items: center; justify-content: center; padding: 20px; } .auth-gate-card { background: linear-gradient(160deg, #0f172a 0%, #090d16 100%); border: 1px solid rgba(245, 158, 11, 0.35); border-radius: 22px; max-width: 440px; width: 100%; padding: 32px 26px; box-shadow: 0 24px 60px rgba(0, 0, 0, 0.75); text-align: center; } .shield-badge { width: 64px; height: 64px; border-radius: 18px; background: linear-gradient(135deg, rgba(245, 158, 11, 0.2), rgba(239, 68, 68, 0.2)); border: 1px solid rgba(245, 158, 11, 0.45); display: flex; align-items: center; justify-content: center; font-size: 30px; margin: 0 auto 16px; } .otp-single-input { width: 100% !important; height: 60px; margin: 14px 0 18px; text-align: center; font-size: 28px !important; font-weight: 900; letter-spacing: 14px; padding-left: 20px !important; font-family: 'JetBrains Mono', monospace; background: #050811 !important; border: 2px solid rgba(245, 158, 11, 0.45) !important; border-radius: 14px !important; color: #fbbf24 !important; transition: all 0.18s; } .otp-single-input:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.22); } /* TOPBAR */ .topbar { position: sticky; top: 0; z-index: 100; display: flex; align-items: center; gap: 12px; padding: 12px 20px; background: rgba(15, 23, 42, 0.88); backdrop-filter: blur(14px); border-bottom: 1px solid var(--border-light); flex-wrap: wrap; } .menuBtn { width: 38px; height: 38px; border-radius: 10px; background: var(--bg-elevated); border: 1px solid var(--border-light); color: var(--text-main); display: flex; align-items: center; justify-content: center; font-size: 18px; cursor: pointer; transition: all 0.2s ease; user-select: none; } .menuBtn:hover { border-color: var(--primary); color: var(--primary); } .appTitle { font-weight: 900; font-size: 16px; letter-spacing: 0.6px; display: flex; align-items: center; gap: 8px; background: linear-gradient(90deg, #fbbf24, #f97316, #38bdf8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .topbar-right { margin-left: auto; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .status-badge { display: inline-flex; align-items: center; gap: 7px; background: var(--bg-input); border: 1px solid var(--border-light); padding: 6px 14px; border-radius: 999px; font-size: 12px; font-weight: 800; color: var(--text-muted); letter-spacing: 0.4px; } .status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-muted); display: inline-block; } .status-dot.pulse { animation: pulseAnim 1.6s infinite; } @keyframes pulseAnim { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.35); opacity: 0.55; } } /* MAIN PAGE LAYOUT */ .page { max-width: 1400px; margin: 0 auto; padding: 20px 16px 48px; display: none; flex-direction: column; gap: 20px; } .page.unlocked { display: flex; } /* HERO METRICS BAR */ .hero-banner { background: linear-gradient(135deg, rgba(30, 41, 59, 0.85), rgba(15, 23, 42, 0.95)); border: 1px solid var(--border-light); border-radius: 18px; padding: 18px 22px; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 16px; box-shadow: var(--shadow-lg); } .hero-title-wrap h1 { font-size: 22px; font-weight: 900; letter-spacing: -0.3px; margin-bottom: 4px; } .hero-title-wrap p { color: var(--text-muted); font-size: 13px; font-family: 'JetBrains Mono', monospace; } .metrics-row { display: flex; flex-wrap: wrap; gap: 10px; } .metric-chip { background: rgba(9, 13, 22, 0.75); border: 1px solid var(--border-light); border-radius: 12px; padding: 8px 14px; min-width: 115px; } .metric-chip .m-label { font-size: 10px; font-weight: 700; text-transform: uppercase; color: var(--text-muted); letter-spacing: 0.6px; } .metric-chip .m-val { font-size: 13px; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace; margin-top: 2px; } /* NAVIGATION TABS */ .nav-tabs { display: flex; gap: 8px; background: var(--bg-card); padding: 6px; border-radius: 14px; border: 1px solid var(--border-light); overflow-x: auto; } .nav-tab { flex: 1; min-width: 150px; padding: 11px 16px; border-radius: 10px; border: none; background: transparent; color: var(--text-muted); font-weight: 800; font-size: 13px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all 0.2s; white-space: nowrap; } .nav-tab:hover { color: var(--text-main); background: rgba(255, 255, 255, 0.04); } .nav-tab.active { background: linear-gradient(135deg, #f59e0b, #ea580c); color: #fff; box-shadow: 0 4px 15px rgba(245, 158, 11, 0.35); } /* GRID & CARDS */ .grid-2 { display: grid; grid-template-columns: 380px 1fr; gap: 20px; } @media (max-width: 980px) { .grid-2 { grid-template-columns: 1fr; } } .card { background: var(--bg-card); border: 1px solid var(--border-light); border-radius: 18px; padding: 20px; box-shadow: var(--shadow-lg); } .card-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid var(--border-light); } .card-title { font-size: 15px; font-weight: 800; color: var(--text-main); display: flex; align-items: center; gap: 8px; } /* INPUTS */ .hf-input-group { margin-bottom: 14px; } .hf-label { font-size: 11px; font-weight: 800; color: var(--text-muted); text-transform: uppercase; margin-bottom: 6px; display: flex; align-items: center; justify-content: space-between; letter-spacing: 0.7px; } input[type="text"], select, textarea { width: 100%; background: var(--bg-input); border: 1px solid var(--border-light); color: var(--text-main); padding: 10px 13px; border-radius: 10px; font-size: 13px; font-family: 'JetBrains Mono', monospace; outline: none; transition: border-color 0.2s; } input:focus, select:focus, textarea:focus { border-color: var(--primary); } /* BUTTONS */ .btn { border: none; border-radius: 11px; padding: 11px 16px; font-size: 13px; font-weight: 800; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; transition: all 0.18s ease; color: #fff; text-decoration: none; } .btn:disabled { opacity: 0.5; cursor: not-allowed; } .btn:active:not(:disabled) { transform: scale(0.98); } .btn.green { background: linear-gradient(135deg, #10b981, #059669); box-shadow: 0 4px 14px rgba(16, 185, 129, 0.28); } .btn.amber { background: linear-gradient(135deg, #f59e0b, #d97706); box-shadow: 0 4px 14px rgba(245, 158, 11, 0.28); } .btn.red { background: linear-gradient(135deg, #ef4444, #dc2626); box-shadow: 0 4px 14px rgba(239, 68, 68, 0.28); } .btn.blue { background: linear-gradient(135deg, #3b82f6, #2563eb); box-shadow: 0 4px 14px rgba(59, 130, 246, 0.28); } .btn.purple { background: linear-gradient(135deg, #8b5cf6, #6d28d9); box-shadow: 0 4px 14px rgba(139, 92, 246, 0.28); } .btn.ghost { background: var(--bg-elevated); border: 1px solid var(--border-light); color: var(--text-main); box-shadow: none; } .btn.ghost:hover { border-color: var(--primary); color: var(--primary); } .btn-sm { padding: 6px 11px; font-size: 11px; border-radius: 8px; } .lifecycle-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 12px; } /* TERMINAL / LOGS */ .terminal-toolbar { background: #162032; padding: 10px 16px; border-bottom: 1px solid var(--border-light); display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; } .log-mode-pills { display: flex; gap: 6px; flex-wrap: wrap; } .log-pill { padding: 5px 11px; border-radius: 8px; font-size: 11px; font-weight: 700; background: rgba(255, 255, 255, 0.05); border: 1px solid var(--border-light); color: var(--text-muted); cursor: pointer; } .log-pill.active { background: rgba(56, 189, 248, 0.16); border-color: #38bdf8; color: #38bdf8; } .terminal-window { background: #050811; padding: 16px; height: 490px; overflow-y: auto; font-family: 'JetBrains Mono', monospace; color: #cbd5e1; font-size: 12.5px; line-height: 1.55; white-space: pre-wrap; word-break: break-word; } .terminal-line { padding: 3px 6px; border-radius: 5px; margin-bottom: 3px; } .terminal-line:hover { background: rgba(255, 255, 255, 0.03); } .terminal-time { color: #64748b; margin-right: 8px; user-select: none; } .terminal-error { color: #f87171; background: rgba(239, 68, 68, 0.07); } .terminal-success { color: #34d399; } .terminal-warning { color: #fbbf24; } .terminal-info { color: #38bdf8; } /* FILE EXPLORER & EDITOR */ .files-layout { display: grid; grid-template-columns: 330px 1fr; gap: 18px; min-height: 600px; } @media (max-width: 980px) { .files-layout { grid-template-columns: 1fr; } } .file-list-box { background: var(--bg-input); border: 1px solid var(--border-light); border-radius: 12px; height: 470px; overflow-y: auto; padding: 6px; } .file-row { display: flex; align-items: center; justify-content: space-between; padding: 9px 11px; border-radius: 9px; cursor: pointer; font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--text-main); margin-bottom: 3px; border: 1px solid transparent; transition: all 0.15s; } .file-row:hover { background: rgba(255, 255, 255, 0.05); border-color: var(--border-light); } .file-row.active { background: rgba(245, 158, 11, 0.15); border-color: var(--primary); color: #fbbf24; font-weight: 700; } .file-meta { display: flex; align-items: center; gap: 6px; font-size: 10px; color: var(--text-muted); } .badge-mini { padding: 2px 6px; border-radius: 5px; font-size: 9px; font-weight: 800; background: rgba(56, 189, 248, 0.15); color: #38bdf8; } .quick-files-bar { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; } .quick-chip { padding: 4px 9px; border-radius: 7px; background: var(--bg-elevated); border: 1px solid var(--border-light); color: var(--text-main); font-family: 'JetBrains Mono', monospace; font-size: 11px; cursor: pointer; } .quick-chip:hover { border-color: var(--primary); color: var(--primary); } .editor-container { display: flex; flex-direction: column; height: 100%; gap: 10px; } .code-editor-area { width: 100%; flex: 1; min-height: 440px; background: #050811; color: #e2e8f0; border: 1px solid var(--border-light); border-radius: 12px; padding: 14px; font-family: 'JetBrains Mono', monospace; font-size: 12.5px; line-height: 1.55; resize: vertical; tab-size: 4; white-space: pre; overflow: auto; } /* UPLOAD DROPZONE */ .dropzone { border: 2px dashed rgba(56, 189, 248, 0.45); background: rgba(15, 23, 42, 0.6); border-radius: 16px; padding: 36px 20px; text-align: center; cursor: pointer; transition: all 0.2s; } .dropzone:hover, .dropzone.dragover { border-color: var(--primary); background: rgba(245, 158, 11, 0.08); } .upload-queue-item { display: flex; align-items: center; justify-content: space-between; background: var(--bg-input); border: 1px solid var(--border-light); padding: 10px 14px; border-radius: 10px; margin-bottom: 8px; font-family: 'JetBrains Mono', monospace; font-size: 12px; } /* MODAL & TOAST */ .modal-backdrop { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.72); backdrop-filter: blur(5px); z-index: 9999; display: none; align-items: center; justify-content: center; padding: 16px; } .modal-card { background: var(--bg-card); border: 1px solid var(--border-light); border-radius: 16px; max-width: 460px; width: 100%; padding: 22px; box-shadow: var(--shadow-lg); } .toast-box { position: fixed; bottom: 22px; right: 22px; z-index: 10000; display: flex; flex-direction: column; gap: 8px; max-width: 380px; } .toast-item { background: #1e293b; border-left: 4px solid var(--primary); color: #fff; padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 600; box-shadow: var(--shadow-lg); animation: slideIn 0.2s ease; } @keyframes slideIn { from { transform: translateY(15px); opacity: 0; } to { transform: translateY(0); opacity: 1; } } /* SLIDE-OUT SUITE DRAWER */ .suite-drawer-backdrop { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6); z-index: 900; display: none; } .suite-drawer { position: fixed; top: 0; left: -290px; width: 280px; height: 100vh; background: var(--bg-card); border-right: 1px solid var(--border-light); z-index: 901; padding: 20px; transition: left 0.25s ease; display: flex; flex-direction: column; gap: 8px; } .suite-drawer.open { left: 0; } .drawer-link { padding: 10px 12px; border-radius: 10px; color: var(--text-main); text-decoration: none; font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 10px; background: rgba(255, 255, 255, 0.03); border: 1px solid transparent; } .drawer-link:hover { border-color: var(--primary); color: var(--primary); } .tab-panel { display: none; } .tab-panel.active { display: block; } </style> </head> <body> <!-- ======================================================================= --> <!-- πŸ”’ FIRST-TIME 6-DIGIT OTP SECURITY GATE (ZERO PERSONAL DETAILS SHOWN) --> <!-- ======================================================================= --> <div id="otpGateScreen" class="auth-gate-screen"> <div class="auth-gate-card"> <div class="shield-badge">πŸ”</div> <h2 style="font-size:20px; font-weight:900; margin-bottom:6px; color:#f8fafc;"> Server Security Verification </h2> <p style="font-size:13px; color:var(--text-muted); line-height:1.5; margin-bottom:18px;"> First-time device verification is required to access the Server Control Center. Request a 6-digit OTP to your registered admin device. </p> <button id="sendOtpBtn" class="btn amber" style="width:100%; margin-bottom:14px;" onclick="requestAdminOtp()"> πŸ“² Send 6-Digit Verification OTP </button> <div id="otpEntrySection" style="margin-top:8px;"> <div style="font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.8px;"> Enter 6-Digit Verification Code </div> <input type="text" id="otpSingleInput" class="otp-single-input" maxlength="6" inputmode="numeric" autocomplete="one-time-code" placeholder="β€’β€’β€’β€’β€’β€’" oninput="onSingleOtpInput(event)" onkeydown="onSingleOtpKeydown(event)" > <button id="verifyOtpBtn" class="btn green" style="width:100%;" onclick="verifyAdminOtpCode()"> βœ… Verify OTP & Save Trusted Device Cookie </button> </div> <div id="otpStatusMsg" style="margin-top:14px; font-size:12px; font-family:'JetBrains Mono',monospace; color:var(--text-muted); min-height:18px;"> Checking existing security session cookie... </div> </div> </div> <!-- SUITE SIDEBAR DRAWER --> <div id="suiteDrawerBackdrop" class="suite-drawer-backdrop" onclick="apsToggleSidebar()"></div> <div id="suiteDrawer" class="suite-drawer"> <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;"> <span style="font-weight:900; color:var(--primary); font-size:15px;">⚑ AI PRO SUITE</span> <button class="btn ghost btn-sm" onclick="apsToggleSidebar()">βœ•</button> </div> <a class="drawer-link" href="#panel-lifecycle" onclick="switchCommanderTab('lifecycle'); apsToggleSidebar(); return false;">πŸŽ›οΈ Lifecycle & Server Logs</a> <a class="drawer-link" href="#panel-editor" onclick="switchCommanderTab('editor'); apsToggleSidebar(); return false;">πŸ“ Edit Space & Server Files</a> <a class="drawer-link" href="#panel-upload" onclick="switchCommanderTab('upload'); apsToggleSidebar(); return false;">πŸ“€ Upload Files to Space</a> <div style="margin-top:auto; padding-top:12px; border-top:1px solid var(--border-light); font-size:11px; color:var(--text-muted);"> Security Mode:<br> <strong style="color:var(--success);">πŸ”’ Private Vault Active</strong> </div> </div> <!-- TOPBAR --> <div class="topbar"> <div class="menuBtn" onclick="apsToggleSidebar()" title="Menu">☰</div> <div class="appTitle">πŸš€ HF SPACE COMMANDER</div> <div class="topbar-right"> <div id="tokenModeBadge" class="status-badge" style="color:#10b981; border-color:rgba(16,185,129,0.35);"> πŸ”’ Vault Protected (Details Hidden) </div> <div id="spaceStatusBadge" class="status-badge"> <span id="statusDot" class="status-dot"></span> <span id="statusText">Status: LOCKED</span> </div> <button class="btn ghost btn-sm" onclick="lockAndRevokeSession()" title="Lock session & clear cookie"> πŸ”’ Lock </button> </div> </div> <div id="commanderMainPage" class="page"> <!-- HERO BANNER & LIVE METRICS --> <div class="hero-banner"> <div class="hero-title-wrap"> <h1>Hugging Face Space & Server Control Center</h1> <p>πŸ”’ Connected to Private Hugging Face Space (All Personal Details & Tokens Hidden)</p> </div> <div class="metrics-row"> <div class="metric-chip"> <div class="m-label">HF Container Stage</div> <div class="m-val" id="metricStage">β€”</div> </div> <div class="metric-chip"> <div class="m-label">Server Traffic Mode</div> <div class="m-val" id="metricStandby">ACTIVE</div> </div> <div class="metric-chip"> <div class="m-label">Hardware Tier</div> <div class="m-val" id="metricHardware">cpu-basic</div> </div> <div class="metric-chip"> <div class="m-label">Server Uptime / RAM</div> <div class="m-val" id="metricUptime">β€”</div> </div> <div class="metric-chip"> <div class="m-label">Latest Commit SHA</div> <div class="m-val" id="metricSha">β€”</div> </div> </div> </div> <!-- MAIN NAVIGATION TABS --> <div class="nav-tabs"> <button id="tabBtn-lifecycle" class="nav-tab active" onclick="switchCommanderTab('lifecycle')"> πŸŽ›οΈ Control Server & Live Logs </button> <button id="tabBtn-editor" class="nav-tab" onclick="switchCommanderTab('editor')"> πŸ“ Browse & Edit Files (<span id="fileCountBadge">0</span>) </button> <button id="tabBtn-upload" class="nav-tab" onclick="switchCommanderTab('upload')"> πŸ“€ Upload Files to Space </button> </div> <!-- ======================================================================= --> <!-- TAB 1: LIFECYCLE CONTROL & LIVE LOGS --> <!-- ======================================================================= --> <div id="panel-lifecycle" class="tab-panel active"> <div class="grid-2"> <!-- LEFT: LIFECYCLE CONTROLS (ALL PERSONAL DETAILS & TOKENS HIDDEN) --> <div class="card" style="display:flex; flex-direction:column; gap:14px;"> <div class="card-header"> <div class="card-title">βš™οΈ Server & Security Control</div> <button class="btn ghost btn-sm" onclick="checkSpaceStatus()">πŸ”„ Refresh</button> </div> <div style="background:rgba(16,185,129,0.08); border:1px solid rgba(16,185,129,0.3); border-radius:12px; padding:12px; display:flex; align-items:center; gap:10px;"> <span style="font-size:20px;">πŸ›‘οΈ</span> <div style="font-size:12px; line-height:1.45;"> <strong style="color:#34d399; display:block;">Private Vault & Zero-Leak Protection Active</strong> <span style="color:var(--text-muted); font-size:11px;">Tokens, phone numbers, and account identifiers are strictly hidden on the server.</span> </div> </div> <div style="border-top:1px solid var(--border-light); padding-top:12px;"> <div class="hf-label" style="margin-bottom:10px;"> <span>πŸš€ Container & Server Lifecycle Controls</span> <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer; text-transform:none;"> <input type="checkbox" id="autoPollStatus" checked onchange="toggleAutoPoll()"> Auto-sync (10s) </label> </div> <div class="lifecycle-grid"> <button class="btn green" onclick="executeSpaceAction('start')"> ▢️ START / WAKE </button> <button class="btn amber" onclick="executeSpaceAction('pause')"> ⏸️ PAUSE SPACE </button> <button class="btn red" onclick="executeSpaceAction('stop')"> πŸ›‘ STOP SERVER </button> <button class="btn purple" onclick="executeSpaceAction('restart')"> πŸ”„ RESTART SPACE </button> </div> <div style="display:flex; gap:8px; margin-top:10px;"> <button class="btn ghost" style="flex:1; font-size:12px;" onclick="executeSpaceAction('factory-reboot')"> πŸ› οΈ Factory Reboot (Rebuild Image) </button> <button class="btn blue" style="flex:1; font-size:12px;" onclick="checkSpaceStatus()"> πŸ“‘ Check Live Status </button> </div> </div> <!-- INSTANT SERVER STANDBY / TRAFFIC GATE --> <div style="background:rgba(9,13,22,0.75); border:1px solid var(--border-light); border-radius:12px; padding:12px;"> <div style="font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase; margin-bottom:8px;"> ⚑ Instant Traffic Gate (Keep hub.html Online) </div> <div style="display:flex; gap:8px; flex-wrap:wrap;"> <button class="btn ghost btn-sm" style="flex:1;" onclick="executeSpaceAction('standby-resume')"> βœ… Stand / Active </button> <button class="btn ghost btn-sm" style="flex:1;" onclick="executeSpaceAction('standby-pause')"> ⏸️ Soft Pause APIs </button> <button class="btn ghost btn-sm" style="flex:1;" onclick="executeSpaceAction('standby-stop')"> πŸ›‘ Soft Stop APIs </button> </div> </div> </div> <!-- RIGHT: LIVE SERVER & HUGGING FACE CONTAINER LOGS --> <div class="card" style="padding:0; overflow:hidden; display:flex; flex-direction:column;"> <div class="terminal-toolbar"> <div class="log-mode-pills"> <button id="logTab-server" class="log-pill active" onclick="switchLogSource('server')"> ⚑ Live Server Logs (server.js) </button> <button id="logTab-run" class="log-pill" onclick="switchLogSource('run')"> 🐳 HF Container Logs (Run) </button> <button id="logTab-build" class="log-pill" onclick="switchLogSource('build')"> πŸ”¨ HF Build Logs </button> </div> <div style="display:flex; align-items:center; gap:6px; flex-wrap:wrap;"> <input type="text" id="logSearchInput" placeholder="Filter logs..." style="width:140px; padding:5px 9px; font-size:11px;" oninput="renderFilteredLogs()"> <button class="btn ghost btn-sm" onclick="refreshCurrentLogs()">πŸ”„ Fetch</button> <button class="btn ghost btn-sm" onclick="copyAllLogs()">πŸ“‹ Copy</button> <button class="btn ghost btn-sm" onclick="downloadLogsFile()">⬇️ .log</button> <button class="btn ghost btn-sm" onclick="clearTerminal()">🧹 Clear</button> </div> </div> <div id="terminalOutput" class="terminal-window"></div> <div style="background:#0b111e; padding:8px 16px; border-top:1px solid var(--border-light); display:flex; justify-content:space-between; align-items:center; font-size:11px; color:var(--text-muted);"> <span id="logStreamStatus">🟒 Live SSE log stream connected</span> <label style="display:inline-flex; align-items:center; gap:6px; cursor:pointer;"> <input type="checkbox" id="autoScrollLogs" checked> Auto-scroll to bottom </label> </div> </div> </div> </div> <!-- ======================================================================= --> <!-- TAB 2: FILE MANAGER & LIVE CODE EDITOR --> <!-- ======================================================================= --> <div id="panel-editor" class="tab-panel"> <div class="card"> <div class="card-header"> <div class="card-title"> πŸ“ Repository & Server File Editor <span style="font-size:11px; color:var(--text-muted); font-weight:500;">(Edits commit directly to Hugging Face Space & sync to live server)</span> </div> <div style="display:flex; gap:8px; flex-wrap:wrap;"> <button class="btn ghost btn-sm" onclick="openNewFileModal()">βž• New File</button> <button class="btn blue btn-sm" onclick="loadRepositoryFiles()">πŸ”„ Reload File List</button> </div> </div> <!-- QUICK ACCESS FILES --> <div class="quick-files-bar"> <span style="font-size:11px; color:var(--text-muted); font-weight:700; align-self:center; margin-right:4px;">Quick Open:</span> <button class="quick-chip" onclick="openFileInEditor('server.js')">πŸ“„ server.js</button> <button class="quick-chip" onclick="openFileInEditor('hub.html')">πŸŽ›οΈ hub.html</button> <button class="quick-chip" onclick="openFileInEditor('index.html')">🏠 index.html</button> <button class="quick-chip" onclick="openFileInEditor('search.html')">πŸ” search.html</button> <button class="quick-chip" onclick="openFileInEditor('package.json')">πŸ“¦ package.json</button> <button class="quick-chip" onclick="openFileInEditor('Dockerfile')">🐳 Dockerfile</button> <button class="quick-chip" onclick="openFileInEditor('README.md')">πŸ“˜ README.md</button> </div> <div class="files-layout"> <!-- LEFT: FILE LIST --> <div style="display:flex; flex-direction:column; gap:8px;"> <input type="text" id="fileFilterInput" placeholder="πŸ” Search files in Space..." oninput="renderFileList()"> <div id="fileListContainer" class="file-list-box"> <div style="padding:20px; text-align:center; color:var(--text-muted); font-size:12px;"> Loading repository files... </div> </div> </div> <!-- RIGHT: CODE EDITOR --> <div class="editor-container"> <div style="display:flex; flex-wrap:wrap; gap:8px; align-items:center; justify-content:space-between; background:var(--bg-input); padding:10px 14px; border-radius:11px; border:1px solid var(--border-light);"> <div style="display:flex; align-items:center; gap:10px; flex:1; min-width:220px;"> <span style="font-size:12px; font-weight:800; color:var(--primary);">FILE:</span> <input type="text" id="currentEditorPath" placeholder="Select a file or type path (e.g. server.js)" style="max-width:340px; padding:6px 10px;"> <span id="editorFileMeta" style="font-size:11px; color:var(--text-muted); font-family:'JetBrains Mono',monospace;"></span> </div> <div style="display:flex; gap:6px; flex-wrap:wrap;"> <button class="btn ghost btn-sm" onclick="toggleEditorWrap()">↩️ Wrap</button> <button class="btn ghost btn-sm" onclick="downloadCurrentEditorFile()">⬇️ Download</button> <button class="btn red btn-sm" onclick="confirmDeleteCurrentFile()">πŸ—‘οΈ Delete</button> <button class="btn green btn-sm" id="saveFileBtn" onclick="saveCurrentFileToSpace()">πŸ’Ύ Save & Commit to HF</button> </div> </div> <!-- COMMIT MESSAGE & SYNC OPTIONS --> <div style="display:flex; flex-wrap:wrap; gap:10px; align-items:center;"> <input type="text" id="editorCommitMsg" placeholder="Commit message (e.g. Update server.js via HF Space Commander)" style="flex:1; min-width:240px; padding:8px 12px; font-size:12px;"> <label style="font-size:12px; color:var(--text-muted); display:inline-flex; align-items:center; gap:5px; cursor:pointer;"> <input type="checkbox" id="chkCommitHf" checked> Commit to HF Space Repo </label> <label style="font-size:12px; color:var(--text-muted); display:inline-flex; align-items:center; gap:5px; cursor:pointer;"> <input type="checkbox" id="chkSaveLocal" checked> Hot-Save on Running Server </label> </div> <textarea id="codeEditorTextarea" class="code-editor-area" spellcheck="false" placeholder="Click any file on the left (such as server.js or hub.html) to view and edit its source code..."></textarea> </div> </div> </div> </div> <!-- ======================================================================= --> <!-- TAB 3: UPLOAD FILES TO HUGGING FACE SPACE --> <!-- ======================================================================= --> <div id="panel-upload" class="tab-panel"> <div class="card"> <div class="card-header"> <div class="card-title">πŸ“€ Upload & Commit Files to Hugging Face Space</div> <button class="btn ghost btn-sm" onclick="clearUploadQueue()">🧹 Clear Queue</button> </div> <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap:14px; margin-bottom:16px;"> <div> <label class="hf-label">Target Folder Prefix in Space (Optional)</label> <input type="text" id="uploadFolderPrefix" placeholder="Leave empty for root / or e.g. public/"> </div> <div> <label class="hf-label">Git Commit Summary</label> <input type="text" id="uploadCommitMessage" value="Upload files via HF Space Commander"> </div> </div> <div id="uploadDropzone" class="dropzone" onclick="document.getElementById('fileUploadInput').click()"> <input type="file" id="fileUploadInput" multiple style="display:none" onchange="handleFileInputSelect(event)"> <div style="font-size:38px; margin-bottom:10px;">☁️</div> <div style="font-size:16px; font-weight:800; color:var(--text-main); margin-bottom:6px;"> Click to Select Files or Drag & Drop Here </div> <div style="font-size:12px; color:var(--text-muted);"> Supports code (.js, .html, .css, .py, .json), configs (Dockerfile), images, audio, and archives β€” commits directly to your configured Space </div> </div> <div id="uploadQueueContainer" style="margin-top:18px;"></div> <div style="margin-top:16px; display:flex; justify-content:flex-end; gap:10px;"> <button class="btn green" id="uploadCommitBtn" onclick="uploadQueuedFilesToSpace()" disabled> πŸš€ Upload & Commit Queued Files (0) </button> </div> </div> </div> </div> <!-- MODAL FOR NEW FILE / DELETE CONFIRMATION --> <div id="commanderModal" class="modal-backdrop"> <div class="modal-card"> <h3 id="modalTitle" style="font-size:16px; font-weight:800; margin-bottom:10px; color:var(--primary);">Modal</h3> <div id="modalBody" style="font-size:13px; color:var(--text-muted); margin-bottom:18px;"></div> <div style="display:flex; justify-content:flex-end; gap:10px;"> <button class="btn ghost btn-sm" onclick="closeCommanderModal()">Cancel</button> <button id="modalConfirmBtn" class="btn green btn-sm">Confirm</button> </div> </div> </div> <!-- TOAST NOTIFICATIONS --> <div id="toastContainer" class="toast-box"></div> <script> // ===================================================================== // STATE & SECURITY SESSION (ZERO PERSONAL DETAILS OR TOKENS IN CLIENT) // ===================================================================== const HF_SERVER_BASE = "/api" + "/hf"; let isSessionUnlocked = false; let latestOtpChallengeToken = ""; let currentLogMode = "server"; // 'server' | 'run' | 'build' let allLogEntries = []; let repoFilesList = []; let uploadQueue = []; let sseLogSource = null; let autoPollTimer = null; function callServerHf(subpath, opts = {}) { const merged = Object.assign({ credentials: "include" }, opts); return fetch(HF_SERVER_BASE + subpath, merged); } function setPersistentAuthCookie(name, val, days = 365) { try { const d = new Date(); d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000)); const sec = location.protocol === "https:" ? ";SameSite=None;Secure" : ";SameSite=Lax"; document.cookie = `${name}=${encodeURIComponent(val)};expires=${d.toUTCString()};path=/${sec}`; } catch (e) {} } function getSavedSessionToken() { try { const s = localStorage.getItem("hf_cmd_session_hdr"); if (s) return s; } catch (e) {} try { const m = document.cookie.match(/(?:^|;\s*)hf_cmd_client_session=([^;]+)/); if (m) return decodeURIComponent(m[1]); } catch (e) {} return ""; } function showToast(msg, type = "info") { const box = document.getElementById("toastContainer"); if (!box) return; const el = document.createElement("div"); el.className = "toast-item"; if (type === "error") el.style.borderLeftColor = "#ef4444"; else if (type === "success") el.style.borderLeftColor = "#10b981"; else if (type === "warning") el.style.borderLeftColor = "#f59e0b"; else el.style.borderLeftColor = "#38bdf8"; el.textContent = msg; box.appendChild(el); setTimeout(() => { try { el.remove(); } catch (e) {} }, 4200); } // ===================================================================== // πŸ”’ 6-DIGIT OTP GATE LOGIC (SINGLE ROCK-SOLID INPUT + STATELESS TOKEN) // ===================================================================== function onSingleOtpInput(ev) { const inp = ev.target; const cleaned = String(inp.value || "").replace(/\D/g, "").slice(0, 6); if (inp.value !== cleaned) inp.value = cleaned; } function onSingleOtpKeydown(ev) { if (ev.key === "Enter") { ev.preventDefault(); verifyAdminOtpCode(); } } function collectEnteredOtp() { const inp = document.getElementById("otpSingleInput"); return String(inp ? inp.value : "").replace(/\D/g, "").slice(0, 6); } async function requestAdminOtp() { const btn = document.getElementById("sendOtpBtn"); const msgEl = document.getElementById("otpStatusMsg"); btn.disabled = true; btn.textContent = "⏳ Sending 6-Digit Verification OTP..."; msgEl.style.color = "#38bdf8"; msgEl.textContent = "Dispatching cryptographic 6-digit OTP to registered admin device..."; try { const res = await callServerHf("/auth/send-otp", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) }); const data = await res.json(); if (res.ok && data.ok) { if (data.challengeToken) { latestOtpChallengeToken = data.challengeToken; try { localStorage.setItem("hf_otp_challenge_tok", data.challengeToken); } catch (e) {} setPersistentAuthCookie("hf_otp_challenge", data.challengeToken, 1); } msgEl.style.color = "#10b981"; msgEl.textContent = "βœ… " + (data.message || "OTP sent! Enter the 6-digit code above."); showToast("6-digit OTP sent to registered admin device!", "success"); const otpInp = document.getElementById("otpSingleInput"); if (otpInp) { otpInp.value = ""; otpInp.focus(); } } else { msgEl.style.color = "#ef4444"; msgEl.textContent = "❌ " + (data.error || "Could not send OTP."); showToast(data.error || "OTP request failed", "error"); } } catch (err) { msgEl.style.color = "#f59e0b"; msgEl.textContent = "⚠️ Server backend unreachable from this preview environment."; } finally { setTimeout(() => { btn.disabled = false; btn.textContent = "πŸ“² Resend 6-Digit Verification OTP"; }, 2500); } } async function verifyAdminOtpCode() { const otp = collectEnteredOtp(); const msgEl = document.getElementById("otpStatusMsg"); if (otp.length !== 6) { msgEl.style.color = "#ef4444"; msgEl.textContent = "⚠️ Please enter all 6 digits of the verification OTP."; return; } let challengeTok = latestOtpChallengeToken; if (!challengeTok) { try { challengeTok = localStorage.getItem("hf_otp_challenge_tok") || ""; } catch (e) {} } const btn = document.getElementById("verifyOtpBtn"); btn.disabled = true; btn.textContent = "⏳ Verifying OTP..."; try { const headers = buildAuthHeaders(); if (challengeTok) headers["x-hf-challenge"] = challengeTok; const res = await callServerHf("/auth/verify-otp", { method: "POST", headers, body: JSON.stringify({ otp, challengeToken: challengeTok || undefined }) }); const data = await res.json(); if (res.ok && data.ok && data.authenticated) { if (data.sessionToken) { setPersistentAuthCookie("hf_cmd_client_session", data.sessionToken, 365); try { localStorage.setItem("hf_cmd_session_hdr", data.sessionToken); } catch (e) {} } try { localStorage.removeItem("hf_otp_challenge_tok"); } catch (e) {} msgEl.style.color = "#10b981"; msgEl.textContent = "βœ… Verified! Saving cookie & unlocking Commander..."; showToast("OTP Verified! Trusted device cookie saved.", "success"); await unlockCommanderDashboard(); return; } else { msgEl.style.color = "#ef4444"; msgEl.textContent = "❌ " + (data.error || "Invalid OTP code."); showToast(data.error || "Invalid OTP code", "error"); } } catch (err) { msgEl.style.color = "#ef4444"; msgEl.textContent = "❌ Verification error: " + err.message; } finally { btn.disabled = false; btn.textContent = "βœ… Verify OTP & Save Trusted Device Cookie"; } } async function checkExistingSessionOnBoot() { const msgEl = document.getElementById("otpStatusMsg"); try { const savedChallenge = localStorage.getItem("hf_otp_challenge_tok"); if (savedChallenge) latestOtpChallengeToken = savedChallenge; } catch (e) {} try { const res = await callServerHf("/auth/session", { method: "GET", headers: buildAuthHeaders() }); if (res.ok) { const data = await res.json(); if (data.authenticated) { await unlockCommanderDashboard(); return; } msgEl.style.color = "#94a3b8"; msgEl.textContent = "πŸ”’ Click 'Send 6-Digit Verification OTP' to verify this device."; return; } } catch (e) { msgEl.style.color = "#f59e0b"; msgEl.textContent = "πŸ”’ Connect to your deployed Hugging Face server to verify via 6-digit OTP."; } } async function unlockCommanderDashboard() { isSessionUnlocked = true; const gate = document.getElementById("otpGateScreen"); const mainPage = document.getElementById("commanderMainPage"); if (gate) gate.style.display = "none"; if (mainPage) mainPage.classList.add("unlocked"); try { const res = await callServerHf("/config", { headers: buildAuthHeaders() }); if (res.ok) { logToTerminal("πŸ”’ Authenticated session verified. Connected to Private Server Vault.", "success"); } } catch (e) {} connectServerLogStream(); await checkSpaceStatus(); loadRepositoryFiles(); toggleAutoPoll(); } async function lockAndRevokeSession() { try { await callServerHf("/auth/logout", { method: "POST", headers: buildAuthHeaders() }); } catch (e) {} try { localStorage.removeItem("hf_cmd_session_hdr"); } catch (e) {} setPersistentAuthCookie("hf_cmd_client_session", "", -1); isSessionUnlocked = false; if (sseLogSource) { try { sseLogSource.close(); } catch (e) {} sseLogSource = null; } if (autoPollTimer) { clearInterval(autoPollTimer); autoPollTimer = null; } document.getElementById("commanderMainPage")?.classList.remove("unlocked"); const gate = document.getElementById("otpGateScreen"); if (gate) gate.style.display = "flex"; const otpInp = document.getElementById("otpSingleInput"); if (otpInp) otpInp.value = ""; const msgEl = document.getElementById("otpStatusMsg"); if (msgEl) { msgEl.style.color = "#f59e0b"; msgEl.textContent = "πŸ”’ Session locked. Verify 6-digit OTP to unlock."; } updateStatusBadge("LOCKED"); showToast("Session locked & security cookie cleared.", "warning"); } function handleUnauthorizedResponse() { if (!isSessionUnlocked) return; isSessionUnlocked = false; document.getElementById("commanderMainPage")?.classList.remove("unlocked"); const gate = document.getElementById("otpGateScreen"); if (gate) gate.style.display = "flex"; showToast("Session expired or unauthorized. Please verify OTP.", "error"); } function apsToggleSidebar() { const drawer = document.getElementById("suiteDrawer"); const backdrop = document.getElementById("suiteDrawerBackdrop"); if (!drawer) return; const isOpen = drawer.classList.toggle("open"); if (backdrop) backdrop.style.display = isOpen ? "block" : "none"; } function switchCommanderTab(tabName) { if (!isSessionUnlocked) return; ["lifecycle", "editor", "upload"].forEach(t => { const btn = document.getElementById("tabBtn-" + t); const panel = document.getElementById("panel-" + t); if (btn) btn.classList.toggle("active", t === tabName); if (panel) panel.classList.toggle("active", t === tabName); }); if (tabName === "editor" && repoFilesList.length === 0) { loadRepositoryFiles(); } } function buildAuthHeaders(extra = {}) { const h = Object.assign({ "Content-Type": "application/json" }, extra); const savedTok = getSavedSessionToken(); if (savedTok) h["x-hf-session"] = savedTok; return h; } // ===================================================================== // TERMINAL & MULTI-SOURCE LOG ENGINE // ===================================================================== function logToTerminal(message, type = "info", customTime = null) { const time = customTime || new Date().toLocaleTimeString("en-US", { hour12: false }); allLogEntries.push({ time, message: String(message || ""), type }); if (allLogEntries.length > 900) allLogEntries.shift(); renderFilteredLogs(); } function renderFilteredLogs() { const terminal = document.getElementById("terminalOutput"); if (!terminal) return; const filter = (document.getElementById("logSearchInput")?.value || "").toLowerCase().trim(); const filtered = filter ? allLogEntries.filter(e => e.message.toLowerCase().includes(filter) || e.time.toLowerCase().includes(filter)) : allLogEntries; terminal.innerHTML = ""; const frag = document.createDocumentFragment(); for (const item of filtered) { const line = document.createElement("div"); let colorClass = ""; if (item.type === "error" || /error|exception|failed|❌/i.test(item.message)) colorClass = "terminal-error"; else if (item.type === "success" || /βœ…|success|running/i.test(item.message)) colorClass = "terminal-success"; else if (item.type === "warning" || /warn|⚠️|paused|stopped/i.test(item.message)) colorClass = "terminal-warning"; else if (item.type === "info") colorClass = "terminal-info"; line.className = `terminal-line ${colorClass}`; const timeSpan = document.createElement("span"); timeSpan.className = "terminal-time"; timeSpan.textContent = `[${item.time}]`; line.appendChild(timeSpan); line.appendChild(document.createTextNode(" " + item.message)); frag.appendChild(line); } terminal.appendChild(frag); if (document.getElementById("autoScrollLogs")?.checked) { terminal.scrollTop = terminal.scrollHeight; } } function clearTerminal() { allLogEntries = []; renderFilteredLogs(); logToTerminal("Terminal output cleared.", "warning"); callServerHf("/logs/clear", { method: "POST", headers: buildAuthHeaders() }).catch(() => {}); } function copyAllLogs() { const text = allLogEntries.map(e => `[${e.time}] ${e.message}`).join("\n"); const ta = document.createElement("textarea"); ta.value = text; document.body.appendChild(ta); ta.select(); try { document.execCommand("copy"); showToast("Copied logs to clipboard!", "success"); } catch (e) {} ta.remove(); } function downloadLogsFile() { const text = allLogEntries.map(e => `[${e.time}] ${e.message}`).join("\n"); const blob = new Blob([text], { type: "text/plain;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `hf-server-${currentLogMode}-logs.log`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } function switchLogSource(mode) { currentLogMode = mode; ["server", "run", "build"].forEach(m => { const pill = document.getElementById("logTab-" + m); if (pill) pill.classList.toggle("active", m === mode); }); refreshCurrentLogs(); } function connectServerLogStream() { if (sseLogSource) { try { sseLogSource.close(); } catch (e) {} sseLogSource = null; } try { const tok = getSavedSessionToken(); const q = tok ? `?session=${encodeURIComponent(tok)}` : ""; const es = new EventSource(HF_SERVER_BASE + "/logs/stream" + q); sseLogSource = es; es.onmessage = (ev) => { if (currentLogMode !== "server") return; try { const data = JSON.parse(ev.data); if (data.type === "init" && Array.isArray(data.logs)) { allLogEntries = data.logs.map(l => ({ time: l.time || "LOG", message: `[${l.level || "INFO"}] ${l.message}`, type: l.level === "ERROR" ? "error" : (l.level === "WARN" ? "warning" : "info") })); renderFilteredLogs(); const stEl = document.getElementById("logStreamStatus"); if (stEl) stEl.textContent = "🟒 Live SSE Server Log Stream Connected"; } else if (data.type === "log" && data.entry) { const l = data.entry; logToTerminal( `[${l.level || "INFO"}] ${l.message}`, l.level === "ERROR" ? "error" : (l.level === "WARN" ? "warning" : "info"), l.time ); } } catch (e) {} }; es.onerror = () => { const stEl = document.getElementById("logStreamStatus"); if (stEl) stEl.textContent = "🟑 Reconnecting live log stream..."; }; } catch (e) {} } async function refreshCurrentLogs() { if (!isSessionUnlocked) return; if (currentLogMode === "server") { try { const res = await callServerHf(`/logs?limit=300`, { headers: buildAuthHeaders() }); if (res.status === 401) return handleUnauthorizedResponse(); if (res.ok) { const data = await res.json(); if (Array.isArray(data.logs)) { allLogEntries = data.logs.map(l => ({ time: l.time || "LOG", message: `[${l.level || "INFO"}] ${l.message}`, type: l.level === "ERROR" ? "error" : (l.level === "WARN" ? "warning" : "info") })); renderFilteredLogs(); return; } } } catch (e) {} return; } const stEl = document.getElementById("logStreamStatus"); if (stEl) stEl.textContent = `⏳ Fetching Hugging Face ${currentLogMode.toUpperCase()} logs...`; logToTerminal(`Fetching Hugging Face Space ${currentLogMode.toUpperCase()} logs...`, "info"); try { const res = await callServerHf(`/space-logs?type=${encodeURIComponent(currentLogMode)}`, { headers: buildAuthHeaders() }); if (res.status === 401) return handleUnauthorizedResponse(); const data = await res.json(); if (res.ok && data.ok && Array.isArray(data.lines)) { allLogEntries = data.lines.map(item => ({ time: item.timestamp ? new Date(item.timestamp).toLocaleTimeString("en-US", { hour12: false }) : currentLogMode.toUpperCase(), message: item.line, type: /error|exception|failed/i.test(item.line) ? "error" : "info" })); if (allLogEntries.length === 0) { logToTerminal(`No ${currentLogMode} log lines returned from Hugging Face.`, "warning"); } else { renderFilteredLogs(); } if (stEl) stEl.textContent = `🟒 Loaded ${data.lines.length} HF ${currentLogMode.toUpperCase()} log lines`; } else { logToTerminal(`❌ Could not fetch HF ${currentLogMode} logs: ${data.error || res.status}`, "error"); } } catch (err) { logToTerminal(`❌ Error fetching HF ${currentLogMode} logs: ${err.message}`, "error"); } } // ===================================================================== // LIFECYCLE CONTROL (START, PAUSE, STOP, RESTART, STATUS) // ===================================================================== function updateStatusBadge(status, standbyMode = null) { const badge = document.getElementById("spaceStatusBadge"); const dot = document.getElementById("statusDot"); const txt = document.getElementById("statusText"); const displayStatus = standbyMode ? `${status} (LOCAL ${standbyMode})` : status; if (txt) txt.textContent = `Status: ${displayStatus.toUpperCase()}`; const low = displayStatus.toLowerCase(); if (low.includes("running") && !standbyMode) { badge.style.color = "#10b981"; badge.style.borderColor = "#10b981"; badge.style.background = "rgba(16, 185, 129, 0.12)"; if (dot) { dot.style.background = "#10b981"; dot.classList.add("pulse"); } } else if (low.includes("paused") || low.includes("stopped") || low.includes("error") || low.includes("locked")) { badge.style.color = "#ef4444"; badge.style.borderColor = "#ef4444"; badge.style.background = "rgba(239, 68, 68, 0.12)"; if (dot) { dot.style.background = "#ef4444"; dot.classList.remove("pulse"); } } else { badge.style.color = "#f59e0b"; badge.style.borderColor = "#f59e0b"; badge.style.background = "rgba(245, 158, 11, 0.12)"; if (dot) { dot.style.background = "#f59e0b"; dot.classList.add("pulse"); } } } function formatUptime(sec) { if (!sec && sec !== 0) return "β€”"; const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; return `${h}h ${m}m ${s}s`; } async function executeSpaceAction(action) { if (!isSessionUnlocked) return handleUnauthorizedResponse(); logToTerminal(`⚑ Sending [${action.toUpperCase()}] command to Space...`, "warning"); try { const res = await callServerHf("/action", { method: "POST", headers: buildAuthHeaders(), body: JSON.stringify({ action, factory: action === "factory-reboot" }) }); if (res.status === 401) return handleUnauthorizedResponse(); const data = await res.json(); if (res.ok && data.ok) { logToTerminal(`βœ… ${data.message || `Successfully executed ${action}!`}`, "success"); showToast(data.message || `Action ${action.toUpperCase()} succeeded!`, "success"); setTimeout(checkSpaceStatus, 1800); } else { logToTerminal(`❌ Action failed: ${data.error || res.status}`, "error"); showToast(data.error || "Action failed", "error"); } } catch (err) { logToTerminal(`❌ Network Error: ${err.message}`, "error"); } } async function checkSpaceStatus() { if (!isSessionUnlocked) return; try { const res = await callServerHf(`/status`, { headers: buildAuthHeaders() }); if (res.status === 401) return handleUnauthorizedResponse(); if (res.ok) { const data = await res.json(); const stage = data.stage || "RUNNING"; document.getElementById("metricStage").textContent = stage; document.getElementById("metricStandby").textContent = data.standbyMode ? `⏸️ ${data.standbyMode}` : "🟒 ACTIVE"; document.getElementById("metricStandby").style.color = data.standbyMode ? "#f59e0b" : "#10b981"; document.getElementById("metricHardware").textContent = data.hardware || "cpu-basic"; document.getElementById("metricSha").textContent = data.sha ? data.sha.slice(0, 8) : "main"; if (data.serverStats) { document.getElementById("metricUptime").textContent = `${formatUptime(data.serverStats.uptimeSec)} Β· ${data.serverStats.rssMb}MB`; } updateStatusBadge(stage, data.standbyMode); } } catch (e) {} } function toggleAutoPoll() { if (autoPollTimer) { clearInterval(autoPollTimer); autoPollTimer = null; } if (document.getElementById("autoPollStatus")?.checked && isSessionUnlocked) { autoPollTimer = setInterval(checkSpaceStatus, 10000); } } // ===================================================================== // FILE MANAGER & CODE EDITOR (BROWSE, READ, EDIT, CREATE, DELETE) // ===================================================================== function formatBytes(bytes) { const b = Number(bytes) || 0; if (b < 1024) return `${b} B`; if (b < 1048576) return `${(b / 1024).toFixed(1)} KB`; return `${(b / 1048576).toFixed(2)} MB`; } async function loadRepositoryFiles() { if (!isSessionUnlocked) return; const container = document.getElementById("fileListContainer"); if (container) container.innerHTML = `<div style="padding:20px; text-align:center; color:var(--text-muted); font-size:12px;">⏳ Loading files from Space...</div>`; try { const res = await callServerHf(`/files`, { headers: buildAuthHeaders() }); if (res.status === 401) return handleUnauthorizedResponse(); if (res.ok) { const data = await res.json(); if (Array.isArray(data.files)) { repoFilesList = data.files; document.getElementById("fileCountBadge").textContent = String(repoFilesList.length); renderFileList(); } } } catch (err) { logToTerminal(`❌ Failed to list files: ${err.message}`, "error"); } } function renderFileList() { const container = document.getElementById("fileListContainer"); if (!container) return; const q = (document.getElementById("fileFilterInput")?.value || "").toLowerCase().trim(); const activePath = document.getElementById("currentEditorPath")?.value || ""; const filtered = q ? repoFilesList.filter(f => f.path.toLowerCase().includes(q)) : repoFilesList; if (filtered.length === 0) { container.innerHTML = `<div style="padding:18px; text-align:center; color:var(--text-muted); font-size:12px;">No matching files found.</div>`; return; } container.innerHTML = ""; for (const f of filtered) { const row = document.createElement("div"); row.className = "file-row" + (f.path === activePath ? " active" : ""); row.onclick = () => openFileInEditor(f.path); const nameSpan = document.createElement("span"); nameSpan.style.overflow = "hidden"; nameSpan.style.textOverflow = "ellipsis"; nameSpan.style.whiteSpace = "nowrap"; nameSpan.textContent = (f.isBinary ? "πŸ–ΌοΈ " : "πŸ“„ ") + f.path; const meta = document.createElement("div"); meta.className = "file-meta"; if (f.inHfRepo) { const b = document.createElement("span"); b.className = "badge-mini"; b.textContent = "HF"; meta.appendChild(b); } const sz = document.createElement("span"); sz.textContent = formatBytes(f.size); meta.appendChild(sz); row.appendChild(nameSpan); row.appendChild(meta); container.appendChild(row); } } async function openFileInEditor(filePath) { if (!isSessionUnlocked) return handleUnauthorizedResponse(); const cleanPath = String(filePath || "").trim(); if (!cleanPath) return; switchCommanderTab("editor"); document.getElementById("currentEditorPath").value = cleanPath; document.getElementById("editorCommitMsg").value = `Update ${cleanPath} via HF Space Commander`; const ta = document.getElementById("codeEditorTextarea"); const meta = document.getElementById("editorFileMeta"); ta.value = `// Loading ${cleanPath}...`; renderFileList(); try { const res = await callServerHf(`/file-content?path=${encodeURIComponent(cleanPath)}`, { headers: buildAuthHeaders() }); if (res.status === 401) return handleUnauthorizedResponse(); if (res.ok) { const data = await res.json(); if (data.ok) { ta.value = data.isBinary ? `/* Binary file (${formatBytes(data.size)}). Base64 preview: */\n${data.content.slice(0, 2000)}` : data.content; ta.dataset.isBinary = data.isBinary ? "1" : "0"; if (meta) meta.textContent = `${formatBytes(data.size)} Β· Source: ${data.source}`; logToTerminal(`πŸ“‚ Opened ${cleanPath} (${formatBytes(data.size)}) in editor.`, "info"); return; } } ta.value = ""; if (meta) meta.textContent = "New file (not yet in repo)"; } catch (err) { ta.value = `// Error loading ${cleanPath}: ${err.message}`; } } async function saveCurrentFileToSpace() { if (!isSessionUnlocked) return handleUnauthorizedResponse(); const pathVal = document.getElementById("currentEditorPath").value.trim(); if (!pathVal) { showToast("Please select or enter a file path first!", "warning"); return; } const contentVal = document.getElementById("codeEditorTextarea").value; const commitMsg = document.getElementById("editorCommitMsg").value.trim() || `Update ${pathVal} via HF Space Commander`; const commitToHf = document.getElementById("chkCommitHf").checked; const saveLocal = document.getElementById("chkSaveLocal").checked; const btn = document.getElementById("saveFileBtn"); btn.disabled = true; btn.textContent = "⏳ Saving & Committing..."; logToTerminal(`πŸ’Ύ Saving & committing ${pathVal}...`, "warning"); try { const res = await callServerHf("/file-save", { method: "POST", headers: buildAuthHeaders(), body: JSON.stringify({ path: pathVal, content: contentVal, encoding: "utf-8", commitMessage: commitMsg, commitToHf, saveLocal }) }); if (res.status === 401) return handleUnauthorizedResponse(); const data = await res.json(); if (res.ok && data.ok) { logToTerminal(`βœ… ${data.message}`, "success"); showToast(`Saved & committed ${pathVal}!`, "success"); loadRepositoryFiles(); checkSpaceStatus(); } else { logToTerminal(`❌ Save failed: ${data.error || res.status}`, "error"); showToast(data.error || "Save failed", "error"); } } catch (e) { logToTerminal(`❌ Save error: ${e.message}`, "error"); showToast(e.message, "error"); } finally { btn.disabled = false; btn.textContent = "πŸ’Ύ Save & Commit to HF"; } } function toggleEditorWrap() { const ta = document.getElementById("codeEditorTextarea"); if (!ta) return; ta.style.whiteSpace = ta.style.whiteSpace === "pre-wrap" ? "pre" : "pre-wrap"; } function downloadCurrentEditorFile() { const pathVal = document.getElementById("currentEditorPath").value.trim() || "file.txt"; const contentVal = document.getElementById("codeEditorTextarea").value; const blob = new Blob([contentVal], { type: "text/plain;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = pathVal.split("/").pop(); document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } function openNewFileModal() { const modal = document.getElementById("commanderModal"); document.getElementById("modalTitle").textContent = "βž• Create New File in Space"; document.getElementById("modalBody").innerHTML = ` <label class="hf-label">File Path (e.g. config.json or public/info.html)</label> <input type="text" id="newFileModalInput" placeholder="new-file.js"> `; const confirmBtn = document.getElementById("modalConfirmBtn"); confirmBtn.className = "btn green btn-sm"; confirmBtn.textContent = "Create & Open"; confirmBtn.onclick = () => { const p = (document.getElementById("newFileModalInput")?.value || "").trim(); if (!p) return; closeCommanderModal(); document.getElementById("currentEditorPath").value = p; document.getElementById("codeEditorTextarea").value = ""; document.getElementById("editorCommitMsg").value = `Create ${p} via HF Space Commander`; document.getElementById("editorFileMeta").textContent = "New unsaved file"; }; modal.style.display = "flex"; } function confirmDeleteCurrentFile() { const pathVal = document.getElementById("currentEditorPath").value.trim(); if (!pathVal) { showToast("Select a file first!", "warning"); return; } const modal = document.getElementById("commanderModal"); document.getElementById("modalTitle").textContent = "πŸ—‘οΈ Delete File from Space"; document.getElementById("modalBody").innerHTML = `Are you sure you want to delete <strong style="color:#f87171;">${pathVal}</strong> from Hugging Face Space & server?`; const confirmBtn = document.getElementById("modalConfirmBtn"); confirmBtn.className = "btn red btn-sm"; confirmBtn.textContent = "Delete File"; confirmBtn.onclick = async () => { closeCommanderModal(); await deleteFileFromSpace(pathVal); }; modal.style.display = "flex"; } function closeCommanderModal() { document.getElementById("commanderModal").style.display = "none"; } async function deleteFileFromSpace(pathVal) { if (!isSessionUnlocked) return handleUnauthorizedResponse(); logToTerminal(`πŸ—‘οΈ Deleting ${pathVal}...`, "warning"); try { const res = await callServerHf("/file-delete", { method: "POST", headers: buildAuthHeaders(), body: JSON.stringify({ path: pathVal }) }); if (res.status === 401) return handleUnauthorizedResponse(); const data = await res.json(); if (res.ok && data.ok) { logToTerminal(`βœ… ${data.message}`, "success"); showToast(`Deleted ${pathVal}`, "success"); document.getElementById("currentEditorPath").value = ""; document.getElementById("codeEditorTextarea").value = ""; loadRepositoryFiles(); } else { logToTerminal(`❌ Delete failed: ${data.error || res.status}`, "error"); } } catch (e) { logToTerminal(`❌ Delete error: ${e.message}`, "error"); } } // ===================================================================== // MULTI-FILE UPLOAD TO HUGGING FACE SPACE // ===================================================================== function initUploadDropzone() { const dz = document.getElementById("uploadDropzone"); if (!dz) return; dz.addEventListener("dragover", (e) => { e.preventDefault(); dz.classList.add("dragover"); }); dz.addEventListener("dragleave", () => dz.classList.remove("dragover")); dz.addEventListener("drop", (e) => { e.preventDefault(); dz.classList.remove("dragover"); if (e.dataTransfer && e.dataTransfer.files) { queueFilesForUpload(e.dataTransfer.files); } }); } function handleFileInputSelect(ev) { if (ev.target && ev.target.files) { queueFilesForUpload(ev.target.files); ev.target.value = ""; } } function queueFilesForUpload(fileList) { const prefix = (document.getElementById("uploadFolderPrefix")?.value || "") .trim() .replace(/^\/+|\/+$/g, ""); Array.from(fileList).forEach(file => { const reader = new FileReader(); reader.onload = () => { const dataUrl = String(reader.result || ""); const base64 = dataUrl.includes(",") ? dataUrl.split(",")[1] : ""; const targetPath = prefix ? `${prefix}/${file.name}` : file.name; uploadQueue.push({ name: file.name, path: targetPath, size: file.size, content: base64, encoding: "base64" }); renderUploadQueue(); }; reader.readAsDataURL(file); }); } function renderUploadQueue() { const box = document.getElementById("uploadQueueContainer"); const btn = document.getElementById("uploadCommitBtn"); if (!box || !btn) return; btn.disabled = uploadQueue.length === 0; btn.textContent = `πŸš€ Upload & Commit Queued Files (${uploadQueue.length})`; if (uploadQueue.length === 0) { box.innerHTML = ""; return; } box.innerHTML = ""; uploadQueue.forEach((item, idx) => { const row = document.createElement("div"); row.className = "upload-queue-item"; row.innerHTML = ` <div> <strong style="color:var(--accent);">${item.path}</strong> <span style="color:var(--text-muted); margin-left:8px;">(${formatBytes(item.size)})</span> </div> `; const rmBtn = document.createElement("button"); rmBtn.className = "btn red btn-sm"; rmBtn.textContent = "Remove"; rmBtn.onclick = () => { uploadQueue.splice(idx, 1); renderUploadQueue(); }; row.appendChild(rmBtn); box.appendChild(row); }); } function clearUploadQueue() { uploadQueue = []; renderUploadQueue(); } async function uploadQueuedFilesToSpace() { if (!isSessionUnlocked) return handleUnauthorizedResponse(); if (uploadQueue.length === 0) return; const commitMsg = document.getElementById("uploadCommitMessage").value.trim() || `Upload ${uploadQueue.length} file(s) via HF Space Commander`; const btn = document.getElementById("uploadCommitBtn"); btn.disabled = true; btn.textContent = "⏳ Uploading & Committing..."; logToTerminal(`πŸ“€ Uploading ${uploadQueue.length} file(s)...`, "warning"); try { const res = await callServerHf("/file-save", { method: "POST", headers: buildAuthHeaders(), body: JSON.stringify({ commitMessage: commitMsg, files: uploadQueue, commitToHf: true, saveLocal: true }) }); if (res.status === 401) return handleUnauthorizedResponse(); const data = await res.json(); if (res.ok && data.ok) { logToTerminal(`βœ… ${data.message}`, "success"); showToast(`Uploaded & committed ${uploadQueue.length} file(s)!`, "success"); clearUploadQueue(); loadRepositoryFiles(); checkSpaceStatus(); } else { logToTerminal(`❌ Upload failed: ${data.error || res.status}`, "error"); showToast(data.error || "Upload failed", "error"); } } catch (e) { logToTerminal(`❌ Upload error: ${e.message}`, "error"); showToast(e.message, "error"); } finally { renderUploadQueue(); } } // ===================================================================== // INITIALIZATION // ===================================================================== document.addEventListener("DOMContentLoaded", async () => { initUploadDropzone(); const editorEl = document.getElementById("codeEditorTextarea"); if (editorEl) { editorEl.addEventListener("keydown", (e) => { if (e.key === "Tab") { e.preventDefault(); const s = editorEl.selectionStart; const end = editorEl.selectionEnd; editorEl.value = editorEl.value.substring(0, s) + " " + editorEl.value.substring(end); editorEl.selectionStart = editorEl.selectionEnd = s + 4; } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") { e.preventDefault(); saveCurrentFileToSpace(); } }); } await checkExistingSessionOnBoot(); }); </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>HF Space Commander β€” AI PRO SUITE</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-main: #070b14;
--bg-card: #0f172a;
--bg-elevated: #1e293b;
--bg-input: #090d16;
--primary: #f59e0b;
--primary-hover: #d97706;
--accent: #38bdf8;
--success: #10b981;
--danger: #ef4444;
--warning: #f59e0b;
--purple: #8b5cf6;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--border-light: rgba(148, 163, 184, 0.18);
--border-focus: rgba(245, 158, 11, 0.65);
--shadow-lg: 0 16px 40px rgba(0, 0, 0, 0.55);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: radial-gradient(circle at 15% 0%, rgba(245, 158, 11, 0.10), transparent 35%),
radial-gradient(circle at 85% 10%, rgba(56, 189, 248, 0.10), transparent 40%),
var(--bg-main);
color: var(--text-main);
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
min-height: 100vh;
overflow-x: hidden;
}
/* OTP SECURITY GATE SCREEN */
.auth-gate-screen {
position: fixed;
inset: 0;
z-index: 5000;
background: radial-gradient(circle at 50% 20%, rgba(245, 158, 11, 0.14), rgba(7, 11, 20, 0.98) 65%);
backdrop-filter: blur(18px);
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.auth-gate-card {
background: linear-gradient(160deg, #0f172a 0%, #090d16 100%);
border: 1px solid rgba(245, 158, 11, 0.35);
border-radius: 22px;
max-width: 440px;
width: 100%;
padding: 32px 26px;
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.75);
text-align: center;
}
.shield-badge {
width: 64px;
height: 64px;
border-radius: 18px;
background: linear-gradient(135deg, rgba(245, 158, 11, 0.2), rgba(239, 68, 68, 0.2));
border: 1px solid rgba(245, 158, 11, 0.45);
display: flex;
align-items: center;
justify-content: center;
font-size: 30px;
margin: 0 auto 16px;
}
.otp-single-input {
width: 100% !important;
height: 60px;
margin: 14px 0 18px;
text-align: center;
font-size: 28px !important;
font-weight: 900;
letter-spacing: 14px;
padding-left: 20px !important;
font-family: 'JetBrains Mono', monospace;
background: #050811 !important;
border: 2px solid rgba(245, 158, 11, 0.45) !important;
border-radius: 14px !important;
color: #fbbf24 !important;
transition: all 0.18s;
}
.otp-single-input:focus {
border-color: var(--primary) !important;
box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.22);