File size: 26,034 Bytes
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
 
 
 
 
 
 
 
 
 
 
 
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aefb7b1
 
 
 
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aefb7b1
 
 
d197c9d
aefb7b1
5dccc28
 
 
 
 
 
 
 
 
 
 
aefb7b1
 
d197c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aefb7b1
 
 
 
d197c9d
aefb7b1
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
5dccc28
 
 
 
 
 
 
d197c9d
 
 
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
5dccc28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d197c9d
 
 
 
 
5dccc28
 
d197c9d
 
 
 
5dccc28
 
 
 
 
 
 
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DocsQA Assignment</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link rel="stylesheet" href="/static/style.css" />
  </head>
  <body>
    <div class="bg-orb orb-one"></div>
    <div class="bg-orb orb-two"></div>
    <main class="shell">
      {% if not user %}
      <section class="hero card">
        <div class="hero-topline">
          <p class="eyebrow">LangGraph Assignment</p>
          <span class="badge">FastAPI + Supabase + PGVector</span>
        </div>
        <h1>DocsQA Workspace</h1>
        <p class="lede">
          Upload PDFs, avoid duplicate reprocessing by file hash, and ask an agent that uses user-scoped document retrieval with optional web search.
        </p>
        <p class="developer-credit">Developed by Baba Kattubadi</p>
        {% if db_unavailable %}
        <p class="db-warning">
          Database connection is temporarily unavailable. This is usually a transient DNS/network issue with the Supabase host. Please retry shortly.
        </p>
        {% endif %}
      </section>
      {% else %}
      {% endif %}

      {% if not user %}
      <section class="grid two auth-grid">
        <form class="card panel" id="register-form" method="post" action="/register">
          <div class="panel-head">
            <h2>Create account</h2>
            <p>Start by creating your personal docs workspace.</p>
          </div>
          <label>Email <input type="email" name="email" required /></label>
          <label>Password <input type="password" name="password" required /></label>
          <button type="submit">Register</button>
          <pre class="result ok" id="register-result"></pre>
        </form>

        <form class="card panel" id="login-form" method="post" action="/login">
          <div class="panel-head">
            <h2>Sign in</h2>
            <p>Continue with your existing account.</p>
          </div>
          <label>Email <input type="email" name="email" required /></label>
          <label>Password <input type="password" name="password" required /></label>
          <button type="submit">Login</button>
          <pre class="result ok" id="login-result"></pre>
        </form>
      </section>
      {% else %}
      <section class="app-layout">
        <aside class="card panel sidebar-panel">
          <div class="panel-head">
            <p class="eyebrow">LangGraph Assignment</p>
            <div class="sidebar-title-row">
              <div>
                <h1 class="sidebar-title">DocsQA Workspace</h1>
                <p class="muted">Private document chat with structured sources.</p>
                <p class="developer-credit">Developed by Baba Kattubadi</p>
              </div>
              <span class="badge">FastAPI + Supabase + PGVector</span>
            </div>
          </div>

          <div class="panel-head account-head">
            <h2 class="user-email">{{ user.email }}</h2>
            <p class="muted">Your uploaded docs are private to this account.</p>
          </div>

          <form id="upload-form" class="panel">
            <label class="muted">Upload PDFs (max 5 files, 10 pages each)</label>
            <input type="file" id="file" name="file" accept="application/pdf" multiple required />
            <button type="submit">Upload</button>
          </form>
          <pre class="result" id="upload-result"></pre>

          <div class="panel-head panel-head-inline">
            <h3>Your documents</h3>
            <span class="badge">{{ documents|length }}</span>
          </div>
          <div class="docs sidebar-docs">
            {% for document in documents %}
            <article class="doc">
              <header class="doc-head">
                <h3>{{ document.filename }}</h3>
                <span class="doc-pages">{{ document.page_count }} pages</span>
              </header>
              <div class="doc-actions">
                <button
                  type="button"
                  class="danger doc-delete-btn"
                  data-document-id="{{ document.id }}"
                  data-document-name="{{ document.filename }}"
                >
                  Delete
                </button>
              </div>
            </article>
            {% else %}
            <p class="muted">No documents uploaded yet.</p>
            {% endfor %}
          </div>

          <form method="post" action="/logout" id="logout-form">
            <button type="submit" class="secondary">Sign out</button>
          </form>
        </aside>

        <section class="card panel chat-shell chat-panel">
          <div class="panel-head panel-head-inline">
            <h2>DocsQA Chat</h2>
            <div style="display: flex; gap: 8px; align-items: center;">
              <button type="button" id="new-chat-btn" class="secondary" style="font-size: 0.875rem; padding: 6px 12px;">New Chat</button>
              <span class="badge">Markdown enabled</span>
            </div>
          </div>
          <div id="chat-thread" class="chat-thread">
            <article class="chat-msg assistant">
              <div class="chat-bubble chat-bubble-assistant chat-markdown">
                <p>Ask anything about your uploaded PDFs and I will answer with citations from retrieved chunks.</p>
              </div>
            </article>
          </div>
          <form id="ask-form" class="chat-composer">
            <textarea
              id="query"
              rows="3"
              placeholder="Message DocsQA..."
              required
            ></textarea>
            <button type="submit">Send</button>
          </form>
        </section>
      </section>
      {% endif %}
    </main>

    <script>
      // Session management
      let currentSessionId = sessionStorage.getItem("chat_session_id") || `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      sessionStorage.setItem("chat_session_id", currentSessionId);
      const chatStorageKey = () => `chat_thread_${currentSessionId}`;

      const registerForm = document.getElementById("register-form");
      const loginForm = document.getElementById("login-form");
      const logoutForm = document.getElementById("logout-form");
      const registerResult = document.getElementById("register-result");
      const loginResult = document.getElementById("login-result");
      const uploadForm = document.getElementById("upload-form");
      const askForm = document.getElementById("ask-form");
      const uploadResult = document.getElementById("upload-result");
      const chatThread = document.getElementById("chat-thread");
      const queryInput = document.getElementById("query");
      const docDeleteButtons = document.querySelectorAll(".doc-delete-btn");
      const newChatBtn = document.getElementById("new-chat-btn");

      const saveChatThread = () => {
        if (!chatThread) return;
        sessionStorage.setItem(chatStorageKey(), chatThread.innerHTML);
      };

      const restoreChatThread = () => {
        if (!chatThread) return;
        const savedThread = sessionStorage.getItem(chatStorageKey());
        if (savedThread) {
          chatThread.innerHTML = savedThread;
        }
      };

      const resetChatThread = () => {
        if (!chatThread) return;
        chatThread.innerHTML = `
          <article class="chat-msg assistant">
            <div class="chat-bubble chat-bubble-assistant chat-markdown">
              <p>Ask anything about your uploaded PDFs and I will answer with citations from retrieved chunks.</p>
            </div>
          </article>
        `;
        saveChatThread();
      };

      restoreChatThread();

      // New Chat button handler
      newChatBtn?.addEventListener("click", () => {
        currentSessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        sessionStorage.setItem("chat_session_id", currentSessionId);
        resetChatThread();
      });

      const safeJson = async (response) => {
        try {
          return await response.json();
        } catch {
          return { detail: "Unexpected non-JSON response" };
        }
      };

      const prettyError = (body) => {
        if (!body) return "Request failed.";
        if (typeof body.detail === "string") return body.detail;
        if (typeof body.message === "string") return body.message;
        return "Request failed.";
      };

      const setBusy = (form, busy) => {
        if (!form) return;
        const button = form.querySelector("button[type='submit']");
        if (!button) return;
        button.disabled = busy;
        if (busy) {
          button.dataset.originalText = button.textContent;
          button.textContent = "Please wait...";
        } else if (button.dataset.originalText) {
          button.textContent = button.dataset.originalText;
        }
      };

      const escapeHtml = (value) =>
        value
          .replaceAll("&", "&amp;")
          .replaceAll("<", "&lt;")
          .replaceAll(">", "&gt;");

      const normalizeTabularAnswer = (text) => {
        const lines = text.split("\n");
        const out = [];
        let i = 0;

        while (i < lines.length) {
          const line = lines[i];
          if (!line.includes("\t")) {
            out.push(line);
            i += 1;
            continue;
          }

          const rows = [];
          while (i < lines.length && lines[i].includes("\t")) {
            rows.push(lines[i].split("\t").map((cell) => cell.trim()));
            i += 1;
          }

          if (rows.length < 2) {
            out.push(...rows.map((row) => row.join(" ")));
            continue;
          }

          const columnCount = Math.max(...rows.map((row) => row.length));
          const paddedRows = rows.map((row) => {
            const copy = [...row];
            while (copy.length < columnCount) copy.push("");
            return copy.map((cell) => cell.replaceAll("|", "\\|").replaceAll("\n", "<br>"));
          });

          out.push(`| ${paddedRows[0].join(" | ")} |`);
          out.push(`| ${Array(columnCount).fill("---").join(" | ")} |`);
          for (const row of paddedRows.slice(1)) {
            out.push(`| ${row.join(" | ")} |`);
          }
        }

        return out.join("\n");
      };

      const sanitizeHtml = (html) => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, "text/html");
        doc.querySelectorAll("script,style,iframe,object,embed").forEach((node) => node.remove());
        for (const el of doc.querySelectorAll("*")) {
          for (const attr of [...el.attributes]) {
            const name = attr.name.toLowerCase();
            const value = attr.value.toLowerCase();
            if (name.startsWith("on")) {
              el.removeAttribute(attr.name);
            }
            if ((name === "href" || name === "src") && value.startsWith("javascript:")) {
              el.removeAttribute(attr.name);
            }
          }
        }
        return doc.body.innerHTML;
      };

      const renderMarkdown = (text) => {
        const normalized = normalizeTabularAnswer(text || "");
        if (window.marked?.parse) {
          const html = window.marked.parse(normalized, { gfm: true, breaks: true });
          return sanitizeHtml(html);
        }
        return `<pre>${escapeHtml(normalized)}</pre>`;
      };

      const stripSourceStatusLines = (text) => {
        if (!text) return "";
        const withoutSourcesSection = text.replace(/\n+\s*(?:#+\s*)?sources\s*:?\s*\n[\s\S]*$/i, "").trim();
        return withoutSourcesSection
          .split("\n")
          .filter((line) => !/^\s*no sources were used for this response\.?\s*$/i.test(line.trim()))
          .filter((line) => !/^\s*no citations available for this turn\.?\s*$/i.test(line.trim()))
          .join("\n")
          .trim();
      };

      const buildSourcesMarkdown = (sources) => {
        const vectorSources = Array.isArray(sources?.vector) ? sources.vector : [];
        const webSources = Array.isArray(sources?.web) ? sources.web : [];
        const lines = [];

        if (vectorSources.length) {
          lines.push("### Document Sources");
          for (const src of vectorSources) {
            const doc = src.document || "Unknown document";
            const page = src.page || "unknown";
            const excerpt = src.excerpt || "";
            lines.push(`- **${doc}**, page **${page}**`);
            if (excerpt) {
              lines.push(`  - "${excerpt}"`);
            }
          }
        }

        if (webSources.length) {
          if (lines.length) lines.push("");
          lines.push("### Web Sources");
          for (const src of webSources) {
            const title = src.title || "Untitled source";
            const url = src.url || "";
            if (url && url !== "N/A") {
              lines.push(`- [${title}](${url})`);
            } else {
              lines.push(`- ${title}`);
            }
          }
        }

        if (lines.length) return lines.join("\n");
        return "_No citations available for this turn._";
      };

      const renderSourcesHtml = (sources, queryText = "") => {
        const vectorSources = Array.isArray(sources?.vector) ? sources.vector : [];
        const webSources = Array.isArray(sources?.web) ? sources.web : [];

        const sections = [];

        if (vectorSources.length) {
          const vectorCards = vectorSources
            .map((src) => {
              const documentId = (src.document_id || "").toString().trim();
              const doc = escapeHtml(src.document || "Unknown document");
              const page = escapeHtml(src.page || "unknown");
              const excerptHtml = escapeHtml(src.excerpt || "");
              const pageNumber = Number.parseInt(src.page || "", 10);
              const pageAnchor = Number.isFinite(pageNumber) && pageNumber > 0 ? `#page=${pageNumber}` : "";
              const pdfUrl = documentId ? `/documents/${encodeURIComponent(documentId)}/pdf${pageAnchor}` : "";
              return `
                <article class="source-card">
                  <div class="source-meta">
                    <span class="source-doc">${doc}</span>
                    <div class="source-meta-right">
                      <span class="source-page">Page ${page}</span>
                    </div>
                  </div>
                  <p class="source-excerpt">${excerptHtml || "No excerpt available."}</p>
                  ${
                    pdfUrl
                      ? `<div class="source-actions"><a class="source-link" href="${pdfUrl}" target="_blank" rel="noopener noreferrer">Open PDF</a></div>`
                      : ""
                  }
                </article>
              `;
            })
            .join("");
          sections.push(`<section><h4>Document Sources</h4><div class="source-list">${vectorCards}</div></section>`);
        }

        if (webSources.length) {
          const webItems = webSources
            .map((src) => {
              const title = escapeHtml(src.title || "Untitled source");
              const url = src.url || "";
              if (url && url !== "N/A") {
                return `<li><a href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">${title}</a></li>`;
              }
              return `<li>${title}</li>`;
            })
            .join("");
          sections.push(`<section><h4>Web Sources</h4><ul class="source-web-list">${webItems}</ul></section>`);
        }

        if (!sections.length) {
          return `<p class="muted">No citations available for this turn.</p>`;
        }
        return sections.join("");
      };

      const renderAssistantResponse = (container, fullAnswerText, sourceDict = null, queryText = "") => {
        if (!container) return;
        const answerContent = stripSourceStatusLines(fullAnswerText) || "Response received.";
        const sourcesContent = renderSourcesHtml(sourceDict, queryText);

        container.innerHTML = "";

        const answerPanel = document.createElement("div");
        answerPanel.className = "message-panel";
        answerPanel.innerHTML = renderMarkdown(answerContent);

        container.appendChild(answerPanel);

        const details = document.createElement("details");
        details.className = "source-dropdown";
        const summary = document.createElement("summary");
        summary.textContent = "Sources";
        const body = document.createElement("div");
        body.className = "sources-panel";
        body.innerHTML = sourcesContent;
        details.appendChild(summary);
        details.appendChild(body);
        container.appendChild(details);
      };

      const readStreamingAnswer = async ({ query, target }) => {
        const response = await fetch("/ask/stream", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-Session-Id": currentSessionId
          },
          body: JSON.stringify({ query }),
        });

        if (!response.ok || !response.body) {
          const body = await safeJson(response);
          throw new Error(prettyError(body));
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        let answerText = "";
        let sources = null;

        const processEvent = (rawEvent) => {
          const lines = rawEvent.split("\n");
          let eventName = "message";
          const dataLines = [];

          for (const line of lines) {
            if (line.startsWith("event:")) {
              eventName = line.slice(6).trim();
            } else if (line.startsWith("data:")) {
              dataLines.push(line.slice(5).trim());
            }
          }

          if (!dataLines.length) return;
          const payload = JSON.parse(dataLines.join("\n"));

          if (eventName === "token") {
            answerText += payload.content || "";
            target.classList.remove("chat-pending");
            target.classList.add("chat-markdown");
            target.innerHTML = renderMarkdown(answerText || "Thinking...");
            chatThread.scrollTop = chatThread.scrollHeight;
            return;
          }

          if (eventName === "sources") {
            sources = payload.sources || null;
            return;
          }

          if (eventName === "done") {
            answerText = payload.answer || answerText || "Response received.";
            target.classList.remove("chat-pending");
            target.classList.add("chat-markdown");
            renderAssistantResponse(target, answerText, sources, query);
            chatThread.scrollTop = chatThread.scrollHeight;
            return;
          }

          if (eventName === "error") {
            throw new Error(payload.detail || "Streaming failed.");
          }
        };

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });
          const events = buffer.split("\n\n");
          buffer = events.pop() || "";
          for (const rawEvent of events) {
            if (rawEvent.trim()) processEvent(rawEvent);
          }
        }

        buffer += decoder.decode();
        if (buffer.trim()) processEvent(buffer);
        return { answer: answerText, sources };
      };

      const appendMessage = ({ role, text, markdown = false, pending = false, isError = false }) => {
        if (!chatThread) return null;
        const row = document.createElement("article");
        row.className = `chat-msg ${role}`;

        const bubble = document.createElement("div");
        bubble.className = `chat-bubble ${role === "user" ? "chat-bubble-user" : "chat-bubble-assistant"}`;
        if (markdown) bubble.classList.add("chat-markdown");
        if (pending) bubble.classList.add("chat-pending");
        if (isError) bubble.classList.add("chat-error");

        if (markdown) {
          bubble.innerHTML = renderMarkdown(text);
        } else {
          bubble.textContent = text;
        }

        row.appendChild(bubble);
        chatThread.appendChild(row);
        chatThread.scrollTop = chatThread.scrollHeight;
        saveChatThread();
        return bubble;
      };

      registerForm?.addEventListener("submit", async (event) => {
        event.preventDefault();
        setBusy(registerForm, true);
        const formData = new FormData(registerForm);
        const response = await fetch("/register", { method: "POST", body: formData });
        const body = await safeJson(response);
        registerResult.textContent = response.ok
          ? "Registration successful. Redirecting to your workspace..."
          : prettyError(body);
        registerResult.classList.toggle("error", !response.ok);
        setBusy(registerForm, false);
        if (response.ok) {
          window.location.reload();
        }
      });

      loginForm?.addEventListener("submit", async (event) => {
        event.preventDefault();
        setBusy(loginForm, true);
        const formData = new FormData(loginForm);
        const response = await fetch("/login", { method: "POST", body: formData });
        const body = await safeJson(response);
        loginResult.textContent = response.ok
          ? "Login successful. Redirecting..."
          : prettyError(body);
        loginResult.classList.toggle("error", !response.ok);
        setBusy(loginForm, false);
        if (response.ok) {
          window.location.reload();
        }
      });

      logoutForm?.addEventListener("submit", async (event) => {
        event.preventDefault();
        const response = await fetch("/logout", { method: "POST" });
        if (response.ok) {
          sessionStorage.removeItem(chatStorageKey());
          window.location.reload();
        }
      });

      uploadForm?.addEventListener("submit", async (event) => {
        event.preventDefault();
        setBusy(uploadForm, true);
        const formData = new FormData();
        const fileInput = document.getElementById("file");
        const files = Array.from(fileInput?.files || []);
        if (!files.length) {
          uploadResult.textContent = "Please choose at least one PDF.";
          uploadResult.classList.add("error");
          setBusy(uploadForm, false);
          return;
        }
        for (const file of files) {
          formData.append("file", file);
        }
        const response = await fetch("/upload", { method: "POST", body: formData });
        const body = await safeJson(response);
        if (response.ok) {
          const createdCount = (body.documents || []).filter((doc) => doc.created).length;
          const reusedCount = (body.documents || []).length - createdCount;
          uploadResult.textContent =
            `Uploaded ${body.count} file(s). ${createdCount} indexed, ${reusedCount} reused.\n` +
            (body.documents || [])
              .map((doc) => `- ${doc.filename} (${doc.page_count} pages)`)
              .join("\n");
        } else {
          uploadResult.textContent = prettyError(body);
        }
        uploadResult.classList.toggle("error", !response.ok);
        setBusy(uploadForm, false);
        if (response.ok) {
          saveChatThread();
          window.location.reload();
        }
      });

      docDeleteButtons.forEach((button) => {
        button.addEventListener("click", async () => {
          const documentId = button.dataset.documentId;
          const documentName = button.dataset.documentName || "this document";
          if (!documentId) return;
          const confirmed = window.confirm(`Delete ${documentName} from your documents?`);
          if (!confirmed) return;

          button.disabled = true;
          const response = await fetch(`/documents/${documentId}`, { method: "DELETE" });
          const body = await safeJson(response);
          if (!response.ok) {
            button.disabled = false;
            uploadResult.textContent = prettyError(body);
            uploadResult.classList.add("error");
            return;
          }
          window.location.reload();
        });
      });

      askForm?.addEventListener("submit", async (event) => {
        event.preventDefault();
        const query = queryInput?.value?.trim() || "";
        if (!query) return;

        appendMessage({ role: "user", text: query });
        if (queryInput) queryInput.value = "";
        setBusy(askForm, true);
        const pendingBubble = appendMessage({ role: "assistant", text: "Thinking...", markdown: false, pending: true });
        const target = pendingBubble || appendMessage({ role: "assistant", text: "", markdown: false });
        if (!target) {
          setBusy(askForm, false);
          return;
        }
        try {
          await readStreamingAnswer({ query, target });
        } catch (error) {
          const message = error instanceof Error ? error.message : "Request failed.";
          target.classList.remove("chat-pending");
          target.classList.add("chat-error");
          target.textContent = message;
        } finally {
          chatThread.scrollTop = chatThread.scrollHeight;
          saveChatThread();
          setBusy(askForm, false);
        }
      });

      queryInput?.addEventListener("keydown", (event) => {
        if (event.key === "Enter" && !event.shiftKey) {
          event.preventDefault();
          askForm?.requestSubmit();
        }
      });
    </script>
  </body>
</html>