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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: log install/venv setup SSE flows to server console (#2432)
Adam Eivyb6d766e75be0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 72b5a7fa59..e13007c519 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changes+- **Runtime/venv install SSE flows now log to the server console too, matching the HF model-download logging (#2432).** The image/video runtime installers (spawning `setup-image-video.sh`) and the FLUX.2 venv bootstrap streamed multi-GB pip/git progress only to the browser via SSE — a headless / PM2 log had no record the install ever ran (the same gap `startHfDownloadStream` had already closed for HF model downloads). A new shared `createInstallLogger` chokepoint (`server/lib/installLogger.js`) now emits a single-line START, throttled heartbeats + `stage` milestones, and the OUTCOME (success/fail/cancel) with installer name, target, and elapsed time — without echoing every raw pip/bash line. Wired into all three install spawn sites in `music.js`, `videoGen.js`, and `imageGen.js`.+- **The four SSE job-slot hooks now share one implementation.** `useReferenceAudioImport`, `useYoutubeTrackImport`, `useVideoDownload`, and `useMidiTranscription` each hand-rolled the same "kick off a job → stream SSE progress → settle on the terminal frame, with double-click and lost-connection recovery" machinery. That logic now lives in exactly one place — a new generic `useSseJobSlot` hook — and the four feature hooks are thin wrappers that pass their own kickoff/SSE/cancel calls plus per-feature toast copy (and, for MuScriptor, its runtime-install and gated-repo modals). Behavior-preserving refactor deferred from the MuScriptor /simplify pass (#2368); ~150 fewer lines.- **Shell page quick-command buttons trimmed to the interactive tools.** Dropped the four shell one-liner shortcuts (`git status`, `git pull`, `npm test`, `npm run dev`) that duplicated things you'd just type, renamed the `antigravity` button to its actual command `agy`, and added a `grok` button alongside the other coding-agent launchers.diff --git a/server/lib/README.md b/server/lib/README.mdindex 0c57f28c68..a454a77223 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hfDownload.js` | `downloadHfRepo({repo,onEvent})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in the FLUX.2 venv (fallback: mflux pythonPath) and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. || `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. || `sseDownload.js` | `startHfDownloadStream({req,res,repo,alreadyDownloadedMessage})`, `openSseStream(res)` (`{send,safeEnd}` SSE boilerplate; uses `SSE_HEADERS` from `sseHeaders.js`) — shared SSE driver used by both image and video gen `/models/:id/download` routes. Owns the cross-route in-flight Map so a double-click (or both pages running) can't spawn two python children against the same repo. |+| `installLogger.js` | `createInstallLogger({installer,target})` → `{start,onEvent,success,failure,cancel}` — server-console chokepoint for install/venv-setup SSE flows (the install-side analogue of `sseDownload.js`). Logs a START line, throttled heartbeats + `stage` milestones (not every raw pip/bash line), and the OUTCOME (success/fail/cancel) with elapsed time. `onEvent(ev)` auto-detects terminal `complete`/`error` SSE events. Used by the music/video runtime installers and the FLUX.2 venv bootstrap. |## File & I/Odiff --git a/server/lib/index.js b/server/lib/index.jsindex e11219c82d..ee8c0d5fee 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -93,6 +93,7 @@ export * from './hfCache.js';export * from './hfDownload.js';export * from './sseDownload.js';export * from './sseHeaders.js';+export * from './installLogger.js';export * from './mediaModels.js';export * from './promptPartials.js';export * from './promptRunner.js';diff --git a/server/lib/installLogger.js b/server/lib/installLogger.jsnew file mode 100644index 0000000000..fe12b92783--- /dev/null+++ b/server/lib/installLogger.js@@ -0,0 +1,85 @@+// Server-console visibility for install / environment-setup SSE flows. The+// runtime installers that spawn `setup-image-video.sh` (music + video gen) and+// the FLUX.2 venv bootstrap stream multi-GB pip/git progress to the browser via+// the SSE `send()` channel ONLY — a headless / PM2 log had no record the install+// ever ran. This is the install-side analogue of+// `sseDownload.js#startHfDownloadStream` (which closed the same gap for HF model+// downloads): a single chokepoint that logs a START line, coarse throttled+// heartbeats + stage milestones, and the OUTCOME (success / fail / cancel) —+// NOT every raw pip/bash line (that would flood the console from a hot loop).+//+// Usage: create one logger per install request, call `start()` at spawn, feed+// every SSE event through `onEvent(ev)` (it auto-detects terminal `complete` /+// `error` events and logs the outcome), and call `cancel()` on client+// disconnect. `success()` / `failure()` are terminal reconcilers for install+// flows that resolve without emitting a terminal SSE event.++// How long a hot log/progress stream may run before the console emits a single+// "still installing" heartbeat. Keeps a multi-minute pip download visible in+// the server log without echoing every line.+const HEARTBEAT_MS = 15000;++export function createInstallLogger({ installer, target } = {}) {+ const name = installer || 'install';+ const suffix = target ? ` (${target})` : '';+ const startedAt = Date.now();+ let started = false;+ let finished = false;+ let lastHeartbeat = 0;+ let lineCount = 0;++ const elapsed = () => `${((Date.now() - startedAt) / 1000).toFixed(1)}s`;++ // These methods run inside child-process stdout/stderr and promise callbacks+ // that live OUTSIDE the Express request lifecycle — an uncaught throw there+ // crashes the Node process (no `next(err)` to bubble to). Wrap every hook body.+ const safe = (fn) => {+ try { fn(); }+ catch (err) { console.error(`❌ Install logger error (${name}): ${err.message}`); }+ };++ const finish = (ok, message) => {+ if (finished) return;+ finished = true;+ if (ok) {+ console.log(`✅ Install complete: ${name}${suffix} in ${elapsed()}${message ? ` — ${message}` : ''}`);+ } else {+ console.error(`❌ Install failed: ${name}${suffix} after ${elapsed()}${message ? ` — ${message}` : ''}`);+ }+ };++ const start = () => safe(() => {+ if (started) return;+ started = true;+ lastHeartbeat = Date.now();+ console.log(`🔧 Install starting: ${name}${target ? ` → ${target}` : ''}`);+ });++ const onEvent = (ev) => safe(() => {+ if (!started || finished || !ev || typeof ev !== 'object') return;+ if (ev.type === 'complete') { finish(true, ev.message); return; }+ if (ev.type === 'error') { finish(false, ev.message); return; }+ if (ev.type === 'stage' && ev.stage) {+ console.log(`🔧 ${name}: ${ev.stage}${ev.message ? ` — ${ev.message}` : ''} (${elapsed()})`);+ return;+ }+ // Raw log/progress lines: count them but surface only a throttled heartbeat+ // so a hot pip/bash stream doesn't flood the server console.+ lineCount += 1;+ const now = Date.now();+ if (now - lastHeartbeat >= HEARTBEAT_MS) {+ lastHeartbeat = now;+ console.log(`⏳ ${name} installing…${suffix} (${lineCount} lines, ${elapsed()})`);+ }+ });++ const success = (message) => safe(() => finish(true, message));+ const failure = (message) => safe(() => finish(false, message));+ const cancel = () => safe(() => {+ if (finished) return;+ finished = true;+ console.log(`🛑 Install cancelled: ${name}${suffix} after ${elapsed()}`);+ });++ return { start, onEvent, success, failure, cancel };+}diff --git a/server/lib/installLogger.test.js b/server/lib/installLogger.test.jsnew file mode 100644index 0000000000..00e63ee0e4--- /dev/null+++ b/server/lib/installLogger.test.js@@ -0,0 +1,86 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { createInstallLogger } from './installLogger.js';++describe('createInstallLogger', () => {+ let logSpy;+ let errSpy;++ beforeEach(() => {+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const logged = () => logSpy.mock.calls.map((c) => c[0]);+ const errored = () => errSpy.mock.calls.map((c) => c[0]);++ it('logs a START line on start() with installer and target', () => {+ const log = createInstallLogger({ installer: 'Example Engine', target: '/venv/py' });+ log.start();+ expect(logged().some((l) => /Install starting: Example Engine/.test(l) && l.includes('/venv/py'))).toBe(true);+ });++ it('no-ops onEvent before start()', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.onEvent({ type: 'complete', message: 'done' });+ log.onEvent({ type: 'error', message: 'boom' });+ log.onEvent({ type: 'stage', stage: 'venv' });+ expect(logged()).toHaveLength(0);+ expect(errored()).toHaveLength(0);+ });++ it('logs stage milestones but throttles raw log lines', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.start();+ log.onEvent({ type: 'stage', stage: 'install', message: 'Installing torch' });+ // A burst of raw log lines within the heartbeat window emits at most one+ // heartbeat (the first line, since lastHeartbeat was set at start()).+ for (let i = 0; i < 50; i += 1) log.onEvent({ type: 'log', message: `line ${i}` });+ const stageLines = logged().filter((l) => /Example: install/.test(l));+ const heartbeats = logged().filter((l) => /installing…/.test(l));+ expect(stageLines).toHaveLength(1);+ expect(heartbeats.length).toBeLessThanOrEqual(1);+ });++ it('logs SUCCESS outcome on a complete event', () => {+ const log = createInstallLogger({ installer: 'Example', target: '/venv/py' });+ log.start();+ log.onEvent({ type: 'complete', message: 'ready' });+ expect(logged().some((l) => /Install complete: Example/.test(l) && /ready/.test(l))).toBe(true);+ });++ it('logs FAILURE outcome on an error event via console.error', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.start();+ log.onEvent({ type: 'error', message: 'pip exploded' });+ expect(errored().some((l) => /Install failed: Example/.test(l) && /pip exploded/.test(l))).toBe(true);+ });++ it('logs a terminal outcome only once (dedupes complete then failure())', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.start();+ log.onEvent({ type: 'complete', message: 'ready' });+ log.failure('should be ignored');+ const outcomes = [...logged(), ...errored()].filter((l) => /Install (complete|failed):/.test(l));+ expect(outcomes).toHaveLength(1);+ });++ it('logs a CANCEL outcome and blocks later outcomes', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.start();+ log.cancel();+ log.onEvent({ type: 'error', message: 'exit code 143' });+ expect(logged().some((l) => /Install cancelled: Example/.test(l))).toBe(true);+ expect(errored()).toHaveLength(0);+ });++ it('survives a malformed event without throwing', () => {+ const log = createInstallLogger({ installer: 'Example' });+ log.start();+ expect(() => log.onEvent(null)).not.toThrow();+ expect(() => log.onEvent('nope')).not.toThrow();+ expect(() => log.onEvent(undefined)).not.toThrow();+ });+});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 1a037e9e6f..34a55dab7c 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -26,6 +26,7 @@ import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModeimport { usesDiffusersRunner } from '../lib/runners.js';import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';+import { createInstallLogger } from '../lib/installLogger.js';import {REQUIRED_PACKAGES, detectPython, installPackages,createVenv, isAllowedPython, pipNameFor,@@ -834,10 +835,23 @@ router.get('/setup/flux2-install', asyncHandler(async (req, res) => {return safeEnd();}- const { promise, kill } = installFlux2Venv(send);+ // Server-console visibility for the multi-GB torch install (start / stage+ // milestones / outcome) — installFlux2Venv streams progress only to `send`.+ const installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });+ const emit = (ev) => { installLog.onEvent(ev); send(ev); };+ installLog.start();++ const { promise, kill } = installFlux2Venv(emit);flux2InstallInFlight = promise;promise- .catch((err) => send({ type: 'error', message: err?.message || 'Unknown installer failure' }))+ // installFlux2Venv resolves { ok:false } on some pip failures without+ // emitting a terminal SSE event, so reconcile the outcome from the result+ // (a no-op if `onEvent` already logged a complete/error frame).+ .then((result) => {+ if (result?.ok) installLog.success(result?.pythonPath ? `ready: ${result.pythonPath}` : undefined);+ else installLog.failure(`failed at stage ${result?.stage || 'unknown'}`);+ })+ .catch((err) => emit({ type: 'error', message: err?.message || 'Unknown installer failure' })).finally(() => {flux2InstallInFlight = null;safeEnd();@@ -845,7 +859,7 @@ router.get('/setup/flux2-install', asyncHandler(async (req, res) => {// Cancel the install if the client navigates away mid-bootstrap. A torch// install is a multi-GB download and would otherwise keep running invisibly.- req.on('close', () => { kill(); safeEnd(); });+ req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });}));// Used by the FLUX.2 model picker: surface a banner when the gated repo'sdiff --git a/server/routes/music.js b/server/routes/music.jsindex a3c2b86f3d..e45345410b 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -28,6 +28,7 @@ import { safeChildProcessEnv } from '../lib/processEnv.js';import { ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineReady, generateMusic } from '../services/pipeline/musicGen.js';import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';+import { createInstallLogger } from '../lib/installLogger.js';import { inspectModelCache } from '../lib/hfCache.js';import * as tracks from '../services/tracks/index.js';import * as albums from '../services/albums/index.js';@@ -116,6 +117,11 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}send({ type: 'log', message: `Starting ${engine.name} install.` });+ // Server-console visibility for the multi-GB install (start / heartbeat /+ // outcome) — the SSE stream otherwise surfaces progress only in the browser.+ const installLog = createInstallLogger({ installer: engine.name, target: engine.venvDefault });+ const emit = (ev) => { installLog.onEvent(ev); send(ev); };+ installLog.start();const child = spawn('bash', [scriptPath], {env: safeChildProcessEnv({ [engine.installEnv]: '1' }),stdio: ['ignore', 'pipe', 'pipe'],@@ -127,7 +133,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {const onChunk = (chunk) => {for (const line of chunk.toString().split(/[\r\n]+/)) {const t = line.trimEnd();- if (t) send({ type: 'log', message: t });+ if (t) emit({ type: 'log', message: t });}};child.stdout.on('data', onChunk);@@ -135,24 +141,25 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {child.on('error', (err) => {finished = true;runtimeInstallInFlight.delete(engine.id);- send({ type: 'error', message: `Installer failed to spawn: ${err.message}` });+ emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });safeEnd();});child.on('close', (code) => {finished = true;runtimeInstallInFlight.delete(engine.id);if (code === 0 && isEngineReady(engine.id)) {- send({ type: 'complete', message: `${engine.name} ready: ${engine.resolvePython() || engine.venvDefault}` });+ emit({ type: 'complete', message: `${engine.name} ready: ${engine.resolvePython() || engine.venvDefault}` });} else if (code === 0) {- send({ type: 'error', message: `Installer exited 0 but ${engine.name} is still not available. Check the log above for setup errors.` });+ emit({ type: 'error', message: `Installer exited 0 but ${engine.name} is still not available. Check the log above for setup errors.` });} else {- send({ type: 'error', message: `Installer exited with code ${code}.` });+ emit({ type: 'error', message: `Installer exited with code ${code}.` });}safeEnd();});req.on('close', () => {if (finished) return;+ installLog.cancel();if (!child.killed && child.pid) {try { process.kill(-child.pid, 'SIGTERM'); }catch { child.kill('SIGTERM'); }diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex beafed64d2..4ff5b00f61 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -45,6 +45,7 @@ import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModelsimport { videoLoraFamily } from '../lib/runners.js';import { inspectModelCache, verifyModelCache, repairModelCache, summarizeVerify } from '../lib/hfCache.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';+import { createInstallLogger } from '../lib/installLogger.js';const router = Router();@@ -325,6 +326,11 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}send({ type: 'log', message: `▸ Starting ${info.label} install via ${info.installEnvVar}=1 bash scripts/setup-image-video.sh` });+ // Server-console visibility for the multi-GB install (start / heartbeat /+ // outcome) — the SSE stream otherwise surfaces progress only in the browser.+ const installLog = createInstallLogger({ installer: info.label, target: info.venvPython });+ const emit = (ev) => { installLog.onEvent(ev); send(ev); };+ installLog.start();// `detached: true` puts bash in its own process group so a cancel from the// client can take down uv / pip / git children too. Without it, SIGTERM on// bash leaves a multi-GB `git clone` (and any subsequent pip downloads)@@ -340,14 +346,14 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {const onChunk = (chunk) => {for (const line of chunk.toString().split(/[\r\n]+/)) {const t = line.trimEnd();- if (t) send({ type: 'log', message: t });+ if (t) emit({ type: 'log', message: t });}};child.stdout.on('data', onChunk);child.stderr.on('data', onChunk);child.on('error', (err) => {runtimeInstallInFlight.delete(info.id);- send({ type: 'error', message: `Installer failed to spawn: ${err.message}` });+ emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });safeEnd();});child.on('close', async (code) => {@@ -360,18 +366,19 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {const binaryPresent = isByovRuntimeInstalled(info.id);const packagesReady = binaryPresent && await isByovRuntimeReady(info.id);if (code === 0 && binaryPresent && packagesReady) {- send({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });+ emit({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });} else if (code === 0 && !binaryPresent) {- send({ type: 'error', message: `Installer exited 0 but ${info.venvPython} is still missing. Re-run from a terminal to see what happened.` });+ emit({ type: 'error', message: `Installer exited 0 but ${info.venvPython} is still missing. Re-run from a terminal to see what happened.` });} else if (code === 0) {- send({ type: 'error', message: `Installer exited 0 but the venv can't import its core packages. Check the log above for pip errors; re-run from a terminal if needed.` });+ emit({ type: 'error', message: `Installer exited 0 but the venv can't import its core packages. Check the log above for pip errors; re-run from a terminal if needed.` });} else {- send({ type: 'error', message: `Installer exited with code ${code}.` });+ emit({ type: 'error', message: `Installer exited with code ${code}.` });}safeEnd();});req.on('close', () => {+ installLog.cancel();if (!child.killed && child.pid) {// Negative pid signals the whole process group — required because// `setup-image-video.sh` shells out to `uv pip install` / `git clone`,