π OpenHands: AI-Driven Development
feat: add expandable startup-log console to desktop loading screen (#1878)
Hiep Le428e33d23d94
diff --git a/electron/loading.html b/electron/loading.htmlindex 1bf53ebb40..4e523c0f56 100644--- a/electron/loading.html+++ b/electron/loading.html@@ -16,6 +16,10 @@--oh-muted: #a3b0c4; /* cool-grey-400 */--oh-text-dim: #7e8a9e; /* cool-grey-500 */--oh-text-subtle: #626d82; /* cool-grey-600 */+ --oh-border: #4b5468; /* cool-grey-700 */+ --oh-border-subtle: #383f50; /* cool-grey-800 */+ --oh-surface-deep: #05070a; /* cool-grey-975 */+ --oh-color-danger: #e76a5e;}html, body {@@ -33,12 +37,21 @@overflow: hidden;}+ body {+ display: flex;+ flex-direction: column;+ }+.container {display: flex;flex-direction: column;align-items: center;justify-content: center;- height: 100vh;+ /* Must equal the collapsed window height (LOADING_WIN_HEIGHT in+ main.mjs): the block keeps its layout when the window grows to+ reveal the startup-log console below it. */+ height: 360px;+ flex: none;gap: 0;}@@ -112,6 +125,108 @@66% { content: ".."; }100% { content: "..."; }}++ .actions {+ margin-top: 16px;+ display: flex;+ gap: 10px;+ -webkit-app-region: no-drag;+ }++ .ghost-button {+ font: inherit;+ font-size: 11px;+ padding: 4px 12px;+ color: var(--oh-muted);+ background: transparent;+ border: 1px solid var(--oh-border);+ border-radius: 8px;+ cursor: pointer;+ -webkit-app-region: no-drag;+ }+ .ghost-button:hover {+ color: var(--oh-foreground);+ background: rgba(255, 255, 255, 0.06);+ }++ /* ββ Startup-log console βββββββββββββββββββββββββββββββββββββββββββββ+ Fills the extra height revealed by "Show details" (the window grows β+ see setLoadingWindowExpanded in main.mjs); zero-height and clipped+ while the window is collapsed. Interactive: opts out of the window+ drag region and re-enables text selection. */+ .console {+ flex: 1 1 auto;+ min-height: 0;+ display: flex;+ flex-direction: column;+ margin: 0 16px 16px;+ background: var(--oh-surface-deep);+ border: 1px solid var(--oh-border-subtle);+ border-radius: 8px;+ overflow: hidden;+ -webkit-app-region: no-drag;+ }++ .console-head {+ flex: none;+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 5px 6px 5px 12px;+ border-bottom: 1px solid var(--oh-border-subtle);+ font-size: 11px;+ color: var(--oh-muted);+ }++ .log {+ flex: 1 1 auto;+ min-height: 0;+ overflow-y: auto;+ padding: 8px 12px;+ /* The app's `code` stack (src/index.css). */+ font-family:+ source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;+ font-size: 10.5px;+ line-height: 1.55;+ color: var(--oh-text-dim);+ user-select: text;+ -webkit-user-select: text;+ cursor: text;+ /* Full lines, never truncated β long uvx/pip output wraps. */+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ }+ .log:empty::before {+ content: "Waiting for outputβ¦";+ color: var(--oh-text-subtle);+ }++ .log-name {+ color: var(--oh-text-subtle);+ }+ .log-line-error {+ color: var(--oh-color-danger);+ }++ /* ββ Failure state (main.mjs::showStartupFailure) ββββββββββββββββββββ */+ body.failed .spinner {+ display: none;+ }+ body.failed .status {+ color: var(--oh-color-danger);+ /* The full error summary matters more than a tidy single line here. */+ white-space: normal;+ line-height: 1.45;+ }+ body.failed .hint {+ display: none;+ }+ .quit-button {+ display: none;+ }+ body.failed .quit-button {+ display: inline-block;+ }</style></head><body>@@ -129,6 +244,21 @@First launch downloads Python + the OpenHands agent server.<br />This can take a few minutes on a fresh machine.</p>+ <div class="actions">+ <button id="details-toggle" type="button" class="ghost-button">+ Show details+ </button>+ <button id="quit-button" type="button" class="ghost-button quit-button">+ Quit+ </button>+ </div>+ </div>+ <div class="console" aria-label="Startup log">+ <div class="console-head">+ <span>Startup log</span>+ <button id="copy-logs" type="button" class="ghost-button">Copy</button>+ </div>+ <div id="log" class="log"></div></div><script>// Called from the Electron main process via webContents.executeJavaScript@@ -140,6 +270,90 @@var text = String(line == null ? "" : line);el.textContent = text || "";};++ // ββ Startup-log console ββββββββββββββββββββββββββββββββββββββββββββββ+ // Fed by the main process over IPC via preload.cjs (window.desktopBoot);+ // undefined when the file is opened outside Electron, so every use is+ // guarded and the static layout stays previewable in a plain browser.+ // All DOM insertion uses textContent β log lines are untrusted process+ // output and must never be parsed as HTML.+ (function () {+ var boot = window.desktopBoot;+ var logEl = document.getElementById("log");+ var statusEl = document.getElementById("status");+ var toggleBtn = document.getElementById("details-toggle");+ var copyBtn = document.getElementById("copy-logs");+ var quitBtn = document.getElementById("quit-button");++ // Cap DOM rows so an hours-long install can't grow layout cost;+ // matches the main process's BOOT_LOG_MAX_LINES buffer cap.+ var MAX_LINES = 2000;+ var expanded = false;+ // Follow the tail only while the user hasn't scrolled up.+ var pinned = true;++ logEl.addEventListener("scroll", function () {+ pinned =+ logEl.scrollTop + logEl.clientHeight >= logEl.scrollHeight - 8;+ });++ function appendBatch(batch) {+ if (!batch || !batch.length) return;+ var frag = document.createDocumentFragment();+ for (var i = 0; i < batch.length; i++) {+ var entry = batch[i];+ var row = document.createElement("div");+ row.className =+ "log-line" + (entry.level === "error" ? " log-line-error" : "");+ var name = document.createElement("span");+ name.className = "log-name";+ name.textContent = "[" + entry.name + "]";+ row.appendChild(name);+ row.appendChild(document.createTextNode(" " + entry.line));+ frag.appendChild(row);+ }+ logEl.appendChild(frag);+ while (logEl.childElementCount > MAX_LINES) {+ logEl.removeChild(logEl.firstElementChild);+ }+ if (pinned) logEl.scrollTop = logEl.scrollHeight;+ }++ function setExpanded(next) {+ expanded = next;+ toggleBtn.textContent = expanded ? "Hide details" : "Show details";+ if (boot) boot.setDetailsExpanded(expanded);+ if (expanded && pinned) logEl.scrollTop = logEl.scrollHeight;+ }++ toggleBtn.addEventListener("click", function () {+ setExpanded(!expanded);+ });++ copyBtn.addEventListener("click", function () {+ if (!boot) return;+ boot.copyLogs().then(function () {+ copyBtn.textContent = "Copied";+ setTimeout(function () {+ copyBtn.textContent = "Copy";+ }, 1200);+ });+ });++ quitBtn.addEventListener("click", function () {+ if (boot) boot.quit();+ });++ if (boot) {+ boot.onLogBatch(appendBatch);+ boot.onFatal(function (summary) {+ document.body.classList.add("failed");+ statusEl.textContent = String(summary == null ? "" : summary);+ // Main already resized the window; sync the local toggle state.+ if (!expanded) setExpanded(true);+ });+ }+ })();</script></body></html>diff --git a/electron/main.mjs b/electron/main.mjsindex 622b9593a0..1ad46237cb 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -29,7 +29,9 @@import {app,BrowserWindow,+ clipboard,dialog,+ ipcMain,nativeImage,nativeTheme,shell,@@ -244,12 +246,35 @@ async function waitForAgentServer(let loadingWin = null;let mainWin = null;+// Collapsed splash size β loading.html's .container height must match. The+// expanded height reveals the startup-log console below it ("Show details").+const LOADING_WIN_WIDTH = 460;+const LOADING_WIN_HEIGHT = 360;+const LOADING_WIN_EXPANDED_HEIGHT = 560;++/**+ * Grow or shrink the loading window to reveal/hide the startup-log console.+ * Keeps the top edge fixed so the splash content doesn't jump. Invoked from+ * the renderer ("Show details" toggle) and from showStartupFailure().+ */+function setLoadingWindowExpanded(expanded) {+ if (!loadingWin || loadingWin.isDestroyed()) return;+ const bounds = loadingWin.getBounds();+ const height = expanded ? LOADING_WIN_EXPANDED_HEIGHT : LOADING_WIN_HEIGHT;+ if (bounds.height === height) return;+ // macOS ignores programmatic resizes of resizable:false windows on some+ // Electron versions β lift the flag around the change.+ loadingWin.setResizable(true);+ loadingWin.setBounds({ ...bounds, height }, true);+ loadingWin.setResizable(false);+}+function createLoadingWindow() {loadingWin = new BrowserWindow({- width: 460,+ width: LOADING_WIN_WIDTH,// Tall enough to fit the streaming status line + the "first launch can// take a few minutes" hint without scrollbars.- height: 360,+ height: LOADING_WIN_HEIGHT,resizable: false,frame: false,center: true,@@ -260,9 +285,27 @@ function createLoadingWindow() {webPreferences: {nodeIntegration: false,contextIsolation: true,+ // Bridges the startup-log console over IPC (see preload.cjs).+ preload: join(__dirname, "preload.cjs"),},});+ // The renderer can only receive IPC once the page has loaded β replay the+ // lines buffered until now, then stream live batches (see appendBootLog).+ loadingWin.webContents.on("did-finish-load", () => {+ if (!loadingWin || loadingWin.isDestroyed()) return;+ clearTimeout(bootLogFlushTimer);+ bootLogFlushTimer = null;+ bootLogPending = [];+ if (bootLog.length) {+ loadingWin.webContents.send("boot-log:batch", bootLog.slice());+ }+ bootLogReady = true;+ if (fatalSummary) {+ loadingWin.webContents.send("boot-log:fatal", fatalSummary);+ }+ });+loadingWin.loadFile(join(__dirname, "loading.html"));loadingWin.once("ready-to-show", () => loadingWin?.show());}@@ -341,6 +384,116 @@ function createMainWindow() {});}+// ββ Startup log buffer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+//+// Every service log line (all services, all levels, sanitized) is kept in a+// bounded buffer and streamed to the loading window's console in batches over+// IPC (see preload.cjs + loading.html). The buffer is the single source of+// truth: it is replayed once the page loads (lines emitted earlier would+// otherwise be lost) and it backs the "Copy logs" action. In a packaged app+// this console is the only log surface β stdout/stderr go to /dev/null when+// launched from Finder, and the winston file logger is a no-op there (see+// AGENTS.md on the node_modules strip).++const BOOT_LOG_MAX_LINES = 2000;+const BOOT_LOG_FLUSH_MS = 200;++const bootLog = []; // {name, line, level}[] β level: stdout|stderr|info|warn|error+let bootLogPending = [];+let bootLogFlushTimer = null;+let bootLogReady = false; // true once loading.html has loaded and can receive+let fatalSummary = null;++// SGR color codes AND cursor-control CSI sequences (uv/uvicorn can emit+// either when they mis-detect a TTY).+const ANSI_CSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;++/**+ * Strip ANSI escapes and reduce carriage-return progress redraws (e.g. uv+ * download bars arrive as one chunk of "\r"-separated frames) to the final+ * frame β what a real terminal would have settled on.+ */+function sanitizeLogLine(line) {+ const frames = String(line ?? "")+ .replace(ANSI_CSI_RE, "")+ .split("\r")+ .map((s) => s.trim())+ .filter(Boolean);+ return frames.length ? frames[frames.length - 1] : "";+}++function appendBootLog(name, line, level) {+ const entry = { name, line, level };+ bootLog.push(entry);+ if (bootLog.length > BOOT_LOG_MAX_LINES) {+ bootLog.splice(0, bootLog.length - BOOT_LOG_MAX_LINES);+ }+ bootLogPending.push(entry);+ if (!bootLogFlushTimer) {+ bootLogFlushTimer = setTimeout(flushBootLog, BOOT_LOG_FLUSH_MS);+ }+}++function flushBootLog() {+ clearTimeout(bootLogFlushTimer);+ bootLogFlushTimer = null;+ if (!bootLogPending.length) return;+ const batch = bootLogPending;+ bootLogPending = [];+ // Not ready / window gone: drop the batch β the entries stay in bootLog,+ // which did-finish-load replays wholesale.+ if (bootLogReady && loadingWin && !loadingWin.isDestroyed()) {+ loadingWin.webContents.send("boot-log:batch", batch);+ }+}++/**+ * Switch the splash into its failure state: expand the console and show the+ * error summary with Copy logs / Quit actions, keeping the window open so the+ * user can actually read why startup failed. Returns false when the loading+ * window is gone (caller falls back to a native dialog).+ */+function showStartupFailure(summary) {+ if (!loadingWin || loadingWin.isDestroyed()) return false;+ fatalSummary = summary;+ setLoadingWindowExpanded(true);+ if (bootLogReady) {+ flushBootLog();+ loadingWin.webContents.send("boot-log:fatal", summary);+ }+ // If the page hasn't loaded yet, did-finish-load replays the buffer and+ // then delivers fatalSummary.+ return true;+}++// IPC surface for the loading window (see preload.cjs). Guarded to that+// window's webContents so the main app window can never reach these.+function isLoadingWinEvent(event) {+ return (+ loadingWin !== null &&+ !loadingWin.isDestroyed() &&+ event.sender === loadingWin.webContents+ );+}++ipcMain.handle("boot-log:set-expanded", (event, expanded) => {+ if (!isLoadingWinEvent(event)) return;+ setLoadingWindowExpanded(Boolean(expanded));+});++ipcMain.handle("boot-log:copy", (event) => {+ if (!isLoadingWinEvent(event)) return 0;+ clipboard.writeText(bootLog.map((e) => `[${e.name}] ${e.line}`).join("\n"));+ return bootLog.length;+});++// The frameless splash has no close control; the failure state shows a Quit+// button instead.+ipcMain.handle("boot-log:quit", (event) => {+ if (!isLoadingWinEvent(event)) return;+ app.quit();+});+// ββ Backend stack βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ/**@@ -370,6 +523,15 @@ function setLoadingStatus(line) {.catch(() => {});}+/**+ * Phase marker: headline + a line in the startup-log console, so the log+ * records which stage a failed boot died in.+ */+function setBootPhase(message) {+ appendBootLog("desktop", message, "info");+ setLoadingStatus(message);+}+/*** Last few `level: "error"` service log lines (spawn failures, non-zero* exits). Appended to the startup-failure dialog: a packaged app launched@@ -386,21 +548,23 @@ const recentServiceErrors = [];* is downloading Python + agent-server.*/function handleServiceLog(name, line, level) {- // Skip empty / noisy progress chatter that overwrites itself rapidly.- // We're mainly interested in agent-server (= uvx output during install).if (!line) return;+ const clean = sanitizeLogLine(line);+ if (!clean) return;+ // Full-fidelity stream: every service and level goes to the console buffer.+ // The one-line headline below stays filtered to the interesting services.+ appendBootLog(name, clean, level);if (name === "agent-server" || name === "automation") {- setLoadingStatus(`${name}: ${line}`);+ setLoadingStatus(`${name}: ${clean}`);}- // Mirror anything to a `[desktop]` log line in addition to the colored- // dev-stack output so the desktop log file is grep-friendly.+ // Mirror errors to a `[desktop]` terminal line so dev runs stay grep-friendly.if (level === "error") {- console.error(`[desktop] [${name}] ${line}`);- // Errors from ANY service (including ingress/static, which the splash+ console.error(`[desktop] [${name}] ${clean}`);+ // Errors from ANY service (including ingress/static, which the headline// filter above skips) are worth showing β a dead ingress is exactly the// case where the user would otherwise stare at a silent 120 s timeout.- setLoadingStatus(`${name}: ${line}`);- recentServiceErrors.push(`${name}: ${line}`);+ setLoadingStatus(`${name}: ${clean}`);+ recentServiceErrors.push(`${name}: ${clean}`);if (recentServiceErrors.length > 5) recentServiceErrors.shift();}}@@ -474,11 +638,11 @@ app.whenReady().then(async () => {createLoadingWindow();try {- setLoadingStatus("Starting backend servicesβ¦");+ setBootPhase("Starting backend servicesβ¦");await startStack();// Stage 1: ingress proxy is bound (anything < 500 on /).- setLoadingStatus("Waiting for proxyβ¦");+ setBootPhase("Waiting for proxyβ¦");await waitForUrl("http://localhost:8000");// Stage 2: the agent-server behind the proxy is actually serving@@ -486,20 +650,28 @@ app.whenReady().then(async () => {// re-probe end-to-end here so that if the user closes the splash race// window between processes binding, we still open the main window with// a live backend. Cheap (a single 200 response) when everything is up.- setLoadingStatus("Connecting to agent serverβ¦");+ setBootPhase("Connecting to agent serverβ¦");await waitForAgentServer("http://localhost:8000/server_info", 60_000);- setLoadingStatus("Ready.");+ setBootPhase("Ready.");createMainWindow();} catch (err) {+ const summary =+ err.message ++ " Ensure ports 8000, 18000, and 18001 are free, then try again.";+ // Record the failure in the terminal and the startup-log buffer so it+ // shows (and copies) as the final console line.+ console.error("[desktop] Startup failed:", err);+ appendBootLog("desktop", summary, "error");+ // Keep the splash open in its failure state so the full startup log can+ // be read and copied; the app quits via the splash's Quit button (or+ // Cmd+Q / closing the window).+ if (showStartupFailure(summary)) return;+ // Loading window already gone β fall back to the old dialog-and-quit.const errorTail = recentServiceErrors.length? `\n\nRecent service errors:\n${recentServiceErrors.join("\n")}`: "";- const msg =- err.message +- "\n\nEnsure ports 8000, 18000, and 18001 are free, then try again." +- errorTail;- dialog.showErrorBox("Agent Canvas failed to start", msg);+ dialog.showErrorBox("Agent Canvas failed to start", summary + errorTail);app.quit();}});diff --git a/electron/preload.cjs b/electron/preload.cjsnew file mode 100644index 0000000000..3c8a1fa879--- /dev/null+++ b/electron/preload.cjs@@ -0,0 +1,31 @@+/**+ * Preload for the loading window (loading.html).+ *+ * Bridges the startup-log console to the main process over IPC while keeping+ * contextIsolation (and the default renderer sandbox) intact. The one-line+ * status headline intentionally does NOT go through here β main.mjs sets it+ * via executeJavaScript β window.__setLoadingStatus (see setLoadingStatus).+ *+ * CommonJS on purpose: sandboxed preload scripts cannot use ESM.+ */+const { contextBridge, ipcRenderer } = require("electron");++contextBridge.exposeInMainWorld("desktopBoot", {+ /** Subscribe to batched startup-log lines: cb([{name, line, level}, β¦]). */+ onLogBatch(cb) {+ if (typeof cb !== "function") return;+ ipcRenderer.on("boot-log:batch", (_event, batch) => cb(batch));+ },+ /** Subscribe to the fatal startup-failure notification: cb(summary). */+ onFatal(cb) {+ if (typeof cb !== "function") return;+ ipcRenderer.on("boot-log:fatal", (_event, summary) => cb(summary));+ },+ /** Grow/shrink the window to reveal or hide the console panel. */+ setDetailsExpanded: (expanded) =>+ ipcRenderer.invoke("boot-log:set-expanded", Boolean(expanded)),+ /** Copy the full buffered startup log to the clipboard. */+ copyLogs: () => ipcRenderer.invoke("boot-log:copy"),+ /** Quit the app (failure-state action; the frameless splash has no close UI). */+ quit: () => ipcRenderer.invoke("boot-log:quit"),+});