File size: 7,578 Bytes
3950291
c49440d
 
 
 
 
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3950291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3950291
 
 
c49440d
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
3950291
 
 
 
 
c49440d
 
 
 
 
 
3950291
c49440d
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
3950291
 
 
c49440d
 
 
 
 
 
3950291
c49440d
3950291
c49440d
3950291
c49440d
 
3950291
 
c49440d
 
 
 
 
 
3950291
 
c49440d
3950291
c49440d
3950291
c49440d
 
3950291
 
c49440d
 
 
 
3950291
c49440d
 
3950291
 
c49440d
 
 
 
 
3950291
c49440d
 
3950291
c49440d
 
 
 
 
 
3950291
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// JurisAI — Thread State Management
let conversationHistory = [];

async function init() {
    try {
        const res = await fetch("/api/info");
        const data = await res.json();

        // Populate runtime models
        const modelSelect = document.getElementById("modelSelect");
        modelSelect.innerHTML = "";
        for (const [name, id] of Object.entries(data.models)) {
            const opt = document.createElement("option");
            opt.value = id;
            opt.textContent = name;
            if (id === data.default_model) opt.selected = true;
            modelSelect.appendChild(opt);
        }

        // Populate curriculum chapters
        const chSelect = document.getElementById("chapterSelect");
        chSelect.innerHTML = "";
        data.chapters.forEach(ch => {
            const opt = document.createElement("option");
            opt.value = ch;
            opt.textContent = ch === "All" ? "All 7 Acts & Chapters" : ch;
            chSelect.appendChild(opt);
        });

        document.getElementById("chunkCount").textContent = data.total_chunks.toLocaleString();
    } catch (e) {
        console.error("Failed to load initial info:", e);
    }

    // Auto-resize textarea
    const textarea = document.getElementById("queryInput");
    textarea.addEventListener("input", () => {
        textarea.style.height = "auto";
        textarea.style.height = Math.min(textarea.scrollHeight, 140) + "px";
    });
}

function setStatus(text, active = false) {
    const indicator = document.getElementById("statusIndicator");
    const dot = indicator.querySelector(".aui-status-dot");
    const label = indicator.querySelector("span:last-child");
    label.textContent = text;
    dot.style.background = active ? "#C9A96E" : "#4CAF72";
}

function handleKeyDown(e) {
    if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        handleFormSubmit(e);
    }
}

function sendPreset(text) {
    const input = document.getElementById("queryInput");
    input.value = text;
    handleFormSubmit();
}

function clearChat() {
    conversationHistory = [];
    document.getElementById("messagesStream").innerHTML = "";
    const hero = document.getElementById("welcomeHero");
    hero.style.display = "flex";
    setStatus("Ready");
}

async function handleFormSubmit(e) {
    if (e) e.preventDefault();
    const input = document.getElementById("queryInput");
    const query = input.value.trim();
    if (!query) return;

    input.value = "";
    input.style.height = "auto";
    document.getElementById("welcomeHero").style.display = "none";

    appendMessage("user", query);

    const assistantRowId = "asst-" + Date.now();
    appendLoadingAssistant(assistantRowId);

    const model = document.getElementById("modelSelect").value;
    const chapter = document.getElementById("chapterSelect").value;
    const sendBtn = document.getElementById("sendBtn");
    sendBtn.disabled = true;
    setStatus("Reasoning…", true);

    // Scroll to bottom
    const viewport = document.getElementById("chatViewport");
    viewport.scrollTop = viewport.scrollHeight;

    try {
        const res = await fetch("/api/chat", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                query,
                history: conversationHistory,
                model,
                chapter_filter: chapter,
                top_k: 5
            })
        });

        const data = await res.json();
        updateAssistantMessage(assistantRowId, data);

        conversationHistory.push({ role: "user", content: query });
        conversationHistory.push({ role: "assistant", content: data.answer || "" });

    } catch (err) {
        updateAssistantError(assistantRowId, err.message);
    } finally {
        sendBtn.disabled = false;
        setStatus("Ready");
        viewport.scrollTop = viewport.scrollHeight;
    }
}

function appendMessage(role, text) {
    const stream = document.getElementById("messagesStream");
    const row = document.createElement("div");
    row.className = `aui-message-row aui-message-${role}`;
    row.innerHTML = `<div class="aui-bubble">${escapeHtml(text)}</div>`;
    stream.appendChild(row);

    const viewport = document.getElementById("chatViewport");
    viewport.scrollTop = viewport.scrollHeight;
}

function appendLoadingAssistant(id) {
    const stream = document.getElementById("messagesStream");
    const row = document.createElement("div");
    row.id = id;
    row.className = "aui-message-row aui-message-assistant";
    row.innerHTML = `
        <div class="aui-thinking-pulse">
            <div class="aui-shimmer-spark"></div>
            <span>Searching statutory context…</span>
        </div>
    `;
    stream.appendChild(row);

    const viewport = document.getElementById("chatViewport");
    viewport.scrollTop = viewport.scrollHeight;
}

function updateAssistantMessage(id, data) {
    const row = document.getElementById(id);
    if (!row) return;

    let html = "";

    // Collapsible thinking block
    if (data.thinking && data.thinking.trim()) {
        html += `
            <details class="aui-thinking-box">
                <summary class="aui-thinking-header">
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M9 18l6-6-6-6"/></svg>
                    <span>Thought process (${data.thinking.length} chars)</span>
                </summary>
                <div class="aui-thinking-content">${escapeHtml(data.thinking)}</div>
            </details>
        `;
    }

    // Main answer
    html += `<div class="aui-bubble">${marked.parse(data.answer || "")}</div>`;

    // Citations
    if (data.used_rag && data.retrieved_chunks && data.retrieved_chunks.length > 0) {
        html += `
            <div class="aui-citations-box">
                <div class="aui-citations-header" onclick="this.nextElementSibling.classList.toggle('hidden')">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 016.5 17H20M4 4.5A2.5 2.5 0 016.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15z"/></svg>
                    <span>${data.retrieved_chunks.length} book excerpt${data.retrieved_chunks.length > 1 ? "s" : ""} used</span>
                </div>
                <div class="aui-citation-list">
        `;
        data.retrieved_chunks.forEach(src => {
            html += `
                <div class="aui-citation-card">
                    <div class="aui-citation-meta">
                        <span>${escapeHtml(src.title)} — p.${src.page_number}</span>
                        <span class="aui-citation-score">${src.retrieval_score}</span>
                    </div>
                    <div class="aui-citation-text">${escapeHtml(src.raw_text)}</div>
                </div>
            `;
        });
        html += `</div></div>`;
    }

    row.innerHTML = html;
}

function updateAssistantError(id, err) {
    const row = document.getElementById(id);
    if (!row) return;
    row.innerHTML = `
        <div class="aui-bubble" style="color:#d4756b; border-left: 2px solid #8b3a35; padding-left: 12px;">
            <strong>Something went wrong.</strong> ${escapeHtml(err)}
        </div>
    `;
}

function escapeHtml(str) {
    return (str || "")
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;");
}

document.addEventListener("DOMContentLoaded", init);