File size: 8,010 Bytes
f17b878
 
 
 
 
 
 
 
d680311
f17b878
 
d680311
f17b878
d680311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0986c85
 
d680311
 
 
 
 
 
 
0986c85
d680311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0986c85
 
 
 
ec837f4
 
 
053c6ef
ec837f4
d680311
ec837f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f17b878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d680311
f17b878
 
ec837f4
f17b878
 
 
 
 
 
 
ec837f4
 
 
 
0986c85
ec837f4
f17b878
 
 
ec837f4
f17b878
d680311
 
 
0986c85
 
f17b878
 
 
 
ec837f4
 
d680311
 
 
0986c85
 
f17b878
 
 
 
ec837f4
 
 
 
 
f17b878
ec837f4
f17b878
ec837f4
f17b878
 
 
 
 
ec837f4
 
 
 
 
f17b878
d680311
0986c85
 
f17b878
ec837f4
 
f17b878
ec837f4
 
 
d680311
ec837f4
 
 
 
 
 
 
 
 
 
f17b878
ec837f4
 
 
 
 
f17b878
ec837f4
 
 
 
 
 
 
 
f17b878
 
27a4db8
 
 
 
 
 
 
 
 
 
d680311
 
 
0986c85
d680311
0986c85
27a4db8
 
ec837f4
 
27a4db8
ec837f4
27a4db8
 
 
 
 
 
ec837f4
 
d680311
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
const chatDiv = document.getElementById("chat");
const promptInput = document.getElementById("prompt");
const sendBtn = document.getElementById("send");
const stopBtn = document.getElementById("stop");
const clearBtn = document.getElementById("clear");
const projectSelect = document.getElementById("project");
const addProjectBtn = document.getElementById("addProject");
const deleteProjectBtn = document.getElementById("deleteProject");
const loginBtn = document.getElementById("loginBtn");

let currentAbortController = null;
let googleUserToken = null;

// ---------- Google Identity Services ----------
window.onload = function () {
  if (typeof google !== 'undefined') {
    google.accounts.id.initialize({
      client_id: window.GOOGLE_CLIENT_ID,
      callback: handleGoogleCredentialResponse
    });
    
    // Render button if element exists
    const loginContainer = document.getElementById("login-button-container");
    if (loginContainer) {
      google.accounts.id.renderButton(loginContainer, { theme: "outline", size: "large" });
    }
  }
  checkLocalAuth();
};

function handleGoogleCredentialResponse(response) {
  googleUserToken = response.credential;
  localStorage.setItem("google_token", googleUserToken);
  updateAuthUI(true);
}

function checkLocalAuth() {
  const savedToken = localStorage.getItem("google_token");
  if (savedToken) {
    googleUserToken = savedToken;
    updateAuthUI(true);
  } else {
    updateAuthUI(false);
  }
}

loginBtn.addEventListener("click", () => {
  if (googleUserToken) {
    // Log out action
    googleUserToken = null;
    localStorage.removeItem("google_token");
    if (typeof google !== 'undefined') {
      google.accounts.id.cancel();
    }
    updateAuthUI(false);
  } else {
    // Trigger Google Sign-In prompt
    if (typeof google !== 'undefined') {
      google.accounts.id.prompt();
    } else {
      alert("Google Identity Services script still loading.");
    }
  }
});

function updateAuthUI(isAuthenticated) {
  if (isAuthenticated) {
    loginBtn.textContent = "Log Out";
    refreshProjects();
  } else {
    loginBtn.textContent = "Log In with Google";
    chatDiv.innerHTML = '<div class="message assistant"><em>Please log in to use the coding assistant.</em></div>';
  }
}

async function getHeaders(includeContentType = true) {
  if (!googleUserToken) {
    throw new Error("User not authenticated with Google.");
  }

  const headers = {};
  headers["Authorization"] = `Bearer ${googleUserToken}`;
  if (includeContentType) headers["Content-Type"] = "application/json";
  return headers;
}

// ---------- Project History Loading ----------
async function loadHistory(project) {
  chatDiv.innerHTML = '<div class="message assistant"><em>Loading history...</em></div>';
  try {
    const res = await fetch(`/history/${encodeURIComponent(project)}`);
    const data = await res.json();
    chatDiv.innerHTML = "";
    if (data.history && data.history.length > 0) {
      data.history.forEach(msg => {
        if (msg.role === "user") {
          appendAndScroll(makeUserNode(msg.content));
        } else {
          const node = makeAssistantNode();
          node.innerHTML = `<strong>Assistant:</strong><br>${marked.parse(msg.content)}`;
          appendAndScroll(node);
        }
      });
      if (typeof hljs !== 'undefined') hljs.highlightAll();
    } else {
      chatDiv.innerHTML = '<div class="message assistant"><em>New project started. No history found.</em></div>';
    }
  } catch (err) {
    console.error("Error loading history:", err);
    chatDiv.innerHTML = '<div class="message assistant"><em>Error loading history for this project.</em></div>';
  }
}

projectSelect.addEventListener("change", () => {
  loadHistory(projectSelect.value);
});

function makeUserNode(text) {
  const node = document.createElement("div");
  node.className = "message user";
  node.innerHTML = `<strong>You:</strong><br>${marked.parse(text)}`;
  return node;
}

function makeAssistantNode() {
  const node = document.createElement("div");
  node.className = "message assistant";
  node.innerHTML = `<strong>Assistant:</strong><br><em>...</em>`;
  return node;
}

function appendAndScroll(node) {
  chatDiv.appendChild(node);
  chatDiv.scrollTop = chatDiv.scrollHeight;
}

async function refreshProjects() {
  if (!googleUserToken) return;
  const res = await fetch("/projects");
  const data = await res.json();
  const currentVal = projectSelect.value;
  projectSelect.innerHTML = "";
  data.forEach(p => {
    const opt = document.createElement("option");
    opt.value = p;
    opt.textContent = p;
    projectSelect.appendChild(opt);
  });
  if (data.includes(currentVal)) {
    projectSelect.value = currentVal;
  } else if (data.length > 0) {
    projectSelect.value = data[0];
    loadHistory(data[0]);
  }
}

addProjectBtn.addEventListener("click", async () => {
  const name = prompt("Project Name:");
  if (!name) return;
  await fetch(`/add_project`, {
    method: "POST",
    headers: await getHeaders(),
    body: JSON.stringify({ project: name })
  });
  await refreshProjects();
});

deleteProjectBtn.addEventListener("click", async () => {
  const p = projectSelect.value;
  if (!p || !confirm(`Delete project ${p}?`)) return;
  await fetch(`/delete_project`, {
    method: "POST",
    headers: await getHeaders(),
    body: JSON.stringify({ project: p })
  });
  await refreshProjects();
});

sendBtn.addEventListener("click", async () => {
  const text = promptInput.value.trim();
  if (!text) return;

  const project = projectSelect.value;
  const useWeb = document.getElementById("useWeb").checked;

  appendAndScroll(makeUserNode(text));
  promptInput.value = "";

  const assistantNode = makeAssistantNode();
  appendAndScroll(assistantNode);

  currentAbortController = new AbortController();

  try {
    let search_results = [];
    if (useWeb) {
      assistantNode.innerHTML = `<strong>Assistant:</strong><br><em>Searching web...</em>`;
      const sResp = await fetch("/search_web", {
        method: "POST",
        headers: await getHeaders(),
        body: JSON.stringify({ query: text }),
        signal: currentAbortController.signal
      });
      const sData = await sResp.json();
      search_results = sData.results || [];
    }

    const res = await fetch("/chat", {
      method: "POST",
      headers: await getHeaders(),
      body: JSON.stringify({ project, message: text, search_results }),
      signal: currentAbortController.signal
    });

    const data = await res.json();
    if (data.response) {
      assistantNode.innerHTML = `<strong>Assistant:</strong><br>${marked.parse(data.response)}`;
      if (typeof hljs !== 'undefined') hljs.highlightAll();
    } else if (data.error) {
      assistantNode.textContent = "Error: " + data.error;
    }
  } catch (err) {
    if (err.name === 'AbortError') {
      assistantNode.innerHTML += "<br><em>[Stopped]</em>";
    } else {
      assistantNode.textContent = "Error: " + err.message;
    }
  } finally {
    currentAbortController = null;
    chatDiv.scrollTop = chatDiv.scrollHeight;
  }
});

clearBtn.addEventListener("click", () => {
  chatDiv.innerHTML = "";
});

async function uploadFile(project) {
  const fileInput = document.getElementById('fileInput');
  if (!fileInput.files.length) {
    alert("Please select a file first.");
    return;
  }
  const formData = new FormData();
  formData.append("file", fileInput.files[0]);

  try {
    const headers = await getHeaders(false); // browser sets multipart boundary
    const res = await fetch(`/upload_file/${project}`, {
      method: "POST",
      headers: headers,
      body: formData
    });
    const data = await res.json();
    if (data.status === "ok") {
      alert(`Uploaded: ${data.filename}`);
      fileInput.value = "";
    } else {
      alert(`Failed: ${data.error}`);
    }
  } catch (err) {
    alert("Error uploading file.");
  }
}

promptInput.addEventListener("keydown", (e) => {
  if (e.ctrlKey && e.key === "Enter") sendBtn.click();
});