Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

27.2 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PortOS Autofixer</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #0a0a0f;
      color: #e0e0e0;
      min-height: 100vh;
    }

    /* Header — stacks vertically on mobile */
    header {
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      padding: 0.75rem 1rem;
      border-bottom: 1px solid #2a2a4a;
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
    }

    h1 {
      font-size: 1.125rem;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    h1 span { font-size: 1.25rem; }

    .nav-links {
      display: flex;
      gap: 0.25rem;
    }

    .nav-links a {
      color: #888;
      text-decoration: none;
      font-size: 0.8125rem;
      padding: 0.5rem 0.75rem;
      border-radius: 0.5rem;
      transition: all 0.2s;
      min-height: 44px;
      display: flex;
      align-items: center;
    }

    .nav-links a:hover, .nav-links a.active {
      color: #fff;
      background: rgba(255,255,255,0.1);
    }

    /* Container — stacked on mobile, side-by-side on tablet+ */
    .container {
      display: flex;
      flex-direction: column;
      height: calc(100vh - 100px);
    }

    /* Sidebar — horizontal scrolling strip on mobile */
    .sidebar {
      background: #12121a;
      border-bottom: 1px solid #2a2a4a;
      padding: 0.75rem;
      overflow-x: auto;
      overflow-y: hidden;
      flex-shrink: 0;
    }

    .sidebar h2 {
      font-size: 0.75rem;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      color: #666;
      margin-bottom: 0.5rem;
    }

    .process-list {
      display: flex;
      flex-direction: row;
      gap: 0.5rem;
    }

    .process-item {
      padding: 0.625rem 0.75rem;
      background: #1a1a2a;
      border-radius: 0.5rem;
      cursor: pointer;
      transition: all 0.2s;
      border: 1px solid transparent;
      min-height: 44px;
      min-width: 140px;
      flex-shrink: 0;
    }

    .process-item:hover {
      border-color: #3a3a5a;
    }

    .process-item.selected {
      border-color: #6366f1;
      background: #1e1e3a;
    }

    .process-name {
      font-weight: 500;
      font-size: 0.8125rem;
      white-space: nowrap;
    }

    .process-app {
      font-size: 0.6875rem;
      color: #666;
      margin-top: 0.125rem;
      white-space: nowrap;
    }

    .process-status {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 0.5rem;
    }

    .status-online { background: #22c55e; }
    .status-stopped { background: #6b7280; }
    .status-errored { background: #ef4444; }
    .status-unknown { background: #eab308; }

    .main-content {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-height: 0;
    }

    .toolbar {
      padding: 0.5rem 0.75rem;
      background: #12121a;
      border-bottom: 1px solid #2a2a4a;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 0.5rem;
    }

    .toolbar-left {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      min-width: 0;
    }

    .toolbar-title {
      font-weight: 500;
      font-size: 0.8125rem;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .toolbar-buttons {
      display: flex;
      gap: 0.375rem;
      flex-wrap: wrap;
      margin-left: auto;
    }

    .toolbar button {
      padding: 0.5rem 0.75rem;
      background: #2a2a4a;
      color: #e0e0e0;
      border: none;
      border-radius: 0.375rem;
      cursor: pointer;
      font-size: 0.8125rem;
      transition: all 0.2s;
      min-height: 40px;
      min-width: 40px;
    }

    .toolbar button:hover {
      background: #3a3a5a;
    }

    .toolbar button.pause-active {
      background: #ef4444;
      color: white;
    }

    .toolbar button.restart-btn {
      background: #22c55e33;
      color: #22c55e;
      border: 1px solid #22c55e44;
    }

    .toolbar button.restart-btn:hover {
      background: #22c55e55;
    }

    .toolbar button.restart-btn:disabled,
    .toolbar button.stop-btn:disabled {
      opacity: 0.4;
      cursor: not-allowed;
    }

    .toolbar button.stop-btn {
      background: #ef444433;
      color: #ef4444;
      border: 1px solid #ef444444;
    }

    .toolbar button.stop-btn:hover {
      background: #ef444455;
    }

    .toast {
      position: fixed;
      bottom: 2rem;
      right: 2rem;
      padding: 0.75rem 1.25rem;
      border-radius: 0.5rem;
      font-size: 0.875rem;
      z-index: 1000;
      opacity: 0;
      transform: translateY(10px);
      transition: all 0.3s;
    }

    .toast.visible {
      opacity: 1;
      transform: translateY(0);
    }

    .toast.success {
      background: #22c55e22;
      color: #22c55e;
      border: 1px solid #22c55e44;
    }

    .toast.error {
      background: #ef444422;
      color: #ef4444;
      border: 1px solid #ef444444;
    }

    #logs {
      flex: 1;
      overflow-y: auto;
      padding: 0.75rem;
      font-family: 'SF Mono', 'Fira Code', monospace;
      font-size: 0.75rem;
      line-height: 1.5;
      background: #0a0a0f;
    }

    .log-line {
      padding: 0.125rem 0;
      white-space: pre-wrap;
      word-break: break-word;
    }

    .log-line.error { color: #f87171; }
    .log-line.info { color: #a5f3fc; }

    .status-bar {
      padding: 0.5rem 0.75rem;
      background: #12121a;
      border-top: 1px solid #2a2a4a;
      font-size: 0.75rem;
      color: #666;
      display: flex;
      justify-content: space-between;
    }

    .status-indicator {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .status-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
    }

    .status-dot.connected { background: #22c55e; }
    .status-dot.disconnected { background: #ef4444; }

    .history-panel {
      display: none;
      overflow-y: auto;
      flex: 1;
      padding: 0.75rem;
    }

    .history-panel.active {
      display: block;
    }

    .history-item {
      padding: 0.75rem;
      background: #1a1a2a;
      border-radius: 0.5rem;
      margin-bottom: 0.5rem;
      cursor: pointer;
      transition: all 0.2s;
      min-height: 44px;
    }

    .history-item:hover {
      background: #1e1e3a;
    }

    .history-item .time {
      font-size: 0.75rem;
      color: #666;
    }

    .history-item .process {
      font-weight: 500;
      margin-top: 0.25rem;
      word-break: break-word;
    }

    .history-item .result {
      font-size: 0.75rem;
      margin-top: 0.25rem;
    }

    .history-item .result.success { color: #22c55e; }
    .history-item .result.failed { color: #ef4444; }

    ::-webkit-scrollbar { width: 8px; height: 8px; }
    ::-webkit-scrollbar-track { background: #0a0a0f; }
    ::-webkit-scrollbar-thumb { background: #2a2a4a; border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: #3a3a5a; }

    /* Tablet and up (768px+) */
    @media (min-width: 768px) {
      header {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: 1rem 1.5rem;
      }

      h1 { font-size: 1.25rem; }
      h1 span { font-size: 1.5rem; }

      .nav-links { gap: 0.5rem; }

      .nav-links a {
        font-size: 0.875rem;
        padding: 0.5rem 1rem;
      }

      .container {
        flex-direction: row;
        height: calc(100vh - 60px);
      }

      .sidebar {
        width: 260px;
        border-right: 1px solid #2a2a4a;
        border-bottom: none;
        overflow-x: hidden;
        overflow-y: auto;
        padding: 1rem;
      }

      .process-list {
        flex-direction: column;
      }

      .process-item {
        min-width: unset;
      }

      .process-name {
        font-size: 0.875rem;
        white-space: normal;
      }

      .process-app {
        font-size: 0.75rem;
        white-space: normal;
      }

      .toolbar {
        padding: 0.75rem 1rem;
      }

      .toolbar-title { font-size: 0.875rem; }

      .toolbar button {
        padding: 0.5rem 1rem;
        font-size: 0.875rem;
      }

      #logs {
        padding: 1rem;
        font-size: 0.8125rem;
        line-height: 1.6;
      }

      .history-panel { padding: 1rem; }

      .history-item { padding: 1rem; }
    }

    /* Login overlay — shown when the PortOS install is password protected
       and this browser has no valid session. */
    .login-overlay {
      position: fixed;
      inset: 0;
      background: #0a0a0f;
      display: none;
      align-items: center;
      justify-content: center;
      padding: 1rem;
      z-index: 100;
    }

    .login-overlay.visible { display: flex; }

    .login-card {
      background: #12121a;
      border: 1px solid #2a2a4a;
      border-radius: 0.75rem;
      padding: 1.5rem;
      width: 100%;
      max-width: 360px;
    }

    .login-card h2 {
      font-size: 1rem;
      margin-bottom: 0.375rem;
    }

    .login-card p {
      font-size: 0.8125rem;
      color: #888;
      margin-bottom: 1rem;
      line-height: 1.5;
    }

    .login-card label {
      display: block;
      font-size: 0.75rem;
      color: #888;
      margin-bottom: 0.375rem;
    }

    .login-card input {
      width: 100%;
      padding: 0.625rem 0.75rem;
      min-height: 44px;
      background: #1a1a2a;
      border: 1px solid #2a2a4a;
      border-radius: 0.5rem;
      color: #e0e0e0;
      font-size: 1rem;
    }

    .login-card input:focus {
      outline: none;
      border-color: #6366f1;
    }

    .login-card button {
      width: 100%;
      margin-top: 0.75rem;
      padding: 0.625rem 1rem;
      min-height: 44px;
      background: #6366f1;
      border: none;
      border-radius: 0.5rem;
      color: #fff;
      font-size: 0.9375rem;
      cursor: pointer;
    }

    .login-card button:disabled { opacity: 0.6; cursor: default; }

    .login-error {
      margin-top: 0.75rem;
      font-size: 0.8125rem;
      color: #f87171;
      min-height: 1.2em;
    }

    #logoutLink { display: none; }
    #logoutLink.visible { display: flex; }

    /* Desktop (1024px+) */
    @media (min-width: 1024px) {
      .sidebar { width: 300px; }

      .nav-links { gap: 1rem; }
    }
  </style>
</head>
<body>
  <header>
    <h1><span>🔧</span> PortOS Autofixer</h1>
    <div class="nav-links">
      <a href="#" id="portosDashboardLink" target="_blank">PortOS Dashboard</a>
      <a href="#" class="active" id="logsTab">Logs</a>
      <a href="#" id="historyTab">History</a>
      <a href="#" id="logoutLink">Log out</a>
    </div>
  </header>

  <div class="container">
    <div class="sidebar">
      <h2>Processes</h2>
      <div class="process-list" id="processList">
        <!-- Populated by JS -->
      </div>
    </div>

    <div class="main-content">
      <div class="toolbar">
        <div class="toolbar-left">
          <span class="toolbar-title" id="currentProcess">Select a process</span>
        </div>
        <div class="toolbar-buttons">
          <button id="restartBtn" class="restart-btn" disabled>Restart</button>
          <button id="stopBtn" class="stop-btn" disabled>Stop</button>
          <button id="clearBtn">Clear</button>
          <button id="pauseBtn">Pause</button>
        </div>
      </div>

      <div id="logs"></div>

      <div id="historyPanel" class="history-panel">
        <!-- History items -->
      </div>

      <div class="status-bar">
        <div class="status-indicator">
          <div class="status-dot" id="statusDot"></div>
          <span id="statusText">Disconnected</span>
        </div>
        <span id="lineCount">0 lines</span>
      </div>
    </div>
  </div>

  <div id="toast" class="toast"></div>

  <div class="login-overlay" id="loginOverlay">
    <form class="login-card" id="loginForm">
      <h2>🔒 PortOS Autofixer</h2>
      <p>This install is password protected. Enter your PortOS password — or sign in to the PortOS dashboard on this host and reload.</p>
      <label for="loginPassword">Password</label>
      <input type="password" id="loginPassword" name="password" autocomplete="current-password" autofocus>
      <button type="submit" id="loginSubmit">Unlock</button>
      <div class="login-error" id="loginError"></div>
    </form>
  </div>

  <script>
    const loginOverlay = document.getElementById('loginOverlay');
    const loginForm = document.getElementById('loginForm');
    const loginPassword = document.getElementById('loginPassword');
    const loginSubmit = document.getElementById('loginSubmit');
    const loginError = document.getElementById('loginError');
    const logoutLink = document.getElementById('logoutLink');

    const processList = document.getElementById('processList');
    const logsContainer = document.getElementById('logs');
    const historyPanel = document.getElementById('historyPanel');
    const currentProcessEl = document.getElementById('currentProcess');
    const clearBtn = document.getElementById('clearBtn');
    const pauseBtn = document.getElementById('pauseBtn');
    const statusDot = document.getElementById('statusDot');
    const statusText = document.getElementById('statusText');
    const lineCount = document.getElementById('lineCount');
    const restartBtn = document.getElementById('restartBtn');
    const stopBtn = document.getElementById('stopBtn');
    const toastEl = document.getElementById('toast');
    const logsTab = document.getElementById('logsTab');
    const historyTab = document.getElementById('historyTab');

    let eventSource = null;
    let isPaused = false;
    let totalLines = 0;
    let autoScroll = true;
    let selectedProcess = null;
    let processStatuses = new Map();
    const processStatusClasses = new Map([
      ['online', 'status-online'],
      ['stopped', 'status-stopped'],
      ['errored', 'status-errored']
    ]);

    // Auth — the sidecar mirrors the main PortOS password gate. When no
    // password is set, /api/auth/status reports enabled:false and nothing
    // below ever shows. A `portos_auth` cookie from the dashboard on this host
    // already counts (cookies ignore port), so the overlay is only for
    // browsers that haven't signed in there.
    let authRequired = false;

    function showLogin(message) {
      authRequired = true;
      loginError.textContent = message || '';
      loginOverlay.classList.add('visible');
      logoutLink.classList.remove('visible');
      if (eventSource) { eventSource.close(); eventSource = null; }
      loginPassword.focus();
    }

    function hideLogin() {
      loginOverlay.classList.remove('visible');
      loginPassword.value = '';
      loginError.textContent = '';
      logoutLink.classList.toggle('visible', authRequired);
    }

    // Every API call routes through here so a 401 (session expired, password
    // rotated on :5555) re-arms the overlay instead of silently failing.
    async function apiFetch(url, options) {
      const res = await fetch(url, options);
      if (res.status === 401) {
        showLogin('Session expired — sign in again.');
        return null;
      }
      return res;
    }

    async function checkAuth() {
      const res = await fetch('/api/auth/status').catch(() => null);
      if (!res || !res.ok) return true; // treat an unreachable gate as open; API calls still 401
      const status = await res.json();
      authRequired = !!status.enabled;
      if (status.enabled && !status.authenticated) {
        showLogin('');
        return false;
      }
      hideLogin();
      return true;
    }

    loginForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      loginSubmit.disabled = true;
      loginSubmit.textContent = 'Unlocking…';
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: loginPassword.value })
      }).catch(() => null);
      loginSubmit.disabled = false;
      loginSubmit.textContent = 'Unlock';
      if (!res || !res.ok) {
        const data = res ? await res.json().catch(() => ({})) : {};
        loginError.textContent = data.error || 'Login failed';
        return;
      }
      hideLogin();
      await start();
    });

    logoutLink.addEventListener('click', async (e) => {
      e.preventDefault();
      await fetch('/api/auth/logout', { method: 'POST' }).catch(() => null);
      showLogin('Signed out.');
    });

    // Fetch PM2 status. A failed PM2 read answers 503 with an error object,
    // not an array (issue #8164) — treat that as "unavailable", never clear
    // every process to unknown/offline by iterating a non-array with forEach.
    async function fetchStatus() {
      const res = await apiFetch('/api/status');
      if (!res) return;
      const body = await res.json();
      if (!res.ok || !Array.isArray(body)) {
        processStatuses = null;
        updateProcessList();
        return;
      }
      processStatuses = new Map();
      body.forEach(s => { processStatuses.set(String(s.name ?? ''), s.status); });
      updateProcessList();
    }

    // Fetch apps and build process list
    async function fetchApps() {
      const res = await apiFetch('/api/apps');
      if (!res) return;
      const apps = await res.json();

      const processes = [];
      apps.forEach(app => {
        (app.pm2ProcessNames || []).forEach(proc => {
          processes.push({ name: proc, app: app.name });
        });
      });

      window.processesList = processes;
      await fetchStatus();
    }

    function updateProcessList() {
      const processes = window.processesList || [];
      processList.replaceChildren();

      processes.forEach(p => {
        const name = String(p.name ?? '');
        const item = document.createElement('div');
        item.classList.add('process-item');
        if (selectedProcess === name) item.classList.add('selected');
        item.dataset.name = name;

        const nameEl = document.createElement('div');
        nameEl.className = 'process-name';

        const statusEl = document.createElement('span');
        // `processStatuses === null` means the last PM2 read failed (503) —
        // render every process unknown rather than throwing on a missing Map.
        const statusClass = processStatusClasses.get(processStatuses?.get(name)) || 'status-unknown';
        statusEl.classList.add('process-status', statusClass);
        nameEl.append(statusEl, document.createTextNode(name));

        const appEl = document.createElement('div');
        appEl.className = 'process-app';
        appEl.textContent = String(p.app ?? '');

        item.append(nameEl, appEl);
        item.addEventListener('click', () => {
          selectProcess(item.dataset.name);
        });
        processList.appendChild(item);
      });
    }

    function selectProcess(name) {
      selectedProcess = name;
      currentProcessEl.textContent = name;
      logsContainer.replaceChildren();
      totalLines = 0;
      lineCount.textContent = '0 lines';
      restartBtn.disabled = false;
      stopBtn.disabled = false;
      updateProcessList();
      connect();
    }

    function showToast(message, type) {
      toastEl.textContent = message;
      toastEl.className = 'toast ' + type;
      requestAnimationFrame(() => toastEl.classList.add('visible'));
      setTimeout(() => toastEl.classList.remove('visible'), 3000);
    }

    async function restartProcess() {
      if (!selectedProcess) return;
      restartBtn.disabled = true;
      restartBtn.textContent = 'Restarting…';
      const res = await apiFetch('/api/restart/' + encodeURIComponent(selectedProcess), { method: 'POST' });
      restartBtn.textContent = 'Restart';
      restartBtn.disabled = false;
      if (!res) return;
      const data = await res.json();
      if (data.success) {
        showToast('Restarted ' + selectedProcess, 'success');
        fetchStatus();
      } else {
        showToast('Failed to restart: ' + (data.error || 'unknown error'), 'error');
      }
    }

    async function stopProcess() {
      if (!selectedProcess) return;
      stopBtn.disabled = true;
      stopBtn.textContent = 'Stopping…';
      const res = await apiFetch('/api/stop/' + encodeURIComponent(selectedProcess), { method: 'POST' });
      stopBtn.textContent = 'Stop';
      stopBtn.disabled = false;
      if (!res) return;
      const data = await res.json();
      if (data.success) {
        showToast('Stopped ' + selectedProcess, 'success');
        fetchStatus();
      } else {
        showToast('Failed to stop: ' + (data.error || 'unknown error'), 'error');
      }
    }

    function connect() {
      if (!selectedProcess) return;

      if (eventSource) {
        eventSource.close();
      }

      eventSource = new EventSource('/logs?process=' + selectedProcess);

      eventSource.onopen = () => {
        statusText.textContent = 'Connected';
        statusDot.className = 'status-dot connected';
      };

      eventSource.onmessage = (event) => {
        if (isPaused) return;

        const data = JSON.parse(event.data);

        if (data.type === 'log') {
          const logLine = document.createElement('div');
          logLine.className = 'log-line ' + (data.stream === 'err' ? 'error' : 'info');
          logLine.textContent = data.message;
          logsContainer.appendChild(logLine);

          totalLines++;
          lineCount.textContent = totalLines + ' lines';

          if (autoScroll) {
            logsContainer.scrollTop = logsContainer.scrollHeight;
          }

          while (logsContainer.children.length > 1000) {
            logsContainer.removeChild(logsContainer.firstChild);
          }
        }
      };

      eventSource.onerror = async () => {
        statusText.textContent = 'Disconnected';
        statusDot.className = 'status-dot disconnected';
        eventSource.close();
        // EventSource surfaces a 401 as a generic error with no status, so
        // re-check the gate before retrying — otherwise an expired session
        // reconnects in a loop with no explanation.
        if (!(await checkAuth())) return;
        setTimeout(connect, 3000);
      };
    }

    async function fetchHistory() {
      const res = await apiFetch('/api/history');
      if (!res) return;
      const history = await res.json();
      historyPanel.replaceChildren();

      if (!Array.isArray(history) || history.length === 0) {
        const empty = document.createElement('div');
        empty.style.padding = '1rem';
        empty.style.color = '#666';
        empty.textContent = 'No fix history yet';
        historyPanel.appendChild(empty);
        return;
      }

      history.forEach(h => {
        const date = new Date(h.startTime).toLocaleString();
        const duration = Math.round(h.duration / 1000);

        const item = document.createElement('div');
        item.className = 'history-item';

        const timeEl = document.createElement('div');
        timeEl.className = 'time';
        timeEl.textContent = `${date} (${duration}s)`;

        const processEl = document.createElement('div');
        processEl.className = 'process';
        processEl.textContent = `${String(h.processName ?? '')} - ${String(h.appName || 'Unknown App')}`;

        const resultEl = document.createElement('div');
        const succeeded = h.success === true;
        resultEl.classList.add('result', succeeded ? 'success' : 'failed');
        resultEl.textContent = h.staged ? 'Staged for review' : h.disposition === 'discarded' ? 'Discarded' : h.promoted ? 'Applied and restarted' : h.disposition === 'recovery-required' ? 'Recovery required — inspect checkout' : succeeded ? 'Fix produced' : 'Fix failed';

        item.append(timeEl, processEl, resultEl);
        if (h.staged) {
          const view = document.createElement('button');
          view.textContent = 'Review patch';
          view.addEventListener('click', async () => {
            view.disabled = true;
            const res = await apiFetch('/api/fixes/' + encodeURIComponent(h.sessionId)).catch(() => null);
            view.disabled = false;
            if (!res) return;
            const fix = await res.json();
            if (!res.ok) { showToast(fix.error || 'Unable to load patch', 'error'); return; }
            view.remove();
            const diff = document.createElement('pre');
            diff.textContent = fix.patch;
            diff.style.cssText = 'white-space:pre-wrap;overflow-wrap:anywhere;max-height:24rem;overflow:auto';
            item.appendChild(diff);
            const controls = [];
            for (const action of ['apply', 'discard']) {
              const button = document.createElement('button');
              button.textContent = action === 'apply' ? 'Apply and restart' : 'Discard';
              controls.push(button);
              button.addEventListener('click', async () => {
                controls.forEach(control => { control.disabled = true; });
                const result = await apiFetch('/api/fixes/' + encodeURIComponent(h.sessionId) + '/' + action, { method: 'POST' }).catch(() => null);
                controls.forEach(control => { control.disabled = false; });
                if (!result) { showToast('Action failed — check connection', 'error'); return; }
                const body = await result.json();
                if (!result.ok) { showToast(body.error || 'Action failed', 'error'); return; }
                resultEl.textContent = body.disposition === 'applied' ? 'Applied and restarted' : 'Discarded';
                controls.forEach(control => control.remove());
                if (body.disposition === 'applied') fetchStatus();
              });
              item.appendChild(button);
            }
          });
          item.appendChild(view);
        }
        historyPanel.appendChild(item);
      });
    }

    clearBtn.addEventListener('click', () => {
      logsContainer.replaceChildren();
      totalLines = 0;
      lineCount.textContent = '0 lines';
    });

    pauseBtn.addEventListener('click', () => {
      isPaused = !isPaused;
      pauseBtn.textContent = isPaused ? 'Resume' : 'Pause';
      pauseBtn.classList.toggle('pause-active', isPaused);
    });

    restartBtn.addEventListener('click', restartProcess);
    stopBtn.addEventListener('click', stopProcess);

    logsContainer.addEventListener('scroll', () => {
      const isAtBottom = logsContainer.scrollHeight - logsContainer.scrollTop <= logsContainer.clientHeight + 50;
      autoScroll = isAtBottom;
    });

    logsTab.addEventListener('click', (e) => {
      e.preventDefault();
      logsTab.classList.add('active');
      historyTab.classList.remove('active');
      logsContainer.style.display = 'block';
      historyPanel.classList.remove('active');
    });

    historyTab.addEventListener('click', (e) => {
      e.preventDefault();
      historyTab.classList.add('active');
      logsTab.classList.remove('active');
      logsContainer.style.display = 'none';
      historyPanel.classList.add('active');
      fetchHistory();
    });

    // Set dynamic PortOS Dashboard link
    document.getElementById('portosDashboardLink').href =
      window.location.protocol + '//' + window.location.hostname + ':5554';

    // Initial load
    async function start() {
      if (!(await checkAuth())) return;
      await fetchApps();
    }

    start();
    setInterval(() => { if (!loginOverlay.classList.contains('visible')) fetchStatus(); }, 10000);
  </script>
</body>
</html>