// SRT Translator — frontend (vanilla JS, no build step).
const $ = (s) => document.querySelector(s);
const LS_SETTINGS = 'srt-tr:settings:v1';
const LS_WORK = 'srt-tr:work:v1:';
const CTX_STEPS = [2048, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 131072, 196608, 262144];
const SETTING_IDS = ['contextLength', 'kvCacheK', 'kvCacheV', 'flashAttention', 'gpuRatio', 'numGpu', 'evalBatchSize', 'unloadOthers', 'temperature', 'topP', 'topK', 'minP', 'repeatPenalty', 'seed', 'disableThinking'];
const OPTION_IDS = ['source', 'target', 'mode', 'batchSize', 'contextBefore', 'contextAfter', 'maxLineLength', 'concurrency', 'songs', 'notes', 'profile'];
const S = {
meta: null,
engine: 'lmstudio',
engineCfg: {},
connected: false,
caps: null,
models: [],
model: null,
modelInfo: null,
applied: {}, // model -> load config applied by our last load (LM Studio)
file: null,
tr: {},
status: {},
rows: new Map(),
job: null,
rowJobs: new Map(),
};
// ---------------------------------------------------------------- utilities
async function api(path, body, { raw = false, query = '' } = {}) {
const res = await fetch(path + query, {
method: body === undefined ? 'GET' : 'POST',
headers: raw ? { 'content-type': 'application/octet-stream' } : { 'content-type': 'application/json' },
body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
return data;
}
const GB = 2 ** 30;
const fmtGB = (b) => (b == null || Number.isNaN(b) ? '—' : `${(b / GB).toFixed(b < 10 * GB ? 2 : 1)} GB`);
// Sizes under 1 GB read better in MB ("61 MB / 498 MB").
const fmtSize = (b) => (b == null ? '—' : b < 2 ** 30 ? `${Math.round(b / 2 ** 20)} MB` : fmtGB(b));
const fmtInt = (n) => (n == null ? '—' : Math.round(n).toLocaleString('pl-PL'));
const fmtCtx = (n) => (n >= 1024 ? `${Math.round(n / 1024)}k` : String(n));
function fmtDur(ms) {
if (ms == null || !Number.isFinite(ms)) return '—';
const s = Math.round(ms / 1000);
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
return h ? `${h} h ${m} min` : m ? `${m} min ${sec} s` : `${sec} s`;
}
const shortTime = (t) => t.replace(/^00:/, '').replace(/,(\d)\d\d$/, '.$1');
const visibleLen = (s) => s.replace(/<[^>]+>|\{\\[^}]*\}/g, '').replace(/\n/g, ' ').length;
const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
let toastTimer;
function toast(msg, err = false) {
const t = $('#toast');
t.textContent = msg;
t.className = 'toast' + (err ? ' err' : '');
t.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { t.hidden = true; }, err ? 7000 : 3500);
}
async function busy(btn, fn) {
btn.classList.add('busy');
btn.disabled = true;
try { return await fn(); } finally { btn.classList.remove('busy'); btn.disabled = false; }
}
function langLabel(code) {
const l = S.meta?.languages.find((x) => x.code === code);
return l ? l.namePl : code;
}
// ---------------------------------------------------------------- persistence
function readValue(id) {
const el = document.getElementById(id);
if (!el) return undefined;
if (el.type === 'checkbox') return el.checked;
return el.value;
}
function writeValue(id, v) {
const el = document.getElementById(id);
if (!el || v === undefined || v === null) return;
if (el.type === 'checkbox') el.checked = !!v; else el.value = v;
}
function collectSettings() {
const s = {};
for (const id of SETTING_IDS) s[id] = readValue(id);
for (const k of ['contextLength', 'numGpu', 'evalBatchSize', 'topK', 'seed']) s[k] = s[k] === '' ? undefined : Number(s[k]);
for (const k of ['temperature', 'topP', 'minP', 'repeatPenalty']) s[k] = s[k] === '' ? undefined : Number(s[k]);
if (s.gpuRatio === '') s.gpuRatio = undefined;
return s;
}
function collectOptions() {
const o = {};
for (const id of OPTION_IDS) o[id] = readValue(id);
for (const k of ['batchSize', 'contextBefore', 'contextAfter', 'maxLineLength', 'concurrency']) o[k] = Number(o[k]) || 0;
o.batchSize ||= 1; o.concurrency ||= 1;
// Dedicated MT models need an explicit source language — use the detected one.
const prof = effectiveProfile();
if (o.source === 'auto' && S.meta.profiles[prof]?.needsSource && S.file?.detectedLanguage) o.source = S.file.detectedLanguage;
return o;
}
function engineConfig() {
const c = { kind: S.engine, baseUrl: $('#baseUrl').value.trim() || S.meta.engines[S.engine].baseUrl };
if (S.engine === 'openai') {
c.apiKey = $('#apiKey').value.trim() || undefined;
c.structuredOutput = $('#structuredOutput').checked;
const extra = $('#extraBody').value.trim();
if (extra) {
try { c.extraBody = JSON.parse(extra); } catch { throw new Error('Pole „Dodatkowe pola żądania” nie jest poprawnym JSON-em.'); }
}
}
return c;
}
function saveSettings() {
const cur = loadSaved();
cur.engine = S.engine;
cur.engineCfg ||= {};
cur.engineCfg[S.engine] = { baseUrl: $('#baseUrl').value.trim(), apiKey: $('#apiKey').value, structuredOutput: $('#structuredOutput').checked, extraBody: $('#extraBody').value };
cur.model ||= {};
if (S.model) cur.model[S.engine] = S.model;
cur.settings = collectSettingsRaw();
cur.options = Object.fromEntries(OPTION_IDS.map((id) => [id, readValue(id)]));
cur.exp = { format: $('#exportFormat').value, eol: $('#exportEol').value, bom: $('#exportBom').checked };
try { localStorage.setItem(LS_SETTINGS, JSON.stringify(cur)); } catch { /* storage unavailable */ }
}
function collectSettingsRaw() { return Object.fromEntries(SETTING_IDS.map((id) => [id, readValue(id)])); }
function loadSaved() {
try { return JSON.parse(localStorage.getItem(LS_SETTINGS)) || {}; } catch { return {}; }
}
function workKey() {
if (!S.file) return null;
const sig = S.file.cues.slice(0, 5).map((c) => c.text).join('|');
let h = 0;
for (let i = 0; i < sig.length; i++) h = (h * 31 + sig.charCodeAt(i)) | 0;
return `${LS_WORK}${S.file.name}:${S.file.cues.length}:${h}:${$('#target').value}`;
}
const saveWork = debounce(() => {
const k = workKey();
if (!k) return;
try { localStorage.setItem(k, JSON.stringify({ tr: S.tr, status: S.status, at: Date.now() })); } catch { /* quota */ }
}, 800);
function loadWork() {
const k = workKey();
if (!k) return;
try {
const w = JSON.parse(localStorage.getItem(k));
S.tr = w?.tr || {};
S.status = w?.status || {};
} catch { S.tr = {}; S.status = {}; }
}
// ---------------------------------------------------------------- init
async function init() {
S.meta = await api('/api/meta');
const langOpts = S.meta.languages.map((l) => ``).join('');
$('#source').innerHTML = `${langOpts}`;
$('#target').innerHTML = langOpts;
$('#target').value = 'pl';
const kv = S.meta.kvTypes.map((t) => ``).join('');
$('#kvCacheK').innerHTML = kv; $('#kvCacheV').innerHTML = kv;
$('#kvCacheK').value = 'f16'; $('#kvCacheV').value = 'f16';
$('#contextLength').value = 8192;
const saved = loadSaved();
S.engine = saved.engine || 'lmstudio';
S.engineCfg = saved.engineCfg || {};
for (const [id, v] of Object.entries(saved.settings || {})) writeValue(id, v);
for (const [id, v] of Object.entries(saved.options || {})) if (id !== 'profile') writeValue(id, v);
if (saved.exp) { writeValue('exportFormat', saved.exp.format); writeValue('exportEol', saved.exp.eol); writeValue('exportBom', saved.exp.bom); }
bindUi();
selectEngine(S.engine, true);
syncCtxRange();
restoreLastFile();
connect().catch(() => {});
}
function bindUi() {
document.querySelectorAll('#engineSeg button').forEach((b) => b.addEventListener('click', () => selectEngine(b.dataset.kind)));
$('#connectBtn').addEventListener('click', () => busy($('#connectBtn'), () => connect(true)));
$('#baseUrl').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('#connectBtn').click(); });
$('#refreshModels').addEventListener('click', () => busy($('#refreshModels'), () => loadModels(true)));
$('#modelSelect').addEventListener('change', (e) => selectModel(e.target.value));
$('#profile').addEventListener('change', () => { renderProfile(); saveSettings(); });
$('#ctxRange').addEventListener('input', () => {
$('#contextLength').value = ctxSteps()[Number($('#ctxRange').value)];
onSettingsChange();
});
$('#contextLength').addEventListener('change', () => { syncCtxRange(); onSettingsChange(); });
for (const id of ['kvCacheK', 'kvCacheV', 'flashAttention', 'gpuRatio', 'numGpu', 'evalBatchSize', 'unloadOthers']) document.getElementById(id).addEventListener('change', onSettingsChange);
for (const id of ['temperature', 'topP', 'topK', 'minP', 'repeatPenalty', 'seed', 'disableThinking', ...OPTION_IDS.filter((x) => x !== 'profile'), 'apiKey', 'structuredOutput', 'extraBody', 'exportFormat', 'exportEol', 'exportBom']) {
document.getElementById(id).addEventListener('change', saveSettings);
}
$('#target').addEventListener('change', () => { if (S.file) { loadWork(); renderTable(); } });
$('#maxLineLength').addEventListener('change', () => refreshAllFlags());
$('#songs').addEventListener('change', () => { if (S.file) { renderFile(); refreshAllFlags(); applyFilter(); } });
$('#applyRecommended').addEventListener('click', applyRecommended);
$('#loadBtn').addEventListener('click', () => busy($('#loadBtn'), loadModel));
$('#unloadBtn').addEventListener('click', () => busy($('#unloadBtn'), unloadModel));
$('#pullBtn').addEventListener('click', () => startPull());
$('#pullName').addEventListener('keydown', (e) => { if (e.key === 'Enter') startPull(); });
// file
const drop = $('#drop');
$('#pickFile').addEventListener('click', (e) => { e.stopPropagation(); $('#fileInput').click(); });
drop.addEventListener('click', () => $('#fileInput').click());
$('#changeFile').addEventListener('click', () => $('#fileInput').click());
$('#fileInput').addEventListener('change', (e) => { if (e.target.files[0]) openFile(e.target.files[0]); e.target.value = ''; });
for (const ev of ['dragenter', 'dragover']) document.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add('drag'); });
for (const ev of ['dragleave', 'drop']) document.addEventListener(ev, (e) => { e.preventDefault(); if (ev === 'drop' || e.target === drop) drop.classList.remove('drag'); });
document.addEventListener('drop', (e) => { const f = e.dataTransfer?.files?.[0]; if (f) openFile(f); });
$('#encoding').addEventListener('change', () => reparse());
$('#startBtn').addEventListener('click', () => startJob(false));
$('#resumeBtn').addEventListener('click', () => startJob(true));
$('#stopBtn').addEventListener('click', stopJob);
$('#downloadBtn').addEventListener('click', download);
$('#onlyFlagged').addEventListener('change', applyFilter);
$('#search').addEventListener('input', debounce(applyFilter, 150));
}
// ---------------------------------------------------------------- engine
function selectEngine(kind, initial = false) {
if (!initial) saveSettings();
S.engine = kind;
document.body.dataset.engine = kind;
document.querySelectorAll('#engineSeg button').forEach((b) => b.classList.toggle('active', b.dataset.kind === kind));
const cfg = S.engineCfg[kind] || loadSaved().engineCfg?.[kind] || {};
$('#baseUrl').value = cfg.baseUrl || S.meta.engines[kind].baseUrl;
$('#baseUrl').placeholder = S.meta.engines[kind].baseUrl;
$('#apiKey').value = cfg.apiKey || '';
$('#structuredOutput').checked = cfg.structuredOutput !== false;
$('#extraBody').value = cfg.extraBody || '';
S.connected = false; S.models = []; S.model = null; S.modelInfo = null;
setPill('', 'niepołączony');
$('#modelSelect').innerHTML = '';
$('#modelSelect').disabled = true;
$('#modelDetails').innerHTML = '';
$('#engineHint').textContent = '';
$('#loadBtn').textContent = kind === 'ollama' ? 'Załaduj (rozgrzej)' : 'Załaduj model';
renderEngineNotes();
renderPullUi();
renderEstimate(null);
if (!initial) { saveSettings(); connect().catch(() => {}); }
}
function renderEngineNotes(extra = []) {
const hints = [...(S.meta.engines[S.engine].notes || []), ...extra];
const code = (h) => escapeHtml(h).replace(/(OLLAMA_FLASH_ATTENTION=1 OLLAMA_KV_CACHE_TYPE=q8_0 ollama serve|setx OLLAMA_\w+ \w+|OLLAMA_\w+=?\w*|launchctl setenv [^;—]+|-c \d+[^,]*|--[\w-]+ [\w.]+)/g, '$1');
$('#kvServerHint').innerHTML = hints.map(code).join('
');
}
function setPill(cls, text) {
$('#enginePill').className = 'engine-pill ' + cls;
$('#enginePillText').textContent = text;
}
async function connect(manual = false) {
try {
const st = await api('/api/engine/status', { engine: engineConfig() });
S.connected = true;
S.caps = st.capabilities;
setPill('ok', `${S.meta.engines[S.engine].label}${st.version ? ' ' + st.version : ''}`);
renderEngineNotes(S.engine === 'lmstudio' && !st.sdk ? ['Brak pakietu @lmstudio/sdk — ładowanie bez kwantyzacji KV-cache (uruchom npm install).'] : []);
$('#engineHint').textContent = '';
saveSettings();
await loadModels();
attachPulls().catch(() => {});
} catch (e) {
S.connected = false;
setPill('err', 'brak połączenia');
$('#engineHint').textContent = e.message;
if (manual) toast(e.message, true);
throw e;
}
}
async function loadModels(keepSelection = true) {
const { models } = await api('/api/engine/models', { engine: engineConfig() });
S.models = models;
renderPullUi();
const sel = $('#modelSelect');
if (!models.length) {
sel.innerHTML = '';
sel.disabled = true;
return;
}
sel.disabled = false;
sel.innerHTML = models.map((m) => {
const bits = [m.params, m.quant, m.sizeBytes ? fmtGB(m.sizeBytes) : null].filter(Boolean).join(' · ');
const tags = [m.loaded?.length ? '● ' : '', m.profile !== 'generic' ? '[MT] ' : ''].join('');
return ``;
}).join('');
const saved = loadSaved().model?.[S.engine];
const want = (keepSelection && S.model && models.find((m) => m.id === S.model)?.id)
|| (saved && models.find((m) => m.id === saved)?.id)
|| models.find((m) => m.loaded?.length)?.id || models[0].id;
sel.value = want;
await selectModel(want);
}
function currentModel() { return S.models.find((m) => m.id === S.model) || null; }
async function selectModel(id) {
S.model = id;
saveSettings();
const m = currentModel();
const det = $('#modelDetails');
det.innerHTML = 'wczytuję szczegóły…';
try {
S.modelInfo = await api('/api/engine/model-info', { engine: engineConfig(), model: id });
} catch (e) {
S.modelInfo = null;
det.innerHTML = `${escapeHtml(e.message)}`;
}
const info = S.modelInfo || {};
const a = info.arch;
const parts = [];
if (a) {
parts.push(`arch ${escapeHtml(a.name)}`, `${a.layers} warstw`);
const kvh = Array.isArray(a.headsKv) ? `${Math.min(...a.headsKv.filter(Boolean))}–${Math.max(...a.headsKv)}` : a.headsKv;
parts.push(`KV heads ${kvh} × ${a.keyLen}`);
if (a.slidingWindow) parts.push('SWA');
if (a.fullAttnInterval) parts.push('hybrydowy');
if (a.kvLoraRank) parts.push('MLA');
} else if (m?.family) parts.push(`${escapeHtml(m.family)}`);
const maxCtx = info.maxContext || m?.maxContext;
if (maxCtx) parts.push(`maks. kontekst ${fmtCtx(maxCtx)}`);
if (info.capabilities?.thinking) parts.push('reasoning');
if (m?.loaded?.length) parts.push('załadowany');
det.innerHTML = parts.join('');
// profile select
const detected = info.profile || m?.profile || 'generic';
$('#profile').innerHTML = `` +
Object.entries(S.meta.profiles).map(([k, p]) => ``).join('');
$('#profile').value = 'auto';
renderProfile();
// context: clamp to model max; prefer the loaded context
const loadedCtx = m?.loaded?.[0]?.contextLength;
if (loadedCtx && S.engine !== 'ollama') $('#contextLength').value = loadedCtx;
if (maxCtx && Number($('#contextLength').value) > maxCtx) $('#contextLength').value = maxCtx;
syncCtxRange();
renderLoaded();
updateEstimate();
}
function effectiveProfile() {
const v = $('#profile').value;
if (v && v !== 'auto') return v;
return S.modelInfo?.profile || currentModel()?.profile || 'generic';
}
function renderProfile() {
const p = S.meta.profiles[effectiveProfile()];
const notes = [];
if (p.note) notes.push(p.note);
if (p.needsSource) notes.push('Wymaga języka źródłowego (użyję wykrytego, jeśli wybrano „automatycznie”).');
if (!p.modes.includes('json')) notes.push('Ten model tłumaczy po jednej linii (bez partii) — wolniej, ale zgodnie z jego formatem.');
$('#profileNote').textContent = notes.join(' ');
$('#applyRecommended').hidden = !p.recommended;
}
function applyRecommended() {
const r = S.meta.profiles[effectiveProfile()].recommended || {};
const map = { temperature: 'temperature', top_p: 'topP', top_k: 'topK', repeat_penalty: 'repeatPenalty', min_p: 'minP' };
for (const [k, v] of Object.entries(r)) writeValue(map[k], v);
saveSettings();
toast('Zastosowano zalecane parametry.');
}
// ---------------------------------------------------------------- context & memory
function ctxSteps() {
const max = S.modelInfo?.maxContext || currentModel()?.maxContext || 262144;
const steps = CTX_STEPS.filter((s) => s <= max);
if (!steps.includes(max) && max < 262144 * 2) steps.push(max);
return steps;
}
function syncCtxRange() {
const steps = ctxSteps();
const v = Number($('#contextLength').value) || 8192;
let idx = 0;
steps.forEach((s, i) => { if (Math.abs(s - v) < Math.abs(steps[idx] - v)) idx = i; });
$('#ctxRange').max = steps.length - 1;
$('#ctxRange').value = idx;
$('#ctxLabel').textContent = `${fmtInt(v)} tok.`;
}
function onSettingsChange() {
syncCtxRange();
saveSettings();
renderLoaded();
updateEstimate();
}
let estSeq = 0;
const updateEstimate = debounce(async () => {
if (!S.connected || !S.model) return renderEstimate(null);
const seq = ++estSeq;
try {
const r = await api('/api/engine/estimate', { engine: engineConfig(), model: S.model, settings: collectSettings(), sizeBytes: currentModel()?.sizeBytes });
if (seq === estSeq) renderEstimate(r);
} catch (e) {
if (seq === estSeq) { renderEstimate(null); $('#vramLines').textContent = e.message; }
}
}, 250);
function renderEstimate(r) {
const box = $('#vram');
const lines = [];
if (!r) {
$('#vramTotal').textContent = '—';
for (const id of ['vW', 'vKV', 'vC']) document.getElementById(id).textContent = '—';
box.querySelector('.seg-w').style.width = box.querySelector('.seg-kv').style.width = box.querySelector('.seg-c').style.width = '0';
box.querySelector('.limit').style.display = 'none';
$('#vramLines').innerHTML = '';
box.classList.remove('over');
return;
}
const o = r.own;
const total = r.engine?.total ?? o.total;
const kvAll = o.kv + (o.recurrent || 0);
const scale = Math.max(r.budget || 0, total, o.total) * 1.08 || 1;
// If the engine gives its own (more reliable) total, scale our breakdown to match it.
const k = r.engine?.total ? r.engine.total / o.total : 1;
box.querySelector('.seg-w').style.width = `${(o.weights * k / scale) * 100}%`;
box.querySelector('.seg-kv').style.width = `${(kvAll * k / scale) * 100}%`;
box.querySelector('.seg-c').style.width = `${(o.compute * k / scale) * 100}%`;
const lim = box.querySelector('.limit');
if (r.budget) { lim.style.display = 'block'; lim.style.left = `${(r.budget / scale) * 100}%`; } else lim.style.display = 'none';
$('#vramTotal').textContent = fmtGB(total);
$('#vW').textContent = fmtGB(o.weights);
$('#vKV').textContent = fmtGB(kvAll);
$('#vC').textContent = fmtGB(o.compute);
const over = r.budget && total > r.budget;
box.classList.toggle('over', !!over);
if (r.engine) {
lines.push(`Szacunek LM Studio: ${fmtGB(r.engine.total)} (model ${fmtGB(r.engine.model)} + kontekst ${fmtGB(r.engine.context)})${r.engine.passesGuardrails === false ? ' — nie przejdzie zabezpieczeń LM Studio' : ''}`);
lines.push(`Własny szacunek: ${fmtGB(o.total)}`);
} else if (r.engineError) lines.push(`Szacunek LM Studio niedostępny: ${escapeHtml(r.engineError)}`);
if (o.perTokenKv) lines.push(`KV-cache: ${(o.perTokenKv / 1024).toFixed(1)} KB/token`);
const g = r.system?.gpus?.[0];
if (g) lines.push(`${escapeHtml(g.name)}: dostępne dla modelu ≈ ${fmtGB(r.budget)}${g.unified ? ` z ${fmtGB(r.system.totalRam)} RAM` : ''}`);
else lines.push(`RAM: ${fmtGB(r.system?.totalRam)} (nie wykryto GPU)`);
if (over) lines.push('Może się nie zmieścić — zmniejsz kontekst lub włącz kwantyzację KV-cache.');
if (r.maxContextFit) lines.push(`Największy kontekst, który się zmieści (wg własnego szacunku): ≈ ${fmtInt(Math.min(r.maxContextFit, r.maxContext || Infinity))} tok.`);
for (const n of o.notes || []) lines.push(escapeHtml(n));
if (S.engine !== 'lmstudio') {
const s = collectSettings();
if (s.kvCacheK !== 'f16' || s.kvCacheV !== 'f16') lines.push(S.engine === 'ollama'
? 'KV-cache w Ollamie zmienia się zmienną środowiskową serwera (patrz wyżej) — tu tylko do szacunku.'
: 'KV-cache ustawia się argumentami serwera — tu tylko do szacunku.');
}
$('#vramLines').innerHTML = lines.map((l) => `
hf.co/…:KWANTYZACJA). Przerwane pobieranie wznowi się od miejsca przerwania.'
: 'Model z katalogu LM Studio albo link do repozytorium GGUF na Hugging Face. Pobierania nie da się przerwać z aplikacji — zrobisz to w panelu Downloads w LM Studio.';
const budget = S.meta.system?.gpus?.[0]?.total;
const have = new Set(S.models.map((m) => m.id));
$('#pullChips').innerHTML = (PULL_SUGGESTIONS[kind] || []).map((s, i) => {
const tooBig = budget && s.size * 1e9 > budget * 0.92;
const owned = have.has(s.name);
const title = `${s.name}${s.quant ? ' · ' + s.quant : ''}${tooBig ? ' — może się nie zmieścić w pamięci GPU' : ''}`;
return ``;
}).join('');
$('#pullChips').querySelectorAll('.chip').forEach((b) => b.addEventListener('click', () => {
const s = PULL_SUGGESTIONS[kind][Number(b.dataset.i)];
$('#pullName').value = s.name;
$('#pullQuant').value = s.quant || '';
$('#pullName').focus();
}));
}
async function startPull() {
const model = $('#pullName').value.trim();
if (!model) return toast('Podaj nazwę modelu do pobrania.', true);
if (!S.connected) return toast('Najpierw połącz się z silnikiem.', true);
try {
const snap = await api('/api/pulls', { engine: engineConfig(), model, quantization: S.engine === 'lmstudio' ? $('#pullQuant').value.trim() || undefined : undefined });
$('#pullName').value = '';
watchPull(snap, S.models.map((m) => m.id));
} catch (e) { toast(e.message, true); }
}
/** Re-attach to downloads kept on the server (after a reload or engine switch). */
async function attachPulls() {
const { pulls } = await api('/api/pulls');
for (const p of pulls) {
const recent = Date.now() - (p.finishedAt || 0) < 60000;
if (p.engineKind === S.engine && (!['done', 'cancelled'].includes(p.state) || recent)) watchPull(p);
}
}
const PULL_TERMINAL = new Set(['done', 'cancelled']);
/** One tile per download for its whole life; the SSE stream stays open until done/cancelled. */
function watchPull(snap, before) {
renderPull(snap);
if (before) S.pullBefore = { ...S.pullBefore, [snap.id]: before };
if (pullStreams.has(snap.id) || PULL_TERMINAL.has(snap.state)) return;
const es = new EventSource(`/api/pulls/${snap.id}/events`);
pullStreams.set(snap.id, es);
let lastState = snap.state;
es.addEventListener('progress', (e) => renderPull(JSON.parse(e.data)));
es.addEventListener('state', async (e) => {
const s = JSON.parse(e.data);
renderPull(s);
const changed = s.state !== lastState;
lastState = s.state;
if (PULL_TERMINAL.has(s.state)) { es.close(); pullStreams.delete(s.id); }
if (!changed) return;
if (s.state === 'done') {
toast(s.note || `Pobrano: ${s.model}`);
await loadModels().catch(() => {});
// Select the new model: same name (Ollama) or whatever appeared in the list (LM Studio).
const was = S.pullBefore?.[s.id];
const fresh = S.models.find((m) => m.id === s.model || m.id === `${s.model}:latest`) || (was && S.models.find((m) => !was.includes(m.id)));
if (fresh) { $('#modelSelect').value = fresh.id; await selectModel(fresh.id); }
} else if (s.state === 'error') toast(s.error, true);
else if (s.state === 'cancelled') setTimeout(() => document.querySelector(`.pull-item[data-id="${s.id}"]`)?.remove(), 6000);
});
es.onerror = () => { /* EventSource reconnects by itself; the first event resyncs the tile */ };
}
async function pullAction(id, action) {
try {
const s = await api(`/api/pulls/${id}/${action}`, {});
renderPull(s);
if (action === 'resume' && !pullStreams.has(id)) watchPull(s);
} catch (e) { toast(e.message, true); }
}
const PULL_BUTTONS = {
pause: ['Wstrzymaj', 'Zatrzymaj pobieranie — pobrane części zostają, można wznowić'],
resume: ['Wznów', 'Kontynuuj od miejsca wstrzymania'],
retry: ['Ponów', 'Spróbuj jeszcze raz (od miejsca przerwania)'],
cancel: ['Anuluj', 'Przerwij i usuń niedokończone pliki tego pobierania'],
hide: ['Ukryj', 'Usuń kafelek z listy'],
};
function renderPull(s) {
let el = document.querySelector(`.pull-item[data-id="${s.id}"]`);
if (!el) {
el = document.createElement('div');
el.className = 'pull-item';
el.dataset.id = s.id;
el.innerHTML = '