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
log HuggingFace model downloads to the server console
Adam Eivydb7a549b93a1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b56e6056e2..ea8f2f189e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Fixes+- **HuggingFace model downloads (Flux and every other image/video/music pull) now log to the server console.** Triggering a base-model download showed a progress bar in the UI but left no trace in the server log — the entire download path emitted progress *only* over the SSE stream to the browser, and PortOS has no HTTP access logger, so a headless/PM2 log had no record the multi-GB fetch ever ran. The shared SSE driver (`server/lib/sseDownload.js#startHfDownloadStream`, the single chokepoint behind the image, video, and music download endpoints) now writes single-line, emoji-prefixed log lines for the start of each repo pull (`⬇️`, with a forced-re-fetch marker), each file as it streams, a cache hit that skips the download (`📦`), the outcome (`✅` complete with byte count / `❌` failed with the error message), and client-disconnect cancellation (`🛑`) — while cancelled results are deliberately not logged as failures.+- **Audio → MIDI transcription now prompts for HuggingFace access instead of dead-ending on a gated-repo traceback.** MuScriptor's model weights turned out to live in a *gated* HuggingFace repo (`MuScriptor/muscriptor-*`), so the first transcription on a fresh install — even right after the runtime auto-installs — 403'd with a raw `GatedRepoError: Access to model … is restricted` traceback the user couldn't act on. The MuScriptor sidecar now runs under the shared `install_hf_error_handler` (the same cause-chain walker the image/video runners use), so a gated download emits a structured `USER_ERROR:gated_repo:<repo>` marker; the server classifies that into a typed `gated_repo` SSE frame (carrying the repo id), and the client opens the same license-accept + token-paste prompt the gated image models use (reusing `HfTokenBanner`): accept the model's license, paste a HuggingFace read token, and the transcription you originally asked for re-runs automatically. Gated-error detection is now shared via `isGatedRepoError`/`extractGatedRepo` in `server/lib/hfErrors.js` (also adopted by the image runner's prose fallback).- **Layered Intelligence no longer silently wedges when pinned to an API-only provider.** After LI became an agent-backed scheduled task (#2322), its reasoning run needs a CLI/TUI coding provider (one with a file-writing harness to emit the `.agent-done` sentinel). Installs that carried an HTTP `api` provider (ollama / LM Studio) through migration 184 hit a dead end: every dispatch failed provider resolution *before* an agent registered, so nothing updated the task's status and it sat pending forever — silently blocking the app's whole improvement slot. Now the LI `buildTaskInput` hook detects an api-only provider up front and **skips** with an actionable reason (surfaced on the Intelligence tab: *"pick a CLI/TUI provider — e.g. the Claude Ollama sample"*), and, as a general safety net, any agent task that fails provider resolution with a **permanent** config error is **blocked** with a `provider-config` reason instead of re-failing on every dispatch.diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex 2530a6fbad..4c01a0beb9 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -52,7 +52,13 @@ export async function startHfDownloadStream({ req, res, repo, repos, alreadyDownlet aborted = false;req.on('close', () => {aborted = true;- if (currentHandle) currentHandle.kill();+ // Only a live handle means a download was mid-flight — `close` also fires+ // on normal completion (currentHandle is nulled after each repo), so this+ // guard keeps the cancel line out of the log on a clean finish.+ if (currentHandle) {+ console.log(`🛑 HuggingFace download cancelled (client disconnect)`);+ currentHandle.kill();+ }safeEnd();});@@ -71,19 +77,38 @@ export async function startHfDownloadStream({ req, res, repo, repos, alreadyDown// (etag match) and pulls only what's gone.if (existing.cached && !force) {totalSize += existing.sizeBytes || 0;+ console.log(`📦 HuggingFace repo already cached: ${r} (${existing.sizeBytes} bytes)`);send({ type: 'log', message: `${r} already cached (${existing.sizeBytes} bytes).`, repo: r, sizeBytes: existing.sizeBytes });continue;}if (inFlight.has(r)) {+ console.log(`⏭️ HuggingFace download already running for ${r} — refusing duplicate`);send({ type: 'error', message: `Another download for ${r} is already running.`, kind: 'already_running', repo: r });return safeEnd();}- const handle = downloadHfRepo({ repo: r, onEvent: (ev) => send({ ...ev, repo: r }) });+ // Server-side visibility for a pull that used to surface only on the SSE+ // stream (the browser) — a headless/PM2 log had no record the multi-GB+ // fetch ever ran. Log the start, each file as it streams, and the outcome.+ console.log(`⬇️ Downloading HuggingFace repo: ${r}${force ? ' (forced re-fetch)' : ''}`);+ const handle = downloadHfRepo({+ repo: r,+ onEvent: (ev) => {+ if (ev.type === 'progress' && ev.file) {+ console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);+ }+ send({ ...ev, repo: r });+ },+ });currentHandle = handle;inFlight.set(r, handle);try {- await handle.promise;+ const result = await handle.promise;downloadedAny = true;+ if (result?.ok) {+ console.log(`✅ HuggingFace download complete: ${r} (${result.sizeBytes || 0} bytes)`);+ } else if (result?.errorKind !== 'cancelled') {+ console.error(`❌ HuggingFace download failed: ${r} — ${result?.errorMessage || 'unknown error'}`);+ }} finally {inFlight.delete(r);currentHandle = null;diff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.jsindex 9111923e87..b99eaed4c3 100644--- a/server/lib/sseDownload.test.js+++ b/server/lib/sseDownload.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// startHfDownloadStream's cache short-circuit (`if (existing.cached) continue`)// must be bypassable via `force` — otherwise a repair that deleted one shard of@@ -11,7 +11,9 @@ vi.mock('./hfCache.js', () => ({}));vi.mock('./hfDownload.js', () => ({- downloadHfRepo: vi.fn(() => ({ promise: Promise.resolve(), kill: vi.fn() })),+ // Resolve with the real `{ ok, sizeBytes }` shape downloadHfRepo always+ // returns — a bare undefined would read as a failure to the outcome logging.+ downloadHfRepo: vi.fn(() => ({ promise: Promise.resolve({ ok: true, sizeBytes: 100 }), kill: vi.fn() })),}));import { startHfDownloadStream } from './sseDownload.js';@@ -62,3 +64,120 @@ describe('startHfDownloadStream force', () => {expect(events.at(-1)).toMatchObject({ type: 'complete', message: 'org/encoder downloaded.' });});});++// The download flow used to surface progress ONLY on the SSE stream to the+// browser — a headless/PM2 server log had no record the multi-GB pull ever+// ran. These assert the server-side console visibility added to the driver.+describe('startHfDownloadStream server-side logging', () => {+ let logSpy;+ let errorSpy;++ // req double whose `close` handler we can fire on demand (to simulate the+ // EventSource client hanging up mid-download).+ const makeLoggingReqRes = () => {+ let closeHandler;+ const req = { on: vi.fn((ev, cb) => { if (ev === 'close') closeHandler = cb; }) };+ const res = {+ writableEnded: false,+ writeHead: vi.fn(),+ write: vi.fn(() => true),+ end: vi.fn(function end() { res.writableEnded = true; }),+ };+ return { req, res, fireClose: () => closeHandler?.() };+ };++ const logged = (spy) => spy.mock.calls.map((c) => String(c[0]));++ beforeEach(() => {+ vi.clearAllMocks();+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ logSpy.mockRestore();+ errorSpy.mockRestore();+ });++ it('logs start, per-file progress, and completion for a fresh download', async () => {+ inspectModelCache.mockResolvedValue({ cached: false });+ downloadHfRepo.mockImplementation(({ onEvent }) => ({+ promise: (async () => {+ onEvent({ type: 'progress', step: 1, total: 2, file: 'model-00001-of-00002.safetensors' });+ return { ok: true, sizeBytes: 4096 };+ })(),+ kill: vi.fn(),+ }));++ const { req, res } = makeLoggingReqRes();+ await startHfDownloadStream({ req, res, repo: 'org/flux-fresh' });++ const lines = logged(logSpy);+ expect(lines.some((l) => l.includes('Downloading HuggingFace repo: org/flux-fresh'))).toBe(true);+ expect(lines.some((l) => l.includes('org/flux-fresh: model-00001-of-00002.safetensors (1/2)'))).toBe(true);+ expect(lines.some((l) => l.includes('download complete: org/flux-fresh (4096 bytes)'))).toBe(true);+ expect(errorSpy).not.toHaveBeenCalled();+ });++ it('logs the forced re-fetch marker', async () => {+ inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 10 });+ downloadHfRepo.mockImplementation(() => ({+ promise: Promise.resolve({ ok: true, sizeBytes: 10 }),+ kill: vi.fn(),+ }));++ const { req, res } = makeLoggingReqRes();+ await startHfDownloadStream({ req, res, repo: 'org/flux-force', force: true });++ expect(logged(logSpy).some((l) => l.includes('Downloading HuggingFace repo: org/flux-force (forced re-fetch)'))).toBe(true);+ });++ it('logs a cache hit without spawning a download', async () => {+ inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 2048 });++ const { req, res } = makeLoggingReqRes();+ await startHfDownloadStream({ req, res, repo: 'org/flux-cached' });++ expect(downloadHfRepo).not.toHaveBeenCalled();+ expect(logged(logSpy).some((l) => l.includes('already cached: org/flux-cached (2048 bytes)'))).toBe(true);+ });++ it('logs a failed download at error level (non-cancelled)', async () => {+ inspectModelCache.mockResolvedValue({ cached: false });+ downloadHfRepo.mockImplementation(() => ({+ promise: Promise.resolve({ ok: false, errorKind: 'auth', errorMessage: 'gated repo' }),+ kill: vi.fn(),+ }));++ const { req, res } = makeLoggingReqRes();+ await startHfDownloadStream({ req, res, repo: 'org/flux-fail' });++ expect(logged(errorSpy).some((l) => l.includes('download failed: org/flux-fail — gated repo'))).toBe(true);+ });++ it('logs cancellation and kills the child on client disconnect', async () => {+ inspectModelCache.mockResolvedValue({ cached: false });+ let resolveDownload;+ const kill = vi.fn();+ downloadHfRepo.mockImplementation(() => ({+ promise: new Promise((resolve) => { resolveDownload = resolve; }),+ kill,+ }));++ const { req, res, fireClose } = makeLoggingReqRes();+ const done = startHfDownloadStream({ req, res, repo: 'org/flux-cancel' });++ // Wait until the driver has actually spawned the download (currentHandle+ // set) before simulating the client hanging up.+ await vi.waitFor(() => expect(downloadHfRepo).toHaveBeenCalled());+ fireClose();++ expect(kill).toHaveBeenCalled();+ expect(logged(logSpy).some((l) => l.includes('cancelled (client disconnect)'))).toBe(true);++ // A cancelled result must NOT be logged as a failure.+ resolveDownload({ ok: false, errorKind: 'cancelled', errorMessage: 'Cancelled' });+ await done;+ expect(logged(errorSpy).some((l) => l.includes('download failed'))).toBe(false);+ });+});