Add sub-question branching + document summary modals

- Source modal now shows LLM-generated document summary (lazy-gen + cached
  in documents.summary) instead of raw chunk text; toggle reveals matched
  chunk; "View all chunks" button fetches every chunk of the document via
  new api/document-chunks.php endpoint
- Each sub-question card gets a "Branch ↓" button that pre-fills the query
  with that sub-question and shows a context panel with the prior brief
  summary; prior_context + branch_notes are injected into interpretSeed()
  and synthesise() so the LLM knows where the research is coming from
- Upload document summaries generated at synthesis time and attached to
  upload sources alongside corpus summaries
- DB: documents.summary TEXT column added to bnl_corpus on chloe

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-15 19:44:27 +02:00
parent 0ff4eb6d31
commit 343b19d0b4
8 changed files with 566 additions and 28 deletions
+165 -2
View File
@@ -2573,7 +2573,7 @@ p {
.dr-source-modal__meta dt:first-of-type { margin-top: 0; }
.dr-source-modal__text {
white-space: pre-wrap;
white-space: normal;
line-height: 1.7;
color: var(--ink);
}
@@ -2600,7 +2600,7 @@ p {
.dr-subq-report__head {
display: grid;
grid-template-columns: auto 1fr;
grid-template-columns: auto 1fr auto;
gap: 10px;
align-items: start;
margin-bottom: 10px;
@@ -3213,3 +3213,166 @@ a.dr-source-title-link:hover {
.adv-role-select, .adv-role-custom { max-width: 100%; }
.adv-banner { flex-direction: column; align-items: flex-start; }
}
/* ── Branch-from-sub-question panel ──────────────────────────────────────── */
.branch-panel {
background: #f0faf8;
border: 1px solid var(--teal);
border-left: 4px solid var(--teal);
border-radius: 8px;
padding: 14px 16px;
margin-bottom: 16px;
}
.branch-panel__head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
}
.branch-panel__label {
font-weight: 700;
font-size: 0.82rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--teal-dark);
}
.branch-panel__origin {
margin: 0 0 8px;
font-size: 0.88rem;
color: var(--ink);
line-height: 1.45;
}
.branch-panel__prior {
margin-bottom: 10px;
font-size: 0.87rem;
}
.branch-panel__prior summary {
cursor: pointer;
color: var(--teal-dark);
font-weight: 600;
user-select: none;
}
.branch-panel__brief {
margin-top: 6px;
padding: 8px 10px;
background: rgba(255,255,255,0.7);
border-radius: 5px;
font-size: 0.86rem;
color: var(--muted);
line-height: 1.5;
white-space: pre-wrap;
}
/* "Branch ↓" button on sub-Q cards */
.dr-branch-btn {
align-self: start;
padding: 4px 10px;
font-size: 0.78rem;
font-weight: 700;
background: transparent;
border: 1px solid var(--teal);
border-radius: 5px;
color: var(--teal-dark);
white-space: nowrap;
transition: background 0.12s, color 0.12s;
}
.dr-branch-btn:hover {
background: var(--teal);
color: #fff;
}
/* ── Source modal: summary + chunk toggle + all-chunks ───────────────────── */
.dr-modal-summary {
font-size: 0.93rem;
line-height: 1.65;
color: var(--ink);
margin-bottom: 14px;
}
.dr-modal-summary--empty em {
color: var(--muted);
font-size: 0.87rem;
}
.dr-modal-chunk-toggle,
.dr-modal-all-chunks {
display: inline-block;
margin-bottom: 8px;
padding: 4px 10px;
font-size: 0.8rem;
font-weight: 600;
background: transparent;
border: 1px solid var(--line);
border-radius: 5px;
color: var(--teal-dark);
cursor: pointer;
transition: background 0.12s, border-color 0.12s;
}
.dr-modal-chunk-toggle:hover,
.dr-modal-all-chunks:hover {
background: var(--soft-teal);
border-color: var(--teal);
}
.dr-modal-chunk-text {
white-space: pre-wrap;
font-size: 0.87rem;
line-height: 1.65;
color: var(--muted);
background: #f8f9fb;
border: 1px solid var(--line);
border-radius: 6px;
padding: 10px 12px;
margin-bottom: 12px;
}
.dr-modal-all-chunks {
display: block;
width: 100%;
text-align: left;
margin-top: 4px;
}
.dr-modal-chunks-list {
margin-top: 4px;
}
.dr-modal-chunks-head {
font-weight: 700;
font-size: 0.82rem;
color: var(--teal-dark);
padding: 6px 0 8px;
border-bottom: 1px solid var(--line);
margin-bottom: 8px;
}
.dr-modal-chunk-item {
padding: 8px 0;
border-bottom: 1px solid var(--line);
}
.dr-modal-chunk-item:last-child { border-bottom: 0; }
.dr-modal-chunk-idx {
display: block;
font-size: 0.78rem;
font-weight: 700;
color: var(--coral);
margin-bottom: 4px;
}
.dr-modal-chunk-preview {
margin: 0;
font-size: 0.86rem;
line-height: 1.5;
color: var(--muted);
white-space: pre-wrap;
}
+101 -1
View File
@@ -6,6 +6,7 @@
let lang = 'en';
let uploadFiles = [];
let lastResult = null;
let branchContext = null;
const SLICE_DEFS = [
{ id: 'family_core', label: 'Family Law Core' },
@@ -65,6 +66,11 @@
modalEyebrow: document.getElementById('advSourceModalEyebrow'),
modalMeta: document.getElementById('advSourceModalMeta'),
modalText: document.getElementById('advSourceModalText'),
branchPanel: document.getElementById('advBranchPanel'),
branchClear: document.getElementById('advBranchClear'),
branchOrigin: document.getElementById('advBranchOrigin'),
branchSummary: document.getElementById('advBranchSummary'),
branchNotes: document.getElementById('advBranchNotes'),
});
if (!els.form) return;
@@ -75,7 +81,12 @@
bindRanges();
bindUpload();
bindModal();
bindBranch();
els.form.addEventListener('submit', onSubmit);
els.results.addEventListener('click', (e) => {
const btn = e.target.closest('.dr-branch-btn');
if (btn) branchFromSubQ(btn.dataset.question || '');
});
renderTrace(STEP_LABELS.map((label) => ({ label, detail: 'Waiting…', status: 'idle' })));
});
@@ -214,7 +225,62 @@
source.matched_sub_questions?.length ? ['Matched sub-Q', source.matched_sub_questions.join(', ')] : null,
].filter(Boolean);
els.modalMeta.innerHTML = '<dl>' + metaRows.map(([k, v]) => `<dt>${escapeHtml(k)}</dt><dd>${escapeHtml(String(v))}</dd>`).join('') + '</dl>';
els.modalText.textContent = source.chunk_text || source.excerpt || '';
const summary = source.summary || '';
const chunkText = source.chunk_text || source.excerpt || '';
const isUpload = source.source_origin === 'upload';
const hasDocId = source.document_id != null;
let html = summary
? `<div class="dr-modal-summary">${escapeHtml(summary)}</div>`
: `<div class="dr-modal-summary dr-modal-summary--empty"><em>Summary not yet generated — showing raw chunk below.</em></div>`;
if (chunkText) {
html += `<button class="dr-modal-chunk-toggle" type="button">Show matching chunk ▼</button>`;
html += `<div class="dr-modal-chunk-text is-hidden">${escapeHtml(chunkText)}</div>`;
}
if (!isUpload && hasDocId) {
html += `<button class="dr-modal-all-chunks" type="button" data-document-id="${source.document_id}">View all document chunks →</button>`;
html += `<div class="dr-modal-chunks-list"></div>`;
}
els.modalText.innerHTML = html;
const chunkToggle = els.modalText.querySelector('.dr-modal-chunk-toggle');
const chunkDiv = els.modalText.querySelector('.dr-modal-chunk-text');
chunkToggle?.addEventListener('click', () => {
const isHidden = chunkDiv.classList.toggle('is-hidden');
chunkToggle.textContent = isHidden ? 'Show matching chunk ▼' : 'Hide matching chunk ▲';
});
const allChunksBtn = els.modalText.querySelector('.dr-modal-all-chunks');
const chunksListDiv = els.modalText.querySelector('.dr-modal-chunks-list');
if (allChunksBtn && chunksListDiv) {
allChunksBtn.addEventListener('click', async () => {
allChunksBtn.disabled = true;
allChunksBtn.textContent = 'Loading…';
try {
const res = await fetch(`api/document-chunks.php?document_id=${source.document_id}`, { credentials: 'same-origin' });
const data = await res.json();
if (data.ok && data.chunks) {
chunksListDiv.innerHTML =
`<div class="dr-modal-chunks-head">${escapeHtml(data.document?.title || '')} · ${data.chunks.length} chunks</div>` +
data.chunks.map((c) => `<div class="dr-modal-chunk-item">
<span class="dr-modal-chunk-idx">#${c.chunk_index + 1}${c.section_title ? ' · ' + escapeHtml(c.section_title) : ''}</span>
<p class="dr-modal-chunk-preview">${escapeHtml(truncate(c.content, 300))}</p>
</div>`).join('');
allChunksBtn.remove();
} else {
allChunksBtn.textContent = 'Could not load chunks.';
allChunksBtn.disabled = false;
}
} catch (_) {
allChunksBtn.textContent = 'Error loading chunks.';
allChunksBtn.disabled = false;
}
});
}
els.modal.classList.remove('is-hidden');
}
@@ -282,6 +348,10 @@
controls: getControls(),
advocate_role: advocateRole,
};
if (branchContext) {
payload.prior_context = branchContext;
payload.branch_notes = (els.branchNotes ? els.branchNotes.value : '').trim();
}
const stepKeyToIndex = {
interpretation: 0,
@@ -370,6 +440,7 @@
return;
}
finalResult.query = query;
lastResult = finalResult;
const meta = finalResult.trace_metadata || {};
const rc = meta.retrieval_counts || {};
@@ -596,6 +667,7 @@
<div class="dr-subq-report__question">${escapeHtml(sq.question || '')}</div>
${sq.rationale ? `<div class="dr-subq-report__rationale">${escapeHtml(sq.rationale)}</div>` : ''}
</div>
<button class="dr-branch-btn" type="button" data-question="${escapeHtml(sq.question || '')}" aria-label="Branch research from this sub-question">Branch ↓</button>
</div>
<ul class="dr-mini-source-list">${sourceItems}</ul>
</div>`;
@@ -611,6 +683,34 @@
}
}
function bindBranch() {
if (!els.branchClear) return;
els.branchClear.addEventListener('click', clearBranch);
}
function clearBranch() {
branchContext = null;
if (els.branchPanel) els.branchPanel.classList.add('is-hidden');
if (els.branchNotes) els.branchNotes.value = '';
}
function branchFromSubQ(question) {
if (!lastResult || !question) return;
branchContext = {
original_query: lastResult.query || '',
brief_summary: (lastResult.brief_markdown || '').slice(0, 600),
what_we_found: lastResult.what_we_found || '',
top_sources: (lastResult.sources || []).slice(0, 5).map((s) => ({
n: s.n, title: s.title, excerpt: (s.excerpt || '').slice(0, 200),
})),
};
els.input.value = question;
if (els.branchOrigin) els.branchOrigin.textContent = 'Original query: ' + branchContext.original_query;
if (els.branchSummary) els.branchSummary.textContent = branchContext.brief_summary;
if (els.branchPanel) els.branchPanel.classList.remove('is-hidden');
els.form.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function renderSourceCard(s) {
const score = s.reranker_score != null ? s.reranker_score : s.similarity;
const originTagClass = s.source_origin === 'upload' ? 'dr-source-tag dr-source-tag--upload' : 'dr-source-tag';
+101 -1
View File
@@ -6,6 +6,7 @@
let lang = 'en';
let uploadFiles = [];
let lastResult = null;
let branchContext = null;
const SLICE_DEFS = [
{ id: 'family_core', label: 'Family Law Core' },
@@ -63,6 +64,11 @@
modalEyebrow: document.getElementById('drSourceModalEyebrow'),
modalMeta: document.getElementById('drSourceModalMeta'),
modalText: document.getElementById('drSourceModalText'),
branchPanel: document.getElementById('drBranchPanel'),
branchClear: document.getElementById('drBranchClear'),
branchOrigin: document.getElementById('drBranchOrigin'),
branchSummary: document.getElementById('drBranchSummary'),
branchNotes: document.getElementById('drBranchNotes'),
});
if (!els.form) return;
@@ -72,7 +78,12 @@
bindRanges();
bindUpload();
bindModal();
bindBranch();
els.form.addEventListener('submit', onSubmit);
els.results.addEventListener('click', (e) => {
const btn = e.target.closest('.dr-branch-btn');
if (btn) branchFromSubQ(btn.dataset.question || '');
});
// Pre-render placeholder trace
renderTrace(STEP_LABELS.map((label) => ({ label, detail: 'Waiting…', status: 'idle' })));
@@ -195,7 +206,62 @@
source.matched_sub_questions?.length ? ['Matched sub-Q', source.matched_sub_questions.join(', ')] : null,
].filter(Boolean);
els.modalMeta.innerHTML = '<dl>' + metaRows.map(([k, v]) => `<dt>${escapeHtml(k)}</dt><dd>${escapeHtml(String(v))}</dd>`).join('') + '</dl>';
els.modalText.textContent = source.chunk_text || source.excerpt || '';
const summary = source.summary || '';
const chunkText = source.chunk_text || source.excerpt || '';
const isUpload = source.source_origin === 'upload';
const hasDocId = source.document_id != null;
let html = summary
? `<div class="dr-modal-summary">${escapeHtml(summary)}</div>`
: `<div class="dr-modal-summary dr-modal-summary--empty"><em>Summary not yet generated — showing raw chunk below.</em></div>`;
if (chunkText) {
html += `<button class="dr-modal-chunk-toggle" type="button">Show matching chunk ▼</button>`;
html += `<div class="dr-modal-chunk-text is-hidden">${escapeHtml(chunkText)}</div>`;
}
if (!isUpload && hasDocId) {
html += `<button class="dr-modal-all-chunks" type="button" data-document-id="${source.document_id}">View all document chunks →</button>`;
html += `<div class="dr-modal-chunks-list"></div>`;
}
els.modalText.innerHTML = html;
const chunkToggle = els.modalText.querySelector('.dr-modal-chunk-toggle');
const chunkDiv = els.modalText.querySelector('.dr-modal-chunk-text');
chunkToggle?.addEventListener('click', () => {
const isHidden = chunkDiv.classList.toggle('is-hidden');
chunkToggle.textContent = isHidden ? 'Show matching chunk ▼' : 'Hide matching chunk ▲';
});
const allChunksBtn = els.modalText.querySelector('.dr-modal-all-chunks');
const chunksListDiv = els.modalText.querySelector('.dr-modal-chunks-list');
if (allChunksBtn && chunksListDiv) {
allChunksBtn.addEventListener('click', async () => {
allChunksBtn.disabled = true;
allChunksBtn.textContent = 'Loading…';
try {
const res = await fetch(`api/document-chunks.php?document_id=${source.document_id}`, { credentials: 'same-origin' });
const data = await res.json();
if (data.ok && data.chunks) {
chunksListDiv.innerHTML =
`<div class="dr-modal-chunks-head">${escapeHtml(data.document?.title || '')} · ${data.chunks.length} chunks</div>` +
data.chunks.map((c) => `<div class="dr-modal-chunk-item">
<span class="dr-modal-chunk-idx">#${c.chunk_index + 1}${c.section_title ? ' · ' + escapeHtml(c.section_title) : ''}</span>
<p class="dr-modal-chunk-preview">${escapeHtml(truncate(c.content, 300))}</p>
</div>`).join('');
allChunksBtn.remove();
} else {
allChunksBtn.textContent = 'Could not load chunks.';
allChunksBtn.disabled = false;
}
} catch (_) {
allChunksBtn.textContent = 'Error loading chunks.';
allChunksBtn.disabled = false;
}
});
}
els.modal.classList.remove('is-hidden');
}
@@ -257,6 +323,10 @@
language: lang,
controls: getControls(),
};
if (branchContext) {
payload.prior_context = branchContext;
payload.branch_notes = (els.branchNotes ? els.branchNotes.value : '').trim();
}
const stepKeyToIndex = {
interpretation: 0,
@@ -348,6 +418,7 @@
return;
}
finalResult.query = query;
lastResult = finalResult;
const meta = finalResult.trace_metadata || {};
const rc = meta.retrieval_counts || {};
@@ -536,11 +607,40 @@
<div class="dr-subq-report__question">${escapeHtml(sq.question || '')}</div>
${sq.rationale ? `<div class="dr-subq-report__rationale">${escapeHtml(sq.rationale)}</div>` : ''}
</div>
<button class="dr-branch-btn" type="button" data-question="${escapeHtml(sq.question || '')}" aria-label="Branch research from this sub-question">Branch ↓</button>
</div>
<ul class="dr-mini-source-list">${sourceItems}</ul>
</div>`;
}
function bindBranch() {
if (!els.branchClear) return;
els.branchClear.addEventListener('click', clearBranch);
}
function clearBranch() {
branchContext = null;
if (els.branchPanel) els.branchPanel.classList.add('is-hidden');
if (els.branchNotes) els.branchNotes.value = '';
}
function branchFromSubQ(question) {
if (!lastResult || !question) return;
branchContext = {
original_query: lastResult.query || '',
brief_summary: (lastResult.brief_markdown || '').slice(0, 600),
what_we_found: lastResult.what_we_found || '',
top_sources: (lastResult.sources || []).slice(0, 5).map((s) => ({
n: s.n, title: s.title, excerpt: (s.excerpt || '').slice(0, 200),
})),
};
els.input.value = question;
if (els.branchOrigin) els.branchOrigin.textContent = 'Original query: ' + branchContext.original_query;
if (els.branchSummary) els.branchSummary.textContent = branchContext.brief_summary;
if (els.branchPanel) els.branchPanel.classList.remove('is-hidden');
els.form.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function flashSource(n) {
document.querySelectorAll('.dr-source-card.is-highlight').forEach((c) => c.classList.remove('is-highlight'));
const target = document.querySelector(`.dr-source-card[data-source-n="${n}"]`);