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

address review (codex): honor auth expiry on the streamed HF LoRA install

[._.]/ Adam Eivy6e8eb4fd3fc4
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 1f2a50ab48..86480c411c 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).
// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for
@@ -282,42 +282,73 @@ export const installLoraFromHuggingface = ({ url, family, silent = false } = {})
});
// Streaming HF LoRA install — same install as installLoraFromHuggingface but
-// over an EventSource so the caller gets byte-level download progress. Resolves
-// with the new sidecar on the `complete` frame; rejects with an Error carrying
-// `.code` (e.g. 'HF_UNKNOWN_FAMILY', 'HF_ALREADY_INSTALLED') on `error`, so the
-// page can drive the same inline family-confirm retry it does for the POST path.
+// reads a byte-level progress stream. Resolves with the new sidecar on the
+// `complete` frame; rejects with an Error carrying `.code` (e.g.
+// 'HF_UNKNOWN_FAMILY', 'HF_ALREADY_INSTALLED') on an `error` frame, so the page
+// can drive the same inline family-confirm retry it does for the POST path.
// `onProgress({ received, total, progress })` fires per throttled download tick
// — `progress` is 0..1, or null when the server had no Content-Length to divide.
-export function installLoraFromHuggingfaceStream({ url, family, onProgress } = {}) {
+//
+// Uses fetch() + a stream reader rather than EventSource, mirroring
+// streamLocalLlmTest: (1) EventSource auto-reconnects on any transport drop,
+// which for this NON-idempotent install would silently start a second multi-GB
+// download; a single fetch never retries. (2) it honors session expiry — a 401
+// AUTH_REQUIRED bounces to /login via maybeRedirectToLogin exactly like
+// request(), instead of dead-ending on a generic stream error. The frames are
+// SSE-encoded (`data: {json}\n\n`).
+export async function installLoraFromHuggingfaceStream({ url, family, onProgress, signal } = {}) {
const params = new URLSearchParams({ url });
if (family) params.set('family', family);
- const es = new EventSource(`/api/loras/install/huggingface/stream?${params.toString()}`);
- return new Promise((resolve, reject) => {
- es.onmessage = (evt) => {
- let data;
- try { data = JSON.parse(evt.data); } catch { return; }
- if (data.type === 'progress') { onProgress?.(data); return; }
- if (data.type === 'complete') { es.close(); resolve(data.sidecar); return; }
- if (data.type === 'error') {
- es.close();
- const err = new Error(data.message || 'HuggingFace install failed');
- err.code = data.code || null;
- reject(err);
- }
- };
- es.onerror = () => {
- // This is a ONE-SHOT, non-idempotent install — a reconnect would start a
- // second server-side download of the same multi-GB LoRA. EventSource
- // auto-reconnects on ANY transport drop (firing onerror with readyState
- // CONNECTING, not CLOSED), so close it on the first error to stop the
- // reconnect, then reject. A normal completion/error already closed the ES
- // in onmessage, so this fires only on a genuine transport failure (a
- // failed open, or a drop before the terminal frame) — the settled promise
- // makes a late reject a no-op.
- es.close();
- reject(new Error('Download stream closed before completing'));
- };
- });
+ const response = await fetch(`${API_BASE}/loras/install/huggingface/stream?${params.toString()}`, { signal });
+ if (!response.ok || !response.body?.getReader) {
+ const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ maybeRedirectToLogin(response, err);
+ const e = new Error(err.error || `HTTP ${response.status}`);
+ e.code = err.code || null;
+ throw e;
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let sidecar;
+ let streamError = null;
+
+ const consume = (line) => {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith('data:')) return; // skip SSE blank separators / comments
+ let frame;
+ try { frame = JSON.parse(trimmed.slice(5).trim()); } catch { return; }
+ if (frame.type === 'progress') onProgress?.(frame);
+ else if (frame.type === 'complete') sidecar = frame.sidecar;
+ else if (frame.type === 'error') {
+ streamError = new Error(frame.message || 'HuggingFace install failed');
+ streamError.code = frame.code || null;
+ }
+ };
+
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ for (const line of lines) consume(line);
+ }
+ if (buffer.trim()) consume(buffer);
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+
+ // An `error` frame is the server's terminal failure signal — surface it (with
+ // its code) over a truncation error.
+ if (streamError) throw streamError;
+ // Clean EOF that never delivered a `complete` frame (server killed mid-stream,
+ // proxy cut the body) — throw so the caller's spinner clears; an intentional
+ // cancel sets signal.aborted and the caller suppresses that.
+ if (!sidecar && !signal?.aborted) throw new Error('Download stream ended before completing');
+ return sidecar;
}
// Civitai LoRA suggestions per runner family. Cached server-side for 1h.