412 lines
14 KiB
JavaScript
412 lines
14 KiB
JavaScript
// The Admin Console owns presentation state only. Batch acceptance, Job state,
|
||
// and retrieval remain behind the versioned public REST contract.
|
||
const API_BASE = "/api/v1";
|
||
const BATCH_POLL_INTERVAL_MS = 1500;
|
||
const terminalBatchStatuses = new Set(["completed", "partial_failure", "failed"]);
|
||
let batchPollTimer;
|
||
let activeBatchId;
|
||
|
||
const statusLabels = {
|
||
uploaded: "Uploaded",
|
||
processing: "Processing",
|
||
ready: "Ready",
|
||
failed: "Failed",
|
||
pending: "Pending",
|
||
accepted: "Accepted",
|
||
rejected: "Rejected",
|
||
queued: "Queued",
|
||
running: "Running",
|
||
retrying: "Retrying",
|
||
succeeded: "Succeeded",
|
||
completed: "Completed",
|
||
partial_failure: "Partial failure",
|
||
};
|
||
|
||
const stageLabels = {
|
||
parsing: "解析",
|
||
cleaning: "清理",
|
||
chunking: "切分",
|
||
embedding: "向量化",
|
||
indexing: "索引",
|
||
};
|
||
|
||
const pageTitles = {
|
||
upload: "上传文档",
|
||
documents: "文档列表",
|
||
search: "Search Lab",
|
||
};
|
||
|
||
function currentPage() {
|
||
const route = window.location.pathname.split("/").filter(Boolean).at(-1);
|
||
return Object.hasOwn(pageTitles, route) ? route : "upload";
|
||
}
|
||
|
||
function showPage(page) {
|
||
document.querySelectorAll("[data-page]").forEach((section) => {
|
||
section.hidden = section.dataset.page !== page;
|
||
});
|
||
document.querySelectorAll("[data-nav]").forEach((link) => {
|
||
const active = link.dataset.nav === page;
|
||
link.classList.toggle("active", active);
|
||
if (active) link.setAttribute("aria-current", "page");
|
||
else link.removeAttribute("aria-current");
|
||
});
|
||
document.querySelector("#page-title").textContent = pageTitles[page];
|
||
}
|
||
|
||
function showNotice(message, kind = "success") {
|
||
const notice = document.querySelector("#notice");
|
||
notice.textContent = message;
|
||
notice.className = `notice ${kind}`;
|
||
notice.hidden = false;
|
||
window.clearTimeout(showNotice.timeout);
|
||
showNotice.timeout = window.setTimeout(() => {
|
||
notice.hidden = true;
|
||
}, 6000);
|
||
}
|
||
|
||
async function requestJson(path, options = {}) {
|
||
const response = await fetch(`${API_BASE}${path}`, options);
|
||
if (!response.ok) {
|
||
let message = `请求失败(HTTP ${response.status})`;
|
||
try {
|
||
const body = await response.json();
|
||
if (body.detail) message = body.detail;
|
||
} catch {
|
||
// A non-JSON upstream error is represented by the stable HTTP message above.
|
||
}
|
||
throw new Error(message);
|
||
}
|
||
return response.status === 204 ? null : response.json();
|
||
}
|
||
|
||
function formatDate(value) {
|
||
if (!value) return "—";
|
||
return new Intl.DateTimeFormat("zh-CN", {
|
||
dateStyle: "medium",
|
||
timeStyle: "short",
|
||
}).format(new Date(value));
|
||
}
|
||
|
||
function formatSize(bytes) {
|
||
if (bytes < 1024) return `${bytes} B`;
|
||
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;
|
||
return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
|
||
}
|
||
|
||
function statusPill(status) {
|
||
const pill = document.createElement("span");
|
||
pill.className = `status-pill status-${status}`;
|
||
pill.textContent = statusLabels[status] ?? status;
|
||
return pill;
|
||
}
|
||
|
||
function setButtonBusy(button, busy, busyText) {
|
||
if (!button.dataset.label) button.dataset.label = button.textContent;
|
||
button.disabled = busy;
|
||
button.textContent = busy ? busyText : button.dataset.label;
|
||
}
|
||
|
||
function initializeUpload() {
|
||
const form = document.querySelector("#upload-form");
|
||
const input = document.querySelector("#file-input");
|
||
const selected = document.querySelector("#selected-file");
|
||
const button = document.querySelector("#upload-button");
|
||
|
||
const updateFilename = () => {
|
||
const files = Array.from(input.files);
|
||
if (!files.length) {
|
||
selected.textContent = "尚未选择文件";
|
||
} else if (files.length === 1) {
|
||
selected.textContent = files[0].name;
|
||
} else {
|
||
selected.textContent = `已选择 ${files.length} 个文件`;
|
||
}
|
||
};
|
||
input.addEventListener("change", updateFilename);
|
||
|
||
form.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
if (!input.files.length) return;
|
||
window.clearTimeout(batchPollTimer);
|
||
activeBatchId = undefined;
|
||
setButtonBusy(button, true, "提交中…");
|
||
try {
|
||
const formData = new FormData();
|
||
Array.from(input.files).forEach((file) => formData.append("files", file));
|
||
const batch = await requestJson("/ingestion-batches", {
|
||
method: "POST",
|
||
body: formData,
|
||
});
|
||
activeBatchId = batch.batch_id;
|
||
renderBatchResult(batch);
|
||
scheduleBatchPoll(batch);
|
||
showNotice(
|
||
`批次已接收:${batch.accepted_files} 个进入后台队列,${batch.rejected_files} 个被拒绝。`,
|
||
batch.rejected_files ? "error" : "success",
|
||
);
|
||
form.reset();
|
||
updateFilename();
|
||
} catch (error) {
|
||
showNotice(`上传失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(button, false, "");
|
||
}
|
||
});
|
||
}
|
||
|
||
function scheduleBatchPoll(batch) {
|
||
window.clearTimeout(batchPollTimer);
|
||
if (batch.batch_id !== activeBatchId) return;
|
||
if (terminalBatchStatuses.has(batch.status)) return;
|
||
batchPollTimer = window.setTimeout(async () => {
|
||
try {
|
||
const latest = await requestJson(`/ingestion-batches/${batch.batch_id}`);
|
||
renderBatchResult(latest);
|
||
scheduleBatchPoll(latest);
|
||
} catch (error) {
|
||
showNotice(`批次状态刷新失败:${error.message}`, "error");
|
||
scheduleBatchPoll(batch);
|
||
}
|
||
}, BATCH_POLL_INTERVAL_MS);
|
||
}
|
||
|
||
function renderBatchResult(batch) {
|
||
const card = document.querySelector("#upload-result");
|
||
document.querySelector("#upload-batch-title").textContent =
|
||
`批次 ${batch.batch_id.slice(0, 8)} · ${formatDate(batch.created_at)}`;
|
||
document.querySelector("#upload-total").textContent = `${batch.total_files} 个`;
|
||
document.querySelector("#upload-completed").textContent =
|
||
`${batch.completed_files} / ${batch.total_files}`;
|
||
document.querySelector("#upload-accepted").textContent =
|
||
`${batch.accepted_files} / ${batch.rejected_files}`;
|
||
document.querySelector("#upload-status").replaceWith(statusPill(batch.status));
|
||
const status = card.querySelector(".status-pill");
|
||
status.id = "upload-status";
|
||
const items = document.querySelector("#batch-items");
|
||
items.replaceChildren(...batch.items.map(batchItem));
|
||
card.hidden = false;
|
||
}
|
||
|
||
function batchItem(item) {
|
||
const row = document.createElement("article");
|
||
row.className = "batch-item";
|
||
|
||
const order = document.createElement("span");
|
||
order.className = "batch-item-order";
|
||
order.textContent = String(item.item_index + 1).padStart(2, "0");
|
||
|
||
const body = document.createElement("div");
|
||
body.className = "batch-item-body";
|
||
const name = document.createElement("strong");
|
||
name.textContent = item.filename;
|
||
const detail = document.createElement("span");
|
||
const stage = item.stage ? ` · ${stageLabels[item.stage] ?? item.stage}` : "";
|
||
const attempts = item.max_attempts == null ? "" : ` · 尝试 ${item.attempt}/${item.max_attempts}`;
|
||
detail.textContent = item.error_message ?? `后台任务${stage}${attempts}`;
|
||
body.append(name, detail);
|
||
|
||
const state = item.job_status ?? item.acceptance_status;
|
||
row.append(order, body, statusPill(state));
|
||
return row;
|
||
}
|
||
|
||
async function loadDocuments() {
|
||
const refresh = document.querySelector("#refresh-documents");
|
||
setButtonBusy(refresh, true, "加载中…");
|
||
try {
|
||
const documents = await requestJson("/documents");
|
||
renderDocuments(documents);
|
||
} catch (error) {
|
||
showNotice(`文档列表加载失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(refresh, false, "");
|
||
}
|
||
}
|
||
|
||
function renderDocuments(documents) {
|
||
const rows = document.querySelector("#document-rows");
|
||
const empty = document.querySelector("#document-empty");
|
||
rows.replaceChildren();
|
||
empty.hidden = documents.length !== 0;
|
||
document.querySelector("#document-count").textContent = `${documents.length} 个文档`;
|
||
document.querySelector("#document-refresh-time").textContent =
|
||
`更新于 ${new Intl.DateTimeFormat("zh-CN", { timeStyle: "short" }).format(new Date())}`;
|
||
|
||
documents.forEach((documentData) => {
|
||
const row = document.createElement("tr");
|
||
row.append(
|
||
tableCell(documentData.filename, "filename-cell"),
|
||
tableCell(documentData.media_type),
|
||
tableCell(formatDate(documentData.created_at)),
|
||
);
|
||
const statusCell = document.createElement("td");
|
||
statusCell.append(statusPill(documentData.status));
|
||
row.append(statusCell);
|
||
|
||
const actions = document.createElement("td");
|
||
actions.className = "row-actions";
|
||
const view = actionButton("查看", () => showDocumentDetail(documentData));
|
||
const remove = actionButton("删除", () => deleteDocument(documentData), "danger-link");
|
||
actions.append(view, remove);
|
||
row.append(actions);
|
||
rows.append(row);
|
||
});
|
||
}
|
||
|
||
function tableCell(value, className = "") {
|
||
const cell = document.createElement("td");
|
||
cell.textContent = value;
|
||
cell.className = className;
|
||
return cell;
|
||
}
|
||
|
||
function actionButton(label, handler, className = "") {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = `table-action ${className}`;
|
||
button.textContent = label;
|
||
button.addEventListener("click", handler);
|
||
return button;
|
||
}
|
||
|
||
function showDocumentDetail(documentData) {
|
||
const dialog = document.querySelector("#document-dialog");
|
||
document.querySelector("#dialog-filename").textContent = documentData.filename;
|
||
const metadata = document.querySelector("#dialog-metadata");
|
||
metadata.replaceChildren();
|
||
[
|
||
["文档 ID", documentData.id],
|
||
["文件类型", documentData.media_type],
|
||
["文件大小", formatSize(documentData.size_bytes)],
|
||
["当前状态", statusLabels[documentData.status] ?? documentData.status],
|
||
["上传时间", formatDate(documentData.created_at)],
|
||
["更新时间", formatDate(documentData.updated_at)],
|
||
["错误信息", documentData.error_message ?? "无"],
|
||
].forEach(([term, value]) => {
|
||
const wrapper = document.createElement("div");
|
||
const dt = document.createElement("dt");
|
||
const dd = document.createElement("dd");
|
||
dt.textContent = term;
|
||
dd.textContent = value;
|
||
wrapper.append(dt, dd);
|
||
metadata.append(wrapper);
|
||
});
|
||
dialog.showModal();
|
||
}
|
||
|
||
async function deleteDocument(documentData) {
|
||
if (!window.confirm(`确认删除“${documentData.filename}”及其索引数据?`)) return;
|
||
try {
|
||
await requestJson(`/documents/${documentData.id}`, { method: "DELETE" });
|
||
showNotice(`已删除 ${documentData.filename}`, "success");
|
||
await loadDocuments();
|
||
} catch (error) {
|
||
showNotice(`删除失败:${error.message}`, "error");
|
||
}
|
||
}
|
||
|
||
function initializeSearch() {
|
||
const form = document.querySelector("#search-form");
|
||
const button = document.querySelector("#search-button");
|
||
form.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
const query = document.querySelector("#search-query").value.trim();
|
||
const topK = Number(document.querySelector("#search-top-k").value);
|
||
if (!query) return;
|
||
setButtonBusy(button, true, "检索中…");
|
||
try {
|
||
const startedAt = performance.now();
|
||
const response = await requestJson("/search", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ query, top_k: topK }),
|
||
});
|
||
renderSearchResults(response.results, performance.now() - startedAt);
|
||
} catch (error) {
|
||
showNotice(`检索失败:${error.message}`, "error");
|
||
} finally {
|
||
setButtonBusy(button, false, "");
|
||
}
|
||
});
|
||
}
|
||
|
||
function renderSearchResults(results, elapsedMs) {
|
||
const container = document.querySelector("#search-results");
|
||
container.replaceChildren();
|
||
document.querySelector("#search-summary").textContent =
|
||
`${results.length} 条结果 · ${(elapsedMs / 1000).toFixed(2)} 秒`;
|
||
if (!results.length) {
|
||
const empty = document.createElement("div");
|
||
empty.className = "empty-state search-empty";
|
||
const strong = document.createElement("strong");
|
||
strong.textContent = "没有找到匹配内容";
|
||
const detail = document.createElement("span");
|
||
detail.textContent = "可以换一种问法,或先确认文档状态为 Ready。";
|
||
empty.append(strong, detail);
|
||
container.append(empty);
|
||
return;
|
||
}
|
||
|
||
results.forEach((result, index) => {
|
||
const card = document.createElement("article");
|
||
card.className = "search-result-card";
|
||
const rank = document.createElement("span");
|
||
rank.className = "rank";
|
||
rank.textContent = String(index + 1).padStart(2, "0");
|
||
const body = document.createElement("div");
|
||
body.className = "result-body";
|
||
const heading = document.createElement("div");
|
||
heading.className = "result-title-row";
|
||
const title = document.createElement("h4");
|
||
title.textContent = result.filename;
|
||
const sourceMeta = document.createElement("div");
|
||
sourceMeta.className = "source-meta";
|
||
sourceMeta.append(
|
||
metadataItem("Page", result.page == null ? "—" : String(result.page)),
|
||
metadataItem("Section", result.section ?? "—"),
|
||
);
|
||
heading.append(title, sourceMeta);
|
||
const content = document.createElement("p");
|
||
content.className = "chunk-content";
|
||
content.textContent = result.content;
|
||
const scores = document.createElement("div");
|
||
scores.className = "score-row";
|
||
scores.append(
|
||
scoreItem("Dense Score", result.score),
|
||
scoreItem("Rerank Score", result.rerank_score),
|
||
);
|
||
body.append(heading, content, scores);
|
||
card.append(rank, body);
|
||
container.append(card);
|
||
});
|
||
}
|
||
|
||
function scoreItem(label, value) {
|
||
const item = document.createElement("span");
|
||
const labelNode = document.createElement("small");
|
||
const valueNode = document.createElement("strong");
|
||
labelNode.textContent = label;
|
||
valueNode.textContent = Number(value).toFixed(4);
|
||
item.append(labelNode, valueNode);
|
||
return item;
|
||
}
|
||
|
||
function metadataItem(label, value) {
|
||
const item = document.createElement("span");
|
||
const labelNode = document.createElement("small");
|
||
const valueNode = document.createElement("strong");
|
||
labelNode.textContent = label;
|
||
valueNode.textContent = value;
|
||
item.append(labelNode, valueNode);
|
||
return item;
|
||
}
|
||
|
||
const page = currentPage();
|
||
showPage(page);
|
||
initializeUpload();
|
||
initializeSearch();
|
||
document.querySelector("#refresh-documents").addEventListener("click", loadDocuments);
|
||
if (page === "documents") loadDocuments();
|
||
window.addEventListener("pagehide", () => window.clearTimeout(batchPollTimer));
|