/* Explicit, per-answer cache approval. No background approval requests. */ (function () { function attach(bubble, payload, threadId, baseUrl) { const review = payload.cache_review; if (!review) return; bubble.querySelector('.answer-cache-actions')?.remove(); const bar = document.createElement('div'); bar.className = 'answer-cache-actions'; const status = document.createElement('span'); status.className = 'answer-cache-status'; status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite'); bar.appendChild(status); bubble.appendChild(bar); if (!review.eligible && !review.cached) { status.textContent = review.reason ? '暂不缓存:' + review.reason : ''; return; } let cached = Boolean(review.cached); let entryId = review.entry_id; const button = document.createElement('button'); button.type = 'button'; button.className = 'answer-cache-button'; const label = () => { button.textContent = cached ? '撤销缓存' : '答案正确,加入缓存'; button.setAttribute('aria-label', button.textContent); }; status.textContent = review.hit ? '已复用你确认的历史答案' : '确认答案正确后,可缓存供本会话重复提问使用'; label(); button.addEventListener('click', async () => { if (button.disabled) return; button.disabled = true; status.textContent = cached ? '正在撤销…' : '正在加入缓存…'; try { const response = await fetch(baseUrl + '/threads/' + encodeURIComponent(threadId) + '/answer-cache', { method: cached ? 'DELETE' : 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({answer_id: review.answer_id, checkpoint_id: review.checkpoint_id, entry_id: entryId || null}) }); const result = await response.json(); if (!response.ok || result.status !== 'ok') throw new Error(result.detail || result.message || '操作失败,请重试'); cached = !cached; entryId = cached ? result.entry_id : null; status.textContent = cached ? '已确认并加入缓存' : '已撤销,后续提问将重新处理'; } catch (error) { status.textContent = error.message || '缓存操作失败,请重试'; } finally { label(); button.disabled = false; } }); bar.appendChild(button); } window.AnswerCacheUI = {attach}; })();