POSA_Copyrighter/web/operator-gui/app-api.js
changukyu 2661af86e5 feat: codex 검토 잔여 ③④⑤ + 밀린 부채 — 투입 충돌 표시, 사용/무관 분리, 측정 불가, VERSION
③ 파일명 stem 충돌: 다른 폴더의 같은 이름 파일이 한 건으로 합쳐져 둘째가 조용히 미심사였다.
   id 는 재유도하지 않고(기존 판정 보존) id_collisions() 로 탐지해 bootstrap.intakeConflicts 와
   파일당 1회 감사로 남기고, 콘솔 투입 상태줄에 경고 목록을 띄운다.
④ 행 버튼 '미사용' 이 false_positive 로 가 대표 근거 하나를 고르면 나머지 점수가 지워졌다 →
   '사용'/'무관', 사용 재클릭은 pending(표시 해제, 점수 유지).
⑤ 분모 0 비율은 None → '측정 불가'. 외부 검색이 꺼진 케이스는 점수 0 유지, 한 줄 요약에
   '외부 검색 꺼짐'.

부채: operator-review-workflow 13px 넘침 해소(겹치지 않는 레인 병합) → 다이어그램 5종 첫
REBUILD OK, v6 이전 카드 문구 교정. tests/conftest.py 로 로컬 Ollama 격리(가동 중에도 통과).
루트 VERSION 0.1.0 단일 출처, /health 와 기동 로그에 버전·스코어러 버전.

verify.ps1 (Ollama 가동 중, override 없음): ruff clean, 680 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BStHFrjQj2VypecSG9ex1V
2026-09-25 18:13:09 +09:00

265 lines
4.8 KiB
JavaScript

// Part 2 of 15 of the operator console app script.
//
// Auth token prompt, fetch wrapper, and bootstrap/refresh of client state.
//
// Load order is significant: these are classic (non-module) scripts sharing one
// global scope, and index.html must keep them in the order listed above/below.
// Splitting is a pure line-range extraction of the former single app.js.
function promptForAuthToken(message = "") {
const gate = document.getElementById("auth-gate");
const form = document.getElementById("auth-gate-form");
const input = document.getElementById("auth-gate-input");
const error = document.getElementById("auth-gate-error");
if (!gate || !form || !input) {
return Promise.resolve("");
}
// Collapse concurrent 401s onto one prompt so a burst of parallel requests
// cannot stack multiple dialogs.
if (pendingAuthPrompt) {
return pendingAuthPrompt;
}
if (error) {
error.hidden = !message;
error.textContent = message || "";
}
gate.hidden = false;
input.value = "";
input.focus();
pendingAuthPrompt = new Promise((resolve) => {
const onSubmit = (event) => {
event.preventDefault();
const value = input.value.trim();
if (!value) {
return;
}
form.removeEventListener("submit", onSubmit);
gate.hidden = true;
input.value = "";
pendingAuthPrompt = null;
resolve(value);
};
form.addEventListener("submit", onSubmit);
});
return pendingAuthPrompt;
}
function authHeaders(extra) {
const headers = { "Content-Type": "application/json", ...(extra || {}) };
if (authToken) {
headers.Authorization = `Bearer ${authToken}`;
}
return headers;
}
async function apiJson(path, options = {}, allowAuthRetry = true) {
const response = await fetch(path, {
...options,
headers: authHeaders(options.headers),
});
const text = await response.text();
let payload = null;
if (text) {
try {
payload = JSON.parse(text);
} catch (error) {
payload = null;
}
}
if (response.status === 401 && allowAuthRetry) {
// Ask for the token, then replay this request once. A second 401 falls
// through to the normal error path instead of looping.
const token = await promptForAuthToken(
authToken ? "토큰이 올바르지 않습니다. 다시 입력하세요." : "",
);
if (token) {
authToken = token;
return apiJson(path, options, false);
}
}
if (!response.ok) {
const message = (payload && payload.error) || `API 요청 실패: ${response.status}`;
throw new Error(message);
}
return payload;
}
function replaceCollection(target, next) {
target.splice(0, target.length, ...(next || []));
}
function clearRuntimeData() {
replaceCollection(submissions, []);
replaceCollection(providers, []);
replaceCollection(knowledgeEntries, []);
replaceCollection(collectionCandidates, []);
replaceCollection(corrections, []);
replaceCollection(auditEvents, []);
Object.assign(coverageThresholds, DEFAULT_COVERAGE_THRESHOLDS);
Object.keys(searchCoverage).forEach((key) => delete searchCoverage[key]);
state.submissionQueue = null;
state.selectedCaseId = "";
}
function applyBootstrap(payload) {
// Any successful payload proves the API is reachable, so clear a stale error
// banner here (not only in refreshFromApi) — actions that applyBootstrap
// directly, e.g. promote/dismiss, otherwise leave the old error visible.
state.apiError = "";
replaceCollection(submissions, payload.submissions);
replaceCollection(providers, payload.providers);
replaceCollection(knowledgeEntries, payload.knowledgeEntries);
state.submissionQueue = payload.submissionQueue || null;
state.intakeConflicts = Array.isArray(payload.intakeConflicts) ? payload.intakeConflicts : [];
Object.assign(
coverageThresholds,
normalizeCoverageThresholds(payload.coverageThresholds || (payload.searchCoverage && payload.searchCoverage.coverageThresholds)),
);
Object.keys(searchCoverage).forEach((key) => delete searchCoverage[key]);
Object.assign(searchCoverage, payload.searchCoverage || {});
replaceCollection(collectionCandidates, payload.collectionCandidates);
replaceCollection(corrections, payload.corrections);
replaceCollection(auditEvents, payload.auditEvents);
replaceCollection(decisionMemoPresets, payload.decisionMemoPresets || []);
if (!submissions.some((item) => item.id === state.selectedCaseId)) {
state.selectedCaseId = submissions[0]?.id || "";
}
}
async function refreshFromApi() {
const payload = await apiJson("/api/bootstrap");
state.apiError = "";
applyBootstrap(payload);
renderAll();
}
function setImportStatus(message, tone = "idle") {
state.importStatus = { message, tone };
renderImportStatus();
}