document.addEventListener("DOMContentLoaded", () => { const workerUrl = "https://ctmresearchagent.aiagents.workers.dev"; const submitButton = document.getElementById("submitButton"); const researchQueryInput = document.getElementById("researchQuery"); const resultDisplay = document.getElementById("resultDisplay"); const historyContainer = document.getElementById("historyContainer"); /** * --- UPDATED: Submits query to the AI backend --- */ async function handleSubmit() { const query = researchQueryInput.value.trim(); if (!query) { alert("Please enter a research query."); return; } // Show a loading state submitButton.disabled = true; submitButton.innerText = "Thinking..."; resultDisplay.innerHTML = "
Generating response...
"; try { // Call the new AI endpoint const response = await fetch(`${workerUrl}/api/query`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: query }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "An unknown error occurred."); } // Display the real result from the AI resultDisplay.innerText = data.result; // Reload history to include the new entry await loadResearchHistory(); } catch (error) { console.error("Error fetching AI response:", error); resultDisplay.innerText = `Error: ${error.message}`; } finally { // Restore the button submitButton.disabled = false; submitButton.innerText = "Submit"; } } /** * Loads and displays the research history from the backend. */ async function loadResearchHistory() { try { // Use the correct endpoint for fetching history const response = await fetch(`${workerUrl}/api/research`); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const logs = await response.json(); historyContainer.innerHTML = ""; // Clear existing history if (logs.length === 0) { historyContainer.innerHTML = "No research history found.
"; return; } logs.forEach(log => { const entryDiv = document.createElement("div"); entryDiv.className = "history-entry"; entryDiv.innerHTML = `Query: ${log.query}
Result: ${log.result}
${new Date(log.timestamp).toLocaleString()}
`; historyContainer.appendChild(entryDiv); }); } catch (error) { console.error("Failed to load research history:", error); historyContainer.innerHTML = "Error loading research history.
"; } } // Event Listeners submitButton.addEventListener("click", handleSubmit); // Initial load of history loadResearchHistory(); });