All files / src utils.ts

100% Statements 209/209
100% Branches 131/131
100% Functions 26/26
100% Lines 209/209

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 3301x                     1x 514x 514x             1x 490x 1x 1x 490x 490x 490x   1x 450x 450x 450x 450x 450x 450x 19x 19x 19x 450x 19x 2x 2x 2x 19x 450x 450x   1x 1x 1x 1x 1x 1x 1x     1x 1x           1x   1x 1x 6x 6x 6x 1x   88x 88x 88x 88x 88x 88x 88x 142x 142x 142x 142x 142x     142x 142x 1x         1x 1x 1x 125x 125x 76x 54x 88x   1x 97x 97x 55x 55x   1x 24x 4x 4x   1x 172x 172x 106x 172x 102x 171x 100x 100x 100x             1x 102x 101x 102x 100x 100x   1x   1x 23x 23x 17x 17x 23x 32x 32x 32x 23x 23x 23x   1x 6x 3x 3x     1x 12x 3x 9x 12x               1x 65x 3x 3x 65x 65x                           1x 31x 2x 2x 31x 26x 26x 4x 4x 26x 25x 25x               1x 35x 35x 13x 13x 13x 11x 11x               1x 32x 32x 13x 27x 10x 10x 32x 6x 6x 6x 32x 3x 3x 2x 2x             1x 7x 7x               1x 44x 44x 7x 7x 11x 11x   1x 89x 84x 84x 84x 84x 84x 84x 89x 2x 2x 82x 82x     1x 81x   81x 81x         81x             1x 47x 35x 35x   1x 1x     1x 9x 9x   508x 508x 508x 508x                 1x 511x 511x 511x 9x 13x 7x 7x 7x 9x 9x  
import { Notice, type Modal } from "obsidian";
import { ServerStartingError, SessionTokenError } from "./api";
import { MESSAGES } from "./locales/en";
import { SERVER_MODE } from "./types";
import type { ServerMode } from "./types";
 
/**
 * Tag the modal's outer wrapper so the stylesheet keeps the close-X button
 * consistently visible. Call from every lilbee modal so users never have to
 * fall back to Escape to dismiss.
 */
export function tagModalChrome(modal: Modal): void {
    modal.modalEl.addClass("lilbee-modal-chrome");
}
 
/**
 * Bind Escape on the modal's own scope so dismissal works even when an inner
 * input (search box, textarea) holds focus, plus apply the chrome tag so the
 * close-X stays visible.
 */
export function bindEscapeToClose(modal: Modal): void {
    modal.scope.register([], "Escape", () => {
        modal.close();
        return false;
    });
    tagModalChrome(modal);
}
 
export function debounce<T extends (...args: unknown[]) => unknown>(
    fn: T,
    ms: number,
): { run: (...args: Parameters<T>) => void; cancel: () => void } {
    let timer: ReturnType<typeof setTimeout> | null = null;
    return {
        run: (...args: Parameters<T>) => {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => fn(...args), ms);
        },
        cancel: () => {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
        },
    };
}
 
export const DEBOUNCE_MS = 300;
export const RETRY_INTERVAL_MS = 5000;
export const NOTICE_DURATION_MS = 3000;
export const NOTICE_ERROR_DURATION_MS = 8000;
export const NOTICE_PERMANENT = 0;
export const TIME_REFRESH_INTERVAL_MS = 30000;
export const HEALTH_PROBE_INTERVAL_MS = 30_000;
// Number of consecutive failed health probes required before flipping the
// status bar to error. One blip every 30s should not announce a problem.
export const HEALTH_FAILURE_STREAK_THRESHOLD = 2;
export const SPINNER_MIN_DISPLAY_MS = 800;
// 2 minutes without a single SSE event is long enough to mean "server is wedged" —
// legitimate OCR/embed pauses are shorter. Larger than this and users think the
// plugin hung; smaller and a slow page-OCR pass could trip it. Applies to sync /
// add / crawl streams; pull streams are excluded because long-download idleness
// is expected.
export const STREAM_IDLE_TIMEOUT_MS = 120_000;
 
export class StreamIdleError extends Error {
    constructor(timeoutMs: number) {
        super(`stream idle for ${Math.round(timeoutMs / 1000)}s`);
        this.name = "StreamIdleError";
    }
}
 
export async function* withIdleTimeout<T>(
    gen: AsyncGenerator<T>,
    timeoutMs: number,
    abort: () => void,
): AsyncGenerator<T> {
    const iter = gen[Symbol.asyncIterator]();
    while (true) {
        let timer: ReturnType<typeof setTimeout> | null = null;
        const idle = new Promise<"idle">((resolve) => {
            timer = setTimeout(() => resolve("idle"), timeoutMs);
        });
        const race = await Promise.race([iter.next(), idle]);
        // Guard against vitest's fake-timer lifecycle leaving clearTimeout undefined
        // across test-file boundaries; in production both are always defined.
        if (timer !== null && typeof clearTimeout === "function") clearTimeout(timer);
        if (race === "idle") {
            abort();
            // Fire-and-forget: iter.return() lets the source generator exit its
            // try/finally blocks, but we don't await it — when the underlying
            // fetch is aborted mid-read, the current iter.next() may hang, and
            // awaiting return() would hang with it. abort() already propagates.
            void iter.return?.(undefined);
            throw new StreamIdleError(timeoutMs);
        }
        const { done, value } = race as IteratorResult<T>;
        if (done) return;
        yield value;
    }
}
 
export function formatAbbreviatedCount(count: number): string {
    if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
    if (count >= 1_000) return `${(count / 1_000).toFixed(1)}K`;
    return String(count);
}
 
export function ensureUrlScheme(url: string): string {
    if (/^https?:\/\//i.test(url)) return url;
    return `https://${url}`;
}
 
export function relativeTime(timestamp: number): string {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);
    if (seconds < 60) return "just now";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    return `${days}d ago`;
}
 
/**
 * Render the server's ISO-8601 timestamp ("2026-05-09T05:49:38.800771+00:00")
 * as a human "5m ago" / "3d ago" string. Returns the raw value when parsing
 * fails so callers never lose the data.
 */
export function relativeTimeFromIso(iso: string): string {
    if (!iso) return "";
    const t = Date.parse(iso);
    if (Number.isNaN(t)) return iso;
    return relativeTime(t);
}
 
const BYTE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const;
 
export function formatBytes(bytes: number): string {
    if (!Number.isFinite(bytes) || bytes < 0) return "0 B";
    if (bytes < 1024) return `${bytes} B`;
    let value = bytes;
    let unit = 0;
    while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
        value /= 1024;
        unit++;
    }
    const rounded = value >= 100 ? value.toFixed(0) : value.toFixed(1);
    return `${rounded} ${BYTE_UNITS[unit]}`;
}
 
export function formatRate(bytesPerSecond: number): string {
    if (!Number.isFinite(bytesPerSecond) || bytesPerSecond <= 0) return "";
    return `${formatBytes(bytesPerSecond)}/s`;
}
 
/** Pick the right session-token-invalid notice for the active server mode. */
export function sessionTokenInvalidMessage(serverMode: ServerMode): string {
    return serverMode === SERVER_MODE.MANAGED
        ? MESSAGES.NOTICE_SESSION_TOKEN_INVALID_MANAGED
        : MESSAGES.NOTICE_SESSION_TOKEN_INVALID;
}
 
/**
 * Pull a human-readable message out of an unknown thrown value.
 * Centralizes the `err instanceof Error ? err.message : <fallback>` pattern.
 * Stale-session-token errors get a dedicated, actionable message so the user
 * knows exactly where to fix it (see SessionTokenError in api.ts).
 */
export function errorMessage(err: unknown, fallback: string, serverMode?: ServerMode): string {
    if (err instanceof SessionTokenError) {
        return sessionTokenInvalidMessage(serverMode ?? SERVER_MODE.EXTERNAL);
    }
    return err instanceof Error ? err.message : fallback;
}
 
/**
 * Returns the most actionable message available for a Result error, falling back to the
 * supplied generic text. Priority:
 *   1. SessionTokenError → the stale-token notice (recovery action: paste a fresh token).
 *   2. Role-mismatch 422 → the server's `detail` string verbatim (tells the user which
 *      endpoint to use instead — see `isRoleMismatchDetail`).
 *   3. Everything else → the operation-specific fallback.
 *
 * Use at `.isErr()` call sites. Centralizing role-mismatch detection here means every
 * caller (Settings panels, CatalogModal, …) surfaces the same actionable diagnostic
 * without duplicating the parse logic.
 */
export function noticeForResultError(err: unknown, fallback: string, serverMode?: ServerMode): string {
    if (err instanceof SessionTokenError) {
        return sessionTokenInvalidMessage(serverMode ?? SERVER_MODE.EXTERNAL);
    }
    if (err instanceof Error) {
        const detail = extractServerErrorDetail(err.message);
        if (detail !== null && isRoleMismatchDetail(detail)) {
            return detail;
        }
    }
    return fallback;
}
 
/**
 * Pull a human-readable error message out of an SSE `error` event payload.
 * Server may send either a raw string or `{message: string}`. Falls back to
 * the given `unknownFallback` if neither shape matches. Centralizes the
 * `typeof d === "string" ? d : (d.message ?? "unknown error")` pattern.
 */
export function extractSseErrorMessage(data: unknown, unknownFallback: string): string {
    if (typeof data === "string") return data;
    if (data && typeof data === "object" && "message" in data) {
        const msg = (data as { message?: unknown }).message;
        if (typeof msg === "string") return msg;
    }
    return unknownFallback;
}
 
/**
 * Extract the server's `detail` string from a `Server responded <status>: <body>`
 * error message when the body is JSON of shape `{"detail": "..."}`. Returns null
 * when the error is not in this shape, the body is not JSON, or `detail` is not
 * a string. Used to surface server-authored role-mismatch diagnostics verbatim.
 */
export function extractServerErrorDetail(message: string): string | null {
    const colonIdx = message.indexOf(":");
    if (colonIdx === -1) return null;
    const body = message.slice(colonIdx + 1).trim();
    if (!body) return null;
    try {
        const parsed = JSON.parse(body) as unknown;
        if (parsed && typeof parsed === "object" && "detail" in parsed) {
            const detail = (parsed as { detail?: unknown }).detail;
            if (typeof detail === "string") return detail;
        }
    } catch {
        return null;
    }
    return null;
}
 
/**
 * Distinguishes the role-mismatch 422 (e.g. setting a vision model as chat) from an
 * auth-shaped 422 by the `Set it via PUT /api/models/` remedy phrase. The full prefix
 * keeps unrelated 422s that just happen to mention the endpoint from being misclassified.
 */
export function isRoleMismatchDetail(detail: string): boolean {
    return detail.includes("Set it via PUT /api/models/");
}
 
/**
 * Compute a percent (0–100) from a server SSE progress payload.
 * Accepts `{percent, current, total}` shape and prefers `percent` if present;
 * otherwise derives from `current/total`. Returns undefined when neither is usable
 * (e.g. total is zero/missing, or current is missing).
 */
export function percentFromSse(data: { percent?: number; current?: number; total?: number }): number | undefined {
    if (data.percent !== undefined) return data.percent;
    if (data.total && data.current !== undefined) {
        return Math.round((data.current / data.total) * 100);
    }
    return undefined;
}
 
export function formatElapsed(ms: number): string {
    if (!Number.isFinite(ms) || ms < 0) return "00:00";
    const totalSeconds = Math.floor(ms / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    const mm = String(minutes).padStart(2, "0");
    const ss = String(seconds).padStart(2, "0");
    if (hours > 0) {
        return `${hours}:${mm}:${ss}`;
    }
    return `${mm}:${ss}`;
}
 
/** Total system RAM in GB, rounded; null when ``os`` is unavailable. */
export function getSystemMemoryGB(): number | null {
    try {
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const os = require("os") as { totalmem(): number };
        return Math.round(os.totalmem() / (1024 * 1024 * 1024));
        /* v8 ignore next 3 */
    } catch {
        return null;
    }
}
 
/**
 * The local machine's RAM only constrains model loads in managed mode where
 * the server runs on this machine. In external mode the server lives on
 * another host whose RAM we don't know — return null and skip the warning.
 */
export function getRelevantSystemMemoryGB(serverMode: ServerMode): number | null {
    if (serverMode !== SERVER_MODE.MANAGED) return null;
    return getSystemMemoryGB();
}
 
const SERVER_UNREACHABLE_DEBOUNCE_MS = 5000;
let lastServerUnreachableAt = 0;
 
/** Reset the debounce timer (test-only). */
export function _resetServerUnreachableDebounce(): void {
    lastServerUnreachableAt = 0;
}
 
function looksLikeConnectionRefused(err: Error): boolean {
    const msg = err.message.toLowerCase();
    return msg.includes("econnrefused") || msg.includes("failed to fetch") || msg.includes("fetch failed");
}
 
/**
 * Inspect a thrown error and emit at most one "server unreachable" notice per
 * debounce window, swallowing the per-feature message in that case. Returns
 * ``true`` when the error was handled and the caller should skip its own
 * follow-up notice. ``ServerStartingError`` is treated as unreachable too —
 * the user can already see the "starting" UI elsewhere.
 */
export function noticeServerUnreachableIfApplicable(err: unknown): boolean {
    if (err instanceof ServerStartingError) return true;
    if (!(err instanceof Error)) return false;
    if (!looksLikeConnectionRefused(err)) return false;
    const now = Date.now();
    if (now - lastServerUnreachableAt > SERVER_UNREACHABLE_DEBOUNCE_MS) {
        lastServerUnreachableAt = now;
        new Notice(MESSAGES.NOTICE_SERVER_UNREACHABLE);
    }
    return true;
}