All files / src/views catalog-helpers.ts

100% Statements 66/66
100% Branches 38/38
100% Functions 25/25
100% Lines 55/55

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          8x 8x           8x             8x             30x         213x           692x         171x         48x         11x 11x 5x 11x 2x         350x     29x         39x 39x 30x 30x 30x 2x   28x       39x 13x 13x 8x         23x       22x 14x         8x             5x       461x                 57x 15x 15x 30x 8x 8x 8x   25x   15x       30x       43x       7x 7x 6x 6x 6x   6x 3x 3x 3x 2x 2x        
import type { App } from "obsidian";
import type { CatalogEntry, CatalogSource, CatalogTab, KeyStatus, ModelTask } from "../types";
import { CATALOG_SOURCE, CATALOG_TAB, HOSTED_SOURCES, KEY_STATUS, MODEL_TASK } from "../types";
import { MESSAGES } from "../locales/en";
 
const DISCOVER_RAIL_LIMIT = 12;
const TASK_TO_TAB: Record<ModelTask, CatalogTab> = {
    [MODEL_TASK.CHAT]: CATALOG_TAB.CHAT,
    [MODEL_TASK.EMBEDDING]: CATALOG_TAB.EMBED,
    [MODEL_TASK.VISION]: CATALOG_TAB.VISION,
    [MODEL_TASK.RERANK]: CATALOG_TAB.RERANK,
};
const TAB_TO_TASK: Partial<Record<CatalogTab, ModelTask>> = {
    [CATALOG_TAB.CHAT]: MODEL_TASK.CHAT,
    [CATALOG_TAB.EMBED]: MODEL_TASK.EMBEDDING,
    [CATALOG_TAB.VISION]: MODEL_TASK.VISION,
    [CATALOG_TAB.RERANK]: MODEL_TASK.RERANK,
};
 
export const KEY_STATUS_PILL_CLASS = {
    READY: "lilbee-key-status-pill-ready",
    NEEDS_KEY: "lilbee-key-status-pill-needs-key",
} as const;
 
/** Hosted rows (frontier + local servers): selectable, no download. */
export function hostedRowsOnly(rows: CatalogEntry[]): CatalogEntry[] {
    return rows.filter((row) => HOSTED_SOURCES.has(row.source));
}
 
/** Everything that isn't hosted — native catalog rows the server can download. */
export function localRowsOnly(rows: CatalogEntry[]): CatalogEntry[] {
    return rows.filter((row) => !HOSTED_SOURCES.has(row.source));
}
 
/** A hosted row is usable unless it's a frontier model still missing its key.
 * Local servers (Ollama, LM Studio) report `key_status` null, so they always pass. */
export function isUsableHostedRow(row: CatalogEntry): boolean {
    return HOSTED_SOURCES.has(row.source) && row.key_status !== KEY_STATUS.MISSING_KEY;
}
 
/** True when at least one hosted row is ready to select right now. */
export function hasReadyHostedRow(rows: CatalogEntry[]): boolean {
    return rows.some(isUsableHostedRow);
}
 
/** Local-server sources (Ollama, LM Studio) lead hosted listings; frontier trails. Lower sorts first. */
function hostedSourceRank(source: CatalogSource): number {
    return source === CATALOG_SOURCE.FRONTIER ? 1 : 0;
}
 
/** Local-first, then provider, then name — deterministic ordering for hosted rows. */
function compareHostedRows(a: CatalogEntry, b: CatalogEntry): number {
    const rankDiff = hostedSourceRank(a.source) - hostedSourceRank(b.source);
    if (rankDiff !== 0) return rankDiff;
    const providerDiff = (a.provider ?? "").localeCompare(b.provider ?? "");
    if (providerDiff !== 0) return providerDiff;
    return a.display_name.localeCompare(b.display_name);
}
 
/** Selectable hosted rows, local-first: local servers always, frontier only with a ready key. Returns [ref, label]. */
export function hostedOptions(rows: CatalogEntry[]): Array<[string, string]> {
    return rows
        .filter(isUsableHostedRow)
        .sort(compareHostedRows)
        .map((e) => [e.hf_repo, `${e.display_name}${e.provider ? ` [${e.provider}]` : ""}`]);
}
 
/** Hosted rows grouped by provider, local-server groups before frontier, providers alphabetical within a rank. */
export function groupByProvider(rows: CatalogEntry[]): [string, CatalogEntry[]][] {
    const groups = new Map<string, CatalogEntry[]>();
    for (const row of rows) {
        const provider = row.provider ?? "";
        const existing = groups.get(provider);
        if (existing) {
            existing.push(row);
        } else {
            groups.set(provider, [row]);
        }
    }
    // Each provider maps to one source, so rank the group by its first row's source.
    return [...groups.entries()].sort(([aProvider, aRows], [bProvider, bRows]) => {
        const rankDiff = hostedSourceRank(aRows[0].source) - hostedSourceRank(bRows[0].source);
        if (rankDiff !== 0) return rankDiff;
        return aProvider.localeCompare(bProvider);
    });
}
 
export function renderProviderPill(parent: HTMLElement, provider: string): HTMLElement {
    return parent.createSpan({ cls: "lilbee-provider-pill", text: provider });
}
 
export function renderKeyStatusPill(parent: HTMLElement, status: KeyStatus): HTMLElement {
    if (status === KEY_STATUS.READY) {
        return parent.createSpan({
            cls: `lilbee-key-status-pill ${KEY_STATUS_PILL_CLASS.READY}`,
            text: MESSAGES.PILL_KEY_READY,
        });
    }
    return parent.createSpan({
        cls: `lilbee-key-status-pill ${KEY_STATUS_PILL_CLASS.NEEDS_KEY}`,
        text: MESSAGES.PILL_KEY_NEEDS_KEY,
    });
}
 
export function taskToTabId(task: ModelTask): CatalogTab {
    return TASK_TO_TAB[task];
}
 
export function tabIdToTask(tab: CatalogTab): ModelTask | null {
    return TAB_TO_TASK[tab] ?? null;
}
 
/**
 * Featured-first ordering, capped at 12. When the user has an active chat
 * model the chat-task entries float to the top so the rail leads with rows
 * matching what they're already using.
 */
export function forYouRail(entries: CatalogEntry[], activeChatModelRef: string): CatalogEntry[] {
    const featured = entries.filter((e) => e.featured);
    const preferChat = activeChatModelRef !== "";
    const sorted = [...featured].sort((a, b) => {
        if (preferChat) {
            const aChat = a.task === MODEL_TASK.CHAT ? 0 : 1;
            const bChat = b.task === MODEL_TASK.CHAT ? 0 : 1;
            if (aChat !== bChat) return aChat - bChat;
        }
        return b.downloads - a.downloads;
    });
    return sorted.slice(0, DISCOVER_RAIL_LIMIT);
}
 
export function yourCollectionRail(entries: CatalogEntry[]): CatalogEntry[] {
    return entries.filter((e) => e.installed);
}
 
export function freshRail(entries: CatalogEntry[]): CatalogEntry[] {
    return [...entries].sort((a, b) => b.downloads - a.downloads).slice(0, DISCOVER_RAIL_LIMIT);
}
 
export function deepLinkToApiKeySettings(app: App, provider: string): void {
    const settingApi = (app as App & { setting?: { open(): void; openTabById(id: string): void } }).setting;
    if (!settingApi) return;
    settingApi.open();
    settingApi.openTabById("lilbee");
    window.setTimeout(() => {
        // Timer can fire after the modal closes; Node test envs don't have a global document.
        if (typeof activeDocument === "undefined") return;
        const escaped = provider.toLowerCase().replace(/[^a-z0-9-]/g, "-");
        const target = activeDocument.querySelector(`[data-lilbee-api-key="${escaped}"]`);
        if (target instanceof HTMLElement) {
            target.scrollIntoView({ behavior: "smooth", block: "center" });
            target.focus();
        }
    }, 50);
}