answer_cache.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Explicit, per-answer cache approval. No background approval requests. */
  2. (function () {
  3. function attach(bubble, payload, threadId, baseUrl) {
  4. const review = payload.cache_review;
  5. if (!review) return;
  6. bubble.querySelector('.answer-cache-actions')?.remove();
  7. const bar = document.createElement('div');
  8. bar.className = 'answer-cache-actions';
  9. const status = document.createElement('span');
  10. status.className = 'answer-cache-status';
  11. status.setAttribute('role', 'status');
  12. status.setAttribute('aria-live', 'polite');
  13. bar.appendChild(status);
  14. bubble.appendChild(bar);
  15. if (!review.eligible && !review.cached) {
  16. status.textContent = review.reason ? '暂不缓存:' + review.reason : '';
  17. return;
  18. }
  19. let cached = Boolean(review.cached);
  20. let entryId = review.entry_id;
  21. const button = document.createElement('button');
  22. button.type = 'button';
  23. button.className = 'answer-cache-button';
  24. const label = () => {
  25. button.textContent = cached ? '撤销缓存' : '答案正确,加入缓存';
  26. button.setAttribute('aria-label', button.textContent);
  27. };
  28. status.textContent = review.hit ? '已复用你确认的历史答案' : '确认答案正确后,可缓存供本会话重复提问使用';
  29. label();
  30. button.addEventListener('click', async () => {
  31. if (button.disabled) return;
  32. button.disabled = true;
  33. status.textContent = cached ? '正在撤销…' : '正在加入缓存…';
  34. try {
  35. const response = await fetch(baseUrl + '/threads/' + encodeURIComponent(threadId) + '/answer-cache', {
  36. method: cached ? 'DELETE' : 'POST',
  37. headers: {'Content-Type': 'application/json'},
  38. body: JSON.stringify({answer_id: review.answer_id, checkpoint_id: review.checkpoint_id,
  39. entry_id: entryId || null})
  40. });
  41. const result = await response.json();
  42. if (!response.ok || result.status !== 'ok') throw new Error(result.detail || result.message || '操作失败,请重试');
  43. cached = !cached;
  44. entryId = cached ? result.entry_id : null;
  45. status.textContent = cached ? '已确认并加入缓存' : '已撤销,后续提问将重新处理';
  46. } catch (error) {
  47. status.textContent = error.message || '缓存操作失败,请重试';
  48. } finally {
  49. label();
  50. button.disabled = false;
  51. }
  52. });
  53. bar.appendChild(button);
  54. }
  55. window.AnswerCacheUI = {attach};
  56. })();